--fiesGO
USE [master]
/*GO
if  exists (
   select *
   from master.dbo.sysdatabases
   where name = 'adminv2')
   begin
    drop DATABASE [adminv2]
   end
GO*/
-- To set SQL timeout
--sp_configure 'remote login timeout', 0
go
--sp_configure 'remote query timeout', 0
go
--sp_configure 'query wait', 0
go
--reconfigure with override
go
/****** Object:  Database [adminv2]    Script Date: 04/16/2012 10:31:44 ******/
CREATE DATABASE [adminv2] ON  PRIMARY 
( NAME = N'Adminv2_Data', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\adminv2.mdf' , SIZE = 345088KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
 LOG ON 
( NAME = N'Adminv2_Log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\adminv2_log.ldf' , SIZE = 1280KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
GO
--ALTER DATABASE [adminv2] SET COMPATIBILITY_LEVEL = 80
EXEC dbo.sp_dbcmptlevel @dbname=N'adminv2', @new_cmptlevel=80--Dominic
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [adminv2].[dbo].[sp_fulltext_database] @action = 'disable'
end
GO
ALTER DATABASE [adminv2] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [adminv2] SET ANSI_NULLS OFF
GO
ALTER DATABASE [adminv2] SET ANSI_PADDING OFF
GO
ALTER DATABASE [adminv2] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [adminv2] SET ARITHABORT OFF
GO
ALTER DATABASE [adminv2] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [adminv2] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [adminv2] SET AUTO_SHRINK ON
GO
ALTER DATABASE [adminv2] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [adminv2] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [adminv2] SET CURSOR_DEFAULT  GLOBAL
GO
ALTER DATABASE [adminv2] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [adminv2] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [adminv2] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [adminv2] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [adminv2] SET  DISABLE_BROKER
GO
ALTER DATABASE [adminv2] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [adminv2] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [adminv2] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [adminv2] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [adminv2] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [adminv2] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [adminv2] SET  READ_WRITE
GO
ALTER DATABASE [adminv2] SET RECOVERY SIMPLE
GO
ALTER DATABASE [adminv2] SET  MULTI_USER
GO
ALTER DATABASE [adminv2] SET PAGE_VERIFY NONE
GO
ALTER DATABASE [adminv2] SET DB_CHAINING OFF
GO
USE [adminv2]
GO
/****** Object:  User [fiespayroll]    Script Date: 04/16/2012 10:31:44 ******/
--CREATE USER [fiespayroll] WITHOUT LOGIN WITH DEFAULT_SCHEMA=[fiespayroll]
--GO
/****** Object:  User [admin]    Script Date: 04/16/2012 10:31:44 ******/
CREATE USER [admin] WITHOUT LOGIN WITH DEFAULT_SCHEMA=[dbo]
GO
/****** Object:  Schema [fiespayroll]    Script Date: 04/16/2012 10:31:44 ******/
--CREATE SCHEMA [fiespayroll] AUTHORIZATION [fiespayroll]
--GO
/****** Object:  Table [dbo].[aCustomsMaster]    Script Date: 04/16/2012 10:32:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aCustomsMaster](
	[CustomID] [int] NOT NULL,
	[CustomCategoryCode] [varchar](50) NOT NULL,
	[CustomCategoryPercent] [numeric](5, 2) NULL,
	[Remarks] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aCustomsCode] PRIMARY KEY NONCLUSTERED 
(
	[CustomID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_197575742] ON [dbo].[aCustomsMaster] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spVendorLedger]    Script Date: 04/16/2012 10:32:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[Discountheader]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Discountheader](
	[Companyid] [int] NOT NULL,
	[Discountid] [int] NOT NULL,
	[DiscountCode] [varchar](50) NULL,
	[DiscountName] [varchar](250) NULL,
	[Discountper] [decimal](18, 2) NULL,
	[staff] [bit] NULL,
	[Customer] [bit] NULL,
	[Guest] [bit] NULL,
	[Startdatetime] [datetime] NULL,
	[enddatetime] [datetime] NULL,
	[dailytrue] [bit] NULL,
	[Mealid] [int] NULL,
 CONSTRAINT [PK_Discountheader] PRIMARY KEY NONCLUSTERED 
(
	[Companyid] ASC,
	[Discountid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aBankMaster]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aBankMaster](
	[BankID] [int] NOT NULL,
	[BankName] [varchar](100) NOT NULL,
	[Address1] [varchar](100) NULL,
	[Address2] [varchar](100) NULL,
	[Address3] [varchar](100) NULL,
	[BankCode] [varchar](100) NULL,
	[BankLocation] [varchar](100) NULL,
	[PhoneNumber] [varchar](100) NULL,
 CONSTRAINT [PK_aBankMaster] PRIMARY KEY CLUSTERED 
(
	[BankID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loscomplaints]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loscomplaints](
	[cmpid] [int] NOT NULL,
	[cmpshopid] [int] NOT NULL,
	[cmpcompanyid] [int] NOT NULL,
	[cmpno] [varchar](50) NOT NULL,
	[cmpdate] [datetime] NULL,
	[cmpcustomerid] [int] NULL,
	[cmpbookingid] [int] NULL,
	[cmpcustomername] [varchar](100) NULL,
	[cmpcustomercardno] [varchar](50) NULL,
	[cmpcustomeraddress] [varchar](250) NULL,
	[cmpcustomeremail] [varchar](100) NULL,
	[cmpcustomerpagermobile] [varchar](50) NULL,
	[cmpcomplaintdetails] [varchar](250) NULL,
	[cmptype] [varchar](50) NULL,
	[cmpcancelled] [bit] NULL,
	[cmpcancelledremarks] [varchar](250) NULL,
	[cmpupdatetime] [datetime] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[cmpItemid] [int] NULL,
	[cmpItemDesc] [varchar](250) NULL,
	[cmpEnterby] [varchar](100) NULL,
 CONSTRAINT [PK_loscomplaints] PRIMARY KEY NONCLUSTERED 
(
	[cmpid] ASC,
	[cmpshopid] ASC,
	[cmpcompanyid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_34099162] ON [dbo].[loscomplaints] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aDeptImageMaster]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aDeptImageMaster](
	[CompanyID] [int] NOT NULL,
	[DeptID] [int] NOT NULL,
	[DepImage] [image] NULL,
	[type] [varchar](5) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spYearSalesShopWise]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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
GO
/****** Object:  Table [dbo].[aDummyReports]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aDummyReports](
	[ReportID] [int] NOT NULL,
	[ReportName] [varchar](100) NULL,
	[Reportconst] [varchar](20) NULL,
	[ReportCatId] [int] NULL,
	[ReportDetailId] [int] NULL,
	[repModuleCode] [varchar](10) NULL,
	[Ported] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spcustomerbalanceasondate]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  Table [dbo].[InterDivisionJournalTransDetails]    Script Date: 04/16/2012 10:32:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[InterDivisionJournalTransDetails](
	[JournalTransID] [int] NOT NULL,
	[JournalTransDetailID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[AccountID] [int] NOT NULL,
	[JournalTransCredit] [bit] NOT NULL,
	[departmentid] [int] NULL,
	[Amount] [numeric](18, 2) NULL,
	[Remarks] [varchar](250) NULL,
	[depexrates] [numeric](18, 8) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO


/****** Object:  Table [dbo].[losfuture]    Script Date: 04/16/2012 10:32:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losfuture](
	[futureint] [int] NOT NULL,
	[futuredatetime] [datetime] NULL,
	[futurevarchar] [varchar](250) NULL,
	[futurenumeric] [numeric](18, 3) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_losfuture] PRIMARY KEY NONCLUSTERED 
(
	[futureint] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_389576426] ON [dbo].[losfuture] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwGdnBinCardSummary]    Script Date: 04/16/2012 10:32:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ===============================================      
-- 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
GO
/****** Object:  Table [dbo].[aFeeMaster]    Script Date: 04/16/2012 10:32:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aFeeMaster](
	[FeeID] [int] NOT NULL,
	[FeeName] [char](50) NULL,
	[HasExpiry] [int] NULL,
 CONSTRAINT [PK_aFeeMaster] PRIMARY KEY CLUSTERED 
(
	[FeeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[InhouseConsumptionReqDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[InhouseConsumptionReqDetail](
	[StoreRequestId] [int] NOT NULL,
	[Slno] [int] NOT NULL,
	[ItemId] [int] NOT NULL,
	[Qty] [numeric](18, 2) NOT NULL,
	[PackingTypeId] [int] NOT NULL,
	[Pqty] [numeric](18, 2) NOT NULL,
	[FinancialYearId] [int] NOT NULL,
	[CompanyId] [int] NOT NULL,
	[ApprQty] [numeric](18, 0) NULL,
	[ApprPackingTypeId] [int] NULL,
	[ApprPqty] [numeric](18, 0) NULL,
 CONSTRAINT [PK_BMS_FM_StockStoreRequestDetail] PRIMARY KEY CLUSTERED 
(
	[StoreRequestId] ASC,
	[Slno] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[denominationheader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[denominationheader](
	[companyid] [int] NOT NULL,
	[shopid] [int] NOT NULL,
	[denominationid] [int] NOT NULL,
	[denominationno] [varchar](50) NOT NULL,
	[denomdate] [datetime] NULL,
	[remarks] [varchar](250) NULL,
	[cancelled] [bit] NULL,
	[cancelledremarks] [varchar](50) NULL,
	[denoUserID] [int] NULL,
	[tillid] [int] NULL,
	[tillHistoryid] [int] NULL,
 CONSTRAINT [pk_denominationheader] PRIMARY KEY CLUSTERED 
(
	[shopid] ASC,
	[denominationid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Losdisplaylayer]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Losdisplaylayer](
	[Displayerid] [int] NULL,
	[DispLayerName] [varchar](100) NULL,
	[DispLayerValue] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spAllotedStock]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliation]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spNonBuyingCustomersItemwise]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[LtimeHeader]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LtimeHeader](
	[LtimeID] [int] NOT NULL,
	[LtimeDate] [datetime] NOT NULL,
	[LtimeCompanyid] [int] NOT NULL,
	[LtimeSupplierId] [int] NULL,
	[LtimeItemid] [numeric](18, 0) NOT NULL,
	[LtimeDepartmentid] [int] NOT NULL,
	[LtimeRemarks] [varchar](50) NULL,
	[LtimePreparedBy] [varchar](50) NULL,
 CONSTRAINT [PK_LtimeHeader] PRIMARY KEY NONCLUSTERED 
(
	[LtimeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spBudgetPurchase]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  Table [dbo].[loaFixedCostDetail]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[loaFixedCostDetail](
	[dFixedCostId] [int] NOT NULL,
	[dFixedCostDetailId] [int] NOT NULL,
	[dFixedCostItemId] [int] NULL,
	[dFixedCostCategoryId] [int] NULL,
	[dFixedCostValue] [numeric](18, 4) NULL,
	[dfixedcompanyid] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[SP_SelectedKOTDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =================================================================================                    
-- 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
GO
/****** Object:  Table [dbo].[DishSegmentHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[DishSegmentHeader](
	[seg_header_id] [int] NOT NULL,
	[seg_header_name] [varchar](50) NOT NULL,
	[seg_header_companyID] [int] NOT NULL,
	[seg_header_remarks] [varchar](250) NULL,
 CONSTRAINT [PK_DishSegment] PRIMARY KEY CLUSTERED 
(
	[seg_header_id] ASC,
	[seg_header_companyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[lopurchasecostingaccountdetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[lopurchasecostingaccountdetails](
	[poadPOID] [int] NOT NULL,
	[poadAccountID] [int] NOT NULL,
	[poadDetailID] [int] NOT NULL,
	[poadDescription] [varchar](250) NULL,
	[poadAmount] [numeric](18, 2) NOT NULL,
	[poadCompanyID] [int] NULL,
	[poadDistribution] [varchar](1500) NULL,
	[poadOtherCharges] [bit] NOT NULL,
	[poadCostingType] [varchar](5) NULL,
	[poaddToLandPrice] [bit] NULL,
 CONSTRAINT [PK_LOPOAccountDetails] PRIMARY KEY NONCLUSTERED 
(
	[poadPOID] ASC,
	[poadAccountID] ASC,
	[poadDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  View [dbo].[vwOpeningStockValue]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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:  Table [dbo].[ReportCategoryDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ReportCategoryDetail](
	[RepDetailId] [int] NULL,
	[RepCatId] [int] NULL,
	[RepDetailName] [varchar](100) NULL,
	[RepConstant] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spDaySales]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[losSerialArrivalDetails]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losSerialArrivalDetails](
	[sadInterfaceID] [int] NOT NULL,
	[sadShopID] [int] NOT NULL,
	[sadTransactionID] [int] NOT NULL,
	[sadDetailID] [int] NOT NULL,
	[sadSerialNo] [nvarchar](50) NOT NULL,
	[sadItemID] [int] NOT NULL,
	[sadItemQty] [numeric](10, 2) NOT NULL,
	[sadPackingTypeID] [int] NOT NULL,
	[sadPackingQty] [numeric](10, 2) NOT NULL,
	[sadCancel] [int] NOT NULL,
	[sadAdjustment] [int] NOT NULL,
	[sadFreeQty] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aContact]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aContact](
	[CompanyID] [int] NOT NULL,
	[ContactID] [int] NOT NULL,
	[Salutation] [varchar](50) NULL,
	[Name] [varchar](50) NOT NULL,
	[Address1] [varchar](250) NOT NULL,
	[Address2] [varchar](250) NULL,
	[Address3] [varchar](250) NULL,
	[CardNo] [varchar](50) NOT NULL,
	[ExpiryDate] [datetime] NOT NULL,
	[Email] [varchar](50) NULL,
	[PhoneNo] [varchar](50) NULL,
	[CountryId] [int] NOT NULL,
	[CityId] [int] NOT NULL,
	[CurrencyId] [int] NOT NULL,
	[DateofBirth] [datetime] NULL,
	[Anniversary] [datetime] NULL,
	[Profession] [varchar](50) NULL,
	[SpouseName] [varchar](50) NULL,
 CONSTRAINT [PK_aContact] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[ContactID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spStockOrdering]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------                
--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
GO
/****** Object:  Table [dbo].[aStatusGroup]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aStatusGroup](
	[CompanyId] [int] NOT NULL,
	[StatusGroupId] [int] NOT NULL,
	[StatusGroupName] [nvarchar](50) NOT NULL,
	[StatusGroupDesc] [nvarchar](500) NULL,
 CONSTRAINT [PK_aStatusGroup] PRIMARY KEY CLUSTERED 
(
	[CompanyId] ASC,
	[StatusGroupId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[SpecialPricing]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SpecialPricing](
	[SPItemId] [int] NULL,
	[SPItemCode] [nvarchar](255) NULL,
	[SPPackingTypeId] [int] NULL,
	[SPItemCostPrice] [float] NULL,
	[SPItemSellingPrice] [float] NULL,
	[SPNewPrice] [float] NULL,
	[SPPriceChanged] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losposWarDet]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losposWarDet](
	[WDCompanyID] [int] NOT NULL,
	[WDShopID] [int] NOT NULL,
	[WDBillId] [int] NOT NULL,
	[WDItemId] [int] NOT NULL,
	[WDSerialNo] [varchar](100) NOT NULL,
	[WDSerMonths] [int] NOT NULL,
	[WDPartMonths] [int] NOT NULL,
	[WDDesc] [varchar](100) NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwInquiryGodownStockSummary]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ===============================================      
-- 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
GO
/****** Object:  Table [dbo].[aHPAccountsSettings]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHPAccountsSettings](
	[CompanyID] [int] NOT NULL,
	[DebtorAcc] [int] NOT NULL,
	[SuspenseAcc] [int] NOT NULL,
	[InterestAcc] [int] NOT NULL,
	[SalesAcc] [int] NOT NULL,
	[COGSAcc] [int] NOT NULL,
	[AdjustmentAcc] [int] NOT NULL,
	[CashControlAcc] [int] NOT NULL,
	[RepossessionInvAcc] [int] NULL,
	[SalesReturnAcc] [int] NULL,
	[wchUnitSerial] [varchar](50) NULL,
	[wchLabourCost] [numeric](12, 2) NULL,
	[wchpartCostSupplier] [numeric](12, 2) NULL,
	[wchLabourCostSupplier] [numeric](12, 2) NULL,
	[wchCreditDate] [datetime] NULL,
	[GracePeriod] [int] NULL,
	[FineCharge] [numeric](18, 2) NULL,
	[ManualOrAutomatic] [char](1) NULL,
	[DueAlertBlock] [int] NULL,
	[DefaultChargeAcc] [int] NULL,
	[AdjustmentCarryingAcc] [int] NULL,
	[posAlertBlock] [int] NULL,
 CONSTRAINT [PK_aHPAccountsSettings] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spnonmovingitems]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------------          
-- 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
GO
/****** Object:  StoredProcedure [dbo].[sp_FandBCancelEdit]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ====================================================================================                          
-- 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
GO
/****** Object:  Table [dbo].[mesfuture]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[mesfuture](
	[futureint] [int] NOT NULL,
	[futuredatetime] [datetime] NULL,
	[futurevarchar] [varchar](250) NULL,
	[futurenumeric] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_mesfuture] PRIMARY KEY NONCLUSTERED 
(
	[futureint] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_405576483] ON [dbo].[mesfuture] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spSummarizeGodownTransactions]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- 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
GO
/****** Object:  Table [dbo].[aHPItemTransferHeader]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHPItemTransferHeader](
	[ithCompanyID] [int] NOT NULL,
	[ithFinancialID] [int] NOT NULL,
	[ithTransferID] [int] NOT NULL,
	[ithTransferNO] [nvarchar](50) NOT NULL,
	[ithTransferDate] [datetime] NOT NULL,
	[ithCancel] [char](10) NULL,
	[ithUser] [nvarchar](50) NULL,
	[ithModifiedUser] [nvarchar](50) NULL,
	[ithModifiedTime] [datetime] NULL,
 CONSTRAINT [PK_aHItemTransferHeader] PRIMARY KEY CLUSTERED 
(
	[ithCompanyID] ASC,
	[ithFinancialID] ASC,
	[ithTransferID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spopeningvendorbalanceperiod]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  Table [dbo].[aAlias]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aAlias](
	[CompanyId] [int] NOT NULL,
	[AliasId] [int] NOT NULL,
	[Name] [nvarchar](50) NOT NULL,
	[Alias] [nvarchar](50) NOT NULL,
	[Description] [nvarchar](500) NOT NULL,
 CONSTRAINT [PK_aAlias] PRIMARY KEY CLUSTERED 
(
	[CompanyId] ASC,
	[AliasId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[misCategoryDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[misCategoryDetail](
	[mcdDetailID] [int] NOT NULL,
	[mcdId] [int] NOT NULL,
	[mcdName] [varchar](100) NULL,
	[CompanyID] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aHpFeePaymentDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aHpFeePaymentDetail](
	[HpDCompanyID] [int] NOT NULL,
	[HpDDepartmentID] [int] NOT NULL,
	[HpDPaymentID] [int] NOT NULL,
	[HpDDetailID] [int] NOT NULL,
	[HpDDebitAccountID] [int] NULL,
	[HpDExRate] [numeric](18, 2) NULL,
	[HpDAmount] [numeric](18, 2) NULL,
	[HpDItemID] [int] NULL,
	[HpDRegID] [int] NULL,
	[HpDExpiry] [datetime] NULL,
	[HPFeeID] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spupdatestockproblem]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  Table [dbo].[misMenu]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[misMenu](
	[MenuID] [int] NOT NULL,
	[MenuName] [varchar](50) NULL,
	[mcID] [int] NOT NULL,
	[mcDetailID] [int] NOT NULL,
	[MenuShortcutShift] [smallint] NULL,
	[MenuShortcutKeycode] [smallint] NULL,
	[CompanyID] [int] NOT NULL,
	[CategoryId] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[misReports]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[misReports](
	[ReportID] [int] NOT NULL,
	[ReportName] [varchar](100) NULL,
	[CompanyID] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aHpProcessingDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHpProcessingDetail](
	[hpdCompanyID] [int] NOT NULL,
	[hpdDepartmentID] [int] NOT NULL,
	[hpdProcessingId] [int] NOT NULL,
	[hpdDetailID] [int] NOT NULL,
	[hpdChequeDate] [datetime] NOT NULL,
	[hpdCapital] [numeric](18, 2) NOT NULL,
	[hpdRental] [numeric](18, 2) NOT NULL,
	[hpdInterest] [numeric](18, 2) NOT NULL,
	[hpdCapitalRepayment] [numeric](18, 2) NOT NULL,
	[hpdCapitalBalance] [numeric](18, 2) NOT NULL,
	[hpdBankName] [nvarchar](50) NULL,
	[hpdChequeNo] [nvarchar](50) NULL,
	[hpdAmount] [numeric](18, 2) NULL,
	[hpdSettlementAmount] [numeric](18, 2) NULL,
	[hpdInterestRate] [numeric](18, 2) NULL,
	[hpdPosted] [int] NULL,
	[hpdChequeStatus] [varchar](50) NULL,
 CONSTRAINT [PK_aHpProcessingDetail] PRIMARY KEY CLUSTERED 
(
	[hpdCompanyID] ASC,
	[hpdDepartmentID] ASC,
	[hpdProcessingId] ASC,
	[hpdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[moafuture]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[moafuture](
	[futureint] [int] NOT NULL,
	[futurevarchar] [varchar](250) NULL,
	[futuredatetime] [datetime] NULL,
	[futurenumeric] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_moafuture] PRIMARY KEY NONCLUSTERED 
(
	[futureint] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_421576540] ON [dbo].[moafuture] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spQuoteItReplace]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
 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
GO
/****** Object:  Table [dbo].[ol1]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ol1](
	[code_no] [nvarchar](255) NULL,
	[on_hand] [float] NULL,
	[code_part] [nvarchar](255) NULL,
	[brand] [nvarchar](255) NULL,
	[size] [nvarchar](255) NULL,
	[cost] [float] NULL,
	[selling] [float] NULL,
	[cnt_dte] [nvarchar](255) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aHqPettyCashPaymentDetails]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHqPettyCashPaymentDetails](
	[pdCompanyID] [int] NOT NULL,
	[pdDepartmentID] [int] NOT NULL,
	[pdPaymentID] [int] NOT NULL,
	[pdDetailID] [int] NOT NULL,
	[pdDebitAccountID] [int] NOT NULL,
	[pdDescription] [varchar](250) NOT NULL,
	[pdExRate] [numeric](18, 2) NOT NULL,
	[pdAmount] [numeric](18, 2) NOT NULL,
 CONSTRAINT [PK_aHqPettyCashPaymentDetails] PRIMARY KEY CLUSTERED 
(
	[pdCompanyID] ASC,
	[pdDepartmentID] ASC,
	[pdPaymentID] ASC,
	[pdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

/****** Object:  Table [dbo].[ol2]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ol2](
	[code_no] [nvarchar](255) NULL,
	[on_hand] [float] NULL,
	[code_part] [nvarchar](255) NULL,
	[brand] [nvarchar](255) NULL,
	[size] [nvarchar](255) NULL,
	[cost] [float] NULL,
	[selling] [float] NULL,
	[cnt_dte] [nvarchar](255) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aShopCustomerSetting]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aShopCustomerSetting](
	[ShopID] [int] NOT NULL,
	[CompanyID] [int] NULL,
	[GroupID] [int] NULL,
	[CatID] [int] NULL,
	[CurrencyID] [int] NULL,
	[CountryID] [int] NULL,
	[AccBit] [bit] NULL,
	[AccID] [int] NULL,
	[CityID] [int] NULL,
	[DuePeriod] [int] NULL,
PRIMARY KEY CLUSTERED 
(
	[ShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aIslandMaster]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aIslandMaster](
	[IslandID] [int] NOT NULL,
	[CompanyiD] [int] NULL,
	[AtollID] [char](10) NULL,
	[IslandName] [nvarchar](50) NULL,
	[DevIslandName] [nvarchar](50) NULL,
 CONSTRAINT [PK_aIslandMaster] PRIMARY KEY CLUSTERED 
(
	[IslandID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aHqPettyCashPaymentHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHqPettyCashPaymentHeader](
	[phCompanyID] [int] NOT NULL,
	[phDepartmentID] [int] NOT NULL,
	[phPaymentID] [int] NOT NULL,
	[phPaymentNo] [varchar](50) NOT NULL,
	[phPaymentDate] [datetime] NOT NULL,
	[phAccountID] [int] NOT NULL,
	[phReferenceno] [varchar](50) NOT NULL,
	[phPayee] [varchar](150) NOT NULL,
	[phRemarks] [varchar](250) NOT NULL,
	[phAmount] [numeric](18, 2) NOT NULL,
	[phFinancialID] [int] NOT NULL,
	[phCancel] [int] NOT NULL,
	[phCancelRemarks] [varchar](50) NULL,
	[phPosted] [int] NOT NULL,
	[phExRate] [numeric](18, 2) NOT NULL,
	[phComExRate] [numeric](18, 2) NOT NULL,
	[phDepExRate] [numeric](18, 2) NOT NULL,
	[phUserName] [varchar](50) NOT NULL,
	[phUpdateUserName] [varchar](50) NULL,
	[phUpdateTime] [datetime] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[reportrangevalues]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[reportrangevalues](
	[Rangeid] [int] NULL,
	[RangeDetailid] [int] NULL,
	[Reportid] [int] NULL,
	[FromRange] [numeric](18, 2) NULL,
	[ToRange] [numeric](18, 2) NULL,
	[rangename] [varchar](250) NULL,
	[rangecode] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[sppandcinquirygodownstock]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  Table [dbo].[paPayAccLinkHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[paPayAccLinkHeader](
	[CompanyID] [int] NOT NULL,
	[TransID] [int] NOT NULL,
	[DepartmentID] [int] NOT NULL,
	[TransNo] [varchar](50) NOT NULL,
	[TransDate] [datetime] NOT NULL,
	[TransType] [char](1) NOT NULL,
	[Remarks] [varchar](250) NOT NULL,
	[Cancelled] [bit] NOT NULL,
	[CancelRemarks] [varchar](250) NULL,
	[Posted] [bit] NOT NULL,
	[UpdateTime] [datetime] NOT NULL,
 CONSTRAINT [pk_paPayAccLinkHeader] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[TransID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aItem]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aItem](
	[ItemID] [int] NOT NULL,
	[ItemCode] [varchar](50) NOT NULL,
	[ItemDescription] [varchar](250) NOT NULL,
	[ItemCategoryID] [int] NOT NULL,
	[ColorID] [int] NULL,
	[SizeID] [int] NULL,
	[Active] [bit] NOT NULL,
	[ItemRate] [numeric](18, 2) NULL,
	[ReorderQuantity] [numeric](18, 3) NULL,
	[ReorderLevel] [numeric](18, 3) NULL,
	[CustomID] [int] NULL,
	[CostingValue] [numeric](18, 2) NULL,
	[MarginPercent] [numeric](5, 2) NULL,
	[DPMargin] [numeric](18, 2) NULL,
	[WPMargin] [numeric](18, 2) NULL,
	[DPQty] [numeric](18, 3) NULL,
	[WPQty] [numeric](18, 3) NULL,
	[UnitsID] [int] NULL,
	[barcode] [varchar](50) NULL,
	[onetimeshipment] [bit] NOT NULL,
	[pricefixedathq] [bit] NOT NULL,
	[GenerateBC] [bit] NOT NULL,
	[ExpiryNoofDays] [int] NULL,
	[brand] [varchar](50) NULL,
	[ModelNo] [varchar](50) NULL,
	[Notes] [varchar](2000) NULL,
	[Vendors] [varchar](500) NOT NULL,
	[QuantityDecimal] [varchar](5) NOT NULL,
	[forsales] [bit] NOT NULL,
	[did] [int] NULL,
	[Part_code] [varchar](100) NULL,
	[bitf1] [bit] NOT NULL,
	[bitf2] [bit] NOT NULL,
	[bitf3] [bit] NOT NULL,
	[intf1] [int] NULL,
	[intf2] [int] NULL,
	[intf3] [int] NULL,
	[varcharf1] [varchar](250) NULL,
	[itemtype] [char](1) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[OrginCountryID] [int] NULL,
	[ConsignmentCountryID] [int] NULL,
	[Volume] [numeric](18, 3) NULL,
	[LimitToBeEligibleForFree] [numeric](18, 3) NULL,
	[FreeNos] [numeric](18, 3) NULL,
	[compvarflag] [bit] NOT NULL,
	[itemvarflag] [bit] NOT NULL,
	[Attribute1] [varchar](250) NULL,
	[Attribute2] [varchar](250) NULL,
	[RateSelEnabled] [bit] NULL,
	[customcode] [varchar](250) NULL,
	[specification] [nvarchar](500) NULL,
	[carddiscount] [numeric](18, 0) NULL,
	[ImageActive] [int] NULL,
	[marketrate] [numeric](9, 0) NULL,
	[LoyaltyAvailable] [int] NULL,
	[SerialNoActive] [bit] NULL,
	[SerialNoDupli] [bit] NOT NULL,
	[HirePurchase] [int] NULL,
	[AddedDate] [datetime] NULL,
	[InhouseConsAccnt] [int] NULL,
	[ItemDescDhivehi] [varchar](250) NULL,
	[servWarrantyPeriod] [int] NULL,
	[partsWarrantyPeriod] [int] NULL,
	[TaxCategoryId] [int] NULL,
 CONSTRAINT [PK_aItem] PRIMARY KEY NONCLUSTERED 
(
	[ItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_933578364] ON [dbo].[aItem] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [itemcodeduplicatecheck] ON [dbo].[aItem] 
(
	[ItemCode] ASC,
	[ItemDescription] ASC,
	[barcode] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ss]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ss](
	[t1] [char](10) NULL,
	[t2] [char](10) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aItemCategoryMergingDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aItemCategoryMergingDetails](
	[CompanyID] [int] NOT NULL,
	[MergeID] [int] NOT NULL,
	[MergeDate] [datetime] NOT NULL,
	[OldCategoryID] [int] NOT NULL,
	[NewCategoryID] [int] NOT NULL,
	[Cancelled] [int] NULL,
	[CancelledRemarks] [nvarchar](250) NULL,
	[Remarks] [nvarchar](250) NULL,
	[UserName] [nvarchar](50) NOT NULL,
	[UpdateDate] [datetime] NOT NULL,
	[UpdateUserName] [nvarchar](50) NULL,
	[Rowguid] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_aItemCategoryMergingDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[MergeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[tempvaluewise]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tempvaluewise](
	[soldyear] [int] NULL,
	[soldmonth] [int] NULL,
	[qty] [int] NULL,
	[cog] [numeric](18, 2) NULL,
	[sales] [numeric](18, 2) NULL,
	[avgnoofmonth] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[loPurchaseOrderOthCharge]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loPurchaseOrderOthCharge](
	[POorderID] [int] NOT NULL,
	[POOCdetailID] [int] NOT NULL,
	[POAccID] [int] NOT NULL,
	[PODescription] [varchar](100) NULL,
	[POAmount] [numeric](18, 2) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ACustomerSalesPerson]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ACustomerSalesPerson](
	[salespersonid] [int] NOT NULL,
	[customerid] [int] NOT NULL,
	[shopid] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [customersalespersonunique] ON [dbo].[ACustomerSalesPerson] 
(
	[salespersonid] ASC,
	[customerid] ASC,
	[shopid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aListViewHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aListViewHeader](
	[lvwid] [int] NOT NULL,
	[lvwtransname] [varchar](50) NULL,
	[lvwmodulename] [varchar](50) NULL,
	[lvwname] [varchar](50) NULL,
 CONSTRAINT [PK_aListViewHeader] PRIMARY KEY NONCLUSTERED 
(
	[lvwid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[tmpSettlements]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tmpSettlements](
	[companyid] [int] NULL,
	[departmentid] [int] NULL,
	[billsid] [int] NULL,
	[settleddate] [datetime] NULL,
	[paidamount] [numeric](18, 2) NULL,
	[vendorid] [int] NULL,
	[shopid] [int] NULL,
	[Type] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aPackingType]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aPackingType](
	[PackingTypeID] [int] NOT NULL,
	[PackingTypeCode] [varchar](50) NOT NULL,
	[PackingTypeName] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aPackingType] PRIMARY KEY NONCLUSTERED 
(
	[PackingTypeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_277576027] ON [dbo].[aPackingType] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[AUserMasterGridSettings]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[AUserMasterGridSettings](
	[CompanyID] [int] NOT NULL,
	[UserID] [int] NOT NULL,
	[BackColor] [varchar](50) NOT NULL,
	[ForeColor] [varchar](50) NOT NULL,
	[GridColor] [varchar](50) NOT NULL,
	[HeaderColor] [varchar](50) NOT NULL,
	[FontName] [varchar](50) NOT NULL,
	[FontSize] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

/****** Object:  StoredProcedure [dbo].[spCreditorAgeSumBackup]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[w02]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[w02](
	[code_no] [nvarchar](255) NULL,
	[on_hand] [float] NULL,
	[code_part] [nvarchar](255) NULL,
	[brand] [nvarchar](255) NULL,
	[size] [nvarchar](255) NULL,
	[cost] [float] NULL,
	[selling] [float] NULL,
	[cnt_dte] [nvarchar](255) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aReccuringPaymentDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aReccuringPaymentDetails](
	[CompanyID] [int] NOT NULL,
	[DepartmentID] [int] NOT NULL,
	[ReccuringID] [varchar](50) NOT NULL,
	[ReccuringNo] [varchar](50) NOT NULL,
	[ReccuringDate] [datetime] NOT NULL,
	[PaymentName] [varchar](50) NOT NULL,
	[PaymentDate] [datetime] NOT NULL,
	[Amount] [numeric](18, 2) NOT NULL,
	[Type] [varchar](50) NOT NULL,
	[Remarks] [varchar](250) NULL,
	[Cancel] [int] NULL,
	[CancelRemarks] [varchar](250) NULL,
 CONSTRAINT [PK_aReccuringPaymentDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[DepartmentID] ASC,
	[ReccuringID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[AgreementScanCopyDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[AgreementScanCopyDetails](
	[agsCompanyID] [int] NOT NULL,
	[agsAgreementID] [int] NOT NULL,
	[agsDepartmentID] [int] NOT NULL,
	[agsDetailID] [int] NOT NULL,
	[agsAgreementName] [varchar](50) NOT NULL,
	[agsDocuments] [image] NOT NULL,
 CONSTRAINT [PK_AgreementScanCopyDetails] PRIMARY KEY CLUSTERED 
(
	[agsCompanyID] ASC,
	[agsAgreementID] ASC,
	[agsDepartmentID] ASC,
	[agsDetailID] 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]
GO
SET ANSI_PADDING OFF
GO

/****** Object:  StoredProcedure [dbo].[spDailySalesCollectionBackUp]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--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
GO
/****** Object:  Table [dbo].[w03]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[w03](
	[code_no] [nvarchar](255) NULL,
	[on_hand] [float] NULL,
	[code_part] [nvarchar](255) NULL,
	[brand] [nvarchar](255) NULL,
	[size] [nvarchar](255) NULL,
	[cost] [float] NULL,
	[selling] [float] NULL,
	[cnt_dte] [nvarchar](255) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aReports]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aReports](
	[ReportID] [int] NOT NULL,
	[ReportName] [varchar](100) NULL,
	[Reportconst] [varchar](20) NULL,
	[ReportCatId] [int] NULL,
	[ReportDetailId] [int] NULL,
	[repModuleCode] [varchar](10) NULL,
	[ReportActive] [bit] NOT NULL,
 CONSTRAINT [pk_aReports] PRIMARY KEY CLUSTERED 
(
	[ReportID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spCompanyMovingItems]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[w04]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[w04](
	[code_no] [nvarchar](255) NULL,
	[on_hand] [float] NULL,
	[code_part] [nvarchar](255) NULL,
	[brand] [nvarchar](255) NULL,
	[size] [nvarchar](255) NULL,
	[cost] [float] NULL,
	[selling] [float] NULL,
	[cnt_dte] [nvarchar](255) NULL
) ON [PRIMARY]
GO


/****** Object:  Table [dbo].[BudgetCheckDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BudgetCheckDetail](
	[bcdCompanyID] [int] NOT NULL,
	[bcdCheckID] [int] NOT NULL,
	[bcdDetailID] [int] NOT NULL,
	[bcdBudgetAllocID] [int] NULL,
	[bcdBudgetAllocDetailID] [int] NULL,
	[bcdActualAmount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_BudgetCheckDetail] PRIMARY KEY NONCLUSTERED 
(
	[bcdCompanyID] ASC,
	[bcdCheckID] ASC,
	[bcdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliationReport]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[aServiceCategory]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aServiceCategory](
	[sercategid] [int] NOT NULL,
	[sercatcompanyid] [int] NOT NULL,
	[sercatcode] [varchar](50) NOT NULL,
	[sercatname] [varchar](250) NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_ASERVICECATEGORY] PRIMARY KEY NONCLUSTERED 
(
	[sercategid] ASC,
	[sercatcompanyid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_469576711] ON [dbo].[aServiceCategory] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[w05]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[w05](
	[code_no] [nvarchar](255) NULL,
	[on_hand] [float] NULL,
	[code_part] [nvarchar](255) NULL,
	[brand] [nvarchar](255) NULL,
	[size] [nvarchar](255) NULL,
	[cost] [float] NULL,
	[selling] [float] NULL,
	[cnt_dte] [nvarchar](255) NULL
) ON [PRIMARY]
GO


/****** Object:  Table [dbo].[w06]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[w06](
	[code_no] [nvarchar](255) NULL,
	[on_hand] [float] NULL,
	[code_part] [nvarchar](255) NULL,
	[brand] [nvarchar](255) NULL,
	[size] [nvarchar](255) NULL,
	[cost] [float] NULL,
	[selling] [float] NULL,
	[cnt_dte] [nvarchar](255) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aShiftMaster]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aShiftMaster](
	[ShiftId] [int] NULL,
	[ShiftName] [varchar](50) NULL,
	[ShopId] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aShipment]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aShipment](
	[sShipmentID] [int] NOT NULL,
	[sShipmentNO] [varchar](50) NULL,
	[sBillID] [int] NULL,
	[sShipmentDate] [datetime] NOT NULL,
	[sCostingDone] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [pk_ashipment] PRIMARY KEY CLUSTERED 
(
	[sShipmentID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_309576141] ON [dbo].[aShipment] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[BudgetMaster]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[BudgetMaster](
	[CompanyID] [int] NOT NULL,
	[BudgetID] [int] NOT NULL,
	[BudgetCode] [varchar](50) NULL,
	[BudgetHead] [varchar](100) NULL,
	[budcurid] [int] NULL,
 CONSTRAINT [PK_BudgetMaster] PRIMARY KEY NONCLUSTERED 
(
	[CompanyID] ASC,
	[BudgetID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losPosChequeDetails]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losPosChequeDetails](
	[PosChequeId] [int] NOT NULL,
	[PoshBillID] [int] NOT NULL,
	[PoshShopID] [int] NOT NULL,
	[PosBankId] [int] NOT NULL,
	[PosBankChequeNo] [varchar](50) NULL,
	[PosBankChequeDate] [datetime] NOT NULL,
	[PosBankAmount] [numeric](18, 2) NOT NULL,
	[PosChequeUsed] [bit] NOT NULL,
	[posCompExRate] [numeric](18, 0) NULL,
	[posDeptExRate] [numeric](18, 0) NULL,
 CONSTRAINT [PK_losPosChequeDetails] PRIMARY KEY CLUSTERED 
(
	[PosChequeId] ASC,
	[PoshBillID] ASC,
	[PoshShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSumCurrencyPrw]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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
GO
/****** Object:  Table [dbo].[CashFlowOpenings]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CashFlowOpenings](
	[accountid] [int] NOT NULL,
	[amount] [numeric](18, 2) NULL,
	[financialyearid] [int] NOT NULL,
	[companyid] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aSubDepartmentMaster]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aSubDepartmentMaster](
	[SubDepartmentID] [int] NOT NULL,
	[SubDepartmentName] [varchar](50) NOT NULL,
	[CompanyID] [int] NOT NULL,
	[BudgetedAmount] [numeric](18, 2) NULL,
	[ParentDepId] [int] NULL,
	[LevelCode] [int] NULL,
	[Selected] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[Subdepcurrencyid] [int] NULL,
	[address1] [varchar](250) NULL,
	[address2] [varchar](250) NULL,
	[payablealertbeforedays] [int] NULL,
 CONSTRAINT [PK_aSubDepartmentMaster] PRIMARY KEY CLUSTERED 
(
	[SubDepartmentID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aTables]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aTables](
	[TableID] [int] NOT NULL,
	[TableName] [varchar](250) NOT NULL,
	[Description] [varchar](250) NULL,
	[Comments] [varchar](250) NULL,
	[Version1] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_Tables] PRIMARY KEY NONCLUSTERED 
(
	[TableID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_357576312] ON [dbo].[aTables] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[CompleteItemlist]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CompleteItemlist](
	[temp_ID] [int] NULL,
	[CODE] [nvarchar](255) NULL,
	[BrandName] [nvarchar](255) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aUserAuditDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aUserAuditDetail](
	[dCompanyId] [int] NOT NULL,
	[dAuditId] [int] NOT NULL,
	[dDetailId] [int] NOT NULL,
	[dAuditControlName] [varchar](250) NOT NULL,
	[dAuditControlType] [varchar](50) NULL,
	[dOldValue] [varchar](8000) NOT NULL,
	[dNewValue] [varchar](8000) NOT NULL,
 CONSTRAINT [PK_aUserAuditDetail] PRIMARY KEY NONCLUSTERED 
(
	[dCompanyId] ASC,
	[dAuditId] ASC,
	[dDetailId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CreditInvoiceUpdates_20030805]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CreditInvoiceUpdates_20030805](
	[ShopID] [int] NULL,
	[InvoiceID] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spHpCustomerLedger]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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                  
            
    
----------------------------------------------------------------------------------------------------------------------------------------
GO
/****** Object:  Table [dbo].[Crmauserreportrights]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Crmauserreportrights](
	[userid] [int] NOT NULL,
	[reportid] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aUserGroupDeptDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aUserGroupDeptDetails](
	[companyid] [int] NULL,
	[userGroupid] [int] NULL,
	[deptid] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[CrmCase]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmCase](
	[CaseId] [int] NOT NULL,
	[Prority] [varchar](50) NULL,
	[Status] [varchar](50) NULL,
	[UserId] [int] NOT NULL,
	[ClientId] [int] NOT NULL,
	[Subject] [varchar](50) NULL,
	[Description] [varchar](250) NULL,
	[Resolution] [varchar](250) NULL,
	[CreateDate] [datetime] NOT NULL,
	[CompanyId] [int] NOT NULL,
	[Deleted] [bit] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO


/****** Object:  StoredProcedure [dbo].[spAccoutReceivableAudit]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  Table [dbo].[aFineHeader]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aFineHeader](
	[fhCompanyID] [int] NOT NULL,
	[fhDepartmentID] [int] NOT NULL,
	[fhShopID] [int] NOT NULL,
	[fhFinancialID] [int] NOT NULL,
	[fhFineID] [int] NOT NULL,
	[fhFineNo] [varchar](50) NOT NULL,
	[fhTransactionType] [varchar](50) NOT NULL,
	[fhInvoiceID] [int] NOT NULL,
	[fhInvoiceNo] [varchar](50) NOT NULL,
	[fhInvoiceDate] [datetime] NOT NULL,
	[fhCustomerID] [int] NOT NULL,
	[fhDueDate] [datetime] NOT NULL,
	[fhLastFineCalDate] [datetime] NOT NULL,
	[fhRespExchangeRate] [numeric](18, 2) NULL,
	[fhDepExchangeRate] [numeric](18, 2) NULL,
	[fhComExchangeRate] [numeric](18, 2) NULL,
	[fhInvoiceCancelled] [bit] NOT NULL,
 CONSTRAINT [PK_aFineHeader] PRIMARY KEY CLUSTERED 
(
	[fhFineID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aUserGroupRights]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aUserGroupRights](
	[UsergroupID] [int] NOT NULL,
	[ModuleCode] [varchar](10) NULL,
	[InterfaceID] [int] NOT NULL,
	[FunctionRights] [varchar](10) NULL,
	[CompanyID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

/****** Object:  Table [dbo].[WeekDays]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[WeekDays](
	[week_id] [int] NOT NULL,
	[week_days] [varchar](10) NOT NULL,
 CONSTRAINT [PK_WeekID] PRIMARY KEY CLUSTERED 
(
	[week_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [Unique_WeekDays] UNIQUE NONCLUSTERED 
(
	[week_days] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CrmQuotation]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmQuotation](
	[QutotationId] [int] NOT NULL,
	[QutotationSubject] [varchar](50) NOT NULL,
	[PurchaseOrederNo] [varchar](50) NULL,
	[PaymentTerms] [varchar](15) NULL,
	[OpertunityId] [int] NULL,
	[Quotestage] [varchar](15) NULL,
	[ValidUntil] [datetime] NULL,
	[OrginalPoDate] [datetime] NULL,
	[billAccountId] [int] NOT NULL,
	[billContactId] [int] NULL,
	[BillAddress] [varchar](250) NULL,
	[BillState] [varchar](50) NULL,
	[BillCity] [int] NULL,
	[BillPostalCode] [char](20) NULL,
	[BillCountry] [int] NULL,
	[ShipAddress] [varchar](250) NULL,
	[ShipState] [varchar](50) NULL,
	[ShipCity] [int] NULL,
	[ShipPostalCode] [char](20) NULL,
	[ShipCountry] [int] NULL,
	[Description] [varchar](1000) NULL,
	[Userid] [int] NOT NULL,
	[Amount] [numeric](18, 2) NULL,
	[shipAccountId] [int] NULL,
	[shipContactId] [int] NULL,
	[ShipAmount] [numeric](18, 2) NULL,
	[ShipProvider] [varchar](50) NULL,
	[CurrencyID] [int] NULL,
	[ExchangeRate] [varchar](50) NULL,
	[CompanyAmount] [numeric](18, 2) NULL,
	[CompanyId] [int] NOT NULL,
	[Deleted] [bit] NOT NULL,
	[CreateDate] [datetime] NOT NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF
ALTER TABLE [dbo].[CrmQuotation] ADD [QuotationNo] [varchar](50) NULL
ALTER TABLE [dbo].[CrmQuotation] ADD [FinancialYearId] [int] NULL
ALTER TABLE [dbo].[CrmQuotation] ADD [ShopId] [int] NULL
ALTER TABLE [dbo].[CrmQuotation] ADD [Id] [int] NULL
ALTER TABLE [dbo].[CrmQuotation] ADD [Clid] [int] NULL
SET ANSI_PADDING ON
ALTER TABLE [dbo].[CrmQuotation] ADD [Item] [varchar](100) NULL
ALTER TABLE [dbo].[CrmQuotation] ADD [Qty] [int] NULL
ALTER TABLE [dbo].[CrmQuotation] ADD [Cofirm] [int] NULL
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aFineSetting]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aFineSetting](
	[FineAmount] [numeric](18, 2) NULL,
	[FineCalculatingPeriod] [int] NOT NULL,
	[Departments] [nvarchar](100) NOT NULL,
	[FineAccountID] [int] NOT NULL,
	[AccotableDate] [datetime] NULL,
	[FineProcessingTime] [datetime] NULL,
	[FinePercentage] [numeric](18, 2) NULL,
	[FineCalculationMethod] [varchar](2) NULL,
	[DiscountAccountID] [int] NULL,
	[DiscountPercentage] [numeric](18, 2) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aUserGroupVenGroupDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aUserGroupVenGroupDetails](
	[CompanyID] [int] NOT NULL,
	[UserGroupID] [int] NOT NULL,
	[VenGroupID] [int] NOT NULL,
	[Rowguid] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_aUserGroupVenGroupDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[UserGroupID] ASC,
	[VenGroupID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[CrmProposal]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmProposal](
	[ProposalId] [int] NOT NULL,
	[QuotationId] [int] NULL,
	[AccountId] [int] NULL,
	[UserId] [int] NULL,
	[ProposalSubject] [varchar](50) NULL,
	[Document] [image] NULL,
	[Extension] [varchar](50) NULL,
	[ProposalDate] [datetime] NULL,
	[CreateDate] [datetime] NULL,
	[Deleted] [int] NULL,
	[IsTemplate] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aUserGroupmisUserRights]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aUserGroupmisUserRights](
	[UserGroupID] [int] NULL,
	[MenuID] [int] NULL,
	[CompanyID] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aHQPDChequeProcessing]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHQPDChequeProcessing](
	[PDTransId] [int] NOT NULL,
	[PDChequeid] [int] NOT NULL,
	[PDChequeDepartmentid] [int] NOT NULL,
	[PDChequeShopid] [int] NOT NULL,
	[PDChequeEntryDate] [datetime] NOT NULL,
	[PDChequeDebitAccid] [int] NOT NULL,
	[PDChequeCreditAccid] [int] NOT NULL,
	[PDChequeRemarks] [varchar](200) NOT NULL,
	[PDChequePosted] [bit] NOT NULL,
	[PDChequeDtlPrefix] [varchar](50) NULL,
 CONSTRAINT [PK_aHQPDChequeProcessing] PRIMARY KEY CLUSTERED 
(
	[PDTransId] ASC,
	[PDChequeid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aUsergroups]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aUsergroups](
	[UserGroupID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[UserGroupName] [varchar](250) NULL,
	[Description] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aUsergroups] PRIMARY KEY CLUSTERED 
(
	[UserGroupID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[DebtorAgeSum]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[DebtorAgeSum](
	[InvAmt] [numeric](18, 2) NULL,
	[SettleAmt] [numeric](18, 2) NULL,
	[InvoiceID] [int] NULL,
	[CustomerID] [int] NULL,
	[ShopID] [int] NULL,
	[Due] [nvarchar](50) NULL,
	[InvoiceDate] [datetime] NULL,
	[InvoiceNo] [varchar](50) NULL,
	[Type] [varchar](50) NULL,
	[Remarks] [varchar](500) NULL,
	[CustomerName] [varchar](250) NULL,
	[CurrencyName] [varchar](50) NULL,
	[Symbol] [varchar](50) NULL,
	[DueDate] [datetime] NULL,
	[OverDueDays] [int] NULL,
	[Address1] [varchar](50) NULL,
	[Address2] [varchar](50) NULL,
	[Address3] [varchar](50) NULL,
	[DebtoAccID] [int] NULL,
	[AccountDesc] [varchar](50) NULL,
	[Currencyid] [int] NULL,
	[ReferenceNo] [varchar](500) NULL,
	[CustomerCategory] [varchar](20) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Crmreportgroup]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Crmreportgroup](
	[reportgroupid] [int] NULL,
	[groupname] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CrmClient]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmClient](
	[CompanyID] [int] NOT NULL,
	[ClientId] [int] NOT NULL,
	[ClientName] [varchar](50) NOT NULL,
	[WebSite] [varchar](50) NULL,
	[TickerSymbol] [varchar](50) NULL,
	[Industry] [varchar](50) NULL,
	[Type] [varchar](50) NULL,
	[AssignedTo] [int] NULL,
	[Phone] [varchar](50) NULL,
	[Fax] [varchar](50) NULL,
	[Other] [varchar](50) NULL,
	[Email] [varchar](50) NULL,
	[AnnualRevenue] [varchar](50) NULL,
	[Rating] [varchar](50) NULL,
	[BillingAddress] [varchar](50) NULL,
	[BCityID] [int] NULL,
	[BCountryID] [int] NULL,
	[BPostalCode] [varchar](50) NULL,
	[ShoppingAddress] [varchar](50) NULL,
	[SCityID] [int] NULL,
	[SCountryID] [int] NULL,
	[SPostalCode] [varchar](50) NULL,
	[Description] [varchar](50) NULL,
 CONSTRAINT [PK_crmClient] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[ClientId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aVendorMasterBackUp]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aVendorMasterBackUp](
	[VendorID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[FinancialID] [int] NOT NULL,
	[OpeningCreditBalance] [numeric](18, 2) NOT NULL,
	[OpeningDebitBalance] [numeric](18, 2) NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aVendorMasterBackUp] PRIMARY KEY NONCLUSTERED 
(
	[VendorID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_389576426] ON [dbo].[aVendorMasterBackUp] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[HPpostDatedCheqReg]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[HPpostDatedCheqReg](
	[RegID] [int] NOT NULL,
	[TranId] [int] NULL,
	[Date] [datetime] NULL,
	[BankId] [int] NULL,
	[CheqDate] [datetime] NULL,
	[CheqNo] [int] NULL,
 CONSTRAINT [PK_HPpostDatedCheqReg] PRIMARY KEY CLUSTERED 
(
	[RegID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[IODocuments]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[IODocuments](
	[DocID] [int] NOT NULL,
	[DepID] [int] NOT NULL,
	[DocDate] [datetime] NULL,
	[DocNo] [varchar](50) NULL,
	[ReferenceNo] [varchar](50) NULL,
	[External] [bit] NULL,
	[Sender] [varchar](250) NULL,
	[AddressedTo] [varchar](250) NULL,
	[AddressedDate] [datetime] NULL,
	[Receiver] [varchar](100) NULL,
	[Description] [varchar](250) NULL,
	[Remark] [varchar](250) NULL,
	[Physicalfilename] [varchar](250) NULL,
	[Doctype] [char](1) NOT NULL,
	[Cancelled] [bit] NULL,
	[CancelledRemarks] [varchar](100) NULL,
	[Type] [varchar](100) NULL,
	[PhysicalDepid] [int] NULL,
	[alertdate] [datetime] NULL,
	[alertnoofdays] [int] NULL,
	[alertremarks] [varchar](250) NULL,
	[DocTypeID] [int] NULL,
	[physicalloc] [varchar](200) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CrmEmail]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmEmail](
	[Emailid] [int] NOT NULL,
	[SendDate] [datetime] NOT NULL,
	[ToEmail] [varchar](max) NULL,
	[CCC] [varchar](500) NULL,
	[BCCC] [varchar](500) NULL,
	[Subject] [nvarchar](500) NOT NULL,
	[Body] [nvarchar](4000) NOT NULL,
	[Send] [bit] NULL,
	[RelatedTo] [varchar](50) NULL,
	[RelatedToId] [int] NULL,
	[CompanyId] [int] NOT NULL,
 CONSTRAINT [PK_CrmEmail] PRIMARY KEY CLUSTERED 
(
	[Emailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aYearEndTemp]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aYearEndTemp](
	[companyid] [int] NULL,
	[accountid] [int] NULL,
	[acctype] [char](1) NULL,
	[financialid] [int] NULL,
	[openingamount] [numeric](18, 2) NULL,
	[openingdepamount] [numeric](18, 2) NULL,
	[openingactualamount] [numeric](18, 2) NULL,
	[accountcode] [varchar](50) NULL,
	[accountdesc] [varchar](250) NULL,
	[departmentid] [int] NULL,
	[DepartmentName] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[JournalDetailBackup]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[JournalDetailBackup](
	[JournalID] [int] NOT NULL,
	[JournalDetailID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[FinancialId] [int] NOT NULL,
	[JournalCredit] [bit] NOT NULL,
	[AccountID] [int] NULL,
	[CustomerID] [int] NULL,
	[VendorID] [int] NULL,
	[Amount] [numeric](18, 2) NULL,
	[ActualAmount] [numeric](18, 2) NULL,
	[DepartmentID] [int] NULL,
 CONSTRAINT [PK_JournalDetailBackup] PRIMARY KEY NONCLUSTERED 
(
	[JournalID] ASC,
	[JournalDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[SpMag_FetchVehicleList]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[aaaa]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aaaa](
	[8-9 am] [numeric](18, 0) NULL,
	[9-10 am] [numeric](18, 0) NULL,
	[10-11 am] [numeric](18, 0) NULL,
	[11-12 am] [numeric](18, 0) NULL,
	[12-1 Pm] [numeric](18, 0) NULL,
	[1-2 Pm] [numeric](18, 0) NULL,
	[2-3 Pm] [numeric](18, 0) NULL,
	[3-4 Pm] [numeric](18, 0) NULL,
	[4-5 Pm] [numeric](18, 0) NULL,
	[5-6 Pm] [numeric](18, 0) NULL,
	[6-7 Pm] [numeric](18, 0) NULL,
	[7-8 Pm] [numeric](18, 0) NULL,
	[8-9 Pm] [numeric](18, 0) NULL,
	[9-10 Pm] [numeric](18, 0) NULL,
	[10-11 Pm] [numeric](18, 0) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losInhouseExchangeDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losInhouseExchangeDetail](
	[sedShopID] [int] NOT NULL,
	[sedExchangeID] [int] NOT NULL,
	[sedExchangedetailID] [int] NOT NULL,
	[sedItemID] [int] NOT NULL,
	[sedPackingTypeID] [int] NOT NULL,
	[sedPUnitID] [int] NULL,
	[sedPQuantity] [numeric](18, 3) NULL,
	[sedQuantity] [numeric](18, 3) NULL,
	[sedUnitPrice] [numeric](18, 2) NULL,
	[sedActualUnitPrice] [numeric](18, 2) NULL,
	[sedExchangePQty] [numeric](18, 2) NULL,
	[sedExchangeQty] [numeric](18, 2) NULL,
	[sedRateType] [int] NOT NULL,
	[sedBillorExchange] [char](1) NULL,
	[sedcostprice] [numeric](18, 2) NULL,
	[sedblockprice] [numeric](18, 2) NULL,
	[sedguarantee] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NULL,
	[sedSerialNo] [varchar](50) NULL,
	[sedFreeQty] [numeric](18, 3) NULL,
	[sedExcFreeQty] [numeric](18, 3) NULL,
 CONSTRAINT [PK_losInhouseExchangeDetail] PRIMARY KEY NONCLUSTERED 
(
	[sedShopID] ASC,
	[sedExchangeID] ASC,
	[sedExchangedetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[abarcodetype]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[abarcodetype](
	[barcodetype] [smallint] NOT NULL,
	[filename] [varchar](50) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_barcodetype] PRIMARY KEY NONCLUSTERED 
(
	[barcodetype] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_133575514] ON [dbo].[abarcodetype] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[JournalHeaderBackup]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[JournalHeaderBackup](
	[JournalID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[FinancialID] [int] NOT NULL,
	[JournalDate] [smalldatetime] NOT NULL,
	[Remarks] [varchar](250) NULL,
	[ReferenceNo] [varchar](50) NULL,
	[Type] [varchar](5) NULL,
	[CurrencyId] [int] NULL,
	[chequedate] [datetime] NULL,
 CONSTRAINT [PK_JournalHeaderBackup] PRIMARY KEY NONCLUSTERED 
(
	[JournalID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[adepcontrolaccounts]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[adepcontrolaccounts](
	[companyid] [int] NOT NULL,
	[maindepid] [int] NOT NULL,
	[otherdepid] [int] NOT NULL,
	[controlaccid] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [uniquerec] ON [dbo].[adepcontrolaccounts] 
(
	[maindepid] ASC,
	[otherdepid] ASC,
	[controlaccid] ASC,
	[companyid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[CrmEmailRecepients]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CrmEmailRecepients](
	[EmailId] [int] NOT NULL,
	[ContactId] [int] NOT NULL,
	[Type] [nchar](2) NULL,
	[CompanyId] [int] NULL,
	[Sent] [bit] NULL,
 CONSTRAINT [PK_CrmEmailRecepients] PRIMARY KEY CLUSTERED 
(
	[EmailId] ASC,
	[ContactId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'T for To,B Bcc,C Cc' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'CrmEmailRecepients', @level2type=N'COLUMN',@level2name=N'Type'
GO
/****** Object:  Table [dbo].[LMSCardRegistration]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LMSCardRegistration](
	[CompanyID] [int] NULL,
	[CardRegistrationID] [int] NULL,
	[CardNumber] [varchar](50) NULL,
	[RegistrationDate] [datetime] NULL,
	[CustmerId] [int] NULL,
	[UserName] [varchar](50) NULL,
	[TypeID] [int] NULL,
	[ExpairyDate] [datetime] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losExpiryVerificationDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losExpiryVerificationDetail](
	[evdId] [int] NOT NULL,
	[evdShipmentId] [int] NOT NULL,
	[evdItemId] [int] NOT NULL,
	[evdShopId] [int] NOT NULL,
	[evdAvailStock] [numeric](18, 3) NULL,
	[evdVerifiedStock] [numeric](18, 3) NULL,
	[evdCostPrice] [numeric](18, 3) NULL,
	[evdPrevExpiryDate] [datetime] NULL,
	[evdVerifiedExpiryDate] [datetime] NOT NULL,
	[evdPrevBatchNo] [varchar](20) NOT NULL,
	[evdBatchNo] [varchar](20) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CrmUserLastVisited]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmUserLastVisited](
	[UserId] [int] NOT NULL,
	[SaveOrder] [int] NOT NULL,
	[Link] [varchar](500) NOT NULL,
	[Module] [varchar](50) NOT NULL,
	[DisplayText] [varchar](250) NOT NULL,
	[CompanyId] [int] NOT NULL,
 CONSTRAINT [PK_CrmUserLastVisited] PRIMARY KEY CLUSTERED 
(
	[UserId] ASC,
	[SaveOrder] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[adistributormaster]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[adistributormaster](
	[did] [int] NOT NULL,
	[dcode] [varchar](50) NOT NULL,
	[dname] [varchar](250) NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_adistributormaster] PRIMARY KEY NONCLUSTERED 
(
	[did] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_325576198] ON [dbo].[adistributormaster] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ahpPaymentDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ahpPaymentDetail](
	[hpdCompanyID] [int] NOT NULL,
	[hpdDepartmentID] [int] NOT NULL,
	[hpdPaymentID] [int] NOT NULL,
	[hpdDetailID] [int] NOT NULL,
	[hpdReceiptID] [int] NOT NULL,
	[hpdProcessingDetailID] [int] NOT NULL,
 CONSTRAINT [PK_ahpPaymentDetail] PRIMARY KEY CLUSTERED 
(
	[hpdCompanyID] ASC,
	[hpdDepartmentID] ASC,
	[hpdPaymentID] ASC,
	[hpdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOUserGroupRights]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOUserGroupRights](
	[UserGroupID] [int] NOT NULL,
	[ModuleCode] [varchar](10) NOT NULL,
	[InterfaceID] [int] NOT NULL,
	[FunctionRights] [varchar](10) NOT NULL,
	[CompanyID] [int] NOT NULL,
	[userid] [int] NULL,
 CONSTRAINT [PK_LOUserGroupRights] PRIMARY KEY CLUSTERED 
(
	[UserGroupID] ASC,
	[InterfaceID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losHPResaleHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losHPResaleHeader](
	[hphCompanyID] [int] NOT NULL,
	[hphShopID] [int] NOT NULL,
	[hphResaleID] [int] NOT NULL,
	[hphResaleNo] [varchar](50) NOT NULL,
	[hphFinancialID] [int] NOT NULL,
	[hphResaleDate] [datetime] NOT NULL,
	[hphCustomerID] [int] NOT NULL,
	[hphCustomerName] [varchar](150) NULL,
	[hphCancel] [int] NOT NULL,
	[hphCancelRemarks] [nvarchar](250) NULL,
	[hphPosted] [int] NOT NULL,
	[hphUser] [varchar](50) NULL,
	[hphUpdatedUser] [varchar](50) NULL,
	[hphUpdatedTime] [datetime] NULL,
	[hphCashAccID] [int] NULL,
	[hphRemarks] [nvarchar](250) NOT NULL,
	[hphCustomerAddress] [varchar](1) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOUserGroups]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOUserGroups](
	[UserGroupID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[UserGroupName] [varchar](250) NOT NULL,
	[GroupDesc] [varchar](250) NOT NULL,
	[LOcation] [varchar](250) NOT NULL,
 CONSTRAINT [PK_LOUserGroups] PRIMARY KEY CLUSTERED 
(
	[UserGroupID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ahpPaymentHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ahpPaymentHeader](
	[hphCompanyID] [int] NOT NULL,
	[hphDepartmentID] [int] NOT NULL,
	[hphPaymentID] [int] NOT NULL,
	[hphPaymentNo] [varchar](50) NOT NULL,
	[hphRefNo] [nvarchar](50) NOT NULL,
	[hphPaymentDate] [datetime] NOT NULL,
	[hphFinancialID] [int] NOT NULL,
	[hphCustomerID] [int] NOT NULL,
	[hphAccountID] [int] NOT NULL,
	[hphRemarks] [nvarchar](250) NOT NULL,
	[hphPaymentAmount] [numeric](18, 2) NOT NULL,
	[hphCancel] [int] NULL,
	[hphCancelRemarks] [nvarchar](250) NULL,
	[hphPosted] [int] NOT NULL,
	[hphUserName] [varchar](50) NULL,
	[hphUpdateUserName] [varchar](50) NULL,
	[hphUpdateTime] [datetime] NULL,
	[hphBankExchangeRate] [numeric](18, 2) NULL,
	[hphCusExchangeRate] [numeric](18, 2) NULL,
	[hphDepExchangeRate] [numeric](18, 2) NULL,
	[hphComExchangeRate] [numeric](18, 2) NULL,
	[hprhCreditAccID] [int] NULL,
	[hprhCreditExRate] [numeric](18, 2) NULL,
	[hprhCreditAmount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_ahpPaymentHeader] PRIMARY KEY CLUSTERED 
(
	[hphCompanyID] ASC,
	[hphDepartmentID] ASC,
	[hphPaymentID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ahpProcessingCashFlowDetail]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ahpProcessingCashFlowDetail](
	[hpcComapnyID] [int] NOT NULL,
	[hpcDepartmentID] [int] NOT NULL,
	[hpcProcessingID] [int] NOT NULL,
	[hpcDetailID] [int] NOT NULL,
	[hpcDiscountFactor] [numeric](18, 16) NULL,
	[hpcRental] [numeric](18, 2) NULL,
	[hpcDiscountCashFlow] [numeric](18, 2) NULL,
 CONSTRAINT [PK_ahpProcessingCashFlowDetail] PRIMARY KEY CLUSTERED 
(
	[hpcComapnyID] ASC,
	[hpcDepartmentID] ASC,
	[hpcProcessingID] ASC,
	[hpcDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[fb_kotHistory]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[fb_kotHistory](
	[fb_kd_Companyid] [int] NOT NULL,
	[fb_kd_Outletid] [int] NOT NULL,
	[fb_kd_kotid] [int] NOT NULL,
	[fb_kd_kotdetailid] [int] NOT NULL,
	[fb_kd_dishid] [int] NOT NULL,
	[fb_kd_kotquantity] [decimal](18, 2) NULL,
	[fb_kd_rate] [decimal](18, 2) NULL,
	[fb_kd_processed] [bit] NOT NULL,
	[fb_kd_remarks] [varchar](250) NULL,
	[fb_kd_Setteled] [int] NULL,
	[fb_kd_AddedItemtype] [int] NULL,
 CONSTRAINT [PK_Fb_fb_kotHistory] PRIMARY KEY NONCLUSTERED 
(
	[fb_kd_Companyid] ASC,
	[fb_kd_Outletid] ASC,
	[fb_kd_kotid] ASC,
	[fb_kd_kotdetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'''1-Added Dish ''2-Added Item ''0-Ordinary Dish' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'fb_kotHistory', @level2type=N'COLUMN',@level2name=N'fb_kd_AddedItemtype'
GO
/****** Object:  Table [dbo].[LOUserMasterGridSettings]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOUserMasterGridSettings](
	[CompanyID] [int] NOT NULL,
	[UserID] [int] NOT NULL,
	[BackColor] [varchar](50) NOT NULL,
	[ForeColor] [varchar](50) NOT NULL,
	[GridColor] [varchar](50) NOT NULL,
	[HeaderColor] [varchar](50) NOT NULL,
	[FontName] [varchar](50) NOT NULL,
	[FontSize] [int] NOT NULL,
 CONSTRAINT [PK_LOUserMasterGridSettings] PRIMARY KEY CLUSTERED 
(
	[CompanyID] 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]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ahpReceiptDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ahpReceiptDetail](
	[hprdCompanyID] [int] NOT NULL,
	[hprdDepartmentID] [int] NOT NULL,
	[hprdReceiptID] [int] NOT NULL,
	[hprdDetailID] [int] NOT NULL,
	[hprdPaymentID] [int] NOT NULL,
	[hprdProcDetailId] [int] NULL,
	[hprdPaymentAmnt] [numeric](18, 2) NULL,
	[hprdSettledAmnt] [numeric](18, 2) NULL,
	[hprdCashSettledAmnt] [numeric](18, 2) NULL,
	[hprdChqSettledAmnt] [numeric](18, 2) NULL,
 CONSTRAINT [PK_ahpReceiptDetail] PRIMARY KEY CLUSTERED 
(
	[hprdCompanyID] ASC,
	[hprdDepartmentID] ASC,
	[hprdReceiptID] ASC,
	[hprdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ahpReceiptHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ahpReceiptHeader](
	[hprhCompanyId] [int] NOT NULL,
	[hprhDepartmentID] [int] NOT NULL,
	[hprhReceiptID] [int] NOT NULL,
	[hprhReceiptNo] [nvarchar](50) NOT NULL,
	[hprhReceiptDate] [datetime] NOT NULL,
	[hprhRefNo] [nvarchar](50) NULL,
	[hprhFinancialID] [int] NOT NULL,
	[hprhCustomerID] [int] NOT NULL,
	[hprhAccountID] [int] NOT NULL,
	[hprhAmount] [numeric](18, 2) NOT NULL,
	[hprhRemarks] [nvarchar](250) NOT NULL,
	[hprhChequeNo] [nvarchar](50) NULL,
	[hprhBankName] [nvarchar](50) NULL,
	[hprhCancel] [int] NOT NULL,
	[hprhCancelRemarks] [nvarchar](50) NULL,
	[hprhPosted] [int] NOT NULL,
	[hprhBankExRate] [numeric](18, 2) NOT NULL,
	[hprhCusExRate] [numeric](18, 2) NOT NULL,
	[hprhDepExRate] [numeric](18, 2) NOT NULL,
	[hprhComExRate] [numeric](18, 2) NOT NULL,
	[hprhUserName] [nvarchar](50) NOT NULL,
	[hprhUpdatedUserName] [nvarchar](50) NULL,
	[hprhUpdatedTime] [datetime] NULL,
	[hprhCreditAccID] [int] NULL,
	[hprhCreditExRate] [numeric](18, 2) NULL,
	[hprhCreditAmount] [numeric](18, 2) NULL,
	[hprhtype] [char](2) NULL,
	[hprhnewcheque] [bit] NULL,
	[hprhNewChequeNo] [nvarchar](100) NULL,
	[hprhNewBankName] [nvarchar](100) NULL,
 CONSTRAINT [PK_ahpReceiptHeader] PRIMARY KEY CLUSTERED 
(
	[hprhCompanyId] ASC,
	[hprhDepartmentID] ASC,
	[hprhReceiptID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ahqPostDatedChequeDetails]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ahqPostDatedChequeDetails](
	[CompanyID] [int] NOT NULL,
	[TransID] [int] NOT NULL,
	[DepartmentID] [int] NULL,
	[TransNo] [varchar](50) NOT NULL,
	[ChDate] [datetime] NOT NULL,
	[CustomerID] [int] NULL,
	[BankName] [varchar](50) NULL,
	[ChequeNo] [varchar](50) NOT NULL,
	[Amount] [numeric](18, 2) NOT NULL,
	[ChequeDate] [datetime] NOT NULL,
	[ShopID] [int] NOT NULL,
	[Status] [varchar](100) NOT NULL,
	[Remarks] [varchar](550) NOT NULL,
	[Cancel] [int] NULL,
	[CustomerName] [varchar](50) NULL,
	[PoshBillID] [int] NULL,
	[FinancialID] [int] NULL,
	[exchangerate] [numeric](18, 8) NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF
ALTER TABLE [dbo].[ahqPostDatedChequeDetails] ADD [depexchangerates] [varchar](250) NULL
ALTER TABLE [dbo].[ahqPostDatedChequeDetails] ADD [updatetime] [datetime] NOT NULL
ALTER TABLE [dbo].[ahqPostDatedChequeDetails] ADD [exchangerates] [varchar](250) NULL
ALTER TABLE [dbo].[ahqPostDatedChequeDetails] ADD [Bankid] [int] NULL
GO
SET ANSI_PADDING OFF
GO
/****** Object:  UserDefinedFunction [dbo].[fnSplit]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------          
--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
GO
/****** Object:  Table [dbo].[LOsPosdummyDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsPosdummyDetail](
	[posdShopID] [int] NOT NULL,
	[posdBillID] [int] NOT NULL,
	[posdItemID] [int] NOT NULL,
	[posdPackingTypeID] [int] NOT NULL,
	[posdPUnitID] [int] NULL,
	[posdPQuantity] [numeric](18, 3) NULL,
	[posdQuantity] [numeric](18, 3) NULL,
	[posdUnitPrice] [numeric](18, 8) NULL,
	[posdRateType] [int] NOT NULL,
	[posdActualUnitPrice] [numeric](18, 2) NULL,
	[posdcostprice] [numeric](18, 2) NULL,
	[posddescription] [varchar](250) NULL,
	[posdblockprice] [numeric](18, 2) NULL,
	[posdguarantee] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[posdSerialNo] [varchar](250) NULL,
	[posdFreeQuantity] [numeric](18, 3) NULL,
	[posdItemSerialNo] [int] NULL,
	[posdItemTaxPercentage] [numeric](18, 8) NULL,
	[posdItemTaxAmount] [numeric](18, 8) NULL,
	[posdItemTaxCategory] [int] NULL,
	[posdBillDetailID] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOsPosdummyHeader]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsPosdummyHeader](
	[poshShopID] [int] NOT NULL,
	[poshBillID] [int] NOT NULL,
	[poshBillNo] [varchar](50) NULL,
	[poshBillDate] [datetime] NULL,
	[poshCustomerName] [varchar](100) NULL,
	[poshCancelled] [bit] NOT NULL,
	[poshCancelledRemarks] [varchar](250) NULL,
	[poshRecAddUser] [varchar](50) NULL,
	[poshRecModifyUser] [varchar](50) NULL,
	[poshPosted] [bit] NOT NULL,
	[poshDiscount] [numeric](18, 2) NULL,
	[poshBillAmount] [numeric](18, 2) NULL,
	[poshCashAccID] [int] NULL,
	[poshSalesAccID] [int] NULL,
	[poshCompanyID] [int] NULL,
	[poshReturned] [bit] NOT NULL,
	[poshWholesale] [bit] NOT NULL,
	[poshcbid] [int] NULL,
	[poshExchangeRate] [numeric](28, 8) NOT NULL,
	[poshfuturevc] [varchar](250) NULL,
	[updatetime] [datetime] NOT NULL,
	[poshDepartmentid] [int] NULL,
	[poshsalespersonid] [int] NULL,
	[poshcustomerid] [int] NULL,
	[poshCustomerCardNo] [varchar](100) NULL,
	[poshfutureint] [int] NULL,
	[poshcurexrates] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[poshdepexrate] [numeric](18, 8) NULL,
	[poshexchangerates] [varchar](250) NULL,
	[poshUserId] [int] NULL,
	[poshCounterId] [int] NULL,
	[ContactCardNo] [varchar](50) NULL,
	[poshDiscountAmt] [numeric](18, 2) NULL,
	[poshBalance] [numeric](18, 2) NULL,
	[poshBillTime] [datetime] NULL,
	[poshbilled] [int] NULL,
	[poshconfirmed] [int] NULL,
	[poshBilledId] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aloGroupreportrights]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aloGroupreportrights](
	[userGroupid] [int] NOT NULL,
	[reportid] [int] NOT NULL,
	[modulecode] [varchar](50) NULL,
	[Companyid] [int] NOT NULL,
 CONSTRAINT [PK_aloGroupreportrights] PRIMARY KEY CLUSTERED 
(
	[userGroupid] ASC,
	[reportid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOsPurchaseReturnDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOsPurchaseReturnDetail](
	[wdShopID] [int] NOT NULL,
	[WdID] [int] NOT NULL,
	[WdItemID] [int] NOT NULL,
	[WdShipmentID] [int] NOT NULL,
	[WdAvailableQty] [numeric](18, 3) NULL,
	[WdPurchaseReturnQty] [numeric](18, 3) NULL,
	[wdcostprice] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_losPurchaseReturndetail] ON [dbo].[LOsPurchaseReturnDetail] 
(
	[WdID] ASC,
	[wdShopID] 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


/****** Object:  Table [dbo].[aTaxCategoryMaster]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aTaxCategoryMaster](
	[TaxCompanyId] [int] NOT NULL,
	[TaxId] [int] NOT NULL,
	[TaxCategoryCode] [varchar](25) NOT NULL,
	[TaxDescription] [varchar](250) NOT NULL,
	[TaxPercentage] [numeric](18, 2) NULL,
	[TaxAccountable] [bit] NOT NULL,
	[TaxCancelled] [int] NOT NULL,
	[TaxType] [int] NULL,
	[TaxAccountId] [int] NOT NULL,
	[TaxInputAccountId] [int] NOT NULL,
 CONSTRAINT [PK_aTaxCategoryMaster] PRIMARY KEY NONCLUSTERED 
(
	[TaxCompanyId] ASC,
	[TaxId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [UQ__aTaxCategoryMast__387BD129] UNIQUE NONCLUSTERED 
(
	[TaxCategoryCode] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aloreportrights]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aloreportrights](
	[userid] [int] NOT NULL,
	[reportid] [int] NOT NULL,
	[modulecode] [varchar](50) NULL,
	[Companyid] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LeadTimeDivision]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LeadTimeDivision](
	[Ldivisionid] [int] NOT NULL,
	[LdivisionName] [varchar](50) NOT NULL,
	[LDivisionCompanyid] [int] NOT NULL,
 CONSTRAINT [PK_LeadTimeDivision] PRIMARY KEY NONCLUSTERED 
(
	[Ldivisionid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LoaEoqProcessDetail]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LoaEoqProcessDetail](
	[EoqDProcessid] [int] NULL,
	[EoqDItemCategoryId] [int] NULL,
	[EodItemId] [int] NULL,
	[EoqdFixedCost] [numeric](18, 4) NULL,
	[EoqdReorderQty] [numeric](18, 4) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[amarketrates]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[amarketrates](
	[itemid] [int] NOT NULL,
	[marketone] [varchar](50) NULL,
	[markettwo] [varchar](50) NULL,
	[priceone] [numeric](18, 0) NULL,
	[pricetwo] [numeric](18, 0) NULL,
	[remarks] [nvarchar](500) NULL,
	[username] [varchar](20) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[amisUserRights]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[amisUserRights](
	[UserID] [int] NULL,
	[MenuID] [int] NULL,
	[CompanyID] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LoaEoqProcessHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LoaEoqProcessHeader](
	[EoqProcessid] [int] NULL,
	[EoqProcessDate] [datetime] NULL,
	[EoqProcessNo] [varchar](25) NULL,
	[EoqProcessedBy] [varchar](100) NULL,
	[EoqSalesFDate] [datetime] NULL,
	[EoqSalesTDate] [datetime] NULL,
	[EoqPurchaseFDate] [datetime] NULL,
	[EoqPurchaseTDate] [datetime] NULL,
	[EoqProcessRemarks] [varchar](250) NULL,
	[EoqProcessDepartmentId] [int] NULL,
	[EoqProcessCompanyid] [int] NULL,
	[EoqCategoryid] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spSeasonalSalesPrediction]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spSettledInvoice]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[arecentmenu]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[arecentmenu](
	[interfaceid] [int] NULL,
	[userid] [int] NULL,
	[usertype] [int] NULL,
	[recentid] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LoiMergeHeader]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LoiMergeHeader](
	[lghID] [int] NOT NULL,
	[lghCompanyID] [int] NOT NULL,
	[lghGodownID] [int] NOT NULL,
	[lghNo] [varchar](50) NULL,
	[lghDate] [datetime] NULL,
	[lghRefMergeID] [int] NULL,
	[lghItemID] [int] NULL,
	[lghTransFinished] [bit] NULL,
	[lghCancelled] [bit] NULL,
	[lghUpdatetime] [datetime] NULL,
	[lghQty] [numeric](18, 3) NULL,
	[lghNoofRec] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[CryptPwd]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  Table [dbo].[areprecvendordetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[areprecvendordetail](
	[rrvdcompanyid] [int] NOT NULL,
	[rrvdreceiveid] [int] NOT NULL,
	[rrvddetailid] [int] NOT NULL,
	[rrvdshopid] [int] NULL,
	[rrvdrepreqid] [int] NULL,
	[rrvdbookingid] [int] NULL,
	[rrvditemid] [int] NULL,
	[rrvdqty] [numeric](18, 3) NULL,
	[rrvdtochargeprice] [numeric](18, 2) NULL,
	[rrvdselected] [bit] NOT NULL,
	[rrvdshopcount] [int] NULL,
 CONSTRAINT [PK_areprerecvendordetail] PRIMARY KEY NONCLUSTERED 
(
	[rrvdcompanyid] ASC,
	[rrvdreceiveid] ASC,
	[rrvddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosApartmentcategory]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosApartmentcategory](
	[rccompanyid] [int] NOT NULL,
	[rcshopid] [int] NOT NULL,
	[rcapartmentcategoryid] [int] NOT NULL,
	[rcapartmentcategorycode] [varchar](25) NULL,
	[rcapartmentcategorydescription] [varchar](50) NULL,
 CONSTRAINT [pk_LosApartmentcategory] PRIMARY KEY CLUSTERED 
(
	[rccompanyid] ASC,
	[rcshopid] ASC,
	[rcapartmentcategoryid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aservicelocations]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aservicelocations](
	[serlocid] [int] NOT NULL,
	[serlocname] [varchar](100) NULL,
	[serlocaddress] [varchar](250) NULL,
	[serlocphone] [varchar](100) NULL,
	[serloccomments] [varchar](250) NULL,
	[serloctype] [varchar](5) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aservicelocations] PRIMARY KEY NONCLUSTERED 
(
	[serlocid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_485576768] ON [dbo].[aservicelocations] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosFacilityTracking]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosFacilityTracking](
	[ftShopid] [int] NOT NULL,
	[ftCompanyId] [int] NOT NULL,
	[ftTrackId] [int] NOT NULL,
	[ftTrackNo] [varchar](50) NULL,
	[ftTrackDate] [datetime] NULL,
	[ftAgreementid] [int] NOT NULL,
	[ftBookingId] [int] NOT NULL,
	[ftBookingDetailId] [int] NULL,
	[ftFaclityID] [int] NOT NULL,
	[ftCheckInTime] [datetime] NULL,
	[ftCheckOutTime] [datetime] NULL,
	[ftChectoutdate] [datetime] NULL,
	[ftcheckinEnteredBy] [int] NULL,
	[ftcheckoutEnteredBy] [int] NULL,
	[ftcheckinCancelled] [bit] NOT NULL,
	[ftcheckinRemark] [varchar](250) NULL,
	[ftcheckoutRemark] [varchar](250) NULL,
	[ftcheckincancellremark] [varchar](250) NULL,
 CONSTRAINT [PK_LosFacilityTracking] PRIMARY KEY NONCLUSTERED 
(
	[ftShopid] ASC,
	[ftCompanyId] ASC,
	[ftTrackId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[SpShopItemSalesForBudget]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spCompanyOpeningStockAsOnDate]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------        
-- 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
GO
/****** Object:  Table [dbo].[ausergroupAccGroupDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ausergroupAccGroupDetails](
	[CompanyID] [int] NOT NULL,
	[UserGroupID] [int] NOT NULL,
	[AccGroupID] [int] NOT NULL,
	[Rowguid] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_ausergroupAccDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[UserGroupID] ASC,
	[AccGroupID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosPackingListHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosPackingListHeader](
	[plhShopId] [int] NOT NULL,
	[plhPackListId] [int] NOT NULL,
	[plhNo] [varchar](50) NULL,
	[plhDate] [datetime] NULL,
	[plhExportId] [int] NULL,
	[plhConsigneeAdress] [varchar](250) NULL,
	[plhOtherRefNo] [varchar](50) NULL,
	[plhExporterRefNo] [varchar](50) NULL,
	[plhPreCarriageBy] [varchar](50) NULL,
	[plhPlaceofReceipt] [varchar](50) NULL,
	[plhVessalNo] [varchar](50) NULL,
	[plhVoyageNo] [varchar](50) NULL,
	[plhPortOfLoading] [varchar](50) NULL,
	[plhPortOfDisCharge] [varchar](50) NULL,
	[plhFinalDest] [varchar](50) NULL,
	[plhTotalPacks] [varchar](50) NULL,
	[plhTotalVolume] [varchar](50) NULL,
	[plhTotalWeight] [varchar](50) NULL,
	[plhTerms] [varchar](50) NULL,
	[plhRemarks] [varchar](250) NULL,
	[plhCancelled] [int] NULL,
	[plhCancelledRemarks] [varchar](250) NULL,
	[plhExporterAddress] [varchar](250) NULL,
 CONSTRAINT [pk_LosPackingListHeader] PRIMARY KEY CLUSTERED 
(
	[plhShopId] ASC,
	[plhPackListId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateGodownGoodCheck]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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*/
*/
GO
/****** Object:  StoredProcedure [dbo].[spMag_IsInvoiceFullyDelivered]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================================================
-- 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
GO
/****** Object:  Table [dbo].[billdate]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[billdate](
	[billdate] [datetime] NULL,
	[cntdate] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwShopBincardAuditSummary]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ===============================================      
-- Author      : Regin T.      
-- Create Date : 03-08-2010      
-- Description :       
-- Generates vwShopBincardAuditSummary with hardcoded summary date.  
--  It is found that hardcoded date improves the performance of the view.  
--  This view is created to increase the speed of calculating item stock.  
-- ===============================================   
-- Referenc No  : Ref-No1          
-- Modified by	: MANUNADH.U      
-- Modified on	: 26/03/2012              
-- Comments     : Add the condition to filter local purchase bill with lphConfirmed=1
-- ===============================================
CREATE PROC [dbo].[spMag_GenerateVwShopBincardAuditSummary]  
    @strSummaryDate as varchar(8)  
AS  
BEGIN  
 -- Since a variable cannot store more than 8000 chars,   
 -- the query is directly executed using EXEC command.  
  
    EXEC (  
'IF EXISTS ( SELECT * FROM SYSOBJECTS WHERE XTYPE=''V'' AND NAME=''vwShopBincardAuditSummary'')  
DROP VIEW vwShopBincardAuditSummary')  
  
 EXEC (  
'-- =============================================================================  
-- This view was automatically generated   
-- by spMag_GenerateVwShopBincardAuditSummary.  
-- Alter above proc to make any change in this view.  
-- =============================================================================   
-- Author      : Regin T.  
-- Create Date : 03-08-2010  
-- Description :   
--    This view was created based on vwShopBincardAudit.  
--    Summary Date filtering was added additionally.  
--    Group By clause was removed to improve performance.  
--    This view is used to compute item stock in Transactions Summary method.  
-- =============================================================================        
CREATE VIEW vwShopBincardAuditSummary AS                              
          
SELECT h.gahshopid ShopId, d.gaditemid ItemId, h.gaharrivaldate sDate,                               
NULL TransNo, NULL TransId,                                
d.gadItemGoodQuantityArrived TransQty,                               
''Arrival From Godown'' [Type], 1 Mode, NULL UpdateTime, NULL CostPrice,                               
NULL DepCostPrice, NULL ConCostPrice           
FROM losgoodsarrivaltoshopheader h, losgoodsarrivaltoshopdetail d   
WHERE h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and                               
h.gahtransfinished=1 and h.gaharrivaldate>'''+@strSummaryDate+'''         
                              
--GOODS RETURN TO SHOPS FROM CREDIT INVOICES                              
UNION ALL                              
                              
SELECT grn.grnhShopid, grd.GRNDItemID, GrnhGoodsreturnnoteDate,                              
NULL, NULL, GRNDQuantity, ''Goods Return'', 1 as mode,   
NULL, NULL, NULL, NULL          
from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd                              
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid =                               
grd.GRNDShopid and GrnhCancel=0 and GRNDDamaged=0 and GrnhGoodsreturnnoteDate>'''+@strSummaryDate+'''                              
                              
union all                              
                              
--transfer in                              
select h.tihshopid,  d.tiditemid, h.tihdate, NULL, NULL,                               
d.TIDrecievedgoodqty, ''Transfer In'', 1 mode,                               
NULL, NULL, NULL, NULL  
from lostransferinheader h, lostransferindetail d where h.tihid=d.tidid and                               
h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1        
and h.tihdate>'''+@strSummaryDate+'''        
                              
union all                              
                              
--recovery add                              
select sr.srshopid, sr.sritemid, sr.srdate, NULL, NULL,                                                   
sum(sr.sraddstock) as recAdd, ''Recovery Plus'', 1 Mode,   
NULL, NULL, NULL, NULL  
from                               
losstockrecovery sr       
where sr.srdate>'''+@strSummaryDate+'''          
group by  sr.srshopid, sr.srdate, sr.srid, sr.sritemid  
having isnull(sum(sr.sraddstock),0) >0                              
                              
union all                              
                              
--stock verification add                              
select svdshopid, svdItemid, svhDate, NULL, NULL,                               
svdVerifiedStock-svdAvailStock as svAddQty,                               
''Verification Plus'', 1 mode, NULL, NULL, NULL, NULL                                
from  losstockverificationheader, losstockverificationdetail where                              
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock                   
and svhCancelled=0 and  left(svhFutureVc, 1) <> ''t''        
and svhDate>'''+@strSummaryDate+'''                                 
                        
union all                              
                              
--TOTAL stock verification add                              
select svdshopid, svdItemid, svhDate, svhno, svhid,                               
svdVerifiedStock-svdAvailStock as svAddQty,                               
''Verification Plus'', 1 mode, NULL, NULL, NULL, NULL  
from  losstockverificationheader, losstockverificationdetail where                              
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock                              
and svhCancelled=0 and  left(svhFutureVc, 2) = ''tc''        
and svhDate>'''+@strSummaryDate+'''          
                                    
union all                              
                              
--exchange in                              
select sehShopID, seditemid, sehExchangeDate, NULL, NULL,                                
sedExchangeQty, ''Exchanged In'',1 mode, NULL, NULL, NULL, NULL  
FROM losposexchangeheader, losposexchangedetail where sedExchangeid=sehExchangeID                               
and sedShopID=sehShopid and sedBillorExchange=''B'' and SEHCANCELLED=0                              
and isnull(sedExchangeQty,0) >0          
and sehExchangeDate>'''+@strSummaryDate+'''                          
                              
union all                              
                              
--local purchase                              
select lphShopid,lpditemid,lphbilldate,NULL,NULL,lpdItemQuantity,''Local Purchase'',1 mode,NULL,NULL,NULL,NULL                                  
from loslocalpurchasedetail, loslocalpurchaseheader   
where lphBillId=lpdBillID and lphShopID= lpdShopid and lphCancelled=0 and lphbilldate>'''+@strSummaryDate+'''       
	and lphConfirmed=1--<<Ref-No1>>
                              
union all                              
                              
--write off                              
select wh.whshopid, wd.wditemid, wh.whdate, NULL, NULL,                               
wd.wdWriteoffQty, ''Write off'', -1 mode, NULL, NULL, NULL, NULL                               
from loswriteoffheader wh, loswriteoffdetail wd                              
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0       
and wh.whdate>'''+@strSummaryDate+'''          
                              
union all                              
                              
--Deapatch                              
select dd.dgdshopid, dd.dgditemid, dh.dghDate, NULL, NULL,                               
dd.dgddespatchedgoodqty, ''Despatch To Godown'' TYpe, -1 mode,  
NULL, NULL, NULL, NULL                             
from mesdespatchtogodownheader dh, mesdespatchtogodowndetail dd                               
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0                 
and dghtransfinished = 1 -- for the concept of stock updation after transaction finish         
and dh.dghDate>'''+@strSummaryDate+'''                            
                             
union all                              
                              
--Transferout                              
select todshopid, toditemid, tohDate, NULL, NULL,                               
todissuedgoodqty, ''Transfer Out'',-1 mode, NULL, NULL, NULL, NULL                               
from mestransferoutheader , mestransferoutdetail  where                              
tohid=todid and Tohshopid=todshopid and tohcancelled=0                              
and tohtransfinished = 1 -- for the concept of stock updation after transaction finish         
and tohDate>'''+@strSummaryDate+'''                            
                              
union all                              
                              
--recovery minus                              
select sr.srshopid, sr.sritemid, sr.srdate, NULL, NULL,                             
sum(sr.srdedstock) as recAdd, ''Recovery Minus'',-1 Mode,   
NULL, NULL, NULL, NULL from                               
losstockrecovery sr        
where sr.srdate>'''+@strSummaryDate+'''         
group by  sr.srshopid, sr.srdate, sr.srid, sr.sritemid   
having sum(isnull(sr.srdedstock,0)) >0                              
                              
union all                              
                       
--stockverification minus                              
select svdshopid, svdItemid, svhDate, NULL, NULL,                               
svdAvailStock-svdVerifiedStock, ''Verification Minus'', -1 mode,  
NULL, NULL, NULL, NULL                                
from  losstockverificationheader, losstockverificationdetail where                              
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock                              
and svhCancelled=0 and  left(svhFutureVc, 1) <> ''t''         
and svhDate>'''+@strSummaryDate+'''        
                        
union all                              
                              
--Total stockverification minus                              
select svdshopid, svdItemid, svhDate, NULL, NULL,                               
svdAvailStock-svdVerifiedStock, ''Verification Minus'', -1 mode,  
NULL, NULL, NULL, NULL                        
from  losstockverificationheader, losstockverificationdetail where                              
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock                              
and svhCancelled=0 and  left(svhFutureVc, 2) = ''tc''           
and svhDate>'''+@strSummaryDate+'''      
                      
union all                              
                              
--pos sales                              
select poshShopID, posditemid, poshBilldate, NULL, NULL,                               
posdquantity, ''Cash Sales'', -1 mode, NULL, NULL, NULL, NULL  
from losposdetail,losposheader                               
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0        
and poshBilldate>'''+@strSummaryDate+'''       
                              
union all                              
                              
--credit invoice                              
select IhShopid, iditemid, ihInvoicedate, NULL, NULL,                                
idquantity, ''Credit Sales'', -1 mode, NULL, NULL, NULL, NULL                               
from losinvoicedetail,losinvoiceheader                              
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0                              
and ihType =''I''           
and ihInvoicedate>'''+@strSummaryDate+'''      
                           
union all                              
                              
--exchange out                              
select sehShopID, seditemid, sehExchangeDate, NULL, NULL,                                
sedquantity, ''Exchange Out'', -1 mode, NULL, NULL, NULL, NULL  
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID                               
and sedShopID=sehShopid and sedBillorExchange=''E'' and SEHCANCELLED=0         
and sehExchangeDate>'''+@strSummaryDate+'''       
                              
union all         
                              
--special invoice return to shop                              
select IhShopid, iditemid, ihInvoicedate, NULL, NULL,  
-reqqty, ''Special Invoice Return'', 1 mode, NULL, NULL, NULL, NULL  
from losspecialinvoicedetail, losspecialinvoiceheader                              
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1                              
and ihproforma=0 and ihTransFinished = 1         
and ihInvoicedate>'''+@strSummaryDate+'''        
                              
union all                              
                              
select serinvhShopid, repinvdpartsid, serinvhdate, NULL, NULL,                                
repinvdqty, ''Parts Replaced'', -1 as mode, NULL, NULL, NULL, NULL  
from losinvoicedpartsreplacedetails, losserviceinvheader where serinvhid = repinvinvoiceid                                
and serinvhshopid = repinvdshopid AND serinvhcancelled=0        
and serinvhdate>'''+@strSummaryDate+'''                             
                              
union all                              
                               
--Re-Exporting                              
select rehShopID, reditemid,  rehExportDate, NULL, NULL,                              
redquantity, ''Re-Export'', -1 mode, NULL, NULL, NULL, NULL  
from losexportdetail, losexportheader                              
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0                              
and rehType=''I''          
and rehExportDate>'''+@strSummaryDate+'''       
                       
union all                        
                      
--MerGing minus                        
select lsdShopID, lsdItemID, lshDate, NULL, NULL,                          
sum(lsdqty), ''Merging Deduct'', -1 as mode, NULL, NULL, NULL, NULL  
from losMergeDetails md, losMergeHeader mh                         
where md.lsdid = mh.lshid                         
and md.lsdShopid = mh.lshShopId                         
and lshCancelled=0          
and lshDate>'''+@strSummaryDate+'''        
group by lsdShopID, lsdItemID, lshDate, lshid  
Having Sum(lsdQty) <> 0                         
                        
union all                        
                      
--MerGing Add                        
select lsdShopID, lshItemID, lshDate, NULL, NULL,                          
sum(lsdqty), ''Merging Add'', 1 as mode, NULL, NULL, NULL, NULL  
from losMergeDetails md, losMergeHeader mh                         
where md.lsdid = mh.lshid                         
and md.lsdShopID = mh.lshShopid                         
and lshCancelled = 0        
and lshDate>'''+@strSummaryDate+'''           
group by lsdShopID, lshItemID, lshDate, lshid  
Having Sum(lsdQty) <> 0               
               
union all                        
                        
--Purchase Return                        
select Ph.whshopid, Pd.wditemid, Ph.whdate, NULL, NULL,                         
Pd.wdPurchaseReturnQty, ''Purchase Return'', -1 mode, NULL, NULL, NULL, NULL  
from losPurchaseReturnheader Ph, losPurchaseReturndetail Pd                        
where Ph.whid=Pd.wdid and Ph.whshopid=Pd.wdshopid and Ph.whcancelled=0 and Ph.whtransfinished=1         
and Ph.whdate>'''+@strSummaryDate+'''        
                    
union all                              
                             
--Warrenty Claim/Business promotion                                 
select wchShopID, wcditemid, wchdate, NULL, NULL,                               
wcdQty, ''WC/BP'', -1 mode, NULL, NULL, NULL, NULL  
from losWarrentyClaimDetail,losWarrentyClaimHeader                               
where wchID=wcdID and wchShopid=wcdshopid AND WCHCANCELLED=0        
and wchdate>'''+@strSummaryDate+'''         
                             
union all                            
                            
-----Hire Purchase Invoice                            
select hpqhShopid,hpqdItemId,hpqhQuotationDate, NULL, NULL,          
1 as Qty, ''Hire Purchase'', -1 mode, NULL, NULL, NULL, NULL  
from loshpInvoiceDetail,losHpInvoiceHeader where hpqdQuotationid=hpqhQuotationID and hpqdShopid=hpqhShopid and                            
hpqhCancel=0 and hpqhType=''I''        
and hpqhQuotationDate>'''+@strSummaryDate+'''')  
  
END
GO
/****** Object:  Table [dbo].[bincardstock]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[bincardstock](
	[locationid] [int] NULL,
	[itemdesc] [varchar](250) NULL,
	[itemid] [int] NULL,
	[curstock] [numeric](18, 3) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CrmLeadMaster]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[CrmLeadMaster](
	[LeadId] [int] NOT NULL,
	[LeadSource] [varchar](50) NOT NULL,
	[Discription] [varchar](1000) NOT NULL,
	[CompanyId] [int] NOT NULL,
 CONSTRAINT [PK_CrmLeadMaster] PRIMARY KEY CLUSTERED 
(
	[LeadId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LosServiceInvHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosServiceInvHeader](
	[serinvhid] [int] NOT NULL,
	[serinvhcompanyid] [int] NOT NULL,
	[serinvhshopid] [int] NOT NULL,
	[serinvhjobcardid] [int] NULL,
	[serinvno] [varchar](50) NULL,
	[serinvhrefno] [varchar](50) NULL,
	[serinvhdate] [datetime] NULL,
	[serinvhduedate] [datetime] NULL,
	[serinvhpreparedby] [varchar](50) NULL,
	[serinvhcancelled] [bit] NULL,
	[serinvhserviceamt] [numeric](18, 2) NULL,
	[serinvhpartsamt] [numeric](18, 2) NULL,
	[serinvhamount] [numeric](18, 2) NULL,
	[serinvhposted] [bit] NULL,
	[serinvhdepartmentid] [int] NULL,
	[serinvhcashacc] [int] NULL,
	[serinvhsalesacc] [int] NULL,
	[serinvhservacc] [int] NULL,
	[serinvhcmpexrate] [numeric](18, 8) NULL,
	[serinvhresexrate] [numeric](18, 8) NULL,
	[serinvhbaserate] [numeric](18, 8) NULL,
	[serinvhsettled] [numeric](18, 2) NULL,
	[serinvhremarks] [varchar](250) NULL,
	[serinvcancelremarks] [varchar](250) NULL,
	[serinvhupdatetime] [datetime] NULL,
	[serinvhlocid] [int] NULL,
	[serinvhitemname] [varchar](250) NULL,
	[serinvhitemid] [int] NULL,
	[serinvhDiscount] [numeric](18, 2) NULL,
	[serinvhfutureint] [int] NULL,
	[serinvhfuturevc] [varchar](250) NULL,
	[serinvhfuturenumuric] [numeric](18, 18) NULL,
	[serinvfinancialid] [int] NULL,
	[seinvhdepexrate] [numeric](9, 2) NULL,
	[serinvhfree] [bit] NULL,
	[serinvhexchangerates] [varchar](250) NULL,
	[serinvhcustname] [varchar](250) NULL,
	[serinvhcategid] [int] NULL,
	[serinvhmetereading] [varchar](100) NULL,
	[serinvhCustomerId] [int] NULL,
	[serinvhCashInv] [bit] NULL,
	[serinvhuserid] [int] NULL,
	[serinvhRegID] [int] NULL,
	[serinvhTaxCateID] [int] NULL,
	[serinvhTaxPercentage] [numeric](18, 2) NULL,
	[serinvhTaxamount] [numeric](18, 2) NULL,
 CONSTRAINT [pk_losserviceinvheader] PRIMARY KEY CLUSTERED 
(
	[serinvhid] ASC,
	[serinvhshopid] ASC,
	[serinvhcompanyid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_losserviceinvheader_serinvhdate] ON [dbo].[LosServiceInvHeader] 
(
	[serinvhdate] 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
CREATE NONCLUSTERED INDEX [index_losserviceinvheader] ON [dbo].[LosServiceInvHeader] 
(
	[serinvhid] ASC,
	[serinvhshopid] ASC,
	[serinvhcancelled] 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
/****** Object:  StoredProcedure [dbo].[spAdvancePaymentsNotSettled]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[lmsPoint]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[lmsPoint](
	[CompanyID] [int] NOT NULL,
	[PointsID] [int] NOT NULL,
	[PointDesc] [varchar](50) NULL,
	[PointCategory] [int] NULL,
	[MinimumPoints] [int] NULL,
	[CurrencyID] [int] NULL,
	[PointValue] [int] NULL,
	[UserName] [varchar](50) NULL,
 CONSTRAINT [PK_lmsPoint] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[PointsID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Losdisplaymode]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Losdisplaymode](
	[Dispmodeid] [int] NULL,
	[Dispmodename] [varchar](100) NULL,
	[Dispmodevalue] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spAsonDateStockDepwise]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spGodownPriceList]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[aComboItemDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aComboItemDetail](
	[ComboId] [int] NOT NULL,
	[ItemId] [int] NOT NULL,
	[PackingTypeId] [int] NOT NULL,
	[UnitId] [int] NOT NULL,
	[PackingTypeQty] [numeric](18, 2) NOT NULL,
	[Qty] [numeric](18, 2) NOT NULL,
	[Price] [numeric](18, 3) NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[InhouseConsumptionReqHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[InhouseConsumptionReqHeader](
	[StoreRequestId] [int] NOT NULL,
	[StoreRequestNo] [varchar](50) NOT NULL,
	[RequestDate] [datetime] NOT NULL,
	[DepartmentId] [int] NOT NULL,
	[ShopId] [int] NULL,
	[Deleted] [bit] NOT NULL,
	[DeletedReason] [nvarchar](250) NULL,
	[FinancialYearId] [int] NOT NULL,
	[CompanyId] [int] NOT NULL,
	[AppovalStatus] [char](2) NOT NULL,
	[RejectionReason] [nvarchar](500) NULL,
	[Remarks] [nvarchar](500) NULL,
	[ReqUserId] [int] NOT NULL,
	[DelUserId] [int] NULL,
	[LastModUserId] [int] NULL,
 CONSTRAINT [PK_InHouseConsumtionRequest] PRIMARY KEY CLUSTERED 
(
	[StoreRequestId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aAutoGenerateInvoiceRiminder]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aAutoGenerateInvoiceRiminder](
	[ReminderGroupID] [int] NULL,
	[CustomerID] [int] NULL,
	[InvoiceID] [int] NULL,
	[InvoiceDate] [datetime] NULL,
	[DepartmentID] [int] NULL,
	[generated] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosserToolsReturnDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosserToolsReturnDetail](
	[tlretdCompanyId] [int] NOT NULL,
	[tlretdShopid] [int] NOT NULL,
	[tlretdid] [int] NOT NULL,
	[tlretdetailid] [int] NOT NULL,
	[tlretdtoolsid] [int] NULL,
	[tlretdcomments] [varchar](250) NULL,
 CONSTRAINT [PK_LosserToolsReturnDetail] PRIMARY KEY NONCLUSTERED 
(
	[tlretdCompanyId] ASC,
	[tlretdShopid] ASC,
	[tlretdid] ASC,
	[tlretdetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spBudgetCostSales]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[loPurchaseOrderHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loPurchaseOrderHeader](
	[pohPoid] [int] NOT NULL,
	[pohpono] [varchar](50) NOT NULL,
	[pohnoSupwise] [varchar](50) NULL,
	[pohPodate] [datetime] NULL,
	[pohVendorID] [int] NULL,
	[pohSupAddr] [varchar](250) NULL,
	[pohdueDate] [datetime] NULL,
	[pohdeliveryaddr] [varchar](250) NULL,
	[pohRefNo] [varchar](50) NULL,
	[pohcancel] [bit] NOT NULL,
	[pohcancelremarks] [varchar](250) NULL,
	[pohPosted] [bit] NOT NULL,
	[pohrecadduser] [varchar](50) NULL,
	[pohrecmoduser] [varchar](50) NULL,
	[pohbillgenerated] [bit] NOT NULL,
	[pohremarks] [varchar](250) NULL,
	[pohtype] [char](2) NULL,
	[pohValue] [numeric](28, 2) NULL,
	[pogenerated] [bit] NOT NULL,
	[pohpogenerated] [bit] NOT NULL,
	[pohQuotationid] [int] NULL,
	[pohUsedinPayments] [bit] NOT NULL,
	[pohLCopened] [bit] NOT NULL,
	[pohDepartmentid] [int] NULL,
	[pohLCAccountid] [int] NULL,
	[pohPurchaseAccountid] [int] NULL,
	[pohLCdueon] [datetime] NULL,
	[pohLCAmount] [numeric](18, 2) NULL,
	[pohLCNumber] [varchar](50) NULL,
	[pohLCRemarks] [varchar](250) NULL,
	[pohcompanyid] [int] NULL,
	[pohLcMarginOpened] [bit] NOT NULL,
	[pohCostingDone] [char](1) NULL,
	[pohDeliveryTerms] [varchar](500) NULL,
	[pohquotconfirmed] [bit] NOT NULL,
	[pohpoonhold] [bit] NULL,
	[pohfuturevc] [varchar](250) NOT NULL,
	[pohshipmentmode] [varchar](50) NULL,
	[pohpaymentmode] [varchar](50) NULL,
	[pohpurpose] [varchar](50) NULL,
	[pohshopid] [int] NULL,
	[pohrequestid] [int] NULL,
	[updatetime] [datetime] NOT NULL,
	[pohbofladno] [varchar](50) NULL,
	[Pohbofladdate] [datetime] NULL,
	[Pohbofladdetails] [varchar](250) NULL,
	[pohexchangerates] [varchar](250) NULL,
	[pohcmpexrate] [numeric](18, 8) NULL,
	[pohdepexrate] [numeric](18, 8) NULL,
	[pohfinancialid] [int] NULL,
	[pohProjectStartDate] [datetime] NULL,
	[pohProjectEndDate] [datetime] NULL,
	[pohProjectOtherInfo] [varchar](1000) NULL,
	[pohCustomDutyByCustomer] [bit] NULL,
	[pohTransportation] [varchar](50) NULL,
	[pohPotime] [datetime] NULL,
	[pohSubDepartmentID] [int] NULL,
	[PohAuthorized] [int] NULL,
	[pohVerified] [int] NULL,
	[pohprepurchaseid] [int] NULL,
	[pohApproved] [int] NULL,
	[pohPriorityid] [int] NULL,
	[pohPurRequestedBy] [varchar](30) NULL,
	[pohReqApprovedBy] [varchar](30) NULL,
	[pohTypeid] [int] NULL,
	[pohPurRequestClosed] [bit] NULL,
	[pohRequestDepartment] [int] NULL,
	[pohSingleItemCatChecked] [bit] NULL,
	[pohSingleItemCatId] [int] NULL,
 CONSTRAINT [PK_loPurchaseOrderHeader] PRIMARY KEY NONCLUSTERED 
(
	[pohPoid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[usp_GetErrorInfo]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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;
GO
/****** Object:  Table [dbo].[aComboItemMaster]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aComboItemMaster](
	[ComboID] [int] NOT NULL,
	[ComboCode] [varchar](50) NOT NULL,
	[ComboName] [varchar](50) NOT NULL,
	[PackingTypeID] [int] NOT NULL,
	[SellingPrice] [numeric](18, 2) NOT NULL,
	[Active] [bit] NOT NULL,
	[Barcode] [varchar](50) NULL,
	[UnitID] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aItemKitHeader]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aItemKitHeader](
	[ItemKitId] [int] NOT NULL,
	[ItemKitCode] [varchar](50) NOT NULL,
	[ItemKitDesc] [varchar](200) NULL,
	[ItemKitRate] [numeric](18, 3) NULL,
	[CustomId] [int] NULL,
	[CostingValue] [numeric](18, 2) NULL,
	[Active] [bit] NOT NULL,
	[ForSales] [bit] NULL,
	[PriceFixedatHQ] [bit] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LosApprovedby]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosApprovedby](
	[Approvedid] [int] NULL,
	[approvedby] [varchar](20) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[crmSettings]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[crmSettings](
	[ShopId] [int] NOT NULL,
	[EmailFooter] [varchar](250) NULL,
	[EmailLimit] [int] NULL,
	[CompanyId] [int] NULL,
	[ShowUsersInAccountsMaster] [bit] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aSSRSReportInterface]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aSSRSReportInterface](
	[IntrefaceId] [int] NOT NULL,
	[ReportUrl] [varchar](4000) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LosIssuedby]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosIssuedby](
	[Issuedid] [int] NULL,
	[Issuedby] [varchar](20) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loaFixedCostHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loaFixedCostHeader](
	[FixedCostId] [int] NOT NULL,
	[FixedCostNo] [varchar](25) NULL,
	[FixedCostDate] [datetime] NULL,
	[FixedCostEnteredby] [varchar](100) NULL,
	[FixedCostRemarks] [varchar](250) NULL,
	[FixedCostDepartmentid] [int] NOT NULL,
	[FixedCostUpdate] [datetime] NULL,
	[fixedcostCompanyid] [int] NULL,
	[FixedCostTime] [datetime] NULL,
	[FixedCostCreated] [varchar](250) NULL,
	[FixedCostModified] [varchar](250) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[MOiGodownStockBackup]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MOiGodownStockBackup](
	[gsGodownID] [int] NOT NULL,
	[gsLocationID] [int] NOT NULL,
	[gsStockDate] [datetime] NOT NULL,
	[gsShipmentID] [int] NOT NULL,
	[gsItemID] [int] NOT NULL,
	[gsOpeningStock] [numeric](18, 3) NULL,
	[gsStock] [numeric](18, 3) NULL,
	[gsOpeningBadStock] [numeric](18, 3) NULL,
	[gsBadStock] [numeric](18, 3) NULL,
	[gsItemCost] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_MOiGodownStockBackup] PRIMARY KEY NONCLUSTERED 
(
	[gsGodownID] ASC,
	[gsLocationID] ASC,
	[gsStockDate] ASC,
	[gsShipmentID] ASC,
	[gsItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_901578250] ON [dbo].[MOiGodownStockBackup] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spBudgetingDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  Table [dbo].[losDeliveryVerificationHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losDeliveryVerificationHeader](
	[CompanyId] [int] NOT NULL,
	[ShopId] [int] NOT NULL,
	[DeliveryVerificationId] [int] NOT NULL,
	[DeliveryVerificationNo] [nvarchar](50) NULL,
	[DeliveryDate] [datetime] NULL,
	[Cancelled] [bit] NULL,
	[AddUserId] [int] NULL,
	[ModifyUserId] [int] NULL,
	[DeleteUserId] [int] NULL,
	[DeletionReason] [nvarchar](500) NULL,
	[UpdateTime] [datetime] NULL,
	[FinancialYearId] [int] NULL,
 CONSTRAINT [PK_losDeliveryItemsVerificationHeader] PRIMARY KEY CLUSTERED 
(
	[CompanyId] ASC,
	[ShopId] ASC,
	[DeliveryVerificationId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[bak_odatestock]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[bak_odatestock](
	[COMPANYID] [int] NULL,
	[SHOPID] [int] NULL,
	[GODOWNID] [int] NULL,
	[TRDATE] [datetime] NULL,
	[ITEMID] [int] NULL,
	[STOCK] [numeric](18, 3) NULL,
	[DEPCOSTPRICE] [numeric](18, 3) NULL,
	[DEPSTOCKVALUE] [numeric](18, 3) NULL,
	[COMCOSTPRICE] [numeric](18, 3) NULL,
	[COMSTOCKVALUE] [numeric](18, 3) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosPriority]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosPriority](
	[Priorityid] [int] NOT NULL,
	[Priority] [varchar](100) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loiExpiryVerificationHeader]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loiExpiryVerificationHeader](
	[evhId] [int] NOT NULL,
	[evhGodownId] [int] NOT NULL,
	[evhNo] [varchar](50) NOT NULL,
	[evhDate] [datetime] NOT NULL,
	[evhRemarks] [varchar](250) NULL,
	[evhCancelled] [bit] NULL,
	[evhVerifiedBy] [varchar](100) NULL,
	[evhCancelRemarks] [varchar](50) NULL,
	[evhFutureVc] [varchar](250) NULL,
	[evhPosted] [bit] NULL,
	[UpdateTime] [datetime] NULL,
	[evhDepartmentId] [int] NULL,
	[evhConExRate] [numeric](18, 8) NULL,
	[evhDepExRate] [numeric](18, 8) NULL,
	[evhExchangeRates] [varchar](250) NULL,
	[evhcreatedtime] [datetime] NULL,
	[evhmodifieduser] [varchar](20) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[MiscInquiry]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MiscInquiry](
	[QueryID] [int] NOT NULL,
	[QueryName] [varchar](250) NOT NULL,
	[Comments] [varchar](1000) NULL,
	[Query] [varchar](5000) NOT NULL,
	[ReportName] [varchar](50) NULL,
	[CompanyId] [int] NULL,
	[Active] [bit] NULL,
	[Type] [char](1) NULL,
	[Modulecode] [varchar](10) NULL,
 CONSTRAINT [PK_MiscInquiry] PRIMARY KEY NONCLUSTERED 
(
	[QueryID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spConvertCurrency]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-------------------------------------------------------------------------------
--Created on 	: 30/11/2002
--Created by	: leo
--Comments	: to do the currency conversion, this formula is tested
-------------------------------------------------------------------------------
--Modified on 	: 24/09/2003
--Modified by	: R Harikrishnan
--Comments	: changed the output parameter precesion to 4
-------------------------------------------------------------------------------
CREATE proc [dbo].[spConvertCurrency] 
	@numfromer 	as numeric(15,8), 
	@numtoer 	as numeric(15,8), 
	@numAmount 	as numeric(18,4), 
	@numequiamount 	as numeric(18,4) output as
begin
	set nocount on
	set @numequiamount = round((@numtoer / @numfromer) * @numamount,4) 
	set nocount off
end
GO
/****** Object:  Table [dbo].[EmailList]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[EmailList](
	[CustomerId] [int] NOT NULL,
	[DepartmentID] [int] NULL,
	[DepartmentName] [varchar](50) NULL,
	[InvocieId] [nchar](10) NOT NULL,
	[InvAmount] [numeric](18, 2) NOT NULL,
	[SettledAmt] [numeric](18, 2) NOT NULL,
	[BalanceAmt] [numeric](18, 2) NOT NULL,
	[Age] [int] NOT NULL,
	[Due] [char](10) NOT NULL,
	[Processed] [bit] NULL,
	[CurrencyName] [nvarchar](20) NULL,
	[Symbol] [nvarchar](20) NULL,
	[Invoicedate] [datetime] NULL,
	[Invoiceno] [varchar](50) NULL,
	[Referenceno] [varchar](100) NULL,
	[remarks] [varchar](1000) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CrmSupportrequest]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmSupportrequest](
	[RequerstId] [int] NOT NULL,
	[Priority] [varchar](50) NULL,
	[Status] [varchar](50) NULL,
	[Type] [varchar](50) NULL,
	[Source] [varchar](50) NULL,
	[Category] [varchar](50) NULL,
	[UserId] [int] NULL,
	[FixedinRelease] [varchar](50) NULL,
	[Subject] [varchar](50) NULL,
	[Description] [varchar](50) NULL,
	[WorkLog] [varchar](50) NULL,
	[Resolution] [varchar](50) NULL,
	[Activie] [bit] NULL,
 CONSTRAINT [PK_CrmSupportrequest] PRIMARY KEY CLUSTERED 
(
	[RequerstId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LosReceivedby]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosReceivedby](
	[Receivedid] [int] NULL,
	[Receivedby] [varchar](20) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loiSerialArrivalDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[loiSerialArrivalDetails](
	[sadInterfaceID] [int] NOT NULL,
	[sadGodownID] [int] NOT NULL,
	[sadTransactionID] [int] NOT NULL,
	[sadDetailID] [int] NOT NULL,
	[sadSerialNo] [nvarchar](50) NOT NULL,
	[sadItemID] [int] NOT NULL,
	[sadItemQty] [numeric](10, 2) NOT NULL,
	[sadPackingQty] [numeric](10, 2) NOT NULL,
	[sadCancel] [int] NOT NULL,
	[sadAdjustment] [int] NOT NULL,
	[sadFreeQty] [int] NOT NULL,
	[sadSavedByShopId] [int] NULL,
	[sadPackingTypeID] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[PurchaseBilldetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PurchaseBilldetail](
	[pbdBillID] [int] NULL,
	[pbdItemID] [int] NULL,
	[pbdDetailID] [int] NULL,
	[pbdPackingTypeID] [int] NULL,
	[pbdPOQuantity] [numeric](18, 3) NULL,
	[pbdPOUnitPrice] [numeric](18, 8) NULL,
	[pbdItemQuantity] [numeric](18, 3) NULL,
	[pbdItemUnitPrice] [numeric](18, 8) NULL,
	[pbdDummyUnitPrice] [numeric](18, 8) NULL,
	[pbdItemCostedPrice] [numeric](18, 8) NULL,
	[pbdItemFixedPrice] [numeric](18, 8) NULL,
	[pbddiscount] [numeric](18, 2) NULL,
	[pbdpoid] [nvarchar](50) NULL,
	[pbdsellingprice] [nvarchar](50) NULL,
	[pbdwholesaleprice] [nvarchar](50) NULL,
	[pbddiscountprice] [nvarchar](50) NULL
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spCustomerSalesQtyWise]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[sp_FBCashSummary]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================                        
-- 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
GO
/****** Object:  Table [dbo].[ItemPriceHistory]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ItemPriceHistory](
	[ItemPriceId] [int] IDENTITY(1,1) NOT NULL,
	[ItemId] [int] NOT NULL,
	[PackId] [int] NOT NULL,
	[ShopId] [int] NULL,
	[SegmentId] [int] NULL,
	[CurrencyId] [int] NULL,
	[SellingPrice] [numeric](18, 2) NULL,
	[DiscountPrice] [numeric](18, 2) NULL,
	[WholesalePrice] [numeric](18, 2) NULL,
	[CreditSP] [numeric](18, 2) NULL,
	[CreditDP] [numeric](18, 2) NULL,
	[CreditWP] [numeric](18, 2) NULL,
	[FixDate] [datetime] NULL,
	[UpdateTime] [datetime] NULL,
	[UserId] [int] NULL,
	[CompanyId] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_ItemPriceHistory] PRIMARY KEY CLUSTERED 
(
	[ItemPriceId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spCRM_SendMail]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 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
GO
/****** Object:  Table [dbo].[RamzanSales]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[RamzanSales](
	[SNO] [int] NULL,
	[ItemCode] [nvarchar](255) NULL,
	[ ] [nvarchar](255) NULL,
	[CostPrice] [float] NULL,
	[SellingPrice] [float] NULL,
	[SalePrice] [float] NULL
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spDateWiseSalesReport]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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
GO
/****** Object:  Table [dbo].[lopackagetype]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[lopackagetype](
	[loctype] [char](10) NULL,
	[locid] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[nid]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[nid](
	[poshShopID] [int] NOT NULL,
	[poshBillID] [int] NOT NULL,
	[poshBillNo] [varchar](50) NULL,
	[poshBillDate] [datetime] NULL,
	[poshCustomerName] [varchar](100) NULL,
	[poshCancelled] [bit] NOT NULL,
	[poshCancelledRemarks] [varchar](250) NULL,
	[poshRecAddUser] [varchar](50) NULL,
	[poshRecModifyUser] [varchar](50) NULL,
	[poshPosted] [bit] NOT NULL,
	[poshDiscount] [numeric](18, 2) NULL,
	[poshBillAmount] [numeric](18, 2) NULL,
	[poshCashAccID] [int] NULL,
	[poshSalesAccID] [int] NULL,
	[poshCompanyID] [int] NULL,
	[poshReturned] [bit] NOT NULL,
	[poshWholesale] [bit] NOT NULL,
	[poshcbid] [int] NULL,
	[poshExchangeRate] [numeric](28, 8) NOT NULL,
	[poshfuturevc] [varchar](250) NULL,
	[updatetime] [datetime] NOT NULL,
	[poshDepartmentid] [int] NULL,
	[poshsalespersonid] [int] NULL,
	[poshcustomerid] [int] NULL,
	[poshCustomerCardNo] [varchar](100) NULL,
	[poshfutureint] [int] NULL,
	[poshcurexrates] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] NOT NULL,
	[poshdepexrate] [numeric](18, 8) NULL,
	[poshexchangerates] [varchar](250) NULL,
	[poshUserId] [int] NULL,
	[poshCounterId] [int] NULL,
	[ContactCardNo] [varchar](50) NULL,
	[poshDiscountAmt] [numeric](18, 2) NULL,
	[poshBalance] [numeric](18, 2) NULL,
	[poshBillTime] [datetime] NULL,
	[poshDeliveryNeeded] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CrmCustomerMaster]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[CrmCustomerMaster](
	[CustomerID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[CustomerName] [varchar](100) NOT NULL,
	[Active] [bit] NOT NULL,
	[Address1] [varchar](250) NULL,
	[Address2] [varchar](250) NULL,
	[Address3] [varchar](250) NULL,
	[CityID] [int] NOT NULL,
	[PhoneNo] [varchar](50) NULL,
	[FaxNo] [varchar](50) NULL,
	[EmailID] [varchar](100) NULL,
	[CurrencyID] [int] NULL,
	[CountryID] [int] NULL,
	[custdob] [datetime] NULL,
	[webadd] [varchar](20) NULL,
	[CreditLimit] [numeric](18, 2) NULL,
	[registerdate] [datetime] NULL,
	[CusGroupId] [int] NULL,
	[MasterApllicationCustomerId] [int] NULL,
	[Deleted] [int] NOT NULL
) ON [PRIMARY]
SET ANSI_PADDING ON
ALTER TABLE [dbo].[CrmCustomerMaster] ADD [CustomerCategory] [varchar](100) NULL
ALTER TABLE [dbo].[CrmCustomerMaster] ADD  CONSTRAINT [PK_CrmCustomerMaster] PRIMARY KEY CLUSTERED 
(
	[CustomerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losApartmentRatesDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losApartmentRatesDetail](
	[rdcompanyid] [int] NOT NULL,
	[rdshopid] [int] NOT NULL,
	[rdRoomRateTypeId] [int] NOT NULL,
	[rdapartmentcategoryid] [int] NOT NULL,
	[rdroomratedetailid] [int] NOT NULL,
	[rdApartmentRate] [numeric](18, 2) NULL,
 CONSTRAINT [pk_losApartmentRatesDetail] PRIMARY KEY CLUSTERED 
(
	[rdcompanyid] ASC,
	[rdshopid] ASC,
	[rdapartmentcategoryid] ASC,
	[rdroomratedetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ReportCategoryHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ReportCategoryHeader](
	[repCatId] [int] NOT NULL,
	[repCatName] [varchar](100) NULL,
	[repCatModCode] [varchar](10) NULL,
	[Type] [char](1) NULL,
 CONSTRAINT [PK_ReportCategoryHeader] PRIMARY KEY CLUSTERED 
(
	[repCatId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spDaySalesShopWise]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwPostingTransType]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------     
 
-----         
-- 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:  Table [dbo].[PIS_EmailScheduler]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[PIS_EmailScheduler](
	[ReportId] [int] NOT NULL,
	[Discription] [nvarchar](50) NOT NULL,
	[ReportPath] [varchar](50) NOT NULL,
	[SendTime] [datetime] NOT NULL,
	[Interval] [char](10) NOT NULL,
	[MonthInterval] [char](10) NULL,
	[WeekInterval] [int] NULL,
	[Subject] [nvarchar](500) NULL,
	[Message] [nvarchar](1000) NULL,
	[CompanyId] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losType]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losType](
	[Typeid] [int] NOT NULL,
	[Type] [varchar](100) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[nidd]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[nidd](
	[id] [int] NULL,
	[name] [varchar](5) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ReportNames]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ReportNames](
	[ReportID] [int] NOT NULL,
	[ReportName] [varchar](200) NOT NULL,
	[ReportFileName] [varchar](200) NULL,
	[FrameID] [smallint] NULL,
	[Criterias] [varchar](250) NULL,
	[ReportTitle] [varchar](100) NULL,
	[BackendType] [varchar](1) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_997578592] ON [dbo].[ReportNames] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSum]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Procedure
-- Modified by   : Kishore                                    
-- Modified on  : 10/06/2003                                    
-- Comments  : Added the Having condition in each select query                                    
--                        (on comparison with v2)                                    
                                    
-----------------------------------------------------------------------------                                    
-- Modified by   : venki, Hariharan R                                    
-- Modified on  : 11/09/2003 ....240903 (added debtoraccid ), 08/01/2004                                    
-- Comments  : given isnull --then 0 for settledamt field                                    
--                        (on comparison with v2)                                    
-- Modified by   : venkitesh                                    
-- Modified on  : 11/09/2003 ....240903 (added debtoraccid )                                    
-- Comments  : given vwSettlements as derived table filtering customerid, depid and invoicedate                                    
-- Modified by   : venkitesh  , Hariharan                                   
-- Modified on  : 29/06/2004, 08/12/2004                                      
-- Comments  : Corrected ageing and due period basis of todate                                    
--           : Corrected the company wise report fetching removing departmentid condition on settlements query                                        
-----------------------------------------------------------------------------                                    
-- RefNo-1                
-- Modified by : Regin                
-- Modified on : 16-06-2010                
-- Comments    : To speed up the execution.                
-- Old technique had below tow steps:                
--   1. Fetch ALL rows of vwInvoices and vwsettlements                 
--      into #tempvwInvoices and #tempvwsettlements respectively.                
--      Since all rows are fetched, it took huge time to complete.                
--   2. Required rows were fetched from #tempvwInvoices                 
--      and #tempvwsettlements applying condition.                
-- New technique eliminates the temporary tables and has one step:                
--   1. Required rows are fetched direcly from vwInvoices                 
--      and vwsettlements applying condition.                
--      Since rows are fetched on condition, fetch completes quickly.                
-- Time taken to generate the outstanding invoices report for one customer                
-- in Simdi DB is...                
--   In old technique: 3 Minues                
--   In new technique: 20 Seconds                
-----------------------------------------------------------------------------               
--RefNo:01            
--Modified By : VinothMurugan V.            
--Modified On : 06/08/2010            
--Purpose     : Adding Currencyid            
--------------------------------------------------------------------------
--Modified By : SHINE        
--Modified On : 28/07/2011        
--Purpose     : When added to VSS some unwaned comments came. So removed it                                   
--  spdebtoragesum '20010101','20100805','',0,0,0,'',''                             
 --RefNo:02
 --Modified By : Jyothish.SR.  
 -- Modified On : 27/03/2012     
 --Purpose     : select *  statement is avoid in vwsettlements and vwinvinvoices           
              
CREATE  PROCEDURE [dbo].[spDebtorAgeSum] (                                     
@dtstartdate varchar(11),@dtinvdate as varchar(11),                                      
@intcustid varchar(1000),@intdepartid int,@intageTodate int=0 ,@intShopID int=0 ,                                
@strCatName as Varchar(30)='', @strGroupName as Varchar(30)=''  )                                        
as                          
begin                      
 declare @strquery as nvarchar(4000)                                      
 declare @SettleCustId as varchar(1500), @Invcustid as varchar(1500)                                      
 declare @strShop as nvarchar(4000)                                 
 declare  @strCatCond as Varchar(300)                                
 declare @strGroupCond as Varchar(300)                        
                                 
 SET @SettleCustId = ''          
 set @Invcustid = ''                                      
 set @strShop = ''                                 
 set @strCatCond=''                                
 set @strGroupCond=''                          
                      
Create table #tmpInvoices (CompanyID int,                                       
shopid int,                                       
DepartmentID int,                 
InvoiceID int,                                       
customerid int,                                       
invoicedate datetime,                          
invoiceno varchar(50),                                       
Referenceno varchar (100),                                      
remarks varchar(1000),                                       
InvAmt numeric(18,2),                                       
Due varchar(7),                                       
Type varchar(7),                                       
Debtortype varchar(50),                                       
updatetime datetime,                                       
CustomerCategory varchar(100),                                      
duedate datetime ,                                      
depexrate numeric(18,2) ,                                      
InterFaceID int ,                                      
SalesPersonID int  ,                                      
CustomerType char(1),                                       
DutyAmt numeric(18,2) ,                                      
CostPrice numeric(18,4),                                
CustGroupName varchar(100), TaxAmount numeric (18,2),                                    
age int                                
)                        
Create Table #tmpSettlements                                       
(customerid int,                                       
ReceiptNo varchar(50),                                      
companyid int,                                       
invoiceid int,                                       
shopid int,                                       
settleddate datetime,                                       
departmentid int,                                       
settledamt numeric(18,2),                                      
Type varchar(50))                       
-- Commented (RefNo-1)                
-- select * into #tempvwInvoices from vwInvoices                        
-- select * into #tempvwsettlements from vwsettlements                       
 if @strCatName<>''                        
 begin                              
  set @strCatCond = ' CustomerCategory = ''' + @strCatName + ''' And '                                
 end                                 
 if @strGroupName<>''                       
 begin                               
  set @strGroupCond = ' CustGroupName = ''' + @strGroupName + ''' And '                                
 end                                 
                                 
 if @intShopID > 0                                 
 Begin                                
  set @strShop=' And  #tmpInvoices.shopid = ' + cast(@intShopID As varchar)                                
 end                                 
 if @intcustid<>''    --hari given to handle with out customerid also                                      
 Begin                                      
  set @SettleCustId = ' customerid in (' + @intcustid + ') and'                                        
  set @Invcustid = 'vwInvoices.customerid in (' + @intcustid + ') and'                                            
 End                        
                      
-- if @dtstartdate =''                                      
-- Begin                                      
--    if @intdepartid >0                                      
--    set @strquery ='insert #tmpInvoices                                      
--     Select *,0 from #tempvwInvoices vwInvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                      
--     ' invoicedate <=''' + @dtinvdate + '''' +                                       
--     ' and departmentid = ' + cast(@intdepartid as varchar)                                       
--    else                                      
--     set @strquery ='insert #tmpInvoices                                      
--     Select *,0 from #tempvwInvoices vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                       
--     ' invoicedate <=''' + @dtinvdate + ''''                      
--    End                          
-- Else                                      
-- Begin                                       
--  if @intdepartid >0                                      
--     set @strquery ='insert #tmpInvoices                                      
--     Select *,0 from #tempvwInvoices vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                       
--     ' invoicedate <=''' + @dtinvdate + '''' +                                       
--     ' and departmentid = ' + cast(@intdepartid as varchar) +                                       
--     ' and invoicedate >=''' + @dtstartdate + ''''                                      
--  else                                      
--   set @strquery ='insert #tmpInvoices                                      
--   Select *,0 from #tempvwInvoices vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                       
--      ' invoicedate <=''' + @dtinvdate + '' +                                       
--   ''' and invoicedate >=''' + @dtstartdate + ''''                                      
-- End                               
                
-- Instead of selecting from #tempvwInvoices,                 
-- required rows are fetched direcly from vwInvoices applying condition.                
-- Thus increasing speed. Old code commented above. (RefNo-1)                 
 if @dtstartdate =''                                      
 Begin                                      
    if @intdepartid >0   
    --RefNo:02                                   
    set @strquery ='insert #tmpInvoices                                      
     Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,Referenceno,remarks,InvAmt,Due,
     Type,Debtortype,updatetime,CustomerCategory,duedate,depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,
     CostPrice,CustGroupName,TaxAmount,0 from vwInvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                
     ' invoicedate <=''' + @dtinvdate + '''' +                                       
     ' and departmentid = ' + cast(@intdepartid as varchar)                                       
    else   
    --   RefNo:02                                
     set @strquery ='insert #tmpInvoices                                      
     Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,Referenceno,remarks,InvAmt,Due,
     Type,Debtortype,updatetime,CustomerCategory,duedate,depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,
     CostPrice,CustGroupName,TaxAmount ,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                       
     ' invoicedate <=''' + @dtinvdate + ''''                                      
    End                          
 Else                                      
 Begin  
                                        
  if @intdepartid >0     
                            
     set @strquery ='insert #tmpInvoices                                      
     Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,Referenceno,remarks,InvAmt,Due,
     Type,Debtortype,updatetime,CustomerCategory,duedate,depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,
     CostPrice,CustGroupName,TaxAmount ,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                       
     ' invoicedate <=''' + @dtinvdate + '''' +                                       
     ' and departmentid = ' + cast(@intdepartid as varchar) +                                       
     ' and invoicedate >=''' + @dtstartdate + '''' 
                                             
  else                                      
   set @strquery ='insert #tmpInvoices                                      
   Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,Referenceno,remarks,InvAmt,Due,
   Type,Debtortype,updatetime,CustomerCategory,duedate,depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,
   CostPrice,CustGroupName,TaxAmount ,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                       
      ' invoicedate <=''' + @dtinvdate + '' +                                       
   ''' and invoicedate >=''' + @dtstartdate + ''''                                      
 End                                      
              
 exec sp_Executesql @strquery                      
                      
--  if @dtstartdate =''                            
--  Begin                                      
--  if @intdepartid >0                                      
--   set @strquery  = ' insert #tmpSettlements Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +                                       
--   ' departmentid = ' + cast(@intdepartid as varchar) +                                       
--   ' and settleddate <=''' + @dtinvdate +  ''''                                       
--  else                                      
--   set @strquery  = 'insert #tmpSettlements  Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +                                       
--      ' settleddate <=''' + @dtinvdate + ''''                                        
--                                      
--  End                          
--    Else                                      
--    Begin                                       
--  if @intdepartid >0                                      
--   set @strquery  = ' insert #tmpSettlements Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +                                       
--      ' departmentid = ' + cast(@intdepartid as varchar) +                                       
--   ' and settleddate <=''' + @dtinvdate +  '' +                                       
--   ''' and settleddate >=''' + @dtstartdate + ''''                                      
--   else                                      
--   set @strquery  = 'insert #tmpSettlements  Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +                                       
--      ' settleddate <=''' + @dtinvdate + '' +                                       
--   ''' and settleddate >=''' + @dtstartdate + ''''                                      
--                                      
--   End                      
                
-- Instead of selecting from #tempvwsettlements,                 
-- required rows are fetched direcly from vwsettlements applying condition.                
-- Thus increasing speed. Old code commented above. (RefNo-1)                 
  if @dtstartdate =''                                      
  Begin                                      
  if @intdepartid >0  
  --RefNo:02                                    
   set @strquery  = ' insert #tmpSettlements Select customerid,ReceiptNo,companyid,invoiceid,shopid,settleddate,departmentid,settledamt,Type from vwsettlements where ' + @SettleCustId +                                       
   ' departmentid = ' + cast(@intdepartid as varchar) +                                       
   ' and settleddate <=''' + @dtinvdate +  ''''                                       
  else                             set @strquery  = 'insert #tmpSettlements  Select customerid,ReceiptNo,companyid,invoiceid,shopid,settleddate,departmentid,settledamt,Type from vwsettlements where ' + @SettleCustId +                                       
      ' settleddate <=''' + @dtinvdate + ''''                                        
                                      
  End                          
    Else                                      
    Begin                                       
  if @intdepartid >0                                      
   set @strquery  = ' insert #tmpSettlements Select customerid,ReceiptNo,companyid,invoiceid,shopid,settleddate,
   departmentid,settledamt,Type from vwsettlements where ' + @SettleCustId +                                       
      ' departmentid = ' + cast(@intdepartid as varchar) +                                       
   ' and settleddate <=''' + @dtinvdate +  '' +                                       
   ''' and settleddate >=''' + @dtstartdate + ''''                                      
   else        
   --   RefNo:02                        
   set @strquery  = 'insert #tmpSettlements  Select customerid,ReceiptNo,companyid,invoiceid,shopid,settleddate,
   departmentid,settledamt,Type from vwsettlements where ' + @SettleCustId +                                       
      ' settleddate <=''' + @dtinvdate + '' +                                       
   ''' and settleddate >=''' + @dtstartdate + ''''                                      
                                      
   End                            
  exec sp_Executesql @strquery                        
                       
-----RefNo:01            
 set @strquery = 'SELECT  max(invamt) invamt,isnull(sum(settledamt),0) settleamt,#tmpInvoices.invoiceid,                                      
    #tmpInvoices.customerid,#tmpInvoices.shopid,#tmpInvoices.due,#tmpInvoices.invoicedate ,                                      
    #tmpInvoices.invoiceno,#tmpInvoices.type,remarks,customername,currencyname,symbol, #tmpInvoices.duedate,       
    datediff(dd,#tmpInvoices.duedate, ''' + @dtinvdate + ''' ) overduedays, address1, address2, address3,                                       
    #tmpInvoices.referenceno,debtoraccid,b.accountdesc, aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID FROM                                       
       #tmpInvoices #tmpInvoices LEFT OUTER JOIN #tmpSettlements                                        
    vwsettlements ON #tmpInvoices.customerid = vwsettlements.customerid AND                                      
       #tmpInvoices.CompanyID = vwsettlements.companyid AND                                      
       #tmpInvoices.InvoiceID = vwsettlements.invoiceid AND                                      
       #tmpInvoices.type = vwsettlements.type AND                                      
       #tmpInvoices.shopid = vwsettlements.shopid  and                                       
   (vwsettlements.settleddate<=''' + @dtinvdate +                                      
  ''' or vwsettlements.settleddate is null),                                       
   aCurrencyMaster ,  aCustomerMaster, aAccountMaster b                                       
   WHERE #tmpInvoices.customerid = aCustomerMaster.CustomerID AND                                      
       #tmpInvoices.CompanyID = aCustomerMaster.CompanyID and                                       
   aCustomerMaster.CurrencyID = aCurrencyMaster.CurrencyID AND                                      
       aCustomerMaster.CompanyID = aCurrencyMaster.CompanyID and                                       
   aCustomerMaster.debtorAccID = b.AccountID ' + @strShop  + '                                     
   and  #tmpInvoices.invoicedate<=''' + @dtinvdate + '''                                         
   group by #tmpInvoices.invoiceid,#tmpInvoices.departmentid,                                       
   #tmpInvoices.customerid, #tmpInvoices.shopid,due ,invoicedate,                                       
   invoiceno,#tmpInvoices.type,remarks,                    
   customername,currencyname,symbol, #tmpInvoices.duedate,                                       
address1, address2, address3, #tmpInvoices.referenceno,                                      
   debtoraccid,b.AccountDesc ,aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID                                      
   having max(invamt) <> sum(isnull(settledamt,0))'                         
                      
  if @intageTodate=1                                       
  begin                                      
   update #tmpInvoices set age=datediff(day,invoicedate,CONVERT(DATETIME, @dtinvdate,102))                                       
   update #tmpInvoices set due =                                      
   case when (age  >=0 and age <= 30) then '0 - 30'                                       
  when (age  >=31 and age <= 60)  then '31 - 60'                                        
   when (age  >=61 and age <= 90) then '61 - 90'                                      
   when (age  >=91) then ' > 90' else '' end                                       
   end                                              
exec sp_Executesql @strquery                         
--select * from #tempvwsettlements                      
                      
-- Commented (RefNo-1)                
-- drop table #tempvwInvoices                      
-- drop table #tempvwsettlements                      
drop table #tmpInvoices                      
drop table #tmpSettlements                      
                      
end
GO
/****** Object:  Table [dbo].[ScheduleHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ScheduleHeader](
	[schid] [int] NOT NULL,
	[schinterval] [int] NOT NULL,
	[schstarttime] [datetime] NULL,
	[schuptime] [datetime] NULL,
 CONSTRAINT [PK_ScheduleHeader] PRIMARY KEY NONCLUSTERED 
(
	[schid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[PIS_EmailSchedulerRecepients]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PIS_EmailSchedulerRecepients](
	[ReportId] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[CompanyId] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosVerifiedby]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosVerifiedby](
	[verifiedid] [int] NULL,
	[verifiedby] [varchar](20) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losDocument]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losDocument](
	[ShopID] [int] NOT NULL,
	[DocID] [int] NOT NULL,
	[DocType] [char](2) NOT NULL,
	[DocNo] [varchar](50) NULL,
	[DocDate] [datetime] NULL,
	[CustomerID] [int] NULL,
	[CurrencyID] [int] NULL,
	[CompanyID] [int] NOT NULL,
	[EmpName] [varchar](100) NULL,
	[PPassportNo] [varchar](100) NULL,
	[PIssueDate] [datetime] NULL,
	[PExpireyDate] [datetime] NULL,
	[PNationality] [varchar](100) NULL,
	[WWorkPermitNo] [varchar](100) NULL,
	[WIssueDate] [datetime] NULL,
	[WExpireyDate] [datetime] NULL,
	[WNoofDays] [int] NULL,
	[WFeeType] [varchar](50) NULL,
	[WFeeExpireyDate] [datetime] NULL,
	[MLastMedicalReportDate] [datetime] NULL,
	[CoMailIn] [bit] NULL,
	[CoMailHandledBy] [varchar](50) NULL,
	[RequestedBy] [varchar](100) NULL,
	[Remarks] [varchar](250) NULL,
	[AlertBeforeDays] [int] NULL,
	[Active] [bit] NULL,
	[Cancelled] [bit] NULL,
	[CancelledRemarks] [varchar](250) NULL,
	[ArrangementDoneDate] [datetime] NULL,
 CONSTRAINT [PK_losDocument] PRIMARY KEY NONCLUSTERED 
(
	[ShopID] ASC,
	[DocID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ShipmentClearenceHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ShipmentClearenceHeader](
	[ShopID] [int] NOT NULL,
	[ClearenceID] [int] NOT NULL,
	[ClearenceNo] [varchar](50) NULL,
	[ClearenceDate] [datetime] NULL,
	[ClearedBy] [varchar](50) NULL,
	[ActualClearenceDate] [datetime] NULL,
	[Remarks] [varchar](250) NULL,
	[Cancelled] [bit] NULL,
	[CancelledRemarks] [varchar](250) NULL,
 CONSTRAINT [pk_ShipmentClearenceHeader] PRIMARY KEY CLUSTERED 
(
	[ShopID] ASC,
	[ClearenceID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[PIS_EmailSchedulerReportParameter]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[PIS_EmailSchedulerReportParameter](
	[ReportId] [int] NOT NULL,
	[ParameterOrder] [int] NOT NULL,
	[ParameterValue] [varchar](50) NOT NULL,
	[CompanyId] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ShopFooterImage]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ShopFooterImage](
	[CompanyID] [int] NOT NULL,
	[ShopID] [int] NOT NULL,
	[FooterImage] [image] NULL,
	[type] [varchar](5) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spFixedCost]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[losDocumentaccom]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losDocumentaccom](
	[ShopID] [int] NOT NULL,
	[DocId] [int] NOT NULL,
	[DetailId] [int] NOT NULL,
	[PaxName] [varchar](50) NULL,
	[Hotelname] [varchar](50) NULL,
	[BedNights] [int] NULL,
	[RoomRate] [numeric](18, 2) NULL,
	[Remarks] [varchar](250) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ShopHeaderImage]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ShopHeaderImage](
	[CompanyID] [int] NOT NULL,
	[ShopID] [int] NOT NULL,
	[HeaderImage] [image] NULL,
	[type] [varchar](5) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spForwardCosting]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--Created by 	: R Harikrishnan
--Created on	: 04/03/2003
--Purpose	: To print the Forward costing details
CREATE procedure [dbo].[spForwardCosting] as 
select * from ##Temp
GO
/****** Object:  Table [dbo].[losDocumentDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losDocumentDetail](
	[ShopID] [int] NOT NULL,
	[DocID] [int] NOT NULL,
	[DetailID] [int] NOT NULL,
	[Particulars] [varchar](250) NULL,
	[FromDetails] [varchar](50) NULL,
	[ToDetails] [varchar](50) NULL,
 CONSTRAINT [PK_losDocumentDetail] PRIMARY KEY NONCLUSTERED 
(
	[ShopID] ASC,
	[DocID] ASC,
	[DetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Product]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Product](
	[Cust] [varchar](25) NULL,
	[Product] [varchar](20) NULL,
	[QTY] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losDocumentoc]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losDocumentoc](
	[ShopID] [int] NOT NULL,
	[DocID] [int] NOT NULL,
	[DetailID] [char](10) NOT NULL,
	[OtherCharge] [varchar](100) NULL,
	[Amount] [numeric](18, 2) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spGdnNonMovingItems]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--spGdnNonMovingItems '20070101','20080105',5,50,1000,'D','',30        
 /****** Object:  Stored Procedure dbo.spGdnNonMovingItems    Script Date: 18/01/2003 9:45:42 PM ******/            
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  
------------------------------------------------------            
-- created by  : Hariharan             
-- created date : 13/12/2002            
-- Comments : V3            
--------------------------------------------------------------------------------------            
-- Modified on  : 13/04/2009              
-- Modified by  : Regin T.            
-- Comments   : User is enabled to select more than one godown in the HQ Reports interface.         
--     So this SP is modified to accept a list of Godown IDs as input.         
--    Input argument @intGodownId is modified as @strGodownID.        
--------------------------------------------------------------------------------------         
--spGdnNonMovingItems '20070709','20080709', 50, 0, 'F', '',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            
            
  -- 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=''          
            
 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 '        
        
---Added by: Sreekanth.M.V          
---Purpose : Dead Items whose bill da date less than (Todate-@NoOfDays) are only shown         
         
if @MoveType = 'D'          
begin          
 set @dtMaxBillDateforDead=(select convert(varchar(8),dateadd("d",-@NoOfBackDays,convert(datetime,@strToDate,120)),112))          
          
          
           
 set @strSql=@strSql + 'inner join          
 (          
 select max(vw.maxbilldate) maxbilldate,vw.itemid from (select max(pbhbilldate) maxbilldate,pbditemid itemid from LOspPurchaseBillheader lph           
 inner join LOspPurchaseBillDetail lpd           
 on lph.pbhbillid=lpd.pbdbillid and lph.pbhcancelled=0          
 group by pbditemid          
           
           
 union           
      
 select max(lphbilldate) maxbilldate,lpditemid itemid from LOslocalpurchaseheader lph           
 inner join LosLocalPurchaseDetail lpd on          
 lph.lphbillid=lpd.lpdbillid and lph.lphcancelled=0          
 group by lpditemid) vw          
 group by vw.itemid          
 ) vw2 on vw1.itemid=vw2.itemid           
     and vw2.maxbilldate<''' + @dtMaxBillDateforDead + ''''          
          
end          
          
            
print @strSql            
           
 exec sp_executeSql @strSql            
            
 drop table #gdnItemStockStart            
 drop table #gdnItemStockEnd            
 drop table #gdnItemStockTrans            
 drop table #gdnItemStock            
 set nocount off            
end
GO
/****** Object:  Table [dbo].[tempCost]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tempCost](
	[lpchCostingid] [int] NOT NULL,
	[lpchDate] [datetime] NULL,
	[lpchBillid] [int] NULL,
	[lpchShopid] [int] NULL,
	[lpcditemid] [int] NULL,
	[lpcdcostedprice] [numeric](28, 16) NULL,
	[lpcditemqty] [numeric](18, 3) NULL,
	[lpcdbillunitprice] [numeric](28, 16) NULL,
	[lpcdolditemcostprice] [numeric](18, 2) NULL,
	[lpcdnewitemcostprice] [numeric](28, 16) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[fb_resttablemaster]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[fb_resttablemaster](
	[fb_rm_companyid] [int] NOT NULL,
	[fb_rm_outletid] [int] NOT NULL,
	[fb_rm_tablemasterid] [int] NOT NULL,
	[fb_rm_tablemastercode] [varchar](50) NULL,
	[fb_rm_tablemastername] [varchar](250) NULL,
 CONSTRAINT [PK_fb_resttablemaster] PRIMARY KEY NONCLUSTERED 
(
	[fb_rm_companyid] ASC,
	[fb_rm_outletid] ASC,
	[fb_rm_tablemasterid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CRMVersion]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[CRMVersion](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Version] [varchar](50) NOT NULL,
	[Release] [int] NOT NULL,
	[UpdatedDate] [datetime] NOT NULL,
 CONSTRAINT [PK_CRMVersion] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spGetAllSubDepartments]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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
GO
/****** Object:  Table [dbo].[TargetAccountsLink]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TargetAccountsLink](
	[tacCompanyID] [int] NOT NULL,
	[tacTargetID] [int] NOT NULL,
	[tacDetailID] [int] NOT NULL,
	[tacAccountID] [int] NULL,
	[tacDepartmentID] [int] NULL,
 CONSTRAINT [PK_TargetAccountsLink] PRIMARY KEY NONCLUSTERED 
(
	[tacCompanyID] ASC,
	[tacTargetID] ASC,
	[tacDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losDocumenttravel]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losDocumenttravel](
	[ShopID] [int] NOT NULL,
	[DocId] [int] NOT NULL,
	[DetailId] [int] NOT NULL,
	[TravellerName] [varchar](50) NULL,
	[Department] [varchar](50) NULL,
	[Designation] [varchar](50) NULL,
	[TravelDate] [datetime] NULL,
	[Remark] [varchar](100) NULL,
	[TravelMode] [varchar](50) NULL,
	[Route] [varchar](50) NULL,
	[Travelclass] [varchar](50) NULL,
	[Travelcost] [varchar](50) NULL,
	[arrivaldate] [datetime] NULL,
	[alertdays] [int] NULL,
 CONSTRAINT [PK_losDocumenttravel] PRIMARY KEY NONCLUSTERED 
(
	[ShopID] ASC,
	[DocId] ASC,
	[DetailId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losFacilityBookingHeader]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losFacilityBookingHeader](
	[fbhcompanyid] [int] NOT NULL,
	[fbhshopid] [int] NOT NULL,
	[fphbookingid] [int] NOT NULL,
	[fbhbookingdate] [datetime] NULL,
	[fbhbookingno] [varchar](100) NOT NULL,
	[fbhregistrationid] [int] NULL,
	[fbhremarks] [varchar](250) NULL,
	[fbhcancelled] [bit] NULL,
	[fbhcancelledremarks] [varchar](250) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TargetCheckHeader]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TargetCheckHeader](
	[tchCompanyID] [int] NOT NULL,
	[tchCheckID] [int] NOT NULL,
	[tchCheckNo] [varchar](50) NULL,
	[tchCheckDate] [datetime] NULL,
	[tchFixationID] [int] NULL,
	[tchActualAsonDate] [datetime] NULL,
	[tchCheckedBy] [varchar](250) NULL,
	[tchRemarks] [varchar](250) NULL,
	[tchCancelled] [bit] NULL,
	[tchCancelledRemarks] [varchar](250) NULL,
	[tchexchagerate] [varchar](250) NULL,
 CONSTRAINT [PK_TargetCheckHeader] PRIMARY KEY NONCLUSTERED 
(
	[tchCompanyID] ASC,
	[tchCheckID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spHPDebtorAgeSum]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*        
 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
GO
/****** Object:  UserDefinedFunction [dbo].[GetIndexColumnOrder]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[sp_sproc_columns]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create 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
GO
/****** Object:  Table [dbo].[TargetFixationHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TargetFixationHeader](
	[tfhCompanyID] [int] NOT NULL,
	[tfhFixationID] [int] NOT NULL,
	[tfhFixationNo] [varchar](50) NULL,
	[tfhFixationDate] [datetime] NULL,
	[tfhFromDate] [datetime] NULL,
	[tfhToDate] [datetime] NULL,
	[tfhFixationPanel] [varchar](250) NULL,
	[tfhReviewPanel] [varchar](250) NULL,
	[tfhReviewDate] [datetime] NULL,
	[tfhSanctionedBy] [varchar](100) NULL,
	[tfhSanctionedDate] [datetime] NULL,
	[tfhRemarks] [varchar](250) NULL,
	[tfhCancelled] [bit] NULL,
	[tfhCancelledRemarks] [varchar](250) NULL,
 CONSTRAINT [PK_TargetAllocationHeader] PRIMARY KEY NONCLUSTERED 
(
	[tfhCompanyID] ASC,
	[tfhFixationID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spHPmonthwisesale]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----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
GO
/****** Object:  Table [dbo].[losHPCustomerDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losHPCustomerDetails](
	[hpCompanyID] [int] NOT NULL,
	[hpDepartmentID] [int] NULL,
	[hpCustID] [int] NOT NULL,
	[hpCustName] [nvarchar](150) NULL,
	[hpCustcommenName] [nvarchar](150) NULL,
	[hpNCCNO] [nvarchar](50) NULL,
	[hpCustDOB] [datetime] NULL,
	[hpCustBornIn] [nvarchar](50) NULL,
	[hpMobNo] [nvarchar](50) NULL,
	[hpAccountNo] [varchar](50) NULL,
	[hpCustPermanentadd] [nvarchar](250) NULL,
	[hpCustPermAtoll] [nvarchar](50) NULL,
	[hpCustPermIsland] [nvarchar](50) NULL,
	[hpCustPremPhno] [nvarchar](50) NULL,
	[hpCustPresentAdd] [nvarchar](250) NULL,
	[hpCustPresAtoll] [nvarchar](50) NULL,
	[hpCustpresIsland] [nvarchar](50) NULL,
	[hpCustPresPhno] [nvarchar](50) NULL,
	[hpDeCustName] [nvarchar](50) NULL,
	[hpDeCustAddress] [nvarchar](50) NULL,
	[hpDeCustAtoll] [nvarchar](50) NULL,
	[hpDeCustIsland] [nvarchar](50) NULL,
	[hpCustPreAgreement] [nvarchar](50) NULL,
	[IslandtoUseMC] [nvarchar](50) NULL,
	[hpCustMCNO] [nvarchar](50) NULL,
	[hpEmployedAt] [nvarchar](50) NULL,
	[hpOfficePH] [nvarchar](50) NULL,
	[hpDesignation] [nvarchar](50) NULL,
	[hpSalary] [nvarchar](50) NULL,
	[hpDuration] [nvarchar](50) NULL,
	[hpOfficeAdd] [nvarchar](250) NULL,
	[hpRefName] [nvarchar](50) NULL,
	[hpRefRelation] [nvarchar](50) NULL,
	[hpRefPermanentAdd] [nvarchar](120) NULL,
	[hpRefPermAtoll] [nvarchar](50) NULL,
	[hpRefPermIsland] [nvarchar](50) NULL,
	[hpRefPermPHNO] [nvarchar](50) NULL,
	[hpRefPresentAdd] [nvarchar](250) NULL,
	[hpRefPresAtoll] [nvarchar](50) NULL,
	[hpRefPresIsland] [nvarchar](50) NULL,
	[hpRefPresPHNo] [nvarchar](50) NULL,
	[hpRefMob] [nvarchar](50) NULL,
	[hpGaName] [nvarchar](50) NULL,
	[hpGaNICNO] [nvarchar](50) NULL,
	[hpGaPermanentAdd] [nvarchar](250) NULL,
	[hpGaPermAtoll] [nvarchar](50) NULL,
	[hpGaPermIsland] [nvarchar](50) NULL,
	[hpGaPermPHNO] [nvarchar](50) NULL,
	[hpGaPresentAdd] [nvarchar](120) NULL,
	[hpGaPresAtoll] [nvarchar](50) NULL,
	[hpGaPresIsland] [nvarchar](50) NULL,
	[hpGaPresPHNO] [nvarchar](50) NULL,
	[hpGaMOB] [nvarchar](50) NULL,
	[hpDeGaName] [nvarchar](50) NULL,
	[hpDeGaAddress] [nvarchar](50) NULL,
	[hpGaRelation] [nvarchar](50) NULL,
	[hpVerified] [int] NULL,
	[hpuser] [nvarchar](50) NULL,
	[hpdate] [datetime] NULL,
	[hpupdateduser] [nvarchar](50) NULL,
	[hpUpdatedTime] [datetime] NULL,
 CONSTRAINT [PK_losHPCustomerDetails] PRIMARY KEY CLUSTERED 
(
	[hpCustID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  UserDefinedFunction [dbo].[SplitStringByComma]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------
-- 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
GO
/****** Object:  Table [dbo].[CrmOppertunityType]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmOppertunityType](
	[TypeId] [int] NOT NULL,
	[Type] [varchar](50) NOT NULL,
	[Discription] [varchar](1000) NOT NULL,
	[CompanyId] [int] NOT NULL,
 CONSTRAINT [PK_CrmOppertunityType] PRIMARY KEY CLUSTERED 
(
	[TypeId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loiSerialNoVerificationDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[loiSerialNoVerificationDetail](
	[svdGodownID] [int] NULL,
	[svdID] [int] NOT NULL,
	[svdShipMentID] [int] NOT NULL,
	[svdItemID] [int] NULL,
	[svdAvlStock] [numeric](18, 0) NULL,
	[svdVerifiedStock] [numeric](18, 0) NULL,
	[svdCostPrice] [numeric](18, 0) NULL,
	[svdPreSerialNo] [nvarchar](50) NULL,
	[svdNewSerialNo] [nvarchar](50) NULL,
	[svdDeleted] [varchar](4) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TargetMaster]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TargetMaster](
	[CompanyID] [int] NOT NULL,
	[TargetID] [int] NOT NULL,
	[TargetCode] [varchar](50) NULL,
	[TargetHead] [varchar](100) NULL,
	[tarcurid] [int] NULL,
 CONSTRAINT [PK_TargetMaster] PRIMARY KEY NONCLUSTERED 
(
	[CompanyID] ASC,
	[TargetID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spInventoryValueAsOnDate_TransWise]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[losHPCustomerQuotationDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losHPCustomerQuotationDetails](
	[HpCustID] [int] NULL,
	[HPQuotationID] [int] NULL,
	[HPItemId] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losHpInvoiceHeader]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losHpInvoiceHeader](
	[hpqhCompanyID] [int] NOT NULL,
	[hpqhShopID] [int] NOT NULL,
	[hpqhQuotationID] [int] NOT NULL,
	[hpqhQuotationNo] [varchar](50) NOT NULL,
	[hpqhQuotationDate] [datetime] NOT NULL,
	[hpqhDelivaryDate] [datetime] NULL,
	[hpqhScheme] [nvarchar](50) NULL,
	[hpqhType] [char](10) NOT NULL,
	[hpqhReferenceid] [int] NULL,
	[hpqhCancel] [int] NULL,
	[hpqhCancelRemarks] [varchar](250) NULL,
	[hpqhPosted] [int] NOT NULL,
	[hpqhCustomerID] [int] NULL,
	[hpqhCustName] [nvarchar](250) NOT NULL,
	[hpqhCustAddress] [nvarchar](250) NOT NULL,
	[hpqhFirstInstAmt] [numeric](18, 2) NOT NULL,
	[hpqhBalAmt] [numeric](18, 2) NOT NULL,
	[hpqhInstPeriod] [int] NOT NULL,
	[hpqhCashAllowance] [numeric](18, 0) NULL,
	[hpqhInstPerc] [numeric](18, 2) NOT NULL,
	[hpqhInstCharge] [numeric](18, 2) NOT NULL,
	[hpqhSurcharge] [numeric](18, 2) NULL,
	[hpqhTotAdditional] [numeric](18, 2) NULL,
	[hpqhInstPrice] [numeric](18, 2) NULL,
	[hpqhMonthilyPay] [numeric](18, 2) NULL,
	[hpqhConfirmed] [int] NULL,
	[hpqhUserName] [nvarchar](50) NULL,
	[hpqhFinancialID] [int] NULL,
	[hpqhRemarks] [nvarchar](250) NULL,
	[hpqhModifiedUser] [nvarchar](50) NULL,
	[hpqhUpdateTime] [datetime] NULL,
	[hpqhDownPaid] [int] NOT NULL,
	[hpqhProcessed] [int] NOT NULL,
	[hpqhInvoiced] [int] NULL,
	[hpqhChqReg] [int] NULL,
	[hpqhDidAgreement] [int] NULL,
	[hpqhServTaxPerc] [numeric](18, 2) NULL,
	[hpqhServTaxAmount] [numeric](18, 2) NULL,
	[hpqhServTaxCateId] [int] NULL,
	[hpqhRepossessionID] [int] NULL,
	[hpqhAmount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_losHpInvoiceHeader] PRIMARY KEY CLUSTERED 
(
	[hpqhQuotationID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_losHpInvoiceHeader_hpqhQuotationDate] ON [dbo].[losHpInvoiceHeader] 
(
	[hpqhQuotationDate] 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
CREATE NONCLUSTERED INDEX [index_losHpInvoiceHeader] ON [dbo].[losHpInvoiceHeader] 
(
	[hpqhQuotationID] ASC,
	[hpqhShopID] ASC,
	[hpqhCancel] ASC,
	[hpqhType] 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
/****** Object:  Table [dbo].[TempVendorCom]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TempVendorCom](
	[CountryId] [int] NULL,
	[VendorId] [int] NULL,
	[VendorName] [varchar](500) NULL,
	[CountryName] [varchar](500) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spMonthWiseProductSalesAllShops]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO

/****** Object:  Table [dbo].[losHpDummyQuotationHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losHpDummyQuotationHeader](
	[hpqhCompanyID] [int] NULL,
	[hpqhShopID] [int] NULL,
	[hpqhQuotationID] [int] NOT NULL,
	[hpqhQuotationNo] [varchar](50) NOT NULL,
	[hpqhQuotationDate] [datetime] NOT NULL,
	[hpqhAmount] [numeric](18, 0) NOT NULL,
	[hpqhScheme] [nvarchar](50) NULL,
	[hpqhType] [char](10) NOT NULL,
	[hpqhCancel] [int] NULL,
	[hpqhCancelRemarks] [nvarchar](50) NULL,
	[hpqhPosted] [int] NOT NULL,
	[hpqhCustomerID] [int] NULL,
	[hpqhCustName] [nvarchar](50) NOT NULL,
	[hpqhCustAddress] [nvarchar](250) NOT NULL,
	[hpqhFirstInstAmt] [numeric](18, 2) NOT NULL,
	[hpqhBalAmt] [numeric](18, 2) NOT NULL,
	[hpqhInstPeriod] [int] NOT NULL,
	[hpqhCashAllowance] [numeric](18, 0) NULL,
	[hpqhInstPerc] [numeric](18, 2) NOT NULL,
	[hpqhInstCharge] [numeric](18, 2) NOT NULL,
	[hpqhSurcharge] [numeric](18, 2) NULL,
	[hpqhTotAdditional] [numeric](18, 2) NULL,
	[hpqhInstPrice] [numeric](18, 2) NULL,
	[hpqhMonthilyPay] [numeric](18, 2) NULL,
	[hpqhConfirmed] [int] NULL,
	[hpqhUserName] [nvarchar](50) NULL,
	[hpqhFinancialID] [int] NULL,
	[hpqhRemarks] [nvarchar](250) NULL,
	[hpqhModifiedUser] [nvarchar](50) NULL,
	[hpqhUpdateTime] [datetime] NULL,
	[hpqhDownPaid] [int] NOT NULL,
	[hpqhProcessed] [int] NOT NULL,
	[hpqhFinished] [int] NULL,
 CONSTRAINT [PK_losHpDummyQuotationHeader] PRIMARY KEY CLUSTERED 
(
	[hpqhQuotationID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TempVendor]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TempVendor](
	[VendorId] [int] NULL,
	[VendorName] [varchar](500) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spMonthWiseProductSales]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[losHpReceiptHeader]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losHpReceiptHeader](
	[hprhCompanyID] [int] NOT NULL,
	[hprhShopID] [int] NOT NULL,
	[hprhReceiptID] [int] NOT NULL,
	[hprhReceiptNo] [nvarchar](50) NOT NULL,
	[hprhReceiptDate] [datetime] NOT NULL,
	[hprhReceiptType] [varchar](50) NOT NULL,
	[hprhinvBal] [numeric](18, 0) NULL,
	[hprhReceiptAmount] [numeric](18, 2) NOT NULL,
	[hprhCustomerID] [int] NOT NULL,
	[hprhHPQuotationID] [int] NULL,
	[hprhFinancialID] [int] NULL,
	[hprhCancel] [int] NOT NULL,
	[hprhCancelRemarks] [nvarchar](250) NULL,
	[hprhPosted] [int] NULL,
	[hprhBankName] [nvarchar](50) NULL,
	[hprhRemarks] [nvarchar](250) NULL,
	[hprhChequeNo] [nvarchar](50) NULL,
	[hprhChequeDate] [datetime] NULL,
	[hprhUsed] [int] NULL,
	[hprhUserName] [nvarchar](50) NOT NULL,
	[hprhUpdateUserName] [nvarchar](50) NULL,
	[hprhupdateTime] [datetime] NULL,
	[hprhCounterID] [int] NULL,
	[hprhTaxPercentage] [numeric](18, 9) NULL,
	[hprhTaxCateID] [int] NULL,
 CONSTRAINT [PK_losHpReceiptHeader] PRIMARY KEY CLUSTERED 
(
	[hprhCompanyID] ASC,
	[hprhShopID] ASC,
	[hprhReceiptID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TmpLosServiceInvHeader]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TmpLosServiceInvHeader](
	[serinvhid] [int] NOT NULL,
	[serinvhcompanyid] [int] NOT NULL,
	[serinvhshopid] [int] NOT NULL,
	[serinvhjobcardid] [int] NULL,
	[serinvno] [varchar](50) NULL,
	[serinvhrefno] [varchar](50) NULL,
	[serinvhdate] [datetime] NULL,
	[serinvhduedate] [datetime] NULL,
	[serinvhpreparedby] [varchar](50) NULL,
	[serinvhcancelled] [bit] NULL,
	[serinvhserviceamt] [numeric](18, 2) NULL,
	[serinvhpartsamt] [numeric](18, 2) NULL,
	[serinvhamount] [numeric](18, 2) NULL,
	[serinvhposted] [bit] NULL,
	[serinvhdepartmentid] [int] NULL,
	[serinvhcashacc] [int] NULL,
	[serinvhsalesacc] [int] NULL,
	[serinvhservacc] [int] NULL,
	[serinvhcmpexrate] [numeric](18, 8) NULL,
	[serinvhresexrate] [numeric](18, 8) NULL,
	[serinvhbaserate] [numeric](18, 8) NULL,
	[serinvhsettled] [numeric](18, 2) NULL,
	[serinvhremarks] [varchar](250) NULL,
	[serinvcancelremarks] [varchar](250) NULL,
	[serinvhupdatetime] [datetime] NULL,
	[serinvhlocid] [int] NULL,
	[serinvhitemname] [varchar](250) NULL,
	[serinvhitemid] [int] NULL,
	[serinvhDiscount] [numeric](18, 2) NULL,
	[serinvhfutureint] [int] NULL,
	[serinvhfuturevc] [varchar](250) NULL,
	[serinvhfuturenumuric] [numeric](18, 18) NULL,
	[serinvfinancialid] [int] NULL,
	[seinvhdepexrate] [numeric](9, 2) NULL,
	[serinvhfree] [bit] NULL,
	[serinvhexchangerates] [varchar](250) NULL,
	[serinvhcustname] [varchar](250) NULL,
	[serinvhcategid] [int] NULL,
	[serinvhmetereading] [varchar](100) NULL,
	[serinvhCustomerId] [int] NULL,
	[serinvhCashInv] [bit] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losHpRepossessionHeader]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losHpRepossessionHeader](
	[hprhCompanyID] [int] NOT NULL,
	[hprhShopID] [int] NOT NULL,
	[hprhRepossessionID] [int] NOT NULL,
	[hprhRepossessionNo] [nvarchar](50) NOT NULL,
	[hprhRepossessionDate] [datetime] NOT NULL,
	[hprhCustomerID] [int] NOT NULL,
	[hprhAgreementID] [int] NOT NULL,
	[hprhRemarks] [nvarchar](500) NOT NULL,
	[hprhFinancialID] [int] NOT NULL,
	[hprhCancel] [int] NOT NULL,
	[hprhCancelRemarks] [nvarchar](250) NULL,
	[hprhPosted] [int] NOT NULL,
	[hprhUser] [nvarchar](50) NULL,
	[hprhUpdatedUser] [nvarchar](50) NULL,
	[hprhUpdatedTime] [datetime] NULL,
 CONSTRAINT [PK_losHpRepossessionHeader] PRIMARY KEY CLUSTERED 
(
	[hprhCompanyID] ASC,
	[hprhShopID] ASC,
	[hprhRepossessionID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aAtollMaster]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aAtollMaster](
	[AtollID] [int] NOT NULL,
	[AtollName] [nvarchar](50) NOT NULL,
	[DevAtollName] [nvarchar](50) NULL,
	[companyid] [int] NULL,
	[CountryID] [int] NULL,
	[rowguid] [uniqueidentifier] NULL,
 CONSTRAINT [PK_aAtollMaster] PRIMARY KEY CLUSTERED 
(
	[AtollID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spRebatePayment]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 
--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
GO
/****** Object:  StoredProcedure [dbo].[spDayWiseAvgQtySalesRpt]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- ==============================================================================================                        
-- 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
GO
/****** Object:  StoredProcedure [dbo].[FindBlanktable]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
GO
/****** Object:  StoredProcedure [dbo].[spRebuildAllIndex]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  Table [dbo].[losInvoicedPartsReplacedetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losInvoicedPartsReplacedetails](
	[repinvcompanyid] [int] NOT NULL,
	[repinvdpartsid] [int] NOT NULL,
	[repinvdshopid] [int] NOT NULL,
	[repinvinvoiceid] [int] NOT NULL,
	[repinvdrate] [numeric](18, 8) NULL,
	[repinvdsellrate] [numeric](18, 8) NULL,
	[repinvdqty] [numeric](18, 3) NULL,
	[repinvreplfromsupp] [bit] NULL,
	[repinvdguarantee] [bit] NULL,
	[repinvdcostprice] [numeric](18, 8) NULL,
	[repinvdcomments] [varchar](250) NULL,
	[repinvpackid] [int] NULL,
	[repinvpackqty] [numeric](18, 8) NULL,
	[repinvdetailid] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[repinvdType] [varchar](10) NULL,
	[repinvdSerialNo] [varchar](100) NULL,
	[repinvdItemTaxPercentage] [numeric](18, 2) NULL,
	[repinvdItemTaxAmount] [numeric](18, 8) NULL,
	[repinvdItemTaxCategory] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [index_losinvoicedpartsreplacedetails] ON [dbo].[losInvoicedPartsReplacedetails] 
(
	[repinvinvoiceid] ASC,
	[repinvdshopid] 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
/****** Object:  Table [dbo].[losLocationVerificationDetail]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losLocationVerificationDetail](
	[lvdid] [int] NOT NULL,
	[lvdShipmentID] [int] NOT NULL,
	[lvditemid] [int] NOT NULL,
	[lvdShopid] [int] NOT NULL,
	[lvdAvailStock] [numeric](18, 3) NULL,
	[lvdVerifiedStock] [numeric](18, 3) NULL,
	[lvdcostprice] [numeric](18, 3) NULL,
	[lvdPrevLocationID] [int] NULL,
	[lvdVerifiedLocationID] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aBackground]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aBackground](
	[BgID] [int] NOT NULL,
	[BgName] [varchar](50) NOT NULL,
	[BgColor] [varchar](50) NOT NULL,
	[BgFileName] [varchar](50) NOT NULL,
 CONSTRAINT [PK_aBackground] PRIMARY KEY CLUSTERED 
(
	[BgID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spReturnExrate]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------
--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
GO
/****** Object:  StoredProcedure [dbo].[spSalesQuantityValueReport]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==============================================================================================                          
-- 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
GO
/****** Object:  Table [dbo].[aBrandMaster]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aBrandMaster](
	[BrandID] [int] NULL,
	[BrandName] [varchar](100) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_261575970] ON [dbo].[aBrandMaster] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spSalesAnalysisByItem]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
    
      
        
          
----             
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  
    
      
          
            
             
--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
GO
/****** Object:  StoredProcedure [dbo].[spDailyItemSalesFandB]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[aKitItemMaster]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aKitItemMaster](
	[KitID] [int] NOT NULL,
	[KitCode] [varchar](50) NOT NULL,
	[KitName] [varchar](50) NOT NULL,
	[PackingTypeID] [int] NOT NULL,
	[SellingPrice] [numeric](18, 2) NOT NULL,
	[Active] [bit] NOT NULL,
	[Barcode] [varchar](50) NULL,
	[UnitID] [int] NULL,
	[GenerateBarcode] [bit] NULL,
	[KitTax] [numeric](18, 2) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losLocationVerificationHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losLocationVerificationHeader](
	[lvhID] [int] NOT NULL,
	[lvhShopID] [int] NOT NULL,
	[lvhNo] [varchar](50) NULL,
	[lvhDate] [datetime] NULL,
	[lvhRemarks] [varchar](250) NULL,
	[lvhVerifiedBy] [varchar](100) NULL,
	[lvhCancelled] [bit] NOT NULL,
	[lvhCancelRemarks] [varchar](100) NULL,
	[lvhfuturevc] [varchar](250) NULL,
	[lvhposted] [bit] NOT NULL,
	[updatetime] [datetime] NULL,
	[lvhdepartmentid] [int] NULL,
	[lvhconexrate] [numeric](18, 8) NULL,
	[lvhdepexrate] [numeric](18, 8) NULL,
	[lvhexchangerates] [varchar](250) NULL,
	[lvhrecaddUser] [varchar](250) NULL,
	[lvhrecmodUser] [varchar](250) NULL,
	[lvhTime] [datetime] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aBrandMergeDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aBrandMergeDetails](
	[CompanyID] [int] NOT NULL,
	[MergeID] [int] NOT NULL,
	[MergeDate] [datetime] NOT NULL,
	[OldBrandID] [int] NOT NULL,
	[NewBrandID] [int] NOT NULL,
	[Cancelled] [int] NOT NULL,
	[CancelledRemarks] [nvarchar](250) NULL,
	[Remarks] [nvarchar](250) NULL,
	[rowguid] [uniqueidentifier] NOT NULL,
	[UserName] [nvarchar](50) NOT NULL,
	[UpdateDate] [nvarchar](50) NULL,
	[UpdateUsername] [nvarchar](50) NULL,
 CONSTRAINT [PK_aBrandMergeDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[MergeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spSalesAndStock]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------------------------------------------------                
-- 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
GO
/****** Object:  Table [dbo].[restbotkotdetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[restbotkotdetails](
	[companyid] [int] NULL,
	[Outletid] [int] NULL,
	[restno] [int] NULL,
	[botid] [int] NULL,
	[kotid] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losSerCallBconditiondetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSerCallBconditiondetails](
	[CallBcndserbookdid] [int] NULL,
	[CallBcndserid] [int] NULL,
	[CallBcndserdcompanyid] [int] NULL,
	[CallBcndserdshopid] [int] NULL,
	[CallBcndcomments] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aColor]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aColor](
	[ColorID] [int] NOT NULL,
	[ColorCode] [varchar](50) NOT NULL,
	[ColorName] [varchar](50) NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aColor] PRIMARY KEY NONCLUSTERED 
(
	[ColorID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_149575571] ON [dbo].[aColor] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spServiceSalesDateWise]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spSalesMarginReport]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==============================================================================================                          
-- 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
GO
/****** Object:  Table [dbo].[aCompanyMaster]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aCompanyMaster](
	[CompanyID] [int] NOT NULL,
	[Name] [varchar](250) NOT NULL,
	[Address1] [varchar](250) NULL,
	[Address2] [varchar](250) NULL,
	[Address3] [varchar](250) NULL,
	[CityID] [int] NULL,
	[CountryID] [int] NULL,
	[PhoneNo] [varchar](50) NULL,
	[FaxNo] [varchar](50) NULL,
	[EmailID] [varchar](50) NULL,
	[CurrencyID] [int] NULL,
	[FinancialID] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF
ALTER TABLE [dbo].[aCompanyMaster] ADD [CompanyTIN] [varchar](50) NULL
ALTER TABLE [dbo].[aCompanyMaster] ADD  CONSTRAINT [PK_aCompanyMaster] PRIMARY KEY NONCLUSTERED 
(
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1237579447] ON [dbo].[aCompanyMaster] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spStockBalancingCompWise]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  Table [dbo].[losCosAvlStock]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losCosAvlStock](
	[CompanyId] [int] NULL,
	[CostingID] [int] NULL,
	[ItemID] [int] NULL,
	[OldStock] [numeric](18, 2) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losSerialIssueDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losSerialIssueDetails](
	[sidInterfaceID] [int] NOT NULL,
	[sidShopID] [int] NOT NULL,
	[sidTransactionID] [int] NOT NULL,
	[sidDetailID] [int] NOT NULL,
	[sidSerialNo] [nvarchar](50) NOT NULL,
	[sidItemID] [int] NOT NULL,
	[sidItemQty] [numeric](10, 2) NOT NULL,
	[sidPackingTypeID] [int] NOT NULL,
	[sidPackingQty] [numeric](10, 2) NOT NULL,
	[sidCancel] [int] NOT NULL,
	[sidAdjustment] [int] NOT NULL,
	[sidFreeQty] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aContainerMaster]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aContainerMaster](
	[CompanyID] [int] NOT NULL,
	[ContainerID] [int] NOT NULL,
	[ContainerCode] [varchar](50) NOT NULL,
	[ContainerDesc] [varchar](100) NOT NULL,
	[CountryID] [int] NOT NULL,
 CONSTRAINT [PK_acontainermaster] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[ContainerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spStockOrdering1]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------------------------                  
--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
GO
/****** Object:  Table [dbo].[losSerStandByReceiptHeader]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSerStandByReceiptHeader](
	[rhCompanyID] [int] NOT NULL,
	[rhShopID] [int] NOT NULL,
	[rhReceiptID] [int] NOT NULL,
	[rhReceiptNo] [varchar](50) NOT NULL,
	[rhDate] [datetime] NOT NULL,
	[rhIssueID] [int] NOT NULL,
	[rhReceivedByID] [int] NOT NULL,
	[rhCancelled] [bit] NOT NULL,
	[rhCancelledRemarks] [varchar](250) NOT NULL,
	[rhRemarks] [varchar](250) NOT NULL,
	[rhUpdateTime] [datetime] NOT NULL,
	[rhFuture] [varchar](250) NULL,
	[rhType] [char](1) NOT NULL,
 CONSTRAINT [PK_losSerStandByReceiptHeader] PRIMARY KEY NONCLUSTERED 
(
	[rhCompanyID] ASC,
	[rhShopID] ASC,
	[rhReceiptID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[FB_dishsubgroupshopdetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[FB_dishsubgroupshopdetails](
	[fb_Ds_companyid] [int] NOT NULL,
	[Fb_Ds_Outletid] [int] NOT NULL,
	[Fb_Ds_Subgroupid] [int] NOT NULL,
	[Fb_Ds_Futureint] [int] NULL,
	[Fb_Ds_Futurevarchar] [varchar](250) NULL,
	[Fb_Ds_Futurebit] [bit] NULL,
	[fb_Ds_CntrTaxper] [decimal](18, 0) NULL,
	[fb_Ds_StateTaxper] [decimal](18, 0) NULL,
	[Fb_Ds_Printerpath] [varchar](250) NULL,
 CONSTRAINT [PK_FB_dishsubgroupshopdetails] PRIMARY KEY NONCLUSTERED 
(
	[fb_Ds_companyid] ASC,
	[Fb_Ds_Outletid] ASC,
	[Fb_Ds_Subgroupid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[FB_Dishdetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[FB_Dishdetails](
	[fb_dd_companyid] [int] NOT NULL,
	[fb_dd_dishid] [int] NOT NULL,
	[fb_dd_dishsubgroupid] [int] NOT NULL,
	[fb_dd_dishcode] [varchar](50) NULL,
	[fb_dd_dishname] [varchar](250) NULL,
	[fb_dd_processingdur] [int] NULL,
	[fb_dd_roombarrestmenu] [varchar](5) NULL,
	[fb_dd_remarks] [varchar](250) NULL,
	[fb_dd_yield] [bit] NOT NULL,
	[fb_dd_Futureint] [int] NULL,
	[fb_dd_Futurevarchar] [varchar](250) NULL,
	[fb_dd_Futurebit] [bit] NULL,
	[fb_dd_preparations] [varchar](5000) NULL,
	[EditDate] [datetime] NULL,
	[UserID] [int] NULL,
	[fb_dd_imagepath] [varchar](500) NULL,
	[fb_dd_dishcp] [decimal](18, 3) NULL,
	[Fb_dd_TaxCategoryId] [int] NULL,
 CONSTRAINT [PK_FB_Dishdetails] PRIMARY KEY NONCLUSTERED 
(
	[fb_dd_companyid] ASC,
	[fb_dd_dishid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aCreditChasing]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aCreditChasing](
	[CompanyID] [int] NOT NULL,
	[DepartmentID] [int] NOT NULL,
	[InvoiceNo] [varchar](250) NOT NULL,
	[CommittedDate] [datetime] NOT NULL,
	[Remarks] [varchar](250) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spStockReOrdering]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------------------------------------------------          
--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
GO
/****** Object:  Table [dbo].[misCategoryHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[misCategoryHeader](
	[mcID] [int] NOT NULL,
	[mcName] [varchar](100) NULL,
	[mcSystem] [bit] NULL,
	[CompanyID] [int] NOT NULL,
	[modulecode] [char](5) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aHQPurchaseOrderStatus]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHQPurchaseOrderStatus](
	[CompanyID] [int] NULL,
	[StatusID] [int] NULL,
	[PoID] [int] NULL,
	[VesselID] [int] NULL,
	[ContainerID] [int] NULL,
	[StatusDate] [datetime] NULL,
	[UserName] [varchar](50) NULL,
	[UpdateUserName] [varchar](50) NULL,
	[UpdateDate] [datetime] NULL,
	[CountryID] [int] NULL,
	[StatusType] [int] NULL,
	[Remarks] [varchar](1000) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[sptemp]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  Table [dbo].[tbTest]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tbTest](
	[itemid] [int] NULL,
	[value] [varchar](10) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Build]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Build](
	[Build] [decimal](18, 0) NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aItemImage]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aItemImage](
	[CompanyID] [int] NOT NULL,
	[ItemID] [int] NOT NULL,
	[ItemImage1] [image] NULL,
	[ItemImage2] [image] NULL,
	[ItemImage3] [image] NULL,
	[ItemImage4] [image] NULL,
 CONSTRAINT [PK_aItemImage] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[ItemID] 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]
GO
/****** Object:  Table [dbo].[ShopbfMealplan]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ShopbfMealplan](
	[Companyid] [int] NOT NULL,
	[Outletid] [int] NOT NULL,
	[Mealnameid] [int] NOT NULL,
 CONSTRAINT [PK_ShopbfMealplan] PRIMARY KEY NONCLUSTERED 
(
	[Companyid] ASC,
	[Outletid] ASC,
	[Mealnameid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[EmailSettings]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[EmailSettings](
	[SMTPHost] [varchar](50) NULL,
	[SMTPPort] [int] NULL,
	[DisplayName] [varchar](50) NULL,
	[EMail] [varchar](50) NULL,
	[Password] [varchar](50) NULL,
	[TimerInterval] [varchar](50) NULL,
	[ForecastingDays] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losSerialNoVerificationHeader]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[losSerialNoVerificationHeader](
	[svhCompanyID] [int] NOT NULL,
	[svhShopID] [int] NOT NULL,
	[svhID] [int] NOT NULL,
	[svhNo] [nvarchar](50) NOT NULL,
	[svhDate] [datetime] NOT NULL,
	[svhVerifiedBy] [char](10) NULL,
	[svhRemarks] [nvarchar](150) NULL,
	[svhCancel] [int] NOT NULL,
	[svhCancellRemarks] [nvarchar](150) NULL,
	[svhFutureVC] [char](10) NULL,
	[svhUser] [varchar](50) NULL,
	[svhUpdateUser] [char](10) NULL,
	[svhUpdateTime] [datetime] NULL,
	[cofirmed] [bit] NULL,
 CONSTRAINT [PK_losSerialNoVerificationHeader] PRIMARY KEY CLUSTERED 
(
	[svhCompanyID] ASC,
	[svhShopID] ASC,
	[svhID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CrmUserPreference]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmUserPreference](
	[UserId] [int] NOT NULL,
	[Theme] [varchar](50) NOT NULL,
	[Appstyle] [varchar](50) NOT NULL,
	[GridWidth] [int] NOT NULL,
	[LastSelectCountry] [int] NULL,
	[LastSelectCity] [int] NULL,
	[ActivityTaskFilter] [varchar](50) NULL,
	[UserFilter] [varchar](50) NULL,
	[ProbablityFilter] [varchar](50) NULL,
	[LeasSourceFilter] [varchar](50) NULL,
	[SalesStageFilter] [varchar](50) NULL,
	[ReportFromdate] [varchar](50) NULL,
	[ReportTodate] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Fb_botheader]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Fb_botheader](
	[Fb_bh_Companyid] [int] NOT NULL,
	[Fb_bh_outletid] [int] NOT NULL,
	[Fb_bh_botid] [int] NOT NULL,
	[Fb_bh_botno] [varchar](50) NULL,
	[Fb_bh_botdatetime] [datetime] NULL,
	[Fb_bh_registrationid] [int] NULL,
	[Fb_bh_Employeeid] [int] NULL,
	[Fb_bh_Tableid] [int] NULL,
	[Fb_bh_ordertakenid] [int] NULL,
	[Fb_bh_Remarks] [varchar](250) NULL,
	[Fb_bh_cancelled] [bit] NOT NULL,
	[Fb_bh_CancelledRemarks] [varchar](250) NULL,
	[Fb_bh_Complimentaryid] [int] NULL,
 CONSTRAINT [PK_Fb_botheader] PRIMARY KEY NONCLUSTERED 
(
	[Fb_bh_Companyid] ASC,
	[Fb_bh_outletid] ASC,
	[Fb_bh_botid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spDailySalesCollectionDay]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
---------------------------------------------

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

-------------------------------------------------------------------
GO
/****** Object:  Table [dbo].[aShopChequeAccountDetails]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[aShopChequeAccountDetails](
	[shopID] [int] NOT NULL,
	[ChequeAccountID] [int] NOT NULL,
	[CompanyID] [int] NULL,
	[futurevc] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losTenantServiceRegisterDetail]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losTenantServiceRegisterDetail](
	[trdTransID] [int] NULL,
	[trdTransShopid] [int] NULL,
	[trdTransCompanyId] [int] NULL,
	[trdTransDetailId] [int] NULL,
	[trdServiceId] [int] NULL,
	[trdServiceQty] [numeric](18, 3) NULL,
	[trdServiceActualRate] [numeric](18, 2) NULL,
	[trdServiceRate] [numeric](18, 2) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aCustomerGroup]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aCustomerGroup](
	[CompanyID] [int] NOT NULL,
	[CusGroupId] [int] NOT NULL,
	[CusGroupName] [varchar](50) NOT NULL,
	[ParentGroupID] [int] NOT NULL,
	[LevelCode] [int] NOT NULL,
	[rowguid] [uniqueidentifier] NOT NULL,
	[Prefix] [varchar](25) NULL,
	[PrefixActive] [bit] NULL,
 CONSTRAINT [PK_aCustomerGroup] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[CusGroupId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spStockReOrderingMonthlyWise]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------------------------------------------------  
--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
GO
/****** Object:  Table [dbo].[aVendorGroup]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aVendorGroup](
	[CompanyID] [int] NOT NULL,
	[VenGroupId] [int] NOT NULL,
	[VenGroupName] [varchar](50) NOT NULL,
	[ParentGroupID] [int] NOT NULL,
	[LevelCode] [int] NOT NULL,
	[rowguid] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_aVendorGroup] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[VenGroupId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aCustomerMasterBackUp]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aCustomerMasterBackUp](
	[CustomerID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[FinancialID] [int] NOT NULL,
	[OpeningCreditBalance] [numeric](18, 2) NOT NULL,
	[OpeningDebitBalance] [numeric](18, 2) NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aCustomerMasterBackUp] PRIMARY KEY NONCLUSTERED 
(
	[CustomerID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_181575685] ON [dbo].[aCustomerMasterBackUp] 
(
	[rowguid] 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
/****** Object:  StoredProcedure [dbo].[spVendorAdvanceasonDate]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  UserDefinedFunction [dbo].[fnHourRange]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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
GO
/****** Object:  Table [dbo].[tempqtywisegrouped]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tempqtywisegrouped](
	[soldyeargrp] [int] NULL,
	[soldmonthgrp] [int] NULL,
	[rangedetail] [int] NULL,
	[rangeqtygrp] [numeric](18, 2) NULL,
	[avgmonth] [int] NULL,
	[currentstock] [numeric](18, 2) NULL,
	[stockvalue] [numeric](18, 2) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losTenantServiceRegisterHeader]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losTenantServiceRegisterHeader](
	[trhTransId] [int] NULL,
	[trhTransShopId] [int] NULL,
	[trhTransCompanyid] [int] NULL,
	[trhTransNo] [varchar](50) NULL,
	[trhDate] [datetime] NULL,
	[trhApartmentId] [int] NULL,
	[trhAgreementID] [int] NULL,
	[trhEnteredBy] [int] NULL,
	[trhRemarks] [varchar](250) NULL,
	[trhCancelled] [bit] NULL,
	[trhCancelledRemarks] [varchar](250) NULL,
	[trhStatus] [char](1) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aListItemMaster]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aListItemMaster](
	[Listid] [int] NOT NULL,
	[ListCode] [varchar](50) NOT NULL,
	[ListDescription] [varchar](50) NOT NULL,
 CONSTRAINT [PK_aListItemMaster] PRIMARY KEY CLUSTERED 
(
	[Listid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LosMergeDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LosMergeDetails](
	[lsdID] [int] NOT NULL,
	[lsdCompanyID] [int] NOT NULL,
	[lsdShopID] [int] NOT NULL,
	[lsdItemID] [int] NULL,
	[lsdQty] [numeric](18, 3) NULL,
	[lsdDetailID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_losMergeDetails] ON [dbo].[LosMergeDetails] 
(
	[lsdID] ASC,
	[lsdShopID] 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
/****** Object:  StoredProcedure [dbo].[SpTotalBinCardAudit]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spgodownitemnotinshop]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[aservicemaster]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aservicemaster](
	[serid] [int] NOT NULL,
	[sercompanyid] [int] NOT NULL,
	[sercategid] [int] NULL,
	[sercode] [varchar](50) NOT NULL,
	[sername] [varchar](250) NOT NULL,
	[sercharge] [numeric](18, 8) NOT NULL,
	[serdetails] [varchar](250) NULL,
	[serfutureint] [int] NULL,
	[serfururevc] [varchar](250) NULL,
	[serfuturenum] [numeric](18, 8) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[serservicetype] [char](5) NOT NULL,
 CONSTRAINT [PK_aservicemaster] PRIMARY KEY NONCLUSTERED 
(
	[serid] ASC,
	[sercompanyid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1013578649] ON [dbo].[aservicemaster] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosMergeHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosMergeHeader](
	[lshID] [int] NOT NULL,
	[lshCompanyID] [int] NOT NULL,
	[lshShopID] [int] NOT NULL,
	[lshNo] [varchar](50) NULL,
	[lshDate] [datetime] NULL,
	[lshRefMergeID] [int] NULL,
	[lshItemID] [int] NULL,
	[lshTransFinished] [bit] NULL,
	[lshCancelled] [bit] NULL,
	[lshUpdatetime] [datetime] NULL,
	[lshNoofRec] [int] NULL,
	[lshQty] [numeric](18, 3) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_losMergeHeader_lshDate] ON [dbo].[LosMergeHeader] 
(
	[lshDate] 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
CREATE NONCLUSTERED INDEX [index_losMergeHeader] ON [dbo].[LosMergeHeader] 
(
	[lshID] ASC,
	[lshShopID] ASC,
	[lshCancelled] 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
/****** Object:  StoredProcedure [dbo].[SpUpdateGodownCheck]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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*/
GO
/****** Object:  Table [dbo].[assetdisposalheader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[assetdisposalheader](
	[disphcompanyid] [int] NOT NULL,
	[disphid] [int] NOT NULL,
	[disphno] [varchar](50) NULL,
	[disphdate] [datetime] NULL,
	[disphremarks] [varchar](250) NULL,
	[disphposted] [bit] NULL,
	[disphcancelled] [bit] NULL,
	[disphcancelledremarks] [varchar](250) NULL,
	[disphauthorisedby] [varchar](100) NULL,
	[disphdepartmentid] [int] NULL,
	[disphexrate] [numeric](18, 8) NULL,
	[disphexchangerates] [varchar](250) NULL,
	[disphdepexrate] [numeric](18, 8) NULL,
	[financialid] [int] NULL,
	[updatetime] [datetime] NULL,
	[disphSubdepartmentid] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[crmItem]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[crmItem](
	[ItemID] [int] NULL,
	[ItemCode] [varchar](50) NULL,
	[ItemDescription] [varchar](250) NULL,
	[ItemPrice] [numeric](18, 2) NULL,
	[ItemImage] [image] NULL,
	[Extension] [char](4) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losHPChequeRegisterHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losHPChequeRegisterHeader](
	[HphCompanyID] [int] NOT NULL,
	[HPhShopID] [int] NOT NULL,
	[HphChqRegID] [int] NOT NULL,
	[HphChqRegNO] [nvarchar](50) NOT NULL,
	[HphDate] [datetime] NOT NULL,
	[hphAgreementID] [int] NULL,
	[hphInvoiceID] [int] NULL,
	[hphCustID] [int] NULL,
	[HPhfinancialid] [int] NOT NULL,
	[HphPeriod] [numeric](18, 0) NULL,
	[HphInstMonthlyPay] [numeric](18, 2) NULL,
	[hphCancel] [int] NULL,
	[hphCancelRemarks] [nvarchar](100) NULL,
	[hphShopverify] [int] NULL,
	[HphUser] [nvarchar](50) NULL,
	[HphModifiedUser] [nvarchar](50) NULL,
	[HphModifiedDate] [nvarchar](50) NULL,
 CONSTRAINT [PK_losHPChequeRegisterHeader] PRIMARY KEY CLUSTERED 
(
	[HphChqRegID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TargetFixationDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TargetFixationDetail](
	[tfdCompanyID] [int] NOT NULL,
	[tfdFixationID] [int] NOT NULL,
	[tfdDetailID] [int] NOT NULL,
	[tfdTargetID] [int] NULL,
	[tfdFromDate] [datetime] NULL,
	[tfdToDate] [datetime] NULL,
	[tfdAmount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_TargetFixationDetail] PRIMARY KEY NONCLUSTERED 
(
	[tfdCompanyID] ASC,
	[tfdFixationID] ASC,
	[tfdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spHPFinancialIncomeEarned]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  Table [dbo].[InterDivisionJournalTransHeader]    Script Date: 04/16/2012 10:32:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[InterDivisionJournalTransHeader](
	[JournalTransID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[JournalNo] [varchar](50) NULL,
	[JournalTransDate] [smalldatetime] NOT NULL,
	[Remarks] [varchar](100) NULL,
	[Cancelled] [bit] NOT NULL,
	[CancelledRemarks] [varchar](100) NULL,
	[Posted] [bit] NOT NULL,
	[FinancialID] [int] NULL,
	[parentjournalid] [int] NULL,
	[childjournalid] [int] NULL,
	[updatetime] [datetime] NOT NULL,
	[exchangerate] [numeric](18, 8) NULL,
	[exchangerates] [varchar](250) NULL,
	[Type] [char](2) NULL,
	[Confirm] [bit] NULL,
	[TypeSeriallNO] [varchar](100) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losexpiryarrivaldetails]    Script Date: 04/16/2012 10:32:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losexpiryarrivaldetails](
	[eadInterfaceID] [int] NULL,
	[eadShopID] [int] NULL,
	[eadTransactionID] [int] NULL,
	[eadDetailID] [int] NULL,
	[eadExpiryDate] [datetime] NULL,
	[eadItemID] [int] NULL,
	[eadItemQty] [numeric](18, 3) NULL,
	[eadPackingtypeID] [int] NULL,
	[eadPackingQty] [numeric](18, 3) NULL,
	[eadCancel] [bit] NOT NULL,
	[eadAdjustment] [bit] NOT NULL,
	[eadfreeqty] [numeric](18, 3) NULL,
	[eadbatchno] [varchar](20) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aDocumentTypeMaster]    Script Date: 04/16/2012 10:32:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aDocumentTypeMaster](
	[DocTypeCompanyId] [int] NOT NULL,
	[DocTypeID] [int] NOT NULL,
	[DocTypeCode] [varchar](50) NOT NULL,
	[DocTypeName] [varchar](100) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spcompstockout]    Script Date: 04/16/2012 10:32:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  Table [dbo].[losexpiryissuedetails]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losexpiryissuedetails](
	[eidInterfaceID] [int] NULL,
	[eidShopID] [int] NULL,
	[eidTransactionID] [int] NULL,
	[eidDetailID] [int] NULL,
	[eidExpiryDate] [datetime] NULL,
	[eidItemID] [int] NULL,
	[eidItemQty] [numeric](18, 3) NULL,
	[eidPackingtypeID] [int] NULL,
	[eidPackingQty] [numeric](18, 3) NULL,
	[eidCancel] [bit] NOT NULL,
	[eidAdjustment] [bit] NOT NULL,
	[eidfreeqty] [numeric](18, 0) NULL,
	[eidbatchno] [varchar](20) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aUserGroupBrandDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aUserGroupBrandDetails](
	[CompanyID] [int] NOT NULL,
	[UserGroupID] [int] NOT NULL,
	[BrandID] [int] NOT NULL,
	[rowguiD] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_aUserGroupBrandDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[UserGroupID] ASC,
	[BrandID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[shopWallpaper]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[shopWallpaper](
	[CompanyID] [int] NULL,
	[ShopID] [int] NULL,
	[WallpaperImage] [image] NULL,
	[types] [varchar](5) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CrmAgreement]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmAgreement](
	[AgreementId] [int] NOT NULL,
	[QuotationID] [int] NULL,
	[AccountId] [int] NULL,
	[UserId] [int] NULL,
	[AgreementSubject] [varchar](50) NULL,
	[Document] [image] NULL,
	[Extension] [varchar](50) NULL,
	[AgreementDate] [datetime] NULL,
	[CreateDate] [datetime] NULL,
	[Deleted] [int] NULL,
	[IsTemplate] [int] NULL,
	[ProposalId] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loiSerialIssueDetails]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[loiSerialIssueDetails](
	[sidInterfaceID] [int] NOT NULL,
	[sidGodownID] [int] NOT NULL,
	[sidTransactionID] [int] NOT NULL,
	[sidDetailID] [int] NOT NULL,
	[sidSerialNo] [nvarchar](50) NOT NULL,
	[sidItemID] [int] NOT NULL,
	[sidItemQty] [numeric](10, 2) NOT NULL,
	[sidPackingQty] [numeric](10, 2) NOT NULL,
	[sidCancel] [int] NOT NULL,
	[sidAdjustment] [int] NOT NULL,
	[sidPackingTypeID] [int] NOT NULL,
	[sidFreeQty] [int] NOT NULL,
	[sidSavedByShopId] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[REPORTOUT]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[REPORTOUT](
	[RDATE] [datetime] NULL,
	[rreceipt] [varchar](50) NULL,
	[rtype] [varchar](5) NULL,
	[rledgername] [varchar](250) NULL,
	[ldebitamt] [varchar](50) NULL,
	[lcreditamt] [varchar](50) NULL,
	[rbalance] [varchar](50) NULL,
	[rcnt] [int] NULL,
	[rremarks] [varchar](1000) NULL,
	[rjournalid] [int] NULL,
	[rreferenceid] [int] NULL,
	[rdiff] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spDailySalesCollection]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
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','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
GO
/****** Object:  Table [dbo].[loiGodownTransactionsSummary]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[loiGodownTransactionsSummary](
	[SummaryDate] [datetime] NOT NULL,
	[GodownId] [int] NOT NULL,
	[ItemId] [int] NOT NULL,
	[Stock] [numeric](18, 3) NULL,
	[BadStock] [numeric](18, 3) NULL,
	[OpeningStock] [numeric](18, 3) NULL,
	[OpeningBadStock] [numeric](18, 3) NULL,
	[ShipmentId] [int] NULL,
	[ItemCostPrice] [numeric](18, 2) NULL,
 CONSTRAINT [PK_loiGodownTransactionsSummary] PRIMARY KEY CLUSTERED 
(
	[GodownId] ASC,
	[ItemId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aHpFeePaymentHeader]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aHpFeePaymentHeader](
	[HpHCompanyID] [int] NOT NULL,
	[HpHDepartmentID] [int] NOT NULL,
	[HpHPaymentID] [int] NOT NULL,
	[HphPaymentNo] [nvarchar](50) NOT NULL,
	[HpHReferenceNo] [nvarchar](50) NULL,
	[HpHPaymentDate] [datetime] NULL,
	[HpHAccountID] [int] NOT NULL,
	[HpHPayee] [nvarchar](50) NULL,
	[HpHAmount] [numeric](18, 0) NULL,
	[HpHFinancialID] [int] NULL,
	[HpHCancel] [int] NULL,
	[HpHPosted] [int] NULL,
	[HpHExRate] [numeric](18, 2) NULL,
	[HpHComExRate] [numeric](18, 2) NULL,
	[HpHDepExRate] [numeric](18, 2) NULL,
	[HpHUsers] [nvarchar](50) NULL,
	[HpHUpdateUserName] [nvarchar](50) NULL,
	[HpHUpdateTime] [datetime] NULL,
	[HpHRemarks] [nvarchar](500) NULL,
	[HpHCancelRemarks] [nvarchar](500) NULL
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[CrmSpGetTask]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
create procedure [dbo].[CrmSpGetTask] 
@Taskid as int
as
select * from CrmTask where TaskId=@Taskid
GO
/****** Object:  Table [dbo].[misReportMenu]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[misReportMenu](
	[ReportID] [int] NOT NULL,
	[MenuID] [int] NOT NULL,
	[MenuName] [varchar](100) NULL,
	[CompanyID] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Fb_Shopdishdetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Fb_Shopdishdetails](
	[Fb_Sd_Companyid] [int] NOT NULL,
	[Fb_Sd_Outletid] [int] NOT NULL,
	[Fb_Sd_Dishid] [int] NOT NULL,
	[Fb_Sd_Dishamt] [decimal](18, 2) NULL,
	[Fb_Sd_Starttime] [datetime] NULL,
	[Fb_Sd_Endtime] [datetime] NULL,
	[fb_sd_processingdur] [int] NULL,
	[Fb_Sd_Futureint] [int] NULL,
	[Fb_Sd_Futurevarchar] [varchar](250) NULL,
	[Fb_Sd_Futurebit] [bit] NULL,
	[fb_sd_dishamtdisc] [decimal](18, 2) NULL,
	[fb_sd_dishamtdlyflght] [decimal](18, 2) NULL,
	[fb_sd_dishamtstaff] [decimal](18, 2) NULL,
 CONSTRAINT [PK_Fb_Shopdishdetails] PRIMARY KEY NONCLUSTERED 
(
	[Fb_Sd_Companyid] ASC,
	[Fb_Sd_Outletid] ASC,
	[Fb_Sd_Dishid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aservicestatus]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aservicestatus](
	[serstatuscompanyid] [int] NOT NULL,
	[serStatusID] [int] NOT NULL,
	[serStatusName] [varchar](50) NULL,
	[serStatusDesc] [varchar](250) NULL,
 CONSTRAINT [PK__aservicestatus__6E0DDAD3] PRIMARY KEY CLUSTERED 
(
	[serstatuscompanyid] ASC,
	[serStatusID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losInvoicedServiceDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losInvoicedServiceDetails](
	[serinvdcompanyid] [int] NOT NULL,
	[serinvdinvoiceid] [int] NOT NULL,
	[serinvdshopid] [int] NOT NULL,
	[serinvdserviceid] [int] NOT NULL,
	[serinvdcharge] [numeric](18, 8) NULL,
	[serinvdchargetaken] [numeric](18, 8) NULL,
	[serinvdcomments] [varchar](250) NULL,
	[serinvdqty] [numeric](18, 2) NULL,
	[serinvddetailid] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[serinvdType] [char](10) NULL,
	[serinvdItemTaxPercentage] [numeric](18, 2) NULL,
	[serinvdItemTaxAmount] [numeric](18, 2) NULL,
	[serinvdItemTaxCategory] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aBackgroundUsers]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aBackgroundUsers](
	[UserID] [int] NULL,
	[Location] [char](10) NULL,
	[BgID] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spReturnValue]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  StoredProcedure [dbo].[spDishCategorySales]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================        
-- Author:  <AADYAKUMAR.D.V>        
-- Create date: <17/01/2012>        
-- =============================================        
-- Modified by : AADYAKUMAR.D.V            
-- Date        : 19/01/2012                
-- RefNo       : 1               
-- Comments    : Bug fixed existing qry            
--==============================================      
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 + '''         
  --'        
   set @strsql='              
  SELECT distinct fb_pd_processid,fb_dd_dishcode ItemCode,fb_dd_dishname DishName,''Dish'',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_reusedqty ,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: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'',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_reusedqty ,fb_pd_cost ,fb_pd_Rate,Fb_Ds_DishSubGroupName,fb_pd_dishid      
'        
-- RefNo:1----------------------------------------end---------------------------------------------------------      
execute sp_executesql @strsql          
 END              
END
GO
/****** Object:  Table [dbo].[LOsPurchaseReturnHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsPurchaseReturnHeader](
	[whShopID] [int] NOT NULL,
	[WhID] [int] NOT NULL,
	[WhNo] [varchar](50) NULL,
	[WhDate] [datetime] NULL,
	[WhUserName] [varchar](50) NULL,
	[WhCancelled] [bit] NOT NULL,
	[WhCancelledRemarks] [varchar](250) NULL,
	[WhRemarks] [varchar](250) NULL,
	[WhRecAddUser] [varchar](250) NULL,
	[WhRecModifyUser] [varchar](250) NULL,
	[Whfuturevc] [varchar](250) NOT NULL,
	[whposted] [bit] NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[whdepartmentid] [int] NULL,
	[whconexrate] [numeric](18, 8) NULL,
	[whdepexrate] [numeric](18, 8) NULL,
	[whexchangerates] [varchar](250) NULL,
	[whotherdepid] [int] NULL,
	[whreceivedby] [varchar](100) NULL,
	[whauthorisedby] [varchar](100) NULL,
	[whtype] [char](1) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[whexpenseaccid] [int] NULL,
	[whapartmentid] [int] NULL,
	[whdoneby] [varchar](150) NULL,
	[whtransfinished] [bit] NULL,
	[whselected] [int] NULL,
	[whtime] [datetime] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_losPurchaseReturnheader_whdate] ON [dbo].[LOsPurchaseReturnHeader] 
(
	[WhDate] 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
CREATE NONCLUSTERED INDEX [index_losPurchaseReturnheader] ON [dbo].[LOsPurchaseReturnHeader] 
(
	[WhID] ASC,
	[whShopID] ASC,
	[WhCancelled] ASC,
	[whtransfinished] 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
/****** Object:  Table [dbo].[alocationdsn]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[alocationdsn](
	[LocationID] [int] NOT NULL,
	[LocationType] [varchar](10) NOT NULL,
	[ServerName] [varchar](100) NULL,
	[DsnName] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spMagnoliaReturnExrate]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[loiExpiryVerificationDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loiExpiryVerificationDetail](
	[evdId] [int] NOT NULL,
	[evdShipmentId] [int] NOT NULL,
	[evdItemId] [int] NOT NULL,
	[evdGodownId] [int] NOT NULL,
	[evdAvailStock] [numeric](18, 3) NULL,
	[evdVerifiedStock] [numeric](18, 3) NULL,
	[evdCostPrice] [numeric](18, 3) NULL,
	[evdPrevExpiryDate] [datetime] NULL,
	[evdVerifiedExpiryDate] [datetime] NOT NULL,
	[evdPrevBatchNo] [varchar](20) NOT NULL,
	[evdBatchNo] [varchar](20) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aRateEditingDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aRateEditingDetails](
	[redID] [int] NOT NULL,
	[redDate] [datetime] NOT NULL,
	[reditemid] [int] NOT NULL,
	[reduserid] [int] NOT NULL,
	[redcompanyid] [int] NOT NULL,
	[redoldcostprice] [numeric](18, 8) NOT NULL,
	[redcostprice] [numeric](18, 8) NOT NULL,
	[UpdateDateTime] [datetime] NOT NULL,
 CONSTRAINT [PK_aRateEditingDetails] PRIMARY KEY CLUSTERED 
(
	[redID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[BudgetCheckHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[BudgetCheckHeader](
	[bchCompanyId] [int] NOT NULL,
	[bchCheckID] [int] NOT NULL,
	[bchCheckNo] [varchar](50) NULL,
	[bchCheckDate] [datetime] NULL,
	[bchBudgetAllocID] [int] NULL,
	[bchActualAsonDate] [datetime] NULL,
	[bchCheckedBy] [varchar](250) NULL,
	[bchRemarks] [varchar](250) NULL,
	[bchCancelled] [bit] NULL,
	[bchCancelledRemarks] [varchar](250) NULL,
	[bchexchagerate] [varchar](250) NULL,
 CONSTRAINT [PK_BudgetCheckHeader] PRIMARY KEY NONCLUSTERED 
(
	[bchCompanyId] ASC,
	[bchCheckID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aUserGroupShopDetails]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aUserGroupShopDetails](
	[CompanyID] [int] NOT NULL,
	[UserGroupID] [int] NOT NULL,
	[ShopID] [int] NOT NULL,
	[rowguID] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_aUserGroupShopDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[UserGroupID] ASC,
	[ShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TmpInvHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TmpInvHeader](
	[serinvhid] [float] NULL,
	[serinvhamount] [float] NULL
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spPaymentWithChequeDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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
GO
/****** Object:  StoredProcedure [dbo].[spCustomerLedger]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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
GO
/****** Object:  Table [dbo].[losHpItemRegistrationDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losHpItemRegistrationDetails](
	[IRCompanyID] [int] NOT NULL,
	[IRShopID] [char](10) NOT NULL,
	[IRRegistrationID] [int] NOT NULL,
	[IRRegistrationNo] [nvarchar](50) NOT NULL,
	[IRRegistrationDate] [datetime] NOT NULL,
	[IRFinancialID] [int] NOT NULL,
	[IRShipment] [nvarchar](50) NULL,
	[IRMode] [nvarchar](50) NULL,
	[IRItemID] [int] NOT NULL,
	[IRColorID] [int] NULL,
	[IRCancel] [int] NULL,
	[IRCancelRemarks] [nvarchar](50) NULL,
	[IRForSales] [int] NULL,
	[IRModelNo] [nvarchar](50) NULL,
	[IRFrameNo] [nvarchar](50) NULL,
	[IREngineNo] [nvarchar](50) NULL,
	[IRProduction] [nvarchar](50) NULL,
	[IRLocation] [nvarchar](50) NULL,
	[IRCustomerID] [int] NULL,
	[IRRegNo] [nvarchar](50) NULL,
	[IRRoadWorthiness] [nvarchar](50) NULL,
	[IRSold] [nvarchar](50) NULL,
	[IRSoldColor] [int] NULL,
	[IRRemarks] [nvarchar](250) NULL,
	[IRUserName] [nvarchar](50) NULL,
	[IRUpdateUser] [nvarchar](50) NULL,
	[IRUpdateTime] [datetime] NULL,
	[IrInterfaceID] [int] NULL,
	[IRTransactionID] [int] NULL,
	[IREngineCapacity] [numeric](18, 2) NULL,
	[IRSeatingCapacity] [int] NULL,
	[IRManufactureYear] [int] NULL,
	[IRImportYear] [int] NULL,
	[IRTypeofVehicle] [varchar](50) NULL,
	[IRCase] [nvarchar](250) NULL,
 CONSTRAINT [PK_losHpItemRegistrationDetails] PRIMARY KEY CLUSTERED 
(
	[IRCompanyID] ASC,
	[IRShopID] ASC,
	[IRRegistrationID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spShopItemSales]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  Table [dbo].[losHpReceiptDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losHpReceiptDetail](
	[hprdCompanyID] [int] NOT NULL,
	[hprdShopId] [int] NOT NULL,
	[hprdReceiptID] [int] NOT NULL,
	[hprdDetailId] [int] NOT NULL,
	[hprdInvoiceID] [int] NULL,
	[hprdProcessingId] [int] NULL,
	[hprdProcessingDetailId] [int] NULL,
	[hprdRentalAmount] [numeric](18, 2) NULL,
	[hprdSettelmentAmount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_losHpReceiptDetail] PRIMARY KEY CLUSTERED 
(
	[hprdCompanyID] ASC,
	[hprdShopId] ASC,
	[hprdReceiptID] ASC,
	[hprdDetailId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TmpInvoice]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TmpInvoice](
	[serinvhid] [float] NULL,
	[serinvhshopid] [float] NULL,
	[serinvhamount] [float] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[SpecialPriceSettings]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SpecialPriceSettings](
	[IsSPApplied] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losroomdetail]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losroomdetail](
	[rdcompanyid] [int] NOT NULL,
	[rdapartmentid] [int] NOT NULL,
	[rdshopid] [int] NOT NULL,
	[rdroomdetailid] [int] NOT NULL,
	[rdroomno] [varchar](50) NULL,
	[rdCapacity] [int] NULL,
	[rdremarks] [varchar](250) NULL,
 CONSTRAINT [PK_losroomdetail] PRIMARY KEY NONCLUSTERED 
(
	[rdcompanyid] ASC,
	[rdapartmentid] ASC,
	[rdshopid] ASC,
	[rdroomdetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwInquiryShopStockSummary]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  Table [dbo].[aHPCustomerMaster]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHPCustomerMaster](
	[hpCompanyID] [int] NOT NULL,
	[hpCustomerID] [int] NOT NULL,
	[hpSalutation] [varchar](50) NULL,
	[hpCustomerName] [varchar](50) NOT NULL,
	[hpAddress1] [varchar](50) NOT NULL,
	[hpAddress2] [varchar](50) NULL,
	[hpAddress3] [varchar](50) NULL,
	[hpPhoneNo] [varchar](50) NOT NULL,
	[hpEmailID] [varchar](50) NULL,
	[hpCountryID] [int] NOT NULL,
	[hpCityID] [int] NOT NULL,
	[hpCurrencyID] [int] NOT NULL,
 CONSTRAINT [PK_aHPCustomerMaster] PRIMARY KEY CLUSTERED 
(
	[hpCompanyID] ASC,
	[hpCustomerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spopeningCustomerbalancewithAge]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  Table [dbo].[losSerStandByIssueHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSerStandByIssueHeader](
	[ishCompanyID] [int] NOT NULL,
	[ishIssueID] [int] NOT NULL,
	[ishShopID] [int] NOT NULL,
	[ishRequestID] [int] NOT NULL,
	[ishIssueNo] [varchar](50) NOT NULL,
	[ishDate] [datetime] NOT NULL,
	[ishIssuedByID] [int] NOT NULL,
	[ishInstallDate] [datetime] NOT NULL,
	[ishTechnicianID] [int] NOT NULL,
	[ishConfirmed] [char](10) NOT NULL,
	[ishUpdateTime] [datetime] NULL,
	[ishCancelled] [bit] NOT NULL,
	[ishCancelledRemarks] [varchar](250) NULL,
	[ishRemarks] [varchar](250) NOT NULL,
	[ishFuture] [varchar](250) NULL,
	[ishType] [char](1) NOT NULL,
 CONSTRAINT [PK_losSerStandByIssueHeader] PRIMARY KEY NONCLUSTERED 
(
	[ishCompanyID] ASC,
	[ishIssueID] ASC,
	[ishShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aCompanyImageMaster]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aCompanyImageMaster](
	[CompanyID] [int] NOT NULL,
	[CompImage] [image] NULL,
	[type] [varchar](5) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spSetupLastYearData]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[TempDishCost]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TempDishCost](
	[DishID] [numeric](18, 0) NULL,
	[DishCostAmt] [decimal](18, 2) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ol3]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ol3](
	[code_no] [nvarchar](255) NULL,
	[on_hand] [float] NULL,
	[code_part] [nvarchar](255) NULL,
	[brand] [nvarchar](255) NULL,
	[size] [nvarchar](255) NULL,
	[cost] [float] NULL,
	[selling] [float] NULL,
	[cnt_dte] [nvarchar](255) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aUserGroupCusGroupDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aUserGroupCusGroupDetails](
	[CompanyID] [int] NOT NULL,
	[UserGroupID] [int] NOT NULL,
	[CusGroupID] [int] NOT NULL,
	[Rowguid] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_aUserGroupCusGroupDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[UserGroupID] ASC,
	[CusGroupID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aInterface]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aInterface](
	[InterfaceID] [int] NOT NULL,
	[InterfaceName] [varchar](50) NULL,
	[ModuleCode] [varchar](25) NULL,
	[PrefixNeeded] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[menuname] [varchar](50) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[customize] [varchar](5) NULL,
 CONSTRAINT [PK_aInterface] PRIMARY KEY NONCLUSTERED 
(
	[InterfaceID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1413580074] ON [dbo].[aInterface] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losUserAuditDetail]    Script Date: 04/16/2012 10:32:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losUserAuditDetail](
	[sdCompanyId] [int] NULL,
	[sdAuditId] [int] NULL,
	[sdShopId] [int] NULL,
	[sdDetailId] [int] NULL,
	[sdAuditControlName] [varchar](250) NULL,
	[sdAuditControlType] [varchar](50) NULL,
	[sdOldValue] [varchar](4000) NULL,
	[sdNewValue] [varchar](4000) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOsExportOC]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsExportOC](
	[ioShopID] [int] NULL,
	[ioInvoiceID] [int] NULL,
	[ioAccID] [int] NULL,
	[ioDescription] [varchar](100) NULL,
	[ioAmount] [numeric](18, 2) NULL,
	[ioCompanyid] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LoiMergeDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LoiMergeDetails](
	[lgdID] [int] NOT NULL,
	[lgdCompanyID] [int] NOT NULL,
	[lgdGodownID] [int] NOT NULL,
	[lgdItemID] [int] NULL,
	[lgsdQty] [numeric](18, 3) NULL,
	[lgdDetailID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[AdvanceReceiptsNotSettled]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[SpGroupLevelOrdering]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
--SpGroupLevelOrdering 1,1    
--Created By   : dheena , Hariharan, Hariharan     
--Created Date : 24/05/2004, 27/05/2004, 31/05/2004    
--Purpose      : Groupwise display, corrected depid wise filteration    
-- modified : venkitesh 28/05/2004    
--Purpose      : Added accountid , Given condition for removing unnecessary groups    
-----------------------------------------------------------------------------------  
Ref No   : 01  
Altered By  : Shine Das  
Referer Task No : M_022 from 'Magnolia Issue Tracking System' ExcelSheet  
Purpose   : In this SP there was a conditions written to filter active accounts only.  
But in BalanceSheet it is not required. So it commented.  
-----------------------------------------------------------------------------------  
*/  
CREATE Procedure [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
GO
/****** Object:  Table [dbo].[aparentCategoryMergingDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aparentCategoryMergingDetails](
	[CompanyID] [int] NOT NULL,
	[MergeID] [int] NOT NULL,
	[MergeDate] [datetime] NOT NULL,
	[OldParentCategoryID] [int] NOT NULL,
	[NewParentCategoryID] [int] NOT NULL,
	[Cancelled] [int] NULL,
	[CancelledRemarks] [nvarchar](250) NULL,
	[Remarks] [nvarchar](50) NULL,
	[UserName] [nvarchar](50) NOT NULL,
	[UpdateUserName] [nvarchar](50) NULL,
	[UpdateDateTime] [datetime] NULL,
	[Rowguid] [uniqueidentifier] NULL,
 CONSTRAINT [PK_aparentCategoryMergingDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[MergeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[MOsShopStockBackup]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MOsShopStockBackup](
	[ShopID] [int] NOT NULL,
	[StockDate] [datetime] NOT NULL,
	[ShipmentID] [int] NOT NULL,
	[ItemID] [int] NOT NULL,
	[OpeningStock] [numeric](18, 3) NULL,
	[Stock] [numeric](18, 3) NULL,
	[OpeningBadStock] [numeric](18, 3) NULL,
	[BadStock] [numeric](18, 3) NULL,
	[ItemCostPrice] [numeric](18, 3) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_MOsShopStockBackup] PRIMARY KEY NONCLUSTERED 
(
	[ShopID] ASC,
	[StockDate] ASC,
	[ShipmentID] ASC,
	[ItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_949578421] ON [dbo].[MOsShopStockBackup] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spContainedRecords]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  Table [dbo].[aAutoGenerateBillRiminder]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[aAutoGenerateBillRiminder](
	[VendorID] [int] NULL,
	[BillID] [int] NULL,
	[BillDate] [datetime] NULL,
	[DepartmentID] [int] NULL,
	[Generated] [bit] NULL,
	[RemainderID] [int] NULL,
	[amount] [numeric](18, 2) NULL,
	[BillsNo] [varchar](50) NULL,
	[RecurrenceDate] [datetime] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TillClosingstock]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TillClosingstock](
	[companyid] [int] NULL,
	[tillHistId] [int] NULL,
	[tillid] [int] NULL,
	[tillNo] [int] NULL,
	[shopid] [int] NULL,
	[itemid] [int] NULL,
	[availablestock] [numeric](17, 3) NULL,
	[physicalstock] [numeric](17, 3) NULL,
	[packingTypeId] [int] NULL,
	[allReceivedStock] [numeric](18, 0) NULL,
	[allUsedStock] [numeric](18, 0) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aUnit]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aUnit](
	[UnitID] [int] NOT NULL,
	[UnitCode] [varchar](50) NOT NULL,
	[UnitName] [varchar](250) NOT NULL,
	[Counts] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [aPK_Unit] PRIMARY KEY NONCLUSTERED 
(
	[UnitID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_373576369] ON [dbo].[aUnit] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[CostPriceUpdations]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CostPriceUpdations](
	[pkCol1Value] [int] NOT NULL,
	[pkCol2Value] [int] NOT NULL,
	[pkCol3Value] [int] NULL,
	[DetailTableName] [varchar](250) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aVendorItem]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aVendorItem](
	[itemid] [int] NOT NULL,
	[vendorid] [int] NOT NULL,
	[vendoritemcode] [varchar](50) NULL,
	[vendoritemdesc] [varchar](50) NULL,
 CONSTRAINT [PK_avendoritem] PRIMARY KEY CLUSTERED 
(
	[itemid] ASC,
	[vendorid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[GovernLoan]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[GovernLoan](
	[Trloanid] [numeric](18, 0) NOT NULL,
	[companyid] [int] NOT NULL,
	[departmentid] [int] NOT NULL,
	[TrNo] [varchar](50) NULL,
	[Trdate] [datetime] NULL,
	[LoanName] [varchar](250) NULL,
	[customerid] [numeric](18, 0) NULL,
	[vendorid] [numeric](18, 0) NULL,
	[Bankid] [numeric](18, 0) NULL,
	[RangeFrom] [datetime] NULL,
	[RangeTo] [datetime] NULL,
	[PeriodicCharge] [numeric](18, 0) NULL,
	[LoanAmount] [numeric](18, 0) NULL,
	[AlertDays] [int] NULL,
	[NextPaymentDate] [datetime] NULL,
	[TrRemarks] [varchar](250) NULL,
	[TrCancelled] [bit] NULL,
	[TrCancelledRemarks] [varchar](250) NULL,
	[trcusvendesc] [varchar](250) NULL,
	[subdepartmentid] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[sp_help_column]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  Table [dbo].[LosReservationHeader]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosReservationHeader](
	[rhcompanyid] [int] NOT NULL,
	[rhshopid] [int] NOT NULL,
	[rhreservationid] [int] NOT NULL,
	[rhreservationno] [varchar](50) NULL,
	[rhreservationdate] [datetime] NULL,
	[rhcustomerid] [int] NULL,
	[rhcustomerfirstname] [varchar](100) NULL,
	[rhcustomerlastname] [varchar](100) NULL,
	[rhcustomeraddress1] [varchar](250) NULL,
	[rhcustomeraddress2] [varchar](250) NULL,
	[rhcityid] [int] NULL,
	[rhcountryid] [int] NULL,
	[rhpassportno] [varchar](50) NULL,
	[rhworkpermitvisano] [varchar](50) NULL,
	[rhvisaexpirydate] [datetime] NULL,
	[rharrivaldate] [datetime] NULL,
	[rhdeparturedate] [datetime] NULL,
	[rhreservationstatus] [char](1) NULL,
	[rhrhreservationconfirmbit] [bit] NULL,
	[rhreservationconfirmdate] [datetime] NULL,
	[rhcancellationcheck] [bit] NULL,
	[rhcancellationdate] [datetime] NULL,
	[rhApartmentTypeID] [int] NULL,
	[rhNoOFBeds] [int] NULL,
	[rhBookingType] [varchar](50) NULL,
	[rhCallAttendedBy] [int] NOT NULL,
	[rhExpRent] [numeric](18, 2) NULL,
	[rhStayType] [varchar](50) NULL,
	[rhRemarks] [varchar](250) NULL,
	[rhCancelledRemarks] [varchar](250) NULL,
	[rhPPExpiryDate] [datetime] NULL,
 CONSTRAINT [pk_LosReservationHeader] PRIMARY KEY CLUSTERED 
(
	[rhcompanyid] ASC,
	[rhshopid] ASC,
	[rhreservationid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateShopStock]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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*/
*/
GO
/****** Object:  StoredProcedure [dbo].[spMag_IsBillFullyDelivered]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================================================
-- 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
GO
/****** Object:  Table [dbo].[losPosHeaderLastBillNo]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losPosHeaderLastBillNo](
	[ShopId] [int] NULL,
	[LastBillNo] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[sppandcinquiryTotalstock]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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
GO
/****** Object:  Table [dbo].[Fb_kotheader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Fb_kotheader](
	[Fb_kh_Companyid] [int] NOT NULL,
	[Fb_kh_outletid] [int] NOT NULL,
	[Fb_kh_kotid] [int] NOT NULL,
	[Fb_kh_kotno] [varchar](50) NULL,
	[Fb_kh_kotdatetime] [datetime] NULL,
	[Fb_kh_expecteddatetime] [datetime] NULL,
	[Fb_kh_registrationid] [int] NULL,
	[Fb_kh_Employeeid] [int] NULL,
	[Fb_kh_Tableid] [int] NULL,
	[Fb_kh_ordertakenid] [int] NULL,
	[Fb_kh_Remarks] [varchar](250) NULL,
	[Fb_kh_noofperson] [int] NULL,
	[Fb_kh_cancelled] [bit] NOT NULL,
	[Fb_Kh_Cancelledremarks] [varchar](250) NULL,
	[fb_kh_mealplanid] [int] NULL,
	[Fb_kh_Complimentaryid] [int] NULL,
	[fb_kh_userid] [int] NULL,
	[fb_kh_currencyid] [int] NOT NULL,
	[fb_exchangerates] [varchar](250) NOT NULL,
	[fb_depexrate] [numeric](18, 8) NOT NULL,
	[fb_ExchangeRate] [numeric](28, 8) NOT NULL,
 CONSTRAINT [PK_Fb_kotheader] PRIMARY KEY NONCLUSTERED 
(
	[Fb_kh_Companyid] ASC,
	[Fb_kh_outletid] ASC,
	[Fb_kh_kotid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aUserGroupreportrights]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aUserGroupreportrights](
	[userGroupid] [int] NOT NULL,
	[reportid] [int] NOT NULL,
	[modulecode] [varchar](20) NULL,
	[Companyid] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CrmQuotationDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmQuotationDetails](
	[Quotationid] [int] NOT NULL,
	[SlOrder] [int] NOT NULL,
	[ItemId] [int] NOT NULL,
	[ItemDescription] [varchar](250) NOT NULL,
	[Qty] [numeric](18, 2) NOT NULL,
	[Price] [numeric](18, 2) NOT NULL,
	[PackingtypeId] [int] NULL,
	[IsCrmItem] [bit] NULL,
	[MappedItemID] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TempItemSaleBal]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TempItemSaleBal](
	[ItemId] [int] NULL,
	[BAlQty] [numeric](18, 0) NULL
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spLedgerPreviewAfterPosting]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  Table [dbo].[losShopTransactionsSummary]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losShopTransactionsSummary](
	[SummaryDate] [datetime] NOT NULL,
	[ShopId] [int] NOT NULL,
	[ItemId] [int] NOT NULL,
	[Stock] [numeric](18, 3) NULL,
	[BadStock] [numeric](18, 3) NULL,
	[OpeningStock] [numeric](18, 3) NULL,
	[OpeningBadStock] [numeric](18, 3) NULL,
	[ShipmentId] [int] NULL,
	[ItemCostPrice] [numeric](18, 2) NULL,
 CONSTRAINT [PK_ShopStockSummary] PRIMARY KEY CLUSTERED 
(
	[ShopId] ASC,
	[ItemId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[FB_Dishgroup]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[FB_Dishgroup](
	[FB_dg_companyid] [int] NOT NULL,
	[FB_dg_Dishgroupid] [int] NOT NULL,
	[FB_dg_Dishgroupcode] [varchar](50) NULL,
	[FB_dg_Dishgroupname] [varchar](250) NULL,
	[fb_dg_foodbeverage] [bit] NULL,
	[FB_dg_futureint] [int] NULL,
	[FB_dg_futurevarchar] [varchar](250) NULL,
	[FB_dg_Futurebit] [bit] NOT NULL,
 CONSTRAINT [PK_FB_Dishgroup] PRIMARY KEY NONCLUSTERED 
(
	[FB_dg_companyid] ASC,
	[FB_dg_Dishgroupid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  UserDefinedFunction [dbo].[FnConvertCustomerStatementToHtml]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 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
GO
/****** Object:  Table [dbo].[w01]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[w01](
	[code_no] [nvarchar](255) NULL,
	[on_hand] [float] NULL,
	[code_part] [nvarchar](255) NULL,
	[brand] [nvarchar](255) NULL,
	[size] [nvarchar](255) NULL,
	[cost] [float] NULL,
	[selling] [float] NULL,
	[cnt_dte] [nvarchar](255) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aParentItemCategory]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aParentItemCategory](
	[PItemCategoryID] [int] NOT NULL,
	[PItemCategoryCode] [varchar](4) NOT NULL,
	[PCategoryDescription] [varchar](250) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[AgreementRegister]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[AgreementRegister](
	[agragreementid] [int] NOT NULL,
	[agrDepartmentid] [int] NOT NULL,
	[agragreementNo] [varchar](50) NULL,
	[agragreementdate] [datetime] NULL,
	[agragreementdesc] [varchar](100) NULL,
	[agragreementtype] [varchar](100) NULL,
	[agrapplicableshopid] [int] NULL,
	[agrapplicablegodownid] [int] NULL,
	[agrapplicableTo] [varchar](100) NULL,
	[agrValidFromdate] [datetime] NULL,
	[agrValidTodate] [datetime] NULL,
	[agrSigneddate] [datetime] NULL,
	[agrwithCustomerid] [int] NULL,
	[agrwithsupplierid] [int] NULL,
	[agragreementwith] [varchar](100) NULL,
	[agrAgencyHOaddress] [varchar](250) NULL,
	[agrAgencyContactNo] [varchar](50) NULL,
	[agrAgencyEmailid] [varchar](50) NULL,
	[agragencyfindepaddress] [varchar](250) NULL,
	[agrfinancecontactNo] [varchar](50) NULL,
	[agrfinanceEmailid] [varchar](50) NULL,
	[agrLawyer] [varchar](100) NULL,
	[agrPhysicalfileLOC] [varchar](50) NULL,
	[agrReferenceNo] [varchar](50) NULL,
	[agrNoofPages] [int] NULL,
	[agrPointofContact] [varchar](100) NULL,
	[agrPOCaddress] [varchar](250) NULL,
	[agrPOCcontactNo] [varchar](50) NULL,
	[agrPOCdesignation] [varchar](100) NULL,
	[agrAlertdays] [int] NULL,
	[agrcancelled] [bit] NOT NULL,
	[agrPOCemailid] [varchar](50) NULL,
	[alertnoofdays] [int] NULL,
	[alertremarks] [varchar](250) NULL,
 CONSTRAINT [PK_AgreementRegister] PRIMARY KEY NONCLUSTERED 
(
	[agragreementid] ASC,
	[agrDepartmentid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TempItemPriceList]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TempItemPriceList](
	[ItemPriceId] [int] NOT NULL,
	[ItemId] [int] NOT NULL,
	[PackingTypeId] [int] NOT NULL,
	[ShopId] [int] NULL,
	[CostPrice] [numeric](18, 2) NOT NULL,
	[SellingPrice] [numeric](18, 2) NOT NULL,
	[DiscountPrice] [numeric](18, 2) NOT NULL,
	[WholeSalePrice] [numeric](18, 2) NOT NULL,
	[UserId] [int] NULL,
	[FixDate] [datetime] NULL,
	[CompanyId] [int] NULL
) ON [PRIMARY]
GO

/****** Object:  Table [dbo].[losShopItemDiffPriceLevels]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losShopItemDiffPriceLevels](
	[IpID] [int] IDENTITY(1,1) NOT NULL,
	[ItemID] [int] NOT NULL,
	[ShopID] [int] NOT NULL,
	[CurrencyID] [int] NOT NULL,
	[PackingTypeID] [int] NOT NULL,
	[SegmentID] [int] NULL,
	[SellingPrice] [numeric](18, 2) NOT NULL,
	[PriceDescription] [varchar](50) NULL,
 CONSTRAINT [PK_losShopItemDiffPriceLevels] PRIMARY KEY CLUSTERED 
(
	[IpID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aCounterMaster]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aCounterMaster](
	[CounterId] [int] NULL,
	[CounterName] [varchar](50) NULL,
	[LoggedOn] [smallint] NULL,
	[CounterUser] [int] NULL,
	[CounterShopId] [int] NULL,
	[NextBillId] [numeric](18, 0) NULL,
	[NextBillNo] [numeric](18, 0) NULL,
	[TouchScreen] [int] NULL,
	[cid] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spStockOrderingOld]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  Table [dbo].[losTenantServiceBillHeader]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losTenantServiceBillHeader](
	[tbhBillId] [int] NOT NULL,
	[tbhShopId] [int] NOT NULL,
	[tbhCompanyId] [int] NOT NULL,
	[tbhAgreementId] [int] NULL,
	[tbhCustomerId] [int] NULL,
	[tbhBillNo] [varchar](50) NULL,
	[tbhBillDate] [datetime] NULL,
	[tbhCancelled] [bit] NULL,
	[tbhRemarks] [varchar](250) NULL,
	[tbhCancelledRemarks] [varchar](250) NULL,
	[tbhDepExRate] [numeric](18, 8) NULL,
	[tbhExRate] [numeric](18, 8) NULL,
	[tbhExchangeRates] [varchar](250) NULL,
	[tbhDepartmentID] [int] NULL,
	[tbhBankCashID] [int] NULL,
	[tbhServiceAccid] [int] NULL,
	[tbhPosted] [bit] NULL,
	[tbhAmount] [numeric](18, 2) NULL,
	[tbhDueDate] [datetime] NULL,
	[tbhReferenceNo] [varchar](50) NULL,
	[tbhUpdateTime] [datetime] NULL,
	[tbhSettledAmount] [numeric](18, 2) NULL,
	[tbhSettled] [bit] NULL,
	[tbhutilityAccid] [int] NULL,
	[tbhUserID] [int] NULL,
 CONSTRAINT [PK_losTenantServiceBillHeader] PRIMARY KEY NONCLUSTERED 
(
	[tbhBillId] ASC,
	[tbhShopId] ASC,
	[tbhCompanyId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spMag_RebuildAllIndexes]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[TillStatusMaster]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TillStatusMaster](
	[tillstatus_id] [int] NOT NULL,
	[tillstatus_name] [varchar](50) NOT NULL,
 CONSTRAINT [PK_TillStatus] PRIMARY KEY CLUSTERED 
(
	[tillstatus_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 - Ready,2 - Used,3 - Not Used' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'TillStatusMaster', @level2type=N'COLUMN',@level2name=N'tillstatus_name'
GO
/****** Object:  Table [dbo].[losHpRepossessionDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losHpRepossessionDetail](
	[hprdCompanyId] [int] NOT NULL,
	[hprdShopID] [int] NOT NULL,
	[hprdRepossessionID] [int] NOT NULL,
	[hprdDetailID] [int] NOT NULL,
	[hprdItemID] [int] NOT NULL,
	[hprdFairValue] [numeric](18, 2) NOT NULL,
	[hprdCostValue] [numeric](18, 2) NULL,
 CONSTRAINT [PK_losHpRepossessionDetail] PRIMARY KEY CLUSTERED 
(
	[hprdCompanyId] ASC,
	[hprdShopID] ASC,
	[hprdRepossessionID] ASC,
	[hprdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aAccountMasterBackup]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aAccountMasterBackup](
	[AccountID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[GroupID] [int] NOT NULL,
	[FinancialID] [int] NOT NULL,
	[OpeningCreditBalance] [numeric](18, 2) NULL,
	[OpeningDebitBalance] [numeric](18, 2) NULL,
	[BudgetAMount] [numeric](18, 2) NULL,
	[CurrencyID] [int] NULL,
 CONSTRAINT [PK_aAccountMasterBackup] PRIMARY KEY NONCLUSTERED 
(
	[AccountID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spRatioDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO

/****** Object:  Table [dbo].[losNonRestrictedItems]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losNonRestrictedItems](
	[NorItemID] [int] NOT NULL,
	[Norshopid] [int] NOT NULL,
	[nortype] [char](1) NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_losNonRestrictedItems] PRIMARY KEY CLUSTERED 
(
	[NorItemID] ASC,
	[Norshopid] ASC,
	[nortype] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_741577680] ON [dbo].[losNonRestrictedItems] 
(
	[rowguid] 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, FILLFACTOR = 100) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aChequeReportDetails]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aChequeReportDetails](
	[CompanyID] [int] NOT NULL,
	[ChequeID] [int] NOT NULL,
	[AccountID] [int] NOT NULL,
	[ReportName] [varchar](250) NOT NULL,
 CONSTRAINT [PK_aChequeReportDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[ChequeID] ASC,
	[AccountID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spSelectAllSubDepartments]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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
GO

/****** Object:  Table [dbo].[aKitItemDetail]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aKitItemDetail](
	[KitId] [int] NOT NULL,
	[ItemId] [int] NOT NULL,
	[PackingTypeId] [int] NOT NULL,
	[UnitId] [int] NOT NULL,
	[PackingTypeQty] [numeric](18, 2) NOT NULL,
	[Qty] [numeric](18, 2) NOT NULL,
	[Price] [numeric](18, 3) NOT NULL,
	[KitDetailId] [int] NOT NULL,
	[KitItemTax] [numeric](18, 2) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aUserGroupGodownDetails]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aUserGroupGodownDetails](
	[CompanyId] [int] NOT NULL,
	[UserGroupID] [int] NOT NULL,
	[GodownID] [int] NOT NULL,
	[rowguID] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_aUserGroupGodownDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyId] ASC,
	[UserGroupID] ASC,
	[GodownID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[CrmContact]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmContact](
	[ContactID] [int] NOT NULL,
	[ClientId] [int] NOT NULL,
	[CompanyId] [int] NOT NULL,
	[FirstName] [varchar](50) NOT NULL,
	[LastName] [varchar](50) NULL,
	[Sex] [varchar](50) NULL,
	[Address] [varchar](250) NULL,
	[Email] [varchar](50) NULL,
	[CityId] [int] NULL,
	[CountryId] [int] NULL,
	[DateofBirth] [datetime] NULL,
	[MartialStatus] [varchar](50) NULL,
	[Anniversary] [datetime] NULL,
	[Profession] [varchar](50) NULL,
	[PointId] [int] NULL,
	[Phone] [varchar](50) NULL,
	[OfficeNo] [varchar](50) NULL,
	[MobileNumber] [varchar](50) NULL,
	[UserId] [int] NOT NULL,
	[username] [varchar](50) NULL,
	[password] [varchar](50) NULL,
	[Deleted] [int] NOT NULL,
	[CreateDate] [datetime] NOT NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF
ALTER TABLE [dbo].[CrmContact] ADD [FaxNo] [varchar](50) NULL
ALTER TABLE [dbo].[CrmContact] ADD  CONSTRAINT [PK_CrmContact] PRIMARY KEY CLUSTERED 
(
	[ContactID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aUserGroupItemCategoryDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aUserGroupItemCategoryDetails](
	[CompanyID] [int] NOT NULL,
	[UserGroupID] [int] NOT NULL,
	[ItemCategoryID] [int] NOT NULL,
	[rowguID] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_aUserGroupItemCategoryDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[UserGroupID] ASC,
	[ItemCategoryID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwGdnBinCardBadQtySummary]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ===============================================      
-- 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
GO
/****** Object:  Table [dbo].[aHQBackground]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHQBackground](
	[ShopId] [int] NOT NULL,
	[Message] [nvarchar](1000) NULL,
	[Background] [int] NULL,
	[BackServer] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spsmsversion]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  StoredProcedure [dbo].[spPoItemListOrGDN]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO

/****** Object:  Table [dbo].[loshpApplication]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[loshpApplication](
	[hpAppCompanyID] [int] NOT NULL,
	[hpAppShopID] [int] NOT NULL,
	[hpAppID] [int] NOT NULL,
	[hpAppDate] [datetime] NULL,
	[hpAppNO] [nvarchar](50) NOT NULL
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwShopBincardBadQtySummary]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ===============================================      
-- 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
GO
/****** Object:  Table [dbo].[aGlobalUsers]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aGlobalUsers](
	[UserID] [int] NOT NULL,
	[FullName] [varchar](100) NULL,
	[LoginName] [varchar](50) NULL,
	[Password] [varchar](50) NULL,
	[phone] [varchar](50) NULL,
	[fax] [varchar](50) NULL,
	[Address] [varchar](250) NULL,
	[email] [varchar](50) NULL,
	[logedon] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aGlobalUsers] PRIMARY KEY NONCLUSTERED 
(
	[UserID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_213575799] ON [dbo].[aGlobalUsers] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[splocationwise]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  Table [dbo].[shopstockcheck]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[shopstockcheck](
	[locid] [int] NULL,
	[loctype] [char](1) NULL,
	[itemid] [int] NULL,
	[sdate] [datetime] NULL,
	[Transno] [varchar](100) NULL,
	[TransID] [int] NULL,
	[Transqty] [numeric](18, 3) NULL,
	[Type] [varchar](50) NULL,
	[mode] [int] NULL,
	[updatetime] [datetime] NULL,
	[oldstock] [numeric](18, 3) NULL,
	[newstock] [numeric](18, 3) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

/****** Object:  Table [dbo].[aItemCategory]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aItemCategory](
	[ItemCategoryID] [int] NOT NULL,
	[ItemCategoryCode] [varchar](4) NOT NULL,
	[CategoryNameDescription] [varchar](250) NOT NULL,
	[SPDefMargin] [numeric](18, 2) NULL,
	[DPDefMargin] [numeric](18, 2) NULL,
	[WPDefMargin] [numeric](18, 2) NULL,
	[DPDefQty] [numeric](18, 3) NULL,
	[WPDefQty] [numeric](18, 3) NULL,
	[SalesValue] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[PItemCategoryId] [int] NULL,
	[InHouseconsumptionAccnt] [int] NULL,
	[CategoryDetail] [varchar](100) NULL,
	[TaxCategoryId] [int] NULL,
 CONSTRAINT [PK_aItemCategory] PRIMARY KEY NONCLUSTERED 
(
	[ItemCategoryID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_245575913] ON [dbo].[aItemCategory] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO

/****** Object:  Table [dbo].[aHqMergingDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aHqMergingDetails](
	[mgdId] [int] NOT NULL,
	[mgdCompanyID] [int] NOT NULL,
	[mgdItemId] [int] NOT NULL,
	[mgdCostPrice] [numeric](18, 2) NULL,
	[mgdDetailID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aHqMergingDetails] PRIMARY KEY CLUSTERED 
(
	[mgdId] ASC,
	[mgdCompanyID] ASC,
	[mgdItemId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[mocostpreviewtemp]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[mocostpreviewtemp](
	[slno] [int] NULL,
	[Itemname] [varchar](250) NULL,
	[itemqty] [numeric](18, 3) NULL,
	[BillUp] [numeric](28, 22) NULL,
	[Itemid] [int] NULL,
	[customsup] [numeric](18, 2) NULL,
	[customsduty] [numeric](18, 2) NULL,
	[ocperitem] [numeric](28, 22) NULL,
	[custompercent] [numeric](18, 2) NULL,
	[dutyperitem] [numeric](18, 2) NULL,
	[billid] [int] NULL,
	[Billno] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

/****** Object:  Table [dbo].[LosApartmentAssets]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosApartmentAssets](
	[aacompanyid] [int] NOT NULL,
	[aashopid] [int] NOT NULL,
	[aaapartmentid] [int] NOT NULL,
	[aadetailid] [int] NOT NULL,
	[aaremarks] [varchar](250) NULL,
	[AaItemName] [varchar](100) NULL,
	[aaassetid] [int] NULL,
 CONSTRAINT [pk_LosApartmentAssets] PRIMARY KEY CLUSTERED 
(
	[aacompanyid] ASC,
	[aashopid] ASC,
	[aaapartmentid] ASC,
	[aadetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[ErrorDemo]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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
GO
/****** Object:  Table [dbo].[areportrights]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[areportrights](
	[userid] [int] NOT NULL,
	[reportid] [int] NOT NULL,
	[modulecode] [varchar](20) NULL,
	[Companyid] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aHqMergingHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHqMergingHeader](
	[mghId] [int] NOT NULL,
	[mghCompanyId] [int] NOT NULL,
	[mghNo] [varchar](50) NULL,
	[mghDate] [datetime] NULL,
	[mghItemId] [int] NULL,
	[mghAddUser] [varchar](50) NULL,
	[mghModUser] [varchar](50) NULL,
	[mghTransFinished] [bit] NULL,
	[mghCostPriceFixed] [char](1) NULL,
	[mghRemarks] [varchar](250) NULL,
	[mghCancelledRemarks] [varchar](250) NULL,
	[mghCancelled] [bit] NULL,
	[mghItemCostPrice] [numeric](18, 2) NULL,
	[mghNoOfRec] [int] NULL,
	[mghOldCostPrice] [numeric](18, 2) NULL,
	[mghQty] [numeric](18, 3) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[mghtime] [datetime] NULL,
	[MghDepartmentId] [int] NULL,
 CONSTRAINT [PK_aHqMergingHeader] PRIMARY KEY CLUSTERED 
(
	[mghId] ASC,
	[mghCompanyId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aDeptAccounts]    Script Date: 04/16/2012 10:32:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aDeptAccounts](
	[daCompanyID] [int] NULL,
	[daDepartmentID] [int] NULL,
	[daAccountID] [int] NULL,
 CONSTRAINT [UQ_aDeptAccounts] UNIQUE NONCLUSTERED 
(
	[daCompanyID] ASC,
	[daDepartmentID] ASC,
	[daAccountID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spYearSales]    Script Date: 04/16/2012 10:32:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  Table [dbo].[aHpProcessingDetailOthers]    Script Date: 04/16/2012 10:32:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHpProcessingDetailOthers](
	[hpdCompanyID] [int] NOT NULL,
	[hpdDepartmentID] [int] NOT NULL,
	[hpdProcessingId] [int] NOT NULL,
	[hpddetailIDBT] [int] NOT NULL,
	[hpdChequeDateBT] [datetime] NOT NULL,
	[hpdCapitalBT] [numeric](18, 2) NOT NULL,
	[hpdRentalBT] [numeric](18, 2) NOT NULL,
	[hpdInterestBT] [numeric](18, 2) NOT NULL,
	[hpdcapitalRepaymentBT] [numeric](18, 2) NOT NULL,
	[hpdCapitalBalanceBT] [numeric](18, 2) NOT NULL,
	[hpdBankNameBT] [nvarchar](50) NULL,
	[hpdChequeNoBT] [nvarchar](50) NULL,
	[hpdAmountBT] [numeric](18, 2) NULL,
	[hpdSettlementAmountBT] [numeric](18, 2) NULL,
	[hpdInterestRateBT] [numeric](18, 2) NULL,
	[hpdPosted] [int] NULL,
	[hpdChequeStatus] [varchar](50) NULL,
PRIMARY KEY CLUSTERED 
(
	[hpdCompanyID] ASC,
	[hpdDepartmentID] ASC,
	[hpdProcessingId] ASC,
	[hpddetailIDBT] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spCreditorAgeSumAllBills]    Script Date: 04/16/2012 10:32:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------        
-- 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
GO
/****** Object:  Table [dbo].[losUserAuditHeader]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losUserAuditHeader](
	[shCompanyId] [int] NULL,
	[shAuditId] [int] NULL,
	[shShopId] [int] NULL,
	[shInterfaceId] [int] NULL,
	[shTransId] [int] NULL,
	[shTransNo] [varchar](50) NULL,
	[shUserFullName] [varchar](250) NULL,
	[shLoggedDateTime] [datetime] NULL,
	[shExitedDateTime] [datetime] NULL,
	[shMode] [char](1) NULL,
	[shSaved] [bit] NULL,
	[shMachineName] [varchar](50) NULL,
	[shWindowsUserName] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_Update_InHouseCons_ReturDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[losSerialNoVerificationDetail]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[losSerialNoVerificationDetail](
	[svdShopID] [int] NULL,
	[svdID] [int] NOT NULL,
	[svdShipMentID] [int] NOT NULL,
	[svdItemID] [int] NULL,
	[svdAvlStock] [numeric](18, 0) NULL,
	[svdVerifiedStock] [numeric](18, 0) NULL,
	[svdCostPrice] [numeric](18, 0) NULL,
	[svdPreSerialNo] [nvarchar](50) NULL,
	[svdNewSerialNo] [nvarchar](50) NULL,
	[svdDeleted] [varchar](5) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LosVrRegistartionReceiveDetail]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LosVrRegistartionReceiveDetail](
	[RegistartionReceiveId] [int] NOT NULL,
	[RegistartionReceiveDtlId] [int] NOT NULL,
	[RegistartionSubConfId] [int] NOT NULL,
	[InvoiceId] [int] NULL,
	[PosId] [int] NULL,
	[SpInvoice] [int] NULL,
	[RegistrationID] [int] NOT NULL,
	[RegistryNoShort] [nvarchar](150) NOT NULL,
	[RegistryNoLong] [nvarchar](150) NOT NULL,
	[RegistrationDate] [datetime] NOT NULL,
	[Companyid] [int] NOT NULL,
 CONSTRAINT [PK_LosVrRegistartionReceiveDetail] PRIMARY KEY CLUSTERED 
(
	[RegistartionReceiveId] ASC,
	[RegistartionReceiveDtlId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aVesselMaster]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aVesselMaster](
	[CompanyId] [int] NOT NULL,
	[VesselID] [int] NOT NULL,
	[VesselCode] [varchar](50) NOT NULL,
	[VesselDes] [varchar](100) NOT NULL,
	[CountryID] [int] NOT NULL,
	[VesselOperatorName] [varchar](100) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spQuickItemInquiryWithFilterCondition]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[HQSalesPromotionHeader]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[HQSalesPromotionHeader](
	[sphCompanyID] [int] NOT NULL,
	[sphPromotionID] [int] NOT NULL,
	[sphPromotionNo] [varchar](250) NULL,
	[sphPromotionDate] [datetime] NULL,
	[sphFromDate] [datetime] NULL,
	[sphToDate] [datetime] NULL,
	[sphApprovedBy] [varchar](100) NULL,
	[sphDepartmentID] [int] NULL,
	[sphTotSalesAmt] [numeric](18, 2) NULL,
	[sphTotprofitAmt] [numeric](18, 2) NULL,
	[sphRemarks] [varchar](250) NULL,
	[sphCancelled] [bit] NULL,
	[sphCancelledRemarks] [varchar](250) NULL,
 CONSTRAINT [pk_HQSalesPromotionHeader] PRIMARY KEY CLUSTERED 
(
	[sphCompanyID] ASC,
	[sphPromotionID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[w07]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[w07](
	[code_no] [nvarchar](255) NULL,
	[on_hand] [float] NULL,
	[code_part] [nvarchar](255) NULL,
	[brand] [nvarchar](255) NULL,
	[size] [nvarchar](255) NULL,
	[cost] [float] NULL,
	[selling] [float] NULL,
	[cnt_dte] [nvarchar](255) NULL
) ON [PRIMARY]
GO

/****** Object:  Table [dbo].[aSize]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aSize](
	[SizeID] [int] NOT NULL,
	[SizeCode] [varchar](50) NOT NULL,
	[SizeName] [varchar](250) NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aSize] PRIMARY KEY NONCLUSTERED 
(
	[SizeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_341576255] ON [dbo].[aSize] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[BudgetPlanHeader]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[BudgetPlanHeader](
	[bphCompanyID] [int] NOT NULL,
	[bphBudgetPlanID] [int] NOT NULL,
	[bphBudgetNo] [varchar](50) NULL,
	[bphBudgetDate] [datetime] NULL,
	[bphBudgetPanel] [varchar](250) NULL,
	[bphReviewPanel] [varchar](250) NULL,
	[bphReviewDate] [datetime] NULL,
	[bphSanctionedBy] [varchar](100) NULL,
	[bphSanctionedDate] [datetime] NULL,
	[bphRemarks] [varchar](250) NULL,
	[bphCancelled] [bit] NULL,
	[bphCancelledRemarks] [varchar](250) NULL,
	[bphDepartmentId] [int] NULL,
	[bphBudgetName] [varchar](100) NULL,
	[bphConfirmed] [bit] NULL,
	[bphPlanYear] [varchar](4) NULL,
	[bphtype] [varchar](4) NULL,
 CONSTRAINT [PK_BudgetPlanHeader] PRIMARY KEY CLUSTERED 
(
	[bphCompanyID] ASC,
	[bphBudgetPlanID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSumDetailed]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--***************************************************************************************************          
-- Created by  :  Nidheesh P V          
-- Created on  : 06/07/2011            
-- Purpose     : To Get Debtor Age For  0 - 15,16 - 30 ,31 - 60, 61 - 120,121 - 240,241 - 365     
--and to display the customer even if the customer has no invoice/settlement but an advance is there.     
--Used in the reprot Debtor Age Analysis with Advance     
--Ref No : Ref-No1  
--***************************************************************************************************  
--- Modified by : Jyothish SR     
-- Modified on : 27/03/2012     
-- Purpose     : Avoid Select * statement in vwinvoices and  vwsettlements
  
--spDebtorAgeSumDetailed '20101231','20111231','9723',0,0,0,'',''    
      
             
create  PROCEDURE [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
GO
/****** Object:  Table [dbo].[aUserAuditHeader]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aUserAuditHeader](
	[hCompanyId] [int] NOT NULL,
	[hAuditId] [int] NOT NULL,
	[hTransId] [int] NULL,
	[hTransNo] [varchar](8000) NULL,
	[hUserFullName] [varchar](250) NOT NULL,
	[hLoggedDateTime] [datetime] NOT NULL,
	[hExitedDateTime] [datetime] NOT NULL,
	[hInterfaceId] [int] NULL,
	[hMode] [char](1) NOT NULL,
	[hSaved] [bit] NOT NULL,
	[hDepartmentId] [int] NULL,
	[hMachineName] [varchar](50) NULL,
	[hWindowsUserName] [varchar](50) NULL,
 CONSTRAINT [PK_aUserAuditHeader] PRIMARY KEY NONCLUSTERED 
(
	[hCompanyId] ASC,
	[hAuditId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losExpiryVerificationHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losExpiryVerificationHeader](
	[evhId] [int] NOT NULL,
	[evhShopId] [int] NOT NULL,
	[evhNo] [varchar](50) NOT NULL,
	[evhDate] [datetime] NOT NULL,
	[evhRemarks] [varchar](250) NULL,
	[evhCancelled] [bit] NULL,
	[evhVerifiedBy] [varchar](100) NULL,
	[evhCancelRemarks] [varchar](50) NULL,
	[evhFutureVc] [varchar](250) NULL,
	[evhPosted] [bit] NULL,
	[UpdateTime] [datetime] NULL,
	[evhDepartmentId] [int] NULL,
	[evhConExRate] [numeric](18, 0) NULL,
	[evhDepExRate] [numeric](18, 0) NULL,
	[evhExchangeRates] [varchar](250) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TargetCheckDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TargetCheckDetail](
	[tcdCompanyID] [int] NOT NULL,
	[tcdCheckID] [int] NOT NULL,
	[tcdDetailId] [int] NOT NULL,
	[tcdFixationID] [int] NULL,
	[tcdFixationDetailID] [int] NULL,
	[tcdActualAmount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_TargetCheckDetail] PRIMARY KEY NONCLUSTERED 
(
	[tcdCompanyID] ASC,
	[tcdCheckID] ASC,
	[tcdDetailId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spHPCustomerAdvanceAsOnDate]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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
GO
/****** Object:  UserDefinedFunction [dbo].[fnMultipleSplit]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[loiLocationVerificationDetail]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[loiLocationVerificationDetail](
	[lvdId] [int] NOT NULL,
	[lvdShipmentId] [int] NOT NULL,
	[lvdItemId] [int] NOT NULL,
	[lvdGodownId] [int] NOT NULL,
	[lvdAvailStock] [numeric](18, 3) NULL,
	[lvdVerifiedStock] [numeric](18, 3) NULL,
	[lvdCostPrice] [numeric](18, 3) NULL,
	[lvdPrevLocationId] [int] NULL,
	[lvdVerifiedLocationId] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[MiscSettings]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MiscSettings](
	[ItemCodeAutoGen] [bit] NOT NULL,
	[SupplierCodeAutoGen] [bit] NOT NULL,
	[CustomerCodeAutoGen] [bit] NOT NULL,
	[showavailableqtyinTrOut] [bit] NULL,
	[showavailableqtyinGReq] [bit] NULL,
	[backdateprocess] [bit] NULL,
	[lastdatatransfercheckdate] [datetime] NULL,
	[showlocationswitch] [bit] NOT NULL,
	[freezbalanceday] [int] NULL,
	[Docomparebcandstock] [bit] NULL,
	[setcom] [varchar](25) NULL,
	[AllowItemCodeDuplication] [bit] NOT NULL,
	[allowlocalpurchhq] [bit] NULL,
	[fixsellingpriceaftercosting] [bit] NULL,
	[allowoldporefinpurchasebill] [bit] NULL,
	[customertoshoponcreation] [bit] NULL,
	[openingbalancenottallying] [bit] NOT NULL,
	[moduleextended] [char](10) NULL,
	[defaultfetch] [varchar](100) NULL,
	[ReportSorting] [bit] NULL,
	[AccountsFreezeDate] [datetime] NULL,
	[Lctoaccount] [bit] NULL,
	[AllowZeroLcMargin] [bit] NULL,
	[CustomisedFor] [varchar](10) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spCreditorAgeSum]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  Table [dbo].[losJobType]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losJobType](
	[TypeId] [int] NOT NULL,
	[TypeName] [varchar](20) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[SP_SelectedBillDetails]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ======================================================================================                     
-- 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
GO
/****** Object:  Table [dbo].[PIS_EmailSettings]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[PIS_EmailSettings](
	[SMTP] [varchar](50) NOT NULL,
	[Password] [varchar](50) NOT NULL,
	[Port] [nchar](10) NOT NULL,
	[Fromaddress] [varchar](50) NOT NULL,
	[OdbcName] [varchar](50) NULL,
	[OdbcUser] [varchar](50) NULL,
	[OdbcPassword] [varchar](50) NULL,
	[DatabaseName] [varchar](50) NULL,
	[CompanyId] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loiLocationVerificationHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loiLocationVerificationHeader](
	[lvhId] [int] NOT NULL,
	[lvhGodownId] [int] NOT NULL,
	[lvhNo] [varchar](50) NULL,
	[lvhDate] [datetime] NULL,
	[lvhRemarks] [varchar](250) NULL,
	[lvhVerifiedBy] [varchar](100) NULL,
	[lvhCancelled] [bit] NOT NULL,
	[lvhCancelRemarks] [varchar](100) NULL,
	[lvhFutureVc] [varchar](250) NULL,
	[lvhPosted] [bit] NOT NULL,
	[UpdateTime] [datetime] NULL,
	[lvhDepartmentId] [int] NULL,
	[lvhConExRate] [numeric](18, 8) NULL,
	[lvhDepExRate] [numeric](18, 8) NULL,
	[lvhExchangeRates] [varchar](250) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[PurchaseBillHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[PurchaseBillHeader](
	[pbhBillID] [int] NULL,
	[pbhBillNo] [varchar](50) NULL,
	[pbhVendorBillNo] [varchar](50) NULL,
	[pbhBillDate] [datetime] NULL,
	[pbhVendorID] [int] NULL,
	[pbhPOID] [int] NULL,
	[pbhBillAmount] [numeric](18, 8) NULL,
	[pbhDiscount] [numeric](18, 2) NULL,
	[pbhDiscountAccID] [int] NULL,
	[pbhAdjustmentAmount] [numeric](18, 2) NULL,
	[pbhDueDateforPayment] [datetime] NULL,
	[pbhBankCashAccID] [int] NULL,
	[pbhChequeNo] [varchar](50) NULL,
	[pbhFinancialID] [int] NULL,
	[pbhDepartmentID] [int] NULL,
	[pbhRemarks] [varchar](50) NULL,
	[pbhTobeDespatched] [bit] NULL,
	[pbhDespatched] [bit] NULL,
	[pbhCashPurchase] [bit] NULL,
	[pbhExchangeNature] [varchar](50) NULL,
	[pbhCancelled] [bit] NULL,
	[pbhCancelledRemarks] [varchar](50) NULL,
	[pbhPosted] [bit] NULL,
	[pbhRecAddUser] [varchar](50) NULL,
	[pbhRecModifyUser] [varchar](50) NULL,
	[pbhCompanyID] [int] NULL,
	[pbhUsed] [bit] NULL,
	[pbhvendorRefNo] [varchar](50) NULL,
	[pbhdummyICost] [numeric](18, 2) NULL,
	[pbhdummyFCharge] [numeric](18, 2) NULL,
	[pbhdummyOCharge] [numeric](18, 2) NULL,
	[pbhCustomExchangeRate] [numeric](18, 8) NULL,
	[pbhPurchaseAccID] [int] NULL,
	[pbhSettled] [bit] NULL,
	[pbhexchangerate] [numeric](18, 8) NULL,
	[updatetime] [datetime] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losHPResaleDetail]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losHPResaleDetail](
	[hpdCompanyID] [int] NOT NULL,
	[hpdShopID] [int] NOT NULL,
	[hpdResaleID] [int] NOT NULL,
	[hpdResaleDetailID] [int] NULL,
	[hpdItemID] [int] NOT NULL,
	[hpdRepossessionID] [int] NOT NULL,
	[hpdFairValue] [numeric](18, 2) NULL,
	[hpdSellingPrice] [numeric](18, 0) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[loiSerialNoVerificationHeader]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[loiSerialNoVerificationHeader](
	[svhCompanyID] [int] NOT NULL,
	[svhGodownID] [int] NOT NULL,
	[svhID] [int] NOT NULL,
	[svhNo] [nvarchar](50) NOT NULL,
	[svhDate] [datetime] NOT NULL,
	[svhVerifiedBy] [char](10) NULL,
	[svhRemarks] [nvarchar](150) NULL,
	[svhCancel] [int] NOT NULL,
	[svhCancellRemarks] [nvarchar](150) NULL,
	[svhFutureVC] [char](10) NULL,
	[svhUser] [varchar](50) NULL,
	[svhUpdateUser] [char](10) NULL,
	[svhUpdateTime] [datetime] NULL,
 CONSTRAINT [PK_loiSerialNoVerificationHeader] PRIMARY KEY CLUSTERED 
(
	[svhCompanyID] ASC,
	[svhGodownID] ASC,
	[svhID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TempItem]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TempItem](
	[Itemid] [int] NULL,
	[VendorId] [int] NULL,
	[VendorName] [varchar](250) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spLCRegister]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

--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
GO
/****** Object:  Table [dbo].[LMSReward]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LMSReward](
	[CompanyID] [int] NULL,
	[RewardId] [int] NULL,
	[CardId] [int] NULL,
	[Dr] [int] NULL,
	[Type] [varchar](50) NULL,
	[Points] [int] NULL,
	[PointDate] [datetime] NULL,
	[Description] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ahpAgreementDetail]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ahpAgreementDetail](
	[hpCompanyID] [int] NOT NULL,
	[hpDepartmentID] [int] NOT NULL,
	[hpFinancialID] [int] NOT NULL,
	[hpAgreementID] [int] NOT NULL,
	[hpAgreementNO] [nvarchar](50) NOT NULL,
	[hpAgreementDate] [datetime] NULL,
	[hpDeliveryDate] [datetime] NULL,
	[hpItemRegID] [int] NOT NULL,
	[hpQuotationID] [int] NULL,
	[hpCustID] [int] NULL,
	[HPofficialName] [nvarchar](50) NULL,
	[HpDeOfficialName] [nvarchar](50) NULL,
	[HpDesignation] [nvarchar](50) NULL,
	[HpDeDesignation] [nvarchar](50) NULL,
	[hpWitnessName] [nvarchar](50) NULL,
	[hpDeWitnessName] [nvarchar](50) NULL,
	[hpWitnessAddress] [nvarchar](250) NULL,
	[hpDeWitnessAddress] [nvarchar](50) NULL,
	[hpWitnessNIC] [nvarchar](50) NULL,
	[hpWitnessName2] [nvarchar](50) NULL,
	[hpDeWitnessName2] [nvarchar](50) NULL,
	[hpWitnessAddress2] [nvarchar](50) NULL,
	[hpDeWitnessAddress2] [nvarchar](50) NULL,
	[hpWitnessNIC2] [nvarchar](50) NULL,
	[hpDevVehicleDescription] [nvarchar](50) NULL,
	[hpDevSoldColor] [nvarchar](50) NULL,
	[hpCancelRemarks] [nvarchar](250) NULL,
	[hpDevInstAmount] [nvarchar](250) NULL,
	[hpDevDownPayment] [nvarchar](250) NULL,
	[hpDevBalAmt] [nvarchar](250) NULL,
	[hpDevMonthlyPay] [nvarchar](250) NULL,
	[hpCancel] [int] NOT NULL,
	[hpConfirmed] [int] NOT NULL,
	[hpRemarks] [nvarchar](150) NULL,
	[hpUser] [nvarchar](50) NOT NULL,
	[hpModifiedUser] [nvarchar](50) NULL,
	[hpModifiedDate] [datetime] NULL,
 CONSTRAINT [PK_loshpAgreementDetail] PRIMARY KEY CLUSTERED 
(
	[hpAgreementID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOSApartmentDetail]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOSApartmentDetail](
	[apdcompanyid] [int] NOT NULL,
	[apdApartmentid] [int] NOT NULL,
	[apdShopid] [int] NOT NULL,
	[apdApartmentcategoryid] [int] NOT NULL,
	[apdApartmentno] [varchar](50) NULL,
	[apdremarks] [varchar](250) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliationAsOn25052011]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  Table [dbo].[mealname]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[mealname](
	[companyid] [int] NOT NULL,
	[mealnameid] [int] NOT NULL,
	[mealnamecode] [varchar](50) NULL,
	[mealname] [varchar](250) NULL,
 CONSTRAINT [PK_mealname_1] PRIMARY KEY NONCLUSTERED 
(
	[companyid] ASC,
	[mealnameid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[tmpBills]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tmpBills](
	[CompanyID] [int] NULL,
	[shopid] [int] NULL,
	[DepartmentID] [int] NULL,
	[billsid] [int] NULL,
	[pbhVendorID] [int] NULL,
	[Billsno] [varchar](50) NULL,
	[pbhremarks] [varchar](1000) NULL,
	[Referenceno] [varchar](100) NULL,
	[pbhBilldate] [datetime] NULL,
	[duedate] [datetime] NULL,
	[pbhBillAmount] [numeric](18, 2) NULL,
	[Due] [varchar](7) NULL,
	[Type] [varchar](4) NULL,
	[updatetime] [datetime] NULL,
	[age] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aLoyaltyCardMaster]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aLoyaltyCardMaster](
	[CompanyID] [int] NOT NULL,
	[CardID] [int] NOT NULL,
	[CardDesc] [varchar](50) NOT NULL,
	[Amount] [numeric](18, 2) NOT NULL,
	[Points] [int] NOT NULL,
	[PointsValue] [int] NOT NULL,
	[UserName] [varchar](50) NOT NULL,
	[MinimumPoints] [int] NOT NULL,
 CONSTRAINT [PK_aLoyaltyCardMaster] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[CardID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ASegmentMaster]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ASegmentMaster](
	[companyid] [int] NOT NULL,
	[Segmentid] [int] NOT NULL,
	[SegmentName] [varchar](100) NULL,
	[Createddate] [datetime] NULL,
	[Remarks] [varchar](250) NULL,
	[Percentage] [numeric](18, 2) NULL,
 CONSTRAINT [pk_ASegmentMaster] PRIMARY KEY CLUSTERED 
(
	[companyid] ASC,
	[Segmentid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[BudgetAccountsLink]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BudgetAccountsLink](
	[bacCompanyID] [int] NOT NULL,
	[bacBudgetID] [int] NOT NULL,
	[bacDetailID] [int] NOT NULL,
	[bacAccountID] [int] NULL,
	[bacDepartmentID] [int] NULL,
 CONSTRAINT [PK_BudgetAccountsLink] PRIMARY KEY NONCLUSTERED 
(
	[bacCompanyID] ASC,
	[bacBudgetID] ASC,
	[bacDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[spDailySalesCollectionUserWise]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
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','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
GO
/****** Object:  Table [dbo].[EmailRecipients]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[EmailRecipients](
	[MailType] [varchar](50) NULL,
	[Recipients] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aUsers]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aUsers](
	[UserID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[UserName] [varchar](250) NULL,
	[UserPwd] [varchar](50) NULL,
	[FullName] [varchar](250) NULL,
	[ShopID] [int] NULL,
	[GodownID] [int] NULL,
	[logedon] [bit] NULL,
	[GlobalUserID] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[UserGroupID] [int] NULL,
	[EmailID] [varchar](50) NULL,
 CONSTRAINT [PK_aUsers] PRIMARY KEY NONCLUSTERED 
(
	[UserID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1829581556] ON [dbo].[aUsers] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[fb_Alternate]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[fb_Alternate](
	[fb_kotID] [int] NOT NULL,
	[fb_dishID] [int] NOT NULL,
	[fb_ItemID] [int] NOT NULL,
	[fb_row] [char](10) NOT NULL,
	[KotOrder] [decimal](18, 3) NOT NULL,
	[Fb_outletid] [int] NOT NULL,
	[fb_costprice] [numeric](18, 2) NULL,
 CONSTRAINT [PK_fb_Alternate] PRIMARY KEY CLUSTERED 
(
	[Fb_outletid] ASC,
	[fb_kotID] ASC,
	[fb_dishID] ASC,
	[fb_ItemID] ASC,
	[fb_row] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Crmreports]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Crmreports](
	[reportid] [int] NOT NULL,
	[reportname] [varchar](50) NULL,
	[groupid] [int] NULL,
	[modulecode] [char](10) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Fb_botdetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Fb_botdetails](
	[Fb_bd_Companyid] [int] NOT NULL,
	[fb_bd_Outletid] [int] NOT NULL,
	[Fb_bd_botid] [int] NOT NULL,
	[Fb_bd_Botdetailid] [int] NOT NULL,
	[fb_bd_dishid] [int] NOT NULL,
	[Fb_bd_botquantity] [decimal](18, 2) NULL,
	[Fb_bd_rate] [decimal](18, 2) NULL,
	[Fb_bd_Remarks] [varchar](250) NULL,
 CONSTRAINT [PK_Fb_botdetails] PRIMARY KEY NONCLUSTERED 
(
	[Fb_bd_Companyid] ASC,
	[fb_bd_Outletid] ASC,
	[Fb_bd_botid] ASC,
	[Fb_bd_Botdetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aCountryMaster]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aCountryMaster](
	[CountryID] [int] NOT NULL,
	[CountryName] [varchar](50) NOT NULL,
	[CompanyID] [int] NOT NULL,
	[Nationality] [varchar](50) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aCountryMaster] PRIMARY KEY NONCLUSTERED 
(
	[CountryID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_165575628] ON [dbo].[aCountryMaster] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aCity]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aCity](
	[CityID] [int] NOT NULL,
	[CountryID] [int] NOT NULL,
	[CityCode] [varchar](50) NOT NULL,
	[CityName] [varchar](250) NULL,
	[AreaCode] [varchar](50) NULL,
	[ZipCodeFrom] [varchar](50) NULL,
	[ZipCodeTo] [varchar](50) NULL,
	[CompanyID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aCity] PRIMARY KEY NONCLUSTERED 
(
	[CityID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [CITYUNIQUE] ON [dbo].[aCity] 
(
	[CountryID] ASC,
	[CityCode] ASC,
	[CityName] ASC,
	[AreaCode] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = ON, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1029578706] ON [dbo].[aCity] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aCurrencyMaster]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aCurrencyMaster](
	[CurrencyID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[CurrencyName] [varchar](50) NOT NULL,
	[Symbol] [varchar](50) NOT NULL,
	[CountryID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aCurrencyMaster] PRIMARY KEY NONCLUSTERED 
(
	[CurrencyID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1045578763] ON [dbo].[aCurrencyMaster] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aCustomerMaster]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aCustomerMaster](
	[CustomerID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[CustomerName] [varchar](100) NOT NULL,
	[Active] [bit] NOT NULL,
	[Address1] [varchar](250) NULL,
	[Address2] [varchar](250) NULL,
	[Address3] [varchar](250) NULL,
	[CityID] [int] NOT NULL,
	[ContactName] [varchar](250) NULL,
	[PhoneNo] [varchar](50) NULL,
	[FaxNo] [varchar](50) NULL,
	[EmailID] [varchar](100) NULL,
	[CreditLimit] [numeric](18, 2) NULL,
	[Comments] [varchar](750) NULL,
	[CurrencyID] [int] NULL,
	[CountryID] [int] NULL,
	[OpeningCreditBalance] [numeric](18, 2) NULL,
	[OpeningDebitBalance] [numeric](18, 2) NULL,
	[CustomerCode] [varchar](50) NULL,
	[CustomerCategory] [varchar](100) NOT NULL,
	[Dueperiod] [int] NOT NULL,
	[Nationality] [varchar](50) NULL,
	[CustomerCardNo] [varchar](100) NULL,
	[custdob] [datetime] NULL,
	[registerdate] [datetime] NULL,
	[discperc] [numeric](18, 0) NULL,
	[Futureint] [int] NULL,
	[futurevc] [varchar](250) NULL,
	[customertype] [char](1) NULL,
	[permitno] [varchar](50) NULL,
	[permitexpirydate] [datetime] NULL,
	[avgsalesmargin] [numeric](5, 2) NULL,
	[debtoraccid] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[segmentid] [int] NULL,
	[custgroupname] [varchar](100) NULL,
	[ContactName1] [varchar](250) NULL,
	[ContactName2] [varchar](250) NULL,
	[ContactDesig] [varchar](100) NULL,
	[ContactDesig1] [varchar](100) NULL,
	[ContactDesig2] [varchar](100) NULL,
	[webadd] [varchar](50) NULL,
	[ContactEmail] [varchar](50) NULL,
	[ContactEmail1] [varchar](50) NULL,
	[ContactEmail2] [varchar](50) NULL,
	[ContactPhone] [varchar](20) NULL,
	[ContactPhone1] [varchar](20) NULL,
	[ContactPhone2] [varchar](20) NULL,
	[ContactDOB] [datetime] NULL,
	[ContactDOB1] [datetime] NULL,
	[ContactDOB2] [datetime] NULL,
	[ContactAnn] [datetime] NULL,
	[ContactAnn1] [datetime] NULL,
	[ContactAnn2] [datetime] NULL,
	[cusGroupID] [int] NULL,
	[MonthlyInvoiceCredit] [bit] NULL,
	[CreditAllowed] [bit] NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF
ALTER TABLE [dbo].[aCustomerMaster] ADD [CUSTOMERTIN] [varchar](50) NULL
SET ANSI_PADDING ON
ALTER TABLE [dbo].[aCustomerMaster] ADD [NICNO] [varchar](100) NULL
ALTER TABLE [dbo].[aCustomerMaster] ADD [ExcludeGST] [bit] NULL
ALTER TABLE [dbo].[aCustomerMaster] ADD  CONSTRAINT [PK_aCustomerMaster] PRIMARY KEY NONCLUSTERED 
(
	[CustomerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1349579846] ON [dbo].[aCustomerMaster] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aVendorMaster]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aVendorMaster](
	[VendorID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[VendorName] [varchar](250) NOT NULL,
	[Address1] [varchar](250) NULL,
	[Address2] [varchar](250) NULL,
	[Address3] [varchar](250) NULL,
	[CityID] [int] NOT NULL,
	[ContactName] [varchar](250) NULL,
	[PhoneNo] [varchar](250) NULL,
	[FaxNo] [varchar](250) NULL,
	[EmailID] [varchar](50) NULL,
	[Local] [bit] NOT NULL,
	[DuePeriod] [smallint] NULL,
	[Comments] [varchar](250) NULL,
	[Active] [bit] NOT NULL,
	[CurrencyID] [int] NULL,
	[CountryID] [int] NULL,
	[OpeningCreditBalance] [numeric](18, 2) NULL,
	[OpeningDebitBalance] [numeric](18, 2) NULL,
	[VendorCode] [varchar](50) NULL,
	[Initial] [varchar](5) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[allowblankcheque] [bit] NOT NULL,
	[creditoraccid] [int] NULL,
	[VenGroupId] [int] NULL,
	[VendorCategory] [varchar](250) NULL,
	[VendorTIN] [varchar](50) NULL,
 CONSTRAINT [PK_aVendorMaster] PRIMARY KEY NONCLUSTERED 
(
	[VendorID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1429580131] ON [dbo].[aVendorMaster] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losLocalClearenceRequestHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losLocalClearenceRequestHeader](
	[ShopID] [int] NOT NULL,
	[ClearenceReqID] [int] NOT NULL,
	[ClearenceReqNo] [varchar](50) NOT NULL,
	[ClearenceReqDate] [datetime] NULL,
	[CustomerID] [int] NULL,
	[VendorID] [int] NULL,
	[PONo] [varchar](50) NULL,
	[PODate] [datetime] NULL,
	[DeliveryTo] [varchar](250) NULL,
	[DeliveryDate] [datetime] NULL,
	[EnteredBy] [varchar](50) NULL,
	[Remarks] [varchar](250) NULL,
	[CashorCredit] [bit] NOT NULL,
	[CashPaidByShop] [bit] NOT NULL,
	[Cancelled] [bit] NULL,
	[CancelledRemarks] [varchar](250) NULL,
	[VendorName] [varchar](50) NULL,
 CONSTRAINT [pk_losLocalClearenceRequestHeader] PRIMARY KEY CLUSTERED 
(
	[ShopID] ASC,
	[ClearenceReqID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losLocalClearenceRequestDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losLocalClearenceRequestDetail](
	[ShopID] [int] NOT NULL,
	[ClearenceReqID] [int] NOT NULL,
	[DetailID] [int] NOT NULL,
	[ItemDescription] [varchar](250) NULL,
	[Unit] [varchar](25) NULL,
	[Qty] [numeric](18, 3) NULL,
	[Amount] [numeric](18, 2) NULL,
	[Remarks] [varchar](250) NULL,
	[NoofPackages] [numeric](18, 2) NULL,
	[Packing] [varchar](50) NULL,
 CONSTRAINT [pk_losLocalClearenceRequestDetail] PRIMARY KEY CLUSTERED 
(
	[ShopID] ASC,
	[ClearenceReqID] ASC,
	[DetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losLPHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losLPHeader](
	[ShopID] [int] NOT NULL,
	[POID] [int] NOT NULL,
	[PONo] [varchar](50) NOT NULL,
	[PODate] [datetime] NULL,
	[CustomerID] [int] NULL,
	[VendorID] [int] NULL,
	[ClearenceReqID] [int] NULL,
	[EnteredBy] [varchar](50) NULL,
	[Remarks] [varchar](250) NULL,
	[CashorCredit] [bit] NOT NULL,
	[CashPaidByShop] [bit] NOT NULL,
	[Cancelled] [bit] NULL,
	[CancelledRemarks] [varchar](250) NULL,
	[vendorname] [varchar](50) NULL,
 CONSTRAINT [pk_losLPHeader] PRIMARY KEY CLUSTERED 
(
	[ShopID] ASC,
	[POID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aGroupMaster]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aGroupMaster](
	[GroupID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[GroupDesc] [varchar](250) NOT NULL,
	[AccountType] [varchar](50) NOT NULL,
	[ParentGroupID] [int] NULL,
	[LevelCode] [int] NOT NULL,
	[OrderNo] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aGroupMaster] PRIMARY KEY NONCLUSTERED 
(
	[GroupID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1397580017] ON [dbo].[aGroupMaster] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aAccountMaster](
	[AccountID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[AccountCode] [varchar](50) NOT NULL,
	[Active] [bit] NOT NULL,
	[GroupID] [int] NOT NULL,
	[AccountDesc] [varchar](250) NOT NULL,
	[ControlledAccount] [varchar](50) NULL,
	[BudgetAmount] [numeric](18, 2) NULL,
	[openingamount] [numeric](18, 2) NULL,
	[openingactualamount] [numeric](18, 2) NULL,
	[openingdepamount] [numeric](18, 2) NULL,
	[OrderNo] [int] NOT NULL,
	[CurrencyID] [int] NULL,
	[Misc] [varchar](50) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aAccountMaster] PRIMARY KEY NONCLUSTERED 
(
	[AccountID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_805577908] ON [dbo].[aAccountMaster] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aDepartmentMaster](
	[DepartmentID] [int] NOT NULL,
	[DepartmentName] [varchar](50) NOT NULL,
	[CompanyID] [int] NOT NULL,
	[BudgetedAmount] [numeric](18, 2) NULL,
	[ParentDepId] [int] NULL,
	[LevelCode] [int] NULL,
	[Selected] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[depcurrencyid] [int] NULL,
	[address1] [varchar](250) NULL,
	[address2] [varchar](250) NULL,
	[payablealertbeforedays] [int] NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF
ALTER TABLE [dbo].[aDepartmentMaster] ADD [InchargeEmail] [varchar](50) NULL
ALTER TABLE [dbo].[aDepartmentMaster] ADD [InchargeName] [varchar](50) NULL
ALTER TABLE [dbo].[aDepartmentMaster] ADD  CONSTRAINT [PK_aDepartmentMaster] PRIMARY KEY NONCLUSTERED 
(
	[DepartmentID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_388912457] ON [dbo].[aDepartmentMaster] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aPAckageSettings]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aPAckageSettings](
	[PAckageDate] [datetime] NULL,
	[BackNoOfDays] [int] NULL,
	[HQSalesAccID] [int] NULL,
	[HQPurchaseAccID] [int] NULL,
	[customsaccid] [int] NULL,
	[GoodsInTransitID] [int] NULL,
	[LCGroupID] [int] NULL,
	[companyid] [int] NULL,
	[servername] [varchar](50) NULL,
	[CostingMethod] [varchar](5) NULL,
	[DayClosed] [varchar](5) NULL,
	[defaultAgeRange] [int] NULL,
	[defaultGodownID] [int] NULL,
	[defaultShopID] [int] NULL,
	[defaultRepRangeStart] [datetime] NULL,
	[defaultRepRangeEnd] [datetime] NULL,
	[InventoryID] [int] NULL,
	[CostofGoodsid] [int] NULL,
	[LcMarginGroupID] [int] NULL,
	[futureint] [int] NULL,
	[futurevc] [varchar](250) NULL,
	[futurenum] [numeric](18, 2) NULL,
	[movementperiod] [int] NULL,
	[importperiod] [int] NULL,
	[analysisperiod] [char](10) NULL,
	[shipmentfixedandactualvaluediff] [int] NULL,
	[compprofitshareacc] [int] NULL,
	[stocktransfercontrolacc] [int] NULL,
	[companydepartment] [int] NULL,
	[profittransfercontrolacc] [int] NULL,
	[mainservername] [varchar](50) NULL,
	[AllowItemCodeDuplication] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[Returnadjustmentaccid] [int] NULL,
	[PurchaseRtnAccID] [int] NULL,
	[POGITAccountid] [int] NULL,
	[costofsalesid] [int] NULL,
	[AssetConversionAccid] [int] NULL,
	[interdepsalescntrlaccid] [int] NULL,
	[instdate] [varchar](250) NULL,
	[lockdate] [varchar](250) NULL,
	[extensionno] [varchar](250) NULL,
	[tempchar] [varchar](250) NULL,
	[spcheck] [smallint] NULL,
	[EnableCRMContacts] [int] NULL,
	[CompanyLogin] [int] NULL,
	[hirepurchase] [int] NULL,
	[Payrollneeded] [int] NULL,
	[DisableDataFiltersForCustomers] [int] NULL,
	[DisableDataFiltersForVendors] [int] NULL,
	[BusinessPromotionAcc] [int] NULL,
	[WarrentyClaimAcc] [int] NULL,
	[MailBasedOnReorderLevel] [bit] NULL,
	[HQLocalPurchaseConfirmation] [int] NULL,
	[BlockAddingNewItemToShops] [int] NULL,
	[FineEnabled] [int] NULL,
	[IntegerQuantity] [int] NULL,
	[Alias] [bit] NOT NULL,
	[ActiveDirectoryLogin] [bit] NULL,
	[AllowEnteringSlNoInSplInvoice] [bit] NULL,
	[AllowDirectPurchaseBill] [int] NULL,
	[ShowCollectFromInDeliveryNote] [bit] NULL,
	[ReorderLevelMandatory] [bit] NULL,
	[ItemwiseAccountinginInHousecon] [bit] NULL,
	[DefaultPurRequestVendor] [int] NULL,
	[TransactionsSummaryDate] [datetime] NULL,
	[AllowDirectLocalPurchaseCosting] [bit] NOT NULL,
	[TransactionsSummary] [bit] NULL,
	[DeliveryItemsVerificationUrl] [varchar](500) NULL,
	[VisibleDepartmentPurReq] [bit] NULL,
	[AllowMultipleQuotations] [bit] NULL,
	[EnableRemainderAccBills] [bit] NOT NULL,
	[AutoConfirmAccTrans] [bit] NOT NULL,
	[SellingPriceBelowCostPrice] [bit] NOT NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF
ALTER TABLE [dbo].[aPAckageSettings] ADD [CreditLimitType] [char](1) NULL
ALTER TABLE [dbo].[aPAckageSettings] ADD [ReportServerName] [varchar](100) NULL
ALTER TABLE [dbo].[aPAckageSettings] ADD [PPandEAccid] [int] NULL
ALTER TABLE [dbo].[aPAckageSettings] ADD [CustomerGroupIdForEmployees] [int] NULL
ALTER TABLE [dbo].[aPAckageSettings] ADD [NoCreditForOverdueCustomers] [bit] NOT NULL
ALTER TABLE [dbo].[aPAckageSettings] ADD [ReportLogo] [int] NULL
ALTER TABLE [dbo].[aPAckageSettings] ADD [postdatedcheque] [bit] NOT NULL
ALTER TABLE [dbo].[aPAckageSettings] ADD [AutomateSegmentwisePrice] [bit] NULL
ALTER TABLE [dbo].[aPAckageSettings] ADD [QuickItemFetchInLoginDepartmentOnly] [bit] NULL
ALTER TABLE [dbo].[aPAckageSettings] ADD [EnableGST] [bit] NULL
ALTER TABLE [dbo].[aPAckageSettings] ADD [TaxCategoryforServices] [int] NULL
ALTER TABLE [dbo].[aPAckageSettings] ADD [EnableGSTinForeignPurchase] [bit] NULL
ALTER TABLE [dbo].[aPAckageSettings] ADD [CustomerGroupIdForManagement] [int] NULL
ALTER TABLE [dbo].[aPAckageSettings] ADD [CustomerGroupIdForStaff] [int] NULL
ALTER TABLE [dbo].[aPAckageSettings] ADD [TaxCategoryforInstallmentSales] [bit] NULL
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idxAps] ON [dbo].[aPAckageSettings] 
(
	[companyid] ASC,
	[InventoryID] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1877581727] ON [dbo].[aPAckageSettings] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losCallBookingHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losCallBookingHeader](
	[serCallBkhid] [int] NOT NULL,
	[serCallBkhno] [varchar](50) NULL,
	[serCallBkhshopid] [int] NOT NULL,
	[serCallBkhslno] [varchar](50) NULL,
	[serCallBkhdate] [datetime] NULL,
	[serCallBkhitemid] [int] NULL,
	[serCallBkpartcode] [varchar](50) NULL,
	[serCallBkrefno] [varchar](50) NULL,
	[serCallBkhaddress] [varchar](250) NULL,
	[serCallBkhMaintenanceContractID] [int] NULL,
	[serCallBkhtelephone] [varchar](50) NULL,
	[serCallBkhrecvdfrom] [varchar](100) NULL,
	[serCallBkhCallClass] [varchar](50) NULL,
	[serCallBkhCallShopID] [int] NULL,
	[serCallBkhCallType] [varchar](250) NULL,
	[serCallBkhcancelled] [bit] NULL,
	[serCallBkhcategid] [int] NULL,
	[serCallBkhcompanyid] [int] NOT NULL,
	[serCallBkhcustomerid] [int] NULL,
	[serCallBkhdepartmentid] [int] NULL,
	[serCallBkhenteredby] [varchar](100) NULL,
	[serCallBkhFaxInTime] [datetime] NULL,
	[serCallBkhfuturevc] [varchar](250) NULL,
	[serCallBkhguarentee] [bit] NULL,
	[serCallBkhinformedby] [varchar](50) NULL,
	[serCallBkhpurchdate] [datetime] NULL,
	[serCallBkhremarks] [varchar](250) NULL,
	[serCallBkhtime] [datetime] NULL,
	[serCallBkhupdatetime] [datetime] NULL,
	[serCallBkcancelremarks] [varchar](250) NULL,
	[serCallBkhinstallation] [bit] NULL,
	[sercallbkhstatus] [varchar](50) NULL,
	[serCallBkhStatusId] [int] NULL,
	[sercallbkhwarrantyfrom] [datetime] NULL,
	[sercallbkhwarrantyto] [datetime] NULL,
	[serCallBkhRegID] [int] NULL,
	[serCallBkhMileage] [nvarchar](30) NULL,
	[serCallBkhcustomerName] [nvarchar](200) NULL,
	[serCallBkhServWarrantyUpto] [datetime] NULL,
	[serCallBkhPartsWarrantyUpto] [datetime] NULL,
	[serCallBkhSerialNo] [nvarchar](200) NULL,
	[sercallbkhonsite] [bit] NULL,
	[serCallBkhExcludeGST] [bit] NULL,
 CONSTRAINT [pk_losCallBookingHeader] PRIMARY KEY CLUSTERED 
(
	[serCallBkhid] ASC,
	[serCallBkhshopid] ASC,
	[serCallBkhcompanyid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losServiceBookingHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losServiceBookingHeader](
	[serbookhid] [int] NOT NULL,
	[serbookhshopid] [int] NOT NULL,
	[serbookhcompanyid] [int] NOT NULL,
	[serbookhpreparedby] [varchar](50) NULL,
	[serbookhdeldate] [datetime] NULL,
	[serbookadvanceamount] [numeric](18, 2) NULL,
	[serbookhserviceamt] [numeric](18, 2) NULL,
	[serbookhpartscost] [numeric](18, 2) NULL,
	[serbookhdepartmentid] [int] NULL,
	[serbookhposted] [bit] NOT NULL,
	[serbookhinvoiced] [bit] NOT NULL,
	[serbookhcashacc] [int] NULL,
	[serbookadvanceacc] [int] NULL,
	[serbookhcmpexrate] [numeric](18, 8) NULL,
	[serbookhresexrate] [numeric](18, 8) NULL,
	[serbookhbaserate] [numeric](18, 8) NULL,
	[serbookconfirmed] [bit] NOT NULL,
	[serbooksermode] [bit] NOT NULL,
	[serbookhfutureint] [int] NULL,
	[serbookhfuturenumer] [numeric](18, 8) NULL,
	[serbookhstatus] [char](10) NULL,
	[serbookhpriority] [int] NULL,
	[serbookhInspectionNo] [varchar](50) NULL,
	[serbookhInspectionDate] [datetime] NULL,
	[serbookhEstExpiryDate] [datetime] NULL,
	[serbookhApprovedDate] [datetime] NULL,
	[serbookhFaxOutTime] [datetime] NULL,
	[serbookhdepexrate] [numeric](18, 8) NULL,
	[serbookhexchangerates] [varchar](250) NULL,
	[serbookhinspectiontime] [datetime] NULL,
	[serbookhinpcancelled] [bit] NULL,
	[serbookhinpstatus] [varchar](1) NULL,
	[serbookadvancedate] [datetime] NULL,
	[serbookhRemarks] [varchar](250) NULL,
	[serbookhinpCancelledRemarks] [varchar](250) NULL,
	[serbookhRefId] [int] NULL,
	[serbookhUpdateTime] [datetime] NOT NULL,
	[serccallbkhrecvdfrom] [varchar](100) NULL,
	[serWarranyFrom] [datetime] NULL,
	[serWarrantyTo] [datetime] NULL,
	[serbookhUserid] [int] NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF
ALTER TABLE [dbo].[losServiceBookingHeader] ADD [serbookhTerms] [varchar](250) NULL
SET ANSI_PADDING ON
ALTER TABLE [dbo].[losServiceBookingHeader] ADD [serbookhSerialNumber] [varchar](100) NULL
ALTER TABLE [dbo].[losServiceBookingHeader] ADD [serserbookhExcludeGST] [bit] NULL
ALTER TABLE [dbo].[losServiceBookingHeader] ADD  CONSTRAINT [PK_LOSSERVICEBOOKINGHEADER] PRIMARY KEY NONCLUSTERED 
(
	[serbookhid] ASC,
	[serbookhshopid] ASC,
	[serbookhcompanyid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losSerestimateapproval]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSerestimateapproval](
	[seaAppShopId] [int] NOT NULL,
	[seaAppId] [int] NOT NULL,
	[seaAppcompanyID] [int] NOT NULL,
	[seaAppDate] [datetime] NULL,
	[seaAppNo] [varchar](50) NULL,
	[seaAppCustomerId] [int] NULL,
	[seaAppSershopID] [int] NULL,
	[seaAppbookingId] [int] NULL,
	[seaApprovedBy] [varchar](50) NULL,
	[seaApporRejected] [bit] NOT NULL,
	[seaAppremarks] [varchar](250) NULL,
	[seaAppusername] [varchar](50) NULL,
	[seaAppCancelled] [bit] NOT NULL,
	[seaAppCancelremarks] [varchar](250) NULL,
 CONSTRAINT [PK_losSerestimateapproval] PRIMARY KEY NONCLUSTERED 
(
	[seaAppShopId] ASC,
	[seaAppId] ASC,
	[seaAppcompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aShops]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aShops](
	[ShopID] [int] NOT NULL,
	[ShopName] [varchar](250) NOT NULL,
	[ShopLocation] [varchar](250) NOT NULL,
	[ShopRegNo] [varchar](50) NOT NULL,
	[ShopIECode] [varchar](50) NOT NULL,
	[InCharge] [varchar](250) NOT NULL,
	[JobTitle] [varchar](250) NULL,
	[TelephoneNo] [varchar](100) NULL,
	[OpenedDate] [datetime] NULL,
	[Address] [varchar](250) NULL,
	[CityID] [int] NULL,
	[FaxNo] [varchar](100) NULL,
	[BillMessage] [varchar](250) NULL,
	[Remarks] [varchar](250) NULL,
	[OwnerName] [varchar](250) NULL,
	[OwnerAddress] [varchar](250) NULL,
	[OwnerTelephone] [varchar](50) NULL,
	[ActiveShop] [bit] NOT NULL,
	[Ipaddress] [varchar](50) NOT NULL,
	[CompanyID] [int] NOT NULL,
	[Countryid] [int] NULL,
	[Selected] [bit] NOT NULL,
	[TruncateCheck] [bit] NOT NULL,
	[FIFO] [bit] NOT NULL,
	[DepartmentID] [int] NULL,
	[DefaultCashaccountID] [int] NULL,
	[ShopSalesaccountID] [int] NULL,
	[ShopPurchaseAcID] [int] NULL,
	[ShopGoodsReturnNoteAccID] [int] NULL,
	[diffinCashBoxAcc] [int] NULL,
	[ExpenseAccount] [int] NULL,
	[maxPaymentAmount] [numeric](18, 2) NULL,
	[maxdiscountpercent] [numeric](18, 2) NULL,
	[dayClosed] [bit] NOT NULL,
	[stockWriteoffAccID] [int] NULL,
	[wholesaleallowed] [bit] NOT NULL,
	[MaxRequestItemsToHQ] [int] NULL,
	[futureint] [int] NULL,
	[futurevarchar] [varchar](250) NULL,
	[futuredatetime] [datetime] NULL,
	[discountaccountid] [int] NULL,
	[miscsettings13] [varchar](50) NULL,
	[allowblockprice] [bit] NOT NULL,
	[showcostpriceinsales] [bit] NULL,
	[RevisedCostPricePercent] [numeric](18, 2) NULL,
	[shopdebitcreditacc] [int] NULL,
	[gstno] [varchar](50) NULL,
	[gstpercent] [numeric](5, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[locationarrangement] [bit] NULL,
	[costofsalespercent] [numeric](5, 2) NULL,
	[segmentid] [int] NULL,
	[Accountable] [datetime] NULL,
	[DeliveryMust] [bit] NULL,
	[interdepsalesaccid] [int] NULL,
	[interdeppurchaseaccid] [int] NULL,
	[otherShopDebitAccId] [int] NULL,
	[SalesCommMarginPer] [numeric](6, 2) NULL,
	[ShopOtherChargesAccID] [int] NULL,
	[ShopCustomsDutyAccID] [int] NULL,
	[utilityaccountID] [int] NULL,
	[CounterLogin] [smallint] NULL,
	[DefaultSave] [int] NULL,
	[RateEditingonDirectCashInv] [int] NOT NULL,
	[RateEditingonDirectCreditInv] [int] NOT NULL,
	[SubDepartmentID] [int] NULL,
	[LoyaltyAccID] [int] NULL,
	[AutoGenerateDeliveryNote] [int] NULL,
	[ShowSellingPriceInItemFetch] [int] NULL,
	[AddCustomDutyToCostPrice] [int] NULL,
	[SeparateRateCheckCreditSales] [int] NULL,
	[InvoicePreviewCurrency] [int] NULL,
	[ShipmentDetails] [int] NULL,
	[showbinlocation] [bit] NULL,
	[RequestForNonShopItem] [bit] NULL,
	[ShowRecentlySavedContactDetails] [bit] NULL,
	[AllowNewCustAndItemCreateServ] [bit] NULL,
	[ShowStockInItemFetch] [bit] NULL,
	[InhouseConAccnt] [int] NULL,
	[AllowDateEditInTrans] [bit] NULL,
	[CustomerNeededForPos] [bit] NULL,
	[PreserveItemDetails] [bit] NULL,
	[ShowStockInTransOnlyOnDemand] [int] NULL,
	[AllowRateEditForFreeItem] [bit] NULL,
	[DefaultChequeaccountID] [int] NULL,
	[ShowDefaultSP] [bit] NULL,
	[RegisteredCustomer] [bit] NULL,
	[UnRegisteredCustomer] [bit] NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF
ALTER TABLE [dbo].[aShops] ADD [SHOPTIN] [varchar](50) NULL
ALTER TABLE [dbo].[aShops] ADD [activateGST] [bit] NULL
ALTER TABLE [dbo].[aShops] ADD [ServiceTaxCategoryId] [int] NULL
ALTER TABLE [dbo].[aShops] ADD [printKOTseperatly] [bit] NULL
ALTER TABLE [dbo].[aShops] ADD  CONSTRAINT [PK_aShops] PRIMARY KEY NONCLUSTERED 
(
	[ShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1237579447] ON [dbo].[aShops] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losServiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losServiceHeader](
	[serinvhid] [int] NOT NULL,
	[serinvhcompanyid] [int] NOT NULL,
	[serinvhbookingid] [int] NULL,
	[serinvhshopid] [int] NOT NULL,
	[serinvhpreparedby] [varchar](50) NULL,
	[serinvhserviceamt] [numeric](18, 2) NULL,
	[serinvhpartsamt] [numeric](18, 2) NULL,
	[serinvhamount] [numeric](18, 2) NULL,
	[serinvhdepartmentid] [int] NULL,
	[serinvhitemname] [varchar](250) NULL,
	[serinvhitemid] [int] NULL,
	[serinvhcustname] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[serinvhJobCardNo] [varchar](50) NULL,
	[serinvhPaceofWork] [varchar](250) NULL,
	[serinvhmetereading] [varchar](100) NULL,
	[serinvhrefno] [int] NULL,
	[serinvhprocno] [varchar](50) NULL,
	[serinvhprocdate] [datetime] NULL,
	[serinvhremarks] [varchar](500) NULL,
	[serinvhjobinvcancelledremarks] [varchar](250) NULL,
	[serinvhjobinvcancelled] [bit] NULL,
	[serinvhcompleted] [bit] NULL,
	[serinvhToInvoice] [bit] NULL,
	[itemDespatch] [bit] NULL,
	[serinvhdespdate] [datetime] NULL,
	[serinvhnotes] [varchar](4000) NULL,
	[serTypeId] [int] NULL,
 CONSTRAINT [PK_losserviceheader] PRIMARY KEY NONCLUSTERED 
(
	[serinvhid] ASC,
	[serinvhcompanyid] ASC,
	[serinvhshopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1573580644] ON [dbo].[losServiceHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losreplacerequestheader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losreplacerequestheader](
	[repreqhid] [int] NOT NULL,
	[repreqhcompanyid] [int] NOT NULL,
	[repreqshopid] [int] NOT NULL,
	[repreqno] [varchar](50) NULL,
	[repreqhdate] [datetime] NULL,
	[repreqhvendorid] [int] NULL,
	[repreqhremarks] [varchar](250) NULL,
	[repreqhcancelled] [bit] NOT NULL,
	[repreqhdoneby] [varchar](50) NULL,
	[repreqcancelremarks] [varchar](250) NULL,
	[repreqhreceived] [bit] NOT NULL,
	[repreqhfutureint] [int] NULL,
	[repreqhfuturevc] [varchar](250) NULL,
	[repreqhfuturenum] [numeric](18, 8) NULL,
	[repreqhupdatetime] [datetime] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[repreqhtransfinished] [bit] NULL,
	[repreqhnoofdetails] [int] NOT NULL,
	[repreqhdepartmentid] [int] NULL,
	[repreqhTime] [datetime] NULL,
 CONSTRAINT [PK_losreplacerequestheader] PRIMARY KEY NONCLUSTERED 
(
	[repreqhid] ASC,
	[repreqhcompanyid] ASC,
	[repreqshopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1525580473] ON [dbo].[losreplacerequestheader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losreplacerequestdetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losreplacerequestdetails](
	[repreqdid] [int] NOT NULL,
	[repreqdcompanyid] [int] NOT NULL,
	[repreqdshopid] [int] NOT NULL,
	[repreqditemid] [int] NOT NULL,
	[repreqdbookid] [int] NOT NULL,
	[repreqqty] [numeric](18, 8) NULL,
	[repreqdtagno] [varchar](50) NULL,
	[repreqdcomments] [varchar](250) NULL,
	[repreqdfutureint] [int] NULL,
	[repreqdfuturevc] [varchar](250) NULL,
	[repreqdfuturenum] [numeric](18, 8) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_losreplacerequestdetails] PRIMARY KEY NONCLUSTERED 
(
	[repreqdid] ASC,
	[repreqdcompanyid] ASC,
	[repreqdshopid] ASC,
	[repreqditemid] ASC,
	[repreqdbookid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_242099903] ON [dbo].[losreplacerequestdetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aproductconditionmaster]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aproductconditionmaster](
	[prodcndcompanyid] [int] NOT NULL,
	[prodcndid] [int] NOT NULL,
	[prodcndsercatid] [int] NOT NULL,
	[prodcndcode] [varchar](50) NULL,
	[prodcndname] [varchar](100) NULL,
	[prodcnddetails] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aproductconditionmaster] PRIMARY KEY NONCLUSTERED 
(
	[prodcndcompanyid] ASC,
	[prodcndid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_997578592] ON [dbo].[aproductconditionmaster] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losserconditiondetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losserconditiondetails](
	[cndserbookdid] [int] NOT NULL,
	[cndserid] [int] NOT NULL,
	[cndserdcompanyid] [int] NOT NULL,
	[cndserdshopid] [int] NOT NULL,
	[cndserbookdcomments] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [pk_losserconditiondetails] PRIMARY KEY NONCLUSTERED 
(
	[cndserbookdid] ASC,
	[cndserid] ASC,
	[cndserdcompanyid] ASC,
	[cndserdshopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_274100017] ON [dbo].[losserconditiondetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losbookservicedetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losbookservicedetails](
	[serbkdcompanyid] [int] NOT NULL,
	[serbkdbookid] [int] NOT NULL,
	[serbkdshopid] [int] NOT NULL,
	[serbkdserviceid] [int] NOT NULL,
	[serbkdcharge] [numeric](18, 8) NULL,
	[serbkdchargetaken] [numeric](18, 8) NULL,
	[serbkdcomments] [varchar](250) NULL,
	[serbkdserviceqty] [numeric](18, 2) NULL,
	[serbkdserdetailid] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[serinvhTaxCateID] [int] NULL,
	[serinvhTaxPercentage] [numeric](18, 2) NULL,
	[serinvhTaxamount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_losbookservicedetails] PRIMARY KEY CLUSTERED 
(
	[serbkdcompanyid] ASC,
	[serbkdbookid] ASC,
	[serbkdshopid] ASC,
	[serbkdserdetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_321540329] ON [dbo].[losbookservicedetails] 
(
	[rowguid] 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, FILLFACTOR = 100) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losbookpartsreplacedetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losbookpartsreplacedetails](
	[repbkdsercompanyid] [int] NOT NULL,
	[repbkdserpartsid] [int] NOT NULL,
	[repbkdshopid] [int] NOT NULL,
	[repbkdserbookid] [int] NOT NULL,
	[repbkdrate] [numeric](18, 8) NULL,
	[repbkdsellrate] [numeric](18, 8) NULL,
	[repbkdqty] [numeric](18, 3) NULL,
	[repbkdfromsupp] [bit] NULL,
	[repbkdguarantee] [bit] NULL,
	[repbkdcomments] [varchar](250) NULL,
	[repbkdcostprice] [numeric](18, 8) NULL,
	[repbkdpackid] [int] NULL,
	[repbkdpackqty] [numeric](18, 8) NULL,
	[repbkddetailid] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[repbkinvhSerialNumber] [varchar](100) NULL,
	[repbkinvhTaxCateID] [int] NULL,
	[repbkinvhTaxPercentage] [numeric](18, 2) NULL,
	[repbkinvhTaxamount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_losbookpartsreplacedetails] PRIMARY KEY CLUSTERED 
(
	[repbkdsercompanyid] ASC,
	[repbkdserbookid] ASC,
	[repbkdshopid] ASC,
	[repbkddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_2099048] ON [dbo].[losbookpartsreplacedetails] 
(
	[rowguid] 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, FILLFACTOR = 100) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losserpartsfromcustomer]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losserpartsfromcustomer](
	[custprodcompanyid] [int] NOT NULL,
	[custprodshopid] [int] NOT NULL,
	[custprodbookingid] [int] NOT NULL,
	[custprodproductid] [int] NOT NULL,
	[custprodname] [varchar](50) NULL,
	[custprodqty] [numeric](18, 3) NULL,
	[custprodcomments] [varchar](250) NULL,
	[custprodusedqty] [numeric](18, 3) NULL,
	[custprodusecomments] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_losserpartsfromcustomer] PRIMARY KEY NONCLUSTERED 
(
	[custprodcompanyid] ASC,
	[custprodshopid] ASC,
	[custprodbookingid] ASC,
	[custprodproductid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_290100074] ON [dbo].[losserpartsfromcustomer] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[AsalesPersonmaster]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[AsalesPersonmaster](
	[Sperid] [int] NOT NULL,
	[Spername] [varchar](50) NULL,
	[Sperqualification] [varchar](100) NULL,
	[Sperage] [int] NULL,
	[SperJoindate] [datetime] NULL,
	[SperDOB] [datetime] NULL,
	[SperSex] [bit] NOT NULL,
	[Speraddress] [varchar](250) NULL,
	[SperPhone] [varchar](100) NULL,
	[SperEmail] [varchar](100) NULL,
	[Companyid] [int] NOT NULL,
	[sperperhrsal] [numeric](18, 2) NULL,
	[targettype] [char](1) NULL,
	[targetamount] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[active] [int] NULL,
 CONSTRAINT [PK_AsalesPersonmaster] PRIMARY KEY NONCLUSTERED 
(
	[Sperid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_453576654] ON [dbo].[AsalesPersonmaster] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losbookservtechniciandetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losbookservtechniciandetails](
	[sertechcompanyid] [int] NOT NULL,
	[sertechbookid] [int] NOT NULL,
	[sertechshopid] [int] NOT NULL,
	[sertechdetailid] [int] NOT NULL,
	[sertechid] [int] NULL,
	[sertechstarttime] [datetime] NULL,
	[sertechendtime] [datetime] NULL,
	[sertechcostperhr] [int] NULL,
	[sertechservicetype] [char](10) NULL,
	[sertechcomments] [varchar](250) NULL,
	[sertechstatus] [char](10) NULL,
	[sertechfuturevc] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[sertechServiceID] [int] NULL,
 CONSTRAINT [PK_losservicetechniciandetails] PRIMARY KEY NONCLUSTERED 
(
	[sertechcompanyid] ASC,
	[sertechbookid] ASC,
	[sertechshopid] ASC,
	[sertechdetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_337540386] ON [dbo].[losbookservtechniciandetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losbookingcancellation]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losbookingcancellation](
	[bkcancellId] [int] NOT NULL,
	[bkcancellshopid] [int] NOT NULL,
	[bkcancellcomapnyid] [int] NOT NULL,
	[bkcancellno] [varchar](50) NULL,
	[bkcancelldate] [datetime] NULL,
	[bkcancellbookingId] [int] NULL,
	[bkcancellperson] [varchar](50) NULL,
	[bkcancelldetails] [varchar](250) NULL,
	[bkcancellcancelled] [bit] NOT NULL,
	[bkcancellRemarks] [varchar](250) NULL,
	[bkcancellposted] [bit] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Discountdetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Discountdetails](
	[Companyid] [int] NOT NULL,
	[Discountid] [int] NOT NULL,
	[Outletid] [int] NOT NULL,
	[Startdatetime] [datetime] NULL,
	[enddatetime] [datetime] NULL,
	[discountper] [decimal](18, 2) NULL,
	[dailytrue] [bit] NULL,
	[alldishtrue] [bit] NULL,
	[discountaccid] [int] NULL,
 CONSTRAINT [PK_Discountdetails] PRIMARY KEY NONCLUSTERED 
(
	[Companyid] ASC,
	[Discountid] ASC,
	[Outletid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[CashBox]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CashBox](
	[CBID] [int] NOT NULL,
	[CBMode] [char](10) NULL,
	[CBUserID] [int] NOT NULL,
	[CBShopID] [int] NOT NULL,
	[CBAmount] [numeric](18, 2) NULL,
	[CBVerifiedAmount] [numeric](18, 2) NULL,
	[CBDate] [datetime] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_CashBox] PRIMARY KEY NONCLUSTERED 
(
	[CBID] ASC,
	[CBShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_933578364] ON [dbo].[CashBox] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aFinancialYear]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aFinancialYear](
	[FinancialID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[StartMonth] [int] NOT NULL,
	[StartYear] [int] NOT NULL,
	[NoOfPeriod] [int] NOT NULL,
	[CurFinancialYear] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aFinancialYear] PRIMARY KEY NONCLUSTERED 
(
	[FinancialID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_213575799] ON [dbo].[aFinancialYear] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losSpecialInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSpecialInvoiceHeader](
	[IhInvoiceID] [int] NOT NULL,
	[IhShopID] [int] NOT NULL,
	[IhInvoiceNo] [varchar](50) NULL,
	[IhInvoiceDate] [datetime] NULL,
	[IhReferenceNo] [varchar](50) NULL,
	[IhCustomerID] [int] NULL,
	[IhProforma] [bit] NOT NULL,
	[IhCashInvoice] [bit] NOT NULL,
	[IhBankcashAccID] [int] NULL,
	[IhChequeNo] [varchar](50) NULL,
	[IhDueDate] [datetime] NULL,
	[IhRemarks] [varchar](250) NULL,
	[IhInvoiceAmount] [numeric](18, 2) NULL,
	[IhDiscount] [numeric](18, 2) NULL,
	[IhDiscountAccID] [int] NULL,
	[IhDepartmentID] [int] NULL,
	[IhFinancialID] [int] NULL,
	[IhCancelled] [bit] NOT NULL,
	[IhCancelledRemarks] [varchar](250) NULL,
	[IhExchangeNature] [varchar](50) NULL,
	[IhCompanyId] [int] NULL,
	[IhPosted] [bit] NOT NULL,
	[IhProformaID] [int] NULL,
	[ihRecAddUser] [varchar](250) NULL,
	[ihRecModifyUser] [varchar](250) NULL,
	[ihGoodsReturned] [bit] NOT NULL,
	[ihUsed] [bit] NOT NULL,
	[IhSalesAccID] [int] NULL,
	[IhSettled] [bit] NOT NULL,
	[ihTransFinished] [bit] NOT NULL,
	[ihNoofDetails] [int] NOT NULL,
	[ihNoofOCDetails] [int] NOT NULL,
	[ihexchangerate] [numeric](28, 8) NOT NULL,
	[ihsettledamount] [numeric](18, 2) NULL,
	[ihcbid] [int] NULL,
	[ihfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[ihsalespersonid] [int] NULL,
	[ihCustomerCardNo] [varchar](100) NULL,
	[ihfutureint] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[ihdepexrate] [numeric](18, 8) NULL,
	[ihexchangerates] [varchar](250) NULL,
	[ihcreatedtime] [datetime] NULL,
	[ihQuotationID] [int] NULL,
	[ihDespachID] [int] NULL,
	[ihReturnBeforeDesID] [int] NULL,
	[ihUserId] [int] NULL,
	[ihModifyUserId] [int] NULL,
 CONSTRAINT [PK_losSpecialInvoiceHeader] PRIMARY KEY NONCLUSTERED 
(
	[IhInvoiceID] ASC,
	[IhShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_losspecialinvoiceheader_ihInvoicedate] ON [dbo].[losSpecialInvoiceHeader] 
(
	[IhInvoiceDate] 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
CREATE UNIQUE NONCLUSTERED INDEX [index_338100245] ON [dbo].[losSpecialInvoiceHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_losspecialinvoiceheader] ON [dbo].[losSpecialInvoiceHeader] 
(
	[IhInvoiceID] ASC,
	[IhShopID] ASC,
	[IhCancelled] ASC,
	[IhProforma] ASC,
	[ihTransFinished] 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
/****** Object:  Table [dbo].[HQSalesPromotionDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[HQSalesPromotionDetail](
	[spdCompanyID] [int] NOT NULL,
	[spdpromotionID] [int] NOT NULL,
	[spdDetailID] [int] NOT NULL,
	[spdCustomerID] [int] NULL,
	[spdSalesAmt] [numeric](18, 2) NULL,
	[spdSalesPer] [numeric](5, 2) NULL,
	[spdProfitAmt] [numeric](18, 2) NULL,
	[spdProfitPer] [numeric](5, 2) NULL,
	[spdPromotionAmt] [numeric](18, 2) NULL,
	[spdToBePaid] [bit] NOT NULL,
	[spdRemarks] [varchar](250) NULL,
 CONSTRAINT [pk_HQSalesPromotionDetail] PRIMARY KEY CLUSTERED 
(
	[spdCompanyID] ASC,
	[spdpromotionID] ASC,
	[spdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOspPurchaseBillHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOspPurchaseBillHeader](
	[pbhBillID] [int] NOT NULL,
	[pbhBillNo] [varchar](50) NULL,
	[pbhVendorBillNo] [varchar](50) NULL,
	[pbhBillDate] [datetime] NULL,
	[pbhVendorID] [int] NULL,
	[pbhPOID] [int] NULL,
	[pbhBillAmount] [numeric](18, 2) NULL,
	[pbhDiscount] [numeric](18, 2) NULL,
	[pbhDiscountAccID] [int] NULL,
	[pbhAdjustmentAmount] [numeric](18, 2) NULL,
	[pbhDueDateforPayment] [datetime] NULL,
	[pbhBankCashAccID] [int] NULL,
	[pbhChequeNo] [varchar](25) NULL,
	[pbhFinancialID] [int] NULL,
	[pbhDepartmentID] [int] NULL,
	[pbhRemarks] [varchar](100) NULL,
	[pbhTobeDespatched] [bit] NOT NULL,
	[pbhDespatched] [bit] NOT NULL,
	[pbhCashPurchase] [bit] NOT NULL,
	[pbhExchangeNature] [varchar](5) NULL,
	[pbhCancelled] [bit] NOT NULL,
	[pbhCancelledRemarks] [varchar](250) NULL,
	[pbhPosted] [bit] NOT NULL,
	[pbhRecAddUser] [varchar](50) NULL,
	[pbhRecModifyUser] [varchar](50) NULL,
	[pbhCompanyID] [int] NULL,
	[pbhUsed] [bit] NOT NULL,
	[pbhvendorRefNo] [varchar](50) NULL,
	[pbhdummyICost] [numeric](18, 2) NULL,
	[pbhdummyFCharge] [numeric](18, 2) NULL,
	[pbhdummyOCharge] [numeric](18, 2) NULL,
	[pbhCustomExchangeRate] [numeric](18, 8) NULL,
	[pbhPurchaseAccID] [int] NULL,
	[pbhSettled] [bit] NOT NULL,
	[pbhexchangerate] [numeric](28, 22) NULL,
	[pbhship] [varchar](50) NULL,
	[pbhportoflading] [varchar](50) NULL,
	[pbhshipdepdate] [datetime] NULL,
	[pbhshipdischarge] [varchar](50) NULL,
	[pbhshiparrivaldate] [datetime] NULL,
	[pbhfinaldestination] [varchar](50) NULL,
	[updatetime] [datetime] NOT NULL,
	[pbhdepexrate] [numeric](18, 8) NULL,
	[pbhinvaccexrate] [numeric](18, 8) NULL,
	[pbhslndcertno] [varchar](50) NULL,
	[pbhslndcertdate] [varchar](50) NULL,
	[pbhComments] [varchar](250) NULL,
	[pbhexchangerates] [varchar](250) NULL,
	[pbhLcAmount] [numeric](18, 8) NULL,
	[pbhBillTime] [datetime] NULL,
	[pbhSubDepartmentID] [int] NULL,
	[pbhusername] [varchar](20) NULL,
 CONSTRAINT [PK_LOspPurchaseBillHeader] PRIMARY KEY NONCLUSTERED 
(
	[pbhBillID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[DebitCreditNote]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[DebitCreditNote](
	[DCNId] [int] NOT NULL,
	[DCNNo] [varchar](50) NULL,
	[DCNDate] [datetime] NULL,
	[DCNCustomerID] [int] NULL,
	[DCNVendorId] [int] NULL,
	[DCNDebit] [bit] NOT NULL,
	[DCNOtherAccId] [int] NULL,
	[DCNReferenceNo] [varchar](100) NULL,
	[DCNBillId] [int] NULL,
	[DCNInvoiceId] [int] NULL,
	[DCNAmount] [numeric](18, 2) NULL,
	[DCNDetails] [varchar](1000) NULL,
	[DCNRemarks] [varchar](250) NULL,
	[DCNCompanyid] [int] NULL,
	[DCNExchangerate] [numeric](18, 8) NULL,
	[DCNRefNo] [varchar](50) NULL,
	[DCNCusvenRefNo] [varchar](250) NULL,
	[Dcnfinancialid] [int] NULL,
	[DCNCancelled] [bit] NOT NULL,
	[DCNCancelledRemarks] [varchar](250) NULL,
	[DCNPosted] [bit] NOT NULL,
	[dcndepartmentid] [int] NULL,
	[DCNRecAddUser] [varchar](50) NULL,
	[DCNRecModifyUser] [varchar](50) NULL,
	[updatetime] [datetime] NULL,
	[parentdcnid] [int] NULL,
	[childdcnid] [int] NULL,
	[dcndepexrate] [numeric](18, 8) NULL,
	[dcnexchangerates] [varchar](250) NULL,
	[debitaccount1] [int] NULL,
	[debitaccount2] [int] NULL,
	[parentpaymentid] [int] NULL,
	[parentreceiptid] [int] NULL,
	[debitamt1] [numeric](18, 2) NULL,
	[debitamt2] [numeric](18, 2) NULL,
	[otheraccamt] [numeric](18, 2) NULL,
	[dcnSalesPromotionID] [int] NULL,
	[dcnSalesPromotionDetID] [int] NULL,
	[DcnSubDepartmentID] [int] NULL,
	[DCNConfirmed] [bit] NOT NULL,
 CONSTRAINT [PK_DebitCreditNote] PRIMARY KEY NONCLUSTERED 
(
	[DCNId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [ind_debitcreditnote_dcnDepartmentId] ON [dbo].[DebitCreditNote] 
(
	[dcndepartmentid] 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
CREATE NONCLUSTERED INDEX [ind_debitcreditnote_dcnvendorid] ON [dbo].[DebitCreditNote] 
(
	[DCNVendorId] 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
/****** Object:  Table [dbo].[LOsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsInvoiceHeader](
	[ihShopID] [int] NOT NULL,
	[ihInvoiceID] [int] NOT NULL,
	[ihInvoiceNo] [varchar](50) NULL,
	[ihInvoiceDate] [datetime] NULL,
	[ihReferenceNo] [varchar](50) NULL,
	[ihCustomerID] [int] NULL,
	[ihProforma] [bit] NOT NULL,
	[ihCashInvoice] [bit] NOT NULL,
	[ihBankcashAccID] [int] NULL,
	[ihChequeNo] [varchar](25) NULL,
	[ihDueDate] [datetime] NULL,
	[ihRemarks] [varchar](250) NULL,
	[ihInvoiceAmount] [numeric](18, 2) NULL,
	[ihDiscount] [numeric](18, 2) NULL,
	[ihDiscountAccID] [int] NULL,
	[ihDepartmentID] [int] NULL,
	[ihFinancialID] [int] NULL,
	[ihCancelled] [bit] NOT NULL,
	[ihCancelledRemarks] [varchar](250) NULL,
	[ihExchangeNature] [varchar](5) NULL,
	[ihCompanyId] [int] NULL,
	[ihPosted] [bit] NOT NULL,
	[ihProformaID] [int] NULL,
	[ihRecAddUser] [varchar](250) NULL,
	[ihRecModifyUser] [varchar](250) NULL,
	[ihGoodsReturned] [bit] NOT NULL,
	[ihSalesAccID] [int] NULL,
	[ihAdjustmentAmount] [numeric](18, 2) NULL,
	[ihSettled] [bit] NOT NULL,
	[ihexchangerate] [numeric](28, 8) NOT NULL,
	[ihsettledamount] [numeric](18, 2) NULL,
	[ihwholesale] [bit] NOT NULL,
	[ihfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[ihsalespersonid] [int] NULL,
	[ihCustomerCardNo] [varchar](100) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[ihgstpercentage] [numeric](18, 0) NULL,
	[ihdutypaidby] [char](1) NULL,
	[ihType] [char](2) NULL,
	[ihdepexrate] [numeric](18, 8) NULL,
	[ihcustomsformno] [varchar](100) NULL,
	[ihexchangerates] [varchar](250) NULL,
	[ihtransfinished] [bit] NULL,
	[ihCustomsDutyAccID] [int] NULL,
	[ihOptedVendorId] [int] NULL,
	[ihReferred] [varchar](10) NULL,
	[ihDeliveryDate] [datetime] NULL,
	[ihInvoiceTime] [datetime] NULL,
	[ContactCardNo] [varchar](50) NULL,
	[ihDeliveryNeeded] [bit] NULL,
	[ihuserid] [int] NULL,
	[ihModifyUserId] [int] NULL,
	[ihRefNo] [varchar](50) NULL,
	[ihCRMQuotationId] [int] NULL,
	[ExcludeGST] [bit] NULL,
 CONSTRAINT [PK_LOsInvoiceHeader] PRIMARY KEY NONCLUSTERED 
(
	[ihShopID] ASC,
	[ihInvoiceID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_losinvoiceheader_ihInvoicedate] ON [dbo].[LOsInvoiceHeader] 
(
	[ihInvoiceDate] 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
CREATE UNIQUE NONCLUSTERED INDEX [index_114099447] ON [dbo].[LOsInvoiceHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_losinvoiceheader] ON [dbo].[LOsInvoiceHeader] 
(
	[ihInvoiceID] ASC,
	[ihShopID] ASC,
	[ihCancelled] ASC,
	[ihProforma] ASC,
	[ihType] 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
/****** Object:  Table [dbo].[losDummyReceiptHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losDummyReceiptHeader](
	[drShopid] [int] NOT NULL,
	[drId] [int] NOT NULL,
	[drCompanyid] [int] NULL,
	[drNo] [varchar](50) NULL,
	[DrDate] [datetime] NULL,
	[drcustomerid] [int] NULL,
	[drbankname] [varchar](100) NULL,
	[drremarks] [varchar](250) NULL,
	[drchequeno] [varchar](50) NULL,
	[drchequedate] [datetime] NULL,
	[drAmount] [numeric](18, 2) NULL,
	[drcbid] [int] NULL,
	[drrecadduser] [varchar](50) NULL,
	[drrecmodifyuser] [varchar](50) NULL,
	[drcancelled] [bit] NOT NULL,
	[drcancelledremarks] [varchar](250) NULL,
	[drfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[drdepartmentid] [int] NULL,
	[drBankExchangeRate] [numeric](28, 8) NULL,
	[drExchangeRate] [numeric](28, 8) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[drdepexRate] [numeric](18, 8) NULL,
	[drexchangerates] [varchar](250) NULL,
	[drreccurrencyid] [int] NULL,
	[drrecamount] [numeric](18, 2) NULL,
	[drTime] [datetime] NULL,
	[drCounterID] [int] NULL,
	[drUserID] [int] NULL,
 CONSTRAINT [PK_losDummyReceipt] PRIMARY KEY NONCLUSTERED 
(
	[drShopid] ASC,
	[drId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1557580587] ON [dbo].[losDummyReceiptHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ReceiptVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ReceiptVoucherHeader](
	[ReceiptID] [int] NOT NULL,
	[CompanyID] [int] NULL,
	[ReceiptNo] [varchar](50) NULL,
	[ReceiptDate] [datetime] NULL,
	[CustomerID] [int] NULL,
	[VendorID] [int] NULL,
	[BankCashAccountID] [int] NOT NULL,
	[ReceivedFrom] [varchar](250) NULL,
	[Remarks] [varchar](250) NULL,
	[DepartmentID] [int] NULL,
	[ChequeDetails] [varchar](50) NULL,
	[ReferenceNo] [varchar](50) NULL,
	[ReferenceDate] [datetime] NULL,
	[Amount] [numeric](18, 2) NULL,
	[FinancialID] [int] NULL,
	[ExchangeNature] [varchar](5) NULL,
	[cbreferenceno] [varchar](50) NULL,
	[exchangerate] [numeric](18, 8) NULL,
	[receipttype] [varchar](50) NULL,
	[customeramount] [numeric](18, 2) NULL,
	[debitaccountid] [int] NULL,
	[debitamount] [numeric](18, 2) NULL,
	[chequedate] [datetime] NULL,
	[Posted] [bit] NOT NULL,
	[Cancelled] [bit] NOT NULL,
	[CancelledRemarks] [varchar](250) NULL,
	[dummyreceiptid] [int] NULL,
	[recshopid] [int] NULL,
	[updatetime] [datetime] NOT NULL,
	[creditaccountid] [int] NULL,
	[creditamount] [numeric](18, 2) NULL,
	[refjournalid] [int] NULL,
	[depexrate] [numeric](18, 8) NULL,
	[receiptcustomerid] [int] NULL,
	[exchangerates] [varchar](250) NULL,
	[paymentid] [int] NULL,
	[refdcnid] [int] NULL,
	[LastModified] [varchar](50) NULL,
	[cusvenaccexrate] [numeric](18, 8) NULL,
	[SubDepartmentID] [int] NULL,
	[Discountaccountid] [int] NULL,
	[DiscountAmount] [numeric](18, 2) NULL,
	[Confirmed] [bit] NOT NULL,
	[UserID] [int] NULL,
 CONSTRAINT [PK_ReceiptVoucherHeader] PRIMARY KEY NONCLUSTERED 
(
	[ReceiptID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [ind_receiptvoucherheader_vendorid] ON [dbo].[ReceiptVoucherHeader] 
(
	[VendorID] 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
/****** Object:  Table [dbo].[LosGoodsReturnNoteHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosGoodsReturnNoteHeader](
	[grnhShopid] [int] NOT NULL,
	[GrnhGoodsreturnnoteID] [int] NOT NULL,
	[GrnhGoodsreturnnoteNO] [varchar](50) NOT NULL,
	[GrnhGoodsreturnnoteDate] [datetime] NOT NULL,
	[GrnhCustomerID] [int] NOT NULL,
	[GrnhInvoiceID] [int] NULL,
	[GrnhRecommendedby] [varchar](250) NULL,
	[GrnhCancel] [bit] NOT NULL,
	[GrnhCancelledRemarks] [varchar](250) NULL,
	[GrnhRecAdduser] [varchar](250) NULL,
	[GrnhRecModifyuser] [varchar](250) NULL,
	[GrnhPosted] [bit] NOT NULL,
	[GrnReturnAccID] [int] NULL,
	[GrnCompanyID] [int] NULL,
	[grnhExchangeRate] [numeric](18, 8) NULL,
	[grnfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[grnhDepartmentid] [int] NULL,
	[grnhfinancialid] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[grnhdepExRate] [numeric](18, 8) NULL,
	[grnexchangerates] [varchar](250) NULL,
	[grnhTime] [datetime] NULL,
	[grnUserID] [int] NULL,
 CONSTRAINT [PK_LosGoodsReturnNoteHeader] PRIMARY KEY NONCLUSTERED 
(
	[grnhShopid] ASC,
	[GrnhGoodsreturnnoteID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_LosGoodsReturnNoteHeader_GrnhGoodsreturnnoteDate] ON [dbo].[LosGoodsReturnNoteHeader] 
(
	[GrnhGoodsreturnnoteDate] 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
CREATE UNIQUE NONCLUSTERED INDEX [index_866102126] ON [dbo].[LosGoodsReturnNoteHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_LosGoodsReturnNoteHeader] ON [dbo].[LosGoodsReturnNoteHeader] 
(
	[GrnhGoodsreturnnoteID] ASC,
	[grnhShopid] ASC,
	[GrnhCancel] 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
/****** Object:  Table [dbo].[CustomerSettlementHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CustomerSettlementHeader](
	[CSID] [int] NOT NULL,
	[CompanyID] [int] NULL,
	[CSNO] [varchar](50) NULL,
	[CSDATE] [datetime] NULL,
	[DepartmentID] [int] NULL,
	[ReceiptID] [int] NULL,
	[dcnid] [int] NULL,
	[shopid] [int] NULL,
	[losReceiptID] [int] NULL,
	[losdcnid] [int] NULL,
	[losGoodsreturnnoteID] [int] NULL,
	[CustomerID] [int] NULL,
	[Cancelled] [bit] NOT NULL,
	[CancelledRemarks] [varchar](250) NULL,
	[FinancialID] [int] NOT NULL,
	[Amount] [numeric](18, 2) NULL,
	[updatetime] [datetime] NOT NULL,
	[losshopdcnid] [int] NULL,
	[SubDepartmentID] [int] NULL,
 CONSTRAINT [PK_CustomerSettlementHeader] PRIMARY KEY NONCLUSTERED 
(
	[CSID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losDebitCreditNote]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losDebitCreditNote](
	[losDCNShopid] [int] NOT NULL,
	[losDCNId] [int] NOT NULL,
	[losDCNNo] [varchar](50) NULL,
	[losDCNDate] [datetime] NULL,
	[losDCNCustomerID] [int] NULL,
	[losDCNVendorId] [int] NULL,
	[losDCNDebit] [bit] NOT NULL,
	[losDCNOtherAccId] [int] NULL,
	[losDCNBillId] [int] NULL,
	[losDCNInvoiceId] [int] NULL,
	[losDCNAmount] [numeric](18, 2) NULL,
	[losDCNDetails] [varchar](1000) NULL,
	[losDCNRemarks] [varchar](250) NULL,
	[losDCNCompanyid] [int] NULL,
	[losDCNCancelled] [bit] NOT NULL,
	[losDCNCancelledRemarks] [varchar](250) NULL,
	[losDCNPosted] [bit] NOT NULL,
	[losDCNRecAddUser] [varchar](250) NULL,
	[losDCNRecModifyUser] [varchar](250) NULL,
	[losReferenceno] [varchar](100) NULL,
	[losrefno] [varchar](50) NULL,
	[loscusvenrefno] [varchar](50) NULL,
	[losfinancialid] [int] NULL,
	[losexchangerate] [numeric](18, 8) NULL,
	[updatetime] [datetime] NOT NULL,
	[losdcndepartmentid] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[losdepexrate] [numeric](18, 8) NULL,
	[losdexchangerates] [varchar](250) NULL,
	[losDCNtype] [char](1) NULL,
	[losDCNDuePeriod] [int] NULL,
	[losDCNUserID] [int] NULL,
 CONSTRAINT [PK_losDebitCreditNote] PRIMARY KEY NONCLUSTERED 
(
	[losDCNShopid] ASC,
	[losDCNId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [ind_losdebitcreditnote_losdcndepartmentid] ON [dbo].[losDebitCreditNote] 
(
	[losdcndepartmentid] 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
CREATE NONCLUSTERED INDEX [ind_losdebitcreditnote_losdcnVendorID] ON [dbo].[losDebitCreditNote] 
(
	[losDCNVendorId] 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
CREATE UNIQUE NONCLUSTERED INDEX [index_850102069] ON [dbo].[losDebitCreditNote] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[AccountsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[AccountsInvoiceHeader](
	[InvoiceID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[InvoiceNo] [varchar](50) NOT NULL,
	[InvoiceDate] [datetime] NOT NULL,
	[OrderNo] [varchar](100) NULL,
	[CustomerID] [int] NULL,
	[Proforma] [bit] NOT NULL,
	[CashInvoice] [bit] NOT NULL,
	[BankCashID] [int] NULL,
	[ChequeNo] [varchar](50) NULL,
	[DuePeriod] [smallint] NULL,
	[Remarks] [varchar](250) NULL,
	[Posted] [bit] NOT NULL,
	[DepartmentID] [int] NULL,
	[Product] [bit] NOT NULL,
	[Discount] [numeric](18, 2) NULL,
	[DiscountAccountID] [int] NULL,
	[Cancelled] [bit] NOT NULL,
	[CancelledRemarks] [varchar](250) NULL,
	[FinancialID] [int] NULL,
	[ExchangeNature] [varchar](5) NULL,
	[SalesAccID] [int] NULL,
	[ExchangeRate] [numeric](18, 8) NULL,
	[Referenceno] [varchar](100) NULL,
	[updatetime] [datetime] NOT NULL,
	[Futurevc] [varchar](250) NOT NULL,
	[depexrate] [numeric](18, 8) NULL,
	[exchangerates] [varchar](250) NULL,
	[dueDate] [datetime] NULL,
	[RefJournalID] [int] NULL,
	[SubDepartmentID] [int] NULL,
	[AutoGenerate] [bit] NULL,
	[ReminderID] [int] NULL,
	[DummyAdvance] [numeric](18, 2) NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF
ALTER TABLE [dbo].[AccountsInvoiceHeader] ADD [Pono] [varchar](60) NULL
ALTER TABLE [dbo].[AccountsInvoiceHeader] ADD [RegNo] [varchar](60) NULL
ALTER TABLE [dbo].[AccountsInvoiceHeader] ADD [Details] [varchar](1000) NULL
ALTER TABLE [dbo].[AccountsInvoiceHeader] ADD [UserID] [int] NULL
ALTER TABLE [dbo].[AccountsInvoiceHeader] ADD [TaxPercentage] [numeric](18, 2) NULL
ALTER TABLE [dbo].[AccountsInvoiceHeader] ADD [TaxAmount] [numeric](18, 2) NULL
ALTER TABLE [dbo].[AccountsInvoiceHeader] ADD [ItemTaxCategory] [int] NULL
ALTER TABLE [dbo].[AccountsInvoiceHeader] ADD [ExcludeGST] [bit] NULL
ALTER TABLE [dbo].[AccountsInvoiceHeader] ADD  CONSTRAINT [PK_AccountsInvoiceHeader] PRIMARY KEY NONCLUSTERED 
(
	[InvoiceID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOsAccountsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsAccountsInvoiceHeader](
	[aiShopID] [int] NOT NULL,
	[aiInvoiceID] [int] NOT NULL,
	[aiCompanyID] [int] NOT NULL,
	[aiInvoiceNo] [varchar](50) NOT NULL,
	[aiInvoiceDate] [datetime] NOT NULL,
	[aiOrderNo] [varchar](50) NULL,
	[aiCustomerID] [int] NULL,
	[aiProforma] [bit] NOT NULL,
	[aiCashInvoice] [bit] NOT NULL,
	[aiBankCashID] [int] NULL,
	[aiChequeNo] [varchar](50) NULL,
	[aiDuePeriod] [smallint] NULL,
	[aiRemarks] [varchar](250) NULL,
	[aiPosted] [bit] NOT NULL,
	[aiDepartmentID] [int] NULL,
	[aiProduct] [bit] NOT NULL,
	[aiDiscount] [numeric](18, 2) NULL,
	[aiDiscountAccountID] [int] NULL,
	[aiCancelled] [bit] NOT NULL,
	[aiCancelledRemarks] [varchar](250) NULL,
	[aiFinancialID] [int] NULL,
	[aiExchangeNature] [varchar](50) NULL,
	[aiSalesAccID] [int] NULL,
	[aiSettled] [bit] NOT NULL,
	[aiExchangeRate] [numeric](28, 8) NOT NULL,
	[aiReferenceno] [varchar](50) NULL,
	[aiSettledamount] [numeric](18, 2) NULL,
	[aicbid] [int] NULL,
	[aicfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[aiAddress] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[aidepexrate] [numeric](18, 8) NULL,
	[aidexchangerates] [varchar](250) NULL,
	[aiClearingComPerc] [numeric](18, 2) NULL,
	[aiInvoiceType] [varchar](5) NULL,
	[aiCashPaidByshop] [bit] NULL,
	[aiPOCommPer] [numeric](18, 2) NULL,
	[aiBoatnoteid] [int] NULL,
	[aiCreated] [varchar](250) NULL,
	[aiModified] [varchar](250) NULL,
	[aiTime] [datetime] NULL,
	[aiUserId] [int] NULL,
	[aiModifyUserId] [int] NULL,
	[aiTaxCategory] [int] NULL,
	[aiTaxAmount] [numeric](18, 2) NULL,
	[aiTaxPercentage] [numeric](18, 2) NULL,
	[ExcludeGST] [bit] NULL,
 CONSTRAINT [PK_LOsAccountsInvoiceHeader] PRIMARY KEY NONCLUSTERED 
(
	[aiShopID] ASC,
	[aiInvoiceID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1541580530] ON [dbo].[LOsAccountsInvoiceHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aHQPaymentVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHQPaymentVoucherHeader](
	[phPaymentID] [int] NOT NULL,
	[phCompanyID] [int] NULL,
	[phPaymentNo] [varchar](50) NOT NULL,
	[phPaymentDate] [datetime] NOT NULL,
	[phRemarks] [varchar](1000) NULL,
	[phBankCashID] [int] NULL,
	[phPayee] [varchar](100) NULL,
	[phVendorID] [int] NULL,
	[phDepartmentID] [int] NULL,
	[phCustomerID] [int] NULL,
	[phChequeDetails] [varchar](50) NULL,
	[phAmount] [numeric](18, 2) NULL,
	[phFinancialID] [int] NULL,
	[phExchangeNature] [varchar](5) NULL,
	[phExchangeRate] [numeric](18, 8) NULL,
	[phcbreferenceno] [varchar](50) NULL,
	[phCustomeramount] [numeric](18, 2) NULL,
	[phdebitaccountid] [int] NULL,
	[phdebitamount] [numeric](18, 2) NULL,
	[phchequedate] [datetime] NULL,
	[phPosted] [bit] NOT NULL,
	[phlcpayment] [varchar](5) NOT NULL,
	[phGoodsinTransitaccid] [int] NULL,
	[phCancelled] [bit] NOT NULL,
	[phCancelledRemarks] [varchar](250) NULL,
	[phfutureint] [int] NULL,
	[phfuturevarchar] [varchar](250) NULL,
	[phfuturenumeric] [numeric](18, 2) NULL,
	[updatetime] [datetime] NOT NULL,
	[phpohid] [int] NULL,
	[refjournalid] [int] NULL,
	[phallowblancheque] [bit] NULL,
	[phdepexrate] [numeric](18, 8) NULL,
	[phpaidbyvendorid] [int] NULL,
	[phexchangerates] [varchar](250) NULL,
	[refreceiptid] [int] NULL,
	[refdcnid] [int] NULL,
	[LastModified] [varchar](50) NULL,
	[refpaymentid] [int] NULL,
	[otherdeppaymentid] [int] NULL,
	[vencusaccexrate] [numeric](18, 8) NULL,
	[phSubDepartmentID] [int] NULL,
	[phPaymentVoucherNo] [varchar](50) NULL,
	[phTracked] [int] NULL,
	[phconfirmed] [bit] NULL,
 CONSTRAINT [PK_aHQPaymentVoucherHeader] PRIMARY KEY NONCLUSTERED 
(
	[phPaymentID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CustomerSettlementDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CustomerSettlementDetail](
	[CSID] [int] NOT NULL,
	[CSDetailID] [int] NOT NULL,
	[CompanyID] [int] NULL,
	[AccInvoiceID] [int] NULL,
	[dcnid] [int] NULL,
	[shopid] [int] NULL,
	[LosAccInvoiceID] [int] NULL,
	[losSpInvoiceId] [int] NULL,
	[losinvoiceid] [int] NULL,
	[losdcnid] [int] NULL,
	[losserinvoiceid] [int] NULL,
	[InvoiceAmount] [numeric](18, 2) NULL,
	[SettlementAmount] [numeric](18, 2) NULL,
	[paymentid] [int] NULL,
	[losexportid] [int] NULL,
	[RoomBillID] [int] NULL,
	[UtilityBillID] [int] NULL,
	[fineid] [int] NULL,
 CONSTRAINT [PK_CustomerSettlementDetail] PRIMARY KEY NONCLUSTERED 
(
	[CSID] ASC,
	[CSDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losSpecialOC]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSpecialOC](
	[ioShopid] [int] NOT NULL,
	[ioInvoiceID] [int] NOT NULL,
	[ioAccid] [int] NOT NULL,
	[ioDescription] [varchar](100) NULL,
	[ioAmount] [numeric](18, 2) NULL,
	[ioCompanyID] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_losSpecialOC] PRIMARY KEY NONCLUSTERED 
(
	[ioShopid] ASC,
	[ioInvoiceID] ASC,
	[ioAccid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1384496111] ON [dbo].[losSpecialOC] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aGodown]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aGodown](
	[GodownID] [int] NOT NULL,
	[GodownName] [varchar](250) NOT NULL,
	[GodownLocation] [varchar](250) NOT NULL,
	[GodownSqqFeet] [numeric](18, 3) NULL,
	[GodownIncharge] [varchar](250) NOT NULL,
	[GodownTelephoneNo] [varchar](50) NULL,
	[GodownFaxNo] [varchar](50) NOT NULL,
	[GodownActive] [bit] NOT NULL,
	[Remarks] [varchar](250) NOT NULL,
	[CityID] [int] NULL,
	[CountryID] [int] NULL,
	[Address] [varchar](250) NULL,
	[OwnerName] [varchar](50) NULL,
	[OwnerAddress] [varchar](250) NULL,
	[OwnerTelephone] [varchar](50) NULL,
	[CompanyID] [int] NOT NULL,
	[LocationArrangement] [bit] NOT NULL,
	[Fifo] [bit] NOT NULL,
	[selected] [bit] NULL,
	[ipaddress] [varchar](50) NULL,
	[stockwriteoffaccid] [int] NULL,
	[DepartmentId] [int] NULL,
	[futureint] [int] NULL,
	[futurevarchar] [varchar](250) NULL,
	[futuredatetime] [datetime] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[Accountable] [datetime] NULL,
	[SubDePartmentID] [int] NULL,
 CONSTRAINT [PK_aGodown] PRIMARY KEY NONCLUSTERED 
(
	[GodownID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_581017251] ON [dbo].[aGodown] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losSpecialInvoiceDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSpecialInvoiceDetail](
	[idInvoiceId] [int] NOT NULL,
	[idGodownID] [int] NOT NULL,
	[idItemid] [int] NOT NULL,
	[idShopid] [int] NOT NULL,
	[locationid] [int] NOT NULL,
	[shipmentid] [int] NOT NULL,
	[idPackingTypeid] [int] NOT NULL,
	[idPunitID] [int] NULL,
	[IDPquantity] [numeric](18, 3) NULL,
	[idQuantity] [numeric](18, 3) NULL,
	[idUnitPrice] [numeric](18, 8) NULL,
	[idRateType] [int] NULL,
	[idActualUnitPrice] [numeric](18, 2) NULL,
	[reqqty] [numeric](18, 3) NULL,
	[despatch] [bit] NOT NULL,
	[idcostprice] [numeric](18, 2) NULL,
	[iddescription] [varchar](250) NULL,
	[idblockprice] [numeric](18, 2) NULL,
	[idguarantee] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[idFreeQuantity] [numeric](18, 3) NULL,
	[idSerialNo] [varchar](50) NULL,
	[idItemType] [varchar](10) NULL,
	[idKitID] [int] NOT NULL,
	[idKitQuantity] [numeric](18, 2) NULL,
	[idKitActualPrice] [numeric](18, 2) NULL,
	[idServWarrantyUpto] [datetime] NULL,
	[idPartsWarrantyUpto] [datetime] NULL,
	[idItemTaxPercentage] [numeric](18, 2) NULL,
	[idItemTaxAmount] [numeric](18, 8) NULL,
	[idItemTaxCategory] [int] NULL,
 CONSTRAINT [PK_losSpecialInvoiceDetail] PRIMARY KEY NONCLUSTERED 
(
	[idInvoiceId] ASC,
	[idGodownID] ASC,
	[idItemid] ASC,
	[idShopid] ASC,
	[locationid] ASC,
	[shipmentid] ASC,
	[idKitID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1090102924] ON [dbo].[losSpecialInvoiceDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_losspecialinvoicedetail] ON [dbo].[losSpecialInvoiceDetail] 
(
	[idInvoiceId] ASC,
	[idShopid] ASC,
	[idRateType] 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
/****** Object:  Table [dbo].[losApartmentAgreementHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losApartmentAgreementHeader](
	[mghCompanyId] [int] NOT NULL,
	[mghShopId] [int] NOT NULL,
	[mghAgreementid] [int] NOT NULL,
	[mghAgreementno] [varchar](50) NULL,
	[mghAgreementDate] [datetime] NULL,
	[mghApartmentId] [int] NOT NULL,
	[mghApartmentIncharge] [int] NOT NULL,
	[mghcontactpersonname] [varchar](250) NULL,
	[mghcontactphoneno] [varchar](100) NULL,
	[mghleaseendingdate] [datetime] NULL,
	[mghleasecommencingdate] [datetime] NULL,
	[mghrentlastdate] [datetime] NULL,
	[mghleasestatus] [char](1) NULL,
	[mghelectricityreadingstart] [numeric](18, 3) NULL,
	[mghelectricityreadingend] [numeric](18, 3) NULL,
	[mghwaterreadingstart] [numeric](18, 3) NULL,
	[mghwaterreadingend] [numeric](18, 3) NULL,
	[mghsecurittyamount] [numeric](18, 2) NULL,
	[mghdiscount] [numeric](18, 2) NULL,
	[mghmodeofpayment] [char](1) NULL,
	[mghRemarks] [varchar](250) NULL,
	[mghCancelled] [bit] NULL,
	[mghCancelledRemarks] [varchar](250) NULL,
	[mghUpdateTime] [datetime] NULL,
	[mghDepartmentid] [int] NULL,
	[mghReservationID] [int] NULL,
	[mghExchangeRate] [numeric](18, 8) NULL,
	[mghDepExRate] [numeric](18, 8) NULL,
	[mghAccountId] [int] NULL,
	[mghNoOfDetails] [int] NULL,
	[mghPosted] [bit] NOT NULL,
	[mghChequeNo] [varchar](50) NULL,
	[mghChequeDate] [datetime] NULL,
	[mghExchangeRates] [varchar](250) NULL,
	[mghAdavanceAccID] [int] NULL,
	[mghRateDetailId] [int] NULL,
	[mghApartmentRate] [numeric](18, 2) NULL,
	[mghadvdate] [datetime] NULL,
 CONSTRAINT [pk_losApartmentAgreementHeader] PRIMARY KEY CLUSTERED 
(
	[mghCompanyId] ASC,
	[mghShopId] ASC,
	[mghAgreementid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losApartmentBillHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losApartmentBillHeader](
	[abhBillId] [int] NOT NULL,
	[abhSHopID] [int] NOT NULL,
	[abhCompanyid] [int] NOT NULL,
	[abhBillNo] [varchar](50) NULL,
	[abhApartmentId] [int] NULL,
	[abhAgreementId] [int] NULL,
	[abhCustomerId] [int] NULL,
	[abhCashAccId] [int] NULL,
	[abhFromDate] [datetime] NULL,
	[abhToDate] [datetime] NULL,
	[abhRate] [numeric](18, 2) NULL,
	[abhAmount] [numeric](18, 2) NULL,
	[abhOtherCharges] [numeric](18, 2) NULL,
	[abhTax] [numeric](18, 2) NULL,
	[abdDepositReturn] [numeric](18, 2) NULL,
	[abhDepExRate] [numeric](18, 8) NULL,
	[abhExRate] [numeric](18, 8) NULL,
	[abhRemarks] [varchar](250) NULL,
	[abhCancelledRemarks] [varchar](250) NULL,
	[abhCancelled] [bit] NULL,
	[abhPosted] [bit] NULL,
	[abhDepartmentid] [int] NOT NULL,
	[abhUpdateTime] [datetime] NULL,
	[abhBillDate] [datetime] NULL,
	[abhSalesAccID] [int] NULL,
	[abhOCAccID] [int] NULL,
	[abhExRates] [varchar](250) NULL,
	[abhDueDate] [datetime] NULL,
	[abhReferenceNo] [varchar](50) NULL,
	[abhSettledAmount] [numeric](18, 2) NULL,
	[abhSettled] [bit] NOT NULL,
	[abhPeriod] [numeric](18, 2) NULL,
	[abhUserID] [int] NULL,
 CONSTRAINT [pk_losApartmentBillHeader] PRIMARY KEY CLUSTERED 
(
	[abhBillId] ASC,
	[abhSHopID] ASC,
	[abhCompanyid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LosDummyReceiptDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LosDummyReceiptDetail](
	[drdShopID] [int] NOT NULL,
	[drdid] [int] NOT NULL,
	[drdDetailid] [int] NOT NULL,
	[drdcompanyid] [int] NULL,
	[drdinvoiceid] [int] NULL,
	[drdsplinvoiceid] [int] NULL,
	[drdserviceinvoiceid] [int] NULL,
	[drdbookserinvoiceid] [int] NULL,
	[drddcnid] [int] NULL,
	[drdinvoiceamount] [numeric](18, 2) NULL,
	[drdsettledamount] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[drdUtilityBillID] [int] NULL,
	[drdRoomBillID] [int] NULL,
	[drdaccInvoiceID] [int] NULL,
	[drdFineid] [int] NULL,
	[drdfandbInvoiceID] [int] NULL,
 CONSTRAINT [PK_LosDummyReceiptDetail] PRIMARY KEY NONCLUSTERED 
(
	[drdShopID] ASC,
	[drdid] ASC,
	[drdDetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_546100986] ON [dbo].[LosDummyReceiptDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Bills]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Bills](
	[BillsID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[BillsNo] [varchar](50) NOT NULL,
	[BillDate] [datetime] NOT NULL,
	[VendorID] [int] NULL,
	[BillAmount] [numeric](18, 2) NULL,
	[ReferenceNo] [varchar](250) NULL,
	[DuePeriod] [smallint] NULL,
	[Discount] [numeric](18, 2) NULL,
	[DiscountAccountID] [int] NULL,
	[FinancialID] [int] NULL,
	[CashPurchase] [bit] NOT NULL,
	[BankCashAccID] [int] NULL,
	[ChequeNo] [varchar](50) NULL,
	[ExchangeNature] [varchar](5) NULL,
	[Remarks] [varchar](250) NULL,
	[departmentid] [int] NULL,
	[Posted] [bit] NOT NULL,
	[Cancelled] [bit] NOT NULL,
	[CancelledRemarks] [varchar](250) NULL,
	[exchangerate] [numeric](18, 8) NULL,
	[vreferenceno] [varchar](250) NULL,
	[updatetime] [datetime] NOT NULL,
	[depexrate] [numeric](18, 8) NULL,
	[exchangerates] [varchar](250) NULL,
	[RefJournalID] [int] NULL,
	[subdepartmentid] [int] NULL,
	[RecurrenceDuePeriod] [int] NULL,
	[AutoGenerate] [bit] NOT NULL,
	[RemainderID] [int] NULL,
 CONSTRAINT [PK_Bills] PRIMARY KEY NONCLUSTERED 
(
	[BillsID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [ind_Bills_vendorid] ON [dbo].[Bills] 
(
	[VendorID] 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
/****** Object:  Table [dbo].[BillsDebitDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[BillsDebitDetails](
	[BillsID] [int] NOT NULL,
	[BillsDebitID] [int] NOT NULL,
	[AccountID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[Amount] [numeric](18, 2) NULL,
	[Remarks] [varchar](250) NULL,
 CONSTRAINT [PK_BillsDebitDetails] PRIMARY KEY NONCLUSTERED 
(
	[BillsID] ASC,
	[BillsDebitID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loaInhousePurchaseHeader]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loaInhousePurchaseHeader](
	[iphCompanyId] [int] NOT NULL,
	[iphDepartmentId] [int] NOT NULL,
	[iphFinancialId] [int] NOT NULL,
	[iphForShopId] [int] NULL,
	[iphForGodownid] [int] NULL,
	[iphId] [int] NOT NULL,
	[iphNo] [varchar](50) NOT NULL,
	[iphDate] [datetime] NOT NULL,
	[iphVendorId] [int] NULL,
	[iphVendorName] [varchar](100) NULL,
	[iphVendorAddress] [varchar](250) NULL,
	[iphRemarks] [nvarchar](250) NULL,
	[iphCancelRemark] [nvarchar](250) NULL,
	[iphUpdateTime] [datetime] NULL,
	[iphUserName] [varchar](50) NULL,
	[iphUpdatedUserName] [varchar](50) NULL,
	[iphCancel] [bit] NOT NULL,
 CONSTRAINT [PK_loaInhousePurchaseHeader] PRIMARY KEY CLUSTERED 
(
	[iphId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[hqInhousePurchaseBillingDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[hqInhousePurchaseBillingDetails](
	[ipbdBillId] [int] NULL,
	[ipbdBillDetailId] [int] NULL,
	[ipbdInhousePurchaseId] [int] NULL,
	[ipbdBilledAmount] [numeric](18, 2) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losSIQuotationHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSIQuotationHeader](
	[IhInvoiceID] [int] NOT NULL,
	[IhShopID] [int] NOT NULL,
	[IhInvoiceNo] [varchar](50) NULL,
	[IhInvoiceDate] [datetime] NULL,
	[IhReferenceNo] [varchar](50) NULL,
	[IhCustomerID] [int] NULL,
	[IhProforma] [bit] NOT NULL,
	[IhCashInvoice] [bit] NOT NULL,
	[IhBankcashAccID] [int] NULL,
	[IhChequeNo] [varchar](50) NULL,
	[IhDueDate] [datetime] NULL,
	[IhRemarks] [varchar](250) NULL,
	[IhInvoiceAmount] [numeric](18, 2) NULL,
	[IhDiscount] [numeric](18, 2) NULL,
	[IhDiscountAccID] [int] NULL,
	[IhDepartmentID] [int] NULL,
	[IhFinancialID] [int] NULL,
	[IhCancelled] [bit] NOT NULL,
	[IhCancelledRemarks] [varchar](250) NULL,
	[IhExchangeNature] [varchar](50) NULL,
	[IhCompanyId] [int] NULL,
	[IhPosted] [bit] NOT NULL,
	[IhProformaID] [int] NULL,
	[ihRecAddUser] [varchar](250) NULL,
	[ihRecModifyUser] [varchar](250) NULL,
	[ihGoodsReturned] [bit] NOT NULL,
	[ihUsed] [bit] NOT NULL,
	[IhSalesAccID] [int] NULL,
	[IhSettled] [bit] NOT NULL,
	[ihTransFinished] [bit] NOT NULL,
	[ihNoofDetails] [int] NOT NULL,
	[ihNoofOCDetails] [int] NOT NULL,
	[ihexchangerate] [numeric](28, 8) NOT NULL,
	[ihsettledamount] [numeric](18, 2) NULL,
	[ihcbid] [int] NULL,
	[ihfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[ihsalespersonid] [int] NULL,
	[ihCustomerCardNo] [varchar](100) NULL,
	[ihfutureint] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[ihdepexrate] [numeric](18, 8) NULL,
	[ihexchangerates] [varchar](250) NULL,
	[ihcreatedtime] [datetime] NULL,
	[ihInvoiced] [int] NULL,
	[ihAddress] [varchar](250) NULL,
	[ihCustomerName] [varchar](50) NULL,
	[ihUserId] [int] NULL,
	[ihModifyUserId] [int] NULL,
 CONSTRAINT [PK_losSIQuotationHeader] PRIMARY KEY NONCLUSTERED 
(
	[IhInvoiceID] ASC,
	[IhShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losPurchaseOrderHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losPurchaseOrderHeader](
	[pohPoid] [int] NOT NULL,
	[pohShopid] [int] NOT NULL,
	[pohpono] [varchar](50) NOT NULL,
	[pohnoSupwise] [varchar](50) NULL,
	[pohPodate] [datetime] NULL,
	[pohVendorID] [int] NULL,
	[pohSupAddr] [varchar](250) NULL,
	[pohdueDate] [datetime] NULL,
	[pohdeliveryaddr] [varchar](250) NULL,
	[pohcancel] [bit] NOT NULL,
	[pohcancelremarks] [varchar](250) NULL,
	[pohrecadduser] [varchar](50) NULL,
	[pohrecmoduser] [varchar](50) NULL,
	[pohbillgenerated] [bit] NOT NULL,
	[pohremarks] [varchar](250) NULL,
	[pohQuotation] [bit] NOT NULL,
	[pohValue] [numeric](18, 2) NULL,
	[pogenerated] [bit] NOT NULL,
	[pohpogenerated] [bit] NOT NULL,
	[pohQuotationid] [int] NULL,
	[pohCompanyID] [int] NULL,
	[pohExchangeRate] [int] NULL,
	[pohfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[pohdepexrate] [numeric](18, 8) NULL,
	[pohexchangerates] [varchar](250) NULL,
	[pohdiscount] [numeric](18, 2) NULL,
	[pohmodepayment] [varchar](50) NULL,
	[pohTime] [datetime] NULL,
	[pohPOclosed] [bit] NOT NULL,
	[poHQConfirmed] [int] NOT NULL,
	[pohExcludeGST] [bit] NULL,
 CONSTRAINT [PK_losPurchaseOrderHeader] PRIMARY KEY NONCLUSTERED 
(
	[pohPoid] ASC,
	[pohShopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_693577509] ON [dbo].[losPurchaseOrderHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosLocalPurchaseHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosLocalPurchaseHeader](
	[lphShopID] [int] NOT NULL,
	[lphBillID] [int] NOT NULL,
	[lphBillNo] [varchar](50) NULL,
	[lphVendorBillNo] [varchar](50) NULL,
	[lphBillDate] [datetime] NULL,
	[lphPOID] [int] NULL,
	[lphBillAmount] [numeric](18, 2) NULL,
	[lphDiscount] [numeric](18, 2) NULL,
	[lphDiscountAccID] [int] NULL,
	[lphDueDateforPayment] [datetime] NULL,
	[lphBankcashAccID] [int] NULL,
	[lphChequeNo] [varchar](25) NULL,
	[lphFinancialID] [int] NULL,
	[lphDepartmentID] [int] NULL,
	[lphRemarks] [varchar](100) NULL,
	[lphCashPurchase] [bit] NOT NULL,
	[lphExchangeNature] [varchar](5) NULL,
	[lphCancelled] [bit] NOT NULL,
	[lphCancelledRemarks] [varchar](250) NULL,
	[lphPosted] [bit] NOT NULL,
	[lphRecAddUser] [varchar](50) NULL,
	[lphRecModifyUser] [varchar](50) NULL,
	[lphCompanyID] [int] NULL,
	[lphUsed] [bit] NOT NULL,
	[lphVendorID] [int] NULL,
	[lphPurchaseAccID] [int] NULL,
	[lphAdjustmentAmount] [numeric](18, 2) NULL,
	[lphSettled] [bit] NOT NULL,
	[lphexchangerate] [numeric](18, 8) NULL,
	[lphcbid] [int] NULL,
	[lphcosted] [bit] NOT NULL,
	[lphfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[lphdepexrate] [numeric](18, 8) NULL,
	[lphexchangerates] [varchar](250) NULL,
	[lphBillTime] [datetime] NULL,
	[lphVendorInvoiceNo] [varchar](50) NULL,
	[lphConfirmed] [bit] NOT NULL,
	[lphUserID] [int] NULL,
	[lphExcludeGST] [bit] NULL,
 CONSTRAINT [PK_LosLocalPurchaseHeader] PRIMARY KEY NONCLUSTERED 
(
	[lphShopID] ASC,
	[lphBillID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_loslocalpurchaseheader_lphbilldate] ON [dbo].[LosLocalPurchaseHeader] 
(
	[lphBillDate] 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
CREATE NONCLUSTERED INDEX [ind_loslocalpurchaseheader_lphdepartmentid] ON [dbo].[LosLocalPurchaseHeader] 
(
	[lphDepartmentID] 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
CREATE NONCLUSTERED INDEX [ind_loslocalpurchaseheader_lphVendorID] ON [dbo].[LosLocalPurchaseHeader] 
(
	[lphVendorID] 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
CREATE UNIQUE NONCLUSTERED INDEX [index_1589580701] ON [dbo].[LosLocalPurchaseHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_loslocalpurchaseheader] ON [dbo].[LosLocalPurchaseHeader] 
(
	[lphBillID] ASC,
	[lphShopID] ASC,
	[lphCancelled] 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
/****** Object:  Table [dbo].[LOsPosHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsPosHeader](
	[poshShopID] [int] NOT NULL,
	[poshBillID] [int] NOT NULL,
	[poshBillNo] [varchar](50) NULL,
	[poshBillDate] [datetime] NULL,
	[poshCustomerName] [varchar](100) NULL,
	[poshCancelled] [bit] NOT NULL,
	[poshCancelledRemarks] [varchar](250) NULL,
	[poshRecAddUser] [varchar](50) NULL,
	[poshRecModifyUser] [varchar](50) NULL,
	[poshPosted] [bit] NOT NULL,
	[poshDiscount] [numeric](18, 2) NULL,
	[poshBillAmount] [numeric](18, 2) NULL,
	[poshCashAccID] [int] NULL,
	[poshSalesAccID] [int] NULL,
	[poshCompanyID] [int] NULL,
	[poshReturned] [bit] NOT NULL,
	[poshWholesale] [bit] NOT NULL,
	[poshcbid] [int] NULL,
	[poshExchangeRate] [numeric](28, 8) NOT NULL,
	[poshfuturevc] [varchar](250) NULL,
	[updatetime] [datetime] NOT NULL,
	[poshDepartmentid] [int] NULL,
	[poshsalespersonid] [int] NULL,
	[poshcustomerid] [int] NULL,
	[poshCustomerCardNo] [varchar](100) NULL,
	[poshfutureint] [int] NULL,
	[poshcurexrates] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[poshdepexrate] [numeric](18, 8) NULL,
	[poshexchangerates] [varchar](250) NULL,
	[poshUserId] [int] NULL,
	[poshCounterId] [int] NULL,
	[ContactCardNo] [varchar](50) NULL,
	[poshDiscountAmt] [numeric](18, 2) NULL,
	[poshBalance] [numeric](18, 2) NULL,
	[poshBillTime] [datetime] NULL,
	[poshDeliveryNeeded] [int] NULL,
	[poshChequeAccID] [int] NULL,
	[PosPostDate] [bit] NULL,
	[poshModifyUserId] [int] NULL,
	[poshCustomerTIN] [varchar](50) NULL,
 CONSTRAINT [PK_LOsPosHeader] PRIMARY KEY NONCLUSTERED 
(
	[poshShopID] ASC,
	[poshBillID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_losposheader_poshBilldate] ON [dbo].[LOsPosHeader] 
(
	[poshBillDate] 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
CREATE NONCLUSTERED INDEX [index_losposheader] ON [dbo].[LOsPosHeader] 
(
	[poshBillID] ASC,
	[poshShopID] ASC,
	[poshCancelled] 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
/****** Object:  Table [dbo].[losposExchangeHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losposExchangeHeader](
	[sehShopID] [int] NOT NULL,
	[sehExchangeID] [int] NOT NULL,
	[sehExchangeNo] [varchar](50) NULL,
	[sehExchangeDate] [datetime] NULL,
	[sehExchangerName] [varchar](100) NULL,
	[sehBillID] [int] NULL,
	[sehDiscount] [numeric](18, 2) NULL,
	[sehBillAmount] [numeric](18, 2) NULL,
	[sehExchangeBillAmount] [numeric](18, 2) NULL,
	[sehRemarks] [varchar](250) NULL,
	[sehCancelled] [bit] NOT NULL,
	[sehCancelledRemarks] [varchar](250) NULL,
	[sehPosted] [bit] NOT NULL,
	[sehRecAddUser] [varchar](50) NULL,
	[sehRecModifyUser] [varchar](50) NULL,
	[sehCashAccID] [int] NULL,
	[sehSalesAccID] [int] NULL,
	[sehCompanyID] [int] NULL,
	[sehFullyReturned] [bit] NOT NULL,
	[sehwholesale] [bit] NOT NULL,
	[sehcbid] [int] NULL,
	[sehExchangeRate] [numeric](28, 8) NOT NULL,
	[sehfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[sehExchangedBillID] [int] NULL,
	[sehDepartmentID] [int] NULL,
	[sehsalespersonid] [int] NULL,
	[sehCustomerCardNo] [varchar](100) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[sehdepexrate] [numeric](18, 8) NULL,
	[sehexchangerates] [varchar](250) NULL,
	[sehTime] [datetime] NULL,
	[sehUserID] [int] NULL,
 CONSTRAINT [PK_losposExchangeHeader] PRIMARY KEY NONCLUSTERED 
(
	[sehShopID] ASC,
	[sehExchangeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_losposexchangeheader_sehExchangeDate] ON [dbo].[losposExchangeHeader] 
(
	[sehExchangeDate] 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
CREATE UNIQUE NONCLUSTERED INDEX [index_978102525] ON [dbo].[losposExchangeHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_losposexchangeheader] ON [dbo].[losposExchangeHeader] 
(
	[sehExchangeID] ASC,
	[sehShopID] ASC,
	[sehCancelled] 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
/****** Object:  Table [dbo].[LOsPaymentVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsPaymentVoucherHeader](
	[phPaymentID] [int] NOT NULL,
	[phShopID] [int] NOT NULL,
	[phCompanyID] [int] NOT NULL,
	[phPaymentNo] [varchar](50) NOT NULL,
	[phPaymentDate] [datetime] NOT NULL,
	[phRemarks] [varchar](250) NULL,
	[phBankCashID] [int] NULL,
	[phPayee] [varchar](50) NULL,
	[phVendorID] [int] NULL,
	[phDepartmentID] [int] NULL,
	[phCustomerID] [int] NULL,
	[phChequeDetails] [varchar](50) NULL,
	[phPosted] [bit] NOT NULL,
	[phCancelled] [bit] NOT NULL,
	[phCancelledRemarks] [varchar](250) NULL,
	[phAmount] [numeric](18, 2) NULL,
	[phFinancialID] [int] NULL,
	[phExchangeNature] [varchar](50) NULL,
	[phcbreferenceno] [varchar](50) NULL,
	[phExchangeRate] [numeric](18, 8) NULL,
	[phcustomeramount] [numeric](18, 2) NULL,
	[phdebitaccountid] [int] NULL,
	[phdebitamount] [numeric](18, 2) NULL,
	[phchequedate] [datetime] NULL,
	[phcbid] [int] NULL,
	[phfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[phdepexrate] [numeric](18, 8) NULL,
	[phexchangerates] [varchar](250) NULL,
	[phUserID] [int] NULL,
 CONSTRAINT [PK_LOsPaymentVoucherHeader] PRIMARY KEY NONCLUSTERED 
(
	[phPaymentID] ASC,
	[phShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1605580758] ON [dbo].[LOsPaymentVoucherHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[discountdishdetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[discountdishdetails](
	[companyid] [int] NOT NULL,
	[discountid] [int] NOT NULL,
	[Outletid] [int] NOT NULL,
	[dishid] [int] NOT NULL,
	[discountper] [decimal](18, 2) NULL,
 CONSTRAINT [PK_discountdishitemdetails] PRIMARY KEY NONCLUSTERED 
(
	[companyid] ASC,
	[discountid] ASC,
	[Outletid] ASC,
	[dishid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ClearenceRequestHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ClearenceRequestHeader](
	[ShopID] [int] NOT NULL,
	[ClearenceReqID] [int] NOT NULL,
	[ClearenceReqNo] [varchar](50) NOT NULL,
	[ClearenceReqDate] [datetime] NULL,
	[CustomerID] [int] NULL,
	[CompanyID] [int] NULL,
	[POCurrencyID] [int] NULL,
	[VendorName] [varchar](250) NULL,
	[VendorAddress] [varchar](250) NULL,
	[PONo] [varchar](50) NULL,
	[PODate] [datetime] NULL,
	[DeliveryTo] [varchar](250) NULL,
	[DeliveryDate] [datetime] NULL,
	[ExpectedArrivalDate] [datetime] NULL,
	[EnteredBy] [varchar](50) NULL,
	[Remarks] [varchar](250) NULL,
	[Cancelled] [bit] NULL,
	[CancelledRemarks] [varchar](250) NULL,
 CONSTRAINT [pk_ClearenceRequestHeader] PRIMARY KEY CLUSTERED 
(
	[ShopID] ASC,
	[ClearenceReqID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ClearenceRequestDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ClearenceRequestDetail](
	[ShopID] [int] NOT NULL,
	[ClearenceReqID] [int] NOT NULL,
	[DetailID] [int] NOT NULL,
	[ItemDescription] [varchar](250) NULL,
	[Packing] [varchar](50) NULL,
	[Unit] [varchar](25) NULL,
	[Qty] [numeric](18, 3) NULL,
	[Amount] [numeric](18, 2) NULL,
	[Remarks] [varchar](250) NULL,
 CONSTRAINT [pk_ClearenceRequestDetail] PRIMARY KEY CLUSTERED 
(
	[ShopID] ASC,
	[ClearenceReqID] ASC,
	[DetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ShipmentClearenceItemDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ShipmentClearenceItemDetails](
	[ShopID] [int] NOT NULL,
	[ClearenceID] [int] NOT NULL,
	[DetailID] [int] NOT NULL,
	[ClearenceReqID] [int] NULL,
	[ClearenceDetailID] [int] NULL,
	[ItemDescription] [varchar](250) NULL,
	[Packing] [varchar](50) NULL,
	[Unit] [varchar](25) NULL,
	[Qty] [numeric](18, 3) NULL,
	[Amount] [numeric](18, 2) NULL,
	[NoofPackages] [numeric](18, 2) NULL,
	[Remarks] [varchar](250) NULL,
 CONSTRAINT [pk_ShipmentClearenceItemDetails] PRIMARY KEY CLUSTERED 
(
	[ShopID] ASC,
	[ClearenceID] ASC,
	[DetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[VendorSettlementHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[VendorSettlementHeader](
	[VSID] [int] NOT NULL,
	[CompanyID] [int] NULL,
	[VSNO] [varchar](50) NULL,
	[VSDate] [datetime] NULL,
	[DepartmentID] [int] NULL,
	[VendorID] [int] NULL,
	[PaymentID] [int] NULL,
	[dcnid] [int] NULL,
	[shopid] [int] NULL,
	[lospaymentid] [int] NULL,
	[losdcnid] [int] NULL,
	[Cancelled] [bit] NOT NULL,
	[CancelledRemarks] [varchar](250) NULL,
	[FinancialID] [int] NOT NULL,
	[Amount] [numeric](18, 2) NULL,
	[updatetime] [datetime] NOT NULL,
	[losshopdcnid] [int] NULL,
	[losexportid] [int] NULL,
	[SubDepartmentID] [int] NULL,
	[PReturnID] [int] NULL,
 CONSTRAINT [PK_VendorSettlementHeader] PRIMARY KEY NONCLUSTERED 
(
	[VSID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [ind_vendorsettlementheader_vsid] ON [dbo].[VendorSettlementHeader] 
(
	[VSID] 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
/****** Object:  Table [dbo].[aHQPaymentVoucherDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aHQPaymentVoucherDetails](
	[pdPaymentVoucherID] [int] NOT NULL,
	[pdPaymentID] [int] NOT NULL,
	[pdCompanyID] [int] NULL,
	[pdBillsID] [int] NULL,
	[pdAccBillsID] [int] NULL,
	[pdHQPOID] [int] NULL,
	[pdshopid] [int] NULL,
	[pdposlpbillid] [int] NULL,
	[pddcnid] [int] NULL,
	[pdPaidAmount] [numeric](18, 2) NULL,
	[pdDuePeriod] [smallint] NULL,
	[pdreceiptid] [int] NULL,
	[shopdcnid] [int] NULL,
	[pdIndevBillsID] [int] NULL,
 CONSTRAINT [PK_aHQPaymentVoucherDetails] PRIMARY KEY NONCLUSTERED 
(
	[pdPaymentVoucherID] ASC,
	[pdPaymentID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [ind_ahqpaymentvoucherdetails_pdBillsID] ON [dbo].[aHQPaymentVoucherDetails] 
(
	[pdBillsID] 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
CREATE NONCLUSTERED INDEX [ind_ahqpaymentvoucherdetails_pddcnid] ON [dbo].[aHQPaymentVoucherDetails] 
(
	[pddcnid] 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
CREATE NONCLUSTERED INDEX [ind_ahqpaymentvoucherdetails_pdposlpbillid] ON [dbo].[aHQPaymentVoucherDetails] 
(
	[pdposlpbillid] 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
CREATE NONCLUSTERED INDEX [ind_ahqpaymentvoucherdetails_pdshopid] ON [dbo].[aHQPaymentVoucherDetails] 
(
	[pdshopid] 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
CREATE NONCLUSTERED INDEX [ind_ahqpaymentvoucherdetails_shopdcnid] ON [dbo].[aHQPaymentVoucherDetails] 
(
	[shopdcnid] 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
/****** Object:  Table [dbo].[VendorSettlementDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[VendorSettlementDetail](
	[VSID] [int] NOT NULL,
	[VSDetailID] [int] NOT NULL,
	[CompanyID] [int] NULL,
	[BillID] [int] NULL,
	[pbhbillid] [int] NULL,
	[dcnid] [int] NULL,
	[shopid] [int] NULL,
	[lphbillid] [int] NULL,
	[losdcnid] [int] NULL,
	[BillAmount] [numeric](18, 2) NULL,
	[SettlementAmount] [numeric](18, 2) NULL,
	[receiptid] [int] NULL,
	[InterdivBillID] [int] NULL,
 CONSTRAINT [PK_VendorSettlementDetail] PRIMARY KEY NONCLUSTERED 
(
	[VSID] ASC,
	[VSDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [ind_vendorsettlementdetail_dcnid] ON [dbo].[VendorSettlementDetail] 
(
	[dcnid] 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
CREATE NONCLUSTERED INDEX [ind_vendorsettlementdetail_losdcnid] ON [dbo].[VendorSettlementDetail] 
(
	[losdcnid] 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
CREATE NONCLUSTERED INDEX [ind_vendorsettlementdetail_lphbillid] ON [dbo].[VendorSettlementDetail] 
(
	[lphbillid] 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
CREATE NONCLUSTERED INDEX [ind_vendorsettlementdetail_pbhbillid] ON [dbo].[VendorSettlementDetail] 
(
	[pbhbillid] 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
CREATE NONCLUSTERED INDEX [ind_vendorsettlementdetail_receiptid] ON [dbo].[VendorSettlementDetail] 
(
	[receiptid] 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
CREATE NONCLUSTERED INDEX [ind_vendorsettlementdetail_shopid] ON [dbo].[VendorSettlementDetail] 
(
	[shopid] 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
CREATE NONCLUSTERED INDEX [ind_vendorsettlementdetail_vsid] ON [dbo].[VendorSettlementDetail] 
(
	[VSID] 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
/****** Object:  Table [dbo].[loaInhousePurchaseDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loaInhousePurchaseDetail](
	[ipdid] [int] NOT NULL,
	[ipddetailId] [int] NOT NULL,
	[ipdItemCode] [varchar](50) NULL,
	[ipdItemDescription] [varchar](250) NULL,
	[ipdQuantity] [numeric](18, 3) NOT NULL,
	[ipdRate] [numeric](18, 2) NOT NULL,
	[ipdDiscountAmount] [numeric](18, 2) NOT NULL,
	[ipdAmount] [numeric](18, 2) NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOUsers]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOUsers](
	[UserID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[UserName] [varchar](250) NULL,
	[UserPwd] [varchar](50) NULL,
	[FullName] [varchar](250) NULL,
	[ShopID] [int] NULL,
	[GodownID] [int] NULL,
	[logedon] [bit] NULL,
	[GlobalUserID] [int] NULL,
	[ShiftId] [int] NULL,
	[userGroupId] [int] NULL,
	[EmailID] [varchar](50) NULL,
 CONSTRAINT [PK_LOUsers] PRIMARY KEY NONCLUSTERED 
(
	[UserID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [unique_userid_companyid_shopid_Godownid ] ON [dbo].[LOUsers] 
(
	[UserID] ASC,
	[CompanyID] ASC,
	[ShopID] ASC,
	[GodownID] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOUserRights]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOUserRights](
	[UserID] [int] NOT NULL,
	[ModuleCode] [varchar](10) NULL,
	[InterfaceID] [int] NOT NULL,
	[FunctionRights] [varchar](10) NULL,
	[CompanyID] [int] NOT NULL,
 CONSTRAINT [PK_LOUserRights] PRIMARY KEY NONCLUSTERED 
(
	[UserID] ASC,
	[InterfaceID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TillHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TillHeader](
	[till_th_tillid] [int] NOT NULL,
	[till_th_tillname] [varchar](50) NOT NULL,
	[till_th_outletid] [int] NOT NULL,
	[till_th_companyid] [int] NOT NULL,
	[till_th_statusid] [int] NULL,
	[till_th_remarks] [varchar](250) NULL,
	[till_th_active] [bit] NULL,
	[till_th_starttime] [datetime] NULL,
	[till_th_endtime] [datetime] NULL,
	[till_th_cashierid] [int] NULL,
 CONSTRAINT [PK_TillHeader] PRIMARY KEY CLUSTERED 
(
	[till_th_tillid] ASC,
	[till_th_outletid] ASC,
	[till_th_companyid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [Unique_TllHeaderName] UNIQUE NONCLUSTERED 
(
	[till_th_tillname] ASC,
	[till_th_outletid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TillHistory]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TillHistory](
	[till_hist_id] [int] NOT NULL,
	[till_id] [int] NOT NULL,
	[till_cashierid] [int] NULL,
	[till_starttime] [datetime] NULL,
	[till_endtime] [datetime] NULL,
	[till_outletid] [int] NOT NULL,
	[till_statusid] [int] NOT NULL,
	[till_companyid] [int] NOT NULL,
	[till_updatettime] [datetime] NOT NULL,
	[till_statusremarks] [varchar](2000) NOT NULL,
	[till_managerid] [int] NULL,
	[till_createmodify_user] [int] NULL,
	[till_no] [int] NULL,
	[till_fandbbillno] [int] NULL,
 CONSTRAINT [PK_TillHistory] PRIMARY KEY CLUSTERED 
(
	[till_hist_id] ASC,
	[till_outletid] ASC,
	[till_companyid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[MEmessages]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MEmessages](
	[fromUserID] [int] NULL,
	[toUserID] [int] NULL,
	[msgDateTime] [datetime] NULL,
	[Subject] [varchar](500) NULL,
	[Body] [varchar](1000) NULL,
	[unread] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_645577338] ON [dbo].[MEmessages] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOaCostingHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOaCostingHeader](
	[chCostingID] [int] NOT NULL,
	[chCostingNo] [varchar](50) NOT NULL,
	[chCostingDate] [datetime] NULL,
	[chBillID] [int] NOT NULL,
	[chRemarks] [varchar](250) NULL,
	[chCostingDone] [bit] NOT NULL,
	[chCostingDoneBy] [varchar](100) NULL,
	[chInventoryaccid] [int] NULL,
	[chGoodsinTransitaccid] [int] NULL,
	[chPosted] [bit] NOT NULL,
	[chCancelled] [bit] NOT NULL,
	[chCancelledRemarks] [varchar](250) NULL,
	[chRecAddUser] [varchar](50) NULL,
	[chRecModifyUser] [varchar](50) NULL,
	[chDepartmentID] [int] NULL,
	[chCompanyID] [int] NULL,
	[updatetime] [datetime] NOT NULL,
	[chSubDepartmentID] [int] NULL,
	[chtime] [datetime] NULL,
 CONSTRAINT [PK_LOaCostingHeader] PRIMARY KEY NONCLUSTERED 
(
	[chCostingID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOaCostingDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOaCostingDetail](
	[cdCostingID] [int] NOT NULL,
	[cdItemID] [int] NOT NULL,
	[cdCostingValue] [numeric](18, 2) NOT NULL,
	[cdCostingPrice] [numeric](28, 16) NULL,
	[cdItemQuantity] [numeric](18, 3) NULL,
	[cdBillUnitPrice] [numeric](28, 16) NULL,
	[cdCustomsUnitPrice] [numeric](18, 8) NULL,
	[cdCustomDutyAmount] [numeric](18, 2) NULL,
	[cdOCPerItem] [numeric](28, 22) NULL,
	[cdOldItemCostPrice] [numeric](18, 8) NULL,
	[cdNewItemCostPrice] [numeric](18, 8) NULL,
	[cdcustcategoryperc] [numeric](18, 2) NULL,
 CONSTRAINT [PK_LOaCostingDetail] PRIMARY KEY NONCLUSTERED 
(
	[cdCostingID] ASC,
	[cdItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOiArrivalHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOiArrivalHeader](
	[ahArrivalID] [int] NOT NULL,
	[ahArrivalNo] [varchar](50) NOT NULL,
	[ahArrivalDate] [datetime] NULL,
	[ahDespatchNoteID] [int] NOT NULL,
	[ahGodownID] [int] NULL,
	[ahShopID] [int] NULL,
	[ahShipmentID] [int] NULL,
	[ahCancelled] [bit] NOT NULL,
	[ahCancelledRemarks] [varchar](250) NULL,
	[ahRemarks] [varchar](250) NULL,
	[ahRecaddUser] [varchar](250) NULL,
	[ahRecmodifyUser] [varchar](250) NULL,
	[ahArrivalType] [char](1) NULL,
	[ahCostPriceFixed] [bit] NOT NULL,
	[ahLocalGodownID] [int] NOT NULL,
	[ahTransFinished] [bit] NOT NULL,
	[ahfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[ahposted] [bit] NOT NULL,
	[ahdepartmentid] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[ahconexrate] [numeric](18, 8) NULL,
	[ahdepexrate] [numeric](18, 8) NULL,
	[ahexchangerates] [varchar](250) NULL,
	[ahcreatedtime] [datetime] NULL,
 CONSTRAINT [PK_LOiArrivalHeader] PRIMARY KEY NONCLUSTERED 
(
	[ahArrivalID] ASC,
	[ahLocalGodownID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LoiItemSplitHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LoiItemSplitHeader](
	[ishgodownid] [int] NOT NULL,
	[ishid] [int] NOT NULL,
	[ishno] [varchar](50) NULL,
	[ishdate] [datetime] NULL,
	[ishremarks] [varchar](250) NULL,
	[ishSplititemid] [int] NULL,
	[ishsplititemqty] [numeric](18, 3) NULL,
	[ishshipmentid] [int] NULL,
	[ishactualqty] [numeric](18, 3) NULL,
	[ishCostPriceFixed] [bit] NOT NULL,
	[ishcancelled] [bit] NOT NULL,
	[ishcancelledremarks] [varchar](250) NULL,
	[ishRecAddUser] [varchar](250) NULL,
	[ishRecModifyUser] [varchar](250) NULL,
	[ishExpiryDate] [datetime] NULL,
	[ishfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[ishArrivalID] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[ishconexrate] [numeric](18, 8) NULL,
	[ishdepexrate] [numeric](18, 8) NULL,
	[ishexchangerates] [varchar](250) NULL,
 CONSTRAINT [PK_LoiItemSplitHeader] PRIMARY KEY NONCLUSTERED 
(
	[ishgodownid] ASC,
	[ishid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1429580131] ON [dbo].[LoiItemSplitHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[loaItemsplitcostingHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loaItemsplitcostingHeader](
	[scfhcompanyid] [int] NOT NULL,
	[scfhid] [int] NOT NULL,
	[scfhNo] [varchar](50) NOT NULL,
	[scfhDate] [datetime] NULL,
	[scfhCostingId] [int] NULL,
	[scfhGodownid] [int] NULL,
	[scfhItemSplitId] [int] NULL,
	[scfhShipmentid] [int] NULL,
	[scfhQuantity] [numeric](18, 3) NULL,
	[scfhCostedPrice] [numeric](18, 2) NULL,
	[scfhRemarks] [varchar](250) NULL,
	[scfhCostFixed] [bit] NOT NULL,
	[scfhCancelled] [bit] NOT NULL,
	[scfhCancelledRemarks] [varchar](250) NULL,
	[scfhdepartmentid] [int] NULL,
	[scfhCreated] [varchar](250) NULL,
	[scfhModified] [varchar](250) NULL,
	[scfhTime] [datetime] NULL,
 CONSTRAINT [PK_loaItemsplitcostingHeader] PRIMARY KEY NONCLUSTERED 
(
	[scfhid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOaCostingAccountDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOaCostingAccountDetails](
	[cadCostingID] [int] NOT NULL,
	[cadAccountID] [int] NOT NULL,
	[cadDetailID] [int] NOT NULL,
	[cadDescription] [varchar](250) NULL,
	[cadAmount] [numeric](18, 2) NOT NULL,
	[cadBankCashAccID] [int] NULL,
	[cadChequeNo] [varchar](50) NULL,
	[cadChequeDate] [datetime] NULL,
	[cadCompanyID] [int] NULL,
	[cadDistribution] [varchar](4000) NULL,
	[cadOtherCharges] [bit] NOT NULL,
	[cadCostingType] [varchar](5) NULL,
 CONSTRAINT [PK_LOaCostingAccountDetails] PRIMARY KEY NONCLUSTERED 
(
	[cadCostingID] ASC,
	[cadAccountID] ASC,
	[cadDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aStatus]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aStatus](
	[CompanyId] [int] NOT NULL,
	[StatusId] [int] NOT NULL,
	[StatusName] [nvarchar](50) NOT NULL,
	[StatusDesc] [nvarchar](500) NULL,
	[StatusGroupId] [int] NOT NULL,
 CONSTRAINT [PK_aStatus] PRIMARY KEY CLUSTERED 
(
	[CompanyId] ASC,
	[StatusId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LoilocationGroup]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LoilocationGroup](
	[Lgcompanyid] [int] NOT NULL,
	[Lggroupid] [int] NOT NULL,
	[Lggodownid] [int] NOT NULL,
	[LgGroupName] [varchar](100) NULL,
 CONSTRAINT [pk_loilocationgroup] PRIMARY KEY CLUSTERED 
(
	[Lgcompanyid] ASC,
	[Lggroupid] ASC,
	[Lggodownid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOiLocation]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOiLocation](
	[lGodownID] [int] NOT NULL,
	[lLocationID] [int] NOT NULL,
	[lLocationCode] [varchar](50) NOT NULL,
	[lLocationName] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[lgroupid] [int] NULL,
	[lcompanyid] [int] NULL,
 CONSTRAINT [PK_iLoacation] PRIMARY KEY NONCLUSTERED 
(
	[lGodownID] ASC,
	[lLocationID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1509580416] ON [dbo].[LOiLocation] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOiGodownShopArrivalToLocation]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOiGodownShopArrivalToLocation](
	[gsalArrivalID] [int] NOT NULL,
	[gsalShipmentID] [int] NOT NULL,
	[gsalItemID] [int] NOT NULL,
	[gsalLocationID] [int] NOT NULL,
	[gsalGoodQty] [numeric](18, 3) NULL,
	[gsalBadQty] [numeric](18, 3) NULL,
	[gsalGodownID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LOiGodownShopArrivalToLocation] PRIMARY KEY NONCLUSTERED 
(
	[gsalArrivalID] ASC,
	[gsalShipmentID] ASC,
	[gsalItemID] ASC,
	[gsalLocationID] ASC,
	[gsalGodownID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1653580929] ON [dbo].[LOiGodownShopArrivalToLocation] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOiArrivalDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOiArrivalDetail](
	[adArrivalID] [int] NOT NULL,
	[adItemID] [int] NOT NULL,
	[adPackingTypeID] [int] NULL,
	[adDespatchedQty] [numeric](18, 3) NULL,
	[adReceivedQty] [numeric](18, 3) NULL,
	[adCostPrice] [numeric](18, 2) NOT NULL,
	[adGodownID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LOiArrivalDetail] PRIMARY KEY NONCLUSTERED 
(
	[adArrivalID] ASC,
	[adItemID] ASC,
	[adGodownID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1589580701] ON [dbo].[LOiArrivalDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOiArrivalShipmentDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOiArrivalShipmentDetail](
	[asdArrivalID] [int] NOT NULL,
	[asdItemID] [int] NOT NULL,
	[asdShipmentID] [int] NOT NULL,
	[asdDespatchedGoodQty] [numeric](18, 3) NULL,
	[asdDespatchedBadQty] [numeric](18, 3) NULL,
	[asdReceivedGoodQty] [numeric](18, 3) NULL,
	[asdReceivedBadQty] [numeric](18, 3) NULL,
	[asdcostprice] [numeric](18, 2) NULL,
	[asdGodownID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LOiArrivalShipmentDetail] PRIMARY KEY NONCLUSTERED 
(
	[asdArrivalID] ASC,
	[asdItemID] ASC,
	[asdShipmentID] ASC,
	[asdGodownID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1605580758] ON [dbo].[LOiArrivalShipmentDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOiArrivaltoLocation]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOiArrivaltoLocation](
	[alArrivalID] [int] NOT NULL,
	[alLocationID] [int] NOT NULL,
	[alItemID] [int] NOT NULL,
	[alQty] [numeric](18, 3) NULL,
	[alGodownID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LOiArrivaltoLocation] PRIMARY KEY NONCLUSTERED 
(
	[alArrivalID] ASC,
	[alLocationID] ASC,
	[alItemID] ASC,
	[alGodownID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1621580815] ON [dbo].[LOiArrivaltoLocation] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LoslocationGroup]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LoslocationGroup](
	[Lgcompanyid] [int] NOT NULL,
	[Lggroupid] [int] NOT NULL,
	[Lgshopid] [int] NOT NULL,
	[LgGroupName] [varchar](100) NULL,
 CONSTRAINT [pk_loslocationgroup] PRIMARY KEY CLUSTERED 
(
	[Lgcompanyid] ASC,
	[Lggroupid] ASC,
	[Lgshopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loslocation]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loslocation](
	[lshopiD] [int] NOT NULL,
	[lLocationID] [int] NOT NULL,
	[lLocationCode] [varchar](50) NULL,
	[lLocationName] [varchar](250) NULL,
	[lgroupid] [int] NOT NULL,
	[lcompanyid] [int] NOT NULL,
 CONSTRAINT [PK_loslocation] PRIMARY KEY NONCLUSTERED 
(
	[lshopiD] ASC,
	[lLocationID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loslocationarrivaldetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[loslocationarrivaldetails](
	[ladinterfaceid] [int] NOT NULL,
	[ladshopid] [int] NOT NULL,
	[ladtransid] [int] NOT NULL,
	[laddetailid] [int] NOT NULL,
	[ladlocationid] [int] NULL,
	[laditemid] [int] NULL,
	[laditemqty] [numeric](18, 3) NULL,
	[ladpackingtypeid] [int] NULL,
	[ladpakingqty] [numeric](18, 3) NULL,
	[ladcancel] [bit] NOT NULL,
	[ladadjustment] [bit] NOT NULL,
	[ladfreeqty] [numeric](18, 3) NULL,
	[ladconfirmed] [int] NOT NULL,
 CONSTRAINT [PK_loslocationarrivaldetails] PRIMARY KEY NONCLUSTERED 
(
	[ladinterfaceid] ASC,
	[ladshopid] ASC,
	[ladtransid] ASC,
	[laddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[loslocationissuedetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[loslocationissuedetails](
	[lidinterfaceid] [int] NOT NULL,
	[lidshopid] [int] NOT NULL,
	[lidtransid] [int] NOT NULL,
	[liddetailid] [int] NOT NULL,
	[lidlocationid] [int] NULL,
	[liditemid] [int] NULL,
	[liditemqty] [numeric](18, 3) NULL,
	[lidpackingtypeid] [int] NULL,
	[lidpakingqty] [numeric](18, 3) NULL,
	[lidcancel] [bit] NOT NULL,
	[lidadjustment] [bit] NOT NULL,
	[lidfreeqty] [numeric](18, 3) NULL,
	[lidconfirmed] [int] NOT NULL,
 CONSTRAINT [PK_loslocationissuedetails] PRIMARY KEY NONCLUSTERED 
(
	[lidinterfaceid] ASC,
	[lidshopid] ASC,
	[lidtransid] ASC,
	[liddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOiDamageClearingHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOiDamageClearingHeader](
	[dchClearingID] [int] NOT NULL,
	[dchGodownid] [int] NOT NULL,
	[dchClearingNO] [varchar](50) NOT NULL,
	[dchClearingDate] [datetime] NULL,
	[dchClearingDoneBY] [varchar](50) NULL,
	[dchRemarks] [varchar](250) NULL,
	[dchCancelled] [bit] NOT NULL,
	[dchCancelledRemarks] [varchar](250) NULL,
	[dchRecAddUser] [varchar](50) NULL,
	[dchRecModifyUser] [varchar](50) NULL,
	[dchfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[dchconexrate] [numeric](18, 8) NULL,
	[dchdepexrate] [numeric](18, 8) NULL,
	[dchexchangerates] [varchar](250) NULL,
	[dchcreatetime] [datetime] NULL,
 CONSTRAINT [PK_LOiDamageClearingHeader] PRIMARY KEY NONCLUSTERED 
(
	[dchClearingID] ASC,
	[dchGodownid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1493580359] ON [dbo].[LOiDamageClearingHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOiDamageClearingDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOiDamageClearingDetails](
	[dcdClearingID] [int] NOT NULL,
	[dcdLocationID] [int] NULL,
	[dcdShipmentID] [int] NOT NULL,
	[dcdItemID] [int] NOT NULL,
	[dcdAvailableQty] [numeric](18, 3) NULL,
	[dcdWriteOffQty] [numeric](18, 3) NULL,
	[dcdGodownid] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LOiDamageClearingDetail] PRIMARY KEY CLUSTERED 
(
	[dcdClearingID] ASC,
	[dcdShipmentID] ASC,
	[dcdItemID] ASC,
	[dcdGodownid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1637580872] ON [dbo].[LOiDamageClearingDetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aHPItemTransferDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aHPItemTransferDetail](
	[itdCompanyID] [int] NOT NULL,
	[itdFinancialID] [int] NOT NULL,
	[itdTransferID] [int] NOT NULL,
	[itdTransferDetailID] [int] NOT NULL,
	[itdItemRegID] [int] NOT NULL,
	[itdCurrentLocation] [nvarchar](50) NULL,
	[itdTransLocation] [nvarchar](50) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOsWriteOffHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsWriteOffHeader](
	[whShopID] [int] NOT NULL,
	[WhID] [int] NOT NULL,
	[WhNo] [varchar](50) NULL,
	[WhDate] [datetime] NULL,
	[WhUserName] [varchar](50) NULL,
	[WhCancelled] [bit] NOT NULL,
	[WhCancelledRemarks] [varchar](250) NULL,
	[WhRemarks] [varchar](250) NULL,
	[WhRecAddUser] [varchar](250) NULL,
	[WhRecModifyUser] [varchar](250) NULL,
	[Whfuturevc] [varchar](250) NOT NULL,
	[whposted] [bit] NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[whdepartmentid] [int] NULL,
	[whconexrate] [numeric](18, 8) NULL,
	[whdepexrate] [numeric](18, 8) NULL,
	[whexchangerates] [varchar](250) NULL,
	[whotherdepid] [int] NULL,
	[whreceivedby] [varchar](100) NULL,
	[whauthorisedby] [varchar](100) NULL,
	[whtype] [char](1) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[whexpenseaccid] [int] NULL,
	[whapartmentid] [int] NULL,
	[whdoneby] [varchar](150) NULL,
	[whApprovedby] [varchar](20) NULL,
	[whApprovedid] [int] NULL,
	[whIhCRequestID] [int] NULL,
	[whIssuedby] [varchar](150) NULL,
	[whIssuedid] [int] NULL,
	[whReceivedid] [int] NULL,
	[whtodepexrate] [numeric](18, 9) NULL,
	[whVerifiedby] [varchar](20) NULL,
	[whverifiedid] [int] NULL,
	[whVerified] [bit] NOT NULL,
 CONSTRAINT [PK_LOsWriteOffHeader] PRIMARY KEY NONCLUSTERED 
(
	[whShopID] ASC,
	[WhID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_loswriteoffheader_whdate] ON [dbo].[LOsWriteOffHeader] 
(
	[WhDate] 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
CREATE NONCLUSTERED INDEX [index_loswriteoffheader] ON [dbo].[LOsWriteOffHeader] 
(
	[WhID] ASC,
	[whShopID] ASC,
	[WhCancelled] 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
/****** Object:  Table [dbo].[LOs_InHouseCons_ReturnHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOs_InHouseCons_ReturnHeader](
	[IHRHShopID] [int] NOT NULL,
	[IHRHID] [int] NOT NULL,
	[IHRHNo] [varchar](50) NULL,
	[IHRHDate] [datetime] NULL,
	[IHRHReferenceid] [int] NOT NULL,
	[IHRHRemarks] [varchar](250) NULL,
	[IHRHCancelled] [bit] NOT NULL,
	[IHRHCancelledRemarks] [varchar](250) NULL,
	[IHRHposted] [bit] NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[IHRHdepartmentid] [int] NULL,
	[IHRHconexrate] [numeric](18, 8) NULL,
	[IHRHdepexrate] [numeric](18, 8) NULL,
	[IHRHexchangerates] [varchar](250) NULL,
	[IHRHotherdepid] [int] NULL,
	[IHRHtodepexrate] [numeric](18, 9) NULL,
	[IHRHexpenseaccid] [int] NULL,
	[IHRHapartmentid] [int] NULL,
	[IHRHUserId] [int] NOT NULL,
	[IHRHModifiedUserId] [int] NULL,
	[IHRHConfirmed] [bit] NULL,
	[IHRHConfirmedUSerID] [int] NULL,
 CONSTRAINT [PK_LOs_InHouseCons_ReturnHeader] PRIMARY KEY CLUSTERED 
(
	[IHRHShopID] ASC,
	[IHRHID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOs_InHouseCons_ReturnDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOs_InHouseCons_ReturnDetail](
	[IHRDShopID] [int] NOT NULL,
	[IHRDID] [int] NOT NULL,
	[IHRDDetailid] [int] NOT NULL,
	[IHRDItemID] [int] NOT NULL,
	[IHRDShipmentID] [int] NOT NULL,
	[IHRDArrivedQty] [numeric](18, 3) NOT NULL,
	[IHRDArrivedPQty] [numeric](18, 3) NOT NULL,
	[IHRDPackID] [int] NULL,
	[IHRDunitID] [int] NULL,
	[IHRDReturnedPqty] [numeric](18, 2) NOT NULL,
	[IHRDReturnedQty] [numeric](18, 2) NOT NULL,
	[IHRDcostprice] [numeric](18, 2) NULL,
	[IHRDInhouseConsAccnt] [int] NULL,
	[IHRDRetrnOrExch] [varchar](1) NULL,
 CONSTRAINT [PK_LOs_InHouseCons_ReturnDetail] PRIMARY KEY CLUSTERED 
(
	[IHRDShopID] ASC,
	[IHRDID] ASC,
	[IHRDDetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losposExchangeDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losposExchangeDetail](
	[sedShopID] [int] NOT NULL,
	[sedExchangeID] [int] NOT NULL,
	[sedExchangedetailID] [int] NOT NULL,
	[sedItemID] [int] NOT NULL,
	[sedPackingTypeID] [int] NOT NULL,
	[sedPUnitID] [int] NULL,
	[sedPQuantity] [numeric](18, 3) NULL,
	[sedQuantity] [numeric](18, 3) NULL,
	[sedUnitPrice] [numeric](18, 2) NULL,
	[sedActualUnitPrice] [numeric](18, 2) NULL,
	[sedExchangePQty] [numeric](18, 2) NULL,
	[sedExchangeQty] [numeric](18, 2) NULL,
	[sedRateType] [int] NOT NULL,
	[sedBillorExchange] [char](1) NULL,
	[sedcostprice] [numeric](18, 2) NULL,
	[sedblockprice] [numeric](18, 2) NULL,
	[sedguarantee] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[sedSerialNo] [varchar](50) NULL,
	[sedFreeQty] [numeric](18, 3) NULL,
	[sedExcFreeQty] [numeric](18, 3) NULL,
	[sedItemTaxPercentage] [numeric](18, 2) NULL,
	[sedItemTaxAmount] [numeric](18, 2) NULL,
	[sedItemTaxCategory] [int] NULL,
	[SedServWarrantyUpto] [datetime] NULL,
	[SedPartsWarrantyUpto] [datetime] NULL,
 CONSTRAINT [PK_losposExchangeDetail] PRIMARY KEY NONCLUSTERED 
(
	[sedShopID] ASC,
	[sedExchangeID] ASC,
	[sedExchangedetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1410104064] ON [dbo].[losposExchangeDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_losposexchangedetail] ON [dbo].[losposExchangeDetail] 
(
	[sedExchangeID] ASC,
	[sedShopID] ASC,
	[sedBillorExchange] ASC,
	[sedExchangeQty] 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
/****** Object:  Table [dbo].[losposExchangeSubItemDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losposExchangeSubItemDetails](
	[seidShopID] [int] NOT NULL,
	[seidExchangeID] [int] NOT NULL,
	[seidExchangeDetailID] [int] NOT NULL,
	[seidItemID] [int] NOT NULL,
	[seidSubItemID] [int] NOT NULL,
	[seidPackingTypeID] [int] NOT NULL,
	[seidPQuantity] [numeric](18, 3) NULL,
	[seidQuantity] [numeric](18, 3) NULL,
	[seidUnitPrice] [numeric](18, 2) NULL,
	[seidAmount] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_losposExchangeSubItemDetails] PRIMARY KEY NONCLUSTERED 
(
	[seidShopID] ASC,
	[seidExchangeID] ASC,
	[seidExchangeDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_626101271] ON [dbo].[losposExchangeSubItemDetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losposExchangeOtherCharges]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losposExchangeOtherCharges](
	[seoShopID] [int] NOT NULL,
	[seoExchangeID] [int] NOT NULL,
	[seoAccID] [int] NOT NULL,
	[seoDescription] [varchar](250) NULL,
	[seoAmount] [numeric](18, 2) NULL,
	[seoCompanyID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_losposExchangeOtherCharges] PRIMARY KEY NONCLUSTERED 
(
	[seoShopID] ASC,
	[seoExchangeID] ASC,
	[seoAccID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_610101214] ON [dbo].[losposExchangeOtherCharges] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losPurchaseOrderDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losPurchaseOrderDetail](
	[podPoid] [int] NOT NULL,
	[poditemid] [int] NOT NULL,
	[podShopid] [int] NOT NULL,
	[podQty] [numeric](18, 3) NULL,
	[podUnitPrice] [numeric](18, 8) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[podActualAmt] [numeric](18, 8) NULL,
	[podpackid] [int] NULL,
	[podItemTaxPercentage] [numeric](18, 2) NULL,
	[podItemTaxAmount] [numeric](18, 8) NULL,
	[podItemTaxCategory] [int] NULL,
	[podpackqty] [numeric](18, 3) NULL,
 CONSTRAINT [PK_losPurchaseOrderDetail] PRIMARY KEY NONCLUSTERED 
(
	[podPoid] ASC,
	[poditemid] ASC,
	[podShopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_677577452] ON [dbo].[losPurchaseOrderDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losrebaterequest]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losrebaterequest](
	[rrshopid] [int] NOT NULL,
	[rrreqid] [int] NOT NULL,
	[rrreqno] [varchar](50) NULL,
	[rrreqdate] [datetime] NULL,
	[rrpoid] [int] NULL,
	[rrsalespersonid] [int] NULL,
	[rrremarks] [varchar](250) NULL,
	[rrtoapprovebefore] [datetime] NULL,
	[rrcancelled] [bit] NOT NULL,
	[rrcancelledremarks] [varchar](250) NULL,
	[rrRebatePerson] [varchar](100) NULL,
	[rrreqTIME] [datetime] NULL,
 CONSTRAINT [PK_losrebaterequest] PRIMARY KEY NONCLUSTERED 
(
	[rrshopid] ASC,
	[rrreqid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losrebateconfirmheader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losrebateconfirmheader](
	[rcshopid] [int] NOT NULL,
	[rcapprovedid] [int] NOT NULL,
	[rcapprovedno] [varchar](50) NULL,
	[rcapproveddate] [datetime] NULL,
	[rcreqid] [int] NULL,
	[rcapprovedby] [varchar](50) NULL,
	[rcremarks] [varchar](250) NULL,
	[rccancelled] [bit] NOT NULL,
	[rccancelledremarks] [varchar](250) NULL,
	[rcCustomerSalesMargin] [numeric](18, 2) NULL,
	[rcRebatePerson] [varchar](100) NULL,
 CONSTRAINT [PK_losrebateconfirmheader] PRIMARY KEY NONCLUSTERED 
(
	[rcshopid] ASC,
	[rcapprovedid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOiWriteOffHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOiWriteOffHeader](
	[whGodownID] [int] NOT NULL,
	[whID] [int] NOT NULL,
	[whNo] [varchar](50) NULL,
	[whDate] [datetime] NULL,
	[whUserName] [varchar](250) NULL,
	[whCancelled] [bit] NOT NULL,
	[whCancelledRemarks] [varchar](250) NULL,
	[whRemarks] [varchar](250) NOT NULL,
	[whRecaddUser] [varchar](250) NULL,
	[whRecmodifyUser] [varchar](250) NULL,
	[whposted] [bit] NOT NULL,
	[whfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[whdepartmentid] [int] NULL,
	[whSelected] [bit] NULL,
	[whtransfinished] [bit] NULL,
	[whNoofDetails] [int] NULL,
	[whtype] [char](1) NULL,
	[whconexrate] [numeric](18, 8) NULL,
	[whdepexrate] [numeric](18, 8) NULL,
	[whexchangerates] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[whTime] [datetime] NULL,
	[whcreatedtime] [datetime] NULL,
 CONSTRAINT [PK_LOiWriteOffHeader] PRIMARY KEY NONCLUSTERED 
(
	[whGodownID] ASC,
	[whID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOiWriteOffDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOiWriteOffDetail](
	[wdID] [int] NOT NULL,
	[wdGodownID] [int] NOT NULL,
	[wdLocationID] [int] NULL,
	[wdShipmentID] [int] NOT NULL,
	[wdItemID] [int] NOT NULL,
	[wdAvailableQty] [numeric](18, 3) NULL,
	[wdWriteoffQty] [numeric](18, 3) NULL,
	[wdcostprice] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LOiWriteOffDetail] PRIMARY KEY CLUSTERED 
(
	[wdID] ASC,
	[wdGodownID] ASC,
	[wdShipmentID] ASC,
	[wdItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1285579618] ON [dbo].[LOiWriteOffDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[FixedAsset]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[FixedAsset](
	[FixedAssetID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[FixedAssetDate] [datetime] NULL,
	[PurchaseDate] [datetime] NULL,
	[InsPolicyNo] [varchar](50) NULL,
	[Location] [varchar](50) NULL,
	[VendorID] [int] NULL,
	[CostPrice] [numeric](18, 2) NULL,
	[Remarks] [varchar](1000) NULL,
	[DepartmentID] [int] NULL,
	[Insured] [char](1) NULL,
	[InsuredAmount] [numeric](18, 2) NULL,
	[Premium] [numeric](18, 2) NULL,
	[DepreciatedValue] [numeric](18, 2) NULL,
	[DepType] [char](1) NULL,
	[DepreciationAccId] [int] NULL,
	[FixedAssetAccID] [int] NULL,
	[depreciationperiod] [char](1) NULL,
	[depreciationpercent] [numeric](5, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[initialDepreciatedValue] [numeric](18, 2) NULL,
	[billsrefid] [int] NULL,
	[assetcode] [varchar](50) NULL,
	[assetname] [varchar](100) NULL,
	[writeoffrefid] [int] NULL,
	[godownrefid] [int] NULL,
	[conversiondiffaccid] [int] NULL,
	[conversiondiff] [numeric](18, 2) NULL,
	[disposed] [bit] NULL,
	[FAGroup] [varchar](100) NULL,
	[Quantity] [int] NULL,
	[depcalcstartdate] [datetime] NULL,
	[FAType] [varchar](10) NULL,
	[exrate] [numeric](18, 8) NULL,
	[depexrate] [numeric](18, 8) NULL,
	[exchangerates] [varchar](250) NULL,
	[actrefamount] [numeric](18, 2) NULL,
	[posted] [bit] NULL,
	[financialid] [int] NULL,
	[FixedAssetNo] [varchar](50) NULL,
	[depriciationexpaccid] [int] NULL,
	[Cancelled] [bit] NULL,
	[CurrentDepartmentId] [int] NULL,
	[lasttoaccid] [int] NULL,
	[ExcludeFirstPeriodDep] [bit] NULL,
	[InsuranceRenewalDate] [datetime] NULL,
	[CurrDeprecExpAccID] [int] NULL,
	[CurrAccDepExpAccID] [int] NULL,
	[SubDepartmentID] [int] NULL,
 CONSTRAINT [PK_FixedAsset] PRIMARY KEY NONCLUSTERED 
(
	[FixedAssetID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_485576768] ON [dbo].[FixedAsset] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losInvoiceProjectRequestDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losInvoiceProjectRequestDetails](
	[idrInvoiceId] [int] NOT NULL,
	[idrShopId] [int] NOT NULL,
	[idrCompanyId] [int] NOT NULL,
	[idrPlanNo] [varchar](100) NULL,
	[idrRefNo] [varchar](100) NULL,
	[idrNature] [varchar](50) NULL,
	[idrProjectStartDate] [datetime] NULL,
	[idrProjectEndDate] [datetime] NULL,
	[idrOtherInfo] [varchar](1000) NULL,
	[idrCustomDutyByCustomer] [bit] NULL,
	[idrTransportation] [varchar](50) NULL,
 CONSTRAINT [PK_losInvoiceProjectRequestDetails] PRIMARY KEY NONCLUSTERED 
(
	[idrInvoiceId] ASC,
	[idrShopId] ASC,
	[idrCompanyId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losEDIRequest]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losEDIRequest](
	[ershopid] [int] NOT NULL,
	[erediid] [int] NOT NULL,
	[eredino] [varchar](50) NULL,
	[eredidate] [datetime] NULL,
	[erreferenceno] [varchar](50) NULL,
	[erpoid] [int] NULL,
	[ersentby] [varchar](100) NULL,
	[erremarks] [varchar](250) NULL,
	[ercancelled] [bit] NOT NULL,
	[ercancelledremarks] [varchar](250) NULL,
 CONSTRAINT [PK_losEDIRequest] PRIMARY KEY NONCLUSTERED 
(
	[ershopid] ASC,
	[erediid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOsInvoiceDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsInvoiceDetail](
	[idShopID] [int] NOT NULL,
	[idInvoiceID] [int] NOT NULL,
	[idItemID] [int] NOT NULL,
	[idPackingTypeID] [int] NOT NULL,
	[idPUnitID] [int] NULL,
	[idPQuantity] [numeric](18, 3) NULL,
	[idQuantity] [numeric](18, 3) NULL,
	[idUnitPrice] [numeric](18, 8) NULL,
	[idRateType] [numeric](18, 3) NULL,
	[idActualUnitPrice] [numeric](18, 2) NULL,
	[idcostprice] [numeric](18, 2) NULL,
	[iddescription] [varchar](1000) NULL,
	[idblockprice] [numeric](18, 2) NULL,
	[idguarantee] [varchar](1000) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[idrebateamount] [numeric](18, 2) NULL,
	[idcorgin] [int] NULL,
	[idcconsignment] [int] NULL,
	[idcdcomcur] [numeric](18, 2) NULL,
	[idcdcustcur] [numeric](18, 2) NULL,
	[idcdcomcurtocustoms] [numeric](18, 2) NULL,
	[idcdcustcurtocustoms] [numeric](18, 2) NULL,
	[idDeclaredPrice] [numeric](20, 4) NULL,
	[idFreeQuantity] [numeric](18, 3) NULL,
	[idType] [varchar](5) NULL,
	[idSerialNo] [varchar](250) NULL,
	[idStatus] [varchar](250) NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD [idItemType] [varchar](10) NULL
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD [idKitID] [int] NOT NULL
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD [idKitQuantity] [numeric](18, 2) NULL
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD [idKitActualPrice] [numeric](18, 2) NULL
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD [idCustomPrice] [numeric](18, 2) NULL
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD [idServWarrantyUpto] [datetime] NULL
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD [idPartsWarrantyUpto] [datetime] NULL
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD [idItemTaxPercentage] [numeric](18, 2) NULL
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD [idItemTaxAmount] [numeric](18, 8) NULL
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD [idItemTaxCategory] [int] NULL
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD [idBillDetailID] [int] NULL
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD  CONSTRAINT [PK_losInvoiceDetail] PRIMARY KEY NONCLUSTERED 
(
	[idShopID] ASC,
	[idInvoiceID] ASC,
	[idItemID] ASC,
	[idPackingTypeID] ASC,
	[idKitID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_882102183] ON [dbo].[LOsInvoiceDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_losinvoicedetail] ON [dbo].[LOsInvoiceDetail] 
(
	[idInvoiceID] ASC,
	[idShopID] 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
/****** Object:  Table [dbo].[LOsInvoiceOC]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsInvoiceOC](
	[ioShopID] [int] NOT NULL,
	[ioInvoiceID] [int] NOT NULL,
	[ioAccID] [int] NULL,
	[ioDescription] [varchar](250) NOT NULL,
	[ioAmount] [numeric](18, 2) NULL,
	[ioCompanyid] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[ioServTaxCateID] [int] NULL,
	[ioServTaxPerc] [numeric](18, 2) NULL,
	[ioServTaxRate] [numeric](18, 2) NULL,
	[ioServTaxAmount] [numeric](18, 2) NULL,
 CONSTRAINT [pk_losInvoiceOC] PRIMARY KEY CLUSTERED 
(
	[ioShopID] ASC,
	[ioInvoiceID] ASC,
	[ioDescription] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1909581841] ON [dbo].[LOsInvoiceOC] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosDeliveryNoteHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosDeliveryNoteHeader](
	[DnShopid] [int] NOT NULL,
	[DndnId] [int] NOT NULL,
	[DndnNo] [varchar](50) NULL,
	[DndnDate] [datetime] NULL,
	[DnCustomerID] [int] NULL,
	[DnDeliveredBy] [varchar](100) NULL,
	[DnVesselName] [varchar](100) NULL,
	[DnRegistryNo] [varchar](50) NULL,
	[DnReceivedBY] [varchar](100) NULL,
	[DnRemarks] [varchar](500) NULL,
	[Dncancelled] [bit] NOT NULL,
	[DnCancelledRemarks] [varchar](250) NULL,
	[DnDeliveryTime] [datetime] NULL,
	[dnCustomerName] [nvarchar](100) NULL,
	[dnContactNumber] [nvarchar](50) NULL,
	[dnCustomerAddress1] [nvarchar](100) NULL,
	[dnCustomerAddress2] [nvarchar](100) NULL,
	[dnCustomerAddress3] [nvarchar](100) NULL,
	[dnDeliveryAddress1] [nvarchar](100) NULL,
	[dnDeliveryAddress2] [nvarchar](100) NULL,
	[dnDeliveryAddress3] [nvarchar](100) NULL,
	[dnCompanyId] [int] NULL,
	[dnStatus] [int] NULL,
	[dnConfirmed] [bit] NULL,
	[DnDeliveryType] [varchar](20) NULL,
 CONSTRAINT [PK_LosDeliveryNoteHeader] PRIMARY KEY NONCLUSTERED 
(
	[DnShopid] ASC,
	[DndnId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LosDeliveryNoteDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LosDeliveryNoteDetail](
	[DnDShopid] [int] NOT NULL,
	[DnDdnId] [int] NOT NULL,
	[DnDetailId] [int] NOT NULL,
	[DnDinvoiceId] [int] NULL,
	[dndBillID] [int] NULL,
 CONSTRAINT [PK_LosDeliveryNoteDetail] PRIMARY KEY NONCLUSTERED 
(
	[DnDShopid] ASC,
	[DnDdnId] ASC,
	[DnDetailId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losDeliveryVerificationDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losDeliveryVerificationDetails](
	[CompanyId] [int] NOT NULL,
	[ShopId] [int] NOT NULL,
	[DeliveryVerificationId] [int] NOT NULL,
	[SlNo] [int] NULL,
	[BillId] [int] NULL,
	[InvoiceId] [int] NULL,
	[ItemId] [int] NOT NULL,
	[PackId] [int] NOT NULL,
	[PackQty] [numeric](18, 3) NOT NULL,
	[Qty] [numeric](18, 3) NOT NULL,
	[FinancialYearId] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOsReceiptVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsReceiptVoucherHeader](
	[rhReceiptID] [int] NOT NULL,
	[rhShopID] [int] NOT NULL,
	[rhReceiptNo] [varchar](50) NOT NULL,
	[rhReceiptDate] [datetime] NOT NULL,
	[rhCustomerID] [int] NULL,
	[rhVendorID] [int] NULL,
	[rhDepartmentID] [int] NULL,
	[rhBankCashAccountID] [int] NOT NULL,
	[rhReceivedFrom] [varchar](50) NULL,
	[rhRemarks] [varchar](250) NULL,
	[rhChequeDetails] [varchar](250) NULL,
	[rhReferenceNo] [varchar](50) NULL,
	[rhReferenceDate] [datetime] NULL,
	[rhPosted] [bit] NOT NULL,
	[rhCancelled] [bit] NOT NULL,
	[rhCancelledRemarks] [varchar](250) NULL,
	[rhAmount] [numeric](18, 2) NULL,
	[rhFinancialID] [int] NULL,
	[rhExchangeNature] [varchar](50) NULL,
	[rhRecAddUser] [varchar](50) NULL,
	[rhRecModifyUser] [varchar](50) NULL,
	[rhCompanyID] [int] NULL,
	[rhcbreferenceno] [varchar](50) NULL,
	[rhExchangeRate] [numeric](18, 8) NULL,
	[rhReceiptType] [varchar](50) NULL,
	[rhcustomeramount] [numeric](18, 2) NULL,
	[rhdebitaccountid] [int] NULL,
	[rhdebitamount] [numeric](18, 2) NULL,
	[rhchequedate] [datetime] NULL,
	[rhfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LOsReceiptVoucherHeader] PRIMARY KEY NONCLUSTERED 
(
	[rhReceiptID] ASC,
	[rhShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1653580929] ON [dbo].[LOsReceiptVoucherHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOsReceiptVoucherDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOsReceiptVoucherDetails](
	[rdReceiptDetailID] [int] NOT NULL,
	[rdReceiptID] [int] NOT NULL,
	[rdShopID] [int] NOT NULL,
	[rdAccountsInvoiceID] [int] NULL,
	[rdInvoiceID] [int] NULL,
	[rdSpecialInvoiceID] [int] NULL,
	[rdAmountReceived] [numeric](18, 2) NULL,
	[rdDuePeriod] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LOsReceiptVoucherDetails] PRIMARY KEY NONCLUSTERED 
(
	[rdReceiptDetailID] ASC,
	[rdReceiptID] ASC,
	[rdShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_66099276] ON [dbo].[LOsReceiptVoucherDetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losDeliveryDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losDeliveryDetails](
	[CompanyId] [int] NOT NULL,
	[ShopId] [int] NOT NULL,
	[CashInvoiceId] [int] NULL,
	[CreditInvoiceId] [int] NULL,
	[CustomerName] [nvarchar](200) NULL,
	[ContactNumber] [nvarchar](100) NULL,
	[CustomerAddress1] [nvarchar](200) NULL,
	[CustomerAddress2] [nvarchar](200) NULL,
	[CustomerAddress3] [nvarchar](200) NULL,
	[DeliveryAddress1] [nvarchar](200) NULL,
	[DeliveryAddress2] [nvarchar](200) NULL,
	[DeliveryAddress3] [nvarchar](200) NULL,
	[DeliveryDate] [datetime] NULL,
	[DeliveryTime] [datetime] NULL,
	[DeliveryRemarks] [nvarchar](500) NULL,
	[DeliveryAddressIsSame] [bit] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosInvoiceST]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosInvoiceST](
	[ioSTShopID] [int] NOT NULL,
	[ioSTInvoiceID] [int] NOT NULL,
	[ioSTCompanyID] [int] NOT NULL,
	[ioSTLocation] [varchar](250) NULL,
	[ioSTShippingService] [varchar](250) NULL,
	[ioSTETA] [varchar](250) NULL,
	[ioSTUSAForwarding] [numeric](18, 2) NULL,
	[ioSTFreightAndHandling] [numeric](18, 2) NULL,
	[ioSTInsurance] [numeric](18, 2) NULL,
	[ioSTCustomDuty] [numeric](18, 2) NULL,
	[ioSTHandling] [numeric](18, 2) NULL,
	[ioSTServiceCharge] [numeric](18, 2) NULL,
	[ioSTCustomPer] [numeric](18, 2) NULL,
	[ioSTServicePer] [numeric](18, 2) NULL,
 CONSTRAINT [PK_LosInvoiceST] PRIMARY KEY CLUSTERED 
(
	[ioSTShopID] ASC,
	[ioSTInvoiceID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOsInvoiceSubItemDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOsInvoiceSubItemDetail](
	[isdShopid] [int] NOT NULL,
	[isdinvoiceid] [int] NOT NULL,
	[isditemid] [int] NOT NULL,
	[isdsubitemid] [int] NOT NULL,
	[isdpackingtypeid] [int] NOT NULL,
	[isdpquantity] [numeric](18, 3) NULL,
	[isdquantity] [numeric](18, 3) NULL,
	[isdunitprice] [numeric](18, 2) NULL,
	[isdamount] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LOsInvoiceSubItemDetail] PRIMARY KEY NONCLUSTERED 
(
	[isdShopid] ASC,
	[isdinvoiceid] ASC,
	[isditemid] ASC,
	[isdsubitemid] ASC,
	[isdpackingtypeid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_2145546827] ON [dbo].[LOsInvoiceSubItemDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosKegReturnHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosKegReturnHeader](
	[krhShopid] [int] NOT NULL,
	[krhKegReturnID] [int] NOT NULL,
	[krhKegReturnNO] [varchar](50) NOT NULL,
	[krhKegReturnDate] [datetime] NOT NULL,
	[krhCustomerID] [int] NOT NULL,
	[krhRemarks] [varchar](250) NULL,
	[krhCancel] [bit] NOT NULL,
	[krhCancelledRemarks] [varchar](250) NULL,
	[krCompanyID] [int] NULL,
	[krhDepartmentid] [int] NULL,
	[updatetime] [datetime] NOT NULL,
	[krhExchangeRates] [varchar](250) NULL,
 CONSTRAINT [PK_LosKegReturnHeader] PRIMARY KEY NONCLUSTERED 
(
	[krhShopid] ASC,
	[krhKegReturnID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LosKegReturnDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosKegReturnDetail](
	[krDReturnNoteID] [int] NOT NULL,
	[krDItemID] [int] NOT NULL,
	[krDShopid] [int] NOT NULL,
	[krDInvoiceId] [int] NOT NULL,
	[krDQuantity] [numeric](18, 3) NULL,
	[krDDamaged] [bit] NOT NULL,
	[krDRemarks] [varchar](250) NULL,
	[krdCostPrice] [numeric](18, 2) NULL,
 CONSTRAINT [PK_LosKegReturnDetail] PRIMARY KEY CLUSTERED 
(
	[krDReturnNoteID] ASC,
	[krDItemID] ASC,
	[krDShopid] ASC,
	[krDInvoiceId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[mesRequesttoShopHeader]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[mesRequesttoShopHeader](
	[SRHshopid] [int] NOT NULL,
	[SRHrequestID] [int] NOT NULL,
	[SRHrequestNO] [varchar](50) NOT NULL,
	[SRHrequestdate] [datetime] NOT NULL,
	[SRHremarks] [varchar](250) NULL,
	[SRHcancelled] [bit] NOT NULL,
	[SRHcancelledRemarks] [varchar](250) NULL,
	[SRHrecadduser] [varchar](250) NULL,
	[SRHrecmoduser] [varchar](250) NULL,
	[SRHtoShopid] [int] NOT NULL,
	[SRHUsed] [bit] NOT NULL,
	[SRHTransfinished] [bit] NOT NULL,
	[SRHNoofDetails] [int] NOT NULL,
	[SRHfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[srhType] [varchar](5) NULL,
	[SRHrequestTime] [datetime] NULL,
 CONSTRAINT [PK_mesRequesttoShopHeader] PRIMARY KEY NONCLUSTERED 
(
	[SRHshopid] ASC,
	[SRHrequestID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[mesTransferOutHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[mesTransferOutHeader](
	[TOHid] [int] NOT NULL,
	[TOHShopid] [int] NOT NULL,
	[TOHtoShopid] [int] NULL,
	[TOHno] [varchar](50) NULL,
	[TOHdate] [datetime] NULL,
	[TOHremarks] [varchar](250) NULL,
	[TOHCancelled] [bit] NOT NULL,
	[TOHCancelledRemarks] [varchar](250) NULL,
	[TOHDoneby] [varchar](100) NULL,
	[TOHrequestid] [int] NULL,
	[TOhUsed] [bit] NOT NULL,
	[TOHTransfinished] [bit] NOT NULL,
	[TOHNoofDetails] [int] NOT NULL,
	[TOHfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[tohdepartmentid] [int] NULL,
	[tohposted] [bit] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[tohconexrate] [numeric](18, 8) NULL,
	[tohdepexrate] [numeric](18, 8) NULL,
	[tohexchangerates] [varchar](250) NULL,
	[tohType] [char](2) NULL,
	[TOHtime] [datetime] NULL,
	[tohrecadduser] [varchar](250) NULL,
	[tohrecmodifyuser] [varchar](250) NULL,
 CONSTRAINT [PK_mesTransferOutHeader] PRIMARY KEY NONCLUSTERED 
(
	[TOHid] ASC,
	[TOHShopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_mestransferoutheader_tohDate] ON [dbo].[mesTransferOutHeader] 
(
	[TOHdate] 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
CREATE UNIQUE NONCLUSTERED INDEX [index_482100758] ON [dbo].[mesTransferOutHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_mestransferoutheader] ON [dbo].[mesTransferOutHeader] 
(
	[TOHid] ASC,
	[TOHShopid] ASC,
	[TOHCancelled] ASC,
	[TOHTransfinished] 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
/****** Object:  Table [dbo].[mosGoodsRequestHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[mosGoodsRequestHeader](
	[GRHrequestID] [int] NOT NULL,
	[GRHshopID] [int] NOT NULL,
	[GRHrequestNO] [varchar](50) NOT NULL,
	[GRHrequestDate] [datetime] NOT NULL,
	[GRHcancel] [bit] NOT NULL,
	[GRHcancelRemarks] [varchar](250) NULL,
	[GRHrecAddUser] [varchar](50) NULL,
	[GRHrecModUser] [varchar](50) NULL,
	[GRHremarks] [varchar](250) NULL,
	[GRHIssuenotegenerated] [bit] NOT NULL,
	[grhSpecialRequest] [bit] NOT NULL,
	[grhTransFinished] [bit] NOT NULL,
	[grhNoofDetails] [int] NOT NULL,
	[grhfuturevc] [varchar](250) NOT NULL,
	[grhrequesttype] [char](10) NULL,
	[updatetime] [datetime] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[GRHrequestTime] [datetime] NULL,
	[grhhqrequestgenerated] [int] NULL,
 CONSTRAINT [PK_mosGoodsRequestHeader] PRIMARY KEY NONCLUSTERED 
(
	[GRHrequestID] ASC,
	[GRHshopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_917578307] ON [dbo].[mosGoodsRequestHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aHQIssueNoteMain]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHQIssueNoteMain](
	[INMIssuenoteID] [int] NOT NULL,
	[INMIssuenoteNO] [varchar](50) NULL,
	[INMIssuedate] [datetime] NOT NULL,
	[INMCancelledremarks] [varchar](250) NULL,
	[INMRemarks] [varchar](250) NULL,
	[INMRecadduser] [varchar](250) NULL,
	[INMModifyuser] [varchar](250) NULL,
	[INMCancel] [bit] NOT NULL,
	[INMRequestID] [int] NULL,
	[INMShopID] [int] NOT NULL,
	[futurevc] [varchar](250) NOT NULL,
	[departmentid] [int] NULL,
	[companyid] [int] NULL,
	[updatetime] [datetime] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[INMTime] [datetime] NULL,
 CONSTRAINT [PK_aHQIssueNoteMain] PRIMARY KEY NONCLUSTERED 
(
	[INMIssuenoteID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1061578820] ON [dbo].[aHQIssueNoteMain] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aHQIssuenoteHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHQIssuenoteHeader](
	[INHIssuenoteID] [int] NOT NULL,
	[INHissuenoteNO] [varchar](50) NULL,
	[INHIssuedate] [datetime] NULL,
	[INHGodownID] [int] NOT NULL,
	[INHCancelled] [bit] NOT NULL,
	[INHToshopID] [int] NULL,
	[INHTogodownID] [int] NULL,
	[INHUsed] [bit] NOT NULL,
	[INHIssuenotemainID] [int] NOT NULL,
	[INHTransFinished] [bit] NOT NULL,
	[INHNoofDetails] [int] NULL,
	[futurevc] [varchar](250) NOT NULL,
	[INHShopReqId] [int] NULL,
	[updatetime] [datetime] NOT NULL,
	[inhshopreqno] [varchar](100) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[INHIssuetime] [datetime] NULL,
 CONSTRAINT [PK_aHQIssuenoteHeader] PRIMARY KEY NONCLUSTERED 
(
	[INHIssuenoteID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[MEiDespatchToShopHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MEiDespatchToShopHeader](
	[dhDespatchID] [int] NOT NULL,
	[dhDespatchNo] [varchar](50) NULL,
	[dhGodownID] [int] NOT NULL,
	[dhDespatchDate] [datetime] NULL,
	[dhShopID] [int] NULL,
	[dhCarrier] [varchar](250) NULL,
	[dhIssueNoteID] [int] NULL,
	[dhVehicleNo] [varchar](50) NULL,
	[dhCancelled] [bit] NOT NULL,
	[dhCancelledRemarks] [varchar](250) NULL,
	[dhRemarks] [varchar](500) NULL,
	[dhRecaddUser] [varchar](250) NULL,
	[dhRecmodifyUser] [varchar](250) NULL,
	[dhSelected] [bit] NOT NULL,
	[dhTransFinished] [bit] NOT NULL,
	[dhNoofDetails] [int] NOT NULL,
	[dhShopReqid] [int] NULL,
	[dhfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[dhshopreqno] [varchar](100) NULL,
	[dhdepartmentid] [int] NULL,
	[dhposted] [bit] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[dhconexrate] [numeric](18, 8) NULL,
	[dhdepexrate] [numeric](18, 8) NULL,
	[dhexchangerates] [varchar](250) NULL,
	[dhDespatchTime] [datetime] NULL,
 CONSTRAINT [PK_MEiDespatchToShopHeader] PRIMARY KEY NONCLUSTERED 
(
	[dhDespatchID] ASC,
	[dhGodownID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1154103152] ON [dbo].[MEiDespatchToShopHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aHQDespatchNoteMain]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHQDespatchNoteMain](
	[dnmDespatchNoteID] [int] NOT NULL,
	[dnmDespatchNoteNo] [varchar](50) NULL,
	[dnmDespatchNoteDate] [datetime] NULL,
	[dnmBillID] [int] NOT NULL,
	[dnmCostPriceFixed] [bit] NOT NULL,
	[dnmRemarks] [varchar](250) NULL,
	[dnmCancelled] [bit] NOT NULL,
	[dnmCancelledRemarks] [varchar](250) NULL,
	[dnmrecAddUser] [varchar](250) NULL,
	[dnmrecModifyUser] [varchar](250) NULL,
	[Futurevc] [varchar](250) NOT NULL,
	[departmentid] [int] NULL,
	[companyid] [int] NULL,
	[updatetime] [datetime] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[dntime] [datetime] NULL,
 CONSTRAINT [PK_aHQDespatchNoteMain] PRIMARY KEY NONCLUSTERED 
(
	[dnmDespatchNoteID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1733581214] ON [dbo].[aHQDespatchNoteMain] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aHQDespatchnoteHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHQDespatchnoteHeader](
	[dhDespatchNoteMainID] [int] NOT NULL,
	[dhDespatchnoteID] [int] NOT NULL,
	[dhDespatchnoteNo] [varchar](250) NOT NULL,
	[dhGodownID] [int] NULL,
	[dhCancelled] [bit] NOT NULL,
	[dhShipmentID] [int] NULL,
	[dhSelected] [bit] NOT NULL,
	[barcodegenerated] [bit] NOT NULL,
	[dhTransFinished] [bit] NOT NULL,
	[dhNoofDetails] [int] NULL,
	[Futurevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[dhshopid] [int] NULL,
	[dhShopReqId] [int] NULL,
 CONSTRAINT [PK_aHQDespatchnoteHeader] PRIMARY KEY NONCLUSTERED 
(
	[dhDespatchnoteID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_245575913] ON [dbo].[aHQDespatchnoteHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOsGoodsArrivaltoShopHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsGoodsArrivaltoShopHeader](
	[gahArrivalID] [int] NOT NULL,
	[gahShopid] [int] NOT NULL,
	[gahArrivalNo] [varchar](50) NULL,
	[gahArrivalDate] [datetime] NULL,
	[gahGodownDespatchID] [int] NULL,
	[gahDespatchedGodownID] [int] NULL,
	[gahCancelled] [bit] NOT NULL,
	[gahCancelledRemarks] [varchar](50) NULL,
	[gahRecAddUser] [varchar](250) NULL,
	[gahRecModifyUser] [varchar](250) NULL,
	[gahremarks] [varchar](250) NULL,
	[gahTransFinished] [bit] NOT NULL,
	[gahfuturevc] [varchar](250) NOT NULL,
	[gahshopreqid] [int] NULL,
	[gahposted] [bit] NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[gahdepartmentid] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[gahhqdespatchid] [int] NULL,
	[gahconexrate] [numeric](18, 8) NULL,
	[gahdepexrate] [numeric](18, 8) NULL,
	[gahexchangerates] [varchar](250) NULL,
	[gahTime] [datetime] NULL,
 CONSTRAINT [PK_LOsGoodsArrivaltoShopHeader] PRIMARY KEY NONCLUSTERED 
(
	[gahArrivalID] ASC,
	[gahShopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_losgoodsarrivaltoshopheader_gaharrivaldate] ON [dbo].[LOsGoodsArrivaltoShopHeader] 
(
	[gahArrivalDate] 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
CREATE UNIQUE NONCLUSTERED INDEX [index_1378103950] ON [dbo].[LOsGoodsArrivaltoShopHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_losgoodsarrivaltoshopheader] ON [dbo].[LOsGoodsArrivaltoShopHeader] 
(
	[gahArrivalID] ASC,
	[gahShopid] ASC,
	[gahCancelled] ASC,
	[gahTransFinished] 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
/****** Object:  Table [dbo].[mesTransferOutArrivalDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[mesTransferOutArrivalDetail](
	[toaShopid] [int] NOT NULL,
	[toaTransOutId] [int] NOT NULL,
	[toaArrivalId] [int] NOT NULL,
 CONSTRAINT [PK_mesTransferOutArrivalDetail] PRIMARY KEY CLUSTERED 
(
	[toaShopid] ASC,
	[toaTransOutId] ASC,
	[toaArrivalId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[mesTransferoutDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[mesTransferoutDetail](
	[TODid] [int] NOT NULL,
	[TODshopid] [int] NOT NULL,
	[TODitemid] [int] NOT NULL,
	[TODshipmentid] [int] NOT NULL,
	[TODtoShopid] [int] NULL,
	[TODrequestedGoodqty] [numeric](18, 3) NULL,
	[TODissuedGoodQty] [numeric](18, 3) NULL,
	[TODrequestedBadQty] [numeric](18, 3) NULL,
	[TODissuedBadQty] [numeric](18, 3) NULL,
	[TODcostprice] [numeric](18, 2) NULL,
	[todSellingPrice] [numeric](18, 2) NULL,
	[packid] [int] NULL,
	[packqty] [numeric](18, 3) NULL,
 CONSTRAINT [PK_mesTransferoutDetail] PRIMARY KEY NONCLUSTERED 
(
	[TODid] ASC,
	[TODshopid] ASC,
	[TODitemid] ASC,
	[TODshipmentid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_mestransferoutdetail] ON [dbo].[mesTransferoutDetail] 
(
	[TODid] ASC,
	[TODshopid] 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
/****** Object:  Table [dbo].[LOSTransferinheader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOSTransferinheader](
	[TIHShopid] [int] NOT NULL,
	[TIHID] [int] NOT NULL,
	[TIHNO] [varchar](50) NOT NULL,
	[TIHDate] [datetime] NOT NULL,
	[TIHfromshopID] [int] NOT NULL,
	[TIHdespatchID] [int] NOT NULL,
	[TIHremarks] [varchar](250) NULL,
	[TIHcancel] [bit] NOT NULL,
	[TIHcancelledremarks] [varchar](250) NULL,
	[TIHDoneBy] [varchar](100) NULL,
	[TIHTransFinished] [bit] NOT NULL,
	[TIHPosted] [bit] NOT NULL,
	[TIHfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[tihdepartmentid] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[tihconexrate] [numeric](18, 8) NULL,
	[tihdepexrate] [numeric](18, 8) NULL,
	[tihexchangerates] [varchar](250) NULL,
	[TIHType] [char](2) NULL,
	[tihrecadduser] [varchar](250) NULL,
	[tihrecmodifyuser] [varchar](250) NULL,
	[tihTime] [datetime] NULL,
 CONSTRAINT [PK_LOSTransferinheader] PRIMARY KEY NONCLUSTERED 
(
	[TIHShopid] ASC,
	[TIHID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_lostransferinheader_tihdate] ON [dbo].[LOSTransferinheader] 
(
	[TIHDate] 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
CREATE UNIQUE NONCLUSTERED INDEX [index_1122103038] ON [dbo].[LOSTransferinheader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_lostransferinheader] ON [dbo].[LOSTransferinheader] 
(
	[TIHID] ASC,
	[TIHShopid] ASC,
	[TIHcancel] ASC,
	[TIHTransFinished] 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
/****** Object:  Table [dbo].[LOsShopDamageClearingHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsShopDamageClearingHeader](
	[dchClearingID] [int] NOT NULL,
	[dchShopid] [int] NOT NULL,
	[dchClearingNo] [varchar](50) NOT NULL,
	[dchClearingDate] [datetime] NULL,
	[dchClearingDoneBy] [varchar](50) NULL,
	[dchRemarks] [varchar](250) NULL,
	[dchCancelled] [bit] NOT NULL,
	[dchCancelledRemarks] [varchar](250) NULL,
	[dchRecAddUser] [varchar](50) NULL,
	[dchRecModifyUser] [varchar](50) NULL,
	[dchfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[dchconexrate] [numeric](18, 8) NULL,
	[dchdepexrate] [numeric](18, 8) NULL,
	[dchexchangerates] [varchar](250) NULL,
 CONSTRAINT [PK_LOsShopDamageClearingHeader] PRIMARY KEY NONCLUSTERED 
(
	[dchClearingID] ASC,
	[dchShopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_2021582240] ON [dbo].[LOsShopDamageClearingHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOsShopDamageClearingDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOsShopDamageClearingDetails](
	[dcdClearingID] [int] NOT NULL,
	[dcdShipmentID] [int] NOT NULL,
	[dcdItemID] [int] NOT NULL,
	[dcdShopid] [int] NOT NULL,
	[dcdAvailableQty] [numeric](18, 3) NULL,
	[dcdWriteOffQty] [numeric](18, 3) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LOsShopDamageClearingDetails] PRIMARY KEY NONCLUSTERED 
(
	[dcdClearingID] ASC,
	[dcdShipmentID] ASC,
	[dcdItemID] ASC,
	[dcdShopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_82099333] ON [dbo].[LOsShopDamageClearingDetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOsWriteOffDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOsWriteOffDetail](
	[wdShopID] [int] NOT NULL,
	[WdID] [int] NOT NULL,
	[WdItemID] [int] NOT NULL,
	[WdShipmentID] [int] NOT NULL,
	[WdAvailableQty] [numeric](18, 3) NULL,
	[WdWriteoffQty] [numeric](18, 3) NULL,
	[wdcostprice] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[WdPackID] [int] NULL,
	[WdunitID] [int] NULL,
	[WdPqty] [numeric](18, 2) NULL,
	[WdInhouseConsAccnt] [int] NULL,
	[wdDetailid] [int] NULL,
 CONSTRAINT [PK_LOsWriteOffDetail] PRIMARY KEY NONCLUSTERED 
(
	[wdShopID] ASC,
	[WdID] ASC,
	[WdItemID] ASC,
	[WdShipmentID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1173579219] ON [dbo].[LOsWriteOffDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_loswriteoffdetail] ON [dbo].[LOsWriteOffDetail] 
(
	[WdID] ASC,
	[wdShopID] 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
/****** Object:  Table [dbo].[aPrefix]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aPrefix](
	[CompanyID] [int] NOT NULL,
	[InterfaceID] [int] NOT NULL,
	[shopid] [int] NULL,
	[godownid] [int] NULL,
	[Prefix] [varchar](25) NOT NULL,
	[ModuleCode] [varchar](50) NULL,
	[departmentid] [int] NULL,
	[Financialid] [int] NULL,
 CONSTRAINT [IX_aPrefix] UNIQUE NONCLUSTERED 
(
	[CompanyID] ASC,
	[InterfaceID] ASC,
	[shopid] ASC,
	[godownid] ASC,
	[departmentid] ASC,
	[Financialid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aUserRights]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aUserRights](
	[UserID] [int] NOT NULL,
	[ModuleCode] [varchar](10) NULL,
	[InterfaceID] [int] NOT NULL,
	[FunctionRights] [varchar](10) NULL,
	[CompanyID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aUserRights] PRIMARY KEY NONCLUSTERED 
(
	[UserID] ASC,
	[InterfaceID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_2117582582] ON [dbo].[aUserRights] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[loiUserAuditHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loiUserAuditHeader](
	[ghCompanyId] [int] NOT NULL,
	[ghAuditId] [int] NOT NULL,
	[ghGodownId] [int] NOT NULL,
	[ghInterfaceId] [int] NOT NULL,
	[ghTransId] [int] NOT NULL,
	[ghTransNo] [varchar](250) NULL,
	[ghUserFullName] [varchar](250) NOT NULL,
	[ghLoggedDateTime] [datetime] NOT NULL,
	[ghExitedDateTime] [datetime] NOT NULL,
	[ghMode] [char](1) NOT NULL,
	[ghSaved] [bit] NOT NULL,
	[ghMachineName] [varchar](50) NULL,
	[ghWindowsUserName] [varchar](50) NULL,
 CONSTRAINT [PK_loiUserAuditHeader] PRIMARY KEY NONCLUSTERED 
(
	[ghCompanyId] ASC,
	[ghAuditId] ASC,
	[ghGodownId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOSTransferindetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOSTransferindetail](
	[TIDID] [int] NOT NULL,
	[TIDshopid] [int] NOT NULL,
	[TIDshipmentID] [int] NOT NULL,
	[TIDitemID] [int] NOT NULL,
	[TIDtransfergoodqty] [numeric](18, 3) NULL,
	[TIDtransferbadqty] [numeric](18, 3) NULL,
	[TIDrecievedgoodqty] [numeric](18, 3) NULL,
	[TIDrecievedbadqty] [numeric](18, 3) NULL,
	[TIDCostprice] [numeric](20, 4) NULL,
	[TIDSellingPrice] [numeric](20, 4) NULL,
 CONSTRAINT [PK_LOSTransferindetail] PRIMARY KEY NONCLUSTERED 
(
	[TIDID] ASC,
	[TIDshopid] ASC,
	[TIDshipmentID] ASC,
	[TIDitemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_lostransferindetail] ON [dbo].[LOSTransferindetail] 
(
	[TIDID] ASC,
	[TIDshopid] 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
/****** Object:  Table [dbo].[paPayAccLinkDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[paPayAccLinkDetails](
	[CompanyID] [int] NOT NULL,
	[TransID] [int] NOT NULL,
	[DetailID] [int] NOT NULL,
	[DepartmentID] [int] NOT NULL,
	[RefTransID] [int] NOT NULL,
	[RefTransNo] [varchar](50) NOT NULL,
	[RefTransType] [varchar](25) NOT NULL,
	[RefTransDate] [datetime] NOT NULL,
	[EmpID] [int] NOT NULL,
	[EmpName] [varchar](100) NOT NULL,
	[EmpNo] [varchar](100) NOT NULL,
	[AccountID] [int] NOT NULL,
	[AccountDesc] [varchar](250) NOT NULL,
	[TransCurrSymbol] [varchar](25) NOT NULL,
	[AccCurrSymbol] [varchar](25) NOT NULL,
	[TransCurrID] [varchar](25) NOT NULL,
	[AccCurrID] [varchar](25) NOT NULL,
	[RefTransAmount] [numeric](18, 2) NOT NULL,
	[AccountAmount] [numeric](18, 2) NOT NULL,
	[DeptAmount] [numeric](18, 2) NOT NULL,
	[CompAmount] [numeric](18, 2) NOT NULL,
	[Credit] [tinyint] NOT NULL,
 CONSTRAINT [pk_paPayAccLinkDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[TransID] ASC,
	[DetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[paPayAccLinkPostingDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[paPayAccLinkPostingDetails](
	[CompanyID] [int] NOT NULL,
	[TransID] [int] NOT NULL,
	[DetailID] [int] NOT NULL,
	[DepartmentID] [int] NOT NULL,
	[AccountID] [int] NOT NULL,
	[AccountDesc] [varchar](250) NOT NULL,
	[Description] [varchar](250) NOT NULL,
	[AccCurrID] [int] NOT NULL,
	[AccCurrSymbol] [varchar](25) NOT NULL,
	[RefCurrID] [int] NOT NULL,
	[RefCurrSymbol] [varchar](25) NOT NULL,
	[DebitAmount] [numeric](18, 2) NOT NULL,
	[CreditAmount] [numeric](18, 2) NOT NULL,
	[RefTransAmount] [numeric](18, 2) NOT NULL,
	[DeptAmount] [numeric](18, 2) NOT NULL,
	[CompAmount] [numeric](18, 2) NOT NULL,
	[Editable] [char](1) NOT NULL,
 CONSTRAINT [pk_paPayAccLinkPostingDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[TransID] ASC,
	[DetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[moStockWriteOffHQ]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[moStockWriteOffHQ](
	[swID] [int] NOT NULL,
	[swShopID] [int] NULL,
	[swGodownID] [int] NULL,
	[swDate] [datetime] NULL,
	[swItemID] [int] NULL,
	[swCostPrice] [numeric](18, 2) NULL,
	[swAddStock] [numeric](18, 3) NULL,
	[swDedStock] [numeric](18, 3) NULL,
	[swUserName] [varchar](50) NULL,
	[swposted] [bit] NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[swTransId] [int] NULL,
	[swTransCode] [varchar](50) NULL,
	[swWriteOffType] [bit] NULL,
	[swdepExRate] [numeric](18, 8) NULL,
	[swdConExRate] [numeric](18, 8) NULL,
	[swExchangeRates] [varchar](250) NULL,
	[swTranDate] [datetime] NULL,
 CONSTRAINT [PK_moStockWriteOffHQ] PRIMARY KEY NONCLUSTERED 
(
	[swID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TillOpeningstock]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TillOpeningstock](
	[companyid] [int] NOT NULL,
	[tillHistId] [int] NOT NULL,
	[tillid] [int] NOT NULL,
	[tillNo] [int] NULL,
	[shopid] [int] NOT NULL,
	[itemid] [int] NOT NULL,
	[openstock] [numeric](17, 3) NULL,
	[allReceivedStock] [numeric](18, 0) NULL,
	[allUsedStock] [numeric](18, 0) NULL,
 CONSTRAINT [PK_TillOpeningstock_companyid_tillHistId_tillid_shopid_itemid] PRIMARY KEY CLUSTERED 
(
	[companyid] ASC,
	[tillHistId] ASC,
	[tillid] ASC,
	[shopid] ASC,
	[itemid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[mosshopservicestock]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[mosshopservicestock](
	[serstkshopid] [int] NOT NULL,
	[serstkcompanyid] [int] NOT NULL,
	[serstkitemid] [int] NOT NULL,
	[serstkstock] [numeric](18, 3) NOT NULL,
	[serstkcost] [numeric](18, 8) NULL,
	[serstkfutureint] [int] NULL,
	[serstkfuturevc] [varchar](250) NULL,
	[serstkfuturebit] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_mosshopservicestock] PRIMARY KEY CLUSTERED 
(
	[serstkshopid] ASC,
	[serstkcompanyid] ASC,
	[serstkitemid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1733581214] ON [dbo].[mosshopservicestock] 
(
	[rowguid] 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, FILLFACTOR = 100) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losSerStandByReceiptDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSerStandByReceiptDetail](
	[rdCompanyID] [int] NOT NULL,
	[rdReceiptID] [int] NOT NULL,
	[rdShopID] [int] NOT NULL,
	[rdDetailID] [int] NOT NULL,
	[rdMachineID] [int] NOT NULL,
	[rdQuantity] [numeric](18, 2) NOT NULL,
	[rdRemarks] [varchar](250) NOT NULL,
 CONSTRAINT [PK_losSerStandByReceiptDetail] PRIMARY KEY NONCLUSTERED 
(
	[rdCompanyID] ASC,
	[rdReceiptID] ASC,
	[rdShopID] ASC,
	[rdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losSerStandByIssueDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSerStandByIssueDetail](
	[isdCompanyID] [int] NOT NULL,
	[isdIssueID] [int] NOT NULL,
	[isdShopID] [int] NOT NULL,
	[isdDetailID] [int] NOT NULL,
	[isdMachineID] [int] NOT NULL,
	[isdQuantity] [numeric](18, 2) NOT NULL,
	[isdRemarks] [varchar](250) NULL,
 CONSTRAINT [PK_losSerStandByIssueDetail] PRIMARY KEY NONCLUSTERED 
(
	[isdCompanyID] ASC,
	[isdIssueID] ASC,
	[isdShopID] ASC,
	[isdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loPurchaseOrderDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loPurchaseOrderDetail](
	[podPoid] [int] NOT NULL,
	[poditemid] [int] NOT NULL,
	[podDetailID] [int] NOT NULL,
	[podpackingtypeID] [int] NULL,
	[podQty] [numeric](18, 3) NULL,
	[podUnitPrice] [numeric](25, 8) NULL,
	[poddescription] [varchar](250) NULL,
	[podstatus] [char](1) NULL,
	[podstatusinfo] [varchar](100) NULL,
	[podlastbillrate] [numeric](18, 2) NULL,
	[podcostingvalue] [int] NULL,
	[podcostingprice] [numeric](18, 2) NULL,
	[podbillunitprice] [numeric](18, 2) NULL,
	[podcustomdutyamount] [numeric](18, 2) NULL,
	[podocperitem] [numeric](28, 22) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[poddiscount] [numeric](18, 2) NULL,
	[poddiscountprice] [numeric](18, 2) NULL,
	[podsellingprice] [numeric](18, 2) NULL,
	[podRoyalty] [numeric](18, 2) NULL,
	[podLstCustRate] [numeric](18, 0) NULL,
	[podItemTaxPercentage] [numeric](18, 2) NULL,
	[podItemTaxAmount] [numeric](18, 2) NULL,
	[podItemTaxCategory] [int] NULL,
 CONSTRAINT [PK_loPurchaseOrderDetail] PRIMARY KEY NONCLUSTERED 
(
	[podPoid] ASC,
	[poditemid] ASC,
	[podDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losStockRecovery]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losStockRecovery](
	[srID] [int] NOT NULL,
	[srShopID] [int] NOT NULL,
	[srDate] [datetime] NULL,
	[srItemID] [int] NULL,
	[srAddStock] [numeric](18, 3) NULL,
	[srDedStock] [numeric](18, 3) NULL,
	[srcostprice] [numeric](18, 2) NULL,
	[srUserName] [varchar](50) NULL,
	[srposted] [bit] NOT NULL,
	[srfutureint] [int] NULL,
	[updatetime] [datetime] NOT NULL,
	[srdepartmentid] [int] NULL,
	[srlocid] [int] NULL,
	[srtransno] [varchar](50) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[srConExRate] [numeric](18, 8) NULL,
	[srDepExRate] [numeric](18, 8) NULL,
	[srExchangeRates] [varchar](250) NULL,
	[srTransDate] [datetime] NULL,
 CONSTRAINT [PK_losStockRecovery] PRIMARY KEY NONCLUSTERED 
(
	[srID] ASC,
	[srShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_losstockrecovery_srdate] ON [dbo].[losStockRecovery] 
(
	[srDate] 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
CREATE UNIQUE NONCLUSTERED INDEX [index_1637580872] ON [dbo].[losStockRecovery] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losShopItemShipmentDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losShopItemShipmentDetail](
	[ipid] [int] IDENTITY(1,1) NOT NULL,
	[shipmentid] [int] NOT NULL,
	[itemid] [int] NOT NULL,
	[shopid] [int] NULL,
	[PackingTypeid] [int] NOT NULL,
	[spFixdate] [datetime] NULL,
	[sellingPrice] [numeric](18, 2) NULL,
	[WholesalePrice] [numeric](18, 2) NULL,
	[DiscountPrice] [numeric](18, 2) NULL,
	[Pricechanged] [bit] NOT NULL,
	[currencyid] [int] NULL,
	[companyid] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[segmentid] [int] NULL,
	[CreditSP] [numeric](18, 2) NULL,
	[CreditDP] [numeric](18, 2) NULL,
	[CreditWP] [numeric](18, 2) NULL,
	[Userid] [int] NULL,
 CONSTRAINT [PK_losShopItemShipmentDetail] PRIMARY KEY CLUSTERED 
(
	[ipid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_853578079] ON [dbo].[losShopItemShipmentDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [uniq_sellprice] ON [dbo].[losShopItemShipmentDetail] 
(
	[itemid] ASC,
	[shopid] ASC,
	[PackingTypeid] ASC,
	[currencyid] ASC,
	[segmentid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[MEsDespatchtoGodownHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MEsDespatchtoGodownHeader](
	[dghID] [int] NOT NULL,
	[dghShopID] [int] NOT NULL,
	[dghNo] [varchar](50) NULL,
	[dghDate] [datetime] NULL,
	[dghGodownID] [int] NULL,
	[dghRemarks] [varchar](100) NULL,
	[dghCancelled] [bit] NOT NULL,
	[dghCancelledRemarks] [varchar](250) NULL,
	[dghRecAddUser] [varchar](50) NULL,
	[dghRecModifyUser] [varchar](50) NULL,
	[dghUsed] [bit] NOT NULL,
	[dghTransFinished] [bit] NOT NULL,
	[dghNoofDetails] [int] NOT NULL,
	[dghfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[dghposted] [bit] NULL,
	[dghdepartmentid] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[dghconexrate] [numeric](18, 8) NULL,
	[dghdepexrate] [numeric](18, 8) NULL,
	[dghexchangerates] [varchar](250) NULL,
	[dghtime] [datetime] NULL,
	[dghGdnReqId] [int] NULL,
 CONSTRAINT [PK_MEsDespatchtoGodownHeader] PRIMARY KEY NONCLUSTERED 
(
	[dghID] ASC,
	[dghShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_mesdespatchtogodownheader_dghDate] ON [dbo].[MEsDespatchtoGodownHeader] 
(
	[dghDate] 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
CREATE UNIQUE NONCLUSTERED INDEX [index_450100644] ON [dbo].[MEsDespatchtoGodownHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_mesdespatchtogodownheader] ON [dbo].[MEsDespatchtoGodownHeader] 
(
	[dghID] ASC,
	[dghShopID] ASC,
	[dghCancelled] ASC,
	[dghTransFinished] 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
/****** Object:  Table [dbo].[MEsDespatchtoGodownDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MEsDespatchtoGodownDetail](
	[dgdID] [int] NOT NULL,
	[dgdShipmentID] [int] NOT NULL,
	[dgdItemID] [int] NOT NULL,
	[dgdShopID] [int] NOT NULL,
	[dgdGodownid] [int] NULL,
	[dgdAvailableGoodQty] [numeric](18, 3) NULL,
	[dgdAvailableBadQty] [numeric](18, 3) NULL,
	[dgdDespatchedGoodQty] [numeric](18, 3) NULL,
	[dgdDespatchedBadQty] [numeric](18, 3) NULL,
	[dgdcostprice] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_MEsDespatchtoGodownDetail] PRIMARY KEY NONCLUSTERED 
(
	[dgdID] ASC,
	[dgdShipmentID] ASC,
	[dgdItemID] ASC,
	[dgdShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_2053582354] ON [dbo].[MEsDespatchtoGodownDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_mesdespatchtogodowndetail] ON [dbo].[MEsDespatchtoGodownDetail] 
(
	[dgdID] ASC,
	[dgdShopID] 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
/****** Object:  Table [dbo].[loPurchaseOrderItemSplitDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[loPurchaseOrderItemSplitDetails](
	[podID] [int] NOT NULL,
	[VendorID] [int] NOT NULL,
	[ItemID] [int] NOT NULL,
	[PoDetailID] [int] NOT NULL,
	[VendorItemDesc] [nvarchar](50) NULL,
	[VendorPackingType] [nvarchar](50) NULL,
	[VendorQty] [numeric](18, 2) NULL,
	[VendorUnitPrice] [numeric](18, 2) NULL,
	[VendorAmount] [numeric](18, 2) NULL,
	[CustomItemDesc] [nvarchar](50) NULL,
	[CustomPackingType] [nvarchar](50) NULL,
	[CustomQty] [numeric](18, 2) NULL,
	[CustomUnitPrice] [numeric](18, 2) NULL,
	[CustomAmount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_loPurchaseOrderItemSplitDetails] PRIMARY KEY CLUSTERED 
(
	[podID] ASC,
	[VendorID] ASC,
	[ItemID] ASC,
	[PoDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Fb_recipedetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Fb_recipedetails](
	[Fb_rd_Companyid] [int] NOT NULL,
	[Fb_rd_dishid] [int] NOT NULL,
	[Fb_rd_recipedetailid] [int] NOT NULL,
	[Fb_rd_itemid] [int] NOT NULL,
	[fb_rd_quantity] [decimal](20, 5) NULL,
	[fb_rd_packingtypeid] [int] NULL,
	[fb_rd_packingqty] [decimal](18, 5) NULL,
	[fb_rd_recipechoiceid] [varchar](250) NULL,
	[Fb_rd_Futureint] [int] NULL,
	[Fb_rd_Futurevarchar] [varchar](250) NULL,
	[Fb_rd_Futurebit] [bit] NULL,
	[Fb_rd_YieldPer] [decimal](9, 2) NULL,
	[Fb_rd_costprice] [numeric](18, 2) NULL,
 CONSTRAINT [PK_Fb_recipedetails] PRIMARY KEY NONCLUSTERED 
(
	[Fb_rd_Companyid] ASC,
	[Fb_rd_dishid] ASC,
	[Fb_rd_recipedetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loiStockVerificationHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loiStockVerificationHeader](
	[svhid] [int] NOT NULL,
	[svhGodownid] [int] NOT NULL,
	[svhNo] [varchar](50) NOT NULL,
	[svhDate] [datetime] NULL,
	[svhVerificationby] [varchar](250) NULL,
	[svhCancelled] [bit] NOT NULL,
	[svhCancelledRemarks] [varchar](50) NULL,
	[svhRecAddUser] [varchar](50) NULL,
	[svhRecModUser] [varchar](50) NULL,
	[svhRemarks] [varchar](250) NULL,
	[svhfuturevc] [varchar](250) NOT NULL,
	[svhposted] [bit] NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[svhdepartmentid] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[svhdepexrate] [numeric](18, 8) NULL,
	[svhconexrate] [numeric](18, 8) NULL,
	[svhexchangerates] [varchar](250) NULL,
	[svhcreatedtime] [datetime] NULL,
 CONSTRAINT [PK_loiStockVerificationHeader] PRIMARY KEY NONCLUSTERED 
(
	[svhid] ASC,
	[svhGodownid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loiStockVerificationDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[loiStockVerificationDetail](
	[svdid] [int] NOT NULL,
	[svdGodownID] [int] NOT NULL,
	[svdLocationid] [int] NULL,
	[svdShipmentID] [int] NOT NULL,
	[svdItemID] [int] NOT NULL,
	[svdAvailStock] [numeric](18, 3) NULL,
	[svdVerifiedStock] [numeric](18, 3) NULL,
	[svdAvailBadStock] [numeric](18, 3) NULL,
	[svdVerifiedBadStock] [numeric](18, 3) NULL,
	[svdcostprice] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_loiStockVerificationDetail] PRIMARY KEY CLUSTERED 
(
	[svdid] ASC,
	[svdGodownID] ASC,
	[svdShipmentID] ASC,
	[svdItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1125579048] ON [dbo].[loiStockVerificationDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[loPurchasereturnheader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loPurchasereturnheader](
	[prhcompanyid] [int] NOT NULL,
	[prhreturnid] [int] NOT NULL,
	[prhreturnno] [varchar](50) NULL,
	[prhreturndate] [datetime] NULL,
	[prhvendorid] [int] NULL,
	[prhgodownid] [int] NULL,
	[prhwriteoffid] [int] NULL,
	[prhremarks] [varchar](250) NULL,
	[prhadjaccountid] [int] NULL,
	[prhcancelled] [bit] NOT NULL,
	[prhcancelledremarks] [varchar](250) NULL,
	[prhposted] [bit] NOT NULL,
	[prhupdatetime] [datetime] NULL,
	[prhexrate] [numeric](18, 8) NULL,
	[prhdepexrate] [numeric](18, 8) NULL,
	[prhexchangerates] [varchar](250) NULL,
	[prhinvexrate] [numeric](18, 8) NULL,
	[prhFinancialID] [int] NULL,
	[prhdepartmentid] [int] NULL,
	[prhSubDepartmentID] [int] NULL,
	[prhreturntime] [datetime] NULL,
	[prhreturnupdatetime] [datetime] NULL,
	[prhTime] [datetime] NULL,
	[prhModified] [varchar](250) NULL,
	[prhCreated] [varchar](250) NULL,
	[prhShopID] [int] NULL,
 CONSTRAINT [PK_loPurchasereturnheader] PRIMARY KEY NONCLUSTERED 
(
	[prhcompanyid] ASC,
	[prhreturnid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loPurchasereturndetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[loPurchasereturndetail](
	[prdcompanyid] [int] NOT NULL,
	[prdreturnid] [int] NOT NULL,
	[prddetailid] [int] NOT NULL,
	[prditemid] [int] NULL,
	[prdqty] [numeric](18, 3) NULL,
	[prdcostprice] [numeric](18, 2) NULL,
	[prdsuppamount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_loPurchasereturndetail] PRIMARY KEY NONCLUSTERED 
(
	[prdcompanyid] ASC,
	[prdreturnid] ASC,
	[prddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosReserveItem]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LosReserveItem](
	[godownid] [int] NOT NULL,
	[itemid] [int] NOT NULL,
	[locationid] [int] NOT NULL,
	[shipmentid] [int] NOT NULL,
	[qty] [numeric](18, 3) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LosReserveItem] PRIMARY KEY NONCLUSTERED 
(
	[godownid] ASC,
	[itemid] ASC,
	[locationid] ASC,
	[shipmentid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_805577908] ON [dbo].[LosReserveItem] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[areprecvendorheader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[areprecvendorheader](
	[rrvhcompanyid] [int] NOT NULL,
	[rrvhreceiveid] [int] NOT NULL,
	[rrvhreceiveno] [varchar](50) NULL,
	[rrvhreceivedate] [datetime] NULL,
	[rrvhvendorid] [int] NULL,
	[rrvhvendorrefno] [varchar](50) NULL,
	[rrvhremarks] [varchar](250) NULL,
	[rrvhtransfinished] [bit] NOT NULL,
	[rrvhcancelled] [bit] NOT NULL,
	[rrvhcancelledremarks] [varchar](250) NULL,
	[rrvhTime] [datetime] NULL,
	[rrvhcreated] [varchar](20) NULL,
	[rrvhModified] [varchar](20) NULL,
 CONSTRAINT [PK_areprecvendorheader] PRIMARY KEY NONCLUSTERED 
(
	[rrvhcompanyid] ASC,
	[rrvhreceiveid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losreplacereceiveheader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losreplacereceiveheader](
	[reprechid] [int] NOT NULL,
	[reprechcompanyid] [int] NOT NULL,
	[reprechshopid] [int] NOT NULL,
	[reprechno] [varchar](50) NULL,
	[reprechdate] [datetime] NULL,
	[reprechremarks] [varchar](250) NULL,
	[reprechcancelled] [bit] NOT NULL,
	[repreccancelremarks] [varchar](250) NULL,
	[reprecfutureint] [int] NULL,
	[reprecfuturevc] [varchar](250) NULL,
	[reprecfuturenum] [numeric](18, 8) NULL,
	[reprechupdatetime] [datetime] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[reprechqreceiveid] [int] NULL,
 CONSTRAINT [PK_losreplacereceiveheader] PRIMARY KEY NONCLUSTERED 
(
	[reprechid] ASC,
	[reprechcompanyid] ASC,
	[reprechshopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_226099846] ON [dbo].[losreplacereceiveheader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losreplacereceivedetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losreplacereceivedetails](
	[reprecdid] [int] NOT NULL,
	[reprecdcompanyid] [int] NOT NULL,
	[reprecdshopid] [int] NOT NULL,
	[reprecditemid] [int] NOT NULL,
	[reprecdbookid] [int] NOT NULL,
	[repRepReqID] [int] NOT NULL,
	[reprecqty] [numeric](18, 8) NULL,
	[reprecdtagno] [varchar](50) NULL,
	[reprecdcomments] [varchar](250) NULL,
	[repreqdfutureint] [int] NULL,
	[repreqdfuturevc] [varchar](250) NULL,
	[repreqdfuturenum] [numeric](18, 8) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_losreplacereceivedetails] PRIMARY KEY CLUSTERED 
(
	[reprecdid] ASC,
	[reprecdcompanyid] ASC,
	[reprecdshopid] ASC,
	[reprecditemid] ASC,
	[reprecdbookid] ASC,
	[repRepReqID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1010102639] ON [dbo].[losreplacereceivedetails] 
(
	[rowguid] 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, FILLFACTOR = 100) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losSerMaintenanceContractHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSerMaintenanceContractHeader](
	[mchCompanyID] [int] NOT NULL,
	[mchID] [int] NOT NULL,
	[mchShopID] [int] NOT NULL,
	[mchCustomerID] [int] NOT NULL,
	[mchNo] [varchar](50) NOT NULL,
	[mchContractRefNo] [varchar](50) NOT NULL,
	[mchCancelled] [bit] NOT NULL,
	[mchCancelledDate] [datetime] NULL,
	[mchCancelledRemarks] [varchar](50) NULL,
	[mchAccID] [int] NULL,
	[mchRemarks] [varchar](250) NULL,
	[mchFuture] [varchar](250) NULL,
	[mchdate] [datetime] NULL,
	[mchguarantee] [bit] NULL,
	[mchExchangeRates] [varchar](250) NULL,
	[mchDepExrate] [numeric](18, 8) NULL,
	[mchExchangeRate] [numeric](18, 8) NULL,
 CONSTRAINT [PK_losSerMaintenanceContractHeader] PRIMARY KEY NONCLUSTERED 
(
	[mchCompanyID] ASC,
	[mchID] ASC,
	[mchShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losSerMaintenanceServiceDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSerMaintenanceServiceDetail](
	[msdCompanyID] [int] NOT NULL,
	[msdMCID] [int] NOT NULL,
	[msdShopID] [int] NOT NULL,
	[msdDetailID] [int] NOT NULL,
	[msdMachineID] [int] NOT NULL,
	[msdServiceID] [int] NOT NULL,
	[msdSerPeriod] [int] NULL,
	[msdSerRemarks] [varchar](250) NOT NULL,
	[msdSerPeriodType] [char](1) NULL,
	[msdAlertdays] [int] NULL,
	[msdAlerttype] [bit] NULL,
 CONSTRAINT [PK_losSerMaintenanceServiceDetail] PRIMARY KEY NONCLUSTERED 
(
	[msdCompanyID] ASC,
	[msdMCID] ASC,
	[msdShopID] ASC,
	[msdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losSerMaintenanceMachineDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSerMaintenanceMachineDetail](
	[mmdCompanyID] [int] NOT NULL,
	[mmdMCID] [int] NOT NULL,
	[mmdShopID] [int] NOT NULL,
	[mmdDetailID] [int] NOT NULL,
	[mmdMachineID] [int] NOT NULL,
	[mmdRemarks] [varchar](250) NOT NULL,
	[mmdSerShopid] [int] NULL,
	[mmdSerProcessid] [int] NULL,
	[mmdSerProcessType] [char](2) NULL,
	[mmdAlertdays] [int] NULL,
 CONSTRAINT [PK_losSerMaintenanceMachineDetail] PRIMARY KEY NONCLUSTERED 
(
	[mmdCompanyID] ASC,
	[mmdMCID] ASC,
	[mmdShopID] ASC,
	[mmdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aAnalysedPOItems]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aAnalysedPOItems](
	[alid] [int] NOT NULL,
	[alitemid] [int] NULL,
	[almoveperiod] [int] NULL,
	[almovedqty] [decimal](18, 0) NULL,
	[alimportperiod] [int] NULL,
	[alimportqty] [decimal](18, 0) NULL,
	[alDate] [datetime] NULL,
	[alvendorid] [int] NULL,
	[updatetime] [datetime] NOT NULL,
	[alfromdate] [datetime] NULL,
	[altodate] [datetime] NULL,
 CONSTRAINT [PK_aAnalysedPOItems] PRIMARY KEY NONCLUSTERED 
(
	[alid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losSerStandByRequestHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSerStandByRequestHeader](
	[reqhCompanyID] [int] NOT NULL,
	[reqhRequestID] [int] NOT NULL,
	[reqhShopID] [int] NOT NULL,
	[reqhNo] [varchar](50) NOT NULL,
	[reqhDate] [datetime] NOT NULL,
	[reqhCustomerID] [int] NOT NULL,
	[reqhProcessedDate] [datetime] NULL,
	[reqhApprovedByID] [int] NULL,
	[reqhCancelled] [bit] NOT NULL,
	[reqhCancelledRemarks] [varchar](250) NULL,
	[reqhRemarks] [varchar](250) NOT NULL,
	[reqhFuture] [varchar](250) NULL,
	[reqhUpdateTime] [datetime] NOT NULL,
	[reqhType] [char](1) NULL,
	[reqhCustomerName] [varchar](250) NULL,
	[reqhContactNo] [varchar](100) NULL,
	[reqhContactName] [varchar](250) NULL,
	[reqhtime] [datetime] NULL,
 CONSTRAINT [PK_losSerStandByRequestHeader] PRIMARY KEY NONCLUSTERED 
(
	[reqhCompanyID] ASC,
	[reqhRequestID] ASC,
	[reqhShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losSerStandByRequestDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSerStandByRequestDetail](
	[reqdCompanyID] [int] NOT NULL,
	[reqdShopID] [int] NOT NULL,
	[reqdRequestID] [int] NOT NULL,
	[reqdDetailID] [int] NOT NULL,
	[reqdMachineID] [int] NOT NULL,
	[reqdQuantity] [numeric](18, 2) NOT NULL,
	[reqdRemarks] [varchar](250) NULL,
	[reqdslno] [varchar](50) NULL,
 CONSTRAINT [PK_losSerStandByRequestDetail] PRIMARY KEY NONCLUSTERED 
(
	[reqdCompanyID] ASC,
	[reqdShopID] ASC,
	[reqdRequestID] ASC,
	[reqdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losStockVerificationHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losStockVerificationHeader](
	[svhid] [int] NOT NULL,
	[svhShopId] [int] NOT NULL,
	[svhno] [varchar](50) NULL,
	[svhdate] [datetime] NULL,
	[svhverificationby] [varchar](250) NULL,
	[svhremarks] [varchar](250) NULL,
	[svhcancelled] [bit] NOT NULL,
	[svhcancelremarks] [varchar](250) NULL,
	[svhrecmoduser] [varchar](250) NULL,
	[svhrecadduser] [varchar](250) NULL,
	[svhfuturevc] [varchar](250) NOT NULL,
	[svhposted] [bit] NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[svhdepartmentid] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[svhconexrate] [numeric](18, 8) NULL,
	[svhdepexrate] [numeric](18, 8) NULL,
	[svhexchangerates] [varchar](250) NULL,
 CONSTRAINT [PK_lopStockVerificationHeader] PRIMARY KEY NONCLUSTERED 
(
	[svhid] ASC,
	[svhShopId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_losstockverificationheader_svhDate] ON [dbo].[losStockVerificationHeader] 
(
	[svhdate] 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
CREATE UNIQUE NONCLUSTERED INDEX [index_1653580929] ON [dbo].[losStockVerificationHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_losstockverificationheader] ON [dbo].[losStockVerificationHeader] 
(
	[svhid] ASC,
	[svhShopId] ASC,
	[svhcancelled] ASC,
	[svhfuturevc] 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
/****** Object:  Table [dbo].[losStockVerificationDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losStockVerificationDetail](
	[svdid] [int] NOT NULL,
	[svdShipmentID] [int] NOT NULL,
	[svditemid] [int] NOT NULL,
	[svdShopid] [int] NOT NULL,
	[svdAvailStock] [numeric](18, 3) NULL,
	[svdVerifiedStock] [numeric](18, 3) NULL,
	[svdAvailBadStock] [numeric](18, 3) NULL,
	[svdVerifiedBadStock] [numeric](18, 3) NULL,
	[svdcostprice] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_losStockVerificationDetail] PRIMARY KEY NONCLUSTERED 
(
	[svdid] ASC,
	[svdShipmentID] ASC,
	[svditemid] ASC,
	[svdShopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1141579105] ON [dbo].[losStockVerificationDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_losstockverificationdetail] ON [dbo].[losStockVerificationDetail] 
(
	[svdid] ASC,
	[svdShopid] ASC,
	[svdVerifiedStock] ASC,
	[svdAvailStock] 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
/****** Object:  Table [dbo].[losinvpartsreplacedetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losinvpartsreplacedetails](
	[repinvcompanyid] [int] NOT NULL,
	[repinvdpartsid] [int] NOT NULL,
	[repinvdshopid] [int] NOT NULL,
	[repinvinvoiceid] [int] NOT NULL,
	[repinvdrate] [numeric](18, 8) NULL,
	[repinvdsellrate] [numeric](18, 8) NULL,
	[repinvdqty] [numeric](18, 3) NULL,
	[repinvreplfromsupp] [bit] NULL,
	[repinvdguarantee] [bit] NULL,
	[repinvdcostprice] [numeric](18, 8) NULL,
	[repinvdcomments] [varchar](250) NULL,
	[repinvpackid] [int] NULL,
	[repinvpackqty] [numeric](18, 8) NULL,
	[repinvdetailid] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[repinvdType] [varchar](10) NULL,
	[repinvdSerialNo] [varchar](100) NULL,
	[repinvdItemTaxPercentage] [numeric](18, 2) NULL,
	[repinvdItemTaxAmount] [numeric](18, 2) NULL,
	[repinvdItemTaxCategory] [int] NULL,
 CONSTRAINT [PK_losinvpartsreplacedetails] PRIMARY KEY CLUSTERED 
(
	[repinvcompanyid] ASC,
	[repinvinvoiceid] ASC,
	[repinvdshopid] ASC,
	[repinvdetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_98099390] ON [dbo].[losinvpartsreplacedetails] 
(
	[rowguid] 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, FILLFACTOR = 100) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losInquiryHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losInquiryHeader](
	[ihcompanyid] [int] NOT NULL,
	[ihshopid] [int] NOT NULL,
	[ihid] [int] NOT NULL,
	[ihno] [varchar](50) NULL,
	[ihdate] [datetime] NULL,
	[ihcustid] [int] NULL,
	[ihcustname] [varchar](100) NULL,
	[ihcustaddress] [varchar](250) NULL,
	[ihcusttele] [varchar](50) NULL,
	[ihremarks] [varchar](250) NULL,
	[ihupdatetime] [datetime] NOT NULL,
	[ihcancelled] [bit] NOT NULL,
	[ihcancelledremarks] [varchar](250) NULL,
	[ihCreated] [varchar](250) NULL,
	[ihModified] [varchar](250) NULL,
	[ihTime] [datetime] NULL,
 CONSTRAINT [PK_losInquiryHeader] PRIMARY KEY NONCLUSTERED 
(
	[ihcompanyid] ASC,
	[ihshopid] ASC,
	[ihid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losinquirydetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losinquirydetail](
	[idcompanyid] [int] NOT NULL,
	[idshopid] [int] NOT NULL,
	[idid] [int] NOT NULL,
	[iddetailid] [int] NOT NULL,
	[iditemid] [int] NULL,
	[iditemname] [varchar](100) NULL,
	[idcomments] [varchar](250) NULL,
 CONSTRAINT [PK_losinquirydetail] PRIMARY KEY NONCLUSTERED 
(
	[idcompanyid] ASC,
	[idshopid] ASC,
	[idid] ASC,
	[iddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LoiItemSplitDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LoiItemSplitDetail](
	[isdgodownid] [int] NOT NULL,
	[isdid] [int] NOT NULL,
	[isditemid] [int] NOT NULL,
	[isdqty] [numeric](18, 3) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LoiItemSplitDetail] PRIMARY KEY NONCLUSTERED 
(
	[isdgodownid] ASC,
	[isdid] ASC,
	[isditemid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_2117582582] ON [dbo].[LoiItemSplitDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[MEiGodownTransferHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MEiGodownTransferHeader](
	[gthDespatchID] [int] NOT NULL,
	[gthDespatchNo] [varchar](50) NOT NULL,
	[gthFromGodownID] [int] NOT NULL,
	[gthToGodownID] [int] NOT NULL,
	[gthDespatchDate] [datetime] NOT NULL,
	[gthCarrier] [varchar](250) NULL,
	[gthIssueNoteID] [int] NULL,
	[gthVehicleNo] [varchar](50) NULL,
	[gthCancelled] [bit] NOT NULL,
	[gthCancelledRemarks] [varchar](250) NULL,
	[gthRemarks] [varchar](250) NULL,
	[gthRecAddUser] [varchar](250) NULL,
	[gthRecModifyUser] [varchar](250) NULL,
	[gthSelected] [bit] NOT NULL,
	[gthTransFinished] [bit] NOT NULL,
	[gthNoofDetails] [int] NOT NULL,
	[gthfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[gthdepartmentid] [int] NULL,
	[gthposted] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[gthconexrate] [numeric](18, 8) NULL,
	[gthdepexrate] [numeric](18, 8) NULL,
	[gthexchangerates] [varchar](250) NULL,
	[gthDespatchtime] [datetime] NULL,
	[gthGdnReqId] [int] NULL,
 CONSTRAINT [PK_MEiGodownTransferHeader] PRIMARY KEY NONCLUSTERED 
(
	[gthDespatchID] ASC,
	[gthFromGodownID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[MEiGodownTransferDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MEiGodownTransferDetail](
	[gtdDespatchID] [int] NOT NULL,
	[gtdGodownID] [int] NOT NULL,
	[gtdLocationID] [int] NULL,
	[gtdShipmentID] [int] NOT NULL,
	[gtdItemID] [int] NOT NULL,
	[gtdToGodownid] [int] NULL,
	[gtdItemBadQty] [numeric](18, 3) NULL,
	[gtdItemGoodQty] [numeric](18, 3) NULL,
	[gtdcostprice] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_MEiGodownTransferDetail] PRIMARY KEY CLUSTERED 
(
	[gtdDespatchID] ASC,
	[gtdGodownID] ASC,
	[gtdShipmentID] ASC,
	[gtdItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1333579789] ON [dbo].[MEiGodownTransferDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[MOiGodownStock]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MOiGodownStock](
	[gsGodownID] [int] NOT NULL,
	[gsLocationID] [int] NULL,
	[gsStockDate] [datetime] NOT NULL,
	[gsShipmentID] [int] NOT NULL,
	[gsItemID] [int] NOT NULL,
	[gsOpeningStock] [numeric](18, 3) NULL,
	[gsStock] [numeric](18, 3) NULL,
	[gsOpeningBadStock] [numeric](18, 3) NULL,
	[gsBadStock] [numeric](18, 3) NULL,
	[gsItemCost] [numeric](18, 2) NULL,
	[futureint] [int] NULL,
	[futuredate] [datetime] NULL,
	[futurevarchar] [varchar](50) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_MOiGodownStock] PRIMARY KEY CLUSTERED 
(
	[gsGodownID] ASC,
	[gsShipmentID] ASC,
	[gsItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1525580473] ON [dbo].[MOiGodownStock] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosGoodsReturnNoteDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosGoodsReturnNoteDetail](
	[GRNDReturnNoteID] [int] NOT NULL,
	[GRNDItemID] [int] NOT NULL,
	[GRNDShopid] [int] NOT NULL,
	[GRNDQuantity] [numeric](18, 5) NULL,
	[GRNDunitprice] [numeric](18, 5) NULL,
	[GRNDDamaged] [bit] NOT NULL,
	[GRNDRemarks] [varchar](250) NULL,
	[grncostprice] [numeric](18, 2) NULL,
	[grndFreeQuantity] [numeric](18, 0) NULL,
	[grndPackTypeId] [int] NULL,
	[idItemTaxPercentage] [numeric](18, 2) NULL,
	[idItemTaxAmount] [numeric](18, 3) NULL,
	[idItemTaxCategory] [numeric](18, 2) NULL,
 CONSTRAINT [PK_LosGoodsReturnNoteDetail] PRIMARY KEY NONCLUSTERED 
(
	[GRNDReturnNoteID] ASC,
	[GRNDItemID] ASC,
	[GRNDShopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [index_LosGoodsReturnNoteDetail] ON [dbo].[LosGoodsReturnNoteDetail] 
(
	[GRNDReturnNoteID] ASC,
	[GRNDShopid] ASC,
	[GRNDDamaged] 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
/****** Object:  Table [dbo].[aPurchasePriceRange]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aPurchasePriceRange](
	[CompanyId] [int] NOT NULL,
	[ItemId] [int] NOT NULL,
	[MinPrice] [numeric](18, 2) NOT NULL,
	[MaxPrice] [numeric](18, 2) NOT NULL,
	[CurrencyId] [int] NOT NULL,
	[UpdateTime] [datetime] NULL,
	[UpdateUser] [nvarchar](50) NULL,
 CONSTRAINT [PK_aPurchasePriceRange] PRIMARY KEY CLUSTERED 
(
	[CompanyId] ASC,
	[ItemId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[meiSpecialDespatchtoshopHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[meiSpecialDespatchtoshopHeader](
	[dhdespatchid] [int] NOT NULL,
	[dhdespatchno] [varchar](50) NULL,
	[dhgodownid] [int] NOT NULL,
	[dhdespatchdate] [datetime] NULL,
	[dhShopID] [int] NULL,
	[dhCarrier] [varchar](250) NULL,
	[dhIssueNoteID] [int] NULL,
	[dhVehicleno] [varchar](50) NULL,
	[dhCancelled] [bit] NOT NULL,
	[dhCancelledRemarks] [varchar](250) NULL,
	[dhRemarks] [varchar](250) NULL,
	[dhRecAddUser] [varchar](250) NULL,
	[dhRecModifyUser] [varchar](250) NULL,
	[dhSelected] [bit] NOT NULL,
	[dhFuture] [varchar](250) NULL,
	[dhposted] [bit] NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[dhdepartmentid] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[dhconexrate] [numeric](18, 8) NULL,
	[dhdepexrate] [numeric](18, 8) NULL,
	[dhexchangerates] [varchar](250) NULL,
 CONSTRAINT [PK_meiSpecialDespatchtoshopHeader] PRIMARY KEY NONCLUSTERED 
(
	[dhdespatchid] ASC,
	[dhgodownid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_434100587] ON [dbo].[meiSpecialDespatchtoshopHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[meiSpecialDespatchtoShopDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[meiSpecialDespatchtoShopDetail](
	[ddDespatchid] [int] NOT NULL,
	[ddlocationid] [int] NULL,
	[ddGodownid] [int] NOT NULL,
	[ddShipmentid] [int] NOT NULL,
	[ddItemid] [int] NOT NULL,
	[ddShopid] [int] NULL,
	[ddItemBadQty] [numeric](18, 3) NULL,
	[ddItemGoodQty] [numeric](18, 3) NULL,
	[ddCostedPrice] [numeric](18, 2) NULL,
	[ddinvqty] [numeric](18, 3) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[ddPackingTypeID] [int] NULL,
	[ddPackQty] [numeric](18, 5) NULL,
 CONSTRAINT [PK_meiSpecialDespatchtoShopDetail] PRIMARY KEY CLUSTERED 
(
	[ddDespatchid] ASC,
	[ddGodownid] ASC,
	[ddShipmentid] ASC,
	[ddItemid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_997578592] ON [dbo].[meiSpecialDespatchtoShopDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOsPosSubItemDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOsPosSubItemDetail](
	[posidshopid] [int] NOT NULL,
	[posidbillid] [int] NOT NULL,
	[posiditemid] [int] NOT NULL,
	[posidsubitemid] [int] NOT NULL,
	[posidpackingtypeid] [int] NOT NULL,
	[posidpquantity] [numeric](18, 3) NULL,
	[posidquantity] [numeric](18, 3) NULL,
	[posidunitprice] [numeric](18, 2) NULL,
	[posidamount] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LOsPosSubItemDetail] PRIMARY KEY NONCLUSTERED 
(
	[posidshopid] ASC,
	[posidbillid] ASC,
	[posiditemid] ASC,
	[posidsubitemid] ASC,
	[posidpackingtypeid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1413580074] ON [dbo].[LOsPosSubItemDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aHpItemDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aHpItemDetails](
	[ItemID] [int] NOT NULL,
	[SellingPrice] [numeric](18, 2) NULL,
	[CCashAllowence] [numeric](18, 2) NULL,
	[SCashAllowence] [numeric](18, 2) NULL,
	[CSurCharge] [numeric](18, 2) NULL,
	[SSurCharge] [numeric](18, 2) NULL,
	[COnInstallment] [int] NULL,
	[SOnInstallment] [int] NULL,
	[CMaxMonths] [numeric](18, 0) NULL,
	[SMaxMonths] [numeric](18, 0) NULL,
	[CInflation] [numeric](18, 2) NULL,
	[SInflation] [numeric](18, 2) NULL,
	[CDownPayment] [numeric](18, 2) NULL,
	[SDownPayment] [numeric](18, 2) NULL,
 CONSTRAINT [PK_aHpItemDetails] PRIMARY KEY CLUSTERED 
(
	[ItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aItemPackingDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aItemPackingDetail](
	[ItemID] [int] NOT NULL,
	[PackingTypeID] [int] NOT NULL,
	[PackingSlNo] [int] NOT NULL,
	[PackingBarCode] [varchar](25) NULL,
	[active] [bit] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aItemPackingDetail] PRIMARY KEY NONCLUSTERED 
(
	[ItemID] ASC,
	[PackingTypeID] ASC,
	[PackingSlNo] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idxBarCode] ON [dbo].[aItemPackingDetail] 
(
	[PackingBarCode] ASC,
	[ItemID] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [idxItemId] ON [dbo].[aItemPackingDetail] 
(
	[ItemID] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1253579504] ON [dbo].[aItemPackingDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aHQIssuenoteDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aHQIssuenoteDetail](
	[INDIssuenoteID] [int] NOT NULL,
	[INDGodownid] [int] NOT NULL,
	[INDLocationID] [int] NOT NULL,
	[INDShipmentID] [int] NOT NULL,
	[INDItemID] [int] NOT NULL,
	[INDQty] [numeric](18, 3) NULL,
	[INDBadQty] [numeric](18, 3) NULL,
	[INDBadQtyRequested] [numeric](18, 3) NULL,
	[INDgoodQtyRequested] [numeric](18, 3) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aHQIssuenoteDetail] PRIMARY KEY NONCLUSTERED 
(
	[INDIssuenoteID] ASC,
	[INDGodownid] ASC,
	[INDLocationID] ASC,
	[INDShipmentID] ASC,
	[INDItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_229575856] ON [dbo].[aHQIssuenoteDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losrebateconfirmdetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losrebateconfirmdetail](
	[rcdshopid] [int] NOT NULL,
	[rcdapprovedid] [int] NOT NULL,
	[rcddetailid] [int] NOT NULL,
	[rcditemid] [int] NULL,
	[rcdrebateamount] [numeric](18, 2) NULL,
	[rcdCostPrice] [numeric](18, 4) NULL,
	[rcdQuantity] [numeric](18, 3) NULL,
	[rcdUnitPrice] [numeric](18, 4) NULL,
	[rcdRebatePer] [numeric](18, 2) NULL,
 CONSTRAINT [PK_losrebateconfirmdetail] PRIMARY KEY NONCLUSTERED 
(
	[rcdshopid] ASC,
	[rcdapprovedid] ASC,
	[rcddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[loalocalpurchaseCostingheader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loalocalpurchaseCostingheader](
	[lpchCostingid] [int] NOT NULL,
	[lpchCostingNo] [varchar](50) NULL,
	[lpchDate] [datetime] NULL,
	[lpchBillid] [int] NULL,
	[lpchShopid] [int] NULL,
	[lpchOtherCharges] [numeric](18, 2) NULL,
	[lpchRemarks] [varchar](250) NULL,
	[lpchCostingDone] [bit] NOT NULL,
	[lpchCostingDoneBy] [varchar](50) NULL,
	[lpchInventoryaccid] [int] NULL,
	[lpchGoodsinTransitaccid] [int] NULL,
	[lpchDepartmentid] [int] NULL,
	[lpchCompanyid] [int] NULL,
	[lpchposted] [bit] NOT NULL,
	[lpchCancelled] [bit] NOT NULL,
	[lpchcancelledremarks] [varchar](250) NULL,
	[lpchrecadduser] [varchar](50) NULL,
	[lpchrecmodifiyuser] [varchar](50) NULL,
	[updatetime] [datetime] NULL,
	[lpchSubDepartmentID] [int] NULL,
	[lpchTime] [datetime] NULL,
 CONSTRAINT [PK_loalocalpurchaseCostingheader] PRIMARY KEY NONCLUSTERED 
(
	[lpchCostingid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loalocalpurchasecostingdetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[loalocalpurchasecostingdetail](
	[lpcdcostingid] [int] NOT NULL,
	[lpcddetailid] [int] NOT NULL,
	[lpcditemid] [int] NULL,
	[lpcdcostedprice] [numeric](28, 16) NULL,
	[lpcditemqty] [numeric](18, 3) NULL,
	[lpcdbillunitprice] [numeric](28, 16) NULL,
	[lpcdolditemcostprice] [numeric](18, 2) NULL,
	[lpcdnewitemcostprice] [numeric](28, 16) NULL,
 CONSTRAINT [PK_loalocalpurchasecostingdetail] PRIMARY KEY NONCLUSTERED 
(
	[lpcdcostingid] ASC,
	[lpcddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aSubItemDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aSubItemDetails](
	[ItemID] [int] NOT NULL,
	[SubItemID] [int] NOT NULL,
	[PackingTypeID] [int] NULL,
	[UnitsID] [int] NULL,
	[Quantity] [numeric](18, 3) NULL,
	[SubItemRate] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aSubItemDetails] PRIMARY KEY NONCLUSTERED 
(
	[ItemID] ASC,
	[SubItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1269579561] ON [dbo].[aSubItemDetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[MEiDespatchToShopDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MEiDespatchToShopDetail](
	[ddDespatchID] [int] NOT NULL,
	[ddLocationId] [int] NULL,
	[ddGodownID] [int] NOT NULL,
	[ddShipmentID] [int] NOT NULL,
	[ddItemID] [int] NOT NULL,
	[ddShopId] [int] NULL,
	[ddItemBadQty] [numeric](18, 3) NULL,
	[ddItemGoodQty] [numeric](18, 3) NULL,
	[ddcostedprice] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[ddpackingtypeid] [int] NULL,
	[ddpackqty] [numeric](18, 3) NULL,
 CONSTRAINT [PK_MEiDespatchToShopDetail] PRIMARY KEY CLUSTERED 
(
	[ddDespatchID] ASC,
	[ddGodownID] ASC,
	[ddShipmentID] ASC,
	[ddItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_773577794] ON [dbo].[MEiDespatchToShopDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Fb_DishAdds]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Fb_DishAdds](
	[Fb_da_Companyid] [int] NOT NULL,
	[Fb_da_dishid] [int] NOT NULL,
	[Fb_da_dishaddsid] [int] NOT NULL,
	[Fb_da_itemid] [int] NOT NULL,
	[fb_da_quantity] [decimal](20, 5) NULL,
	[fb_da_packingtypeid] [int] NULL,
	[fb_da_packingqty] [decimal](18, 5) NULL,
	[fb_da_dishaddschoiceid] [varchar](250) NULL,
	[Fb_da_Futureint] [int] NULL,
	[Fb_da_Futurevarchar] [varchar](250) NULL,
	[Fb_da_Futurebit] [bit] NULL,
	[Fb_da_YieldPer] [decimal](9, 2) NULL,
	[fb_da_costprice] [numeric](18, 2) NULL,
 CONSTRAINT [PK_Fb_dishaddsdetails] PRIMARY KEY NONCLUSTERED 
(
	[Fb_da_Companyid] ASC,
	[Fb_da_dishid] ASC,
	[Fb_da_dishaddsid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losSIQuotationDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSIQuotationDetail](
	[idInvoiceId] [int] NOT NULL,
	[idGodownID] [int] NOT NULL,
	[idItemid] [int] NOT NULL,
	[idShopid] [int] NOT NULL,
	[locationid] [int] NOT NULL,
	[shipmentid] [int] NOT NULL,
	[idPackingTypeid] [int] NOT NULL,
	[idPunitID] [int] NULL,
	[IDPquantity] [numeric](18, 3) NULL,
	[idQuantity] [numeric](18, 3) NULL,
	[idUnitPrice] [numeric](18, 2) NULL,
	[idRateType] [int] NULL,
	[idActualUnitPrice] [numeric](18, 2) NULL,
	[reqqty] [numeric](18, 3) NULL,
	[despatch] [bit] NOT NULL,
	[idcostprice] [numeric](18, 2) NULL,
	[iddescription] [varchar](250) NULL,
	[idblockprice] [numeric](18, 2) NULL,
	[idguarantee] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[idFreeQuantity] [numeric](18, 3) NULL,
	[idSerialNo] [varchar](50) NULL,
	[idItemTaxPercentage] [numeric](18, 2) NULL,
	[idItemTaxAmount] [numeric](18, 2) NULL,
	[idItemTaxCategory] [int] NULL,
 CONSTRAINT [PK_losSIQuotationDetail] PRIMARY KEY NONCLUSTERED 
(
	[idInvoiceId] ASC,
	[idGodownID] ASC,
	[idItemid] ASC,
	[idShopid] ASC,
	[locationid] ASC,
	[shipmentid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loilocationarrivaldetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[loilocationarrivaldetails](
	[ladinterfaceid] [int] NOT NULL,
	[ladgodownid] [int] NOT NULL,
	[ladtransid] [int] NOT NULL,
	[laddetailid] [int] NOT NULL,
	[ladlocationid] [int] NULL,
	[laditemid] [int] NULL,
	[laditemqty] [numeric](18, 3) NULL,
	[ladpackingtypeid] [int] NULL,
	[ladpakingqty] [numeric](18, 3) NULL,
	[ladcancel] [bit] NOT NULL,
	[ladadjustment] [bit] NOT NULL,
	[ladconfirmed] [int] NOT NULL,
 CONSTRAINT [PK_loilocationarrivaldetails] PRIMARY KEY NONCLUSTERED 
(
	[ladinterfaceid] ASC,
	[ladgodownid] ASC,
	[ladtransid] ASC,
	[laddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[moapoitems]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[moapoitems](
	[shopid] [int] NOT NULL,
	[itemid] [int] NOT NULL,
	[quantity] [numeric](18, 3) NULL,
	[remarks] [varchar](250) NULL,
	[username] [varchar](100) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_moapoitems] PRIMARY KEY NONCLUSTERED 
(
	[shopid] ASC,
	[itemid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1109578991] ON [dbo].[moapoitems] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[MEDifferenceinStock]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MEDifferenceinStock](
	[dstransid] [int] NULL,
	[dstranscode] [varchar](50) NULL,
	[dsItemid] [int] NOT NULL,
	[dsToAdd] [numeric](18, 2) NOT NULL,
	[dsToDeduct] [numeric](18, 2) NOT NULL,
	[dsFromGodownID] [int] NOT NULL,
	[dsToGodownID] [int] NOT NULL,
	[dsFromShopID] [int] NOT NULL,
	[dsToShopID] [int] NOT NULL,
	[dsFutureint] [int] NULL,
	[dsFutureVC] [varchar](50) NULL,
	[dsCostPrice] [numeric](18, 2) NULL,
	[dsTransDate] [datetime] NULL,
	[dsDate] [datetime] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[MOsShopStock]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MOsShopStock](
	[ShopID] [int] NOT NULL,
	[StockDate] [datetime] NOT NULL,
	[ShipmentID] [int] NOT NULL,
	[ItemID] [int] NOT NULL,
	[OpeningStock] [numeric](18, 3) NULL,
	[Stock] [numeric](18, 3) NULL,
	[OpeningBadStock] [numeric](18, 3) NULL,
	[BadStock] [numeric](18, 3) NULL,
	[ItemCostPrice] [numeric](18, 3) NULL,
	[futureint] [int] NULL,
	[futuredate] [datetime] NULL,
	[futurevarchar] [varchar](50) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_MOsShopStock] PRIMARY KEY NONCLUSTERED 
(
	[ShopID] ASC,
	[StockDate] ASC,
	[ShipmentID] ASC,
	[ItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idxItemID] ON [dbo].[MOsShopStock] 
(
	[ItemID] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [idxShopId] ON [dbo].[MOsShopStock] 
(
	[ShopID] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_2085582468] ON [dbo].[MOsShopStock] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosLocalPurchaseDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LosLocalPurchaseDetail](
	[lpdShopID] [int] NOT NULL,
	[lpdBillID] [int] NOT NULL,
	[lpdItemID] [int] NOT NULL,
	[lpdPOQuantity] [numeric](18, 3) NULL,
	[lpdPOUnitPrice] [numeric](18, 8) NULL,
	[lpdItemQuantity] [numeric](18, 3) NULL,
	[lpdItemUnitPrice] [numeric](18, 8) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[lpdItemActualAmount] [numeric](18, 8) NULL,
	[lpdItemTaxPercentage] [numeric](18, 2) NULL,
	[lpdItemTaxAmount] [numeric](18, 8) NULL,
	[lpdItemTaxCategory] [int] NULL,
	[lpdpackid] [numeric](18, 2) NULL,
 CONSTRAINT [PK_LosLocalPurchaseDetail] PRIMARY KEY NONCLUSTERED 
(
	[lpdShopID] ASC,
	[lpdBillID] ASC,
	[lpdItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1925581898] ON [dbo].[LosLocalPurchaseDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_loslocalpurchasedetail] ON [dbo].[LosLocalPurchaseDetail] 
(
	[lpdBillID] ASC,
	[lpdShopID] 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
/****** Object:  Table [dbo].[loPrePurchaseOrderHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loPrePurchaseOrderHeader](
	[pohPoid] [int] NOT NULL,
	[pohpono] [varchar](50) NOT NULL,
	[pohnoSupwise] [varchar](50) NULL,
	[pohPodate] [datetime] NULL,
	[pohVendorID] [int] NULL,
	[pohSupAddr] [varchar](250) NULL,
	[pohdueDate] [datetime] NULL,
	[pohdeliveryaddr] [varchar](250) NULL,
	[pohRefNo] [varchar](50) NULL,
	[pohcancel] [bit] NOT NULL,
	[pohcancelremarks] [varchar](250) NULL,
	[pohPosted] [bit] NOT NULL,
	[pohrecadduser] [varchar](50) NULL,
	[pohrecmoduser] [varchar](50) NULL,
	[pohbillgenerated] [bit] NOT NULL,
	[pohremarks] [varchar](250) NULL,
	[pohtype] [char](2) NULL,
	[pohValue] [numeric](18, 2) NULL,
	[pogenerated] [bit] NOT NULL,
	[pohpogenerated] [bit] NOT NULL,
	[pohQuotationid] [int] NULL,
	[pohUsedinPayments] [bit] NOT NULL,
	[pohLCopened] [bit] NOT NULL,
	[pohDepartmentid] [int] NULL,
	[pohLCAccountid] [int] NULL,
	[pohPurchaseAccountid] [int] NULL,
	[pohLCdueon] [datetime] NULL,
	[pohLCAmount] [numeric](18, 2) NULL,
	[pohLCNumber] [varchar](50) NULL,
	[pohLCRemarks] [varchar](250) NULL,
	[pohcompanyid] [int] NULL,
	[pohLcMarginOpened] [bit] NOT NULL,
	[pohCostingDone] [char](1) NULL,
	[pohDeliveryTerms] [varchar](500) NULL,
	[pohppconfirmed] [bit] NOT NULL,
	[pohpoonhold] [bit] NULL,
	[pohfuturevc] [varchar](250) NOT NULL,
	[pohshipmentmode] [varchar](50) NULL,
	[pohpaymentmode] [varchar](50) NULL,
	[pohpurpose] [varchar](50) NULL,
	[pohshopid] [int] NULL,
	[pohrequestid] [int] NULL,
	[updatetime] [datetime] NOT NULL,
	[pohbofladno] [varchar](50) NULL,
	[Pohbofladdate] [datetime] NULL,
	[Pohbofladdetails] [varchar](250) NULL,
	[pohexchangerates] [varchar](250) NULL,
	[pohcmpexrate] [numeric](18, 8) NULL,
	[pohdepexrate] [numeric](18, 8) NULL,
	[pohfinancialid] [int] NULL,
	[pohProjectStartDate] [datetime] NULL,
	[pohProjectEndDate] [datetime] NULL,
	[pohProjectOtherInfo] [varchar](1000) NULL,
	[pohCustomDutyByCustomer] [bit] NULL,
	[pohTransportation] [varchar](50) NULL,
	[pohPotime] [datetime] NULL,
	[pohSubDepartmentID] [int] NULL,
	[PohAuthorized] [int] NULL,
	[pohVerified] [int] NULL,
	[pohSingleItemCatChecked] [bit] NULL,
	[pohSingleItemCatId] [int] NULL,
 CONSTRAINT [PK_loPrePurchaseOrderHeader] PRIMARY KEY NONCLUSTERED 
(
	[pohPoid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loPrePurchaseOrderDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loPrePurchaseOrderDetail](
	[podPoid] [int] NOT NULL,
	[poditemid] [int] NOT NULL,
	[podDetailID] [int] NOT NULL,
	[podpackingtypeID] [int] NULL,
	[podQty] [numeric](18, 3) NULL,
	[podUnitPrice] [numeric](18, 8) NULL,
	[poddescription] [varchar](250) NULL,
	[podstatus] [char](1) NULL,
	[podstatusinfo] [varchar](100) NULL,
	[podlastbillrate] [numeric](18, 2) NULL,
	[podcostingvalue] [int] NULL,
	[podcostingprice] [numeric](18, 2) NULL,
	[podbillunitprice] [numeric](18, 2) NULL,
	[podcustomdutyamount] [numeric](18, 2) NULL,
	[podocperitem] [numeric](28, 22) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[poddiscount] [numeric](18, 2) NULL,
	[poddiscountprice] [numeric](18, 2) NULL,
	[podsellingprice] [numeric](18, 2) NULL,
	[podRoyalty] [numeric](18, 2) NULL,
	[podLstCustRate] [numeric](18, 0) NULL,
	[podItemTaxPercentage] [numeric](18, 2) NULL,
	[podtemTaxAmount] [numeric](18, 2) NULL,
	[podItemTaxCategory] [numeric](18, 2) NULL,
 CONSTRAINT [PK_loPrePurchaseOrderDetail] PRIMARY KEY NONCLUSTERED 
(
	[podPoid] ASC,
	[poditemid] ASC,
	[podDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aGodownDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aGodownDetail](
	[GodownID] [int] NOT NULL,
	[ItemID] [int] NOT NULL,
	[ItemReorderLevel] [numeric](18, 3) NULL,
	[ReorderQuantity] [numeric](18, 3) NULL,
	[OrderRaised] [bit] NOT NULL,
	[QuotationRaised] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aGodownDetail] PRIMARY KEY NONCLUSTERED 
(
	[GodownID] ASC,
	[ItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1461580245] ON [dbo].[aGodownDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aHQDespatchNoteDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aHQDespatchNoteDetails](
	[ddDespatchnoteID] [int] NOT NULL,
	[ddItemID] [int] NOT NULL,
	[ddGodownid] [int] NULL,
	[ddDetailID] [int] NOT NULL,
	[ddShopID] [int] NULL,
	[ddPackingTypeID] [int] NULL,
	[ddQty] [numeric](18, 3) NULL,
	[ddCostPrice] [numeric](18, 2) NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aHQDespatchNoteDetails] PRIMARY KEY NONCLUSTERED 
(
	[ddDespatchnoteID] ASC,
	[ddDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1144495256] ON [dbo].[aHQDespatchNoteDetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOsGoodsArrivaltoShopDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOsGoodsArrivaltoShopDetail](
	[gadArrivalID] [int] NOT NULL,
	[gadShopid] [int] NOT NULL,
	[gadShipmentID] [int] NOT NULL,
	[gadItemID] [int] NOT NULL,
	[gadItemGoodQuantity] [numeric](18, 3) NULL,
	[gadItemBAdQuantity] [numeric](18, 3) NULL,
	[gadItemGoodQuantityArrived] [numeric](18, 3) NULL,
	[gadItemBadQuantityArrived] [numeric](18, 3) NULL,
	[gadcostprice] [numeric](18, 2) NULL,
	[gadpackingtypeid] [int] NULL,
	[gadpackqty] [numeric](18, 3) NULL,
	[gadreceivepackqty] [numeric](18, 3) NULL,
 CONSTRAINT [PK_LOsGoodsArrivaltoShopDetail] PRIMARY KEY NONCLUSTERED 
(
	[gadArrivalID] ASC,
	[gadShopid] ASC,
	[gadShipmentID] ASC,
	[gadItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_losgoodsarrivaltoshopdetail] ON [dbo].[LOsGoodsArrivaltoShopDetail] 
(
	[gadArrivalID] ASC,
	[gadShopid] 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
/****** Object:  Table [dbo].[loilocationissuedetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[loilocationissuedetails](
	[lidinterfaceid] [int] NOT NULL,
	[lidgodownid] [int] NOT NULL,
	[lidtransactionid] [int] NOT NULL,
	[liddetailid] [int] NOT NULL,
	[lidlocationid] [int] NULL,
	[liditemid] [int] NULL,
	[liditemqty] [numeric](18, 3) NULL,
	[lidpackingtypeid] [int] NULL,
	[lidpakingqty] [numeric](18, 3) NULL,
	[lidcancel] [bit] NOT NULL,
	[lidadjustment] [bit] NOT NULL,
	[lidconfirmed] [int] NOT NULL,
 CONSTRAINT [PK_loilocationissuedetails] PRIMARY KEY NONCLUSTERED 
(
	[lidinterfaceid] ASC,
	[lidgodownid] ASC,
	[lidtransactionid] ASC,
	[liddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aShopItemDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aShopItemDetail](
	[ShopID] [int] NOT NULL,
	[ItemID] [int] NOT NULL,
	[ItemReorderLevel] [numeric](18, 3) NULL,
	[RequestRaised] [bit] NOT NULL,
	[ReorderQuantity] [numeric](18, 3) NULL,
	[ShortcutNo] [int] NULL,
	[orderraised] [bit] NOT NULL,
	[quotationraised] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aShopItemDetail] PRIMARY KEY NONCLUSTERED 
(
	[ShopID] ASC,
	[ItemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1797581442] ON [dbo].[aShopItemDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[mesRequesttoShopDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[mesRequesttoShopDetail](
	[SRDrequestid] [int] NOT NULL,
	[srdshopid] [int] NOT NULL,
	[srditemid] [int] NOT NULL,
	[srdToShopid] [int] NULL,
	[srdgoodqty] [numeric](18, 3) NULL,
	[srdbadqty] [numeric](18, 3) NULL,
	[srdSellingPrice] [numeric](18, 2) NULL,
 CONSTRAINT [PK_mesShopRequestDetail] PRIMARY KEY NONCLUSTERED 
(
	[SRDrequestid] ASC,
	[srdshopid] ASC,
	[srditemid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOspPurchaseBillDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOspPurchaseBillDetail](
	[pbdBillID] [int] NOT NULL,
	[pbdItemID] [int] NOT NULL,
	[pbdDetailID] [int] NOT NULL,
	[pbdPackingTypeID] [int] NULL,
	[pbdPOQuantity] [numeric](18, 3) NULL,
	[pbdPOUnitPrice] [numeric](18, 8) NULL,
	[pbdItemQuantity] [numeric](18, 3) NULL,
	[pbdItemUnitPrice] [numeric](28, 16) NULL,
	[pbdDummyUnitPrice] [numeric](28, 16) NULL,
	[pbdItemCostedPrice] [numeric](18, 8) NULL,
	[pbdItemFixedPrice] [numeric](18, 8) NULL,
	[pbddiscount] [numeric](18, 2) NULL,
	[pbdpoid] [int] NULL,
	[pbdsellingprice] [numeric](18, 2) NULL,
	[pbdwholesaleprice] [numeric](18, 2) NULL,
	[pbddiscountprice] [numeric](18, 2) NULL,
	[pbdbatchno] [varchar](50) NULL,
	[pbdItemTaxPercentage] [numeric](18, 2) NULL,
	[pbdItemTaxAmount] [numeric](18, 2) NULL,
	[pbdItemTaxCategory] [int] NULL,
 CONSTRAINT [PK_LOspPurchaseBillDetail] PRIMARY KEY NONCLUSTERED 
(
	[pbdBillID] ASC,
	[pbdItemID] ASC,
	[pbdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aPurchasePriceRangeHistory]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aPurchasePriceRangeHistory](
	[SlNo] [int] NOT NULL,
	[CompanyId] [int] NOT NULL,
	[ItemId] [int] NOT NULL,
	[MinPrice] [numeric](18, 2) NOT NULL,
	[MaxPrice] [numeric](18, 2) NOT NULL,
	[CurrencyId] [int] NOT NULL,
	[UpdateTime] [datetime] NULL,
	[UpdateUser] [nvarchar](50) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losExportHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losExportHeader](
	[rehExportID] [int] NOT NULL,
	[rehShopID] [int] NOT NULL,
	[rehExportNo] [varchar](50) NULL,
	[rehExportDate] [datetime] NULL,
	[rehReferenceNo] [varchar](50) NULL,
	[rehVendorID] [int] NULL,
	[rehcustomerid] [int] NULL,
	[rehProforma] [bit] NULL,
	[rehCashInvoice] [bit] NULL,
	[rehBankCashAccID] [int] NULL,
	[rehChequeNo] [varchar](10) NULL,
	[rehDueDate] [datetime] NULL,
	[rehRemarks] [varchar](250) NULL,
	[rehExportAmount] [numeric](20, 4) NULL,
	[rehDiscount] [numeric](20, 4) NULL,
	[rehDiscountAccID] [int] NULL,
	[rehDepartmentID] [int] NULL,
	[rehFinancialID] [int] NULL,
	[rehCancelled] [bit] NULL,
	[rehCancelledRemarks] [varchar](250) NULL,
	[rehExchangeNature] [varchar](50) NULL,
	[rehCompanyID] [int] NULL,
	[rehPosted] [bit] NULL,
	[rehProformaID] [int] NULL,
	[rehSalesAccID] [int] NULL,
	[rehSettled] [bit] NULL,
	[rehExchangeRate] [numeric](18, 8) NULL,
	[rehSettledAmount] [numeric](20, 4) NULL,
	[rehWholeSale] [bit] NULL,
	[rehFutureVC] [varchar](250) NULL,
	[rehUpdatetime] [datetime] NULL,
	[rehSalesPersonID] [int] NULL,
	[rehShip] [varchar](50) NULL,
	[rehPortofLoading] [varchar](50) NULL,
	[rehShipDepDate] [datetime] NULL,
	[rehShipDischarge] [varchar](50) NULL,
	[rehShipArrivalDate] [datetime] NULL,
	[rehFinalDestination] [varchar](50) NULL,
	[rehDeliveryDate] [datetime] NULL,
	[rehgstpercentage] [numeric](18, 0) NULL,
	[rehPaymentterm] [varchar](250) NULL,
	[updatetime] [datetime] NULL,
	[rehDepExRate] [numeric](18, 8) NULL,
	[rehtype] [char](2) NULL,
	[rehcustomsformno] [varchar](100) NULL,
	[rehexchangerates] [varchar](250) NULL,
	[rehBuyerPoNo] [varchar](50) NULL,
	[rehBuyerName] [varchar](50) NULL,
	[rehBuyerAddress] [varchar](250) NULL,
	[rehLoadedDate] [datetime] NULL,
	[rehDetailsOfShipment] [varchar](250) NULL,
	[rehConsigneeName] [varchar](250) NULL,
	[rehNameOfVessel] [varchar](100) NULL,
	[rehShipmentDepartureDate] [datetime] NULL,
	[rehCustomerFormRegNo] [varchar](50) NULL,
	[rehBlOrAwbNo] [varchar](50) NULL,
	[rehMissingOrDamagedItems] [varchar](250) NULL,
	[rehInsuranceCertificateNo] [varchar](50) NULL,
	[rehDemurrageRemarkds] [varchar](250) NULL,
	[rehContainerNo] [varchar](50) NULL,
	[rehTerminate] [bit] NULL,
	[rehTerminateRemarks] [varchar](250) NULL,
	[rehBankName] [varchar](100) NULL,
	[rehBankaddress] [varchar](250) NULL,
	[rehSwiftaddress] [varchar](250) NULL,
	[rehAdvanceAmt] [numeric](18, 2) NULL,
	[rehPriceType] [varchar](100) NULL,
 CONSTRAINT [pk_losexportheader] PRIMARY KEY CLUSTERED 
(
	[rehExportID] ASC,
	[rehShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_losexportheader_rehExportDate] ON [dbo].[losExportHeader] 
(
	[rehExportDate] 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
CREATE NONCLUSTERED INDEX [index_losexportheader] ON [dbo].[losExportHeader] 
(
	[rehExportID] ASC,
	[rehShopID] ASC,
	[rehCancelled] ASC,
	[rehProforma] ASC,
	[rehtype] 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
/****** Object:  Table [dbo].[losExportDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losExportDetail](
	[redShopID] [int] NOT NULL,
	[redExportID] [int] NOT NULL,
	[redItemID] [int] NOT NULL,
	[redPckingTypeID] [int] NOT NULL,
	[redPUnitID] [int] NOT NULL,
	[redQuantity] [numeric](18, 2) NULL,
	[redUnitPrice] [numeric](20, 4) NULL,
	[redRateType] [numeric](18, 2) NULL,
	[redActualUnitPrice] [numeric](20, 4) NULL,
	[redCostPrice] [numeric](20, 4) NULL,
	[redDescription] [varchar](250) NULL,
	[redbLockPrice] [numeric](20, 4) NULL,
	[redguarantee] [varchar](250) NULL,
	[redrebateamount] [numeric](20, 4) NULL,
	[redcorgin] [int] NULL,
	[redcconsignment] [int] NULL,
	[redcdcomcur] [numeric](20, 4) NULL,
	[redcdcustcur] [numeric](20, 4) NULL,
	[redcdcomcurtocustoms] [numeric](20, 4) NULL,
	[redcdcustcurtocustoms] [numeric](20, 4) NULL,
	[redPQuantity] [numeric](18, 0) NULL,
	[redroyaltyamt] [numeric](18, 2) NULL,
	[redRoyalty] [numeric](18, 2) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [index_losexportdetail] ON [dbo].[losExportDetail] 
(
	[redExportID] ASC,
	[redShopID] 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
/****** Object:  Table [dbo].[mosGoodsRequestDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[mosGoodsRequestDetail](
	[GRDrequestID] [int] NOT NULL,
	[GRDshopID] [int] NOT NULL,
	[GRDitemID] [int] NOT NULL,
	[GRDgoodQty] [numeric](18, 3) NULL,
	[GRDbadQty] [numeric](18, 3) NULL,
	[grdreqcomments] [varchar](250) NULL,
	[grdReqorderstat] [char](10) NULL,
	[grdexpectremarks] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[GRDDetailID] [int] NULL,
 CONSTRAINT [PK_mosGoodsRequestDetail] PRIMARY KEY NONCLUSTERED 
(
	[GRDrequestID] ASC,
	[GRDshopID] ASC,
	[GRDitemID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1205579333] ON [dbo].[mosGoodsRequestDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOsPosDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsPosDetail](
	[posdShopID] [int] NOT NULL,
	[posdBillID] [int] NOT NULL,
	[posdItemID] [int] NOT NULL,
	[posdPackingTypeID] [int] NOT NULL,
	[posdPUnitID] [int] NULL,
	[posdPQuantity] [numeric](18, 3) NULL,
	[posdQuantity] [numeric](18, 3) NULL,
	[posdUnitPrice] [numeric](18, 8) NULL,
	[posdRateType] [int] NOT NULL,
	[posdActualUnitPrice] [numeric](18, 2) NULL,
	[posdcostprice] [numeric](18, 2) NULL,
	[posddescription] [varchar](250) NULL,
	[posdblockprice] [numeric](18, 2) NULL,
	[posdguarantee] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[posdSerialNo] [varchar](250) NULL,
	[posdFreeQuantity] [numeric](18, 3) NULL,
	[posdItemSerialNo] [int] NULL,
	[posdKitID] [int] NOT NULL,
	[posdKitQuantity] [numeric](18, 2) NULL,
	[posdKitActualPrice] [numeric](18, 2) NULL,
	[posdServWarrantyUpto] [datetime] NULL,
	[posdPartsWarrantyUpto] [datetime] NULL,
	[posdItemTaxPercentage] [numeric](18, 2) NULL,
	[posdItemTaxAmount] [numeric](18, 8) NULL,
	[posdItemTaxCategory] [int] NULL,
	[posdBillDetailID] [int] NULL,
	[posdItemType] [varchar](10) NULL,
 CONSTRAINT [PK_LOsPosDetail] PRIMARY KEY NONCLUSTERED 
(
	[posdShopID] ASC,
	[posdBillID] ASC,
	[posdItemID] ASC,
	[posdPackingTypeID] ASC,
	[posdKitID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_962102468] ON [dbo].[LOsPosDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_losposdetail] ON [dbo].[LOsPosDetail] 
(
	[posdBillID] ASC,
	[posdShopID] 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
/****** Object:  Table [dbo].[loiStockRecovery]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loiStockRecovery](
	[srID] [int] NOT NULL,
	[srGodownID] [int] NOT NULL,
	[srDate] [datetime] NULL,
	[srItemID] [int] NULL,
	[srcostprice] [numeric](18, 2) NULL,
	[srAddStock] [numeric](18, 3) NULL,
	[srDedStock] [numeric](18, 3) NULL,
	[srUserName] [varchar](50) NULL,
	[srposted] [bit] NOT NULL,
	[srfutureint] [int] NULL,
	[updatetime] [datetime] NOT NULL,
	[srtransno] [varchar](50) NULL,
	[srlocid] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[srConExRate] [numeric](18, 8) NULL,
	[srDepExRate] [numeric](18, 8) NULL,
	[srExchangeRates] [varchar](250) NULL,
	[srTransDate] [datetime] NULL,
 CONSTRAINT [PK_loiStockRecovery] PRIMARY KEY NONCLUSTERED 
(
	[srID] ASC,
	[srGodownID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aserviceitemdetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aserviceitemdetails](
	[ServiceId] [int] NULL,
	[ItemId] [int] NULL,
	[Detailid] [int] NULL,
	[Quantity] [numeric](18, 3) NULL,
	[PackId] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[loaItemSplitCostingDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[loaItemSplitCostingDetail](
	[scfdid] [int] NOT NULL,
	[scfddetailid] [int] NOT NULL,
	[scfdItemid] [int] NULL,
	[scfdQuantity] [numeric](18, 3) NULL,
	[scfdCostprice] [numeric](18, 2) NULL,
	[scfdFixedPrice] [numeric](18, 2) NULL,
	[scfdOldItemRate] [numeric](18, 2) NULL,
 CONSTRAINT [PK_loaItemSplitCostingDetail] PRIMARY KEY NONCLUSTERED 
(
	[scfdid] ASC,
	[scfddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aGodownItemCategory]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aGodownItemCategory](
	[Godownid] [int] NOT NULL,
	[categoryID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aGodownItemCategory] PRIMARY KEY NONCLUSTERED 
(
	[Godownid] ASC,
	[categoryID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_229575856] ON [dbo].[aGodownItemCategory] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aShopitemCategory]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aShopitemCategory](
	[shopid] [int] NOT NULL,
	[itemcategoryid] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aShopitemCategory] PRIMARY KEY NONCLUSTERED 
(
	[shopid] ASC,
	[itemcategoryid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_405576483] ON [dbo].[aShopitemCategory] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losDeliveryNoteImage]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losDeliveryNoteImage](
	[CompanyId] [int] NOT NULL,
	[ShopId] [int] NOT NULL,
	[DeliveryNoteId] [int] NOT NULL,
	[DeliveryNoteImage] [image] NULL,
 CONSTRAINT [PK_losDeliveryNoteImage] PRIMARY KEY CLUSTERED 
(
	[CompanyId] ASC,
	[ShopId] ASC,
	[DeliveryNoteId] 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]
GO
/****** Object:  Table [dbo].[aListItemDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aListItemDetails](
	[ListID] [int] NOT NULL,
	[ItemID] [int] NOT NULL,
	[Qty] [numeric](18, 2) NOT NULL,
	[PackingTypeID] [int] NOT NULL,
	[PQty] [numeric](18, 2) NOT NULL,
 CONSTRAINT [PK_aListItemDetails] PRIMARY KEY CLUSTERED 
(
	[ListID] ASC,
	[ItemID] ASC,
	[PackingTypeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[FlightOperatorMaster]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[FlightOperatorMaster](
	[companyid] [int] NOT NULL,
	[FlghtOpid] [int] NOT NULL,
	[FlghtOpName] [varchar](100) NOT NULL,
	[FlghtSegID] [int] NOT NULL,
	[Createddate] [datetime] NOT NULL,
	[Remarks] [varchar](250) NULL,
	[Active] [bit] NOT NULL,
 CONSTRAINT [pk_FlghtOpIDMaster] PRIMARY KEY CLUSTERED 
(
	[companyid] ASC,
	[FlghtOpid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [Unique_FlightOperatorName] UNIQUE NONCLUSTERED 
(
	[FlghtOpName] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Flights]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Flights](
	[companyid] [int] NOT NULL,
	[FlightID] [int] NOT NULL,
	[FlightOpid] [int] NOT NULL,
	[FlightNo] [varchar](50) NOT NULL,
	[FlightDepDay] [int] NULL,
	[FlightDepTime] [datetime] NULL,
	[Remarks] [varchar](250) NULL,
	[Active] [bit] NULL,
 CONSTRAINT [PK_Flights_1] PRIMARY KEY CLUSTERED 
(
	[companyid] ASC,
	[FlightID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [Unique_FlightNo] UNIQUE NONCLUSTERED 
(
	[FlightNo] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[VoucherMaster]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[VoucherMaster](
	[VoucherID] [int] NOT NULL,
	[VoucherName] [varchar](50) NOT NULL,
	[VoucherAmount] [decimal](18, 2) NOT NULL,
	[VoucherCurrencyID] [int] NOT NULL,
	[VoucherCompanyID] [int] NOT NULL,
	[VoucherActive] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_VoucherMaster] PRIMARY KEY CLUSTERED 
(
	[VoucherID] ASC,
	[VoucherCompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [Unique_VoucherName] UNIQUE NONCLUSTERED 
(
	[VoucherName] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LosPosFAndBHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosPosFAndBHeader](
	[poshShopID] [int] NOT NULL,
	[poshBillID] [int] NOT NULL,
	[poshBillNo] [varchar](50) NULL,
	[poshBillDate] [datetime] NULL,
	[poshCustomerName] [varchar](100) NULL,
	[poshCancelled] [bit] NOT NULL,
	[poshCancelledRemarks] [varchar](250) NULL,
	[poshRecAddUser] [varchar](50) NULL,
	[poshRecModifyUser] [varchar](50) NULL,
	[poshPosted] [bit] NOT NULL,
	[poshDiscount] [decimal](18, 2) NULL,
	[poshBillAmount] [decimal](18, 4) NULL,
	[poshCashAccID] [int] NULL,
	[poshSalesAccID] [int] NULL,
	[poshCompanyID] [int] NULL,
	[poshReturned] [bit] NOT NULL,
	[poshWholesale] [bit] NOT NULL,
	[poshcbid] [int] NULL,
	[poshExchangeRate] [decimal](28, 8) NOT NULL,
	[poshfuturevc] [varchar](250) NOT NULL,
	[updatetime] [datetime] NOT NULL,
	[poshDepartmentid] [int] NULL,
	[poshsalespersonid] [int] NULL,
	[poshCustomerCardNo] [varchar](100) NULL,
	[poshbillorprocess] [char](5) NULL,
	[poshfutureint] [int] NULL,
	[poshtableid] [int] NULL,
	[poshemployeeid] [int] NULL,
	[poshdiscid] [int] NULL,
	[poshdiscper] [decimal](18, 2) NULL,
	[poshservicechargeid] [int] NULL,
	[poshservicechargeper] [decimal](18, 2) NULL,
	[poshtaxaccid] [int] NULL,
	[poshcentraltaxaccid] [int] NULL,
	[poshtaxper] [decimal](18, 2) NULL,
	[poshcustomerid] [int] NULL,
	[poshcustdiscount] [decimal](18, 2) NULL,
	[roomdetailid] [int] NULL,
	[poshgbillno] [varchar](50) NULL,
	[poshgbilldate] [datetime] NULL,
	[Billedto] [varchar](250) NULL,
	[receipted] [bit] NOT NULL,
	[poshfolioid] [int] NULL,
	[salesbillbit] [bit] NOT NULL,
	[poshremarks] [varchar](250) NULL,
	[poshcash] [bit] NOT NULL,
	[complimentary] [int] NULL,
	[poshCreditCardNo] [varchar](100) NULL,
	[PoshBuffetBit] [bit] NULL,
	[PoshMealnameid] [int] NULL,
	[poshgBillUser] [varchar](50) NULL,
	[poshtelephone] [bit] NULL,
	[cashreceiptid] [int] NULL,
	[poshmiscbillrefno] [int] NULL,
	[closebill] [bit] NULL,
	[poshservicecharge] [numeric](18, 2) NULL,
	[poshAccAuditid] [int] NULL,
	[poshSettled] [int] NULL,
	[PoshStatus] [varchar](50) NULL,
	[poshtips] [decimal](8, 2) NULL,
	[poshBillType] [varchar](50) NULL,
	[PoshBillCount] [int] NULL,
	[poshGrossTotal] [numeric](8, 2) NULL,
	[poshServiceID] [int] NULL,
	[poshDishTakenPax] [int] NULL,
	[poshCashSale] [int] NULL,
	[poshexchangerates] [varchar](250) NOT NULL,
	[poshdepexrate] [numeric](18, 8) NOT NULL,
	[poshvoucherid] [int] NULL,
	[poshCurrencyID] [int] NULL,
	[poshRateType] [int] NULL,
	[poshFinancialId] [int] NULL,
	[poshFlightID] [int] NULL,
	[poshTillID] [int] NULL,
	[poshFlightOpID] [int] NULL,
	[poshTillHistID] [int] NULL,
	[poshUserID] [int] NULL,
	[poshVoucherAmt] [decimal](18, 2) NULL,
	[PoshCounterID] [int] NULL,
	[poshSegID] [int] NULL,
 CONSTRAINT [PK_LosPosFAndBHeader] PRIMARY KEY NONCLUSTERED 
(
	[poshShopID] ASC,
	[poshBillID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [IX_LosPosFAndBHeader_poshcompanyid] ON [dbo].[LosPosFAndBHeader] 
(
	[poshCompanyID] 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
CREATE NONCLUSTERED INDEX [IX_LosPosFAndBHeader_poshgBillNo] ON [dbo].[LosPosFAndBHeader] 
(
	[poshgbillno] 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
CREATE NONCLUSTERED INDEX [IX_LosPosFAndBHeader_poshgBillUser] ON [dbo].[LosPosFAndBHeader] 
(
	[poshgBillUser] 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
CREATE NONCLUSTERED INDEX [IX_LosPosFAndBHeader_poshRecAddUser] ON [dbo].[LosPosFAndBHeader] 
(
	[poshRecAddUser] 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
CREATE NONCLUSTERED INDEX [IX_LosPosFAndBHeader_poshRecModifyUser] ON [dbo].[LosPosFAndBHeader] 
(
	[poshRecModifyUser] 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
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'CR-Credit,CA-Cash,VO-Voucher,NP-NoPay,VCA-Voucher&Cash,VCR-Voucher&Credit' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'LosPosFAndBHeader', @level2type=N'COLUMN',@level2name=N'poshBillType'
GO
/****** Object:  Table [dbo].[Fb_processdetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Fb_processdetail](
	[fb_pd_companyid] [int] NOT NULL,
	[fb_pd_outletid] [int] NOT NULL,
	[fb_pd_processid] [int] NOT NULL,
	[fb_pd_processdetailid] [int] NOT NULL,
	[fb_pd_kotid] [int] NULL,
	[fb_pd_botid] [int] NULL,
	[fb_pd_dishid] [int] NOT NULL,
	[fb_pd_reusedqty] [decimal](18, 2) NULL,
	[fb_pd_Rate] [decimal](18, 2) NULL,
	[fb_pd_cost] [decimal](18, 2) NULL,
	[fb_pd_Actualrate] [decimal](18, 2) NULL,
	[fb_pd_discountper] [decimal](18, 2) NULL,
	[fb_pd_centraltaxper] [decimal](18, 2) NULL,
	[fb_pd_statetaxper] [decimal](18, 2) NULL,
	[fb_pd_usedqty] [decimal](18, 2) NULL,
	[fd_pd_discountid] [int] NULL,
	[fb_pd_AddedItemtype] [int] NULL,
	[fb_pd_DishTaxPercentage] [numeric](18, 2) NULL,
	[fb_pd_DishTaxAmount] [numeric](18, 2) NULL,
	[fb_pd_DishTaxCategoryId] [int] NULL,
	[fb_pd_packingtypeid] [int] NULL,
	[fb_pd_dishidofextra] [int] NULL,
 CONSTRAINT [PK_Fb_processdetail] PRIMARY KEY NONCLUSTERED 
(
	[fb_pd_companyid] ASC,
	[fb_pd_outletid] ASC,
	[fb_pd_processid] ASC,
	[fb_pd_processdetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aListViewDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aListViewDetails](
	[lvwdid] [int] NOT NULL,
	[lvwcolid] [int] NOT NULL,
	[lvwdcolname] [varchar](50) NULL,
	[lvwdcolwidth] [int] NOT NULL,
	[lvwdcolalign] [int] NOT NULL,
	[lvwdlistcoltype] [numeric](18, 0) NULL,
	[lvwdcolprec] [numeric](18, 0) NULL,
 CONSTRAINT [PK_aListViewDetails] PRIMARY KEY NONCLUSTERED 
(
	[lvwdid] ASC,
	[lvwcolid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aLoyaltyCardContactDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aLoyaltyCardContactDetails](
	[CompanyID] [int] NOT NULL,
	[ID] [int] NOT NULL,
	[CardID] [int] NOT NULL,
	[ContactID] [int] NOT NULL,
	[UserName] [varchar](50) NOT NULL,
	[ExpiryDate] [datetime] NOT NULL,
	[CardNo] [varchar](50) NOT NULL,
 CONSTRAINT [PK_aLoyaltyCardContactDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[ID] ASC,
	[CardID] ASC,
	[ContactID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aPackingTypeCapacityDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aPackingTypeCapacityDetail](
	[PackingTypeID] [int] NOT NULL,
	[UnitsID] [int] NOT NULL,
	[Quantity] [numeric](18, 5) NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aPackingTypeCapacityDetail] PRIMARY KEY NONCLUSTERED 
(
	[PackingTypeID] ASC,
	[UnitsID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [idxPack] ON [dbo].[aPackingTypeCapacityDetail] 
(
	[PackingTypeID] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1093578934] ON [dbo].[aPackingTypeCapacityDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[mesRQtoHQforItem]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[mesRQtoHQforItem](
	[ShopID] [int] NOT NULL,
	[RequestID] [int] NOT NULL,
	[ItemCode] [varchar](50) NULL,
	[ItemDescription] [varchar](250) NULL,
	[Barcode] [varchar](50) NULL,
	[UnitID] [int] NULL,
	[PackingTypeID] [int] NULL,
	[ColorID] [int] NULL,
	[SizeID] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_mesRQtoHQforItem] PRIMARY KEY NONCLUSTERED 
(
	[ShopID] ASC,
	[RequestID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1093578934] ON [dbo].[mesRQtoHQforItem] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[meiRQtoHQforItem]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[meiRQtoHQforItem](
	[GodownID] [int] NOT NULL,
	[RequestID] [int] NOT NULL,
	[ItemCode] [varchar](50) NULL,
	[ItemDescription] [varchar](250) NULL,
	[Barcode] [varchar](50) NULL,
	[UnitID] [int] NULL,
	[PackingTypeID] [int] NULL,
	[ColorID] [int] NULL,
	[SizeID] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_meiRQtoHQforItem] PRIMARY KEY NONCLUSTERED 
(
	[GodownID] ASC,
	[RequestID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1781581385] ON [dbo].[meiRQtoHQforItem] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TillDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TillDetail](
	[till_td_detailid] [int] NOT NULL,
	[till_td_tillid] [int] NOT NULL,
	[till_td_currencyid] [int] NOT NULL,
	[till_td_amount] [numeric](18, 2) NOT NULL,
	[till_td_companyid] [int] NOT NULL,
	[till_td_outletid] [int] NOT NULL,
 CONSTRAINT [PK_TillDetail] PRIMARY KEY CLUSTERED 
(
	[till_td_detailid] ASC,
	[till_td_tillid] ASC,
	[till_td_companyid] ASC,
	[till_td_outletid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [Unique_TillHeaderID_TillCurrencyID] UNIQUE NONCLUSTERED 
(
	[till_td_tillid] ASC,
	[till_td_currencyid] ASC,
	[till_td_outletid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[AgreementDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[AgreementDetails](
	[agdAgreementid] [int] NOT NULL,
	[agdDepartmentid] [int] NOT NULL,
	[agdDetailid] [int] NOT NULL,
	[agdDetails] [varchar](250) NULL,
 CONSTRAINT [PK_AgreementDetails] PRIMARY KEY NONCLUSTERED 
(
	[agdAgreementid] ASC,
	[agdDepartmentid] ASC,
	[agdDetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[AgreementContents]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[AgreementContents](
	[agcagreementid] [int] NOT NULL,
	[agcDepartmentid] [int] NOT NULL,
	[agcDetailid] [int] NOT NULL,
	[agcContentdesc] [varchar](100) NULL,
	[agcRemark] [varchar](250) NULL,
 CONSTRAINT [PK_AgreementContents] PRIMARY KEY NONCLUSTERED 
(
	[agcagreementid] ASC,
	[agcDepartmentid] ASC,
	[agcDetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[AgreementWitnessDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[AgreementWitnessDetails](
	[agwAgreementid] [int] NOT NULL,
	[agwDepartmentid] [int] NOT NULL,
	[agwDetailid] [int] NOT NULL,
	[agwSignedBy] [varchar](50) NULL,
	[agwPostion] [varchar](50) NULL,
	[agwSignedDate] [datetime] NULL,
	[agwWitenessAddress] [varchar](250) NULL,
	[agwAgency] [bit] NULL,
 CONSTRAINT [PK_AgreementWitnessDetails] PRIMARY KEY NONCLUSTERED 
(
	[agwAgreementid] ASC,
	[agwDepartmentid] ASC,
	[agwDetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[AgreementSignedDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[AgreementSignedDetails](
	[agsagreementid] [int] NOT NULL,
	[agsDepartmentid] [int] NOT NULL,
	[agsDetailid] [int] NOT NULL,
	[agsSignedBy] [varchar](50) NULL,
	[agsPosition] [varchar](50) NULL,
	[agsSignedDate] [datetime] NULL,
	[agsAgency] [bit] NULL,
 CONSTRAINT [PK_AgreementSignedDetails] PRIMARY KEY NONCLUSTERED 
(
	[agsagreementid] ASC,
	[agsDepartmentid] ASC,
	[agsDetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[AgreementFinancialDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[AgreementFinancialDetails](
	[agfAgreementid] [int] NOT NULL,
	[agfDepartmentId] [int] NOT NULL,
	[agffinanceDetailid] [int] NOT NULL,
	[agffinanceDetail] [varchar](250) NULL,
 CONSTRAINT [PK_AgreementFinancialDetails] PRIMARY KEY NONCLUSTERED 
(
	[agfAgreementid] ASC,
	[agfDepartmentId] ASC,
	[agffinanceDetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ReceiptVoucherCustomerDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ReceiptVoucherCustomerDetails](
	[Companyid] [int] NOT NULL,
	[ReceiptId] [int] NOT NULL,
	[Detailid] [int] NOT NULL,
	[CustomerId] [int] NULL,
	[Amount] [numeric](18, 2) NULL,
	[CustomerAmount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_ReceiptVoucherCustomerDetails] PRIMARY KEY NONCLUSTERED 
(
	[Companyid] ASC,
	[ReceiptId] ASC,
	[Detailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ReceiptVoucherDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ReceiptVoucherDetails](
	[ReceiptID] [int] NOT NULL,
	[ReceiptDetailID] [int] NOT NULL,
	[CompanyID] [int] NULL,
	[hqAccountsInvoiceID] [int] NULL,
	[shopid] [int] NULL,
	[posaccountsInvoiceID] [int] NULL,
	[posinvoiceid] [int] NULL,
	[posspinvoiceid] [int] NULL,
	[Posserviceinvoiceid] [int] NULL,
	[AmountReceived] [numeric](18, 2) NULL,
	[dcnid] [int] NULL,
	[dueperiod] [smallint] NULL,
	[phpaymentid] [int] NULL,
	[losdcnid] [int] NULL,
	[posexportid] [int] NULL,
	[RoomBillID] [int] NULL,
	[UtilityBillID] [int] NULL,
	[AccInvoiceID] [int] NULL,
	[fineid] [int] NULL,
	[fandbInvoiceID] [int] NULL,
 CONSTRAINT [PK_ReceiptVoucherDetails] PRIMARY KEY NONCLUSTERED 
(
	[ReceiptID] ASC,
	[ReceiptDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TillBalanceHistory]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TillBalanceHistory](
	[till_hist_id] [int] NOT NULL,
	[till_currencyid] [int] NOT NULL,
	[till_amount] [numeric](18, 2) NOT NULL,
	[till_outletid] [int] NOT NULL,
	[till_companyid] [int] NOT NULL,
	[till_status] [bit] NOT NULL,
 CONSTRAINT [PK_TillBalanceHistory] PRIMARY KEY CLUSTERED 
(
	[till_hist_id] ASC,
	[till_currencyid] ASC,
	[till_outletid] ASC,
	[till_companyid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 - Open,0 - Close' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'TillBalanceHistory', @level2type=N'COLUMN',@level2name=N'till_status'
GO
/****** Object:  Table [dbo].[BudgetPlanReviseDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[BudgetPlanReviseDetail](
	[brdCompanyID] [int] NOT NULL,
	[brdBudgetPlanID] [int] NOT NULL,
	[brdDetailID] [int] NOT NULL,
	[brdDate] [datetime] NULL,
	[brdRevisedBy] [varchar](250) NULL,
	[brdApprovedBy] [varchar](250) NULL,
	[brdRemarks] [varchar](250) NULL,
	[brdConfirmed] [bit] NULL,
 CONSTRAINT [PK_BudgetPlanReviseDetail] PRIMARY KEY CLUSTERED 
(
	[brdCompanyID] ASC,
	[brdBudgetPlanID] ASC,
	[brdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[BudgetPlanDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BudgetPlanDetail](
	[bpdCompanyID] [int] NOT NULL,
	[bpdBudgetPlanID] [int] NOT NULL,
	[bpdDetailID] [int] NOT NULL,
	[bpdBudgetHeadID] [int] NULL,
	[bpdMonthNo] [int] NULL,
	[bpdAmount] [numeric](18, 2) NULL,
	[bpdRevised] [bit] NULL,
	[bpdReviseDetailId] [int] NULL,
 CONSTRAINT [PK_BudgetPlanDetail] PRIMARY KEY CLUSTERED 
(
	[bpdCompanyID] ASC,
	[bpdBudgetPlanID] ASC,
	[bpdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[BudgetitemPlanDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BudgetitemPlanDetail](
	[bpdICompanyID] [int] NOT NULL,
	[bpdIBudgetPlanID] [int] NOT NULL,
	[bpdIDetailID] [int] NOT NULL,
	[bpdIBudgetItemID] [int] NULL,
	[bpdIMonthNo] [int] NULL,
	[bpdIPurchaseAmt] [numeric](18, 2) NULL,
	[bpdISalesAmt] [numeric](18, 2) NULL,
	[bpdICostAmt] [numeric](18, 2) NULL,
	[bpditemcategory] [numeric](18, 0) NULL,
 CONSTRAINT [pk_BudgetitemPlanDetail] PRIMARY KEY CLUSTERED 
(
	[bpdICompanyID] ASC,
	[bpdIBudgetPlanID] ASC,
	[bpdIDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aTableColumns]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aTableColumns](
	[TableID] [int] NOT NULL,
	[ColumnID] [int] NOT NULL,
	[ColumnName] [varchar](50) NOT NULL,
	[ColumnDescription] [varchar](250) NULL,
	[ColumnHeader] [varchar](50) NULL,
	[ColumnType] [varchar](50) NULL,
	[ColumnLength] [smallint] NULL,
	[ColumnDecimals] [tinyint] NULL,
	[Mandatory] [bit] NOT NULL,
	[Version1] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_TableColumns] PRIMARY KEY NONCLUSTERED 
(
	[TableID] ASC,
	[ColumnID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1109578991] ON [dbo].[aTableColumns] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losSerToolsAllocationHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSerToolsAllocationHeader](
	[alchCompanyId] [int] NOT NULL,
	[alchShopid] [int] NOT NULL,
	[alchid] [int] NOT NULL,
	[alchno] [varchar](50) NOT NULL,
	[alchdate] [datetime] NULL,
	[alchtechnicianid] [int] NOT NULL,
	[alchRemarks] [varchar](50) NULL,
	[alchCancelled] [bit] NULL,
	[alchCancelledremarks] [varchar](50) NULL,
 CONSTRAINT [PK_lossertoolsallocationheader] PRIMARY KEY NONCLUSTERED 
(
	[alchCompanyId] ASC,
	[alchShopid] ASC,
	[alchid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losSerToolsAllocationDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSerToolsAllocationDetail](
	[alcdCompanyId] [int] NOT NULL,
	[alcdShopid] [int] NOT NULL,
	[alcdid] [int] NOT NULL,
	[alcdtoolsid] [int] NOT NULL,
	[alcddetailid] [int] NOT NULL,
	[alcdtechnicianid] [int] NOT NULL,
	[alcdreturned] [char](1) NOT NULL,
	[alcdfrom] [datetime] NULL,
	[alcdto] [datetime] NULL,
 CONSTRAINT [PK_lossertoolsallocationdetail] PRIMARY KEY NONCLUSTERED 
(
	[alcdCompanyId] ASC,
	[alcdShopid] ASC,
	[alcdid] ASC,
	[alcddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ASalesPersonCommisionDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ASalesPersonCommisionDetail](
	[salespersonid] [int] NOT NULL,
	[detailid] [int] NOT NULL,
	[FromRange] [numeric](18, 2) NULL,
	[ToRange] [numeric](18, 2) NULL,
	[percentage] [numeric](5, 2) NULL,
	[phPercentage] [numeric](5, 2) NULL,
 CONSTRAINT [PK_ASalesPersonCommisionDetail] PRIMARY KEY NONCLUSTERED 
(
	[salespersonid] ASC,
	[detailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[hqSalesCommisionHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[hqSalesCommisionHeader](
	[schCommisionid] [int] NOT NULL,
	[schSalesCommisionNo] [varchar](50) NULL,
	[schSalesCommisionDate] [datetime] NULL,
	[schApprovedBy] [varchar](50) NULL,
	[schCancelled] [bit] NULL,
	[schCancelledRemarks] [varchar](250) NULL,
	[schcompanyid] [int] NOT NULL,
	[schdepartmentid] [int] NULL,
	[schsalespersonid] [int] NULL,
	[schfinancialid] [int] NULL,
	[schFromDate] [datetime] NULL,
	[schToDate] [datetime] NULL,
	[schAfterSales] [bit] NULL,
	[schTargetAmount] [numeric](18, 0) NULL,
	[schTargetType] [char](1) NULL,
	[schRemarks] [varchar](250) NULL,
 CONSTRAINT [pk_hqsalescommisionheader] PRIMARY KEY CLUSTERED 
(
	[schCommisionid] ASC,
	[schcompanyid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losSerMaintenanceContractDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losSerMaintenanceContractDetail](
	[mcdCompanyID] [int] NOT NULL,
	[mcdID] [int] NOT NULL,
	[mcdShopID] [int] NOT NULL,
	[mcdPeriodDetailID] [int] NOT NULL,
	[mcdFromDate] [datetime] NOT NULL,
	[mcdToDate] [datetime] NOT NULL,
	[mcdPrepByID] [int] NOT NULL,
	[mcdAmount] [numeric](18, 2) NOT NULL,
	[mcdRemarks] [varchar](250) NULL,
	[mcdAlertdays] [int] NULL,
 CONSTRAINT [PK_losSerMaintenanceContractDetail] PRIMARY KEY NONCLUSTERED 
(
	[mcdCompanyID] ASC,
	[mcdID] ASC,
	[mcdShopID] ASC,
	[mcdPeriodDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aTechnicianServiceDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aTechnicianServiceDetails](
	[serid] [int] NOT NULL,
	[orderId] [int] NULL,
	[serTechnicianID] [int] NOT NULL,
	[serTimeReqInMins] [int] NULL,
	[sercompanyid] [int] NOT NULL,
 CONSTRAINT [pk_aTechnicianServiceDetails] PRIMARY KEY CLUSTERED 
(
	[serid] ASC,
	[sercompanyid] ASC,
	[serTechnicianID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losservinvoicetechniciandetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losservinvoicetechniciandetails](
	[serinvtechcompanyid] [int] NOT NULL,
	[sertechinvid] [int] NOT NULL,
	[serinvtechshopid] [int] NOT NULL,
	[serinvtechdetailid] [int] NOT NULL,
	[serinvtechid] [int] NULL,
	[serinvtechstarttime] [datetime] NULL,
	[serinvtechendtime] [datetime] NULL,
	[serinvtechcostperhr] [int] NULL,
	[serinvtechservicetype] [char](10) NULL,
	[serinvtechcomments] [varchar](100) NULL,
	[serinvtechstatus] [char](10) NULL,
	[serinvhfuturevc] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[serinvTechServiceID] [int] NOT NULL,
	[serinvTechEstStartDate] [datetime] NOT NULL,
	[serinvTechEstEndDate] [datetime] NOT NULL,
 CONSTRAINT [PK_losservinvoicetechniciandetails] PRIMARY KEY NONCLUSTERED 
(
	[serinvtechcompanyid] ASC,
	[sertechinvid] ASC,
	[serinvtechshopid] ASC,
	[serinvtechdetailid] ASC,
	[serinvTechServiceID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_497540956] ON [dbo].[losservinvoicetechniciandetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Ashopsalespersondetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ashopsalespersondetails](
	[SperShopid] [int] NOT NULL,
	[SperID] [int] NOT NULL,
	[sptype] [bit] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_Ashopsalespersondetails] PRIMARY KEY NONCLUSTERED 
(
	[SperID] ASC,
	[SperShopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1413580074] ON [dbo].[Ashopsalespersondetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ExchangeRate]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ExchangeRate](
	[ExchangeID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[ExchangeDate] [smalldatetime] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_ExchangeRate] PRIMARY KEY NONCLUSTERED 
(
	[ExchangeID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_453576654] ON [dbo].[ExchangeRate] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ExchangeRateDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ExchangeRateDetail](
	[ExchangeID] [int] NOT NULL,
	[CurrencyID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[BuyingRate] [numeric](18, 2) NULL,
	[SellingRate] [numeric](18, 2) NULL,
	[AverageRate] [numeric](18, 2) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_ExchangeRateDetail] PRIMARY KEY NONCLUSTERED 
(
	[ExchangeID] ASC,
	[CurrencyID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [idxErd] ON [dbo].[ExchangeRateDetail] 
(
	[CurrencyID] ASC,
	[CompanyID] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_469576711] ON [dbo].[ExchangeRateDetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aFineDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aFineDetail](
	[fdFineID] [int] NOT NULL,
	[fdFineDetailID] [int] NOT NULL,
	[fdFineDate] [datetime] NOT NULL,
	[fdFineAmount] [numeric](18, 2) NOT NULL,
	[fdPosted] [int] NOT NULL,
 CONSTRAINT [PK_afineDetail] PRIMARY KEY CLUSTERED 
(
	[fdFineID] ASC,
	[fdFineDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[CrmTask]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmTask](
	[TaskId] [int] NOT NULL,
	[Type] [varchar](50) NOT NULL,
	[Subject] [varchar](50) NULL,
	[StartDate] [datetime] NULL,
	[StartHour] [char](2) NULL,
	[StartMinute] [char](2) NULL,
	[DurationHour] [char](2) NULL,
	[DurationMinitue] [char](2) NULL,
	[Status] [varchar](50) NULL,
	[Direction] [varchar](50) NULL,
	[UserId] [int] NOT NULL,
	[Description] [text] NULL,
	[ContactId] [int] NULL,
	[Active] [bit] NULL,
	[RelatedTo] [varchar](50) NULL,
	[Deleted] [bit] NOT NULL,
	[CreateDate] [datetime] NOT NULL,
	[CompanyId] [int] NOT NULL,
	[ModifiedUser] [int] NULL,
	[ModifiedDate] [datetime] NULL,
	[Reminder] [bit] NULL,
	[UserGroupId] [int] NULL,
	[TransGroupId] [int] NULL,
	[UserType] [char](2) NULL,
	[Priority] [varchar](50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CrmUserHirarchey]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmUserHirarchey](
	[UserHirarcheyId] [int] NOT NULL,
	[MasterUserId] [int] NOT NULL,
	[UserGroupID] [int] NULL,
	[Description] [varchar](50) NOT NULL,
	[Deleted] [bit] NOT NULL,
	[CreateDate] [datetime] NOT NULL,
	[DeleteDate] [datetime] NULL,
	[CompanyId] [int] NOT NULL,
 CONSTRAINT [PK_CrmUserHirarchey] PRIMARY KEY CLUSTERED 
(
	[UserHirarcheyId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aUserDeptDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aUserDeptDetails](
	[companyid] [int] NULL,
	[userid] [int] NULL,
	[deptid] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aAccRatioGroupMaster]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aAccRatioGroupMaster](
	[CompanyID] [int] NOT NULL,
	[GroupID] [int] NOT NULL,
	[GroupDesc] [varchar](250) NULL,
	[ParentGroupId] [int] NULL,
	[LevelCode] [int] NULL,
	[Active] [bit] NOT NULL,
	[RatioType] [char](1) NOT NULL,
	[Multiplier] [numeric](18, 8) NOT NULL,
 CONSTRAINT [PK_aAccRatioGroupMaster] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[GroupID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[AAccRatioEntitiesMaster]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[AAccRatioEntitiesMaster](
	[CompanyID] [int] NOT NULL,
	[EntityId] [int] NOT NULL,
	[GroupID] [int] NOT NULL,
	[EntityDesc] [varchar](250) NOT NULL,
	[Numerator] [bit] NOT NULL,
	[GetAverageFigure] [bit] NULL,
 CONSTRAINT [PK_AAccRatioEntitiesMaster] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[EntityId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Forex]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Forex](
	[companyid] [int] NOT NULL,
	[forexid] [int] NOT NULL,
	[forexno] [varchar](50) NULL,
	[forexdate] [datetime] NULL,
	[type] [char](1) NULL,
	[salesorpurchaseaccid] [int] NULL,
	[otheraccid] [int] NULL,
	[forexgainlossaccid] [int] NULL,
	[salesorpurchaseamt] [numeric](18, 2) NULL,
	[otheramount] [numeric](18, 2) NULL,
	[forexgainlossamt] [numeric](18, 2) NULL,
	[chequeno] [varchar](50) NULL,
	[paymentmode] [varchar](50) NULL,
	[customerid] [int] NULL,
	[vendorid] [int] NULL,
	[personname] [varchar](250) NULL,
	[passportno] [varchar](50) NULL,
	[nationalityid] [int] NULL,
	[remarks] [varchar](250) NULL,
	[posted] [bit] NOT NULL,
	[cancelled] [bit] NOT NULL,
	[financialid] [int] NULL,
	[departmentid] [int] NULL,
	[cancelledremarks] [varchar](250) NULL,
	[exchangerate] [numeric](18, 8) NULL,
	[depexrate] [numeric](18, 8) NULL,
	[exchangerates] [varchar](250) NULL,
	[subdepartmentid] [int] NULL,
 CONSTRAINT [PK_Forex] PRIMARY KEY NONCLUSTERED 
(
	[companyid] ASC,
	[forexid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aHQPaymentVoucherRebateDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aHQPaymentVoucherRebateDetails](
	[CompanyID] [int] NOT NULL,
	[PaymentID] [int] NOT NULL,
	[DetailID] [int] NOT NULL,
	[ShopID] [int] NULL,
	[RebateApprovalID] [int] NULL,
	[CustomerID] [int] NULL,
	[RebateAmt] [numeric](18, 4) NULL,
	[SettleAmt] [numeric](18, 4) NULL,
	[CustEquivalentAmount] [numeric](18, 4) NULL,
 CONSTRAINT [pk_aHQPaymentVoucherRebateDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[PaymentID] ASC,
	[DetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[MOaJournalHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MOaJournalHeader](
	[JournalID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[JournalDate] [smalldatetime] NOT NULL,
	[ReferenceNo] [varchar](50) NULL,
	[Remarks] [varchar](1000) NULL,
	[Type] [varchar](10) NULL,
	[Cancel] [bit] NOT NULL,
	[Realised] [bit] NOT NULL,
	[CurrencyId] [int] NULL,
	[FinancialID] [int] NULL,
	[chequedate] [datetime] NULL,
	[updatetime] [datetime] NULL,
	[bankdate] [datetime] NULL,
 CONSTRAINT [PK_MOaJournalHeader] PRIMARY KEY NONCLUSTERED 
(
	[JournalID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [IDX_MOaJournalHDR_JournalDate_BankDate] ON [dbo].[MOaJournalHeader] 
(
	[JournalDate] ASC,
	[bankdate] 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
/****** Object:  Table [dbo].[DepreciationHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[DepreciationHeader](
	[DepreciationID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[DepreciationDate] [smalldatetime] NOT NULL,
	[DeprAccountID] [int] NULL,
	[Amount] [numeric](18, 2) NULL,
	[Remarks] [varchar](100) NULL,
	[DepartmentID] [int] NULL,
	[DepreciationNo] [varchar](50) NOT NULL,
	[Cancelled] [bit] NOT NULL,
	[cancelledremarks] [varchar](250) NULL,
	[Posted] [bit] NOT NULL,
	[FinancialID] [int] NULL,
	[updatetime] [datetime] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[depexrate] [numeric](18, 8) NULL,
	[consexrate] [numeric](18, 8) NULL,
	[exChangeRates] [varchar](250) NULL,
	[SubDepartmentID] [int] NULL,
 CONSTRAINT [PK_Depreciation] PRIMARY KEY NONCLUSTERED 
(
	[DepreciationID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_437576597] ON [dbo].[DepreciationHeader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aAccountFinYearOpening]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aAccountFinYearOpening](
	[Companyid] [int] NOT NULL,
	[Accountid] [int] NOT NULL,
	[Financialid] [int] NOT NULL,
	[departmentid] [int] NOT NULL,
	[Openingamount] [numeric](18, 2) NULL,
	[Openingactualamount] [numeric](18, 2) NULL,
	[openingdepamount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_aAccountFinYearOpening] PRIMARY KEY NONCLUSTERED 
(
	[Companyid] ASC,
	[Accountid] ASC,
	[Financialid] ASC,
	[departmentid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Contra]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Contra](
	[ContraID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[ContraNo] [varchar](50) NOT NULL,
	[ContraDate] [smalldatetime] NOT NULL,
	[ContraType] [varchar](3) NULL,
	[FromAccountID] [int] NOT NULL,
	[ToAccountID] [int] NOT NULL,
	[ChargeAccountID] [int] NULL,
	[ContraAmount] [numeric](18, 2) NULL,
	[ContraChargeAmount] [numeric](18, 2) NULL,
	[Remarks] [varchar](250) NULL,
	[Cancelled] [bit] NOT NULL,
	[CancelledRemarks] [varchar](250) NULL,
	[Posted] [bit] NOT NULL,
	[FinancialID] [int] NULL,
	[ExchangeNature] [varchar](5) NULL,
	[DepartmentID] [int] NULL,
	[ExchangeRate] [numeric](18, 8) NULL,
	[updatetime] [datetime] NOT NULL,
	[depexrate] [numeric](18, 8) NULL,
	[exchangerates] [varchar](250) NULL,
	[Chequeno] [varchar](50) NULL,
	[SubDepartmentID] [int] NULL,
 CONSTRAINT [PK_Contra] PRIMARY KEY NONCLUSTERED 
(
	[ContraID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[InterDivisionBillsHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[InterDivisionBillsHeader](
	[BillsID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[BillsNo] [varchar](50) NOT NULL,
	[BillDate] [datetime] NOT NULL,
	[VendorID] [int] NULL,
	[BillAmount] [numeric](18, 2) NULL,
	[ReferenceNo] [varchar](250) NULL,
	[DuePeriod] [smallint] NULL,
	[Discount] [numeric](18, 2) NULL,
	[DiscountAccountID] [int] NULL,
	[FinancialID] [int] NULL,
	[CashPurchase] [bit] NOT NULL,
	[BankCashAccID] [int] NULL,
	[ChequeNo] [varchar](50) NULL,
	[ExchangeNature] [varchar](5) NULL,
	[Remarks] [varchar](250) NULL,
	[departmentid] [int] NULL,
	[Posted] [bit] NOT NULL,
	[Cancelled] [bit] NOT NULL,
	[CancelledRemarks] [varchar](250) NULL,
	[exchangerate] [numeric](18, 8) NULL,
	[vreferenceno] [varchar](250) NULL,
	[updatetime] [datetime] NOT NULL,
	[depexrate] [numeric](18, 8) NULL,
	[exchangerates] [varchar](250) NULL,
	[RefJournalID] [int] NULL,
	[subdepartmentid] [int] NULL,
 CONSTRAINT [PK_InterDivisionBillsHeader] PRIMARY KEY CLUSTERED 
(
	[BillsID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[AdjustmentHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[AdjustmentHeader](
	[AdjustmentID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[AdjustmentDate] [smalldatetime] NOT NULL,
	[Remarks] [varchar](1000) NULL,
	[AdjustmentNo] [varchar](50) NULL,
	[AdjustmentType] [varchar](2) NULL,
	[ExchangeGain] [char](1) NOT NULL,
	[Accountid] [int] NULL,
	[Exchangerate] [numeric](18, 8) NULL,
	[Amount] [numeric](18, 2) NULL,
	[FinancialID] [int] NULL,
	[Departmentid] [int] NULL,
	[Cancelled] [bit] NOT NULL,
	[Posted] [bit] NOT NULL,
	[CancelledRemarks] [varchar](250) NULL,
	[DepExchangerate] [numeric](18, 8) NULL,
	[Exchangerates] [varchar](250) NULL,
	[SubDepartmentID] [int] NULL,
 CONSTRAINT [PK_AdjustmentHeader] PRIMARY KEY NONCLUSTERED 
(
	[AdjustmentID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[JournalTransHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[JournalTransHeader](
	[JournalTransID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[JournalNo] [varchar](50) NULL,
	[JournalTransDate] [smalldatetime] NOT NULL,
	[Remarks] [varchar](100) NULL,
	[Cancelled] [bit] NOT NULL,
	[CancelledRemarks] [varchar](100) NULL,
	[Posted] [bit] NOT NULL,
	[FinancialID] [int] NULL,
	[parentjournalid] [int] NULL,
	[childjournalid] [int] NULL,
	[receiptid] [int] NULL,
	[paymentid] [int] NULL,
	[departmentid] [int] NULL,
	[updatetime] [datetime] NOT NULL,
	[exchangerate] [numeric](18, 8) NULL,
	[exchangerates] [varchar](250) NULL,
	[depexrates] [numeric](18, 8) NULL,
	[InvoiceID] [int] NULL,
	[BillID] [int] NULL,
	[subdepartmentid] [int] NULL,
	[Confirmed] [bit] NULL,
 CONSTRAINT [PK_JournalTransHeader] PRIMARY KEY NONCLUSTERED 
(
	[JournalTransID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loiUserAuditDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loiUserAuditDetail](
	[gdCompanyId] [int] NOT NULL,
	[gdAuditId] [int] NOT NULL,
	[gdGodownId] [int] NOT NULL,
	[gdDetailId] [int] NOT NULL,
	[gdAuditControlName] [varchar](250) NOT NULL,
	[gdAuditControlType] [varchar](25) NOT NULL,
	[gdOldValue] [varchar](4000) NOT NULL,
	[gdNewValue] [varchar](4000) NOT NULL,
 CONSTRAINT [PK_loiUserAuditDetail] PRIMARY KEY NONCLUSTERED 
(
	[gdCompanyId] ASC,
	[gdAuditId] ASC,
	[gdGodownId] ASC,
	[gdDetailId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aSettings]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aSettings](
	[SettingID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[NoOfPreviousDays] [smallint] NULL,
	[InvoicePeriod] [smallint] NULL,
	[FinancialYearPeriod] [smallint] NULL,
	[FixedAssetGroupID] [int] NOT NULL,
	[CashGroupID] [int] NULL,
	[BankGroupID] [int] NOT NULL,
	[TradeDebtorAcID] [int] NOT NULL,
	[TradeCreditorAcID] [int] NOT NULL,
	[SalesGroupID] [int] NOT NULL,
	[PurchaseGroupID] [int] NOT NULL,
	[SepProformaInvoiceNo] [bit] NOT NULL,
	[SepProductServiceNo] [bit] NOT NULL,
	[AverageRate] [bit] NOT NULL,
	[EnableTargetCheck] [bit] NOT NULL,
	[EnableBudgetCheck] [bit] NOT NULL,
	[ExchangeDiffAcID] [int] NULL,
	[Retainedearningsacc] [int] NULL,
	[openingfreezed] [bit] NOT NULL,
	[BackDay] [datetime] NULL,
	[depreciationid] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[autogenerateasstcode] [bit] NULL,
	[debtorsaccid] [varchar](250) NULL,
	[creditorsaccid] [varchar](250) NULL,
	[payablealertbeforedays] [int] NULL,
	[alertbeforedays] [int] NULL,
	[depriciationexpaccid] [int] NULL,
	[disposalaccount] [int] NULL,
	[transferaccount] [int] NULL,
	[astopendate] [datetime] NULL,
	[RefBillId] [int] NULL,
	[CurrentAssetGroupId] [int] NULL,
	[CurrentLiabilityGroupId] [int] NULL,
	[CurrentShareCapitalGroupId] [int] NULL,
 CONSTRAINT [PK_aSettings] PRIMARY KEY NONCLUSTERED 
(
	[SettingID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_517576882] ON [dbo].[aSettings] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losApartmentAgreementDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losApartmentAgreementDetails](
	[mgdcompanyid] [int] NOT NULL,
	[mgdshopid] [int] NOT NULL,
	[mgdAgreementId] [int] NOT NULL,
	[mgdAgreementDetailID] [int] NOT NULL,
	[mgdPersonName] [varchar](100) NULL,
	[mgdcheckintime] [datetime] NULL,
	[mgdcheckouttime] [datetime] NULL,
	[mgdPassPortNo] [varchar](100) NULL,
	[mgdWorkPermitVisaNo] [varchar](100) NULL,
	[mgdPPExpiryDate] [datetime] NULL,
	[mgdVisaExpiryDate] [datetime] NULL,
	[mgdstatus] [varchar](100) NULL,
	[mgdremarks] [varchar](250) NULL,
 CONSTRAINT [pk_losApartmentAgreementDetails] PRIMARY KEY CLUSTERED 
(
	[mgdcompanyid] ASC,
	[mgdshopid] ASC,
	[mgdAgreementId] ASC,
	[mgdAgreementDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losApartmentCheckOut]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losApartmentCheckOut](
	[chID] [int] NOT NULL,
	[chShopID] [int] NOT NULL,
	[chCompanyId] [int] NOT NULL,
	[chNo] [varchar](50) NULL,
	[chDate] [datetime] NULL,
	[chApartmentId] [int] NULL,
	[chAgreementID] [int] NULL,
	[chEnteredBy] [int] NULL,
	[chCheckoutTime] [datetime] NULL,
	[chDepositReturned] [numeric](18, 2) NULL,
	[chDepositAmount] [numeric](18, 2) NULL,
	[chCashAccId] [int] NULL,
	[chRemarks] [varchar](250) NULL,
	[chPosted] [bit] NULL,
	[chCancelled] [bit] NULL,
	[chCancelledRemarks] [varchar](250) NULL,
	[ChDepartmentID] [int] NOT NULL,
	[chUpdateTime] [datetime] NULL,
	[chExRate] [numeric](18, 8) NULL,
	[chDepExRate] [numeric](18, 8) NULL,
	[chExRates] [varchar](250) NULL,
	[chWriteOffAccID] [int] NULL,
	[chAvaliedAmount] [numeric](18, 2) NULL,
	[chCustomerID] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losDebitCreditNoteDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losDebitCreditNoteDetail](
	[DCNID] [int] NOT NULL,
	[ShopID] [int] NOT NULL,
	[DetailID] [int] NOT NULL,
	[ClearenceID] [int] NULL,
	[POID] [int] NULL,
	[Amount] [numeric](18, 2) NULL,
	[ResAmount] [numeric](18, 2) NULL,
	[BoatNoteID] [int] NULL,
	[ClearenceDetID] [int] NULL,
	[BoatNoteDetID] [int] NULL,
 CONSTRAINT [pk_LosDebitCreditNoteDetail] PRIMARY KEY CLUSTERED 
(
	[ShopID] ASC,
	[DCNID] ASC,
	[DetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losLPDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losLPDetail](
	[ShopID] [int] NOT NULL,
	[POID] [int] NOT NULL,
	[DetailID] [int] NOT NULL,
	[ItemDescription] [varchar](250) NULL,
	[Unit] [varchar](25) NULL,
	[Qty] [numeric](18, 3) NULL,
	[Amount] [numeric](18, 2) NULL,
	[Remarks] [varchar](250) NULL,
	[Packing] [varchar](50) NULL,
	[NoofPackages] [numeric](18, 2) NULL,
	[ClrReqDetID] [int] NULL,
	[status] [char](1) NOT NULL,
 CONSTRAINT [pk_losLPDetail] PRIMARY KEY CLUSTERED 
(
	[ShopID] ASC,
	[POID] ASC,
	[DetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LosserToolsReturnHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosserToolsReturnHeader](
	[tlrethCompanyId] [int] NOT NULL,
	[tlrethShopid] [int] NOT NULL,
	[tlrethid] [int] NOT NULL,
	[tlrethno] [varchar](50) NULL,
	[tlrethdate] [datetime] NULL,
	[tlrethtechnicianid] [int] NULL,
	[tlrethRemarks] [varchar](250) NULL,
	[tlrethCancelled] [bit] NULL,
	[tlrethCancelledRemarks] [varchar](250) NULL,
	[tlrethallocid] [int] NULL,
 CONSTRAINT [PK_LosserToolsReturnHeader] PRIMARY KEY NONCLUSTERED 
(
	[tlrethCompanyId] ASC,
	[tlrethShopid] ASC,
	[tlrethid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aaccrepgroup]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aaccrepgroup](
	[companyid] [int] NOT NULL,
	[Groupid] [int] NOT NULL,
	[GroupName] [varchar](100) NULL,
	[Displayorderid] [int] NULL,
	[formatid] [int] NULL,
	[iscaption] [char](5) NOT NULL,
	[groupcode] [varchar](50) NULL,
	[Departmentwise] [char](5) NULL,
	[Inflow] [bit] NULL,
 CONSTRAINT [pk_aaccrepgroup] PRIMARY KEY CLUSTERED 
(
	[companyid] ASC,
	[Groupid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aRepFormatAccounts]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aRepFormatAccounts](
	[CompanyId] [int] NOT NULL,
	[FormatId] [int] NOT NULL,
	[GroupId] [int] NOT NULL,
	[Mode] [char](1) NULL,
	[Accountid] [int] NOT NULL,
 CONSTRAINT [pk_aRepFormatAccounts] PRIMARY KEY CLUSTERED 
(
	[CompanyId] ASC,
	[FormatId] ASC,
	[GroupId] ASC,
	[Accountid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LeadTimeStage]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LeadTimeStage](
	[Lstageid] [int] NOT NULL,
	[LstageName] [varchar](50) NOT NULL,
	[Lstagedivisionid] [int] NOT NULL,
	[LStageCompanyid] [int] NOT NULL,
 CONSTRAINT [PK_LeadTimeStage] PRIMARY KEY NONCLUSTERED 
(
	[Lstageid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losinvservicedetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losinvservicedetails](
	[serinvdcompanyid] [int] NOT NULL,
	[serinvdinvoiceid] [int] NOT NULL,
	[serinvdshopid] [int] NOT NULL,
	[serinvdserviceid] [int] NOT NULL,
	[serinvdcharge] [numeric](18, 8) NULL,
	[serinvdchargetaken] [numeric](18, 8) NULL,
	[serinvdcomments] [varchar](250) NULL,
	[serinvdqty] [numeric](18, 2) NULL,
	[serinvddetailid] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[serinvdType] [char](2) NULL,
	[serinvdItemTaxPercentage] [numeric](18, 2) NULL,
	[serinvdItemTaxAmount] [numeric](18, 2) NULL,
	[serinvdItemTaxCategory] [int] NULL,
 CONSTRAINT [PK_losinvservicedetails] PRIMARY KEY NONCLUSTERED 
(
	[serinvdcompanyid] ASC,
	[serinvdinvoiceid] ASC,
	[serinvdshopid] ASC,
	[serinvddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_114099447] ON [dbo].[losinvservicedetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[MeiGodownRequestHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MeiGodownRequestHeader](
	[GRHRequestId] [int] NOT NULL,
	[GRHGodownId] [int] NOT NULL,
	[GRHRequestNo] [varchar](50) NOT NULL,
	[GRHRequestDate] [datetime] NULL,
	[GRHRemarks] [varchar](250) NULL,
	[GRHCancelled] [bit] NOT NULL,
	[GRHCancelledRemarks] [varchar](250) NULL,
	[GRHRecAddUserId] [int] NOT NULL,
	[GRHRecModUserId] [int] NULL,
	[GRHToShopId] [int] NULL,
	[GRHToGodownId] [int] NULL,
	[GRHTransfinished] [bit] NOT NULL,
	[GRHNoofDetails] [int] NOT NULL,
	[GRHType] [varchar](5) NULL,
	[GRHUsed] [bit] NOT NULL,
	[UpdateTime] [datetime] NOT NULL,
	[rowguid] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_MeiGodownRequestHeader] PRIMARY KEY CLUSTERED 
(
	[GRHRequestId] ASC,
	[GRHGodownId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[MeiGodownRequestDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MeiGodownRequestDetail](
	[GRDRequestId] [int] NOT NULL,
	[GRDDetailId] [int] NOT NULL,
	[GRDGodownId] [int] NOT NULL,
	[GRDItemId] [int] NOT NULL,
	[GRDReqQty] [numeric](18, 3) NOT NULL,
	[rowguid] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_MeiGodownRequestDetail] PRIMARY KEY CLUSTERED 
(
	[GRDRequestId] ASC,
	[GRDDetailId] ASC,
	[GRDGodownId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ExchangeRateHistoryHeader]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ExchangeRateHistoryHeader](
	[ExchangeID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[ExchangeDate] [datetime] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_ExchangeRateHistoryHeader] PRIMARY KEY CLUSTERED 
(
	[ExchangeID] ASC,
	[CompanyID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ExchangeRateHistoryDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ExchangeRateHistoryDetails](
	[ExchangeID] [int] NOT NULL,
	[CurrencyID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[BuyingRate] [numeric](18, 2) NOT NULL,
	[SellingRate] [numeric](18, 2) NOT NULL,
	[AverageRate] [numeric](18, 2) NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losWarrentyClaimHeader]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losWarrentyClaimHeader](
	[wchCompanyID] [int] NOT NULL,
	[wchShopID] [int] NOT NULL,
	[wchID] [int] NOT NULL,
	[wchDate] [datetime] NOT NULL,
	[wchNo] [varchar](50) NOT NULL,
	[wchCustomerID] [int] NULL,
	[wchRemarks] [varchar](500) NULL,
	[wchType] [varchar](50) NOT NULL,
	[wchCancelled] [int] NULL,
	[wchCancelRemarks] [nvarchar](250) NULL,
	[wchPosted] [int] NOT NULL,
	[wchUser] [varchar](25) NOT NULL,
	[wchUpdatedUser] [varchar](25) NULL,
	[wchUpdatedTime] [datetime] NULL,
	[wchFinancialID] [int] NOT NULL,
	[wchAmount] [numeric](18, 2) NULL,
	[wchExchangeRate] [varchar](250) NULL,
	[wchcomexrate] [numeric](18, 0) NULL,
	[wchdepexrate] [numeric](18, 0) NULL,
	[wchModel] [nvarchar](300) NULL,
	[wchUnitSerial] [nvarchar](300) NULL,
	[wchLabourCost] [numeric](12, 2) NULL,
	[wchpartCostSupplier] [numeric](12, 2) NULL,
	[wchLabourCostSupplier] [numeric](12, 2) NULL,
	[wchCreditDate] [datetime] NULL,
	[wchRefNo] [varchar](200) NULL,
	[wchConfirmed] [bit] NULL,
	[wchCustomerName] [varchar](500) NULL,
	[wchCustomerAddress] [varchar](500) NULL,
	[whVerified] [bit] NULL,
	[whApprovedby] [varchar](20) NULL,
	[whIhCRequestID] [int] NULL,
	[whApprovedid] [int] NULL,
 CONSTRAINT [PK_losWarrentyClaimHeader] PRIMARY KEY CLUSTERED 
(
	[wchCompanyID] ASC,
	[wchShopID] ASC,
	[wchID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [idx_losWarrentyClaimHeader_wchdate] ON [dbo].[losWarrentyClaimHeader] 
(
	[wchDate] 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
CREATE NONCLUSTERED INDEX [index_losWarrentyClaimHeader] ON [dbo].[losWarrentyClaimHeader] 
(
	[wchID] ASC,
	[wchShopID] ASC,
	[wchCancelled] 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
/****** Object:  Table [dbo].[losWarrentyClaimDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losWarrentyClaimDetail](
	[wcdCompanyID] [int] NOT NULL,
	[wcdShopID] [int] NOT NULL,
	[wcdID] [int] NOT NULL,
	[wcdDetailID] [int] NOT NULL,
	[wcdItemID] [int] NOT NULL,
	[wcdPackingTypeID] [int] NOT NULL,
	[wcdPQty] [numeric](18, 2) NOT NULL,
	[wcdQty] [numeric](18, 0) NOT NULL,
	[wcdAvailQty] [numeric](18, 0) NOT NULL,
	[wcdCostPrice] [numeric](18, 4) NOT NULL,
	[wcdSerialNo] [varchar](50) NULL,
	[wcdcustomprice] [numeric](18, 2) NULL,
 CONSTRAINT [PK_losWarrentyClaimDetail] PRIMARY KEY CLUSTERED 
(
	[wcdCompanyID] ASC,
	[wcdShopID] ASC,
	[wcdID] ASC,
	[wcdDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE NONCLUSTERED INDEX [index_losWarrentyClaimDetail] ON [dbo].[losWarrentyClaimDetail] 
(
	[wcdID] ASC,
	[wcdShopID] 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
/****** Object:  Table [dbo].[losFacilityBookingDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losFacilityBookingDetail](
	[ftShopid] [int] NULL,
	[ftCompanyId] [int] NOT NULL,
	[ftBookingId] [int] NOT NULL,
	[ftBookingDetailId] [int] NOT NULL,
	[ftFaclityID] [int] NOT NULL,
	[ftCheckInTime] [datetime] NULL,
	[ftCheckOutTime] [datetime] NULL,
	[ftnoofunit] [int] NULL,
	[ftweekdays] [int] NULL,
	[ftRemarks] [varchar](250) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aShopServiceCharges]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aShopServiceCharges](
	[serid] [int] NOT NULL,
	[sercompanyid] [int] NOT NULL,
	[serShopID] [int] NOT NULL,
	[sercharge] [numeric](18, 2) NULL,
 CONSTRAINT [pk_aShopServiceCharges] PRIMARY KEY CLUSTERED 
(
	[serid] ASC,
	[sercompanyid] ASC,
	[serShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosPackingListDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosPackingListDetail](
	[PldShopId] [int] NULL,
	[PldId] [int] NULL,
	[PldDetailId] [int] NULL,
	[PldMarks] [varchar](50) NULL,
	[PldPacking] [varchar](50) NULL,
	[PldDescription] [varchar](250) NULL,
	[PldSize] [varchar](50) NULL,
	[PldWeight] [varchar](50) NULL,
	[PldQty] [varchar](50) NULL,
	[PldOrgin] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losfuturetabheader]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losfuturetabheader](
	[futheadid] [int] NOT NULL,
	[futhcompanyid] [int] NOT NULL,
	[futhshopid] [int] NOT NULL,
	[futhno] [varchar](50) NULL,
	[futhdate] [datetime] NULL,
	[futhremarks] [varchar](250) NULL,
	[futhcancelledremarks] [varchar](250) NULL,
	[futhcancelled] [bit] NULL,
	[futhposted] [bit] NULL,
	[futhtransidentifier] [char](5) NULL,
	[futhupdatetime] [datetime] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_losfuturetabheader] PRIMARY KEY NONCLUSTERED 
(
	[futheadid] ASC,
	[futhcompanyid] ASC,
	[futhshopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1493580359] ON [dbo].[losfuturetabheader] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losfuturetabdetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losfuturetabdetail](
	[futdid] [int] NOT NULL,
	[futdcompanyid] [int] NOT NULL,
	[futdshopid] [int] NOT NULL,
	[futdref1id] [int] NOT NULL,
	[futdref2id] [int] NULL,
	[futdref3id] [int] NULL,
	[futdrefnum1] [numeric](18, 8) NULL,
	[futdrefnum2] [numeric](18, 8) NULL,
	[futdrefnum3] [numeric](18, 8) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_losfuturetabdetail] PRIMARY KEY NONCLUSTERED 
(
	[futdid] ASC,
	[futdcompanyid] ASC,
	[futdshopid] ASC,
	[futdref1id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_66099276] ON [dbo].[losfuturetabdetail] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[CrmLeads]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmLeads](
	[LeadId] [int] NOT NULL,
	[LeadSource] [varchar](50) NULL,
	[LeadSourceDescription] [varchar](250) NULL,
	[ReferredBy] [varchar](50) NULL,
	[FirstName] [varchar](50) NULL,
	[LastName] [varchar](50) NULL,
	[ClientId] [int] NULL,
	[UserId] [int] NULL,
	[Status] [varchar](50) NULL,
	[OfficePhone] [varchar](50) NULL,
	[Mobile] [varchar](50) NULL,
	[Fax] [varchar](50) NULL,
	[Email] [varchar](50) NULL,
	[PrimaryAddress] [varchar](50) NULL,
	[PCity] [int] NULL,
	[PCountry] [int] NULL,
	[PPostalCode] [varchar](50) NULL,
	[OtherAddress] [varchar](50) NULL,
	[OCity] [int] NULL,
	[OCountry] [int] NULL,
	[OPostalCode] [varchar](50) NULL,
	[Descriptions] [varchar](250) NULL,
	[Tittle] [varchar](50) NULL,
	[Department] [varchar](50) NULL,
	[DonotCall] [bit] NULL,
	[StatusDescription] [varchar](250) NULL,
	[Salutation] [varchar](5) NULL,
	[PState] [varchar](50) NULL,
	[OState] [varchar](50) NULL,
	[OtherPhno] [varchar](50) NULL,
	[HomePhno] [varchar](50) NULL,
	[CompanyId] [int] NOT NULL,
	[CreateDate] [datetime] NOT NULL,
	[Deleted] [bit] NOT NULL,
	[LeadTypeId] [int] NULL,
 CONSTRAINT [PK_CrmLeads] PRIMARY KEY CLUSTERED 
(
	[LeadId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[CrmOpportunity]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[CrmOpportunity](
	[OppertunityId] [int] NOT NULL,
	[ClientId] [int] NULL,
	[OpportunitName] [varchar](50) NOT NULL,
	[Type] [varchar](50) NULL,
	[LeadSource] [varchar](50) NULL,
	[UserId] [int] NULL,
	[Description] [varchar](250) NULL,
	[Currencyid] [int] NULL,
	[Amount] [numeric](18, 2) NULL,
	[ExpectedCloseDate] [datetime] NULL,
	[NextStep] [varchar](50) NULL,
	[SalesStage] [varchar](50) NULL,
	[Probability] [int] NULL,
	[Active] [int] NULL,
	[CreateDate] [datetime] NOT NULL,
	[ExchangeRate] [varchar](50) NULL,
	[CompanyAmount] [numeric](18, 2) NULL,
	[Deleted] [bit] NOT NULL,
	[CompanyId] [int] NOT NULL,
	[LeadTypeId] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loreplacereqtovendorheader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loreplacereqtovendorheader](
	[rrvcompanyid] [int] NOT NULL,
	[rrvrequestid] [int] NOT NULL,
	[rrvrequestno] [varchar](50) NULL,
	[rrvrequestdate] [datetime] NULL,
	[rrvvendorid] [int] NULL,
	[rrvshopid] [int] NULL,
	[rrvrepreqid] [int] NULL,
	[rrvremarks] [varchar](250) NULL,
	[rrvcancelled] [bit] NOT NULL,
	[rrvcancelledremarks] [varchar](250) NULL,
	[rrvTime] [datetime] NULL,
	[rrvCreated] [varchar](250) NULL,
	[rrvModified] [varchar](250) NULL,
 CONSTRAINT [PK_loreplacereqtovendorheader] PRIMARY KEY NONCLUSTERED 
(
	[rrvcompanyid] ASC,
	[rrvrequestid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[denominationdetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[denominationdetail](
	[dshopid] [int] NOT NULL,
	[ddenominationid] [int] NOT NULL,
	[dcurrencyid] [int] NULL,
	[ddenominationtype] [numeric](18, 2) NULL,
	[ddenominationcount] [numeric](18, 0) NULL,
	[damount] [numeric](18, 4) NULL,
	[ddepamount] [numeric](18, 4) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[DenominationChequeDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[DenominationChequeDetails](
	[dcdShopId] [int] NOT NULL,
	[dcdDenomId] [int] NOT NULL,
	[dcdDetailId] [int] NOT NULL,
	[dcdCurrId] [int] NULL,
	[dcdChequeDetails] [varchar](250) NULL,
	[dcdAmount] [numeric](18, 2) NULL,
	[dcdDepAmount] [numeric](18, 2) NULL,
 CONSTRAINT [pk_DenominationChequeDetails] PRIMARY KEY CLUSTERED 
(
	[dcdShopId] ASC,
	[dcdDenomId] ASC,
	[dcdDetailId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aHQPaymentVoucherDebitDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHQPaymentVoucherDebitDetails](
	[pddPaymentDebitID] [int] NOT NULL,
	[pddPaymentID] [int] NOT NULL,
	[pddCompanyID] [int] NULL,
	[pddAccountID] [int] NULL,
	[pddAmount] [numeric](18, 2) NULL,
	[pddhqpoid] [int] NULL,
	[pdddescription] [varchar](250) NULL,
	[pddcustomeramount] [numeric](18, 2) NULL,
	[pddAccountAmount] [numeric](18, 2) NULL,
	[pddVendorExchangeDifference] [numeric](18, 2) NULL,
	[pddpaylinktransid] [int] NULL,
	[pddAgrrementtransID] [int] NULL,
 CONSTRAINT [PK_aHQPaymentVoucherDebitDetails] PRIMARY KEY NONCLUSTERED 
(
	[pddPaymentDebitID] ASC,
	[pddPaymentID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loPurchaseOrderOC]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loPurchaseOrderOC](
	[podOthPoId] [int] NOT NULL,
	[podOthDetailId] [int] NOT NULL,
	[podOthDesc] [varchar](250) NULL,
	[podOthAmount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_loPurchaseOrderOC] PRIMARY KEY NONCLUSTERED 
(
	[podOthPoId] ASC,
	[podOthDetailId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LtimeDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LtimeDetail](
	[Ltimeid] [int] NOT NULL,
	[LtimeCompanyid] [int] NOT NULL,
	[Ltimestageid] [int] NOT NULL,
	[LtimeDivisionId] [int] NOT NULL,
	[LtimeNoofDays] [int] NOT NULL,
	[LtimeDetailNo] [numeric](18, 0) NULL,
 CONSTRAINT [PK_LtimeDetail] PRIMARY KEY NONCLUSTERED 
(
	[Ltimeid] ASC,
	[Ltimestageid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[AAccRatioEntitiesAccounts]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AAccRatioEntitiesAccounts](
	[CompanyID] [int] NOT NULL,
	[EntityID] [int] NOT NULL,
	[AccountID] [int] NOT NULL,
	[CalcType] [smallint] NOT NULL,
 CONSTRAINT [PK_AAccRatioEntitiesAccounts] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[EntityID] ASC,
	[AccountID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[mosrequestinvdetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[mosrequestinvdetail](
	[reqcompanyid] [int] NOT NULL,
	[reqdid] [int] NOT NULL,
	[reqinvdshopid] [int] NOT NULL,
	[reqinvdinvoiceid] [int] NULL,
	[reqddetailid] [int] NULL,
	[reqReexportID] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aShopToolsDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aShopToolsDetails](
	[companyid] [int] NOT NULL,
	[shopid] [int] NOT NULL,
	[toolsastid] [int] NOT NULL,
 CONSTRAINT [pk_ashoptoolsdetails] PRIMARY KEY CLUSTERED 
(
	[companyid] ASC,
	[shopid] ASC,
	[toolsastid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[assetexpensetrackingdetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[assetexpensetrackingdetail](
	[aexcompanyid] [int] NULL,
	[aexpaymentid] [int] NULL,
	[aexpaymentno] [varchar](50) NULL,
	[aexassetid] [int] NULL,
	[aexpaymentdate] [datetime] NULL,
	[aexpaymentamount] [numeric](18, 2) NULL,
	[aexcurrencyid] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[assetdisposaldetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[assetdisposaldetail](
	[dispdcompanyid] [int] NOT NULL,
	[dispID] [int] NOT NULL,
	[dispdid] [int] NOT NULL,
	[dispdasstid] [int] NULL,
	[dispdaccid] [int] NULL,
	[dispdcredit] [bit] NULL,
	[dispcancelledremarks] [varchar](250) NULL,
	[dispdamount] [numeric](18, 2) NULL,
	[dispdtype] [char](1) NULL,
	[DisAstSaleValue] [numeric](18, 2) NULL,
	[disdepeBalamt] [numeric](18, 2) NULL,
	[disUptoDepAmt] [numeric](19, 2) NULL,
 CONSTRAINT [PK_assetdisposaldetail] PRIMARY KEY NONCLUSTERED 
(
	[dispdcompanyid] ASC,
	[dispID] ASC,
	[dispdid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[DepreciationDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DepreciationDetail](
	[CompanyID] [int] NULL,
	[DepreciationID] [int] NULL,
	[DetailID] [int] NULL,
	[FixedAssetID] [int] NULL,
	[DepreciationAmount] [numeric](18, 2) NULL,
	[DepreciationAccountID] [int] NULL,
	[assetaccountid] [int] NULL,
	[Depexpaccid] [int] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[MOaJournalDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MOaJournalDetails](
	[JournalDetailID] [int] NOT NULL,
	[JournalID] [int] NOT NULL,
	[JournalCredit] [bit] NOT NULL,
	[AccountID] [int] NULL,
	[CustomerID] [int] NULL,
	[VendorID] [int] NULL,
	[Amount] [numeric](18, 9) NULL,
	[ActualAmount] [numeric](18, 9) NULL,
	[CompanyID] [int] NOT NULL,
	[DepartmentID] [int] NULL,
	[depamount] [numeric](18, 9) NULL,
	[PostGroup] [int] NULL,
	[SubDepartmentID] [int] NULL,
 CONSTRAINT [PK_MOaJournalDetails] PRIMARY KEY NONCLUSTERED 
(
	[JournalDetailID] ASC,
	[JournalID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IDX_MOaJournalDet_DeptID_AccID] ON [dbo].[MOaJournalDetails] 
(
	[AccountID] ASC,
	[DepartmentID] 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
/****** Object:  Table [dbo].[DishSegmentDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DishSegmentDetail](
	[seg_detail_id] [int] NOT NULL,
	[seg_detail_header_id] [int] NOT NULL,
	[seg_detail_dishid] [int] NOT NULL,
	[seg_detail_outletid] [int] NULL,
	[seg_detail_companyid] [int] NOT NULL,
	[Seg_Detail_UpdateTime] [datetime] NOT NULL,
	[Seg_Detail_UserID] [int] NULL,
	[seg_detail_dish_cp] [decimal](18, 3) NULL,
	[seg_detail_dish_sp_fig] [decimal](18, 3) NULL,
	[seg_detail_dish_sp_per] [decimal](18, 3) NULL,
 CONSTRAINT [PK_segid_segheaderid_segdishid_segcompanyid_SegUpdateTime] PRIMARY KEY CLUSTERED 
(
	[seg_detail_id] ASC,
	[seg_detail_header_id] ASC,
	[seg_detail_dishid] ASC,
	[seg_detail_companyid] ASC,
	[Seg_Detail_UpdateTime] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [UK_segid_segheaderid_segdishid_segcompanyid_segoutletid_SegUpdateTime] UNIQUE NONCLUSTERED 
(
	[seg_detail_id] ASC,
	[seg_detail_header_id] ASC,
	[seg_detail_dishid] ASC,
	[seg_detail_companyid] ASC,
	[seg_detail_outletid] ASC,
	[Seg_Detail_UpdateTime] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[TempDishSegmentDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TempDishSegmentDetail](
	[seg_detail_Tid] [int] NOT NULL,
	[seg_detail_Theader_id] [int] NOT NULL,
	[seg_detail_Tdishid] [int] NOT NULL,
	[seg_detail_Toutletid] [int] NULL,
	[seg_detail_Tcompanyid] [int] NOT NULL,
	[seg_detail_TUpdateTime] [datetime] NOT NULL,
	[seg_detail_TUserID] [int] NULL,
	[seg_detail_TLatestID] [int] NOT NULL,
	[seg_detail_Tdish_cp] [decimal](18, 3) NULL,
	[seg_detail_Tdish_sp_fig] [decimal](18, 3) NULL,
	[seg_detail_Tdish_sp_per] [decimal](18, 3) NULL,
 CONSTRAINT [PK_segTid_segTheaderid_segTdishid_segTcompanyid_segTNewInsertedID_SegTUpdateTime] PRIMARY KEY CLUSTERED 
(
	[seg_detail_Tid] ASC,
	[seg_detail_Theader_id] ASC,
	[seg_detail_Tdishid] ASC,
	[seg_detail_Tcompanyid] ASC,
	[seg_detail_TLatestID] ASC,
	[seg_detail_TUpdateTime] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [UK_segTid_segTheaderid_segTdishid_segTcompanyid_segToutletid_SegTUpdateTime_SegTNewInsertedID] UNIQUE NONCLUSTERED 
(
	[seg_detail_Tid] ASC,
	[seg_detail_Theader_id] ASC,
	[seg_detail_Tdishid] ASC,
	[seg_detail_Tcompanyid] ASC,
	[seg_detail_Toutletid] ASC,
	[seg_detail_TUpdateTime] ASC,
	[seg_detail_TLatestID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ReceiptVoucherCreditDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ReceiptVoucherCreditDetails](
	[ReceiptDebitID] [int] NOT NULL,
	[ReceiptID] [int] NOT NULL,
	[CompanyID] [int] NULL,
	[AccountID] [int] NULL,
	[Amount] [numeric](18, 2) NULL,
	[AccountDescription] [nvarchar](100) NULL,
 CONSTRAINT [PK_ReceiptVoucherCreditDetails] PRIMARY KEY NONCLUSTERED 
(
	[ReceiptDebitID] ASC,
	[ReceiptID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[AdjustmentDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AdjustmentDetails](
	[AdjustmentDetailID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[AdjustmentID] [int] NOT NULL,
	[JournalCredit] [bit] NOT NULL,
	[AccountID] [int] NULL,
	[CustomerID] [int] NULL,
	[VendorID] [int] NULL,
	[Amount] [numeric](18, 2) NULL,
	[ActualAmount] [numeric](18, 2) NULL,
	[ConsAmount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_AdjustmentDetails] PRIMARY KEY NONCLUSTERED 
(
	[AdjustmentDetailID] ASC,
	[CompanyID] ASC,
	[AdjustmentID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ashopcashaccountdetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ashopcashaccountdetails](
	[shopID] [int] NOT NULL,
	[CashAccountID] [int] NOT NULL,
	[CompanyID] [int] NULL,
	[futurevc] [varchar](250) NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_ashopcashaccountdetails] PRIMARY KEY NONCLUSTERED 
(
	[shopID] ASC,
	[CashAccountID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1429580131] ON [dbo].[ashopcashaccountdetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[JournalTransDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[JournalTransDetails](
	[JournalTransID] [int] NOT NULL,
	[JournalTransDetailID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[AccountID] [int] NOT NULL,
	[JournalTransCredit] [bit] NOT NULL,
	[Amount] [numeric](18, 2) NULL,
	[Remarks] [varchar](250) NULL,
	[PayrollLinktransId] [int] NULL,
 CONSTRAINT [PK_JournalTransDetails] PRIMARY KEY NONCLUSTERED 
(
	[JournalTransID] ASC,
	[JournalTransDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOspPurchaseBillOC]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOspPurchaseBillOC](
	[pboBillID] [int] NOT NULL,
	[pboAccID] [int] NOT NULL,
	[pboDescription] [varchar](50) NULL,
	[pboCompanyID] [int] NULL,
	[pboAmount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_LOspPurchaseBillOC] PRIMARY KEY NONCLUSTERED 
(
	[pboBillID] ASC,
	[pboAccID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOsPosOthercharges]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsPosOthercharges](
	[posoShopID] [int] NOT NULL,
	[posoBillID] [int] NOT NULL,
	[posoAccID] [int] NOT NULL,
	[posoDescription] [varchar](250) NULL,
	[posoAmount] [numeric](18, 2) NULL,
	[posoCompanyID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LOsPosOthercharges] PRIMARY KEY NONCLUSTERED 
(
	[posoShopID] ASC,
	[posoBillID] ASC,
	[posoAccID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1701581100] ON [dbo].[LOsPosOthercharges] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[InterDivisionBillsDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[InterDivisionBillsDetails](
	[BillsID] [int] NOT NULL,
	[BillsDetailID] [int] NOT NULL,
	[AccountID] [int] NOT NULL,
	[DepartmentId] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[Amount] [numeric](18, 2) NULL,
	[Remarks] [varchar](250) NULL,
 CONSTRAINT [PK_InterDivisionBillsDetails] PRIMARY KEY NONCLUSTERED 
(
	[BillsID] ASC,
	[BillsDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[assettransfer]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[assettransfer](
	[asttransid] [int] NOT NULL,
	[asttranscompanyid] [int] NOT NULL,
	[asttrransno] [varchar](50) NOT NULL,
	[asttransdate] [datetime] NOT NULL,
	[asttransassetid] [int] NOT NULL,
	[asttransfromdepid] [int] NOT NULL,
	[asttranstodepid] [int] NULL,
	[asttransvalue] [numeric](18, 2) NOT NULL,
	[asttransposted] [bit] NULL,
	[asttransremarks] [varchar](250) NOT NULL,
	[asttranscancelled] [bit] NULL,
	[asttranscancelledremarks] [varchar](250) NULL,
	[exchangerates] [varchar](250) NULL,
	[financialid] [int] NULL,
	[consexrate] [numeric](18, 8) NULL,
	[fromdepexrate] [numeric](18, 8) NULL,
	[todepexrate] [numeric](18, 8) NULL,
	[Updatetime] [datetime] NULL,
	[FromAssetAccId] [int] NULL,
	[ToAssetAccID] [int] NULL,
	[FromDeprAccId] [int] NULL,
	[ToDeprAccId] [int] NULL,
	[FromACCDeprAccId] [int] NULL,
	[ToACCDeprAccId] [int] NULL,
	[astDeprValue] [numeric](18, 2) NULL,
 CONSTRAINT [PK_assettransfer] PRIMARY KEY NONCLUSTERED 
(
	[asttransid] ASC,
	[asttranscompanyid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOsLocalPurchaseOC]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsLocalPurchaseOC](
	[lpoShopID] [int] NOT NULL,
	[lpoBillID] [int] NOT NULL,
	[lpoAccID] [int] NOT NULL,
	[lpoDescription] [varchar](50) NULL,
	[lpoAmount] [numeric](18, 2) NULL,
	[lpoCompanyID] [int] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LOsLocalPurchaseOC] PRIMARY KEY NONCLUSTERED 
(
	[lpoShopID] ASC,
	[lpoBillID] ASC,
	[lpoAccID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1941581955] ON [dbo].[LOsLocalPurchaseOC] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[BudgetAllocationDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BudgetAllocationDetail](
	[badCompanyID] [int] NOT NULL,
	[badBudgetAllocID] [int] NOT NULL,
	[badDetailID] [int] NOT NULL,
	[badBudgetHeadID] [int] NULL,
	[badFromDate] [datetime] NULL,
	[badToDate] [datetime] NULL,
	[badAmount] [numeric](18, 2) NULL,
	[badMonthNo] [int] NOT NULL,
	[badRevised] [bit] NULL,
 CONSTRAINT [PK_BudgetAllocationDetail] PRIMARY KEY NONCLUSTERED 
(
	[badCompanyID] ASC,
	[badBudgetAllocID] ASC,
	[badDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aShopCustomerDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aShopCustomerDetails](
	[ShopID] [int] NOT NULL,
	[CustomerID] [int] NOT NULL,
	[creditlimit] [numeric](18, 2) NULL,
	[custdiscperc] [numeric](18, 2) NULL,
	[futurevc] [varchar](250) NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[DuePeriod] [numeric](18, 2) NULL,
	[segmentid] [int] NULL,
 CONSTRAINT [PK_aShopCustomerDetails] PRIMARY KEY NONCLUSTERED 
(
	[ShopID] ASC,
	[CustomerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_325576198] ON [dbo].[aShopCustomerDetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LosShipmentbnheader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosShipmentbnheader](
	[bnhShopId] [int] NOT NULL,
	[bnhboatnoteId] [int] NOT NULL,
	[bnhboateNoteNo] [varchar](50) NULL,
	[bnhboatenotedate] [datetime] NULL,
	[bnhCustomerId] [int] NULL,
	[bnhRemark] [varchar](250) NULL,
	[bnhsentBy] [varchar](100) NULL,
	[bnhcancelled] [bit] NOT NULL,
	[bnhcancelledRemarks] [varchar](250) NULL,
	[bnhBoatNoteRecTime] [datetime] NULL,
	[bnhPersonReceived] [varchar](50) NULL,
	[bnhattento] [varchar](100) NULL,
	[bnhboatname] [varchar](100) NULL,
 CONSTRAINT [PK_LosShipmentbhheader] PRIMARY KEY NONCLUSTERED 
(
	[bnhShopId] ASC,
	[bnhboatnoteId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[BudgetAllocationHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[BudgetAllocationHeader](
	[bahCompanyID] [int] NOT NULL,
	[bahBudgetAllocID] [int] NOT NULL,
	[bahBudgetNo] [varchar](50) NULL,
	[bahBudgetDate] [datetime] NULL,
	[bahFromdate] [datetime] NULL,
	[bahToDate] [datetime] NULL,
	[bahBudgetPanel] [varchar](250) NULL,
	[bahReviewPanel] [varchar](250) NULL,
	[bahReviewDate] [datetime] NULL,
	[bahSanctionedBy] [varchar](100) NULL,
	[bahSanctionedDate] [datetime] NULL,
	[bahRemarks] [varchar](250) NULL,
	[bahCancelled] [bit] NULL,
	[bahCancelledRemarks] [varchar](250) NULL,
	[bahDepartmentId] [int] NULL,
 CONSTRAINT [PK_BudgetAllocationHeader] PRIMARY KEY NONCLUSTERED 
(
	[bahCompanyID] ASC,
	[bahBudgetAllocID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aLCRegisterDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aLCRegisterDetails](
	[LcCompanyID] [int] NOT NULL,
	[LcDepartmentID] [int] NOT NULL,
	[LcID] [int] NOT NULL,
	[LcNo] [varchar](100) NOT NULL,
	[LcDate] [datetime] NOT NULL,
	[LcFinancialid] [int] NOT NULL,
	[LcVendorID] [int] NULL,
	[LcVendorName] [varchar](250) NULL,
	[LcVendorCurrId] [int] NULL,
	[LcBankName] [varchar](100) NOT NULL,
	[LcBankAccName] [int] NOT NULL,
	[LcShipmentDetails] [varchar](250) NULL,
	[LcShipmentTermsDetails] [varchar](250) NULL,
	[LcPaymentTerms] [varchar](250) NULL,
	[LcReference] [varchar](250) NULL,
	[LcUsername] [varchar](250) NOT NULL,
	[LcUpdatedUsername] [varchar](250) NULL,
	[LcCancel] [int] NOT NULL,
	[LcCancelRemarks] [varchar](250) NULL,
	[LcEstDate] [datetime] NOT NULL,
	[LcDueDate] [datetime] NOT NULL,
	[LcAmount] [numeric](18, 2) NOT NULL,
	[LcMargin] [numeric](18, 2) NOT NULL,
	[LcBalance] [numeric](18, 2) NULL,
	[LcExchangeRates] [varchar](100) NOT NULL,
	[LcComExchangeRate] [numeric](18, 2) NOT NULL,
	[LcDepExchangeRate] [numeric](18, 2) NOT NULL,
 CONSTRAINT [PK_aLCRegisterDetails] PRIMARY KEY NONCLUSTERED 
(
	[LcID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aBouncedChequeDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aBouncedChequeDetails](
	[BcCompanyID] [int] NOT NULL,
	[BcDepartmentID] [int] NOT NULL,
	[BcID] [int] NOT NULL,
	[BcDate] [datetime] NOT NULL,
	[BcCustomerID] [int] NULL,
	[BcBankAccName] [varchar](100) NOT NULL,
	[BcReturnedDate] [datetime] NOT NULL,
	[BcCollectionDate] [datetime] NOT NULL,
	[BcAmount] [numeric](18, 2) NOT NULL,
	[BcChequeNo] [varchar](250) NOT NULL,
	[BcReference] [varchar](250) NULL,
	[BcUsername] [varchar](250) NOT NULL,
	[BcUpdatedUsername] [varchar](250) NULL,
	[BcCancel] [int] NOT NULL,
	[BcCancelRemarks] [varchar](250) NULL,
PRIMARY KEY CLUSTERED 
(
	[BcID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aHQPaymentVoucherVendorDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aHQPaymentVoucherVendorDetails](
	[pvdcompanyid] [int] NOT NULL,
	[pvdPaymentid] [int] NOT NULL,
	[pvdDetailid] [int] NOT NULL,
	[pvdVendorid] [int] NOT NULL,
	[pvdAmount] [numeric](18, 2) NOT NULL,
	[pvdVendorAmount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_aHQPaymentVoucherVendorDetails] PRIMARY KEY NONCLUSTERED 
(
	[pvdcompanyid] ASC,
	[pvdPaymentid] ASC,
	[pvdDetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aShopVendorDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aShopVendorDetails](
	[ShopID] [int] NOT NULL,
	[VendorID] [int] NOT NULL,
	[futurevc] [varchar](250) NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aShopVendorDetails] PRIMARY KEY NONCLUSTERED 
(
	[ShopID] ASC,
	[VendorID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1813581499] ON [dbo].[aShopVendorDetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[SCHEDULEDETAIL]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[SCHEDULEDETAIL](
	[scdid] [int] NULL,
	[scdjobid] [varchar](100) NOT NULL,
	[scdjobname] [varchar](250) NOT NULL,
	[scdlaststarttime] [datetime] NOT NULL,
	[scdlastexecutedtime] [datetime] NOT NULL,
	[scdskipno] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ShipmentClearenceRequestDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ShipmentClearenceRequestDetails](
	[ShopID] [int] NOT NULL,
	[ClearenceID] [int] NOT NULL,
	[DetailID] [int] NOT NULL,
	[ClearenceReqID] [int] NULL,
	[ArrivalDate] [datetime] NULL,
	[BLorAWNo] [varchar](50) NULL,
	[BLorAWDate] [datetime] NULL,
	[NoofPackages] [int] NULL,
	[GrossWeight] [numeric](18, 3) NULL,
	[NameofVessel] [varchar](250) NULL,
	[Remarks] [varchar](250) NULL,
 CONSTRAINT [pk_ShipmentClearenceRequestDetails] PRIMARY KEY CLUSTERED 
(
	[ShopID] ASC,
	[ClearenceID] ASC,
	[DetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ShipmentClearenceOCDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ShipmentClearenceOCDetails](
	[ShopID] [int] NOT NULL,
	[ClearenceID] [int] NOT NULL,
	[DetailID] [int] NOT NULL,
	[ClearenceReqID] [int] NULL,
	[OCDescription] [varchar](250) NULL,
	[OCAmt] [numeric](18, 2) NULL,
	[Remarks] [varchar](250) NULL,
 CONSTRAINT [pk_ShipmentClearenceOCDetails] PRIMARY KEY CLUSTERED 
(
	[ShopID] ASC,
	[ClearenceID] ASC,
	[DetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ShipmentClearenceChequeDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ShipmentClearenceChequeDetails](
	[ShopID] [int] NOT NULL,
	[ClearenceID] [int] NOT NULL,
	[DetailID] [int] NOT NULL,
	[ChequeNo] [varchar](50) NULL,
	[ChequeAmt] [numeric](18, 2) NULL,
	[Remarks] [varchar](250) NULL,
 CONSTRAINT [pk_ShipmentClearenceChequeDetails] PRIMARY KEY CLUSTERED 
(
	[ShopID] ASC,
	[ClearenceID] ASC,
	[DetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[ServiceInvoiceDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ServiceInvoiceDetails](
	[InvoiceID] [int] NOT NULL,
	[InvoiceDetailID] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[ServiceName] [varchar](100) NULL,
	[ServiceTerm] [varchar](50) NULL,
	[ServiceQty] [int] NOT NULL,
	[Amount] [numeric](18, 2) NULL,
	[Accountid] [int] NULL,
	[clearingReqId] [int] NULL,
	[ClearingOCAmt] [numeric](18, 2) NULL,
	[ClearingCommAmt] [numeric](18, 2) NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF
ALTER TABLE [dbo].[ServiceInvoiceDetails] ADD [Remarks] [varchar](250) NULL
ALTER TABLE [dbo].[ServiceInvoiceDetails] ADD [UserID] [int] NULL
ALTER TABLE [dbo].[ServiceInvoiceDetails] ADD  CONSTRAINT [PK_ServiceInvoiceDetails] PRIMARY KEY NONCLUSTERED 
(
	[InvoiceID] ASC,
	[InvoiceDetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOsServiceInvoiceDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsServiceInvoiceDetails](
	[siInvoiceDetailID] [int] NOT NULL,
	[siCompanyID] [int] NOT NULL,
	[siInvoiceID] [int] NOT NULL,
	[siServiceName] [varchar](250) NULL,
	[siServiceTerm] [varchar](100) NULL,
	[siServiceQty] [int] NULL,
	[siAmount] [numeric](18, 2) NULL,
	[siAccountid] [int] NULL,
	[siShopID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[siclearingReqId] [int] NULL,
	[siClearingOCAmt] [numeric](18, 2) NULL,
	[siClearingCommAmt] [numeric](18, 2) NULL,
	[siLocalPOId] [int] NULL,
	[siUserID] [int] NULL,
 CONSTRAINT [PK_LOsServiceInvoiceDetails] PRIMARY KEY NONCLUSTERED 
(
	[siInvoiceDetailID] ASC,
	[siInvoiceID] ASC,
	[siShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_709577566] ON [dbo].[LOsServiceInvoiceDetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Fb_resttable]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Fb_resttable](
	[Fb_rt_companyid] [int] NOT NULL,
	[Fb_rt_outletid] [int] NOT NULL,
	[fb_rt_tablemasterid] [int] NOT NULL,
	[Fb_rt_tableid] [int] NOT NULL,
	[Fb_rt_tablecode] [varchar](50) NULL,
	[Fb_rt_tablename] [varchar](250) NULL,
	[Fb_rt_Futureint] [int] NULL,
	[Fb_rt_Futurevarchar] [varchar](250) NULL,
	[Fb_rt_Futurebit] [bit] NULL,
 CONSTRAINT [PK_Fb_resttable] PRIMARY KEY NONCLUSTERED 
(
	[Fb_rt_companyid] ASC,
	[Fb_rt_outletid] ASC,
	[Fb_rt_tableid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOsPaymentVoucherDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LOsPaymentVoucherDetails](
	[pdPaymentVoucherID] [int] NOT NULL,
	[pdPaymentID] [int] NOT NULL,
	[pdShopID] [int] NOT NULL,
	[pdBillsID] [int] NOT NULL,
	[pdPaidAmount] [numeric](18, 2) NULL,
	[pdDuePeriod] [smallint] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_LOsPaymentVoucherDetails] PRIMARY KEY NONCLUSTERED 
(
	[pdPaymentVoucherID] ASC,
	[pdPaymentID] ASC,
	[pdShopID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_50099219] ON [dbo].[LOsPaymentVoucherDetails] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[fb_Tableoccupancy]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[fb_Tableoccupancy](
	[Fb_to_companyid] [int] NOT NULL,
	[fb_to_Outletid] [int] NOT NULL,
	[fb_to_Kotbotid] [int] NOT NULL,
	[fb_to_tableid] [int] NOT NULL,
	[fb_to_coverid] [int] NOT NULL,
	[fb_to_billcoverid] [int] NULL,
	[fb_to_billroomid] [int] NULL,
	[fb_to_billempid] [int] NULL,
	[fb_to_kotbotdatetime] [datetime] NULL,
	[fb_to_billdatetime] [datetime] NULL,
	[fb_to_kottrue] [bit] NOT NULL,
	[fb_to_cashreceived] [bit] NOT NULL,
	[fb_to_cashdatetime] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losHPChequeRegisterDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losHPChequeRegisterDetail](
	[HpdCompanyID] [int] NOT NULL,
	[HpdShopID] [int] NOT NULL,
	[HpdChqRegID] [int] NOT NULL,
	[HpdChqdetailID] [int] NOT NULL,
	[HpdChqNo] [nvarchar](50) NULL,
	[HpdBankName] [nvarchar](50) NULL,
	[HpdChqDate] [datetime] NULL,
	[HpdChqAmount] [numeric](18, 2) NULL,
	[hpdActualChqAmount] [numeric](18, 2) NULL,
	[HpdAccountNo] [varchar](50) NULL,
	[hpdchequeStatus] [nvarchar](50) NULL,
 CONSTRAINT [PK_losHPChequeRegistryDetail] PRIMARY KEY CLUSTERED 
(
	[HpdChqRegID] ASC,
	[HpdChqdetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aHQPaymentVoucherSPDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aHQPaymentVoucherSPDetails](
	[CompanyID] [int] NOT NULL,
	[PaymentID] [int] NOT NULL,
	[DetailID] [int] NOT NULL,
	[PromotionID] [int] NULL,
	[PromotionDetailID] [int] NULL,
	[PromotionAmt] [numeric](18, 2) NULL,
	[SettledAmt] [numeric](18, 2) NULL,
	[DeptEquiAmt] [numeric](18, 2) NULL,
 CONSTRAINT [pk_aHQPaymentVoucherSPDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[PaymentID] ASC,
	[DetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[FB_Dishsubgroup]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[FB_Dishsubgroup](
	[Fb_Ds_CompanyID] [int] NOT NULL,
	[Fb_Ds_DishSubGroupID] [int] NOT NULL,
	[Fb_Ds_DishGroupID] [int] NOT NULL,
	[Fb_Ds_DishSubGroupcode] [varchar](50) NULL,
	[Fb_Ds_DishSubGroupName] [varchar](250) NULL,
	[Fb_Ds_FutureInt] [int] NULL,
	[Fb_Ds_FutureVarChar] [varchar](250) NULL,
	[Fb_Ds_FutureBit] [bit] NOT NULL,
	[Fb_Ds_ProfitPer] [decimal](9, 2) NULL,
	[fb_ds_printerpath] [varchar](250) NULL,
	[fb_ds_imagepath] [varchar](500) NULL,
	[Fb_Ds_TaxCategoryId] [int] NULL,
 CONSTRAINT [PK_FB_Dishsubgroup] PRIMARY KEY NONCLUSTERED 
(
	[Fb_Ds_CompanyID] ASC,
	[Fb_Ds_DishSubGroupID] ASC,
	[Fb_Ds_DishGroupID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losHpDummyQuotationDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losHpDummyQuotationDetails](
	[hpqdCompanyID] [int] NULL,
	[hpqdShopId] [int] NULL,
	[hpqdQuotationID] [int] NULL,
	[hpqdDetailID] [int] NOT NULL,
	[hpqdItemID] [int] NOT NULL,
	[hpqdItemRegistrationId] [int] NULL,
	[hpqdFrameNo] [nvarchar](50) NULL,
	[hpqdSellingPrice] [numeric](18, 2) NOT NULL,
	[hpqdCostPrice] [numeric](18, 0) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losHpInvoiceDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losHpInvoiceDetail](
	[hpqdCompanyID] [int] NOT NULL,
	[hpqdShopId] [int] NOT NULL,
	[hpqdQuotationID] [int] NOT NULL,
	[hpqdDetailID] [int] NOT NULL,
	[hpqdItemID] [int] NOT NULL,
	[hpqdItemRegistrationId] [int] NULL,
	[hpqdFrameNo] [nvarchar](50) NULL,
	[hpqdSellingPrice] [numeric](18, 2) NULL,
	[hpqdCostPrice] [numeric](18, 2) NULL
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [index_loshpInvoiceDetail] ON [dbo].[losHpInvoiceDetail] 
(
	[hpqdQuotationID] ASC,
	[hpqdShopId] 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
/****** Object:  Table [dbo].[losHpInvoiceDetailOthers]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losHpInvoiceDetailOthers](
	[hpqdCompanyID] [int] NOT NULL,
	[hpqdShopId] [int] NOT NULL,
	[hpqdQuotationID] [int] NOT NULL,
	[hpqdActSellingPrice] [numeric](18, 2) NULL,
	[hpqdActInterest] [numeric](18, 2) NULL,
	[hpqdActDP] [numeric](18, 2) NULL,
	[hpqdActSurcharge] [numeric](18, 2) NULL,
	[hpqdActInstallmentPrice] [numeric](18, 2) NULL,
	[hpqdActMonthlyPayment] [numeric](18, 2) NULL,
	[hpqdTotalTax] [numeric](18, 2) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losBoatNoteConfirmHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losBoatNoteConfirmHeader](
	[ShopID] [int] NOT NULL,
	[ConfirmID] [int] NOT NULL,
	[ConfirmNO] [varchar](50) NULL,
	[ConfirmDate] [datetime] NULL,
	[BoatNoteID] [int] NULL,
	[InformedTime] [datetime] NULL,
	[InformedBy] [varchar](100) NULL,
	[Remarks] [varchar](250) NULL,
	[Cancelled] [bit] NOT NULL,
	[CancelledRemarks] [varchar](250) NULL,
	[DetailIDs] [varchar](250) NULL,
 CONSTRAINT [pk_losBoatNoteConfirmHeader] PRIMARY KEY CLUSTERED 
(
	[ShopID] ASC,
	[ConfirmID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LosShipmentbndetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LosShipmentbndetail](
	[bndShopId] [int] NOT NULL,
	[bndboatnoteId] [int] NOT NULL,
	[bnddetailId] [int] NOT NULL,
	[bndclearanceId] [int] NULL,
	[bndclearanceDetailId] [int] NULL,
	[bndPacking] [varchar](250) NULL,
	[bndqty] [numeric](10, 0) NULL,
	[bndunit] [varchar](25) NULL,
	[bndnoofpackage] [numeric](10, 0) NULL,
	[bndremarks] [varchar](100) NULL,
	[bndlppoid] [int] NULL,
	[bndlpdetailid] [int] NULL,
	[bndStatus] [char](1) NULL,
 CONSTRAINT [PK_LosShipmentbhdetail] PRIMARY KEY NONCLUSTERED 
(
	[bndShopId] ASC,
	[bndboatnoteId] ASC,
	[bnddetailId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losShipmentBNOCDetail]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losShipmentBNOCDetail](
	[ShopID] [int] NOT NULL,
	[BoatNoteID] [int] NOT NULL,
	[DetailID] [int] NOT NULL,
	[OCDesc] [varchar](250) NULL,
	[Remarks] [varchar](250) NULL,
	[Amount] [numeric](18, 2) NULL,
 CONSTRAINT [pk_losShipmentOCDetail] PRIMARY KEY CLUSTERED 
(
	[ShopID] ASC,
	[BoatNoteID] ASC,
	[DetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[loiexpiryissuedetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loiexpiryissuedetails](
	[eidinterfaceid] [int] NOT NULL,
	[eidgodownid] [int] NOT NULL,
	[eidtransactionid] [int] NOT NULL,
	[eiddetailid] [int] NOT NULL,
	[eidexpirydate] [datetime] NULL,
	[eiditemid] [int] NULL,
	[eiditemqty] [numeric](18, 3) NULL,
	[eidpackingtypeid] [int] NULL,
	[eidpackingqty] [numeric](18, 2) NULL,
	[eidcancel] [bit] NOT NULL,
	[eidAdjustment] [bit] NOT NULL,
	[eidbatchno] [varchar](20) NOT NULL,
 CONSTRAINT [PK_loiexpiryissuedetails] PRIMARY KEY NONCLUSTERED 
(
	[eidinterfaceid] ASC,
	[eidgodownid] ASC,
	[eidtransactionid] ASC,
	[eiddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[LOiSettings]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOiSettings](
	[Godownid] [int] NOT NULL,
	[sNoBackDays] [int] NOT NULL,
	[OpeningStockDate] [datetime] NULL,
	[barcodetype] [smallint] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[defaultfetch] [varchar](100) NULL,
	[reportsetting] [varchar](250) NULL,
 CONSTRAINT [PK_LOiSettings] PRIMARY KEY NONCLUSTERED 
(
	[Godownid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_565577053] ON [dbo].[LOiSettings] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[loiexpiryarrivaldetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[loiexpiryarrivaldetails](
	[eadinterfaceid] [int] NOT NULL,
	[eadgodownid] [int] NOT NULL,
	[eadtransactionid] [int] NOT NULL,
	[eaddetailid] [int] NOT NULL,
	[eadexpirydate] [datetime] NULL,
	[eaditemid] [int] NULL,
	[eaditemqty] [numeric](18, 3) NULL,
	[eadpackingtypeid] [int] NULL,
	[eadpackingqty] [numeric](18, 2) NULL,
	[eadcancel] [bit] NOT NULL,
	[eadAdjustment] [bit] NOT NULL,
	[eadbatchno] [varchar](20) NOT NULL,
 CONSTRAINT [PK_loiexpiryarrivaldetails] PRIMARY KEY NONCLUSTERED 
(
	[eadinterfaceid] ASC,
	[eadgodownid] ASC,
	[eadtransactionid] ASC,
	[eaddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[losDeliveryNoteItemDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[losDeliveryNoteItemDetails](
	[dndShopID] [int] NOT NULL,
	[dndId] [int] NOT NULL,
	[dndDetailID] [int] NOT NULL,
	[dndItemID] [int] NOT NULL,
	[dndQty] [numeric](18, 2) NULL,
	[dndItemType] [varchar](10) NULL,
	[dndKitID] [int] NOT NULL,
	[dndKitQuantity] [numeric](18, 2) NULL,
	[issueQty] [numeric](18, 2) NULL,
	[dndItemRemarks] [nvarchar](500) NULL,
	[dndCollectFromGodownId] [int] NULL,
	[dndPackingTypeID] [int] NOT NULL,
 CONSTRAINT [PK_LosDeliveryNoteItemDetails] PRIMARY KEY NONCLUSTERED 
(
	[dndShopID] ASC,
	[dndId] ASC,
	[dndDetailID] ASC,
	[dndItemID] ASC,
	[dndKitID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[MEsTransLog]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MEsTransLog](
	[TransLogID] [int] NOT NULL,
	[LogDateTime] [datetime] NULL,
	[InterfaceName] [varchar](250) NULL,
	[UserName] [varchar](250) NULL,
	[Function] [varchar](10) NULL,
	[ShopID] [int] NULL,
	[GodownID] [int] NULL,
	[Comment] [varchar](1000) NULL,
	[systemlog] [bit] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_MEsTransLog] PRIMARY KEY NONCLUSTERED 
(
	[TransLogID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1861581670] ON [dbo].[MEsTransLog] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aHQPaymentVoucherSCDetails]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aHQPaymentVoucherSCDetails](
	[CompanyID] [int] NOT NULL,
	[PaymentID] [int] NOT NULL,
	[DetailID] [int] NOT NULL,
	[SalesCommID] [int] NULL,
	[SalesCommAmt] [numeric](18, 2) NULL,
	[SettledAmt] [numeric](18, 2) NULL,
	[DeptEquiAmt] [numeric](18, 2) NULL,
 CONSTRAINT [PK_aHQPaymentVoucherSCDetails] PRIMARY KEY CLUSTERED 
(
	[CompanyID] ASC,
	[PaymentID] ASC,
	[DetailID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ashopsercategory]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ashopsercategory](
	[ssercategid] [int] NOT NULL,
	[ssercatcompanyid] [int] NOT NULL,
	[sshopid] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_ASHOPSERCATEGORY] PRIMARY KEY NONCLUSTERED 
(
	[ssercategid] ASC,
	[ssercatcompanyid] ASC,
	[sshopid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_1429580131] ON [dbo].[ashopsercategory] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[aHpReceiptVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[aHpReceiptVoucherHeader](
	[hprhCompanyID] [int] NOT NULL,
	[hprhShopID] [int] NOT NULL,
	[hprhReceiptID] [int] NOT NULL,
	[hprhInvoiceNo] [int] NOT NULL,
	[hprhInvoiceDate] [datetime] NOT NULL,
	[hprhCustomerID] [int] NOT NULL,
	[hprhCancel] [int] NOT NULL,
	[hprhCancelledRemarks] [nvarchar](50) NULL,
	[hprhPosted] [int] NOT NULL,
	[hprhBankName] [nvarchar](50) NULL,
	[hprhRemarks] [nvarchar](250) NULL,
	[hprhChequeNo] [nvarchar](50) NULL,
	[hprhChequeDate] [datetime] NULL,
	[hprhAmount] [numeric](18, 0) NOT NULL,
 CONSTRAINT [PK_aHpReceiptVoucherHeader] PRIMARY KEY CLUSTERED 
(
	[hprhCompanyID] ASC,
	[hprhShopID] ASC,
	[hprhReceiptID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[ashopprintmessages]    Script Date: 04/16/2012 10:32:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ashopprintmessages](
	[shopid] [int] NOT NULL,
	[transtype] [varchar](50) NOT NULL,
	[messageid] [int] NOT NULL,
	[message] [varchar](500) NULL,
	[allignment] [char](1) NULL,
	[futureint] [int] NULL,
	[futurevarchar] [varchar](250) NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_ashopprintmessages] PRIMARY KEY NONCLUSTERED 
(
	[shopid] ASC,
	[transtype] ASC,
	[messageid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_901578250] ON [dbo].[ashopprintmessages] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[LOsSettings]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[LOsSettings](
	[ShopId] [int] NOT NULL,
	[sNoofBackDays] [int] NULL,
	[sGoodsReturnPeriod] [int] NULL,
	[OpeningStockDate] [datetime] NULL,
	[CBUserID] [int] NULL,
	[barcodetype] [smallint] NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
	[reportsetting] [varchar](50) NULL,
	[defaultfetch] [varchar](100) NULL,
	[ClearingCOMPerc] [numeric](18, 2) NULL,
	[HandlingPer] [numeric](18, 2) NULL,
	[HandlingAndPaymentPer] [numeric](18, 2) NULL,
	[allshops] [bit] NULL,
	[PopulateDateWise] [bit] NULL,
	[QuickItemFetch] [bit] NULL,
	[BlockAboveSP] [bit] NULL,
	[ShopActiveDirectoryLogin] [bit] NOT NULL,
	[DirectLocalPurchaseCosting] [bit] NOT NULL,
 CONSTRAINT [PK_LOsSettings] PRIMARY KEY NONCLUSTERED 
(
	[ShopId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE UNIQUE NONCLUSTERED INDEX [index_725577623] ON [dbo].[LOsSettings] 
(
	[rowguid] 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, FILLFACTOR = 90) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losEDIConfirmation]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[losEDIConfirmation](
	[ecshopid] [int] NOT NULL,
	[ecconfirmid] [int] NOT NULL,
	[ecconfirmno] [varchar](50) NULL,
	[ecconfirmdate] [datetime] NULL,
	[ecediid] [int] NULL,
	[ecrefno] [varchar](100) NULL,
	[ecstatus] [char](1) NULL,
	[ecconfirmedby] [varchar](100) NULL,
	[eccancelled] [bit] NOT NULL,
	[eccancelledremarks] [varchar](250) NULL,
 CONSTRAINT [PK_losEDIConfirmation] PRIMARY KEY NONCLUSTERED 
(
	[ecshopid] ASC,
	[ecconfirmid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aaccrepformat]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aaccrepformat](
	[companyid] [int] NOT NULL,
	[formatid] [int] NOT NULL,
	[Type] [char](5) NULL,
	[Partionchar] [char](5) NULL,
	[FormatName] [varchar](50) NULL,
	[UserCreated] [varchar](50) NULL,
	[DefaultFormat] [bit] NOT NULL,
	[NetCarriedForward] [bit] NOT NULL,
	[departmentid] [int] NULL,
 CONSTRAINT [pk_aaccrepformat] PRIMARY KEY CLUSTERED 
(
	[companyid] ASC,
	[formatid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aletterformat]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aletterformat](
	[letterid] [int] NOT NULL,
	[companyid] [int] NOT NULL,
	[lettercode] [varchar](50) NULL,
	[lettername] [varchar](100) NULL,
	[details] [varchar](2000) NULL,
 CONSTRAINT [PK_aletterformat] PRIMARY KEY NONCLUSTERED 
(
	[letterid] ASC,
	[companyid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[aHpProcessingHeader]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[aHpProcessingHeader](
	[hphCompanyID] [int] NOT NULL,
	[hphDepartmentID] [int] NOT NULL,
	[hphProcessingID] [int] NOT NULL,
	[hphProcessingNo] [nvarchar](50) NOT NULL,
	[hphProcessingDate] [datetime] NOT NULL,
	[hphCustomerID] [int] NULL,
	[hphInvoiceID] [int] NOT NULL,
	[hphUsed] [int] NOT NULL,
	[hphFinancialID] [int] NOT NULL,
	[hphCancel] [int] NOT NULL,
	[hphcancelRemarks] [nvarchar](50) NULL,
	[hphCashPrice] [numeric](18, 2) NOT NULL,
	[hphDownPayment] [numeric](18, 2) NOT NULL,
	[hphBalance] [numeric](18, 2) NOT NULL,
	[hphNoOfRentals] [int] NOT NULL,
	[hphInterestRate] [numeric](18, 2) NOT NULL,
	[hphInstallmentPrice] [numeric](18, 2) NOT NULL,
	[hphRentalAmount] [numeric](18, 2) NULL,
	[hphAdjustmentAmount] [numeric](18, 2) NULL,
	[hphAmended] [int] NULL,
	[hphRemarks] [nvarchar](250) NULL,
	[hphuserName] [nvarchar](50) NULL,
	[hphUpdateUserName] [nvarchar](50) NULL,
	[hphUpdateTime] [datetime] NULL,
	[hphReprocessingType] [char](7) NULL,
	[hphReferenceID] [int] NULL,
	[hphBalanceInterest] [numeric](18, 2) NULL,
	[hphreprocessaftersettlement] [bit] NULL,
	[hphAdjustmentPosted] [int] NULL,
 CONSTRAINT [PK_aHpProcessingHeader] PRIMARY KEY CLUSTERED 
(
	[hphCompanyID] ASC,
	[hphDepartmentID] ASC,
	[hphProcessingID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[hqSalesCommisiondetail]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[hqSalesCommisiondetail](
	[scdCommisionID] [int] NULL,
	[scdDetailID] [int] NULL,
	[scdInterfaceID] [int] NULL,
	[scdShopID] [int] NULL,
	[scdtransactionID] [int] NULL,
	[scdCommisionAmount] [numeric](18, 2) NULL,
	[scdcompanyid] [int] NULL,
	[scdEligiblePer] [numeric](5, 2) NULL,
	[scdCommissionPer] [numeric](5, 2) NULL
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Fb_processrecipedetail]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Fb_processrecipedetail](
	[fb_pr_companyid] [int] NOT NULL,
	[fb_pr_outletid] [int] NOT NULL,
	[fb_pr_Processid] [int] NOT NULL,
	[fb_pr_processdetailid] [int] NOT NULL,
	[fb_pr_processrecdetailid] [int] NOT NULL,
	[fb_pr_recipeitemid] [int] NOT NULL,
	[fb_pr_quantity] [decimal](18, 2) NULL,
	[fb_pr_yieldqtyper] [decimal](18, 0) NULL,
	[fb_pr_recipedishid] [int] NULL,
	[fb_pr_recipedishqty] [decimal](9, 3) NULL,
 CONSTRAINT [PK_Fb_processrecipedetail] PRIMARY KEY NONCLUSTERED 
(
	[fb_pr_companyid] ASC,
	[fb_pr_outletid] ASC,
	[fb_pr_Processid] ASC,
	[fb_pr_processdetailid] ASC,
	[fb_pr_processrecdetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losTenantUtilityBillDetail]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losTenantUtilityBillDetail](
	[utdBillId] [int] NOT NULL,
	[utdShopId] [int] NOT NULL,
	[utdCompanyId] [int] NOT NULL,
	[utdServiceId] [int] NOT NULL,
	[utdFromDate] [datetime] NULL,
	[utdToDate] [datetime] NULL,
	[utdMeterReading] [numeric](28, 8) NULL,
	[utdUnits] [numeric](18, 8) NULL,
	[utdRate] [numeric](18, 2) NULL,
	[utdAmount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_losTenantUtilityBillDetail] PRIMARY KEY NONCLUSTERED 
(
	[utdBillId] ASC,
	[utdShopId] ASC,
	[utdCompanyId] ASC,
	[utdServiceId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[losTenantServiceBillDetail]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[losTenantServiceBillDetail](
	[tbdBillId] [int] NOT NULL,
	[tbdShopId] [int] NOT NULL,
	[tbdCompanyId] [int] NOT NULL,
	[tbdUtilityTransID] [int] NOT NULL,
	[tbddetailid] [int] NOT NULL,
	[tbdAmount] [numeric](18, 2) NULL,
	[tbdRefAmount] [numeric](18, 2) NULL,
 CONSTRAINT [PK_losTenantServiceBillDetail] PRIMARY KEY NONCLUSTERED 
(
	[tbdBillId] ASC,
	[tbdShopId] ASC,
	[tbdCompanyId] ASC,
	[tbdUtilityTransID] ASC,
	[tbddetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[Fb_kotdetails]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Fb_kotdetails](
	[fb_kd_Companyid] [int] NOT NULL,
	[fb_kd_Outletid] [int] NOT NULL,
	[fb_kd_kotid] [int] NOT NULL,
	[fb_kd_kotdetailid] [int] NOT NULL,
	[fb_kd_dishid] [int] NOT NULL,
	[fb_kd_kotquantity] [decimal](18, 2) NULL,
	[fb_kd_rate] [decimal](18, 2) NULL,
	[fb_kd_processed] [bit] NOT NULL,
	[fb_kd_remarks] [varchar](250) NULL,
	[fb_kd_Setteled] [int] NULL,
	[fb_kd_AddedItemtype] [int] NULL,
 CONSTRAINT [PK_Fb_kotdetails] PRIMARY KEY NONCLUSTERED 
(
	[fb_kd_Companyid] ASC,
	[fb_kd_Outletid] ASC,
	[fb_kd_kotid] ASC,
	[fb_kd_kotdetailid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'''1-Added Dish ''2-Added Item ''0-Ordinary Dish' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Fb_kotdetails', @level2type=N'COLUMN',@level2name=N'fb_kd_AddedItemtype'
GO
/****** Object:  StoredProcedure [dbo].[spHandlingDebitNote]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO





/****** Object:  View [dbo].[VwCommisionInvDetails]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[spCommissiONInvoice]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spCommissiONInvoiceItemDetails]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spBoatNote]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spTenantRegister]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-------------------------------------------------------------------------------
-- 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
GO

/****** Object:  View [dbo].[vwItemDescription]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  
  
/*  
 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].[vwcustomerGroupcategory]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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:  View [dbo].[vwsuppreplacements]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwserbookingpartsblocked]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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].[vwCustomerWiseService]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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].[vwServiceHistory]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwOnsiteJobCardforprinting]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwservicebookinginvoices]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[VwPartsReplacerequestdtls]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwcustomerwiseservices]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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].[vwproductwiseservices]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[Vwbookingservicespartsforprint]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[machinerepairegister]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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].[vwservicetechniciandetails]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  
  
--------------------------------------------------------------     
--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].[vwInvoiceServicePartsForPrinting]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwJobcardServicePartsForPrinting]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwTransactionListAson15062011]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwServiceReplacements]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwbookingserviceinvoicedtls]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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].[vwbookservicesdone]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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].[vwbookingpartsneeded]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwpartsfromcustomer]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwservicedbookdetails]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwUnPostedShopTransactions]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==================================================================       
-- Created by : MANUNADH. U    
-- Created on : 23/03/2012
-- Comments   : To create a report for showing unposted shop transactions
-- =================================================================       
create VIEW [dbo].[vwUnPostedShopTransactions] AS  
SELECT 'POS' TransactionType,poshbillid TransactionId,poshbillno TransactionNo,poshbilldate TransactionDate,
	poshDepartmentid Departmentid,ph.poshshopid LocationId,S.ShopName LocationName
FROM losposheader ph 
	LEFT OUTER JOIN Ashops S ON ph.poshshopid = S.ShopID            
WHERE ph.poshcancellED = 0 and ph.poshpostED = 0 

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

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

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

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

UNION ALL

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

UNION ALL

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

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

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

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

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

UNION ALL

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

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

UNION ALL

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

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

UNION ALL

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

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

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

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

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

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

UNION ALL

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNION ALL
SELECT 'Warrenty Claim',wchID,wchNo,wchDate,0,wchShopID,S.ShopName
FROM losWarrentyClaimHeader
	LEFT OUTER JOIN Ashops S ON wchSHOPID = S.ShopID
WHERE wchType='WC' and wchposted=0 and wchCancelled=0 and wchConfirmed=1
GO
/****** Object:  View [dbo].[vwcustomerwiseservicepending]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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].[vwmachinesinstalled]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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].[vwServDeptRevenueSeperated]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----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].[vwMagnolia_ServiceHistoryWeb]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwbookingpartsreplaced]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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].[vwmachinerepairegister]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwTransactionList]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- 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].[vwbookservicesneeded]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwpendingbilldetails]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
----------------------------------------------------------------- 
--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:  StoredProcedure [dbo].[spULHPSaleInv]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Procedure



--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    
---------------------------------------------------------------------      
  
--spULHPSaleInv 1,4  
       
CREATE proc [dbo].[spULHPSaleInv]               
 @intCompanyID as int,               
 @intShopId as int               
as               
              
begin              
 Declare @intJournalId    as int,              
  @intJournalDetailId   as int,              
  @intFinancialID   as int,              
  @intInvoiceId    as int,              
  @intCustomerId    as int,                
  @intDepartmentID   as int,              
  @intComCurID    as int,              
  @intinventoryaccid   as int,              
  @intCostOfGoodsAccId   as int,                
  @intcomdeptid    as int,              
  @intCurrencyId    as int,               
  @intSalesaccid    as int,               
  @intCustomerAccID   as int,               
  @intSuspenseAccID  as int,               
  @numtotalinvValue   as NumEric(18,2),                
  @numTotalCostValue   as NumEric(18,2),                
  @InterestAmount   as NumEric(18,2),                 
  @numSalesValue   as NumEric(18,2),          
  @numTotatInstAmount  as NumEric(18,2),               
  @strinvoiceNo    as varchar(50),              
  @strRemarks    as varchar(250),                
  @dtinvoiceDate    as datetime,              
  @dtutime    as datetime,              
  @numtaxamount as numeric(18,2), --RefNo:1-    
  @numSurcharge as numeric(18,2)  --RefNo:1-  
              
 /* getting the defaults into the variables */              
 /* getting the maximum Journal ID FROM journal table */              
 SELECT               
  @intJournalId = isnull(max(JournalId),0)               
 FROM               
  moaJournalHeader               
 WHERE               
  CompanyID = @intCompanyID              
 --->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>              
 set @numTotalinvValue  = 0.0              
 set @numTotalCostValue = 0.0               
 --->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>              
 select               
  @intcomcurid = CurrencyId               
 from               
  acompanymaster               
 where               
  companyid = @intcompanyid              
 --->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>              
 select  @intcomdeptid  =companydepartment               
                
 from               
  apackagesettings               
 where                
  companyid = @intcompanyid              
 --->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>              
 Select @intdepartmentid =DepartmentID From aShops where shopID=@intShopID              
 --->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>              
 Select               
  @intCostOfGoodsAccId =COGSAcc, @intCustomerAccID =DebtorAcc,               
  @intSalesaccid =SalesAcc,@intSuspenseAccID=SuspenseAcc              
 from               
  ahpaccountssettings               
 where                
  companyid = @intcompanyid              
 --->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>              
 select  @intInventoryaccid =inventoryid                
 from               
  apackagesettings               
 where                
  companyid = @intcompanyid              
 --To return if the corresponding accounts are not selected               
 if isnull(@intCostOfGoodsAccId,0)=0 or isnull(@intInventoryaccid,0)=0              
  return 0              
 --To return if the corresponding accounts are not selected               
 if (isnull(@intCustomerAccID,0)=0 or isnull(@intSalesaccid,0)=0)              
  return 0              
 set @intJournalId = @intJournalId + 1              
               
 Declare invcur cursor for               
  SELECT               
   hpqhQuotationID, hpqhQuotationNo, hpqhQuotationDate, hpqhCustomerId,  hpqhremarks,               
   hpqhfinancialid,hpqhupdatetime,hpqhTotAdditional,hpqhInstPrice             
  FROM               
   loshpinvoiceheader               
  WHERE               
   hpqhcancel =0 and hpqhposted =0  and hpqhConfirmed=1 and              
   hpqhCompanyID = @intCompanyID and hpqhShopId = @intShopId              
   and hpqhType='I'                 
 open invcur              
               
 fetch next FROM invcur into               
  @intInvoiceId, @strinvoiceno, @dtinvoicedate, @intCustomerId, @strremarks,               
  @intfinancialid,  @dtutime,@InterestAmount, @numTotatInstAmount             
 while @@Fetch_status = 0              
 begin              
  set @numTotalinvValue  = 0.0              
  set @numTotalCostValue = 0.0                 
  SELECT               
   @numTotalinvValue = sum(hpqdCostPrice),               
   @numTotalCostValue = sum(hpqdCostPrice),              
   @numSalesValue=sum(hpqdSellingPrice)                 
  FROM               
   loshpinvoicedetail               
  WHERE               
   hpqdShopId = @intShopId and hpqdQuotationId  = @intInvoiceId               
  group by               
   hpqdShopId, hpqdQuotationId    
            
-------RefNo:1------    
if exists (select * from losHpInvoiceDetailOthers where hpqdShopId = @intShopId and hpqdQuotationId  = @intInvoiceId)  
begin

  select @numSalesValue=hpqdActSellingPrice    
  ,@InterestAmount=hpqdActInterest
  ,@numSurcharge =hpqdActSurcharge    
  ,@numTotatInstAmount=hpqdActInstallmentPrice    
  ,@numtaxamount=hpqdTotalTax    
  from losHpInvoiceDetailOthers    
  WHERE hpqdShopId = @intShopId and hpqdQuotationId  = @intInvoiceId  

  
  set @InterestAmount=@InterestAmount+@numSurcharge --Total Additional Amount->Interest A/C
  
  --Actually Total Addition Amount is saved as Total Interest Amount and posted to Interest a/c.
  --So interest amount is added upto Surcharge to find total Additional Amount         
end   
-------RefNo:1------            
              
  insert into moaJournalHeader               
   (JournalId, CompanyID, JournalDate, referenceno, remarks, financialID,               
   Type, CurrencyId, chequedate, updatetime)               
  values               
   (@intJournalId, @intCompanyID, @dtinvoicedate, @strinvoiceNo,               
   @strRemarks, @intFinancialID,'HPI', @intcomCurID,@dtinvoicedate, @dtutime)              
              
  set @intJournalDetailId = 1               
              
  /* crediing the sales account with the full invoice Amount */              
  insert into moaJournalDetails               
   (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,               
   Amount, actualAmount, departmentID, depamount, PostGroup)              
  values               
   (@intJournalId, @intJournalDetailId, @intCompanyID, 1,               
   @intSalesaccid, @numSalesValue,               
   @numSalesValue,@intDepartmentID,@numSalesValue, 1)              
              
  set @intJournalDetailId = @intJournalDetailId +1              
  /* Crediting Interest Amount */               
  insert into moaJournalDetails               
   (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,               
   Amount, actualAmount, departmentID, depamount, PostGroup)              
  values               
   (@intJournalId, @intJournalDetailId, @intCompanyID, 1,               
   @intSuspenseAccID, @InterestAmount,               
   @InterestAmount,@intDepartmentID, @InterestAmount, 1)              
              
  set @intJournalDetailId = @intJournalDetailId +1              
  -- DEBITING customer Invoice amount              
  insert into moaJournalDetails               
   (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountId,               
   Amount, actualAmount, departmentID, depamount, PostGroup)              
   values               
   (@intJournalId, @intJournalDetailId, @intCompanyID, 0, @intCustomerAccID,               
   @numTotatInstAmount, @numTotatInstAmount,              
   @intDepartmentID, @numTotatInstAmount, 1)              
               
   set @intJournalDetailId = @intJournalDetailId + 1        
              
  /* crediing the INVENTORY with the full cost Amount */              
  insert into moaJournalDetails               
   (JournalId, JournalDetailId, CompanyID,               
   JournalCrEDit, AccountID, Amount, actualAmount, departmentID, depamount, PostGroup)              
  values               
   (@intJournalId, @intJournalDetailId, @intCompanyID, 1,               
   @intINVentoryAccID, @numTotalCostValue, @numTotalCostValue,              
   @intDepartmentID,@numTotalCostValue , 4)              
                 
  set @intJournalDetailId = @intJournalDetailId +1              
              
  -- DEBITING THE COST OF GOODS ACCOUNT              
  insert into moaJournalDetails      
   (JournalId, JournalDetailId,CompanyID,               
   JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount, PostGroup)              
  values               
   (@intJournalId, @intJournalDetailId, @intCompanyID, 0,               
   @intCostOfGoodsAccId, @numTotalCostValue, @numTotalCostValue,               
   @intDepartmentID, @numTotalCostValue , 4)              
              
  /* mark the record as postED */              
  update loshpinvoiceheader set               
   hpqhpostED =1               
  WHERE               
   hpqhCompanyID = @intCompanyID               
   and hpqhShopId = @intShopId and hpqhQuotationId = @intInvoiceId               
              
  set @intJournalId = @intJournalId + 1              
                
  fetch next FROM invcur into               
  @intInvoiceId, @strinvoiceno, @dtinvoicedate, @intCustomerId, @strremarks,               
  @intfinancialid,  @dtutime,@InterestAmount,@numTotatInstAmount              
 end              
 Close invcur              
 Deallocate invcur              
              
end
GO
/****** Object:  View [dbo].[vwShopItemSales]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Modified on  : 20/12/02                              
--Modified by   : Hariharan R                              
--Comments  : v3                              
--Added reexporting transaction                              
--------------------------------------------------------------------------                              
-- Modified by     : Kishore                              
-- Modified on  : 12/06/2003                              
-- Comments  : Added the aMount, cAmount and dAmount columns                              
--                        (On comparison with v2)                              
--------------------------------------------------------------------------                              
                              
 --------------------------------------------------------------------                              
--Modified on                  : 27/08/2003                              
--Modified by                  : Reji Abraham                              
--Comments                     : Replaced table losserviceheader by losserviceinvheader                                  
--          : and modified fields, previous fields are alias names                              
--          :given ihTransFinised = 1 condition check to pick the confirmed                              
--          :Transactions Only.                              
                              
-------------------------------------------------------------------------------------                              
--Modified on                  : 15/04/04                              
--Modified by                  : venkitesh                              
--Comments                     : Replaced - symbol for goods return case and Given convert for getting accurated figure                            
-------------------------------------------------------------------------------------                              
--Modified on                  : 26/08/08                              
--Modified by                  : Benzigar                              
--Comments                     : Added condition ihNoofOCDetails=0 in specialinvoice to avoid return before despatch items from daily sales                           
--                             : Added case for Direct invoice - return before despatch                          
---------------------------------------------------------------------------------------                      
--Modified on                  : 05/08/09                              
--Modified by                  : Nidheesh                               
--Comments                     : taken the reqqty as negative in the case of RBD of (4  Direct invoice - return before despatch )                           
-- : removed the minus sign of unitprice,margin               
---------------------------------------------------------------------------------------            
--Modified on                  : 23/10/09                  
--Modified by                  : Nidheesh                  
--Comments                     : Included the requiremnet of adding custom price to cost price for shop credit invoice.(case-2)                
--                             : checked whether the shop is BondedWareHouse or not and  'AddCustomDutyToCostPrice'.             
---------------------------------------------------------------------------------------                      
--Modified on                  : 10/11/09                              
--Modified by                  : Regin              
--Comments                     : To get the margin of sale correctly modified the margin portion               
---------------------------------------------------------------------------------------                      
--Modified on                  : 10/11/09                              
--Modified by                  : Regin              
--Comments                     : In Goods Exchange part, sedquantity was replaced by sedExchangeQty since sedExchangeQty is the returned qty              
---------------------------------------------------------------------------------------                      
--Modified on                  : 05/12/2009            
--Modified by                  : Benzigar              
--Comments                     : In invoice part added case condition to handle divided by 0 problem             
---------------------------------------------------------------------------------------                      
--Modified on                  : 07/08/2010              
--Modified by                  : Sreejith G A              
--Comments                     : Added an additional field Actual Price of the item from Transaction table         
---------------------------------------------------------------------------------------                      
--Modified on                  : 17/11/2010              
--Modified by                  : Abhishek CS             
--Comments                     : customerid added for koddoo salesanalysisbyitem(actual)report need to filter by customer      
---------------------------------------------------------------------------------------                      
--Modified on                  : 19/05/2011              
--Modified by                  : Aadyakumar.D.V             
--Comments                     : FRS-409830,divide by zero errror     
---------------------------------------------------------------------------------------                      
--Modified on                  : 18/06/2011              
--Modified by                  : Nidheesh P V           
--Comments                     : Added ELSE part in the checking of wheather quantity is zero or not.  
--Modified Area       : All reports which are showing sales of items.  
--Reference        : RefNo:1  
---------------------------------------------------------------------------------------         
     
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].[vwAverageSalesQtyItemWise]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------  
-- 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:  View [dbo].[vwAverageSalesQtyOfAllShopsItemWise]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[spPDChequeRegisterForPOS]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spDepUsed]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwaccountsdepwise]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwNonControlAccounts]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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:  StoredProcedure [dbo].[spPOPaymentStatus]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------          
-- 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
GO
/****** Object:  View [dbo].[vwShopItemSalesforSeasonalPrediction]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwDiscountGiven]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------------------------------------------------    
--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].[vwKeyPerformanceIndexes]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  View [dbo].[vwCustomerSalesQtyWise]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*     
--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].[spShopSalesByHour]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwShopInvoices]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwBasketSales]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  View [dbo].[vwShopBinCardAudit_Pos]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Created By : Benzigar S D    
--Created On : 20/01/2009       
--Comment    : To Speed up POS   
-----------------------------------------  
--MODIFIED BY : NIDHEESH PV  
--MODIFIED ON :09/02/2011  
--cOMMENTS : ADDED INHOUSE RETURN  
--------------------------------------------------------------------------------      
--Modified by          : Nidheesh P V  
--Modified on          : 6/07/2011          
--Comments             : Added In-House Consumption part seperately.  
--Modified Area        : All Interfaces where stock effects  
--Referenc No          : Ref-No1      
--------------------------------------------------------------------------------        
-- Referenc No  : Ref-No2
-- Modified by	: MANUNADH.U      
-- Modified on	: 26/03/2012              
-- Comments     : Add the condition to filter local purchase bill with lphConfirmed=1
-------------------------------------------------------------------------------- 

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

--Deapatch        
select dd.dgdshopid, dd.dgditemid         
from mesdespatchtogodownheader dh, mesdespatchtogodowndetail dd         
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0         
and dghtransfinished = 1 -- for the concept of stock updation after transaction finish         
group by dd.dgdshopid, dh.dghdate, dh.dghid, dh.dghNo,dd.dgditemid,updatetime,         
dgdCostPrice, dghdepexrate, dghconexrate        
        
union all        
        
--Transferout        
select todshopid, toditemid        
 from mestransferoutheader , mestransferoutdetail  where        
tohid=todid and Tohshopid=todshopid and tohcancelled=0        
and tohtransfinished = 1 -- for the concept of stock updation after transaction finish         
group by todshopid, tohdate, tohid, tohno, todItemid,updatetime, todCostPrice,         
tohdepexrate, tohConExrate        
        
union all        
        
--recovery minus        
select sr.srshopid, sr.sritemid from         
losstockrecovery sr group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,         
srCostPrice, srdepexrate, srconexrate having sum(isnull(sr.srdedstock,0)) >0        
        
union all        
        
--stockverification minus        
select svdshopid, svdItemid      
from  losstockverificationheader, losstockverificationdetail where        
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock        
and svhCancelled=0 group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,         
svdCostPrice, svhdepexrate , svhconexrate         
  union all        
        
--pos sales        
select poshShopID, posditemid from losposdetail,losposheader         
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0 group by        
poshshopid, poshbillid, poshBillNo, poshbilldate, poshbillid, poshBillNo,         
posditemid,updatetime, posdCostPrice, poshdepexrate, poshExchangeRate        
        
union all        
        
--credit invoice        
select IhShopid, iditemid  from losinvoicedetail,losinvoiceheader        
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0        
and ihType ='I' group by ihshopid, ihinvoicedate, ihInvoiceid, ihInvoiceNo, iditemid,         
updatetime, idCostPrice, ihdepexrate, ihExchangeRate        
        
union all        
        
--exchange out        
select sehShopID, seditemid           
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID         
and sedShopID=sehShopid and sedBillorExchange='E' and SEHCANCELLED=0        
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,         
sedCostPRice, sehdepexrate, sehExchangerate         
        
union all        
        
--special invoice return to shop        
select IhShopid, iditemid     
from losspecialinvoicedetail, losspecialinvoiceheader        
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1        
and ihproforma=0 and ihTransFinished = 1 group by ihshopid, ihinvoicedate, ihInvoiceid,         
ihInvoiceNo, iditemid, updatetime, idCostPrice, ihdepexrate, ihExchangerate        
 -- transfinished added as stock is updated only after confirming        
        
union all        
        
 --COMMENTED AS MODIFICATIONS ON SERVICE IS GOING ON. TO BE REMOVED ONCE IT IS COMPLETED        
  select serinvhShopid, repinvdpartsid       
  from losinvoicedpartsreplacedetails, losserviceinvheader where serinvhid = repinvinvoiceid          
  and serinvhshopid = repinvdshopid AND serinvhcancelled=0         
  group by serinvhShopid,  serinvhdate , serinvhid , serinvNo ,  repinvdpartsid,         
 serinvhupdatetime, repinvdcostprice, seinvhdepexrate, serinvhcmpexrate        
        
  union all        
         
--Re-Exporting        
select rehShopID, reditemid         
from losexportdetail, losexportheader        
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0        
and rehType='I' group by rehShopID, rehExportDate, rehExportID, rehExportNo, redItemID,         
rehUpdatetime, redCostPrice, rehdepexrate, rehExchangerate  
  
UNION ALL  
  
--InHouse Return                           
SELECT IHRHShopID,IHRDItemID  
FROM LOs_InHouseCons_ReturnHeader rh    
INNER JOIN  LOs_InHouseCons_ReturnDetail rd   
on IHRHShopID=IHRDShopID and IHRHID=IHRDID AND IHRHCancelled=0 AND IHRHConfirmed=1  
group by IHRHShopID,IHRHID,IHRDItemID                       
                     
  
)        
 shopbin        
    
-------------------------------------------------------------------------------------------
GO
/****** Object:  View [dbo].[vwsalespersonperformance]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------          
--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].[vwitempackingtypecheck]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwSpecialInvoiceDetails]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------                            
/*                            
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].[vwspecialreturninvoicetosettle]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwShopBincardAudit]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Modified By   : Benzigar 23092008                              
-- Modified Date : 23092008                              
-- Comment       : Added Business Promotion/Warrenty claim                    
-- =====================================                    
-- Upgraded By : Regin T.                    
-- Upgraded On : 22-07-2010                    
-- Upgrade     : An outer Group By clause was used to change                     
--   the position of TransId and TransNo fields.                    
--   This Group By clause casued delay. So I removed it, and                     
--   changed the position of fields in all union all parts.                    
--   Old position: TransId, TransNo                    
--   New position: TransNo, TransId                    
-- =====================================                    
-- Upgraded By : Regin T.                  
-- Upgraded On : 18-09-2010                    
-- Upgrade     : Added FandB Bill                  
-- =====================================                  
-- Upgraded By : NIDHEESH P.V.                  
-- Upgraded On : 09-02-2011                    
-- Upgrade     : Added In-House Return                 
-- =====================================             
--------------------------------------------------------------------------------        
-- Modified by          : MANUNADH.U ON : 11/05/2011        
-- Comments             : Added the column From/To for Bincard Audit report                      
--------------------------------------------------------------------------------             
 --------------------------------------------------------------------------------        
-- Modified by          : AADYAKUMAR.D.V ON : 31/05/2011        
-- Comments             : Bug fixed in transfer out      
--------------------------------------------------------------------------------    
--Modified by          : Nidheesh P V
--Modified on		   : 6/07/2011        
--Comments             : Added In-House Consumption part seperately.
--Modified Area        : All Interfaces where stock effects
--Referenc No          : Ref-No1    
--------------------------------------------------------------------------------             
-- Referenc No  : Ref-No2
-- Modified by	: MANUNADH.U      
-- Modified on	: 26/03/2012              
-- Comments     : Add the condition to filter local purchase bill with lphConfirmed=1      
--------------------------------------------------------------------------------             
CREATE VIEW [dbo].[vwShopBincardAudit]  AS           
--arrival from godown           
select h.gahshopid ShopId, d.gaditemid ItemId, h.gaharrivaldate sDate,h.gaharrivalno TransNo,h.gaharrivalid TransId,        
 convert(numeric(18,3),isnull(sum(d.gadItemGoodQuantityArrived),0)) TransQty,'Arrival From Godown' [Type],         
 1 Mode, UpdateTime, gadCostprice CostPrice,gadCostPrice * gahdepexrate DepCostPrice,         
 gadCostPrice * gahconexrate ConCostPrice,        
 --(case when g.GodownName IS null then 'HQ' else g.GodownName end  + '/' + s.ShopName)  as 'From/To'         
 (case when g.GodownName IS null then 'HQ' else g.GodownName end  )  as 'From/To'                      
from losgoodsarrivaltoshopheader h        
 left outer join aGodown g on g.GodownID=h.gahDespatchedGodownID        
 left outer join ashops s on s.ShopID=h.gahShopid,losgoodsarrivaltoshopdetail d        
where h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and h.gahtransfinished=1             
group by  h.gahshopid, h.gaharrivaldate, h.gaharrivalid,gaharrivalno, d.gaditemid,updatetime, gadCostprice,         
 gahdepexrate, gahconexrate,g.GodownName,s.ShopName                                              
                                        
----GOODS RETURN TO SHOPS FROM CREDIT INVOICES                                        
union all                                        
                                        
select grn.grnhShopid, grd.GRNDItemID, GrnhGoodsreturnnoteDate sdate,GrnhGoodsreturnnoteNO transno,         
 GrnhGoodsreturnnoteID transid, convert(numeric(18,3),isnull(GRNDQuantity,0)) transqty,'Goods Return',1 as mode,        
 updatetime, grncostprice,grncostprice * grnhdepexrate depCostPrice, grncostprice * grnhExchangeRate ConCostPrice,        
 '' as 'From/To'        
from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd                                        
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid = grd.GRNDShopid and GrnhCancel=0         
 and GRNDDamaged=0        
                                        
union all      
                                        
--transfer in                       
select h.tihshopid shopid,  d.tiditemid itemid, h.tihdate sdate, h.tihno, h.tihid,                                         
 convert(numeric(18,3),sum(d.TIDrecievedgoodqty)) as TinQty, 'Transfer In' TYpe, 1 mode,updatetime, tidCostPrice,         
 tidCostPrice * tihdepexrate depCostPrice, tidCostPrice * tihconexrate ConCostPrice ,s.ShopName as 'From/To'                                        
from lostransferinheader h        
 left outer join ashops s on s.ShopID=h.TIHfromshopID,lostransferindetail d         
where h.tihid=d.tidid and h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1                    
group by h.tihshopid, h.tihdate,  h.tihid, h.tihno, d.tiditemid ,updatetime, tidCostPrice ,                                         
 tihdepexrate, tihconexrate,s.ShopName                                        
                                        
union all           
                                        
--recovery add                                        
select sr.srshopid, sr.sritemid, sr.srdate sdate, 'Rec' + convert(varchar(50), sr.srid) srno, sr.srid,                                                             
 convert(numeric(18,3),isnull(sum(sr.sraddstock),0))  as recAdd, 'Recovery Plus' Type,1 Mode,updatetime,         
 srCostPrice,srcostprice * srdepexrate depCostPrice, srcostprice * srconexrate ConCostPrice,'' as 'From/To'          
from losstockrecovery sr                     
group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,srCostPrice, srdepexrate, srconexrate                                         
having isnull(sum(sr.sraddstock),0) >0        
                                        
union all                                        
                                        
--stock verification add                                        
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,        
 convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,'Verification Plus' Type, 1 mode,        
 updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice        
 ,'' as 'From/To'                                          
from  losstockverificationheader, losstockverificationdetail         
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock and svhCancelled=0 and          
 left(svhFutureVc, 1) <> 't'                       
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,svdCostPrice, svhdepexrate, svhconexrate                                        
                                  
union all                                        
                                        
--TOTAL stock verification add                                        
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,        
 convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,'Verification Plus' Type, 1 mode,        
 updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice         
 ,'' as 'From/To'                                         
from  losstockverificationheader, losstockverificationdetail         
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock and svhCancelled=0 and          
 left(svhFutureVc, 2) = 'tc'                      
group by svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,svdCostPrice, svhdepexrate, svhconexrate                                        
                                              
union all                                        
                                        
--exchange in                                        
                                        
select sehShopID, seditemid, sehExchangeDate sdate, sehexchangeno, sehexchangeid,                      
 convert(numeric(18,3),sum(isnull(sedExchangeQty,0)))  as exchangedin, 'Exchanged In' Type,1 mode,updatetime,         
 sedCostPrice,sedCostPrice * sehdepexrate depCostPrice, sedCostPrice * sehExchangerate ConCostPrice,'' as 'From/To'             
from losposexchangeheader, losposexchangedetail         
where sedExchangeid=sehExchangeID and sedShopID=sehShopid and sedBillorExchange='B' and SEHCANCELLED=0                                        
 and isnull(sedExchangeQty,0) >0                                        
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,                                         
 sedCostPrice, sehDepExrate, sehExchangerate                                          
                                        
union all                                        
                                        
--local purchase                                      
select lphShopid, lpditemid, lphbilldate, lphBillNo, lphBillid,                                          
	convert(numeric(18,3),sum(isnull(lpdItemQuantity,0))) localpurchase,'Local Purchase' Type, 1 mode,updatetime,         
	(lpdItemUnitPrice/ lpdItemQuantity),(lpdItemUnitPrice/ lpdItemQuantity) * lphdepexrate depCostPrice,                                         
	(lpdItemUnitPrice/ lpdItemQuantity)* lphExchangerate ConCostPrice ,'' as 'From/To'                                            
from loslocalpurchasedetail, loslocalpurchaseheader         
where lphBillId=lpdBillID and lphShopID= lpdShopid and lphCancelled=0 and lphConfirmed=1--Ref-No2                     
group by lphshopid, lphBillid, lphBillNo,lphbilldate, lpditemid,updatetime, lpdItemUnitPrice, lpdItemQuantity,         
	lphdepexrate,lphExchangerate                       
                                        
union all                                        
                                        
--write off                                        
select wh.whshopid, wd.wditemid, wh.whdate sdate, wh.whno, wh.whid,                                         
 convert(numeric(18,3),sum(wd.wdWriteoffQty)) as writeoffqty, 'Write off' TYpe, -1 mode,updatetime, wdCostPrice,                                         
 wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,'' as 'From/To'                                         
from loswriteoffheader wh, loswriteoffdetail wd                                        
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and  whtype<>'I' --Ref-No1                  
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,                                         
 whDepExrate, whConExrate                                        
                                        
union all  

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



/****** Object:  View [dbo].[vwShopItemSalesWithCustomerAndPack]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwguraranteesales]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[spCurrentShopStock]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwspecialdespatch]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwAccountsInvolved]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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:  StoredProcedure [dbo].[SP_MONTHLYCREDIT]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwShopBincardAuditSummary]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================================================  
-- 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].[vwshopservicesales]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Last Modified on  : 19/10/2004  
--Modified by  : Aneesh
------------------------------------------------------------------------------------------					  		
-- Modified by  : Bijesh.B
-- Date         : 19/08/2011
-- RefNo        : RefNo-5 
-- Ticket Id    : JSZ-828136 (SHEESHA)
-- Description  : Need UserWise selection for Cash Denomination interface
--              : siUserID column included
------------------------------------------------------------------------------------------					  		
   
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(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) End
        * aiexchangerate As sicamount,   
     
    Case Convert(Int, IsNull(aiCashPaidByShop,0)) When 0 Then   
        (Sum(siServiceQty * siAmount)) -IsNull( aiDiscount,0) * aidepexrate
    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)
GO

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

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

/****** Object:  StoredProcedure [dbo].[spBankPosition]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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
GO

/****** Object:  View [dbo].[vwSpecialInvoiceDiffGodown]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwCustomerSalesByitem]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------    
----       
--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:  StoredProcedure [dbo].[spCorrectCostPriceinSplInvoice]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  View [dbo].[vwshopitemsalesWithActualPrice]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------------------    
--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].[vwCustomerSettlementDetails]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-------------------------------------------------------------------------------------------------------------------------
-- 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].[vwShopBincardAudit_new]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--sp_helptext vwshopbincardaudit
   
-- Modified By   : Benzigar 23092008                        
-- Modified Date : 23092008                        
-- Comment       : Added Business Promotion/Warrenty claim              
-- =====================================              
-- Upgraded By : Regin T.              
-- Upgraded On : 22-07-2010              
-- Upgrade     : An outer Group By clause was used to change               
--   the position of TransId and TransNo fields.              
--   This Group By clause casued delay. So I removed it, and               
--   changed the position of fields in all union all parts.              
--   Old position: TransId, TransNo              
--   New position: TransNo, TransId              
-- =====================================              
-- Upgraded By : Regin T.            
-- Upgraded On : 18-09-2010              
-- Upgrade     : Added FandB Bill            
-- =====================================            
-- Upgraded By : NIDHEESH P.V.            
-- Upgraded On : 09-02-2011              
-- Upgrade     : Added In-House Return           
-- =====================================       
--------------------------------------------------------------------------------  
-- Modified by          : MANUNADH.U ON : 11/05/2011  
-- Comments             : Added the column From/To for Bincard Audit report                
--------------------------------------------------------------------------------       
 --------------------------------------------------------------------------------  
-- Modified by          : AADYAKUMAR.D.V ON : 31/05/2011  
-- Comments             : Bug fixed in transfer out
--------------------------------------------------------------------------------       
-- Referenc No  : Ref-No1          
-- Modified by	: MANUNADH.U      
-- Modified on	: 26/03/2012              
-- Comments     : Add the condition to filter local purchase bill with lphConfirmed=1
-- ------------------------------------------------------------------------------

                       
create VIEW [dbo].[vwShopBincardAudit_new] AS     
--arrival from godown     
select h.gahshopid ShopId, d.gaditemid ItemId, h.gaharrivaldate sDate,h.gaharrivalno TransNo,h.gaharrivalid TransId,  
 convert(numeric(18,3),isnull(sum(d.gadItemGoodQuantityArrived),0)) TransQty,'Arrival From Godown' [Type],   
 1 Mode, UpdateTime, gadCostprice CostPrice,gadCostPrice * gahdepexrate DepCostPrice,   
 gadCostPrice * gahconexrate ConCostPrice,  
 --(case when g.GodownName IS null then 'HQ' else g.GodownName end  + '/' + s.ShopName)  as 'From/To'   
 (case when g.GodownName IS null then 'HQ' else g.GodownName end  )  as 'From/To'                
from losgoodsarrivaltoshopheader h  
 left outer join aGodown g on g.GodownID=h.gahDespatchedGodownID  
 left outer join ashops s on s.ShopID=h.gahShopid,losgoodsarrivaltoshopdetail d  
where h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and h.gahtransfinished=1       
 AND gaharrivaldate >='20100101' and gaharrivaldate<='20110131' --and h.gahshopid=5  
group by  h.gahshopid, h.gaharrivaldate, h.gaharrivalid,gaharrivalno, d.gaditemid,updatetime, gadCostprice,   
 gahdepexrate, gahconexrate,g.GodownName,s.ShopName                                        
                                  
----GOODS RETURN TO SHOPS FROM CREDIT INVOICES                                  
union all                                  
                                  
select grn.grnhShopid, grd.GRNDItemID, GrnhGoodsreturnnoteDate sdate,GrnhGoodsreturnnoteNO transno,   
 GrnhGoodsreturnnoteID transid, convert(numeric(18,3),isnull(GRNDQuantity,0)) transqty,'Goods Return',1 as mode,  
 updatetime, grncostprice,grncostprice * grnhdepexrate depCostPrice, grncostprice * grnhExchangeRate ConCostPrice,  
 '' as 'From/To'  
from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd                                  
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid = grd.GRNDShopid and GrnhCancel=0   
 and GRNDDamaged=0  
                                  
union all                                  
                                  
--transfer in                                  
select h.tihshopid shopid,  d.tiditemid itemid, h.tihdate sdate, h.tihno, h.tihid,                                   
 convert(numeric(18,3),sum(d.TIDrecievedgoodqty)) as TinQty, 'Transfer In' TYpe, 1 mode,updatetime, tidCostPrice,   
 tidCostPrice * tihdepexrate depCostPrice, tidCostPrice * tihconexrate ConCostPrice ,s.ShopName as 'From/To'                                  
from lostransferinheader h  
 left outer join ashops s on s.ShopID=h.TIHfromshopID,lostransferindetail d   
where h.tihid=d.tidid and h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1              
group by h.tihshopid, h.tihdate,  h.tihid, h.tihno, d.tiditemid ,updatetime, tidCostPrice ,                                   
 tihdepexrate, tihconexrate,s.ShopName                                  
                                  
union all     
                                  
--recovery add                                  
select sr.srshopid, sr.sritemid, sr.srdate sdate, 'Rec' + convert(varchar(50), sr.srid) srno, sr.srid,                                                       
 convert(numeric(18,3),isnull(sum(sr.sraddstock),0))  as recAdd, 'Recovery Plus' Type,1 Mode,updatetime,   
 srCostPrice,srcostprice * srdepexrate depCostPrice, srcostprice * srconexrate ConCostPrice,'' as 'From/To'    
from losstockrecovery sr               
group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,srCostPrice, srdepexrate, srconexrate                                   
having isnull(sum(sr.sraddstock),0) >0  
                                  
union all                                  
                                  
--stock verification add                                  
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,  
 convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,'Verification Plus' Type, 1 mode,  
 updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice  
 ,'' as 'From/To'                                    
from  losstockverificationheader, losstockverificationdetail   
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock and svhCancelled=0 and    
 left(svhFutureVc, 1) <> 't'                 
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,svdCostPrice, svhdepexrate, svhconexrate                                  
                            
union all                                  
                                  
--TOTAL stock verification add                                  
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,  
 convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,'Verification Plus' Type, 1 mode,  
 updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice   
 ,'' as 'From/To'                                   
from  losstockverificationheader, losstockverificationdetail   
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock and svhCancelled=0 and    
 left(svhFutureVc, 2) = 'tc'                
group by svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,svdCostPrice, svhdepexrate, svhconexrate                                  
                                        
union all                                  
                                  
--exchange in                                  
                                  
select sehShopID, seditemid, sehExchangeDate sdate, sehexchangeno, sehexchangeid,                
 convert(numeric(18,3),sum(isnull(sedExchangeQty,0)))  as exchangedin, 'Exchanged In' Type,1 mode,updatetime,   
 sedCostPrice,sedCostPrice * sehdepexrate depCostPrice, sedCostPrice * sehExchangerate ConCostPrice,'' as 'From/To'       
from losposexchangeheader, losposexchangedetail   
where sedExchangeid=sehExchangeID and sedShopID=sehShopid and sedBillorExchange='B' and SEHCANCELLED=0                                  
 and isnull(sedExchangeQty,0) >0                                  
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,                                   
 sedCostPrice, sehDepExrate, sehExchangerate                                    
                                  
union all                                  
                                  
--local purchase                                
select lphShopid, lpditemid, lphbilldate, lphBillNo, lphBillid,                                    
	convert(numeric(18,3),sum(isnull(lpdItemQuantity,0))) localpurchase,'Local Purchase' Type, 1 mode,updatetime,   
	(lpdItemUnitPrice/ lpdItemQuantity),(lpdItemUnitPrice/ lpdItemQuantity) * lphdepexrate depCostPrice,                                   
	(lpdItemUnitPrice/ lpdItemQuantity)* lphExchangerate ConCostPrice ,'' as 'From/To'                                      
from loslocalpurchasedetail, loslocalpurchaseheader   
where lphBillId=lpdBillID and lphShopID= lpdShopid and lphCancelled=0 and lphConfirmed=1 --<<Ref-No1>>               
group by lphshopid, lphBillid, lphBillNo,lphbilldate, lpditemid,updatetime, lpdItemUnitPrice, lpdItemQuantity,   
	lphdepexrate,lphExchangerate                 
                                  
union all                                  
                                  
--write off                                  
select wh.whshopid, wd.wditemid, wh.whdate sdate, wh.whno, wh.whid,                                   
 convert(numeric(18,3),sum(wd.wdWriteoffQty)) as writeoffqty, 'Write off' TYpe, -1 mode,updatetime, wdCostPrice,                                   
 wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,'' as 'From/To'                                   
from loswriteoffheader wh, loswriteoffdetail wd                                  
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0               
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,                                   
 whDepExrate, whConExrate                                  
                                  
union all                                  
                                  
--Despatch                                  
select dd.dgdshopid, dd.dgditemid, dh.dghDate sdate, dh.dghNo, dh.dghid,                                   
 convert(numeric(18,3),sum(dd.dgddespatchedgoodqty)) as despatchqty,'Despatch To Godown' TYpe, -1 mode,updatetime,  
 dgdCostPrice,dgdCostPrice * dghdepexrate depCostPrice, dgdCostPrice * dghConExrate ConCostPrice  
 ,g.GodownName  as 'From/To'                                                
from mesdespatchtogodownheader dh  
 left outer join aGodown g on g.GodownID=dh.dghGodownID,mesdespatchtogodowndetail dd                                   
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0                     
 and dghtransfinished = 1 -- for the concept of stock updation after transaction finish                                   
group by dd.dgdshopid, dh.dghdate, dh.dghid, dh.dghNo,dd.dgditemid,updatetime,                                   
 dgdCostPrice, dghdepexrate, dghconexrate,g.GodownName                                  
                                 
union all                                  
                                  
--Transferout                                  
select todshopid, toditemid, tohDate sdate, tohno, tohid,                                   
convert(numeric(18,3),sum(todissuedgoodqty)) as ToutQty ,
'Transfer Out' Type,-1 mode,updatetime, todCostPrice,                                   
todCostPrice * tohdepexrate depCostPrice, todCostPrice * tohConExrate ConCostPrice,s.ShopName as 'From/To'
from mestransferoutdetail inner join mestransferoutheader h 
on tohid=todid and Tohshopid=todshopid and tohcancelled=0 and tohtransfinished = 1 inner join 
ashops s on s.ShopID=h.TOHtoShopid --inner join lostransferindetail on TODitemid=TIDitemID 
where TOHShopid=5 and TODitemid=8626 
group by todissuedgoodqty,tohid,todshopid, tohdate, tohid, tohno, todItemid,updatetime, todCostPrice,                                   
tohdepexrate, tohConExrate,s.ShopName  
                              
                                  
union all                                  
                                  
--recovery minus                                  
select sr.srshopid, sr.sritemid, sr.srdate sdate,'Rec' + convert(varchar(50), sr.srid) srno, sr.srid,                                 
 convert(numeric(18,3),sum(isnull(sr.srdedstock,0)))  as recAdd, 'Recovery Minus' type,-1 Mode, updatetime,   
 srCostPrice,srcostprice * srdepexrate depCostPrice, srcostprice * srconexrate ConCostPrice,'' as 'From/To'   
from losstockrecovery sr               
group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,                                   
 srCostPrice, srdepexrate, srconexrate having sum(isnull(sr.srdedstock,0)) >0                                  
                               
union all                                  
                                  
--stockverification minus                                  
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,                                   
 convert(numeric(18,3),sum(svdAvailStock-svdVerifiedStock)) as svMinusQty,'Verification Minus' type, -1 mode,  
 updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice  
 ,'' as 'From/To'                                    
from  losstockverificationheader, losstockverificationdetail   
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock                                  
 and svhCancelled=0 and  left(svhFutureVc, 1) <> 't'               
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,                                   
 svdCostPrice, svhdepexrate , svhconexrate                                     
                            
union all                                  
                                  
--Total stockverification minus                                  
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,                                   
 convert(numeric(18,3),sum(svdAvailStock-svdVerifiedStock)) as svMinusQty,'Verification Minus' type, -1 mode,  
 updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice,  
 '' as 'From/To'                                    
from losstockverificationheader,losstockverificationdetail   
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock                                  
 and svhCancelled=0 and  left(svhFutureVc, 2) = 'tc'               
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,                                   
 svdCostPrice, svhdepexrate , svhconexrate                              
                          
union all                                  
                                  
--pos sales                                  
select poshShopID, posditemid, poshBilldate sdate, poshBillNo, poshbillid,                                   
 convert(numeric(18,3),sum(isnull(posdquantity,0))) cashsales,'Cash Sales' as type, -1 mode,updatetime,   
 posdCostPrice,posdCostPrice * poshdepexrate depCostPrice,posdCostPrice * poshExchangeRate ConCostPrice  
 ,'' as 'From/To'  
from losposdetail,losposheader                                   
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0               
group by poshshopid, poshbillid, poshBillNo, poshbilldate, poshbillid, poshBillNo,                                   
 posditemid,updatetime, posdCostPrice, poshdepexrate, poshExchangeRate                            
                                  
union all                                  
                                  
--credit invoice                                  
select IhShopid, iditemid, ihInvoicedate sdate, ihInvoiceNo, ihInvoiceid,                                    
 convert(numeric(18,3),sum(isnull(idquantity,0))) as creditsales, 'Credit Sales' Type,                                   
 -1 mode,updatetime, idCostPrice, idCostPrice * ihdepexrate depCostPrice,                                   
 idCostPrice * ihExchangeRate ConCostPrice,'' as 'From/To'    
from losinvoicedetail,losinvoiceheader                                  
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0 and ihType ='I'               
group by ihshopid, ihinvoicedate, ihInvoiceid, ihInvoiceNo, iditemid,                    
 updatetime, idCostPrice, ihdepexrate, ihExchangeRate                                  
                               
union all                                  
                                  
--exchange out                                  
select sehShopID, seditemid, sehExchangeDate sdate, sehexchangeno, sehexchangeid,                                    
 convert(numeric(18,3),sum(isnull(sedquantity,0)))  as exchangedout ,                                   
 'Exchange Out' Type, -1 mode,updatetime, sedCostPRice,                                  
 sedCostPrice * sehdepexrate depCostPrice, sedCostPrice * sehExchangerate ConCostPrice,'' as 'From/To'                                       
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID                                   
 and sedShopID=sehShopid and sedBillorExchange='E' and SEHCANCELLED=0              
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,                                   
 sedCostPRice, sehdepexrate, sehExchangerate                                   
                                  
union all                                  
                                  
--special invoice return to shop                                  
select IhShopid, iditemid, ihInvoicedate sdate, ihInvoiceNo, ihInvoiceid,                                    
 convert(numeric(18,3),-sum(isnull(reqqty,0)))   as SpecialReturn, 'Special Invoice Return' Type,                                   
 1 mode,updatetime, idCostPrice,                                   
 idCostPrice * ihdepexrate depCostPrice, idCostPrice * ihExchangerate ConCostPrice,'' as 'From/To'   
from losspecialinvoicedetail, losspecialinvoiceheader                                  
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1                                  
 and ihproforma=0 and ihTransFinished = 1               
group by ihshopid, ihinvoicedate, ihInvoiceid,                                   
 ihInvoiceNo, iditemid, updatetime, idCostPrice, ihdepexrate, ihExchangerate                       
 -- transfinished added as stock is updated only after confirming                                  
                                  
union all                                  
                                  
 --COMMENTED AS MODIFICATIONS ON SERVICE IS GOING ON. TO BE REMOVED ONCE IT IS COMPLETED                                  
select serinvhShopid, repinvdpartsid, serinvhdate , serinvNo, serinvhid,                                    
 convert(numeric(18,3) , sum(repinvdqty)) , 'Parts Replaced' type,-1 as mode, serinvhupdatetime, repinvdcostprice,                                   
 repinvdCostPrice * seinvhdepexrate depCostPrice, repinvdCostPrice * serinvhcmpexrate ConCostPrice,'' as 'From/To'  
from losinvoicedpartsreplacedetails, losserviceinvheader where serinvhid = repinvinvoiceid                                    
 and serinvhshopid = repinvdshopid AND serinvhcancelled=0                                   
group by serinvhShopid,  serinvhdate , serinvhid , serinvNo ,  repinvdpartsid,                                   
 serinvhupdatetime, repinvdcostprice, seinvhdepexrate, serinvhcmpexrate                                  
                                  
union all                                  
                                   
--Re-Exporting                                  
select rehShopID, reditemid, rehExportDate sdate, rehExportNo, rehExportID,                                  
 convert(numeric(18,3),sum(isnull(redquantity,0)))  as creditsales, 'Re-Export' Type,                                   
 -1 mode, rehUpdatetime, redCostPrice,                                   
 redCostPrice * rehdepexrate depCostPrice, redCostPrice * rehExchangerate ConCostPrice,'' as 'From/To'  
from losexportdetail, losexportheader                                  
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0 and rehType='I'               
group by rehShopID, rehExportDate, rehExportID, rehExportNo, redItemID,                                   
 rehUpdatetime, redCostPrice, rehdepexrate, rehExchangerate                                  
                           
union all                            
                          
--MerGing minus                            
select lsdShopID, lsdItemID, lshDate, lshno, lshid,convert(numeric(18,3), sum(lsdqty)) as mergeded,                             
 'Merging Deduct' as type, -1 as mode, lshUpdatetime,null,null,null,'' as 'From/To'                            
from losMergeDetails md, losMergeHeader mh                             
where md.lsdid = mh.lshid and md.lsdShopid = mh.lshShopId and lshCancelled=0                
group by lsdShopID, lsdItemID, lshDate, lshid, lshno, lshUpdatetime                            
Having Sum(lsdQty) <> 0                             
                            
union all                            
                          
--MerGing Add                            
select lsdShopID, lshItemID, lshDate, lshno, lshid,convert(numeric(18,3),sum(lsdqty)) as splitminus,                             
 'Merging Add' as type, 1 as mode, lshUpdatetime,null,null,null,'' as 'From/To'                            
from losMergeDetails md, losMergeHeader mh                             
where md.lsdid = mh.lshid and md.lsdShopID = mh.lshShopid and lshCancelled = 0                 
group by lsdShopID, lshItemID, lshDate, lshid, lshno, lshUpdatetime                            
Having Sum(lsdQty) <> 0                   
                   
union all                            
                            
--Purchase Return                            
select Ph.whshopid, Pd.wditemid, Ph.whdate sdate, Ph.whno, Ph.whid,                             
 convert(numeric(18,3),sum(Pd.wdPurchaseReturnQty)) as PurchaseReturnqty, 'Purchase Return' TYpe, -1 mode,                             
 updatetime, wdCostPrice,                             
 wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,'' as 'From/To'                             
from losPurchaseReturnheader Ph, losPurchaseReturndetail Pd                            
where Ph.whid=Pd.wdid and Ph.whshopid=Pd.wdshopid and Ph.whcancelled=0 and Ph.whtransfinished=1               
group by Ph.whshopid, Ph.whDate, Ph.whid, Ph.whno, Pd.wditemid,updatetime, wdCostPrice,                             
 whDepExrate, whConExrate                         
                        
union all                                  
                                 
--Warrenty Claim/Business promotion                                     
select wchShopID, wcditemid, wchdate sdate, wchNo, wchid,convert(numeric(18,3),sum(isnull(wcdQty,0))) BPWP,                                   
 'WC/BP' as type, -1 mode,wchupdatedtime, wcdCostPrice,wcdCostPrice * wchdepexrate depCostPrice,                                   
 wcdCostPrice * wchcomexrate ConCostPrice,'' as 'From/To'    
from losWarrentyClaimDetail,losWarrentyClaimHeader                                   
where wchID=wcdID and wchShopid=wcdshopid AND WCHCANCELLED=0               
group by wchShopid, wchid, wchNo, wchdate, wchid, wchNo,                                   
 wcditemid,wchupdatedtime, wcdCostPrice, wchdepexrate, wchcomexrate                                 
                                 
union all                                
                                
-----Hire Purchase Invoice                               
select hpqhShopid,hpqdItemId,hpqhQuotationDate sDate,hpqhQuotationNo,hpqhQuotationID,1 as Qty, 'Hire Purchase' Type,                           
 -1 mode,hpqhUpdatetime,hpqdCostPrice,hpqdCostPrice*1 depCostPrice,hpqdCostPrice*1 ComCostPrice,'' as 'From/To'  
from loshpInvoiceDetail,losHpInvoiceHeader where hpqdQuotationid=hpqhQuotationID and hpqdShopid=hpqhShopid and                                
 hpqhCancel=0 and hpqhType='I'               
group by hpqhShopid,hpqhQuotationDate,hpqhQuotationID,hpqhQuotationNo,hpqdItemId,hpqhUpdatetime,hpqdCostPrice              
              
union all                               
            
-- Food and Beverages Bill - added by Regin on 18-09-2010            
SELECT Fb_kh_outletid, a.fb_ItemID, DATEADD(D, 0, DATEDIFF(D, 0, Fb_kh_kotdatetime)) sdate,Fb_kh_kotno, Fb_kh_kotid,   
 a.KotOrder,'FandB Bill' Type, -1 mode, Fb_kh_kotdatetime,fb_costprice, fb_costprice*h.fb_depexrate depCostPrice,   
 fb_costprice*h.fb_ExchangeRate conCostPrice,'' as 'From/To'            
from fb_kotheader h            
 inner join fb_alternate a on Fb_kh_kotid=fb_kotID            
where Fb_kh_cancelled=0         
        
union all        
        
--InHouse Return                                 
SELECT IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,        
 convert(numeric(18,3),sum(IHRDReturnedqty)) as IHRDReturnedqty,'In-House Return' Type,1 mode,updatetime,        
 IHRDcostprice,(IHRHdepexrate*IHRDcostprice) DepCostPrice,(IHRHconexrate*IHRDcostprice)ConCostPrice  
 ,'' as 'From/To'        
FROM LOs_InHouseCons_ReturnHeader rh          
INNER JOIN  LOs_InHouseCons_ReturnDetail rd         
on IHRHShopID=IHRDShopID and IHRHID=IHRDID AND IHRHCancelled=0 AND IHRHConfirmed=1         
AND (IHRDRetrnOrExch='R' OR IHRDRetrnOrExch='B' OR IHRDRetrnOrExch IS NULL) AND IHRDReturnedqty<>0        
group by IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,updatetime,                                
IHRDcostprice,IHRHdepexrate,IHRHconexrate          
        
UNION ALL        
        
--InHouse Exchanged In                      
SELECT IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,        
 convert(numeric(18,3),sum(IHRDArrivedQty)) as IHRDExchgdqty,'In-House Exchnaged In' Type,-1 mode,updatetime,        
 IHRDcostprice,(IHRHdepexrate*IHRDcostprice) DepCostPrice,(IHRHconexrate*IHRDcostprice)ConCostPrice,'' as 'From/To'        
FROM LOs_InHouseCons_ReturnHeader rh          
 INNER JOIN  LOs_InHouseCons_ReturnDetail rd on IHRHShopID=IHRDShopID and IHRHID=IHRDID AND IHRHCancelled=0 AND   
 IHRHConfirmed=1 AND IHRDRetrnOrExch='E' AND IHRDArrivedQty<>0        
group by IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,updatetime,IHRDcostprice,IHRHdepexrate,IHRHconexrate
GO
/****** Object:  View [dbo].[vwSpecialInvoiceItemStatus]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
---------------------------------------------                      
/*                      
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].[vwUnConfirmedTransactions]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Created by : Hariharan     
-- Created on : 19/01/2004 (at Male' From V2)    
-- Comments   : For alert display of unconfirmed transactions    
-- =================================================================       
-- Ref.No:1
-- Upgraded By : AADYAKUMAR D V      
-- Upgraded On : 13-03-2012        
-- Upgrade     : Added more transactions     
-- ==================================================================       
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  
    
Create VIEW [dbo].[vwUnConfirmedTransactions] AS    
    
SELECT 'Despatch Note Generation' TransactionType, dnmDespatchNoteId TransactionId,    
dnmDespatchNoteNo TransactionNo, dnmDespatchNoteDate TransactionDate,     
0 LocationId, 'HQ' LocationName, Departmentid, 'H' LocType    
FROM aHqDespatchNoteMain Main LEFT OUTER JOIN aHqDespatchNoteHeader Header    
ON Main.dnmDespatchNoteId = Header.dhDespatchNoteMainID    
WHERE dnmCancelled = 0 AND dhTransFinished = 0 group by     
dnmDespatchNoteId, dnmDespatchNoteNo, dnmDespatchNoteDate, Departmentid    
    
    
UNION ALL    
    
SELECT 'Issue Note Generation' TransactionType, inmIssueNoteId TransactionId,    
inmIssueNoteNo TransactionNo, inmIssueDate TransactionDate,     
0 LocationId, 'HQ' LocationName, Departmentid, 'H' LocType    
FROM aHqIssueNoteMain Main LEFT OUTER JOIN aHqIssueNoteHeader Header    
ON Main.inmIssueNoteId = Header.inhIssueNoteMainId    
    
WHERE inmCancel = 0    
AND inhTransFinished = 0 group by inmIssueNoteId ,    
inmIssueNoteNo, inmIssueDate, Departmentid    
    
UNION ALL    
    
    
SELECT 'Costing', chCostingId, chCostingNo, chCostingDate, 0, 'HQ', chDepartmentId, 'H' LocType    
FROM loaCostingHeader WHERE chCancelled = 0 AND chCostingDone = 0    
and chCostingId >0    
    
UNION ALL    
    
SELECT 'Local Purchase Costing', lpchCostingId, lpchCostingNo, lpchDate, 0, 'HQ',     
lpchDepartmentid, 'H' LocType FROM loaLocalPurchaseCostingHeader    
WHERE lpchCancelled = 0    
AND lpchCostingDone = 0    
    
UNION ALL    
    
SELECT 'Item Split Costing', scfhId, scfhNo, scfhDate, 0, 'HQ', scfhdepartmentid, 'H' LocType    
FROM loaItemSplitCostingHeader    
WHERE scfhCancelled = 0    
AND scfhCostFixed = 0    
    
UNION ALL    
    
SELECT 'Goods Arrival To Godown', ahArrivalId, ahArrivalNo, ahArrivalDate,     
ahLocalGodownId, aGodown.GodownName, ahDepartmentid, 'G' LocType    
FROM loiArrivalHeader LEFT OUTER JOIN aGodown    
ON ahLocalGodownId = GodownId    
WHERE ahCancelled = 0    
AND ahTransFinished = 0    
    
UNION ALL    
    
    
SELECT 'Despatch To Shop', dhDespatchId, dhDespatchNo, dhDespatchDate,     
dhGodownId, GodownName, dhDepartmentId, 'g' LocType    
FROM meiDespatchToShopHeader LEFT OUTER JOIN aGodown    
ON dhGodownId = GodownId    
WHERE dhCancelled = 0    
AND dhTransFinished = 0    
    
UNION ALL    
    
SELECT 'Godown To Godown Transfer', gthDespatchId, gthDespatchNo, gthDespatchDate,     
gthFromGodownId, GodownName, gthDepartmentId, 'H' LocType    
FROM meiGOdownTransferHeader LEFT OUTER JOIN aGodown    
ON gthFromGodownId = GodownId    
WHERE gthCancelled = 0 AND gthTransFinished = 0    
    
UNION ALL    
    
SELECT 'Goods Arrival To Shop', gahArrivalId, gahArrivalNo, gahArrivalDate,     
gahShopId, ShopName, gahDepartmentId, 'S' LocType    
FROM LOsGoodsArrivaltoShopHeader LEFT OUTER JOIN aShops    
ON gahShopId = ShopId    
WHERE gahCancelled = 0    
AND gahTransFinished = 0    
    
UNION ALL    
    
--SELECT 'Request To Shop', srhRequestId, srhRequestNo, srhRequestDate,     
--srhShopId, ShopName, Departmentid , 'S' LocType    
--FROM mesRequestToShopHeader LEFT OUTER JOIN aShops    
--ON srhShopId = aShops.ShopId    
--WHERE srhCancelled = 0    
--AND srhTransFinished = 0    
    
--UNION ALL    
    
SELECT 'Request To HQ', grhRequestId, grhRequestNo, grhRequestDate,     
grhShopId, ShopName, departmentid, 'S' LocType    
FROM mosGoodsRequestHeader LEFT OUTER JOIN aShops    
ON grhShopId = aShops.ShopId    
WHERE grhCancel = 0    
AND grhTransFinished = 0    
    
--UNION ALL    
    
--SELECT 'Transfer Out', tohId, tohNo, tohDate, tohShopId,    
--ShopName, tohDepartmentid, 'S' LocType    
--FROM mesTransferOutHeader LEFT OUTER JOIN aShops    
--ON tohShopId = aShops.ShopId    
--WHERE tohCancelled = 0    
--AND tohTransFinished = 0    
    
UNION ALL    
    
SELECT 'Transfer In', tihId, tihNo, tihDate, tihShopId,    
ShopName, tihDepartmentid, 'S' LocType    
FROM losTransferInHeader LEFT OUTER JOIN aShops    
ON tihShopId = aShops.ShopId    
WHERE tihCancel = 0    
AND tihTransFinished = 0    
    
UNION ALL    
    
SELECT 'Shop To Godown Transfer', dghID, dghNo, dghDate, dghShopId,    
ShopName, dghDepartmentid, 'S' LocType    
FROM mesDespatchtoGodownHeader LEFT OUTER JOIN aShops    
ON dghShopid = aShops.ShopId    
WHERE dghCancelled = 0 AND dghTransFinished = 0    
    
UNION ALL    
    
SELECT 'Special Invoice', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopId,    
ShopName, ihDepartmentid, 'S' LocType FROM losSpecialInvoiceHeader LEFT OUTER JOIN aShops    
ON ihShopId = aShops.ShopId WHERE ihCancelled = 0 AND ihTransFinished = 0 

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

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

UNION ALL    

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

UNION ALL    

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

UNION ALL    

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

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

UNION ALL    

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

UNION ALL    

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

UNION ALL    

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

--UNION ALL

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

UNION ALL

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

UNION ALL

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

UNION ALL

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

UNION ALL

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

UNION ALL

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

UNION ALL

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

UNION ALL

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

UNION ALL

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

UNION ALL

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

UNION ALL

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

UNION ALL

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

--Ref.No:1-------------------------------END-----------------------------------------------
GO
/****** Object:  View [dbo].[vwSalesHistory]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------    
-- 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].[vwspecialinvoiceamount]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[newss]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwBillsCheckList]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwBills]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Modified on  : 05/09/2003              
-- Modified by  : Kishore              
-- Comments     : Changed BillAmount to BillAmount + LcAmount in purchase bill           
-- Modified on  : 05/12/2009              
-- Modified by  : jyothish          
 --  change localpurchase bill  amount          
--------------------------------------------------------------------------------              
-- Upgraded by : Regin T.      
-- Upgraded on : 13-08-2010      
--   Local Purchase Bill Amount was corrected.      
--   Since bill discount is already distributed to all items,       
--   discount should not be deducted again.      
--   Old formula: Bill Amount = sum(lpdItemUnitPrice)-(lphdiscount)      
--   New formula: Bill Amount = sum(lpdItemUnitPrice)      
-- Reference: RefNo-1      
--------------------------------------------------------------------------------      
--Altered By Sreejith    
--Altered on 20100827    
--Added the condition ''and  ph.lphConfirmed=1'' to the view to load only confirmed Local Purchase Bills    
---------------------------------------------------------------------------------  
--Modified By : VinothMurugan V.  
--Date    : 14/10/2010  
--Purpose   : Adding interdivision bills  
---------------------------------------------------------------------------------  
--Modified By : Bijesh.b  
--Date    : 04/06/2011  
--Ticket ID   : NML-689759 (Sonee)  
--RefNo.      : RefNo-2   
--Purpose   : For Shop Local Purchase Order, in vendor statement report(accounts)  
--              No need to include discount in Balance amount (in sub report)  
---------------------------------------------------------------------------------  
 --Altered By jyothish  
--Altered on 20111018 
--Reference: RefNo-3
---sum(lpdItemUnitPrice+ISNULL(lpdItemTaxAmount,0))  billamount added 
-----(lphdiscount) is commented 

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.lphVendorBillNo, 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.lphVendorBillNo,                
ph.lphbilldate, lphDueDateforPayment, ph.updatetime,lphdiscount                
                
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,  -- 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.lphVendorBillNo,                
ph.lphbilldate, lphDueDateforPayment, ph.updatetime ,lphdiscount               
                
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,   -- 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.lphVendorBillNo,                
ph.lphbilldate, lphDueDateforPayment, ph.updatetime,lphdiscount                
                
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,  -- 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.lphVendorBillNo,                
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].[vwbillswithcontrolaccs]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwHQAccBills]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwBillsWithControlAccounts]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[spRemineVendordueDate]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------        
--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
GO
/****** Object:  View [dbo].[vwInhousePurchasesBilled]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------  
-- 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:  StoredProcedure [dbo].[spSetZeroLocationStockForNonVerifiedItemsInShop]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  View [dbo].[vwShopBincardBadQtySummary]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ===============================================      
-- 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].[vwShopTotalStockVerification]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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:  StoredProcedure [dbo].[spReverseShopTotalStockVerification]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------

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

--------------------------------------------------------------
GO
/****** Object:  View [dbo].[vwShopStockVerification]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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:  StoredProcedure [dbo].[spUpdateShopVerification]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  View [dbo].[vwshopbincardbadqty]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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].[vwInquiryShopStock]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  View [dbo].[vwGdnBinCard]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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].[vwstock]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create view [dbo].[vwstock] as
(select  top 5 itemid,stock from vwInquiryShopStock)
union (select
top 5 gsitemid,gsstock from vwInquirygodownStock)
GO

/****** Object:  View [dbo].[vwstockcolor]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create view [dbo].[vwstockcolor] as
(select itemid,sum(stock) as stocks from vwInquiryShopStock 
group by itemid)
    union
(select gsitemid,gsstock from vwInquirygodownStock)
GO


/****** Object:  StoredProcedure [dbo].[spSetZeroExpiryStockForNonVerifiedItemsInShop]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  View [dbo].[vwExpiryItemDetails]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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:  View [dbo].[vwShopExpirywiseStock]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------
-- 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].[vwshopexpirystock]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwCompanyExpiryAlertItems]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------
-- 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:  StoredProcedure [dbo].[spShopExpiryTotalStockVerification]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateBPWCStock]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwwarrentyclaim]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  StoredProcedure [dbo].[spULBusinessPromotion]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec spULBusinessPromotion 1,2    
--Created on   : 10/09/2008            
--Created by  : Prasanth Joseph            
--Comments  : For Posting Business Promotions Transactions   
--RefNo1: Added by MANUNADH.U on 03.06.2011 for the Ticket: ZES-242125   
--to post only confirmed BusinessPromotion           
---------------------------------------------------------------------            
--RefNO       : RefNo-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
GO
/****** Object:  StoredProcedure [dbo].[spULWarrentyClaim]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwdcnwithcontrolaccdep]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[sp_audittool_trans_details]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
GO
/****** Object:  StoredProcedure [dbo].[sp_audittool_ledger]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
GO
/****** Object:  View [dbo].[vwadvancepaidDebits]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwCustomerSettlementHeader]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------------------------------------------------  
-- 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].[vwDebitNote]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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].[vwreceiptswithcontrolaccs]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwpaymentswithcontrolaccs]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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].[vwadvancepaidCredits]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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].[vwhqdrcrinvandrecamount]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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].[vwVendorSettlementHeader]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------------------------------------------------  
-- 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].[vwcreditnote]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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].[vwVendorSettlementDetails]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-------------------------------------------------------------------------------------------------------------------------
-- 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].[vwinhousepurchase]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwInhousePurchasesAgainstVendors]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------  
-- 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].[vwHPFeePaymentFrameWise]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwHPFeePaymentVoucherdetails]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
 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:  StoredProcedure [dbo].[spUpdatePOSHeaderAsOn07062011]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Created By  : Aneesh              
--Created On  : 14-09-2006              
--Purpose     : To update details to the POS Header Table [losPosheader]            
--Modified BY : Shinu        
--Modifies On : 15-03-2007,20-11-2007       
--Purpose : To insert Discount amount In LOSPOSHEADER       
--    : To Insert Delivery note Bit       
--Last Modified By:MANUNADH.U 18-03-2011    
-----------------------------------------------------------------------------------------------------------------------------              
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    
----------------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_CheckLoginShop]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================        
-- 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
GO
/****** Object:  View [dbo].[vwunpostedposbills]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwAllUsers]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  StoredProcedure [dbo].[spUpdatePOSHeader]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Created By  : Aneesh              
--Created On  : 14-09-2006              
--Purpose     : To update details to the POS Header Table [losPosheader]            
--Modified BY : Shinu        
--Modifies On : 15-03-2007,20-11-2007       
--Purpose : To insert Discount amount In LOSPOSHEADER       
--    : To Insert Delivery note Bit       
--Last Modified By:MANUNADH.U 18-03-2011    
---------------------------------------------------------------------------------------------
--Upgrade By : Bijesh. B
--Date		 : 07/06/2011
--Purpose	 : adding chequeid column and post date cheque Column(Upgrading PD Cheque
--	           feature from Sonee)
---------------------------------------------------------------------------------------------
--Upgrade By : Bijesh. B
--Date		 : 27/12/2011
--Purpose    : Need Tin for Cash customer
--Desc       : @CustomerTIN column added
--Ticket id  : BLE-583962 (Sonee)  
---------------------------------------------------------------------------------------------

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,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,  
 @intChequeId As Int,      
 @PostdateChk as bit,
 @CustomerTIN as varchar(50)=''                 
As                  
Begin                    
 Declare @intDepId As Int                
 Declare @intFinId As Int                  
 Declare @intBillNo as Int                
 Declare @strUser As Varchar(20)                  
 Declare @intSalesAccId As Int                  
 Declare @intWholeSale As Int                
 Declare @strBillNo as Varchar(20)                  
 Declare @strCardNo as Varchar(20)                   
              
 --Finding the username with the @intUserId passed                
 --Select @strUser = UserName From aUsers Where UserId=@intUserId                  
 Select @strUser = UserName From lousers Where UserId=@intUserId  -- Modified By MANUNADH  
            
 --Finding the Sales Acc Id,Wholesale bit,Department Id with the @intShopId passed                
 Select @intSalesAccId = ShopSalesaccountID,@intWholeSale = TruncateCheck,@intDepId = DepartmentId     
 From aShops Where ShopId=@intShopId                  
                
 --Getting the Customer Card Id - Uncomment the following code if you need to save it.                
 --If @intCustId>0 Select @strCardNo=CustomerCardNo From aCustomerMaster Where customerid=@intCustId                
                
 --Setting the customer id to null if no customer is selected                 
 If @intCustId=0 Set @intCustId=NULL                 
                
 --Setting the sales person id to null if no sales person is selected                 
 If @intSalesPerId=0 Set @intSalesPerId=NULL                 
            
 Update losPosHeader     
 Set poshCustomerName=@strCustName,poshCancelledRemarks=@strRemarks,poshRecModifyUser=@strUser,    
  poshDiscount=@intDiscount,poshBillAmount=@intBillAmt,poshCashAccID=@intCashAccId,poshSalesAccID=@intSalesAccId,    
  poshExchangeRate=@intCmpExRate,updatetime=GetDate(),poshsalespersonid=@intSalesPerId,    
  poshcustomerid=@intCustId,poshdepexrate=@intDepExRate,poshexchangerates=@strExRate,    
  --poshUserId=@intUserId,              
  poshModifyUserId=@intUserId,              
  poshCounterId=@intCounterId ,poshDiscountAmt=@intDiscountAmt ,poshDeliveryNeeded=@intDeliveryNeeded,     
  poshChequeAccID = @intChequeId, PosPostDate = @PostdateChk ,poshCustomerTIN= @CustomerTIN  
 Where poshBillId=@intBillId And poshShopId=@intShopId                
End
GO
/****** Object:  View [dbo].[vwDailyCounterSales]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwLocalUserRightsRptDtls]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[SpUpdateLOUserRights]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwpaymentsusedincosting]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------  
--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].[vwCostingDifference]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwBillOtherCharges]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
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].[vwCosting]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwItemsinTransaction]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwitemsplitDetail]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spCorrectCostPriceinDespatch]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  View [dbo].[vwshipmentexpense]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spGITDifference_GL]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
/*
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
GO
/****** Object:  View [dbo].[vwpaymentsusedincoasting]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------      
--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].[vwSelingPriceAfterEachShipment]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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:  StoredProcedure [dbo].[spCorrectCostPriceinCreditInvoice]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  View [dbo].[vwForeignShipWiseCostPrice]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[spGITDifference]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spLeadTimeForPurchase]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
------------------------------------------------------------------------------

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


-----------------------------------------------------
GO
/****** Object:  View [dbo].[vwShipmentRelatedExpenses]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwshipmentcostprice]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwCostSheet]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================                    
-- 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].[vwItemShipmentPrice]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spUpdateLEDgersHPInterest]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spULHPResale]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spULHPShopDownPayment]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersHPReprocessing]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------         
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersHPReceipts]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spULHPShopReceipt]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spULHPRepossession]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersHPPayments]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwdatewisearrivalHQ]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwGodownTranferFlow]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwGdnBinCardSummary]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ===============================================        
-- 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:  View [dbo].[vwArrivalToGodownFromShop]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwTransferIn]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwItemSplit]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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].[vwarrivaldistributedetails]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwImportShortageExcess]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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].[vwGdnBinCardForGdnReport]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwimportqty]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwShopLocationWiseStock]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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:  StoredProcedure [dbo].[spUpdateShopLocationItemMerge]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
---------------------------------------------------------------

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

-----------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[spShopLocationTotalStockVerification]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  View [dbo].[vwGdnBinCardBadQtySummary]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ===============================================      
-- 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].[vwGodownDamageClearing]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwhpItemTransfer]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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:  StoredProcedure [dbo].[spMagnolia_PopulateInHosueRetunDetls]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[sptrial]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[sptrial1]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_GetInHosueRetunDetls]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_Insert_InHouseCons_ReturnHeader1]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwPosExchangeDetails]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwPosExchangeDetailsWithMarginWithOutGST]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--RefNo        : Newly created view (copy of vwPosExchangeDetailsWithMargin)
--Modified by  : Bijesh.B
--Date         : 13/03/2012
--Ticket id    : JDJ-400367 (Sonee)
--comments     : Need to show GST separately
----------------------------------------------------------------------------------------------   

create View [dbo].[vwPosExchangeDetailsWithMarginWithOutGST]   as
select           
   sehExchangeID,shopname, sehshopid, sehexchangedate, 
   convert(numeric(18,2),sum(sedunitprice-isnull(sedItemTaxAmount,0))) cashsales,
   convert(numeric(18,2),sum(sedunitprice-isnull(sedItemTaxAmount,0) * sehdepexrate)) dcashsales,
   convert(numeric(18,2),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,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
   ,convert(numeric(18,2),sum(isnull(sedItemTaxAmount,0)))GSTAmount
     ,convert(numeric(18,2),sum(isnull(sedItemTaxAmount,0)* sehdepexrate))dGSTAmount,
    convert(numeric(18,2),sum(isnull(sedItemTaxAmount,0)* sehexchangerate))cGSTAmount
            
  from           
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d           
  where           
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and           
   sedbillorexchange = 'E' and sehshopid = shopid and sehdepartmentid = d.departmentid           
  group by           
   shopname, sehshopid, departmentname, sehdepartmentid, sehexchangedate ,          
   departmentname,sehdepexrate, sehexchangerate,sehExchangeID  

 union all          
          
   select           
   sedExchangeID,shopname, sehshopid, sehexchangedate,
   convert(numeric(18,2),-sum(sedunitprice-isnull(sedItemTaxAmount,0))) cashsales,
   convert(numeric(18,2),-sum(sedunitprice-isnull(sedItemTaxAmount,0) * sehdepexrate)) dcashsales,
   convert(numeric(18,2),-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,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
   ,convert(numeric(18,2),-sum(isnull(sedItemTaxAmount,0)))GSTAmount    
   ,convert(numeric(18,2),-sum(isnull(sedItemTaxAmount,0)* sehdepexrate))dGSTAmount,
    convert(numeric(18,2),-sum(isnull(sedItemTaxAmount,0)* sehexchangerate))cGSTAmount
         
  from           
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d           
  where           
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and           
   sedbillorexchange ='B' and sedexchangeqty>0 and sehshopid = shopid           
   and sehdepartmentid = d.departmentid           
  group by           
   shopname, sehshopid, sehdepartmentid, departmentname,sehexchangedate, sehexchangerate,          
   sehdepexrate,sedExchangeid
GO
/****** Object:  View [dbo].[vwshopSalesAccountWise]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Created By : Benzigar S D
-- Created On : 29-11-2008

CREATE VIEW [dbo].[vwshopSalesAccountWise] 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].[vwsalesdetail]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwserialnoAudit]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwPosExchangeDetailsWithMargin]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  StoredProcedure [dbo].[spLCRegisterAllDetails]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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      
-----------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[spRebateRequest]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-----------------------------------------------------------------
--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
GO
/****** Object:  View [dbo].[vwrebatePO]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spRebateApproval]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-----------------------------------------------------------------
--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
GO
/****** Object:  View [dbo].[vwrebateapproval]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 
--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].[vwfixedassetsconvertedfromstock]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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].[vwHqPurchaseReturn]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwPurchaseOrderStatus]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwCreditPurchaseOrder]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwPendingDeliveries]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------              
-- 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].[vwKegItemsHistory]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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:  View [dbo].[vwcreditpurchaserequest]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwConfirmedDeliveryNote]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------------------                               
-- 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:  StoredProcedure [dbo].[spMag_FetchCreditSaleDeliveryDetails]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================================================  
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spSalesConfirmation]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------  
--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
GO
/****** Object:  StoredProcedure [dbo].[spMag_getInvoiceByNumber]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- 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
GO
/****** Object:  View [dbo].[vwLoyaltyPointsDetails]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwdeliverynotenew]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------  
-----------------------------------------------------------------------------------------------------------------    
--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].[vwshopCreditInvoice]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwInvoiceQuotation]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwinvoiceout]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spShopReqFlowWithPrj]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------  
--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
GO
/****** Object:  StoredProcedure [dbo].[spULSaleInv]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--spULSaleInv 1,1                
--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)             
------------------------------------------------------------------------------                   
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,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                
                
--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 @IntServTaxAccnt as integer          
declare @IntServTaxAccntCurrID as integer    
declare @numOCTaxAmount as numeric(18,2)          
-----------------------------              
declare  @Taxtable table              
(              
taxTransId int,     
taxShopId int,                    
taxAccntId int,              
taxAmount numeric(18,2),              
CtaxAmount numeric(18,2),              
DtaxAmount numeric(18,2)              
)              
--RefNo-2-added for gst--              
              
SET NOCOUNT ON              
              
--RefNo-2---to insert tax cateid,tax A/C & tax amount in the table variable---              
 insert into @Taxtable               
 select ihInvoiceId,ihShopID,TaxAccountId,isnull(sum(idItemTaxAmount),0)as TaxAmount,              
 sum(isnull(idItemTaxAmount,0)* ihexchangerate) as ComTaxAmount,              
 sum(isnull(idItemTaxAmount,0)* ihdepExRate) as DepTaxAmount              
 FROM losinvoiceheader ih inner join losinvoicedetail id               
 on ih.ihInvoiceId = id.idInvoiceId and ih.ihShopID = id.idShopID             
 inner join ataxcategorymaster tc on TaxCompanyId=ih.ihCompanyId and idItemTaxCategory=TaxId              
 and TaxCancelled=0 and TaxAccountable=1                
 WHERE ihcancelled =0 and ihposted =0 and ihproforma = 0 AND ihcashinvoice =0 and ihtype ='i'                 
 and isnull(idItemTaxCategory,0)<>0            
 and isnull(TaxPercentage,0)<>0                 
 and ih.ihCompanyId = @intCompanyID                     
 and ih.ihShopID = @intshopid                      
 group by  TaxAccountId,ihInvoiceId,ihShopID                
---RefNo-2----              
              
 /* getting the defaults into the variables */                
 /* getting the maximum Journal ID FROM journal table */                
 SELECT                 
  @intJournalId = isnull(max(JournalId),0)                 
 FROM                 
  moaJournalHeader                 
 WHERE                 
  CompanyID = @intCompanyID                
                 
 set @numTotalinvValue  = 0.0                
 set @numTotalCostValue = 0.0                
 set @numTotalDiscountValue = 0.0                
 set @numTotalOCValue = 0.0                
 set @numCustomsDutyAmt = 0.0 --R Harikrishnan for Customs Duty Posting                
                 
 select                 
  @intcomcurid = CurrencyId                 
 from                 
  acompanymaster                 
 where                 
  companyid = @intcompanyid                
                
 --R Harikrishnan for Customs Duty Posting                
 select                 
  @intDiscountAccountID = discountaccountid,                 
  @intOtherChargesAccountID = shopOtherChargesAccID,                
  @numProfitTrans = isnull(RevisedCostPricePercent,0) ,                
  @chrShopType = upper(left(futureVarchar,1))                
 from                 
  ashops                 
 where                 
  ShopId = @intShopId                
                
 select                 
  @intCostOfGoodsAccId =CostofGoodsid, @intInventoryaccid =inventoryid,                 
  @intPlTransAccId =profittransfercontrolacc, @intcomdeptid  =companydepartment,                 
  @intcomprofitaccid =compprofitshareacc                 
 from                 
  apackagesettings                 
 where                  
  companyid = @intcompanyid                
 --To return if the corresponding accounts are not selected                
 --R Harikrishnan 08/08/2003                
 if isnull(@intCostOfGoodsAccId,0)=0 or isnull(@intInventoryaccid,0)=0                
  return 0                
 --To return if the corresponding accounts are not selected                
 --R Harikrishnan 08/08/2003                
 if @numProfitTrans>0 and (isnull(@intPlTransAccId,0)=0 or isnull(@intPlTransAccId,0)=0)                
  return 0                
                
 set @intJournalId = @intJournalId + 1                
                
 --R Harikrishnan for Customs Duty Posting                
 Declare invcur cursor for                 
  SELECT                 
   ihInvoiceId, ihinvoiceno, ihinvoicedate, ihCustomerId,  ihremarks,                 
   ihdepartmentid, ihfinancialid,  ihsalesaccid, ihexchangerate, updatetime,                
   ihdepExRate, ihexchangerates, ihCustomsDutyAccID, ihdutypaidby                
  FROM                 
   losinvoiceheader                 
  WHERE                 
   ihcancelled =0 and ihposted =0 and ihproforma = 0 and                 
   ihCompanyID = @intCompanyID and ihShopId = @intShopId and                 
   ihcashinvoice =0 and ihtype ='i'                 
                   
 open invcur                
                
 --R Harikrishnan for Customs Duty Posting                
 fetch next FROM invcur into                 
  @intInvoiceId, @strinvoiceno, @dtinvoicedate, @intCustomerId, @strremarks,                 
  @intdepartmentid, @intfinancialid, @intsalesaccountid, @NumEr, @dtutime,                
  @depExRate, @strExRates, @intCustomsDutyID, @chrCustomsDutyPaidType                
                
 while @@Fetch_status = 0                
 begin                
  set @numTotalinvValue  = 0.0                
  set @numTotalCostValue = 0.0                
  set @numTotalDiscountValue = 0.0                
  set @numTotalOCValue = 0.0                
  set @numCustomsDutyAmt = 0.0                 
                
  --FOR GETTING TRANS EXCHANGE RATE                
  select                 
   @intCurrencyId = CurrencyId                 
  from                 
   aCustomerMaster                 
  where                 
   CustomerId = @intCustomerId                
                
  exec spReturnExRate @intCurrencyId, @strExRates, @numTransEr output                
                
  --R Harikrishnan for Customs Duty Posting                
  --FOR GETTING TRANS EXCHANGE RATE                
  SELECT                 
   @numTotalinvValue = sum(idactualunitprice),                 
   @numTotalDiscountValue = sum(idunitprice),                
   @numCustomsDutyAmt = isnull(sum(isnull(idcdcustcur,0.00)),0.00),                
   @numTotalCostValue = isnull(sum(idquantity * idcostprice),0)                
  FROM                 
   losinvoicedetail                 
  WHERE                 
   idShopId = @intShopId and idInvoiceId  = @intInvoiceId                 
  group by                 
   idShopId, idInvoiceId                
                
  --R Harikrishnan for Customs Duty Posting                
  --Checking whether the AccountID is saved in the transaction                
  if (@chrShopType='B' and @chrCustomsDutyPaidType<>'C' and                 
   isnull(@intCustomsDutyID,0) = 0 AND @numCustomsDutyAmt>0)                
  Begin                
   Close invcur                
   Deallocate invcur                
   Return 0                
  End                
          
       -----------------------------------------------        
          
  SELECT                 
   @numTotalOCValue = sum(ioAmount) , @numOCTaxAmount = sum(isnull(ioServTaxAmount,0)) --RefNo-3 Null handled             
  FROM                 
   losInvoiceOC                 
  WHERE                 
   ioShopId = @intShopId and ioInvoiceId  = @intInvoiceId               
   group by  ioShopId, ioInvoiceId                
           
                
  --To return if the corresponding accounts are not selected                
  --R Harikrishnan 08/08/2003                
  if isnull(@intOtherChargesAccountID,0)=0 and @numTotalOCValue<>0                
  begin                
   Close invcur                
   Deallocate invcur                
   return 0   
  end     
                
  Set @numSalesValue = @numTotalDiscountValue                 
                
  --R Harikrishnan for Customs Duty Posting                
  /*if (@chrShopType='B' and @chrCustomsDutyPaidType<>'C')                
  begin                
   set @numTotalDiscountValue = @numTotalDiscountValue + @numTotalOCValue +                
    @numCustomsDutyAmt                
  end                
  else                
  begin                 
   set @numTotalDiscountValue = @numTotalDiscountValue + @numTotalOCValue                 
   set @numCustomsDutyAmt = 0.00                
  end */                
                
  insert into moaJournalHeader                 
   (JournalId, CompanyID, JournalDate, referenceno, remarks, financialID,                 
   Type, CurrencyId, chequedate, updatetime)                 
  values                 
   (@intJournalId, @intCompanyID, @dtinvoicedate, @strinvoiceNo,                 
   @strRemarks, @intFinancialID,'SCI', @intcomCurID,@dtinvoicedate, @dtutime)                
                
  set @intJournalDetailId = 1     
  ---  RefNo-5         
  set @TotalTaxAmnt=0.00              
  set @CTotalTaxAmount=0.00              
  set @DTotalTaxAmount=0.00 
         
--RefNo-2--------------------------------------               
  select @TotalTaxAmnt=sum(isnull(taxAmount,0)),@CTotalTaxAmount=sum(isnull(CtaxAmount,0)),@DTotalTaxAmount=sum(isnull(DtaxAmount,0))               
  from @Taxtable where taxTransId=@intInvoiceId and taxShopId=@intShopId group by taxTransId,taxShopId              
              
  if @TotalTaxAmnt is null               
  begin              
  set @TotalTaxAmnt=0.00              
  set @CTotalTaxAmount=0.00              
  set @DTotalTaxAmount=0.00              
  end              
--TO CONVERT INTO SALE A/C CURRENCY---              
select @intCurrencyId = CurrencyId                 
  from  aAccountMaster  where accountid = @intSalesAccountID                
              
  exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                 
  exec spconvertcurrency @numTransEr , @numAccEr , @TotalTaxAmnt,                     
  @TotalAccTax output                
--TO CONVERT INTO SALE A/C CURRENCY---              
--RefNo-2----------------------------------------              
                  
  --FOR CONVERTING AMOUNT--->                
  select @intCurrencyId = CurrencyId from  aAccountMaster  where accountid = @intSalesAccountID                
            
  exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                 
                
  exec spConvertCurrency @numTransEr , @numAccEr, @numSalesValue ,                 
       @numAaccAmt output                
                
  --FOR CONVERTING AMOUNT <---                
                
  /* crediing the sales account with the full invoice Amount */                
  insert into moaJournalDetails                 
   (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                 
   Amount, actualAmount, departmentID, depamount, PostGroup)                
  values                 
   (@intJournalId, @intJournalDetailId, @intCompanyID, 1,                 
   @intSalesAccountID, (@numSalesValue * @NumEr)-(@CTotalTaxAmount),                 
   (@numAaccAmt-@TotalAccTax),@intDepartmentID, (@numSalesValue * @depExRate)-(@DTotalTaxAmount), 1)  --RefNo-2---tax amount is deducted                
              
              
  set @intJournalDetailId = @intJournalDetailId +1                
                
  if @numTotalOCValue >0                 
  begin           
          
    -- DEBITING customer with other charges                
   insert into moaJournalDetails                 
    (JournalId, JournalDetailId, CompanyID, JournalCrEDit, CustomerId,                 
    Amount, actualAmount, departmentID, depamount, PostGroup)         
   values         
    (@intJournalId, @intJournalDetailId, @intCompanyID, 0, @intCustomerId,                 
    @numTotalOCValue * @NumEr, @numTotalOCValue,                
    @intDepartmentID, @numTotalOCValue * @depExRate, 2)                
                 
   set @intJournalDetailId = @intJournalDetailId + 1          
           
  set @numTotalOCValue=@numTotalOCValue-@numOCTaxAmount    -------        
           
   select                 
    @intCurrencyId = CurrencyId                 
   from                 
    aAccountMaster                
   where                 
    accountid = @intOtherChargesAccountID                
                
   exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                 
                
   exec spConvertCurrency @numTransEr , @numAccEr , @numTotalOCValue,                 
       @numAaccAmt output                
   --FOR CONVERTING AMOUNT <---                
                
   /* crediing the sales account with the full invoice Amount */                
  insert into moaJournalDetails                 
    (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                 
    Amount, actualAmount, departmentID, depamount, PostGroup)                
   values                 
    (@intJournalId, @intJournalDetailId, @intCompanyID, 1,                 
    @intOtherChargesAccountID, @numTotalOCValue* @NumEr,                 
    @numAaccAmt, @intDepartmentID, @numTotalOCValue * @depExRate, 2)       
                
   set @intJournalDetailId = @intJournalDetailId + 1           
              
           
   -----------------------------------------------------------------------------------------------------        
        
      /* crediing the other charge amount to service tax account  */                
   select @IntServTaxAccnt=t.TaxAccountId ,@IntServTaxAccntCurrID=a.CurrencyID        
   from ashops s inner join aTaxCategoryMaster t on s.ServiceTaxCategoryId=t.TaxId         
   inner join aAccountMaster a on a.AccountID=t.TaxAccountId        
              
   exec spReturnExRate @IntServTaxAccntCurrID, @strExRates, @numAccEr output                 
   exec spConvertCurrency @numTransEr , @numAccEr , @numOCTaxAmount,                 
       @numAaccAmt output                
   --FOR CONVERTING AMOUNT <---             
              
  insert into moaJournalDetails                 
    (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                 
    Amount, actualAmount, departmentID, depamount, PostGroup)                
   values                 
    (@intJournalId, @intJournalDetailId, @intCompanyID, 1,                 
    @IntServTaxAccnt, @numOCTaxAmount* @NumEr,                 
    @numAaccAmt, @intDepartmentID, @numOCTaxAmount * @depExRate, 2)                
                
   set @intJournalDetailId = @intJournalDetailId + 1                
   --------------------------------------------------------------------------------------------------------        
                  
  end                 
                  
  --R Harikrishnan for Customs Duty Posting                
  if @numCustomsDutyAmt >0 and @chrCustomsDutyPaidType<>'C' and @chrShopType='B'                 
  Begin                
   select                 
    @intCurrencyId = CurrencyId                 
   from                 
    aAccountMaster                
   where                 
    accountid = @intCustomsDutyID                
                
   exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                
                
   exec spConvertCurrency @numTransEr , @numAccEr,                 
    @numCustomsDutyAmt, @numAaccAmt output                
                 
   -- crediing the Customs Duty account                 
   insert into moaJournalDetails                 
    (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                 
    Amount, actualAmount, departmentID, depamount, PostGroup)                
   values                 
    (@intJournalId, @intJournalDetailId, @intCompanyID, 1,                 
    @intCustomsDutyID, @numCustomsDutyAmt * @NumEr,                 
    @numAaccAmt, @intDepartmentID,                 
    @numCustomsDutyAmt * @depExRate, 3)                
                
   set @intJournalDetailId = @intJournalDetailId + 1                
                
   -- DEBITING customer Custom Duty amount                
   insert into moaJournalDetails                 
    (JournalId, JournalDetailId, CompanyID, JournalCrEDit, CustomerId,                 
    Amount, actualAmount, departmentID, depamount, PostGroup)                
   values                 
    (@intJournalId, @intJournalDetailId, @intCompanyID, 0, @intCustomerId,                 
    @numCustomsDutyAmt * @NumEr, @numCustomsDutyAmt,                
    @intDepartmentID, @numCustomsDutyAmt * @depExRate, 3)                
                 
   set @intJournalDetailId = @intJournalDetailId + 1                 
  End                
                  
  -- DEBITING customer Invoice amount                
  insert into moaJournalDetails                 
   (JournalId, JournalDetailId, CompanyID, JournalCrEDit, CustomerId,                 
   Amount, actualAmount, departmentID, depamount, PostGroup)                
   values                 
   (@intJournalId, @intJournalDetailId, @intCompanyID, 0, @intCustomerId,                 
   @numTotalDiscountValue * @NumEr, @numTotalDiscountValue,                
   @intDepartmentID, @numTotalDiscountValue * @depExRate, 1)                
                 
   set @intJournalDetailId = @intJournalDetailId + 1                 
                
  -- FOR CONVERTING AMOUNT --->                
  select                 
   @intCurrencyId = CurrencyId                 
  from                 
   aAccountMaster                
  where                  
   accountid = @intINVentoryAccID                
                  
  exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                 
                
  exec spConvertCurrency @numTransEr, @numAccEr, @numTotalCostValue,                 
        @numAaccAmt output                
 if @numTotalCostValue<>0                
 begin                
  --FOR CONVERTING AMOUNT <---                
                
  /* crediing the INVENTORY with the full cost Amount */                
  insert into moaJournalDetails                 
   (JournalId, JournalDetailId, CompanyID,                 
   JournalCrEDit, AccountID, Amount, actualAmount, departmentID, depamount, PostGroup)                
  values                 
   (@intJournalId, @intJournalDetailId, @intCompanyID, 1,                 
   @intINVentoryAccID, @numTotalCostValue * @NumEr, @numAaccAmt,                
   @intDepartmentID, @numTotalCostValue * @DepExRate , 4)                         
  set @intJournalDetailId = @intJournalDetailId +1                
                
  --FOR CONVERTING AMOUNT--->                
  select                 
   @intCurrencyId = CurrencyId                 
  from                  
   aAccountMaster                
  where                  
   accountid = @intCostOfGoodsAccId                  
                
  exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                 
                
  exec spConvertCurrency @numTransEr, @numAccEr, @numTotalCostValue,                  
       @numAaccAmt output                
  --FOR CONVERTING AMOUNT <---                
                
  -- DEBITING THE COST OF GOODS ACCOUNT                
  insert into moaJournalDetails                 
   (JournalId, JournalDetailId,CompanyID,                 
   JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount, PostGroup)                
values                 
   (@intJournalId, @intJournalDetailId, @intCompanyID, 0,                 
   @intCostOfGoodsAccId, @numTotalCostValue * @NumEr, @numAaccAmt,                 
   @intDepartmentID, @numTotalCostValue * @depExRate, 4)                
 end                
  -- transfering the profit to company department                
  -- calcuating the shopwise profit transfering based on RevisedCostPricePercent                
              
--RefNo-2-----------------------------------              
select @IntCount=count(*) from @Taxtable where taxTransId=@intInvoiceId and taxShopId=@intShopId             
while (@IntCount>0)              
begin              
  select top 1 @TaxAcntId=taxAccntId,@CTaxAmount=CtaxAmount,@TaxAmount=taxAmount,@DTaxAmount=DtaxAmount               
  from @Taxtable where taxTransId=@intInvoiceId and taxShopId=@intShopId order by taxAccntId              
              
  --TO GET TAX EXCHANGE RATE --------------->                    
  select @TaxCurrId = currencyid from aaccountmaster a where                     
  accountid = @TaxAcntId                    
  exec spReturnExrate @TaxCurrId, @strExRates, @numTaxEr output                    
  --TO GET TAX EXCHANGE RATE <---------------                    
  ---------------------------------------                    
  exec spconvertcurrency @numTransEr , @numTaxEr , @TaxAmount,                     
  @TaxAccAmount output                
  ------------------------------------------              
  set @intjournalDetailID=@intjournalDetailID+1              
              
  /* crediting TO TAX ACCOUNT   */              
  insert into moaJournalDetails                 
   (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                 
   Amount, actualAmount, departmentID, depamount, PostGroup)                
  values                 
   (@intJournalId, @intJournalDetailId, @intCompanyID, 1,                 
   @TaxAcntId, @CTaxAmount,                 
   @TaxAccAmount,@intDepartmentID, @DTaxAmount, 1)                
                
  delete from @Taxtable where taxTransId=@intInvoiceId and taxShopId=@intShopId and taxAccntId=@TaxAcntId             
  set @IntCount=@IntCount-1              
end              
--RefNo-2-------------------------------------------              
              
 if @numProfitTrans <> 0                
 begin                
                
  -- FOR CONVERTING TO ACCOUNT AMOUNT---------->                
                   
  select                 
   @intCurrencyId = CurrencyId                 
  from                 
   aAccountMaster                
  where                 
   accountid = @intPlTransAccId                
                  
  exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                 
                
  exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,                 
  @numAaccAmt output              
                
  select                 
   @intCurrencyId = depCurrencyId                 
  from                 
   adepartmentmaster                 
  where                 
   departmentid = @intcomdeptid                
                  
  exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                 
                
  exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,             
      @NumDepAmt output                
                
  -- FOR CONVERTING TO ACCOUNT AMOUNT<------------------                
  set @intJournalDetailId = @intJournalDetailId + 1                 
                   
  -- credit transfer control account with shop department                
  insert into moaJournalDetails                 
   (JournalId, JournalDetailId, CompanyID,                 
   JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount, PostGroup)                
  values                 
   (@intJournalId, @intJournalDetailId, @intCompanyID, 1,                 
   @intPlTransAccId , @numTotalCostValue * @NumEr * @numProfitTrans * 0.01,                 
   @numAaccAmt * @numProfitTrans * 0.01, @intDepartmentID,                
   @numTotalCostValue * @numProfitTrans * 0.01 * @depExRate, null )                
                
  set @intJournalDetailId = @intJournalDetailId +1                 
                   
  -- credit transfer control account with comp department                
  insert into moaJournalDetails                 
   (JournalId, JournalDetailId, CompanyID,                 
   JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount, PostGroup)                
  values                 
   (@intJournalId, @intJournalDetailId, @intCompanyID, 0,                 
   @intPlTransAccId , @numTotalCostValue * @NumEr * @numProfitTrans * 0.01,                 
   @numAaccAmt * @numProfitTrans * 0.01, @intcomdeptid,                 
   @numDepAmt * @numProfitTrans * 0.01, null)                
                  
  -- FOR CONVERTING TO ACCOUNT AMOUNT ---------->                
  select                 
   @intCurrencyId = CurrencyId                 
  from                  
   aAccountMaster                
  where                 
   accountid = @intcomprofitaccid                
                  
  exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                 
                
  exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,                 
  @numAaccAmt output                
                
  select                 
   @intCurrencyId = depCurrencyId                 
  from                 
   adepartmentmaster                 
  where                
   departmentid = @intcomdeptid                
                  
  exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                 
                
  exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,                 
      @NumDepAmt output                
  -- FOR CONVERTING TO ACCOUNT AMOUNT< ----------                
                
  set @intJournalDetailId = @intJournalDetailId +1                
                  
  insert into moaJournalDetails                 
   (JournalId, JournalDetailId, CompanyID,                 
   JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount, PostGroup)                
  values                 
   (@intJournalId, @intJournalDetailId, @intCompanyID, 1,                 
   @intcomprofitaccid , @numTotalCostValue * @NumEr * @numProfitTrans * 0.01,                 
   @numAaccAmt * @numProfitTrans * 0.01, @intcomdeptid,                 
   @numDepAmt * @numProfitTrans * 0.01, null )                
                
  -- debit company profit account with shop department                 
  set @intJournalDetailId = @intJournalDetailId +1                
                
  insert into moaJournalDetails                 
   (JournalId, JournalDetailId, CompanyID,                 
   JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount, PostGroup)                
  values                 
   (@intJournalId, @intJournalDetailId, @intCompanyID, 0,                 
   @intcomprofitaccid , @numTotalCostValue * @NumEr * @numProfitTrans * 0.01,                 
   @numAaccAmt * @numProfitTrans * 0.01, @intDepartmentID,                
   @numTotalCostValue * @numProfitTrans * 0.01 * @depExRate, null )                 
 end                
                
  /* mark the record as postED */                
  update losinvoiceheader set                 
   ihpostED =1                 
  WHERE                 
   ihCompanyID = @intCompanyID                 
   and ihShopId = @intShopId and ihInvoiceId = @intInvoiceId                 
                
  set @intJournalId = @intJournalId + 1                
                
  --R Harikrishnan for Customs Duty Posting                
  fetch next FROM invcur into                 
   @intInvoiceId, @strinvoiceno, @dtinvoicedate, @intCustomerId,                 
   @strremarks, @intdepartmentid, @intfinancialid, @intsalesaccountid,                
   @NumEr, @dtutime,@depExRate, @strExRates, @intCustomsDutyID,                 
   @chrCustomsDutyPaidType                 
 end                
 Close invcur                
 Deallocate invcur                
SET NOCOUNT OFF              
end
GO
/****** Object:  View [dbo].[vwInvoicedPosRequests]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[spUpdateLEDgersHPFeePayment]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
GO
/****** Object:  View [dbo].[vwReplacementReceipt]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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:  StoredProcedure [dbo].[spDeletePOSDetail]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------------------------------    
--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
GO
/****** Object:  StoredProcedure [dbo].[spInsertPOSDetail]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--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       
-----------------------------------------------------------------
GO
/****** Object:  View [dbo].[vwPosSales]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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:  StoredProcedure [dbo].[spUpdateRecepieDetails]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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
GO
/****** Object:  StoredProcedure [dbo].[spMag_FetchCashSaleDeliveryDetails]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================================================  
-- 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
GO
/****** Object:  View [dbo].[TestView_2]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[SpUpdateShopStockPos]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----   
-- 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
GO
/****** Object:  View [dbo].[vwHPFeePaymentCheckList]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
 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].[vwchequereportprint]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  View [dbo].[vwposposamount]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spHpReceiptTracking]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwHPOverDueBalanceTEST]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwHPAdvancePayment]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[spHpProcessingtracking]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------  
--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
GO
/****** Object:  StoredProcedure [dbo].[SPHPOVERDUE]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*        
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
GO
/****** Object:  StoredProcedure [dbo].[spPopulateHpInterestDetails]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Created by: Nidheesh P V        
--Created on: 18/07/2010      
--Comments: To populate interest details for hp cheques      
-----------------------------------------------------------------------------
--Modified by: Nidheesh P V        
--Modified on: 18/07/2010      
--Comments: added isnull condition 
--Reference : RefNo-1     
-----------------------------------------------------------------------------
--spPopulateHpInterestDetails 2,1,168,'20100808'     
                            
CREATE proc [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
GO
/****** Object:  View [dbo].[vwHPOverDueBalance]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwHPFinancialIncomeEarned]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwHPProcessingDetails]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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:  StoredProcedure [dbo].[spHPCustomerClassification]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[sphpBouncedChequeDetails]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateGodownStockSpecial]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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
GO
/****** Object:  View [dbo].[vwSpecialDespatchOutQty]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spGodownLocationTotalStockVerification]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
 
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spGodownExpiryTotalStockVerification]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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
GO
/****** Object:  View [dbo].[vwposout]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spCheckAlertOnMergeComplete]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
----------------------------

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

---------------------------------------------
GO
/****** Object:  View [dbo].[vwMergeCompleteDetails]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
------------------------------------------------------

-- 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:  StoredProcedure [dbo].[spMagnolia_Insert_InHouseCons_ReturnDetail]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwShoprequestpending]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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:  StoredProcedure [dbo].[spBouncedChequeDetailsLC]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------  
  
--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
GO
/****** Object:  View [dbo].[vwTransferInOutRequest]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwTransferOutShopToShop]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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:  StoredProcedure [dbo].[SpMag_FetchTransferIn]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 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
GO
/****** Object:  View [dbo].[vwinterdepsales]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
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:  StoredProcedure [dbo].[SpMag_SaveTransferOutHeader]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ===========================================================  
-- 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
GO
/****** Object:  View [dbo].[vwpcpaymentvoucherdetails]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[spUpdateLEDgersPCP]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
GO
/****** Object:  StoredProcedure [dbo].[spReexportProjFlow]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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
GO
/****** Object:  StoredProcedure [dbo].[spshoprequestflow]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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
GO
/****** Object:  View [dbo].[vwShopDamageClearing]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
/****** 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].[vwpcpaymentCLbankwise]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------------------------------------------
--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: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwpcpaymentlisting]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  StoredProcedure [dbo].[spAssetDetailsuptoDate]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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
GO
/****** Object:  View [dbo].[vwInHouseConsumption]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  StoredProcedure [dbo].[spMagnolia_Insert_InHouseCons_ReturnHeader]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwaHQadminuserRightsRptDtls]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[spMagnolia_CheckShopUserRights]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================        
-- 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
GO
/****** Object:  View [dbo].[vwinterdeppurchase]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
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:  View [dbo].[vwDiscountFromSupplierPerShipment]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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:  View [dbo].[vwShipmentwiseitem]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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].[vwPurchaseBillDetailwithunit]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** Object:  View dbo.vwPurchaseBillDetailwithunit    Script Date: 18/01/2003 9:45:36 PM ******/  
--Last Modified on  : 12/12/02  
--Modified by  : leo  
--Comments  : v3  
--Modified On : 17/06/2006 
--modified By : aneesh [removed text in convert function and added varchar]  
CREATE view [dbo].[vwPurchaseBillDetailwithunit]  
as select pb.*,u.unitcode,u.unitname, p.packingtypecode, 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].[shopstock1]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwimportitem_sa]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwpandcPurchasebillamount]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwDummyUniPriceVariancePerBill]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwHQbatchno]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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:  StoredProcedure [dbo].[spPurchaseAndStock]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwPayrollLinkwithjournal]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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].[vwPayrollLinkwithPayment]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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:  StoredProcedure [dbo].[spCompSalesQuantityWise]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwcompsalesquantitywise]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----   
  
/****** 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:  View [dbo].[vwcurrentstocksonee]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  View [dbo].[vwGodownIssueArrivalLocationWise]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spLocalPurchaseSerilNumer]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spTillEndStockVerificationRpt]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==========================================================================================    
-- 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
GO
/****** Object:  View [dbo].[vwPackQuantity]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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:  StoredProcedure [dbo].[Sp_param_SellingPrice]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwIssueNote]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwItemAttributes1]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE view [dbo].[vwItemAttributes1] as  select distinct isnull(Attribute1,'') Attribute1 ,1 Aid from aitem
GO
/****** Object:  View [dbo].[vwItemAttributes2]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE view [dbo].[vwItemAttributes2] as  select distinct isnull(Attribute2,'') Attribute2 ,1 Aid from aitem
GO
/****** Object:  View [dbo].[vwreexportInvoice]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[Sp_KotItemDetails]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwDepWiseItems]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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:  View [dbo].[vwItemRetailPacking]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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:  View [dbo].[vwissuenoteGodown]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwitemDescriptionprint]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwloiarrivaldetail]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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].[vwvendorItemDescription]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  StoredProcedure [dbo].[spUpdateShopItemMerge]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
---------------------------------------------------------

-- 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
---------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[spFindItemsRateNotFixed]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[generatebc]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwGoodReqDespArrDtls]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  StoredProcedure [dbo].[spUpdateGodownItemSplit]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spReorderLevelForecastingMailAlert]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ===================================================    
-- 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
GO
/****** Object:  View [dbo].[vwshopstockitemwithnegative]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwsalesandcostvalue]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[spStockBalancingGodownWise]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spfetchforsegment]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  StoredProcedure [dbo].[spReturnSellingPriceDetail]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO

/****** Object:  View [dbo].[vwItemDetailedSales]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwShopItemShipmentDetail]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----             
-- 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].[vwPandCInquiryShopStock]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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:  StoredProcedure [dbo].[proc1]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwSalesAnalysisByItem]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[gdnstockout]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwShopItemSalesFandB]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  View [dbo].[vwbrandcategory]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwstockout]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----   
--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].[vwgodownstockitemwithnegative]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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].[vwGodownExpiryAlertItems]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
---------------------------------------------------------------

-- 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].[vwcollectionbrandwisegraph]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwreexportquotation]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwreexportPurchaseOrder]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwreexportpurchaserequest]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 
--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:  StoredProcedure [dbo].[spStockBalancingShopWise]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
GO
/****** Object:  View [dbo].[vwitemcustomcode]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create view [dbo].[vwitemcustomcode] as select distinct isnull(customcode,'') Customcode ,1 customid from aitem
GO
/****** Object:  View [dbo].[vwhpSPfinding]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----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].[vwitempackingonebarcode]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwitemdesc]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwHpItemDetails]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--*********************************************************************************   
-- 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:  View [dbo].[vwItemDescription_ASKholdings]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[sp_Crm_Report_Quotation]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- 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
GO

/****** Object:  View [dbo].[vwshopstockout]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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].[vwCollectionBrandWise]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwEligibleForDiscount]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwItemDiscountList]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[spSellpriceCurrwiseWOPriceChange]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[gdnstockout1]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spUpdateShopStockRecvr]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwCompanyTotalStock]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[spsellpriceCurrwise]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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
GO
/****** Object:  View [dbo].[vwItemSearching]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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:  View [dbo].[vwtmpstock]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwshopstockitem]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----   
--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].[SpUpdateGodownarrival]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwItemSplitCosting]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwSalesMarginAndPerc]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Modified on          : 12/12/02        
-- Modified by   : leo        
-- Comments  : v3        
----------------------------------------------------------------------------------------        
-- Modified on          : 12/06/2003        
-- Modified by          : Kishore        
-- Comments             : Added amount column        
--                        Added cAmount and dAmount on 18/06/2003        
-- Sebin(24/06/09)-Changed itemunitprice,ditemunitprice & citemUnitPrice,it was taken average before                      
----------------------------------------------------------------------------------------       
-- Modified on  :-12-08-09    
-- Modified by  :Nidheesh     
--Comments :to avoid Divide by zero error 'itemunitprice'is diredctly taken from view vs    
--comments  :included the condition avg(posdunitprice)in MARGIN and PERCENTAGE to consider RBD    
----------------------------------------------------------------------------------------    
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:  StoredProcedure [dbo].[spMag_SaveDeliveryVerificationDetails]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================================================  
-- 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
GO
/****** Object:  View [dbo].[vwFixedCost]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[tempItems]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[spFindInActiveItems]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------                       
--Created By : AADYAKUMAR.D.V
--Created On : 10/04/2012            
--Purpose    : Checking Active & For Sale in Kit&List Item            
-------------------------------------------------------------------------- 
--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
GO
/****** Object:  View [dbo].[vwdespatchestogodown]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwLeadtime]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[spQuotereplaceSelPrice]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwShopItemSalesDecimalQty]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwGoodsRequestToHq]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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:  StoredProcedure [dbo].[spUpdateGodownItemMerge]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------

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


-------------------------------------------------------------------------
GO
/****** Object:  View [dbo].[vwservicedoneforotherbranditems]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spUpdateGodownRecovery]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO

/****** Object:  View [dbo].[VwItemSalesGrouped]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------------------------------------------------    
-- 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:  View [dbo].[vwsalesSumYearWise]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwItemDetailedSalesForecastment]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------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:  View [dbo].[vwGodownToGodownTransfer]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[VWDailyItemSalesWithStock]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------------------------------------------------
--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].[vwgodownstockitem]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwPurchaseBillPackQty]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------      
--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].[vwlosShopItemShipment]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwCollectionCategoryWise]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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:  StoredProcedure [dbo].[spItemFlowAnalysis]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- 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'
GO
/****** Object:  StoredProcedure [dbo].[spproductwiseservices]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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
GO
/****** Object:  View [dbo].[vwmonthwiseproductsales]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[SP_FETCH_SELLINGPRICE]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO

/****** Object:  View [dbo].[VwTemplocation]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwShopItemStockitemsItemDtls]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwgodownwisevalue]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[spUpdateGodownLocationItemMerge]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------

-- 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
--------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[SP_FETCH_AITEM]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO

/****** Object:  View [dbo].[vwGdnInventoryValue]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwGodownTotalStockVerification]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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].[vwHpItemRegistrationDetails]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--*********************************************************************************     
-- 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:  View [dbo].[vwpendingpoitems]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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].[vwShopPendingRequestsForPo]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[spUpdateGodownDamageClearing]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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
GO
/****** Object:  View [dbo].[vwGodownLocationWiseStock]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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:  StoredProcedure [dbo].[SP_FETCH_AITEMCATEGORY]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwDailyDeliveryNote]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------------------
--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].[spUpdateGodownWriteOff]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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
GO
/****** Object:  View [dbo].[vwCancelEditUser]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwbillpopulategrid]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  StoredProcedure [dbo].[spTillEndPriceSegment]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================================================================                          
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spGenPrefix]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spTillEndReport]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================                      
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spComplimentaryItemValue]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================          
-- 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
GO
/****** Object:  View [dbo].[vwFANDBInvoice]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------        
--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:  StoredProcedure [dbo].[spCompSalesValueWise]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  View [dbo].[vwpurchaseorderothcharge]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create view [dbo].[vwpurchaseorderothcharge] as
select POorderID,SUM(POAmount)POAmount from lopurchaseorderothcharge group by POorderID
GO
/****** Object:  View [dbo].[vwLoyaltyCardContactDetails]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwshopservicesalesWithOutGST]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Last Modified on  : 19/10/2004  
--Modified by  : Aneesh
------------------------------------------------------------------------------------------					  		
-- Modified by  : Bijesh.B
-- Date         : 19/08/2011
-- RefNo        : RefNo-5 
-- Ticket Id    : JSZ-828136 (SHEESHA)
-- Description  : Need UserWise selection for Cash Denomination interface
--              : siUserID column included
------------------------------------------------------------------------------------------					  		
--RefNo        : Newly created view (copy of vwshopservicesales)
--Modified by  : Bijesh.B
--Date         : 13/03/2012,11/04/2012 (addes sum() in GST Amount)
--Ticket id    : JDJ-400367 (Sonee)
--comments     : Need to show GST separately
----------------------------------------------------------------------------------------------   

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)) -isnull(aiTaxAmount,0)
    Else   
        (Sum((siServiceQty * siAmount) + siClearingCommAmt)) -IsNull(aiDiscount,0)-isnull(aiTaxAmount,0)  End
        As siamount, Sum(aiSettledamount) Settledamount ,   

    Case Convert(Int, IsNull(aiCashPaidByShop,0)) When 0 Then   
        ((Sum(siServiceQty * siAmount)) -IsNull( aiDiscount,0))-isnull(aiTaxAmount,0)  * aiexchangerate
    Else   
        ((Sum((siServiceQty * siAmount) + siClearingCommAmt)) -IsNull(aiDiscount,0))-isnull(aiTaxAmount,0) End
        * aiexchangerate As sicamount,   
     
    Case Convert(Int, IsNull(aiCashPaidByShop,0)) When 0 Then   
        ((Sum(siServiceQty * siAmount)) -IsNull( aiDiscount,0))-isnull(aiTaxAmount,0) * aidepexrate
    Else   
        ((Sum((siServiceQty * siAmount) + siClearingCommAmt)) -IsNull(aiDiscount,0))-isnull(aiTaxAmount,0) End
        * aidepexrate As sidamount     
    ,ISNULL(siUserID,0) as UserID
    ,sum(isnull(aiTaxAmount,0)) GSTAmount
    ,sum(isnull(aiTaxAmount,0) * aidepexrate) as dGSTAmount
    ,sum(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:  View [dbo].[vwPosServiceInvoiceDetails]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwshopsaleinvoiceamount]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwTransferOUT]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwpackingtype]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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:  StoredProcedure [dbo].[spMonthSales]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwTill]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  StoredProcedure [dbo].[spInsertTillHeader]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------
--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
GO
/****** Object:  View [dbo].[vwTillhistory]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  StoredProcedure [dbo].[spUpdateTillStatus]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------------------
--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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateTillName]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------
--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
GO
/****** Object:  View [dbo].[vwTransferOutshoptoGdn]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwsettlements]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[spWeekSales]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwgoodsreturnamount]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------------------------------------     
--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].[vwShopgrn]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[spUpdateShopStockGReturn]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----   
-- 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
GO
/****** Object:  View [dbo].[vwposgrnamount]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[SpUpdateGodownStock]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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
GO
/****** Object:  View [dbo].[vwdatewisestock]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwTableBlock]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spReverseGodownTotalStockVerification]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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
GO
/****** Object:  View [dbo].[vwCompanyOpeningStock]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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:  View [dbo].[vwGdnBinCardWithOpening]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[SpUpdateGTransGodownStock]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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
GO
/****** Object:  View [dbo].[vwOpeningStock]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[splocupdatestock]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwCompBinCardWithOpening]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------     
-- 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].[vwCompanyBincard]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwHpSaleMothwise]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----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].[spEditGodownStock]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateDailyGodownStock]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  StoredProcedure [dbo].[spSetZeroLocationStockForNonVerifiedItemsInGodown]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spSetZeroExpiryStockForNonVerifiedItemsInGodown]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateGodownVerification]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  StoredProcedure [dbo].[spreportInformation]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockLP]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO

/****** Object:  StoredProcedure [dbo].[spUlShopPurchase]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockExchange]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockTrout]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO

/****** Object:  StoredProcedure [dbo].[spGetExchangeRate]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO

/****** Object:  StoredProcedure [dbo].[spOpeningGodownstockondate]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
   --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
GO

/****** Object:  StoredProcedure [dbo].[spshopOpeningstockondate]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO

/****** Object:  StoredProcedure [dbo].[spgetshopstockasondate]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwshopbincardauditwithopening]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[spUpdateshopDamageClearing]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockKegReturn]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateShopStockInv]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockSplInvRet]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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
GO
/****** Object:  View [dbo].[vwInquiryShopStock_Pos]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[spUpdateDailyShopStock]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  StoredProcedure [dbo].[SpUpdateShopStockArrival]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockTrIN]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwdatewisestockshop]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spUpdateShopWriteOff]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateStockExport]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockStg]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateStockServiceInvoice]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopPurchaseReturn]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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  
  
---------------------------------------------------------------------------------------------------------------------------------
GO
/****** Object:  View [dbo].[vwBudgetActualAnalysismax]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  View [dbo].[vwServiceInvoicePostAmount]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwserviceinvlisting]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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].[vwHQSerinvoice]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------------------        
--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].[vwinvoiceswithcontrolaccs]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[spCustomerSettlement]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*                            
-------------------------------------------------------------------------------------------                                    
SPName      : spCustomerSettlement                                      
Coded By    : Vinoth Murugan                                      
Date        : 16-02-2010                                      
Purpose     : To speed up Customer settlement.                           
Modified on : 17/03/2007                          
Modified By : VINOTHMURUGAN V                                     
-------------------------------------------------------------------------------------------                              
Modified On : 20-04-2010        
Modified By : Sreejith G A        
Purpose: Added the condition of fhinvoicecancelled = 0     
     and fhshopid=0 in Fine portion to populate Fine Invoices generated from Acc Invoices.    
-------------------------------------------------------------------------------------------       
Modified On : 22-12-2010        
Modified By : Shine Das
Purpose: Changed DELETE FROM  #tempid  to TRUNCATE TABLE #tempid
-------------------------------------------------------------------------------------------                               
EXEC spCustomerSettlement '217','3','1'      
*/                                 
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                                  
                                           
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))  Commented by SHINE  
create table #tempid(id int identity(0,1),InvoiceID int,Product int,discount 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' 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' 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                                  
   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                                  
   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 @INVAMT =(select isnull(sum(ServiceQty * Amount),0) prodamount from ServiceInvoiceDetails                                   
 where companyid = @companyid and @product=0 and invoiceid = @ID )                                   
                              
 set @INVAMT = @INVAMT - @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' 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' 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' from ahqpaymentvoucherheader                                 
 where phcancelled =0 and phcompanyid = @companyid and phcustomerid = @customerid                                  
                                           
END                                
     Else                                  
BEGIN                                
  INSERT INTO #TEMPID                                
     select phpaymentID, 0,'0.00' from ahqpaymentvoucherheader                                  
     where phcancelled =0 and phcompanyid = @companyid and phcustomerid = @customerid                                
     and phDepartmentID = @departmentid                                
End                                 
                                 
SET @INDEX = 1                                           
SET @RECCOUNT =(SELECT COUNT(id) from #TEMPid)                
                                            
WHILE (@INDEX <= @RECCOUNT)                                  
BEGIN                                   
                                 
 SET @ID = (SELECT InvoiceID FROM #TEMPID WHERE ID= @INDEX)                                 
                                    
 SET @AMT =(SELECT isnull(sum(AmountReceived),0) FROM receiptvoucherdetails rd, receiptvoucherheader rh                                
 WHERE  rd.companyid = rh.companyid and rh.companyid = @companyid                                 
 and rd.receiptid = rh.receiptid and rh.cancelled = 0 and rd.phpaymentid = @ID)                                
                                 
 SET @AMT1 =( SELECT isnull(sum(settlementamount),0) FROM customersettlementdetail cd, customersettlementheader ch                                 
 WHERE  ch.companyid = cd.companyid and ch.csid = cd.csid and ch.cancelled = 0                                  
 and ch.companyid = @companyid  AND cd.paymentid = @ID)                 
                                  
 INSERT INTO #TEMP                                
 SELECT 'Head Quarters',phpaymentno,phPaymentDate,ISNULL( phcustomeramount- (@AMT+@AMT1),0),'0.00',                                
 phpaymentid,'payment',0  from ahqpaymentvoucherheader                                  
 where phcancelled =0 and phcompanyid = @companyid and phcustomerid = @customerid                                
 and phDepartmentID = @departmentid AND (@AMT+@AMT1)<= phcustomeramount  AND phpaymentID =@ID                                
                                  
 set @index = @index + 1                                 
 END                                
                              
insert into #temp                                         
exec SPPopulateShopInvoiceDetails_vw @customerid ,@companyid ,@departmentid                             
                          
                     
                              
select * from #temp where InvoiceAmount > 0                                
Drop table #temp                                  
Drop table #tempid                                  
end
GO
/****** Object:  View [dbo].[vwserviceinvoiceamt]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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].[vwServiceInvoiceDetails]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwHQinvoicereceipt]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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:  StoredProcedure [dbo].[spSalesPersonInvandSettled]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwspecialinvoicereceipt]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwApartmentBillSettlementNo]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwshopcreditinvoicereceipt]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwshopsaleinvoicereceipt]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spBankUsed]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwDebitNoteSettlementNo]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwBookServiceSettlementNo]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwreceiptlisting]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwpdcreceipts]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwReceiptDetailsDebit]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  View [dbo].[vwaccountinvsettledamount]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwReceiptVoucherHeader]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-------------------------------------------------------------------------------------------------------------------------  
-- 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].[vwShopSplInvoiceSettlementNo]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwhqpaymentinvandrecamount]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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].[vwbookservicesettlements]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwShopInvoiceSettlementNo]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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].[vwUtitilityBillSettlementNo]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwReceiptsCheckList]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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:  StoredProcedure [dbo].[SPPopulateShopInvoiceDetails_vw]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwreceiptCLbankwise]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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].[vwadvancepaidreceipts]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

--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].[vwAccInvoiceSettlementNo]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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].[vwshopdrcrinvandrecamount]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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].[vwcashreceipt]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[dataExist]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwreexportsettlements]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwShopAccInvoiceSettlementNo]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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:  StoredProcedure [dbo].[spInsertAccountsDefaultValues]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
---*****************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')

end
GO
/****** Object:  View [dbo].[vwSpecialInvoicePopulate]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------            
-- 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].[vwBudgetAllocationDetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwreexportvendorsettle]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwBillSettlementNo]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwshoppurchasePayments]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwhqposbillsettlementdetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwhqpbillsettlementdetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwAccVendrPayments]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwHQCNSettlementDetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwshopvendordebitnotes]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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].[vwHQPBillVendrPayments]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwLocalPurchaseBillSettlementNo]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwInterdivBillSettlementNo]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwaccbillvs]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwCreditNoteSettlementNo]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwConfirmedLocalPurchaseBill]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------------------                             
-- 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].[vwLPBillVendrPayments]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwPayments]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwPurchaseBillSettlementNo]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwReceiptSettlementNo]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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:  StoredProcedure [dbo].[spDaySalesAndBankPosition]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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
GO
/****** Object:  View [dbo].[vwariivaltoshoppendinglist]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  StoredProcedure [dbo].[spIssueStockBlock]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwAlreadyIssuedItemsReport]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwRequestIssueDesptachArrival]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwHQIssueDetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------    
--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].[vwGodownIssuedItems]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
---------------------------------------------  
/*  
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:  View [dbo].[vwAsstdisposalTransdetail]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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:  View [dbo].[vwAssetDisposal]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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:  View [dbo].[vwpaymentvoucher]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwHQPBillPaymentDetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwHQBillPaidDetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwLCMarginPaid]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwLcOutstandingPaid]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwShipmentExpences]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwpaymentvoucherdebitdetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwLCMarginOutstanding]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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:  StoredProcedure [dbo].[spLCRegisterAllDetailsOld]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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    
-----------------------------------------
GO
/****** Object:  View [dbo].[vwHqPurchasePayments]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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].[vwnotcoastingpayments]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwPaymentsOnPO]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
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].[vwLCOutstandingAge]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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:  StoredProcedure [dbo].[spAgreement]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-------------------------------------------------------------------------------
-- 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
GO
/****** Object:  View [dbo].[vwfacilitytracking]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwtoolsreturn]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  View [dbo].[vwtoolsallocation]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[spReservation]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
---------------------------------------------------------------------------
--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
GO
/****** Object:  StoredProcedure [dbo].[spcustomeritemsold]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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
GO
/****** Object:  View [dbo].[vwapartmentcheckdtls]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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:  StoredProcedure [dbo].[spRemoveTillDetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------
--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
GO
/****** Object:  StoredProcedure [dbo].[spInsertTillDetail]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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
GO
/****** Object:  View [dbo].[vwAdvancePaidPayments]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwGodownStockVerification]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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:  StoredProcedure [dbo].[SpUpdateUserRights]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwgodownlocationstock]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[spCustomerCreditLimitExceeds]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[spCustomerCreditLimitExceeds]                                           
 @intCompanyID  as int,                                           
 @intCustomerID  as int,                        
 @CheckMode as char(1),---denotes from where this invoice is generated                 
 @intLocationID as int=0,                                          
 @dtInvDate as datetime,                              
 @numInvoiceAmt  as numeric(18,2),                                           
 @ExcludeInvAmt as numeric(18,2) =0,                   
 --@numDebitbalanceIn  as numeric(18,2)=null --RefNo-5              
  @numDebitbalanceIn  as numeric(18,2)=0 --Ref -6                                     
                                           
as                  
 Declare @numCreditLimit as numeric (18,2),                                          
 @numDebitBal as numeric (18,2),                                                        
---------------------------------------RefNo-3                                                
 @dtintdatecon as varchar(10),                                      
 @intCustomerIDcon as varchar(1000),                                      
-----------------------------------                                             
 @intDept as int,                  
 @chCreditLimitType as char(1)                    
---------------------------------------------RefNo-3                                    
declare @tempDebtorage as table ( invamt numeric(18,2),settleamt numeric(18,2),invoiceid int,                                                                    
customerid int,shopid int,due  varchar(7),invoicedate datetime ,                                                                    
invoiceno varchar(50),type varchar(20),remarks varchar(1000),customername varchar(100),                                            
currencyname varchar(50),symbol varchar(50),duedate datetime,                                                                     
overduedays int, address1 varchar(50), address2 varchar(50), address3 varchar(50),                                                                     
referenceno varchar (100),debtoraccid int,accountdesc varchar(100),CustomerCategory varchar(100),CurrencyID int)                                            
 ------------------------------------------------------                                         
begin                  
SET NOCOUNT ON                                            
 SET @numCreditLimit = 0                                          
 SET @numDebitBal  = 0                                                
 ------------------------------------------------------------------------- RefNo-3                                                            
  -- Get credit limit type and override the parameter                                      
  -- (S-Shopwise, D-Deptwise, C-Companywise) (RefNo-2)                                      
select @chCreditLimitType=isnull(CreditLimitType,'S') from aPackageSettings                                       
                    
 --If shop credit limit level is set and a hq invoice is selected then it checks as company level credit limit.                   
if @chCreditLimitType='S' and @CheckMode='D'                   
begin                  
  set @chCreditLimitType='C'                   
end                
              
if @chCreditLimitType='S'              
begin              
-- Get customer credit limit from shop customer details----              
   SELECT @numCreditLimit = CreditLimit FROM  aShopCustomerDetails                                           
   WHERE ShopID = @intLocationID and customerID = @intCustomerID                 
end                 
else              
begin --(@chCreditLimitType='C' or 'D')              
    -- Get customer credit limit from customer master-----                                     
   SELECT @numCreditLimit = CreditLimit FROM  aCustomerMaster                                            
   WHERE CustomerID = @intCustomerID                  
end                   
          
--If hq invoice is selected then it checks the credit limit in customer master.          
--If this credit limit in customer master is zero no need to check the credit limit          
if @CheckMode='C' or @CheckMode='D'  and @numCreditLimit=0        
begin           
SELECT 0                              
RETURN 0            
end             
                               
IF @numDebitbalanceIn = NULL ---RefNo-5  --Ref -6         
                    
BEGIN                             
 -- **** METHOD 1: SHOP-WISE ****                                      
 -- Check if check mode is SHOP-WISE credit limit checking.                       
 -- In shop-wise credit limit checking, the credit in given shop                                       
 -- cannot exceeding set credit limit for the shop.                
  ----RefNo-4 ------------                    
                                    
  if @chCreditLimitType='S' and @CheckMode='S'                   
  --If shop credit limit level is set and shop invoice is selected then this will executed.                                       
  begin                   
    -- Get customer credit limit from shop customer details----                                      
   SELECT @numCreditLimit = CreditLimit FROM  aShopCustomerDetails                                           
   WHERE ShopID = @intLocationID and customerID = @intCustomerID                                  
   --Get Debit Amount-----                       
   INSERT INTO @tempDebtorage EXEC spdebtoragesum '',@dtInvDate,@intcustomerid,0,0,@intlocationid,'',''--shopwise                            
   SELECT @numDebitbal=ISNULL(SUM(ISNULL(invamt,0)-ISNULL(settleamt,0)),0) FROM @tempDebtorage                            
   --SELECT @numDebitbal,@numCreditLimit                          
  end                              
                                                           
  -- **** METHOD 2: DEPARTMENT-WISE ****                                      
  --If Department credit limit level is set then this will executed.                                       
  if @chCreditLimitType='D'                   
  begin                       
    -- Get customer credit limit from customer master-----                                     
   SELECT @numCreditLimit = CreditLimit FROM  aCustomerMaster                                            
   WHERE CustomerID = @intCustomerID                   
                                    
   if @CheckMode='S'                   
   begin                  
    SELECT @intDept=DepartmentID from ashops where ShopID=@intlocationid                            
   end                  
   else if @CheckMode='D'                  
   begin                  
   SELECT @intDept=@intlocationid                            
   end                  
   --Get Debit Amount------                  
   INSERT INTO @tempDebtorage EXEC spdebtoragesum '',@dtInvDate,@intcustomerid,@intDept,0,0,'',''--Deptwise                            
   SELECT @numDebitbal=ISNULL(SUM(ISNULL(invamt,0)-ISNULL(settleamt,0)),0) FROM @tempDebtorage                            
   --SELECT @numDebitbal                              
  end                              
                                                
  -- **** METHOD 3: COMPANY-WISE ****                                      
  --If Company credit limit level is set then this will executed.                                       
  if @chCreditLimitType='C'                                         
  begin                  
    -- Get customer credit limit from customer master--                                    
   SELECT @numCreditLimit = CreditLimit FROM  aCustomerMaster                                            
   WHERE CustomerID = @intCustomerID                   
   --Get Debit Amount---                                 
   INSERT INTO @tempDebtorage EXEC spdebtoragesum '',@dtInvDate,@intcustomerid,0,0,0,'',''--Comwise                            
   SELECT @numDebitbal=ISNULL(SUM(ISNULL(invamt,0)-ISNULL(settleamt,0)),0) FROM @tempDebtorage                            
   ---SELECT @numDebitbal                              
  end                       
END                      
ELSE                      
BEGIN                      
SET @numDebitbal=@numDebitbalanceIn ---RefNo-5                        
END                                       
----RefNo-4 ------------        
            
if (@numDebitbal + @numINvoiceamt - @ExcludeInvAmt) > @numCreditLimit and @numCreditLimit >0                                  
begin                                
SELECT 1                            
RETURN 1                                          
end                                    
else                                
begin                                
SELECT 0                              
RETURN 0                                
end                       
 ------------------RefNo-4---------------                             
                            
 ----SELECT @numdebitbal = @numdebitbal - @numCreditBal                                 
                                  
   --------RefNo-4-------------                              
 ------------else                                       
                                    
 ------------begin                                    
 ------------      SELECT @numDebitbal , @numINvoiceamt,@numCreditLimit            
 ------------  ------------------------------------------------------------------------- RefNo-3                                         
 ------------   --here checking  pending invoice against the customer( having settings in package settings)                                             
 ------------   set @NoCreditForOverdueCustomers = (select isnull(NoCreditForOverdueCustomers,0) from apackagesettings)                                            
 ------------   if @NoCreditForOverdueCustomers = 1                                             
 ------------   begin                                            
 ------------    set @dtintdatecon = convert (varchar(10),@dtInvDate,120)                                        
 ------------    set @intCustomerIDcon = cast(@intCustomerID as varchar(1000))                                        
                                              
 ------------    -- set @dtintdatecon = cast (@dtInvDate as varchar(50),120)                                       
                                            
 ------------   insert into #temp                                              
 ------------   exec spDebtorAgeSum '',@dtintdatecon,@intCustomerID,0,0 ,0,'',''                                       
 ------------   set @intdue = (select count(*) from #temp where duedate < @dtInvDate )                                            
                                                  
 ------------    if @intdue > 0   -- having any pending dues against the customer                                            
 ------------   begin                                              
 ------------    SELECT 1                                             
 ------------    return 1                                        
 ------------   end                            
 ------------    else                                      
 ------------   begin                                              
 ------------    SELECT 0                                             
 ------------    return 0                                        
 ------------   end                                            
 ------------   end                                       
 ------------     else                                         
 ------------  -------------------------------------------------------------------------                           
 ------------  begin                                          
 ------------   SELECT 0       
 ------------   return 0                                          
 ------------  end                                      
 ------------  end                                      
 --------------------RefNo-4-------------                     
 SET NOCOUNT OFF                              
end
GO
/****** Object:  View [dbo].[vwShopCustomerDetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwcustomerlisting]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spCreditForOverdueCustomers]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Procedure
--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           
------------------------------------------------------------                    
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)                              
                       
begin       
  SET NOCOUNT ON        
  SET @numDebitBal  = 0                            
  SET @intdue=0                          
  SET @NoCreditForOverdueCustomers = 0         
  SET @numDebitbalanceOut=0       
  SET @numDebitBal = 0        
          
  ----------------             
  --here checking  pending invoice against the customer( having settings in package settings)                               
  select @NoCreditForOverdueCustomers =isnull(NoCreditForOverdueCustomers,0) from apackagesettings                            
  ----------------       
  -- Get customer Due period                         
  if @CheckMode='S'       
  begin      
	--If shop invoice is selected the it checks the due period given in that shop      
	SELECT @intdue=DuePeriod FROM aShopCustomerDetails                             
	WHERE ShopID = @intLocationID and customerID = @intCustomerID        
	end      
  else      
	--If hq invoice is selected the it checks the due period given in hq(customer master)      
  begin      
	SELECT @intdue=Dueperiod  from aCustomerMaster where CustomerID = @intCustomerID       
  end      

  ----------------        
  -- Get credit limit type and override the parameter                        
  -- (S-Shopwise, D-Deptwise, C-Companywise)                       
  select @chCreditLimitType=isnull(CreditLimitType,'S') from aPackageSettings         
  ----------------      
        
  --If credit limit level is shop and a hq invoice is selected then it checks as company level credit limit.       
  if @chCreditLimitType='S' and @CheckMode='D'       
  begin      
	set @chCreditLimitType='C'       
  end       
                         
  -- **** METHOD 1: SHOP-WISE ****                            
  if @chCreditLimitType='S' and @CheckMode='S'       
   --If shop credit limit level is set and shop invoice is selected then this will executed.                                               
	begin              
	  INSERT INTO @tempDebtorage EXEC spdebtoragesum '',@dtInvDate,@intcustomerid,0,0,@intlocationid,'',''--shopwise              
      SELECT @numDebitbal=ISNULL(SUM(ISNULL(invamt,0)-ISNULL(settleamt,0)),0),@dtInvMinDate=MIN(invoicedate) FROM @tempDebtorage              
	  ------SELECT @numDebitbal,@dtInvMinDate            
	end                
                                           
	-- **** METHOD 2: DEPARTMENT-WISE ****                        
	--If Department credit limit level is set then this will executed.                           
  if @chCreditLimitType='D'                        
	begin               
		SELECT @intDept=DepartmentID from ashops where ShopID=@intlocationid              
		INSERT INTO @tempDebtorage EXEC spdebtoragesum '',@dtInvDate,@intcustomerid,@intDept,0,0,'',''--Deptwise              
		SELECT @numDebitbal=ISNULL(SUM(ISNULL(invamt,0)-ISNULL(settleamt,0)),0),@dtInvMinDate=MIN(invoicedate) FROM @tempDebtorage              
		-----SELECT @numDebitbal,@dtInvMinDate            
	end                
                                
	-- **** METHOD 3: COMPANY-WISE ****                        
	-- Else, check if credit exceeds COMPANY-WISE credit limit.                                     
  if @chCreditLimitType='C'                           
	begin                
		INSERT INTO @tempDebtorage EXEC spdebtoragesum '',@dtInvDate,@intcustomerid,0,0,0,'',''--Comwise              
		SELECT @numDebitbal=ISNULL(SUM(ISNULL(invamt,0)-ISNULL(settleamt,0)),0),@dtInvMinDate=MIN(invoicedate) FROM @tempDebtorage              
		-----SELECT @numDebitbal,@dtInvMinDate            
	end         
	------------------      
  SET @numDebitbalanceOut=@numDebitbal       

  SET @dtDuedate = dateadd(d,@intdue,@dtInvMinDate)                                         
------------------------------------------------            
  if (@numDebitbal-@ExcludeInvAmt)>0 and @dtInvDate>@dtDuedate and @dtInvMinDate is not null                  
	begin                  
		set @NoCreditForOverdueCustomers=1                  
	end                  
  else                  
	begin                  
		set @NoCreditForOverdueCustomers=0                  
	end                  
-----------------                  
  if @NoCreditForOverdueCustomers=1                   
	begin                  
		set @StrMessage='No credit for overdue customers.An invoice of this Customer is overdue.'                  
		--SELECT @NoCreditForOverdueCustomers ---No Credit For Overdue Customer             
		--SELECT @StrMessage             
		RETURN @NoCreditForOverdueCustomers ---No Credit For Overdue Customer        
		RETURN @StrMessage             
		RETURN @numDebitbalanceOut          
	end                  
  else                
	begin             
		set @StrMessage=''                     
		--SELECT 0            
		--SELECT ''            
		RETURN @NoCreditForOverdueCustomers ---Credit For Overdue Customer           
		RETURN @StrMessage         
		RETURN @numDebitbalanceOut           
	end                  
-----------------       
  SET NOCOUNT OFF                      
end
GO
/****** Object:  View [dbo].[vwDenominationTotal]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  StoredProcedure [dbo].[spCrEDitDebitOpeningCur]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[currencyexchangerate]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwBillCurrency]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwediPO]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwtotalstockcolor]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create view [dbo].[vwtotalstockcolor] as
select itemid,sum(stocks) as totalstocks from vwstockcolor
group by itemid
GO
/****** Object:  StoredProcedure [dbo].[UpdateData]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
GO
/****** Object:  View [dbo].[vwShopSplInvItemAmount]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwDailySalesUserWise]    Script Date: 04/16/2012 10:32:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[VWLOSSPECIALINVOICEDETAIL]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------
/*
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].[vwMEDifferenceinStock]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwHqDiffWriteOff]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----   
-- 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:  UserDefinedFunction [dbo].[GenerateNextTransactionNo]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--================================================================
--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
----------------------------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[spPDChequeRegisterProcessingForPOS]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwshoplocationstock]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[SPLatestSegmentRates]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetUsers]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
----------------------------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[spShipmentClearence]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-------------------------------------------------------------------------
--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
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_CheckLogin]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================        
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spInsertPOSdummyHeader]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------------------------------            
--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
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetRecepients]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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  
----------------------------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[spUpdatePOSdummyHeader]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-----------------------------------------------------------------------------------------------------------------------------      
--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
GO
/****** Object:  StoredProcedure [dbo].[spGetUser]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [dbo].[spGetUser]  AS

select UserID,UserName from aUsers
GO
/****** Object:  View [dbo].[vwprePurchaseAmount]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------
--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].[vwVendorGroupcategory]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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:  StoredProcedure [dbo].[spUpdateLEDgerspandcRet]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  Trigger [delPayrollCountryMaster]    Script Date: 04/16/2012 10:32:46 ******/
--  /*SET ANSI_NULLS ON
--GO
--SET QUOTED_IDENTIFIER OFF
--GO
--/*  
-- Created by :  R Harikrishnan  
-- Created on : 17/12/2002  
-- Purpose      : To Delete Payroll pcountrymaster table when there is a Delete in Admiv2 acountrymaster Table  
--*/  
--CREATE TRIGGER [dbo].[delPayrollCountryMaster]   
--ON [dbo].[aCountryMaster]  
--FOR Delete as  
--Begin  
-- declare @companyId as int,@CountryID as int  
-- select @companyId=companyId,@CountryID=CountryID from Deleted  
-- if exists (select 1 from payroll.dbo.pCountrymaster where companyId=@companyId and CountryID=@CountryID)  
--  Delete from payroll.dbo.pCountrymaster where  companyId=@companyId and CountryID=@CountryID  
--End
--GO*/
--/****** Object:  Trigger [udtPayrollCountryMaster]    Script Date: 04/16/2012 10:32:46 ******/
--/*SET ANSI_NULLS ON
--GO
--SET QUOTED_IDENTIFIER OFF
--GO
--/*  
-- Created by :  R Harikrishnan  
-- Created on : 17/12/2002  
-- Modified by : R Harikrishnan  
-- Modified on : 21/12/2002  
-- Purpose      : To Insert & update Payroll pcountrymaster table when there is an Insert or update in Admiv2 acountrymaster Table  
-- */  
--CREATE TRIGGER [dbo].[udtPayrollCountryMaster]   
--ON [dbo].[aCountryMaster]  
--FOR INSERT, UPDATE as  
--Begin  
-- declare @CompanyID as int,@CountryID as int,@CountryName as varchar(50),@Nationality as varchar(100)  
-- select @CompanyID=CompanyID,@CountryID=CountryID,@CountryName=CountryName,  
--  @Nationality=Nationality  
--  from inserted  
-- if exists (select 1 from payroll.dbo.pcountrymaster where CompanyID=@CompanyID and CountryID=@CountryID)  
--  Update payroll.dbo.pcountrymaster set   
--   CountryName=@CountryName,Nationality=@Nationality   
--   where CompanyID=@CompanyID and CountryID=@CountryID  
-- else  
--  if @CompanyID is not null and @CountryID is not null -- R Harikrishnan 21/12/20002  
--   Insert into payroll.dbo.pcountrymaster  
--    (CompanyID,CountryID,CountryName,Nationality)  
--    values (@CompanyID,@CountryID,@CountryName,@Nationality)  
--  
--End
--GO*/
/****** Object:  StoredProcedure [dbo].[spPLCarryForwardAmt]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_GeneratePosBill]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--spMagnolia_GeneratePosBill 8,3  
------------------------------------------------------------     
--CREATED BY: Nidheesh                  
--CREATED ON: 06-04-2011                  
--COMMENTS: TO GENERATE THE POS BILLID,BILLNO FOR ALL SHOPS      
--THE LOGIC TO GENERATE BILLID,BILLNO IS DONE AS LIKE IN THE FRONT END CODE.          
------------------------------------------------------------     
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    
  SELECT @intNextBillNo=LastBillNo + 1  
  FROM losPosHeaderLastBillNo WHERE ShopId=@intShopId     
     UPDATE losPosHeaderLastBillNo   
     SET LastBillNo = @intNextBillNo WHERE ShopId=@intShopId                               
 END                
 ELSE                
 BEGIN ---IF LASTBILLNO IS NOT IN losPosHeaderLastBillNo THEN IT TAKES THESE FROM THE losposheader TABLE                 
    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)                
 END     
SET @intBillID = (SELECT CASE WHEN COUNT(poshBillid)=0 THEN 1 ELSE MAX(poshBillid)+1 END FROM losposheader WHERE poshShopID=@intShopId)    
SET @strBillNo = @Prefix+CONVERT(VARCHAR,@intNextBillNo)  
END -----FOR NO COUNTER SHOPS-----     
ELSE            
BEGIN -----FOR COUNTER SHOPS-----     
SELECT @NumberFound=COUNT(NextBillNo)  
FROM aCounterMaster WHERE CounterShopId=@intshopId AND counterid=@intCounterId               
 IF @NumberFound >0   
 BEGIN              
  SELECT @intNextBillID = NextBillId,@intNextBillNo = NextBillNo   
  FROM aCounterMaster WHERE CounterShopId=@intshopId AND counterid=@intCounterId               
   IF @intNextBillID IS NOT NULL             
   BEGIN   ---IF NextBillId,NextBillNo IS IN aCounterMaster THEN IT DIRECTLY TAKES THESE FROM THE TABLE    
    UPDATE aCounterMaster SET NextBillId = @intNextBillID+1,NextBillNo=@intNextBillNo+1   
    WHERE CounterShopId=@intshopId AND counterid=@intCounterId                                
   END                
   ELSE                
   BEGIN  ---IF NextBillId IS NULL IN aCounterMaster THEN IT DIRECTLY TAKES NextBillId FROM THE TABLE aSettings       
    Select @intNextBillID=RefBillId From aSettings   
    IF @intNextBillID IS NOT NULL   
    BEGIN  
     UPDATE aCounterMaster SET NextBillId = @intNextBillID+1,NextBillNo=@intNextBillNo+1   
     WHERE CounterShopId=@intshopId AND counterid=@intCounterId                                   
    END  
   END     
 SET @intBillID = CONVERT(INT, CAST(100 + @intCounterId AS VARCHAR) + CAST (@intNextBillID AS VARCHAR))  
 SET @strBillNo = @Prefix+'C'+CONVERT(VARCHAR,@intCounterId)+'/'+CONVERT(VARCHAR,@intNextBillNo)    
 END  
END -----FOR COUNTER SHOPS-----    
--SELECT @strBillNo  
--SELECT @intBillID  
SET NOCOUNT OFF  
END
GO
/****** Object:  StoredProcedure [dbo].[spRatioAnalysis]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
    
----       
-- 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
GO
/****** Object:  View [dbo].[vwfinyearperiod]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[SpCashFlowStatement1]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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
GO
/****** Object:  StoredProcedure [dbo].[SpMag_SaveTransferOutDetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spbankdetailsdatewise]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwAssets]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spBudgetExceeds]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwNonControlsGroupAccounts]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spBalanceSheetOutPut]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spValidPlFormats]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwAccountGroupOrderCounter]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwBudget]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spLeafNode]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[gmwithlevel]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[spLeafNodeValues]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spPostings_Detail]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwShopSplSettlementDetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwHQDNSettlementDetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwshopcustomercreditnotes]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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].[vwShopInvSettlementDetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwShopSerSettlementDetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwRecSettlementDetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwGodownExpirywiseStock]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwDespatchArrival]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwDespatchOutQty]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwMonthlyTenantutilityBills]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwRommapartmentOccupancydtls]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
---------------*****************************-------------------------------------
--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].[vwapartmentrommcheckout]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwHPSettlements]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*           
--------------------------------------------------------------------------------             
 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].[Vwjournalswithcontrolaccs]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[SpLmsDetails]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetRegistaion]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
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
GO
/****** Object:  StoredProcedure [dbo].[SpLmsDeleteCardRegistation]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE Procedure [dbo].[SpLmsDeleteCardRegistation]
@CardRegistrationID as int
as

Delete from      LMSCardRegistration where CardRegistrationID=@CardRegistrationID
GO
/****** Object:  StoredProcedure [dbo].[SpLmsRewardsearch]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
---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
GO
/****** Object:  StoredProcedure [dbo].[SpLmsInsertCardRegistation]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
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
GO
/****** Object:  StoredProcedure [dbo].[spLlmsGetCard]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
create procedure [dbo].[spLlmsGetCard]
as
select CardRegistrationID,CardNumber from LMSCardRegistration
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetShowDetails]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
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)
GO
/****** Object:  StoredProcedure [dbo].[SpLmsUpdateCardRegistation]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
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
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetReward]    Script Date: 04/16/2012 10:32:41 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetRegistatioDetails]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
create procedure [dbo].[SpLmsGetRegistatioDetails]
@CardRegistrationID as int
As

select * from LMSCardRegistration  where CardRegistrationID=@CardRegistrationID
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetRewards]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
create procedure [dbo].[SpLmsGetRewards]
@RewardId as int 
as

select * from LMSReward where RewardId=@RewardId
GO
/****** Object:  StoredProcedure [dbo].[SpLMsUpateRewardPoint]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
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
GO
/****** Object:  StoredProcedure [dbo].[SpLmsDeleteReward]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
create procedure [dbo].[SpLmsDeleteReward]
@RewardId as int
as 
delete from LMSReward where  RewardId=@RewardId
GO
/****** Object:  View [dbo].[vwlosDebitCreditNote]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  StoredProcedure [dbo].[spInsertListItemDetails]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spDeleteListItemDetails]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-----------------------------------------------------------------------------------------------------------------------------          
--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
GO
/****** Object:  View [dbo].[vwhpPDChequeRegistry]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
---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].[vwHpCustomerDetails]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----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].[vwHPAgreement]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwHpChequeReceived]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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:  StoredProcedure [dbo].[spUpdateTillBalance]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------
--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
GO
/****** Object:  View [dbo].[vwreexportinvoices]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
----------------------------------------------------------------
--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:  StoredProcedure [dbo].[spULReexport]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  View [dbo].[vwHPOutstandingAmount]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*          
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:  View [dbo].[vwhpunsettledProcessing]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwHPAccountPayment]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  View [dbo].[vwHPinvoices]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*      
 Created by :  Shinu      
 Created on : 12/12/2007        
 Modified by :       
 Modified on :        
 Purpose      : To Get all the hire purchase Receivables of customers        
 */        
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,        
 hpqhinstprice as InvAmt ,'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         
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        
        
UNION ALL        
        
SELECT         
 LIH.hpqhCompanyID, hpqhshopid, a.DepartmentID, LIH.hpqhQuotationID, LIH.hpqhcustomerid,         
 LIH.hpqhQuotationDate, LIH.hpqhQuotationNo,'', LIH.hpqhremarks,        
 hpqhinstprice as InvAmt ,'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         
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        
      
union all        
        
SELECT         
 LIH.hpqhCompanyID, hpqhshopid, a.DepartmentID, LIH.hpqhQuotationID, LIH.hpqhcustomerid,         
 LIH.hpqhQuotationDate, LIH.hpqhQuotationNo,'', LIH.hpqhremarks,        
 hpqhinstprice as InvAmt ,'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         
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           
        
union all        
       
SELECT         
 LIH.hpqhCompanyID, hpqhshopid, a.DepartmentID, LIH.hpqhQuotationID, LIH.hpqhcustomerid,         
 LIH.hpqhQuotationDate, LIH.hpqhQuotationNo,'', LIH.hpqhremarks,        
 hpqhinstprice as InvAmt ,'>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         
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           
      
-- 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].[vwhpSettlementDetails]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwHPcustomersummaryasdate]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*        
 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].[vwhpReceiptDetails]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwshoppurchasePayments_OLD]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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].[vwHQAccinterdevbillPayments]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwposBillsettlementpay]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwHQAccBillPaidDetails]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwHQLCPaidDetails]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwaccBillsettlementpay]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwHPSettiementReceipts]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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].[vwhpReceipt]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  StoredProcedure [dbo].[spMag_LocationwiseStock]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spDeletePOSdummyDetail]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------------------------------    
--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
GO
/****** Object:  StoredProcedure [dbo].[spInsertPOSdummyDetail]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwShopPurchaseReturn]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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].[vwArrivalGdnToshop]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwSellingPrice]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  StoredProcedure [dbo].[SpServiceAlerts]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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
GO
/****** Object:  View [dbo].[vwGetWarntyDtlsForReplacedItem]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  StoredProcedure [dbo].[spcustomerwiseservices]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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
GO
/****** Object:  View [dbo].[vwserbookconditions]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwItemRetailPackingPricelist]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwshopitemshipmentdetailPU]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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].[vwShopItemShipmentDetailSegmentWise]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------     
  
   
-- 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].[vwshopitemshipmentdetailcompany]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  Trigger [TRIGGER_UPDATE_ITEMPRICEHISTORY]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		VinothMurugan V.
-- Create date: 07/08/2010
-- Description:	Update Item Price History When losShopitemShipmentDetail is Updated.
-- =============================================
CREATE TRIGGER [dbo].[TRIGGER_UPDATE_ITEMPRICEHISTORY] ON [dbo].[losShopItemShipmentDetail] 
   AFTER  INSERT,DELETE,UPDATE
AS 
BEGIN
	
	SET NOCOUNT ON;
   
	DECLARE @ItemId AS INT,
			@PackId AS INT,
			@ShopId AS INT,
			@SegmentId AS INT,
			@CurrencyId AS INT,
			@SellingPrice AS NUMERIC(18,2),
			@DiscountPrice AS  NUMERIC(18,2),
			@WholesalePrice AS NUMERIC(18,2),
			@CreditSP AS NUMERIC(18,2),
			@CreditDP AS NUMERIC(18,2),
			@CreditWP AS NUMERIC(18,2),
			@FixDate AS DATETIME,
			@UpdateTime AS DATETIME,
			@UserId AS NUMERIC(18,2),
			@CompanyId AS NUMERIC(18,2),
			@FinancialId AS NUMERIC(18,2),
			@rowguid AS NUMERIC(18,2)

	SET @UpdateTime = (SELECT GETDATE())

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

	FROM   losShopitemShipmentDetail


INSERT INTO ItemPriceHistory(ItemId,PackId,	ShopId,SegmentId,CurrencyId,SellingPrice,DiscountPrice,
							 WholesalePrice,CreditSP,CreditDP,CreditWP,FixDate,UpdateTime,UserId,CompanyId) 
		VALUES(@ItemId ,@PackId,@ShopId,@SegmentId ,@CurrencyId ,@SellingPrice ,@DiscountPrice ,
			@WholesalePrice ,@CreditSP ,@CreditDP ,	@CreditWP,@FixDate,@UpdateTime,	@UserId ,@CompanyId )
  

END
GO
/****** Object:  View [dbo].[vwAllMergeDetails]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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].[vwAllMergeHeader]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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:  UserDefinedFunction [dbo].[fnHQPurchaseorder]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*            
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
GO
/****** Object:  View [dbo].[vwPurchaseAmount]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwItemOrderedInPO]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spMagnolia_ExchangeRateHistory]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwHPDummyQuotationReport]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwdummyQuotationReport]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------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:  View [dbo].[vwHPInvoiceDetails]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
 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].[vwHPQuotationReport]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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:  View [dbo].[vwbookingservinvoices]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  StoredProcedure [dbo].[SpLmsGetpoint]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE procedure [dbo].[SpLmsGetpoint]

@PointsID as int
as
select  * from LmsPoint where PointsID=@PointsID
GO
/****** Object:  StoredProcedure [dbo].[SpLmsGetPoints]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
create procedure [dbo].[SpLmsGetPoints]
as
select PointsID,PointDesc from LmsPoint
GO
/****** Object:  StoredProcedure [dbo].[SpLmsDeletePoint]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CrEATE PROCEDURE [dbo].[SpLmsDeletePoint]


@Point as int
as
delete from LmsPoint where PointsID=@Point
GO
/****** Object:  View [dbo].[vwRequestQuotationPurchase]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[purchsetracking]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[spUpdateLedgersPAndCBill]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 
-- 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
GO
/****** Object:  View [dbo].[vwPurchaseOrderReportHdr]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[vwPurchaseOrderReportHdr] AS      
	SELECT PoHdr.pohPoid,PoHdr.pohDepartmentid,PS.CompanyId,PS.ReportLogo
	FROM lopurchaseorderheader PoHdr,aPackageSettings PS
GO

/****** Object:  View [dbo].[vwquotationtracking1]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwquotationtracking2]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwPurchaseOrderTracking1]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwPurchaseOrderTracking2]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwPurchaseOrderTracking3]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwpurchasetransflow]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwpurchasebilltracking]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwPurchaseStatus]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  StoredProcedure [dbo].[spUpdateLEDgersPO]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwrqtohqforitem]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwGodownCloseDate]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spMag_DeleteDeliveryVerification]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================================================  
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spMag_SaveDeliveryVerificationHeader]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================================================  
-- 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
GO
/****** Object:  View [dbo].[vwShopCloseDate]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[spConvertequiamounttemp]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 

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


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

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

/****** Object:  View [dbo].[vwtotalpayablevedorwise]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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:  StoredProcedure [dbo].[spSalesCommissionPayment]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spSalesCommissionEligiblity]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spSalesPromotionDetails]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spSalesCommissionTrans]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-----------------------------------------------------------------
--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
GO
/****** Object:  StoredProcedure [dbo].[spSalesCommissionDetail]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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'
GO
/****** Object:  View [dbo].[vwcurrexrateagainstcompcurr]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spMagnolia_GetExchangeRates]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------      
--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
GO
/****** Object:  View [dbo].[vwcurrexrateagainstInventorycurr]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[vwpaymentlisting]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwAssetTransfer]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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:  UserDefinedFunction [dbo].[fnGetExchangeRates]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[SpLmGetCurrency]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[SpLmGetCurrency]

as

select CurrencyID,CurrencyName from aCurrencyMaster
GO
/****** Object:  StoredProcedure [dbo].[spcustomeritemorbrandsold]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
GO

/****** Object:  StoredProcedure [dbo].[spSalesCommission]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwpaymentCLbankwise]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwtotalreceivablecustwise]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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].[vwprePurchaseOrderTracking1]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------
--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:  StoredProcedure [dbo].[spDebtorAgeSum_EmailClient]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------  
-- 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
GO
/****** Object:  StoredProcedure [dbo].[SendSMS]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================            
-- 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
GO
/****** Object:  View [dbo].[vwserialnogodownstock]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwSerialNoArrival]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------    
/*    
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].[vwGodownExchangerateDetails]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[spDebtorAgeSumForAgeing]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwShopExchangerateDetails]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwserialnoissuegodownstock]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwSerialNofetch]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------  
/*  
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:  UserDefinedFunction [dbo].[fnIssueSerialNosForSpINV]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------        
-- 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
  ---------------------------------------------------------------
GO
/****** Object:  View [dbo].[vwAssetTransferHistory]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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:  StoredProcedure [dbo].[spUpdateLEDgersDepreciation]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwjournaldebitcreditamt]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------------
-- 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].[vwSales]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwpdcpayments]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwpostdatedreceipts]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwNewJournalDetails]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwpostdatedpayments]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[sp_TargetAchievement]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwNewJournalDetails_GST]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwJournalDetailOneName]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwJournalParticulars]    Script Date: 04/16/2012 10:32:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwpaymentandreceipt]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[sp_BudgetUtilization]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  StoredProcedure [dbo].[spPostingTransactionwise]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwreceiptvouchercreditdetails]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwReceiptDetailsCredit]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwJournalCheckList]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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].[vwContraCheckList]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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].[vwBillsCheckListInterDiv]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
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].[vwPaymentCheckList]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
 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].[vwcustomercategory]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  Trigger [CRMInsertAccounts]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE trigger [dbo].[CRMInsertAccounts]
on [dbo].[aCustomerMaster]
AFTER Insert
as
BEGIN
declare @CustomerID as int
select @CustomerID=case isnull(max(CustomerID),0) when 0 then 1 else max(CustomerID)+1 end  from [dbo].CrmCustomerMaster      
INSERT INTO dbo.CrmCustomerMaster
(
	CustomerID,CompanyID,CustomerName,Active,Address1,Address2,Address3,CityID,PhoneNo,FaxNo,EmailID,CurrencyID,
	CountryID,custdob,webadd,CreditLimit,registerdate,CusGroupId,MasterApllicationCustomerId,Deleted
)
select @CustomerID,CompanyID,CustomerName,Active,Address1,Address2,Address3,CityID,PhoneNo,FaxNo,EmailID,
	CurrencyID,CountryID,custdob,webadd,CreditLimit,registerdate,CusGroupId,CustomerID,0
 from INSERTED
end
GO
/****** Object:  Trigger [CRMUpdateAccounts]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE trigger [dbo].[CRMUpdateAccounts]  
	on [dbo].[aCustomerMaster]  
	after update  
	as  
		if update(customerid)  
		BEGIN  
			update dbo.CrmCustomerMaster  
			set  
				CustomerName=up.CustomerName,  
				Address1=up.Address1,  
				Address2=up.Address2,  
				Address3=up.Address3,  
				CityID=up.CityID,  
				PhoneNo=up.PhoneNo,  
				FaxNo=up.FaxNo,  
				EmailID=up.EmailID,  
				CurrencyID=up.CurrencyID,  
				CountryID=up.CountryID,  
				custdob=up.custdob,  
				webadd=up.webadd,  
				CreditLimit=up.CreditLimit,  
				CusGroupId=up.CusGroupId  
			from acustomermaster up  
			where  up.customerid=CrmCustomerMaster.MasterApllicationCustomerId  
		end
GO
/****** Object:  View [dbo].[vwjournaldetails]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[SendEmails]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================            
-- Author:  Rajesh Kamalakshan            
-- Create date: 06-06-2009            
-- Description: For sending emails to customers            
-- =============================================            
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))          
          
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 @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)
set @table='<table style="font-family: ''''Arial'''', Times, serif">'          
set @Message='<table><tr style="background-color: #FFFF00; color: #FF0000"><td>Unable to send the mail to the customer, Email address for the customer was not found. You are requested to forward this mail manually.</td></tr></table> '+@table       
--set @table='<table style="font-family: ''''Courier New'''', Courier, monospace"><tr><td><img alt="" src="c:\editicon.png" /></td></tr>'          
set @cccEmail='accounts.male@fi-es.com;visam.hassan@fi-es.com '          
set @subject1='Over Due Paymentst-  '          
set @profile='Fies Automated Mail Service'          
set @Divisionhead=')'          
--set @Signature='<tr><td>Kind Regards<br>          
-- <br>Ikram Hazzan          
-- <br>Chief Executive Officer,          
-- <br>Panorama Comcare Pvt Ltd / Maldives,          
-- <br>1st Floor, Bangufadige ,          
-- <br>irumatheebai,           
-- <br>Majeedheemagu,          
-- <br>Maafannu,          
-- <br>Male'', Maldives,                   
-- <br>Mobile: +960 7773451          
-- <br>Fax     : +960 3310719         
-- <br>Phone : 960 3329232 (4 lines)          
-- <br>E-mail: ikram.hassan@fi-es.com          
-- <br>Skype: ikramhassan
-- <br>Skypein: USA: +1 247 789 7752  |   UK: 44 20 3286 9559  |  Hong Kong: +852 819 1277
-- <br>Web   : www.fi-es.com'          
--    +'</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>'          
select @CompanyName=Name,@CompanyTelephone=Phoneno,@Companyemail=emailid,@CompanyAddress1=address1,@CompanyAddress2=address2,@CompanyAddress3=address3,@CompanyFax=faxno from aCompanyMaster where CompanyID=@CompanyID
--select * from aCompanyMaster
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=''
  set @amount=0
  select @departmentid=max(departmentid)from #Departments  
  select  @ccEmail=InchargeEmail,@Divisionhead=InchargeName from adepartmentmaster where  departmentid=@departmentid and companyId=@CompanyID       
  ------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          
  set @CopycEmail=   @ccEmail+';'+@cccEmail
  if @amount>0          
  begin       
	if @EmailID is null or @EmailID=''
    begin
		set @table=@Message
        set @EmailID=@ccEmail
    end
 set @Signature=''
 set @Signature='<tr><td>Kind Regards<br>          
 <br>'+@Divisionhead+
 '<br>Division Incharge,          
 <br>'+@CompanyName+
 '<br>'+@CompanyAddress1+
 '<br>'+@CompanyAddress2+
 '<br>'+@CompanyAddress3+
 '<br>Phone : '+@CompanyTelephone+
 '<br>Fax   : '+@CompanyFax+
 '<br>E-mail: '+@Companyemail
    +'</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>'          
   set @body1 = @table+'<tr><td>Date '+cast( left(getdate(),11) as varchar(50))+'<br><br></td></tr><tr><td>Dear '+@CustomerName +',<br><br></td></tr>'+@Address+          
   '<tr><td><u>Sub:Over Due Payments –  '+@departmentname+ ' '+@currencysymbol +' ' +cast(@amount as varchar(50)) +'</u><br><br></td></tr><tr><td>Greetings from Panorama Comcare Pvt Ltd / Fi-es Systems Pvt Ltd………….<br><br></td></tr><tr><td> If you have made the payment please inform me by return mail with the receipt number.<br><br></td></tr><tr><td>I would like to bring to your kind notice; we have  '+ @currencysymbol +' ' +cast(@amount as varchar(50)) +' overdue in our records.<br><br></td></tr>    <td><tr> We would request you to kindly settle the due amount urgently. We prefer to receive the due amount in <b>invoiced currency</b>.<br><br></td></tr><tr><td>Please contact 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.<br><br></td></tr><tr><td>Thanking you in advance for your immediate attention to this request.<br><br></td></tr>'+@Signature    
   set @subject1=@subject1+@DepartmentName 
   EXEC msdb.dbo.sp_send_dbmail @recipients=@EmailID,@copy_recipients=@CopycEmail,          
   @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>Dear '+@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)) +' 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          
--   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 for 60 to 75 days days   
--  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>Dear '+@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 attached  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
--   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 for 75 days          
--  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>Dear '+@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          
--   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 for 90 days     
-- 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>Dear '+@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 that you have an overdue debt of   '+ @currencysymbol +' ' +cast(@amount as varchar(50)) +'.<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 payment 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    
--   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 for 100 days   
--  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>Dear '+@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)) +'.<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 SIMDI Company divisions 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          
--   set @subject1=@subject1+@DepartmentName  
--   EXEC msdb.dbo.sp_send_dbmail @recipients=@EmailID,@copy_recipients=@ccEmail,          
--   @subject = @subject1,          
--   @body = @body1,          
--   @body_format = 'HTML',          
--   @profile_name=@profile,@importance ='High'          
--  end          
--  --------------------------------------------------------------------------------------------------------------          
 delete from #MailListCustomerwise where departmentid=@departmentid          
 delete from #Departments where departmentid =@departmentid          
 end          
    delete from #Departments          
 drop table  #MailListCustomerwise           
 delete from #MailList where customerid=@customerid           
--select * from #MailList          
--print @body1          
end          
END            
          
--msdb.dbo.sysmail_start_sp
GO
/****** Object:  StoredProcedure [dbo].[spDeleteFlightOperator]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateFlightOperator]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------
--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
GO
/****** Object:  StoredProcedure [dbo].[spInsertFlightOperator]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------
--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
GO
/****** Object:  StoredProcedure [dbo].[spMonthsalesall]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------

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

--------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[spMonthSalesShopWise]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
GO
/****** Object:  View [dbo].[vwPurchaseBillNotCosted]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-------------------------------------------------------------------------------------------------------------
--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:  StoredProcedure [dbo].[SpMag_FetchDepartments]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spTotalTax]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
GO
/****** Object:  StoredProcedure [dbo].[spWeekSalesShopWise]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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'
GO
/****** Object:  StoredProcedure [dbo].[spvendoroutstanding]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_SaveReport]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
----------------------------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetByIdRepost]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
-----------------------------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetRepost]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[SpEmail_GetRepost]
	@CompanyId int
as
begin
	select * from dbo.PIS_EmailScheduler where companyid=@CompanyId
end
-----------------------------------------------------------------------------------------------------------------
GO
/****** Object:  View [dbo].[vwbillvendorcurrency]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwVendorCategory]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE view [dbo].[vwVendorCategory] as  select distinct VendorCategory ,companyid  from AVendorMaster where isnull(VendorCategory,'')<>''
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_SaveRecepients]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
----------------------------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_DeleteRecepients]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[SpEmail_DeleteRecepients] 
	@ReportId  int,
	@CompanyId  int
as
begin
	DELETE FROM [dbo].[PIS_EmailSchedulerRecepients]
      WHERE ReportId=@ReportId and CompanyId=@CompanyId
end
-----------------------------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_GetByIdRepostParameter]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
-----------------------------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_SaveReportParameter]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
----------------------------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_DeleteReportParameter]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[SpEmail_DeleteReportParameter] 
	@ReportId  int,
	@CompanyId  int
as
begin
	DELETE FROM [dbo].[PIS_EmailSchedulerReportParameter]
      WHERE ReportId=@ReportId and CompanyId=@CompanyId
end
-----------------------------------------------------------------------------------------------------------------
GO
/****** Object:  View [dbo].[vwHQAccinterdevBills]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwServiceInvoice]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------------------------------------------  
----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:  StoredProcedure [dbo].[SpEmail_GetSettings]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
----------------------------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[SpEmail_SaveSettings]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
----------------------------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[spDeleteFlights]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------
--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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateFlights]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------
--Created on 	: 08/Oct/2010
--Created by	: Praveen S
--Comments	: For Updating the Details of Flights
------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[spUpdateFlights]
@flghtopcompanyid INT,
@flghtid INT,
@prevflghtopid INT,
@flghtopid INT,
@flghtno VARCHAR(50),
@flghtdepday INT,
@flghtdeptime DATETIME,
@flghtremarks VARCHAR(250),
@flghtactive BIT
AS BEGIN
	 SET NOCOUNT ON

	 UPDATE Flights
	 SET FlightNo = @flghtno,FlightDepDay = @flghtdepday,
 	 FlightDepTime = @flghtdeptime,Remarks=@flghtremarks,Active=@flghtactive, 
	 FlightOpid = @flghtopid
	 WHERE FlightOpid = @prevflghtopid AND FlightID = @flghtid AND companyid = @flghtopcompanyid
	 SET NOCOUNT OFF

END
GO
/****** Object:  StoredProcedure [dbo].[spInsertFlights]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------
--Created on 	: 08/Oct/2010
--Created by	: Praveen S
--Comments	: For Inserting the Details In Flights
------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[spInsertFlights]
@flghtopcompanyid INT,
@flghtid INT,
@flghtopid INT,
@flghtno VARCHAR(50),
@flghtdepday INT,
@flghtdeptime DATETIME,
@flghtremarks VARCHAR(250),
@flghtactive BIT
AS BEGIN
	 SET NOCOUNT ON

	 INSERT INTO Flights(companyid,FlightID,FlightOpid,FlightNo,FlightDepDay,FlightDepTime,Remarks,Active)
	 VALUES
	 (@flghtopcompanyid,@flghtid,@flghtopid,@flghtno,@flghtdepday,@flghtdeptime,@flghtremarks,@flghtactive)		
	 SET NOCOUNT OFF
END
GO

/****** Object:  View [dbo].[vwTargetActualAnalysismax]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  UserDefinedFunction [dbo].[GetIndexColumns]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwTargetAllocationdetails]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwHpShopReceipt]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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].[vwhpAdvanceReceived]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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].[vwHPAdvaneShopReceipt]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/*    
 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].[vwJournalPostAmount]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwshoppurchaseBills]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwShopPurchaseBillsPaid]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwDishIngrdItems]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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:  StoredProcedure [dbo].[spDateCheck]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
GO
/****** Object:  View [dbo].[vwDiscountSales]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------------------------------      
--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].[spPosMasterFetch]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
------------------------------------------------------------  
---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
GO
/****** Object:  View [dbo].[vwHqPurchaseBills]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwShopHPInvoiceSettlementNo]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- 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].[vwDeparmentBinCardAudit]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwPandCInquiryGodownStock]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwShopGodownDepWise]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[spGodownExpiryStock]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spGodownLocationStock]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spReorderLevelForecasting]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[sptempinsert]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_GetPackagesettings]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================      
-- 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
GO
/****** Object:  View [dbo].[vwGlobalAccounts]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[spInventoryForecast]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------                      
-- This stored procedure is going to be useed to generate Inventory Forecast report                      
-- This report model is given by Echocam                      
--------------------------------------------------------------------------------                      
-- Coded By: Regin T.                      
-- Coded On: 16-04-2009        
--Modified By : YOgesh Joe      
--Modified On :12-05-2009                    
--------------------------------------------------------------------------------                      
-- spInventoryForecast 10      -- 6 Months                       
-- spInventoryForecast 100, 1,'',''3,4,5,6,7,8','1,2,3,4,5,6,7,8,9' -- 100 Days                      
/*                      
User may select one of the below options                      
Parameter: Stock Out in                       
 Next 3 months (A)                      
 Next 6 months (A)                      
 Next 9 months (A)                      
 Next 12 months (A)                      
 No of Days (A)                      
*/                    
CREATE  proc [dbo].[spInventoryForecast]                       
 @intDuration        as int,  -- the number of months/days. e.g. 3 if user selects Stock Out In 3 Months                      
 @bitDurationInDays  as int = 0, -- 1 if duration is in days, 0 if duration is in months                      
 @strDepartmentId as varchar(50),        
 @strCategoryId as varchar(50)        
as                      
begin  -- procedure begins                      
                      
 set nocount on                       
 declare @ItemId as nvarchar(2000),        
   @GodownId as nvarchar(2000),        
   @ShopId as nvarchar(2000),        
   @strSQL as nvarchar(2000)                      
 declare @dtPackageDate   as datetime                      
 declare @intNoOfSaleDays as int                        
 declare @intDays1 as int                        
 declare @intDays2 as int -- Stores the days inbetween the reporting date and the selected future date                      
 declare @intDays3 as int                        
 declare @Monthname1 as varchar(10),                  
   @Monthname2 as varchar(10),                  
   @Monthname3 as varchar(10),                  
   @Monthname4 as varchar(10),                  
   @Monthname5 as varchar(10),                  
   @Monthname6 as varchar(10),                  
   @Monthname7 as varchar(10),                  
   @Monthname8 as varchar(10),                  
   @Monthname9 as varchar(10),                  
   @Monthname10 as varchar(10),                  
   @Monthname11 as varchar(10),                  
   @Monthname12 as varchar(10),                  
   @BeforeSelected as varchar(25),                
   @Selected as varchar(25),                
   @AfterSelected as varchar(25),                
   @DayORMonth as varchar(10)                
                
 -- Below variables store the beginning day of the respective months                       
 declare                        
   @dtMonthCurrent as datetime,                      
   @dtMonthOne     as datetime,                      
   @dtMonthTwo     as datetime,                      
   @dtMonthThree   as datetime,                      
   @dtMonthFour    as datetime,                      
   @dtMonthFive    as datetime,                      
   @dtMonthSix     as datetime,                      
   @dtMonthSeven   as datetime,                      
   @dtMonthEight   as datetime,                      
   @dtMonthNine    as datetime,                      
   @dtMonthTen     as datetime,                      
   @dtMonthEleven  as datetime,                      
   @dtMonthTwelve  as datetime                      
                      
 create table #CurrentStock (                      
         csItemID int,  -- Current Stock Item ID                      
         csStock  numeric(18,2)  
        )-- Current Stock Stock                       
 create table #OrderedItems (                      
         oiItemID     int,  -- Ordered Items Item ID                      
         oiOrderedQty numeric(18,2)  
        )                        
 create table #AverageSale (                      
         asItemID     int,                       
         asAvgSaleQty numeric(18,2)  
        )  
 create table #MonthSale1 (                     
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
 create table #MonthSale2 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
 create table #MonthSale3 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
 create table #MonthSale4 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
 create table #MonthSale5 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
 create table #MonthSale6 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
 create table #MonthSale7 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
 create table #MonthSale8 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
 create table #MonthSale9 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
 create table #MonthSale10 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
 create table #MonthSale11 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
 create table #MonthSale12 (                      
         msItemID  int,                 
         msSaleQty numeric(18,2)  
        )  
 select @dtPackageDate = PackageDate from aPackageSettings                      
                      
 -- I. Getting the total stock in all locations of the company  -- Starts          
 create table #ItemIdTable ( ItemId int )        
 create table #ShopIdTable ( ShopId int )        
 create table #GodownIdTable (   GodownId int )        
 create table #DepartmentIdTable ( DepartmentID int )        
 if @strCategoryId<>''        
  begin        
   set @strSQL=N'        
   insert into #ItemIdTable        
   select ItemId from aitem where ItemCategoryID in ('+ @strCategoryId +')'        
   exec sp_executesql @strSQL        
  end        
 else        
  begin        
   insert into #ItemIdTable select ItemId from aitem         
  end        
        
 if @strDepartmentId<>''         
  begin        
   set @strSQL=N'        
   insert into #ShopIdTable         
   select ShopID from ashops where DepartmentID in('+ @strDepartmentId +')'         
   exec sp_executesql @strSQL        
     
   set @strSQL=N'        
   insert into #GodownIdTable        
   select GodownID from aGodown where DepartmentID in('+ @strDepartmentId +')'               
   exec sp_executesql @strSQL        
         
   set @strSQL=N'        
   insert into #DepartmentIdTable        
   select DepartmentID from adepartmentmaster where DepartmentID in('+@strDepartmentId+')'        
   exec sp_executesql @strSQL        
  end        
 else        
  begin        
   insert into #ShopIdTable select ShopID from ashops        
   insert into #GodownIdTable select GodownID from aGodown        
   insert into #DepartmentIdTable select DepartmentID from adepartmentmaster        
  end        
      
 insert into #CurrentStock                      
  select ItemID, sum(stock) Stock                      
  from               
  ( -- All Shop Stocks             
   select s.itemid ItemID, s.shopid LocationID, sum(s.stock) as Stock                       
   from  vwInquiryShopStock s          
   where s.itemid in (select * from #ItemIdTable)        
    and  s.shopid in(select * from #ShopIdTable)                  
   GROUP BY s.shopid, s.itemid                      
                      
   union all                      
                      
   -- All Godown Stocks                      
   select gsitemid ItemID, gsGodownid LocationID, sum(gsstock) as Stock                      
   from vwInquiryGodownStock g        
   where g.gsitemid in (select * from #ItemIdTable)        
    and  g.gsGodownid in(select * from #GodownIdTable)               
   GROUP BY gsitemid, gsgodownid                      
  )a   
  group by ItemID                      
                    
  -- I. Getting the total stock in all locations of the company  -- Ends                       
        -- II. Finding the Purchase Ordered Quantities  -- Starts                       
                      
 insert into #OrderedItems                      
  select                
   podItemID, sum(podQty*Quantity) OrderedItemQty                       
  from        
   loPurchaseOrderHeader                       
   left outer join loPurchaseOrderDetail on  pohPoid=podPoid        
   left outer join aItem i on i.ItemID = podItemID                       
   left outer join aPackingTypeCapacityDetail c                       
   on c.PackingTypeID = podPackingTypeID and c.UnitsID = i.UnitsID                      
  where     
   podPOID in (  
       select pohPOID from loPurchaseOrderHeader                       
       where pohbillgenerated=0 and pohpoid<>0 and pohcompanyid=1                       
        and pohcancel=0 AND left(pohtype,1)='P' and pohpoonhold = 0  
      )        
   and podItemID in (select * from #ItemIdTable)        
   and pohDepartmentid in (select * from #DepartmentIdTable)        
   group by podItemID        
 -- II. Finding the Purchase Ordered Quantities  -- Ends                      
 -- III. Calculating the sale in the last 12 months -- Starts --                      
 -- Beginning of the current month                      
 set @dtMonthCurrent = dateadd("m", 0, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                      
                 
 -- Beginning of of 1st previous month                      
 set @dtMonthOne = dateadd("m", -1, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                      
                      
 -- Beginning of the 2nd previous month                      
 set @dtMonthTwo = dateadd("m", -2, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                      
                      
 -- Beginning of the 3rd previous month                      
 set @dtMonthThree = dateadd("m", -3, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                      
                       
 -- Beginning of the 4th previous month                      
 set @dtMonthFour =  dateadd("m", -4, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                      
                       
 -- Beginning of the 5th previous month                      
 set @dtMonthFive = dateadd("m", -5, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                      
                       
 -- Beginning of the 6th previous month                      
 set @dtMonthSix = dateadd("m", -6, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                      
                      
 -- Beginning of the 7th previous month                      
 set @dtMonthSeven = dateadd("m", -7, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                      
                       
 -- Beginning of the 8th previous month                      
 set @dtMonthEight = dateadd("m", -8, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))            
                       
 -- Beginning of the 9th previous month                      
 set @dtMonthNine = dateadd("m", -9, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                      
                       
 -- Beginning of the 10th previous month                      
 set @dtMonthTen = dateadd("m", -10, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                      
                       
 -- Beginning of the 11th previous month                      
 set @dtMonthEleven = dateadd("m", -11, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                      
                       
 -- Beginning of the 12th previous month                      
 set @dtMonthTwelve = dateadd("m", -12, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                      
                      
 -- Sale in the 1st previous month                      
 insert into #MonthSale1                      
  select                       
   posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                   
  from vwShopItemSales                       
  where                      
   poshBilldate >= @dtMonthOne and poshBilldate < @dtMonthCurrent         
   and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                   
  group by posdItemID                      
 -- Sale in the 2nd previous month                      
 insert into #MonthSale2                      
  select                       
   posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
  from vwShopItemSales                       
  where                      
   poshBilldate >= @dtMonthTwo and poshBilldate < @dtMonthOne         
   and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                   
   group by posdItemID                     
                      
 -- Sale in the 3rd previous month                      
 insert into #MonthSale3                      
  select                       
   posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
  from vwShopItemSales                       
  where                      
   poshBilldate >= @dtMonthThree and poshBilldate < @dtMonthTwo         
   and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                     
  group by posdItemID        
                     
 -- Sale in the 4th previous month                     
 insert into #MonthSale4                      
  select                       
   posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
  from vwShopItemSales                       
  where                      
   poshBilldate >= @dtMonthFour and poshBilldate < @dtMonthThree                      
  and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)         
  group by posdItemID     
                    
 -- Sale in the 5th previous month                      
 insert into #MonthSale5                      
  select                       
   posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
  from vwShopItemSales                       
  where                      
   poshBilldate >= @dtMonthFive and poshBilldate < @dtMonthFour                      
   and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)         
  group by posdItemID        
                    
 -- Sale in the 6th previous month                      
 insert into #MonthSale6                      
  select                       
   posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
  from vwShopItemSales                       
  where                      
   poshBilldate >= @dtMonthSix and poshBilldate < @dtMonthFive                      
   and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)         
  group by posdItemID        
                                 
 -- Sale in the 7th previous month                      
 insert into #MonthSale7               
  select                       
   posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
  from vwShopItemSales                       
  where                      
   poshBilldate >= @dtMonthSeven and poshBilldate < @dtMonthSix         
   and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                      
  group by posdItemID                      
                         
 -- Sale in the 8th previous month                      
 insert into #MonthSale8                      
  select                       
   posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
  from vwShopItemSales    
  where                      
   poshBilldate >= @dtMonthEight and poshBilldate < @dtMonthSeven                      
   and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)           
  group by posdItemID                      
 -- Sale in the 9th previous month                      
 insert into #MonthSale9                      
  select                       
   posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
  from vwShopItemSales                       
  where                      
   poshBilldate >= @dtMonthNine and poshBilldate < @dtMonthEight                      
   and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)           
   group by posdItemID                     
                       
 -- Sale in the 10th previous month                      
 insert into #MonthSale10                      
  select                       
   posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
  from vwShopItemSales                       
  where                      
   poshBilldate >= @dtMonthTen and poshBilldate < @dtMonthNine                      
   and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)          
  group by posdItemID                      
                    
 -- Sale in the 11th previous month                      
 insert into #MonthSale11                      
  select                       
   posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
  from vwShopItemSales                       
  where                      
   poshBilldate >= @dtMonthEleven and poshBilldate < @dtMonthTen                      
   and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)        
  group by posdItemID   
     
 -- Sale in the 12th previous month                      
 insert into #MonthSale12                      
  select                       
   posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale   
  from vwShopItemSales                  
  where                      
   poshBilldate >= @dtMonthTwelve and poshBilldate < @dtMonthEleven                      
   and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)        
  group by posdItemID        
                   
 -- III. Calculating the sale in the last 12 months -- Ends --                      
    -- IV. Finding Average Sale -- Starts here --                      
 set @intNoOfSaleDays = datediff("d",@dtMonthTwelve,@dtMonthCurrent)                      
 --set @intNoOfSaleDays = datediff("d",convert(datetime,@strSaleStartDate),convert(datetime,@strSaleEndDate))                      
 insert into #AverageSale                      
  select                       
   posdItemID ItemID,                       
   case                       
    when @intNoOfSaleDays = 0 then 0                     
    else                        
     convert(numeric(18,2),sum(posdquantity)/@intNoOfSaleDays)                       
   end AvgSale                      
  from vwShopItemSales                       
  where                       
   poshBilldate >= @dtMonthTwelve and poshBilldate < @dtMonthCurrent         
   and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                     
  group by posdItemID        
                
 -- IV. Finding Average Sale -- Ends here --                      
                      
 -- V. Counting the days inbetween the reporting date and the future date  -- Starts                      
 if @bitDurationInDays = 1 -- If duration is specified in days                      
  begin                      
   set @intDays1 = @intDuration - 90  -- before 3 months                      
   if @intDays1 < 0 set @intDays1 = 0                      
   set @intDays2 = @intDuration                      
   set @intDays3 = @intDuration + 90  -- after 3 months                      
  end                      
 else                      -- If duration is specified in months                      
  begin                      
   set @intDays1 = datediff("d", @dtPackageDate, dateadd("m", @intDuration-3, @dtPackageDate))                        
   if @intDays1 < 0 set @intDays1 = 0                      
   set @intDays2 = datediff("d", @dtPackageDate, dateadd("m", @intDuration, @dtPackageDate))                        
   set @intDays3 = datediff("d", @dtPackageDate, dateadd("m", @intDuration+3, @dtPackageDate))                        
  end                      
 -- V. Counting the days inbetween the reporting date and the future date  -- Ends                      
 --VI.Making Before,Next and After Periods---Starts--                
 /*  
 select @DayOrMonth=case @bitDurationInDays when 1 then 'Days' when 0 then 'Months' end                
 select @Selected='Next'+space(1)+rtrim(ltrim(str(@intDuration)))+space(1)+rtrim(ltrim(@DayOrMonth))                
 if @DayOrMonth='Months'                
  begin                
   if (@intDuration-3) >0                
    begin                
     select @BeforeSelected='Next'+space(1)+ltrim(rtrim(str(@intDuration-3)))+space(1)+@DayOrMonth                
    end                
   else                
    begin                
     select @BeforeSelected='Next'+space(1)+'0'+space(1)+'Months'                
    end                
  end                
 else -- Days                
  begin                
   if (@intDuration-90) >0                
    begin                
     select @BeforeSelected='Next'+space(1)+ltrim(rtrim(str(@intDuration-90)))+space(1)+@DayOrMonth                
    end                
   else                
    begin                
     select @BeforeSelected='Next'+space(1)+'0'+space(1)+'Days'                
    end                
  end                
 if @DayOrMonth='Months'                
  begin                
   select @AfterSelected='Next'+space(1)+rtrim(ltrim(str(@intDuration+3)))+space(1)+rtrim(ltrim(@DayOrMonth))                
  end                
 else                
  begin                
   select @AfterSelected='Next'+space(1)+rtrim(ltrim(str(@intDuration+90)))+space(1)+rtrim(ltrim(@DayOrMonth))                
  end                
 */  
 /*  
 select @DayOrMonth=case @bitDurationInDays when 1 then 'D' when 0 then 'M' end                
 select @Selected=rtrim(ltrim(str(@intDuration)))  
 if @bitDurationInDays=0 -- Months                    
  begin                
   if (@intDuration-3) >0                
    begin                
     select @BeforeSelected=ltrim(rtrim(str(@intDuration-3)))  
    end                
   else                
    begin                
     select @BeforeSelected='0'  
    end                
  end                
 else -- Days                
  begin                
   if (@intDuration-90) >0                
    begin                
     select @BeforeSelected=ltrim(rtrim(str(@intDuration-90)))  
    end                
   else                
    begin                
     select @BeforeSelected='0'  
    end                
  end                
 if @bitDurationInDays=0 -- Months               
  begin                
   select @AfterSelected=rtrim(ltrim(str(@intDuration+3)))  
  end             
 else                
  begin                
   select @AfterSelected=rtrim(ltrim(str(@intDuration+90)))  
  end                
 */  
 --select @DayOrMonth=case @bitDurationInDays when 1 then 'D' when 0 then 'M' end                
 select @DayOrMonth=''  
 select @Selected=convert(varchar,@intDuration)--+' '+@DayOrMonth                
 if @bitDurationInDays=0 -- Months               
  begin                
   if (@intDuration-3) >0                
    begin                
     select @BeforeSelected=convert(varchar,@intDuration-3)+' '+@DayOrMonth                
    end                
   else                
    begin                
     select @BeforeSelected='0 '+@DayOrMonth               
    end                
  end                
 else -- Days                
  begin                
   if (@intDuration-90) >0                
    begin                
     select @BeforeSelected=convert(varchar,@intDuration-90)+' '+@DayOrMonth                
    end                
   else                
    begin                
     select @BeforeSelected='0 '+@DayOrMonth                
    end                
  end                
 if @bitDurationInDays=0 -- Months              
  begin                
   select @AfterSelected=convert(varchar,@intDuration+3)+' '+@DayOrMonth                
  end                
 else                
  begin                
   select @AfterSelected=convert(varchar,@intDuration+90)+' '+@DayOrMonth                
  end                
 --VI.Making Before,Next and After Periods---Ends--                       
 -- VII. Giving output -- Starts --                      
                  
 SELECT    
  @Monthname1=substring(upper(DATENAME(month, DATEADD(month, -1, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -1, PAckageDate)),3,2),              
  @Monthname2=substring(upper(DATENAME(month, DATEADD(month, -2, PAckageDate))),1,3) +'-'+  substring(DATENAME(year,DATEADD(month, -2, PAckageDate)),3,2),              
  @Monthname3=substring(upper(DATENAME(month, DATEADD(month, -3, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -3, PAckageDate)),3,2),              
  @Monthname4=substring(upper(DATENAME(month, DATEADD(month, -4, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -4, PAckageDate)),3,2),              
  @Monthname5=substring(upper(DATENAME(month, DATEADD(month, -5, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -5, PAckageDate)),3,2),              
  @Monthname6=substring(upper(DATENAME(month, DATEADD(month, -6, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -6, PAckageDate)),3,2),              
  @Monthname7=substring(upper(DATENAME(month, DATEADD(month, -7, PAckageDate))),1,3) +'-'+  substring(DATENAME(year,DATEADD(month, -7, PAckageDate)),3,2),              
  @Monthname8=substring(upper(DATENAME(month, DATEADD(month, -8, PAckageDate))),1,3) +'-'+  substring(DATENAME(year,DATEADD(month, -8, PAckageDate)),3,2),              
  @Monthname9=substring(upper(DATENAME(month, DATEADD(month, -9, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -9, PAckageDate)),3,2),              
  @Monthname10=substring(upper(DATENAME(month, DATEADD(month, -10, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -10, PAckageDate)),3,2),              
  @Monthname11=substring(upper(DATENAME(month, DATEADD(month, -11, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -11, PAckageDate)),3,2),              
  @Monthname12=substring(upper(DATENAME(month, DATEADD(month, -12, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -12, PAckageDate)),3,2)               
 From aPAckageSettings                  
                     
 select                       
  ItemID, ItemCode, ItemDescription, isnull(csStock,0) CurrentStock, isnull(oiOrderedQty,0) OrderedQty,                       
  isnull(csStock,0)+isnull(oiOrderedQty,0) CurrStockAndOrdered,  -- CS+O                      
  isnull(asAvgSaleQty,0) AverageSale,               
  convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays1) BalanceBefore3Months,                       
  convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays2) SufficientBalance,                      
  convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays3) BalanceAfter3Months,                      
  isnull(m12.msSaleQty,0) Month12, -- Oldest months are listed first                      
  isnull(m11.msSaleQty,0) Month11,                      
  isnull(m10.msSaleQty,0) Month10,                      
  isnull(m9.msSaleQty,0) Month9,                      
  isnull(m8.msSaleQty,0) Month8,                      
  isnull(m7.msSaleQty,0) Month7,                      
  isnull(m6.msSaleQty,0) Month6,                      
  isnull(m5.msSaleQty,0) Month5,                      
  isnull(m4.msSaleQty,0) Month4,                      
  isnull(m3.msSaleQty,0) Month3,                      
  isnull(m2.msSaleQty,0) Month2,                      
  isnull(m1.msSaleQty,0) Month1,              
  @Monthname12 Monthname12,              
  @Monthname11 Monthname11,              
  @Monthname10 Monthname10,              
  @Monthname9 Monthname9,                
  @Monthname8 Monthname8,              
  @Monthname7 Monthname7,              
  @Monthname6 Monthname6,              
  @Monthname5 Monthname5,              
  @Monthname4 Monthname4,                
  @Monthname3 Monthname3,              
  @Monthname2 Monthname2,              
  @Monthname1 Monthname1,              
  @Selected Selected,              
  @BeforeSelected BeforeSelected,              
  @AfterSelected AfterSelected                
 /*                      
 ,case                      
  when isnull(csStock,0)+isnull(oiOrderedQty,0) >= convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays2) then                      
  'Inventory OK' --If CS+O(Currennt Stock + Ordered Qty) is enough for given period                      
  when isnull(csStock,0)+isnull(oiOrderedQty,0) >= convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays1) then                      
  'Order Soon'  --If CS+O is not enough for the given period'                      
  else                      
  'Order Urgently' --If CS+O is not enough for even half of the given period                      
  end                      
 Suggestion                      
 */                      
 from                       
  aItem left outer join #CurrentStock on ItemID = csItemID                      
  left outer join #OrderedItems on ItemID = oiItemID                      
  left outer join #AverageSale on ItemID = asItemID                      
  left outer join #MonthSale12 m12 on ItemID = m12.msItemID                      
  left outer join #MonthSale11 m11 on ItemID = m11.msItemID                      
  left outer join #MonthSale10 m10 on ItemID = m10.msItemID                      
  left outer join #MonthSale9 m9 on ItemID = m9.msItemID                      
  left outer join #MonthSale8 m8 on ItemID = m8.msItemID                      
  left outer join #MonthSale7 m7 on ItemID = m7.msItemID                      
  left outer join #MonthSale6 m6 on ItemID = m6.msItemID                      
  left outer join #MonthSale5 m5 on ItemID = m5.msItemID                      
  left outer join #MonthSale4 m4 on ItemID = m4.msItemID                      
  left outer join #MonthSale3 m3 on ItemID = m3.msItemID                      
  left outer join #MonthSale2 m2 on ItemID = m2.msItemID                      
  left outer join #MonthSale1 m1 on ItemID = m1.msItemID                      
 where                      
  isnull(csStock,0)+isnull(oiOrderedQty,0) < isnull(asAvgSaleQty,0)*@intDays2 -- if CS+O is less than sufficient stock                      
 -- VI. Giving output -- Ends --                      
                      
 drop table #CurrentStock                      
 drop table #OrderedItems                      
 drop table #AverageSale                      
 drop table #MonthSale1                      
 drop table #MonthSale2                      
 drop table #MonthSale3                      
 drop table #MonthSale4                      
 drop table #MonthSale5                      
 drop table #MonthSale6                      
 drop table #MonthSale7                      
 drop table #MonthSale8                      
 drop table #MonthSale9                      
 drop table #MonthSale10                      
 drop table #MonthSale11                      
 drop table #MonthSale12                      
 drop table #ItemIdTable      
 drop table #ShopIdTable      
 drop table #GodownIdTable      
 drop table #DepartmentIdTable                      
 set nocount off                      
                      
end -- procedure ends                      
                      
-----------------------------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[spSalesAndCostValue]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
   
-- 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
GO
/****** Object:  StoredProcedure [dbo].[sPBasketSalesAnalysis]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[new1]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE view [dbo].[new1] 
as
select top 2 * from ashops order by shopid
GO
/****** Object:  View [dbo].[vwAllshops]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create view [dbo].[vwAllshops] as  
select shopid as sid,shopname as sname from ashops  
union   
select 0,'HQ'
GO
/****** Object:  StoredProcedure [dbo].[spShopLocationStock]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spShopExpiryStock]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 
-- 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
GO
/****** Object:  View [dbo].[vwshops]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[SP_FETCH_ASHOP]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_FetchShops]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================        
-- 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
GO
/****** Object:  StoredProcedure [dbo].[SP_MIS_GetCompanyImage]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[SP_MIS_GetCompanyImage]  
 as   
 begin  
 select CompImage from acompanyimagemaster  
 end
GO
/****** Object:  Trigger [delPayrollCompanyMaster]    Script Date: 04/16/2012 10:32:46 ******/
--/*SET ANSI_NULLS ON
--GO
--SET QUOTED_IDENTIFIER OFF
--GO
--/*  
-- Created by :  R Harikrishnan  
-- Created on : 17/12/2002  
-- Purpose      : To Delete Payroll pCompanyMaster table when there is a Delete in Admiv2 aCompanyMaster Table  
--*/  
--CREATE TRIGGER [dbo].[delPayrollCompanyMaster]   
--ON [dbo].[aCompanyMaster]  
--FOR Delete as  
--Begin  
-- declare @CompanyID as int  
-- select @CompanyID=CompanyID from Deleted  
-- if exists (select 1 from payroll.dbo.pCompanyMaster where companyId=@CompanyID)  
--  Delete from payroll.dbo.pCompanyMaster where companyId= @CompanyID  
--  
--End */
GO
/****** Object:  View [dbo].[vwserialnoshopstock]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  UserDefinedFunction [dbo].[fnIssueSerialNos]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
--------------------------------------------------------------------------------    
-- 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
GO
/****** Object:  View [dbo].[vwadvancepaidReturn]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE view [dbo].[vwadvancepaidReturn] as  
select prhReturnID, prhCompanyID, prhVendorId from loPurchaseReturnheader where prhcancelled = 0
GO
/****** Object:  View [dbo].[vwitemdescpurchseorder]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwendoritemdescription]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwCAshSales]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Modified On          : 21/06/2004      
-- Modified by          : Hariharan R, Vekitesh , Aneesh      
-- Comments             : added Goods return Case      
--   : added utility bills And corrected amount column for dep in room billing      
--   : Other charges given in Group Byclause to avoid doubling in Invoice queries      
--   : corrrected order of goods return note amount selecitOn      
--   : Shop debit credit note query added   
-------------------------------------------------------------------------------------------  
--Modified by           : Bijesh.B as on 07/06/2011  
--            : RefNo-1  
--Comments              : Since Post Dated Cheque (Fully/Partially) option was included   
--        in POS(Sonee) interface,the difference between 'BILL AMOUNT' and   
--        PD Cheque Amount is the actual Cash Sales      
--Backup                : vwCAshSalesAsOn07062011   
------------------------------------------------------------------------------------------           
-- Modified by : Bijesh.B  
-- Date        : 17/06/2011, 04/07/2011  
-- RefNo       : RefNo-2   
-- Comments    : PD Cheque feature added      
------------------------------------------------------------------------------------------           
-- Modified by : Bijesh.B  
-- Date        : 03/07/2011  
-- RefNo       : RefNo-3   
-- Comments    : Removed the link from ahqPostDatedChequeDetails  
--               Need to show 'pd cheque amount' even if it is not registered     
------------------------------------------------------------------------------------------           
-- Modified by : Bijesh.B  
-- Date        : 28/07/2011  
-- RefNo       : RefNo-4   
-- Comments    : Bugsheet - Spl Invoice amount is wrongly updated in cash sales,  
------------------------------------------------------------------------------------------           
-- RefNo        : RefNo-5   
-- Modified by  : Bijesh.B  
-- Date         : 19/08/2011  
-- Ticket Id    : JSZ-828136 (SHEESHA)  
-- Description  : Need UserWise selection for Cash Denomination interface  
--              : UserID column included in all query   
------------------------------------------------------------------------------------------  
-- RefNo        : RefNo-6   
-- Modified by  : AADYAKUMAR D V
-- Date         : 21/01/2012  
-- Description  : Added F&B part 
------------------------------------------------------------------------------------------          
  
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].[vwDailySalesCollection_shopwise]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Last Modified on  : 12/12/02, 01/11/2004                          
--Modified by  : leo, Hariharan                             
--Comments  : v3                            
--          : Removed VwCashSalesTruncated as max tables error (256 tables) was coming                             
--          : while executing query with this view. Made vwCashSales to Refer Only Once                       
--Modified By: Benzigar S D                    
--Modified On: 23/03/2009                    
--Comments   : Added exchange rate amount in receipts                 
----------------------------------------------------------------------------------------------                    
--Modified By: Regin Thangaraj          
--Modified On: 26/10/2010          
--Comments   : Corrected receipt amount calculation (RefNo-1)          
----------------------------------------------------------------------------------------------     
-- RefNo-1 this view is userd for rptdailysalescollectionshopwise report.shop wise recipt is not showing     
--correct  in this vwDailySalesCollection  .  so i have created vwDailySalesCollection_shopwise  view    
--jyothish 2-2-2011      
----------------------------------------------------------------------------------------------     
--RefNo        : RefNo-2  
--Modified by  : Bijesh.B  
--Date         : 12/06/2011  
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)  
----------------------------------------------------------------------------------------------    
--RefNo        : RefNo-3  
--Modified by  : SHINE DAS  
--Date         : 27/07/2011  
--Comments     : The code added for RefNo-1 was wrong. So commented it, and  
--uncommented the old one.  
----------------------------------------------------------------------------------------------    
--RefNo        : RefNo-4  
--Modified by  : Bijesh.B  
--Date         : 03/07/2011  
--Comments     : Bugsheet (P & C/REPORTS/PandC report.xls) against ticket id CBN-603540  
--               (defect id 33)    
----------------------------------------------------------------------------------------------    
  
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].[vwDailySalesCollection]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Last Modified on  : 12/12/02, 01/11/2004                      
--Modified by  : leo, Hariharan                         
--Comments  : v3                        
--          : Removed VwCashSalesTruncated as max tables error (256 tables) was coming                         
--          : while executing query with this view. Made vwCashSales to Refer Only Once                   
--Modified By: Benzigar S D                
--Modified On: 23/03/2009                
--Comments   : Added exchange rate amount in receipts             
----------------------------------------------------------------------------------------------                
--Modified By: Regin Thangaraj      
--Modified On: 26/10/2010      
--Comments   : Corrected receipt amount calculation (RefNo-1)      
----------------------------------------------------------------------------------------------                
--RefNo        : RefNo-2    
--Modified by  : Bijesh.B    
--Date         : 12/06/2011    
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)    
----------------------------------------------------------------------------------------------       
--RefNo        : RefNo-3    
--Modified by  : Bijesh.B    
--Date         : 31/08/2011    
--Comments     : Bugsheet (P & C/REPORTS/PandC report.xls) against ticket id CBN-603540    
--               (defect id 59) - No need to show Dummy Receipt amount with Department wise option    
----------------------------------------------------------------------------------------------      
--RefNo        : RefNo-4   
--Modified by  : AADYAKUMAR.D.V
--Date         : 12/12/2011    
--Comments     : As per ticket NRT-913015 i am modified
----------------------------------------------------------------------------------------------   
    
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:  StoredProcedure [dbo].[spULBookInvoice]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Modified ON                   : 21/08/2003,28/08/2003, 10/10/2003, 18/10/2003, 06/12/2003              
--Modified by                   : Reji Abraham, Hariharan R, Hariharan R              
--Comments                     : Additional table loscallbookingheader,losserviceinvheader  is added  AND modified fields, previous fields are alias names              
--           : given accoutn wise positng              
--    : given advance amount in transaction currency for easy conversions              
-- Modified by Aneesh - description below            
--    AND li.serinvhamount>0   //Commented by  Aneesh AS the invoices with the parts amount are not posting          
---------------------------------------------------------------------------------------------        
--Ref-01        
--Modified ON :- 22/06/2011        
--Modified By :- Benzigar S D        
--Comment     :- Advance paid is greater than invoice amount condition handled. Previously        
--               in this case, against customer posting will not happened          
---------------------------------------------------------------------------------------------       
--<<Ref-02>>    
--Modified ON :- 03/08/2011        
--Modified By :- MANUNADH.U    
--Comment     :- To avoid the foreign key error because of @intJournalDetailID is not incrementing.     
---------------------------------------------------------------------------------------------------    
--<<Ref-03>>    
--Modified ON :- 10/10/2011        
--Modified By :- SHINE DAS    
--Comment     :- Modification done for GST    
---------------------------------------------    
--<<Ref-04>>    
--Modified ON :- 30/10/2011        
--Modified By :- Nidheesh P V    
--Comment     :- Added isnull condition    
---------------------------------------------    
--<<Ref-05>>    
--Modified ON :- 09/11/2011        
--Modified By :- MANUNADH.U    
--Comment     :- While take Advance Amount in Invoice Currency, ServiceTaxAmount and PartsTaxAmount 
--				 should be considered. Otherwise posting will be wrong.       
---------------------------------------------------------------------------------------------------    

--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, @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
GO

/****** Object:  View [dbo].[vwcashsalestruncated]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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:  View [dbo].[vwSalesAnalysisByWeek]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwnetcashinflow]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwSalesAnalysisByMonth]    Script Date: 04/16/2012 10:32:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwsalesyearmonthdaywise]    Script Date: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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: 04/16/2012 10:32:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwCAshSalesAsOn07062011]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Modified On          : 21/06/2004    
-- Modified by          : Hariharan R, Vekitesh , Aneesh    
-- Comments             : added Goods return Case    
--   : added utility bills And corrected amount column for dep in room billing    
--   : Other charges given in Group Byclause to avoid doubling in Invoice queries    
--   : corrrected order of goods return note amount selecitOn    
--   : Shop debit credit note query added 
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------






  
    
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: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Modified On          : 21/06/2004    
-- Modified by          : Hariharan R, Vekitesh , Aneesh    
-- Comments             : added Goods return Case    
--   : added utility bills And corrected amount column for dep in room billing    
--   : Other charges given in Group Byclause to avoid doubling in Invoice queries    
--   : corrrected order of goods return note amount selecitOn    
--   : Shop debit credit note query added 
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------




  
    
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:  StoredProcedure [dbo].[spULBookInvoice_BEFOREGST]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Modified on                   : 21/08/2003,28/08/2003, 10/10/2003, 18/10/2003, 06/12/2003            
--Modified by                   : Reji Abraham, Hariharan R, Hariharan R            
--Comments                     : Additional table loscallbookingheader,losserviceinvheader  is added  and modified fields, previous fields are alias names            
--           : given accoutn wise positng            
--    : given advance amount in transaction currency for easy conversions            
-- Modified by Aneesh - description below          
--    and li.serinvhamount>0   //Commented by  Aneesh as the invoices with the parts amount are not posting        
---------------------------------------------------------------------------------------------      
--Ref-01      
--Modified On :- 22/06/2011      
--Modified By :- Benzigar S D      
--Comment     :- Advance paid is greater than invoice amount condition handled. Previously      
--               in this case, against customer posting will not happened        
---------------------------------------------------------------------------------------------     
--<<Ref-02>>  
--Modified On :- 03/08/2011      
--Modified By :- MANUNADH.U  
--Comment     :- To avoid the foreign key error because of @intJournalDetailID is not incrementing.         
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
GO
/****** Object:  StoredProcedure [dbo].[spGetServiceHistory]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
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
GO
/****** Object:  StoredProcedure [dbo].[spULSerBooking]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  View [dbo].[vwCAshSalesDetAsOn15062011]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
	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:  StoredProcedure [dbo].[spULSerBookingCancellation]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  View [dbo].[vwCollectedSalesTax]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- View
------------------------------------------------------------------------------------------                             
-- 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                   
------------------------------------------------------------------------------------------                                   

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,                          
 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, 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].[vwTotalTax]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwCAshSalesDet]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------------------                  
--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].[vwDailySalesCollectionDet]    Script Date: 04/16/2012 10:32:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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:  StoredProcedure [dbo].[spGodownTotalStockVerification]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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
GO
/****** Object:  View [dbo].[vwCompanyBinCardAudit]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[spPurchaseandSalesItemwise]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwInquirygodownStockDatewise]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  StoredProcedure [dbo].[spUpdateLedgersAdjustments_BackUp]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------



--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  
  
  
  
  
  
  
---------------------------------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAdjustments]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Procedure

/*  



       
 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)
*/
-----------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------    
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)   
      
 /* 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         
 
 --Ref No : 102 Commented Below
 --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     
 
 --Ref No : 102 Added
  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       
    
  ---------------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 --Ref No : 102 Commented  
  
  if @strextype <> ''       --Ref No : 102 Added
  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)      
  
  --Ref No : 102 Commented Below  
 ----------   insert into moajournaldetails (JournalID, journaldetailID, CompanyID,         
 ----------JournalCredit, AccountID, Amount, actualAmount,departmentid, Depamount) values        
 ----------( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,         
 ----------@intexAccountID, @numexamountCom, @numexamountAccnt,         
 ----------@intDepartmentID, @numexamountDep)       
 
 --Ref No : 102 Added
     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 : 102   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 : 102  added        
  while @@Fetch_status =0        
  begin        
   if isnull(@intaccountid,0) <> 0        
   
   --Ref No : 102 Commented Below 
   --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 : 102 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 : 102 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)    
   
   --Ref No : 102 Added Below
		   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 : 102 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)    
   
   --Ref No : 102 Added Below
		 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  ------Ref No : 102 added    
    
  end    
  Close DetailCur    
  Deallocate DetailCur    
      
        
  /* mark the record as postED */        
  update Adjustmentheader set postED =1 WHERE CompanyID = @intCompanyID and adjustmentID = @intadjID         
        
 fetch next FROM JTcur into @intAdjid, @strAdjustmentNo, @dtAdjustmentDate, @strremarks,    
 @numcAmount,@numAccAmount,@numdAmount, @strextype, @intexaccountid, @intfinancialid, @intdepartmentid, @adjType,     
 @strexrates, @numDepExRate, @numConExRate            
 end        
 Close JTCur        
 Deallocate JTCur        
set nocount off        

      
        
END
GO

/****** Object:  StoredProcedure [dbo].[spLedgersPreview]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAdjustments_BACKUP24022012]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*    
         
 Last Modified : 07/02/2004        
 Modified by   : Hariharan R        
COMMENTS  : RESP AMOUNT posting done for` exchange diff acc        
Verified by      : Hariharan         
Verified Date     : 03/05/2004 (verified From Client DB)        
Modified By   :Benzigar S D      
Modified On   :20/03/2009      
Comment       :Modified Company and Department amount calculation for adjustment     
----------------------------------------------------------------------------------------------------  
Ref No : 101  
Modified By : SHINE DAS  
Modified On : 05.05.2011  
Comments : Calcuation of amount which has to be posted to "Exchange Gain/Loss" account was wrong.   
*/  
-----------------------------------------------------------------------------------------------------  
-------------------------------------------------------------------------------------------      
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        
        
        
        
        
        
        
---------------------------------------------------------------------------------------------------------------------
GO
/****** Object:  View [dbo].[vwHqPurchaseOrder1]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwHqPurchaseOrder]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*                            
Altered By Sreejith                            
Altered on 20100724                            
Added the left outer join with the function [dbo].[fnHQPurchaseorder]()                            
*/                            
------------------------------------------                  
--RefNo : 01                  
--Modified By : VinothMurugan V.                  
--Modified Date : 30/07/2010                  
--Purpose : adding priority and type                  
------------------------------------------                 
--Altered by SReejith                         
--Altered on 20100818              
--Added  h.pohvendorid and h.pohDepartmentid fileds into the view                       
--Already there was a column for vendorid from vwvendorItemDescription(Will be null in the cases if item does'nt exist)              
--So Added  h.pohvendorid also into the view for using in the report rptPurchaseOrderVendorWiseDetail              
--------------------------------------------          
--Altered by Abhishek CS                        
--Altered on 20100914              
--Added  vwitemdescription for item description          
---------------------------------------------------------        
--RefNo:02        
--Modified by : VinothMurugan V        
--Date    : 06/10/2010             
--purpose   : Adding Other Charge Amount for kooddoo        
---------------------------------------------------------        
--Modified By : Sreejith    
--Modified on : 20101105    
--Comment : added tow fields : pohcmpexrate,pohdepexrate,pohSingleItemCatChecked,pohSingleItemCatId    
---------------------------------------------------------        
--Modified By : Nidheesh P V    
--Modified on : 20101105    
--Comment : added podItemTaxPercentage,podItemTaxAmount,podItemTaxCategory
       
create VIEW [dbo].[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, pohProjectStartDate,                                             
 pohProjectEndDate, pohProjectOtherInfo, pohCustomDutyByCustomer, pohTransportation,pohcancel ,                           
fn.PreviousPO as PreviousPurchaseorder,fn.SupplierName as PreviousSupplier,                
a.itemrate LastItemRate,lp.priority,lt.type,        
sum( o.POAmount) POAmount,pohcmpexrate,pohdepexrate,pohSingleItemCatChecked,pohSingleItemCatId,    --RefNo:02                                        
podItemTaxPercentage,podItemTaxAmount,podItemTaxCategory
FROM lopurchaseorderheader h            
------------------------------------------------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,                                            
 pohdeliveryterms, pohProjectStartDate,                                             
pohProjectEndDate, pohProjectOtherInfo, pohCustomDutyByCustomer, pohTransportation,pohcancel ,                           
fn.PreviousPO, fn.SupplierName,                
a.itemrate,lp.priority,lt.type,pohcmpexrate,pohdepexrate,pohSingleItemCatChecked,pohSingleItemCatId 
,podItemTaxPercentage,podItemTaxAmount,podItemTaxCategory           
---------------------------------------------------------
GO
/****** Object:  View [dbo].[vwHqprePurchaseOrder]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------      
--Created By    :- Benzigar S D      
--Created Date  :- 09092008      
------------------------------------------------------------------------------      
--Modified By : Sreejith      
--Modified on : 20101108      
--Comment : added tow fields : pohSingleItemCatChecked,pohSingleItemCatId      
--select * from vwHqprePurchaseOrder    
------------------------------------------------------------------------------      
--RefNo   : RefNo-01                      
--Modified By : MANUNADH.U                     
--Modified Date : 26/08/2011                      
--Purpose  : Add packingtypename to show in Pre-PurchaseOrder Prvw Report  
------------------------------------------------------------------------------  
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>>  
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].[vwQuotationBaseUnit]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwPurchaseBillDetail]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwImportRegister]    Script Date: 04/16/2012 10:32:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------------------------------------------------  
--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:  StoredProcedure [dbo].[spDailyItemSales]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  View [dbo].[vwPurchaseBillDetail_BeforeUpdate_to_Focus]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwSpecialInvoiceReturnReport]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Modified on : 29/07/2003                    
-- Modified by : Kishore                    
-- Comments    : Replace with script from v2                    
-----------------------------------------------------------                    
-- Modified on : 14/10/2003                    
-- Modified by : Kishore                    
-- Comments    : Added idFreeQuantity column                    
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
         
--modified by 181203 venki specialinvoice filteration                    
--Verified by      : Hariharan                     
--Verified Date     : 04/05/2004 (verified From Dev Server(Fies))                
              
--Modified by :Benzigar S D              
--Action :  sum(idUnitPrice)              
--Purpose :  To show the total price in case of multiple godown              
            
--Modified by :Abhishek CS              
--Action :  Add sales person and change view by using joins in case sales person name is null            
          
--Modified By : Yogesh Joe 14-07-2010          
--Action : Added the column idGodownID. It was missing.          
--     'rptSpecialInvReturn_Multi.rpt' and 'rptSpecialInvReturnwoutdisc_Multi.rpt' need it.        
        
--Modified by :Abhishek CS on 12-10-10              
--Action :  Add cancelled remarks for modified addree showing in SInvoice report            
-----------------------------------------------------------------------------    
--Modified by :Nidheesh P V    
--Modified on :20/07/2011    
--Action :  Included Exchange Rates & currency id in select statement.    
--Modified Area: In Spl Invoice Reports.    
--Reference No :RefNo-1           
-----------------------------------------------------------------------------    
--Modified by :SHINE   
--Modified on :16/09/2011    
--Action :  ADDE NEW FIELDS FOR WARRANTY FEATURE  
--Modified Area: In Spl Invoice Reports.    
--Reference No :RefNo-2     
-----------------------------------------------------------------------------   
--Modified by :MANUNADH.U   
--Modified on :21/09/2011    
--Action :  ADD NEW CONDITION TO FILTER SPL INVOICE CASH AND CREDIT TRANSACTIONS TO AVOID DUPLICATE 
--			DATA  
--Modified Area: In Spl Invoice Reports.    
--Reference No :RefNo-3     
-----------------------------------------------------------------------------   

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     
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   
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     
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
GO
/****** Object:  View [dbo].[gmlevelone]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spBankCashBalance]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  View [dbo].[vwCashInvoices]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwDailySalesCollectionWithMargin]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Modified on           : 04/09/2004                
--Modified by           : Hariharan                 
--Comments              : Added LOsAccountsInvoiceHeader                
--   : Added lnvoiceheader - Id grouping                
--   : included service details of service boooking invoices                  
--   : Corrected join condition of ashops with LOsAccountsInvoiceHeader                
--   : Corrected the service invoice query to consider the repinvdtype field              
---------------------------------------------------------------------------------------                      
--Modified on                  : 22/11/2010             
--Modified by                  : Nidheesh P V              
--Comments                     : AddedF&B             
---------------------------------------------------------------------------------------                      
--RefNo        : RefNo-2      
--Modified by  : Bijesh.B      
--Date         : 16/06/2011, 21/06/2011      
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)      
----------------------------------------------------------------------------------------------       
--RefNo        : RefNo-3      
--Modified by  : Nidheesh P V     
--Date         : 16/06/2011      
--Comments     : Used -costprice instead of costprice     
--Modified Area: Daily Sales Report    
----------------------------------------------------------------------------------------------          
--RefNo        : RefNo-4    
--Modified by  : Bijesh.B    
--Date         : 29/07/2011    
--Comments     : Bugsheet - Special invoice cash and credit,costvalue and margin is wrong    
--             : since, Special invoice return after desp, reqqty is negative,    
--     -1 is multiplied with reqqty    
----------------------------------------------------------------------------------------------       
--RefNo        : RefNo-5      
--Modified by  : AADYAKUMAR.D.V     
--Date         : 19/01/2012
--Comments     : Modified F&B part.
----------------------------------------------------------------------------------------------       
               
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:  StoredProcedure [dbo].[spUlSplInv]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwinvoices]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Added the tables of rexporting to select in the transaction , inculded duedate field                                    
--Modified by  : Hariharan , Hariharan R                                    
--Modified Date  : 14/03/2004, 03/05/2004                                    
--Comments  : v3, included bonded customs duty calculations                                    
--   given specialinvoice chking                                    
--   : included sales person id selection in Simtec Service Invoices                                    
--   : Included ocd.IoAmount for grouping invoice query                                    
--------------------------------------------------------------------------------------                                    
--Modified on :-17-08-09                                
--Modified by :Nidheesh                                 
--comments: added the condition ihNoofOCDetails=0 in the case of special inv to avoid RBD                                
----------------------------------------------------------------------------------------                            
--Modified on :13-11-09                                
--Modified by :Benzigar S D                                 
--comments: Modified Credit invoice other charges taking part                            
--        : If there is mor than one other charges then the same no of rows came in view.                            
--        : Here we need to take sum(other charges)                                    
----------------------------------------------------------------------------------------                             
--Modified on :20-03-10                                   
--Modified by :Nidheesh P V                                     
--comments: added Fine Invocie type ---                              
----------------------------------------------------------------------------------------                   
--Modified on :10-04-10                                   
--Modified by :Sreejith G A                                    
--comments: added the condition of checking 'fhInvoiceCancelled' bit in aFineheader table                  
--Purpose : to check if the main Invoice is deleted or not.                   
--   if deleted the bit 'fhInvoiceCancelled' in aFineHeader table becomes 1                            
----------------------------------------------------------------------------------------                              
--Modified on :21-04-10                                       
--Modified by :Sreejith G A                                   
--comments: Corrected the field service due date in SBI type. Initially it used Invoice date as due date                                   
----------------------------------------------------------------------------------------                     
--Modified on :29-11-10                                       
--Modified by :jyothish                           
--comments: FandB Invoice  is added             
----------------------------------------------------------------------------------------               
--Modified on :22-11-2011                                       
--Modified by :AADYA KUMAR.D.V                                   
--comments    :Added Tax in Account Service invoice            
--Ref.No      :1                                   
----------------------------------------------------------------------------------------          
--Modified on :30-11-2011                                       
--Modified by :MANUNADH. U      
--comments    :Added Tax in Shop Service invoice            
--Ref.No      :<<Ref.No2>>                                   
----------------------------------------------------------------------------------------                                     
--Modified on :11-02-2012                                             
--Modified by :JYOTHISH          
--comments    : commets condition in service invoice       
---Reason: negative invoice is entered in bb client         
 --Ref.No      :<<Ref.No3>>                                        
----------------------------------------------------------------------------------------                                          
--Ref.No.4            
--Modified on :18-02-2012                  
--Modified by :BIJESH.B      
--Ticket id   :FGJ-870028      
--Comment     :Added Tax in service invoice        
----------------------------------------------------------------------------------------          
--Ref.No.5           
--Modified on :29-02-2012                  
--Modified by :AADYA KUMAR.D.V      
--Ticket id   :FGY-413407      
--Comment     :Added new column TaxAmount        
----------------------------------------------------------------------------------------                 
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,            
 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,             
  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,             
  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,             
  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].[vwinvoicesettleformis]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spULInvSplDesp]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------------------------------  
-- 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
GO
/****** Object:  View [dbo].[vwDailySalesCollectionWithMarginGSTSeparately]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Modified on           : 04/09/2004                
--Modified by           : Hariharan                 
--Comments              : Added LOsAccountsInvoiceHeader                
--   : Added lnvoiceheader - Id grouping                
--   : included service details of service boooking invoices                  
--   : Corrected join condition of ashops with LOsAccountsInvoiceHeader                
--   : Corrected the service invoice query to consider the repinvdtype field              
---------------------------------------------------------------------------------------                      
--Modified on                  : 22/11/2010             
--Modified by                  : Nidheesh P V              
--Comments                     : AddedF&B             
---------------------------------------------------------------------------------------                      
--RefNo        : RefNo-2      
--Modified by  : Bijesh.B      
--Date         : 16/06/2011, 21/06/2011      
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)      
----------------------------------------------------------------------------------------------       
--RefNo        : RefNo-3      
--Modified by  : Nidheesh P V     
--Date         : 16/06/2011      
--Comments     : Used -costprice instead of costprice     
--Modified Area: Daily Sales Report    
----------------------------------------------------------------------------------------------          
--RefNo        : RefNo-4    
--Modified by  : Bijesh.B    
--Date         : 29/07/2011    
--Comments     : Bugsheet - Special invoice cash and credit,costvalue and margin is wrong    
--             : since, Special invoice return after desp, reqqty is negative,    
--     -1 is multiplied with reqqty    
----------------------------------------------------------------------------------------------       
--RefNo        : RefNo-5      
--Modified by  : AADYAKUMAR.D.V     
--Date         : 19/01/2012
--Comments     : Modified F&B part.
----------------------------------------------------------------------------------------------       
----------------------------------------------------------------------------------------------       
--Created by   : Bijesh.B 
--Date         : 29/03/2012
--Ticket id    : JDJ-400367 (new report (rptdailysalescollectionGSTSeparately) for sonee - GST separation)
--Comments     : Created new view and report (Copy of vwDailySalesCollectionWithMargin)
----------------------------------------------------------------------------------------------       

create VIEW [dbo].[vwDailySalesCollectionWithMarginGSTSeparately] 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 -------------------------      
convert(numeric(18,2),sum(GSTAmount))GSTAmount,
convert(numeric(18,2),sum(dGSTAmount))dGSTAmount,
convert(numeric(18,2),sum(cGSTAmount))cGSTAmount
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,
   convert(numeric(18,2),sum(posdunitprice-isnull(posdItemTaxAmount,0))) cashsales, 
   convert(numeric(18,2),sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshdepexrate)) dcashsales,
   convert(numeric(18,2),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,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,                 
   (convert(numeric(18,2),sum((posdunitprice-isnull(posdItemTaxAmount,0))))) - sum(posdcostprice*posdquantity) margin,
   (convert(numeric(18,2),sum((posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate))) -                 
								sum(posdcostprice*posdquantity) * poshdepexrate dmargin,
   (convert(numeric(18,2),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,2),sum(isnull(posdItemTaxAmount,0)))GSTAmount,
   convert(numeric(18,2),sum(isnull(posdItemTaxAmount,0)* poshdepexrate))dGSTAmount,
   convert(numeric(18,2),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,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 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,  
   (convert(numeric(18,2), sum((posdunitprice-isnull(posdItemTaxAmount,0))))) - 
								sum(posdcostprice*posdquantity) margin,
   (convert(numeric(18,2), sum((posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate))) -                 
								sum(posdcostprice*posdquantity) * poshdepexrate dmargin,
   (convert(numeric(18,2),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,2),sum(posdunitprice-isnull(posdItemTaxAmount,0))) PdChequeSales, 
   convert(numeric(18,2),sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshdepexrate)) dPdChequeSales,
   convert(numeric(18,2),sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshexchangerate)) cPdChequeSales
   ,convert(numeric(18,2),sum(isnull(posdItemTaxAmount,0)))GSTAmount
   ,convert(numeric(18,2),sum(isnull(posdItemTaxAmount,0)* poshdepexrate))dGSTAmount,
   convert(numeric(18,2),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,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(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) creditsales,           
   convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,           
   convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,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,                 
   (convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) -           
   sum(isnull(idcostprice*idquantity,0)))) margin,           
   (convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -           
   sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,           
   (convert(numeric(18,2), (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,2),sum(isnull(idItemTaxAmount,0)))GSTAmount
   ,convert(numeric(18,2),sum(isnull(idItemTaxAmount,0)* ihdepexrate))dGSTAmount,
   convert(numeric(18,2),sum(isnull(idItemTaxAmount,0)* ihexchangerate))cGSTAmount
  from                 
   losinvoiceheader  ih                
   left outer join losinvoicedetail invd                
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                 
   left outer join                 
   (select                
    ioShopID,ioInvoiceID,sum(ioAmount) ioAmount                
   from                
    losInvoiceOC                 
   group by                
   ioShopID,ioInvoiceID) ocd                 
   on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                 
   ashops s, adepartmentmaster d                 
  where                 
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                 
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'          
  group by                 
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                 
   ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                
 union all                
                
  select                 
   shopname, ihShopID, ihinvoicedate,                
   --convert(numeric(18,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,                 
   convert(numeric(18,2), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) Cashsales,           
   convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,           
   convert(numeric(18,2), (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,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,                 
	(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) -           
	sum(isnull(idcostprice*idquantity,0)))) margin,           
	(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) * ihdepexrate -           
	sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,           
	(convert(numeric(18,2), (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,2),sum(isnull(idItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,2),sum(isnull(idItemTaxAmount,0)* ihdepexrate))dGSTAmount,
	convert(numeric(18,2),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,2),sum(sedunitprice )) cashsales,
   --convert(numeric(18,2),sum(sedunitprice * sehdepexrate)) dcashsales,
   --convert(numeric(18,2),sum(sedunitprice * sehexchangerate)) ccashsales,
   convert(numeric(18,2),sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,
   convert(numeric(18,2),sum((sedunitprice-isnull(sedItemTaxAmount,0)) * sehdepexrate)) dcashsales,
   convert(numeric(18,2),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,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,
   convert(numeric(18,2), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) - sum(sedcostprice * sedquantity) margin,
   convert(numeric(18,2), sum((sedunitprice-isnull(sedItemTaxAmount,0)) * sehdepexrate)) -                 
							   sum(sedcostprice * sedquantity) * sehdepexrate dmargin,
   convert(numeric(18,2), 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,2),sum(isnull(sedItemTaxAmount,0)))GSTAmount
   ,convert(numeric(18,2),sum(isnull(sedItemTaxAmount,0)* sehdepexrate))dGSTAmount,
    convert(numeric(18,2),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,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,                
   convert(numeric(18,2),-sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,
   convert(numeric(18,2),-sum((sedunitprice-isnull(sedItemTaxAmount,0)) * sehdepexrate)) dcashsales,
   convert(numeric(18,2),-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,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,                 
    -(convert(numeric(18,2), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) - 
											sum(sedcostprice * sedExchangeQty)) margin,
    -(convert(numeric(18,2), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -                 
								sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,
    -(convert(numeric(18,2), 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,2),-sum(isnull(sedItemTaxAmount,0)))GSTAmount
   ,convert(numeric(18,2),-sum(isnull(sedItemTaxAmount,0)* sehdepexrate))dGSTAmount,
    convert(numeric(18,2),-sum(isnull(sedItemTaxAmount,0)* sehexchangerate))cGSTAmount
  from                 
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d                 
  where                 
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and                 
   sedbillorexchange ='B' and sedexchangeqty>0 and sehshopid = shopid                 
   and sehdepartmentid = d.departmentid                 
  group by                 
   shopname, sehshopid, sehdepartmentid, departmentname,sehexchangedate, sehexchangerate,                
   sehdepexrate,sedExchangeid                
 union all     
     
 -- RefNo-4 start                
 ------ --gave idratetype condition for special invoice return                
 ------ --special invoice return - cash                
 ------ select                 
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,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,  
convert(numeric(18, 2),sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,
convert(numeric(18, 2),sum(idUnitPrice-isnull(idItemTaxAmount,0) * ihDepExRate)) dcashsales,
convert(numeric(18, 2),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,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,    
(convert(numeric(18,2), sum(idunitprice-isnull(idItemTaxAmount,0) )))- sum(idcostprice*reqqty) margin,           
(convert(numeric(18,2), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty)) * ihdepexrate dmargin,      
(convert(numeric(18,2), 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,2),sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,2),sum(isnull(idItemTaxAmount,0)* ihDepExRate))dGSTAmount,
 convert(numeric(18,2),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, 2),-sum(idUnitPrice)) cashsales,    
 --convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) dcashsales,    
 --convert(numeric(18, 2),-sum(idUnitPrice * ihExchangeRate)) ccashsales,     
 convert(numeric(18, 2),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,    
 convert(numeric(18, 2),-sum((idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate)) dcashsales,    
 convert(numeric(18, 2),-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,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,    
-(convert(numeric(18,2), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) margin,               
-(convert(numeric(18,2), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,               
-(convert(numeric(18,2), 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,2),-sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,2),-sum(isnull(idItemTaxAmount,0)* ihDepExRate))dGSTAmount
,convert(numeric(18,2),-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, 2),-sum(idUnitPrice)) cashsales,    
 --convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) dcashsales,    
 --convert(numeric(18, 2),-sum(idUnitPrice * ihExchangeRate)) ccashsales,   
 convert(numeric(18, 2),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,    
 convert(numeric(18, 2),-sum((idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate)) dcashsales,    
 convert(numeric(18, 2),-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,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,    
-(convert(numeric(18,2), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,               
-(convert(numeric(18,2), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,               
-(convert(numeric(18,2), 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,2),-sum(isnull(idItemTaxAmount,0)))GSTAmount 
,convert(numeric(18,2),-sum(isnull(idItemTaxAmount,0)* ihDepExRate))dGSTAmount,
convert(numeric(18,2),-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, 2),sum(idUnitPrice)) creditsales,    
 --convert(numeric(18, 2),sum(idUnitPrice * ihDepExRate)) dcreditsales,    
 --convert(numeric(18, 2),sum(idUnitPrice * ihExchangeRate)) ccreditsales,  
 convert(numeric(18, 2),sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,    
 convert(numeric(18, 2),sum((idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate)) dcreditsales,    
 convert(numeric(18, 2),sum((idUnitPrice-isnull(idItemTaxAmount,0)) * 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,    
(convert(numeric(18,2), sum((idunitprice-isnull(idItemTaxAmount,0)))))-sum(idcostprice*reqqty) margin,               
(convert(numeric(18,2), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,               
(convert(numeric(18,2), 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,2),sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,2),sum(isnull(idItemTaxAmount,0)* ihDepExRate))dGSTAmount,
convert(numeric(18,2),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, 2),-sum(idUnitPrice)) creditsales,    
 --convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) dcreditsales,    
 --convert(numeric(18, 2),-sum(idUnitPrice * ihExchangeRate)) ccreditsales,   
 convert(numeric(18, 2),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,    
 convert(numeric(18, 2),-sum((idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate)) dcreditsales,    
 convert(numeric(18, 2),-sum((idUnitPrice-isnull(idItemTaxAmount,0)) * 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,    
-(convert(numeric(18,2), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) margin,               
-(convert(numeric(18,2), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,               
-(convert(numeric(18,2), 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,2),-sum(isnull(idItemTaxAmount,0)))GSTAmount 
,convert(numeric(18,2),-sum(isnull(idItemTaxAmount,0)* ihDepExRate))dGSTAmount,
convert(numeric(18,2),-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, 2),-sum(idUnitPrice)) creditsales,    
 --convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate))dcreditsales,    
 --convert(numeric(18, 2),-sum(idUnitPrice * ihExchangeRate))ccreditsales,     
 convert(numeric(18, 2),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,    
 convert(numeric(18, 2),-sum((idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate))dcreditsales,    
 convert(numeric(18, 2),-sum((idUnitPrice-isnull(idItemTaxAmount,0)) * 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,    
-(convert(numeric(18,2), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,               
-(convert(numeric(18,2), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,               
-(convert(numeric(18,2), 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,2),-sum(isnull(idItemTaxAmount,0)))GSTAmount 
,convert(numeric(18,2),-sum(isnull(idItemTaxAmount,0)* ihDepExRate))dGSTAmount,
 convert(numeric(18,2),-sum(isnull(idItemTaxAmount,0)* ihExchangeRate))cGSTAmount
from                                     
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                     
where              
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                     
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice <>1                                   
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID      
Group By      
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,         
 ihdepexrate, ihexchangerate    
    
 -- RefNo-4 ends     
  union all               
  select                 
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                
   -- -convert(numeric(18,2), (sum(GRNDunitprice ))) creditsales,                 
   -- -convert(numeric(18,2), (sum(GRNDunitprice * grnhdepexRate))) dcreditsales,                 
   -- -convert(numeric(18,2), (sum(GRNDunitprice * grnhExchangeRate))) ccreditsales, 
   -convert(numeric(18,2), (sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) creditsales,                 
   -convert(numeric(18,2), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)) * grnhdepexRate))) dcreditsales,                 
   -convert(numeric(18,2), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)) * 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,                 
   -(convert(numeric(18,2),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))))-
											sum(grncostprice*grndquantity)) margin,
   -(convert(numeric(18,2),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -                 
							sum(grncostprice*grndquantity))* grnhdepexRate dmargin,
   -(convert(numeric(18,2),(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,2),sum(isnull(idItemTaxAmount,0)))GSTAmount
   ,-convert(numeric(18,2),sum(isnull(idItemTaxAmount,0)* grnhdepexrate))dGSTAmount,
    -convert(numeric(18,2),sum(isnull(idItemTaxAmount,0)* grnhexchangerate))cGSTAmount
  from                 
   losgoodsreturnnoteheader , losgoodsreturnnotedetail, ashops s, adepartmentmaster d                 
  where             
   GrnhGoodsreturnnoteID = GRNDReturnNoteID and grnhShopid = GRNDShopid AND GrnhCancel =0                 
   and grnhshopid = shopid and grnhdepartmentid = d.departmentid                 
  group by                 
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname,                 
   grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID                
  --hari added to include the service booking invoice parts replaced items                
 UNION ALL                
                
  select                 
   shopname, repinvdshopid, serinvhdate,
   --convert(numeric(18,2),sum(repinvdrate* repinvdqty)) cashsales,
   --convert(numeric(18,2),sum(repinvdrate* seinvhdepexrate * repinvdqty)) dcashsales,                
   --convert(numeric(18,2),sum(repinvdrate* serinvhcmpexrate * repinvdqty)) ccashsales,                
   convert(numeric(18,2),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))) cashsales,
   convert(numeric(18,2),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)* seinvhdepexrate)) dcashsales,          
   convert(numeric(18,2),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,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,           
   convert(numeric(18,2),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))
						-sum(repinvdcostprice * repinvdqty),           
   convert(numeric(18,2),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))
						-sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate,
   convert(numeric(18,2),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))
						-sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate,          

   departmentname, serinvhDepartmentid departmentid                 
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
	,convert(numeric(18,2),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,2),sum(isnull(repinvdItemTaxAmount,0)* seinvhdepexrate))dGSTAmount,
	convert(numeric(18,2),sum(isnull(repinvdItemTaxAmount,0)* serinvhcmpexrate))cGSTAmount
  from                 
   losinvoicedpartsreplacedetails, losserviceinvheader, ashops s, adepartmentmaster d                 
  where                 
   serinvhid = repinvinvoiceid and serinvhshopid = repinvdshopid AND serinvhcancelled=0                 
    and repinvdshopid = shopid and serinvhcashacc is not null and serinvhCashInv = 1                
   and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0              
  group by                 
   shopname, repinvdshopid, serinvhDepartmentid,                 
   departmentname, serinvhdate, serinvhcmpexrate, seinvhdepexrate,serinvhid                 
                
 union all                
                
  select                 
   shopname, repinvdshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                 
   --convert(numeric(18,2) , (sum(repinvdrate* repinvdqty))) creditsales ,                 
   --convert(numeric(18,2) , (sum(repinvdrate * seinvhdepexrate * repinvdqty))) dcreditsales ,                 
   --convert(numeric(18,2) , (sum(repinvdrate * serinvhcmpexrate * repinvdqty))) ccreditsales , 
   convert(numeric(18,2),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) creditsales,              
   convert(numeric(18,2),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)) dcreditsales ,           
   convert(numeric(18,2),(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,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 ,                 
   convert(numeric(18,2),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),
   convert(numeric(18,2),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * seinvhdepexrate,
   convert(numeric(18,2),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate,
   departmentname, serinvhDepartmentid departmentid                 
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
	,convert(numeric(18,2),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,2),sum(isnull(repinvdItemTaxAmount,0)* seinvhdepexrate))dGSTAmount,
	convert(numeric(18,2),sum(isnull(repinvdItemTaxAmount,0)* serinvhcmpexrate))cGSTAmount
  from                 
   losinvoicedpartsreplacedetails, losserviceinvheader,                 
   ashops s, adepartmentmaster d where serinvhid = repinvinvoiceid and                 
   serinvhshopid = repinvdshopid AND serinvhcancelled=0                 
    and repinvdshopid = shopid and serinvhcashacc is null                 
   and serinvhCashInv = 0  and serinvhDepartmentid = d.departmentid                  
   and Patindex('%y%',repinvdtype)>0              
  group by                 
   shopname, repinvdshopid, departmentname, serinvhDepartmentid, serinvhdate, seinvhdepexrate,                
   serinvhcmpexrate ,serinvhid                 
  union all                

  --service Details                
  select                 
   shopname, serinvhshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                 
   --convert(numeric(18,2) , serinvhserviceamt) creditsales ,                 
   --convert(numeric(18,2) , serinvhserviceamt * seinvhdepexrate) dcreditsales ,                 
   --convert(numeric(18,2) , serinvhserviceamt * serinvhcmpexrate) ccreditsales ,   
   convert(numeric(18,2),serinvhserviceamt-isnull(serinvhTaxamount,0)) creditsales ,           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate) dcreditsales ,           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,0))* 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) ,                 
   convert(numeric(18,2),serinvhserviceamt-isnull(serinvhTaxamount,0)) ,           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,0))*seinvhdepexrate) ,           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,0))*serinvhcmpexrate) ,           

   departmentname, serinvhDepartmentid departmentid                 
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2   
	,convert(numeric(18,2),isnull(serinvhTaxamount,0))GSTAmount
	,convert(numeric(18,2),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,
	convert(numeric(18,2),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount  
  from                 
   losserviceinvheader, ashops s, adepartmentmaster d                 
  where                 
   serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid                 
  union all                
  
  --service Details                
  select                 
   shopname, serinvhshopid, serinvhdate,
   --convert(numeric(18,2) , serinvhserviceamt) cashsales ,                 
   --convert(numeric(18,2) , serinvhserviceamt * seinvhdepexrate) dcashsales ,                 
   --convert(numeric(18,2) , serinvhserviceamt * serinvhcmpexrate) ccashsales ,                 
   convert(numeric(18,2),serinvhserviceamt-isnull(serinvhTaxamount,0))cashsales ,           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate)dcashsales ,           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,0))* 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) ,  
   convert(numeric(18,2),serinvhserviceamt-isnull(serinvhTaxamount,0)),           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,0)) *  serinvhcmpexrate) ,           

   departmentname, serinvhDepartmentid departmentid                 
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
	,convert(numeric(18,2),isnull(serinvhTaxamount,0))GSTAmount
	,convert(numeric(18,2),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,
	convert(numeric(18,2),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount
  from                 
   losserviceinvheader, ashops s, adepartmentmaster d                 
  where                 
   serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1                
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid                
                
 union all                
  --FOR REXOPRTING INVOCIE FOR CUSTOMERS AND VENDORS  -- 22/12/2002                
  --credit         
  select         
   shopname, REhShopID, rehExportdate, 0.0 cashsales, 0.0 cashsales,                 
   0.0 ccashsales,                
    convert(numeric(18,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      
 ,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,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      
  , 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,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      
    , 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,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  
       ,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,2),Sum(serviceqty * amount))  creditsales,                   
    --COnvert(numeric(18,2),Sum(serviceqty * amount) * depexrate)  dcreditsales,             
    --COnvert(numeric(18,2),Sum(serviceqty * amount) * exchangerate)  ccreditsales,             
    COnvert(numeric(18,2),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  creditsales,             
    COnvert(numeric(18,2),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dcreditsales,       
    COnvert(numeric(18,2),Sum((serviceqty * amount)-isnull(TaxAmount,0))* 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, 
    COnvert(numeric(18,2),Sum((serviceqty * amount)-isnull(TaxAmount,0)))margin,             
    COnvert(numeric(18,2),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dmargin,       
    COnvert(numeric(18,2),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,2),sum(isnull(TaxAmount,0)))GSTAmount 
     ,convert(numeric(18,2),sum(isnull(TaxAmount,0)* depexrate))dGSTAmount,
      convert(numeric(18,2),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,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     

/*
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,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].[vwDailySalesCollectionWithMarginDetWithOutGST]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---Created ON :13/01/2008
---Comments   :For Daily Sales With Returns Report   
---------------------------------------------------------------------------------------                
--RefNo        : RefNo-2
--Modified by  : Bijesh.B
--Date         : 21/06/2011
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)
----------------------------------------------------------------------------------------------   
--RefNo        : RefNo-3
--Modified by  : Bijesh.B
--Date         : 29/07/2011
--Comments     : Bugsheet - Special invoice cash and credit,costvalue and margin is wrong
--             : since, Special invoice return after desp, reqqty is negative,
--				 -1 is multiplied with reqqty
----------------------------------------------------------------------------------------------   
--RefNo        : Newly created view (copy of vwDailySalesCollectionWithMarginDet)
--Modified by  : Bijesh.B
--Date         : 13/03/2012
--Ticket id    : JDJ-400367 (Sonee)
--comments     : Need to show GST separately
----------------------------------------------------------------------------------------------   

create VIEW [dbo].[vwDailySalesCollectionWithMarginDetWithOutGST] 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 -------------------------
convert(numeric(18,2),sum(GSTAmount))GSTAmount,
convert(numeric(18,2),sum(dGSTAmount))dGSTAmount,
convert(numeric(18,2),sum(cGSTAmount))cGSTAmount

from           
 (          
  select           
   shopname, losposheader.poshShopID, poshbilldate, 
   convert(numeric(18,2),sum(posdunitprice-isnull(posdItemTaxAmount,0))) cashsales, 
   convert(numeric(18,2),sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshdepexrate)) dcashsales,
   convert(numeric(18,2),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,2), sum(posdunitprice -isnull(posdItemTaxAmount,0)))) -           
   sum(posdcostprice*posdquantity) margin, (convert(numeric(18,2), sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshdepexrate))) -           
   sum(posdcostprice*posdquantity) * poshdepexrate dmargin, (convert(numeric(18,2),           
   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,2),sum(isnull(posdItemTaxAmount,0)))GSTAmount,
   convert(numeric(18,2),sum(isnull(posdItemTaxAmount,0)* poshdepexrate))dGSTAmount,
   convert(numeric(18,2),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,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-isnull(posdItemTaxAmount,0))-pdCheque.PosBankAmount) cashsales, 
   --convert(numeric(18,2),sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshdepexrate)-pdCheque.PosBankAmount) dcashsales, 
   --convert(numeric(18,2),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,2), sum(posdunitprice -isnull(posdItemTaxAmount,0) ))) -           
   sum(posdcostprice*posdquantity) margin, (convert(numeric(18,2), sum(posdunitprice -isnull(posdItemTaxAmount,0) * poshdepexrate))) -           
   sum(posdcostprice*posdquantity) * poshdepexrate dmargin, (convert(numeric(18,2),           
   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,2),sum(posdunitprice-isnull(posdItemTaxAmount,0))) PdChequeSales, 
   convert(numeric(18,2),sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshdepexrate)) dPdChequeSales,
   convert(numeric(18,2),sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshexchangerate)) cPdChequeSales
   ,convert(numeric(18,2),sum(isnull(posdItemTaxAmount,0)))GSTAmount
   ,convert(numeric(18,2),sum(isnull(posdItemTaxAmount,0)* poshdepexrate))dGSTAmount,
   convert(numeric(18,2),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,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
   ,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          
           
  select           
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,           
   convert(numeric(18,2), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) creditsales,           
   convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,           
   convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,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(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) -           
   sum(isnull(idcostprice*idquantity,0)))) margin,           
	(convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -           
   sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,           
   (convert(numeric(18,2), (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,2),sum(isnull(idItemTaxAmount,0)))GSTAmount
  ,convert(numeric(18,2),sum(isnull(idItemTaxAmount,0)* ihdepexrate))dGSTAmount,
   convert(numeric(18,2),sum(isnull(idItemTaxAmount,0)* ihexchangerate))cGSTAmount
  from           
   losinvoiceheader  ih          
   left outer join losinvoicedetail invd          
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid           
   left outer join           
   (select          
    ioShopID,ioInvoiceID,sum(ioAmount) ioAmount          
   from          
    losInvoiceOC           
   group by          
   ioShopID,ioInvoiceID) ocd           
   on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,           
   ashops s, adepartmentmaster d           
  where           
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and           
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'          
  group by           
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,           
   ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount          
 union all          
          
  select           
   shopname, ihShopID, ihinvoicedate,          
   convert(numeric(18,2), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) Cashsales,           
   convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,           
   convert(numeric(18,2), (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,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(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) -           
   sum(isnull(idcostprice*idquantity,0)))) margin,           
   (convert(numeric(18,2), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) * ihdepexrate -           
   sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,           
   (convert(numeric(18,2), (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,2),sum(isnull(idItemTaxAmount,0)))GSTAmount
   ,convert(numeric(18,2),sum(isnull(idItemTaxAmount,0)* ihdepexrate))dGSTAmount,
    convert(numeric(18,2),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,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
  ,convert(numeric(18,2),sum(GSTAmount)) GSTAmount  
  ,convert(numeric(18,2),sum(dGSTAmount)) dGSTAmount  
  ,convert(numeric(18,2),sum(cGSTAmount)) cGSTAmount  
  from           
      vwPosExchangeDetailsWithMarginWithOutGST      
  group by           
   shopname, sehshopid, departmentname, departmentid, sehexchangedate ,          
   departmentname,sehExchangeID   
  having sum(cashsales )>0       
 
union all  
        
   select           
   shopname, sehshopid, sehexchangedate,0.00,0.00,0.00, 0.0 creditsales,           
   0.0 dcreditsales , 0.0 ccreditsales , sum(costvalue) costvalue,          
   sum(dcostvalue) dcostvalue,sum(ccostvalue) ccostvalue,          
   sum(margin) margin, sum(dmargin) dmargin, sum(cmargin)cmargin,
   convert(numeric(18,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
  ,convert(numeric(18,2),sum(GSTAmount)) GSTAmount 
  ,convert(numeric(18,2),sum(dGSTAmount)) dGSTAmount  
  ,convert(numeric(18,2),sum(cGSTAmount)) cGSTAmount  

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

 union all    
 
-- RefNo-3 starts
-- special Invoice (cash)  
select   
shopname,                               
 ihshopid, ihinvoicedate,            
 convert(numeric(18, 2),sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,
 convert(numeric(18, 2),sum(idUnitPrice-isnull(idItemTaxAmount,0) * ihDepExRate)) dcashsales,
 convert(numeric(18, 2),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,2), sum(idunitprice-isnull(idItemTaxAmount,0) )))- sum(idcostprice*reqqty) margin,           
(convert(numeric(18,2), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty)) * ihdepexrate dmargin,      
(convert(numeric(18,2), 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,2),sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,2),sum(isnull(idItemTaxAmount,0)* ihDepExRate))dGSTAmount,
 convert(numeric(18,2),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, 2),-sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,
 convert(numeric(18, 2),-sum(idUnitPrice-isnull(idItemTaxAmount,0) * ihDepExRate)) dcashsales,
 convert(numeric(18, 2),-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,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
,convert(numeric(18,2),-sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,2),-sum(isnull(idItemTaxAmount,0)* ihDepExRate))dGSTAmount,
convert(numeric(18,2),-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, 2),-sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,
 convert(numeric(18, 2),-sum(idUnitPrice-isnull(idItemTaxAmount,0)* ihDepExRate)) dcashsales,
 convert(numeric(18, 2),-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,2), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) margin,           
-(convert(numeric(18,2), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,           
-(convert(numeric(18,2), 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,2),-sum(isnull(idItemTaxAmount,0)))GSTAmount 
,convert(numeric(18,2),-sum(isnull(idItemTaxAmount,0)* ihDepExRate))dGSTAmount,
convert(numeric(18,2),-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, 2),sum(idUnitPrice-isnull(idItemTaxAmount,0))) creditsales,
 convert(numeric(18, 2),sum(idUnitPrice-isnull(idItemTaxAmount,0) * ihDepExRate)) dcreditsales,
 convert(numeric(18, 2),sum(idUnitPrice-isnull(idItemTaxAmount,0) * ihExchangeRate)) ccreditsales, 
 
 sum(idcostprice * reqqty) costvalue,
 sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
 sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
(convert(numeric(18,2), sum(idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty) margin,           
(convert(numeric(18,2), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,           
(convert(numeric(18,2), 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,2),sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,2),sum(isnull(idItemTaxAmount,0)* ihDepExRate))dGSTAmount,
convert(numeric(18,2),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, 2),-sum(idUnitPrice-isnull(idItemTaxAmount,0))) creditsales,
 convert(numeric(18, 2),-sum(idUnitPrice-isnull(idItemTaxAmount,0) * ihDepExRate)) dcreditsales,
 convert(numeric(18, 2),-sum(idUnitPrice-isnull(idItemTaxAmount,0) * 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-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty)) margin,           
-(convert(numeric(18,2), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,           
-(convert(numeric(18,2), 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,2),-sum(isnull(idItemTaxAmount,0)))GSTAmount 
    ,convert(numeric(18,2),-sum(isnull(idItemTaxAmount,0)* ihDepExRate))dGSTAmount,
    convert(numeric(18,2),-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, 2),-sum(idUnitPrice-isnull(idItemTaxAmount,0))) creditsales,
 convert(numeric(18, 2),-sum(idUnitPrice-isnull(idItemTaxAmount,0) * ihDepExRate)) dcreditsales,
 convert(numeric(18, 2),-sum(idUnitPrice-isnull(idItemTaxAmount,0) * 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-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) margin,           
-(convert(numeric(18,2), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,           
-(convert(numeric(18,2), 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,2),-sum(isnull(idItemTaxAmount,0)))GSTAmount 
    ,convert(numeric(18,2),-sum(isnull(idItemTaxAmount,0)* ihDepExRate))dGSTAmount,
    convert(numeric(18,2),-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,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-isnull(idItemTaxAmount,0)))) - sum(grncostprice*grndquantity)) margin,
   -(convert(numeric(18,2),(sum(GRNDunitprice-isnull(idItemTaxAmount,0)))) - sum(grncostprice*grndquantity))* grnhdepexRate dmargin,
   -(convert(numeric(18,2),(sum(GRNDunitprice-isnull(idItemTaxAmount,0)))) - sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,           
   0.00,0.00,0.00,
   -convert(numeric(18,2),(sum(GRNDunitprice-isnull(idItemTaxAmount,0)))) GReturn,           
   -convert(numeric(18,2),(sum(GRNDunitprice-isnull(idItemTaxAmount,0) * grnhdepexRate))) dGReturn,           
   -convert(numeric(18,2),(sum(GRNDunitprice-isnull(idItemTaxAmount,0) * grnhExchangeRate))) cGReturn,
   departmentname, grnhdepartmentid departmentid          
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,2),sum(isnull(idItemTaxAmount,0)))GSTAmount
  ,convert(numeric(18,2),sum(isnull(idItemTaxAmount,0)* grnhdepexrate))dGSTAmount,
   convert(numeric(18,2),sum(isnull(idItemTaxAmount,0)* grnhexchangerate))cGSTAmount
  from           
   losgoodsreturnnoteheader , losgoodsreturnnotedetail, ashops s, adepartmentmaster d           
  where           
   GrnhGoodsreturnnoteID = GRNDReturnNoteID and grnhShopid = GRNDShopid AND GrnhCancel =0           
   and grnhshopid = shopid and grnhdepartmentid = d.departmentid           
  group by           
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname,           
   grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID          
  --hari added to include the service booking invoice parts replaced items          
 UNION ALL          
          
  select           
   shopname, repinvdshopid, serinvhdate, 
   convert(numeric(18,2),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))) cashsales,
   convert(numeric(18,2),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)* seinvhdepexrate)) dcashsales,          
   convert(numeric(18,2),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,2),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),           
   convert(numeric(18,2),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate,
   convert(numeric(18,2),(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
  ,convert(numeric(18,2),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount
  ,convert(numeric(18,2),sum(isnull(repinvdItemTaxAmount,0)* seinvhdepexrate))dGSTAmount,
  convert(numeric(18,2),sum(isnull(repinvdItemTaxAmount,0)* serinvhcmpexrate))cGSTAmount
  from           
   losinvoicedpartsreplacedetails, losserviceinvheader, ashops s, adepartmentmaster d           
  where           
   serinvhid = repinvinvoiceid and serinvhshopid = repinvdshopid AND serinvhcancelled=0           
    and repinvdshopid = shopid and serinvhcashacc is not null and serinvhCashInv = 1          
   and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0        
  group by           
   shopname, repinvdshopid, serinvhDepartmentid,           
   departmentname, serinvhdate, serinvhcmpexrate, seinvhdepexrate,serinvhid           
          
 union all          
          
  select           
   shopname, repinvdshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,           
   convert(numeric(18,2),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) creditsales,              
   convert(numeric(18,2),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)) dcreditsales ,           
   convert(numeric(18,2),(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,2),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),
   convert(numeric(18,2),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * seinvhdepexrate,
   convert(numeric(18,2),(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
  ,convert(numeric(18,2),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount
  	,convert(numeric(18,2),sum(isnull(repinvdItemTaxAmount,0)* seinvhdepexrate))dGSTAmount,
    convert(numeric(18,2),sum(isnull(repinvdItemTaxAmount,0)* serinvhcmpexrate))cGSTAmount
  from           
   losinvoicedpartsreplacedetails, losserviceinvheader,           
   ashops s, adepartmentmaster d where serinvhid = repinvinvoiceid and           
   serinvhshopid = repinvdshopid AND serinvhcancelled=0           
    and repinvdshopid = shopid and serinvhcashacc is null           
   and serinvhCashInv = 0  and serinvhDepartmentid = d.departmentid            
   and Patindex('%y%',repinvdtype)>0        
  group by           
   shopname, repinvdshopid, departmentname, serinvhDepartmentid, serinvhdate, seinvhdepexrate,          
   serinvhcmpexrate ,serinvhid           
  
  union all          
  
--  --service Details          
  select           
   shopname, serinvhshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,           
   convert(numeric(18,2),serinvhserviceamt-isnull(serinvhTaxamount,0)) creditsales ,           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate) dcreditsales ,           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,0))* serinvhcmpexrate) ccreditsales ,           
   0 costvalue, 0 dcostvalue, 0 ccostvalue,           
   convert(numeric(18,2),serinvhserviceamt-isnull(serinvhTaxamount,0)) ,           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,0))*seinvhdepexrate) ,           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,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,2),isnull(serinvhTaxamount,0))GSTAmount
  ,convert(numeric(18,2),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,
  convert(numeric(18,2),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount
from           
   losserviceinvheader, ashops s, adepartmentmaster d           
  where           
   serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0          
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid      
        
  union all          

  --service Details          
  select           
   shopname, serinvhshopid, serinvhdate,
   convert(numeric(18,2),serinvhserviceamt-isnull(serinvhTaxamount,0))cashsales ,           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate)dcashsales ,           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,0))* serinvhcmpexrate)ccashsales ,           
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,               
   0 costvalue, 0 dcostvalue, 0 ccostvalue,           
   convert(numeric(18,2),serinvhserviceamt-isnull(serinvhTaxamount,0)),           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,           
   convert(numeric(18,2),(serinvhserviceamt-isnull(serinvhTaxamount,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,2),isnull(serinvhTaxamount,0))GSTAmount
  ,convert(numeric(18,2),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,
   convert(numeric(18,2),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount

  from           
   losserviceinvheader, ashops s, adepartmentmaster d           
  where           
   serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1          
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid          
          
 union all  
         
  --FOR REXOPRTING INVOCIE FOR CUSTOMERS AND VENDORS  -- 22/12/2002          
  --credit          
 
  select           
   shopname, REhShopID, rehExportdate, 0.0 cashsales, 0.0 cashsales,           
   0.0 ccashsales,          
   convert(numeric(18,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
  ,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,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
 , 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,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
    , 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,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
     ,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,2),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  creditsales,             
    COnvert(numeric(18,2),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dcreditsales,       
    COnvert(numeric(18,2),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)ccreditsales,       
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                   
    COnvert(numeric(18,2),Sum((serviceqty * amount)-isnull(TaxAmount,0)))margin,             
    COnvert(numeric(18,2),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dmargin,       
    COnvert(numeric(18,2),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,2),sum(isnull(TaxAmount,0)))GSTAmount 
   ,convert(numeric(18,2),sum(isnull(TaxAmount,0)* depexrate))dGSTAmount,
    convert(numeric(18,2),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].[vwinvoiceswithAdvance]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--***************************************************************************************************          
-- 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].[vwDailySalesCollectionWithMarginAsOn10062011]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Modified on           : 04/09/2004          
--Modified by           : Hariharan           
--Comments              : Added LOsAccountsInvoiceHeader          
--   : Added lnvoiceheader - Id grouping          
--   : included service details of service boooking invoices            
--   : Corrected join condition of ashops with LOsAccountsInvoiceHeader          
--   : Corrected the service invoice query to consider the repinvdtype field        
---------------------------------------------------------------------------------------                
--Modified on                  : 22/11/2010       
--Modified by                  : Nidheesh P V        
--Comments                     : AddedF&B       
---------------------------------------------------------------------------------------                
          
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].[vwGetSlNoWarrantyDetails]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
 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].[vwCreditSales]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwnetcreditsales]    Script Date: 04/16/2012 10:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwItemSalesRate]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwDailySalesCollectionWithMarginDet]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---Created ON :13/01/2008  
---Comments   :For Daily Sales With Returns Report     
---------------------------------------------------------------------------------------                  
--RefNo        : RefNo-2  
--Modified by  : Bijesh.B  
--Date         : 21/06/2011  
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)  
----------------------------------------------------------------------------------------------     
--RefNo        : RefNo-3  
--Modified by  : Bijesh.B  
--Date         : 29/07/2011  
--Comments     : Bugsheet - Special invoice cash and credit,costvalue and margin is wrong  
--             : since, Special invoice return after desp, reqqty is negative,  
--     -1 is multiplied with reqqty  
----------------------------------------------------------------------------------------------     
            
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].[vwDebtorAge]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwCustomerSalesmonthwise]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwCustomerSales]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Modified on   : 05/09/2004                      
-- Modified by  : Hariharan,Sebin                       
-- CommentS             : Added details for rexporting to customers                      
--   : Separated Exchange in and exchange out into 2 queries                      
--                      : Changed the linking with losposHeader to country master and                       
--                      : currency master into left outer join. In pos and Exchange.                      
--   : Added columns for depsalesamt and cmpsalesamt, added referenceno                      
--   : Other charges changes                      
--   : specialinvoice chking transfinished, transfinished checking given for special invoice which were missed earlier                      
--    : added goods return also on venkitesh 150404                      
--   : Other charges given in group by clause to avoid doubling in Invoice queries               
--   : Updated the shop credit special invoice               
--   :--jyothish changed -ve to depsales and cmpsalses  on exchange in(151209)          
--select * from vwCustomerSales where ihshopid=6 and Year(ihinvoiceDate)=2009 and Month(ihinvoiceDate)>=05             
-----------------------------        
--RefNo:01        
--Modified : VinothMurugan V         
--Purpose  : changed -ve to depsales and cmpsalses          
-----------------------------          
-----------------------    
--RefNo   : 02    
--Date   : 20/09/2010    
--Modified By : VinothMurugan V.    
--Purpose  : Adding Item category this one is missed in standard db.Now i added compared with simdi db.    
--Ticket--SXJ-583458    
    
------------------------      
--RefNo    : 03        
--Modified : Aadyakumar.D.V  
--Purpose  : For "rptsalesregister" all are requsted to use vwSalesRegister.  
--         : This view is modified as per reference 01 and 02 so new view is created.  
-----------------------------          
       
          
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
GO
/****** Object:  View [dbo].[vwSalesRegister]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  StoredProcedure [dbo].[spUpdateLEDgersBills]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwCreditorAge]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[VwpendingControlAccTrans]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[spUlShopSv]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** Object:  Stored Procedure dbo.spULshopSV    Script Date: 18/01/2003 9:45:46 PM ******/
-- Modified      : 17/07/2002
-- Modified by   : leo
-----------------------------------------
-- Modified on      : 03/01/2003
-- Modified by      : Kishore
-- Comments         : Added code to insert depAmount and to convert amount
-----------------------------------------
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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersInterDivisionJournal]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersDebitCredit]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO

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

/****** Object:  StoredProcedure [dbo].[spULshopTrOut]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwTransferInShop]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwShopStockWriteoff]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwlocalpurchasebill]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  
    
      
----         
--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].[vwpendingorderstilldate]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwdummyPosSalesForReport]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwGoodReqDespArrDtlsPurReq]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwLocalPurchaseCosting]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwShopSerInvAndRecAmount]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  StoredProcedure [dbo].[spUpdateLedgersAssetdepreciation]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spulShopConsumption]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spUlShopSWO]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------
-- 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
GO
/****** Object:  View [dbo].[vwserialnoitemsissuedshopstock]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwspecialinvrecamount]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwreexportinvoicesettled]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  StoredProcedure [dbo].[spUlShopTrIn]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spInventoryAgeAnalysis]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwInventoryAge_old]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwInventoryAge]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[spUpdateLedgersPayroll]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spUlShopRecover]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spULShopDebitNote]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spULHQSWO]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spULMASAgreement]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spPLAmtForBS]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  StoredProcedure [dbo].[spPLdep]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spPL]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheet_Asset_Comp]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------      
--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
GO
/****** Object:  StoredProcedure [dbo].[spYearEndCheck]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Last Modified : 01/06/2004, 13/07/2004
-- Modified by   : Hariharan 
--               : Included subdepartmetns of given dept in the filteration (11/12/2003)
--               : included consolidation venki 261203
--		 : Removed cursor and given temporary table names
--		 : carry forwarding of unclosed financial year done
--		 : Financialid considerations corrected
--		 : consolidation option department wise is corrected
--		 : Script Verified
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
GO
/****** Object:  StoredProcedure [dbo].[spYearEnd]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheetDep_old]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Last Modified : 01/06/2004, 13/07/2004  
-- Modified by   : Hariharan   
--               : Included subdepartmetns of given dept in the filteration (11/12/2003)  
--               : included consolidation venki 261203  
--   : Removed cursor and given temporary table names  
--   : carry forwarding of unclosed financial year done  
--   : Financialid considerations corrected  
--   : consolidation option department wise is corrected  
--   : Script Verified  
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
GO
/****** Object:  StoredProcedure [dbo].[spBankReconciliation_SIMDI]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ----------------------------------------------------------
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spULUtilityBilling]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
---------------------------
--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
GO
/****** Object:  StoredProcedure [dbo].[spUlInvSv]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spCFUserFormat]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spULShopGR]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------    
      
-----         
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spPlannedTB]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spTrialBalanceDep]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Last Modified : 26/04/2004, 13/07/2004, 28/07/2004  
-- Modified by   : Kishore, Hariharan   
-- Comments  : the department accoiunt filter given (23/01/2003)  
--               : removed account head filteration deptwise (25/08/2003)  
--               : Included subdepartmetns of given dept in the filteration (11/12/2003)  
--   : Included consolidation 261203 venki  
--   : Hari corrected the A, L, I ,E TYPE checking and made temporary table source  
--   : Removed Cursor and looping to make the printing fast  
--   : COnsolidation group corrected avoiding departmentid from grouping  
--   : Opening Debit and credit net is found and kept in opening columns  
----------------------------------------
--Ref.No:1 
--Modifted By:Shine Das  
--Modified On:09/03/2012    
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"   
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).   
--It has to be corrected.  
-----------------------------------------------------    
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  
CREATE PROC [dbo].[spTrialBalanceDep] (@strFromDate as varchar(10),   
                                    @strToDate as varchar(10),   
                                    @intCompanyId as int,   
                                    @intDepartmentId as int,   
                                    @bitCons as bit,  
                                    @intLevel as int = 0,  
        @intconsolidation as int =0) AS  
begin  
    set nocount on  
    set ansi_warnings off  
  
    Declare   
 @dtFROMDate as datetime,  
 @dtToDate as datetime,  
 @intParentGroupID int,   
 @intFinId as int,   
 @dtPrevFinUnclosedSDate as datetime,   
 @dtLastFinUnclosedEDate as datetime,   
 @intCount as int,   
 @intLastFinId as int  
  
Create table #vwJournalDetails(companyid int,  
journalid int,  
journaldetailid int,  
journalcredit bit,  
accountid int,  
Amount numeric(18,2),  
ActualAmount numeric(18,2),  
departmentid int,  
depamount numeric(18,2),   
PostGroup int)  
  
Create table #Tempjournalheader  
  
(JournalID int,  
CompanyID int,  
JournalDate smalldatetime,   
ReferenceNo varchar(100),   
Remarks varchar(250),  
Type char(10),   
Cancel bit,   
Realised bit,   
CurrencyId int,   
FinancialID int,   
chequedate datetime,   
updatetime datetime,   
bankdate datetime)  
  
    Create table #TrialBal(  
 CompanyID int,  
 AccCode varchar(100),  
 AccDesc varchar(100),  
 AcType varchar(1),  
 GroupID int,  
 GroupName varchar(100),  
 OBDr numeric(18,2),  
 OBCr numeric(18,2),  
 DebitAmt numeric(18,2),  
 CrEDitAmt numeric(18,2),   
 OpDebit numeric(18,2),   
 OpCredit Numeric(18,2),   
 AccountId int,   
 DepartmentId int)  
  
    -- create the temporary table to insert sub departments  
    -- table name is given as #SubDepts1 to avoid conflicts  
    -- with #SubDepts inside the sp  
    create table #SubDepts1(DeptId int)  
   if @intconsolidation=0   
     insert into #SubDepts1 values(@intDepartmentId)  
   else  
    -- get the sub depts  
    insert into #SubDepts1  
        Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId  
   
    SELECT @dtFROMDate = convert(datetime, @strFROMDate)  
    SELECT @dtToDate = convert(datetime, @strToDate)  
  
 Select @intFinId = financialid from vwfinyearperiod   
        where convert(datetime,@strFROMDate,101) between sdate and edate  
  
 select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )  
  
 select @intCount = count(*) from aAccountfinyearOpening where   
 CompanyId = @intCompanyId and FinancialId = @intFinId  
  
 Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening   
 where CompanyId = @intCompanyId and FinancialId <= @intFinId  
  
 --if @intLastFinId = 0   --Ref.No:1 Commented
 if ISNULL(@intLastFinId,0) = 0   --Ref.No:1 Added
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod  
  where financialid = (Select min(financialid) from afinancialyear where  
  companyid = @intCompanyId ) and CompanyId= @intCompanyId  
 ELSE  
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod  
  where financialid = @intLastFinId and CompanyId= @intCompanyId  
  
insert #Tempjournalheader   
Select H.* from moajournalheader h where JournalDate>=@dtPrevFinUnclosedSDate and   
 JournalDate <=@dtToDate and h.CompanyId = @intCompanyId  
  
insert #vwJournalDetails  
Select d.* from #Tempjournalheader h, vwJournalDetails d where JournalDate>=@dtPrevFinUnclosedSDate and   
 JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId  
 and h.Cancel = 0 and h.CompanyId = @intCompanyId and d.departmentid in   
 (Select Deptid from #SubDepts1)   
  
     -----------------------------  
    insert into #TrialBal  
     SELECT acc.CompanyId, acc.AccountCode, acc.AccountDesc, acc.accounttype,   
    acc.GroupID, acc.GroupDesc, OpDr, OpCr, Debit, Credit, OpDebit, OpCredit,   
    acc.AccountId, acc.Departmentid from  
    (SELECT am.CompanyId, am.AccountCode, am.AccountDesc, gm.accounttype,   
    GM.GroupID, GM.GroupDesc, 0 OpDr, 0 OpCr, 0 Debit, 0 Credit, 0 OpDebit , 0 OpCredit,   
   am.AccountId, d.DaDepartmentid Departmentid  
    FROM aaccountmaster AM, aGroupMaster GM, adeptAccounts d  
    WHERE GM.GroupID = AM.GroupID   
    AND GM.CompanyID = AM.CompanyID   
    AND AM.CompanyID = @intcompanyid   
    and am.accountid = d.daAccountid  
    and am.companyid = d.dacompanyid  
    and d.daDepartmentId in  (Select DeptId from #SubDepts1)    
    union all  
    SELECT am.CompanyId, am.AccountCode, am.AccountDesc, gm.accounttype,   
    GM.GroupID, GM.GroupDesc, 0 OpDr, 0 OpCr, 0 Debit, 0 Credit, 0 OpDebit , 0 OpCredit,   
    am.AccountId, deptid DepartmentId  
    FROM aaccountmaster AM, aGroupMaster GM, vwGlobalAccounts vg,  #SubDepts1  
    WHERE GM.GroupID = AM.GroupID   
    AND GM.CompanyID = AM.CompanyID   
    AND AM.CompanyID = @intcompanyid   
    and am.accountid = vg.AccountId  
    and am.companyid = vg.CompanyId ) acc   
    group by acc.CompanyId,  acc.accounttype,   acc.GroupID, acc.GroupDesc, acc.AccountCode,   
    acc.AccountDesc, acc.AccountId, acc.Departmentid,   
    OpDr, OpCr, Debit, Credit, OpDebit, OpCredit order by acc.accountid asc  
  
  
 Update #TrialBal set OBDr = abs(opening.Openingamount) from (Select AccountId,   
 DepartmentId, CompanyId,   
 case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount from   
 aaccountfinyearopening where   
 Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where   
 opening.Accountid = #TrialBal.AccountId and   
 opening.DepartmentId = #TrialBal.DepartmentId  
 and opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId  
 and (((#TrialBal.ACType = 'A' or #TrialBal.ACType = 'E' ) and   
 opening.Openingamount >0) or ((#TrialBal.ACType = 'L' or #TrialBal.ACType = 'I' ) and   
 opening.Openingamount <0))  
  
 Update #TrialBal set OBCr = abs(opening.Openingamount) from (Select AccountId,   
 DepartmentId, CompanyId,   
 case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount   
 from aaccountfinyearopening where   
 Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where   
 opening.Accountid = #TrialBal.AccountId and   
 opening.DepartmentId = #TrialBal.DepartmentId  
 and opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId  
 and (((#TrialBal.ACType = 'A' or #TrialBal.ACType = 'E' ) and   
 opening.Openingamount <0) or ((#TrialBal.ACType = 'L' or #TrialBal.ACType = 'I' ) and   
 opening.Openingamount >0))  
  
 Update #TrialBal set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId,   
 case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From   
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId and   
 trialDeb.DepartmentId = #TrialBal.DepartmentId  
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
 Update #TrialBal set OBCr = OBCr + isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId,   
 case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From   
 #vwJournalDetails v , #TempJournalHeader h where v.JournalCredit = 1 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId and   
 trialDeb.DepartmentId = #TrialBal.DepartmentId  
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId   
  
 Update #TrialBal set OBCr = OBCr - OBDr, OBDr =0 Where OBCr > OBDr   
  
 Update #TrialBal set OBDr = OBDr - OBCr, OBCr = 0 Where OBDr > OBCr   
  
 Update #TrialBal set DebitAmt = trialDeb.amount from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId,   
 case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From   
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId and   
 trialDeb.DepartmentId = #TrialBal.DepartmentId  
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
 Update #TrialBal set CreditAmt = trialDeb.amount from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId,   
 case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From   
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId and   
 trialDeb.DepartmentId = #TrialBal.DepartmentId  
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
    /*SELECT * FROM #TrialBal    
    where (isnull(obcr, 0)+  isnull(obdr, 0) + isnull(debitamt, 0) + isnull(creditamt, 0)) <> 0  
    ORDER BY AcType, AccCode */  
  
    SELECT CompanyID, AccCode , AccDesc, AcType, GroupID, GroupName , sum(OBDr),  
 sum(OBCr), sum(DebitAmt), sum(CrEDitAmt), sum(OpDebit), sum(OpCredit),  
 AccountId , min(Departmentid) FROM #TrialBal    
   Group By CompanyID, AccCode , AccDesc, AcType, GroupID, GroupName, AccountId    
   having (sum(isnull(obcr, 0))+  sum(isnull(obdr, 0)) + sum(isnull(debitamt, 0)) +   
   sum(isnull(creditamt, 0))) <> 0  
  
   ORDER BY AcType, AccCode  
  
      
    drop table #SubDepts1  
    drop table #vwJournalDetails  
    drop table #Tempjournalheader  
    Drop Table #TrialBal    
    set nocount on  
    set ansi_warnings on  
end
GO
/****** Object:  StoredProcedure [dbo].[spBudgetBalSheet]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--   : 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
GO
/****** Object:  StoredProcedure [dbo].[spULShopPosBackUpAsOn05042011]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------
---     
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spTrialBalanceConsol]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--modified by  : Hariharan     
--Modified Date  : 03/02/2004, 20/03/2004, 29/03/2004    
--Comments   : v3 (given depamount instead of amount on bitcon=0 else part)    
--   : used temporary tables for getting data after fetching for first time    
--exec spTrialBalanceConsol '20090107','20100526',1,0,1,1  
-----------------------------  
--Modified by : VinothMurugan V  
--Date : 25/06/2010  
--Refno : RefNo-01  
--Purpose : Extend Verchar Value  
----------------------------  
--Ref.No:2  
--Modifted By:Shine Das  
--Modified On:09/03/2012    
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"   
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).   
--It has to be corrected.  
----------------------------------------------------- 
CREATE proc [dbo].[spTrialBalanceConsol] @strFROMDate as varchar(10), @strToDate as varchar(10),     
@intcompanyid as int, @intdepartmentid as int, @bitcons as bit,    
@intconsolidation as int=0  as    
set nocount on    
begin    
    
declare @dtFROMDate as datetime    
declare @dtToDate as datetime,    
 @intFinId as int,     
 @dtPrevFinUnclosedSDate as datetime,     
 @dtLastFinUnclosedEDate as datetime,     
 @intCount as int,     
 @intLastFinId as int    
    
Create table #vwJournalDetails(companyid int,    
journalid int,    
journaldetailid int,    
journalcredit bit,    
accountid int,    
Amount numeric(18,2),    
ActualAmount numeric(18,2),    
departmentid int,    
depamount numeric(18,2),     
Postgroup int)    
    
Create table #Tempjournalheader    
    
(JournalID int,    
CompanyID int,    
JournalDate smalldatetime,     
ReferenceNo varchar(200),  --RefNo-01   
Remarks varchar(400), --RefNo-01   
Type char(20),  --RefNo-01   
Cancel bit,     
Realised bit,     
CurrencyId int,     
FinancialID int,     
chequedate datetime,     
updatetime datetime,     
bankdate datetime)    
    
    
Create table #TrialBal(    
 CompanyID int,    
 DepartmentId int,    
 DepartmentName varchar(100),     
 accountid int,    
 AccCode varchar(50),     
 AccDesc varchar(100),    
 AcType varchar(1),    
 GroupID int,    
 GroupName varchar(100),    
 Debit numeric(18,2),    
 Credit numeric(18,2),     
 OpDebit numeric(18,2),     
 OpCredit Numeric(18,2),    
 OpBal numeric(18,2))    
    
    
 SELECT @dtFROMDate = convert(datetime, @strFROMDate)    
 SELECT @dtToDate = convert(datetime,@strToDate)    
     
     
 Select @intFinId = financialid from vwfinyearperiod     
        where convert(datetime,@strFROMDate,101) between sdate and edate    
    
 select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )    
    
 select @intCount = count(*) from aAccountfinyearOpening where     
 CompanyId = @intCompanyId and FinancialId = @intFinId    
    
 Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening     
 where CompanyId = @intCompanyId and FinancialId <= @intFinId    
     
     
 --if @intLastFinId = 0   --Ref.No:2  Commented  
 if ISNULL(@intLastFinId,0) = 0   --Ref.No:2  Added
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod    
  where financialid = (Select min(financialid) from afinancialyear where    
  companyid = @intCompanyId ) and CompanyId= @intCompanyId    
 ELSE    
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod    
  where financialid = @intLastFinId and CompanyId= @intCompanyId    
     
 -- create the temporary table to insert sub departments    
    -- table name is given as #SubDepts1 to avoid conflicts    
    -- with #SubDepts inside the sp    
    create table #SubDepts1(DeptId int)     
    if @intconsolidation=0     
             insert into #SubDepts1 values(@intDepartmentId)    
    else    
    -- get the sub depts into the temporary table    
         insert into #SubDepts1    
        Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId    
    
 insert #Tempjournalheader     
 Select H.* from moajournalheader h (NOLOCK) where JournalDate>= @dtPrevFinUnclosedSDate     
 and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId    
 if @intDepartmentId = 0    
 begin    
 insert #vwJournalDetails    
 Select d.* from #Tempjournalheader h (NOLOCK), vwJournalDetails  d (NOLOCK) where     
 JournalDate>= @dtPrevFinUnclosedSDate and JournalDate <=@dtToDate and     
 h.JournalId = d.JournalId and h.CompanyId = d.CompanyId and h.Cancel = 0 and     
 h.CompanyId = @intCompanyId      
 end    
 else    
 begin    
 insert #vwJournalDetails    
 Select d.* from #Tempjournalheader h (NOLOCK), vwJournalDetails  d (NOLOCK) where     
 JournalDate>= @dtPrevFinUnclosedSDate and JournalDate <=@dtToDate and     
 h.JournalId = d.JournalId and h.CompanyId = d.CompanyId and h.Cancel = 0 and     
 h.CompanyId = @intCompanyId and d.departmentid in (Select Deptid from #SubDepts1)     
 end    
    
 insert into #TrialBal(CompanyID, DepartmentId, DepartmentName, accountid, AccCode,     
 AccDesc, AcType, GroupID, GroupName , Debit, Credit, OpBal, OpDebit, OpCredit )     
 Select a.CompanyId, m.DepartmentId, DepartmentName, a.AccountId, a.AccountCode,     
 a.AccountDesc,  g.AccountType, g.GroupID, g.GroupDesc, 0 Debit, 0 Credit, 0 OpBal,     
 0, 0 From aAccountMaster a, aGroupMaster g, aDepartmentMaster m where     
 a.GroupId = g.GroupID and a.CompanyId = g.CompanyId and a.companyid = m.companyid     
 and a.CompanyId = @intCompanyid    
    
 Update #TrialBal set OpBal = opening.Openingamount from (Select AccountId,     
 DepartmentId, CompanyId, Openingamount from aaccountfinyearopening where     
 Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where     
 opening.Accountid = #TrialBal.AccountId and     
 opening.DepartmentId = #TrialBal.DepartmentId    
 and opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId    
    
 Update #TrialBal set OpDebit = trialDeb.amount from (Select v.AccountId,     
 v.DepartmentId, v.CompanyId, Sum(isnull(v.Amount,0)) Amount From     
 #vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 0 and     
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and     
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate     
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where     
 trialDeb.Accountid = #TrialBal.AccountId and     
 trialDeb.DepartmentId = #TrialBal.DepartmentId    
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId    
    
 Update #TrialBal set OpCredit = trialDeb.amount from (Select v.AccountId,     
 v.DepartmentId, v.CompanyId, Sum(isnull(v.Amount,0)) Amount From     
 #vwJournalDetails v , MoaJournalHeader h where v.JournalCredit = 1 and     
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and     
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate     
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where     
 trialDeb.Accountid = #TrialBal.AccountId and     
 trialDeb.DepartmentId = #TrialBal.DepartmentId    
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId    
    
 Update #TrialBal set Debit = trialDeb.amount from (Select v.AccountId,     
 v.DepartmentId, v.CompanyId, Sum(isnull(v.Amount,0)) Amount From     
 #vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 0 and     
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and     
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate     
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where     
 trialDeb.Accountid = #TrialBal.AccountId and     
 trialDeb.DepartmentId = #TrialBal.DepartmentId    
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId    
    
 Update #TrialBal set Credit = trialDeb.amount from (Select v.AccountId,     
 v.DepartmentId, v.CompanyId, Sum(isnull(Amount,0)) Amount From     
 #vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 1 and     
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and     
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate     
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where     
 trialDeb.Accountid = #TrialBal.AccountId and     
 trialDeb.DepartmentId = #TrialBal.DepartmentId    
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId    
     
 /*delete from #TrialBal where departmentid in     
 (Select departmentid from #TrialBal group by DepartmentId    
 having sum(debit) = 0 and sum(credit)=0) */    
    
 Delete from #TrialBal from (Select accountid, Departmentid from #TrialBal     
 group by accountid, departmentid having sum(debit) = 0 and sum(credit) = 0 and     
 sum(OpDebit) = 0 and sum(OpCredit)=0 and     
 sum(OpBal)=0 ) chk where #TrialBal.accountid = chk.accountid and    
 #TrialBal.departmentid = chk.departmentid    
     
    
 --TEMPORARY CODE GIVEN TO CONSOLIDATION IMM1, 2 AND 3 AS IMM STORE    
    
 Update #TrialBal set departmentid = 3 where departmentid in (15, 16, 17)    
    
 Select CompanyID, DepartmentId, DepartmentName , accountid,    
 AccCode, AccDesc , AcType , GroupID , GroupName , Debit ,    
 Credit, OpDebit, OpCredit, OpBal , 'Debit' DebitTitle, 'Credit' CreditTitle,     
 case AcType when 'A' then '1' when 'L' THEN '2' WHEN 'I' then '3'    
 WHEN 'E' THEN '4' end GroupNo from #TrialBal     
 order by AcType, GroupId, AccountId    
    
    --drop table #TrialBal    
    drop table #SubDepts1    
    drop table #vwJournalDetails    
    drop table #Tempjournalheader     
end    
set nocount off
GO
/****** Object:  StoredProcedure [dbo].[spulShopPurchReturn]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--spulShopPurchReturn 1,6
--Created 	: 21/06/2008
--Created by 	: Shinu
--Purpose	: For Posting Shop Purchase Returns
-----------------------------------------------------------------------------------------------------------------------
--Modified  On	:
--Modified  By	:
--Comments	:
-----------------------------------------------------------------------------------------------------------------------
CREATE proc [dbo].[spulShopPurchReturn] @intCompanyId as int, @intShopID as int as 
begin
	Declare 
	@intJournalID as int,
	@intJournalDetailID as int,
	@intswoid as int,
	@intFinancialID as int,
	@strswoNo as varchar(50),
	@dtswoDate as datetime,
	@strRemarks as varchar(500),
	@intDepartmentId as int,
	@numSwoAmt as numeric(18, 2),
	@intCompanyCurID as int,
	@intInventoryAccId as int,
	@intPurchRetAccid as int,
	@dtutime as datetime,
	@strzerorate as varchar(1),
	@intFailcount as int,
	@numDepExRate as numeric(18, 8),
	@numConExRate as numeric(18, 8),
	@intCurrencyId as int,
	@strExRates VarChar(250),	
	@numAccExRate Numeric(18, 2),
	@numTransEr Numeric(18, 2),
	@numAaccAmt Numeric(18, 2)

	--get the companyCurrencyID 
	SELECT @intCompanyCurID = CurrencyID 
		FROM acompanymaster 
		WHERE CompanyId = @intCompanyId

	select @intPurchRetAccid = PurchaseRtnAccID from aPackageSettings where 
		CompanyId = @intCompanyId

	select @intInventoryAccId = InventoryID, 
		@strzerorate = substring(isnull(futurevc, ''), 1, 1) 
		from aPackageSettings 

	/* getting the maximum Journal ID FROM journal table */
	SELECT @intJournalID = isnull(max(JournalID),0) 
		FROM moaJournalHeader 
		WHERE CompanyId = @intCompanyId

	set @intJournalID = @intJournalID + 1

	Declare swoCur cursor for 
		SELECT whID, whNo, whDate,  whRemarks, UpdateTime, whConExRate, 
		whDepExRate, whDepartmentId, whExchangeRates   
		FROM losPurchaseReturnHeader WHERE whCancelled = 0 And whShopId = @intShopID 
		And whPosted = 0 And whType ='P'

	open swocur

	fetch next FROM  swoCur 
		into @intswoiD, @strswono, @dtswoDate, @strRemarks, 
		@dtutime, @numConExRate, @numDepExRate, @intDepartmentId, @strExRates

	while @@Fetch_status = 0	
	begin	-- cur begin
	
		select @intCurrencyId = CurrencyId 
			from aAccountMaster 
			where AccountId = @intInventoryAccId 
			and CompanyId = @intCompanyId
		
		exec spReturnExRate @intCurrencyId, @strExRates, 
			@numTransEr output	

		-- to take financialid from afinancialyear table with curfinancialyear=1 -- hari011211
		select @intFinancialID = financialid from vwfinyearperiod where @dtswoDate between sdate and edate

		-- to check the no of records with item rate =0 or null in both the detail table
		-- and the item master table. If so we cannot do any thing in the posting with out item rate.
		-- so that transaction will be avoided from posting
		-- hariharan 011211
		set @intFailcount = 0

		select @intFailcount = count(*) from losPurchaseReturnDetail, aItem where 
			wdID = @intswoiD and wdShopId = @intShopId and wdItemId = ItemId 
			and ( wdCostPrice =null or wdCostPrice =0) and (itemrate=0 or itemrate is null) 

		-- to allow to proceed if allow zero rate condition given - hari 020905
 		if @strzerorate = 'z'   
		begin
		 	set @intFailcount=0
		end

		if @intfailcount = 0 -- for item rate = 0 check
		begin
			-- to update the item rate to the gadCostPrice 		
			update losPurchaseReturnDetail set wdCostPrice = itemrate from 
				aItem where ( wdCostPrice =null or wdCostPrice = 0) and wdID = @intswoiD and 
				wdShopId = @intShopId and wdItemId = ItemId

			insert into moaJournalHeader (JournalID, CompanyId, JournalDate, 
				referenceno, remarks, financialID, Type, CurrencyID,chequedate, updatetime )
				values (@intJournalID, @intCompanyId, @dtswoDate, @strswono, 
				@strRemarks, @intFinancialID, 'sret', @intcompanycurID, @dtswoDate, @dtutime )

			set @intJournalDetailID = 1

			-- getting the total amount with qty and item cost price
			select @numSwoAmt = isnull(sum(wdPurchaseReturnqty * wdCostPrice),0) from 
				losPurchaseReturnDetail swod where wdShopId = @intShopId and wdid = @intswoid

			-- for converting the amount --->
			select @intCurrencyId = CurrencyId 
					from aAccountMaster
					where AccountId = @intPurchRetAccId
		
			exec spReturnExRate @intCurrencyId, @strExRates, 
					@numAccExRate output	
										
			exec spConvertCurrency @numTransEr, @numAccExRate, 
					@numSwoAmt, 
					@numAaccAmt output

			-- debiting the Purchase Return accid 
			insert into moaJournalDetails 
				(JournalID, journaldetailID, CompanyId, 
				JournalCrEDit, AccountID, Amount, actualAmount, 
				DepAmount, DepartmentId) 
				values 
				(@intJournalID, @intjournalDetailID, @intCompanyId, 
				0, @intPurchRetAccid, @numSwoAmt * @numConExRate, @numAaccAmt, 
				@numSwoAmt * @numDepExRate,  @intDepartmentId)	

			set @intJournalDetailID = @intJournalDetailID + 1

			-- credit the inventory acc id
			insert into moaJournalDetails (JournalID, journaldetailID, CompanyId, 
				JournalCrEDit, accountid, Amount, actualamount, 
				DepAmount, DepartmentId) 
				values 
				(@intJournalID, @intjournalDetailID, @intCompanyId, 1, 
				@intInventoryAccId, @numSwoAmt * @numConExRate, @numSwoAmt, 
				@numSwoAmt * @numDepExRate, @intDepartmentId )

			update losPurchaseReturnHeader set whPosted = 1 WHERE WhID = 
				@intswoID and whShopId = @intShopId

			set @intJournalId = @intJournalId + 1	

		end -- for item rate = 0 check

		fetch next FROM  swoCur into @intswoiD, @strswono, @dtswoDate, 
			@strRemarks, @dtutime, @numConExRate, 
			@numDepExRate, @intDepartmentId, @strExRates

	end	-- CUR END

	Close swoCur 
	Deallocate swoCur 

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

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
 
CREATE PROC [dbo].[spTrialBalance] (@strFromDate as varchar(10),   
                                    @strToDate as varchar(10),   
                                    @intCompanyId as int) AS  
begin  
    set nocount on  
    set ansi_warnings off  
  
    Declare @dtFROMDate as datetime,  
 @dtToDate as datetime,  
 @intParentGroupID int,   
 @intFinId as int,   
 @dtPrevFinUnclosedSDate as datetime,   
 @dtLastFinUnclosedEDate as datetime,   
 @intCount as int,   
 @intLastFinId as int  
  
Create table #vwJournalDetails(companyid int,  
journalid int,  
journaldetailid int,  
journalcredit bit,  
accountid int,  
Amount numeric(18,2),  
ActualAmount numeric(18,2),  
departmentid int,  
depamount numeric(18,2),   
PostGroup int)  
  
Create table #Tempjournalheader  
  
(JournalID int,  
CompanyID int,  
JournalDate smalldatetime,   
ReferenceNo varchar(100),   
Remarks varchar(250),  
Type char(10),   
Cancel bit,   
Realised bit,   
CurrencyId int,   
FinancialID int,   
chequedate datetime,   
updatetime datetime,   
bankdate datetime)  
  
    Create table #TrialBal(  
 CompanyID int,  
 AccCode varchar(100),  
 AccDesc varchar(100),  
 AcType varchar(1),  
 GroupID int,  
 GroupName varchar(100),  
 OBDr numeric(18,2),  
 OBCr numeric(18,2),  
 DebitAmt numeric(18,2),  
 CrEDitAmt numeric(18,2),   
 AccountId int)  
  
   
    SELECT @dtFROMDate = convert(datetime, @strFROMDate)  
    SELECT @dtToDate = convert(datetime, @strToDate)  
  
 Select @intFinId = financialid from vwfinyearperiod   
        where convert(datetime,@strFROMDate,101) between sdate and edate  
  
 select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )  
  
 select @intCount = count(*) from aAccountfinyearOpening where   
 CompanyId = @intCompanyId and FinancialId = @intFinId  
  
 Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening   
 where CompanyId = @intCompanyId and FinancialId <= @intFinId  
  
 --if @intLastFinId = 0   --Ref.No:1 Commented
 
 if ISNULL(@intLastFinId,0) = 0   --Ref.No:1 Added
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod  
  where financialid = (Select min(financialid) from afinancialyear where  
  companyid = @intCompanyId ) and CompanyId= @intCompanyId  
 ELSE  
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod  
  where financialid = @intLastFinId and CompanyId= @intCompanyId  
  
insert #Tempjournalheader   
Select H.* from moajournalheader h where JournalDate>=@dtPrevFinUnclosedSDate and   
 JournalDate <=@dtToDate and h.CompanyId = @intCompanyId  
  
insert #vwJournalDetails  
Select d.* from #Tempjournalheader h, vwJournalDetails d where JournalDate>=@dtPrevFinUnclosedSDate and   
 JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId  
 and h.Cancel = 0 and h.CompanyId = @intCompanyId   
  
     -----------------------------  
    insert into #TrialBal  
    SELECT am.CompanyId, am.AccountCode, am.AccountDesc, gm.accounttype,   
    GM.GroupID, GM.GroupDesc, 0 OpDr, 0 OpCr, 0 Debit, 0 Credit,    
    am.AccountId FROM aaccountmaster AM, aGroupMaster GM  
    WHERE GM.GroupID = AM.GroupID AND GM.CompanyID = AM.CompanyID   
    AND AM.CompanyID = @intcompanyid order by aM.accountid asc  
  
  
 Update #TrialBal set OBDr = abs(opening.Openingamount) from (Select AccountId,   
 CompanyId, sum(Openingamount) Openingamount from aaccountfinyearopening where   
 Financialid = @intLastFinId and CompanyId = @intCompanyId   
 Group BY AccountId, CompanyId) opening Where   
 opening.Accountid = #TrialBal.AccountId and   
 opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId  
 and (((#TrialBal.ACType = 'A' or #TrialBal.ACType = 'E' ) and   
 opening.Openingamount >0) or ((#TrialBal.ACType = 'L' or #TrialBal.ACType = 'I' ) and   
 opening.Openingamount <0))  
  
 Update #TrialBal set OBCr = abs(opening.Openingamount) from (Select AccountId,   
 CompanyId, sum(Openingamount) Openingamount from aaccountfinyearopening where   
 Financialid = @intLastFinId and CompanyId = @intCompanyId   
 Group BY AccountId, CompanyId) opening Where   
 opening.Accountid = #TrialBal.AccountId and   
 opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId  
 and (((#TrialBal.ACType = 'A' or #TrialBal.ACType = 'E' ) and   
 opening.Openingamount <0) or ((#TrialBal.ACType = 'L' or #TrialBal.ACType = 'I' ) and   
 opening.Openingamount >0))  
  
 Update #TrialBal set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount From   
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate   
 group by v.AccountId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId   
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
 Update #TrialBal set OBCr = OBCr + isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v ,   
 #TempJournalHeader h where v.JournalCredit = 1 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate   
 group by v.AccountId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId and trialDeb.CompanyId = #TrialBal.CompanyID   
 and trialDeb.CompanyId = @intCompanyId  
  
 Update #TrialBal set OBCr = OBCr - OBDr, OBDr =0 where OBCr > OBDr  
  
 Update #TrialBal set OBDr = OBDr - OBCr, OBCr =0 where OBDr > OBCr  
  
 Update #TrialBal set DebitAmt = trialDeb.amount from (Select v.AccountId,   
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount From   
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate   
 group by v.AccountId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId and   
 trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
 Update #TrialBal set CreditAmt = trialDeb.amount from (Select v.AccountId,   
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount From   
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate   
 group by v.AccountId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId and   
 trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
    SELECT * FROM #TrialBal    
    where (isnull(obcr, 0)+  isnull(obdr, 0) + isnull(debitamt, 0) + isnull(creditamt, 0)) <> 0  
    ORDER BY AcType, AccCode  
  
   
    drop table #vwJournalDetails  
    drop table #Tempjournalheader  
    Drop Table #TrialBal    
    set nocount on  
    set ansi_warnings on  
end
GO
/****** Object:  StoredProcedure [dbo].[spULShopPosBackUpAsOn04042011]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheet]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Last Modified : 28/04/2004, 02/06/2004, 13/07/2004      
-- Modified by   : Hariharan R      
--Comments  : Taken from dep wise sp avoiding loooping for acccount balances      
--   : verified the script       
/*      
exec spBalanceSheet '20100520',1,1      
*/      
-----------------------------------------------------    
--Ref.No:1    
--Modifted By:Aadyakumar.D.V    
--Modified On:03/11/2011    
--Reason      :String or binary data would be truncated,bug came so field length is increased      
-----------------------------------------------------    
--Ref.No:2  
--Modifted By:Shine Das  
--Modified On:09/03/2012    
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"   
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).   
--It has to be corrected.  
-----------------------------------------------------    
CREATE proc [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
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheetDep]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Last Modified : 01/06/2004, 13/07/2004  
-- Modified by   : Hariharan   
--               : Included subdepartmetns of given dept in the filteration (11/12/2003)  
--               : included consolidation venki 261203  
--   : Removed cursor and given temporary table names  
--   : carry forwarding of unclosed financial year done  
--   : Financialid considerations corrected  
--   : consolidation option department wise is corrected  
--   : Script Verified  

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

/*  
exec spBalanceSheetDep '20100520',1,0,0,0,0  
 */  
CREATE PROCEDURE [dbo].[spBalanceSheetDep] (@strToDate as varchar(10),   
                                        @intCompanyID as int,   
                                        @intDepartmentId as int,   
                                        @bitcons as bit,  
                                        @intlevel as int = 0,  
                                        @intconsolidation as int =0 ) AS  
Begin  
  
    set nocount on  
    Declare @AcCode as varchar(100),  
 @AcID as int,  
 @dblDebit as numeric(18,2),  
 @dblCredit as numeric(18,2),  
 @GroupID as int,  
 @dtToDate as datetime,  
 @dtFromDate as datetime,  
 @strFromdate as varchar(10),   
 @intCount as integer,   
 @intFinId as int,   
 @dtPrevFinUnclosedSDate as datetime,   
 @dtLastFinUnclosedEDate as datetime,   
 @intLastFinId as int  
  
Create table #vwJournalDetails(companyid int,  
journalid int,  
journaldetailid int,  
journalcredit bit,  
accountid int,  
Amount numeric(18,2),  
ActualAmount numeric(18,2),  
departmentid int,  
depamount numeric(18,2),   
PostGroup int)  
  
Create table #Tempjournalheader  
  
(JournalID int,  
CompanyID int,  
JournalDate smalldatetime,   
ReferenceNo varchar(50),   
Remarks varchar(1000),  
Type varchar(10),   
Cancel bit,   
Realised bit,   
CurrencyId int,   
FinancialID int,   
chequedate datetime,   
updatetime datetime,   
bankdate datetime)  
  
    Create table #BalSheet(  
 CompanyID int,  
 AccCode varchar(100),  
 AcDesc varchar(100),  
 AcType varchar(1),  
 GroupID int,  
 GroupName varchar(100),  
 OBDr numeric(18,2),  
 OBCr numeric(18,2),  
 DebitAmt numeric(18,2),  
 CreditAmt numeric(18,2),  
 ParentGroupID int,   
 AccId int,   
 DepartmentId int)  
  
CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),   
   AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,   
   orderno int, levelcode int, departmentid int,   
   DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))   
  
  
    Create table #BalSheetFinal(  
 CompanyID int,  
 AccCode varchar(100),  
 AcDesc varchar(100),  
 AcType varchar(1),  
 GroupID int,  
 GroupName varchar(100),  
 OBDr numeric(18,2),  
 OBCr numeric(18,2),  
 DebitAmt numeric(18,2),  
 CreditAmt numeric(18,2),  
 AccId int, DepartmentId int, orderno int,   
 levelcode int,   
 Checked int,   
 ProfitLoss Numeric(18,2),  
 ParentGroupId int)  
  
    -- create the temporary table to insert sub departments  
    -- table name is given as #SubDepts1 to avoid conflicts  
-- with #SubDepts inside the sp  
    create table #SubDepts1(DeptId int)  
    if @intconsolidation=0   
             insert into #SubDepts1 values(@intDepartmentId)  
    else  
    -- get the sub depts into the temporary table  
        insert into #SubDepts1 Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId  
  
    set @dtToDate = CONVERT(DATETIME,@strToDate)  
  
 select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),   
        @intFinId = financialid from vwfinyearperiod   
        where convert(datetime,@strToDate,101) between sdate and edate  
  
  select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )  
  
 Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening   
 where CompanyId = @intCompanyId and FinancialId <= @intFinId  
  
 --if @intLastFinId = 0  --Ref.No:1 Commented
  if ISNULL(@intLastFinId,0) = 0   --Ref.No:1 Commented
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod  
  where financialid = (Select min(financialid) from afinancialyear where  
  companyid = @intCompanyId ) and CompanyId= @intCompanyId  
 ELSE  
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod  
  where financialid = @intLastFinId and CompanyId= @intCompanyId  
  
 insert into #Tempjournalheader   
 Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate  
 and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId  
  
 insert #vwJournalDetails  
 Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where   
 Journaldate>=@dtPrevFinUnclosedSDate and  
 JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId  
 and h.Cancel = 0 and h.CompanyId = @intCompanyId and d.departmentid in   
 (Select Deptid from #SubDepts1)   
------------------------------------------------OK  
 --to change the parent group if level id > 0   
 Insert into #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName,   
 OBDr, OBCr, DebitAmt, CreditAmt, ParentGroupID, AccId, DepartmentID)   
 Select CompanyId, AccountCode, AccountDesc, AccountType, GroupID,   
 GroupDesc, OBDR, OBCR, DebitAmt, CreditAmt, ParentGroupID, AccountID,   
 daDepartmentid from (SELECT am.CompanyId, AccountID, AccountCode, AccountDesc,   
 AccountType, GM.GroupID, GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,   
 ParentGroupID, daDepartmentid FROM aAccountMaster AM,aGroupMaster GM,   
 adeptAccounts d, #SubDepts1 dep WHERE GM.GroupID = AM.GroupID AND   
 (GM.AccountType = 'A' OR GM.AccountType = 'L') AND GM.CompanyID = am.companyid AND   
 AM.CompanyID = @intCompanyID and am.Accountid = d.daAccountId and   
 am.CompanyId = d.daCompanyId AND d.dadepartmentid = dep.deptid  
 Union   
 SELECT am.CompanyId, am.AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID,   
 GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt, ParentGroupID, dd.deptid   
 FROM aAccountMaster AM,aGroupMaster GM,   
 vwGlobalAccounts d, #SubDepts1 dd WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = 'A' OR   
 GM.AccountType = 'L') AND GM.CompanyID = am.companyid AND AM.CompanyID = @intCompanyID   
 and am.Accountid = d.AccountId and am.CompanyId = d.CompanyId) GrpAcId   
 group by CompanyId, AccountCode, AccountDesc, AccountType, GroupID,   
 GroupDesc, OBDR, OBCR, DebitAmt, CreditAmt, ParentGroupID, AccountID,   
 daDepartmentid ORDER BY GrpAcId.AccountID   
  
 Update #BalSheet set OBDr = opening.Openingamount from (Select AccountId,   
 DepartmentId, CompanyId,   
 case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount from   
 aaccountfinyearopening where   
 Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where   
 opening.Accountid = #BalSheet.AccId and opening.DepartmentId = #BalSheet.DepartmentId  
 and opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId  
  
  
 Update #BalSheet set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h   
 where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId   
 and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId  
 and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId  
 and #BalSheet.AcType ='A'  
  
 Update #BalSheet set OBDr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h   
 where v.JournalCredit = 1 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId   
 and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId  
 and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId  
 and #BalSheet.AcType ='A'  
  
 Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,   
 #TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and   
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and   
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,   
 v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId and   
 trialDeb.DepartmentId = #BalSheet.DepartmentId and   
 trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId   
 and #BalSheet.AcType ='L'  
  
 Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,   
 #TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and   
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and   
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,   
 v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId and   
 trialDeb.DepartmentId = #BalSheet.DepartmentId and   
 trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId   
 and #BalSheet.AcType ='L'  
  
 Update #BalSheet set DebitAmt = trialDeb.amount from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h   
 where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId   
 and h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId   
 and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
 Update #BalSheet set CreditAmt = trialDeb.amount from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId,   
 case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From   
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #BalSheet.AccId and   
 trialDeb.DepartmentId = #BalSheet.DepartmentId  
 and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
 set  @intCount = 0  
  
  
    SET @dblDebit = 0.0  
    SET @dblCredit = 0.0  
    
    if @intFinId > (Select max(financialid) from aAccountfinyearopening where   
    CompanyId = @intCOmpanyId )    
    Begin  
     select @dtPrevFinUnclosedSDate = sdate from vwfinyearperiod where CompanyId = @intCompanyId   
     and FinancialId = (Select max(financialid) from aAccountfinyearopening where   
      CompanyId = @intCOmpanyId )  
  
     select @dblDebit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end  
     from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g  
     where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid   
     and h.cancel =0 and journalcredit = 0 and   
     (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )   
      and (accounttype ='e' or accounttype ='i') and h.financialid > 0   
     and d.departmentid IN (Select DeptId from #SubDepts1)  
  
     select @dblCredit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end  
     from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g  
     where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid   
     and h.cancel =0 and journalcredit = 1 and   
     (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )   
     and (accounttype ='e' or accounttype ='i' ) and h.financialid > 0   
     and d.departmentid IN (Select DeptId from #SubDepts1)  
  
     if isnull(@dblDebit,0) + isnull(@dblCredit,0) >0   
  Begin  
   Update #BalSheet set OBDr = isnull(OBDr,0) +   
   (isnull(@dblCredit,0)) - isnull(@dblDebit,0) , OBCr = 0  
   where AccId = (Select RetainedEarningsAcc from aSettings where   
   CompanyId = @intCompanyId)  
  End    
    
    End   
  
    set @dblDebit = 0.0  
    set @dblCredit = 0.0  
    /*select @strfromdate = convert(varchar,sdate,120) from vwfinyearperiod where CompanyId = @intCompanyId   
    and FinancialId = (Select max(financialid) from aAccountfinyearopening where   
    CompanyId = @intCompanyId ) */  
  
    select @dblDebit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end  
    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g  
    where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid   
    and h.cancel =0 and journalcredit = 0 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and   
    (accounttype ='e' or accounttype ='i') and h.financialid > 0   
    and d.departmentid IN (Select DeptId from #SubDepts1)  
  
    select @dblCredit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end  
    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g  
    where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid   
    and h.cancel =0 and journalcredit = 1 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and   
    (accounttype ='e' or accounttype ='i' ) and h.financialid > 0   
    and d.departmentid IN (Select DeptId from #SubDepts1)  
  
 --SELECT b.*, isnull(@dblDebit,0) - isnull(@dblCredit,0) as Bal FROM #balsheet b   
 --where (isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) + isnull(creditamt,0)) <> 0  
 --order by b.parentgroupid  
 if @intConsolidation = 0   
 Begin   
  Insert #FilteredResult(groupid , AccountCode ,   
  AccountDesc , groupdesc , parentGroupid ,   
  orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)   
  exec SpGroupLevelOrdering @intCompanyId, @intDepartmentId  
 End  
 Else  
 Begin   
  Insert #FilteredResult(groupid , AccountCode ,   
  AccountDesc , groupdesc , parentGroupid ,   
  orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)   
  exec SpGroupLevelOrdering @intCompanyId, 0  
 End   
Insert #BalSheetFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,   
 OBCr, DebitAmt, CreditAmt, AccId, departmentid, orderno, levelcode, Checked,   
 ProfitLoss, ParentGroupId)  
SELECT b.CompanyId, b.AccCode, b.AcDesc, r.AccType, r.GroupId, r.GroupDesc, sum(b.OBDr),   
 sum(b.OBCr), sum(b.DebitAmt), sum(b.CreditAmt), b.AccId, 0, r.OrderNo,   
 r.LevelCode,  0,  isnull(@dblDebit,0) - isnull(@dblCredit,0) Bal, r.ParentGroupId from   
 #FilteredResult r left outer join #balsheet b on  ((r.GroupId = b.GroupId  and   
 r.AccountId is null) or (r.GroupId = b.GroupId  and r.AccountId  = b.AccId and   
 r.AccountId is not null))  
group by b.CompanyId, r.OrderNo, r.AccType, r.GroupId, r.GroupDesc,   
 r.LevelCode, r.ParentGroupId, b.AccId, b.AccCode, b.AcDesc  
having ((((sum(isnull(obdr,0)) + sum(isnull(obcr,0)) + sum(isnull(debitamt,0)) - sum(isnull(creditamt,0))) <> 0 and  
isnull(r.AccType,'') ='A') or ((sum(isnull(obdr,0)) + sum(isnull(obcr,0)) + sum(isnull(creditamt,0))) -  sum(isnull(debitamt,0))   
<> 0 and isnull(r.AccType,'') ='L') and b.accCode is not null) or b.accCode is null)  
and (r.AccType ='A' or r.AccType ='L' )  
order by r.orderno  
  
 set @GroupId = 0   
  
-- TO avoid the groups which does not have any accounts information  
 Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0  
 Order by OrderNo Desc  
  
 While @GroupID <>0   
 Begin  
  set @intCount = 0   
  Select @intCount = count(*) from #BalSheetFinal where   
  ((AcDesc is not Null and Groupid= @GroupID)  
   or ParentGroupid = @GroupID)  
  
  if @intCount = 0   
   Delete from #BalSheetFinal where GroupId = @GroupID  
  else  
   Update #BalSheetFinal set Checked = 1 where Groupid = @GroupID  
  
  Set @GroupID  = 0  
  
  Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0  
  Order by OrderNo Desc  
  
 End   
  
 if @intLevel>0  
 Delete from #BalSheetFinal where LevelCode >= @intLevel and AccId is null  
   
Select * from #BalSheetFinal order by OrderNo   
  
  
Drop Table #Tempjournalheader  
Drop Table #vwJournalDetails  
Drop Table #BalSheet   
Drop Table #FilteredResult  
Drop table #BalSheetFinal  
  
set nocount off  
End
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheet_Detail]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Created By :Benzigar S D              
--Created On :26/07/2010              
--Details    :To get Balance sheet teport with Department waise splitup    
--Modified By :Sreejith G A        
--Created On :28/07/2010              
--Details    :To get Balance sheet teport with Department waise splitup     
--Ref.No:2  
--Modifted By:Shine Das  
--Modified On:09/03/2012    
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"   
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).   
--It has to be corrected.  
----------------------------------------------------- 
         
CREATE proc [dbo].[spBalanceSheet_Detail] (@strToDate as varchar(10), @intCompanyID as int,                     
@intlevel as int =0) as                    
Begin                    
    set nocount on                    
    Declare @AcCode as varchar(100),                    
 @AcID as int,                    
 @dblDebit as numeric(18,2),                    
 @dblCredit as numeric(18,2),                    
 @GroupDesc as varchar(100),                    
 @GroupID as int,                    
 @dtToDate as datetime,                    
 @dtFromDate as datetime,                    
 @strFromdate as varchar(10),                     
 @intCount as integer,                     
 @intFinId as int,                     
 @dtPrevFinUnclosedSDate as datetime,                     
 @dtLastFinUnclosedEDate as datetime,                     
 @intLastFinId as int          
           
                    
Create table #vwJournalDetails(companyid int,                    
journalid int,                    
journaldetailid int,                    
journalcredit bit,                    
accountid int,                    
Amount numeric(18,2),                    
ActualAmount numeric(18,2),                    
departmentid int,                    
depamount numeric(18,2),                     
PostGroup int)                    
                    
Create table #Tempjournalheader                    
                    
(JournalID int,                    
CompanyID int,                    
JournalDate smalldatetime,                     
ReferenceNo varchar(100),                     
Remarks varchar(1000),  --jyothish changed 250 to 1000                  
Type char(10),                     
Cancel bit,                     
Realised bit,                     
CurrencyId int,                     
FinancialID int,                     
chequedate datetime,                     
updatetime datetime,                     
bankdate datetime)                    
                    
                   
                    
    Create table #BalSheet(                    
 CompanyID int,                    
 AccCode varchar(100),                    
 AcDesc varchar(100),                    
 AcType varchar(1),                    
 GroupID int,                    
 GroupName varchar(100),                    
 OBDr numeric(18,2),                    
 OBCr numeric(18,2),                    
 DebitAmt numeric(18,2),                    
 CreditAmt numeric(18,2),                    
 ParentGroupID int,AccId int,departmentid int)           
          
   CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),                     
  AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,                     
  orderno int, levelcode int, departmentid int,                     
  DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))                     
                    
    Create table #BalSheetFinal(                  
 CompanyID int,                    
 AccCode varchar(100),                    
 AcDesc varchar(100),                    
 AcType varchar(1),                    
 GroupID int,                    
 GroupName varchar(100),                    
 OBDr numeric(18,2),                    
 OBCr numeric(18,2),                    
 DebitAmt numeric(18,2),                    
 CreditAmt numeric(18,2),                    
 AccId int, DepartmentId int, orderno int,                     
 levelcode int,                     
 Checked int,                     
 ProfitLoss Numeric(18,2),                    
 ParentGroupId int,DepartmentName varchar(50))                    
                    
 set @dtToDate = CONVERT(DATETIME,@strToDate)                    
                 
 select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),                     
        @intFinId = financialid from vwfinyearperiod                     
        where convert(datetime,@strToDate,101) between sdate and edate                    
                    
  select @dtLastFinUnclosedEDate = dateadd(day, -1, @dtFromDate )                    
                    
 Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening                     
 where CompanyId = @intCompanyId and FinancialId <= @intFinId                    
                    
 --if @intLastFinId = 0    --Ref.No:2  Commented  
  if ISNULL(@intLastFinId,0) = 0    --Ref.No:2 Added               
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod                    
  where financialid = (Select min(financialid) from afinancialyear where                    
  companyid = @intCompanyId ) and CompanyId= @intCompanyId                    
 ELSE                    
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod                    
  where financialid = @intLastFinId and CompanyId= @intCompanyId                    
                    
                    
 insert #Tempjournalheader                     
 Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate                    
 and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId                    
                    
 insert #vwJournalDetails                    
 Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where                     
 Journaldate>=@dtPrevFinUnclosedSDate and                    
 JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId                    
 and h.Cancel = 0 and h.CompanyId = @intCompanyId                     
            
      
          
          
      
      
 Insert into #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, ------NEW MODIFIED                   
 OBDr, OBCr, DebitAmt, CreditAmt, ParentGroupID, AccId, departmentid)       
 select  vss.CompanyId, vss.AccountCode, vss.AccountDesc, vss.AccountType, vss.GroupID,                     
 vss.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,vss.ParentGroupID, vss.AccountID,vss.departmentid        
 from                    
 (SELECT   ad.CompanyId, AM.AccountCode, AM.AccountDesc, GM.AccountType, GM.GroupID,                     
 GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,GM.ParentGroupID, ad.AccountID,ad.departmentid        
 from aaccountfinyearopening ad      
 left outer join   aaccountmaster AM on AM.accountid=ad.accountid      
 left outer join agroupmaster gm on GM.GroupID = AM.GroupID      
 union all      
 SELECT   v.CompanyId, AM.AccountCode,AM.AccountDesc,GM.AccountType, GM.GroupID,                     
 GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,GM.ParentGroupID, v.AccountID,v.departmentid       
 from  #vwJournalDetails v       
 left outer join   aaccountmaster AM on AM.accountid=v.accountid      
 left outer join agroupmaster gm on GM.GroupID = AM.GroupID      
)vss      
 where      
 (VSS.AccountType = 'A' OR VSS.AccountType = 'L')       
 AND VSS.CompanyID =@intCompanyID   group by  AccountID,departmentid , CompanyId, AccountCode, AccountDesc, AccountType, GroupID,                     
 GroupDesc,ParentGroupID      
      
    
      
            
 Update #BalSheet set  OBDr = opening.Openingamount from (Select AccountId,                     
 CompanyId, Sum(Openingamount) Openingamount,departmentid from aaccountfinyearopening where                     
 Financialid = @intLastFinId and CompanyId = @intCompanyId Group By CompanyId,                     
 AccountId,departmentid) opening Where opening.Accountid = #BalSheet.AccId and                     
 opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId              
 and opening.departmentid= #BalSheet.departmentid                   
                   
          
       
      
 Update #BalSheet set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,        
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount,v.departmentid From #vwJournalDetails v,                     
 #TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and                     
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and                     
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb                     
 Where trialDeb.Accountid = #BalSheet.AccId and                     
 trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId                    
 and #BalSheet.AcType ='A' and trialDeb.departmentid=#BalSheet.departmentid                    
                  
      
                
 Update #BalSheet set  OBDr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,                     
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount,v.departmentid From #vwJournalDetails v,                     
 #TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and                     
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and                     
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb                     
 Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID                     
 and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType ='A'              
 and trialDeb.departmentid=#BalSheet.departmentid                    
                    
          
 Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,                     
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,                     
 #TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and                     
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and                     
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb                     
 Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID                     
 and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType ='L'              
 and trialDeb.departmentid=#BalSheet.departmentid                     
                    
          
          
 Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,                     
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,                     
 #TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and                     
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and                     
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb                     
 Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID                     
 and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType ='L'                
 and trialDeb.departmentid=#BalSheet.departmentid                  
          
          
 Update #BalSheet set DebitAmt = trialDeb.amount from (Select v.AccountId,                     
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.Departmentid From #vwJournalDetails v,                     
 #TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and                     
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtFROMDate and                     
 h.JournalDate <= @dtToDate group by v.CompanyId, v.AccountId, v.Departmentid) trialDeb Where                     
 trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID                     
 and trialDeb.CompanyId = @intCompanyId and trialDeb.Departmentid=#BalSheet.departmentid                 
                    
 Update #BalSheet set CreditAmt = trialDeb.amount from (Select v.AccountId,                     
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From                     
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and                     
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and                     
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate                    
 group by v.CompanyId, v.AccountId, v.departmentid) trialDeb Where                     
 trialDeb.Accountid = #BalSheet.AccId and                     
 trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId              
 and trialDeb.departmentid = #BalSheet.departmentid                      
      
      
         
 set  @intCount = 0                    
                    
                    
    SET @dblDebit = 0.0                    
    SET @dblCredit = 0.0                    
                      
    if @intFinId > (Select max(financialid) from aAccountfinyearopening where                     
    CompanyId = @intCOmpanyId )                      
    Begin                    
     select @dtPrevFinUnclosedSDate = sdate from vwfinyearperiod where                     
     CompanyId = @intCompanyId                     
     and FinancialId = (Select max(financialid) from aAccountfinyearopening where                     
      CompanyId = @intCOmpanyId )                    
                    
     select @dblDebit = Sum(isnull(Amount,0))                     
     from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g                    
     where g.groupid = a.groupid and  d.accountid = a.accountid and                     
     h.journalid = d.journalid and h.companyid = d.companyid                     
     and h.cancel =0 and journalcredit = 0 and                     
     (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )                     
      and (accounttype ='e' or accounttype ='i') and h.financialid > 0                     
                    
     select @dblCredit = Sum(isnull(Amount,0))                     
     from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g                    
     where g.groupid = a.groupid and  d.accountid = a.accountid and                     
     h.journalid = d.journalid and h.companyid = d.companyid                     
     and h.cancel =0 and journalcredit = 1 and                     
     (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )                     
     and (accounttype ='e' or accounttype ='i' ) and h.financialid > 0                     
                    
     if isnull(@dblDebit,0) + isnull(@dblCredit,0) >0                     
Begin                    
   Update #BalSheet set OBDr = isnull(OBDr,0) +                     
   (isnull(@dblCredit,0)) - isnull(@dblDebit,0) , OBCr = 0                    
   where AccId = (Select RetainedEarningsAcc from aSettings where                     
   CompanyId = @intCompanyId)                    
  End                      
                      
    End                     
                 
          
             
    set @dblDebit = 0.0                    
    set @dblCredit = 0.0                    
    /*select @strfromdate = convert(varchar,sdate,120) from vwfinyearperiod where CompanyId = @intCompanyId                     
    and FinancialId = (Select max(financialid) from aAccountfinyearopening where                     
    CompanyId = @intCompanyId ) */                    
                    
    select @dblDebit = Sum(isnull(Amount,0))                     
    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g                    
    where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid                     
    and h.cancel =0 and journalcredit = 0 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and                     
    (accounttype ='e' or accounttype ='i') and h.financialid > 0                     
                    
    select @dblCredit = Sum(isnull(Amount,0))                     
    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g                    
    where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid                     
    and h.cancel =0 and journalcredit = 1 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and                     
    (accounttype ='e' or accounttype ='i' ) and h.financialid > 0                     
                    
          
      
      
   Insert #FilteredResult(groupid , AccountCode ,        
    AccountDesc , groupdesc , parentGroupid ,                     
     orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)                     
--   exec SpGroupLevelOrdering_DETAIL @intCompanyId, 0          
   exec SpGroupLevelOrdering @intCompanyId, 0         
      
          
                    
              
Insert #BalSheetFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,                     
 OBCr, DebitAmt, CreditAmt, AccId, Departmentid, DepartmentName, orderno, levelcode, Checked,                     
 ProfitLoss, ParentGroupId)                    
SELECT b.CompanyId, b.AccCode, b.AcDesc, r.AccType, r.GroupId, r.GroupDesc, b.OBDr,                     
 b.OBCr, b.DebitAmt, b.CreditAmt, b.AccId,b.Departmentid, ad.DepartmentName, r.OrderNo, r.LevelCode,                     
 0,  isnull(@dblDebit,0) - isnull(@dblCredit,0) Bal, r.ParentGroupId from #FilteredResult r                     
 left outer join #balsheet b on  ((r.GroupId = b.GroupId  and r.AccountId is null  )                     
 or (r.GroupId = b.GroupId  and r.AccountId  = b.AccId and r.AccountId is not null ))      
 left outer join adepartmentmaster ad on ad.departmentid=b.departmentid                      
 where ((((isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) - isnull(creditamt,0))                     
 <> 0 and isnull(AcType,'') ='A') or ((isnull(obdr,0) + isnull(obcr,0) +                     
 isnull(creditamt,0)) -  isnull(debitamt,0) <> 0 and isnull(AcType,'') ='L') and                     
 b.accCode is not null) or b.accCode is null) and (r.AccType ='A' or r.AccType ='L' )              
--and r.departmentid=b.departmentid                    
 order by r.orderno                    
set @GroupId = 0         
      
      
                
-- TO avoid the groups which does not have any accounts information                    
 Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0                    
 Order by OrderNo Desc                    
                    
 While @GroupID <>0                     
 Begin                    
  set @intCount = 0                     
  Select @intCount = count(*) from #BalSheetFinal where                     
  ((AcDesc is not Null and Groupid= @GroupID)                    
   or ParentGroupid = @GroupID)                    
                    
  if @intCount = 0                     
   Delete from #BalSheetFinal where GroupId = @GroupID                    
  else                    
   Update #BalSheetFinal set Checked = 1 where Groupid = @GroupID                    
                    
  Set @GroupID  = 0                    
                    
  Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0                    
  Order by OrderNo Desc                    
                    
 End                     
                    
 Set @GroupID  = 0                    
                    
 if @intLevel>0                    
 Delete from #BalSheetFinal where LevelCode >= @intLevel and AccId is null                    
                    
 Select * from #BalSheetFinal order by OrderNo                     
                  
drop table #BalSheet                     
drop table #Tempjournalheader                    
drop table #vwJournalDetails                    
Drop Table #FilteredResult                    
Drop table #BalSheetFinal                    
                    
set nocount off                    
End
GO
/****** Object:  StoredProcedure [dbo].[spPLBudget]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO

/****** Object:  StoredProcedure [dbo].[spBankBalance]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 

/****** 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
GO

/****** Object:  StoredProcedure [dbo].[spBalanceconscheck]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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
GO

/****** Object:  StoredProcedure [dbo].[spFixedAssetopeningBalance]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spPLuserformat]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
 
  
  
/****** Object:  Stored Procedure dbo.spPLuserformat    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   : Accounts id taken from the table aRepFormatAccounts  
  
CREATE  proc [dbo].[spPLuserformat] (@strFROMDate as varchar(10), @strToDate as varchar(10),   
@intCompanyID as int,@intformatid as int, @intdep as int =0, @bitcons as bit)  
as  
set nocount on  
Declare @AcCode as varchar(50),  
 @AcID as int,  
 @AccDesc as varchar(100),  
 @AcType as varchar(1),  
 @dblDebit as numeric(18,2),  
 @dblCrEDit as numeric(18,2),  
 @AccountOBamount 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 int,  
 @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,   
 @strpartcode as varchar(5),   
 @jnObDr as numeric(18, 2),        
 @jnObCr as numeric(18, 2),  
 @dtFinStartDate as datetime  
  
Create table #PL(  
 CompanyID int,  
 AcID int,  
 AccCode varchar(25),  
 AccDesc varchar(60),  
 AcType varchar(1),  
 GroupID int,  
 GroupName varchar(50),  
 departmentname varchar(100),  
 tmonth int,  
 OpeningAmount numeric(18, 2),  
 amount numeric(18,2),  
 ParentGroupID int,  
 reportgroupid int,  
 iscaption varchar(5),  
 repgroupname varchar(50),  
 note varchar(50),  
 dwise char(1),  
 dorder int)  
  
SELECT @dtFROMDate = convert(datetime, @strFROMDate)  
SELECT @dtToDate = convert(datetime, @strToDate)  
  
select @strpartcode = partionchar from aaccrepformat where companyid = @intcompanyid and  
formatid = @intformatid  and type = 'p'  
  
set @strpartcode = '%'+rtrim(ltrim(@strpartcode))+'%'  
  
Declare curPL Cursor For  
-- Changed to accountid taken from the table   
SELECT   
 isnull(arg.AccountID,'') accountid, isnull(GM.GroupID,'') groupid ,   
 isnull(GM.GroupDesc,'') groupdesc , isnull(AccountCode,'') accountcode,   
 isnull(AccountDesc,'') accountdesc, isnull(AccountType,'') accounttype,   
 isnull(Openingamount,0) Openingamount, isnull(Openingdepamount,0) Openingdepamount,  
 isnull(ParentGroupID,0) ParentGroupID, arg.repgroupid, repg.iscaption,   
 repg.groupname, repg.groupcode, repg.departmentwise, repg.displayorderid  
FROM aaccrepgroup repg   
 left outer join   
  (select a.companyid,a.Openingamount,a.Openingdepamount, a.accountcode,  
  a.accountdesc,a.accountid,b.formatid,b.groupid repgroupid  
  from aAccountMaster a, aRepFormatAccounts b  
  where a.accountid=b.accountid and a.companyid=b.companyid)arg on  
  repg.companyid = arg.companyid  and repg.groupid = arg.repgroupid     
 left outer join aGroupMaster GM on    
  arg.companyid = gm.companyid and arg.repgroupid = gm.groupid   
  AND (GM.AccountType = 'I' OR GM.AccountType = 'E') ,  
  aaccrepformat repf   
 WHERE   
       repg.companyid= arg.companyid and repg.groupid = arg.repgroupid and   
           
       arg.companyid = repf.companyid and   
       repg.formatid = repf.formatid and repg.formatid = @intformatid  and repf.type ='p'   
       AND repg.CompanyID = @intCompanyID  
ORDER BY repg.displayorderid  
/*SELECT isnull(am.AccountID,'') accountid, isnull(GM.GroupID,'') groupid ,   
isnull(GM.GroupDesc,'') groupdesc , isnull(AccountCode,'') accountcode,   
isnull(AccountDesc,'') accountdesc, isnull(AccountType,'') accounttype,   
isnull(Openingamount,0) Openingamount, isnull(Openingdepamount,0) Openingdepamount,  
isnull(ParentGroupID,0) ParentGroupID, arg.repgroupid, repg.iscaption,   
repg.groupname, repg.groupcode, repg.departmentwise, repg.displayorderid  
FROM aaccrepgroup repg left outer join (select am.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 am, agroupmaster gm where am.companyid = gm.companyid and   
am.groupid = gm.groupid and (gm.accounttype='i' or gm.accounttype ='e')) arg on  
repg.companyid = arg.companyid  and repg.groupid = arg.repgroupid     
left outer join aAccountMaster AM on arg.companyid = am.companyid and   
arg.accountid = am.accountid left outer join aGroupMaster GM on   
am.companyid = gm.companyid and am.groupid = gm.groupid   
AND (GM.AccountType = 'I' OR GM.AccountType = 'E') ,  
 aaccrepformat repf WHERE repg.companyid = repf.companyid and   
repg.formatid = repf.formatid and repg.formatid = @intformatid and repf.type ='p'   
AND repg.CompanyID = @intCompanyID   
ORDER BY repg.displayorderid  
*/  
  
  
Open curPL  
  
Fetch Next FROM curPL into @AcID, @GroupID, @GroupDesc, @AcCode, @AccDesc, @AcType,   
@AccountOBamount, @AccountOBdepamount, @intParentGroupID, @intrepgroupid, @striscaption,@strrepgroupname,  
@strnote, @strdwise, @intdorder  
  
while @@fetch_status <> -1  
begin  
 set @dblDebit = 0.0  
 set @dblCrEDit = 0.0  
  
if (@strdwise ='a')  
begin  
 select @dtFinStartDate = sdate from vwfinyearperiod where companyid = @intcompanyid   
 and CurFinancialYear =1  
  
 if @intdep =0  --with out departmentselection  
 begin  
  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  
  
  SELECT @JournalOBDr = case when @bitcons =1 then isnull(Sum(isnull(Amount,0)),0)   
  else isnull(Sum(isnull(depAmount,0)),0) end FROM vwjournaldetails JD, moajournalheader JH  
  WHERE JD.JournalID = JH.JournalID AND JH.CompanyID = JD.CompanyID AND   
  JH.Cancel = 0 AND JD.CompanyID = @intCompanyID AND (jh.journaldate >=@dtFinStartDate and   
  JH.JournalDate < @dtFROMDate) AND JD.JournalCrEDit = 0 AND   
  jh.financialid > 0 and JD.AccountID = @AcID   
 end  
 else --including departmentcondition  
 begin  
  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  
  
  SELECT @JournalOBDr = case when @bitcons =1 then isnull(Sum(isnull(Amount,0)),0)   
  else isnull(Sum(isnull(depAmount,0)),0) end FROM vwjournaldetails JD, moajournalheader JH  
  WHERE JD.JournalID = JH.JournalID AND JH.CompanyID = JD.CompanyID AND   
  JH.Cancel = 0 AND JD.CompanyID = @intCompanyID AND (jh.journaldate >=@dtFinStartDate and   
  JH.JournalDate < @dtFROMDate) AND JD.JournalCrEDit = 0 AND   
  jh.financialid > 0 and JD.AccountID = @AcID   
 end   
  
 if @intdep =0  --with out departmentselection - credit  
 begin  
  SELECT @JournalOBCr = case when @bitcons =1 then isnull(Sum(isnull(Amount,0)),0)   
  else isnull(Sum(isnull(depAmount,0)),0) end FROM vwjournaldetails JD, moajournalheader JH  
  WHERE JD.JournalID = JH.JournalID AND JH.CompanyID = JD.CompanyID AND   
  JH.Cancel = 0 AND JD.CompanyID = @intCompanyID AND (jh.journaldate >=@dtFinStartDate and   
  JH.JournalDate < @dtFROMDate) AND JD.JournalCrEDit = 1   
  AND jh.financialid > 0  AND JD.AccountID = @AcID  
  
  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  
 end  
 else  --including departmentcondition  
 begin  
  SELECT @JournalOBCr = case when @bitcons =1 then isnull(Sum(isnull(Amount,0)),0)   
  else isnull(Sum(isnull(depAmount,0)),0) end FROM vwjournaldetails JD, moajournalheader JH  
  WHERE JD.JournalID = JH.JournalID AND JH.CompanyID = JD.CompanyID AND   
  JH.Cancel = 0 AND JD.CompanyID = @intCompanyID AND (jh.journaldate >=@dtFinStartDate and   
  JH.JournalDate < @dtFROMDate) AND JD.JournalCrEDit = 1   
  AND jh.financialid > 0  AND JD.AccountID = @AcID  
  
  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  
 end   
 if @AcType = 'I'   
  insert into #PL values(@intCompanyID, @AcID, @AcCode, @AccDesc, @AcType,   
  @GroupID, @GroupDesc, null,null, @JournalObCr - @JournalObDr,   
  @dblcredit - @dbldebit, @intparentgroupid, @intrepgroupid,   
  @striscaption, @strrepgroupname,@strnote,@strdwise,@intdorder)  
 else  
  insert into #PL values(@intCompanyID, @AcID, @AcCode, @AccDesc, @AcType,   
  @GroupID, @GroupDesc, null,null, @JournalObDr - @JournalObCr,   
  @dbldebit - @dblcredit, @intparentgroupid, @intrepgroupid,   
  @striscaption, @strrepgroupname, @strnote, @strdwise,@intdorder)    
end  
else  
begin --departmentwise  
 if @intdep =0  --with out department  
 begin  
  insert into #PL   
  select companyid, null, null, null, null, null,   
  null, departmentname, tmonth, 0 openingAmount, case when @bitcons =1 then isnull(Sum(isnull(Amount,0)),0)   
  else isnull(Sum(isnull(depAmount,0)),0) end amount,null, @intrepgroupid,   
  @striscaption, @strrepgroupname,@strnote,@strdwise,@intdorder from   
  ((SELECT jh.companyid,d.departmentname, tmonth, case when @bitcons =1 then   
  - isnull(sum(isnull(jd.amount,0)),0) else isnull(sum(isnull(jd.depamount,0)),0)   
  end amount FROM vwjournaldetailsmonthwise JD, moajournalheader JH, acompanymaster c,   
  adepartmentmaster d WHERE c.companyid = jh.companyid and d.companyid =   
  jd.companyid and d.departmentid = jd.departmentid and   
  JD.JournalID = JH.JournalID AND JH.CompanyID = jd.companyid AND JH.Cancel = 0   
  AND JD.CompanyID = @intcompanyid and jh.financialid > 0 AND   
  (JH.JournalDate >= @dtfromdate AND JH.JournalDate <=   
  @dttodate) AND JD.JournalCrEDit = 'n' AND JD.AccountID = @acid  
  group by jh.companyid, d.departmentname,tmonth)   
  union all  
  (SELECT jh.companyid,d.departmentname, tmonth, case when @bitcons =1 then   
  isnull(sum(isnull(jd.amount,0)),0) else isnull(sum(isnull(jd.depamount,0)),0)   
  end amount FROM vwjournaldetailsmonthwise JD, moajournalheader JH, acompanymaster c,   
  adepartmentmaster d WHERE c.companyid = jh.companyid and d.companyid =   
  jd.companyid and d.departmentid = jd.departmentid and   
  JD.JournalID = JH.JournalID AND JH.CompanyID = jd.companyid AND JH.Cancel = 0   
  AND JD.CompanyID = @intcompanyid and jh.financialid > 0 AND   
  (JH.JournalDate >= @dtfromdate AND JH.JournalDate <= @dttodate) AND   
  JD.JournalCrEDit = 'y' AND JD.AccountID = @acid group by jh.companyid,   
  d.departmentname,tmonth)) alltrans  
  group by companyid, departmentname, tmonth  
 end  
 else --with department selection  
 begin  
  insert into #PL   
  select companyid, null, null, null, null, null,   
  null, departmentname, tmonth, 0 OpeningAmount, case when @bitcons = 1 then   
  sum(isnull(amount,0)) else sum(isnull(depamount,0)) end amount,null, @intrepgroupid,   
  @striscaption, @strrepgroupname,@strnote,@strdwise,@intdorder from   
  ((SELECT jh.companyid,d.departmentname, tmonth, case when @bitcons =1 then   
  - isnull(sum(isnull(jd.amount,0)),0) else - isnull(sum(isnull(jd.depamount,0)),0)   
  end amount FROM vwjournaldetailsmonthwise JD, moajournalheader JH, acompanymaster c,   
  adepartmentmaster d WHERE c.companyid = jh.companyid and d.companyid =   
  jd.companyid and d.departmentid = jd.departmentid and   
  JD.JournalID = JH.JournalID AND JH.CompanyID = jd.companyid AND JH.Cancel = 0   
  AND JD.CompanyID = @intcompanyid and jh.financialid > 0 AND   
  (JH.JournalDate >= @dtfromdate AND JH.JournalDate <=   
  @dttodate ) AND JD.JournalCrEDit = 'n' AND JD.AccountID = @acid  
  and jd.departmentid = @intdep  
  group by jh.companyid, d.departmentname,tmonth)   
  union all  
  (SELECT jh.companyid,d.departmentname, tmonth, case when @bitcons =1 then   
  isnull(sum(isnull(jd.amount,0)),0) else isnull(sum(isnull(jd.depamount,0)),0)   
  end amount FROM vwjournaldetailsmonthwise JD, moajournalheader JH, acompanymaster c,   
  adepartmentmaster d WHERE c.companyid = jh.companyid and d.companyid =   
  jd.companyid and d.departmentid = jd.departmentid and   
  JD.JournalID = JH.JournalID AND JH.CompanyID = jd.companyid AND JH.Cancel = 0   
  AND JD.CompanyID = @intcompanyid and jh.financialid > 0 AND   
  (JH.JournalDate >= @dtfromdate AND JH.JournalDate <= @dttodate) AND   
  JD.JournalCrEDit = 'y' AND JD.AccountID = @acid and jd.departmentid = @intdep   
  group by jh.companyid,  d.departmentname,tmonth)) alltrans  
  group by companyid, departmentname, tmonth  
 end  
end  
  
 Fetch Next FROM curPL into @AcID, @GroupID, @GroupDesc, @AcCode, @AccDesc, @AcType,   
 @AccountOBamount, @AccountOBdepamount, @intParentGroupID, @intrepgroupid, @striscaption,  
 @strrepgroupname, @strnote,@strdwise,@intdorder  
  
end  
  
SELECT 's' as summary, rg.companyid, null dorder,   
rg.groupname repgroupname, null departmentname,   
null tmonth, null accdesc, null acid, null acccode, null actype, null groupid,   
null groupname, max(isnull(rg.groupcode,'')) note,    
max(rg.iscaption) iscaption, sum(isnull(OpeningAmount, 0)) OpeningAmount,  
 sum(isnull(amount, 0)) amount, null parentgroupid,   
null reportgroupid, null dwise  
FROM #PL right outer join (aaccrepgroup rg inner join aaccrepformat rf  on rg.companyid =   
rf.companyid and rg.formatid = rf.formatid and   
rf.companyid = @intcompanyid and rf.formatid = @intformatid and rf.type ='p') on  
#PL.reportgroupid = rg.groupid and  #PL.companyid = rg.companyid and   
rg.companyid = @intcompanyid  
group by rg.companyid, rg.groupid, rg.groupname   
  
union all  
  
select 'd' as summary, CompanyID, dorder, repgroupname, departmentname, tmonth, accdesc,   
max(AcID) acid,max(AccCode) acccode, max(AcType) actype,max(GroupID) groupid,   
max(GroupName) groupname,  max(note) note, max(iscaption) iscaption,   
sum(isnull(OpeningAmount, 0)) OpeningAmount,  
sum(isnull(amount,0)) amount, max(ParentGroupID) parentgroupid,   
max(reportgroupid) reportgroupid, max(dwise) dwise from #PL   
group by companyid, dorder,repgroupname, departmentname, tmonth, accdesc  
having sum(isnull(amount,0)) <> 0  
  
close curPL  
deallocate curPL  
set nocount off
GO
/****** Object:  StoredProcedure [dbo].[spULMASRoomBilling]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spULMASCheckOut]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
----------------------------------------------------------------------------
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spPlannedPL]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO

/****** Object:  StoredProcedure [dbo].[spMagnolia_Update_InHouseCons_ReturnHeader]    Script Date: 04/16/2012 10:32:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO

/****** Object:  StoredProcedure [dbo].[spUlShopDespToGodown]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spTrialBalance_Detail]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spSummarizeShopTransactions]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spULInvRecover]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spBudgetPLdep]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spULshopGoodsArrival]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheetDepNew]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spUL_FandB_Bill]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================      
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spPostingsAll]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spBalanceSheet_Liability_Comp]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------  
--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
GO
/****** Object:  StoredProcedure [dbo].[spOpeningBalance_Adjustment]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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  
  

------------------------------------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[spUlInvGdnToGdnTransfer]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
------------------------------
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spRptCustomBalanceSheet]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spPlannedBsheet]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---	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
GO
/****** Object:  StoredProcedure [dbo].[spUlInvDespToShop]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spULShopPosForSoneeAsOn04042011]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwlosshopitemshipmentdetail]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwShopInventoryValue]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwshipmentwiseshopstock]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwsellingtotalstockwithnegative]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwPandCInquiryUnprocessedStock]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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:  View [dbo].[vwAnalysisItems]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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:  StoredProcedure [dbo].[spItemStockDepartmentWise]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwSalesImportProdWise]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Last Modified by : Kishore, Hariharan , Hariharan R      
-- Modified on      : 09/05/2003, 14/05/2003, 06/06/2003      
-- Comments         : Added sales date column and removed grouping by      
--                    Month and year (08/03/2003)      
--                    Replaced view vwImportQty with vwPurchaseBillDetail (18/03/2003)      
--      : Given convert function to take the numeric values         
-----------------------------------------------------------------      
-- Replaced with source from v2 on 12/06/2003      
-----------------------------------------------------------------      
-- Modified on      : 18/06/2003      
-- Modified by      : Kishore      
-- Comment          : Added MonthName, MonthNo, YearName columns and other columns      
    
--Modified on       :12-08-09    
--Modified By       :Nidheesh     
--comment           :considered 'Percentage' as negative for RBD case     
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  
    
    
    
      
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].[vwserialnoitemsshopstock]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  StoredProcedure [dbo].[spSellingPriceFetchWOPriceChange]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spAnalysisofItemSalesByWeek]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Created by  :  Nidheesh P V        
-- Created on  : 15/01/2010         
-- Purpose     : To get weekly report for the Analysis of Item Sales        
  
--spAnalysisofItemSalesByWeek 0,0,'','20101202','20101202',0,0,0  
-------------------------------------    
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
GO
/****** Object:  View [dbo].[vwshopwisevalue]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwItemsoldCustomerwise]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[vwItemsoldCustomerwise] AS     
SELECT posdItemId ItemId,itemcode,itemdescription,    
poshShopId ShopId, posdQuantity Qty,     
posdUnitPrice SoldRate, dUnitPrice dSoldRate, cUnitPrice cSoldRate,    
poshBillDate SoldDate, 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, aItem a, aItemcategory b, apackingtype apt,adepartmentmaster adp     
WHERE posdItemId = a.ItemId    
AND a.ItemCategoryId = b.ItemCategoryId and apt.packingtypeid=vwShopItemSalesWithCustomerAndPack .packingtypeid 
AND vwShopItemSalesWithCustomerAndPack.poshShopId=adp.departmentid
GO
/****** Object:  StoredProcedure [dbo].[sppandcinquiryunprocessedstock]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwshipmentwisegodownstock]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[spSellingPriceFetch]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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
GO
/****** Object:  View [dbo].[vwserialnogodownitemstock]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  StoredProcedure [dbo].[spShipmentWiseItemFlow]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spULshopServiceInv]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spGetAccExrate]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
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
GO
/****** Object:  View [dbo].[vwdespatchtoshop]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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].[vwbookservinvoicesettle]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
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:  StoredProcedure [dbo].[spRemoveTillHeader]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------
--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
GO
/****** Object:  View [dbo].[vwAlreadyIssuedItems]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 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:  View [dbo].[vwHQAccPaidBills]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwhpfeePaymentdetails]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
 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].[vwInquiryShopStockSummary]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ===============================================      
-- 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:  View [dbo].[vwInquiryShopStockDatewise]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwInquiryShopStockDirect]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- 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:  StoredProcedure [dbo].[spItemDetailedSalesForecastment]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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
GO
/****** Object:  View [dbo].[vwBudgetActualAnalysis]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[spUpdateLedgersServiceInv]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Procedure
/****** 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: Jyothish S R
Modified On: 27.10.2011  
 Comments   : -isnull(TaxAmount,0) added in cursor    
*/    
--Ref No2    
--Modified By: Nidheesh P V   
--Modified On: 29.10.2011    
--Comments   : Checked isnull condition      

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,         
 @bitProduct = Product, @intFinancialID = FinancialID, @intCashAccountID = BankCashID,         
 @numconsRate = exchangeRate, @dtutime = updatetime, @numdeprate = depexrate,         
 @strexrates = exchangerates, @numGSTTaxAmount= isnull(TaxAmount,0) FROM AccountsInvoiceHeader         
 WHERE Cancelled = 0 and Posted = 0 and CompanyID = @intCompanyID and Proforma = 0 and         
 Product = 0 and invoiceid = @intInvoiceID        
        --Ref No2  isnull(TaxAmount,0) is added
 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))        
        
  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   - Ref No2 
  IF (@intServiceTaxID<>0  and @numAccGSTTaxAmount<>0 )      
 Begin      
  --   exec spConvertequiamount @intcustomerid, 'c', @intGSTOutPutAccountID, 'a',         
  --@strexrates, @numGSTTaxAmount, @numAccGSTTaxAmount output       
         
  INSERT INTO moajournaldetails (JournalID, JournalDetailID, CompanyID,         
  JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)         
   VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 1,         
  @intGSTOutPutAccountID, (@numGSTTaxAmount * @numconsRate),         
  @numAccGSTTaxAmount, @intDepartmentID, (@numGSTTaxAmount * @numdepRate) )        
  set @intJournalDetailID = @intJournalDetailID +1           
 END      
 ---Ref No1 end posting of GST amount    
       
 UPDATE AccountsInvoiceHeader SET Posted = 1 WHERE CompanyID = @intCompanyID and         
 InvoiceID = @intInvoiceID         
        
end
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersReceipts]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwadvancepaidreceiptsamounts]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[vwHPAgreementDetails]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*  
 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:  StoredProcedure [dbo].[spBudgetUtilization]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  View [dbo].[vwadvancepaidReturnAmounts]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwadvancepaidpaymentsamounts]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwadvancepaidtoretrive]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  StoredProcedure [dbo].[SpCashFlowSummary]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---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
GO
/****** Object:  StoredProcedure [dbo].[spReverseOldCostPrice]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateOldCostPrice]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-----------------------------------------------------------------------------------------
--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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAssetDisposal]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- Modified by : Hariharan R, Hariharan R 
-- Modified on : 04/03/2004, 07/04/2004, 16/04/2004
-- Comments    : Incremented the @intJournalDetailId after inserting to moaJournalDetails
--	       : Depreciation Exp AccId is used to get the disposal control account from asettings 
--             : Given postgroup columns
------------------------------------------------------------------------------
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

	Select @intDepExpControlAccId = depriciationexpaccid from aSettings where 
	Companyid = @intCompanyId

	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 
			Begin
			set @intJournalDetailID = @intJournalDetailID + 1

			--FOR POSTING REMAINING DEPRECIATION -------------------------------->
			exec spConvertequiamount @intdepid, 'd', 
			@intAccumDepaccid, 'a', @strexrates,
			@numDisDepeBalamt , @numaccamt output			
	
			insert into moajournaldetails(JournalID, journaldetailID, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, 
			PostGroup) 
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 1, 
			@intAccumDepaccid, @numDisDepeBalamt  * @numconsrate, @numaccamt, 
			@intDepID, @numDisDepeBalamt * @numdeprate, 2)
	
			set @intJournalDetailID = @intJournalDetailID + 1				

			exec spConvertequiamount @intdepid, 'd', 
			@intDepExpAccId, 'a', @strexrates,
			@numDisDepeBalamt , @numaccamt output			
			    	
			insert into moajournaldetails(JournalID, journaldetailID, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentid, 
			depamount, PostGroup) 
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 0, 
			@intDepExpAccId, @numDisDepeBalamt * @numconsrate, @numaccamt, 
			@intDepID, @numDisDepeBalamt * @numdeprate, 2)

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

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

			set @intJournalDetailID = @intJournalDetailID + 1	

			exec spConvertequiamount @intdepid, 'd', 
			@intDepExpControlAccId, 'a', @strexrates,
			 @numDispSalesValue , @numaccamt output,''			
	
			insert into MoaJournalDetails(JournalID, journaldetailID, CompanyID,
			JournalCrEDit, AccountID, Amount, actualAmount,departmentid, 
			depamount, PostGroup) 
			values (@intJournalID, @intjournalDetailID, @intCompanyID, 0 , 
			@intDepExpControlAccId,  @numDispSalesValue * @numconsrate, @numaccamt, 
			@intDepID,  @numDispSalesValue * @numdeprate, 4)

			End	

			set @intJournalDetailID = @intJournalDetailID + 1	
			--<POSTING OF SALES WHILE DISPOSING -----------------------------------	

			Set @numDebitAmt = 0.0
			Set @numDisDepeBalamt = 0.0
			Set @numDispSalesValue = 0.0
			Set @numUPTODepValue = 0.0

		fetch next FROM DebitassetdisposalCur into @intassetid,@intDiposalAccId, 
		@numDebitAmt, @numDisDepeBalamt, @numDispSalesValue, @numUPTODepValue,
		@intassetaccountid, @intAccumDepaccid, @intDepExpAccId

	 end 	
	end  
 update AssetDisposalHeader set disphposted =1 WHERE disphcompanyid =  @intCompanyID 
	and disphid=@intdisposalid

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

-- 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAssetRegister]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLedgersAssetTransfer]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersForex]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spaccountsarriveexdiff]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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] @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  
  
-------------------------------------------------------------------------------------------
GO
/****** Object:  StoredProcedure [dbo].[spULshopPayments]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersJournal]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersContra]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersInterDivisionBills]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spvendorarriveexdiff]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------    
  
    
      
        
          
----                 
--Modified on  : 08/02/2004                
--Modified by   : Hariharan                 
--Comments  : modified the vendor selection                
--Verified by      : Hariharan                 
--Verified Date     : 03/05/2004 (verified From Client DB)    
----modified by      : jyothish    
--modified Date     : 15/12/2011      
/*    
This SP modified and send to SIMDI as emergency. So to keep a back up I changed name of SP and placed in same server.    
    
*/            
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)              
              
                
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              
  exec spConvertequiamount @intvenCurrID, 'm', @intConsCurrID,                 
  'm', @strexrates , @numresbal, @numdepamount output,  'r'                 
 END              
 ---------------------------------------------------------------              
 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              
 ------------------------            
  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)              
  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                
    ---exec spConvertequiamount @intConsCurrID, 'm', @intDepCurrID,                 
    ---'m', @strexrates , @numdiffamt, @numConsamount output,  'r'                 
    ---insert into #temp2 values (@intcompanyid, @intvendorid, @strvendorname, @numdepbal,                 
    ---@numConsbal,@numresbal,@numConsamount ,@numdepamount, @bitjournalcredit)               
                
insert into #temp2 values (@intcompanyid, @intvendorid, @strvendorname, @numdepbal,                 
    @numConsbal,@numresbal,@numdiffamtDep,@numdiffamtCon , @bitjournalcredit)                
  END                
 END  ---END OF exchange difference                
 delete from #temp1 where vendorid = @intvendorid                
 select @intcount = count(*) from #temp1                
end -- for while                
select * from #temp2                
set nocount off                
end
GO
/****** Object:  StoredProcedure [dbo].[spCustomerArriveExDiff]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Modified on  : 14/06/2005    
--Modified by   : Hariharan R    
--Comments  : Modified the vendor selection    
--   : Removed the currencyid filteration and allowed all     
--   : customers to undergo checking, Incorporated vwCustomerledger in temp1 insertion to increase speed 
   ----modified by      : jyothish    
--modified Date     : 15/12/2011 
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)    
    
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,    
  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, 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,@numdiffamt, @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
GO
/****** Object:  StoredProcedure [dbo].[spCustomerArriveExDiff_ServerBackup]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------




--Modified on		: 14/06/2005
--Modified by 		: Hariharan R
--Comments		: Modified the vendor selection
--			: Removed the currencyid filteration and allowed all 
--			: customers to undergo checking, Incorporated vwCustomerledger in temp1 insertion to increase speed
/*
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
GO
/****** Object:  StoredProcedure [dbo].[spPostingsBankDateWise]    Script Date: 04/16/2012 10:32:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spTargetAchievement]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_ServiceHistoryWeb1]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spMagnolia_ServiceHistoryWeb]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spInventoryValueAsOnDate]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------  
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateOldExchangeRates1]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
--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
GO
/****** Object:  StoredProcedure [dbo].[spBudgetvariance]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spInterdivisionalBalance]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[SpShopItemSalesOfLastYear]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwPrePurchaseOrderTracking2]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------
--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].[vwhpCustomerLedger]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*      
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].[vwHPNonSettledCustomer]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*          
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].[vwHQPurchaseBillsPaid]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwavgmonthlysale]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------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].[spUnsettledAccBills]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  View [dbo].[vwsellingtotalstock]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwpostingsdifference]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwjournaldetailsmonthwise]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[spBankCashBalanceMIS]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  StoredProcedure [dbo].[spSerialNoFetch]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------  
--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
GO
/****** Object:  StoredProcedure [dbo].[spCRM_GeneratePrefix]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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]
GO
/****** Object:  View [dbo].[vwTargetActualAnalysis]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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:  StoredProcedure [dbo].[spQuoteDiscount]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vAllIndexes]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  View [dbo].[vwCashInflow]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[spBankCashBalanceDept]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ===========================================================      
-- 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
GO
/****** Object:  View [dbo].[vwcreditinvoicesettlecommision]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  StoredProcedure [dbo].[spShopTotalStockVerification]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  
-- 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
GO
/****** Object:  View [dbo].[vwtotalbillpaidamount]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

/****** 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:  StoredProcedure [dbo].[spPostings]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spSummarizeTransactions]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spaccountsarriveexdiff_BACKUP24022012]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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        
        
-------------------------------------------------------------------------------------------
GO

/****** Object:  StoredProcedure [dbo].[spUpdateCostingMethodPrice]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----   
--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
GO
/****** Object:  StoredProcedure [dbo].[spUpdateCostingMethodPriceSummary]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---Created By : Bijesh.B
--Date       : 07/11/2011
--Ref No.    : RefNo-1
--Des : this is a copy of spUpdateCostingMethodPrice
--      Since Sonee reported ODBC-Time Out error,
--      to overcome this issue, instead of  taking stock from 
--		vwinquiryshopstock in this sp, we use vwinquiryshopstockSummary
--      and used vwInquiryGodownStockSummary instead of vwInquiryGodownStock 
 --modified by  : jyothish 
 --modified Date : 01/02/2012  
 --prevoius  stock and costprice insert to losCosAvlStock
create proc [dbo].[spUpdateCostingMethodPriceSummary] (@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  
     
--RefNo-1 start commented and added  
 --   Select @numGdnQty = isnull(sum(isnull(gsstock,0)),0) from vwinquirygodownstock where --  
 --   gsitemid = @intItemID    
    Select @numGdnQty = isnull(sum(isnull(gsstock,0)),0) from vwInquiryGodownStockSummary where   
 gsitemid = @intItemID    
  
   --Select @numShopQty = isnull(sum(isnull(stock,0)),0) from vwinquiryshopstock where   
   --itemid = @intItemID    
 Select @numShopQty = isnull(sum(isnull(stock,0)),0) from vwInquiryShopStockSummary where   
 itemid = @intItemID   
--RefNo-1 ends  
  
   Select @intcostingid = chCostingID from loacostingheader where chBillID = @intBillid  
   and chCancelled=0  
 Select @numBillQty = cdItemQuantity from loacostingdetail where cdcostingid = @intcostingid  
 and cditemid = @intItemid  
  
 set @numtotalqty = isnull(@numGdnQty,0) + isnull(@numShopQty,0)  +   
 isnull(@numprocpendqtystock,0) +  isnull(@numprevunreceivedqty,0)  +   
 isnull(@numprevunconfirmedqty,0) + isnull(@numnondespbillqty,0)   
 - isnull(@numothershipments ,0)  
 
 insert into losCosAvlStock (CompanyId,CostingID,ItemID,OldStock) values(1,@IntCostingID,@intItemID,@numtotalqty)

   if @numtotalqty < 0   
 set @numtotalqty = 0  
   set @numTotal = (@numBillQty * @costPrice) + (isnull(@numtotalqty,0) * isnull(@numItemUP,0))  

   set @numWAVGAmt = @numTotal / (@numtotalqty  + @numBillQty)  
  
end
GO
/****** Object:  View [dbo].[vwHPProcessingWithAllDetails]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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:  StoredProcedure [dbo].[spUpdateOldExchangeRates2]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-----------------------------------------------------------------------------------------
--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
GO
/****** Object:  View [dbo].[vwPORequestFlow]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwtotalinventory]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[sphpadvancePayments]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spMag_GetShopItemPrice]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--CREATED BY : NIDHEESH P V            
--CREATED ON : 01/08/2011            
--COMMENTES : TO GET SHOP ITEM DETAILS INCLUDING PRICE LIST(CAN MODIFY FOR MORE DETAILS)            
--MODIFIED AREA : RPTITEMPRICELIST            
            
--spMag_GetShopItemPrice 1,0,0,'33,34',0,'',1,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)            
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 (select cid from dbo.fnSplit(@strItemCate,',')) OR @strItemCate='')    --(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))            
 INNER JOIN acurrencymaster cm on cm.currencyid=ssd.currencyid            
 INNER JOIN  aShops s ON asd.shopid = s.ShopID            
 LEFT OUTER JOIN vwInquiryShopStock vs ON  @IntStock=1 and vs.shopid=asd.shopid and vs.itemid=asd.itemid and vs.stock>0      
)            
select * from cteShopItems where selectORder=1 ORder by shopname            
SET NOCOUNT OFF            
            
END
GO
/****** Object:  StoredProcedure [dbo].[spUpdateShopStockMerging]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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
GO

/****** Object:  StoredProcedure [dbo].[spUpdateGodownStockMerging]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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      
		---------------------------------------------------------
GO

/****** Object:  StoredProcedure [dbo].[spLocationMerging]    Script Date: 04/16/2012 10:32:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-----------------------------------------------------

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

--------------------------------------------------------------
GO


/****** Object:  StoredProcedure [dbo].[spULshopinterdepsale]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spTotalInventory]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[SpMag_FetchItem]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ===========================================================
-- 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
GO
/****** Object:  View [dbo].[vwSellingFixAtShops]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
----     
-- 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:  StoredProcedure [dbo].[spULshopinterdeppurchase]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---- 
/*
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
GO
/****** Object:  StoredProcedure [dbo].[spbsuserformat]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spAssetDetails]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
----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
GO
/****** Object:  StoredProcedure [dbo].[spBudUserFormat]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spFixedAssetRpt]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[splocalpurchasecosting]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec splocalpurchasecosting 47 ,2,35        
        
        
---------------------------------------------------------------------------          
--Create By : VinothMurugan V.          
--Date     : 26/07/2010          
--Purpose   : Doing Direct Local Purchase Costing From Local Purchase Bill          
--ReQuest By: Kooddoo          
---modified by : Jyothish S R        
--Date      :09/08/2010        
----purpose division by zero erro        
---------------------------------------------------------------------------
--Ref.No.1    
--Modified By :AADYA KUMAR D V
--Modified on :24/11/2011
--Modification:Just remove hardcoded department id
---------------------------------------------------------------------------         
          
--select * from aitem where itemid = 2294           
--exec splocalpurchasecosting 47,2,1            
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,3),          
lpcdbillunitprice numeric(28,16),          
lpcdolditemcostprice numeric(18,2),          
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,2)          
declare @costingid as int    
declare @index as int          
declare @count as int           
declare @lpditemid as int           
declare @olditemrate as int          
set @costingid = (select isnull(max(lpchcostingid),1) from loaLocalPurchaseCostingHeader)          
set @count = (select count(lpcddetailid) from #temp where lpcdcostingid = @costingid )          
set @index = 1          
          
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      
 update  #temp set lpcdnewitemcostprice =( ((@totalStock * @olditemrate) + (lpcdcostedprice * lpcditemqty))/(@totalStock + lpcditemqty ) )           
 where lpcdcostingid = @costingid and  lpcddetailid = @index   and  @totalStock + lpcditemqty <>0        
 End      
Else      
 begin      
 update  #temp set lpcdnewitemcostprice=lpcdcostedprice where  lpcdcostingid = @costingid and  lpcddetailid = @index       
End      
--- @totalStock + lpcditemqty <>0 added for avoid divsion by zeoro error         
    update aitem set itemrate= lpcdnewitemcostprice from #temp where itemid=lpcditemid and lpcddetailid = @index and lpcdcostingid = @costingid          
 if @olditemrate <> (select lpcdnewitemcostprice from #temp where  lpcdcostingid = @costingid and  lpcddetailid = @index )          
 begin           
  Update losshopitemshipmentdetail set pricechanged=1 from #temp where itemid=lpcditemid          
 end          
          
 set @index = @index +1          
end          
          
insert into loalocalpurchasecostingdetail          
select * from #temp          
          
drop table #temp          
          
end
GO
/****** Object:  StoredProcedure [dbo].[spStockOutCompanyWiseForecasting]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spStockOutCompanyWise]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  StoredProcedure [dbo].[spPandCInquiryShopStock]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================================================  
-- 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
GO

/****** Object:  View [dbo].[vwItemDetailsForStockReordering]    Script Date: 04/16/2012 10:32:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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:  StoredProcedure [dbo].[SpPopulateAccountsBills]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------------------------------------------                                                
--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
GO
/****** Object:  View [dbo].[vwcustomeradvance]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwbillspaymentformis]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwAdvancePaidToRetriveCustomer]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- 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].[gmleveltwo]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[VWItemRateDetails]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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:  StoredProcedure [dbo].[spDayendReportBackupAsOn07062011]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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 ,''
GO
/****** Object:  StoredProcedure [dbo].[spDayendReport_Sonee]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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 ,''
GO
/****** Object:  StoredProcedure [dbo].[spDayendReport_BackupAsOn_22032011]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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 ,''
GO
/****** Object:  StoredProcedure [dbo].[spDayendReport]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Last Modified on  : 12/12/02                
--Modified by  : leo                
--Comments  : v3                
--last modified on  :16/06/03                
--modified by  :venki                
--comments  :added dept symbol also                
--modified by  :Prasanth Joseph                
--comments  :added HP Details   
-------------------------------------     
--MODIFIED BY: NIDHEESH PV  
--MODIFIED ON: 16/12/2010  
--COMMENTS: CHANGED THE LABEL       
--changed 'Payments Deducted' to 'Amount After Payments'    
--because 'Payments Deducted' makes a bit confusion while using the report.  
------------------------------------------------------------------------------     
-- Modified by : Bijesh.B  
-- Date        : 25/07/2011  
-- RefNo       : RefNo-1   
-- Comments    : PD Cheque feature added, corrected error in total sales      
--               Since Post Dated Cheque (Fully/Partially) option was included  --     in POS(Sonee) interface,the difference between 'BILL AMOUNT' and  --     PD Cheque Amount is the actual Cash Sales     -- spDayendReport '20110606',11  
-------------------------------------------------------------------------------  
-- Modified by : Nidheesh P V    
-- Date        : 20/10/2011        
-- RefNo       : RefNo-2         
-- Comments    : Added tax details in the day end report.    
--commented the service invocie section because service invoice is already listing in Credit Sales     
-------------------------------------------------------------------------------       
-- Modified by : Benzigar S D    
-- Date        : 28/10/2011        
-- RefNo       :        
-- Comments    : Added prefix for GrnhGoodsreturnnoteDate    
-------------------------------------------------------------------------------       
  
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                
                
select lh.GrnCompanyID,lh.grnhShopid,CustomerName,lh.GrnhGoodsreturnnoteNO reference,                
lh.GrnhGoodsreturnnoteDate, vw.goodsreturnamt amount, vw.goodsreturnamt* grnhdepexrate damount,                
vw.goodsreturnamt*grnhexchangerate camount,15 as type, 'Goods Return' as Trans,  
-- RefNo-1 start  
--0.0 as mode,0.0 as dmode, 0.0 as cmode,   
 -vw.goodsreturnamt  as mode, -vw.goodsreturnamt* grnhdepexrate as dmode,   
 -vw.goodsreturnamt*grnhexchangerate as cmode,  
-- RefNo-1 end  
 0.0 as sales, 0.0 as dsales, 0.0 as csales ,cu.symbol                
 from                 
losgoodsreturnnoteheader lh,vwgoodsreturnamount vw,acustomermaster ac,                
ashops sh,adepartmentmaster ad,acurrencymaster cu                
where vw.GrnhGoodsreturnnoteID=lh.GrnhGoodsreturnnoteID and vw.grnhshopid=lh.grnhShopid                
and lh.GrnhCancel=0 and                 
sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and sh.shopid=lh.grnhShopid and                
lh.GrnhGoodsreturnnoteDate=@dttransdate and lh.grnhShopid=@intshopid                
and ac.CustomerID=lh.GrnhCustomerID                
                
                
union all                
                
select s.companyid, s.shopid, '' accountdesc, '', billdate, 0.0 amount, 0.0 damount, 0.0 camount,                 
16 as type, 'Total Sales' as trans, 0.0 amount, 0.0 damount, 0.0 camount, 0.0 sales, 0.0 dsales,                 
0.0 csales ,cu.symbol                 
from ashops s, vwcashsales  c,adepartmentmaster ad,acurrencymaster cu                
where                
s.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and                 
s.shopid=c.shopid and                
billdate=@dttransdate  and s.shopid =@intshopid          
group by s.companyid,s.shopid,billdate ,cu.symbol                
                
UNION ALL           
  
    
 ---RefNo-2---------------                 
    
select cs.companyid , cs.shopid, convert(varchar(10),TaxPercentage) + '% GST' as Description, '' as reference, billdate,                       
sum(TaxAmount) amount, sum(DTaxAmount) damount, sum(CTaxAmount) camount, 17 as type, 'Collected Sales Tax Splitup' as trans,                        
sum(TaxAmount) as mode, sum(DTaxAmount) as dmode, sum(CTaxAmount) as cmode,     
0.0 sales,0.0 dsales,0.0 csales, '' as symbol --,cu.symbol        
---------kept symbol as blank.becuase there can be cash/credit.so cannot link to accountmastre--------------                  
from vwCollectedSalesTax cs    
--,aaccountmaster am,ashops sh,adepartmentmaster ad,acurrencymaster cu                      
where --cs.accountid = am.accountid and cs.companyid = am.companyid and                      
--sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and sh.shopid=cs.shopid and     
TaxPercentage<>0 and                     
billdate=@dttransdate and cs.shopid =@intshopid                      
group by cs.companyid ,cs.shopid, billdate,TaxPercentage     
--,accountdesc     
                   
UNION ALL      
    
select cs.companyid , cs.shopid, convert(varchar(10),TaxPercentage) + '% GST' as Description, '' as reference, billdate,                       
sum(TaxAmount) amount, sum(DTaxAmount) damount, sum(CTaxAmount) camount, 18 as type, 'Refunded Sales Tax Splitup' as trans,                        
sum(-TaxAmount) as mode, sum(-DTaxAmount) as dmode, sum(-CTaxAmount) as cmode,     
0.0 sales,0.0 dsales,0.0 csales, '' as symbol --,cu.symbol       
---------kept symbol as blank.becuase there can be cash/credit.so cannot link to accountmastre--------------                                   
from vwRefundedSalesTax cs    
--, aaccountmaster am,ashops sh,adepartmentmaster ad,acurrencymaster cu                      
where     
--cs.accountid = am.accountid and cs.companyid = am.companyid and                      
--sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and                       
--sh.shopid=cs.shopid and     
TaxPercentage<>0 and                 
billdate=@dttransdate and cs.shopid =@intshopid                      
group by cs.companyid ,cs.shopid, billdate,TaxPercentage     
--accountdesc ,cu.symbol,    
       
                     
UNION ALL      
    
select s.companyid, s.shopid, '' accountdesc, '', billdate, 0.0 amount, 0.0 damount, 0.0 camount,                       
19 as type, 'Total tax' as trans, 0.0 amount, 0.0 damount, 0.0 camount, 0.0 sales, 0.0 dsales,                       
0.0 csales ,cu.symbol                       
from ashops s, vwcashsales  c,adepartmentmaster ad,acurrencymaster cu                      
where                      
s.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and                       
s.shopid=c.shopid and                      
billdate=@dttransdate  and s.shopid =@intshopid                
group by s.companyid,s.shopid,billdate ,cu.symbol                      
    
UNION ALL      
 ---RefNo-2---------------      
       
                
select 0, 0, '' , '', null, 0.0 amount, 0.0 damount, 0.0 camount,                 
'' as type, '' as trans, 0.0 amount, 0.0 damount, 0.0 camount, 0.0 sales, 0.0 dsales ,                
0.0 csales ,''
GO
/****** Object:  StoredProcedure [dbo].[spgetgodownstockasondate]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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
GO
/****** Object:  View [dbo].[vwTotalInvoiceReceiptAmount]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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].[vwcustomersummaryasdate]    Script Date: 04/16/2012 10:32:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--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].[spDebtorAgeSum_tem]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwshipmentwisestock]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwItemsHavingStock]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--------------------------------------------------------------------------------  
-- 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].[vwsellingtotalstockwithnegative_company]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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:  StoredProcedure [dbo].[spQuickItemInquiry]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
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.      
        
--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        
        
*/
GO
/****** Object:  StoredProcedure [dbo].[spvendorarriveexdiff_BackUp]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

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

----   
--Modified on  : 08/02/2004  
--Modified by   : Hariharan   
--Comments  : modified the vendor selection  
--Verified by      : Hariharan   
--Verified Date     : 03/05/2004 (verified From Client DB)  
--modified by      : jyothish
--modified Date     : 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
GO
/****** Object:  StoredProcedure [dbo].[spPostingsBankMonthWise]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  StoredProcedure [dbo].[spDebtorAgeSumWithAdvance]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--***************************************************************************************************          
-- Created by  :  Nidheesh P V          
-- Created on  : 06/07/2011            
-- Purpose     : To Get Debtor Age For  0 - 15,16 - 30 ,31 - 60, 61 - 120,121 - 240,241 - 365     
--and to display the customer even if the customer has no invoice/settlement but an advance is there.       
--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
GO
/****** Object:  StoredProcedure [dbo].[spCustomerAdvanceAsOnDate]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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
GO
/****** Object:  View [dbo].[vwquotationtracking3]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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].[vwPrePurchaseOrderTracking3]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
------------------------------------------------------------------------
--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:  StoredProcedure [dbo].[sphpCustomerReconcilation]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--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
GO
/****** Object:  View [dbo].[vwVendorSummaryAsDate]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 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: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
-- 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].[gmlevelthree]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwCreditorAgeSum]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[gmlevelfour]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwgroupmasterwithlevel]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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].[vwchartofaccounts]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  View [dbo].[vwfixedassetbills]    Script Date: 04/16/2012 10:32:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/****** 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:  Default [DF__aCustomsM__rowgu__48DABF76]    Script Date: 04/16/2012 10:32:02 ******/
ALTER TABLE [dbo].[aCustomsMaster] ADD  CONSTRAINT [DF__aCustomsM__rowgu__48DABF76]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__InterDivi__Cance__05D055CB]    Script Date: 04/16/2012 10:32:21 ******/
ALTER TABLE [dbo].[InterDivisionJournalTransHeader] ADD  DEFAULT ((0)) FOR [Cancelled]
GO
/****** Object:  Default [DF_losexpiryarrivaldetails_eadCancel]    Script Date: 04/16/2012 10:32:21 ******/
ALTER TABLE [dbo].[losexpiryarrivaldetails] ADD  CONSTRAINT [DF_losexpiryarrivaldetails_eadCancel]  DEFAULT (0) FOR [eadCancel]
GO
/****** Object:  Default [DF_losexpiryarrivaldetails_eadAdjustment]    Script Date: 04/16/2012 10:32:21 ******/
ALTER TABLE [dbo].[losexpiryarrivaldetails] ADD  CONSTRAINT [DF_losexpiryarrivaldetails_eadAdjustment]  DEFAULT (0) FOR [eadAdjustment]
GO
/****** Object:  Default [DF__InterDivi__Amoun__07B89E3D]    Script Date: 04/16/2012 10:32:21 ******/
ALTER TABLE [dbo].[InterDivisionJournalTransDetails] ADD  DEFAULT ((0)) FOR [Amount]
GO
/****** Object:  Default [DF__losfuture__rowgu__6FB62C23]    Script Date: 04/16/2012 10:32:31 ******/
ALTER TABLE [dbo].[losfuture] ADD  CONSTRAINT [DF__losfuture__rowgu__6FB62C23]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aGlobalUs__rowgu__63E3BB6D]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aGlobalUsers] ADD  CONSTRAINT [DF__aGlobalUs__rowgu__63E3BB6D]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losposWarDet__rowgu__2937F6EB]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[losposWarDet] ADD  CONSTRAINT [DF__losposWarDet__rowgu__2937F6EB]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__mesfuture__rowgu__5E2AE217]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[mesfuture] ADD  CONSTRAINT [DF__mesfuture__rowgu__5E2AE217]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aShipment_sCostingDone]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aShipment] ADD  CONSTRAINT [DF_aShipment_sCostingDone]  DEFAULT (0) FOR [sCostingDone]
GO
/****** Object:  Default [DF__aShipment__rowgu__70E8B0D0]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aShipment] ADD  CONSTRAINT [DF__aShipment__rowgu__70E8B0D0]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_Fb_botheader_Fb_bh_cancelled]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[Fb_botheader] ADD  CONSTRAINT [DF_Fb_botheader_Fb_bh_cancelled]  DEFAULT ((0)) FOR [Fb_bh_cancelled]
GO
/****** Object:  Default [DF__aShopCheq__futur__010BA0AE]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aShopChequeAccountDetails] ADD  DEFAULT ('') FOR [futurevc]
GO
/****** Object:  Default [DF__aShopCheq__rowgu__01FFC4E7]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aShopChequeAccountDetails] ADD  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aCustomerGroup_rowguid]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aCustomerGroup] ADD  CONSTRAINT [DF_aCustomerGroup_rowguid]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aCustomer__Prefi__2A8CD92E]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aCustomerGroup] ADD  DEFAULT ('') FOR [Prefix]
GO
/****** Object:  Default [DF__aCustomer__Prefi__2B80FD67]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aCustomerGroup] ADD  DEFAULT ((0)) FOR [PrefixActive]
GO
/****** Object:  Default [DF_aUserAuditHeader_hSaved]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aUserAuditHeader] ADD  CONSTRAINT [DF_aUserAuditHeader_hSaved]  DEFAULT (0) FOR [hSaved]
GO
/****** Object:  Default [DF__ahqPostDa__updat__7C46EB91]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[ahqPostDatedChequeDetails] ADD  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF_aItemCategory_SPDefMargin]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aItemCategory] ADD  CONSTRAINT [DF_aItemCategory_SPDefMargin]  DEFAULT (0) FOR [SPDefMargin]
GO
/****** Object:  Default [DF_aItemCategory_DPDefMargin]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aItemCategory] ADD  CONSTRAINT [DF_aItemCategory_DPDefMargin]  DEFAULT (0) FOR [DPDefMargin]
GO
/****** Object:  Default [DF_aItemCategory_WPDefMargin]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aItemCategory] ADD  CONSTRAINT [DF_aItemCategory_WPDefMargin]  DEFAULT (0) FOR [WPDefMargin]
GO
/****** Object:  Default [DF_aItemCategory_DPDefQty]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aItemCategory] ADD  CONSTRAINT [DF_aItemCategory_DPDefQty]  DEFAULT (0) FOR [DPDefQty]
GO
/****** Object:  Default [DF_aItemCategory_WPDefQty]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aItemCategory] ADD  CONSTRAINT [DF_aItemCategory_WPDefQty]  DEFAULT (0) FOR [WPDefQty]
GO
/****** Object:  Default [DF_aItemCategory_SalesValue_1]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aItemCategory] ADD  CONSTRAINT [DF_aItemCategory_SalesValue_1]  DEFAULT (0) FOR [SalesValue]
GO
/****** Object:  Default [DF__aItemCate__rowgu__5A054B78]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aItemCategory] ADD  CONSTRAINT [DF__aItemCate__rowgu__5A054B78]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aHQPDCheq__PDChe__332D0C27]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aHQPDChequeProcessing] ADD  DEFAULT ((0)) FOR [PDChequePosted]
GO
/****** Object:  Default [DF__aBrandMas__rowgu__38102627]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aBrandMaster] ADD  CONSTRAINT [DF__aBrandMas__rowgu__38102627]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aKitItemM__Gener__78015961]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aKitItemMaster] ADD  DEFAULT (0) FOR [GenerateBarcode]
GO
/****** Object:  Default [DF_Discountheader_Discountid]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[Discountheader] ADD  CONSTRAINT [DF_Discountheader_Discountid]  DEFAULT ((0)) FOR [Discountid]
GO
/****** Object:  Default [DF__aReports__Report__18F838D8]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aReports] ADD  DEFAULT ((0)) FOR [ReportActive]
GO
/****** Object:  Default [DF_losSerStandByReceiptHeader_rhUpdateTime]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[losSerStandByReceiptHeader] ADD  CONSTRAINT [DF_losSerStandByReceiptHeader_rhUpdateTime]  DEFAULT (getdate()) FOR [rhUpdateTime]
GO
/****** Object:  Default [DF__aCompanyM__rowgu__41A3B202]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aCompanyMaster] ADD  CONSTRAINT [DF__aCompanyM__rowgu__41A3B202]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aUserGroupGodownDetails_rowguID]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aUserGroupGodownDetails] ADD  CONSTRAINT [DF_aUserGroupGodownDetails_rowguID]  DEFAULT (newid()) FOR [rowguID]
GO
/****** Object:  Default [DF_aUsergroups_rowguid]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aUsergroups] ADD  CONSTRAINT [DF_aUsergroups_rowguid]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losexpiryissuedetails_eidCancel]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[losexpiryissuedetails] ADD  CONSTRAINT [DF_losexpiryissuedetails_eidCancel]  DEFAULT (0) FOR [eidCancel]
GO
/****** Object:  Default [DF_losexpiryissuedetails_eidAdjustment]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[losexpiryissuedetails] ADD  CONSTRAINT [DF_losexpiryissuedetails_eidAdjustment]  DEFAULT (0) FOR [eidAdjustment]
GO
/****** Object:  Default [DF_losPosChequeDetails_PosChequeUsed]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[losPosChequeDetails] ADD  CONSTRAINT [DF_losPosChequeDetails_PosChequeUsed]  DEFAULT ((0)) FOR [PosChequeUsed]
GO
/****** Object:  Default [DF__aSize__rowguid__7C5A637C]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aSize] ADD  CONSTRAINT [DF__aSize__rowguid__7C5A637C]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__BudgetPla__bphCa__7B1CF1D7]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[BudgetPlanHeader] ADD  CONSTRAINT [DF__BudgetPla__bphCa__7B1CF1D7]  DEFAULT (0) FOR [bphCancelled]
GO
/****** Object:  Default [DF_JournalDetailBackup_Amount]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[JournalDetailBackup] ADD  CONSTRAINT [DF_JournalDetailBackup_Amount]  DEFAULT (0) FOR [Amount]
GO
/****** Object:  Default [DF_JournalDetailBackup_ActualAmount]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[JournalDetailBackup] ADD  CONSTRAINT [DF_JournalDetailBackup_ActualAmount]  DEFAULT (0) FOR [ActualAmount]
GO
/****** Object:  Default [DF__loiSerial__sidSa__5A86D06A]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[loiSerialIssueDetails] ADD  DEFAULT (NULL) FOR [sidSavedByShopId]
GO
/****** Object:  Default [DF_losHpInvoiceHeader_hpqhPosted]    Script Date: 04/16/2012 10:32:34 ******/
ALTER TABLE [dbo].[losHpInvoiceHeader] ADD  CONSTRAINT [DF_losHpInvoiceHeader_hpqhPosted]  DEFAULT (0) FOR [hpqhPosted]
GO
/****** Object:  Default [DF_losHpInvoiceHeader_hpqhDownPaid]    Script Date: 04/16/2012 10:32:34 ******/
ALTER TABLE [dbo].[losHpInvoiceHeader] ADD  CONSTRAINT [DF_losHpInvoiceHeader_hpqhDownPaid]  DEFAULT (0) FOR [hpqhDownPaid]
GO
/****** Object:  Default [DF_losHpInvoiceHeader_hpqhProcessed]    Script Date: 04/16/2012 10:32:34 ******/
ALTER TABLE [dbo].[losHpInvoiceHeader] ADD  CONSTRAINT [DF_losHpInvoiceHeader_hpqhProcessed]  DEFAULT (0) FOR [hpqhProcessed]
GO
/****** Object:  Default [DF__aKitItemD__KitDe__79E9A1D3]    Script Date: 04/16/2012 10:32:34 ******/
ALTER TABLE [dbo].[aKitItemDetail] ADD  DEFAULT (0) FOR [KitDetailId]
GO
/****** Object:  Default [DF__aFineHead__fhInv__0AAA1981]    Script Date: 04/16/2012 10:32:34 ******/
ALTER TABLE [dbo].[aFineHeader] ADD  DEFAULT ((0)) FOR [fhInvoiceCancelled]
GO
/****** Object:  Default [DF__aUserGrou__rowgu__03F163A3]    Script Date: 04/16/2012 10:32:34 ******/
ALTER TABLE [dbo].[aUserGroupRights] ADD  CONSTRAINT [DF__aUserGrou__rowgu__03F163A3]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aUserGroupShopDetails_rowguID]    Script Date: 04/16/2012 10:32:34 ******/
ALTER TABLE [dbo].[aUserGroupShopDetails] ADD  CONSTRAINT [DF_aUserGroupShopDetails_rowguID]  DEFAULT (newid()) FOR [rowguID]
GO
/****** Object:  Default [DF_LosFacilityTracking_ftcheckinCancelled]    Script Date: 04/16/2012 10:32:34 ******/
ALTER TABLE [dbo].[LosFacilityTracking] ADD  CONSTRAINT [DF_LosFacilityTracking_ftcheckinCancelled]  DEFAULT (0) FOR [ftcheckinCancelled]
GO
/****** Object:  Default [DF__aservicel__rowgu__18977ACE]    Script Date: 04/16/2012 10:32:34 ******/
ALTER TABLE [dbo].[aservicelocations] ADD  CONSTRAINT [DF__aservicel__rowgu__18977ACE]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aUnit__rowguid__07CC1628]    Script Date: 04/16/2012 10:32:34 ******/
ALTER TABLE [dbo].[aUnit] ADD  CONSTRAINT [DF__aUnit__rowguid__07CC1628]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aCustomer__rowgu__4321E620]    Script Date: 04/16/2012 10:32:34 ******/
ALTER TABLE [dbo].[aCustomerMasterBackUp] ADD  CONSTRAINT [DF__aCustomer__rowgu__4321E620]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aPackingT__rowgu__6576FE24]    Script Date: 04/16/2012 10:32:34 ******/
ALTER TABLE [dbo].[aPackingType] ADD  CONSTRAINT [DF__aPackingT__rowgu__6576FE24]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__loscompla__cmpup__013F142A]    Script Date: 04/16/2012 10:32:34 ******/
ALTER TABLE [dbo].[loscomplaints] ADD  CONSTRAINT [DF__loscompla__cmpup__013F142A]  DEFAULT (getdate()) FOR [cmpupdatetime]
GO
/****** Object:  Default [DF__loscompla__rowgu__009FF5AC]    Script Date: 04/16/2012 10:32:34 ******/
ALTER TABLE [dbo].[loscomplaints] ADD  CONSTRAINT [DF__loscompla__rowgu__009FF5AC]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__paPayAccL__Cance__04866080]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[paPayAccLinkHeader] ADD  CONSTRAINT [DF__paPayAccL__Cance__04866080]  DEFAULT (0) FOR [Cancelled]
GO
/****** Object:  Default [DF__paPayAccL__Poste__057A84B9]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[paPayAccLinkHeader] ADD  CONSTRAINT [DF__paPayAccL__Poste__057A84B9]  DEFAULT (0) FOR [Posted]
GO
/****** Object:  Default [DF__paPayAccL__Updat__066EA8F2]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[paPayAccLinkHeader] ADD  CONSTRAINT [DF__paPayAccL__Updat__066EA8F2]  DEFAULT (getdate()) FOR [UpdateTime]
GO
/****** Object:  Default [DF__moafuture__rowgu__587208C1]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[moafuture] ADD  CONSTRAINT [DF__moafuture__rowgu__587208C1]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aHqMergingDetails_rowguid]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aHqMergingDetails] ADD  CONSTRAINT [DF_aHqMergingDetails_rowguid]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__loiExpiry__evdPr__033D368C]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loiExpiryVerificationDetail] ADD  CONSTRAINT [DF__loiExpiry__evdPr__033D368C]  DEFAULT ('OLDBATCH') FOR [evdPrevBatchNo]
GO
/****** Object:  Default [DF__loiExpiry__evdBa__04315AC5]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loiExpiryVerificationDetail] ADD  CONSTRAINT [DF__loiExpiry__evdBa__04315AC5]  DEFAULT ('OLDBATCH') FOR [evdBatchNo]
GO
/****** Object:  Default [DF_aHqMergingHeader_rowguid]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aHqMergingHeader] ADD  CONSTRAINT [DF_aHqMergingHeader_rowguid]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_TempDishCost_DishCostAmt]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[TempDishCost] ADD  CONSTRAINT [DF_TempDishCost_DishCostAmt]  DEFAULT ((0)) FOR [DishCostAmt]
GO
/****** Object:  Default [DF_aUserGroupCusGroupDetails_Rowguid]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aUserGroupCusGroupDetails] ADD  CONSTRAINT [DF_aUserGroupCusGroupDetails_Rowguid]  DEFAULT (newid()) FOR [Rowguid]
GO
/****** Object:  Default [DF_aInterface_PrefixNeeded]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aInterface] ADD  CONSTRAINT [DF_aInterface_PrefixNeeded]  DEFAULT (0) FOR [PrefixNeeded]
GO
/****** Object:  Default [DF__aInterfac__rowgu__3631FF56]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aInterface] ADD  CONSTRAINT [DF__aInterfac__rowgu__3631FF56]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aItem_ReorderQuantity]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_ReorderQuantity]  DEFAULT (0) FOR [ReorderQuantity]
GO
/****** Object:  Default [DF_aItem_ReorderLevel]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_ReorderLevel]  DEFAULT (0) FOR [ReorderLevel]
GO
/****** Object:  Default [DF_aItem_MarginPercent]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_MarginPercent]  DEFAULT (0) FOR [MarginPercent]
GO
/****** Object:  Default [DF_aItem_DPMargin]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_DPMargin]  DEFAULT (0) FOR [DPMargin]
GO
/****** Object:  Default [DF_aItem_WPMargin]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_WPMargin]  DEFAULT (0) FOR [WPMargin]
GO
/****** Object:  Default [DF_aItem_DPQty]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_DPQty]  DEFAULT (0) FOR [DPQty]
GO
/****** Object:  Default [DF_aItem_WPQty]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_WPQty]  DEFAULT (0) FOR [WPQty]
GO
/****** Object:  Default [DF_aItem_onetimeshipment]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_onetimeshipment]  DEFAULT (0) FOR [onetimeshipment]
GO
/****** Object:  Default [DF_aItem_pricefixedathq]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_pricefixedathq]  DEFAULT (0) FOR [pricefixedathq]
GO
/****** Object:  Default [DF_aItem_GenerateBC]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_GenerateBC]  DEFAULT (1) FOR [GenerateBC]
GO
/****** Object:  Default [DF_aItem_ExpiryNoofDays]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_ExpiryNoofDays]  DEFAULT (0) FOR [ExpiryNoofDays]
GO
/****** Object:  Default [DF_aItem_brand]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_brand]  DEFAULT ('') FOR [brand]
GO
/****** Object:  Default [DF_aItem_ModelNo]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_ModelNo]  DEFAULT ('') FOR [ModelNo]
GO
/****** Object:  Default [DF_aItem_Vendors]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_Vendors]  DEFAULT ('0') FOR [Vendors]
GO
/****** Object:  Default [DF_aItem_QuantityDecimal]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_QuantityDecimal]  DEFAULT ('') FOR [QuantityDecimal]
GO
/****** Object:  Default [DF_aItem_itemforsale]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_itemforsale]  DEFAULT (1) FOR [forsales]
GO
/****** Object:  Default [DF_aItem_bitf1]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_bitf1]  DEFAULT (0) FOR [bitf1]
GO
/****** Object:  Default [DF_aItem_bitf2]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_bitf2]  DEFAULT (0) FOR [bitf2]
GO
/****** Object:  Default [DF_aItem_bitf3]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF_aItem_bitf3]  DEFAULT (0) FOR [bitf3]
GO
/****** Object:  Default [DF__aItem__rowguid__5CECA51B]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF__aItem__rowguid__5CECA51B]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [df_aitem_compvarflag]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [df_aitem_compvarflag]  DEFAULT (0) FOR [compvarflag]
GO
/****** Object:  Default [df_aitem_itemvarflag]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [df_aitem_itemvarflag]  DEFAULT (0) FOR [itemvarflag]
GO
/****** Object:  Default [DF__aitem__SerialNoD__59B43E70]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  CONSTRAINT [DF__aitem__SerialNoD__59B43E70]  DEFAULT (0) FOR [SerialNoDupli]
GO
/****** Object:  Default [DF__aItem__servWarra__4F9440AB]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  DEFAULT ((0)) FOR [servWarrantyPeriod]
GO
/****** Object:  Default [DF__aItem__partsWarr__508864E4]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItem] ADD  DEFAULT ((0)) FOR [partsWarrantyPeriod]
GO
/****** Object:  Default [DF_aItemCategoryMergingDetails_Rowguid]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aItemCategoryMergingDetails] ADD  CONSTRAINT [DF_aItemCategoryMergingDetails_Rowguid]  DEFAULT (newid()) FOR [Rowguid]
GO
/****** Object:  Default [DF_AgreementRegister_agrcancelled]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[AgreementRegister] ADD  CONSTRAINT [DF_AgreementRegister_agrcancelled]  DEFAULT (0) FOR [agrcancelled]
GO
/****** Object:  Default [DF__aservicec__rowgu__12DEA178]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aServiceCategory] ADD  CONSTRAINT [DF__aservicec__rowgu__12DEA178]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aSubDepartmentMaster_BudgetedAmount]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aSubDepartmentMaster] ADD  CONSTRAINT [DF_aSubDepartmentMaster_BudgetedAmount]  DEFAULT (0) FOR [BudgetedAmount]
GO
/****** Object:  Default [DF_aSubDepartmentMaster_Selected]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aSubDepartmentMaster] ADD  CONSTRAINT [DF_aSubDepartmentMaster_Selected]  DEFAULT (0) FOR [Selected]
GO
/****** Object:  Default [DF_aSubDepartmentMaster_rowguid]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aSubDepartmentMaster] ADD  CONSTRAINT [DF_aSubDepartmentMaster_rowguid]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aTables__rowguid__02133CD2]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aTables] ADD  CONSTRAINT [DF__aTables__rowguid__02133CD2]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aUserGroupBrandDetails_rowguiD]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aUserGroupBrandDetails] ADD  CONSTRAINT [DF_aUserGroupBrandDetails_rowguiD]  DEFAULT (newid()) FOR [rowguiD]
GO
/****** Object:  Default [DF_aUserGroupItemCategoryDetails_rowguID]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aUserGroupItemCategoryDetails] ADD  CONSTRAINT [DF_aUserGroupItemCategoryDetails_rowguID]  DEFAULT (newid()) FOR [rowguID]
GO
/****** Object:  Default [DF_aUserGroupVenGroupDetails_Rowguid]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aUserGroupVenGroupDetails] ADD  CONSTRAINT [DF_aUserGroupVenGroupDetails_Rowguid]  DEFAULT (newid()) FOR [Rowguid]
GO
/****** Object:  Default [DF__fb_kothea__Fb_kd__70C98096]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[Fb_kotheader] ADD  CONSTRAINT [DF__fb_kothea__Fb_kd__70C98096]  DEFAULT ((0)) FOR [Fb_kh_cancelled]
GO
/****** Object:  Default [DF__aUsers__rowguid__2724C5F0]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aUsers] ADD  CONSTRAINT [DF__aUsers__rowguid__2724C5F0]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aVendorGroup_rowguid]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aVendorGroup] ADD  CONSTRAINT [DF_aVendorGroup_rowguid]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aVendorMa__rowgu__0D84EF7E]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aVendorMasterBackUp] ADD  CONSTRAINT [DF__aVendorMa__rowgu__0D84EF7E]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losInhous__sedco__3C816C37]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losInhouseExchangeDetail] ADD  DEFAULT ((0)) FOR [sedcostprice]
GO
/****** Object:  Default [DF__losInhous__rowgu__3D759070]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losInhouseExchangeDetail] ADD  DEFAULT (newsequentialid()) FOR [rowguid]
GO
/****** Object:  Default [DF__abarcodet__rowgu__699C94C3]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[abarcodetype] ADD  CONSTRAINT [DF__abarcodet__rowgu__699C94C3]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losExpiry__evdPr__0154EE1A]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losExpiryVerificationDetail] ADD  CONSTRAINT [DF__losExpiry__evdPr__0154EE1A]  DEFAULT ('OLDBATCH') FOR [evdPrevBatchNo]
GO
/****** Object:  Default [DF__losExpiry__evdBa__02491253]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losExpiryVerificationDetail] ADD  CONSTRAINT [DF__losExpiry__evdBa__02491253]  DEFAULT ('OLDBATCH') FOR [evdBatchNo]
GO
/****** Object:  Default [DF__adistribu__rowgu__5F35AB97]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[adistributormaster] ADD  CONSTRAINT [DF__adistribu__rowgu__5F35AB97]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losHPResa__hphRe__581DCE5D]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losHPResaleHeader] ADD  CONSTRAINT [DF__losHPResa__hphRe__581DCE5D]  DEFAULT ('w') FOR [hphRemarks]
GO
/****** Object:  Default [DF_LOsPurchaseReturnDetail_rowguid]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[LOsPurchaseReturnDetail] ADD  CONSTRAINT [DF_LOsPurchaseReturnDetail_rowguid]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LOsPosdum__posdB__447793BA]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[LOsPosdummyDetail] ADD  DEFAULT ((1)) FOR [posdBillDetailID]
GO
/****** Object:  Default [DF_LOsPurchaseReturnHeader_Whfuturevc]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[LOsPurchaseReturnHeader] ADD  CONSTRAINT [DF_LOsPurchaseReturnHeader_Whfuturevc]  DEFAULT ('') FOR [Whfuturevc]
GO
/****** Object:  Default [DF_LOsPurchaseReturnHeader_whposted]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[LOsPurchaseReturnHeader] ADD  CONSTRAINT [DF_LOsPurchaseReturnHeader_whposted]  DEFAULT (0) FOR [whposted]
GO
/****** Object:  Default [DF_LOsPurchaseReturnHeader_updatetime]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[LOsPurchaseReturnHeader] ADD  CONSTRAINT [DF_LOsPurchaseReturnHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF_LOsPurchaseReturnHeader_rowguid]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[LOsPurchaseReturnHeader] ADD  CONSTRAINT [DF_LOsPurchaseReturnHeader_rowguid]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LOsPurchaseReturnHeader_whselected]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[LOsPurchaseReturnHeader] ADD  CONSTRAINT [DF_LOsPurchaseReturnHeader_whselected]  DEFAULT (0) FOR [whselected]
GO
/****** Object:  Default [DF_aparentCategoryMergingDetails_Rowguid]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aparentCategoryMergingDetails] ADD  CONSTRAINT [DF_aparentCategoryMergingDetails_Rowguid]  DEFAULT (newid()) FOR [Rowguid]
GO
/****** Object:  Default [DF_areprerecvendordetail_rrvdselected]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[areprecvendordetail] ADD  CONSTRAINT [DF_areprerecvendordetail_rrvdselected]  DEFAULT (0) FOR [rrvdselected]
GO
/****** Object:  Default [DF__aservicem__rowgu__365CE7DF]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aservicemaster] ADD  CONSTRAINT [DF__aservicem__rowgu__365CE7DF]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aServiceM__serse__387018DA]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aservicemaster] ADD  CONSTRAINT [DF__aServiceM__serse__387018DA]  DEFAULT ('S') FOR [serservicetype]
GO
/****** Object:  Default [DF__AssetDisp__updat__5AE52C6F]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[assetdisposalheader] ADD  CONSTRAINT [DF__AssetDisp__updat__5AE52C6F]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF_ausergroupAccDetails_Rowguid]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[ausergroupAccGroupDetails] ADD  CONSTRAINT [DF_ausergroupAccDetails_Rowguid]  DEFAULT (newid()) FOR [Rowguid]
GO
/****** Object:  Default [DF_LosServiceInvHeader_serinvhcancelled]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[LosServiceInvHeader] ADD  CONSTRAINT [DF_LosServiceInvHeader_serinvhcancelled]  DEFAULT (0) FOR [serinvhcancelled]
GO
/****** Object:  Default [DF_LosServiceInvHeader_serinvhposted]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[LosServiceInvHeader] ADD  CONSTRAINT [DF_LosServiceInvHeader_serinvhposted]  DEFAULT (0) FOR [serinvhposted]
GO
/****** Object:  Default [DF__losservic__serin__3B6C8116]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[LosServiceInvHeader] ADD  CONSTRAINT [DF__losservic__serin__3B6C8116]  DEFAULT (0) FOR [serinvhCashInv]
GO
/****** Object:  Default [DF_loPurchaseOrderHeader_pohcancel]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loPurchaseOrderHeader] ADD  CONSTRAINT [DF_loPurchaseOrderHeader_pohcancel]  DEFAULT (0) FOR [pohcancel]
GO
/****** Object:  Default [DF_loPurchaseOrderHeader_pohPosted]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loPurchaseOrderHeader] ADD  CONSTRAINT [DF_loPurchaseOrderHeader_pohPosted]  DEFAULT (0) FOR [pohPosted]
GO
/****** Object:  Default [DF_loPurchaseOrderHeader_pohbillgenerated]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loPurchaseOrderHeader] ADD  CONSTRAINT [DF_loPurchaseOrderHeader_pohbillgenerated]  DEFAULT (0) FOR [pohbillgenerated]
GO
/****** Object:  Default [DF_loPurchaseOrderHeader_pogenerated]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loPurchaseOrderHeader] ADD  CONSTRAINT [DF_loPurchaseOrderHeader_pogenerated]  DEFAULT (0) FOR [pogenerated]
GO
/****** Object:  Default [DF_loPurchaseOrderHeader_pohpogenerated]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loPurchaseOrderHeader] ADD  CONSTRAINT [DF_loPurchaseOrderHeader_pohpogenerated]  DEFAULT (0) FOR [pohpogenerated]
GO
/****** Object:  Default [DF_loPurchaseOrderHeader_pohUsedinPayments]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loPurchaseOrderHeader] ADD  CONSTRAINT [DF_loPurchaseOrderHeader_pohUsedinPayments]  DEFAULT (0) FOR [pohUsedinPayments]
GO
/****** Object:  Default [DF_loPurchaseOrderHeader_pohLCopened]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loPurchaseOrderHeader] ADD  CONSTRAINT [DF_loPurchaseOrderHeader_pohLCopened]  DEFAULT (0) FOR [pohLCopened]
GO
/****** Object:  Default [DF_loPurchaseOrderHeader_pohLcMarginOpened]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loPurchaseOrderHeader] ADD  CONSTRAINT [DF_loPurchaseOrderHeader_pohLcMarginOpened]  DEFAULT (0) FOR [pohLcMarginOpened]
GO
/****** Object:  Default [DF__lopurchas__pohCo__0B22DD87]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loPurchaseOrderHeader] ADD  CONSTRAINT [DF__lopurchas__pohCo__0B22DD87]  DEFAULT ('P') FOR [pohCostingDone]
GO
/****** Object:  Default [DF_loPurchaseOrderHeader_pohDeladdress]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loPurchaseOrderHeader] ADD  CONSTRAINT [DF_loPurchaseOrderHeader_pohDeladdress]  DEFAULT ('') FOR [pohDeliveryTerms]
GO
/****** Object:  Default [DF_loPurchaseOrderHeader_pohquotconfirmed]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loPurchaseOrderHeader] ADD  CONSTRAINT [DF_loPurchaseOrderHeader_pohquotconfirmed]  DEFAULT (0) FOR [pohquotconfirmed]
GO
/****** Object:  Default [DF_loPurchaseOrderHeader_pohpoonhold]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loPurchaseOrderHeader] ADD  CONSTRAINT [DF_loPurchaseOrderHeader_pohpoonhold]  DEFAULT (0) FOR [pohpoonhold]
GO
/****** Object:  Default [DF_loPurchaseOrderHeader_pohfuturevc]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loPurchaseOrderHeader] ADD  CONSTRAINT [DF_loPurchaseOrderHeader_pohfuturevc]  DEFAULT ('') FOR [pohfuturevc]
GO
/****** Object:  Default [DF_loPurchaseOrderHeader_updatetime]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loPurchaseOrderHeader] ADD  CONSTRAINT [DF_loPurchaseOrderHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__loPurchas__pohCu__17CE3F1E]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loPurchaseOrderHeader] ADD  CONSTRAINT [DF__loPurchas__pohCu__17CE3F1E]  DEFAULT (0) FOR [pohCustomDutyByCustomer]
GO
/****** Object:  Default [DF__MOiGodown__rowgu__0FA2421A]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[MOiGodownStockBackup] ADD  CONSTRAINT [DF__MOiGodown__rowgu__0FA2421A]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__MOsShopSt__rowgu__155B1B70]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[MOsShopStockBackup] ADD  CONSTRAINT [DF__MOsShopSt__rowgu__155B1B70]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aAutoGenerateBillRiminder_Generated]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aAutoGenerateBillRiminder] ADD  CONSTRAINT [DF_aAutoGenerateBillRiminder_Generated]  DEFAULT ((0)) FOR [Generated]
GO
/****** Object:  Default [DF_MiscSettings_ItemCodeAutoGen]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[MiscSettings] ADD  CONSTRAINT [DF_MiscSettings_ItemCodeAutoGen]  DEFAULT (0) FOR [ItemCodeAutoGen]
GO
/****** Object:  Default [DF_MiscSettings_SupplierCodeAutoGen]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[MiscSettings] ADD  CONSTRAINT [DF_MiscSettings_SupplierCodeAutoGen]  DEFAULT (0) FOR [SupplierCodeAutoGen]
GO
/****** Object:  Default [DF_MiscSettings_CustomerCodeAutoGen]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[MiscSettings] ADD  CONSTRAINT [DF_MiscSettings_CustomerCodeAutoGen]  DEFAULT (0) FOR [CustomerCodeAutoGen]
GO
/****** Object:  Default [DF_MiscSettings_showlocationswitch]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[MiscSettings] ADD  CONSTRAINT [DF_MiscSettings_showlocationswitch]  DEFAULT (1) FOR [showlocationswitch]
GO
/****** Object:  Default [DF_MiscSettings_AllowItemCodeDuplication]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[MiscSettings] ADD  CONSTRAINT [DF_MiscSettings_AllowItemCodeDuplication]  DEFAULT (0) FOR [AllowItemCodeDuplication]
GO
/****** Object:  Default [DF__miscsetti__allow__27FB509D]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[MiscSettings] ADD  CONSTRAINT [DF__miscsetti__allow__27FB509D]  DEFAULT (0) FOR [allowlocalpurchhq]
GO
/****** Object:  Default [DF__miscsetti__fixse__047D0A36]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[MiscSettings] ADD  CONSTRAINT [DF__miscsetti__fixse__047D0A36]  DEFAULT (1) FOR [fixsellingpriceaftercosting]
GO
/****** Object:  Default [DF_MiscSettings_customertoshoponcreation]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[MiscSettings] ADD  CONSTRAINT [DF_MiscSettings_customertoshoponcreation]  DEFAULT (0) FOR [customertoshoponcreation]
GO
/****** Object:  Default [DF__miscsetti__openi__01368937]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[MiscSettings] ADD  CONSTRAINT [DF__miscsetti__openi__01368937]  DEFAULT (0) FOR [openingbalancenottallying]
GO
/****** Object:  Default [DF__MiscSetti__Allow__2374FBF4]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[MiscSettings] ADD  CONSTRAINT [DF__MiscSetti__Allow__2374FBF4]  DEFAULT (0) FOR [AllowZeroLcMargin]
GO
/****** Object:  Default [DF__loiSerial__sadSa__2CCA275B]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[loiSerialArrivalDetails] ADD  DEFAULT (NULL) FOR [sadSavedByShopId]
GO
/****** Object:  Default [DF_ItemPriceHistory_rowguid]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[ItemPriceHistory] ADD  CONSTRAINT [DF_ItemPriceHistory_rowguid]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__CrmCustom__Delet__609ED11C]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[CrmCustomerMaster] ADD  DEFAULT ((0)) FOR [Deleted]
GO
/****** Object:  Default [DF__ReportNam__rowgu__2685A772]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[ReportNames] ADD  CONSTRAINT [DF__ReportNam__rowgu__2685A772]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losDocument_CoMailIn]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losDocument] ADD  CONSTRAINT [DF_losDocument_CoMailIn]  DEFAULT (1) FOR [CoMailIn]
GO
/****** Object:  Default [DF_losDocument_AlertBeforeDays]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losDocument] ADD  CONSTRAINT [DF_losDocument_AlertBeforeDays]  DEFAULT (0) FOR [AlertBeforeDays]
GO
/****** Object:  Default [DF_losDocument_Active]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losDocument] ADD  CONSTRAINT [DF_losDocument_Active]  DEFAULT (1) FOR [Active]
GO
/****** Object:  Default [DF_losDocument_Cancelled]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losDocument] ADD  CONSTRAINT [DF_losDocument_Cancelled]  DEFAULT (0) FOR [Cancelled]
GO
/****** Object:  Default [DF_FB_Dishgroup_fb_dg_foodbeverage]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[FB_Dishgroup] ADD  CONSTRAINT [DF_FB_Dishgroup_fb_dg_foodbeverage]  DEFAULT ((0)) FOR [fb_dg_foodbeverage]
GO
/****** Object:  Default [DF_FB_Dishgroup_FB_dg_Futurebit]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[FB_Dishgroup] ADD  CONSTRAINT [DF_FB_Dishgroup_FB_dg_Futurebit]  DEFAULT ((0)) FOR [FB_dg_Futurebit]
GO
/****** Object:  Default [DF__losHpDumm__hpqhP__1F5292B1]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losHpDummyQuotationHeader] ADD  CONSTRAINT [DF__losHpDumm__hpqhP__1F5292B1]  DEFAULT (0) FOR [hpqhPosted]
GO
/****** Object:  Default [DF__losHpDumm__hpqhD__2046B6EA]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losHpDummyQuotationHeader] ADD  CONSTRAINT [DF__losHpDumm__hpqhD__2046B6EA]  DEFAULT (0) FOR [hpqhDownPaid]
GO
/****** Object:  Default [DF__losHpDumm__hpqhP__213ADB23]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losHpDummyQuotationHeader] ADD  CONSTRAINT [DF__losHpDumm__hpqhP__213ADB23]  DEFAULT (0) FOR [hpqhProcessed]
GO
/****** Object:  Default [DF_losInvoicedServiceDetails_rowguid]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losInvoicedServiceDetails] ADD  CONSTRAINT [DF_losInvoicedServiceDetails_rowguid]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losInvoicedPartsReplacedetails_rowguid]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losInvoicedPartsReplacedetails] ADD  CONSTRAINT [DF_losInvoicedPartsReplacedetails_rowguid]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losLocati__lvhCa__129488B5]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losLocationVerificationHeader] ADD  CONSTRAINT [DF__losLocati__lvhCa__129488B5]  DEFAULT (0) FOR [lvhCancelled]
GO
/****** Object:  Default [DF__losLocati__lvhpo__1388ACEE]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losLocationVerificationHeader] ADD  CONSTRAINT [DF__losLocati__lvhpo__1388ACEE]  DEFAULT (0) FOR [lvhposted]
GO
/****** Object:  Default [DF__losLocati__updat__147CD127]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losLocationVerificationHeader] ADD  CONSTRAINT [DF__losLocati__updat__147CD127]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF_aBrandMergeDetails_Cancelled]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aBrandMergeDetails] ADD  CONSTRAINT [DF_aBrandMergeDetails_Cancelled]  DEFAULT (0) FOR [Cancelled]
GO
/****** Object:  Default [DF_aBrandMergeDetails_rowguid]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aBrandMergeDetails] ADD  CONSTRAINT [DF_aBrandMergeDetails_rowguid]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losNonRes__rowgu__5F29F348]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[losNonRestrictedItems] ADD  CONSTRAINT [DF__losNonRes__rowgu__5F29F348]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aColor__rowguid__37B03374]    Script Date: 04/16/2012 10:32:35 ******/
ALTER TABLE [dbo].[aColor] ADD  CONSTRAINT [DF__aColor__rowguid__37B03374]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losSerStandByIssueHeader_ishInstallDate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerStandByIssueHeader] ADD  CONSTRAINT [DF_losSerStandByIssueHeader_ishInstallDate]  DEFAULT (getdate()) FOR [ishInstallDate]
GO
/****** Object:  Default [DF_FB_Dishdetails_fb_dd_yield]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FB_Dishdetails] ADD  CONSTRAINT [DF_FB_Dishdetails_fb_dd_yield]  DEFAULT ((0)) FOR [fb_dd_yield]
GO
/****** Object:  Default [DF__losLPHead__Casho__37E608F5]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losLPHeader] ADD  CONSTRAINT [DF__losLPHead__Casho__37E608F5]  DEFAULT (0) FOR [CashorCredit]
GO
/****** Object:  Default [DF__losLPHead__CashP__38DA2D2E]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losLPHeader] ADD  CONSTRAINT [DF__losLPHead__CashP__38DA2D2E]  DEFAULT (0) FOR [CashPaidByShop]
GO
/****** Object:  Default [DF__apackages__Allow__4615C369]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings] ADD  CONSTRAINT [DF__apackages__Allow__4615C369]  DEFAULT (0) FOR [AllowItemCodeDuplication]
GO
/****** Object:  Default [DF__aPAckageS__rowgu__5FBE24CE]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings] ADD  CONSTRAINT [DF__aPAckageS__rowgu__5FBE24CE]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aPAckageS__HQLoc__39CF1CBE]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings] ADD  DEFAULT ((0)) FOR [HQLocalPurchaseConfirmation]
GO
/****** Object:  Default [DF__aPAckageS__Alias__1804149F]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings] ADD  DEFAULT ((0)) FOR [Alias]
GO
/****** Object:  Default [DF__aPAckageS__Allow__02D3ED8F]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings] ADD  DEFAULT ((0)) FOR [AllowDirectLocalPurchaseCosting]
GO
/****** Object:  Default [DF__aPAckageS__Enabl__599CCDD2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings] ADD  DEFAULT ((0)) FOR [EnableRemainderAccBills]
GO
/****** Object:  Default [DF__aPAckageS__AutoC__0A40052D]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings] ADD  DEFAULT ((0)) FOR [AutoConfirmAccTrans]
GO
/****** Object:  Default [DF__aPAckageS__Selli__0B342966]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings] ADD  DEFAULT ((0)) FOR [SellingPriceBelowCostPrice]
GO
/****** Object:  Default [DF__aPAckageS__NoCre__66C1BEC6]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings] ADD  DEFAULT ((0)) FOR [NoCreditForOverdueCustomers]
GO
/****** Object:  Default [DF__aPAckageS__postd__7D3B0FCA]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings] ADD  DEFAULT ((0)) FOR [postdatedcheque]
GO
/****** Object:  Default [DF__losserpar__rowgu__7AE71C56]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losserpartsfromcustomer] ADD  CONSTRAINT [DF__losserpar__rowgu__7AE71C56]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losreplac__rowgu__5C629536]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacerequestdetails] ADD  CONSTRAINT [DF__losreplac__rowgu__5C629536]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losservic__rowgu__3A6282ED]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceHeader] ADD  CONSTRAINT [DF__losservic__rowgu__3A6282ED]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losserviceheader_serinvhjobinvcancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceHeader] ADD  CONSTRAINT [DF_losserviceheader_serinvhjobinvcancelled]  DEFAULT (0) FOR [serinvhjobinvcancelled]
GO
/****** Object:  Default [DF__losServic__serin__1DA71405]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceHeader] ADD  CONSTRAINT [DF__losServic__serin__1DA71405]  DEFAULT (0) FOR [serinvhToInvoice]
GO
/****** Object:  Default [DF_losbookingcancellation_bkcancellcancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losbookingcancellation] ADD  CONSTRAINT [DF_losbookingcancellation_bkcancellcancelled]  DEFAULT (0) FOR [bkcancellcancelled]
GO
/****** Object:  Default [DF_losbookingcancellation_bkcancellposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losbookingcancellation] ADD  CONSTRAINT [DF_losbookingcancellation_bkcancellposted]  DEFAULT (0) FOR [bkcancellposted]
GO
/****** Object:  Default [DF__losbookpa__rowgu__752E4300]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losbookpartsreplacedetails] ADD  CONSTRAINT [DF__losbookpa__rowgu__752E4300]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losSerestimateapproval_seaRejected]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerestimateapproval] ADD  CONSTRAINT [DF_losSerestimateapproval_seaRejected]  DEFAULT (1) FOR [seaApporRejected]
GO
/****** Object:  Default [DF_losSerestimateapproval_seaCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerestimateapproval] ADD  CONSTRAINT [DF_losSerestimateapproval_seaCancelled]  DEFAULT (0) FOR [seaAppCancelled]
GO
/****** Object:  Default [DF__lossercon__rowgu__42A2C333]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losserconditiondetails] ADD  CONSTRAINT [DF__lossercon__rowgu__42A2C333]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losbookse__rowgu__4DABF839]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losbookservtechniciandetails] ADD  CONSTRAINT [DF__losbookse__rowgu__4DABF839]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losbookse__rowgu__76E317F6]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losbookservicedetails] ADD  CONSTRAINT [DF__losbookse__rowgu__76E317F6]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_Discountdetails_dailytrue]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Discountdetails] ADD  CONSTRAINT [DF_Discountdetails_dailytrue]  DEFAULT ((0)) FOR [dailytrue]
GO
/****** Object:  Default [DF_Discountdetails_alldishtrue]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Discountdetails] ADD  CONSTRAINT [DF_Discountdetails_alldishtrue]  DEFAULT ((0)) FOR [alldishtrue]
GO
/****** Object:  Default [DF_CustomerSettlementHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementHeader] ADD  CONSTRAINT [DF_CustomerSettlementHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF_losSpecialInvoiceDetail_idRateType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceDetail] ADD  CONSTRAINT [DF_losSpecialInvoiceDetail_idRateType]  DEFAULT (0) FOR [idRateType]
GO
/****** Object:  Default [DF_losSpecialInvoiceDetail_despatch]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceDetail] ADD  CONSTRAINT [DF_losSpecialInvoiceDetail_despatch]  DEFAULT (0) FOR [despatch]
GO
/****** Object:  Default [DF_losSpecialInvoiceDetail_idcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceDetail] ADD  CONSTRAINT [DF_losSpecialInvoiceDetail_idcostprice]  DEFAULT (0) FOR [idcostprice]
GO
/****** Object:  Default [DF__losSpecia__rowgu__17D9F76D]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceDetail] ADD  CONSTRAINT [DF__losSpecia__rowgu__17D9F76D]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losSpecia__idFre__32B73F84]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceDetail] ADD  CONSTRAINT [DF__losSpecia__idFre__32B73F84]  DEFAULT (0) FOR [idFreeQuantity]
GO
/****** Object:  Default [DF_losSpecialInvoiceDetail_idItemType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceDetail] ADD  CONSTRAINT [DF_losSpecialInvoiceDetail_idItemType]  DEFAULT ('I') FOR [idItemType]
GO
/****** Object:  Default [DF_losSpecialInvoiceDetail_idKitID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceDetail] ADD  CONSTRAINT [DF_losSpecialInvoiceDetail_idKitID]  DEFAULT ((0)) FOR [idKitID]
GO
/****** Object:  Default [DF__losSpecia__rowgu__1D92D0C3]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialOC] ADD  CONSTRAINT [DF__losSpecia__rowgu__1D92D0C3]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LosDummyR__rowgu__4ACEC037]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosDummyReceiptDetail] ADD  CONSTRAINT [DF__LosDummyR__rowgu__4ACEC037]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losSIQuotationHeader_IhProforma]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF_losSIQuotationHeader_IhProforma]  DEFAULT (0) FOR [IhProforma]
GO
/****** Object:  Default [DF_losSIQuotationHeader_IhCashInvoice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF_losSIQuotationHeader_IhCashInvoice]  DEFAULT (0) FOR [IhCashInvoice]
GO
/****** Object:  Default [DF_losSIQuotationHeader_IhCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF_losSIQuotationHeader_IhCancelled]  DEFAULT (0) FOR [IhCancelled]
GO
/****** Object:  Default [DF_losSIQuotationHeader_IhCompanyId]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF_losSIQuotationHeader_IhCompanyId]  DEFAULT (1) FOR [IhCompanyId]
GO
/****** Object:  Default [DF_losSIQuotationHeader_IhPosted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF_losSIQuotationHeader_IhPosted]  DEFAULT (0) FOR [IhPosted]
GO
/****** Object:  Default [DF_losSIQuotationHeader_ihGoodsReturned]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF_losSIQuotationHeader_ihGoodsReturned]  DEFAULT (0) FOR [ihGoodsReturned]
GO
/****** Object:  Default [DF_losSIQuotationHeader_ihUsed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF_losSIQuotationHeader_ihUsed]  DEFAULT (0) FOR [ihUsed]
GO
/****** Object:  Default [DF_losSIQuotationHeader_IhSettled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF_losSIQuotationHeader_IhSettled]  DEFAULT (0) FOR [IhSettled]
GO
/****** Object:  Default [DF_losSIQuotationHeader_ihTransFinished]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF_losSIQuotationHeader_ihTransFinished]  DEFAULT (0) FOR [ihTransFinished]
GO
/****** Object:  Default [DF_losSIQuotationHeader_ihNoofDetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF_losSIQuotationHeader_ihNoofDetails]  DEFAULT (0) FOR [ihNoofDetails]
GO
/****** Object:  Default [DF_losSIQuotationHeader_ihNoofOCDetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF_losSIQuotationHeader_ihNoofOCDetails]  DEFAULT (0) FOR [ihNoofOCDetails]
GO
/****** Object:  Default [DF_losSIQuotationHeader_ihexchangerate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF_losSIQuotationHeader_ihexchangerate]  DEFAULT (1) FOR [ihexchangerate]
GO
/****** Object:  Default [DF_losSIQuotationHeader_ihsettledamount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF_losSIQuotationHeader_ihsettledamount]  DEFAULT (0) FOR [ihsettledamount]
GO
/****** Object:  Default [DF_losSIQuotationHeader_ihfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF_losSIQuotationHeader_ihfuturevc]  DEFAULT ('') FOR [ihfuturevc]
GO
/****** Object:  Default [DF_losSIQuotationHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF_losSIQuotationHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__losQuo__rowgu__318D45CA]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader] ADD  CONSTRAINT [DF__losQuo__rowgu__318D45CA]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losDummyReceipt_cancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDummyReceiptHeader] ADD  CONSTRAINT [DF_losDummyReceipt_cancelled]  DEFAULT (0) FOR [drcancelled]
GO
/****** Object:  Default [DF_losDummyReceiptHeader_drfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDummyReceiptHeader] ADD  CONSTRAINT [DF_losDummyReceiptHeader_drfuturevc]  DEFAULT ('') FOR [drfuturevc]
GO
/****** Object:  Default [DF_losDummyReceiptHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDummyReceiptHeader] ADD  CONSTRAINT [DF_losDummyReceiptHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF_losDummyReceiptHeader_drBankExchangeRate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDummyReceiptHeader] ADD  CONSTRAINT [DF_losDummyReceiptHeader_drBankExchangeRate]  DEFAULT (1) FOR [drBankExchangeRate]
GO
/****** Object:  Default [DF_losDummyReceiptHeader_drExchangeRate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDummyReceiptHeader] ADD  CONSTRAINT [DF_losDummyReceiptHeader_drExchangeRate]  DEFAULT (1) FOR [drExchangeRate]
GO
/****** Object:  Default [DF__losDummyR__rowgu__5AF01967]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDummyReceiptHeader] ADD  CONSTRAINT [DF__losDummyR__rowgu__5AF01967]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losposExchangeHeader_sehCompanyID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeHeader] ADD  CONSTRAINT [DF_losposExchangeHeader_sehCompanyID]  DEFAULT (1) FOR [sehCompanyID]
GO
/****** Object:  Default [DF_losposExchangeHeader_sehwholesale]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeHeader] ADD  CONSTRAINT [DF_losposExchangeHeader_sehwholesale]  DEFAULT (0) FOR [sehwholesale]
GO
/****** Object:  Default [DF_losposExchangeHeader_sehExchangeRate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeHeader] ADD  CONSTRAINT [DF_losposExchangeHeader_sehExchangeRate]  DEFAULT (1) FOR [sehExchangeRate]
GO
/****** Object:  Default [DF_losposExchangeHeader_sehfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeHeader] ADD  CONSTRAINT [DF_losposExchangeHeader_sehfuturevc]  DEFAULT ('') FOR [sehfuturevc]
GO
/****** Object:  Default [DF_losposExchangeHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeHeader] ADD  CONSTRAINT [DF_losposExchangeHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__losposExc__rowgu__52C4E7BA]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeHeader] ADD  CONSTRAINT [DF__losposExc__rowgu__52C4E7BA]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losSpecialInvoiceHeader_IhProforma]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF_losSpecialInvoiceHeader_IhProforma]  DEFAULT (0) FOR [IhProforma]
GO
/****** Object:  Default [DF_losSpecialInvoiceHeader_IhCashInvoice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF_losSpecialInvoiceHeader_IhCashInvoice]  DEFAULT (0) FOR [IhCashInvoice]
GO
/****** Object:  Default [DF_losSpecialInvoiceHeader_IhCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF_losSpecialInvoiceHeader_IhCancelled]  DEFAULT (0) FOR [IhCancelled]
GO
/****** Object:  Default [DF_losSpecialInvoiceHeader_IhCompanyId]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF_losSpecialInvoiceHeader_IhCompanyId]  DEFAULT (1) FOR [IhCompanyId]
GO
/****** Object:  Default [DF_losSpecialInvoiceHeader_IhPosted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF_losSpecialInvoiceHeader_IhPosted]  DEFAULT (0) FOR [IhPosted]
GO
/****** Object:  Default [DF_losSpecialInvoiceHeader_ihGoodsReturned]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF_losSpecialInvoiceHeader_ihGoodsReturned]  DEFAULT (0) FOR [ihGoodsReturned]
GO
/****** Object:  Default [DF_losSpecialInvoiceHeader_ihUsed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF_losSpecialInvoiceHeader_ihUsed]  DEFAULT (0) FOR [ihUsed]
GO
/****** Object:  Default [DF_losSpecialInvoiceHeader_IhSettled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF_losSpecialInvoiceHeader_IhSettled]  DEFAULT (0) FOR [IhSettled]
GO
/****** Object:  Default [DF_losSpecialInvoiceHeader_ihTransFinished]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF_losSpecialInvoiceHeader_ihTransFinished]  DEFAULT (0) FOR [ihTransFinished]
GO
/****** Object:  Default [DF_losSpecialInvoiceHeader_ihNoofDetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF_losSpecialInvoiceHeader_ihNoofDetails]  DEFAULT (0) FOR [ihNoofDetails]
GO
/****** Object:  Default [DF_losSpecialInvoiceHeader_ihNoofOCDetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF_losSpecialInvoiceHeader_ihNoofOCDetails]  DEFAULT (0) FOR [ihNoofOCDetails]
GO
/****** Object:  Default [DF_losSpecialInvoiceHeader_ihexchangerate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF_losSpecialInvoiceHeader_ihexchangerate]  DEFAULT (1) FOR [ihexchangerate]
GO
/****** Object:  Default [DF_losSpecialInvoiceHeader_ihsettledamount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF_losSpecialInvoiceHeader_ihsettledamount]  DEFAULT (0) FOR [ihsettledamount]
GO
/****** Object:  Default [DF_losSpecialInvoiceHeader_ihfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF_losSpecialInvoiceHeader_ihfuturevc]  DEFAULT ('') FOR [ihfuturevc]
GO
/****** Object:  Default [DF_losSpecialInvoiceHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF_losSpecialInvoiceHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__losSpecia__rowgu__318D45CA]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader] ADD  CONSTRAINT [DF__losSpecia__rowgu__318D45CA]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LosLocalPurchaseHeader_lphUsed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader] ADD  CONSTRAINT [DF_LosLocalPurchaseHeader_lphUsed]  DEFAULT (0) FOR [lphUsed]
GO
/****** Object:  Default [DF_LosLocalPurchaseHeader_lphAdjustmentAmount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader] ADD  CONSTRAINT [DF_LosLocalPurchaseHeader_lphAdjustmentAmount]  DEFAULT (0) FOR [lphAdjustmentAmount]
GO
/****** Object:  Default [DF_LosLocalPurchaseHeader_lphSettled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader] ADD  CONSTRAINT [DF_LosLocalPurchaseHeader_lphSettled]  DEFAULT (0) FOR [lphSettled]
GO
/****** Object:  Default [DF_LosLocalPurchaseHeader_lphexchangerate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader] ADD  CONSTRAINT [DF_LosLocalPurchaseHeader_lphexchangerate]  DEFAULT (1) FOR [lphexchangerate]
GO
/****** Object:  Default [DF_LosLocalPurchaseHeader_lphcosted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader] ADD  CONSTRAINT [DF_LosLocalPurchaseHeader_lphcosted]  DEFAULT (0) FOR [lphcosted]
GO
/****** Object:  Default [DF_LosLocalPurchaseHeader_lphfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader] ADD  CONSTRAINT [DF_LosLocalPurchaseHeader_lphfuturevc]  DEFAULT ('') FOR [lphfuturevc]
GO
/****** Object:  Default [DF_LosLocalPurchaseHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader] ADD  CONSTRAINT [DF_LosLocalPurchaseHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__LosLocalP__rowgu__67C004A0]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader] ADD  CONSTRAINT [DF__LosLocalP__rowgu__67C004A0]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LosLocalP__lphCo__56C06127]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader] ADD  DEFAULT ((0)) FOR [lphConfirmed]
GO
/****** Object:  Default [DF_LOsPaymentVoucherHeader_phExchangeRate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherHeader] ADD  CONSTRAINT [DF_LOsPaymentVoucherHeader_phExchangeRate]  DEFAULT (1) FOR [phExchangeRate]
GO
/****** Object:  Default [DF_LOsPaymentVoucherHeader_phfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherHeader] ADD  CONSTRAINT [DF_LOsPaymentVoucherHeader_phfuturevc]  DEFAULT ('') FOR [phfuturevc]
GO
/****** Object:  Default [DF_LOsPaymentVoucherHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherHeader] ADD  CONSTRAINT [DF_LOsPaymentVoucherHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__LOsPaymen__rowgu__35F39EE2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherHeader] ADD  CONSTRAINT [DF__LOsPaymen__rowgu__35F39EE2]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LOsAccountsInvoiceHeader_aiCashInvoice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] ADD  CONSTRAINT [DF_LOsAccountsInvoiceHeader_aiCashInvoice]  DEFAULT (0) FOR [aiCashInvoice]
GO
/****** Object:  Default [DF_LOsAccountsInvoiceHeader_aiProduct]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] ADD  CONSTRAINT [DF_LOsAccountsInvoiceHeader_aiProduct]  DEFAULT (0) FOR [aiProduct]
GO
/****** Object:  Default [DF_LOsAccountsInvoiceHeader_aiSettled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] ADD  CONSTRAINT [DF_LOsAccountsInvoiceHeader_aiSettled]  DEFAULT (0) FOR [aiSettled]
GO
/****** Object:  Default [DF_LOsAccountsInvoiceHeader_aiExchangeRate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] ADD  CONSTRAINT [DF_LOsAccountsInvoiceHeader_aiExchangeRate]  DEFAULT (1) FOR [aiExchangeRate]
GO
/****** Object:  Default [DF_LOsAccountsInvoiceHeader_aiSettledamount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] ADD  CONSTRAINT [DF_LOsAccountsInvoiceHeader_aiSettledamount]  DEFAULT (0) FOR [aiSettledamount]
GO
/****** Object:  Default [DF_LOsAccountsInvoiceHeader_aicfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] ADD  CONSTRAINT [DF_LOsAccountsInvoiceHeader_aicfuturevc]  DEFAULT ('') FOR [aicfuturevc]
GO
/****** Object:  Default [DF_LOsAccountsInvoiceHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] ADD  CONSTRAINT [DF_LOsAccountsInvoiceHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__LOsAccoun__rowgu__419A5BB8]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] ADD  CONSTRAINT [DF__LOsAccoun__rowgu__419A5BB8]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losAccoun__aiCas__05107065]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] ADD  CONSTRAINT [DF__losAccoun__aiCas__05107065]  DEFAULT (0) FOR [aiCashPaidByshop]
GO
/****** Object:  Default [DF__LOsAccoun__Exclu__3FB2DE9D]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] ADD  DEFAULT ((0)) FOR [ExcludeGST]
GO
/****** Object:  Default [DF_VendorSettlementHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VendorSettlementHeader] ADD  CONSTRAINT [DF_VendorSettlementHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__MEmessage__rowgu__3FA65AF7]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEmessages] ADD  CONSTRAINT [DF__MEmessage__rowgu__3FA65AF7]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_loaItemsplitcostingHeader_scfhCostFixed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loaItemsplitcostingHeader] ADD  CONSTRAINT [DF_loaItemsplitcostingHeader_scfhCostFixed]  DEFAULT (0) FOR [scfhCostFixed]
GO
/****** Object:  Default [DF_loaItemsplitcostingHeader_scfhCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loaItemsplitcostingHeader] ADD  CONSTRAINT [DF_loaItemsplitcostingHeader_scfhCancelled]  DEFAULT (0) FOR [scfhCancelled]
GO
/****** Object:  Default [DF__LOiArriva__rowgu__06ED0088]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivaltoLocation] ADD  CONSTRAINT [DF__LOiArriva__rowgu__06ED0088]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LOiGodown__rowgu__7B7B4DDC]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiGodownShopArrivalToLocation] ADD  CONSTRAINT [DF__LOiGodown__rowgu__7B7B4DDC]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LOiArrivalShipmentDetail_asdcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalShipmentDetail] ADD  CONSTRAINT [DF_LOiArrivalShipmentDetail_asdcostprice]  DEFAULT (0) FOR [asdcostprice]
GO
/****** Object:  Default [DF__LOiArriva__rowgu__01342732]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalShipmentDetail] ADD  CONSTRAINT [DF__LOiArriva__rowgu__01342732]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LOiArrivalDetail_adCostPrice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalDetail] ADD  CONSTRAINT [DF_LOiArrivalDetail_adCostPrice]  DEFAULT (0) FOR [adCostPrice]
GO
/****** Object:  Default [DF__LOiArriva__rowgu__1DD065E0]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalDetail] ADD  CONSTRAINT [DF__LOiArriva__rowgu__1DD065E0]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LoiItemSplitHeader_ishCostPriceFixed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LoiItemSplitHeader] ADD  CONSTRAINT [DF_LoiItemSplitHeader_ishCostPriceFixed]  DEFAULT (0) FOR [ishCostPriceFixed]
GO
/****** Object:  Default [DF_LoiItemSplitHeader_ishfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LoiItemSplitHeader] ADD  CONSTRAINT [DF_LoiItemSplitHeader_ishfuturevc]  DEFAULT ('') FOR [ishfuturevc]
GO
/****** Object:  Default [DF_LoiItemSplitHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LoiItemSplitHeader] ADD  CONSTRAINT [DF_LoiItemSplitHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__LoiItemSp__rowgu__17CD73C7]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LoiItemSplitHeader] ADD  CONSTRAINT [DF__LoiItemSp__rowgu__17CD73C7]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_loslocationissuedetails_ladcancel]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loslocationissuedetails] ADD  CONSTRAINT [DF_loslocationissuedetails_ladcancel]  DEFAULT (0) FOR [lidcancel]
GO
/****** Object:  Default [DF_loslocationissuedetails_lidadjustment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loslocationissuedetails] ADD  CONSTRAINT [DF_loslocationissuedetails_lidadjustment]  DEFAULT (0) FOR [lidadjustment]
GO
/****** Object:  Default [DF__loslocati__lidco__78F4B243]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loslocationissuedetails] ADD  CONSTRAINT [DF__loslocati__lidco__78F4B243]  DEFAULT (1) FOR [lidconfirmed]
GO
/****** Object:  Default [DF_loslocationarrivaldetails_ladcancel]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loslocationarrivaldetails] ADD  CONSTRAINT [DF_loslocationarrivaldetails_ladcancel]  DEFAULT (0) FOR [ladcancel]
GO
/****** Object:  Default [DF_loslocationarrivaldetails_ladadjustment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loslocationarrivaldetails] ADD  CONSTRAINT [DF_loslocationarrivaldetails_ladadjustment]  DEFAULT (0) FOR [ladadjustment]
GO
/****** Object:  Default [DF__loslocati__ladco__78008E0A]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loslocationarrivaldetails] ADD  CONSTRAINT [DF__loslocati__ladco__78008E0A]  DEFAULT (1) FOR [ladconfirmed]
GO
/****** Object:  Default [DF__LOiDamage__rowgu__7740A8A4]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiDamageClearingDetails] ADD  CONSTRAINT [DF__LOiDamage__rowgu__7740A8A4]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LOs_InHouseCons_ReturnDetail_IHRDcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOs_InHouseCons_ReturnDetail] ADD  CONSTRAINT [DF_LOs_InHouseCons_ReturnDetail_IHRDcostprice]  DEFAULT ((0)) FOR [IHRDcostprice]
GO
/****** Object:  Default [DF__losposExc__rowgu__52F9F1E4]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeOtherCharges] ADD  CONSTRAINT [DF__losposExc__rowgu__52F9F1E4]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losposExchangeDetail_sedcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeDetail] ADD  CONSTRAINT [DF_losposExchangeDetail_sedcostprice]  DEFAULT (0) FOR [sedcostprice]
GO
/****** Object:  Default [DF__losposExc__rowgu__05306BF6]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeDetail] ADD  CONSTRAINT [DF__losposExc__rowgu__05306BF6]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losposExc__rowgu__10A21EA2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeSubItemDetails] ADD  CONSTRAINT [DF__losposExc__rowgu__10A21EA2]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losPurcha__rowgu__2A212E2C]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderDetail] ADD  CONSTRAINT [DF__losPurcha__rowgu__2A212E2C]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losrebateconfirmheader_rccancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losrebateconfirmheader] ADD  CONSTRAINT [DF_losrebateconfirmheader_rccancelled]  DEFAULT (0) FOR [rccancelled]
GO
/****** Object:  Default [DF_LOiWriteOffDetail_wdcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiWriteOffDetail] ADD  CONSTRAINT [DF_LOiWriteOffDetail_wdcostprice]  DEFAULT (0) FOR [wdcostprice]
GO
/****** Object:  Default [DF__LOiWriteO__rowgu__5AA469F6]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiWriteOffDetail] ADD  CONSTRAINT [DF__LOiWriteO__rowgu__5AA469F6]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_FixedAsset_CostPrice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FixedAsset] ADD  CONSTRAINT [DF_FixedAsset_CostPrice]  DEFAULT (0) FOR [CostPrice]
GO
/****** Object:  Default [DF__FixedAsse__rowgu__28A2FA0E]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FixedAsset] ADD  CONSTRAINT [DF__FixedAsse__rowgu__28A2FA0E]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__fixedasse__poste__0DE4E231]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FixedAsset] ADD  CONSTRAINT [DF__fixedasse__poste__0DE4E231]  DEFAULT (0) FOR [posted]
GO
/****** Object:  Default [DF__fixedasse__Cance__48DB8ACD]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FixedAsset] ADD  CONSTRAINT [DF__fixedasse__Cance__48DB8ACD]  DEFAULT (0) FOR [Cancelled]
GO
/****** Object:  Default [DF__fixedasse__Exclu__1605F23D]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FixedAsset] ADD  CONSTRAINT [DF__fixedasse__Exclu__1605F23D]  DEFAULT (0) FOR [ExcludeFirstPeriodDep]
GO
/****** Object:  Default [DF__losInvoic__idrCu__16DA1AE5]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losInvoiceProjectRequestDetails] ADD  CONSTRAINT [DF__losInvoic__idrCu__16DA1AE5]  DEFAULT (0) FOR [idrCustomDutyByCustomer]
GO
/****** Object:  Default [DF_LOsInvoiceOC_icCompanyid]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceOC] ADD  CONSTRAINT [DF_LOsInvoiceOC_icCompanyid]  DEFAULT (1) FOR [ioCompanyid]
GO
/****** Object:  Default [DF__LOsInvoic__rowgu__795DFB40]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceOC] ADD  CONSTRAINT [DF__LOsInvoic__rowgu__795DFB40]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losrebaterequest_rrcancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losrebaterequest] ADD  CONSTRAINT [DF_losrebaterequest_rrcancelled]  DEFAULT (0) FOR [rrcancelled]
GO
/****** Object:  Default [DF_LosKegReturnDetail_krDDamaged]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosKegReturnDetail] ADD  CONSTRAINT [DF_LosKegReturnDetail_krDDamaged]  DEFAULT (0) FOR [krDDamaged]
GO
/****** Object:  Default [DF__LOsReceip__rowgu__04CFADEC]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsReceiptVoucherDetails] ADD  CONSTRAINT [DF__LOsReceip__rowgu__04CFADEC]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losEDIRequest_ercancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losEDIRequest] ADD  CONSTRAINT [DF_losEDIRequest_ercancelled]  DEFAULT (0) FOR [ercancelled]
GO
/****** Object:  Default [DF_LosGoodsReturnNoteHeader_GrnhCancel]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader] ADD  CONSTRAINT [DF_LosGoodsReturnNoteHeader_GrnhCancel]  DEFAULT (0) FOR [GrnhCancel]
GO
/****** Object:  Default [DF_LosGoodsReturnNoteHeader_GrnhPosted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader] ADD  CONSTRAINT [DF_LosGoodsReturnNoteHeader_GrnhPosted]  DEFAULT (0) FOR [GrnhPosted]
GO
/****** Object:  Default [DF_LosGoodsReturnNoteHeader_GrnCompanyID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader] ADD  CONSTRAINT [DF_LosGoodsReturnNoteHeader_GrnCompanyID]  DEFAULT (1) FOR [GrnCompanyID]
GO
/****** Object:  Default [DF_LosGoodsReturnNoteHeader_grnfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader] ADD  CONSTRAINT [DF_LosGoodsReturnNoteHeader_grnfuturevc]  DEFAULT ('') FOR [grnfuturevc]
GO
/****** Object:  Default [DF_LosGoodsReturnNoteHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader] ADD  CONSTRAINT [DF_LosGoodsReturnNoteHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__LosGoodsR__rowgu__10416098]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader] ADD  CONSTRAINT [DF__LosGoodsR__rowgu__10416098]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LOsInvoic__rowgu__426F4FB7]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceSubItemDetail] ADD  CONSTRAINT [DF__LOsInvoic__rowgu__426F4FB7]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LOsInvoiceDetail_idcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD  CONSTRAINT [DF_LOsInvoiceDetail_idcostprice]  DEFAULT (0) FOR [idcostprice]
GO
/****** Object:  Default [DF__LOsInvoic__rowgu__6497E884]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD  CONSTRAINT [DF__LOsInvoic__rowgu__6497E884]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losinvoic__idTyp__18C26357]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD  CONSTRAINT [DF__losinvoic__idTyp__18C26357]  DEFAULT (' ') FOR [idType]
GO
/****** Object:  Default [DF_losInvoiceDetail_idKitID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD  CONSTRAINT [DF_losInvoiceDetail_idKitID]  DEFAULT (0) FOR [idKitID]
GO
/****** Object:  Default [DF__losInvoic__idCus__70E97C27]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD  CONSTRAINT [DF__losInvoic__idCus__70E97C27]  DEFAULT (0) FOR [idCustomPrice]
GO
/****** Object:  Default [DF_LOSTransferinheader_TIHcancel]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOSTransferinheader] ADD  CONSTRAINT [DF_LOSTransferinheader_TIHcancel]  DEFAULT (0) FOR [TIHcancel]
GO
/****** Object:  Default [DF_LOSTransferinheader_TIHTransFinished]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOSTransferinheader] ADD  CONSTRAINT [DF_LOSTransferinheader_TIHTransFinished]  DEFAULT (0) FOR [TIHTransFinished]
GO
/****** Object:  Default [DF_LOSTransferinheader_TIHPosted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOSTransferinheader] ADD  CONSTRAINT [DF_LOSTransferinheader_TIHPosted]  DEFAULT (0) FOR [TIHPosted]
GO
/****** Object:  Default [DF_LOSTransferinheader_TIHfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOSTransferinheader] ADD  CONSTRAINT [DF_LOSTransferinheader_TIHfuturevc]  DEFAULT ('') FOR [TIHfuturevc]
GO
/****** Object:  Default [DF_LOSTransferinheader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOSTransferinheader] ADD  CONSTRAINT [DF_LOSTransferinheader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__LOSTransf__rowgu__387A3A7B]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOSTransferinheader] ADD  CONSTRAINT [DF__LOSTransf__rowgu__387A3A7B]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LOsShopDa__rowgu__0A888742]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsShopDamageClearingDetails] ADD  CONSTRAINT [DF__LOsShopDa__rowgu__0A888742]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LOsWriteOffDetail_wdcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsWriteOffDetail] ADD  CONSTRAINT [DF_LOsWriteOffDetail_wdcostprice]  DEFAULT (0) FOR [wdcostprice]
GO
/****** Object:  Default [DF__LOsWriteO__rowgu__52CE3E04]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsWriteOffDetail] ADD  CONSTRAINT [DF__LOsWriteO__rowgu__52CE3E04]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LOs_InHou__IHRHC__0DFB8778]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOs_InHouseCons_ReturnHeader] ADD  DEFAULT ((0)) FOR [IHRHCancelled]
GO
/****** Object:  Default [DF_LOsWriteOffHeader_IHRHposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOs_InHouseCons_ReturnHeader] ADD  CONSTRAINT [DF_LOsWriteOffHeader_IHRHposted]  DEFAULT ((0)) FOR [IHRHposted]
GO
/****** Object:  Default [DF__LOs_InHou__updat__0FE3CFEA]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOs_InHouseCons_ReturnHeader] ADD  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__aUserRigh__rowgu__515009E6]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aUserRights] ADD  CONSTRAINT [DF__aUserRigh__rowgu__515009E6]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LOSTransferindetail_TIDCostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOSTransferindetail] ADD  CONSTRAINT [DF_LOSTransferindetail_TIDCostprice]  DEFAULT (0) FOR [TIDCostprice]
GO
/****** Object:  Default [DF_MEsDespatchtoGodownDetail_dgdcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsDespatchtoGodownDetail] ADD  CONSTRAINT [DF_MEsDespatchtoGodownDetail_dgdcostprice]  DEFAULT (0) FOR [dgdcostprice]
GO
/****** Object:  Default [DF__MEsDespat__rowgu__70099B30]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsDespatchtoGodownDetail] ADD  CONSTRAINT [DF__MEsDespat__rowgu__70099B30]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aAnalysedPOItems_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aAnalysedPOItems] ADD  CONSTRAINT [DF_aAnalysedPOItems_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF_losSIQuotationDetail_idRateType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationDetail] ADD  CONSTRAINT [DF_losSIQuotationDetail_idRateType]  DEFAULT (0) FOR [idRateType]
GO
/****** Object:  Default [DF_losSIQuotationDetail_despatch]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationDetail] ADD  CONSTRAINT [DF_losSIQuotationDetail_despatch]  DEFAULT (0) FOR [despatch]
GO
/****** Object:  Default [DF_losSIQuotationDetail_idcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationDetail] ADD  CONSTRAINT [DF_losSIQuotationDetail_idcostprice]  DEFAULT (0) FOR [idcostprice]
GO
/****** Object:  Default [DF__losSIQuo__rowgu__17D9F76D]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationDetail] ADD  CONSTRAINT [DF__losSIQuo__rowgu__17D9F76D]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losSIQuo__idFre__32B73F84]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationDetail] ADD  CONSTRAINT [DF__losSIQuo__idFre__32B73F84]  DEFAULT (0) FOR [idFreeQuantity]
GO
/****** Object:  Default [DF_aHQDespatchNoteDetails_ddCostPrice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchNoteDetails] ADD  CONSTRAINT [DF_aHQDespatchNoteDetails_ddCostPrice]  DEFAULT (0) FOR [ddCostPrice]
GO
/****** Object:  Default [DF__aHQDespat__rowgu__62720AF5]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchNoteDetails] ADD  CONSTRAINT [DF__aHQDespat__rowgu__62720AF5]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_loilocationissuedetails_lidcancel]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loilocationissuedetails] ADD  CONSTRAINT [DF_loilocationissuedetails_lidcancel]  DEFAULT (0) FOR [lidcancel]
GO
/****** Object:  Default [DF_loilocationissuedetails_lidadjustment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loilocationissuedetails] ADD  CONSTRAINT [DF_loilocationissuedetails_lidadjustment]  DEFAULT (0) FOR [lidadjustment]
GO
/****** Object:  Default [DF__loilocati__lidco__770C69D1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loilocationissuedetails] ADD  CONSTRAINT [DF__loilocati__lidco__770C69D1]  DEFAULT (1) FOR [lidconfirmed]
GO
/****** Object:  Default [DF_LOsPosDetail_posdRateType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosDetail] ADD  CONSTRAINT [DF_LOsPosDetail_posdRateType]  DEFAULT (0) FOR [posdRateType]
GO
/****** Object:  Default [DF_LOsPosDetail_posdcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosDetail] ADD  CONSTRAINT [DF_LOsPosDetail_posdcostprice]  DEFAULT (0) FOR [posdcostprice]
GO
/****** Object:  Default [DF__LOsPosDet__rowgu__384F51F2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosDetail] ADD  CONSTRAINT [DF__LOsPosDet__rowgu__384F51F2]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losPosDetail_posdKitID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosDetail] ADD  CONSTRAINT [DF_losPosDetail_posdKitID]  DEFAULT (0) FOR [posdKitID]
GO
/****** Object:  Default [DF__LOsPosDet__posdB__428F4B48]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosDetail] ADD  DEFAULT ((1)) FOR [posdBillDetailID]
GO
/****** Object:  Default [DF__LOsPosDet__posdI__5C6F18DC]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosDetail] ADD  DEFAULT ('I') FOR [posdItemType]
GO
/****** Object:  Default [DF__losinvpar__rowgu__0C11A858]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losinvpartsreplacedetails] ADD  CONSTRAINT [DF__losinvpar__rowgu__0C11A858]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_MEDifferenceinStock_dsToAdd]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEDifferenceinStock] ADD  CONSTRAINT [DF_MEDifferenceinStock_dsToAdd]  DEFAULT (0) FOR [dsToAdd]
GO
/****** Object:  Default [DF_MEDifferenceinStock_dsToDeduct]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEDifferenceinStock] ADD  CONSTRAINT [DF_MEDifferenceinStock_dsToDeduct]  DEFAULT (0) FOR [dsToDeduct]
GO
/****** Object:  Default [DF_MEDifferenceinStock_dsFromGodownID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEDifferenceinStock] ADD  CONSTRAINT [DF_MEDifferenceinStock_dsFromGodownID]  DEFAULT (0) FOR [dsFromGodownID]
GO
/****** Object:  Default [DF_MEDifferenceinStock_dsToGodownID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEDifferenceinStock] ADD  CONSTRAINT [DF_MEDifferenceinStock_dsToGodownID]  DEFAULT (0) FOR [dsToGodownID]
GO
/****** Object:  Default [DF_MEDifferenceinStock_dsFromShopID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEDifferenceinStock] ADD  CONSTRAINT [DF_MEDifferenceinStock_dsFromShopID]  DEFAULT (0) FOR [dsFromShopID]
GO
/****** Object:  Default [DF_MEDifferenceinStock_dsToShopID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEDifferenceinStock] ADD  CONSTRAINT [DF_MEDifferenceinStock_dsToShopID]  DEFAULT (0) FOR [dsToShopID]
GO
/****** Object:  Default [DF_LosGoodsReturnNoteDetail_GRNDunitprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteDetail] ADD  CONSTRAINT [DF_LosGoodsReturnNoteDetail_GRNDunitprice]  DEFAULT (0) FOR [GRNDunitprice]
GO
/****** Object:  Default [DF_LosGoodsReturnNoteDetail_GRNDDamaged]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteDetail] ADD  CONSTRAINT [DF_LosGoodsReturnNoteDetail_GRNDDamaged]  DEFAULT (0) FOR [GRNDDamaged]
GO
/****** Object:  Default [DF_LosGoodsReturnNoteDetail_grncostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteDetail] ADD  CONSTRAINT [DF_LosGoodsReturnNoteDetail_grncostprice]  DEFAULT (0) FOR [grncostprice]
GO
/****** Object:  Default [DF__MOiGodown__rowgu__23893F36]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOiGodownStock] ADD  CONSTRAINT [DF__MOiGodown__rowgu__23893F36]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LosLocalP__rowgu__6A50C1DA]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseDetail] ADD  CONSTRAINT [DF__LosLocalP__rowgu__6A50C1DA]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__loPurchas__rowgu__18F6A22A]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPurchaseOrderDetail] ADD  CONSTRAINT [DF__loPurchas__rowgu__18F6A22A]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LosReserv__rowgu__386F4D83]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosReserveItem] ADD  CONSTRAINT [DF__LosReserv__rowgu__386F4D83]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losreplac__rowgu__0658CF02]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacereceivedetails] ADD  CONSTRAINT [DF__losreplac__rowgu__0658CF02]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_meiSpecialDespatchtoShopDetail_ddItemBadQty]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoShopDetail] ADD  CONSTRAINT [DF_meiSpecialDespatchtoShopDetail_ddItemBadQty]  DEFAULT (0) FOR [ddItemBadQty]
GO
/****** Object:  Default [DF_meiSpecialDespatchtoShopDetail_ddItemGoodQty]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoShopDetail] ADD  CONSTRAINT [DF_meiSpecialDespatchtoShopDetail_ddItemGoodQty]  DEFAULT (0) FOR [ddItemGoodQty]
GO
/****** Object:  Default [DF_meiSpecialDespatchtoShopDetail_ddCostedPrice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoShopDetail] ADD  CONSTRAINT [DF_meiSpecialDespatchtoShopDetail_ddCostedPrice]  DEFAULT (0) FOR [ddCostedPrice]
GO
/****** Object:  Default [DF_meiSpecialDespatchtoShopDetail_ddinvqty]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoShopDetail] ADD  CONSTRAINT [DF_meiSpecialDespatchtoShopDetail_ddinvqty]  DEFAULT (0) FOR [ddinvqty]
GO
/****** Object:  Default [DF__meiSpecia__rowgu__1A74D648]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoShopDetail] ADD  CONSTRAINT [DF__meiSpecia__rowgu__1A74D648]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LOsPosSub__rowgu__070CFC19]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosSubItemDetail] ADD  CONSTRAINT [DF__LOsPosSub__rowgu__070CFC19]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losStockVerificationDetail_svdcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockVerificationDetail] ADD  CONSTRAINT [DF_losStockVerificationDetail_svdcostprice]  DEFAULT (0) FOR [svdcostprice]
GO
/****** Object:  Default [DF__losStockV__rowgu__7ADC2F5E]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockVerificationDetail] ADD  CONSTRAINT [DF__losStockV__rowgu__7ADC2F5E]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LoiItemSp__rowgu__7484378A]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LoiItemSplitDetail] ADD  CONSTRAINT [DF__LoiItemSp__rowgu__7484378A]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losSerMai__msdAl__19176912]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerMaintenanceServiceDetail] ADD  CONSTRAINT [DF__losSerMai__msdAl__19176912]  DEFAULT (0) FOR [msdAlerttype]
GO
/****** Object:  Default [DF_LOspPurchaseBillDetail_pbdItemCostedPrice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillDetail] ADD  CONSTRAINT [DF_LOspPurchaseBillDetail_pbdItemCostedPrice]  DEFAULT (0) FOR [pbdItemCostedPrice]
GO
/****** Object:  Default [DF_LOspPurchaseBillDetail_pbdItemFixedPrice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillDetail] ADD  CONSTRAINT [DF_LOspPurchaseBillDetail_pbdItemFixedPrice]  DEFAULT (0) FOR [pbdItemFixedPrice]
GO
/****** Object:  Default [DF_aPurchasePriceRange_MinPrice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPurchasePriceRange] ADD  CONSTRAINT [DF_aPurchasePriceRange_MinPrice]  DEFAULT ((0)) FOR [MinPrice]
GO
/****** Object:  Default [DF_aPurchasePriceRange_MaxPrice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPurchasePriceRange] ADD  CONSTRAINT [DF_aPurchasePriceRange_MaxPrice]  DEFAULT ((0)) FOR [MaxPrice]
GO
/****** Object:  Default [DF_losShopItemShipmentDetail_PackingTypeid]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losShopItemShipmentDetail] ADD  CONSTRAINT [DF_losShopItemShipmentDetail_PackingTypeid]  DEFAULT (1) FOR [PackingTypeid]
GO
/****** Object:  Default [DF_losShopItemShipmentDetail_sellingPrice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losShopItemShipmentDetail] ADD  CONSTRAINT [DF_losShopItemShipmentDetail_sellingPrice]  DEFAULT (0) FOR [sellingPrice]
GO
/****** Object:  Default [DF_losShopItemShipmentDetail_WholesalePrice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losShopItemShipmentDetail] ADD  CONSTRAINT [DF_losShopItemShipmentDetail_WholesalePrice]  DEFAULT (0) FOR [WholesalePrice]
GO
/****** Object:  Default [DF_losShopItemShipmentDetail_DiscountPrice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losShopItemShipmentDetail] ADD  CONSTRAINT [DF_losShopItemShipmentDetail_DiscountPrice]  DEFAULT (0) FOR [DiscountPrice]
GO
/****** Object:  Default [DF_losShopItemShipmentDetail_Pricechanged]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losShopItemShipmentDetail] ADD  CONSTRAINT [DF_losShopItemShipmentDetail_Pricechanged]  DEFAULT (0) FOR [Pricechanged]
GO
/****** Object:  Default [DF__losShopIt__rowgu__7ECCBBD3]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losShopItemShipmentDetail] ADD  CONSTRAINT [DF__losShopIt__rowgu__7ECCBBD3]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__MOsShopSt__rowgu__75C27486]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOsShopStock] ADD  CONSTRAINT [DF__MOsShopSt__rowgu__75C27486]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_loiStockVerificationDetail_svdcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockVerificationDetail] ADD  CONSTRAINT [DF_loiStockVerificationDetail_svdcostprice]  DEFAULT (0) FOR [svdcostprice]
GO
/****** Object:  Default [DF__loiStockV__rowgu__75235608]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockVerificationDetail] ADD  CONSTRAINT [DF__loiStockV__rowgu__75235608]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_loilocationarrivaldetails_ladcancel]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loilocationarrivaldetails] ADD  CONSTRAINT [DF_loilocationarrivaldetails_ladcancel]  DEFAULT (0) FOR [ladcancel]
GO
/****** Object:  Default [DF_loilocationarrivaldetails_ladadjustment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loilocationarrivaldetails] ADD  CONSTRAINT [DF_loilocationarrivaldetails_ladadjustment]  DEFAULT (0) FOR [ladadjustment]
GO
/****** Object:  Default [DF__loilocati__ladco__76184598]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loilocationarrivaldetails] ADD  CONSTRAINT [DF__loilocati__ladco__76184598]  DEFAULT (1) FOR [ladconfirmed]
GO
/****** Object:  Default [DF_aGodownDetail_OrderRaised]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodownDetail] ADD  CONSTRAINT [DF_aGodownDetail_OrderRaised]  DEFAULT (0) FOR [OrderRaised]
GO
/****** Object:  Default [DF_aGodownDetail_QuotationRaised]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodownDetail] ADD  CONSTRAINT [DF_aGodownDetail_QuotationRaised]  DEFAULT (0) FOR [QuotationRaised]
GO
/****** Object:  Default [DF__aGodownDe__rowgu__40257DE4]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodownDetail] ADD  CONSTRAINT [DF__aGodownDe__rowgu__40257DE4]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_MEiGodownTransferDetail_gtdcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiGodownTransferDetail] ADD  CONSTRAINT [DF_MEiGodownTransferDetail_gtdcostprice]  DEFAULT (0) FOR [gtdcostprice]
GO
/****** Object:  Default [DF__MEiGodown__rowgu__4979DDF4]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiGodownTransferDetail] ADD  CONSTRAINT [DF__MEiGodown__rowgu__4979DDF4]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__loPrePurchas__rowgu__18F6A22A]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderDetail] ADD  CONSTRAINT [DF__loPrePurchas__rowgu__18F6A22A]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_loiStockRecovery_srcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockRecovery] ADD  CONSTRAINT [DF_loiStockRecovery_srcostprice]  DEFAULT (0) FOR [srcostprice]
GO
/****** Object:  Default [DF_loiStockRecovery_srposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockRecovery] ADD  CONSTRAINT [DF_loiStockRecovery_srposted]  DEFAULT (0) FOR [srposted]
GO
/****** Object:  Default [DF_loiStockRecovery_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockRecovery] ADD  CONSTRAINT [DF_loiStockRecovery_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__loiStockR__rowgu__2BD46C74]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockRecovery] ADD  CONSTRAINT [DF__loiStockR__rowgu__2BD46C74]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aItemPackingDetail_active]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aItemPackingDetail] ADD  CONSTRAINT [DF_aItemPackingDetail_active]  DEFAULT (0) FOR [active]
GO
/****** Object:  Default [DF__aItemPack__rowgu__66161CA2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aItemPackingDetail] ADD  CONSTRAINT [DF__aItemPack__rowgu__66161CA2]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aShopItemDetail_RequestRaised]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopItemDetail] ADD  CONSTRAINT [DF_aShopItemDetail_RequestRaised]  DEFAULT (0) FOR [RequestRaised]
GO
/****** Object:  Default [DF_aShopItemDetail_orderraised]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopItemDetail] ADD  CONSTRAINT [DF_aShopItemDetail_orderraised]  DEFAULT (0) FOR [orderraised]
GO
/****** Object:  Default [DF_aShopItemDetail_quotationraised]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopItemDetail] ADD  CONSTRAINT [DF_aShopItemDetail_quotationraised]  DEFAULT (0) FOR [quotationraised]
GO
/****** Object:  Default [DF__aShopItem__rowgu__4F32B74A]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopItemDetail] ADD  CONSTRAINT [DF__aShopItem__rowgu__4F32B74A]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_mosshopservicestock_serstkfuturebit]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mosshopservicestock] ADD  CONSTRAINT [DF_mosshopservicestock_serstkfuturebit]  DEFAULT (0) FOR [serstkfuturebit]
GO
/****** Object:  Default [DF__mosshopse__rowgu__052FA09F]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mosshopservicestock] ADD  CONSTRAINT [DF__mosshopse__rowgu__052FA09F]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__moapoitem__rowgu__1F4543B4]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[moapoitems] ADD  CONSTRAINT [DF__moapoitem__rowgu__1F4543B4]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_moStockWriteOffHQ_swposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[moStockWriteOffHQ] ADD  CONSTRAINT [DF_moStockWriteOffHQ_swposted]  DEFAULT (0) FOR [swposted]
GO
/****** Object:  Default [DF_moStockWriteOffHQ_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[moStockWriteOffHQ] ADD  CONSTRAINT [DF_moStockWriteOffHQ_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__mosGoodsR__rowgu__064DE20A]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mosGoodsRequestDetail] ADD  CONSTRAINT [DF__mosGoodsR__rowgu__064DE20A]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aSubItemD__rowgu__7187CF4E]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSubItemDetails] ADD  CONSTRAINT [DF__aSubItemD__rowgu__7187CF4E]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aHQIssuen__rowgu__544C7222]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteDetail] ADD  CONSTRAINT [DF__aHQIssuen__rowgu__544C7222]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__MEiDespat__rowgu__6D4D2A16]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiDespatchToShopDetail] ADD  CONSTRAINT [DF__MEiDespat__rowgu__6D4D2A16]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LOsGoodsArrivaltoShopDetail_gadcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopDetail] ADD  CONSTRAINT [DF_LOsGoodsArrivaltoShopDetail_gadcostprice]  DEFAULT (0) FOR [gadcostprice]
GO
/****** Object:  Default [DF_losStockRecovery_srcostprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockRecovery] ADD  CONSTRAINT [DF_losStockRecovery_srcostprice]  DEFAULT (0) FOR [srcostprice]
GO
/****** Object:  Default [DF_losStockRecovery_srposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockRecovery] ADD  CONSTRAINT [DF_losStockRecovery_srposted]  DEFAULT (0) FOR [srposted]
GO
/****** Object:  Default [DF_losStockRecovery_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockRecovery] ADD  CONSTRAINT [DF_losStockRecovery_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__losStockR__rowgu__306FCFB6]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockRecovery] ADD  CONSTRAINT [DF__losStockR__rowgu__306FCFB6]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LOiLocati__rowgu__0E240DFC]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiLocation] ADD  CONSTRAINT [DF__LOiLocati__rowgu__0E240DFC]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aGodownIt__rowgu__13FCE2E3]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodownItemCategory] ADD  CONSTRAINT [DF__aGodownIt__rowgu__13FCE2E3]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aShopitem__rowgu__4964CF5B]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopitemCategory] ADD  CONSTRAINT [DF__aShopitem__rowgu__4964CF5B]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aListItemDetails_Qty]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aListItemDetails] ADD  CONSTRAINT [DF_aListItemDetails_Qty]  DEFAULT (1) FOR [Qty]
GO
/****** Object:  Default [DF_aListViewDetails_lvwdcolwidth]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aListViewDetails] ADD  CONSTRAINT [DF_aListViewDetails_lvwdcolwidth]  DEFAULT (1500) FOR [lvwdcolwidth]
GO
/****** Object:  Default [DF_aListViewDetails_lvwdcolalign]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aListViewDetails] ADD  CONSTRAINT [DF_aListViewDetails_lvwdcolalign]  DEFAULT (0) FOR [lvwdcolalign]
GO
/****** Object:  Default [DF_aCustomerMaster_Active]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCustomerMaster] ADD  CONSTRAINT [DF_aCustomerMaster_Active]  DEFAULT (1) FOR [Active]
GO
/****** Object:  Default [DF_aCustomerMaster_CreditLimit]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCustomerMaster] ADD  CONSTRAINT [DF_aCustomerMaster_CreditLimit]  DEFAULT (0) FOR [CreditLimit]
GO
/****** Object:  Default [DF_aCustomerMaster_OpeningCreditBalance]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCustomerMaster] ADD  CONSTRAINT [DF_aCustomerMaster_OpeningCreditBalance]  DEFAULT (0) FOR [OpeningCreditBalance]
GO
/****** Object:  Default [DF_aCustomerMaster_OpeningDebitBalance]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCustomerMaster] ADD  CONSTRAINT [DF_aCustomerMaster_OpeningDebitBalance]  DEFAULT (0) FOR [OpeningDebitBalance]
GO
/****** Object:  Default [DF_aCustomerMaster_CustomerCategory]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCustomerMaster] ADD  CONSTRAINT [DF_aCustomerMaster_CustomerCategory]  DEFAULT ('') FOR [CustomerCategory]
GO
/****** Object:  Default [DF_aCustomerMaster_Dueperiod]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCustomerMaster] ADD  CONSTRAINT [DF_aCustomerMaster_Dueperiod]  DEFAULT (0) FOR [Dueperiod]
GO
/****** Object:  Default [DF__aCustomer__rowgu__1F4E99FE]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCustomerMaster] ADD  CONSTRAINT [DF__aCustomer__rowgu__1F4E99FE]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aCustomer__Exclu__3CD671F2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCustomerMaster] ADD  DEFAULT ((0)) FOR [ExcludeGST]
GO
/****** Object:  Default [DF_aShops_Selected]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  CONSTRAINT [DF_aShops_Selected]  DEFAULT (0) FOR [Selected]
GO
/****** Object:  Default [DF_aShops_Truncate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  CONSTRAINT [DF_aShops_Truncate]  DEFAULT (1) FOR [TruncateCheck]
GO
/****** Object:  Default [DF_aShops_FIFO]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  CONSTRAINT [DF_aShops_FIFO]  DEFAULT (1) FOR [FIFO]
GO
/****** Object:  Default [DF_aShops_dayClosed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  CONSTRAINT [DF_aShops_dayClosed]  DEFAULT (0) FOR [dayClosed]
GO
/****** Object:  Default [DF_aShops_wholesaleallowed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  CONSTRAINT [DF_aShops_wholesaleallowed]  DEFAULT (0) FOR [wholesaleallowed]
GO
/****** Object:  Default [DF_aShops_allowblockprice]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  CONSTRAINT [DF_aShops_allowblockprice]  DEFAULT (0) FOR [allowblockprice]
GO
/****** Object:  Default [DF__ashops__showcost__08211BE3]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  CONSTRAINT [DF__ashops__showcost__08211BE3]  DEFAULT (0) FOR [showcostpriceinsales]
GO
/****** Object:  Default [DF_aShops_RevisedCostPricePercent]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  CONSTRAINT [DF_aShops_RevisedCostPricePercent]  DEFAULT (0) FOR [RevisedCostPricePercent]
GO
/****** Object:  Default [DF__aShops__rowguid__319832C2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  CONSTRAINT [DF__aShops__rowguid__319832C2]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__ashops__location__7579271A]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  CONSTRAINT [DF__ashops__location__7579271A]  DEFAULT (0) FOR [locationarrangement]
GO
/****** Object:  Default [DF__aShops__Delivery__0FB81C0A]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  CONSTRAINT [DF__aShops__Delivery__0FB81C0A]  DEFAULT (0) FOR [DeliveryMust]
GO
/****** Object:  Default [DF__aShops__RateEdit__07C1F487]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  CONSTRAINT [DF__aShops__RateEdit__07C1F487]  DEFAULT (1) FOR [RateEditingonDirectCashInv]
GO
/****** Object:  Default [DF__aShops__RateEdit__08B618C0]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  CONSTRAINT [DF__aShops__RateEdit__08B618C0]  DEFAULT (1) FOR [RateEditingonDirectCreditInv]
GO
/****** Object:  Default [DF__aShops__Shipment__35FE8BDA]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  DEFAULT ((0)) FOR [ShipmentDetails]
GO
/****** Object:  Default [DF__aShops__showbinl__4DD6156B]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  DEFAULT ((0)) FOR [showbinlocation]
GO
/****** Object:  Default [DF__aShops__printKOT__589E87F8]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops] ADD  DEFAULT ((0)) FOR [printKOTseperatly]
GO
/****** Object:  Default [DF__aPackingT__rowgu__475C8B58]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPackingTypeCapacityDetail] ADD  CONSTRAINT [DF__aPackingT__rowgu__475C8B58]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__mesRQtoHQ__rowgu__50A7951E]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesRQtoHQforItem] ADD  CONSTRAINT [DF__mesRQtoHQ__rowgu__50A7951E]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__meiRQtoHQ__rowgu__3C0AD43D]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiRQtoHQforItem] ADD  CONSTRAINT [DF__meiRQtoHQ__rowgu__3C0AD43D]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__Agreement__agwAg__17AE438D]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AgreementWitnessDetails] ADD  CONSTRAINT [DF__Agreement__agwAg__17AE438D]  DEFAULT (0) FOR [agwAgency]
GO
/****** Object:  Default [DF__Agreement__agsAg__15C5FB1B]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AgreementSignedDetails] ADD  CONSTRAINT [DF__Agreement__agsAg__15C5FB1B]  DEFAULT (0) FOR [agsAgency]
GO
/****** Object:  Default [DF__aproductc__rowgu__3C15C135]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aproductconditionmaster] ADD  CONSTRAINT [DF__aproductc__rowgu__3C15C135]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_ReceiptVoucherDetails_AmountReceived]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherDetails] ADD  CONSTRAINT [DF_ReceiptVoucherDetails_AmountReceived]  DEFAULT (0) FOR [AmountReceived]
GO
/****** Object:  Default [DF_ReceiptVoucherDetails_dueperiod]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherDetails] ADD  CONSTRAINT [DF_ReceiptVoucherDetails_dueperiod]  DEFAULT (0) FOR [dueperiod]
GO
/****** Object:  Default [DF_LOiArrivalHeader_ahGodownID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalHeader] ADD  CONSTRAINT [DF_LOiArrivalHeader_ahGodownID]  DEFAULT (0) FOR [ahGodownID]
GO
/****** Object:  Default [DF_LOiArrivalHeader_ahShopID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalHeader] ADD  CONSTRAINT [DF_LOiArrivalHeader_ahShopID]  DEFAULT (0) FOR [ahShopID]
GO
/****** Object:  Default [DF_LOiArrivalHeader_ahCostPriceFixed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalHeader] ADD  CONSTRAINT [DF_LOiArrivalHeader_ahCostPriceFixed]  DEFAULT (0) FOR [ahCostPriceFixed]
GO
/****** Object:  Default [DF_LOiArrivalHeader_ahTransFinished]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalHeader] ADD  CONSTRAINT [DF_LOiArrivalHeader_ahTransFinished]  DEFAULT (0) FOR [ahTransFinished]
GO
/****** Object:  Default [DF_LOiArrivalHeader_ahfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalHeader] ADD  CONSTRAINT [DF_LOiArrivalHeader_ahfuturevc]  DEFAULT ('') FOR [ahfuturevc]
GO
/****** Object:  Default [DF_LOiArrivalHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalHeader] ADD  CONSTRAINT [DF_LOiArrivalHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF_LOiArrivalHeader_ahposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalHeader] ADD  CONSTRAINT [DF_LOiArrivalHeader_ahposted]  DEFAULT (0) FOR [ahposted]
GO
/****** Object:  Default [DF__LOiArriva__rowgu__02B25B50]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalHeader] ADD  CONSTRAINT [DF__LOiArriva__rowgu__02B25B50]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aHQDespatchnoteHeader_dhCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchnoteHeader] ADD  CONSTRAINT [DF_aHQDespatchnoteHeader_dhCancelled]  DEFAULT (0) FOR [dhCancelled]
GO
/****** Object:  Default [DF_aHQDespatchnoteHeader_dhSelected]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchnoteHeader] ADD  CONSTRAINT [DF_aHQDespatchnoteHeader_dhSelected]  DEFAULT (0) FOR [dhSelected]
GO
/****** Object:  Default [DF_aHQDespatchnoteHeader_barcodegenerated]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchnoteHeader] ADD  CONSTRAINT [DF_aHQDespatchnoteHeader_barcodegenerated]  DEFAULT (0) FOR [barcodegenerated]
GO
/****** Object:  Default [DF_aHQDespatchnoteHeader_dhTransFinished]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchnoteHeader] ADD  CONSTRAINT [DF_aHQDespatchnoteHeader_dhTransFinished]  DEFAULT (0) FOR [dhTransFinished]
GO
/****** Object:  Default [DF_aHQDespatchnoteHeader_dhNoofDetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchnoteHeader] ADD  CONSTRAINT [DF_aHQDespatchnoteHeader_dhNoofDetails]  DEFAULT (0) FOR [dhNoofDetails]
GO
/****** Object:  Default [DF_aHQDespatchnoteHeader_Futurevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchnoteHeader] ADD  CONSTRAINT [DF_aHQDespatchnoteHeader_Futurevc]  DEFAULT ('') FOR [Futurevc]
GO
/****** Object:  Default [DF_aHQDespatchnoteHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchnoteHeader] ADD  CONSTRAINT [DF_aHQDespatchnoteHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__aHQDespat__rowgu__2942188C]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchnoteHeader] ADD  CONSTRAINT [DF__aHQDespat__rowgu__2942188C]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__BudgetPla__brdCo__13E89FA1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[BudgetPlanReviseDetail] ADD  CONSTRAINT [DF__BudgetPla__brdCo__13E89FA1]  DEFAULT (0) FOR [brdConfirmed]
GO
/****** Object:  Default [DF_MEiDespatchToShopHeader_dhTransFinished]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiDespatchToShopHeader] ADD  CONSTRAINT [DF_MEiDespatchToShopHeader_dhTransFinished]  DEFAULT (0) FOR [dhTransFinished]
GO
/****** Object:  Default [DF_MEiDespatchToShopHeader_dhNoofDetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiDespatchToShopHeader] ADD  CONSTRAINT [DF_MEiDespatchToShopHeader_dhNoofDetails]  DEFAULT (0) FOR [dhNoofDetails]
GO
/****** Object:  Default [DF_MEiDespatchToShopHeader_dhfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiDespatchToShopHeader] ADD  CONSTRAINT [DF_MEiDespatchToShopHeader_dhfuturevc]  DEFAULT ('') FOR [dhfuturevc]
GO
/****** Object:  Default [DF_MEiDespatchToShopHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiDespatchToShopHeader] ADD  CONSTRAINT [DF_MEiDespatchToShopHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__meidespat__dhpos__37088A03]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiDespatchToShopHeader] ADD  CONSTRAINT [DF__meidespat__dhpos__37088A03]  DEFAULT (0) FOR [dhposted]
GO
/****** Object:  Default [DF__MEiDespat__rowgu__554B8353]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiDespatchToShopHeader] ADD  CONSTRAINT [DF__MEiDespat__rowgu__554B8353]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aTableCol__rowgu__6F6A7CB2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aTableColumns] ADD  CONSTRAINT [DF__aTableCol__rowgu__6F6A7CB2]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LOsInvoiceHeader_ihCompanyId]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader] ADD  CONSTRAINT [DF_LOsInvoiceHeader_ihCompanyId]  DEFAULT (1) FOR [ihCompanyId]
GO
/****** Object:  Default [DF_LOsInvoiceHeader_ihGoodsReturned]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader] ADD  CONSTRAINT [DF_LOsInvoiceHeader_ihGoodsReturned]  DEFAULT (0) FOR [ihGoodsReturned]
GO
/****** Object:  Default [DF_LOsInvoiceHeader_ihAdjustmentAmount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader] ADD  CONSTRAINT [DF_LOsInvoiceHeader_ihAdjustmentAmount]  DEFAULT (0) FOR [ihAdjustmentAmount]
GO
/****** Object:  Default [DF_LOsInvoiceHeader_ihSettled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader] ADD  CONSTRAINT [DF_LOsInvoiceHeader_ihSettled]  DEFAULT (0) FOR [ihSettled]
GO
/****** Object:  Default [DF_LOsInvoiceHeader_ihexchangerate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader] ADD  CONSTRAINT [DF_LOsInvoiceHeader_ihexchangerate]  DEFAULT (1) FOR [ihexchangerate]
GO
/****** Object:  Default [DF_LOsInvoiceHeader_ihsettledamount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader] ADD  CONSTRAINT [DF_LOsInvoiceHeader_ihsettledamount]  DEFAULT (0) FOR [ihsettledamount]
GO
/****** Object:  Default [DF_LOsInvoiceHeader_ihwholesale]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader] ADD  CONSTRAINT [DF_LOsInvoiceHeader_ihwholesale]  DEFAULT (0) FOR [ihwholesale]
GO
/****** Object:  Default [DF_LOsInvoiceHeader_ihfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader] ADD  CONSTRAINT [DF_LOsInvoiceHeader_ihfuturevc]  DEFAULT ('') FOR [ihfuturevc]
GO
/****** Object:  Default [DF_LOsInvoiceHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader] ADD  CONSTRAINT [DF_LOsInvoiceHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__LOsInvoic__rowgu__23D4EEA7]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader] ADD  CONSTRAINT [DF__LOsInvoic__rowgu__23D4EEA7]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LOsInvoic__Exclu__3DCA962B]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader] ADD  DEFAULT ((0)) FOR [ExcludeGST]
GO
/****** Object:  Default [DF__losservin__rowgu__12211E17]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losservinvoicetechniciandetails] ADD  CONSTRAINT [DF__losservin__rowgu__12211E17]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__HQSalesCo__schAf__6F16424E]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[hqSalesCommisionHeader] ADD  CONSTRAINT [DF__HQSalesCo__schAf__6F16424E]  DEFAULT (0) FOR [schAfterSales]
GO
/****** Object:  Default [DF__Ashopsale__rowgu__12549193]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Ashopsalespersondetails] ADD  CONSTRAINT [DF__Ashopsale__rowgu__12549193]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losSerStandByRequestHeader_reqhUpdateTime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerStandByRequestHeader] ADD  CONSTRAINT [DF_losSerStandByRequestHeader_reqhUpdateTime]  DEFAULT (getdate()) FOR [reqhUpdateTime]
GO
/****** Object:  Default [DF_ExchangeRateDetail_BuyingRate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ExchangeRateDetail] ADD  CONSTRAINT [DF_ExchangeRateDetail_BuyingRate]  DEFAULT (0) FOR [BuyingRate]
GO
/****** Object:  Default [DF_ExchangeRateDetail_SellingRate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ExchangeRateDetail] ADD  CONSTRAINT [DF_ExchangeRateDetail_SellingRate]  DEFAULT (0) FOR [SellingRate]
GO
/****** Object:  Default [DF_ExchangeRateDetail_AverageRate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ExchangeRateDetail] ADD  CONSTRAINT [DF_ExchangeRateDetail_AverageRate]  DEFAULT (0) FOR [AverageRate]
GO
/****** Object:  Default [DF__ExchangeR__rowgu__22EA20B8]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ExchangeRateDetail] ADD  CONSTRAINT [DF__ExchangeR__rowgu__22EA20B8]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__AAccRatio__Numer__71C891C7]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AAccRatioEntitiesMaster] ADD  CONSTRAINT [DF__AAccRatio__Numer__71C891C7]  DEFAULT (1) FOR [Numerator]
GO
/****** Object:  Default [DF__aCurrency__rowgu__63F8CA06]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCurrencyMaster] ADD  CONSTRAINT [DF__aCurrency__rowgu__63F8CA06]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aCity__rowguid__5E3FF0B0]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCity] ADD  CONSTRAINT [DF__aCity__rowguid__5E3FF0B0]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aVendorMaster_DuePeriod]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aVendorMaster] ADD  CONSTRAINT [DF_aVendorMaster_DuePeriod]  DEFAULT (0) FOR [DuePeriod]
GO
/****** Object:  Default [DF_aVendorMaster_OpeningCreditBalance]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aVendorMaster] ADD  CONSTRAINT [DF_aVendorMaster_OpeningCreditBalance]  DEFAULT (0) FOR [OpeningCreditBalance]
GO
/****** Object:  Default [DF_aVendorMaster_OpeningDebitBalance]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aVendorMaster] ADD  CONSTRAINT [DF_aVendorMaster_OpeningDebitBalance]  DEFAULT (0) FOR [OpeningDebitBalance]
GO
/****** Object:  Default [DF__aVendorMa__rowgu__3BEAD8AC]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aVendorMaster] ADD  CONSTRAINT [DF__aVendorMa__rowgu__3BEAD8AC]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__avendorma__allow__40B05920]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aVendorMaster] ADD  CONSTRAINT [DF__avendorma__allow__40B05920]  DEFAULT (0) FOR [allowblankcheque]
GO
/****** Object:  Default [DF_aGodown_LocationArrangement]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodown] ADD  CONSTRAINT [DF_aGodown_LocationArrangement]  DEFAULT (0) FOR [LocationArrangement]
GO
/****** Object:  Default [DF_aGodown_Fifo]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodown] ADD  CONSTRAINT [DF_aGodown_Fifo]  DEFAULT (1) FOR [Fifo]
GO
/****** Object:  Default [DF__agodown__selecte__24A84BF8]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodown] ADD  CONSTRAINT [DF__agodown__selecte__24A84BF8]  DEFAULT (0) FOR [selected]
GO
/****** Object:  Default [DF__aGodown__rowguid__31CED39A]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodown] ADD  CONSTRAINT [DF__aGodown__rowguid__31CED39A]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_Forex_posted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Forex] ADD  CONSTRAINT [DF_Forex_posted]  DEFAULT (0) FOR [posted]
GO
/****** Object:  Default [DF_Forex_cancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Forex] ADD  CONSTRAINT [DF_Forex_cancelled]  DEFAULT (0) FOR [cancelled]
GO
/****** Object:  Default [DF_Depreciation_Amount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DepreciationHeader] ADD  CONSTRAINT [DF_Depreciation_Amount]  DEFAULT (0) FOR [Amount]
GO
/****** Object:  Default [DF_Depreciation_Cancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DepreciationHeader] ADD  CONSTRAINT [DF_Depreciation_Cancelled]  DEFAULT (0) FOR [Cancelled]
GO
/****** Object:  Default [DF_Depreciation_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DepreciationHeader] ADD  CONSTRAINT [DF_Depreciation_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__Depreciat__rowgu__17786E0C]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DepreciationHeader] ADD  CONSTRAINT [DF__Depreciat__rowgu__17786E0C]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_AccountsInvoiceHeader_Discount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AccountsInvoiceHeader] ADD  CONSTRAINT [DF_AccountsInvoiceHeader_Discount]  DEFAULT (0) FOR [Discount]
GO
/****** Object:  Default [DF_AccountsInvoiceHeader_ExchangeRate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AccountsInvoiceHeader] ADD  CONSTRAINT [DF_AccountsInvoiceHeader_ExchangeRate]  DEFAULT (1) FOR [ExchangeRate]
GO
/****** Object:  Default [DF_AccountsInvoiceHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AccountsInvoiceHeader] ADD  CONSTRAINT [DF_AccountsInvoiceHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF_AccountsInvoiceHeader_Futurevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AccountsInvoiceHeader] ADD  CONSTRAINT [DF_AccountsInvoiceHeader_Futurevc]  DEFAULT ('') FOR [Futurevc]
GO
/****** Object:  Default [DF__AccountsI__Exclu__3EBEBA64]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AccountsInvoiceHeader] ADD  DEFAULT ((0)) FOR [ExcludeGST]
GO
/****** Object:  Default [DF_InterDivisionBillsHeader_exchangerate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[InterDivisionBillsHeader] ADD  CONSTRAINT [DF_InterDivisionBillsHeader_exchangerate]  DEFAULT ((1)) FOR [exchangerate]
GO
/****** Object:  Default [DF_InterDivisionBillsHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[InterDivisionBillsHeader] ADD  CONSTRAINT [DF_InterDivisionBillsHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF_losDebitCreditNote_DCNDebit]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDebitCreditNote] ADD  CONSTRAINT [DF_losDebitCreditNote_DCNDebit]  DEFAULT (0) FOR [losDCNDebit]
GO
/****** Object:  Default [DF_losDebitCreditNote_DCNCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDebitCreditNote] ADD  CONSTRAINT [DF_losDebitCreditNote_DCNCancelled]  DEFAULT (0) FOR [losDCNCancelled]
GO
/****** Object:  Default [DF_losDebitCreditNote_DCNPosted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDebitCreditNote] ADD  CONSTRAINT [DF_losDebitCreditNote_DCNPosted]  DEFAULT (0) FOR [losDCNPosted]
GO
/****** Object:  Default [DF_losDebitCreditNote_losexchangerate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDebitCreditNote] ADD  CONSTRAINT [DF_losDebitCreditNote_losexchangerate]  DEFAULT (1) FOR [losexchangerate]
GO
/****** Object:  Default [DF_losDebitCreditNote_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDebitCreditNote] ADD  CONSTRAINT [DF_losDebitCreditNote_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__losDebitC__rowgu__271B6FA6]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDebitCreditNote] ADD  CONSTRAINT [DF__losDebitC__rowgu__271B6FA6]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losDebitC__losDC__1546D82E]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDebitCreditNote] ADD  CONSTRAINT [DF__losDebitC__losDC__1546D82E]  DEFAULT (0) FOR [losDCNDuePeriod]
GO
/****** Object:  Default [DF_DebitCreditNote_DCNDebit]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DebitCreditNote] ADD  CONSTRAINT [DF_DebitCreditNote_DCNDebit]  DEFAULT (0) FOR [DCNDebit]
GO
/****** Object:  Default [DF_DebitCreditNote_DCNExchangerate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DebitCreditNote] ADD  CONSTRAINT [DF_DebitCreditNote_DCNExchangerate]  DEFAULT (1) FOR [DCNExchangerate]
GO
/****** Object:  Default [DF_DebitCreditNote_DCNCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DebitCreditNote] ADD  CONSTRAINT [DF_DebitCreditNote_DCNCancelled]  DEFAULT (0) FOR [DCNCancelled]
GO
/****** Object:  Default [DF_DebitCreditNote_DCNPosted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DebitCreditNote] ADD  CONSTRAINT [DF_DebitCreditNote_DCNPosted]  DEFAULT (0) FOR [DCNPosted]
GO
/****** Object:  Default [DF_DebitCreditNote_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DebitCreditNote] ADD  CONSTRAINT [DF_DebitCreditNote_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__DebitCred__DCNCo__5992AC31]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DebitCreditNote] ADD  DEFAULT ((1)) FOR [DCNConfirmed]
GO
/****** Object:  Default [DF_ReceiptVoucherHeader_Amount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherHeader] ADD  CONSTRAINT [DF_ReceiptVoucherHeader_Amount]  DEFAULT (0) FOR [Amount]
GO
/****** Object:  Default [DF_ReceiptVoucherHeader_exchangerate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherHeader] ADD  CONSTRAINT [DF_ReceiptVoucherHeader_exchangerate]  DEFAULT (1) FOR [exchangerate]
GO
/****** Object:  Default [DF_ReceiptVoucherHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherHeader] ADD  CONSTRAINT [DF_ReceiptVoucherHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__receiptvo__recei__47284C85]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherHeader] ADD  CONSTRAINT [DF__receiptvo__recei__47284C85]  DEFAULT (null) FOR [receiptcustomerid]
GO
/****** Object:  Default [DF__ReceiptVo__Confi__7E2F3403]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherHeader] ADD  DEFAULT ((0)) FOR [Confirmed]
GO
/****** Object:  Default [DF_loPurchasereturnheader_prhcancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPurchasereturnheader] ADD  CONSTRAINT [DF_loPurchasereturnheader_prhcancelled]  DEFAULT (0) FOR [prhcancelled]
GO
/****** Object:  Default [DF_loPurchasereturnheader_prhposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPurchasereturnheader] ADD  CONSTRAINT [DF_loPurchasereturnheader_prhposted]  DEFAULT (0) FOR [prhposted]
GO
/****** Object:  Default [DF_MOaJournalHeader_Cancel]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOaJournalHeader] ADD  CONSTRAINT [DF_MOaJournalHeader_Cancel]  DEFAULT (0) FOR [Cancel]
GO
/****** Object:  Default [DF_MOaJournalHeader_Realised]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOaJournalHeader] ADD  CONSTRAINT [DF_MOaJournalHeader_Realised]  DEFAULT (0) FOR [Realised]
GO
/****** Object:  Default [DF_LOspPurchaseBillHeader_pbhAdjustmentAmount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillHeader] ADD  CONSTRAINT [DF_LOspPurchaseBillHeader_pbhAdjustmentAmount]  DEFAULT (0) FOR [pbhAdjustmentAmount]
GO
/****** Object:  Default [DF_LOspPurchaseBillHeader_pbhDespatched]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillHeader] ADD  CONSTRAINT [DF_LOspPurchaseBillHeader_pbhDespatched]  DEFAULT (0) FOR [pbhDespatched]
GO
/****** Object:  Default [DF_LOspPurchaseBillHeader_pbhUsed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillHeader] ADD  CONSTRAINT [DF_LOspPurchaseBillHeader_pbhUsed]  DEFAULT (0) FOR [pbhUsed]
GO
/****** Object:  Default [DF_LOspPurchaseBillHeader_pbhSettled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillHeader] ADD  CONSTRAINT [DF_LOspPurchaseBillHeader_pbhSettled]  DEFAULT (0) FOR [pbhSettled]
GO
/****** Object:  Default [DF_LOspPurchaseBillHeader_pbhexchangerate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillHeader] ADD  CONSTRAINT [DF_LOspPurchaseBillHeader_pbhexchangerate]  DEFAULT (1) FOR [pbhexchangerate]
GO
/****** Object:  Default [DF_LOspPurchaseBillHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillHeader] ADD  CONSTRAINT [DF_LOspPurchaseBillHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF_Bills_exchangerate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Bills] ADD  CONSTRAINT [DF_Bills_exchangerate]  DEFAULT (1) FOR [exchangerate]
GO
/****** Object:  Default [DF_Bills_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Bills] ADD  CONSTRAINT [DF_Bills_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__Bills__AutoGener__5A90F20B]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Bills] ADD  DEFAULT ((0)) FOR [AutoGenerate]
GO
/****** Object:  Default [DF_LosPosFAndBHeader_poshCompanyID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader] ADD  CONSTRAINT [DF_LosPosFAndBHeader_poshCompanyID]  DEFAULT ((1)) FOR [poshCompanyID]
GO
/****** Object:  Default [DF_LosPosFAndBHeader_poshReturned]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader] ADD  CONSTRAINT [DF_LosPosFAndBHeader_poshReturned]  DEFAULT ((0)) FOR [poshReturned]
GO
/****** Object:  Default [DF_LosPosFAndBHeader_poshWholesale]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader] ADD  CONSTRAINT [DF_LosPosFAndBHeader_poshWholesale]  DEFAULT ((0)) FOR [poshWholesale]
GO
/****** Object:  Default [DF_LosPosFAndBHeader_poshfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader] ADD  CONSTRAINT [DF_LosPosFAndBHeader_poshfuturevc]  DEFAULT ('') FOR [poshfuturevc]
GO
/****** Object:  Default [DF_LosPosFAndBHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader] ADD  CONSTRAINT [DF_LosPosFAndBHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF_LosPosFAndBHeader_receipted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader] ADD  CONSTRAINT [DF_LosPosFAndBHeader_receipted]  DEFAULT ((0)) FOR [receipted]
GO
/****** Object:  Default [DF_LosPosFAndBHeader_salesbillbit]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader] ADD  CONSTRAINT [DF_LosPosFAndBHeader_salesbillbit]  DEFAULT ((0)) FOR [salesbillbit]
GO
/****** Object:  Default [DF_LosPosFAndBHeader_poshcash]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader] ADD  CONSTRAINT [DF_LosPosFAndBHeader_poshcash]  DEFAULT ((0)) FOR [poshcash]
GO
/****** Object:  Default [DF_LosPosFAndBHeader_poshservicec0harge]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader] ADD  CONSTRAINT [DF_LosPosFAndBHeader_poshservicec0harge]  DEFAULT ((0)) FOR [poshservicecharge]
GO
/****** Object:  Default [DF_LosPosFAndBHeader_poshAccAuditid]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader] ADD  CONSTRAINT [DF_LosPosFAndBHeader_poshAccAuditid]  DEFAULT ((0)) FOR [poshAccAuditid]
GO
/****** Object:  Default [DF__losposhea__PoshB__5B1BCD47]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader] ADD  CONSTRAINT [DF__losposhea__PoshB__5B1BCD47]  DEFAULT ((0)) FOR [PoshBillCount]
GO
/****** Object:  Default [DF_aHQPaymentVoucherHeader_phExchangeRate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherHeader] ADD  CONSTRAINT [DF_aHQPaymentVoucherHeader_phExchangeRate]  DEFAULT (1) FOR [phExchangeRate]
GO
/****** Object:  Default [DF_aHQPaymentVoucherHeader_phlcpayment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherHeader] ADD  CONSTRAINT [DF_aHQPaymentVoucherHeader_phlcpayment]  DEFAULT ('OP') FOR [phlcpayment]
GO
/****** Object:  Default [DF_aHQPaymentVoucherHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherHeader] ADD  CONSTRAINT [DF_aHQPaymentVoucherHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF_aHQPaymentVoucherHeader_refreceiptid]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherHeader] ADD  CONSTRAINT [DF_aHQPaymentVoucherHeader_refreceiptid]  DEFAULT (null) FOR [refreceiptid]
GO
/****** Object:  Default [DF__aHQPaymen__phcon__1F3B2213]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherHeader] ADD  DEFAULT ((0)) FOR [phconfirmed]
GO
/****** Object:  Default [DF_JournalTransHeader_Cancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[JournalTransHeader] ADD  CONSTRAINT [DF_JournalTransHeader_Cancelled]  DEFAULT (0) FOR [Cancelled]
GO
/****** Object:  Default [DF_JournalTransHeader_Posted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[JournalTransHeader] ADD  CONSTRAINT [DF_JournalTransHeader_Posted]  DEFAULT (0) FOR [Posted]
GO
/****** Object:  Default [DF_JournalTransHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[JournalTransHeader] ADD  CONSTRAINT [DF_JournalTransHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__JournalTr__Confi__7F23583C]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[JournalTransHeader] ADD  DEFAULT ((1)) FOR [Confirmed]
GO
/****** Object:  Default [DF_Contra_ContraAmount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Contra] ADD  CONSTRAINT [DF_Contra_ContraAmount]  DEFAULT (0) FOR [ContraAmount]
GO
/****** Object:  Default [DF_Contra_ContraChargeAmount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Contra] ADD  CONSTRAINT [DF_Contra_ContraChargeAmount]  DEFAULT (0) FOR [ContraChargeAmount]
GO
/****** Object:  Default [DF_Contra_ExchangeRate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Contra] ADD  CONSTRAINT [DF_Contra_ExchangeRate]  DEFAULT (1) FOR [ExchangeRate]
GO
/****** Object:  Default [DF_Contra_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Contra] ADD  CONSTRAINT [DF_Contra_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF_AdjustmentHeader_ExchangeGain]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AdjustmentHeader] ADD  CONSTRAINT [DF_AdjustmentHeader_ExchangeGain]  DEFAULT ('') FOR [ExchangeGain]
GO
/****** Object:  Default [DF_AdjustmentHeader_Cancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AdjustmentHeader] ADD  CONSTRAINT [DF_AdjustmentHeader_Cancelled]  DEFAULT (0) FOR [Cancelled]
GO
/****** Object:  Default [DF_AdjustmentHeader_Posted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AdjustmentHeader] ADD  CONSTRAINT [DF_AdjustmentHeader_Posted]  DEFAULT (0) FOR [Posted]
GO
/****** Object:  Default [DF__HQSalesPr__spdTo__7B7C1933]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[HQSalesPromotionDetail] ADD  CONSTRAINT [DF__HQSalesPr__spdTo__7B7C1933]  DEFAULT (1) FOR [spdToBePaid]
GO
/****** Object:  Default [DF_aSettings_Averagerate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSettings] ADD  CONSTRAINT [DF_aSettings_Averagerate]  DEFAULT (0) FOR [AverageRate]
GO
/****** Object:  Default [DF_aSettings_EnableTargetCheck]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSettings] ADD  CONSTRAINT [DF_aSettings_EnableTargetCheck]  DEFAULT (0) FOR [EnableTargetCheck]
GO
/****** Object:  Default [DF_aSettings_EnableBudgetCheck]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSettings] ADD  CONSTRAINT [DF_aSettings_EnableBudgetCheck]  DEFAULT (0) FOR [EnableBudgetCheck]
GO
/****** Object:  Default [DF_aSettings_openingfreezed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSettings] ADD  CONSTRAINT [DF_aSettings_openingfreezed]  DEFAULT (0) FOR [openingfreezed]
GO
/****** Object:  Default [DF__aSettings__rowgu__7CF981FA]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSettings] ADD  CONSTRAINT [DF__aSettings__rowgu__7CF981FA]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__asettings__autog__3FF13F11]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSettings] ADD  CONSTRAINT [DF__asettings__autog__3FF13F11]  DEFAULT (0) FOR [autogenerateasstcode]
GO
/****** Object:  Default [DF_aAccountMaster_BudgetAmount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aAccountMaster] ADD  CONSTRAINT [DF_aAccountMaster_BudgetAmount]  DEFAULT (0) FOR [BudgetAmount]
GO
/****** Object:  Default [DF_aAccountMaster_Misc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aAccountMaster] ADD  CONSTRAINT [DF_aAccountMaster_Misc]  DEFAULT ('') FOR [Misc]
GO
/****** Object:  Default [DF__aAccountM__rowgu__7B5CE8F9]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aAccountMaster] ADD  CONSTRAINT [DF__aAccountM__rowgu__7B5CE8F9]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LOsGoodsArrivaltoShopHeader_gahCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopHeader] ADD  CONSTRAINT [DF_LOsGoodsArrivaltoShopHeader_gahCancelled]  DEFAULT (0) FOR [gahCancelled]
GO
/****** Object:  Default [DF_LOsGoodsArrivaltoShopHeader_gahTransFinished]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopHeader] ADD  CONSTRAINT [DF_LOsGoodsArrivaltoShopHeader_gahTransFinished]  DEFAULT (0) FOR [gahTransFinished]
GO
/****** Object:  Default [DF_LOsGoodsArrivaltoShopHeader_gahfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopHeader] ADD  CONSTRAINT [DF_LOsGoodsArrivaltoShopHeader_gahfuturevc]  DEFAULT ('') FOR [gahfuturevc]
GO
/****** Object:  Default [DF_LOsGoodsArrivaltoShopHeader_gahposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopHeader] ADD  CONSTRAINT [DF_LOsGoodsArrivaltoShopHeader_gahposted]  DEFAULT (0) FOR [gahposted]
GO
/****** Object:  Default [DF_LOsGoodsArrivaltoShopHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopHeader] ADD  CONSTRAINT [DF_LOsGoodsArrivaltoShopHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__LOsGoodsA__rowgu__37BB206C]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopHeader] ADD  CONSTRAINT [DF__LOsGoodsA__rowgu__37BB206C]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losApartm__chUpd__2A76FF3E]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentCheckOut] ADD  CONSTRAINT [DF__losApartm__chUpd__2A76FF3E]  DEFAULT (getdate()) FOR [chUpdateTime]
GO
/****** Object:  Default [DF__losApartm__abhUp__157BE258]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentBillHeader] ADD  CONSTRAINT [DF__losApartm__abhUp__157BE258]  DEFAULT (getdate()) FOR [abhUpdateTime]
GO
/****** Object:  Default [DF_losApartmentBillHeader_abhSettled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentBillHeader] ADD  CONSTRAINT [DF_losApartmentBillHeader_abhSettled]  DEFAULT (0) FOR [abhSettled]
GO
/****** Object:  Default [DF_LosDeliveryNoteHeader_Dncancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosDeliveryNoteHeader] ADD  CONSTRAINT [DF_LosDeliveryNoteHeader_Dncancelled]  DEFAULT (0) FOR [Dncancelled]
GO
/****** Object:  Default [DF__losLPDeta__statu__0BD27C8D]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losLPDetail] ADD  CONSTRAINT [DF__losLPDeta__statu__0BD27C8D]  DEFAULT ('D') FOR [status]
GO
/****** Object:  Default [DF__losinvser__rowgu__5733CBC5]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losinvservicedetails] ADD  CONSTRAINT [DF__losinvser__rowgu__5733CBC5]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_MeiGodownRequestDetail_rowguid]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MeiGodownRequestDetail] ADD  CONSTRAINT [DF_MeiGodownRequestDetail_rowguid]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__ExchangeR__rowgu__52069902]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ExchangeRateHistoryDetails] ADD  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losfuture__rowgu__401B5C43]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losfuturetabdetail] ADD  CONSTRAINT [DF__losfuture__rowgu__401B5C43]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losApartmentAgreementHeader_mghUpdateTime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentAgreementHeader] ADD  CONSTRAINT [DF_losApartmentAgreementHeader_mghUpdateTime]  DEFAULT (getdate()) FOR [mghUpdateTime]
GO
/****** Object:  Default [DF__losApartm__mghPo__27CF9CBD]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentAgreementHeader] ADD  CONSTRAINT [DF__losApartm__mghPo__27CF9CBD]  DEFAULT (0) FOR [mghPosted]
GO
/****** Object:  Default [DF_loreplacereqtovendorheader_rrvcancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loreplacereqtovendorheader] ADD  CONSTRAINT [DF_loreplacereqtovendorheader_rrvcancelled]  DEFAULT (0) FOR [rrvcancelled]
GO
/****** Object:  Default [DF_LOsWriteOffHeader_Whfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsWriteOffHeader] ADD  CONSTRAINT [DF_LOsWriteOffHeader_Whfuturevc]  DEFAULT ('') FOR [Whfuturevc]
GO
/****** Object:  Default [DF_LOsWriteOffHeader_whposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsWriteOffHeader] ADD  CONSTRAINT [DF_LOsWriteOffHeader_whposted]  DEFAULT (0) FOR [whposted]
GO
/****** Object:  Default [DF_LOsWriteOffHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsWriteOffHeader] ADD  CONSTRAINT [DF_LOsWriteOffHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__LOsWriteO__rowgu__679450C0]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsWriteOffHeader] ADD  CONSTRAINT [DF__LOsWriteO__rowgu__679450C0]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LOsWriteO__whVer__354A5EC3]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsWriteOffHeader] ADD  DEFAULT ((1)) FOR [whVerified]
GO
/****** Object:  Default [DF__aHQpaymen__pddVe__2C0A41F5]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherDebitDetails] ADD  CONSTRAINT [DF__aHQpaymen__pddVe__2C0A41F5]  DEFAULT (0) FOR [pddVendorExchangeDifference]
GO
/****** Object:  Default [DF__AAccRatio__CalcT__77816B1D]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AAccRatioEntitiesAccounts] ADD  CONSTRAINT [DF__AAccRatio__CalcT__77816B1D]  DEFAULT (1) FOR [CalcType]
GO
/****** Object:  Default [DF_mesTransferOutHeader_TOHCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferOutHeader] ADD  CONSTRAINT [DF_mesTransferOutHeader_TOHCancelled]  DEFAULT (0) FOR [TOHCancelled]
GO
/****** Object:  Default [DF_mesTransferOutHeader_TOhUsed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferOutHeader] ADD  CONSTRAINT [DF_mesTransferOutHeader_TOhUsed]  DEFAULT (0) FOR [TOhUsed]
GO
/****** Object:  Default [DF_mesTransferOutHeader_TOHTransfinished]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferOutHeader] ADD  CONSTRAINT [DF_mesTransferOutHeader_TOHTransfinished]  DEFAULT (0) FOR [TOHTransfinished]
GO
/****** Object:  Default [DF_mesTransferOutHeader_TOHNoofDetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferOutHeader] ADD  CONSTRAINT [DF_mesTransferOutHeader_TOHNoofDetails]  DEFAULT (0) FOR [TOHNoofDetails]
GO
/****** Object:  Default [DF_mesTransferOutHeader_TOHfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferOutHeader] ADD  CONSTRAINT [DF_mesTransferOutHeader_TOHfuturevc]  DEFAULT ('') FOR [TOHfuturevc]
GO
/****** Object:  Default [DF_mesTransferOutHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferOutHeader] ADD  CONSTRAINT [DF_mesTransferOutHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__mestransf__tohpo__3AD91AE7]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferOutHeader] ADD  CONSTRAINT [DF__mestransf__tohpo__3AD91AE7]  DEFAULT (0) FOR [tohposted]
GO
/****** Object:  Default [DF__mesTransf__rowgu__5145E845]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferOutHeader] ADD  CONSTRAINT [DF__mesTransf__rowgu__5145E845]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_VoucherMaster_rowguid]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VoucherMaster] ADD  CONSTRAINT [DF_VoucherMaster_rowguid]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aDepartmentMaster_BudgetedAmount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aDepartmentMaster] ADD  CONSTRAINT [DF_aDepartmentMaster_BudgetedAmount]  DEFAULT (0) FOR [BudgetedAmount]
GO
/****** Object:  Default [DF_aDepartmentMaster_Selected]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aDepartmentMaster] ADD  CONSTRAINT [DF_aDepartmentMaster_Selected]  DEFAULT (0) FOR [Selected]
GO
/****** Object:  Default [DF__aDepartme__rowgu__271AA44F]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aDepartmentMaster] ADD  CONSTRAINT [DF__aDepartme__rowgu__271AA44F]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aHQIssueNoteMain_INMCancel]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssueNoteMain] ADD  CONSTRAINT [DF_aHQIssueNoteMain_INMCancel]  DEFAULT (0) FOR [INMCancel]
GO
/****** Object:  Default [DF_aHQIssueNoteMain_futurevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssueNoteMain] ADD  CONSTRAINT [DF_aHQIssueNoteMain_futurevc]  DEFAULT ('') FOR [futurevc]
GO
/****** Object:  Default [DF_aHQIssueNoteMain_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssueNoteMain] ADD  CONSTRAINT [DF_aHQIssueNoteMain_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__aHQIssueN__rowgu__69B1A35C]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssueNoteMain] ADD  CONSTRAINT [DF__aHQIssueN__rowgu__69B1A35C]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aHQIssuenoteHeader_INHCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteHeader] ADD  CONSTRAINT [DF_aHQIssuenoteHeader_INHCancelled]  DEFAULT (0) FOR [INHCancelled]
GO
/****** Object:  Default [DF_aHQIssuenoteHeader_INHUsed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteHeader] ADD  CONSTRAINT [DF_aHQIssuenoteHeader_INHUsed]  DEFAULT (0) FOR [INHUsed]
GO
/****** Object:  Default [DF_aHQIssuenoteHeader_INHTransFinished]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteHeader] ADD  CONSTRAINT [DF_aHQIssuenoteHeader_INHTransFinished]  DEFAULT (0) FOR [INHTransFinished]
GO
/****** Object:  Default [DF_aHQIssuenoteHeader_INHNoofDetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteHeader] ADD  CONSTRAINT [DF_aHQIssuenoteHeader_INHNoofDetails]  DEFAULT (0) FOR [INHNoofDetails]
GO
/****** Object:  Default [DF_aHQIssuenoteHeader_futurevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteHeader] ADD  CONSTRAINT [DF_aHQIssuenoteHeader_futurevc]  DEFAULT ('') FOR [futurevc]
GO
/****** Object:  Default [DF_aHQIssuenoteHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteHeader] ADD  CONSTRAINT [DF_aHQIssuenoteHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__aHQIssuen__rowgu__216BEC9A]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteHeader] ADD  CONSTRAINT [DF__aHQIssuen__rowgu__216BEC9A]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__assetdisp__dispd__4A6ECD84]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[assetdisposaldetail] ADD  CONSTRAINT [DF__assetdisp__dispd__4A6ECD84]  DEFAULT (0) FOR [dispdcredit]
GO
/****** Object:  Default [DF_MOaJournalDetails_Amount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOaJournalDetails] ADD  CONSTRAINT [DF_MOaJournalDetails_Amount]  DEFAULT (0) FOR [Amount]
GO
/****** Object:  Default [DF_MOaJournalDetails_ActualAmount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOaJournalDetails] ADD  CONSTRAINT [DF_MOaJournalDetails_ActualAmount]  DEFAULT (0) FOR [ActualAmount]
GO
/****** Object:  Default [DF_MOaJournalDetails_depamount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOaJournalDetails] ADD  CONSTRAINT [DF_MOaJournalDetails_depamount]  DEFAULT (0) FOR [depamount]
GO
/****** Object:  Default [DF_ashopcashaccountdetails_futurevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ashopcashaccountdetails] ADD  CONSTRAINT [DF_ashopcashaccountdetails_futurevc]  DEFAULT ('') FOR [futurevc]
GO
/****** Object:  Default [DF__ashopcash__rowgu__7E97B1A9]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ashopcashaccountdetails] ADD  CONSTRAINT [DF__ashopcash__rowgu__7E97B1A9]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_loalocalpurchaseCostingheader_lpchCostingDone]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loalocalpurchaseCostingheader] ADD  CONSTRAINT [DF_loalocalpurchaseCostingheader_lpchCostingDone]  DEFAULT (0) FOR [lpchCostingDone]
GO
/****** Object:  Default [DF_loalocalpurchaseCostingheader_lpchposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loalocalpurchaseCostingheader] ADD  CONSTRAINT [DF_loalocalpurchaseCostingheader_lpchposted]  DEFAULT (0) FOR [lpchposted]
GO
/****** Object:  Default [DF_loalocalpurchaseCostingheader_lpchCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loalocalpurchaseCostingheader] ADD  CONSTRAINT [DF_loalocalpurchaseCostingheader_lpchCancelled]  DEFAULT (0) FOR [lpchCancelled]
GO
/****** Object:  Default [DF_loalocalpurchaseCostingheader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loalocalpurchaseCostingheader] ADD  CONSTRAINT [DF_loalocalpurchaseCostingheader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF_LOsReceiptVoucherHeader_rhPosted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsReceiptVoucherHeader] ADD  CONSTRAINT [DF_LOsReceiptVoucherHeader_rhPosted]  DEFAULT (0) FOR [rhPosted]
GO
/****** Object:  Default [DF_LOsReceiptVoucherHeader_rhCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsReceiptVoucherHeader] ADD  CONSTRAINT [DF_LOsReceiptVoucherHeader_rhCancelled]  DEFAULT (0) FOR [rhCancelled]
GO
/****** Object:  Default [DF_LOsReceiptVoucherHeader_rhCompanyID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsReceiptVoucherHeader] ADD  CONSTRAINT [DF_LOsReceiptVoucherHeader_rhCompanyID]  DEFAULT (1) FOR [rhCompanyID]
GO
/****** Object:  Default [DF_LOsReceiptVoucherHeader_rhExchangeRate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsReceiptVoucherHeader] ADD  CONSTRAINT [DF_LOsReceiptVoucherHeader_rhExchangeRate]  DEFAULT (1) FOR [rhExchangeRate]
GO
/****** Object:  Default [DF_LOsReceiptVoucherHeader_rhfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsReceiptVoucherHeader] ADD  CONSTRAINT [DF_LOsReceiptVoucherHeader_rhfuturevc]  DEFAULT ('') FOR [rhfuturevc]
GO
/****** Object:  Default [DF_LOsReceiptVoucherHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsReceiptVoucherHeader] ADD  CONSTRAINT [DF_LOsReceiptVoucherHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__LOsReceip__rowgu__08EBEE41]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsReceiptVoucherHeader] ADD  CONSTRAINT [DF__LOsReceip__rowgu__08EBEE41]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LOsPosOth__rowgu__605D434C]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosOthercharges] ADD  CONSTRAINT [DF__LOsPosOth__rowgu__605D434C]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LOsLocalP__rowgu__5708E33C]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsLocalPurchaseOC] ADD  CONSTRAINT [DF__LOsLocalP__rowgu__5708E33C]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_JournalTransDetails_Amount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[JournalTransDetails] ADD  CONSTRAINT [DF_JournalTransDetails_Amount]  DEFAULT (0) FOR [Amount]
GO
/****** Object:  Default [DF__JournalTr__Payro__2ED1A007]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[JournalTransDetails] ADD  CONSTRAINT [DF__JournalTr__Payro__2ED1A007]  DEFAULT (null) FOR [PayrollLinktransId]
GO
/****** Object:  Default [DF_LOaCostingHeader_chCostingDone]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOaCostingHeader] ADD  CONSTRAINT [DF_LOaCostingHeader_chCostingDone]  DEFAULT (0) FOR [chCostingDone]
GO
/****** Object:  Default [DF_LOaCostingHeader_chPosted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOaCostingHeader] ADD  CONSTRAINT [DF_LOaCostingHeader_chPosted]  DEFAULT (0) FOR [chPosted]
GO
/****** Object:  Default [DF_LOaCostingHeader_chCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOaCostingHeader] ADD  CONSTRAINT [DF_LOaCostingHeader_chCancelled]  DEFAULT (0) FOR [chCancelled]
GO
/****** Object:  Default [DF_LOaCostingHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOaCostingHeader] ADD  CONSTRAINT [DF_LOaCostingHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__BudgetAll__badMo__6621D4F1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[BudgetAllocationDetail] ADD  CONSTRAINT [DF__BudgetAll__badMo__6621D4F1]  DEFAULT (0) FOR [badMonthNo]
GO
/****** Object:  Default [DF__BudgetAll__badRe__6715F92A]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[BudgetAllocationDetail] ADD  CONSTRAINT [DF__BudgetAll__badRe__6715F92A]  DEFAULT (0) FOR [badRevised]
GO
/****** Object:  Default [DF__assettran__asttr__3E08F69F]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[assettransfer] ADD  CONSTRAINT [DF__assettran__asttr__3E08F69F]  DEFAULT (0) FOR [asttransposted]
GO
/****** Object:  Default [DF__assettran__asttr__3EFD1AD8]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[assettransfer] ADD  CONSTRAINT [DF__assettran__asttr__3EFD1AD8]  DEFAULT (0) FOR [asttranscancelled]
GO
/****** Object:  Default [DF__assettran__Updat__5BD950A8]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[assettransfer] ADD  CONSTRAINT [DF__assettran__Updat__5BD950A8]  DEFAULT (getdate()) FOR [Updatetime]
GO
/****** Object:  Default [DF_loPrePurchaseOrderHeader_pohcancel]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] ADD  CONSTRAINT [DF_loPrePurchaseOrderHeader_pohcancel]  DEFAULT (0) FOR [pohcancel]
GO
/****** Object:  Default [DF_loPrePurchaseOrderHeader_pohPosted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] ADD  CONSTRAINT [DF_loPrePurchaseOrderHeader_pohPosted]  DEFAULT (0) FOR [pohPosted]
GO
/****** Object:  Default [DF_loPrePurchaseOrderHeader_pohbillgenerated]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] ADD  CONSTRAINT [DF_loPrePurchaseOrderHeader_pohbillgenerated]  DEFAULT (0) FOR [pohbillgenerated]
GO
/****** Object:  Default [DF_loPrePurchaseOrderHeader_pogenerated]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] ADD  CONSTRAINT [DF_loPrePurchaseOrderHeader_pogenerated]  DEFAULT (0) FOR [pogenerated]
GO
/****** Object:  Default [DF_loPrePurchaseOrderHeader_pohpogenerated]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] ADD  CONSTRAINT [DF_loPrePurchaseOrderHeader_pohpogenerated]  DEFAULT (0) FOR [pohpogenerated]
GO
/****** Object:  Default [DF_loPrePurchaseOrderHeader_pohUsedinPayments]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] ADD  CONSTRAINT [DF_loPrePurchaseOrderHeader_pohUsedinPayments]  DEFAULT (0) FOR [pohUsedinPayments]
GO
/****** Object:  Default [DF_loPrePurchaseOrderHeader_pohLCopened]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] ADD  CONSTRAINT [DF_loPrePurchaseOrderHeader_pohLCopened]  DEFAULT (0) FOR [pohLCopened]
GO
/****** Object:  Default [DF_loPrePurchaseOrderHeader_pohLcMarginOpened]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] ADD  CONSTRAINT [DF_loPrePurchaseOrderHeader_pohLcMarginOpened]  DEFAULT (0) FOR [pohLcMarginOpened]
GO
/****** Object:  Default [DF__loPrepurchas__pohCo__0B22DD87]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] ADD  CONSTRAINT [DF__loPrepurchas__pohCo__0B22DD87]  DEFAULT ('P') FOR [pohCostingDone]
GO
/****** Object:  Default [DF_loPrePurchaseOrderHeader_pohDeladdress]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] ADD  CONSTRAINT [DF_loPrePurchaseOrderHeader_pohDeladdress]  DEFAULT ('') FOR [pohDeliveryTerms]
GO
/****** Object:  Default [DF_loPrePurchaseOrderHeader_pohquotconfirmed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] ADD  CONSTRAINT [DF_loPrePurchaseOrderHeader_pohquotconfirmed]  DEFAULT (0) FOR [pohppconfirmed]
GO
/****** Object:  Default [DF_loPrePurchaseOrderHeader_pohpoonhold]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] ADD  CONSTRAINT [DF_loPrePurchaseOrderHeader_pohpoonhold]  DEFAULT (0) FOR [pohpoonhold]
GO
/****** Object:  Default [DF_loPrePurchaseOrderHeader_pohfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] ADD  CONSTRAINT [DF_loPrePurchaseOrderHeader_pohfuturevc]  DEFAULT ('') FOR [pohfuturevc]
GO
/****** Object:  Default [DF_loPrePurchaseOrderHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] ADD  CONSTRAINT [DF_loPrePurchaseOrderHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__loPrePurchas__pohCu__17CE3F1E]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] ADD  CONSTRAINT [DF__loPrePurchas__pohCu__17CE3F1E]  DEFAULT (0) FOR [pohCustomDutyByCustomer]
GO
/****** Object:  Default [DF_ReceiptVoucherCreditDetails_Amount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherCreditDetails] ADD  CONSTRAINT [DF_ReceiptVoucherCreditDetails_Amount]  DEFAULT (0) FOR [Amount]
GO
/****** Object:  Default [DF_losInquiryHeader_ihupdatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losInquiryHeader] ADD  CONSTRAINT [DF_losInquiryHeader_ihupdatetime]  DEFAULT (getdate()) FOR [ihupdatetime]
GO
/****** Object:  Default [DF_losInquiryHeader_ihcancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losInquiryHeader] ADD  CONSTRAINT [DF_losInquiryHeader_ihcancelled]  DEFAULT (0) FOR [ihcancelled]
GO
/****** Object:  Default [DF__losSerMai__mchgu__1CE7F9F6]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerMaintenanceContractHeader] ADD  CONSTRAINT [DF__losSerMai__mchgu__1CE7F9F6]  DEFAULT (0) FOR [mchguarantee]
GO
/****** Object:  Default [DF_LosShipmentbhheader_bnhcancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosShipmentbnheader] ADD  CONSTRAINT [DF_LosShipmentbhheader_bnhcancelled]  DEFAULT (0) FOR [bnhcancelled]
GO
/****** Object:  Default [DF_LOsPosHeader_poshCompanyID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosHeader] ADD  CONSTRAINT [DF_LOsPosHeader_poshCompanyID]  DEFAULT (1) FOR [poshCompanyID]
GO
/****** Object:  Default [DF_LOsPosHeader_poshReturned]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosHeader] ADD  CONSTRAINT [DF_LOsPosHeader_poshReturned]  DEFAULT (0) FOR [poshReturned]
GO
/****** Object:  Default [DF_LOsPosHeader_poshWholesale]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosHeader] ADD  CONSTRAINT [DF_LOsPosHeader_poshWholesale]  DEFAULT (0) FOR [poshWholesale]
GO
/****** Object:  Default [DF_LOsPosHeader_poshExchangeRate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosHeader] ADD  CONSTRAINT [DF_LOsPosHeader_poshExchangeRate]  DEFAULT (1) FOR [poshExchangeRate]
GO
/****** Object:  Default [DF_LOsPosHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosHeader] ADD  CONSTRAINT [DF_LOsPosHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__LOsPosHea__rowgu__2937F6EB]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosHeader] ADD  CONSTRAINT [DF__LOsPosHea__rowgu__2937F6EB]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LOsPosHea__poshC__705615F8]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosHeader] ADD  DEFAULT ('') FOR [poshCustomerTIN]
GO
/****** Object:  Default [DF__losLocalC__Casho__1C3DEE80]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losLocalClearenceRequestHeader] ADD  CONSTRAINT [DF__losLocalC__Casho__1C3DEE80]  DEFAULT (0) FOR [CashorCredit]
GO
/****** Object:  Default [DF__losLocalC__CashP__1D3212B9]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losLocalClearenceRequestHeader] ADD  CONSTRAINT [DF__losLocalC__CashP__1D3212B9]  DEFAULT (0) FOR [CashPaidByShop]
GO
/****** Object:  Default [DF_LosKegReturnHeader_krhCancel]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosKegReturnHeader] ADD  CONSTRAINT [DF_LosKegReturnHeader_krhCancel]  DEFAULT (0) FOR [krhCancel]
GO
/****** Object:  Default [DF_LosKegReturnHeader_krCompanyID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosKegReturnHeader] ADD  CONSTRAINT [DF_LosKegReturnHeader_krCompanyID]  DEFAULT (1) FOR [krCompanyID]
GO
/****** Object:  Default [DF_LosKegReturnHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosKegReturnHeader] ADD  CONSTRAINT [DF_LosKegReturnHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__losExport__rehTe__1BBECB93]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losExportHeader] ADD  CONSTRAINT [DF__losExport__rehTe__1BBECB93]  DEFAULT (0) FOR [rehTerminate]
GO
/****** Object:  Default [DF_aShopCustomerDetails_creditlimit]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopCustomerDetails] ADD  CONSTRAINT [DF_aShopCustomerDetails_creditlimit]  DEFAULT (0) FOR [creditlimit]
GO
/****** Object:  Default [DF_aShopCustomerDetails_futurevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopCustomerDetails] ADD  CONSTRAINT [DF_aShopCustomerDetails_futurevc]  DEFAULT ('') FOR [futurevc]
GO
/****** Object:  Default [DF__aShopCust__rowgu__76A18A26]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopCustomerDetails] ADD  CONSTRAINT [DF__aShopCust__rowgu__76A18A26]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losreplacerequestheader_repreqhcancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacerequestheader] ADD  CONSTRAINT [DF_losreplacerequestheader_repreqhcancelled]  DEFAULT (0) FOR [repreqhcancelled]
GO
/****** Object:  Default [DF_losreplacerequestheader_repreqhreceived]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacerequestheader] ADD  CONSTRAINT [DF_losreplacerequestheader_repreqhreceived]  DEFAULT (0) FOR [repreqhreceived]
GO
/****** Object:  Default [DF__losreplac__repre__7F56CBB8]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacerequestheader] ADD  CONSTRAINT [DF__losreplac__repre__7F56CBB8]  DEFAULT (getdate()) FOR [repreqhupdatetime]
GO
/****** Object:  Default [DF__losreplac__rowgu__758348BB]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacerequestheader] ADD  CONSTRAINT [DF__losreplac__rowgu__758348BB]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losreplac__repre__37861642]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacerequestheader] ADD  CONSTRAINT [DF__losreplac__repre__37861642]  DEFAULT (0) FOR [repreqhtransfinished]
GO
/****** Object:  Default [DF__losreplac__repre__387A3A7B]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacerequestheader] ADD  CONSTRAINT [DF__losreplac__repre__387A3A7B]  DEFAULT (0) FOR [repreqhnoofdetails]
GO
/****** Object:  Default [DF_losservicebookingheader_serbookhposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceBookingHeader] ADD  CONSTRAINT [DF_losservicebookingheader_serbookhposted]  DEFAULT (0) FOR [serbookhposted]
GO
/****** Object:  Default [DF_losservicebookingheader_serbookhinvoiced]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceBookingHeader] ADD  CONSTRAINT [DF_losservicebookingheader_serbookhinvoiced]  DEFAULT (0) FOR [serbookhinvoiced]
GO
/****** Object:  Default [DF_losservicebookingheader_serbookconfirmed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceBookingHeader] ADD  CONSTRAINT [DF_losservicebookingheader_serbookconfirmed]  DEFAULT (0) FOR [serbookconfirmed]
GO
/****** Object:  Default [DF_losservicebookingheader_serbooksermode]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceBookingHeader] ADD  CONSTRAINT [DF_losservicebookingheader_serbooksermode]  DEFAULT (0) FOR [serbooksermode]
GO
/****** Object:  Default [DF__losservic__serbo__55E08030]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceBookingHeader] ADD  CONSTRAINT [DF__losservic__serbo__55E08030]  DEFAULT (0) FOR [serbookhinpcancelled]
GO
/****** Object:  Default [DF_losServiceBookingHeader_serbookhUpdateTime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceBookingHeader] ADD  CONSTRAINT [DF_losServiceBookingHeader_serbookhUpdateTime]  DEFAULT (getdate()) FOR [serbookhUpdateTime]
GO
/****** Object:  Default [DF__losServic__serse__52C5B311]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceBookingHeader] ADD  DEFAULT ((0)) FOR [serserbookhExcludeGST]
GO
/****** Object:  Default [DF_aHQDespatchNoteMain_dnmCostPriceFixed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchNoteMain] ADD  CONSTRAINT [DF_aHQDespatchNoteMain_dnmCostPriceFixed]  DEFAULT (0) FOR [dnmCostPriceFixed]
GO
/****** Object:  Default [DF_aHQDespatchNoteMain_dnmCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchNoteMain] ADD  CONSTRAINT [DF_aHQDespatchNoteMain_dnmCancelled]  DEFAULT (0) FOR [dnmCancelled]
GO
/****** Object:  Default [DF_aHQDespatchNoteMain_Futurevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchNoteMain] ADD  CONSTRAINT [DF_aHQDespatchNoteMain_Futurevc]  DEFAULT ('') FOR [Futurevc]
GO
/****** Object:  Default [DF_aHQDespatchNoteMain_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchNoteMain] ADD  CONSTRAINT [DF_aHQDespatchNoteMain_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__aHQDespat__rowgu__45DE573A]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchNoteMain] ADD  CONSTRAINT [DF__aHQDespat__rowgu__45DE573A]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aShopVendorDetails_futurevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopVendorDetails] ADD  CONSTRAINT [DF_aShopVendorDetails_futurevc]  DEFAULT ('') FOR [futurevc]
GO
/****** Object:  Default [DF__aShopVend__rowgu__54EB90A0]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopVendorDetails] ADD  CONSTRAINT [DF__aShopVend__rowgu__54EB90A0]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losPurchaseOrderHeader_pohcancel]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderHeader] ADD  CONSTRAINT [DF_losPurchaseOrderHeader_pohcancel]  DEFAULT (0) FOR [pohcancel]
GO
/****** Object:  Default [DF_losPurchaseOrderHeader_pohbillgenerated]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderHeader] ADD  CONSTRAINT [DF_losPurchaseOrderHeader_pohbillgenerated]  DEFAULT (0) FOR [pohbillgenerated]
GO
/****** Object:  Default [DF_losPurchaseOrderHeader_pohPocheck]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderHeader] ADD  CONSTRAINT [DF_losPurchaseOrderHeader_pohPocheck]  DEFAULT (0) FOR [pohQuotation]
GO
/****** Object:  Default [DF_losPurchaseOrderHeader_pogenerated]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderHeader] ADD  CONSTRAINT [DF_losPurchaseOrderHeader_pogenerated]  DEFAULT (0) FOR [pogenerated]
GO
/****** Object:  Default [DF_losPurchaseOrderHeader_pohpogenerated]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderHeader] ADD  CONSTRAINT [DF_losPurchaseOrderHeader_pohpogenerated]  DEFAULT (0) FOR [pohpogenerated]
GO
/****** Object:  Default [DF_losPurchaseOrderHeader_pohfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderHeader] ADD  CONSTRAINT [DF_losPurchaseOrderHeader_pohfuturevc]  DEFAULT ('') FOR [pohfuturevc]
GO
/****** Object:  Default [DF_losPurchaseOrderHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderHeader] ADD  CONSTRAINT [DF_losPurchaseOrderHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__losPurcha__rowgu__2FDA0782]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderHeader] ADD  CONSTRAINT [DF__losPurcha__rowgu__2FDA0782]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__lospurcha__pohPO__71DDA060]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderHeader] ADD  CONSTRAINT [DF__lospurcha__pohPO__71DDA060]  DEFAULT (0) FOR [pohPOclosed]
GO
/****** Object:  Default [DF__losPurcha__poHQC__19EC5D11]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderHeader] ADD  DEFAULT ((0)) FOR [poHQConfirmed]
GO
/****** Object:  Default [DF_areprecvendorheader_rrvhtransfinished]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[areprecvendorheader] ADD  CONSTRAINT [DF_areprecvendorheader_rrvhtransfinished]  DEFAULT (0) FOR [rrvhtransfinished]
GO
/****** Object:  Default [DF_areprecvendorheader_rrvhposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[areprecvendorheader] ADD  CONSTRAINT [DF_areprecvendorheader_rrvhposted]  DEFAULT (0) FOR [rrvhcancelled]
GO
/****** Object:  Default [DF_ServiceInvoiceDetails_ServiceQty]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ServiceInvoiceDetails] ADD  CONSTRAINT [DF_ServiceInvoiceDetails_ServiceQty]  DEFAULT (0) FOR [ServiceQty]
GO
/****** Object:  Default [DF_ServiceInvoiceDetails_Amount]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ServiceInvoiceDetails] ADD  CONSTRAINT [DF_ServiceInvoiceDetails_Amount]  DEFAULT (0) FOR [Amount]
GO
/****** Object:  Default [DF__LOsServic__rowgu__5C229E14]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsServiceInvoiceDetails] ADD  CONSTRAINT [DF__LOsServic__rowgu__5C229E14]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LOsPaymen__rowgu__7F16D496]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherDetails] ADD  CONSTRAINT [DF__LOsPaymen__rowgu__7F16D496]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_fb_Tableoccupancy_fb_to_kottrue]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[fb_Tableoccupancy] ADD  CONSTRAINT [DF_fb_Tableoccupancy_fb_to_kottrue]  DEFAULT ((1)) FOR [fb_to_kottrue]
GO
/****** Object:  Default [DF_fb_Tableoccupancy_fb_to_cashreceived]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[fb_Tableoccupancy] ADD  CONSTRAINT [DF_fb_Tableoccupancy_fb_to_cashreceived]  DEFAULT ((0)) FOR [fb_to_cashreceived]
GO
/****** Object:  Default [DF_FB_Dishsubgroup_Fb_Ds_FutureBit]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FB_Dishsubgroup] ADD  CONSTRAINT [DF_FB_Dishsubgroup_Fb_Ds_FutureBit]  DEFAULT ((0)) FOR [Fb_Ds_FutureBit]
GO
/****** Object:  Default [DF__losShipme__bndSt__1B14C01D]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosShipmentbndetail] ADD  CONSTRAINT [DF__losShipme__bndSt__1B14C01D]  DEFAULT ('D') FOR [bndStatus]
GO
/****** Object:  Default [DF__losBoatNo__Cance__1CFD088F]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losBoatNoteConfirmHeader] ADD  CONSTRAINT [DF__losBoatNo__Cance__1CFD088F]  DEFAULT (0) FOR [Cancelled]
GO
/****** Object:  Default [DF_METransLog_systemlog]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsTransLog] ADD  CONSTRAINT [DF_METransLog_systemlog]  DEFAULT (0) FOR [systemlog]
GO
/****** Object:  Default [DF__MEsTransL__rowgu__5F54107A]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsTransLog] ADD  CONSTRAINT [DF__MEsTransL__rowgu__5F54107A]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_loiexpiryarrivaldetails_eadcancel]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiexpiryarrivaldetails] ADD  CONSTRAINT [DF_loiexpiryarrivaldetails_eadcancel]  DEFAULT (0) FOR [eadcancel]
GO
/****** Object:  Default [DF_loiexpiryarrivaldetails_eadAdjustment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiexpiryarrivaldetails] ADD  CONSTRAINT [DF_loiexpiryarrivaldetails_eadAdjustment]  DEFAULT (0) FOR [eadAdjustment]
GO
/****** Object:  Default [DF_loiStockVerificationHeader_svhCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockVerificationHeader] ADD  CONSTRAINT [DF_loiStockVerificationHeader_svhCancelled]  DEFAULT (0) FOR [svhCancelled]
GO
/****** Object:  Default [DF_loiStockVerificationHeader_svhfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockVerificationHeader] ADD  CONSTRAINT [DF_loiStockVerificationHeader_svhfuturevc]  DEFAULT ('') FOR [svhfuturevc]
GO
/****** Object:  Default [DF_loiStockVerificationHeader_svhposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockVerificationHeader] ADD  CONSTRAINT [DF_loiStockVerificationHeader_svhposted]  DEFAULT (0) FOR [svhposted]
GO
/****** Object:  Default [DF_loiStockVerificationHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockVerificationHeader] ADD  CONSTRAINT [DF_loiStockVerificationHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__loiStockV__rowgu__246854D6]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockVerificationHeader] ADD  CONSTRAINT [DF__loiStockV__rowgu__246854D6]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_MEsDespatchtoGodownHeader_dghCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsDespatchtoGodownHeader] ADD  CONSTRAINT [DF_MEsDespatchtoGodownHeader_dghCancelled]  DEFAULT (0) FOR [dghCancelled]
GO
/****** Object:  Default [DF_MEsDespatchtoGodownHeader_dgUsed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsDespatchtoGodownHeader] ADD  CONSTRAINT [DF_MEsDespatchtoGodownHeader_dgUsed]  DEFAULT (0) FOR [dghUsed]
GO
/****** Object:  Default [DF_MEsDespatchtoGodownHeader_dghTransFinished]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsDespatchtoGodownHeader] ADD  CONSTRAINT [DF_MEsDespatchtoGodownHeader_dghTransFinished]  DEFAULT (0) FOR [dghTransFinished]
GO
/****** Object:  Default [DF_MEsDespatchtoGodownHeader_dghNoofDetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsDespatchtoGodownHeader] ADD  CONSTRAINT [DF_MEsDespatchtoGodownHeader_dghNoofDetails]  DEFAULT (0) FOR [dghNoofDetails]
GO
/****** Object:  Default [DF_MEsDespatchtoGodownHeader_dghfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsDespatchtoGodownHeader] ADD  CONSTRAINT [DF_MEsDespatchtoGodownHeader_dghfuturevc]  DEFAULT ('') FOR [dghfuturevc]
GO
/****** Object:  Default [DF_MEsDespatchtoGodownHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsDespatchtoGodownHeader] ADD  CONSTRAINT [DF_MEsDespatchtoGodownHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__mesdespat__dghpo__3CC16359]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsDespatchtoGodownHeader] ADD  CONSTRAINT [DF__mesdespat__dghpo__3CC16359]  DEFAULT (0) FOR [dghposted]
GO
/****** Object:  Default [DF__MEsDespat__rowgu__0F7824E8]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsDespatchtoGodownHeader] ADD  CONSTRAINT [DF__MEsDespat__rowgu__0F7824E8]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_MEiGodownTransferHeader_gthTransFinished]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiGodownTransferHeader] ADD  CONSTRAINT [DF_MEiGodownTransferHeader_gthTransFinished]  DEFAULT (0) FOR [gthTransFinished]
GO
/****** Object:  Default [DF_MEiGodownTransferHeader_gthNoofDetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiGodownTransferHeader] ADD  CONSTRAINT [DF_MEiGodownTransferHeader_gthNoofDetails]  DEFAULT (0) FOR [gthNoofDetails]
GO
/****** Object:  Default [DF_MEiGodownTransferHeader_gthfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiGodownTransferHeader] ADD  CONSTRAINT [DF_MEiGodownTransferHeader_gthfuturevc]  DEFAULT ('') FOR [gthfuturevc]
GO
/****** Object:  Default [DF_MEiGodownTransferHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiGodownTransferHeader] ADD  CONSTRAINT [DF_MEiGodownTransferHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__meigodown__gthpo__23C0AB65]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiGodownTransferHeader] ADD  CONSTRAINT [DF__meigodown__gthpo__23C0AB65]  DEFAULT (0) FOR [gthposted]
GO
/****** Object:  Default [DF__MEiGodown__rowgu__78BEDCC2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiGodownTransferHeader] ADD  CONSTRAINT [DF__MEiGodown__rowgu__78BEDCC2]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__LOiSettin__rowgu__453F38BC]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiSettings] ADD  CONSTRAINT [DF__LOiSettin__rowgu__453F38BC]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LOiDamageClearingHeader_dchfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiDamageClearingHeader] ADD  CONSTRAINT [DF_LOiDamageClearingHeader_dchfuturevc]  DEFAULT ('') FOR [dchfuturevc]
GO
/****** Object:  Default [DF_LOiDamageClearingHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiDamageClearingHeader] ADD  CONSTRAINT [DF_LOiDamageClearingHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__LOiDamage__rowgu__086B34A6]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiDamageClearingHeader] ADD  CONSTRAINT [DF__LOiDamage__rowgu__086B34A6]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LOiWriteOffHeader_whposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiWriteOffHeader] ADD  CONSTRAINT [DF_LOiWriteOffHeader_whposted]  DEFAULT (0) FOR [whposted]
GO
/****** Object:  Default [DF_LOiWriteOffHeader_whfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiWriteOffHeader] ADD  CONSTRAINT [DF_LOiWriteOffHeader_whfuturevc]  DEFAULT ('') FOR [whfuturevc]
GO
/****** Object:  Default [DF_LOiWriteOffHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiWriteOffHeader] ADD  CONSTRAINT [DF_LOiWriteOffHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__loiwriteo__whSel__55F58EC9]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiWriteOffHeader] ADD  CONSTRAINT [DF__loiwriteo__whSel__55F58EC9]  DEFAULT (0) FOR [whSelected]
GO
/****** Object:  Default [DF__loiwriteo__whtra__56E9B302]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiWriteOffHeader] ADD  CONSTRAINT [DF__loiwriteo__whtra__56E9B302]  DEFAULT (0) FOR [whtransfinished]
GO
/****** Object:  Default [DF__LOiWriteO__rowgu__4AF81212]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiWriteOffHeader] ADD  CONSTRAINT [DF__LOiWriteO__rowgu__4AF81212]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_MeiGodownRequestHeader_GRHCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MeiGodownRequestHeader] ADD  CONSTRAINT [DF_MeiGodownRequestHeader_GRHCancelled]  DEFAULT ((0)) FOR [GRHCancelled]
GO
/****** Object:  Default [DF_MeiGodownRequestHeader_GRHUsed]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MeiGodownRequestHeader] ADD  CONSTRAINT [DF_MeiGodownRequestHeader_GRHUsed]  DEFAULT ((0)) FOR [GRHUsed]
GO
/****** Object:  Default [DF_MeiGodownRequestHeader_rowguid]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MeiGodownRequestHeader] ADD  CONSTRAINT [DF_MeiGodownRequestHeader_rowguid]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_loiexpiryissuedetails_eidcancel]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiexpiryissuedetails] ADD  CONSTRAINT [DF_loiexpiryissuedetails_eidcancel]  DEFAULT (0) FOR [eidcancel]
GO
/****** Object:  Default [DF_loiexpiryissuedetails_eidAdjustment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiexpiryissuedetails] ADD  CONSTRAINT [DF_loiexpiryissuedetails_eidAdjustment]  DEFAULT (0) FOR [eidAdjustment]
GO
/****** Object:  Default [DF_meiSpecialDespatchtoshopHeader_dhCancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoshopHeader] ADD  CONSTRAINT [DF_meiSpecialDespatchtoshopHeader_dhCancelled]  DEFAULT (0) FOR [dhCancelled]
GO
/****** Object:  Default [DF_meiSpecialDespatchtoshopHeader_dhSelected]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoshopHeader] ADD  CONSTRAINT [DF_meiSpecialDespatchtoshopHeader_dhSelected]  DEFAULT (0) FOR [dhSelected]
GO
/****** Object:  Default [DF_meiSpecialDespatchtoshopHeader_dhposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoshopHeader] ADD  CONSTRAINT [DF_meiSpecialDespatchtoshopHeader_dhposted]  DEFAULT (0) FOR [dhposted]
GO
/****** Object:  Default [DF_meiSpecialDespatchtoshopHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoshopHeader] ADD  CONSTRAINT [DF_meiSpecialDespatchtoshopHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__meiSpecia__rowgu__1530FE3E]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoshopHeader] ADD  CONSTRAINT [DF__meiSpecia__rowgu__1530FE3E]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LosDeliveryNoteItemDetails_dndItemType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDeliveryNoteItemDetails] ADD  CONSTRAINT [DF_LosDeliveryNoteItemDetails_dndItemType]  DEFAULT ('I') FOR [dndItemType]
GO
/****** Object:  Default [DF_LosDeliveryNoteItemDetails_dndKitID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDeliveryNoteItemDetails] ADD  CONSTRAINT [DF_LosDeliveryNoteItemDetails_dndKitID]  DEFAULT ((0)) FOR [dndKitID]
GO
/****** Object:  Default [DF__losDelive__dndPa__5B7AF4A3]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDeliveryNoteItemDetails] ADD  DEFAULT ((0)) FOR [dndPackingTypeID]
GO
/****** Object:  Default [DF_losCallBookingHeader_serCallBkhcancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losCallBookingHeader] ADD  CONSTRAINT [DF_losCallBookingHeader_serCallBkhcancelled]  DEFAULT (0) FOR [serCallBkhcancelled]
GO
/****** Object:  Default [DF_losCallBookingHeader_serCallBkhinstallation]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losCallBookingHeader] ADD  CONSTRAINT [DF_losCallBookingHeader_serCallBkhinstallation]  DEFAULT (0) FOR [serCallBkhinstallation]
GO
/****** Object:  Default [DF__losCallBo__serCa__51D18ED8]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losCallBookingHeader] ADD  DEFAULT ((0)) FOR [serCallBkhExcludeGST]
GO
/****** Object:  Default [DF__CashBox__rowguid__18ED4BE0]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CashBox] ADD  CONSTRAINT [DF__CashBox__rowguid__18ED4BE0]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_lopStockVerificationHeader_svhcancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockVerificationHeader] ADD  CONSTRAINT [DF_lopStockVerificationHeader_svhcancelled]  DEFAULT (0) FOR [svhcancelled]
GO
/****** Object:  Default [DF_losStockVerificationHeader_svhfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockVerificationHeader] ADD  CONSTRAINT [DF_losStockVerificationHeader_svhfuturevc]  DEFAULT ('') FOR [svhfuturevc]
GO
/****** Object:  Default [DF_losStockVerificationHeader_svhposted]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockVerificationHeader] ADD  CONSTRAINT [DF_losStockVerificationHeader_svhposted]  DEFAULT (0) FOR [svhposted]
GO
/****** Object:  Default [DF_losStockVerificationHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockVerificationHeader] ADD  CONSTRAINT [DF_losStockVerificationHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__losStockV__rowgu__3592E0D8]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockVerificationHeader] ADD  CONSTRAINT [DF__losStockV__rowgu__3592E0D8]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_LOsShopDamageClearingHeader_dchfuturevc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsShopDamageClearingHeader] ADD  CONSTRAINT [DF_LOsShopDamageClearingHeader_dchfuturevc]  DEFAULT ('') FOR [dchfuturevc]
GO
/****** Object:  Default [DF_LOsShopDamageClearingHeader_updatetime]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsShopDamageClearingHeader] ADD  CONSTRAINT [DF_LOsShopDamageClearingHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__LOsShopDa__rowgu__43C1049E]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsShopDamageClearingHeader] ADD  CONSTRAINT [DF__LOsShopDa__rowgu__43C1049E]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__ashopserc__rowgu__08CB2759]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ashopsercategory] ADD  CONSTRAINT [DF__ashopserc__rowgu__08CB2759]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__ashopprin__rowgu__1EA62536]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ashopprintmessages] ADD  CONSTRAINT [DF__ashopprin__rowgu__1EA62536]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losreplacereceiveheader_reprechcancelled]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacereceiveheader] ADD  CONSTRAINT [DF_losreplacereceiveheader_reprechcancelled]  DEFAULT (0) FOR [reprechcancelled]
GO
/****** Object:  Default [DF__losreplac__repre__004AEFF1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacereceiveheader] ADD  CONSTRAINT [DF__losreplac__repre__004AEFF1]  DEFAULT (getdate()) FOR [reprechupdatetime]
GO
/****** Object:  Default [DF__losreplac__rowgu__34A9A997]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacereceiveheader] ADD  CONSTRAINT [DF__losreplac__rowgu__34A9A997]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_mosGoodsRequestHeader_GRHcancel]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mosGoodsRequestHeader] ADD  CONSTRAINT [DF_mosGoodsRequestHeader_GRHcancel]  DEFAULT (0) FOR [GRHcancel]
GO
/****** Object:  Default [DF_mosGoodsRequestHeader_GRHIssuenotegenerated]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mosGoodsRequestHeader] ADD  CONSTRAINT [DF_mosGoodsRequestHeader_GRHIssuenotegenerated]  DEFAULT (0) FOR [GRHIssuenotegenerated]
GO
/****** Object:  Default [DF_mosGoodsRequestHeader_grhSpecialRequest]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mosGoodsRequestHeader] ADD  CONSTRAINT [DF_mosGoodsRequestHeader_grhSpecialRequest]  DEFAULT (0) FOR [grhSpecialRequest]
GO
/****** Object:  Default [DF_mosGoodsRequestHeader_grhTransFinished]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[mosGoodsRequestHeader] ADD  CONSTRAINT [DF_mosGoodsRequestHeader_grhTransFinished]  DEFAULT (0) FOR [grhTransFinished]
GO
/****** Object:  Default [DF_mosGoodsRequestHeader_grhNoofDetails]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[mosGoodsRequestHeader] ADD  CONSTRAINT [DF_mosGoodsRequestHeader_grhNoofDetails]  DEFAULT (0) FOR [grhNoofDetails]
GO
/****** Object:  Default [DF_mosGoodsRequestHeader_grhfuturevc]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[mosGoodsRequestHeader] ADD  CONSTRAINT [DF_mosGoodsRequestHeader_grhfuturevc]  DEFAULT ('') FOR [grhfuturevc]
GO
/****** Object:  Default [DF_mosGoodsRequestHeader_updatetime]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[mosGoodsRequestHeader] ADD  CONSTRAINT [DF_mosGoodsRequestHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__mosGoodsR__rowgu__4C764630]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[mosGoodsRequestHeader] ADD  CONSTRAINT [DF__mosGoodsR__rowgu__4C764630]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_mesRequesttoShopHeader_SRHcancelled]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[mesRequesttoShopHeader] ADD  CONSTRAINT [DF_mesRequesttoShopHeader_SRHcancelled]  DEFAULT (0) FOR [SRHcancelled]
GO
/****** Object:  Default [DF_mesRequesttoShopHeader_SRHUsed]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[mesRequesttoShopHeader] ADD  CONSTRAINT [DF_mesRequesttoShopHeader_SRHUsed]  DEFAULT (0) FOR [SRHUsed]
GO
/****** Object:  Default [DF_mesRequesttoShopHeader_SRHTransfinished]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[mesRequesttoShopHeader] ADD  CONSTRAINT [DF_mesRequesttoShopHeader_SRHTransfinished]  DEFAULT (0) FOR [SRHTransfinished]
GO
/****** Object:  Default [DF_mesRequesttoShopHeader_SRHNoofDetails]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[mesRequesttoShopHeader] ADD  CONSTRAINT [DF_mesRequesttoShopHeader_SRHNoofDetails]  DEFAULT (0) FOR [SRHNoofDetails]
GO
/****** Object:  Default [DF_mesRequesttoShopHeader_SRHfuturevc]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[mesRequesttoShopHeader] ADD  CONSTRAINT [DF_mesRequesttoShopHeader_SRHfuturevc]  DEFAULT ('') FOR [SRHfuturevc]
GO
/****** Object:  Default [DF_mesRequesttoShopHeader_updatetime]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[mesRequesttoShopHeader] ADD  CONSTRAINT [DF_mesRequesttoShopHeader_updatetime]  DEFAULT (getdate()) FOR [updatetime]
GO
/****** Object:  Default [DF__LOsSettin__rowgu__61DB776A]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[LOsSettings] ADD  CONSTRAINT [DF__LOsSettin__rowgu__61DB776A]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__losSettin__Popul__25C758BA]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[LOsSettings] ADD  CONSTRAINT [DF__losSettin__Popul__25C758BA]  DEFAULT ((0)) FOR [PopulateDateWise]
GO
/****** Object:  Default [DF__losSettin__Quick__31390B66]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[LOsSettings] ADD  CONSTRAINT [DF__losSettin__Quick__31390B66]  DEFAULT ((1)) FOR [QuickItemFetch]
GO
/****** Object:  Default [DF__losSettin__Block__5EFFD616]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[LOsSettings] ADD  CONSTRAINT [DF__losSettin__Block__5EFFD616]  DEFAULT ((0)) FOR [BlockAboveSP]
GO
/****** Object:  Default [DF__LOsSettin__ShopA__32B80ADB]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[LOsSettings] ADD  CONSTRAINT [DF__LOsSettin__ShopA__32B80ADB]  DEFAULT ((0)) FOR [ShopActiveDirectoryLogin]
GO
/****** Object:  Default [DF__LOsSettin__Direc__4689F95E]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[LOsSettings] ADD  DEFAULT ((0)) FOR [DirectLocalPurchaseCosting]
GO
/****** Object:  Default [DF__losfuture__futhu__02333863]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[losfuturetabheader] ADD  CONSTRAINT [DF__losfuture__futhu__02333863]  DEFAULT (getdate()) FOR [futhupdatetime]
GO
/****** Object:  Default [DF__losfuture__rowgu__7B3C2211]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[losfuturetabheader] ADD  CONSTRAINT [DF__losfuture__rowgu__7B3C2211]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_losEDIConfirmation_eccancelled]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[losEDIConfirmation] ADD  CONSTRAINT [DF_losEDIConfirmation_eccancelled]  DEFAULT (0) FOR [eccancelled]
GO
/****** Object:  Default [DF__ExchangeR__Excha__4E36081E]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[ExchangeRateHistoryHeader] ADD  DEFAULT (getdate()) FOR [ExchangeDate]
GO
/****** Object:  Default [DF__ExchangeR__rowgu__4F2A2C57]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[ExchangeRateHistoryHeader] ADD  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__ExchangeR__rowgu__1D314762]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[ExchangeRate] ADD  CONSTRAINT [DF__ExchangeR__rowgu__1D314762]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aCountryM__rowgu__3D690CCA]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aCountryMaster] ADD  CONSTRAINT [DF__aCountryM__rowgu__3D690CCA]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aAccRatio__Activ__4401C717]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aAccRatioGroupMaster] ADD  CONSTRAINT [DF__aAccRatio__Activ__4401C717]  DEFAULT (0) FOR [Active]
GO
/****** Object:  Default [DF__aAccRatio__Ratio__74A4FE72]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aAccRatioGroupMaster] ADD  CONSTRAINT [DF__aAccRatio__Ratio__74A4FE72]  DEFAULT ('P') FOR [RatioType]
GO
/****** Object:  Default [DF__aAccRatio__Multi__759922AB]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aAccRatioGroupMaster] ADD  CONSTRAINT [DF__aAccRatio__Multi__759922AB]  DEFAULT (1.00) FOR [Multiplier]
GO
/****** Object:  Default [DF_AsalesPersonmaster_SperSex]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[AsalesPersonmaster] ADD  CONSTRAINT [DF_AsalesPersonmaster_SperSex]  DEFAULT (0) FOR [SperSex]
GO
/****** Object:  Default [DF__AsalesPer__rowgu__23150941]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[AsalesPersonmaster] ADD  CONSTRAINT [DF__AsalesPer__rowgu__23150941]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF_aFinancialYear_CurFinancialYear]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aFinancialYear] ADD  CONSTRAINT [DF_aFinancialYear_CurFinancialYear]  DEFAULT (0) FOR [CurFinancialYear]
GO
/****** Object:  Default [DF__aFinancia__rowgu__4E9398CC]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aFinancialYear] ADD  CONSTRAINT [DF__aFinancia__rowgu__4E9398CC]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__aGroupMas__rowgu__30792600]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aGroupMaster] ADD  CONSTRAINT [DF__aGroupMas__rowgu__30792600]  DEFAULT (newid()) FOR [rowguid]
GO
/****** Object:  Default [DF__fb_kotdet__fb_kd__5F9EF494]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[Fb_kotdetails] ADD  CONSTRAINT [DF__fb_kotdet__fb_kd__5F9EF494]  DEFAULT ((0)) FOR [fb_kd_processed]
GO
/****** Object:  Check [CK_aUserAuditHeader_hMode]    Script Date: 04/16/2012 10:32:32 ******/
ALTER TABLE [dbo].[aUserAuditHeader]  WITH NOCHECK ADD  CONSTRAINT [CK_aUserAuditHeader_hMode] CHECK  (([hMode] = 'V' or ([hMode] = 'C' or ([hMode] = 'P' or ([hMode] = 'D' or ([hMode] = 'E' or [hMode] = 'N'))))))
GO
ALTER TABLE [dbo].[aUserAuditHeader] CHECK CONSTRAINT [CK_aUserAuditHeader_hMode]
GO
/****** Object:  Check [CK_loiUserAuditHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiUserAuditHeader]  WITH NOCHECK ADD  CONSTRAINT [CK_loiUserAuditHeader] CHECK  (([ghMode] = 'C' or ([ghMode] = 'P' or ([ghMode] = 'D' or ([ghMode] = 'E' or [ghMode] = 'N')))))
GO
ALTER TABLE [dbo].[loiUserAuditHeader] CHECK CONSTRAINT [CK_loiUserAuditHeader]
GO
/****** Object:  ForeignKey [FK_Fb_botdetails_Fb_botheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Fb_botdetails]  WITH CHECK ADD  CONSTRAINT [FK_Fb_botdetails_Fb_botheader] FOREIGN KEY([Fb_bd_Companyid], [fb_bd_Outletid], [Fb_bd_botid])
REFERENCES [dbo].[Fb_botheader] ([Fb_bh_Companyid], [Fb_bh_outletid], [Fb_bh_botid])
GO
ALTER TABLE [dbo].[Fb_botdetails] CHECK CONSTRAINT [FK_Fb_botdetails_Fb_botheader]
GO
/****** Object:  ForeignKey [FK_Fb_botdetails_FB_Dishdetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Fb_botdetails]  WITH CHECK ADD  CONSTRAINT [FK_Fb_botdetails_FB_Dishdetails] FOREIGN KEY([Fb_bd_Companyid], [fb_bd_dishid])
REFERENCES [dbo].[FB_Dishdetails] ([fb_dd_companyid], [fb_dd_dishid])
GO
ALTER TABLE [dbo].[Fb_botdetails] CHECK CONSTRAINT [FK_Fb_botdetails_FB_Dishdetails]
GO
/****** Object:  ForeignKey [fk_losLocalClearenceRequestDetail_losLocalClearenceRequestHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losLocalClearenceRequestDetail]  WITH CHECK ADD  CONSTRAINT [fk_losLocalClearenceRequestDetail_losLocalClearenceRequestHeader] FOREIGN KEY([ShopID], [ClearenceReqID])
REFERENCES [dbo].[losLocalClearenceRequestHeader] ([ShopID], [ClearenceReqID])
GO
ALTER TABLE [dbo].[losLocalClearenceRequestDetail] CHECK CONSTRAINT [fk_losLocalClearenceRequestDetail_losLocalClearenceRequestHeader]
GO
/****** Object:  ForeignKey [fk_losLPHeader_aCustomerMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losLPHeader]  WITH CHECK ADD  CONSTRAINT [fk_losLPHeader_aCustomerMaster] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[losLPHeader] CHECK CONSTRAINT [fk_losLPHeader_aCustomerMaster]
GO
/****** Object:  ForeignKey [fk_losLPHeader_aVendorMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losLPHeader]  WITH CHECK ADD  CONSTRAINT [fk_losLPHeader_aVendorMaster] FOREIGN KEY([VendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[losLPHeader] CHECK CONSTRAINT [fk_losLPHeader_aVendorMaster]
GO
/****** Object:  ForeignKey [fk_losLPHeader_losLocalClearenceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losLPHeader]  WITH CHECK ADD  CONSTRAINT [fk_losLPHeader_losLocalClearenceHeader] FOREIGN KEY([ShopID], [ClearenceReqID])
REFERENCES [dbo].[losLocalClearenceRequestHeader] ([ShopID], [ClearenceReqID])
GO
ALTER TABLE [dbo].[losLPHeader] CHECK CONSTRAINT [fk_losLPHeader_losLocalClearenceHeader]
GO
/****** Object:  ForeignKey [fk_aaccountmaster_assetconvacc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings]  WITH CHECK ADD  CONSTRAINT [fk_aaccountmaster_assetconvacc] FOREIGN KEY([AssetConversionAccid], [companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aPAckageSettings] CHECK CONSTRAINT [fk_aaccountmaster_assetconvacc]
GO
/****** Object:  ForeignKey [FK_aPAckageSettings_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings]  WITH CHECK ADD  CONSTRAINT [FK_aPAckageSettings_aAccountMaster] FOREIGN KEY([HQSalesAccID], [companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aPAckageSettings] CHECK CONSTRAINT [FK_aPAckageSettings_aAccountMaster]
GO
/****** Object:  ForeignKey [fk_apackagesettings_aaccountmaster_rtnadj]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings]  WITH CHECK ADD  CONSTRAINT [fk_apackagesettings_aaccountmaster_rtnadj] FOREIGN KEY([Returnadjustmentaccid], [companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aPAckageSettings] CHECK CONSTRAINT [fk_apackagesettings_aaccountmaster_rtnadj]
GO
/****** Object:  ForeignKey [FK_aPAckageSettings_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings]  WITH CHECK ADD  CONSTRAINT [FK_aPAckageSettings_aAccountMaster1] FOREIGN KEY([HQPurchaseAccID], [companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aPAckageSettings] CHECK CONSTRAINT [FK_aPAckageSettings_aAccountMaster1]
GO
/****** Object:  ForeignKey [FK_aPAckageSettings_aAccountMaster2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings]  WITH CHECK ADD  CONSTRAINT [FK_aPAckageSettings_aAccountMaster2] FOREIGN KEY([customsaccid], [companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aPAckageSettings] CHECK CONSTRAINT [FK_aPAckageSettings_aAccountMaster2]
GO
/****** Object:  ForeignKey [FK_aPAckageSettings_aAccountMaster3]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings]  WITH CHECK ADD  CONSTRAINT [FK_aPAckageSettings_aAccountMaster3] FOREIGN KEY([GoodsInTransitID], [companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aPAckageSettings] CHECK CONSTRAINT [FK_aPAckageSettings_aAccountMaster3]
GO
/****** Object:  ForeignKey [FK_aPAckageSettings_aAccountMaster4]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings]  WITH CHECK ADD  CONSTRAINT [FK_aPAckageSettings_aAccountMaster4] FOREIGN KEY([InventoryID], [companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aPAckageSettings] CHECK CONSTRAINT [FK_aPAckageSettings_aAccountMaster4]
GO
/****** Object:  ForeignKey [FK_aPAckageSettings_aAccountMaster5]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings]  WITH CHECK ADD  CONSTRAINT [FK_aPAckageSettings_aAccountMaster5] FOREIGN KEY([shipmentfixedandactualvaluediff], [companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aPAckageSettings] CHECK CONSTRAINT [FK_aPAckageSettings_aAccountMaster5]
GO
/****** Object:  ForeignKey [FK_aPAckageSettings_aAccountMaster6]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings]  WITH CHECK ADD  CONSTRAINT [FK_aPAckageSettings_aAccountMaster6] FOREIGN KEY([compprofitshareacc], [companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aPAckageSettings] CHECK CONSTRAINT [FK_aPAckageSettings_aAccountMaster6]
GO
/****** Object:  ForeignKey [FK_aPAckageSettings_aAccountMaster7]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings]  WITH CHECK ADD  CONSTRAINT [FK_aPAckageSettings_aAccountMaster7] FOREIGN KEY([stocktransfercontrolacc], [companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aPAckageSettings] CHECK CONSTRAINT [FK_aPAckageSettings_aAccountMaster7]
GO
/****** Object:  ForeignKey [FK_aPAckageSettings_aAccountMaster8]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings]  WITH CHECK ADD  CONSTRAINT [FK_aPAckageSettings_aAccountMaster8] FOREIGN KEY([profittransfercontrolacc], [companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aPAckageSettings] CHECK CONSTRAINT [FK_aPAckageSettings_aAccountMaster8]
GO
/****** Object:  ForeignKey [FK_aPackageSettings_aCustomerGroup]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings]  WITH CHECK ADD  CONSTRAINT [FK_aPackageSettings_aCustomerGroup] FOREIGN KEY([companyid], [CustomerGroupIdForEmployees])
REFERENCES [dbo].[aCustomerGroup] ([CompanyID], [CusGroupId])
GO
ALTER TABLE [dbo].[aPAckageSettings] CHECK CONSTRAINT [FK_aPackageSettings_aCustomerGroup]
GO
/****** Object:  ForeignKey [FK_aPAckageSettings_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPAckageSettings]  WITH CHECK ADD  CONSTRAINT [FK_aPAckageSettings_aDepartmentMaster] FOREIGN KEY([companydepartment], [companyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[aPAckageSettings] CHECK CONSTRAINT [FK_aPAckageSettings_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_LOSSERPA_REF_312_LOSSERVI]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losserpartsfromcustomer]  WITH CHECK ADD  CONSTRAINT [FK_LOSSERPA_REF_312_LOSSERVI] FOREIGN KEY([custprodbookingid], [custprodshopid], [custprodcompanyid])
REFERENCES [dbo].[losServiceBookingHeader] ([serbookhid], [serbookhshopid], [serbookhcompanyid])
GO
ALTER TABLE [dbo].[losserpartsfromcustomer] CHECK CONSTRAINT [FK_LOSSERPA_REF_312_LOSSERVI]
GO
/****** Object:  ForeignKey [FK_losserpartsfromcustomer_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losserpartsfromcustomer]  WITH CHECK ADD  CONSTRAINT [FK_losserpartsfromcustomer_aItem] FOREIGN KEY([custprodproductid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losserpartsfromcustomer] CHECK CONSTRAINT [FK_losserpartsfromcustomer_aItem]
GO
/****** Object:  ForeignKey [FK_LOSREPLA_REF_637_LOSSERVI]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacerequestdetails]  WITH CHECK ADD  CONSTRAINT [FK_LOSREPLA_REF_637_LOSSERVI] FOREIGN KEY([repreqdbookid], [repreqdshopid], [repreqdcompanyid])
REFERENCES [dbo].[losServiceBookingHeader] ([serbookhid], [serbookhshopid], [serbookhcompanyid])
GO
ALTER TABLE [dbo].[losreplacerequestdetails] CHECK CONSTRAINT [FK_LOSREPLA_REF_637_LOSSERVI]
GO
/****** Object:  ForeignKey [FK_LOSREPLA_REF_656_LOSREPLA]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacerequestdetails]  WITH CHECK ADD  CONSTRAINT [FK_LOSREPLA_REF_656_LOSREPLA] FOREIGN KEY([repreqdid], [repreqdcompanyid], [repreqdshopid])
REFERENCES [dbo].[losreplacerequestheader] ([repreqhid], [repreqhcompanyid], [repreqshopid])
GO
ALTER TABLE [dbo].[losreplacerequestdetails] CHECK CONSTRAINT [FK_LOSREPLA_REF_656_LOSREPLA]
GO
/****** Object:  ForeignKey [FK_losreplacerequestdetails_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacerequestdetails]  WITH CHECK ADD  CONSTRAINT [FK_losreplacerequestdetails_aItem] FOREIGN KEY([repreqditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losreplacerequestdetails] CHECK CONSTRAINT [FK_losreplacerequestdetails_aItem]
GO
/****** Object:  ForeignKey [fk_losserviceheader_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceHeader]  WITH CHECK ADD  CONSTRAINT [fk_losserviceheader_adepartmentmaster] FOREIGN KEY([serinvhdepartmentid], [serinvhcompanyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[losServiceHeader] CHECK CONSTRAINT [fk_losserviceheader_adepartmentmaster]
GO
/****** Object:  ForeignKey [fk_losserviceheader_aitem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceHeader]  WITH CHECK ADD  CONSTRAINT [fk_losserviceheader_aitem] FOREIGN KEY([serinvhitemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losServiceHeader] CHECK CONSTRAINT [fk_losserviceheader_aitem]
GO
/****** Object:  ForeignKey [FK_losserviceheader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_losserviceheader_aShops] FOREIGN KEY([serinvhshopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losServiceHeader] CHECK CONSTRAINT [FK_losserviceheader_aShops]
GO
/****** Object:  ForeignKey [fk_losserviceheader_losservicebookingheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceHeader]  WITH CHECK ADD  CONSTRAINT [fk_losserviceheader_losservicebookingheader] FOREIGN KEY([serinvhbookingid], [serinvhshopid], [serinvhcompanyid])
REFERENCES [dbo].[losServiceBookingHeader] ([serbookhid], [serbookhshopid], [serbookhcompanyid])
GO
ALTER TABLE [dbo].[losServiceHeader] CHECK CONSTRAINT [fk_losserviceheader_losservicebookingheader]
GO
/****** Object:  ForeignKey [FK_losbookingcancellation_losservicebookingheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losbookingcancellation]  WITH CHECK ADD  CONSTRAINT [FK_losbookingcancellation_losservicebookingheader] FOREIGN KEY([bkcancellbookingId], [bkcancellshopid], [bkcancellcomapnyid])
REFERENCES [dbo].[losServiceBookingHeader] ([serbookhid], [serbookhshopid], [serbookhcompanyid])
GO
ALTER TABLE [dbo].[losbookingcancellation] CHECK CONSTRAINT [FK_losbookingcancellation_losservicebookingheader]
GO
/****** Object:  ForeignKey [fk_losbookpartsreplacedetails_aitem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losbookpartsreplacedetails]  WITH CHECK ADD  CONSTRAINT [fk_losbookpartsreplacedetails_aitem] FOREIGN KEY([repbkdserpartsid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losbookpartsreplacedetails] CHECK CONSTRAINT [fk_losbookpartsreplacedetails_aitem]
GO
/****** Object:  ForeignKey [fk_losbookpartsreplacedetails_apackingtype]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losbookpartsreplacedetails]  WITH CHECK ADD  CONSTRAINT [fk_losbookpartsreplacedetails_apackingtype] FOREIGN KEY([repbkdpackid])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[losbookpartsreplacedetails] CHECK CONSTRAINT [fk_losbookpartsreplacedetails_apackingtype]
GO
/****** Object:  ForeignKey [fk_losbookpartsreplacedetails_losservicebookingheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losbookpartsreplacedetails]  WITH CHECK ADD  CONSTRAINT [fk_losbookpartsreplacedetails_losservicebookingheader] FOREIGN KEY([repbkdserbookid], [repbkdshopid], [repbkdsercompanyid])
REFERENCES [dbo].[losServiceBookingHeader] ([serbookhid], [serbookhshopid], [serbookhcompanyid])
GO
ALTER TABLE [dbo].[losbookpartsreplacedetails] CHECK CONSTRAINT [fk_losbookpartsreplacedetails_losservicebookingheader]
GO
/****** Object:  ForeignKey [FK_losSerestimateapproval_losservicebookingheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerestimateapproval]  WITH CHECK ADD  CONSTRAINT [FK_losSerestimateapproval_losservicebookingheader] FOREIGN KEY([seaAppbookingId], [seaAppShopId], [seaAppcompanyID])
REFERENCES [dbo].[losServiceBookingHeader] ([serbookhid], [serbookhshopid], [serbookhcompanyid])
GO
ALTER TABLE [dbo].[losSerestimateapproval] CHECK CONSTRAINT [FK_losSerestimateapproval_losservicebookingheader]
GO
/****** Object:  ForeignKey [FK_LOSSERCO_REF_221_LOSSERVI]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losserconditiondetails]  WITH CHECK ADD  CONSTRAINT [FK_LOSSERCO_REF_221_LOSSERVI] FOREIGN KEY([cndserbookdid], [cndserdshopid], [cndserdcompanyid])
REFERENCES [dbo].[losServiceBookingHeader] ([serbookhid], [serbookhshopid], [serbookhcompanyid])
GO
ALTER TABLE [dbo].[losserconditiondetails] CHECK CONSTRAINT [FK_LOSSERCO_REF_221_LOSSERVI]
GO
/****** Object:  ForeignKey [FK_losserconditiondetails_aproductconditionmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losserconditiondetails]  WITH CHECK ADD  CONSTRAINT [FK_losserconditiondetails_aproductconditionmaster] FOREIGN KEY([cndserdcompanyid], [cndserid])
REFERENCES [dbo].[aproductconditionmaster] ([prodcndcompanyid], [prodcndid])
GO
ALTER TABLE [dbo].[losserconditiondetails] CHECK CONSTRAINT [FK_losserconditiondetails_aproductconditionmaster]
GO
/****** Object:  ForeignKey [FK_losbookservtechniciandetails_AsalesPersonmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losbookservtechniciandetails]  WITH CHECK ADD  CONSTRAINT [FK_losbookservtechniciandetails_AsalesPersonmaster] FOREIGN KEY([sertechid])
REFERENCES [dbo].[AsalesPersonmaster] ([Sperid])
GO
ALTER TABLE [dbo].[losbookservtechniciandetails] CHECK CONSTRAINT [FK_losbookservtechniciandetails_AsalesPersonmaster]
GO
/****** Object:  ForeignKey [fk_losbookservtechniciandetails_aservicemaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losbookservtechniciandetails]  WITH CHECK ADD  CONSTRAINT [fk_losbookservtechniciandetails_aservicemaster] FOREIGN KEY([sertechServiceID], [sertechcompanyid])
REFERENCES [dbo].[aservicemaster] ([serid], [sercompanyid])
GO
ALTER TABLE [dbo].[losbookservtechniciandetails] CHECK CONSTRAINT [fk_losbookservtechniciandetails_aservicemaster]
GO
/****** Object:  ForeignKey [FK_losbookservtechniciandetails_losservicebookingheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losbookservtechniciandetails]  WITH CHECK ADD  CONSTRAINT [FK_losbookservtechniciandetails_losservicebookingheader] FOREIGN KEY([sertechbookid], [sertechshopid], [sertechcompanyid])
REFERENCES [dbo].[losServiceBookingHeader] ([serbookhid], [serbookhshopid], [serbookhcompanyid])
GO
ALTER TABLE [dbo].[losbookservtechniciandetails] CHECK CONSTRAINT [FK_losbookservtechniciandetails_losservicebookingheader]
GO
/****** Object:  ForeignKey [FK_LOSBOOKS_REF_2125_ASERVICE]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losbookservicedetails]  WITH CHECK ADD  CONSTRAINT [FK_LOSBOOKS_REF_2125_ASERVICE] FOREIGN KEY([serbkdserviceid], [serbkdcompanyid])
REFERENCES [dbo].[aservicemaster] ([serid], [sercompanyid])
GO
ALTER TABLE [dbo].[losbookservicedetails] CHECK CONSTRAINT [FK_LOSBOOKS_REF_2125_ASERVICE]
GO
/****** Object:  ForeignKey [FK_LOSBOOKS_REF_252_LOSSERVI]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losbookservicedetails]  WITH CHECK ADD  CONSTRAINT [FK_LOSBOOKS_REF_252_LOSSERVI] FOREIGN KEY([serbkdbookid], [serbkdshopid], [serbkdcompanyid])
REFERENCES [dbo].[losServiceBookingHeader] ([serbookhid], [serbookhshopid], [serbookhcompanyid])
GO
ALTER TABLE [dbo].[losbookservicedetails] CHECK CONSTRAINT [FK_LOSBOOKS_REF_252_LOSSERVI]
GO
/****** Object:  ForeignKey [FK_Discountdetails_Discountheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Discountdetails]  WITH CHECK ADD  CONSTRAINT [FK_Discountdetails_Discountheader] FOREIGN KEY([Companyid], [Discountid])
REFERENCES [dbo].[Discountheader] ([Companyid], [Discountid])
GO
ALTER TABLE [dbo].[Discountdetails] CHECK CONSTRAINT [FK_Discountdetails_Discountheader]
GO
/****** Object:  ForeignKey [FK_CustomerSettlementHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementHeader]  WITH CHECK ADD  CONSTRAINT [FK_CustomerSettlementHeader_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[CustomerSettlementHeader] CHECK CONSTRAINT [FK_CustomerSettlementHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [fk_CustomerSettlementHeader_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementHeader]  WITH CHECK ADD  CONSTRAINT [fk_CustomerSettlementHeader_acustomermaster] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[CustomerSettlementHeader] CHECK CONSTRAINT [fk_CustomerSettlementHeader_acustomermaster]
GO
/****** Object:  ForeignKey [FK_CustomerSettlementHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementHeader]  WITH CHECK ADD  CONSTRAINT [FK_CustomerSettlementHeader_aDepartmentMaster] FOREIGN KEY([DepartmentID], [CompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[CustomerSettlementHeader] CHECK CONSTRAINT [FK_CustomerSettlementHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_CustomerSettlementHeader_aFinancialYear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementHeader]  WITH CHECK ADD  CONSTRAINT [FK_CustomerSettlementHeader_aFinancialYear] FOREIGN KEY([FinancialID], [CompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[CustomerSettlementHeader] CHECK CONSTRAINT [FK_CustomerSettlementHeader_aFinancialYear]
GO
/****** Object:  ForeignKey [FK_CustomerSettlementHeader_DebitCreditNote]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementHeader]  WITH CHECK ADD  CONSTRAINT [FK_CustomerSettlementHeader_DebitCreditNote] FOREIGN KEY([dcnid])
REFERENCES [dbo].[DebitCreditNote] ([DCNId])
GO
ALTER TABLE [dbo].[CustomerSettlementHeader] CHECK CONSTRAINT [FK_CustomerSettlementHeader_DebitCreditNote]
GO
/****** Object:  ForeignKey [FK_CustomerSettlementHeader_LosGoodsReturnNoteHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementHeader]  WITH CHECK ADD  CONSTRAINT [FK_CustomerSettlementHeader_LosGoodsReturnNoteHeader] FOREIGN KEY([shopid], [losGoodsreturnnoteID])
REFERENCES [dbo].[LosGoodsReturnNoteHeader] ([grnhShopid], [GrnhGoodsreturnnoteID])
GO
ALTER TABLE [dbo].[CustomerSettlementHeader] CHECK CONSTRAINT [FK_CustomerSettlementHeader_LosGoodsReturnNoteHeader]
GO
/****** Object:  ForeignKey [fk_CustomerSettlementHeader_LOSspecialinvoiceheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementHeader]  WITH CHECK ADD  CONSTRAINT [fk_CustomerSettlementHeader_LOSspecialinvoiceheader] FOREIGN KEY([losdcnid], [shopid])
REFERENCES [dbo].[losSpecialInvoiceHeader] ([IhInvoiceID], [IhShopID])
GO
ALTER TABLE [dbo].[CustomerSettlementHeader] CHECK CONSTRAINT [fk_CustomerSettlementHeader_LOSspecialinvoiceheader]
GO
/****** Object:  ForeignKey [FK_CustomerSettlementHeader_ReceiptVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementHeader]  WITH CHECK ADD  CONSTRAINT [FK_CustomerSettlementHeader_ReceiptVoucherHeader] FOREIGN KEY([ReceiptID])
REFERENCES [dbo].[ReceiptVoucherHeader] ([ReceiptID])
GO
ALTER TABLE [dbo].[CustomerSettlementHeader] CHECK CONSTRAINT [FK_CustomerSettlementHeader_ReceiptVoucherHeader]
GO
/****** Object:  ForeignKey [FK_losSpecialInvoiceDetail_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceDetail]  WITH CHECK ADD  CONSTRAINT [FK_losSpecialInvoiceDetail_aGodown] FOREIGN KEY([idGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[losSpecialInvoiceDetail] CHECK CONSTRAINT [FK_losSpecialInvoiceDetail_aGodown]
GO
/****** Object:  ForeignKey [FK_losSpecialInvoiceDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceDetail]  WITH CHECK ADD  CONSTRAINT [FK_losSpecialInvoiceDetail_aItem] FOREIGN KEY([idItemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losSpecialInvoiceDetail] CHECK CONSTRAINT [FK_losSpecialInvoiceDetail_aItem]
GO
/****** Object:  ForeignKey [FK_losSpecialInvoiceDetail_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceDetail]  WITH CHECK ADD  CONSTRAINT [FK_losSpecialInvoiceDetail_aPackingType] FOREIGN KEY([idPackingTypeid])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[losSpecialInvoiceDetail] CHECK CONSTRAINT [FK_losSpecialInvoiceDetail_aPackingType]
GO
/****** Object:  ForeignKey [fk_losSpecialInvoiceDetail_ashipment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSpecialInvoiceDetail_ashipment] FOREIGN KEY([shipmentid])
REFERENCES [dbo].[aShipment] ([sShipmentID])
GO
ALTER TABLE [dbo].[losSpecialInvoiceDetail] CHECK CONSTRAINT [fk_losSpecialInvoiceDetail_ashipment]
GO
/****** Object:  ForeignKey [FK_losSpecialInvoiceDetail_losSpecialInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceDetail]  WITH CHECK ADD  CONSTRAINT [FK_losSpecialInvoiceDetail_losSpecialInvoiceHeader] FOREIGN KEY([idInvoiceId], [idShopid])
REFERENCES [dbo].[losSpecialInvoiceHeader] ([IhInvoiceID], [IhShopID])
GO
ALTER TABLE [dbo].[losSpecialInvoiceDetail] CHECK CONSTRAINT [FK_losSpecialInvoiceDetail_losSpecialInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_losSpecialOC_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialOC]  WITH CHECK ADD  CONSTRAINT [FK_losSpecialOC_aAccountMaster] FOREIGN KEY([ioAccid], [ioCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[losSpecialOC] CHECK CONSTRAINT [FK_losSpecialOC_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_losSpecialOC_losSpecialInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialOC]  WITH CHECK ADD  CONSTRAINT [FK_losSpecialOC_losSpecialInvoiceHeader] FOREIGN KEY([ioInvoiceID], [ioShopid])
REFERENCES [dbo].[losSpecialInvoiceHeader] ([IhInvoiceID], [IhShopID])
GO
ALTER TABLE [dbo].[losSpecialOC] CHECK CONSTRAINT [FK_losSpecialOC_losSpecialInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_LosDummyReceiptDetail_LOsAccountsInvoiceHeader1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosDummyReceiptDetail]  WITH CHECK ADD  CONSTRAINT [FK_LosDummyReceiptDetail_LOsAccountsInvoiceHeader1] FOREIGN KEY([drdShopID], [drdserviceinvoiceid])
REFERENCES [dbo].[LOsAccountsInvoiceHeader] ([aiShopID], [aiInvoiceID])
GO
ALTER TABLE [dbo].[LosDummyReceiptDetail] CHECK CONSTRAINT [FK_LosDummyReceiptDetail_LOsAccountsInvoiceHeader1]
GO
/****** Object:  ForeignKey [fk_LosDummyReceiptDetail_losApartmentBillHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosDummyReceiptDetail]  WITH CHECK ADD  CONSTRAINT [fk_LosDummyReceiptDetail_losApartmentBillHeader] FOREIGN KEY([drdRoomBillID], [drdShopID], [drdcompanyid])
REFERENCES [dbo].[losApartmentBillHeader] ([abhBillId], [abhSHopID], [abhCompanyid])
GO
ALTER TABLE [dbo].[LosDummyReceiptDetail] CHECK CONSTRAINT [fk_LosDummyReceiptDetail_losApartmentBillHeader]
GO
/****** Object:  ForeignKey [FK_LosDummyReceiptDetail_losDebitCreditNote]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosDummyReceiptDetail]  WITH CHECK ADD  CONSTRAINT [FK_LosDummyReceiptDetail_losDebitCreditNote] FOREIGN KEY([drdShopID], [drddcnid])
REFERENCES [dbo].[losDebitCreditNote] ([losDCNShopid], [losDCNId])
GO
ALTER TABLE [dbo].[LosDummyReceiptDetail] CHECK CONSTRAINT [FK_LosDummyReceiptDetail_losDebitCreditNote]
GO
/****** Object:  ForeignKey [FK_LosDummyReceiptDetail_losDummyReceiptHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosDummyReceiptDetail]  WITH CHECK ADD  CONSTRAINT [FK_LosDummyReceiptDetail_losDummyReceiptHeader] FOREIGN KEY([drdShopID], [drdid])
REFERENCES [dbo].[losDummyReceiptHeader] ([drShopid], [drId])
GO
ALTER TABLE [dbo].[LosDummyReceiptDetail] CHECK CONSTRAINT [FK_LosDummyReceiptDetail_losDummyReceiptHeader]
GO
/****** Object:  ForeignKey [FK_LosDummyReceiptDetail_LOsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosDummyReceiptDetail]  WITH CHECK ADD  CONSTRAINT [FK_LosDummyReceiptDetail_LOsInvoiceHeader] FOREIGN KEY([drdShopID], [drdinvoiceid])
REFERENCES [dbo].[LOsInvoiceHeader] ([ihShopID], [ihInvoiceID])
GO
ALTER TABLE [dbo].[LosDummyReceiptDetail] CHECK CONSTRAINT [FK_LosDummyReceiptDetail_LOsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_LosDummyReceiptDetail_losSpecialInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosDummyReceiptDetail]  WITH CHECK ADD  CONSTRAINT [FK_LosDummyReceiptDetail_losSpecialInvoiceHeader] FOREIGN KEY([drdsplinvoiceid], [drdShopID])
REFERENCES [dbo].[losSpecialInvoiceHeader] ([IhInvoiceID], [IhShopID])
GO
ALTER TABLE [dbo].[LosDummyReceiptDetail] CHECK CONSTRAINT [FK_LosDummyReceiptDetail_losSpecialInvoiceHeader]
GO
/****** Object:  ForeignKey [fk_LosDummyReceiptDetail_losTenantServiceBillHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosDummyReceiptDetail]  WITH CHECK ADD  CONSTRAINT [fk_LosDummyReceiptDetail_losTenantServiceBillHeader] FOREIGN KEY([drdUtilityBillID], [drdShopID], [drdcompanyid])
REFERENCES [dbo].[losTenantServiceBillHeader] ([tbhBillId], [tbhShopId], [tbhCompanyId])
GO
ALTER TABLE [dbo].[LosDummyReceiptDetail] CHECK CONSTRAINT [fk_LosDummyReceiptDetail_losTenantServiceBillHeader]
GO
/****** Object:  ForeignKey [FK_CustomerSettlementDetail_AccountsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementDetail]  WITH CHECK ADD  CONSTRAINT [FK_CustomerSettlementDetail_AccountsInvoiceHeader] FOREIGN KEY([AccInvoiceID])
REFERENCES [dbo].[AccountsInvoiceHeader] ([InvoiceID])
GO
ALTER TABLE [dbo].[CustomerSettlementDetail] CHECK CONSTRAINT [FK_CustomerSettlementDetail_AccountsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_CustomerSettlementDetail_aHQPaymentVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementDetail]  WITH CHECK ADD  CONSTRAINT [FK_CustomerSettlementDetail_aHQPaymentVoucherHeader] FOREIGN KEY([paymentid])
REFERENCES [dbo].[aHQPaymentVoucherHeader] ([phPaymentID])
GO
ALTER TABLE [dbo].[CustomerSettlementDetail] CHECK CONSTRAINT [FK_CustomerSettlementDetail_aHQPaymentVoucherHeader]
GO
/****** Object:  ForeignKey [FK_CustomerSettlementDetail_CustomerSettlementHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementDetail]  WITH CHECK ADD  CONSTRAINT [FK_CustomerSettlementDetail_CustomerSettlementHeader] FOREIGN KEY([CSID])
REFERENCES [dbo].[CustomerSettlementHeader] ([CSID])
GO
ALTER TABLE [dbo].[CustomerSettlementDetail] CHECK CONSTRAINT [FK_CustomerSettlementDetail_CustomerSettlementHeader]
GO
/****** Object:  ForeignKey [FK_CustomerSettlementDetail_DebitCreditNote]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementDetail]  WITH CHECK ADD  CONSTRAINT [FK_CustomerSettlementDetail_DebitCreditNote] FOREIGN KEY([dcnid])
REFERENCES [dbo].[DebitCreditNote] ([DCNId])
GO
ALTER TABLE [dbo].[CustomerSettlementDetail] CHECK CONSTRAINT [FK_CustomerSettlementDetail_DebitCreditNote]
GO
/****** Object:  ForeignKey [FK_CustomerSettlementDetail_LOsAccountsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementDetail]  WITH CHECK ADD  CONSTRAINT [FK_CustomerSettlementDetail_LOsAccountsInvoiceHeader] FOREIGN KEY([shopid], [LosAccInvoiceID])
REFERENCES [dbo].[LOsAccountsInvoiceHeader] ([aiShopID], [aiInvoiceID])
GO
ALTER TABLE [dbo].[CustomerSettlementDetail] CHECK CONSTRAINT [FK_CustomerSettlementDetail_LOsAccountsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_CustomerSettlementDetail_losDebitCreditNote]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementDetail]  WITH CHECK ADD  CONSTRAINT [FK_CustomerSettlementDetail_losDebitCreditNote] FOREIGN KEY([shopid], [losdcnid])
REFERENCES [dbo].[losDebitCreditNote] ([losDCNShopid], [losDCNId])
GO
ALTER TABLE [dbo].[CustomerSettlementDetail] CHECK CONSTRAINT [FK_CustomerSettlementDetail_losDebitCreditNote]
GO
/****** Object:  ForeignKey [FK_CustomerSettlementDetail_LOsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementDetail]  WITH CHECK ADD  CONSTRAINT [FK_CustomerSettlementDetail_LOsInvoiceHeader] FOREIGN KEY([shopid], [losinvoiceid])
REFERENCES [dbo].[LOsInvoiceHeader] ([ihShopID], [ihInvoiceID])
GO
ALTER TABLE [dbo].[CustomerSettlementDetail] CHECK CONSTRAINT [FK_CustomerSettlementDetail_LOsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_CustomerSettlementDetail_losSpecialInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CustomerSettlementDetail]  WITH CHECK ADD  CONSTRAINT [FK_CustomerSettlementDetail_losSpecialInvoiceHeader] FOREIGN KEY([losSpInvoiceId], [shopid])
REFERENCES [dbo].[losSpecialInvoiceHeader] ([IhInvoiceID], [IhShopID])
GO
ALTER TABLE [dbo].[CustomerSettlementDetail] CHECK CONSTRAINT [FK_CustomerSettlementDetail_losSpecialInvoiceHeader]
GO
/****** Object:  ForeignKey [fk_hqInhousePurchaseBillingDetails_BillsDebitDetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[hqInhousePurchaseBillingDetails]  WITH CHECK ADD  CONSTRAINT [fk_hqInhousePurchaseBillingDetails_BillsDebitDetails] FOREIGN KEY([ipbdBillId], [ipbdBillDetailId])
REFERENCES [dbo].[BillsDebitDetails] ([BillsID], [BillsDebitID])
GO
ALTER TABLE [dbo].[hqInhousePurchaseBillingDetails] CHECK CONSTRAINT [fk_hqInhousePurchaseBillingDetails_BillsDebitDetails]
GO
/****** Object:  ForeignKey [fk_hqInhousePurchaseBillingDetails_loaInhousePurchaseHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[hqInhousePurchaseBillingDetails]  WITH CHECK ADD  CONSTRAINT [fk_hqInhousePurchaseBillingDetails_loaInhousePurchaseHeader] FOREIGN KEY([ipbdInhousePurchaseId])
REFERENCES [dbo].[loaInhousePurchaseHeader] ([iphId])
GO
ALTER TABLE [dbo].[hqInhousePurchaseBillingDetails] CHECK CONSTRAINT [fk_hqInhousePurchaseBillingDetails_loaInhousePurchaseHeader]
GO
/****** Object:  ForeignKey [FK_losSIQuotationHeader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader]  WITH CHECK ADD  CONSTRAINT [FK_losSIQuotationHeader_aAccountMaster] FOREIGN KEY([IhBankcashAccID], [IhCompanyId])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[losSIQuotationHeader] CHECK CONSTRAINT [FK_losSIQuotationHeader_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_losSIQuotationHeader_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader]  WITH CHECK ADD  CONSTRAINT [FK_losSIQuotationHeader_aAccountMaster1] FOREIGN KEY([IhDiscountAccID], [IhCompanyId])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[losSIQuotationHeader] CHECK CONSTRAINT [FK_losSIQuotationHeader_aAccountMaster1]
GO
/****** Object:  ForeignKey [fk_losSIQuotationHeader_aaccountmaster5]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader]  WITH CHECK ADD  CONSTRAINT [fk_losSIQuotationHeader_aaccountmaster5] FOREIGN KEY([IhSalesAccID], [IhCompanyId])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[losSIQuotationHeader] CHECK CONSTRAINT [fk_losSIQuotationHeader_aaccountmaster5]
GO
/****** Object:  ForeignKey [fk_losSIQuotationHeader_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader]  WITH CHECK ADD  CONSTRAINT [fk_losSIQuotationHeader_acustomermaster] FOREIGN KEY([IhCustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[losSIQuotationHeader] CHECK CONSTRAINT [fk_losSIQuotationHeader_acustomermaster]
GO
/****** Object:  ForeignKey [FK_losSIQuotationHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader]  WITH CHECK ADD  CONSTRAINT [FK_losSIQuotationHeader_aDepartmentMaster] FOREIGN KEY([IhDepartmentID], [IhCompanyId])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[losSIQuotationHeader] CHECK CONSTRAINT [FK_losSIQuotationHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_losSIQuotationHeader_aFinancialYear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader]  WITH CHECK ADD  CONSTRAINT [FK_losSIQuotationHeader_aFinancialYear] FOREIGN KEY([IhFinancialID], [IhCompanyId])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[losSIQuotationHeader] CHECK CONSTRAINT [FK_losSIQuotationHeader_aFinancialYear]
GO
/****** Object:  ForeignKey [FK_losSIQuotationHeader_AsalesPersonmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader]  WITH CHECK ADD  CONSTRAINT [FK_losSIQuotationHeader_AsalesPersonmaster] FOREIGN KEY([ihsalespersonid])
REFERENCES [dbo].[AsalesPersonmaster] ([Sperid])
GO
ALTER TABLE [dbo].[losSIQuotationHeader] CHECK CONSTRAINT [FK_losSIQuotationHeader_AsalesPersonmaster]
GO
/****** Object:  ForeignKey [FK_losSIQuotationHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader]  WITH CHECK ADD  CONSTRAINT [FK_losSIQuotationHeader_aShops] FOREIGN KEY([IhShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losSIQuotationHeader] CHECK CONSTRAINT [FK_losSIQuotationHeader_aShops]
GO
/****** Object:  ForeignKey [FK_losSIQuotationHeader_CashBox]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationHeader]  WITH CHECK ADD  CONSTRAINT [FK_losSIQuotationHeader_CashBox] FOREIGN KEY([ihcbid], [IhShopID])
REFERENCES [dbo].[CashBox] ([CBID], [CBShopID])
GO
ALTER TABLE [dbo].[losSIQuotationHeader] CHECK CONSTRAINT [FK_losSIQuotationHeader_CashBox]
GO
/****** Object:  ForeignKey [FK_losDummyReceiptHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDummyReceiptHeader]  WITH CHECK ADD  CONSTRAINT [FK_losDummyReceiptHeader_aDepartmentMaster] FOREIGN KEY([drdepartmentid], [drCompanyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[losDummyReceiptHeader] CHECK CONSTRAINT [FK_losDummyReceiptHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_losDummyReceiptHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDummyReceiptHeader]  WITH CHECK ADD  CONSTRAINT [FK_losDummyReceiptHeader_aShops] FOREIGN KEY([drShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losDummyReceiptHeader] CHECK CONSTRAINT [FK_losDummyReceiptHeader_aShops]
GO
/****** Object:  ForeignKey [FK_losDummyReceiptHeader_CashBox]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDummyReceiptHeader]  WITH CHECK ADD  CONSTRAINT [FK_losDummyReceiptHeader_CashBox] FOREIGN KEY([drcbid], [drShopid])
REFERENCES [dbo].[CashBox] ([CBID], [CBShopID])
GO
ALTER TABLE [dbo].[losDummyReceiptHeader] CHECK CONSTRAINT [FK_losDummyReceiptHeader_CashBox]
GO
/****** Object:  ForeignKey [FK_losposExchangeHeader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeHeader]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeHeader_aAccountMaster] FOREIGN KEY([sehSalesAccID], [sehCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[losposExchangeHeader] CHECK CONSTRAINT [FK_losposExchangeHeader_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_losposExchangeHeader_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeHeader]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeHeader_aAccountMaster1] FOREIGN KEY([sehCashAccID], [sehCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[losposExchangeHeader] CHECK CONSTRAINT [FK_losposExchangeHeader_aAccountMaster1]
GO
/****** Object:  ForeignKey [FK_losposExchangeHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeHeader]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeHeader_aDepartmentMaster] FOREIGN KEY([sehDepartmentID], [sehCompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[losposExchangeHeader] CHECK CONSTRAINT [FK_losposExchangeHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_losposExchangeHeader_AsalesPersonmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeHeader]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeHeader_AsalesPersonmaster] FOREIGN KEY([sehsalespersonid])
REFERENCES [dbo].[AsalesPersonmaster] ([Sperid])
GO
ALTER TABLE [dbo].[losposExchangeHeader] CHECK CONSTRAINT [FK_losposExchangeHeader_AsalesPersonmaster]
GO
/****** Object:  ForeignKey [FK_losposExchangeHeader_CashBox]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeHeader]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeHeader_CashBox] FOREIGN KEY([sehcbid], [sehShopID])
REFERENCES [dbo].[CashBox] ([CBID], [CBShopID])
GO
ALTER TABLE [dbo].[losposExchangeHeader] CHECK CONSTRAINT [FK_losposExchangeHeader_CashBox]
GO
/****** Object:  ForeignKey [FK_losposExchangeHeader_LOsPosHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeHeader]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeHeader_LOsPosHeader] FOREIGN KEY([sehShopID], [sehBillID])
REFERENCES [dbo].[LOsPosHeader] ([poshShopID], [poshBillID])
GO
ALTER TABLE [dbo].[losposExchangeHeader] CHECK CONSTRAINT [FK_losposExchangeHeader_LOsPosHeader]
GO
/****** Object:  ForeignKey [FK_losSpecialInvoiceHeader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_losSpecialInvoiceHeader_aAccountMaster] FOREIGN KEY([IhBankcashAccID], [IhCompanyId])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[losSpecialInvoiceHeader] CHECK CONSTRAINT [FK_losSpecialInvoiceHeader_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_losSpecialInvoiceHeader_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_losSpecialInvoiceHeader_aAccountMaster1] FOREIGN KEY([IhDiscountAccID], [IhCompanyId])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[losSpecialInvoiceHeader] CHECK CONSTRAINT [FK_losSpecialInvoiceHeader_aAccountMaster1]
GO
/****** Object:  ForeignKey [fk_losSpecialInvoiceHeader_aaccountmaster5]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [fk_losSpecialInvoiceHeader_aaccountmaster5] FOREIGN KEY([IhSalesAccID], [IhCompanyId])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[losSpecialInvoiceHeader] CHECK CONSTRAINT [fk_losSpecialInvoiceHeader_aaccountmaster5]
GO
/****** Object:  ForeignKey [fk_losSpecialInvoiceHeader_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [fk_losSpecialInvoiceHeader_acustomermaster] FOREIGN KEY([IhCustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[losSpecialInvoiceHeader] CHECK CONSTRAINT [fk_losSpecialInvoiceHeader_acustomermaster]
GO
/****** Object:  ForeignKey [FK_losSpecialInvoiceHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_losSpecialInvoiceHeader_aDepartmentMaster] FOREIGN KEY([IhDepartmentID], [IhCompanyId])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[losSpecialInvoiceHeader] CHECK CONSTRAINT [FK_losSpecialInvoiceHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_losSpecialInvoiceHeader_aFinancialYear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_losSpecialInvoiceHeader_aFinancialYear] FOREIGN KEY([IhFinancialID], [IhCompanyId])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[losSpecialInvoiceHeader] CHECK CONSTRAINT [FK_losSpecialInvoiceHeader_aFinancialYear]
GO
/****** Object:  ForeignKey [FK_losSpecialInvoiceHeader_AsalesPersonmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_losSpecialInvoiceHeader_AsalesPersonmaster] FOREIGN KEY([ihsalespersonid])
REFERENCES [dbo].[AsalesPersonmaster] ([Sperid])
GO
ALTER TABLE [dbo].[losSpecialInvoiceHeader] CHECK CONSTRAINT [FK_losSpecialInvoiceHeader_AsalesPersonmaster]
GO
/****** Object:  ForeignKey [FK_losSpecialInvoiceHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_losSpecialInvoiceHeader_aShops] FOREIGN KEY([IhShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losSpecialInvoiceHeader] CHECK CONSTRAINT [FK_losSpecialInvoiceHeader_aShops]
GO
/****** Object:  ForeignKey [FK_losSpecialInvoiceHeader_CashBox]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSpecialInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_losSpecialInvoiceHeader_CashBox] FOREIGN KEY([ihcbid], [IhShopID])
REFERENCES [dbo].[CashBox] ([CBID], [CBShopID])
GO
ALTER TABLE [dbo].[losSpecialInvoiceHeader] CHECK CONSTRAINT [FK_losSpecialInvoiceHeader_CashBox]
GO
/****** Object:  ForeignKey [FK_LosLocalPurcaseHeader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader]  WITH CHECK ADD  CONSTRAINT [FK_LosLocalPurcaseHeader_aAccountMaster] FOREIGN KEY([lphDiscountAccID], [lphCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LosLocalPurchaseHeader] CHECK CONSTRAINT [FK_LosLocalPurcaseHeader_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_LosLocalPurcaseHeader_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader]  WITH CHECK ADD  CONSTRAINT [FK_LosLocalPurcaseHeader_aAccountMaster1] FOREIGN KEY([lphBankcashAccID], [lphCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LosLocalPurchaseHeader] CHECK CONSTRAINT [FK_LosLocalPurcaseHeader_aAccountMaster1]
GO
/****** Object:  ForeignKey [FK_LosLocalPurcaseHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader]  WITH CHECK ADD  CONSTRAINT [FK_LosLocalPurcaseHeader_aDepartmentMaster] FOREIGN KEY([lphDepartmentID], [lphCompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[LosLocalPurchaseHeader] CHECK CONSTRAINT [FK_LosLocalPurcaseHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_LosLocalPurcaseHeader_aFinancialYear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader]  WITH CHECK ADD  CONSTRAINT [FK_LosLocalPurcaseHeader_aFinancialYear] FOREIGN KEY([lphFinancialID], [lphCompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[LosLocalPurchaseHeader] CHECK CONSTRAINT [FK_LosLocalPurcaseHeader_aFinancialYear]
GO
/****** Object:  ForeignKey [fk_losLocalPurchaseHeader_aaccountmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader]  WITH CHECK ADD  CONSTRAINT [fk_losLocalPurchaseHeader_aaccountmaster] FOREIGN KEY([lphPurchaseAccID], [lphCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LosLocalPurchaseHeader] CHECK CONSTRAINT [fk_losLocalPurchaseHeader_aaccountmaster]
GO
/****** Object:  ForeignKey [FK_LosLocalPurchaseHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader]  WITH CHECK ADD  CONSTRAINT [FK_LosLocalPurchaseHeader_aShops] FOREIGN KEY([lphShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LosLocalPurchaseHeader] CHECK CONSTRAINT [FK_LosLocalPurchaseHeader_aShops]
GO
/****** Object:  ForeignKey [fk_loslocalpurchaseheader_avendormaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader]  WITH CHECK ADD  CONSTRAINT [fk_loslocalpurchaseheader_avendormaster] FOREIGN KEY([lphVendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[LosLocalPurchaseHeader] CHECK CONSTRAINT [fk_loslocalpurchaseheader_avendormaster]
GO
/****** Object:  ForeignKey [FK_LosLocalPurchaseHeader_CashBox]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader]  WITH CHECK ADD  CONSTRAINT [FK_LosLocalPurchaseHeader_CashBox] FOREIGN KEY([lphcbid], [lphShopID])
REFERENCES [dbo].[CashBox] ([CBID], [CBShopID])
GO
ALTER TABLE [dbo].[LosLocalPurchaseHeader] CHECK CONSTRAINT [FK_LosLocalPurchaseHeader_CashBox]
GO
/****** Object:  ForeignKey [fk_loslocalpurchaseheader_lospurchaseorderheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseHeader]  WITH CHECK ADD  CONSTRAINT [fk_loslocalpurchaseheader_lospurchaseorderheader] FOREIGN KEY([lphPOID], [lphShopID])
REFERENCES [dbo].[losPurchaseOrderHeader] ([pohPoid], [pohShopid])
GO
ALTER TABLE [dbo].[LosLocalPurchaseHeader] CHECK CONSTRAINT [fk_loslocalpurchaseheader_lospurchaseorderheader]
GO
/****** Object:  ForeignKey [FK_LOsPaymentVoucherHeader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsPaymentVoucherHeader_aAccountMaster] FOREIGN KEY([phBankCashID], [phCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsPaymentVoucherHeader] CHECK CONSTRAINT [FK_LOsPaymentVoucherHeader_aAccountMaster]
GO
/****** Object:  ForeignKey [fk_LOsPaymentVoucherHeader_aaccountmaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_LOsPaymentVoucherHeader_aaccountmaster1] FOREIGN KEY([phdebitaccountid], [phCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsPaymentVoucherHeader] CHECK CONSTRAINT [fk_LOsPaymentVoucherHeader_aaccountmaster1]
GO
/****** Object:  ForeignKey [FK_LOsPaymentVoucherHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsPaymentVoucherHeader_aCompanyMaster] FOREIGN KEY([phCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[LOsPaymentVoucherHeader] CHECK CONSTRAINT [FK_LOsPaymentVoucherHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [fk_LOsPaymentVoucherHeader_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_LOsPaymentVoucherHeader_acustomermaster] FOREIGN KEY([phCustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[LOsPaymentVoucherHeader] CHECK CONSTRAINT [fk_LOsPaymentVoucherHeader_acustomermaster]
GO
/****** Object:  ForeignKey [fk_LOsPaymentVoucherHeader_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_LOsPaymentVoucherHeader_adepartmentmaster] FOREIGN KEY([phDepartmentID], [phCompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsPaymentVoucherHeader] CHECK CONSTRAINT [fk_LOsPaymentVoucherHeader_adepartmentmaster]
GO
/****** Object:  ForeignKey [fk_LOsPaymentVoucherHeader_afinancialyear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_LOsPaymentVoucherHeader_afinancialyear] FOREIGN KEY([phFinancialID], [phCompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsPaymentVoucherHeader] CHECK CONSTRAINT [fk_LOsPaymentVoucherHeader_afinancialyear]
GO
/****** Object:  ForeignKey [FK_LOsPaymentVoucherHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsPaymentVoucherHeader_aShops] FOREIGN KEY([phShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LOsPaymentVoucherHeader] CHECK CONSTRAINT [FK_LOsPaymentVoucherHeader_aShops]
GO
/****** Object:  ForeignKey [fk_LOsPaymentVoucherHeader_avendormaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_LOsPaymentVoucherHeader_avendormaster] FOREIGN KEY([phVendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[LOsPaymentVoucherHeader] CHECK CONSTRAINT [fk_LOsPaymentVoucherHeader_avendormaster]
GO
/****** Object:  ForeignKey [FK_LOsPaymentVoucherHeader_CashBox]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsPaymentVoucherHeader_CashBox] FOREIGN KEY([phcbid], [phShopID])
REFERENCES [dbo].[CashBox] ([CBID], [CBShopID])
GO
ALTER TABLE [dbo].[LOsPaymentVoucherHeader] CHECK CONSTRAINT [FK_LOsPaymentVoucherHeader_CashBox]
GO
/****** Object:  ForeignKey [FK_LOsAccountsInvoiceHeader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsAccountsInvoiceHeader_aAccountMaster] FOREIGN KEY([aiBankCashID], [aiCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] CHECK CONSTRAINT [FK_LOsAccountsInvoiceHeader_aAccountMaster]
GO
/****** Object:  ForeignKey [fk_LOsAccountsInvoiceHeader_aaccountmaster_sales]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [fk_LOsAccountsInvoiceHeader_aaccountmaster_sales] FOREIGN KEY([aiSalesAccID], [aiCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] CHECK CONSTRAINT [fk_LOsAccountsInvoiceHeader_aaccountmaster_sales]
GO
/****** Object:  ForeignKey [FK_LOsAccountsInvoiceHeader_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsAccountsInvoiceHeader_aAccountMaster1] FOREIGN KEY([aiDiscountAccountID], [aiCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] CHECK CONSTRAINT [FK_LOsAccountsInvoiceHeader_aAccountMaster1]
GO
/****** Object:  ForeignKey [fk_LOsAccountsInvoiceHeader_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [fk_LOsAccountsInvoiceHeader_acustomermaster] FOREIGN KEY([aiCustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] CHECK CONSTRAINT [fk_LOsAccountsInvoiceHeader_acustomermaster]
GO
/****** Object:  ForeignKey [FK_LOsAccountsInvoiceHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsAccountsInvoiceHeader_aDepartmentMaster] FOREIGN KEY([aiDepartmentID], [aiCompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] CHECK CONSTRAINT [FK_LOsAccountsInvoiceHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_LOsAccountsInvoiceHeader_aFinancialYear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsAccountsInvoiceHeader_aFinancialYear] FOREIGN KEY([aiFinancialID], [aiCompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] CHECK CONSTRAINT [FK_LOsAccountsInvoiceHeader_aFinancialYear]
GO
/****** Object:  ForeignKey [FK_LOsAccountsInvoiceHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsAccountsInvoiceHeader_aShops] FOREIGN KEY([aiShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] CHECK CONSTRAINT [FK_LOsAccountsInvoiceHeader_aShops]
GO
/****** Object:  ForeignKey [FK_LOsAccountsInvoiceHeader_CashBox]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsAccountsInvoiceHeader_CashBox] FOREIGN KEY([aicbid], [aiShopID])
REFERENCES [dbo].[CashBox] ([CBID], [CBShopID])
GO
ALTER TABLE [dbo].[LOsAccountsInvoiceHeader] CHECK CONSTRAINT [FK_LOsAccountsInvoiceHeader_CashBox]
GO
/****** Object:  ForeignKey [FK_discountdishdetails_Discountdetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[discountdishdetails]  WITH CHECK ADD  CONSTRAINT [FK_discountdishdetails_Discountdetails] FOREIGN KEY([companyid], [discountid], [Outletid])
REFERENCES [dbo].[Discountdetails] ([Companyid], [Discountid], [Outletid])
GO
ALTER TABLE [dbo].[discountdishdetails] CHECK CONSTRAINT [FK_discountdishdetails_Discountdetails]
GO
/****** Object:  ForeignKey [fk_ShipmentClearenceItemDetails_ClearenceRequestDetail]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ShipmentClearenceItemDetails]  WITH CHECK ADD  CONSTRAINT [fk_ShipmentClearenceItemDetails_ClearenceRequestDetail] FOREIGN KEY([ShopID], [ClearenceReqID], [ClearenceDetailID])
REFERENCES [dbo].[ClearenceRequestDetail] ([ShopID], [ClearenceReqID], [DetailID])
GO
ALTER TABLE [dbo].[ShipmentClearenceItemDetails] CHECK CONSTRAINT [fk_ShipmentClearenceItemDetails_ClearenceRequestDetail]
GO
/****** Object:  ForeignKey [fk_ShipmentClearenceItemDetails_ShipmentClearenceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ShipmentClearenceItemDetails]  WITH CHECK ADD  CONSTRAINT [fk_ShipmentClearenceItemDetails_ShipmentClearenceHeader] FOREIGN KEY([ShopID], [ClearenceID])
REFERENCES [dbo].[ShipmentClearenceHeader] ([ShopID], [ClearenceID])
GO
ALTER TABLE [dbo].[ShipmentClearenceItemDetails] CHECK CONSTRAINT [fk_ShipmentClearenceItemDetails_ShipmentClearenceHeader]
GO
/****** Object:  ForeignKey [FK_aHQPaymentVoucherDetails_aHQPaymentVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherDetails]  WITH CHECK ADD  CONSTRAINT [FK_aHQPaymentVoucherDetails_aHQPaymentVoucherHeader] FOREIGN KEY([pdPaymentID])
REFERENCES [dbo].[aHQPaymentVoucherHeader] ([phPaymentID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherDetails] CHECK CONSTRAINT [FK_aHQPaymentVoucherDetails_aHQPaymentVoucherHeader]
GO
/****** Object:  ForeignKey [FK_aHQPaymentVoucherDetails_Bills]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_aHQPaymentVoucherDetails_Bills] FOREIGN KEY([pdAccBillsID])
REFERENCES [dbo].[Bills] ([BillsID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherDetails] CHECK CONSTRAINT [FK_aHQPaymentVoucherDetails_Bills]
GO
/****** Object:  ForeignKey [fk_aHQPaymentVoucherDetails_debitcreditnote]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherDetails]  WITH CHECK ADD  CONSTRAINT [fk_aHQPaymentVoucherDetails_debitcreditnote] FOREIGN KEY([pddcnid])
REFERENCES [dbo].[DebitCreditNote] ([DCNId])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherDetails] CHECK CONSTRAINT [fk_aHQPaymentVoucherDetails_debitcreditnote]
GO
/****** Object:  ForeignKey [FK_aHQPaymentVoucherDetails_loPurchaseOrderHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_aHQPaymentVoucherDetails_loPurchaseOrderHeader] FOREIGN KEY([pdHQPOID])
REFERENCES [dbo].[loPurchaseOrderHeader] ([pohPoid])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherDetails] CHECK CONSTRAINT [FK_aHQPaymentVoucherDetails_loPurchaseOrderHeader]
GO
/****** Object:  ForeignKey [FK_aHQPaymentVoucherDetails_losDebitCreditNote]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherDetails]  WITH CHECK ADD  CONSTRAINT [FK_aHQPaymentVoucherDetails_losDebitCreditNote] FOREIGN KEY([pdshopid], [shopdcnid])
REFERENCES [dbo].[losDebitCreditNote] ([losDCNShopid], [losDCNId])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherDetails] CHECK CONSTRAINT [FK_aHQPaymentVoucherDetails_losDebitCreditNote]
GO
/****** Object:  ForeignKey [fk_aHQPaymentVoucherDetails_loslocalpurchaseheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherDetails]  WITH CHECK ADD  CONSTRAINT [fk_aHQPaymentVoucherDetails_loslocalpurchaseheader] FOREIGN KEY([pdshopid], [pdposlpbillid])
REFERENCES [dbo].[LosLocalPurchaseHeader] ([lphShopID], [lphBillID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherDetails] CHECK CONSTRAINT [fk_aHQPaymentVoucherDetails_loslocalpurchaseheader]
GO
/****** Object:  ForeignKey [FK_aHQPaymentVoucherDetails_LOspPurchaseBillHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherDetails]  WITH CHECK ADD  CONSTRAINT [FK_aHQPaymentVoucherDetails_LOspPurchaseBillHeader] FOREIGN KEY([pdBillsID])
REFERENCES [dbo].[LOspPurchaseBillHeader] ([pbhBillID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherDetails] CHECK CONSTRAINT [FK_aHQPaymentVoucherDetails_LOspPurchaseBillHeader]
GO
/****** Object:  ForeignKey [FK_aHQPaymentVoucherDetails_ReceiptVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherDetails]  WITH CHECK ADD  CONSTRAINT [FK_aHQPaymentVoucherDetails_ReceiptVoucherHeader] FOREIGN KEY([pdreceiptid])
REFERENCES [dbo].[ReceiptVoucherHeader] ([ReceiptID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherDetails] CHECK CONSTRAINT [FK_aHQPaymentVoucherDetails_ReceiptVoucherHeader]
GO
/****** Object:  ForeignKey [FK_VendorSettlementDetail_Bills]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VendorSettlementDetail]  WITH NOCHECK ADD  CONSTRAINT [FK_VendorSettlementDetail_Bills] FOREIGN KEY([BillID])
REFERENCES [dbo].[Bills] ([BillsID])
GO
ALTER TABLE [dbo].[VendorSettlementDetail] CHECK CONSTRAINT [FK_VendorSettlementDetail_Bills]
GO
/****** Object:  ForeignKey [FK_VendorSettlementDetail_DebitCreditNote]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VendorSettlementDetail]  WITH CHECK ADD  CONSTRAINT [FK_VendorSettlementDetail_DebitCreditNote] FOREIGN KEY([dcnid])
REFERENCES [dbo].[DebitCreditNote] ([DCNId])
GO
ALTER TABLE [dbo].[VendorSettlementDetail] CHECK CONSTRAINT [FK_VendorSettlementDetail_DebitCreditNote]
GO
/****** Object:  ForeignKey [FK_VendorSettlementDetail_losDebitCreditNote]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VendorSettlementDetail]  WITH CHECK ADD  CONSTRAINT [FK_VendorSettlementDetail_losDebitCreditNote] FOREIGN KEY([shopid], [losdcnid])
REFERENCES [dbo].[losDebitCreditNote] ([losDCNShopid], [losDCNId])
GO
ALTER TABLE [dbo].[VendorSettlementDetail] CHECK CONSTRAINT [FK_VendorSettlementDetail_losDebitCreditNote]
GO
/****** Object:  ForeignKey [FK_VendorSettlementDetail_LosLocalPurchaseHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VendorSettlementDetail]  WITH CHECK ADD  CONSTRAINT [FK_VendorSettlementDetail_LosLocalPurchaseHeader] FOREIGN KEY([shopid], [lphbillid])
REFERENCES [dbo].[LosLocalPurchaseHeader] ([lphShopID], [lphBillID])
GO
ALTER TABLE [dbo].[VendorSettlementDetail] CHECK CONSTRAINT [FK_VendorSettlementDetail_LosLocalPurchaseHeader]
GO
/****** Object:  ForeignKey [FK_VendorSettlementDetail_LOspPurchaseBillHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VendorSettlementDetail]  WITH CHECK ADD  CONSTRAINT [FK_VendorSettlementDetail_LOspPurchaseBillHeader] FOREIGN KEY([pbhbillid])
REFERENCES [dbo].[LOspPurchaseBillHeader] ([pbhBillID])
GO
ALTER TABLE [dbo].[VendorSettlementDetail] CHECK CONSTRAINT [FK_VendorSettlementDetail_LOspPurchaseBillHeader]
GO
/****** Object:  ForeignKey [FK_VendorSettlementDetail_ReceiptVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VendorSettlementDetail]  WITH CHECK ADD  CONSTRAINT [FK_VendorSettlementDetail_ReceiptVoucherHeader] FOREIGN KEY([receiptid])
REFERENCES [dbo].[ReceiptVoucherHeader] ([ReceiptID])
GO
ALTER TABLE [dbo].[VendorSettlementDetail] CHECK CONSTRAINT [FK_VendorSettlementDetail_ReceiptVoucherHeader]
GO
/****** Object:  ForeignKey [FK_VendorSettlementDetail_VendorSettlementHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VendorSettlementDetail]  WITH CHECK ADD  CONSTRAINT [FK_VendorSettlementDetail_VendorSettlementHeader] FOREIGN KEY([VSID])
REFERENCES [dbo].[VendorSettlementHeader] ([VSID])
GO
ALTER TABLE [dbo].[VendorSettlementDetail] CHECK CONSTRAINT [FK_VendorSettlementDetail_VendorSettlementHeader]
GO
/****** Object:  ForeignKey [FK_VendorSettlementHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VendorSettlementHeader]  WITH CHECK ADD  CONSTRAINT [FK_VendorSettlementHeader_aDepartmentMaster] FOREIGN KEY([DepartmentID], [CompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[VendorSettlementHeader] CHECK CONSTRAINT [FK_VendorSettlementHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_VendorSettlementHeader_aFinancialYear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VendorSettlementHeader]  WITH CHECK ADD  CONSTRAINT [FK_VendorSettlementHeader_aFinancialYear] FOREIGN KEY([FinancialID], [CompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[VendorSettlementHeader] CHECK CONSTRAINT [FK_VendorSettlementHeader_aFinancialYear]
GO
/****** Object:  ForeignKey [FK_VendorSettlementHeader_aHQPaymentVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VendorSettlementHeader]  WITH CHECK ADD  CONSTRAINT [FK_VendorSettlementHeader_aHQPaymentVoucherHeader] FOREIGN KEY([PaymentID])
REFERENCES [dbo].[aHQPaymentVoucherHeader] ([phPaymentID])
GO
ALTER TABLE [dbo].[VendorSettlementHeader] CHECK CONSTRAINT [FK_VendorSettlementHeader_aHQPaymentVoucherHeader]
GO
/****** Object:  ForeignKey [fk_vendorsettlementheader_avendormaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VendorSettlementHeader]  WITH CHECK ADD  CONSTRAINT [fk_vendorsettlementheader_avendormaster] FOREIGN KEY([VendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[VendorSettlementHeader] CHECK CONSTRAINT [fk_vendorsettlementheader_avendormaster]
GO
/****** Object:  ForeignKey [FK_VendorSettlementHeader_DebitCreditNote]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VendorSettlementHeader]  WITH CHECK ADD  CONSTRAINT [FK_VendorSettlementHeader_DebitCreditNote] FOREIGN KEY([dcnid])
REFERENCES [dbo].[DebitCreditNote] ([DCNId])
GO
ALTER TABLE [dbo].[VendorSettlementHeader] CHECK CONSTRAINT [FK_VendorSettlementHeader_DebitCreditNote]
GO
/****** Object:  ForeignKey [FK_VendorSettlementHeader_losDebitCreditNote]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VendorSettlementHeader]  WITH CHECK ADD  CONSTRAINT [FK_VendorSettlementHeader_losDebitCreditNote] FOREIGN KEY([shopid], [losdcnid])
REFERENCES [dbo].[losDebitCreditNote] ([losDCNShopid], [losDCNId])
GO
ALTER TABLE [dbo].[VendorSettlementHeader] CHECK CONSTRAINT [FK_VendorSettlementHeader_losDebitCreditNote]
GO
/****** Object:  ForeignKey [FK_VendorSettlementHeader_LOsPaymentVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VendorSettlementHeader]  WITH CHECK ADD  CONSTRAINT [FK_VendorSettlementHeader_LOsPaymentVoucherHeader] FOREIGN KEY([lospaymentid], [shopid])
REFERENCES [dbo].[LOsPaymentVoucherHeader] ([phPaymentID], [phShopID])
GO
ALTER TABLE [dbo].[VendorSettlementHeader] CHECK CONSTRAINT [FK_VendorSettlementHeader_LOsPaymentVoucherHeader]
GO
/****** Object:  ForeignKey [FK_loaInhousePurchaseDetail_loaInhousePurchaseHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loaInhousePurchaseDetail]  WITH CHECK ADD  CONSTRAINT [FK_loaInhousePurchaseDetail_loaInhousePurchaseHeader] FOREIGN KEY([ipdid])
REFERENCES [dbo].[loaInhousePurchaseHeader] ([iphId])
GO
ALTER TABLE [dbo].[loaInhousePurchaseDetail] CHECK CONSTRAINT [FK_loaInhousePurchaseDetail_loaInhousePurchaseHeader]
GO
/****** Object:  ForeignKey [FK_TillHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[TillHeader]  WITH CHECK ADD  CONSTRAINT [FK_TillHeader_aCompanyMaster] FOREIGN KEY([till_th_companyid])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[TillHeader] CHECK CONSTRAINT [FK_TillHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_TillHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[TillHeader]  WITH CHECK ADD  CONSTRAINT [FK_TillHeader_aShops] FOREIGN KEY([till_th_outletid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[TillHeader] CHECK CONSTRAINT [FK_TillHeader_aShops]
GO
/****** Object:  ForeignKey [FK_TillHeader_LOUsers]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[TillHeader]  WITH CHECK ADD  CONSTRAINT [FK_TillHeader_LOUsers] FOREIGN KEY([till_th_cashierid])
REFERENCES [dbo].[LOUsers] ([UserID])
GO
ALTER TABLE [dbo].[TillHeader] CHECK CONSTRAINT [FK_TillHeader_LOUsers]
GO
/****** Object:  ForeignKey [FK_TillHistory_CreateModify_User]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[TillHistory]  WITH CHECK ADD  CONSTRAINT [FK_TillHistory_CreateModify_User] FOREIGN KEY([till_createmodify_user])
REFERENCES [dbo].[LOUsers] ([UserID])
GO
ALTER TABLE [dbo].[TillHistory] CHECK CONSTRAINT [FK_TillHistory_CreateModify_User]
GO
/****** Object:  ForeignKey [FK_TillHistory_LOUsers]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[TillHistory]  WITH CHECK ADD  CONSTRAINT [FK_TillHistory_LOUsers] FOREIGN KEY([till_cashierid])
REFERENCES [dbo].[LOUsers] ([UserID])
GO
ALTER TABLE [dbo].[TillHistory] CHECK CONSTRAINT [FK_TillHistory_LOUsers]
GO
/****** Object:  ForeignKey [FK_TillHistory_LOUsers_ManagerUser]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[TillHistory]  WITH CHECK ADD  CONSTRAINT [FK_TillHistory_LOUsers_ManagerUser] FOREIGN KEY([till_managerid])
REFERENCES [dbo].[LOUsers] ([UserID])
GO
ALTER TABLE [dbo].[TillHistory] CHECK CONSTRAINT [FK_TillHistory_LOUsers_ManagerUser]
GO
/****** Object:  ForeignKey [FK_TillHistory_TillHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[TillHistory]  WITH CHECK ADD  CONSTRAINT [FK_TillHistory_TillHeader] FOREIGN KEY([till_id], [till_outletid], [till_companyid])
REFERENCES [dbo].[TillHeader] ([till_th_tillid], [till_th_outletid], [till_th_companyid])
GO
ALTER TABLE [dbo].[TillHistory] CHECK CONSTRAINT [FK_TillHistory_TillHeader]
GO
/****** Object:  ForeignKey [FK_TillHistory_TillStatusMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[TillHistory]  WITH CHECK ADD  CONSTRAINT [FK_TillHistory_TillStatusMaster] FOREIGN KEY([till_statusid])
REFERENCES [dbo].[TillStatusMaster] ([tillstatus_id])
GO
ALTER TABLE [dbo].[TillHistory] CHECK CONSTRAINT [FK_TillHistory_TillStatusMaster]
GO
/****** Object:  ForeignKey [fk_LOUserRights_ainterface]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOUserRights]  WITH CHECK ADD  CONSTRAINT [fk_LOUserRights_ainterface] FOREIGN KEY([InterfaceID], [CompanyID])
REFERENCES [dbo].[aInterface] ([InterfaceID], [CompanyID])
GO
ALTER TABLE [dbo].[LOUserRights] CHECK CONSTRAINT [fk_LOUserRights_ainterface]
GO
/****** Object:  ForeignKey [FK_LOUserRights_LOUsers]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOUserRights]  WITH CHECK ADD  CONSTRAINT [FK_LOUserRights_LOUsers] FOREIGN KEY([UserID])
REFERENCES [dbo].[LOUsers] ([UserID])
GO
ALTER TABLE [dbo].[LOUserRights] CHECK CONSTRAINT [FK_LOUserRights_LOUsers]
GO
/****** Object:  ForeignKey [FK_LOUsers_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOUsers]  WITH CHECK ADD  CONSTRAINT [FK_LOUsers_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[LOUsers] CHECK CONSTRAINT [FK_LOUsers_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_LOUsers_aGlobalUsers]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOUsers]  WITH CHECK ADD  CONSTRAINT [FK_LOUsers_aGlobalUsers] FOREIGN KEY([GlobalUserID])
REFERENCES [dbo].[aGlobalUsers] ([UserID])
GO
ALTER TABLE [dbo].[LOUsers] CHECK CONSTRAINT [FK_LOUsers_aGlobalUsers]
GO
/****** Object:  ForeignKey [FK_LOUsers_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOUsers]  WITH CHECK ADD  CONSTRAINT [FK_LOUsers_aGodown] FOREIGN KEY([GodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[LOUsers] CHECK CONSTRAINT [FK_LOUsers_aGodown]
GO
/****** Object:  ForeignKey [FK_LOUsers_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOUsers]  WITH CHECK ADD  CONSTRAINT [FK_LOUsers_aShops] FOREIGN KEY([ShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LOUsers] CHECK CONSTRAINT [FK_LOUsers_aShops]
GO
/****** Object:  ForeignKey [FK_MEmessages_aGlobalUsers]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEmessages]  WITH CHECK ADD  CONSTRAINT [FK_MEmessages_aGlobalUsers] FOREIGN KEY([fromUserID])
REFERENCES [dbo].[aGlobalUsers] ([UserID])
GO
ALTER TABLE [dbo].[MEmessages] CHECK CONSTRAINT [FK_MEmessages_aGlobalUsers]
GO
/****** Object:  ForeignKey [FK_MEmessages_aGlobalUsers1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEmessages]  WITH CHECK ADD  CONSTRAINT [FK_MEmessages_aGlobalUsers1] FOREIGN KEY([toUserID])
REFERENCES [dbo].[aGlobalUsers] ([UserID])
GO
ALTER TABLE [dbo].[MEmessages] CHECK CONSTRAINT [FK_MEmessages_aGlobalUsers1]
GO
/****** Object:  ForeignKey [fk_loaitemsplitcostingheader_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loaItemsplitcostingHeader]  WITH CHECK ADD  CONSTRAINT [fk_loaitemsplitcostingheader_adepartmentmaster] FOREIGN KEY([scfhdepartmentid], [scfhcompanyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[loaItemsplitcostingHeader] CHECK CONSTRAINT [fk_loaitemsplitcostingheader_adepartmentmaster]
GO
/****** Object:  ForeignKey [fk_loaItemsplitCostingHeader_ashipment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loaItemsplitcostingHeader]  WITH CHECK ADD  CONSTRAINT [fk_loaItemsplitCostingHeader_ashipment] FOREIGN KEY([scfhShipmentid])
REFERENCES [dbo].[aShipment] ([sShipmentID])
GO
ALTER TABLE [dbo].[loaItemsplitcostingHeader] CHECK CONSTRAINT [fk_loaItemsplitCostingHeader_ashipment]
GO
/****** Object:  ForeignKey [FK_loaItemsplitcostingHeader_LOaCostingHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loaItemsplitcostingHeader]  WITH CHECK ADD  CONSTRAINT [FK_loaItemsplitcostingHeader_LOaCostingHeader] FOREIGN KEY([scfhCostingId])
REFERENCES [dbo].[LOaCostingHeader] ([chCostingID])
GO
ALTER TABLE [dbo].[loaItemsplitcostingHeader] CHECK CONSTRAINT [FK_loaItemsplitcostingHeader_LOaCostingHeader]
GO
/****** Object:  ForeignKey [FK_loaItemsplitcostingHeader_LoiItemSplitHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loaItemsplitcostingHeader]  WITH CHECK ADD  CONSTRAINT [FK_loaItemsplitcostingHeader_LoiItemSplitHeader] FOREIGN KEY([scfhGodownid], [scfhItemSplitId])
REFERENCES [dbo].[LoiItemSplitHeader] ([ishgodownid], [ishid])
GO
ALTER TABLE [dbo].[loaItemsplitcostingHeader] CHECK CONSTRAINT [FK_loaItemsplitcostingHeader_LoiItemSplitHeader]
GO
/****** Object:  ForeignKey [FK_LOaCostingDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOaCostingDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOaCostingDetail_aItem] FOREIGN KEY([cdItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOaCostingDetail] CHECK CONSTRAINT [FK_LOaCostingDetail_aItem]
GO
/****** Object:  ForeignKey [FK_LOaCostingDetail_LOaCostingHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOaCostingDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOaCostingDetail_LOaCostingHeader] FOREIGN KEY([cdCostingID])
REFERENCES [dbo].[LOaCostingHeader] ([chCostingID])
GO
ALTER TABLE [dbo].[LOaCostingDetail] CHECK CONSTRAINT [FK_LOaCostingDetail_LOaCostingHeader]
GO
/****** Object:  ForeignKey [FK_LOaCostingAccountDetails_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOaCostingAccountDetails]  WITH CHECK ADD  CONSTRAINT [FK_LOaCostingAccountDetails_aAccountMaster] FOREIGN KEY([cadAccountID], [cadCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOaCostingAccountDetails] CHECK CONSTRAINT [FK_LOaCostingAccountDetails_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_LOaCostingAccountDetails_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOaCostingAccountDetails]  WITH CHECK ADD  CONSTRAINT [FK_LOaCostingAccountDetails_aAccountMaster1] FOREIGN KEY([cadBankCashAccID], [cadCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOaCostingAccountDetails] CHECK CONSTRAINT [FK_LOaCostingAccountDetails_aAccountMaster1]
GO
/****** Object:  ForeignKey [FK_LOaCostingAccountDetails_LOaCostingHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOaCostingAccountDetails]  WITH CHECK ADD  CONSTRAINT [FK_LOaCostingAccountDetails_LOaCostingHeader] FOREIGN KEY([cadCostingID])
REFERENCES [dbo].[LOaCostingHeader] ([chCostingID])
GO
ALTER TABLE [dbo].[LOaCostingAccountDetails] CHECK CONSTRAINT [FK_LOaCostingAccountDetails_LOaCostingHeader]
GO
/****** Object:  ForeignKey [fk_aStatus_aStatusGroup]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aStatus]  WITH CHECK ADD  CONSTRAINT [fk_aStatus_aStatusGroup] FOREIGN KEY([CompanyId], [StatusGroupId])
REFERENCES [dbo].[aStatusGroup] ([CompanyId], [StatusGroupId])
GO
ALTER TABLE [dbo].[aStatus] CHECK CONSTRAINT [fk_aStatus_aStatusGroup]
GO
/****** Object:  ForeignKey [FK_LOiArrivaltoLocation_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivaltoLocation]  WITH CHECK ADD  CONSTRAINT [FK_LOiArrivaltoLocation_aItem] FOREIGN KEY([alItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOiArrivaltoLocation] CHECK CONSTRAINT [FK_LOiArrivaltoLocation_aItem]
GO
/****** Object:  ForeignKey [FK_LOiArrivaltoLocation_LOiArrivalHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivaltoLocation]  WITH CHECK ADD  CONSTRAINT [FK_LOiArrivaltoLocation_LOiArrivalHeader] FOREIGN KEY([alArrivalID], [alGodownID])
REFERENCES [dbo].[LOiArrivalHeader] ([ahArrivalID], [ahLocalGodownID])
GO
ALTER TABLE [dbo].[LOiArrivaltoLocation] CHECK CONSTRAINT [FK_LOiArrivaltoLocation_LOiArrivalHeader]
GO
/****** Object:  ForeignKey [FK_LOiArrivaltoLocation_LOiLocation1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivaltoLocation]  WITH CHECK ADD  CONSTRAINT [FK_LOiArrivaltoLocation_LOiLocation1] FOREIGN KEY([alGodownID], [alLocationID])
REFERENCES [dbo].[LOiLocation] ([lGodownID], [lLocationID])
GO
ALTER TABLE [dbo].[LOiArrivaltoLocation] CHECK CONSTRAINT [FK_LOiArrivaltoLocation_LOiLocation1]
GO
/****** Object:  ForeignKey [FK_LOiGodownShopArrivalToLocation_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiGodownShopArrivalToLocation]  WITH CHECK ADD  CONSTRAINT [FK_LOiGodownShopArrivalToLocation_aItem] FOREIGN KEY([gsalItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOiGodownShopArrivalToLocation] CHECK CONSTRAINT [FK_LOiGodownShopArrivalToLocation_aItem]
GO
/****** Object:  ForeignKey [FK_LOiGodownShopArrivalToLocation_LOiArrivalHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiGodownShopArrivalToLocation]  WITH CHECK ADD  CONSTRAINT [FK_LOiGodownShopArrivalToLocation_LOiArrivalHeader] FOREIGN KEY([gsalArrivalID], [gsalGodownID])
REFERENCES [dbo].[LOiArrivalHeader] ([ahArrivalID], [ahLocalGodownID])
GO
ALTER TABLE [dbo].[LOiGodownShopArrivalToLocation] CHECK CONSTRAINT [FK_LOiGodownShopArrivalToLocation_LOiArrivalHeader]
GO
/****** Object:  ForeignKey [FK_LOiGodownShopArrivalToLocation_LOiLocation]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiGodownShopArrivalToLocation]  WITH CHECK ADD  CONSTRAINT [FK_LOiGodownShopArrivalToLocation_LOiLocation] FOREIGN KEY([gsalGodownID], [gsalLocationID])
REFERENCES [dbo].[LOiLocation] ([lGodownID], [lLocationID])
GO
ALTER TABLE [dbo].[LOiGodownShopArrivalToLocation] CHECK CONSTRAINT [FK_LOiGodownShopArrivalToLocation_LOiLocation]
GO
/****** Object:  ForeignKey [FK_LOiArrivalShipmentDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalShipmentDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOiArrivalShipmentDetail_aItem] FOREIGN KEY([asdItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOiArrivalShipmentDetail] CHECK CONSTRAINT [FK_LOiArrivalShipmentDetail_aItem]
GO
/****** Object:  ForeignKey [FK_LOiArrivalShipmentDetail_LOiArrivalHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalShipmentDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOiArrivalShipmentDetail_LOiArrivalHeader] FOREIGN KEY([asdArrivalID], [asdGodownID])
REFERENCES [dbo].[LOiArrivalHeader] ([ahArrivalID], [ahLocalGodownID])
GO
ALTER TABLE [dbo].[LOiArrivalShipmentDetail] CHECK CONSTRAINT [FK_LOiArrivalShipmentDetail_LOiArrivalHeader]
GO
/****** Object:  ForeignKey [FK_LOiArrivalDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOiArrivalDetail_aItem] FOREIGN KEY([adItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOiArrivalDetail] CHECK CONSTRAINT [FK_LOiArrivalDetail_aItem]
GO
/****** Object:  ForeignKey [FK_LOiArrivalDetail_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOiArrivalDetail_aPackingType] FOREIGN KEY([adPackingTypeID])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[LOiArrivalDetail] CHECK CONSTRAINT [FK_LOiArrivalDetail_aPackingType]
GO
/****** Object:  ForeignKey [FK_LOiArrivalDetail_LOiArrivalHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOiArrivalDetail_LOiArrivalHeader] FOREIGN KEY([adArrivalID], [adGodownID])
REFERENCES [dbo].[LOiArrivalHeader] ([ahArrivalID], [ahLocalGodownID])
GO
ALTER TABLE [dbo].[LOiArrivalDetail] CHECK CONSTRAINT [FK_LOiArrivalDetail_LOiArrivalHeader]
GO
/****** Object:  ForeignKey [FK_LoiItemSplitHeader_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LoiItemSplitHeader]  WITH CHECK ADD  CONSTRAINT [FK_LoiItemSplitHeader_aGodown] FOREIGN KEY([ishgodownid])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[LoiItemSplitHeader] CHECK CONSTRAINT [FK_LoiItemSplitHeader_aGodown]
GO
/****** Object:  ForeignKey [FK_LoiItemSplitHeader_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LoiItemSplitHeader]  WITH CHECK ADD  CONSTRAINT [FK_LoiItemSplitHeader_aItem] FOREIGN KEY([ishSplititemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LoiItemSplitHeader] CHECK CONSTRAINT [FK_LoiItemSplitHeader_aItem]
GO
/****** Object:  ForeignKey [fk_loiItemSplitHeader_ashipment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LoiItemSplitHeader]  WITH CHECK ADD  CONSTRAINT [fk_loiItemSplitHeader_ashipment] FOREIGN KEY([ishshipmentid])
REFERENCES [dbo].[aShipment] ([sShipmentID])
GO
ALTER TABLE [dbo].[LoiItemSplitHeader] CHECK CONSTRAINT [fk_loiItemSplitHeader_ashipment]
GO
/****** Object:  ForeignKey [fk_loiItemSplitHeader_loiarrivalheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LoiItemSplitHeader]  WITH CHECK ADD  CONSTRAINT [fk_loiItemSplitHeader_loiarrivalheader] FOREIGN KEY([ishArrivalID], [ishgodownid])
REFERENCES [dbo].[LOiArrivalHeader] ([ahArrivalID], [ahLocalGodownID])
GO
ALTER TABLE [dbo].[LoiItemSplitHeader] CHECK CONSTRAINT [fk_loiItemSplitHeader_loiarrivalheader]
GO
/****** Object:  ForeignKey [FK_loslocationissuedetails_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loslocationissuedetails]  WITH CHECK ADD  CONSTRAINT [FK_loslocationissuedetails_aItem] FOREIGN KEY([liditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[loslocationissuedetails] CHECK CONSTRAINT [FK_loslocationissuedetails_aItem]
GO
/****** Object:  ForeignKey [FK_loslocationissuedetails_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loslocationissuedetails]  WITH CHECK ADD  CONSTRAINT [FK_loslocationissuedetails_aPackingType] FOREIGN KEY([lidpackingtypeid])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[loslocationissuedetails] CHECK CONSTRAINT [FK_loslocationissuedetails_aPackingType]
GO
/****** Object:  ForeignKey [FK_loslocationissuedetails_loslocation]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loslocationissuedetails]  WITH CHECK ADD  CONSTRAINT [FK_loslocationissuedetails_loslocation] FOREIGN KEY([lidshopid], [lidlocationid])
REFERENCES [dbo].[loslocation] ([lshopiD], [lLocationID])
GO
ALTER TABLE [dbo].[loslocationissuedetails] CHECK CONSTRAINT [FK_loslocationissuedetails_loslocation]
GO
/****** Object:  ForeignKey [FK_loslocationarrivaldetails_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loslocationarrivaldetails]  WITH CHECK ADD  CONSTRAINT [FK_loslocationarrivaldetails_aItem] FOREIGN KEY([laditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[loslocationarrivaldetails] CHECK CONSTRAINT [FK_loslocationarrivaldetails_aItem]
GO
/****** Object:  ForeignKey [FK_loslocationarrivaldetails_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loslocationarrivaldetails]  WITH CHECK ADD  CONSTRAINT [FK_loslocationarrivaldetails_aPackingType] FOREIGN KEY([ladpackingtypeid])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[loslocationarrivaldetails] CHECK CONSTRAINT [FK_loslocationarrivaldetails_aPackingType]
GO
/****** Object:  ForeignKey [FK_loslocationarrivaldetails_loslocation]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loslocationarrivaldetails]  WITH CHECK ADD  CONSTRAINT [FK_loslocationarrivaldetails_loslocation] FOREIGN KEY([ladshopid], [ladlocationid])
REFERENCES [dbo].[loslocation] ([lshopiD], [lLocationID])
GO
ALTER TABLE [dbo].[loslocationarrivaldetails] CHECK CONSTRAINT [FK_loslocationarrivaldetails_loslocation]
GO
/****** Object:  ForeignKey [FK_LOiDamageClearingDetails_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiDamageClearingDetails]  WITH CHECK ADD  CONSTRAINT [FK_LOiDamageClearingDetails_aItem] FOREIGN KEY([dcdItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOiDamageClearingDetails] CHECK CONSTRAINT [FK_LOiDamageClearingDetails_aItem]
GO
/****** Object:  ForeignKey [fk_LoiDamageClearingDetails_ashipment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiDamageClearingDetails]  WITH CHECK ADD  CONSTRAINT [fk_LoiDamageClearingDetails_ashipment] FOREIGN KEY([dcdShipmentID])
REFERENCES [dbo].[aShipment] ([sShipmentID])
GO
ALTER TABLE [dbo].[LOiDamageClearingDetails] CHECK CONSTRAINT [fk_LoiDamageClearingDetails_ashipment]
GO
/****** Object:  ForeignKey [FK_LOiDamageClearingDetails_LOiDamageClearingHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiDamageClearingDetails]  WITH CHECK ADD  CONSTRAINT [FK_LOiDamageClearingDetails_LOiDamageClearingHeader] FOREIGN KEY([dcdClearingID], [dcdGodownid])
REFERENCES [dbo].[LOiDamageClearingHeader] ([dchClearingID], [dchGodownid])
GO
ALTER TABLE [dbo].[LOiDamageClearingDetails] CHECK CONSTRAINT [FK_LOiDamageClearingDetails_LOiDamageClearingHeader]
GO
/****** Object:  ForeignKey [fk_LoiDamageClearingDetails_loilocation]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiDamageClearingDetails]  WITH CHECK ADD  CONSTRAINT [fk_LoiDamageClearingDetails_loilocation] FOREIGN KEY([dcdGodownid], [dcdLocationID])
REFERENCES [dbo].[LOiLocation] ([lGodownID], [lLocationID])
GO
ALTER TABLE [dbo].[LOiDamageClearingDetails] CHECK CONSTRAINT [fk_LoiDamageClearingDetails_loilocation]
GO
/****** Object:  ForeignKey [FK_aHPItemTransferDetail_aHPItemTransferHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHPItemTransferDetail]  WITH CHECK ADD  CONSTRAINT [FK_aHPItemTransferDetail_aHPItemTransferHeader] FOREIGN KEY([itdCompanyID], [itdFinancialID], [itdTransferID])
REFERENCES [dbo].[aHPItemTransferHeader] ([ithCompanyID], [ithFinancialID], [ithTransferID])
GO
ALTER TABLE [dbo].[aHPItemTransferDetail] CHECK CONSTRAINT [FK_aHPItemTransferDetail_aHPItemTransferHeader]
GO
/****** Object:  ForeignKey [FK_LOs_InHouseCons_ReturnDetail_LOs_InHouseCons_ReturnHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOs_InHouseCons_ReturnDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOs_InHouseCons_ReturnDetail_LOs_InHouseCons_ReturnHeader] FOREIGN KEY([IHRDShopID], [IHRDID])
REFERENCES [dbo].[LOs_InHouseCons_ReturnHeader] ([IHRHShopID], [IHRHID])
GO
ALTER TABLE [dbo].[LOs_InHouseCons_ReturnDetail] CHECK CONSTRAINT [FK_LOs_InHouseCons_ReturnDetail_LOs_InHouseCons_ReturnHeader]
GO
/****** Object:  ForeignKey [FK_losposExchangeOtherCharges_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeOtherCharges]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeOtherCharges_aAccountMaster] FOREIGN KEY([seoAccID], [seoCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[losposExchangeOtherCharges] CHECK CONSTRAINT [FK_losposExchangeOtherCharges_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_losposExchangeOtherCharges_losposExchangeHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeOtherCharges]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeOtherCharges_losposExchangeHeader] FOREIGN KEY([seoShopID], [seoExchangeID])
REFERENCES [dbo].[losposExchangeHeader] ([sehShopID], [sehExchangeID])
GO
ALTER TABLE [dbo].[losposExchangeOtherCharges] CHECK CONSTRAINT [FK_losposExchangeOtherCharges_losposExchangeHeader]
GO
/****** Object:  ForeignKey [FK_losposExchangeDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeDetail]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeDetail_aItem] FOREIGN KEY([sedItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losposExchangeDetail] CHECK CONSTRAINT [FK_losposExchangeDetail_aItem]
GO
/****** Object:  ForeignKey [FK_losposExchangeDetail_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeDetail]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeDetail_aPackingType] FOREIGN KEY([sedPackingTypeID])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[losposExchangeDetail] CHECK CONSTRAINT [FK_losposExchangeDetail_aPackingType]
GO
/****** Object:  ForeignKey [FK_losposExchangeDetail_aUnit]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeDetail]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeDetail_aUnit] FOREIGN KEY([sedPUnitID])
REFERENCES [dbo].[aUnit] ([UnitID])
GO
ALTER TABLE [dbo].[losposExchangeDetail] CHECK CONSTRAINT [FK_losposExchangeDetail_aUnit]
GO
/****** Object:  ForeignKey [FK_losposExchangeDetail_losposExchangeHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeDetail]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeDetail_losposExchangeHeader] FOREIGN KEY([sedShopID], [sedExchangeID])
REFERENCES [dbo].[losposExchangeHeader] ([sehShopID], [sehExchangeID])
GO
ALTER TABLE [dbo].[losposExchangeDetail] CHECK CONSTRAINT [FK_losposExchangeDetail_losposExchangeHeader]
GO
/****** Object:  ForeignKey [FK_losposExchangeSubItemDetails_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeSubItemDetails]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeSubItemDetails_aItem] FOREIGN KEY([seidItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losposExchangeSubItemDetails] CHECK CONSTRAINT [FK_losposExchangeSubItemDetails_aItem]
GO
/****** Object:  ForeignKey [FK_losposExchangeSubItemDetails_aItem1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeSubItemDetails]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeSubItemDetails_aItem1] FOREIGN KEY([seidSubItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losposExchangeSubItemDetails] CHECK CONSTRAINT [FK_losposExchangeSubItemDetails_aItem1]
GO
/****** Object:  ForeignKey [FK_losposExchangeSubItemDetails_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeSubItemDetails]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeSubItemDetails_aPackingType] FOREIGN KEY([seidPackingTypeID])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[losposExchangeSubItemDetails] CHECK CONSTRAINT [FK_losposExchangeSubItemDetails_aPackingType]
GO
/****** Object:  ForeignKey [FK_losposExchangeSubItemDetails_losposExchangeHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losposExchangeSubItemDetails]  WITH CHECK ADD  CONSTRAINT [FK_losposExchangeSubItemDetails_losposExchangeHeader] FOREIGN KEY([seidShopID], [seidExchangeID])
REFERENCES [dbo].[losposExchangeHeader] ([sehShopID], [sehExchangeID])
GO
ALTER TABLE [dbo].[losposExchangeSubItemDetails] CHECK CONSTRAINT [FK_losposExchangeSubItemDetails_losposExchangeHeader]
GO
/****** Object:  ForeignKey [FK_losPurchaseOrderDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderDetail]  WITH CHECK ADD  CONSTRAINT [FK_losPurchaseOrderDetail_aItem] FOREIGN KEY([poditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losPurchaseOrderDetail] CHECK CONSTRAINT [FK_losPurchaseOrderDetail_aItem]
GO
/****** Object:  ForeignKey [FK_losPurchaseOrderDetail_losPurchaseOrderHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderDetail]  WITH CHECK ADD  CONSTRAINT [FK_losPurchaseOrderDetail_losPurchaseOrderHeader] FOREIGN KEY([podPoid], [podShopid])
REFERENCES [dbo].[losPurchaseOrderHeader] ([pohPoid], [pohShopid])
GO
ALTER TABLE [dbo].[losPurchaseOrderDetail] CHECK CONSTRAINT [FK_losPurchaseOrderDetail_losPurchaseOrderHeader]
GO
/****** Object:  ForeignKey [FK_losrebateconfirmheader_losrebaterequest]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losrebateconfirmheader]  WITH CHECK ADD  CONSTRAINT [FK_losrebateconfirmheader_losrebaterequest] FOREIGN KEY([rcshopid], [rcreqid])
REFERENCES [dbo].[losrebaterequest] ([rrshopid], [rrreqid])
GO
ALTER TABLE [dbo].[losrebateconfirmheader] CHECK CONSTRAINT [FK_losrebateconfirmheader_losrebaterequest]
GO
/****** Object:  ForeignKey [FK_LOiWriteOffDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiWriteOffDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOiWriteOffDetail_aItem] FOREIGN KEY([wdItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOiWriteOffDetail] CHECK CONSTRAINT [FK_LOiWriteOffDetail_aItem]
GO
/****** Object:  ForeignKey [fk_loiwriteoffdetail_ashipment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiWriteOffDetail]  WITH CHECK ADD  CONSTRAINT [fk_loiwriteoffdetail_ashipment] FOREIGN KEY([wdShipmentID])
REFERENCES [dbo].[aShipment] ([sShipmentID])
GO
ALTER TABLE [dbo].[LOiWriteOffDetail] CHECK CONSTRAINT [fk_loiwriteoffdetail_ashipment]
GO
/****** Object:  ForeignKey [fk_loiwriteoffdetail_loilocation]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiWriteOffDetail]  WITH CHECK ADD  CONSTRAINT [fk_loiwriteoffdetail_loilocation] FOREIGN KEY([wdGodownID], [wdLocationID])
REFERENCES [dbo].[LOiLocation] ([lGodownID], [lLocationID])
GO
ALTER TABLE [dbo].[LOiWriteOffDetail] CHECK CONSTRAINT [fk_loiwriteoffdetail_loilocation]
GO
/****** Object:  ForeignKey [FK_LOiWriteOffDetail_LOiWriteOffHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiWriteOffDetail]  WITH NOCHECK ADD  CONSTRAINT [FK_LOiWriteOffDetail_LOiWriteOffHeader] FOREIGN KEY([wdGodownID], [wdID])
REFERENCES [dbo].[LOiWriteOffHeader] ([whGodownID], [whID])
GO
ALTER TABLE [dbo].[LOiWriteOffDetail] CHECK CONSTRAINT [FK_LOiWriteOffDetail_LOiWriteOffHeader]
GO
/****** Object:  ForeignKey [fk_FixedAsset_aAccountMaster_5]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FixedAsset]  WITH CHECK ADD  CONSTRAINT [fk_FixedAsset_aAccountMaster_5] FOREIGN KEY([CurrDeprecExpAccID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[FixedAsset] CHECK CONSTRAINT [fk_FixedAsset_aAccountMaster_5]
GO
/****** Object:  ForeignKey [fk_FixedAsset_aAccountMaster_6]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FixedAsset]  WITH CHECK ADD  CONSTRAINT [fk_FixedAsset_aAccountMaster_6] FOREIGN KEY([CurrAccDepExpAccID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[FixedAsset] CHECK CONSTRAINT [fk_FixedAsset_aAccountMaster_6]
GO
/****** Object:  ForeignKey [fk_fixedasset_accountmaster_conv]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FixedAsset]  WITH CHECK ADD  CONSTRAINT [fk_fixedasset_accountmaster_conv] FOREIGN KEY([conversiondiffaccid], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[FixedAsset] CHECK CONSTRAINT [fk_fixedasset_accountmaster_conv]
GO
/****** Object:  ForeignKey [fk_fixedasset_accountmaster_dep]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FixedAsset]  WITH CHECK ADD  CONSTRAINT [fk_fixedasset_accountmaster_dep] FOREIGN KEY([DepreciationAccId], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[FixedAsset] CHECK CONSTRAINT [fk_fixedasset_accountmaster_dep]
GO
/****** Object:  ForeignKey [fk_fixedasset_accountmaster_fxa]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FixedAsset]  WITH CHECK ADD  CONSTRAINT [fk_fixedasset_accountmaster_fxa] FOREIGN KEY([FixedAssetAccID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[FixedAsset] CHECK CONSTRAINT [fk_fixedasset_accountmaster_fxa]
GO
/****** Object:  ForeignKey [FK_FixedAsset_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FixedAsset]  WITH CHECK ADD  CONSTRAINT [FK_FixedAsset_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[FixedAsset] CHECK CONSTRAINT [FK_FixedAsset_aCompanyMaster]
GO
/****** Object:  ForeignKey [fk_fixedasset_adepartmentmaster_c]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FixedAsset]  WITH CHECK ADD  CONSTRAINT [fk_fixedasset_adepartmentmaster_c] FOREIGN KEY([CurrentDepartmentId], [CompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[FixedAsset] CHECK CONSTRAINT [fk_fixedasset_adepartmentmaster_c]
GO
/****** Object:  ForeignKey [fk_fixedasset_afinancialyear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FixedAsset]  WITH CHECK ADD  CONSTRAINT [fk_fixedasset_afinancialyear] FOREIGN KEY([financialid], [CompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[FixedAsset] CHECK CONSTRAINT [fk_fixedasset_afinancialyear]
GO
/****** Object:  ForeignKey [fk_fixedasset_bills]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FixedAsset]  WITH NOCHECK ADD  CONSTRAINT [fk_fixedasset_bills] FOREIGN KEY([billsrefid])
REFERENCES [dbo].[Bills] ([BillsID])
GO
ALTER TABLE [dbo].[FixedAsset] CHECK CONSTRAINT [fk_fixedasset_bills]
GO
/****** Object:  ForeignKey [fk_fixedasset_writeoff]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FixedAsset]  WITH NOCHECK ADD  CONSTRAINT [fk_fixedasset_writeoff] FOREIGN KEY([godownrefid], [writeoffrefid])
REFERENCES [dbo].[LOiWriteOffHeader] ([whGodownID], [whID])
GO
ALTER TABLE [dbo].[FixedAsset] CHECK CONSTRAINT [fk_fixedasset_writeoff]
GO
/****** Object:  ForeignKey [FK_losInvoiceProjectRequestDetails_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losInvoiceProjectRequestDetails]  WITH CHECK ADD  CONSTRAINT [FK_losInvoiceProjectRequestDetails_aShops] FOREIGN KEY([idrShopId])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losInvoiceProjectRequestDetails] CHECK CONSTRAINT [FK_losInvoiceProjectRequestDetails_aShops]
GO
/****** Object:  ForeignKey [FK_losInvoiceProjectRequestDetails_LOsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losInvoiceProjectRequestDetails]  WITH CHECK ADD  CONSTRAINT [FK_losInvoiceProjectRequestDetails_LOsInvoiceHeader] FOREIGN KEY([idrShopId], [idrInvoiceId])
REFERENCES [dbo].[LOsInvoiceHeader] ([ihShopID], [ihInvoiceID])
GO
ALTER TABLE [dbo].[losInvoiceProjectRequestDetails] CHECK CONSTRAINT [FK_losInvoiceProjectRequestDetails_LOsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceOC_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceOC]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceOC_aAccountMaster] FOREIGN KEY([ioAccID], [ioCompanyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsInvoiceOC] CHECK CONSTRAINT [FK_LOsInvoiceOC_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceOC_LOsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceOC]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceOC_LOsInvoiceHeader] FOREIGN KEY([ioShopID], [ioInvoiceID])
REFERENCES [dbo].[LOsInvoiceHeader] ([ihShopID], [ihInvoiceID])
GO
ALTER TABLE [dbo].[LOsInvoiceOC] CHECK CONSTRAINT [FK_LOsInvoiceOC_LOsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_losDeliveryItemsVerificationDetails_losDeliveryItemsVerificationHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDeliveryVerificationDetails]  WITH CHECK ADD  CONSTRAINT [FK_losDeliveryItemsVerificationDetails_losDeliveryItemsVerificationHeader] FOREIGN KEY([CompanyId], [ShopId], [DeliveryVerificationId])
REFERENCES [dbo].[losDeliveryVerificationHeader] ([CompanyId], [ShopId], [DeliveryVerificationId])
GO
ALTER TABLE [dbo].[losDeliveryVerificationDetails] CHECK CONSTRAINT [FK_losDeliveryItemsVerificationDetails_losDeliveryItemsVerificationHeader]
GO
/****** Object:  ForeignKey [FK_losDeliveryItemsVerificationDetails_LOsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDeliveryVerificationDetails]  WITH CHECK ADD  CONSTRAINT [FK_losDeliveryItemsVerificationDetails_LOsInvoiceHeader] FOREIGN KEY([ShopId], [InvoiceId])
REFERENCES [dbo].[LOsInvoiceHeader] ([ihShopID], [ihInvoiceID])
GO
ALTER TABLE [dbo].[losDeliveryVerificationDetails] CHECK CONSTRAINT [FK_losDeliveryItemsVerificationDetails_LOsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_losDeliveryItemsVerificationDetails_LOsPosHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDeliveryVerificationDetails]  WITH CHECK ADD  CONSTRAINT [FK_losDeliveryItemsVerificationDetails_LOsPosHeader] FOREIGN KEY([ShopId], [BillId])
REFERENCES [dbo].[LOsPosHeader] ([poshShopID], [poshBillID])
GO
ALTER TABLE [dbo].[losDeliveryVerificationDetails] CHECK CONSTRAINT [FK_losDeliveryItemsVerificationDetails_LOsPosHeader]
GO
/****** Object:  ForeignKey [FK_losDeliveryVerificationDetails_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDeliveryVerificationDetails]  WITH CHECK ADD  CONSTRAINT [FK_losDeliveryVerificationDetails_aItem] FOREIGN KEY([ItemId])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losDeliveryVerificationDetails] CHECK CONSTRAINT [FK_losDeliveryVerificationDetails_aItem]
GO
/****** Object:  ForeignKey [FK_losDeliveryVerificationDetails_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDeliveryVerificationDetails]  WITH CHECK ADD  CONSTRAINT [FK_losDeliveryVerificationDetails_aPackingType] FOREIGN KEY([PackId])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[losDeliveryVerificationDetails] CHECK CONSTRAINT [FK_losDeliveryVerificationDetails_aPackingType]
GO
/****** Object:  ForeignKey [FK_losDeliveryDetails_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDeliveryDetails]  WITH CHECK ADD  CONSTRAINT [FK_losDeliveryDetails_aCompanyMaster] FOREIGN KEY([CompanyId])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[losDeliveryDetails] CHECK CONSTRAINT [FK_losDeliveryDetails_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_losDeliveryDetails_LOsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDeliveryDetails]  WITH CHECK ADD  CONSTRAINT [FK_losDeliveryDetails_LOsInvoiceHeader] FOREIGN KEY([ShopId], [CreditInvoiceId])
REFERENCES [dbo].[LOsInvoiceHeader] ([ihShopID], [ihInvoiceID])
GO
ALTER TABLE [dbo].[losDeliveryDetails] CHECK CONSTRAINT [FK_losDeliveryDetails_LOsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_losDeliveryDetails_losPosHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDeliveryDetails]  WITH CHECK ADD  CONSTRAINT [FK_losDeliveryDetails_losPosHeader] FOREIGN KEY([ShopId], [CashInvoiceId])
REFERENCES [dbo].[LOsPosHeader] ([poshShopID], [poshBillID])
GO
ALTER TABLE [dbo].[losDeliveryDetails] CHECK CONSTRAINT [FK_losDeliveryDetails_losPosHeader]
GO
/****** Object:  ForeignKey [FK_losrebaterequest_AsalesPersonmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losrebaterequest]  WITH CHECK ADD  CONSTRAINT [FK_losrebaterequest_AsalesPersonmaster] FOREIGN KEY([rrsalespersonid])
REFERENCES [dbo].[AsalesPersonmaster] ([Sperid])
GO
ALTER TABLE [dbo].[losrebaterequest] CHECK CONSTRAINT [FK_losrebaterequest_AsalesPersonmaster]
GO
/****** Object:  ForeignKey [FK_losrebaterequest_LOsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losrebaterequest]  WITH CHECK ADD  CONSTRAINT [FK_losrebaterequest_LOsInvoiceHeader] FOREIGN KEY([rrshopid], [rrpoid])
REFERENCES [dbo].[LOsInvoiceHeader] ([ihShopID], [ihInvoiceID])
GO
ALTER TABLE [dbo].[losrebaterequest] CHECK CONSTRAINT [FK_losrebaterequest_LOsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_LosKegReturnDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosKegReturnDetail]  WITH CHECK ADD  CONSTRAINT [FK_LosKegReturnDetail_aItem] FOREIGN KEY([krDItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LosKegReturnDetail] CHECK CONSTRAINT [FK_LosKegReturnDetail_aItem]
GO
/****** Object:  ForeignKey [FK_LosKegReturnDetail_LOsInvoiceDetail]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosKegReturnDetail]  WITH CHECK ADD  CONSTRAINT [FK_LosKegReturnDetail_LOsInvoiceDetail] FOREIGN KEY([krDShopid], [krDInvoiceId])
REFERENCES [dbo].[LOsInvoiceHeader] ([ihShopID], [ihInvoiceID])
GO
ALTER TABLE [dbo].[LosKegReturnDetail] CHECK CONSTRAINT [FK_LosKegReturnDetail_LOsInvoiceDetail]
GO
/****** Object:  ForeignKey [FK_LosKegReturnDetail_LosKegReturnHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosKegReturnDetail]  WITH CHECK ADD  CONSTRAINT [FK_LosKegReturnDetail_LosKegReturnHeader] FOREIGN KEY([krDShopid], [krDReturnNoteID])
REFERENCES [dbo].[LosKegReturnHeader] ([krhShopid], [krhKegReturnID])
GO
ALTER TABLE [dbo].[LosKegReturnDetail] CHECK CONSTRAINT [FK_LosKegReturnDetail_LosKegReturnHeader]
GO
/****** Object:  ForeignKey [FK_LOsReceiptVoucherDetails_LOsAccountsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsReceiptVoucherDetails]  WITH CHECK ADD  CONSTRAINT [FK_LOsReceiptVoucherDetails_LOsAccountsInvoiceHeader] FOREIGN KEY([rdShopID], [rdAccountsInvoiceID])
REFERENCES [dbo].[LOsAccountsInvoiceHeader] ([aiShopID], [aiInvoiceID])
GO
ALTER TABLE [dbo].[LOsReceiptVoucherDetails] CHECK CONSTRAINT [FK_LOsReceiptVoucherDetails_LOsAccountsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_LOsReceiptVoucherDetails_LOsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsReceiptVoucherDetails]  WITH CHECK ADD  CONSTRAINT [FK_LOsReceiptVoucherDetails_LOsInvoiceHeader] FOREIGN KEY([rdShopID], [rdInvoiceID])
REFERENCES [dbo].[LOsInvoiceHeader] ([ihShopID], [ihInvoiceID])
GO
ALTER TABLE [dbo].[LOsReceiptVoucherDetails] CHECK CONSTRAINT [FK_LOsReceiptVoucherDetails_LOsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_LOsReceiptVoucherDetails_LOsReceiptVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsReceiptVoucherDetails]  WITH CHECK ADD  CONSTRAINT [FK_LOsReceiptVoucherDetails_LOsReceiptVoucherHeader] FOREIGN KEY([rdReceiptID], [rdShopID])
REFERENCES [dbo].[LOsReceiptVoucherHeader] ([rhReceiptID], [rhShopID])
GO
ALTER TABLE [dbo].[LOsReceiptVoucherDetails] CHECK CONSTRAINT [FK_LOsReceiptVoucherDetails_LOsReceiptVoucherHeader]
GO
/****** Object:  ForeignKey [FK_LosInvoiceST_LOsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosInvoiceST]  WITH CHECK ADD  CONSTRAINT [FK_LosInvoiceST_LOsInvoiceHeader] FOREIGN KEY([ioSTShopID], [ioSTInvoiceID])
REFERENCES [dbo].[LOsInvoiceHeader] ([ihShopID], [ihInvoiceID])
GO
ALTER TABLE [dbo].[LosInvoiceST] CHECK CONSTRAINT [FK_LosInvoiceST_LOsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_LosDeliveryNoteDetail_LosDeliveryNoteHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosDeliveryNoteDetail]  WITH CHECK ADD  CONSTRAINT [FK_LosDeliveryNoteDetail_LosDeliveryNoteHeader] FOREIGN KEY([DnDShopid], [DnDdnId])
REFERENCES [dbo].[LosDeliveryNoteHeader] ([DnShopid], [DndnId])
GO
ALTER TABLE [dbo].[LosDeliveryNoteDetail] CHECK CONSTRAINT [FK_LosDeliveryNoteDetail_LosDeliveryNoteHeader]
GO
/****** Object:  ForeignKey [FK_LosDeliveryNoteDetail_LOsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosDeliveryNoteDetail]  WITH CHECK ADD  CONSTRAINT [FK_LosDeliveryNoteDetail_LOsInvoiceHeader] FOREIGN KEY([DnDShopid], [DnDinvoiceId])
REFERENCES [dbo].[LOsInvoiceHeader] ([ihShopID], [ihInvoiceID])
GO
ALTER TABLE [dbo].[LosDeliveryNoteDetail] CHECK CONSTRAINT [FK_LosDeliveryNoteDetail_LOsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_losEDIRequest_LOsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losEDIRequest]  WITH CHECK ADD  CONSTRAINT [FK_losEDIRequest_LOsInvoiceHeader] FOREIGN KEY([ershopid], [erpoid])
REFERENCES [dbo].[LOsInvoiceHeader] ([ihShopID], [ihInvoiceID])
GO
ALTER TABLE [dbo].[losEDIRequest] CHECK CONSTRAINT [FK_losEDIRequest_LOsInvoiceHeader]
GO
/****** Object:  ForeignKey [fk_LosGoodsReturnNoteHeader_aaccountmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader]  WITH CHECK ADD  CONSTRAINT [fk_LosGoodsReturnNoteHeader_aaccountmaster] FOREIGN KEY([GrnReturnAccID], [GrnCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader] CHECK CONSTRAINT [fk_LosGoodsReturnNoteHeader_aaccountmaster]
GO
/****** Object:  ForeignKey [fk_LosGoodsReturnNoteHeader_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader]  WITH CHECK ADD  CONSTRAINT [fk_LosGoodsReturnNoteHeader_acustomermaster] FOREIGN KEY([GrnhCustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader] CHECK CONSTRAINT [fk_LosGoodsReturnNoteHeader_acustomermaster]
GO
/****** Object:  ForeignKey [FK_LosGoodsReturnNoteHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader]  WITH CHECK ADD  CONSTRAINT [FK_LosGoodsReturnNoteHeader_aDepartmentMaster] FOREIGN KEY([grnhDepartmentid], [GrnCompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader] CHECK CONSTRAINT [FK_LosGoodsReturnNoteHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_LosGoodsReturnNoteHeader_aFinancialYear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader]  WITH CHECK ADD  CONSTRAINT [FK_LosGoodsReturnNoteHeader_aFinancialYear] FOREIGN KEY([grnhfinancialid], [GrnCompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader] CHECK CONSTRAINT [FK_LosGoodsReturnNoteHeader_aFinancialYear]
GO
/****** Object:  ForeignKey [FK_LosGoodsReturnNoteHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader]  WITH CHECK ADD  CONSTRAINT [FK_LosGoodsReturnNoteHeader_aShops] FOREIGN KEY([grnhShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader] CHECK CONSTRAINT [FK_LosGoodsReturnNoteHeader_aShops]
GO
/****** Object:  ForeignKey [FK_LosGoodsReturnNoteHeader_LOsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader]  WITH CHECK ADD  CONSTRAINT [FK_LosGoodsReturnNoteHeader_LOsInvoiceHeader] FOREIGN KEY([grnhShopid], [GrnhInvoiceID])
REFERENCES [dbo].[LOsInvoiceHeader] ([ihShopID], [ihInvoiceID])
GO
ALTER TABLE [dbo].[LosGoodsReturnNoteHeader] CHECK CONSTRAINT [FK_LosGoodsReturnNoteHeader_LOsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceSubItemDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceSubItemDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceSubItemDetail_aItem] FOREIGN KEY([isditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOsInvoiceSubItemDetail] CHECK CONSTRAINT [FK_LOsInvoiceSubItemDetail_aItem]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceSubItemDetail_aItem1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceSubItemDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceSubItemDetail_aItem1] FOREIGN KEY([isdsubitemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOsInvoiceSubItemDetail] CHECK CONSTRAINT [FK_LOsInvoiceSubItemDetail_aItem1]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceSubItemDetail_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceSubItemDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceSubItemDetail_aPackingType] FOREIGN KEY([isdpackingtypeid])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[LOsInvoiceSubItemDetail] CHECK CONSTRAINT [FK_LOsInvoiceSubItemDetail_aPackingType]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceSubItemDetail_LOsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceSubItemDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceSubItemDetail_LOsInvoiceHeader] FOREIGN KEY([isdShopid], [isdinvoiceid])
REFERENCES [dbo].[LOsInvoiceHeader] ([ihShopID], [ihInvoiceID])
GO
ALTER TABLE [dbo].[LOsInvoiceSubItemDetail] CHECK CONSTRAINT [FK_LOsInvoiceSubItemDetail_LOsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceDetail_aItem] FOREIGN KEY([idItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOsInvoiceDetail] CHECK CONSTRAINT [FK_LOsInvoiceDetail_aItem]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceDetail_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceDetail_aPackingType] FOREIGN KEY([idPackingTypeID])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[LOsInvoiceDetail] CHECK CONSTRAINT [FK_LOsInvoiceDetail_aPackingType]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceDetail_aUnit]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceDetail_aUnit] FOREIGN KEY([idPUnitID])
REFERENCES [dbo].[aUnit] ([UnitID])
GO
ALTER TABLE [dbo].[LOsInvoiceDetail] CHECK CONSTRAINT [FK_LOsInvoiceDetail_aUnit]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceDetail_LOsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceDetail_LOsInvoiceHeader] FOREIGN KEY([idShopID], [idInvoiceID])
REFERENCES [dbo].[LOsInvoiceHeader] ([ihShopID], [ihInvoiceID])
GO
ALTER TABLE [dbo].[LOsInvoiceDetail] CHECK CONSTRAINT [FK_LOsInvoiceDetail_LOsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_mesTransferOutArrivalDetail_LOsGoodsArrivaltoShopHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferOutArrivalDetail]  WITH CHECK ADD  CONSTRAINT [FK_mesTransferOutArrivalDetail_LOsGoodsArrivaltoShopHeader] FOREIGN KEY([toaArrivalId], [toaShopid])
REFERENCES [dbo].[LOsGoodsArrivaltoShopHeader] ([gahArrivalID], [gahShopid])
GO
ALTER TABLE [dbo].[mesTransferOutArrivalDetail] CHECK CONSTRAINT [FK_mesTransferOutArrivalDetail_LOsGoodsArrivaltoShopHeader]
GO
/****** Object:  ForeignKey [FK_mesTransferOutArrivalDetail_mesTransferOutHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferOutArrivalDetail]  WITH CHECK ADD  CONSTRAINT [FK_mesTransferOutArrivalDetail_mesTransferOutHeader] FOREIGN KEY([toaTransOutId], [toaShopid])
REFERENCES [dbo].[mesTransferOutHeader] ([TOHid], [TOHShopid])
GO
ALTER TABLE [dbo].[mesTransferOutArrivalDetail] CHECK CONSTRAINT [FK_mesTransferOutArrivalDetail_mesTransferOutHeader]
GO
/****** Object:  ForeignKey [FK_LOSTransferinheader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOSTransferinheader]  WITH CHECK ADD  CONSTRAINT [FK_LOSTransferinheader_aShops] FOREIGN KEY([TIHShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LOSTransferinheader] CHECK CONSTRAINT [FK_LOSTransferinheader_aShops]
GO
/****** Object:  ForeignKey [FK_LOSTransferinheader_aShops1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOSTransferinheader]  WITH CHECK ADD  CONSTRAINT [FK_LOSTransferinheader_aShops1] FOREIGN KEY([TIHfromshopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LOSTransferinheader] CHECK CONSTRAINT [FK_LOSTransferinheader_aShops1]
GO
/****** Object:  ForeignKey [FK_LOSTransferinheader_mesTransferOutHeader1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOSTransferinheader]  WITH CHECK ADD  CONSTRAINT [FK_LOSTransferinheader_mesTransferOutHeader1] FOREIGN KEY([TIHdespatchID], [TIHfromshopID])
REFERENCES [dbo].[mesTransferOutHeader] ([TOHid], [TOHShopid])
GO
ALTER TABLE [dbo].[LOSTransferinheader] CHECK CONSTRAINT [FK_LOSTransferinheader_mesTransferOutHeader1]
GO
/****** Object:  ForeignKey [FK_mesTransferoutDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferoutDetail]  WITH CHECK ADD  CONSTRAINT [FK_mesTransferoutDetail_aItem] FOREIGN KEY([TODitemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[mesTransferoutDetail] CHECK CONSTRAINT [FK_mesTransferoutDetail_aItem]
GO
/****** Object:  ForeignKey [FK_mesTransferoutDetail_aShops1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferoutDetail]  WITH CHECK ADD  CONSTRAINT [FK_mesTransferoutDetail_aShops1] FOREIGN KEY([TODtoShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[mesTransferoutDetail] CHECK CONSTRAINT [FK_mesTransferoutDetail_aShops1]
GO
/****** Object:  ForeignKey [FK_mesTransferoutDetail_mesTransferOutHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferoutDetail]  WITH CHECK ADD  CONSTRAINT [FK_mesTransferoutDetail_mesTransferOutHeader] FOREIGN KEY([TODid], [TODshopid])
REFERENCES [dbo].[mesTransferOutHeader] ([TOHid], [TOHShopid])
GO
ALTER TABLE [dbo].[mesTransferoutDetail] CHECK CONSTRAINT [FK_mesTransferoutDetail_mesTransferOutHeader]
GO
/****** Object:  ForeignKey [FK_LOsShopDamageClearingDetails_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsShopDamageClearingDetails]  WITH CHECK ADD  CONSTRAINT [FK_LOsShopDamageClearingDetails_aItem] FOREIGN KEY([dcdItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOsShopDamageClearingDetails] CHECK CONSTRAINT [FK_LOsShopDamageClearingDetails_aItem]
GO
/****** Object:  ForeignKey [FK_LOsShopDamageClearingDetails_LOsShopDamageClearingHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsShopDamageClearingDetails]  WITH CHECK ADD  CONSTRAINT [FK_LOsShopDamageClearingDetails_LOsShopDamageClearingHeader] FOREIGN KEY([dcdClearingID], [dcdShopid])
REFERENCES [dbo].[LOsShopDamageClearingHeader] ([dchClearingID], [dchShopid])
GO
ALTER TABLE [dbo].[LOsShopDamageClearingDetails] CHECK CONSTRAINT [FK_LOsShopDamageClearingDetails_LOsShopDamageClearingHeader]
GO
/****** Object:  ForeignKey [FK_LOsWriteOffDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsWriteOffDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsWriteOffDetail_aItem] FOREIGN KEY([WdItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOsWriteOffDetail] CHECK CONSTRAINT [FK_LOsWriteOffDetail_aItem]
GO
/****** Object:  ForeignKey [FK_LOsWriteOffDetail_LOsWriteOffHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsWriteOffDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsWriteOffDetail_LOsWriteOffHeader] FOREIGN KEY([wdShopID], [WdID])
REFERENCES [dbo].[LOsWriteOffHeader] ([whShopID], [WhID])
GO
ALTER TABLE [dbo].[LOsWriteOffDetail] CHECK CONSTRAINT [FK_LOsWriteOffDetail_LOsWriteOffHeader]
GO
/****** Object:  ForeignKey [FK_LOs_InHouseCons_ReturnHeader_LOswriteoffheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOs_InHouseCons_ReturnHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOs_InHouseCons_ReturnHeader_LOswriteoffheader] FOREIGN KEY([IHRHShopID], [IHRHReferenceid])
REFERENCES [dbo].[LOsWriteOffHeader] ([whShopID], [WhID])
GO
ALTER TABLE [dbo].[LOs_InHouseCons_ReturnHeader] CHECK CONSTRAINT [FK_LOs_InHouseCons_ReturnHeader_LOswriteoffheader]
GO
/****** Object:  ForeignKey [FK_loiUserAuditHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiUserAuditHeader]  WITH NOCHECK ADD  CONSTRAINT [FK_loiUserAuditHeader_aCompanyMaster] FOREIGN KEY([ghCompanyId])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[loiUserAuditHeader] CHECK CONSTRAINT [FK_loiUserAuditHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_loiUserAuditHeader_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiUserAuditHeader]  WITH NOCHECK ADD  CONSTRAINT [FK_loiUserAuditHeader_aGodown] FOREIGN KEY([ghGodownId])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[loiUserAuditHeader] CHECK CONSTRAINT [FK_loiUserAuditHeader_aGodown]
GO
/****** Object:  ForeignKey [FK_loiUserAuditHeader_aInterface]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiUserAuditHeader]  WITH NOCHECK ADD  CONSTRAINT [FK_loiUserAuditHeader_aInterface] FOREIGN KEY([ghInterfaceId], [ghCompanyId])
REFERENCES [dbo].[aInterface] ([InterfaceID], [CompanyID])
GO
ALTER TABLE [dbo].[loiUserAuditHeader] CHECK CONSTRAINT [FK_loiUserAuditHeader_aInterface]
GO
/****** Object:  ForeignKey [FK_aPrefix_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPrefix]  WITH CHECK ADD  CONSTRAINT [FK_aPrefix_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aPrefix] CHECK CONSTRAINT [FK_aPrefix_aCompanyMaster]
GO
/****** Object:  ForeignKey [fk_aPrefix_aFinancialYear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPrefix]  WITH CHECK ADD  CONSTRAINT [fk_aPrefix_aFinancialYear] FOREIGN KEY([Financialid], [CompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[aPrefix] CHECK CONSTRAINT [fk_aPrefix_aFinancialYear]
GO
/****** Object:  ForeignKey [FK_aPrefix_aInterface]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPrefix]  WITH CHECK ADD  CONSTRAINT [FK_aPrefix_aInterface] FOREIGN KEY([InterfaceID], [CompanyID])
REFERENCES [dbo].[aInterface] ([InterfaceID], [CompanyID])
GO
ALTER TABLE [dbo].[aPrefix] CHECK CONSTRAINT [FK_aPrefix_aInterface]
GO
/****** Object:  ForeignKey [FK_aUserRights_aInterface]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aUserRights]  WITH CHECK ADD  CONSTRAINT [FK_aUserRights_aInterface] FOREIGN KEY([InterfaceID], [CompanyID])
REFERENCES [dbo].[aInterface] ([InterfaceID], [CompanyID])
GO
ALTER TABLE [dbo].[aUserRights] CHECK CONSTRAINT [FK_aUserRights_aInterface]
GO
/****** Object:  ForeignKey [FK_aUserRights_aUsers1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aUserRights]  WITH CHECK ADD  CONSTRAINT [FK_aUserRights_aUsers1] FOREIGN KEY([UserID], [CompanyID])
REFERENCES [dbo].[aUsers] ([UserID], [CompanyID])
GO
ALTER TABLE [dbo].[aUserRights] CHECK CONSTRAINT [FK_aUserRights_aUsers1]
GO
/****** Object:  ForeignKey [FK_LOSTransferindetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOSTransferindetail]  WITH CHECK ADD  CONSTRAINT [FK_LOSTransferindetail_aItem] FOREIGN KEY([TIDitemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOSTransferindetail] CHECK CONSTRAINT [FK_LOSTransferindetail_aItem]
GO
/****** Object:  ForeignKey [FK_LOSTransferindetail_LOSTransferinheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOSTransferindetail]  WITH CHECK ADD  CONSTRAINT [FK_LOSTransferindetail_LOSTransferinheader] FOREIGN KEY([TIDshopid], [TIDID])
REFERENCES [dbo].[LOSTransferinheader] ([TIHShopid], [TIHID])
GO
ALTER TABLE [dbo].[LOSTransferindetail] CHECK CONSTRAINT [FK_LOSTransferindetail_LOSTransferinheader]
GO
/****** Object:  ForeignKey [fk_paPayAccLinkPostingDetails_paPayAccLinkHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[paPayAccLinkPostingDetails]  WITH CHECK ADD  CONSTRAINT [fk_paPayAccLinkPostingDetails_paPayAccLinkHeader] FOREIGN KEY([CompanyID], [TransID])
REFERENCES [dbo].[paPayAccLinkHeader] ([CompanyID], [TransID])
GO
ALTER TABLE [dbo].[paPayAccLinkPostingDetails] CHECK CONSTRAINT [fk_paPayAccLinkPostingDetails_paPayAccLinkHeader]
GO
/****** Object:  ForeignKey [fk_paPayAccLinkDetails_paPayAccLinkHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[paPayAccLinkDetails]  WITH CHECK ADD  CONSTRAINT [fk_paPayAccLinkDetails_paPayAccLinkHeader] FOREIGN KEY([CompanyID], [TransID])
REFERENCES [dbo].[paPayAccLinkHeader] ([CompanyID], [TransID])
GO
ALTER TABLE [dbo].[paPayAccLinkDetails] CHECK CONSTRAINT [fk_paPayAccLinkDetails_paPayAccLinkHeader]
GO
/****** Object:  ForeignKey [FK_MEsDespatchtoGodownDetail_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsDespatchtoGodownDetail]  WITH CHECK ADD  CONSTRAINT [FK_MEsDespatchtoGodownDetail_aGodown] FOREIGN KEY([dgdGodownid])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[MEsDespatchtoGodownDetail] CHECK CONSTRAINT [FK_MEsDespatchtoGodownDetail_aGodown]
GO
/****** Object:  ForeignKey [FK_MEsDespatchtoGodownDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsDespatchtoGodownDetail]  WITH CHECK ADD  CONSTRAINT [FK_MEsDespatchtoGodownDetail_aItem] FOREIGN KEY([dgdItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[MEsDespatchtoGodownDetail] CHECK CONSTRAINT [FK_MEsDespatchtoGodownDetail_aItem]
GO
/****** Object:  ForeignKey [FK_MEsDespatchtoGodownDetail_MEsDespatchtoGodownHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsDespatchtoGodownDetail]  WITH CHECK ADD  CONSTRAINT [FK_MEsDespatchtoGodownDetail_MEsDespatchtoGodownHeader] FOREIGN KEY([dgdID], [dgdShopID])
REFERENCES [dbo].[MEsDespatchtoGodownHeader] ([dghID], [dghShopID])
GO
ALTER TABLE [dbo].[MEsDespatchtoGodownDetail] CHECK CONSTRAINT [FK_MEsDespatchtoGodownDetail_MEsDespatchtoGodownHeader]
GO
/****** Object:  ForeignKey [FK_aAnalysedPOItems_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aAnalysedPOItems]  WITH CHECK ADD  CONSTRAINT [FK_aAnalysedPOItems_aItem] FOREIGN KEY([alitemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[aAnalysedPOItems] CHECK CONSTRAINT [FK_aAnalysedPOItems_aItem]
GO
/****** Object:  ForeignKey [FK_losSIQuotationDetail_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationDetail]  WITH CHECK ADD  CONSTRAINT [FK_losSIQuotationDetail_aGodown] FOREIGN KEY([idGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[losSIQuotationDetail] CHECK CONSTRAINT [FK_losSIQuotationDetail_aGodown]
GO
/****** Object:  ForeignKey [FK_losSIQuotationDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationDetail]  WITH CHECK ADD  CONSTRAINT [FK_losSIQuotationDetail_aItem] FOREIGN KEY([idItemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losSIQuotationDetail] CHECK CONSTRAINT [FK_losSIQuotationDetail_aItem]
GO
/****** Object:  ForeignKey [FK_losSIQuotationDetail_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationDetail]  WITH CHECK ADD  CONSTRAINT [FK_losSIQuotationDetail_aPackingType] FOREIGN KEY([idPackingTypeid])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[losSIQuotationDetail] CHECK CONSTRAINT [FK_losSIQuotationDetail_aPackingType]
GO
/****** Object:  ForeignKey [fk_losSIQuotationDetail_ashipment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSIQuotationDetail_ashipment] FOREIGN KEY([shipmentid])
REFERENCES [dbo].[aShipment] ([sShipmentID])
GO
ALTER TABLE [dbo].[losSIQuotationDetail] CHECK CONSTRAINT [fk_losSIQuotationDetail_ashipment]
GO
/****** Object:  ForeignKey [FK_losSIQuotationDetail_losSIQuotationHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSIQuotationDetail]  WITH CHECK ADD  CONSTRAINT [FK_losSIQuotationDetail_losSIQuotationHeader] FOREIGN KEY([idInvoiceId], [idShopid])
REFERENCES [dbo].[losSIQuotationHeader] ([IhInvoiceID], [IhShopID])
GO
ALTER TABLE [dbo].[losSIQuotationDetail] CHECK CONSTRAINT [FK_losSIQuotationDetail_losSIQuotationHeader]
GO
/****** Object:  ForeignKey [FK_aHQDespatchNoteDetails_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchNoteDetails]  WITH CHECK ADD  CONSTRAINT [FK_aHQDespatchNoteDetails_aGodown] FOREIGN KEY([ddGodownid])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[aHQDespatchNoteDetails] CHECK CONSTRAINT [FK_aHQDespatchNoteDetails_aGodown]
GO
/****** Object:  ForeignKey [FK_aHQDespatchNoteDetails_aHQDespatchnoteHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchNoteDetails]  WITH CHECK ADD  CONSTRAINT [FK_aHQDespatchNoteDetails_aHQDespatchnoteHeader] FOREIGN KEY([ddDespatchnoteID])
REFERENCES [dbo].[aHQDespatchnoteHeader] ([dhDespatchnoteID])
GO
ALTER TABLE [dbo].[aHQDespatchNoteDetails] CHECK CONSTRAINT [FK_aHQDespatchNoteDetails_aHQDespatchnoteHeader]
GO
/****** Object:  ForeignKey [FK_aHQDespatchnoteDetails_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchNoteDetails]  WITH CHECK ADD  CONSTRAINT [FK_aHQDespatchnoteDetails_aItem] FOREIGN KEY([ddItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[aHQDespatchNoteDetails] CHECK CONSTRAINT [FK_aHQDespatchnoteDetails_aItem]
GO
/****** Object:  ForeignKey [FK_aHQDespatchNoteDetails_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchNoteDetails]  WITH CHECK ADD  CONSTRAINT [FK_aHQDespatchNoteDetails_aPackingType] FOREIGN KEY([ddPackingTypeID])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[aHQDespatchNoteDetails] CHECK CONSTRAINT [FK_aHQDespatchNoteDetails_aPackingType]
GO
/****** Object:  ForeignKey [fk_aHQDespatchNoteDetails_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchNoteDetails]  WITH CHECK ADD  CONSTRAINT [fk_aHQDespatchNoteDetails_aShops] FOREIGN KEY([ddShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[aHQDespatchNoteDetails] CHECK CONSTRAINT [fk_aHQDespatchNoteDetails_aShops]
GO
/****** Object:  ForeignKey [fk_loSExportDetail_aitem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losExportDetail]  WITH CHECK ADD  CONSTRAINT [fk_loSExportDetail_aitem] FOREIGN KEY([redItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losExportDetail] CHECK CONSTRAINT [fk_loSExportDetail_aitem]
GO
/****** Object:  ForeignKey [fk_losexportdetail_losexportheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losExportDetail]  WITH CHECK ADD  CONSTRAINT [fk_losexportdetail_losexportheader] FOREIGN KEY([redExportID], [redShopID])
REFERENCES [dbo].[losExportHeader] ([rehExportID], [rehShopID])
GO
ALTER TABLE [dbo].[losExportDetail] CHECK CONSTRAINT [fk_losexportdetail_losexportheader]
GO
/****** Object:  ForeignKey [FK_loilocationissuedetails_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loilocationissuedetails]  WITH CHECK ADD  CONSTRAINT [FK_loilocationissuedetails_aItem] FOREIGN KEY([liditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[loilocationissuedetails] CHECK CONSTRAINT [FK_loilocationissuedetails_aItem]
GO
/****** Object:  ForeignKey [FK_loilocationissuedetails_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loilocationissuedetails]  WITH CHECK ADD  CONSTRAINT [FK_loilocationissuedetails_aPackingType] FOREIGN KEY([lidpackingtypeid])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[loilocationissuedetails] CHECK CONSTRAINT [FK_loilocationissuedetails_aPackingType]
GO
/****** Object:  ForeignKey [FK_loilocationissuedetails_LOiLocation]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loilocationissuedetails]  WITH CHECK ADD  CONSTRAINT [FK_loilocationissuedetails_LOiLocation] FOREIGN KEY([lidgodownid], [lidlocationid])
REFERENCES [dbo].[LOiLocation] ([lGodownID], [lLocationID])
GO
ALTER TABLE [dbo].[loilocationissuedetails] CHECK CONSTRAINT [FK_loilocationissuedetails_LOiLocation]
GO
/****** Object:  ForeignKey [fk_losSerMaintenanceMachineDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerMaintenanceMachineDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSerMaintenanceMachineDetail_aItem] FOREIGN KEY([mmdMachineID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losSerMaintenanceMachineDetail] CHECK CONSTRAINT [fk_losSerMaintenanceMachineDetail_aItem]
GO
/****** Object:  ForeignKey [fk_losSerMaintenanceMachineDetail_losSerMaintenanceContractHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerMaintenanceMachineDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSerMaintenanceMachineDetail_losSerMaintenanceContractHeader] FOREIGN KEY([mmdCompanyID], [mmdMCID], [mmdShopID])
REFERENCES [dbo].[losSerMaintenanceContractHeader] ([mchCompanyID], [mchID], [mchShopID])
GO
ALTER TABLE [dbo].[losSerMaintenanceMachineDetail] CHECK CONSTRAINT [fk_losSerMaintenanceMachineDetail_losSerMaintenanceContractHeader]
GO
/****** Object:  ForeignKey [FK_LOsPosDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsPosDetail_aItem] FOREIGN KEY([posdItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOsPosDetail] CHECK CONSTRAINT [FK_LOsPosDetail_aItem]
GO
/****** Object:  ForeignKey [FK_LOsPosDetail_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsPosDetail_aPackingType] FOREIGN KEY([posdPackingTypeID])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[LOsPosDetail] CHECK CONSTRAINT [FK_LOsPosDetail_aPackingType]
GO
/****** Object:  ForeignKey [FK_LOsPosDetail_aUnit]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsPosDetail_aUnit] FOREIGN KEY([posdPUnitID])
REFERENCES [dbo].[aUnit] ([UnitID])
GO
ALTER TABLE [dbo].[LOsPosDetail] CHECK CONSTRAINT [FK_LOsPosDetail_aUnit]
GO
/****** Object:  ForeignKey [FK_LOsPosDetail_LOsPosHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsPosDetail_LOsPosHeader] FOREIGN KEY([posdShopID], [posdBillID])
REFERENCES [dbo].[LOsPosHeader] ([poshShopID], [poshBillID])
GO
ALTER TABLE [dbo].[LOsPosDetail] CHECK CONSTRAINT [FK_LOsPosDetail_LOsPosHeader]
GO
/****** Object:  ForeignKey [FK_losinquirydetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losinquirydetail]  WITH CHECK ADD  CONSTRAINT [FK_losinquirydetail_aItem] FOREIGN KEY([iditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losinquirydetail] CHECK CONSTRAINT [FK_losinquirydetail_aItem]
GO
/****** Object:  ForeignKey [FK_losinquirydetail_losInquiryHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losinquirydetail]  WITH CHECK ADD  CONSTRAINT [FK_losinquirydetail_losInquiryHeader] FOREIGN KEY([idcompanyid], [idshopid], [idid])
REFERENCES [dbo].[losInquiryHeader] ([ihcompanyid], [ihshopid], [ihid])
GO
ALTER TABLE [dbo].[losinquirydetail] CHECK CONSTRAINT [FK_losinquirydetail_losInquiryHeader]
GO
/****** Object:  ForeignKey [fk_losinvpartsreplacedetails_aitem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losinvpartsreplacedetails]  WITH CHECK ADD  CONSTRAINT [fk_losinvpartsreplacedetails_aitem] FOREIGN KEY([repinvdpartsid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losinvpartsreplacedetails] CHECK CONSTRAINT [fk_losinvpartsreplacedetails_aitem]
GO
/****** Object:  ForeignKey [fk_losinvpartsreplacedetails_losserviceheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losinvpartsreplacedetails]  WITH CHECK ADD  CONSTRAINT [fk_losinvpartsreplacedetails_losserviceheader] FOREIGN KEY([repinvinvoiceid], [repinvcompanyid], [repinvdshopid])
REFERENCES [dbo].[losServiceHeader] ([serinvhid], [serinvhcompanyid], [serinvhshopid])
GO
ALTER TABLE [dbo].[losinvpartsreplacedetails] CHECK CONSTRAINT [fk_losinvpartsreplacedetails_losserviceheader]
GO
/****** Object:  ForeignKey [fk_losinvpartsreplacedetails_packingtype]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losinvpartsreplacedetails]  WITH CHECK ADD  CONSTRAINT [fk_losinvpartsreplacedetails_packingtype] FOREIGN KEY([repinvpackid])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[losinvpartsreplacedetails] CHECK CONSTRAINT [fk_losinvpartsreplacedetails_packingtype]
GO
/****** Object:  ForeignKey [FK_losrebateconfirmdetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losrebateconfirmdetail]  WITH CHECK ADD  CONSTRAINT [FK_losrebateconfirmdetail_aItem] FOREIGN KEY([rcditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losrebateconfirmdetail] CHECK CONSTRAINT [FK_losrebateconfirmdetail_aItem]
GO
/****** Object:  ForeignKey [FK_losrebateconfirmdetail_losrebateconfirmheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losrebateconfirmdetail]  WITH CHECK ADD  CONSTRAINT [FK_losrebateconfirmdetail_losrebateconfirmheader] FOREIGN KEY([rcdshopid], [rcdapprovedid])
REFERENCES [dbo].[losrebateconfirmheader] ([rcshopid], [rcapprovedid])
GO
ALTER TABLE [dbo].[losrebateconfirmdetail] CHECK CONSTRAINT [FK_losrebateconfirmdetail_losrebateconfirmheader]
GO
/****** Object:  ForeignKey [FK_MEDifferenceinStock_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEDifferenceinStock]  WITH CHECK ADD  CONSTRAINT [FK_MEDifferenceinStock_aItem] FOREIGN KEY([dsItemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[MEDifferenceinStock] CHECK CONSTRAINT [FK_MEDifferenceinStock_aItem]
GO
/****** Object:  ForeignKey [FK_LosGoodsReturnNoteDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteDetail]  WITH CHECK ADD  CONSTRAINT [FK_LosGoodsReturnNoteDetail_aItem] FOREIGN KEY([GRNDItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LosGoodsReturnNoteDetail] CHECK CONSTRAINT [FK_LosGoodsReturnNoteDetail_aItem]
GO
/****** Object:  ForeignKey [FK_LosGoodsReturnNoteDetail_LosGoodsReturnNoteHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteDetail]  WITH CHECK ADD  CONSTRAINT [FK_LosGoodsReturnNoteDetail_LosGoodsReturnNoteHeader] FOREIGN KEY([GRNDShopid], [GRNDReturnNoteID])
REFERENCES [dbo].[LosGoodsReturnNoteHeader] ([grnhShopid], [GrnhGoodsreturnnoteID])
GO
ALTER TABLE [dbo].[LosGoodsReturnNoteDetail] CHECK CONSTRAINT [FK_LosGoodsReturnNoteDetail_LosGoodsReturnNoteHeader]
GO
/****** Object:  ForeignKey [FK_TillOpeningstock_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[TillOpeningstock]  WITH CHECK ADD  CONSTRAINT [FK_TillOpeningstock_aItem] FOREIGN KEY([itemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[TillOpeningstock] CHECK CONSTRAINT [FK_TillOpeningstock_aItem]
GO
/****** Object:  ForeignKey [FK_MOiGodownStock_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOiGodownStock]  WITH CHECK ADD  CONSTRAINT [FK_MOiGodownStock_aGodown] FOREIGN KEY([gsGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[MOiGodownStock] CHECK CONSTRAINT [FK_MOiGodownStock_aGodown]
GO
/****** Object:  ForeignKey [FK_MOiGodownStock_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOiGodownStock]  WITH CHECK ADD  CONSTRAINT [FK_MOiGodownStock_aItem] FOREIGN KEY([gsItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[MOiGodownStock] CHECK CONSTRAINT [FK_MOiGodownStock_aItem]
GO
/****** Object:  ForeignKey [fk_loslocalpurchasedetail_aitem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseDetail]  WITH CHECK ADD  CONSTRAINT [fk_loslocalpurchasedetail_aitem] FOREIGN KEY([lpdItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LosLocalPurchaseDetail] CHECK CONSTRAINT [fk_loslocalpurchasedetail_aitem]
GO
/****** Object:  ForeignKey [fk_loslocalpurchasedetail_loslocalpurchaseheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosLocalPurchaseDetail]  WITH CHECK ADD  CONSTRAINT [fk_loslocalpurchasedetail_loslocalpurchaseheader] FOREIGN KEY([lpdShopID], [lpdBillID])
REFERENCES [dbo].[LosLocalPurchaseHeader] ([lphShopID], [lphBillID])
GO
ALTER TABLE [dbo].[LosLocalPurchaseDetail] CHECK CONSTRAINT [fk_loslocalpurchasedetail_loslocalpurchaseheader]
GO
/****** Object:  ForeignKey [FK_loPurchaseOrderDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPurchaseOrderDetail]  WITH NOCHECK ADD  CONSTRAINT [FK_loPurchaseOrderDetail_aItem] FOREIGN KEY([poditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[loPurchaseOrderDetail] CHECK CONSTRAINT [FK_loPurchaseOrderDetail_aItem]
GO
/****** Object:  ForeignKey [FK_loPurchaseOrderDetail_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPurchaseOrderDetail]  WITH NOCHECK ADD  CONSTRAINT [FK_loPurchaseOrderDetail_aPackingType] FOREIGN KEY([podpackingtypeID])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[loPurchaseOrderDetail] CHECK CONSTRAINT [FK_loPurchaseOrderDetail_aPackingType]
GO
/****** Object:  ForeignKey [FK_loPurchaseOrderDetail_loPurchaseOrderHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPurchaseOrderDetail]  WITH NOCHECK ADD  CONSTRAINT [FK_loPurchaseOrderDetail_loPurchaseOrderHeader] FOREIGN KEY([podPoid])
REFERENCES [dbo].[loPurchaseOrderHeader] ([pohPoid])
GO
ALTER TABLE [dbo].[loPurchaseOrderDetail] CHECK CONSTRAINT [FK_loPurchaseOrderDetail_loPurchaseOrderHeader]
GO
/****** Object:  ForeignKey [fk_losSerStandByRequestDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerStandByRequestDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSerStandByRequestDetail_aItem] FOREIGN KEY([reqdMachineID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losSerStandByRequestDetail] CHECK CONSTRAINT [fk_losSerStandByRequestDetail_aItem]
GO
/****** Object:  ForeignKey [fk_losSerStandByRequestDetail_losSerStandByRequestHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerStandByRequestDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSerStandByRequestDetail_losSerStandByRequestHeader] FOREIGN KEY([reqdCompanyID], [reqdRequestID], [reqdShopID])
REFERENCES [dbo].[losSerStandByRequestHeader] ([reqhCompanyID], [reqhRequestID], [reqhShopID])
GO
ALTER TABLE [dbo].[losSerStandByRequestDetail] CHECK CONSTRAINT [fk_losSerStandByRequestDetail_losSerStandByRequestHeader]
GO
/****** Object:  ForeignKey [FK_LosReserveItem_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosReserveItem]  WITH CHECK ADD  CONSTRAINT [FK_LosReserveItem_aGodown] FOREIGN KEY([godownid])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[LosReserveItem] CHECK CONSTRAINT [FK_LosReserveItem_aGodown]
GO
/****** Object:  ForeignKey [FK_LosReserveItem_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosReserveItem]  WITH CHECK ADD  CONSTRAINT [FK_LosReserveItem_aItem] FOREIGN KEY([itemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LosReserveItem] CHECK CONSTRAINT [FK_LosReserveItem_aItem]
GO
/****** Object:  ForeignKey [FK_LOSREPLA_REF_686_LOSREPLA]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacereceivedetails]  WITH CHECK ADD  CONSTRAINT [FK_LOSREPLA_REF_686_LOSREPLA] FOREIGN KEY([reprecdid], [reprecdcompanyid], [reprecdshopid])
REFERENCES [dbo].[losreplacereceiveheader] ([reprechid], [reprechcompanyid], [reprechshopid])
GO
ALTER TABLE [dbo].[losreplacereceivedetails] CHECK CONSTRAINT [FK_LOSREPLA_REF_686_LOSREPLA]
GO
/****** Object:  ForeignKey [FK_losreplacereceivedetails_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacereceivedetails]  WITH CHECK ADD  CONSTRAINT [FK_losreplacereceivedetails_aItem] FOREIGN KEY([reprecditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losreplacereceivedetails] CHECK CONSTRAINT [FK_losreplacereceivedetails_aItem]
GO
/****** Object:  ForeignKey [fk_meiSpecialDespatchtoshodeatil_aitem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoShopDetail]  WITH CHECK ADD  CONSTRAINT [fk_meiSpecialDespatchtoshodeatil_aitem] FOREIGN KEY([ddItemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[meiSpecialDespatchtoShopDetail] CHECK CONSTRAINT [fk_meiSpecialDespatchtoshodeatil_aitem]
GO
/****** Object:  ForeignKey [fk_meiSpecialDespatchtoshodeatil_ashipment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoShopDetail]  WITH CHECK ADD  CONSTRAINT [fk_meiSpecialDespatchtoshodeatil_ashipment] FOREIGN KEY([ddShipmentid])
REFERENCES [dbo].[aShipment] ([sShipmentID])
GO
ALTER TABLE [dbo].[meiSpecialDespatchtoShopDetail] CHECK CONSTRAINT [fk_meiSpecialDespatchtoshodeatil_ashipment]
GO
/****** Object:  ForeignKey [fk_meiSpecialDespatchtoshodeatil_ashops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoShopDetail]  WITH CHECK ADD  CONSTRAINT [fk_meiSpecialDespatchtoshodeatil_ashops] FOREIGN KEY([ddShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[meiSpecialDespatchtoShopDetail] CHECK CONSTRAINT [fk_meiSpecialDespatchtoshodeatil_ashops]
GO
/****** Object:  ForeignKey [FK_meiSpecialDespatchtoShopDetail_meiSpecialDespatchtoshopHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoShopDetail]  WITH CHECK ADD  CONSTRAINT [FK_meiSpecialDespatchtoShopDetail_meiSpecialDespatchtoshopHeader] FOREIGN KEY([ddDespatchid], [ddGodownid])
REFERENCES [dbo].[meiSpecialDespatchtoshopHeader] ([dhdespatchid], [dhgodownid])
GO
ALTER TABLE [dbo].[meiSpecialDespatchtoShopDetail] CHECK CONSTRAINT [FK_meiSpecialDespatchtoShopDetail_meiSpecialDespatchtoshopHeader]
GO
/****** Object:  ForeignKey [FK_LOsPosSubItemDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosSubItemDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsPosSubItemDetail_aItem] FOREIGN KEY([posiditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOsPosSubItemDetail] CHECK CONSTRAINT [FK_LOsPosSubItemDetail_aItem]
GO
/****** Object:  ForeignKey [FK_LOsPosSubItemDetail_aItem1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosSubItemDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsPosSubItemDetail_aItem1] FOREIGN KEY([posidsubitemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOsPosSubItemDetail] CHECK CONSTRAINT [FK_LOsPosSubItemDetail_aItem1]
GO
/****** Object:  ForeignKey [FK_LOsPosSubItemDetail_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosSubItemDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsPosSubItemDetail_aPackingType] FOREIGN KEY([posidpackingtypeid])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[LOsPosSubItemDetail] CHECK CONSTRAINT [FK_LOsPosSubItemDetail_aPackingType]
GO
/****** Object:  ForeignKey [FK_LOsPosSubItemDetail_LOsPosHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosSubItemDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsPosSubItemDetail_LOsPosHeader] FOREIGN KEY([posidshopid], [posidbillid])
REFERENCES [dbo].[LOsPosHeader] ([poshShopID], [poshBillID])
GO
ALTER TABLE [dbo].[LOsPosSubItemDetail] CHECK CONSTRAINT [FK_LOsPosSubItemDetail_LOsPosHeader]
GO
/****** Object:  ForeignKey [fk_aPurchasePriceRangeHistory_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPurchasePriceRangeHistory]  WITH CHECK ADD  CONSTRAINT [fk_aPurchasePriceRangeHistory_aCompanyMaster] FOREIGN KEY([CompanyId])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aPurchasePriceRangeHistory] CHECK CONSTRAINT [fk_aPurchasePriceRangeHistory_aCompanyMaster]
GO
/****** Object:  ForeignKey [fk_aPurchasePriceRangeHistory_aCurrencyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPurchasePriceRangeHistory]  WITH CHECK ADD  CONSTRAINT [fk_aPurchasePriceRangeHistory_aCurrencyMaster] FOREIGN KEY([CurrencyId], [CompanyId])
REFERENCES [dbo].[aCurrencyMaster] ([CurrencyID], [CompanyID])
GO
ALTER TABLE [dbo].[aPurchasePriceRangeHistory] CHECK CONSTRAINT [fk_aPurchasePriceRangeHistory_aCurrencyMaster]
GO
/****** Object:  ForeignKey [fk_aPurchasePriceRangeHistory_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPurchasePriceRangeHistory]  WITH CHECK ADD  CONSTRAINT [fk_aPurchasePriceRangeHistory_aItem] FOREIGN KEY([ItemId])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[aPurchasePriceRangeHistory] CHECK CONSTRAINT [fk_aPurchasePriceRangeHistory_aItem]
GO
/****** Object:  ForeignKey [FK_loaItemSplitCostingDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loaItemSplitCostingDetail]  WITH CHECK ADD  CONSTRAINT [FK_loaItemSplitCostingDetail_aItem] FOREIGN KEY([scfdItemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[loaItemSplitCostingDetail] CHECK CONSTRAINT [FK_loaItemSplitCostingDetail_aItem]
GO
/****** Object:  ForeignKey [FK_loaItemSplitCostingDetail_loaItemsplitcostingHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loaItemSplitCostingDetail]  WITH CHECK ADD  CONSTRAINT [FK_loaItemSplitCostingDetail_loaItemsplitcostingHeader] FOREIGN KEY([scfdid])
REFERENCES [dbo].[loaItemsplitcostingHeader] ([scfhid])
GO
ALTER TABLE [dbo].[loaItemSplitCostingDetail] CHECK CONSTRAINT [FK_loaItemSplitCostingDetail_loaItemsplitcostingHeader]
GO
/****** Object:  ForeignKey [FK_losStockVerificationDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockVerificationDetail]  WITH CHECK ADD  CONSTRAINT [FK_losStockVerificationDetail_aItem] FOREIGN KEY([svditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losStockVerificationDetail] CHECK CONSTRAINT [FK_losStockVerificationDetail_aItem]
GO
/****** Object:  ForeignKey [FK_losStockVerificationDetail_losStockVerificationHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockVerificationDetail]  WITH CHECK ADD  CONSTRAINT [FK_losStockVerificationDetail_losStockVerificationHeader] FOREIGN KEY([svdid], [svdShopid])
REFERENCES [dbo].[losStockVerificationHeader] ([svhid], [svhShopId])
GO
ALTER TABLE [dbo].[losStockVerificationDetail] CHECK CONSTRAINT [FK_losStockVerificationDetail_losStockVerificationHeader]
GO
/****** Object:  ForeignKey [FK_LoiItemSplitDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LoiItemSplitDetail]  WITH CHECK ADD  CONSTRAINT [FK_LoiItemSplitDetail_aItem] FOREIGN KEY([isditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LoiItemSplitDetail] CHECK CONSTRAINT [FK_LoiItemSplitDetail_aItem]
GO
/****** Object:  ForeignKey [FK_LoiItemSplitDetail_LoiItemSplitHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LoiItemSplitDetail]  WITH CHECK ADD  CONSTRAINT [FK_LoiItemSplitDetail_LoiItemSplitHeader] FOREIGN KEY([isdgodownid], [isdid])
REFERENCES [dbo].[LoiItemSplitHeader] ([ishgodownid], [ishid])
GO
ALTER TABLE [dbo].[LoiItemSplitDetail] CHECK CONSTRAINT [FK_LoiItemSplitDetail_LoiItemSplitHeader]
GO
/****** Object:  ForeignKey [fk_losSerMaintenanceServiceDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerMaintenanceServiceDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSerMaintenanceServiceDetail_aItem] FOREIGN KEY([msdMachineID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losSerMaintenanceServiceDetail] CHECK CONSTRAINT [fk_losSerMaintenanceServiceDetail_aItem]
GO
/****** Object:  ForeignKey [fk_losSerMaintenanceServiceDetail_aservicemaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerMaintenanceServiceDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSerMaintenanceServiceDetail_aservicemaster] FOREIGN KEY([msdServiceID], [msdCompanyID])
REFERENCES [dbo].[aservicemaster] ([serid], [sercompanyid])
GO
ALTER TABLE [dbo].[losSerMaintenanceServiceDetail] CHECK CONSTRAINT [fk_losSerMaintenanceServiceDetail_aservicemaster]
GO
/****** Object:  ForeignKey [fk_losSerMaintenanceServiceDetail_losSerMaintenanceContractHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerMaintenanceServiceDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSerMaintenanceServiceDetail_losSerMaintenanceContractHeader] FOREIGN KEY([msdCompanyID], [msdMCID], [msdShopID])
REFERENCES [dbo].[losSerMaintenanceContractHeader] ([mchCompanyID], [mchID], [mchShopID])
GO
ALTER TABLE [dbo].[losSerMaintenanceServiceDetail] CHECK CONSTRAINT [fk_losSerMaintenanceServiceDetail_losSerMaintenanceContractHeader]
GO
/****** Object:  ForeignKey [FK_mesRequesttoShopDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesRequesttoShopDetail]  WITH CHECK ADD  CONSTRAINT [FK_mesRequesttoShopDetail_aItem] FOREIGN KEY([srditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[mesRequesttoShopDetail] CHECK CONSTRAINT [FK_mesRequesttoShopDetail_aItem]
GO
/****** Object:  ForeignKey [FK_mesRequesttoShopDetail_aShops1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesRequesttoShopDetail]  WITH CHECK ADD  CONSTRAINT [FK_mesRequesttoShopDetail_aShops1] FOREIGN KEY([srdToShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[mesRequesttoShopDetail] CHECK CONSTRAINT [FK_mesRequesttoShopDetail_aShops1]
GO
/****** Object:  ForeignKey [FK_mesRequesttoShopDetail_mesRequesttoShopHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesRequesttoShopDetail]  WITH CHECK ADD  CONSTRAINT [FK_mesRequesttoShopDetail_mesRequesttoShopHeader] FOREIGN KEY([srdshopid], [SRDrequestid])
REFERENCES [dbo].[mesRequesttoShopHeader] ([SRHshopid], [SRHrequestID])
GO
ALTER TABLE [dbo].[mesRequesttoShopDetail] CHECK CONSTRAINT [FK_mesRequesttoShopDetail_mesRequesttoShopHeader]
GO
/****** Object:  ForeignKey [FK_LOspPurchaseBillDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOspPurchaseBillDetail_aItem] FOREIGN KEY([pbdItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOspPurchaseBillDetail] CHECK CONSTRAINT [FK_LOspPurchaseBillDetail_aItem]
GO
/****** Object:  ForeignKey [fk_losppurchasebilldetail_apackingtype]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillDetail]  WITH CHECK ADD  CONSTRAINT [fk_losppurchasebilldetail_apackingtype] FOREIGN KEY([pbdPackingTypeID])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[LOspPurchaseBillDetail] CHECK CONSTRAINT [fk_losppurchasebilldetail_apackingtype]
GO
/****** Object:  ForeignKey [FK_LOspPurchaseBillDetail_loPurchaseOrderHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillDetail]  WITH NOCHECK ADD  CONSTRAINT [FK_LOspPurchaseBillDetail_loPurchaseOrderHeader] FOREIGN KEY([pbdpoid])
REFERENCES [dbo].[loPurchaseOrderHeader] ([pohPoid])
GO
ALTER TABLE [dbo].[LOspPurchaseBillDetail] CHECK CONSTRAINT [FK_LOspPurchaseBillDetail_loPurchaseOrderHeader]
GO
/****** Object:  ForeignKey [FK_LOspPurchaseBillDetail_LOspPurchaseBillHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOspPurchaseBillDetail_LOspPurchaseBillHeader] FOREIGN KEY([pbdBillID])
REFERENCES [dbo].[LOspPurchaseBillHeader] ([pbhBillID])
GO
ALTER TABLE [dbo].[LOspPurchaseBillDetail] CHECK CONSTRAINT [FK_LOspPurchaseBillDetail_LOspPurchaseBillHeader]
GO
/****** Object:  ForeignKey [fk_aPurchasePriceRange_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPurchasePriceRange]  WITH CHECK ADD  CONSTRAINT [fk_aPurchasePriceRange_aCompanyMaster] FOREIGN KEY([CompanyId])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aPurchasePriceRange] CHECK CONSTRAINT [fk_aPurchasePriceRange_aCompanyMaster]
GO
/****** Object:  ForeignKey [fk_aPurchasePriceRange_aCurrencyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPurchasePriceRange]  WITH CHECK ADD  CONSTRAINT [fk_aPurchasePriceRange_aCurrencyMaster] FOREIGN KEY([CurrencyId], [CompanyId])
REFERENCES [dbo].[aCurrencyMaster] ([CurrencyID], [CompanyID])
GO
ALTER TABLE [dbo].[aPurchasePriceRange] CHECK CONSTRAINT [fk_aPurchasePriceRange_aCurrencyMaster]
GO
/****** Object:  ForeignKey [fk_aPurchasePriceRange_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPurchasePriceRange]  WITH CHECK ADD  CONSTRAINT [fk_aPurchasePriceRange_aItem] FOREIGN KEY([ItemId])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[aPurchasePriceRange] CHECK CONSTRAINT [fk_aPurchasePriceRange_aItem]
GO
/****** Object:  ForeignKey [FK_losShopItemShipmentDetail_aCurrencyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losShopItemShipmentDetail]  WITH NOCHECK ADD  CONSTRAINT [FK_losShopItemShipmentDetail_aCurrencyMaster] FOREIGN KEY([currencyid], [companyid])
REFERENCES [dbo].[aCurrencyMaster] ([CurrencyID], [CompanyID])
GO
ALTER TABLE [dbo].[losShopItemShipmentDetail] CHECK CONSTRAINT [FK_losShopItemShipmentDetail_aCurrencyMaster]
GO
/****** Object:  ForeignKey [FK_losShopItemShipmentDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losShopItemShipmentDetail]  WITH NOCHECK ADD  CONSTRAINT [FK_losShopItemShipmentDetail_aItem] FOREIGN KEY([itemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losShopItemShipmentDetail] CHECK CONSTRAINT [FK_losShopItemShipmentDetail_aItem]
GO
/****** Object:  ForeignKey [FK_losShopItemShipmentDetail_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losShopItemShipmentDetail]  WITH NOCHECK ADD  CONSTRAINT [FK_losShopItemShipmentDetail_aPackingType] FOREIGN KEY([PackingTypeid])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[losShopItemShipmentDetail] CHECK CONSTRAINT [FK_losShopItemShipmentDetail_aPackingType]
GO
/****** Object:  ForeignKey [fk_losshopitemshipmentdetail_asegmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losShopItemShipmentDetail]  WITH NOCHECK ADD  CONSTRAINT [fk_losshopitemshipmentdetail_asegmentmaster] FOREIGN KEY([companyid], [segmentid])
REFERENCES [dbo].[ASegmentMaster] ([companyid], [Segmentid])
GO
ALTER TABLE [dbo].[losShopItemShipmentDetail] CHECK CONSTRAINT [fk_losshopitemshipmentdetail_asegmentmaster]
GO
/****** Object:  ForeignKey [FK_losShopItemShipmentDetail_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losShopItemShipmentDetail]  WITH NOCHECK ADD  CONSTRAINT [FK_losShopItemShipmentDetail_aShops] FOREIGN KEY([shopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losShopItemShipmentDetail] CHECK CONSTRAINT [FK_losShopItemShipmentDetail_aShops]
GO
/****** Object:  ForeignKey [FK_MOsShopStock_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOsShopStock]  WITH CHECK ADD  CONSTRAINT [FK_MOsShopStock_aItem] FOREIGN KEY([ItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[MOsShopStock] CHECK CONSTRAINT [FK_MOsShopStock_aItem]
GO
/****** Object:  ForeignKey [FK_MOsShopStock_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOsShopStock]  WITH CHECK ADD  CONSTRAINT [FK_MOsShopStock_aShops] FOREIGN KEY([ShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[MOsShopStock] CHECK CONSTRAINT [FK_MOsShopStock_aShops]
GO
/****** Object:  ForeignKey [FK_loiStockVerificationDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockVerificationDetail]  WITH CHECK ADD  CONSTRAINT [FK_loiStockVerificationDetail_aItem] FOREIGN KEY([svdItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[loiStockVerificationDetail] CHECK CONSTRAINT [FK_loiStockVerificationDetail_aItem]
GO
/****** Object:  ForeignKey [fk_loiStockVerificationDetail_ashipment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockVerificationDetail]  WITH CHECK ADD  CONSTRAINT [fk_loiStockVerificationDetail_ashipment] FOREIGN KEY([svdShipmentID])
REFERENCES [dbo].[aShipment] ([sShipmentID])
GO
ALTER TABLE [dbo].[loiStockVerificationDetail] CHECK CONSTRAINT [fk_loiStockVerificationDetail_ashipment]
GO
/****** Object:  ForeignKey [fk_loiStockVerificationDetail_loilocation]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockVerificationDetail]  WITH CHECK ADD  CONSTRAINT [fk_loiStockVerificationDetail_loilocation] FOREIGN KEY([svdGodownID], [svdLocationid])
REFERENCES [dbo].[LOiLocation] ([lGodownID], [lLocationID])
GO
ALTER TABLE [dbo].[loiStockVerificationDetail] CHECK CONSTRAINT [fk_loiStockVerificationDetail_loilocation]
GO
/****** Object:  ForeignKey [FK_loiStockVerificationDetail_loiStockVerificationHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockVerificationDetail]  WITH CHECK ADD  CONSTRAINT [FK_loiStockVerificationDetail_loiStockVerificationHeader] FOREIGN KEY([svdid], [svdGodownID])
REFERENCES [dbo].[loiStockVerificationHeader] ([svhid], [svhGodownid])
GO
ALTER TABLE [dbo].[loiStockVerificationDetail] CHECK CONSTRAINT [FK_loiStockVerificationDetail_loiStockVerificationHeader]
GO
/****** Object:  ForeignKey [FK_loilocationarrivaldetails_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loilocationarrivaldetails]  WITH CHECK ADD  CONSTRAINT [FK_loilocationarrivaldetails_aItem] FOREIGN KEY([laditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[loilocationarrivaldetails] CHECK CONSTRAINT [FK_loilocationarrivaldetails_aItem]
GO
/****** Object:  ForeignKey [FK_loilocationarrivaldetails_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loilocationarrivaldetails]  WITH CHECK ADD  CONSTRAINT [FK_loilocationarrivaldetails_aPackingType] FOREIGN KEY([ladpackingtypeid])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[loilocationarrivaldetails] CHECK CONSTRAINT [FK_loilocationarrivaldetails_aPackingType]
GO
/****** Object:  ForeignKey [FK_loilocationarrivaldetails_LOiLocation]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loilocationarrivaldetails]  WITH CHECK ADD  CONSTRAINT [FK_loilocationarrivaldetails_LOiLocation] FOREIGN KEY([ladgodownid], [ladlocationid])
REFERENCES [dbo].[LOiLocation] ([lGodownID], [lLocationID])
GO
ALTER TABLE [dbo].[loilocationarrivaldetails] CHECK CONSTRAINT [FK_loilocationarrivaldetails_LOiLocation]
GO
/****** Object:  ForeignKey [FK_aGodownDetail_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodownDetail]  WITH CHECK ADD  CONSTRAINT [FK_aGodownDetail_aGodown] FOREIGN KEY([GodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[aGodownDetail] CHECK CONSTRAINT [FK_aGodownDetail_aGodown]
GO
/****** Object:  ForeignKey [FK_aGodownDetail_Item]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodownDetail]  WITH CHECK ADD  CONSTRAINT [FK_aGodownDetail_Item] FOREIGN KEY([ItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[aGodownDetail] CHECK CONSTRAINT [FK_aGodownDetail_Item]
GO
/****** Object:  ForeignKey [FK_MEiGodownTransferDetail_aGodown1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiGodownTransferDetail]  WITH CHECK ADD  CONSTRAINT [FK_MEiGodownTransferDetail_aGodown1] FOREIGN KEY([gtdToGodownid])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[MEiGodownTransferDetail] CHECK CONSTRAINT [FK_MEiGodownTransferDetail_aGodown1]
GO
/****** Object:  ForeignKey [FK_MEiGodownTransferDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiGodownTransferDetail]  WITH CHECK ADD  CONSTRAINT [FK_MEiGodownTransferDetail_aItem] FOREIGN KEY([gtdItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[MEiGodownTransferDetail] CHECK CONSTRAINT [FK_MEiGodownTransferDetail_aItem]
GO
/****** Object:  ForeignKey [fk_MEiGodownTransferDetail_ashipment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiGodownTransferDetail]  WITH CHECK ADD  CONSTRAINT [fk_MEiGodownTransferDetail_ashipment] FOREIGN KEY([gtdShipmentID])
REFERENCES [dbo].[aShipment] ([sShipmentID])
GO
ALTER TABLE [dbo].[MEiGodownTransferDetail] CHECK CONSTRAINT [fk_MEiGodownTransferDetail_ashipment]
GO
/****** Object:  ForeignKey [fk_MEiGodownTransferDetail_loilocation]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiGodownTransferDetail]  WITH CHECK ADD  CONSTRAINT [fk_MEiGodownTransferDetail_loilocation] FOREIGN KEY([gtdGodownID], [gtdLocationID])
REFERENCES [dbo].[LOiLocation] ([lGodownID], [lLocationID])
GO
ALTER TABLE [dbo].[MEiGodownTransferDetail] CHECK CONSTRAINT [fk_MEiGodownTransferDetail_loilocation]
GO
/****** Object:  ForeignKey [FK_MEiGodownTransferDetail_MEiGodownTransferHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiGodownTransferDetail]  WITH CHECK ADD  CONSTRAINT [FK_MEiGodownTransferDetail_MEiGodownTransferHeader] FOREIGN KEY([gtdDespatchID], [gtdGodownID])
REFERENCES [dbo].[MEiGodownTransferHeader] ([gthDespatchID], [gthFromGodownID])
GO
ALTER TABLE [dbo].[MEiGodownTransferDetail] CHECK CONSTRAINT [FK_MEiGodownTransferDetail_MEiGodownTransferHeader]
GO
/****** Object:  ForeignKey [FK_Fb_DishAdds_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Fb_DishAdds]  WITH CHECK ADD  CONSTRAINT [FK_Fb_DishAdds_aItem] FOREIGN KEY([Fb_da_itemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[Fb_DishAdds] CHECK CONSTRAINT [FK_Fb_DishAdds_aItem]
GO
/****** Object:  ForeignKey [FK_Fb_DishAdds_FB_Dishdetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Fb_DishAdds]  WITH CHECK ADD  CONSTRAINT [FK_Fb_DishAdds_FB_Dishdetails] FOREIGN KEY([Fb_da_Companyid], [Fb_da_dishid])
REFERENCES [dbo].[FB_Dishdetails] ([fb_dd_companyid], [fb_dd_dishid])
GO
ALTER TABLE [dbo].[Fb_DishAdds] CHECK CONSTRAINT [FK_Fb_DishAdds_FB_Dishdetails]
GO
/****** Object:  ForeignKey [FK_loPrePurchaseOrderDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderDetail]  WITH CHECK ADD  CONSTRAINT [FK_loPrePurchaseOrderDetail_aItem] FOREIGN KEY([poditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[loPrePurchaseOrderDetail] CHECK CONSTRAINT [FK_loPrePurchaseOrderDetail_aItem]
GO
/****** Object:  ForeignKey [FK_loPrePurchaseOrderDetail_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderDetail]  WITH CHECK ADD  CONSTRAINT [FK_loPrePurchaseOrderDetail_aPackingType] FOREIGN KEY([podpackingtypeID])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[loPrePurchaseOrderDetail] CHECK CONSTRAINT [FK_loPrePurchaseOrderDetail_aPackingType]
GO
/****** Object:  ForeignKey [FK_loPrePurchaseOrderDetail_loPrePurchaseOrderHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderDetail]  WITH CHECK ADD  CONSTRAINT [FK_loPrePurchaseOrderDetail_loPrePurchaseOrderHeader] FOREIGN KEY([podPoid])
REFERENCES [dbo].[loPrePurchaseOrderHeader] ([pohPoid])
GO
ALTER TABLE [dbo].[loPrePurchaseOrderDetail] CHECK CONSTRAINT [FK_loPrePurchaseOrderDetail_loPrePurchaseOrderHeader]
GO
/****** Object:  ForeignKey [FK_loPurchasereturndetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPurchasereturndetail]  WITH CHECK ADD  CONSTRAINT [FK_loPurchasereturndetail_aItem] FOREIGN KEY([prditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[loPurchasereturndetail] CHECK CONSTRAINT [FK_loPurchasereturndetail_aItem]
GO
/****** Object:  ForeignKey [FK_loPurchasereturndetail_loPurchasereturnheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPurchasereturndetail]  WITH CHECK ADD  CONSTRAINT [FK_loPurchasereturndetail_loPurchasereturnheader] FOREIGN KEY([prdcompanyid], [prdreturnid])
REFERENCES [dbo].[loPurchasereturnheader] ([prhcompanyid], [prhreturnid])
GO
ALTER TABLE [dbo].[loPurchasereturndetail] CHECK CONSTRAINT [FK_loPurchasereturndetail_loPurchasereturnheader]
GO
/****** Object:  ForeignKey [FK_loiStockRecovery_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockRecovery]  WITH CHECK ADD  CONSTRAINT [FK_loiStockRecovery_aGodown] FOREIGN KEY([srGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[loiStockRecovery] CHECK CONSTRAINT [FK_loiStockRecovery_aGodown]
GO
/****** Object:  ForeignKey [FK_loiStockRecovery_aGodown1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockRecovery]  WITH CHECK ADD  CONSTRAINT [FK_loiStockRecovery_aGodown1] FOREIGN KEY([srGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[loiStockRecovery] CHECK CONSTRAINT [FK_loiStockRecovery_aGodown1]
GO
/****** Object:  ForeignKey [FK_loiStockRecovery_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockRecovery]  WITH CHECK ADD  CONSTRAINT [FK_loiStockRecovery_aItem] FOREIGN KEY([srItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[loiStockRecovery] CHECK CONSTRAINT [FK_loiStockRecovery_aItem]
GO
/****** Object:  ForeignKey [FK_aHpItemDetails_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHpItemDetails]  WITH CHECK ADD  CONSTRAINT [FK_aHpItemDetails_aItem] FOREIGN KEY([ItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[aHpItemDetails] CHECK CONSTRAINT [FK_aHpItemDetails_aItem]
GO
/****** Object:  ForeignKey [FK_aItemPackingDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aItemPackingDetail]  WITH CHECK ADD  CONSTRAINT [FK_aItemPackingDetail_aItem] FOREIGN KEY([ItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[aItemPackingDetail] CHECK CONSTRAINT [FK_aItemPackingDetail_aItem]
GO
/****** Object:  ForeignKey [fk_aitemPackingDetail_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aItemPackingDetail]  WITH CHECK ADD  CONSTRAINT [fk_aitemPackingDetail_aPackingType] FOREIGN KEY([PackingTypeID])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[aItemPackingDetail] CHECK CONSTRAINT [fk_aitemPackingDetail_aPackingType]
GO
/****** Object:  ForeignKey [FK_aShopItemDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopItemDetail]  WITH CHECK ADD  CONSTRAINT [FK_aShopItemDetail_aItem] FOREIGN KEY([ItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[aShopItemDetail] CHECK CONSTRAINT [FK_aShopItemDetail_aItem]
GO
/****** Object:  ForeignKey [FK_aShopItemDetail_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopItemDetail]  WITH CHECK ADD  CONSTRAINT [FK_aShopItemDetail_aShops] FOREIGN KEY([ShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[aShopItemDetail] CHECK CONSTRAINT [FK_aShopItemDetail_aShops]
GO
/****** Object:  ForeignKey [FK_mosshopservicestock_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mosshopservicestock]  WITH CHECK ADD  CONSTRAINT [FK_mosshopservicestock_aCompanyMaster] FOREIGN KEY([serstkcompanyid])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[mosshopservicestock] CHECK CONSTRAINT [FK_mosshopservicestock_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_mosshopservicestock_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mosshopservicestock]  WITH CHECK ADD  CONSTRAINT [FK_mosshopservicestock_aItem] FOREIGN KEY([serstkitemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[mosshopservicestock] CHECK CONSTRAINT [FK_mosshopservicestock_aItem]
GO
/****** Object:  ForeignKey [FK_mosshopservicestock_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mosshopservicestock]  WITH CHECK ADD  CONSTRAINT [FK_mosshopservicestock_aShops] FOREIGN KEY([serstkshopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[mosshopservicestock] CHECK CONSTRAINT [FK_mosshopservicestock_aShops]
GO
/****** Object:  ForeignKey [FK_moapoitems_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[moapoitems]  WITH CHECK ADD  CONSTRAINT [FK_moapoitems_aItem] FOREIGN KEY([itemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[moapoitems] CHECK CONSTRAINT [FK_moapoitems_aItem]
GO
/****** Object:  ForeignKey [FK_moapoitems_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[moapoitems]  WITH CHECK ADD  CONSTRAINT [FK_moapoitems_aShops] FOREIGN KEY([shopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[moapoitems] CHECK CONSTRAINT [FK_moapoitems_aShops]
GO
/****** Object:  ForeignKey [FK_moStockWriteOffHQ_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[moStockWriteOffHQ]  WITH CHECK ADD  CONSTRAINT [FK_moStockWriteOffHQ_aGodown] FOREIGN KEY([swGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[moStockWriteOffHQ] CHECK CONSTRAINT [FK_moStockWriteOffHQ_aGodown]
GO
/****** Object:  ForeignKey [FK_moStockWriteOffHQ_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[moStockWriteOffHQ]  WITH CHECK ADD  CONSTRAINT [FK_moStockWriteOffHQ_aItem] FOREIGN KEY([swItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[moStockWriteOffHQ] CHECK CONSTRAINT [FK_moStockWriteOffHQ_aItem]
GO
/****** Object:  ForeignKey [fk_losSerStandByReceiptDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerStandByReceiptDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSerStandByReceiptDetail_aItem] FOREIGN KEY([rdMachineID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losSerStandByReceiptDetail] CHECK CONSTRAINT [fk_losSerStandByReceiptDetail_aItem]
GO
/****** Object:  ForeignKey [fk_losSerStandByReceiptDetail_losSerStandByReceiptHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerStandByReceiptDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSerStandByReceiptDetail_losSerStandByReceiptHeader] FOREIGN KEY([rdCompanyID], [rdShopID], [rdReceiptID])
REFERENCES [dbo].[losSerStandByReceiptHeader] ([rhCompanyID], [rhShopID], [rhReceiptID])
GO
ALTER TABLE [dbo].[losSerStandByReceiptDetail] CHECK CONSTRAINT [fk_losSerStandByReceiptDetail_losSerStandByReceiptHeader]
GO
/****** Object:  ForeignKey [fk_losSerStandByIssueDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerStandByIssueDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSerStandByIssueDetail_aItem] FOREIGN KEY([isdMachineID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losSerStandByIssueDetail] CHECK CONSTRAINT [fk_losSerStandByIssueDetail_aItem]
GO
/****** Object:  ForeignKey [fk_losSerStandByIssueDetail_losSerStandByIssueHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerStandByIssueDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSerStandByIssueDetail_losSerStandByIssueHeader] FOREIGN KEY([isdCompanyID], [isdIssueID], [isdShopID])
REFERENCES [dbo].[losSerStandByIssueHeader] ([ishCompanyID], [ishIssueID], [ishShopID])
GO
ALTER TABLE [dbo].[losSerStandByIssueDetail] CHECK CONSTRAINT [fk_losSerStandByIssueDetail_losSerStandByIssueHeader]
GO
/****** Object:  ForeignKey [FK_mosGoodsRequestDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mosGoodsRequestDetail]  WITH CHECK ADD  CONSTRAINT [FK_mosGoodsRequestDetail_aItem] FOREIGN KEY([GRDitemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[mosGoodsRequestDetail] CHECK CONSTRAINT [FK_mosGoodsRequestDetail_aItem]
GO
/****** Object:  ForeignKey [FK_aSubItemDetails_aItem1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSubItemDetails]  WITH CHECK ADD  CONSTRAINT [FK_aSubItemDetails_aItem1] FOREIGN KEY([ItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[aSubItemDetails] CHECK CONSTRAINT [FK_aSubItemDetails_aItem1]
GO
/****** Object:  ForeignKey [FK_aSubItemDetails_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSubItemDetails]  WITH CHECK ADD  CONSTRAINT [FK_aSubItemDetails_aPackingType] FOREIGN KEY([PackingTypeID])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[aSubItemDetails] CHECK CONSTRAINT [FK_aSubItemDetails_aPackingType]
GO
/****** Object:  ForeignKey [FK_aSubItemDetails_aUnit]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSubItemDetails]  WITH CHECK ADD  CONSTRAINT [FK_aSubItemDetails_aUnit] FOREIGN KEY([UnitsID])
REFERENCES [dbo].[aUnit] ([UnitID])
GO
ALTER TABLE [dbo].[aSubItemDetails] CHECK CONSTRAINT [FK_aSubItemDetails_aUnit]
GO
/****** Object:  ForeignKey [FK_loalocalpurchasecostingdetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loalocalpurchasecostingdetail]  WITH CHECK ADD  CONSTRAINT [FK_loalocalpurchasecostingdetail_aItem] FOREIGN KEY([lpcditemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[loalocalpurchasecostingdetail] CHECK CONSTRAINT [FK_loalocalpurchasecostingdetail_aItem]
GO
/****** Object:  ForeignKey [FK_loalocalpurchasecostingdetail_loalocalpurchaseCostingheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loalocalpurchasecostingdetail]  WITH CHECK ADD  CONSTRAINT [FK_loalocalpurchasecostingdetail_loalocalpurchaseCostingheader] FOREIGN KEY([lpcdcostingid])
REFERENCES [dbo].[loalocalpurchaseCostingheader] ([lpchCostingid])
GO
ALTER TABLE [dbo].[loalocalpurchasecostingdetail] CHECK CONSTRAINT [FK_loalocalpurchasecostingdetail_loalocalpurchaseCostingheader]
GO
/****** Object:  ForeignKey [fk_aHQIssuenotedetail_agodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteDetail]  WITH CHECK ADD  CONSTRAINT [fk_aHQIssuenotedetail_agodown] FOREIGN KEY([INDGodownid])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[aHQIssuenoteDetail] CHECK CONSTRAINT [fk_aHQIssuenotedetail_agodown]
GO
/****** Object:  ForeignKey [FK_aHQIssuenoteDetail_aHQIssuenoteHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteDetail]  WITH CHECK ADD  CONSTRAINT [FK_aHQIssuenoteDetail_aHQIssuenoteHeader] FOREIGN KEY([INDIssuenoteID])
REFERENCES [dbo].[aHQIssuenoteHeader] ([INHIssuenoteID])
GO
ALTER TABLE [dbo].[aHQIssuenoteDetail] CHECK CONSTRAINT [FK_aHQIssuenoteDetail_aHQIssuenoteHeader]
GO
/****** Object:  ForeignKey [fk_aHQIssuenotedetail_aitem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteDetail]  WITH CHECK ADD  CONSTRAINT [fk_aHQIssuenotedetail_aitem] FOREIGN KEY([INDItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[aHQIssuenoteDetail] CHECK CONSTRAINT [fk_aHQIssuenotedetail_aitem]
GO
/****** Object:  ForeignKey [fk_aHQIssuenotedetail_ashipment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteDetail]  WITH CHECK ADD  CONSTRAINT [fk_aHQIssuenotedetail_ashipment] FOREIGN KEY([INDShipmentID])
REFERENCES [dbo].[aShipment] ([sShipmentID])
GO
ALTER TABLE [dbo].[aHQIssuenoteDetail] CHECK CONSTRAINT [fk_aHQIssuenotedetail_ashipment]
GO
/****** Object:  ForeignKey [fk_aHQIssuenotedetail_loilocation]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteDetail]  WITH CHECK ADD  CONSTRAINT [fk_aHQIssuenotedetail_loilocation] FOREIGN KEY([INDGodownid], [INDLocationID])
REFERENCES [dbo].[LOiLocation] ([lGodownID], [lLocationID])
GO
ALTER TABLE [dbo].[aHQIssuenoteDetail] CHECK CONSTRAINT [fk_aHQIssuenotedetail_loilocation]
GO
/****** Object:  ForeignKey [FK_MEiDespatchToShopDetail_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiDespatchToShopDetail]  WITH CHECK ADD  CONSTRAINT [FK_MEiDespatchToShopDetail_aItem] FOREIGN KEY([ddItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[MEiDespatchToShopDetail] CHECK CONSTRAINT [FK_MEiDespatchToShopDetail_aItem]
GO
/****** Object:  ForeignKey [FK_MEiDespatchToShopDetail_MEiDespatchToShopHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiDespatchToShopDetail]  WITH CHECK ADD  CONSTRAINT [FK_MEiDespatchToShopDetail_MEiDespatchToShopHeader] FOREIGN KEY([ddDespatchID], [ddGodownID])
REFERENCES [dbo].[MEiDespatchToShopHeader] ([dhDespatchID], [dhGodownID])
GO
ALTER TABLE [dbo].[MEiDespatchToShopDetail] CHECK CONSTRAINT [FK_MEiDespatchToShopDetail_MEiDespatchToShopHeader]
GO
/****** Object:  ForeignKey [FK_LOsGoodsArrivaltoShopDetail_aItem1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsGoodsArrivaltoShopDetail_aItem1] FOREIGN KEY([gadItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopDetail] CHECK CONSTRAINT [FK_LOsGoodsArrivaltoShopDetail_aItem1]
GO
/****** Object:  ForeignKey [FK_LOsGoodsArrivaltoShopDetail_LOsGoodsArrivaltoShopHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopDetail]  WITH CHECK ADD  CONSTRAINT [FK_LOsGoodsArrivaltoShopDetail_LOsGoodsArrivaltoShopHeader] FOREIGN KEY([gadArrivalID], [gadShopid])
REFERENCES [dbo].[LOsGoodsArrivaltoShopHeader] ([gahArrivalID], [gahShopid])
GO
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopDetail] CHECK CONSTRAINT [FK_LOsGoodsArrivaltoShopDetail_LOsGoodsArrivaltoShopHeader]
GO
/****** Object:  ForeignKey [FK_losStockRecovery_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockRecovery]  WITH CHECK ADD  CONSTRAINT [FK_losStockRecovery_aItem] FOREIGN KEY([srItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losStockRecovery] CHECK CONSTRAINT [FK_losStockRecovery_aItem]
GO
/****** Object:  ForeignKey [FK_losStockRecovery_aItem1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockRecovery]  WITH CHECK ADD  CONSTRAINT [FK_losStockRecovery_aItem1] FOREIGN KEY([srItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[losStockRecovery] CHECK CONSTRAINT [FK_losStockRecovery_aItem1]
GO
/****** Object:  ForeignKey [FK_losStockRecovery_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockRecovery]  WITH CHECK ADD  CONSTRAINT [FK_losStockRecovery_aShops] FOREIGN KEY([srShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losStockRecovery] CHECK CONSTRAINT [FK_losStockRecovery_aShops]
GO
/****** Object:  ForeignKey [FK_losStockRecovery_aShops1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockRecovery]  WITH CHECK ADD  CONSTRAINT [FK_losStockRecovery_aShops1] FOREIGN KEY([srShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losStockRecovery] CHECK CONSTRAINT [FK_losStockRecovery_aShops1]
GO
/****** Object:  ForeignKey [fk_aserviceitemdetails_aitem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aserviceitemdetails]  WITH CHECK ADD  CONSTRAINT [fk_aserviceitemdetails_aitem] FOREIGN KEY([ItemId])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[aserviceitemdetails] CHECK CONSTRAINT [fk_aserviceitemdetails_aitem]
GO
/****** Object:  ForeignKey [FK_Fb_recipedetails_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Fb_recipedetails]  WITH CHECK ADD  CONSTRAINT [FK_Fb_recipedetails_aItem] FOREIGN KEY([Fb_rd_itemid])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[Fb_recipedetails] CHECK CONSTRAINT [FK_Fb_recipedetails_aItem]
GO
/****** Object:  ForeignKey [FK_Fb_recipedetails_FB_Dishdetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Fb_recipedetails]  WITH CHECK ADD  CONSTRAINT [FK_Fb_recipedetails_FB_Dishdetails] FOREIGN KEY([Fb_rd_Companyid], [Fb_rd_dishid])
REFERENCES [dbo].[FB_Dishdetails] ([fb_dd_companyid], [fb_dd_dishid])
GO
ALTER TABLE [dbo].[Fb_recipedetails] CHECK CONSTRAINT [FK_Fb_recipedetails_FB_Dishdetails]
GO
/****** Object:  ForeignKey [FK_loPurchaseOrderItemSplitDetails_aItem]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPurchaseOrderItemSplitDetails]  WITH CHECK ADD  CONSTRAINT [FK_loPurchaseOrderItemSplitDetails_aItem] FOREIGN KEY([ItemID])
REFERENCES [dbo].[aItem] ([ItemID])
GO
ALTER TABLE [dbo].[loPurchaseOrderItemSplitDetails] CHECK CONSTRAINT [FK_loPurchaseOrderItemSplitDetails_aItem]
GO
/****** Object:  ForeignKey [FK_loPurchaseOrderItemSplitDetails_aVendorMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPurchaseOrderItemSplitDetails]  WITH CHECK ADD  CONSTRAINT [FK_loPurchaseOrderItemSplitDetails_aVendorMaster] FOREIGN KEY([VendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[loPurchaseOrderItemSplitDetails] CHECK CONSTRAINT [FK_loPurchaseOrderItemSplitDetails_aVendorMaster]
GO
/****** Object:  ForeignKey [FK_loPurchaseOrderItemSplitDetails_loPurchaseOrderHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPurchaseOrderItemSplitDetails]  WITH CHECK ADD  CONSTRAINT [FK_loPurchaseOrderItemSplitDetails_loPurchaseOrderHeader] FOREIGN KEY([podID])
REFERENCES [dbo].[loPurchaseOrderHeader] ([pohPoid])
GO
ALTER TABLE [dbo].[loPurchaseOrderItemSplitDetails] CHECK CONSTRAINT [FK_loPurchaseOrderItemSplitDetails_loPurchaseOrderHeader]
GO
/****** Object:  ForeignKey [FK_LOiLocation_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiLocation]  WITH CHECK ADD  CONSTRAINT [FK_LOiLocation_aGodown] FOREIGN KEY([lGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[LOiLocation] CHECK CONSTRAINT [FK_LOiLocation_aGodown]
GO
/****** Object:  ForeignKey [fk_loilocation_loilocationgroup]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiLocation]  WITH CHECK ADD  CONSTRAINT [fk_loilocation_loilocationgroup] FOREIGN KEY([lcompanyid], [lgroupid], [lGodownID])
REFERENCES [dbo].[LoilocationGroup] ([Lgcompanyid], [Lggroupid], [Lggodownid])
GO
ALTER TABLE [dbo].[LOiLocation] CHECK CONSTRAINT [fk_loilocation_loilocationgroup]
GO
/****** Object:  ForeignKey [FK_aGodownItemCategory_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodownItemCategory]  WITH CHECK ADD  CONSTRAINT [FK_aGodownItemCategory_aGodown] FOREIGN KEY([Godownid])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[aGodownItemCategory] CHECK CONSTRAINT [FK_aGodownItemCategory_aGodown]
GO
/****** Object:  ForeignKey [FK_aGodownItemCategory_aItemCategory]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodownItemCategory]  WITH CHECK ADD  CONSTRAINT [FK_aGodownItemCategory_aItemCategory] FOREIGN KEY([categoryID])
REFERENCES [dbo].[aItemCategory] ([ItemCategoryID])
GO
ALTER TABLE [dbo].[aGodownItemCategory] CHECK CONSTRAINT [FK_aGodownItemCategory_aItemCategory]
GO
/****** Object:  ForeignKey [FK_aShopitemCategory_aItemCategory]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopitemCategory]  WITH CHECK ADD  CONSTRAINT [FK_aShopitemCategory_aItemCategory] FOREIGN KEY([itemcategoryid])
REFERENCES [dbo].[aItemCategory] ([ItemCategoryID])
GO
ALTER TABLE [dbo].[aShopitemCategory] CHECK CONSTRAINT [FK_aShopitemCategory_aItemCategory]
GO
/****** Object:  ForeignKey [FK_aShopitemCategory_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopitemCategory]  WITH CHECK ADD  CONSTRAINT [FK_aShopitemCategory_aShops] FOREIGN KEY([shopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[aShopitemCategory] CHECK CONSTRAINT [FK_aShopitemCategory_aShops]
GO
/****** Object:  ForeignKey [fk_losDeliveryNoteImage_losDeliveryNoteHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDeliveryNoteImage]  WITH CHECK ADD  CONSTRAINT [fk_losDeliveryNoteImage_losDeliveryNoteHeader] FOREIGN KEY([ShopId], [DeliveryNoteId])
REFERENCES [dbo].[LosDeliveryNoteHeader] ([DnShopid], [DndnId])
GO
ALTER TABLE [dbo].[losDeliveryNoteImage] CHECK CONSTRAINT [fk_losDeliveryNoteImage_losDeliveryNoteHeader]
GO
/****** Object:  ForeignKey [FK_aListItemDetails_aListItemMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aListItemDetails]  WITH CHECK ADD  CONSTRAINT [FK_aListItemDetails_aListItemMaster] FOREIGN KEY([ListID])
REFERENCES [dbo].[aListItemMaster] ([Listid])
GO
ALTER TABLE [dbo].[aListItemDetails] CHECK CONSTRAINT [FK_aListItemDetails_aListItemMaster]
GO
/****** Object:  ForeignKey [FK_Fb_processdetail_LosPosFAndBHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Fb_processdetail]  WITH NOCHECK ADD  CONSTRAINT [FK_Fb_processdetail_LosPosFAndBHeader] FOREIGN KEY([fb_pd_outletid], [fb_pd_processid])
REFERENCES [dbo].[LosPosFAndBHeader] ([poshShopID], [poshBillID])
GO
ALTER TABLE [dbo].[Fb_processdetail] CHECK CONSTRAINT [FK_Fb_processdetail_LosPosFAndBHeader]
GO
/****** Object:  ForeignKey [FK_aListViewDetails_aListViewHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aListViewDetails]  WITH CHECK ADD  CONSTRAINT [FK_aListViewDetails_aListViewHeader] FOREIGN KEY([lvwdid])
REFERENCES [dbo].[aListViewHeader] ([lvwid])
GO
ALTER TABLE [dbo].[aListViewDetails] CHECK CONSTRAINT [FK_aListViewDetails_aListViewHeader]
GO
/****** Object:  ForeignKey [fk_loslocation_ashops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loslocation]  WITH CHECK ADD  CONSTRAINT [fk_loslocation_ashops] FOREIGN KEY([lshopiD])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[loslocation] CHECK CONSTRAINT [fk_loslocation_ashops]
GO
/****** Object:  ForeignKey [fk_loslocation_loslocationgroup]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loslocation]  WITH CHECK ADD  CONSTRAINT [fk_loslocation_loslocationgroup] FOREIGN KEY([lcompanyid], [lgroupid], [lshopiD])
REFERENCES [dbo].[LoslocationGroup] ([Lgcompanyid], [Lggroupid], [Lgshopid])
GO
ALTER TABLE [dbo].[loslocation] CHECK CONSTRAINT [fk_loslocation_loslocationgroup]
GO
/****** Object:  ForeignKey [FK_aLoyaltyCardContactDetails_aLoyaltyCardMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aLoyaltyCardContactDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_aLoyaltyCardContactDetails_aLoyaltyCardMaster] FOREIGN KEY([CompanyID], [CardID])
REFERENCES [dbo].[aLoyaltyCardMaster] ([CompanyID], [CardID])
GO
ALTER TABLE [dbo].[aLoyaltyCardContactDetails] CHECK CONSTRAINT [FK_aLoyaltyCardContactDetails_aLoyaltyCardMaster]
GO
/****** Object:  ForeignKey [FK_aCustomerMaster_aCity]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCustomerMaster]  WITH CHECK ADD  CONSTRAINT [FK_aCustomerMaster_aCity] FOREIGN KEY([CityID])
REFERENCES [dbo].[aCity] ([CityID])
GO
ALTER TABLE [dbo].[aCustomerMaster] CHECK CONSTRAINT [FK_aCustomerMaster_aCity]
GO
/****** Object:  ForeignKey [FK_aCustomerMaster_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCustomerMaster]  WITH CHECK ADD  CONSTRAINT [FK_aCustomerMaster_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aCustomerMaster] CHECK CONSTRAINT [FK_aCustomerMaster_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_aCustomerMaster_aCountryMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCustomerMaster]  WITH CHECK ADD  CONSTRAINT [FK_aCustomerMaster_aCountryMaster] FOREIGN KEY([CountryID], [CompanyID])
REFERENCES [dbo].[aCountryMaster] ([CountryID], [CompanyID])
GO
ALTER TABLE [dbo].[aCustomerMaster] CHECK CONSTRAINT [FK_aCustomerMaster_aCountryMaster]
GO
/****** Object:  ForeignKey [FK_aCustomerMaster_aCurrencyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCustomerMaster]  WITH CHECK ADD  CONSTRAINT [FK_aCustomerMaster_aCurrencyMaster] FOREIGN KEY([CurrencyID], [CompanyID])
REFERENCES [dbo].[aCurrencyMaster] ([CurrencyID], [CompanyID])
GO
ALTER TABLE [dbo].[aCustomerMaster] CHECK CONSTRAINT [FK_aCustomerMaster_aCurrencyMaster]
GO
/****** Object:  ForeignKey [fk_acustomermaster_asegmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCustomerMaster]  WITH CHECK ADD  CONSTRAINT [fk_acustomermaster_asegmentmaster] FOREIGN KEY([CompanyID], [segmentid])
REFERENCES [dbo].[ASegmentMaster] ([companyid], [Segmentid])
GO
ALTER TABLE [dbo].[aCustomerMaster] CHECK CONSTRAINT [fk_acustomermaster_asegmentmaster]
GO
/****** Object:  ForeignKey [fk_AShops_aaccountmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops]  WITH CHECK ADD  CONSTRAINT [fk_AShops_aaccountmaster] FOREIGN KEY([DefaultCashaccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aShops] CHECK CONSTRAINT [fk_AShops_aaccountmaster]
GO
/****** Object:  ForeignKey [fk_AShops_aaccountmaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops]  WITH CHECK ADD  CONSTRAINT [fk_AShops_aaccountmaster1] FOREIGN KEY([ShopSalesaccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aShops] CHECK CONSTRAINT [fk_AShops_aaccountmaster1]
GO
/****** Object:  ForeignKey [fk_AShops_aaccountmaster2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops]  WITH CHECK ADD  CONSTRAINT [fk_AShops_aaccountmaster2] FOREIGN KEY([ShopPurchaseAcID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aShops] CHECK CONSTRAINT [fk_AShops_aaccountmaster2]
GO
/****** Object:  ForeignKey [fk_AShops_aaccountmaster3]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops]  WITH CHECK ADD  CONSTRAINT [fk_AShops_aaccountmaster3] FOREIGN KEY([ShopGoodsReturnNoteAccID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aShops] CHECK CONSTRAINT [fk_AShops_aaccountmaster3]
GO
/****** Object:  ForeignKey [fk_AShops_aaccountmaster4]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops]  WITH CHECK ADD  CONSTRAINT [fk_AShops_aaccountmaster4] FOREIGN KEY([stockWriteoffAccID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aShops] CHECK CONSTRAINT [fk_AShops_aaccountmaster4]
GO
/****** Object:  ForeignKey [fk_AShops_aaccountmaster5]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops]  WITH CHECK ADD  CONSTRAINT [fk_AShops_aaccountmaster5] FOREIGN KEY([discountaccountid], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aShops] CHECK CONSTRAINT [fk_AShops_aaccountmaster5]
GO
/****** Object:  ForeignKey [fk_AShops_aaccountmaster6]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops]  WITH CHECK ADD  CONSTRAINT [fk_AShops_aaccountmaster6] FOREIGN KEY([discountaccountid], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aShops] CHECK CONSTRAINT [fk_AShops_aaccountmaster6]
GO
/****** Object:  ForeignKey [fk_AShops_aCity]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops]  WITH CHECK ADD  CONSTRAINT [fk_AShops_aCity] FOREIGN KEY([CityID])
REFERENCES [dbo].[aCity] ([CityID])
GO
ALTER TABLE [dbo].[aShops] CHECK CONSTRAINT [fk_AShops_aCity]
GO
/****** Object:  ForeignKey [fk_AShops_acountrymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops]  WITH CHECK ADD  CONSTRAINT [fk_AShops_acountrymaster] FOREIGN KEY([Countryid], [CompanyID])
REFERENCES [dbo].[aCountryMaster] ([CountryID], [CompanyID])
GO
ALTER TABLE [dbo].[aShops] CHECK CONSTRAINT [fk_AShops_acountrymaster]
GO
/****** Object:  ForeignKey [FK_aShops_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops]  WITH CHECK ADD  CONSTRAINT [FK_aShops_aDepartmentMaster] FOREIGN KEY([DepartmentID], [CompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[aShops] CHECK CONSTRAINT [FK_aShops_aDepartmentMaster]
GO
/****** Object:  ForeignKey [fk_ashops_asegmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShops]  WITH CHECK ADD  CONSTRAINT [fk_ashops_asegmentmaster] FOREIGN KEY([CompanyID], [segmentid])
REFERENCES [dbo].[ASegmentMaster] ([companyid], [Segmentid])
GO
ALTER TABLE [dbo].[aShops] CHECK CONSTRAINT [fk_ashops_asegmentmaster]
GO
/****** Object:  ForeignKey [FK_aPackingTypeCapacityDetail_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPackingTypeCapacityDetail]  WITH CHECK ADD  CONSTRAINT [FK_aPackingTypeCapacityDetail_aPackingType] FOREIGN KEY([PackingTypeID])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[aPackingTypeCapacityDetail] CHECK CONSTRAINT [FK_aPackingTypeCapacityDetail_aPackingType]
GO
/****** Object:  ForeignKey [FK_aPackingTypeCapacityDetail_aUnit]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aPackingTypeCapacityDetail]  WITH CHECK ADD  CONSTRAINT [FK_aPackingTypeCapacityDetail_aUnit] FOREIGN KEY([UnitsID])
REFERENCES [dbo].[aUnit] ([UnitID])
GO
ALTER TABLE [dbo].[aPackingTypeCapacityDetail] CHECK CONSTRAINT [FK_aPackingTypeCapacityDetail_aUnit]
GO
/****** Object:  ForeignKey [FK_mesRQtoHQforItem_aColor]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesRQtoHQforItem]  WITH CHECK ADD  CONSTRAINT [FK_mesRQtoHQforItem_aColor] FOREIGN KEY([ColorID])
REFERENCES [dbo].[aColor] ([ColorID])
GO
ALTER TABLE [dbo].[mesRQtoHQforItem] CHECK CONSTRAINT [FK_mesRQtoHQforItem_aColor]
GO
/****** Object:  ForeignKey [FK_mesRQtoHQforItem_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesRQtoHQforItem]  WITH CHECK ADD  CONSTRAINT [FK_mesRQtoHQforItem_aPackingType] FOREIGN KEY([PackingTypeID])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[mesRQtoHQforItem] CHECK CONSTRAINT [FK_mesRQtoHQforItem_aPackingType]
GO
/****** Object:  ForeignKey [FK_mesRQtoHQforItem_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesRQtoHQforItem]  WITH CHECK ADD  CONSTRAINT [FK_mesRQtoHQforItem_aShops] FOREIGN KEY([ShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[mesRQtoHQforItem] CHECK CONSTRAINT [FK_mesRQtoHQforItem_aShops]
GO
/****** Object:  ForeignKey [FK_mesRQtoHQforItem_aSize]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesRQtoHQforItem]  WITH CHECK ADD  CONSTRAINT [FK_mesRQtoHQforItem_aSize] FOREIGN KEY([SizeID])
REFERENCES [dbo].[aSize] ([SizeID])
GO
ALTER TABLE [dbo].[mesRQtoHQforItem] CHECK CONSTRAINT [FK_mesRQtoHQforItem_aSize]
GO
/****** Object:  ForeignKey [FK_mesRQtoHQforItem_aUnit]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesRQtoHQforItem]  WITH CHECK ADD  CONSTRAINT [FK_mesRQtoHQforItem_aUnit] FOREIGN KEY([UnitID])
REFERENCES [dbo].[aUnit] ([UnitID])
GO
ALTER TABLE [dbo].[mesRQtoHQforItem] CHECK CONSTRAINT [FK_mesRQtoHQforItem_aUnit]
GO
/****** Object:  ForeignKey [FK_meiRQtoHQforItem_aColor]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiRQtoHQforItem]  WITH CHECK ADD  CONSTRAINT [FK_meiRQtoHQforItem_aColor] FOREIGN KEY([ColorID])
REFERENCES [dbo].[aColor] ([ColorID])
GO
ALTER TABLE [dbo].[meiRQtoHQforItem] CHECK CONSTRAINT [FK_meiRQtoHQforItem_aColor]
GO
/****** Object:  ForeignKey [FK_meiRQtoHQforItem_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiRQtoHQforItem]  WITH CHECK ADD  CONSTRAINT [FK_meiRQtoHQforItem_aGodown] FOREIGN KEY([GodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[meiRQtoHQforItem] CHECK CONSTRAINT [FK_meiRQtoHQforItem_aGodown]
GO
/****** Object:  ForeignKey [FK_meiRQtoHQforItem_aPackingType]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiRQtoHQforItem]  WITH CHECK ADD  CONSTRAINT [FK_meiRQtoHQforItem_aPackingType] FOREIGN KEY([PackingTypeID])
REFERENCES [dbo].[aPackingType] ([PackingTypeID])
GO
ALTER TABLE [dbo].[meiRQtoHQforItem] CHECK CONSTRAINT [FK_meiRQtoHQforItem_aPackingType]
GO
/****** Object:  ForeignKey [FK_meiRQtoHQforItem_aSize]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiRQtoHQforItem]  WITH CHECK ADD  CONSTRAINT [FK_meiRQtoHQforItem_aSize] FOREIGN KEY([SizeID])
REFERENCES [dbo].[aSize] ([SizeID])
GO
ALTER TABLE [dbo].[meiRQtoHQforItem] CHECK CONSTRAINT [FK_meiRQtoHQforItem_aSize]
GO
/****** Object:  ForeignKey [FK_meiRQtoHQforItem_aUnit]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiRQtoHQforItem]  WITH CHECK ADD  CONSTRAINT [FK_meiRQtoHQforItem_aUnit] FOREIGN KEY([UnitID])
REFERENCES [dbo].[aUnit] ([UnitID])
GO
ALTER TABLE [dbo].[meiRQtoHQforItem] CHECK CONSTRAINT [FK_meiRQtoHQforItem_aUnit]
GO
/****** Object:  ForeignKey [FK_TillDetail_aCurrencyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[TillDetail]  WITH CHECK ADD  CONSTRAINT [FK_TillDetail_aCurrencyMaster] FOREIGN KEY([till_td_currencyid], [till_td_companyid])
REFERENCES [dbo].[aCurrencyMaster] ([CurrencyID], [CompanyID])
GO
ALTER TABLE [dbo].[TillDetail] CHECK CONSTRAINT [FK_TillDetail_aCurrencyMaster]
GO
/****** Object:  ForeignKey [FK_TillDetail_TillHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[TillDetail]  WITH CHECK ADD  CONSTRAINT [FK_TillDetail_TillHeader] FOREIGN KEY([till_td_tillid], [till_td_outletid], [till_td_companyid])
REFERENCES [dbo].[TillHeader] ([till_th_tillid], [till_th_outletid], [till_th_companyid])
GO
ALTER TABLE [dbo].[TillDetail] CHECK CONSTRAINT [FK_TillDetail_TillHeader]
GO
/****** Object:  ForeignKey [FK_AgreementWitnessDetails_AgreementRegister]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AgreementWitnessDetails]  WITH CHECK ADD  CONSTRAINT [FK_AgreementWitnessDetails_AgreementRegister] FOREIGN KEY([agwAgreementid], [agwDepartmentid])
REFERENCES [dbo].[AgreementRegister] ([agragreementid], [agrDepartmentid])
GO
ALTER TABLE [dbo].[AgreementWitnessDetails] CHECK CONSTRAINT [FK_AgreementWitnessDetails_AgreementRegister]
GO
/****** Object:  ForeignKey [FK_AgreementFinancialDetails_AgreementRegister]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AgreementFinancialDetails]  WITH CHECK ADD  CONSTRAINT [FK_AgreementFinancialDetails_AgreementRegister] FOREIGN KEY([agfAgreementid], [agfDepartmentId])
REFERENCES [dbo].[AgreementRegister] ([agragreementid], [agrDepartmentid])
GO
ALTER TABLE [dbo].[AgreementFinancialDetails] CHECK CONSTRAINT [FK_AgreementFinancialDetails_AgreementRegister]
GO
/****** Object:  ForeignKey [FK_AgreementSignedDetails_AgreementRegister]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AgreementSignedDetails]  WITH CHECK ADD  CONSTRAINT [FK_AgreementSignedDetails_AgreementRegister] FOREIGN KEY([agsagreementid], [agsDepartmentid])
REFERENCES [dbo].[AgreementRegister] ([agragreementid], [agrDepartmentid])
GO
ALTER TABLE [dbo].[AgreementSignedDetails] CHECK CONSTRAINT [FK_AgreementSignedDetails_AgreementRegister]
GO
/****** Object:  ForeignKey [FK_AgreementDetails_AgreementRegister]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AgreementDetails]  WITH CHECK ADD  CONSTRAINT [FK_AgreementDetails_AgreementRegister] FOREIGN KEY([agdAgreementid], [agdDepartmentid])
REFERENCES [dbo].[AgreementRegister] ([agragreementid], [agrDepartmentid])
GO
ALTER TABLE [dbo].[AgreementDetails] CHECK CONSTRAINT [FK_AgreementDetails_AgreementRegister]
GO
/****** Object:  ForeignKey [FK_AgreementContents_AgreementRegister]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AgreementContents]  WITH CHECK ADD  CONSTRAINT [FK_AgreementContents_AgreementRegister] FOREIGN KEY([agcagreementid], [agcDepartmentid])
REFERENCES [dbo].[AgreementRegister] ([agragreementid], [agrDepartmentid])
GO
ALTER TABLE [dbo].[AgreementContents] CHECK CONSTRAINT [FK_AgreementContents_AgreementRegister]
GO
/****** Object:  ForeignKey [FK_APRODUCT_REF_82_ASERVICE]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aproductconditionmaster]  WITH CHECK ADD  CONSTRAINT [FK_APRODUCT_REF_82_ASERVICE] FOREIGN KEY([prodcndsercatid], [prodcndcompanyid])
REFERENCES [dbo].[aServiceCategory] ([sercategid], [sercatcompanyid])
GO
ALTER TABLE [dbo].[aproductconditionmaster] CHECK CONSTRAINT [FK_APRODUCT_REF_82_ASERVICE]
GO
/****** Object:  ForeignKey [FK_ReceiptVoucherCustomerDetails_aCustomerMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherCustomerDetails]  WITH CHECK ADD  CONSTRAINT [FK_ReceiptVoucherCustomerDetails_aCustomerMaster] FOREIGN KEY([CustomerId])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[ReceiptVoucherCustomerDetails] CHECK CONSTRAINT [FK_ReceiptVoucherCustomerDetails_aCustomerMaster]
GO
/****** Object:  ForeignKey [FK_ReceiptVoucherCustomerDetails_ReceiptVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherCustomerDetails]  WITH CHECK ADD  CONSTRAINT [FK_ReceiptVoucherCustomerDetails_ReceiptVoucherHeader] FOREIGN KEY([ReceiptId])
REFERENCES [dbo].[ReceiptVoucherHeader] ([ReceiptID])
GO
ALTER TABLE [dbo].[ReceiptVoucherCustomerDetails] CHECK CONSTRAINT [FK_ReceiptVoucherCustomerDetails_ReceiptVoucherHeader]
GO
/****** Object:  ForeignKey [FK_ReceiptVoucherDetails_aHQPaymentVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherDetails]  WITH CHECK ADD  CONSTRAINT [FK_ReceiptVoucherDetails_aHQPaymentVoucherHeader] FOREIGN KEY([phpaymentid])
REFERENCES [dbo].[aHQPaymentVoucherHeader] ([phPaymentID])
GO
ALTER TABLE [dbo].[ReceiptVoucherDetails] CHECK CONSTRAINT [FK_ReceiptVoucherDetails_aHQPaymentVoucherHeader]
GO
/****** Object:  ForeignKey [FK_ReceiptVoucherDetails_LOsAccountsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherDetails]  WITH CHECK ADD  CONSTRAINT [FK_ReceiptVoucherDetails_LOsAccountsInvoiceHeader] FOREIGN KEY([shopid], [posaccountsInvoiceID])
REFERENCES [dbo].[LOsAccountsInvoiceHeader] ([aiShopID], [aiInvoiceID])
GO
ALTER TABLE [dbo].[ReceiptVoucherDetails] CHECK CONSTRAINT [FK_ReceiptVoucherDetails_LOsAccountsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_ReceiptVoucherDetails_losDebitCreditNote]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherDetails]  WITH CHECK ADD  CONSTRAINT [FK_ReceiptVoucherDetails_losDebitCreditNote] FOREIGN KEY([shopid], [losdcnid])
REFERENCES [dbo].[losDebitCreditNote] ([losDCNShopid], [losDCNId])
GO
ALTER TABLE [dbo].[ReceiptVoucherDetails] CHECK CONSTRAINT [FK_ReceiptVoucherDetails_losDebitCreditNote]
GO
/****** Object:  ForeignKey [FK_ReceiptVoucherDetails_ReceiptVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherDetails]  WITH CHECK ADD  CONSTRAINT [FK_ReceiptVoucherDetails_ReceiptVoucherHeader] FOREIGN KEY([ReceiptID])
REFERENCES [dbo].[ReceiptVoucherHeader] ([ReceiptID])
GO
ALTER TABLE [dbo].[ReceiptVoucherDetails] CHECK CONSTRAINT [FK_ReceiptVoucherDetails_ReceiptVoucherHeader]
GO
/****** Object:  ForeignKey [FK_LOiArrivalHeader_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOiArrivalHeader_aGodown] FOREIGN KEY([ahGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[LOiArrivalHeader] CHECK CONSTRAINT [FK_LOiArrivalHeader_aGodown]
GO
/****** Object:  ForeignKey [fk_LOiArrivalHeader_agodown1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalHeader]  WITH CHECK ADD  CONSTRAINT [fk_LOiArrivalHeader_agodown1] FOREIGN KEY([ahLocalGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[LOiArrivalHeader] CHECK CONSTRAINT [fk_LOiArrivalHeader_agodown1]
GO
/****** Object:  ForeignKey [fk_LOiArrivalHeader_ashipment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalHeader]  WITH CHECK ADD  CONSTRAINT [fk_LOiArrivalHeader_ashipment] FOREIGN KEY([ahShipmentID])
REFERENCES [dbo].[aShipment] ([sShipmentID])
GO
ALTER TABLE [dbo].[LOiArrivalHeader] CHECK CONSTRAINT [fk_LOiArrivalHeader_ashipment]
GO
/****** Object:  ForeignKey [fk_LOiArrivalHeader_ashops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiArrivalHeader]  WITH CHECK ADD  CONSTRAINT [fk_LOiArrivalHeader_ashops] FOREIGN KEY([ahShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LOiArrivalHeader] CHECK CONSTRAINT [fk_LOiArrivalHeader_ashops]
GO
/****** Object:  ForeignKey [FK_aHQDespatchnoteHeader_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchnoteHeader]  WITH CHECK ADD  CONSTRAINT [FK_aHQDespatchnoteHeader_aGodown] FOREIGN KEY([dhGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[aHQDespatchnoteHeader] CHECK CONSTRAINT [FK_aHQDespatchnoteHeader_aGodown]
GO
/****** Object:  ForeignKey [FK_aHQDespatchnoteHeader_aHQDespatchNoteMain]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchnoteHeader]  WITH CHECK ADD  CONSTRAINT [FK_aHQDespatchnoteHeader_aHQDespatchNoteMain] FOREIGN KEY([dhDespatchNoteMainID])
REFERENCES [dbo].[aHQDespatchNoteMain] ([dnmDespatchNoteID])
GO
ALTER TABLE [dbo].[aHQDespatchnoteHeader] CHECK CONSTRAINT [FK_aHQDespatchnoteHeader_aHQDespatchNoteMain]
GO
/****** Object:  ForeignKey [fk_aHQDespatchNoteHeader_ashipment]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchnoteHeader]  WITH CHECK ADD  CONSTRAINT [fk_aHQDespatchNoteHeader_ashipment] FOREIGN KEY([dhShipmentID])
REFERENCES [dbo].[aShipment] ([sShipmentID])
GO
ALTER TABLE [dbo].[aHQDespatchnoteHeader] CHECK CONSTRAINT [fk_aHQDespatchNoteHeader_ashipment]
GO
/****** Object:  ForeignKey [fk_aHQDespatchnoteHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchnoteHeader]  WITH CHECK ADD  CONSTRAINT [fk_aHQDespatchnoteHeader_aShops] FOREIGN KEY([dhshopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[aHQDespatchnoteHeader] CHECK CONSTRAINT [fk_aHQDespatchnoteHeader_aShops]
GO
/****** Object:  ForeignKey [FK_TillBalanceHistory_TillHistory]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[TillBalanceHistory]  WITH CHECK ADD  CONSTRAINT [FK_TillBalanceHistory_TillHistory] FOREIGN KEY([till_hist_id], [till_outletid], [till_companyid])
REFERENCES [dbo].[TillHistory] ([till_hist_id], [till_outletid], [till_companyid])
GO
ALTER TABLE [dbo].[TillBalanceHistory] CHECK CONSTRAINT [FK_TillBalanceHistory_TillHistory]
GO
/****** Object:  ForeignKey [FK_BudgetPlanDetail_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[BudgetPlanDetail]  WITH CHECK ADD  CONSTRAINT [FK_BudgetPlanDetail_aAccountMaster] FOREIGN KEY([bpdBudgetHeadID], [bpdCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[BudgetPlanDetail] CHECK CONSTRAINT [FK_BudgetPlanDetail_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_BudgetPlanDetail_BudgetPlanHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[BudgetPlanDetail]  WITH CHECK ADD  CONSTRAINT [FK_BudgetPlanDetail_BudgetPlanHeader] FOREIGN KEY([bpdCompanyID], [bpdBudgetPlanID])
REFERENCES [dbo].[BudgetPlanHeader] ([bphCompanyID], [bphBudgetPlanID])
GO
ALTER TABLE [dbo].[BudgetPlanDetail] CHECK CONSTRAINT [FK_BudgetPlanDetail_BudgetPlanHeader]
GO
/****** Object:  ForeignKey [FK_BudgetPlanDetail_BudgetPlanReviseDetail]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[BudgetPlanDetail]  WITH CHECK ADD  CONSTRAINT [FK_BudgetPlanDetail_BudgetPlanReviseDetail] FOREIGN KEY([bpdCompanyID], [bpdBudgetPlanID], [bpdReviseDetailId])
REFERENCES [dbo].[BudgetPlanReviseDetail] ([brdCompanyID], [brdBudgetPlanID], [brdDetailID])
GO
ALTER TABLE [dbo].[BudgetPlanDetail] CHECK CONSTRAINT [FK_BudgetPlanDetail_BudgetPlanReviseDetail]
GO
/****** Object:  ForeignKey [fk_BudgetitemPlanDetail_BudgetPlanHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[BudgetitemPlanDetail]  WITH CHECK ADD  CONSTRAINT [fk_BudgetitemPlanDetail_BudgetPlanHeader] FOREIGN KEY([bpdICompanyID], [bpdIBudgetPlanID])
REFERENCES [dbo].[BudgetPlanHeader] ([bphCompanyID], [bphBudgetPlanID])
GO
ALTER TABLE [dbo].[BudgetitemPlanDetail] CHECK CONSTRAINT [fk_BudgetitemPlanDetail_BudgetPlanHeader]
GO
/****** Object:  ForeignKey [FK_BudgetReviseDetail_BudgetPlanHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[BudgetPlanReviseDetail]  WITH CHECK ADD  CONSTRAINT [FK_BudgetReviseDetail_BudgetPlanHeader] FOREIGN KEY([brdCompanyID], [brdBudgetPlanID])
REFERENCES [dbo].[BudgetPlanHeader] ([bphCompanyID], [bphBudgetPlanID])
GO
ALTER TABLE [dbo].[BudgetPlanReviseDetail] CHECK CONSTRAINT [FK_BudgetReviseDetail_BudgetPlanHeader]
GO
/****** Object:  ForeignKey [FK_MEiDespatchToShopHeader_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiDespatchToShopHeader]  WITH CHECK ADD  CONSTRAINT [FK_MEiDespatchToShopHeader_aGodown] FOREIGN KEY([dhGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[MEiDespatchToShopHeader] CHECK CONSTRAINT [FK_MEiDespatchToShopHeader_aGodown]
GO
/****** Object:  ForeignKey [FK_MEiDespatchToShopHeader_aHQIssuenoteHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiDespatchToShopHeader]  WITH CHECK ADD  CONSTRAINT [FK_MEiDespatchToShopHeader_aHQIssuenoteHeader] FOREIGN KEY([dhIssueNoteID])
REFERENCES [dbo].[aHQIssuenoteHeader] ([INHIssuenoteID])
GO
ALTER TABLE [dbo].[MEiDespatchToShopHeader] CHECK CONSTRAINT [FK_MEiDespatchToShopHeader_aHQIssuenoteHeader]
GO
/****** Object:  ForeignKey [FK_MEiDespatchToShopHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiDespatchToShopHeader]  WITH CHECK ADD  CONSTRAINT [FK_MEiDespatchToShopHeader_aShops] FOREIGN KEY([dhShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[MEiDespatchToShopHeader] CHECK CONSTRAINT [FK_MEiDespatchToShopHeader_aShops]
GO
/****** Object:  ForeignKey [FK_TableColumns_Tables]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aTableColumns]  WITH CHECK ADD  CONSTRAINT [FK_TableColumns_Tables] FOREIGN KEY([TableID])
REFERENCES [dbo].[aTables] ([TableID])
GO
ALTER TABLE [dbo].[aTableColumns] CHECK CONSTRAINT [FK_TableColumns_Tables]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceHeader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceHeader_aAccountMaster] FOREIGN KEY([ihBankcashAccID], [ihCompanyId])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsInvoiceHeader] CHECK CONSTRAINT [FK_LOsInvoiceHeader_aAccountMaster]
GO
/****** Object:  ForeignKey [fk_LOsInvoiceHeader_aaccountmaster_sales]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [fk_LOsInvoiceHeader_aaccountmaster_sales] FOREIGN KEY([ihSalesAccID], [ihCompanyId])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsInvoiceHeader] CHECK CONSTRAINT [fk_LOsInvoiceHeader_aaccountmaster_sales]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceHeader_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceHeader_aAccountMaster1] FOREIGN KEY([ihDiscountAccID], [ihCompanyId])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsInvoiceHeader] CHECK CONSTRAINT [FK_LOsInvoiceHeader_aAccountMaster1]
GO
/****** Object:  ForeignKey [fk_losinvoiceheader_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [fk_losinvoiceheader_acustomermaster] FOREIGN KEY([ihCustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[LOsInvoiceHeader] CHECK CONSTRAINT [fk_losinvoiceheader_acustomermaster]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceHeader_aDepartmentMaster] FOREIGN KEY([ihDepartmentID], [ihCompanyId])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsInvoiceHeader] CHECK CONSTRAINT [FK_LOsInvoiceHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceHeader_aFinancialYear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceHeader_aFinancialYear] FOREIGN KEY([ihFinancialID], [ihCompanyId])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsInvoiceHeader] CHECK CONSTRAINT [FK_LOsInvoiceHeader_aFinancialYear]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceHeader_AsalesPersonmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceHeader_AsalesPersonmaster] FOREIGN KEY([ihsalespersonid])
REFERENCES [dbo].[AsalesPersonmaster] ([Sperid])
GO
ALTER TABLE [dbo].[LOsInvoiceHeader] CHECK CONSTRAINT [FK_LOsInvoiceHeader_AsalesPersonmaster]
GO
/****** Object:  ForeignKey [FK_LOsInvoiceHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsInvoiceHeader_aShops] FOREIGN KEY([ihShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LOsInvoiceHeader] CHECK CONSTRAINT [FK_LOsInvoiceHeader_aShops]
GO
/****** Object:  ForeignKey [FK_losInvoiceHeader_aVendorMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_losInvoiceHeader_aVendorMaster] FOREIGN KEY([ihOptedVendorId])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[LOsInvoiceHeader] CHECK CONSTRAINT [FK_losInvoiceHeader_aVendorMaster]
GO
/****** Object:  ForeignKey [FK_losservinvoicetechniciandetails_AsalesPersonmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losservinvoicetechniciandetails]  WITH CHECK ADD  CONSTRAINT [FK_losservinvoicetechniciandetails_AsalesPersonmaster] FOREIGN KEY([serinvtechid])
REFERENCES [dbo].[AsalesPersonmaster] ([Sperid])
GO
ALTER TABLE [dbo].[losservinvoicetechniciandetails] CHECK CONSTRAINT [FK_losservinvoicetechniciandetails_AsalesPersonmaster]
GO
/****** Object:  ForeignKey [fk_losservinvoicetechniciandetails_aservicemaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losservinvoicetechniciandetails]  WITH CHECK ADD  CONSTRAINT [fk_losservinvoicetechniciandetails_aservicemaster] FOREIGN KEY([serinvTechServiceID], [serinvtechcompanyid])
REFERENCES [dbo].[aservicemaster] ([serid], [sercompanyid])
GO
ALTER TABLE [dbo].[losservinvoicetechniciandetails] CHECK CONSTRAINT [fk_losservinvoicetechniciandetails_aservicemaster]
GO
/****** Object:  ForeignKey [FK_losservinvoicetechniciandetails_losserviceheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losservinvoicetechniciandetails]  WITH CHECK ADD  CONSTRAINT [FK_losservinvoicetechniciandetails_losserviceheader] FOREIGN KEY([sertechinvid], [serinvtechcompanyid], [serinvtechshopid])
REFERENCES [dbo].[losServiceHeader] ([serinvhid], [serinvhcompanyid], [serinvhshopid])
GO
ALTER TABLE [dbo].[losservinvoicetechniciandetails] CHECK CONSTRAINT [FK_losservinvoicetechniciandetails_losserviceheader]
GO
/****** Object:  ForeignKey [FK_ASalesPersonCommisionDetail_AsalesPersonmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ASalesPersonCommisionDetail]  WITH CHECK ADD  CONSTRAINT [FK_ASalesPersonCommisionDetail_AsalesPersonmaster] FOREIGN KEY([salespersonid])
REFERENCES [dbo].[AsalesPersonmaster] ([Sperid])
GO
ALTER TABLE [dbo].[ASalesPersonCommisionDetail] CHECK CONSTRAINT [FK_ASalesPersonCommisionDetail_AsalesPersonmaster]
GO
/****** Object:  ForeignKey [fk_hqsalescommisionheader_acompanymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[hqSalesCommisionHeader]  WITH CHECK ADD  CONSTRAINT [fk_hqsalescommisionheader_acompanymaster] FOREIGN KEY([schcompanyid])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[hqSalesCommisionHeader] CHECK CONSTRAINT [fk_hqsalescommisionheader_acompanymaster]
GO
/****** Object:  ForeignKey [fk_hqsalescommisionheader_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[hqSalesCommisionHeader]  WITH CHECK ADD  CONSTRAINT [fk_hqsalescommisionheader_adepartmentmaster] FOREIGN KEY([schdepartmentid], [schcompanyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[hqSalesCommisionHeader] CHECK CONSTRAINT [fk_hqsalescommisionheader_adepartmentmaster]
GO
/****** Object:  ForeignKey [fk_hqsalescommisionheader_afinancialyear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[hqSalesCommisionHeader]  WITH CHECK ADD  CONSTRAINT [fk_hqsalescommisionheader_afinancialyear] FOREIGN KEY([schfinancialid], [schcompanyid])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[hqSalesCommisionHeader] CHECK CONSTRAINT [fk_hqsalescommisionheader_afinancialyear]
GO
/****** Object:  ForeignKey [fk_hqsalescommisionheader_asalespersonmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[hqSalesCommisionHeader]  WITH CHECK ADD  CONSTRAINT [fk_hqsalescommisionheader_asalespersonmaster] FOREIGN KEY([schsalespersonid])
REFERENCES [dbo].[AsalesPersonmaster] ([Sperid])
GO
ALTER TABLE [dbo].[hqSalesCommisionHeader] CHECK CONSTRAINT [fk_hqsalescommisionheader_asalespersonmaster]
GO
/****** Object:  ForeignKey [FK_lossertoolsallocationdetail_AsalesPersonmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerToolsAllocationDetail]  WITH CHECK ADD  CONSTRAINT [FK_lossertoolsallocationdetail_AsalesPersonmaster] FOREIGN KEY([alcdtechnicianid])
REFERENCES [dbo].[AsalesPersonmaster] ([Sperid])
GO
ALTER TABLE [dbo].[losSerToolsAllocationDetail] CHECK CONSTRAINT [FK_lossertoolsallocationdetail_AsalesPersonmaster]
GO
/****** Object:  ForeignKey [fk_LosserToolsAllocationDetail_FixedAsset]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerToolsAllocationDetail]  WITH CHECK ADD  CONSTRAINT [fk_LosserToolsAllocationDetail_FixedAsset] FOREIGN KEY([alcdtoolsid], [alcdCompanyId])
REFERENCES [dbo].[FixedAsset] ([FixedAssetID], [CompanyID])
GO
ALTER TABLE [dbo].[losSerToolsAllocationDetail] CHECK CONSTRAINT [fk_LosserToolsAllocationDetail_FixedAsset]
GO
/****** Object:  ForeignKey [FK_lossertoolsallocationdetail_lossertoolsallocationheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerToolsAllocationDetail]  WITH CHECK ADD  CONSTRAINT [FK_lossertoolsallocationdetail_lossertoolsallocationheader] FOREIGN KEY([alcdCompanyId], [alcdShopid], [alcdid])
REFERENCES [dbo].[losSerToolsAllocationHeader] ([alchCompanyId], [alchShopid], [alchid])
GO
ALTER TABLE [dbo].[losSerToolsAllocationDetail] CHECK CONSTRAINT [FK_lossertoolsallocationdetail_lossertoolsallocationheader]
GO
/****** Object:  ForeignKey [FK_Ashopsalespersondetails_AsalesPersonmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Ashopsalespersondetails]  WITH CHECK ADD  CONSTRAINT [FK_Ashopsalespersondetails_AsalesPersonmaster] FOREIGN KEY([SperID])
REFERENCES [dbo].[AsalesPersonmaster] ([Sperid])
GO
ALTER TABLE [dbo].[Ashopsalespersondetails] CHECK CONSTRAINT [FK_Ashopsalespersondetails_AsalesPersonmaster]
GO
/****** Object:  ForeignKey [FK_Ashopsalespersondetails_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Ashopsalespersondetails]  WITH CHECK ADD  CONSTRAINT [FK_Ashopsalespersondetails_aShops] FOREIGN KEY([SperShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[Ashopsalespersondetails] CHECK CONSTRAINT [FK_Ashopsalespersondetails_aShops]
GO
/****** Object:  ForeignKey [fk_losSerStandByRequestHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerStandByRequestHeader]  WITH CHECK ADD  CONSTRAINT [fk_losSerStandByRequestHeader_aCompanyMaster] FOREIGN KEY([reqhCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[losSerStandByRequestHeader] CHECK CONSTRAINT [fk_losSerStandByRequestHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [fk_losSerStandByRequestHeader_aCustomerMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerStandByRequestHeader]  WITH CHECK ADD  CONSTRAINT [fk_losSerStandByRequestHeader_aCustomerMaster] FOREIGN KEY([reqhCustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[losSerStandByRequestHeader] CHECK CONSTRAINT [fk_losSerStandByRequestHeader_aCustomerMaster]
GO
/****** Object:  ForeignKey [fk_losSerStandByRequestHeader_AsalesPersonmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerStandByRequestHeader]  WITH CHECK ADD  CONSTRAINT [fk_losSerStandByRequestHeader_AsalesPersonmaster] FOREIGN KEY([reqhApprovedByID])
REFERENCES [dbo].[AsalesPersonmaster] ([Sperid])
GO
ALTER TABLE [dbo].[losSerStandByRequestHeader] CHECK CONSTRAINT [fk_losSerStandByRequestHeader_AsalesPersonmaster]
GO
/****** Object:  ForeignKey [fk_losSerStandByRequestHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerStandByRequestHeader]  WITH CHECK ADD  CONSTRAINT [fk_losSerStandByRequestHeader_aShops] FOREIGN KEY([reqhShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losSerStandByRequestHeader] CHECK CONSTRAINT [fk_losSerStandByRequestHeader_aShops]
GO
/****** Object:  ForeignKey [fk_LosserToolsAllocationHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerToolsAllocationHeader]  WITH CHECK ADD  CONSTRAINT [fk_LosserToolsAllocationHeader] FOREIGN KEY([alchShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losSerToolsAllocationHeader] CHECK CONSTRAINT [fk_LosserToolsAllocationHeader]
GO
/****** Object:  ForeignKey [fk_LosserToolsAllocationHeader_acompanymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerToolsAllocationHeader]  WITH CHECK ADD  CONSTRAINT [fk_LosserToolsAllocationHeader_acompanymaster] FOREIGN KEY([alchCompanyId])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[losSerToolsAllocationHeader] CHECK CONSTRAINT [fk_LosserToolsAllocationHeader_acompanymaster]
GO
/****** Object:  ForeignKey [FK_lossertoolsallocationheader_AsalesPersonmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerToolsAllocationHeader]  WITH CHECK ADD  CONSTRAINT [FK_lossertoolsallocationheader_AsalesPersonmaster] FOREIGN KEY([alchtechnicianid])
REFERENCES [dbo].[AsalesPersonmaster] ([Sperid])
GO
ALTER TABLE [dbo].[losSerToolsAllocationHeader] CHECK CONSTRAINT [FK_lossertoolsallocationheader_AsalesPersonmaster]
GO
/****** Object:  ForeignKey [fk_aTechnicianServiceDetails_aSalesPersonMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aTechnicianServiceDetails]  WITH CHECK ADD  CONSTRAINT [fk_aTechnicianServiceDetails_aSalesPersonMaster] FOREIGN KEY([serTechnicianID])
REFERENCES [dbo].[AsalesPersonmaster] ([Sperid])
GO
ALTER TABLE [dbo].[aTechnicianServiceDetails] CHECK CONSTRAINT [fk_aTechnicianServiceDetails_aSalesPersonMaster]
GO
/****** Object:  ForeignKey [fk_aTechnicianServiceDetails_aServiceMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aTechnicianServiceDetails]  WITH CHECK ADD  CONSTRAINT [fk_aTechnicianServiceDetails_aServiceMaster] FOREIGN KEY([serid], [sercompanyid])
REFERENCES [dbo].[aservicemaster] ([serid], [sercompanyid])
GO
ALTER TABLE [dbo].[aTechnicianServiceDetails] CHECK CONSTRAINT [fk_aTechnicianServiceDetails_aServiceMaster]
GO
/****** Object:  ForeignKey [fk_losSerMaintenanceContractDetail_acompanymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerMaintenanceContractDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSerMaintenanceContractDetail_acompanymaster] FOREIGN KEY([mcdCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[losSerMaintenanceContractDetail] CHECK CONSTRAINT [fk_losSerMaintenanceContractDetail_acompanymaster]
GO
/****** Object:  ForeignKey [fk_losSerMaintenanceContractDetail_AsalesPersonmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerMaintenanceContractDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSerMaintenanceContractDetail_AsalesPersonmaster] FOREIGN KEY([mcdPrepByID])
REFERENCES [dbo].[AsalesPersonmaster] ([Sperid])
GO
ALTER TABLE [dbo].[losSerMaintenanceContractDetail] CHECK CONSTRAINT [fk_losSerMaintenanceContractDetail_AsalesPersonmaster]
GO
/****** Object:  ForeignKey [fk_losSerMaintenanceContractDetail_losSerMaintenanceContractHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerMaintenanceContractDetail]  WITH CHECK ADD  CONSTRAINT [fk_losSerMaintenanceContractDetail_losSerMaintenanceContractHeader] FOREIGN KEY([mcdCompanyID], [mcdID], [mcdShopID])
REFERENCES [dbo].[losSerMaintenanceContractHeader] ([mchCompanyID], [mchID], [mchShopID])
GO
ALTER TABLE [dbo].[losSerMaintenanceContractDetail] CHECK CONSTRAINT [fk_losSerMaintenanceContractDetail_losSerMaintenanceContractHeader]
GO
/****** Object:  ForeignKey [FK_ExchangeRateDetail_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ExchangeRateDetail]  WITH CHECK ADD  CONSTRAINT [FK_ExchangeRateDetail_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[ExchangeRateDetail] CHECK CONSTRAINT [FK_ExchangeRateDetail_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_ExchangeRateDetail_aCurrencyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ExchangeRateDetail]  WITH CHECK ADD  CONSTRAINT [FK_ExchangeRateDetail_aCurrencyMaster] FOREIGN KEY([CurrencyID], [CompanyID])
REFERENCES [dbo].[aCurrencyMaster] ([CurrencyID], [CompanyID])
GO
ALTER TABLE [dbo].[ExchangeRateDetail] CHECK CONSTRAINT [FK_ExchangeRateDetail_aCurrencyMaster]
GO
/****** Object:  ForeignKey [FK_ExchangeRateDetail_ExchangeRate]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ExchangeRateDetail]  WITH CHECK ADD  CONSTRAINT [FK_ExchangeRateDetail_ExchangeRate] FOREIGN KEY([ExchangeID], [CompanyID])
REFERENCES [dbo].[ExchangeRate] ([ExchangeID], [CompanyID])
GO
ALTER TABLE [dbo].[ExchangeRateDetail] CHECK CONSTRAINT [FK_ExchangeRateDetail_ExchangeRate]
GO
/****** Object:  ForeignKey [FK_afineDetail_aFineHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aFineDetail]  WITH CHECK ADD  CONSTRAINT [FK_afineDetail_aFineHeader] FOREIGN KEY([fdFineID])
REFERENCES [dbo].[aFineHeader] ([fhFineID])
GO
ALTER TABLE [dbo].[aFineDetail] CHECK CONSTRAINT [FK_afineDetail_aFineHeader]
GO
/****** Object:  ForeignKey [FK_CrmTask_aUsergroups]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CrmTask]  WITH CHECK ADD  CONSTRAINT [FK_CrmTask_aUsergroups] FOREIGN KEY([UserGroupId], [CompanyId])
REFERENCES [dbo].[aUsergroups] ([UserGroupID], [CompanyID])
GO
ALTER TABLE [dbo].[CrmTask] CHECK CONSTRAINT [FK_CrmTask_aUsergroups]
GO
/****** Object:  ForeignKey [FK_CrmUserHirarchey_aUsergroups]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CrmUserHirarchey]  WITH CHECK ADD  CONSTRAINT [FK_CrmUserHirarchey_aUsergroups] FOREIGN KEY([UserGroupID], [CompanyId])
REFERENCES [dbo].[aUsergroups] ([UserGroupID], [CompanyID])
GO
ALTER TABLE [dbo].[CrmUserHirarchey] CHECK CONSTRAINT [FK_CrmUserHirarchey_aUsergroups]
GO
/****** Object:  ForeignKey [fk_aUserDeptDetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aUserDeptDetails]  WITH CHECK ADD  CONSTRAINT [fk_aUserDeptDetails] FOREIGN KEY([userid], [companyid])
REFERENCES [dbo].[aUsers] ([UserID], [CompanyID])
GO
ALTER TABLE [dbo].[aUserDeptDetails] CHECK CONSTRAINT [fk_aUserDeptDetails]
GO
/****** Object:  ForeignKey [FK_AAccRatioEntitiesMaster_aAccRatioGroupMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AAccRatioEntitiesMaster]  WITH CHECK ADD  CONSTRAINT [FK_AAccRatioEntitiesMaster_aAccRatioGroupMaster] FOREIGN KEY([CompanyID], [GroupID])
REFERENCES [dbo].[aAccRatioGroupMaster] ([CompanyID], [GroupID])
GO
ALTER TABLE [dbo].[AAccRatioEntitiesMaster] CHECK CONSTRAINT [FK_AAccRatioEntitiesMaster_aAccRatioGroupMaster]
GO
/****** Object:  ForeignKey [FK_aCurrencyMaster_aCountryMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCurrencyMaster]  WITH CHECK ADD  CONSTRAINT [FK_aCurrencyMaster_aCountryMaster] FOREIGN KEY([CountryID], [CompanyID])
REFERENCES [dbo].[aCountryMaster] ([CountryID], [CompanyID])
GO
ALTER TABLE [dbo].[aCurrencyMaster] CHECK CONSTRAINT [FK_aCurrencyMaster_aCountryMaster]
GO
/****** Object:  ForeignKey [fk_aCity_acompanymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCity]  WITH CHECK ADD  CONSTRAINT [fk_aCity_acompanymaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aCity] CHECK CONSTRAINT [fk_aCity_acompanymaster]
GO
/****** Object:  ForeignKey [fk_aCity_acountrymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aCity]  WITH CHECK ADD  CONSTRAINT [fk_aCity_acountrymaster] FOREIGN KEY([CountryID], [CompanyID])
REFERENCES [dbo].[aCountryMaster] ([CountryID], [CompanyID])
GO
ALTER TABLE [dbo].[aCity] CHECK CONSTRAINT [fk_aCity_acountrymaster]
GO
/****** Object:  ForeignKey [FK_aVendorMaster_aCity]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aVendorMaster]  WITH CHECK ADD  CONSTRAINT [FK_aVendorMaster_aCity] FOREIGN KEY([CityID])
REFERENCES [dbo].[aCity] ([CityID])
GO
ALTER TABLE [dbo].[aVendorMaster] CHECK CONSTRAINT [FK_aVendorMaster_aCity]
GO
/****** Object:  ForeignKey [FK_aVendorMaster_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aVendorMaster]  WITH CHECK ADD  CONSTRAINT [FK_aVendorMaster_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aVendorMaster] CHECK CONSTRAINT [FK_aVendorMaster_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_aVendorMaster_aCountryMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aVendorMaster]  WITH CHECK ADD  CONSTRAINT [FK_aVendorMaster_aCountryMaster] FOREIGN KEY([CountryID], [CompanyID])
REFERENCES [dbo].[aCountryMaster] ([CountryID], [CompanyID])
GO
ALTER TABLE [dbo].[aVendorMaster] CHECK CONSTRAINT [FK_aVendorMaster_aCountryMaster]
GO
/****** Object:  ForeignKey [FK_aVendorMaster_aCurrencyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aVendorMaster]  WITH CHECK ADD  CONSTRAINT [FK_aVendorMaster_aCurrencyMaster] FOREIGN KEY([CurrencyID], [CompanyID])
REFERENCES [dbo].[aCurrencyMaster] ([CurrencyID], [CompanyID])
GO
ALTER TABLE [dbo].[aVendorMaster] CHECK CONSTRAINT [FK_aVendorMaster_aCurrencyMaster]
GO
/****** Object:  ForeignKey [fk_aGodown_aaccountmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodown]  WITH CHECK ADD  CONSTRAINT [fk_aGodown_aaccountmaster] FOREIGN KEY([stockwriteoffaccid], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aGodown] CHECK CONSTRAINT [fk_aGodown_aaccountmaster]
GO
/****** Object:  ForeignKey [FK_aGodown_aCity]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodown]  WITH CHECK ADD  CONSTRAINT [FK_aGodown_aCity] FOREIGN KEY([CityID])
REFERENCES [dbo].[aCity] ([CityID])
GO
ALTER TABLE [dbo].[aGodown] CHECK CONSTRAINT [FK_aGodown_aCity]
GO
/****** Object:  ForeignKey [FK_aGodown_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodown]  WITH CHECK ADD  CONSTRAINT [FK_aGodown_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aGodown] CHECK CONSTRAINT [FK_aGodown_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_aGodown_aCountryMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodown]  WITH CHECK ADD  CONSTRAINT [FK_aGodown_aCountryMaster] FOREIGN KEY([CountryID], [CompanyID])
REFERENCES [dbo].[aCountryMaster] ([CountryID], [CompanyID])
GO
ALTER TABLE [dbo].[aGodown] CHECK CONSTRAINT [FK_aGodown_aCountryMaster]
GO
/****** Object:  ForeignKey [FK_aGodown_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aGodown]  WITH CHECK ADD  CONSTRAINT [FK_aGodown_aDepartmentMaster] FOREIGN KEY([DepartmentId], [CompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[aGodown] CHECK CONSTRAINT [FK_aGodown_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_Forex_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Forex]  WITH CHECK ADD  CONSTRAINT [FK_Forex_aAccountMaster] FOREIGN KEY([salesorpurchaseaccid], [companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[Forex] CHECK CONSTRAINT [FK_Forex_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_Forex_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Forex]  WITH CHECK ADD  CONSTRAINT [FK_Forex_aAccountMaster1] FOREIGN KEY([otheraccid], [companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[Forex] CHECK CONSTRAINT [FK_Forex_aAccountMaster1]
GO
/****** Object:  ForeignKey [FK_Forex_aAccountMaster2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Forex]  WITH CHECK ADD  CONSTRAINT [FK_Forex_aAccountMaster2] FOREIGN KEY([forexgainlossaccid], [companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[Forex] CHECK CONSTRAINT [FK_Forex_aAccountMaster2]
GO
/****** Object:  ForeignKey [FK_Forex_aAccountMaster3]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Forex]  WITH CHECK ADD  CONSTRAINT [FK_Forex_aAccountMaster3] FOREIGN KEY([forexgainlossaccid], [companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[Forex] CHECK CONSTRAINT [FK_Forex_aAccountMaster3]
GO
/****** Object:  ForeignKey [FK_Forex_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Forex]  WITH CHECK ADD  CONSTRAINT [FK_Forex_aCompanyMaster] FOREIGN KEY([companyid])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[Forex] CHECK CONSTRAINT [FK_Forex_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_Forex_aCountryMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Forex]  WITH CHECK ADD  CONSTRAINT [FK_Forex_aCountryMaster] FOREIGN KEY([nationalityid], [companyid])
REFERENCES [dbo].[aCountryMaster] ([CountryID], [CompanyID])
GO
ALTER TABLE [dbo].[Forex] CHECK CONSTRAINT [FK_Forex_aCountryMaster]
GO
/****** Object:  ForeignKey [FK_Forex_aCustomerMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Forex]  WITH CHECK ADD  CONSTRAINT [FK_Forex_aCustomerMaster] FOREIGN KEY([customerid])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[Forex] CHECK CONSTRAINT [FK_Forex_aCustomerMaster]
GO
/****** Object:  ForeignKey [FK_Forex_aVendorMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Forex]  WITH CHECK ADD  CONSTRAINT [FK_Forex_aVendorMaster] FOREIGN KEY([vendorid])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[Forex] CHECK CONSTRAINT [FK_Forex_aVendorMaster]
GO
/****** Object:  ForeignKey [fk_aHQPaymentVoucherRebateDetails_aHQPaymentVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherRebateDetails]  WITH CHECK ADD  CONSTRAINT [fk_aHQPaymentVoucherRebateDetails_aHQPaymentVoucherHeader] FOREIGN KEY([PaymentID])
REFERENCES [dbo].[aHQPaymentVoucherHeader] ([phPaymentID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherRebateDetails] CHECK CONSTRAINT [fk_aHQPaymentVoucherRebateDetails_aHQPaymentVoucherHeader]
GO
/****** Object:  ForeignKey [pk_aHQPaymentVoucherRebateDetails_losRebateConfirmHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherRebateDetails]  WITH CHECK ADD  CONSTRAINT [pk_aHQPaymentVoucherRebateDetails_losRebateConfirmHeader] FOREIGN KEY([ShopID], [RebateApprovalID])
REFERENCES [dbo].[losrebateconfirmheader] ([rcshopid], [rcapprovedid])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherRebateDetails] CHECK CONSTRAINT [pk_aHQPaymentVoucherRebateDetails_losRebateConfirmHeader]
GO
/****** Object:  ForeignKey [FK_Depreciation_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DepreciationHeader]  WITH NOCHECK ADD  CONSTRAINT [FK_Depreciation_aAccountMaster1] FOREIGN KEY([DeprAccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[DepreciationHeader] CHECK CONSTRAINT [FK_Depreciation_aAccountMaster1]
GO
/****** Object:  ForeignKey [FK_Depreciation_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DepreciationHeader]  WITH NOCHECK ADD  CONSTRAINT [FK_Depreciation_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[DepreciationHeader] CHECK CONSTRAINT [FK_Depreciation_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_Depreciation_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DepreciationHeader]  WITH NOCHECK ADD  CONSTRAINT [FK_Depreciation_aDepartmentMaster] FOREIGN KEY([DepartmentID], [CompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[DepreciationHeader] CHECK CONSTRAINT [FK_Depreciation_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_Depreciation_aFinancialYear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DepreciationHeader]  WITH NOCHECK ADD  CONSTRAINT [FK_Depreciation_aFinancialYear] FOREIGN KEY([FinancialID], [CompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[DepreciationHeader] CHECK CONSTRAINT [FK_Depreciation_aFinancialYear]
GO
/****** Object:  ForeignKey [FK_AccountsInvoiceHeader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AccountsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_AccountsInvoiceHeader_aAccountMaster] FOREIGN KEY([BankCashID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[AccountsInvoiceHeader] CHECK CONSTRAINT [FK_AccountsInvoiceHeader_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_AccountsInvoiceHeader_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AccountsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_AccountsInvoiceHeader_aAccountMaster1] FOREIGN KEY([DiscountAccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[AccountsInvoiceHeader] CHECK CONSTRAINT [FK_AccountsInvoiceHeader_aAccountMaster1]
GO
/****** Object:  ForeignKey [FK_AccountsInvoiceHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AccountsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_AccountsInvoiceHeader_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[AccountsInvoiceHeader] CHECK CONSTRAINT [FK_AccountsInvoiceHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [fk_accountsinvoiceheader_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AccountsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [fk_accountsinvoiceheader_acustomermaster] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[AccountsInvoiceHeader] CHECK CONSTRAINT [fk_accountsinvoiceheader_acustomermaster]
GO
/****** Object:  ForeignKey [FK_AccountsInvoiceHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AccountsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_AccountsInvoiceHeader_aDepartmentMaster] FOREIGN KEY([DepartmentID], [CompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[AccountsInvoiceHeader] CHECK CONSTRAINT [FK_AccountsInvoiceHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_AccountsInvoiceHeader_aFinancialYear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AccountsInvoiceHeader]  WITH CHECK ADD  CONSTRAINT [FK_AccountsInvoiceHeader_aFinancialYear] FOREIGN KEY([FinancialID], [CompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[AccountsInvoiceHeader] CHECK CONSTRAINT [FK_AccountsInvoiceHeader_aFinancialYear]
GO
/****** Object:  ForeignKey [fk_InterDivisionBillsHeader_accountmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[InterDivisionBillsHeader]  WITH NOCHECK ADD  CONSTRAINT [fk_InterDivisionBillsHeader_accountmaster] FOREIGN KEY([BankCashAccID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[InterDivisionBillsHeader] CHECK CONSTRAINT [fk_InterDivisionBillsHeader_accountmaster]
GO
/****** Object:  ForeignKey [fk_InterDivisionBillsHeader_accountmasterDiscAcc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[InterDivisionBillsHeader]  WITH NOCHECK ADD  CONSTRAINT [fk_InterDivisionBillsHeader_accountmasterDiscAcc] FOREIGN KEY([DiscountAccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[InterDivisionBillsHeader] CHECK CONSTRAINT [fk_InterDivisionBillsHeader_accountmasterDiscAcc]
GO
/****** Object:  ForeignKey [fk_InterDivisionBillsHeader_avendormaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[InterDivisionBillsHeader]  WITH NOCHECK ADD  CONSTRAINT [fk_InterDivisionBillsHeader_avendormaster] FOREIGN KEY([VendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[InterDivisionBillsHeader] CHECK CONSTRAINT [fk_InterDivisionBillsHeader_avendormaster]
GO
/****** Object:  ForeignKey [fk_InterDivisionBillsHeader_Company]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[InterDivisionBillsHeader]  WITH NOCHECK ADD  CONSTRAINT [fk_InterDivisionBillsHeader_Company] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[InterDivisionBillsHeader] CHECK CONSTRAINT [fk_InterDivisionBillsHeader_Company]
GO
/****** Object:  ForeignKey [fk_InterDivisionBillsHeader_financialyear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[InterDivisionBillsHeader]  WITH NOCHECK ADD  CONSTRAINT [fk_InterDivisionBillsHeader_financialyear] FOREIGN KEY([FinancialID], [CompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[InterDivisionBillsHeader] CHECK CONSTRAINT [fk_InterDivisionBillsHeader_financialyear]
GO
/****** Object:  ForeignKey [fk_losdebitcreditnote_accountmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDebitCreditNote]  WITH CHECK ADD  CONSTRAINT [fk_losdebitcreditnote_accountmaster] FOREIGN KEY([losDCNOtherAccId], [losDCNCompanyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[losDebitCreditNote] CHECK CONSTRAINT [fk_losdebitcreditnote_accountmaster]
GO
/****** Object:  ForeignKey [fk_losDebitCreditNote_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDebitCreditNote]  WITH CHECK ADD  CONSTRAINT [fk_losDebitCreditNote_acustomermaster] FOREIGN KEY([losDCNCustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[losDebitCreditNote] CHECK CONSTRAINT [fk_losDebitCreditNote_acustomermaster]
GO
/****** Object:  ForeignKey [fk_losDebitCreditNote_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDebitCreditNote]  WITH CHECK ADD  CONSTRAINT [fk_losDebitCreditNote_adepartmentmaster] FOREIGN KEY([losdcndepartmentid], [losDCNCompanyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[losDebitCreditNote] CHECK CONSTRAINT [fk_losDebitCreditNote_adepartmentmaster]
GO
/****** Object:  ForeignKey [fk_losDebitCreditNote_afinancialyear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDebitCreditNote]  WITH CHECK ADD  CONSTRAINT [fk_losDebitCreditNote_afinancialyear] FOREIGN KEY([losfinancialid], [losDCNCompanyid])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[losDebitCreditNote] CHECK CONSTRAINT [fk_losDebitCreditNote_afinancialyear]
GO
/****** Object:  ForeignKey [fk_losDebitCreditNote_avendormaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDebitCreditNote]  WITH CHECK ADD  CONSTRAINT [fk_losDebitCreditNote_avendormaster] FOREIGN KEY([losDCNVendorId])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[losDebitCreditNote] CHECK CONSTRAINT [fk_losDebitCreditNote_avendormaster]
GO
/****** Object:  ForeignKey [fk_losdebitcreditnote_shop]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDebitCreditNote]  WITH CHECK ADD  CONSTRAINT [fk_losdebitcreditnote_shop] FOREIGN KEY([losDCNShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losDebitCreditNote] CHECK CONSTRAINT [fk_losdebitcreditnote_shop]
GO
/****** Object:  ForeignKey [fk_debitcreditnote_accountmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DebitCreditNote]  WITH CHECK ADD  CONSTRAINT [fk_debitcreditnote_accountmaster] FOREIGN KEY([DCNOtherAccId], [DCNCompanyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[DebitCreditNote] CHECK CONSTRAINT [fk_debitcreditnote_accountmaster]
GO
/****** Object:  ForeignKey [fk_debitcreditnote_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DebitCreditNote]  WITH CHECK ADD  CONSTRAINT [fk_debitcreditnote_acustomermaster] FOREIGN KEY([DCNCustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[DebitCreditNote] CHECK CONSTRAINT [fk_debitcreditnote_acustomermaster]
GO
/****** Object:  ForeignKey [fk_DebitCreditNote_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DebitCreditNote]  WITH CHECK ADD  CONSTRAINT [fk_DebitCreditNote_adepartmentmaster] FOREIGN KEY([dcndepartmentid], [DCNCompanyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[DebitCreditNote] CHECK CONSTRAINT [fk_DebitCreditNote_adepartmentmaster]
GO
/****** Object:  ForeignKey [fk_DebitCreditNote_afinancialyear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DebitCreditNote]  WITH CHECK ADD  CONSTRAINT [fk_DebitCreditNote_afinancialyear] FOREIGN KEY([Dcnfinancialid], [DCNCompanyid])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[DebitCreditNote] CHECK CONSTRAINT [fk_DebitCreditNote_afinancialyear]
GO
/****** Object:  ForeignKey [fk_debitcreditnote_avendormaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DebitCreditNote]  WITH CHECK ADD  CONSTRAINT [fk_debitcreditnote_avendormaster] FOREIGN KEY([DCNVendorId])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[DebitCreditNote] CHECK CONSTRAINT [fk_debitcreditnote_avendormaster]
GO
/****** Object:  ForeignKey [fk_debitcreditnote_companymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DebitCreditNote]  WITH CHECK ADD  CONSTRAINT [fk_debitcreditnote_companymaster] FOREIGN KEY([DCNCompanyid])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[DebitCreditNote] CHECK CONSTRAINT [fk_debitcreditnote_companymaster]
GO
/****** Object:  ForeignKey [fk_DebitCreditNote_HQSalesPromotionDetail]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DebitCreditNote]  WITH CHECK ADD  CONSTRAINT [fk_DebitCreditNote_HQSalesPromotionDetail] FOREIGN KEY([DCNCompanyid], [dcnSalesPromotionID], [dcnSalesPromotionDetID])
REFERENCES [dbo].[HQSalesPromotionDetail] ([spdCompanyID], [spdpromotionID], [spdDetailID])
GO
ALTER TABLE [dbo].[DebitCreditNote] CHECK CONSTRAINT [fk_DebitCreditNote_HQSalesPromotionDetail]
GO
/****** Object:  ForeignKey [fk_debitcreditnote_losppurchasebillheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DebitCreditNote]  WITH CHECK ADD  CONSTRAINT [fk_debitcreditnote_losppurchasebillheader] FOREIGN KEY([DCNBillId])
REFERENCES [dbo].[LOspPurchaseBillHeader] ([pbhBillID])
GO
ALTER TABLE [dbo].[DebitCreditNote] CHECK CONSTRAINT [fk_debitcreditnote_losppurchasebillheader]
GO
/****** Object:  ForeignKey [FK_ReceiptVoucherHeader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherHeader]  WITH CHECK ADD  CONSTRAINT [FK_ReceiptVoucherHeader_aAccountMaster] FOREIGN KEY([BankCashAccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[ReceiptVoucherHeader] CHECK CONSTRAINT [FK_ReceiptVoucherHeader_aAccountMaster]
GO
/****** Object:  ForeignKey [fk_receiptvoucherheader_aaccountmaster_deb]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_receiptvoucherheader_aaccountmaster_deb] FOREIGN KEY([debitaccountid], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[ReceiptVoucherHeader] CHECK CONSTRAINT [fk_receiptvoucherheader_aaccountmaster_deb]
GO
/****** Object:  ForeignKey [FK_ReceiptVoucherHeader_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherHeader]  WITH CHECK ADD  CONSTRAINT [FK_ReceiptVoucherHeader_aAccountMaster1] FOREIGN KEY([creditaccountid], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[ReceiptVoucherHeader] CHECK CONSTRAINT [FK_ReceiptVoucherHeader_aAccountMaster1]
GO
/****** Object:  ForeignKey [FK_ReceiptVoucherHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherHeader]  WITH CHECK ADD  CONSTRAINT [FK_ReceiptVoucherHeader_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[ReceiptVoucherHeader] CHECK CONSTRAINT [FK_ReceiptVoucherHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [fk_receiptvoucherheader_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_receiptvoucherheader_acustomermaster] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[ReceiptVoucherHeader] CHECK CONSTRAINT [fk_receiptvoucherheader_acustomermaster]
GO
/****** Object:  ForeignKey [fk_receiptvoucherheader_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_receiptvoucherheader_adepartmentmaster] FOREIGN KEY([DepartmentID], [CompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[ReceiptVoucherHeader] CHECK CONSTRAINT [fk_receiptvoucherheader_adepartmentmaster]
GO
/****** Object:  ForeignKey [fk_receiptvoucherheader_afinancialyear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_receiptvoucherheader_afinancialyear] FOREIGN KEY([FinancialID], [CompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[ReceiptVoucherHeader] CHECK CONSTRAINT [fk_receiptvoucherheader_afinancialyear]
GO
/****** Object:  ForeignKey [fk_receiptvoucherheader_avendormaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_receiptvoucherheader_avendormaster] FOREIGN KEY([VendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[ReceiptVoucherHeader] CHECK CONSTRAINT [fk_receiptvoucherheader_avendormaster]
GO
/****** Object:  ForeignKey [fk_receiptvoucherheader_losDummyReceiptHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_receiptvoucherheader_losDummyReceiptHeader] FOREIGN KEY([recshopid], [dummyreceiptid])
REFERENCES [dbo].[losDummyReceiptHeader] ([drShopid], [drId])
GO
ALTER TABLE [dbo].[ReceiptVoucherHeader] CHECK CONSTRAINT [fk_receiptvoucherheader_losDummyReceiptHeader]
GO
/****** Object:  ForeignKey [fk_lopurchasereturndetail_afinancialyear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPurchasereturnheader]  WITH CHECK ADD  CONSTRAINT [fk_lopurchasereturndetail_afinancialyear] FOREIGN KEY([prhFinancialID], [prhcompanyid])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[loPurchasereturnheader] CHECK CONSTRAINT [fk_lopurchasereturndetail_afinancialyear]
GO
/****** Object:  ForeignKey [FK_loPurchasereturnheader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPurchasereturnheader]  WITH CHECK ADD  CONSTRAINT [FK_loPurchasereturnheader_aAccountMaster] FOREIGN KEY([prhadjaccountid], [prhcompanyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[loPurchasereturnheader] CHECK CONSTRAINT [FK_loPurchasereturnheader_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_loPurchasereturnheader_aVendorMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPurchasereturnheader]  WITH CHECK ADD  CONSTRAINT [FK_loPurchasereturnheader_aVendorMaster] FOREIGN KEY([prhvendorid])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[loPurchasereturnheader] CHECK CONSTRAINT [FK_loPurchasereturnheader_aVendorMaster]
GO
/****** Object:  ForeignKey [FK_MOaJournalHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOaJournalHeader]  WITH CHECK ADD  CONSTRAINT [FK_MOaJournalHeader_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[MOaJournalHeader] CHECK CONSTRAINT [FK_MOaJournalHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [fk_moajournalheader_acurrencymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOaJournalHeader]  WITH CHECK ADD  CONSTRAINT [fk_moajournalheader_acurrencymaster] FOREIGN KEY([CurrencyId], [CompanyID])
REFERENCES [dbo].[aCurrencyMaster] ([CurrencyID], [CompanyID])
GO
ALTER TABLE [dbo].[MOaJournalHeader] CHECK CONSTRAINT [fk_moajournalheader_acurrencymaster]
GO
/****** Object:  ForeignKey [fk_moajournalheader_afinancialyear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOaJournalHeader]  WITH CHECK ADD  CONSTRAINT [fk_moajournalheader_afinancialyear] FOREIGN KEY([FinancialID], [CompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[MOaJournalHeader] CHECK CONSTRAINT [fk_moajournalheader_afinancialyear]
GO
/****** Object:  ForeignKey [fk_aaccountfinyearopening_aaccountmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aAccountFinYearOpening]  WITH CHECK ADD  CONSTRAINT [fk_aaccountfinyearopening_aaccountmaster] FOREIGN KEY([Accountid], [Companyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aAccountFinYearOpening] CHECK CONSTRAINT [fk_aaccountfinyearopening_aaccountmaster]
GO
/****** Object:  ForeignKey [fk_aaccountfinyearopening_acompanymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aAccountFinYearOpening]  WITH CHECK ADD  CONSTRAINT [fk_aaccountfinyearopening_acompanymaster] FOREIGN KEY([Companyid])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aAccountFinYearOpening] CHECK CONSTRAINT [fk_aaccountfinyearopening_acompanymaster]
GO
/****** Object:  ForeignKey [fk_aaccountfinyearopening_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aAccountFinYearOpening]  WITH CHECK ADD  CONSTRAINT [fk_aaccountfinyearopening_adepartmentmaster] FOREIGN KEY([departmentid], [Companyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[aAccountFinYearOpening] CHECK CONSTRAINT [fk_aaccountfinyearopening_adepartmentmaster]
GO
/****** Object:  ForeignKey [fk_aaccountfinyearopening_afinancialyear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aAccountFinYearOpening]  WITH CHECK ADD  CONSTRAINT [fk_aaccountfinyearopening_afinancialyear] FOREIGN KEY([Financialid], [Companyid])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[aAccountFinYearOpening] CHECK CONSTRAINT [fk_aaccountfinyearopening_afinancialyear]
GO
/****** Object:  ForeignKey [FK_LOspPurchaseBillHeader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOspPurchaseBillHeader_aAccountMaster] FOREIGN KEY([pbhDiscountAccID], [pbhCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOspPurchaseBillHeader] CHECK CONSTRAINT [FK_LOspPurchaseBillHeader_aAccountMaster]
GO
/****** Object:  ForeignKey [fk_lospPurchasebillHeader_aaccountmaster_pacc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillHeader]  WITH CHECK ADD  CONSTRAINT [fk_lospPurchasebillHeader_aaccountmaster_pacc] FOREIGN KEY([pbhPurchaseAccID], [pbhCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOspPurchaseBillHeader] CHECK CONSTRAINT [fk_lospPurchasebillHeader_aaccountmaster_pacc]
GO
/****** Object:  ForeignKey [FK_LOspPurchaseBillHeader_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOspPurchaseBillHeader_aAccountMaster1] FOREIGN KEY([pbhBankCashAccID], [pbhCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOspPurchaseBillHeader] CHECK CONSTRAINT [FK_LOspPurchaseBillHeader_aAccountMaster1]
GO
/****** Object:  ForeignKey [FK_LOspPurchaseBillHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOspPurchaseBillHeader_aCompanyMaster] FOREIGN KEY([pbhCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[LOspPurchaseBillHeader] CHECK CONSTRAINT [FK_LOspPurchaseBillHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_LOspPurchaseBillHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOspPurchaseBillHeader_aDepartmentMaster] FOREIGN KEY([pbhDepartmentID], [pbhCompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[LOspPurchaseBillHeader] CHECK CONSTRAINT [FK_LOspPurchaseBillHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_LOspPurchaseBillHeader_aFinancialYear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOspPurchaseBillHeader_aFinancialYear] FOREIGN KEY([pbhFinancialID], [pbhCompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[LOspPurchaseBillHeader] CHECK CONSTRAINT [FK_LOspPurchaseBillHeader_aFinancialYear]
GO
/****** Object:  ForeignKey [fk_lospPurchaseBillHeader_avendormaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillHeader]  WITH CHECK ADD  CONSTRAINT [fk_lospPurchaseBillHeader_avendormaster] FOREIGN KEY([pbhVendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[LOspPurchaseBillHeader] CHECK CONSTRAINT [fk_lospPurchaseBillHeader_avendormaster]
GO
/****** Object:  ForeignKey [FK_LOspPurchaseBillHeader_loPurchaseOrderHeader1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillHeader]  WITH NOCHECK ADD  CONSTRAINT [FK_LOspPurchaseBillHeader_loPurchaseOrderHeader1] FOREIGN KEY([pbhPOID])
REFERENCES [dbo].[loPurchaseOrderHeader] ([pohPoid])
GO
ALTER TABLE [dbo].[LOspPurchaseBillHeader] CHECK CONSTRAINT [FK_LOspPurchaseBillHeader_loPurchaseOrderHeader1]
GO
/****** Object:  ForeignKey [fk_Bills_accountmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Bills]  WITH NOCHECK ADD  CONSTRAINT [fk_Bills_accountmaster] FOREIGN KEY([BankCashAccID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[Bills] CHECK CONSTRAINT [fk_Bills_accountmaster]
GO
/****** Object:  ForeignKey [fk_Bills_accountmaster2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Bills]  WITH NOCHECK ADD  CONSTRAINT [fk_Bills_accountmaster2] FOREIGN KEY([DiscountAccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[Bills] CHECK CONSTRAINT [fk_Bills_accountmaster2]
GO
/****** Object:  ForeignKey [fk_bills_avendormaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Bills]  WITH NOCHECK ADD  CONSTRAINT [fk_bills_avendormaster] FOREIGN KEY([VendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[Bills] CHECK CONSTRAINT [fk_bills_avendormaster]
GO
/****** Object:  ForeignKey [fk_Bills_Company]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Bills]  WITH NOCHECK ADD  CONSTRAINT [fk_Bills_Company] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[Bills] CHECK CONSTRAINT [fk_Bills_Company]
GO
/****** Object:  ForeignKey [fk_Bills3_financialyear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Bills]  WITH NOCHECK ADD  CONSTRAINT [fk_Bills3_financialyear] FOREIGN KEY([FinancialID], [CompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[Bills] CHECK CONSTRAINT [fk_Bills3_financialyear]
GO
/****** Object:  ForeignKey [FK_FlightOperatorMaster_LosposFandBHeader_poshCompanyID_poshFlightOpID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader]  WITH CHECK ADD  CONSTRAINT [FK_FlightOperatorMaster_LosposFandBHeader_poshCompanyID_poshFlightOpID] FOREIGN KEY([poshCompanyID], [poshFlightOpID])
REFERENCES [dbo].[FlightOperatorMaster] ([companyid], [FlghtOpid])
GO
ALTER TABLE [dbo].[LosPosFAndBHeader] CHECK CONSTRAINT [FK_FlightOperatorMaster_LosposFandBHeader_poshCompanyID_poshFlightOpID]
GO
/****** Object:  ForeignKey [FK_losposfandbheader_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader]  WITH CHECK ADD  CONSTRAINT [FK_losposfandbheader_acustomermaster] FOREIGN KEY([poshcustomerid])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[LosPosFAndBHeader] CHECK CONSTRAINT [FK_losposfandbheader_acustomermaster]
GO
/****** Object:  ForeignKey [fk_losposfandbheader_afinancialyear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader]  WITH CHECK ADD  CONSTRAINT [fk_losposfandbheader_afinancialyear] FOREIGN KEY([poshFinancialId], [poshCompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[LosPosFAndBHeader] CHECK CONSTRAINT [fk_losposfandbheader_afinancialyear]
GO
/****** Object:  ForeignKey [FK_LosPosFAndBHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader]  WITH CHECK ADD  CONSTRAINT [FK_LosPosFAndBHeader_aShops] FOREIGN KEY([poshShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LosPosFAndBHeader] CHECK CONSTRAINT [FK_LosPosFAndBHeader_aShops]
GO
/****** Object:  ForeignKey [FK_Losposfandbheader_dishsegmentheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader]  WITH CHECK ADD  CONSTRAINT [FK_Losposfandbheader_dishsegmentheader] FOREIGN KEY([poshSegID], [poshCompanyID])
REFERENCES [dbo].[DishSegmentHeader] ([seg_header_id], [seg_header_companyID])
GO
ALTER TABLE [dbo].[LosPosFAndBHeader] CHECK CONSTRAINT [FK_Losposfandbheader_dishsegmentheader]
GO
/****** Object:  ForeignKey [FK_LosPosFAndBHeader_Flights]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader]  WITH CHECK ADD  CONSTRAINT [FK_LosPosFAndBHeader_Flights] FOREIGN KEY([poshCompanyID], [poshFlightID])
REFERENCES [dbo].[Flights] ([companyid], [FlightID])
GO
ALTER TABLE [dbo].[LosPosFAndBHeader] CHECK CONSTRAINT [FK_LosPosFAndBHeader_Flights]
GO
/****** Object:  ForeignKey [FK_losposfandbheader_vouchermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPosFAndBHeader]  WITH CHECK ADD  CONSTRAINT [FK_losposfandbheader_vouchermaster] FOREIGN KEY([poshvoucherid], [poshCompanyID])
REFERENCES [dbo].[VoucherMaster] ([VoucherID], [VoucherCompanyID])
GO
ALTER TABLE [dbo].[LosPosFAndBHeader] CHECK CONSTRAINT [FK_losposfandbheader_vouchermaster]
GO
/****** Object:  ForeignKey [FK_aHQPaymentVoucherHeader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [FK_aHQPaymentVoucherHeader_aAccountMaster] FOREIGN KEY([phBankCashID], [phCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherHeader] CHECK CONSTRAINT [FK_aHQPaymentVoucherHeader_aAccountMaster]
GO
/****** Object:  ForeignKey [fk_aHQPaymentVoucherheader_aaccountmaster_debit]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_aHQPaymentVoucherheader_aaccountmaster_debit] FOREIGN KEY([phdebitaccountid], [phCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherHeader] CHECK CONSTRAINT [fk_aHQPaymentVoucherheader_aaccountmaster_debit]
GO
/****** Object:  ForeignKey [FK_aHQPaymentVoucherHeader_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [FK_aHQPaymentVoucherHeader_aAccountMaster1] FOREIGN KEY([phGoodsinTransitaccid], [phCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherHeader] CHECK CONSTRAINT [FK_aHQPaymentVoucherHeader_aAccountMaster1]
GO
/****** Object:  ForeignKey [FK_aHQPaymentVoucherHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [FK_aHQPaymentVoucherHeader_aCompanyMaster] FOREIGN KEY([phCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherHeader] CHECK CONSTRAINT [FK_aHQPaymentVoucherHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [fk_aHQPaymentVoucherheader_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_aHQPaymentVoucherheader_acustomermaster] FOREIGN KEY([phCustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherHeader] CHECK CONSTRAINT [fk_aHQPaymentVoucherheader_acustomermaster]
GO
/****** Object:  ForeignKey [fk_aHQPaymentVoucherheader_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_aHQPaymentVoucherheader_adepartmentmaster] FOREIGN KEY([phDepartmentID], [phCompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherHeader] CHECK CONSTRAINT [fk_aHQPaymentVoucherheader_adepartmentmaster]
GO
/****** Object:  ForeignKey [fk_aHQPaymentVoucherheader_afinancialyear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_aHQPaymentVoucherheader_afinancialyear] FOREIGN KEY([phFinancialID], [phCompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherHeader] CHECK CONSTRAINT [fk_aHQPaymentVoucherheader_afinancialyear]
GO
/****** Object:  ForeignKey [fk_aHQPaymentVoucherheader_avendormaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherHeader]  WITH CHECK ADD  CONSTRAINT [fk_aHQPaymentVoucherheader_avendormaster] FOREIGN KEY([phVendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherHeader] CHECK CONSTRAINT [fk_aHQPaymentVoucherheader_avendormaster]
GO
/****** Object:  ForeignKey [fk_aHQPaymentVoucherheader_lopurchaseorderheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherHeader]  WITH NOCHECK ADD  CONSTRAINT [fk_aHQPaymentVoucherheader_lopurchaseorderheader] FOREIGN KEY([phpohid])
REFERENCES [dbo].[loPurchaseOrderHeader] ([pohPoid])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherHeader] CHECK CONSTRAINT [fk_aHQPaymentVoucherheader_lopurchaseorderheader]
GO
/****** Object:  ForeignKey [FK_JournalTransHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[JournalTransHeader]  WITH CHECK ADD  CONSTRAINT [FK_JournalTransHeader_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[JournalTransHeader] CHECK CONSTRAINT [FK_JournalTransHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_JournalTransHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[JournalTransHeader]  WITH CHECK ADD  CONSTRAINT [FK_JournalTransHeader_aDepartmentMaster] FOREIGN KEY([departmentid], [CompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[JournalTransHeader] CHECK CONSTRAINT [FK_JournalTransHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_JournalTransHeader_aFinancialYear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[JournalTransHeader]  WITH CHECK ADD  CONSTRAINT [FK_JournalTransHeader_aFinancialYear] FOREIGN KEY([FinancialID], [CompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[JournalTransHeader] CHECK CONSTRAINT [FK_JournalTransHeader_aFinancialYear]
GO
/****** Object:  ForeignKey [FK_Contra_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Contra]  WITH CHECK ADD  CONSTRAINT [FK_Contra_aAccountMaster] FOREIGN KEY([FromAccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[Contra] CHECK CONSTRAINT [FK_Contra_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_Contra_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Contra]  WITH CHECK ADD  CONSTRAINT [FK_Contra_aAccountMaster1] FOREIGN KEY([ToAccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[Contra] CHECK CONSTRAINT [FK_Contra_aAccountMaster1]
GO
/****** Object:  ForeignKey [fk_contra_aaccountmaster2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Contra]  WITH CHECK ADD  CONSTRAINT [fk_contra_aaccountmaster2] FOREIGN KEY([ChargeAccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[Contra] CHECK CONSTRAINT [fk_contra_aaccountmaster2]
GO
/****** Object:  ForeignKey [FK_Contra_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Contra]  WITH CHECK ADD  CONSTRAINT [FK_Contra_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[Contra] CHECK CONSTRAINT [FK_Contra_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_Contra_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Contra]  WITH CHECK ADD  CONSTRAINT [FK_Contra_aDepartmentMaster] FOREIGN KEY([DepartmentID], [CompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[Contra] CHECK CONSTRAINT [FK_Contra_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_Contra_aFinancialYear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Contra]  WITH CHECK ADD  CONSTRAINT [FK_Contra_aFinancialYear] FOREIGN KEY([FinancialID], [CompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[Contra] CHECK CONSTRAINT [FK_Contra_aFinancialYear]
GO
/****** Object:  ForeignKey [FK_AdjustmentHeader_AccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AdjustmentHeader]  WITH CHECK ADD  CONSTRAINT [FK_AdjustmentHeader_AccountMaster] FOREIGN KEY([Accountid], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[AdjustmentHeader] CHECK CONSTRAINT [FK_AdjustmentHeader_AccountMaster]
GO
/****** Object:  ForeignKey [FK_AdjustmentHeader_CompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AdjustmentHeader]  WITH CHECK ADD  CONSTRAINT [FK_AdjustmentHeader_CompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[AdjustmentHeader] CHECK CONSTRAINT [FK_AdjustmentHeader_CompanyMaster]
GO
/****** Object:  ForeignKey [FK_AdjustmentHeader_DepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AdjustmentHeader]  WITH CHECK ADD  CONSTRAINT [FK_AdjustmentHeader_DepartmentMaster] FOREIGN KEY([Departmentid], [CompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[AdjustmentHeader] CHECK CONSTRAINT [FK_AdjustmentHeader_DepartmentMaster]
GO
/****** Object:  ForeignKey [FK_AdjustmentHeader_FinancialYear]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AdjustmentHeader]  WITH CHECK ADD  CONSTRAINT [FK_AdjustmentHeader_FinancialYear] FOREIGN KEY([FinancialID], [CompanyID])
REFERENCES [dbo].[aFinancialYear] ([FinancialID], [CompanyID])
GO
ALTER TABLE [dbo].[AdjustmentHeader] CHECK CONSTRAINT [FK_AdjustmentHeader_FinancialYear]
GO
/****** Object:  ForeignKey [fk_HQSalesPromotionDetail_aCustomerMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[HQSalesPromotionDetail]  WITH CHECK ADD  CONSTRAINT [fk_HQSalesPromotionDetail_aCustomerMaster] FOREIGN KEY([spdCustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[HQSalesPromotionDetail] CHECK CONSTRAINT [fk_HQSalesPromotionDetail_aCustomerMaster]
GO
/****** Object:  ForeignKey [fk_HQSalesPromotionDetail_HQSalesPromotionHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[HQSalesPromotionDetail]  WITH CHECK ADD  CONSTRAINT [fk_HQSalesPromotionDetail_HQSalesPromotionHeader] FOREIGN KEY([spdCompanyID], [spdpromotionID])
REFERENCES [dbo].[HQSalesPromotionHeader] ([sphCompanyID], [sphPromotionID])
GO
ALTER TABLE [dbo].[HQSalesPromotionDetail] CHECK CONSTRAINT [fk_HQSalesPromotionDetail_HQSalesPromotionHeader]
GO
/****** Object:  ForeignKey [FK_loiUserAuditDetail_loiUserAuditHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiUserAuditDetail]  WITH NOCHECK ADD  CONSTRAINT [FK_loiUserAuditDetail_loiUserAuditHeader] FOREIGN KEY([gdCompanyId], [gdAuditId], [gdGodownId])
REFERENCES [dbo].[loiUserAuditHeader] ([ghCompanyId], [ghAuditId], [ghGodownId])
GO
ALTER TABLE [dbo].[loiUserAuditDetail] CHECK CONSTRAINT [FK_loiUserAuditDetail_loiUserAuditHeader]
GO
/****** Object:  ForeignKey [fk_asettings_aaccountmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSettings]  WITH CHECK ADD  CONSTRAINT [fk_asettings_aaccountmaster] FOREIGN KEY([TradeDebtorAcID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aSettings] CHECK CONSTRAINT [fk_asettings_aaccountmaster]
GO
/****** Object:  ForeignKey [fk_asettings_aaccountmaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSettings]  WITH CHECK ADD  CONSTRAINT [fk_asettings_aaccountmaster1] FOREIGN KEY([TradeCreditorAcID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aSettings] CHECK CONSTRAINT [fk_asettings_aaccountmaster1]
GO
/****** Object:  ForeignKey [fk_asettings_aaccountmaster2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSettings]  WITH CHECK ADD  CONSTRAINT [fk_asettings_aaccountmaster2] FOREIGN KEY([ExchangeDiffAcID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aSettings] CHECK CONSTRAINT [fk_asettings_aaccountmaster2]
GO
/****** Object:  ForeignKey [fk_asettings_ACURRENCYMASTER]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSettings]  WITH CHECK ADD  CONSTRAINT [fk_asettings_ACURRENCYMASTER] FOREIGN KEY([CashGroupID], [CompanyID])
REFERENCES [dbo].[aCurrencyMaster] ([CurrencyID], [CompanyID])
GO
ALTER TABLE [dbo].[aSettings] CHECK CONSTRAINT [fk_asettings_ACURRENCYMASTER]
GO
/****** Object:  ForeignKey [fk_asettings_agroupmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSettings]  WITH CHECK ADD  CONSTRAINT [fk_asettings_agroupmaster] FOREIGN KEY([FixedAssetGroupID], [CompanyID])
REFERENCES [dbo].[aGroupMaster] ([GroupID], [CompanyID])
GO
ALTER TABLE [dbo].[aSettings] CHECK CONSTRAINT [fk_asettings_agroupmaster]
GO
/****** Object:  ForeignKey [fk_asettings_agroupmaster2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSettings]  WITH CHECK ADD  CONSTRAINT [fk_asettings_agroupmaster2] FOREIGN KEY([BankGroupID], [CompanyID])
REFERENCES [dbo].[aGroupMaster] ([GroupID], [CompanyID])
GO
ALTER TABLE [dbo].[aSettings] CHECK CONSTRAINT [fk_asettings_agroupmaster2]
GO
/****** Object:  ForeignKey [fk_asettings_agroupmaster3]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSettings]  WITH CHECK ADD  CONSTRAINT [fk_asettings_agroupmaster3] FOREIGN KEY([SalesGroupID], [CompanyID])
REFERENCES [dbo].[aGroupMaster] ([GroupID], [CompanyID])
GO
ALTER TABLE [dbo].[aSettings] CHECK CONSTRAINT [fk_asettings_agroupmaster3]
GO
/****** Object:  ForeignKey [fk_asettings_agroupmaster4]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aSettings]  WITH CHECK ADD  CONSTRAINT [fk_asettings_agroupmaster4] FOREIGN KEY([PurchaseGroupID], [CompanyID])
REFERENCES [dbo].[aGroupMaster] ([GroupID], [CompanyID])
GO
ALTER TABLE [dbo].[aSettings] CHECK CONSTRAINT [fk_asettings_agroupmaster4]
GO
/****** Object:  ForeignKey [fk_aaccountmaster_acurrencymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aAccountMaster]  WITH CHECK ADD  CONSTRAINT [fk_aaccountmaster_acurrencymaster] FOREIGN KEY([CurrencyID], [CompanyID])
REFERENCES [dbo].[aCurrencyMaster] ([CurrencyID], [CompanyID])
GO
ALTER TABLE [dbo].[aAccountMaster] CHECK CONSTRAINT [fk_aaccountmaster_acurrencymaster]
GO
/****** Object:  ForeignKey [fk_aaccountmaster_agroupmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aAccountMaster]  WITH CHECK ADD  CONSTRAINT [fk_aaccountmaster_agroupmaster] FOREIGN KEY([GroupID], [CompanyID])
REFERENCES [dbo].[aGroupMaster] ([GroupID], [CompanyID])
GO
ALTER TABLE [dbo].[aAccountMaster] CHECK CONSTRAINT [fk_aaccountmaster_agroupmaster]
GO
/****** Object:  ForeignKey [FK_LOsGoodsArrivaltoShopHeader_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsGoodsArrivaltoShopHeader_aGodown] FOREIGN KEY([gahDespatchedGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopHeader] CHECK CONSTRAINT [FK_LOsGoodsArrivaltoShopHeader_aGodown]
GO
/****** Object:  ForeignKey [fk_LOsGoodsArrivaltoShopHeader_aHQDespatchnoteHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopHeader]  WITH CHECK ADD  CONSTRAINT [fk_LOsGoodsArrivaltoShopHeader_aHQDespatchnoteHeader] FOREIGN KEY([gahhqdespatchid])
REFERENCES [dbo].[aHQDespatchnoteHeader] ([dhDespatchnoteID])
GO
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopHeader] CHECK CONSTRAINT [fk_LOsGoodsArrivaltoShopHeader_aHQDespatchnoteHeader]
GO
/****** Object:  ForeignKey [FK_LOsGoodsArrivaltoShopHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsGoodsArrivaltoShopHeader_aShops] FOREIGN KEY([gahShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopHeader] CHECK CONSTRAINT [FK_LOsGoodsArrivaltoShopHeader_aShops]
GO
/****** Object:  ForeignKey [FK_LOsGoodsArrivaltoShopHeader_MEiDespatchToShopHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsGoodsArrivaltoShopHeader_MEiDespatchToShopHeader] FOREIGN KEY([gahGodownDespatchID], [gahDespatchedGodownID])
REFERENCES [dbo].[MEiDespatchToShopHeader] ([dhDespatchID], [dhGodownID])
GO
ALTER TABLE [dbo].[LOsGoodsArrivaltoShopHeader] CHECK CONSTRAINT [FK_LOsGoodsArrivaltoShopHeader_MEiDespatchToShopHeader]
GO
/****** Object:  ForeignKey [fk_losApartmentCheckOut_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentCheckOut]  WITH CHECK ADD  CONSTRAINT [fk_losApartmentCheckOut_aAccountMaster] FOREIGN KEY([chCashAccId], [chCompanyId])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[losApartmentCheckOut] CHECK CONSTRAINT [fk_losApartmentCheckOut_aAccountMaster]
GO
/****** Object:  ForeignKey [fk_losApartmentCheckOut_aAccountMaster_chWriteOffAccID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentCheckOut]  WITH CHECK ADD  CONSTRAINT [fk_losApartmentCheckOut_aAccountMaster_chWriteOffAccID] FOREIGN KEY([chWriteOffAccID], [chCompanyId])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[losApartmentCheckOut] CHECK CONSTRAINT [fk_losApartmentCheckOut_aAccountMaster_chWriteOffAccID]
GO
/****** Object:  ForeignKey [fk_losApartmentCheckOut_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentCheckOut]  WITH CHECK ADD  CONSTRAINT [fk_losApartmentCheckOut_aDepartmentMaster] FOREIGN KEY([ChDepartmentID], [chCompanyId])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[losApartmentCheckOut] CHECK CONSTRAINT [fk_losApartmentCheckOut_aDepartmentMaster]
GO
/****** Object:  ForeignKey [fk_losApartmentCheckOut_ashops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentCheckOut]  WITH CHECK ADD  CONSTRAINT [fk_losApartmentCheckOut_ashops] FOREIGN KEY([chShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losApartmentCheckOut] CHECK CONSTRAINT [fk_losApartmentCheckOut_ashops]
GO
/****** Object:  ForeignKey [fk_losApartmentCheckOut_LOSApartmentAgreementHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentCheckOut]  WITH CHECK ADD  CONSTRAINT [fk_losApartmentCheckOut_LOSApartmentAgreementHeader] FOREIGN KEY([chCompanyId], [chShopID], [chAgreementID])
REFERENCES [dbo].[losApartmentAgreementHeader] ([mghCompanyId], [mghShopId], [mghAgreementid])
GO
ALTER TABLE [dbo].[losApartmentCheckOut] CHECK CONSTRAINT [fk_losApartmentCheckOut_LOSApartmentAgreementHeader]
GO
/****** Object:  ForeignKey [fk_losApartmentAgreementDetails_losApartmentAgreementHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentAgreementDetails]  WITH CHECK ADD  CONSTRAINT [fk_losApartmentAgreementDetails_losApartmentAgreementHeader] FOREIGN KEY([mgdcompanyid], [mgdshopid], [mgdAgreementId])
REFERENCES [dbo].[losApartmentAgreementHeader] ([mghCompanyId], [mghShopId], [mghAgreementid])
GO
ALTER TABLE [dbo].[losApartmentAgreementDetails] CHECK CONSTRAINT [fk_losApartmentAgreementDetails_losApartmentAgreementHeader]
GO
/****** Object:  ForeignKey [fk_losApartmentBillHeader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentBillHeader]  WITH CHECK ADD  CONSTRAINT [fk_losApartmentBillHeader_aAccountMaster] FOREIGN KEY([abhCashAccId], [abhCompanyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[losApartmentBillHeader] CHECK CONSTRAINT [fk_losApartmentBillHeader_aAccountMaster]
GO
/****** Object:  ForeignKey [fk_losApartmentBillHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentBillHeader]  WITH CHECK ADD  CONSTRAINT [fk_losApartmentBillHeader_aDepartmentMaster] FOREIGN KEY([abhDepartmentid], [abhCompanyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[losApartmentBillHeader] CHECK CONSTRAINT [fk_losApartmentBillHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [fk_losApartmentBillHeader_ashops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentBillHeader]  WITH CHECK ADD  CONSTRAINT [fk_losApartmentBillHeader_ashops] FOREIGN KEY([abhSHopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losApartmentBillHeader] CHECK CONSTRAINT [fk_losApartmentBillHeader_ashops]
GO
/****** Object:  ForeignKey [fk_losApartmentBillHeader_LOSApartmentAgreementHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentBillHeader]  WITH CHECK ADD  CONSTRAINT [fk_losApartmentBillHeader_LOSApartmentAgreementHeader] FOREIGN KEY([abhCompanyid], [abhSHopID], [abhAgreementId])
REFERENCES [dbo].[losApartmentAgreementHeader] ([mghCompanyId], [mghShopId], [mghAgreementid])
GO
ALTER TABLE [dbo].[losApartmentBillHeader] CHECK CONSTRAINT [fk_losApartmentBillHeader_LOSApartmentAgreementHeader]
GO
/****** Object:  ForeignKey [FK_LosDeliveryNoteHeader_aCustomerMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosDeliveryNoteHeader]  WITH CHECK ADD  CONSTRAINT [FK_LosDeliveryNoteHeader_aCustomerMaster] FOREIGN KEY([DnCustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[LosDeliveryNoteHeader] CHECK CONSTRAINT [FK_LosDeliveryNoteHeader_aCustomerMaster]
GO
/****** Object:  ForeignKey [fk_LosDeliverynoteHeader_ashops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosDeliveryNoteHeader]  WITH CHECK ADD  CONSTRAINT [fk_LosDeliverynoteHeader_ashops] FOREIGN KEY([DnShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LosDeliveryNoteHeader] CHECK CONSTRAINT [fk_LosDeliverynoteHeader_ashops]
GO
/****** Object:  ForeignKey [fk_LosDeliveryNoteHeader_aStatus]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosDeliveryNoteHeader]  WITH CHECK ADD  CONSTRAINT [fk_LosDeliveryNoteHeader_aStatus] FOREIGN KEY([dnCompanyId], [dnStatus])
REFERENCES [dbo].[aStatus] ([CompanyId], [StatusId])
GO
ALTER TABLE [dbo].[LosDeliveryNoteHeader] CHECK CONSTRAINT [fk_LosDeliveryNoteHeader_aStatus]
GO
/****** Object:  ForeignKey [FK_losDebitcreditNotedetail_losDebitcreditNote]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDebitCreditNoteDetail]  WITH CHECK ADD  CONSTRAINT [FK_losDebitcreditNotedetail_losDebitcreditNote] FOREIGN KEY([ShopID], [DCNID])
REFERENCES [dbo].[losDebitCreditNote] ([losDCNShopid], [losDCNId])
GO
ALTER TABLE [dbo].[losDebitCreditNoteDetail] CHECK CONSTRAINT [FK_losDebitcreditNotedetail_losDebitcreditNote]
GO
/****** Object:  ForeignKey [fk_LosDebitCreditNoteDetail_losLPHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDebitCreditNoteDetail]  WITH CHECK ADD  CONSTRAINT [fk_LosDebitCreditNoteDetail_losLPHeader] FOREIGN KEY([ShopID], [POID])
REFERENCES [dbo].[losLPHeader] ([ShopID], [POID])
GO
ALTER TABLE [dbo].[losDebitCreditNoteDetail] CHECK CONSTRAINT [fk_LosDebitCreditNoteDetail_losLPHeader]
GO
/****** Object:  ForeignKey [fk_losLPDetail_losLPHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losLPDetail]  WITH CHECK ADD  CONSTRAINT [fk_losLPDetail_losLPHeader] FOREIGN KEY([ShopID], [POID])
REFERENCES [dbo].[losLPHeader] ([ShopID], [POID])
GO
ALTER TABLE [dbo].[losLPDetail] CHECK CONSTRAINT [fk_losLPDetail_losLPHeader]
GO
/****** Object:  ForeignKey [fk_LosserToolsReturnHeader_LosserToolsAllocationHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosserToolsReturnHeader]  WITH CHECK ADD  CONSTRAINT [fk_LosserToolsReturnHeader_LosserToolsAllocationHeader] FOREIGN KEY([tlrethCompanyId], [tlrethShopid], [tlrethallocid])
REFERENCES [dbo].[losSerToolsAllocationHeader] ([alchCompanyId], [alchShopid], [alchid])
GO
ALTER TABLE [dbo].[LosserToolsReturnHeader] CHECK CONSTRAINT [fk_LosserToolsReturnHeader_LosserToolsAllocationHeader]
GO
/****** Object:  ForeignKey [Fk_aRepFormatAccounts_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aRepFormatAccounts]  WITH CHECK ADD  CONSTRAINT [Fk_aRepFormatAccounts_aAccountMaster] FOREIGN KEY([Accountid], [CompanyId])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aRepFormatAccounts] CHECK CONSTRAINT [Fk_aRepFormatAccounts_aAccountMaster]
GO
/****** Object:  ForeignKey [Fk_aRepFormatAccounts_aAccRepGroup]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aRepFormatAccounts]  WITH CHECK ADD  CONSTRAINT [Fk_aRepFormatAccounts_aAccRepGroup] FOREIGN KEY([CompanyId], [GroupId])
REFERENCES [dbo].[aaccrepgroup] ([companyid], [Groupid])
GO
ALTER TABLE [dbo].[aRepFormatAccounts] CHECK CONSTRAINT [Fk_aRepFormatAccounts_aAccRepGroup]
GO
/****** Object:  ForeignKey [FK_LeadTimeStage_LeadTimeDivision]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LeadTimeStage]  WITH CHECK ADD  CONSTRAINT [FK_LeadTimeStage_LeadTimeDivision] FOREIGN KEY([Lstagedivisionid])
REFERENCES [dbo].[LeadTimeDivision] ([Ldivisionid])
GO
ALTER TABLE [dbo].[LeadTimeStage] CHECK CONSTRAINT [FK_LeadTimeStage_LeadTimeDivision]
GO
/****** Object:  ForeignKey [FK_LOSINVSE_REF_1308_LOSSERVI]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losinvservicedetails]  WITH CHECK ADD  CONSTRAINT [FK_LOSINVSE_REF_1308_LOSSERVI] FOREIGN KEY([serinvdinvoiceid], [serinvdcompanyid], [serinvdshopid])
REFERENCES [dbo].[losServiceHeader] ([serinvhid], [serinvhcompanyid], [serinvhshopid])
GO
ALTER TABLE [dbo].[losinvservicedetails] CHECK CONSTRAINT [FK_LOSINVSE_REF_1308_LOSSERVI]
GO
/****** Object:  ForeignKey [FK_LOSINVSE_REF_2134_ASERVICE]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losinvservicedetails]  WITH CHECK ADD  CONSTRAINT [FK_LOSINVSE_REF_2134_ASERVICE] FOREIGN KEY([serinvdserviceid], [serinvdcompanyid])
REFERENCES [dbo].[aservicemaster] ([serid], [sercompanyid])
GO
ALTER TABLE [dbo].[losinvservicedetails] CHECK CONSTRAINT [FK_LOSINVSE_REF_2134_ASERVICE]
GO
/****** Object:  ForeignKey [FK_MeiGodownRequestDetail_MeiGodownRequestHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MeiGodownRequestDetail]  WITH CHECK ADD  CONSTRAINT [FK_MeiGodownRequestDetail_MeiGodownRequestHeader] FOREIGN KEY([GRDRequestId], [GRDGodownId])
REFERENCES [dbo].[MeiGodownRequestHeader] ([GRHRequestId], [GRHGodownId])
GO
ALTER TABLE [dbo].[MeiGodownRequestDetail] CHECK CONSTRAINT [FK_MeiGodownRequestDetail_MeiGodownRequestHeader]
GO
/****** Object:  ForeignKey [FK_ExchangeRateHistoryDetails]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ExchangeRateHistoryDetails]  WITH CHECK ADD  CONSTRAINT [FK_ExchangeRateHistoryDetails] FOREIGN KEY([ExchangeID], [CompanyID])
REFERENCES [dbo].[ExchangeRateHistoryHeader] ([ExchangeID], [CompanyID])
GO
ALTER TABLE [dbo].[ExchangeRateHistoryDetails] CHECK CONSTRAINT [FK_ExchangeRateHistoryDetails]
GO
/****** Object:  ForeignKey [FK_losWarrentyClaimDetail_losWarrentyClaimHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losWarrentyClaimDetail]  WITH CHECK ADD  CONSTRAINT [FK_losWarrentyClaimDetail_losWarrentyClaimHeader] FOREIGN KEY([wcdCompanyID], [wcdShopID], [wcdID])
REFERENCES [dbo].[losWarrentyClaimHeader] ([wchCompanyID], [wchShopID], [wchID])
GO
ALTER TABLE [dbo].[losWarrentyClaimDetail] CHECK CONSTRAINT [FK_losWarrentyClaimDetail_losWarrentyClaimHeader]
GO
/****** Object:  ForeignKey [FK_losFacilityBookingDetail_aservicemaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losFacilityBookingDetail]  WITH CHECK ADD  CONSTRAINT [FK_losFacilityBookingDetail_aservicemaster] FOREIGN KEY([ftFaclityID], [ftCompanyId])
REFERENCES [dbo].[aservicemaster] ([serid], [sercompanyid])
GO
ALTER TABLE [dbo].[losFacilityBookingDetail] CHECK CONSTRAINT [FK_losFacilityBookingDetail_aservicemaster]
GO
/****** Object:  ForeignKey [fk_aShopServiceCharges_aServiceMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopServiceCharges]  WITH CHECK ADD  CONSTRAINT [fk_aShopServiceCharges_aServiceMaster] FOREIGN KEY([serid], [sercompanyid])
REFERENCES [dbo].[aservicemaster] ([serid], [sercompanyid])
GO
ALTER TABLE [dbo].[aShopServiceCharges] CHECK CONSTRAINT [fk_aShopServiceCharges_aServiceMaster]
GO
/****** Object:  ForeignKey [fk_aShopServiceCharges_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopServiceCharges]  WITH CHECK ADD  CONSTRAINT [fk_aShopServiceCharges_aShops] FOREIGN KEY([serShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[aShopServiceCharges] CHECK CONSTRAINT [fk_aShopServiceCharges_aShops]
GO
/****** Object:  ForeignKey [fk_LosPackingListDetail_LosPackingListHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosPackingListDetail]  WITH CHECK ADD  CONSTRAINT [fk_LosPackingListDetail_LosPackingListHeader] FOREIGN KEY([PldShopId], [PldId])
REFERENCES [dbo].[LosPackingListHeader] ([plhShopId], [plhPackListId])
GO
ALTER TABLE [dbo].[LosPackingListDetail] CHECK CONSTRAINT [fk_LosPackingListDetail_LosPackingListHeader]
GO
/****** Object:  ForeignKey [FK_LOSFUTUR_REF_6391_LOSFUTUR]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losfuturetabdetail]  WITH CHECK ADD  CONSTRAINT [FK_LOSFUTUR_REF_6391_LOSFUTUR] FOREIGN KEY([futdid], [futdcompanyid], [futdshopid])
REFERENCES [dbo].[losfuturetabheader] ([futheadid], [futhcompanyid], [futhshopid])
GO
ALTER TABLE [dbo].[losfuturetabdetail] CHECK CONSTRAINT [FK_LOSFUTUR_REF_6391_LOSFUTUR]
GO
/****** Object:  ForeignKey [FK_losfuturetabdetail_losfuturetabheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losfuturetabdetail]  WITH CHECK ADD  CONSTRAINT [FK_losfuturetabdetail_losfuturetabheader] FOREIGN KEY([futdid], [futdcompanyid], [futdshopid])
REFERENCES [dbo].[losfuturetabheader] ([futheadid], [futhcompanyid], [futhshopid])
GO
ALTER TABLE [dbo].[losfuturetabdetail] CHECK CONSTRAINT [FK_losfuturetabdetail_losfuturetabheader]
GO
/****** Object:  ForeignKey [fk_losApartmentAgreementHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentAgreementHeader]  WITH CHECK ADD  CONSTRAINT [fk_losApartmentAgreementHeader_aDepartmentMaster] FOREIGN KEY([mghDepartmentid], [mghCompanyId])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[losApartmentAgreementHeader] CHECK CONSTRAINT [fk_losApartmentAgreementHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [fk_losApartmentAgreementHeader_ashops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentAgreementHeader]  WITH CHECK ADD  CONSTRAINT [fk_losApartmentAgreementHeader_ashops] FOREIGN KEY([mghShopId])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losApartmentAgreementHeader] CHECK CONSTRAINT [fk_losApartmentAgreementHeader_ashops]
GO
/****** Object:  ForeignKey [fk_losApartmentAgreementHeader_losReservationHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losApartmentAgreementHeader]  WITH CHECK ADD  CONSTRAINT [fk_losApartmentAgreementHeader_losReservationHeader] FOREIGN KEY([mghCompanyId], [mghShopId], [mghReservationID])
REFERENCES [dbo].[LosReservationHeader] ([rhcompanyid], [rhshopid], [rhreservationid])
GO
ALTER TABLE [dbo].[losApartmentAgreementHeader] CHECK CONSTRAINT [fk_losApartmentAgreementHeader_losReservationHeader]
GO
/****** Object:  ForeignKey [FK_CrmOpportunity_CrmLeadMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CrmOpportunity]  WITH CHECK ADD  CONSTRAINT [FK_CrmOpportunity_CrmLeadMaster] FOREIGN KEY([LeadTypeId])
REFERENCES [dbo].[CrmLeadMaster] ([LeadId])
GO
ALTER TABLE [dbo].[CrmOpportunity] CHECK CONSTRAINT [FK_CrmOpportunity_CrmLeadMaster]
GO
/****** Object:  ForeignKey [FK_CrmLeads_CrmLeadMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CrmLeads]  WITH CHECK ADD  CONSTRAINT [FK_CrmLeads_CrmLeadMaster] FOREIGN KEY([LeadTypeId])
REFERENCES [dbo].[CrmLeadMaster] ([LeadId])
GO
ALTER TABLE [dbo].[CrmLeads] CHECK CONSTRAINT [FK_CrmLeads_CrmLeadMaster]
GO
/****** Object:  ForeignKey [FK_loreplacereqtovendorheader_aVendorMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loreplacereqtovendorheader]  WITH CHECK ADD  CONSTRAINT [FK_loreplacereqtovendorheader_aVendorMaster] FOREIGN KEY([rrvvendorid])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[loreplacereqtovendorheader] CHECK CONSTRAINT [FK_loreplacereqtovendorheader_aVendorMaster]
GO
/****** Object:  ForeignKey [FK_loreplacereqtovendorheader_losreplacerequestheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loreplacereqtovendorheader]  WITH CHECK ADD  CONSTRAINT [FK_loreplacereqtovendorheader_losreplacerequestheader] FOREIGN KEY([rrvrepreqid], [rrvcompanyid], [rrvshopid])
REFERENCES [dbo].[losreplacerequestheader] ([repreqhid], [repreqhcompanyid], [repreqshopid])
GO
ALTER TABLE [dbo].[loreplacereqtovendorheader] CHECK CONSTRAINT [FK_loreplacereqtovendorheader_losreplacerequestheader]
GO
/****** Object:  ForeignKey [fk_denominationdetail_denominationHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[denominationdetail]  WITH CHECK ADD  CONSTRAINT [fk_denominationdetail_denominationHeader] FOREIGN KEY([dshopid], [ddenominationid])
REFERENCES [dbo].[denominationheader] ([shopid], [denominationid])
GO
ALTER TABLE [dbo].[denominationdetail] CHECK CONSTRAINT [fk_denominationdetail_denominationHeader]
GO
/****** Object:  ForeignKey [Fk_DenominationChequeDetails_DenominationHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DenominationChequeDetails]  WITH CHECK ADD  CONSTRAINT [Fk_DenominationChequeDetails_DenominationHeader] FOREIGN KEY([dcdShopId], [dcdDenomId])
REFERENCES [dbo].[denominationheader] ([shopid], [denominationid])
GO
ALTER TABLE [dbo].[DenominationChequeDetails] CHECK CONSTRAINT [Fk_DenominationChequeDetails_DenominationHeader]
GO
/****** Object:  ForeignKey [FK_LOsWriteOffHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsWriteOffHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsWriteOffHeader_aShops] FOREIGN KEY([whShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LOsWriteOffHeader] CHECK CONSTRAINT [FK_LOsWriteOffHeader_aShops]
GO
/****** Object:  ForeignKey [FK_LOsWriteOffHeader_whIhCRequestID]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsWriteOffHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsWriteOffHeader_whIhCRequestID] FOREIGN KEY([whIhCRequestID])
REFERENCES [dbo].[InhouseConsumptionReqHeader] ([StoreRequestId])
GO
ALTER TABLE [dbo].[LOsWriteOffHeader] CHECK CONSTRAINT [FK_LOsWriteOffHeader_whIhCRequestID]
GO
/****** Object:  ForeignKey [FK_aHQPaymentVoucherDebitDetails_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherDebitDetails]  WITH CHECK ADD  CONSTRAINT [FK_aHQPaymentVoucherDebitDetails_aAccountMaster] FOREIGN KEY([pddAccountID], [pddCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherDebitDetails] CHECK CONSTRAINT [FK_aHQPaymentVoucherDebitDetails_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_aHQPaymentVoucherDebitDetails_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherDebitDetails]  WITH CHECK ADD  CONSTRAINT [FK_aHQPaymentVoucherDebitDetails_aCompanyMaster] FOREIGN KEY([pddCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherDebitDetails] CHECK CONSTRAINT [FK_aHQPaymentVoucherDebitDetails_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_aHQPaymentVoucherDebitDetails_aHQPaymentVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherDebitDetails]  WITH CHECK ADD  CONSTRAINT [FK_aHQPaymentVoucherDebitDetails_aHQPaymentVoucherHeader] FOREIGN KEY([pddPaymentID])
REFERENCES [dbo].[aHQPaymentVoucherHeader] ([phPaymentID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherDebitDetails] CHECK CONSTRAINT [FK_aHQPaymentVoucherDebitDetails_aHQPaymentVoucherHeader]
GO
/****** Object:  ForeignKey [fk_aHQPaymentVoucherdebitDetails_lopurchaseorderheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherDebitDetails]  WITH NOCHECK ADD  CONSTRAINT [fk_aHQPaymentVoucherdebitDetails_lopurchaseorderheader] FOREIGN KEY([pddhqpoid])
REFERENCES [dbo].[loPurchaseOrderHeader] ([pohPoid])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherDebitDetails] CHECK CONSTRAINT [fk_aHQPaymentVoucherdebitDetails_lopurchaseorderheader]
GO
/****** Object:  ForeignKey [FK_loPurchaseOrderOC_loPurchaseOrderHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPurchaseOrderOC]  WITH NOCHECK ADD  CONSTRAINT [FK_loPurchaseOrderOC_loPurchaseOrderHeader] FOREIGN KEY([podOthPoId])
REFERENCES [dbo].[loPurchaseOrderHeader] ([pohPoid])
GO
ALTER TABLE [dbo].[loPurchaseOrderOC] CHECK CONSTRAINT [FK_loPurchaseOrderOC_loPurchaseOrderHeader]
GO
/****** Object:  ForeignKey [FK_LtimeDetail_LtimeHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LtimeDetail]  WITH CHECK ADD  CONSTRAINT [FK_LtimeDetail_LtimeHeader] FOREIGN KEY([Ltimeid])
REFERENCES [dbo].[LtimeHeader] ([LtimeID])
GO
ALTER TABLE [dbo].[LtimeDetail] CHECK CONSTRAINT [FK_LtimeDetail_LtimeHeader]
GO
/****** Object:  ForeignKey [FK_AAccRatioEntitiesAccounts_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AAccRatioEntitiesAccounts]  WITH CHECK ADD  CONSTRAINT [FK_AAccRatioEntitiesAccounts_aAccountMaster] FOREIGN KEY([AccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[AAccRatioEntitiesAccounts] CHECK CONSTRAINT [FK_AAccRatioEntitiesAccounts_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_AAccRatioEntitiesAccounts_AAccRatioEntitiesMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AAccRatioEntitiesAccounts]  WITH CHECK ADD  CONSTRAINT [FK_AAccRatioEntitiesAccounts_AAccRatioEntitiesMaster] FOREIGN KEY([CompanyID], [EntityID])
REFERENCES [dbo].[AAccRatioEntitiesMaster] ([CompanyID], [EntityId])
GO
ALTER TABLE [dbo].[AAccRatioEntitiesAccounts] CHECK CONSTRAINT [FK_AAccRatioEntitiesAccounts_AAccRatioEntitiesMaster]
GO
/****** Object:  ForeignKey [FK_mesTransferOutHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferOutHeader]  WITH CHECK ADD  CONSTRAINT [FK_mesTransferOutHeader_aShops] FOREIGN KEY([TOHShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[mesTransferOutHeader] CHECK CONSTRAINT [FK_mesTransferOutHeader_aShops]
GO
/****** Object:  ForeignKey [FK_mesTransferOutHeader_aShops1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferOutHeader]  WITH CHECK ADD  CONSTRAINT [FK_mesTransferOutHeader_aShops1] FOREIGN KEY([TOHtoShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[mesTransferOutHeader] CHECK CONSTRAINT [FK_mesTransferOutHeader_aShops1]
GO
/****** Object:  ForeignKey [FK_mesTransferOutHeader_mesRequesttoShopHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mesTransferOutHeader]  WITH CHECK ADD  CONSTRAINT [FK_mesTransferOutHeader_mesRequesttoShopHeader] FOREIGN KEY([TOHtoShopid], [TOHrequestid])
REFERENCES [dbo].[mesRequesttoShopHeader] ([SRHshopid], [SRHrequestID])
GO
ALTER TABLE [dbo].[mesTransferOutHeader] CHECK CONSTRAINT [FK_mesTransferOutHeader_mesRequesttoShopHeader]
GO
/****** Object:  ForeignKey [FK_VoucherMaster_VoucherMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[VoucherMaster]  WITH CHECK ADD  CONSTRAINT [FK_VoucherMaster_VoucherMaster] FOREIGN KEY([VoucherCurrencyID], [VoucherCompanyID])
REFERENCES [dbo].[aCurrencyMaster] ([CurrencyID], [CompanyID])
GO
ALTER TABLE [dbo].[VoucherMaster] CHECK CONSTRAINT [FK_VoucherMaster_VoucherMaster]
GO
/****** Object:  ForeignKey [fk_ClearenceRequestHeader_aCurrencyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ClearenceRequestHeader]  WITH CHECK ADD  CONSTRAINT [fk_ClearenceRequestHeader_aCurrencyMaster] FOREIGN KEY([POCurrencyID], [CompanyID])
REFERENCES [dbo].[aCurrencyMaster] ([CurrencyID], [CompanyID])
GO
ALTER TABLE [dbo].[ClearenceRequestHeader] CHECK CONSTRAINT [fk_ClearenceRequestHeader_aCurrencyMaster]
GO
/****** Object:  ForeignKey [fk_ClearenceRequestHeader_aCustomerMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ClearenceRequestHeader]  WITH CHECK ADD  CONSTRAINT [fk_ClearenceRequestHeader_aCustomerMaster] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[ClearenceRequestHeader] CHECK CONSTRAINT [fk_ClearenceRequestHeader_aCustomerMaster]
GO
/****** Object:  ForeignKey [FK_aDepartmentMaster_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aDepartmentMaster]  WITH CHECK ADD  CONSTRAINT [FK_aDepartmentMaster_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aDepartmentMaster] CHECK CONSTRAINT [FK_aDepartmentMaster_aCompanyMaster]
GO
/****** Object:  ForeignKey [fk_adepartmentmaster_acurrencymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aDepartmentMaster]  WITH CHECK ADD  CONSTRAINT [fk_adepartmentmaster_acurrencymaster] FOREIGN KEY([depcurrencyid], [CompanyID])
REFERENCES [dbo].[aCurrencyMaster] ([CurrencyID], [CompanyID])
GO
ALTER TABLE [dbo].[aDepartmentMaster] CHECK CONSTRAINT [fk_adepartmentmaster_acurrencymaster]
GO
/****** Object:  ForeignKey [fk_department_Dep]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aDepartmentMaster]  WITH CHECK ADD  CONSTRAINT [fk_department_Dep] FOREIGN KEY([ParentDepId], [CompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[aDepartmentMaster] CHECK CONSTRAINT [fk_department_Dep]
GO
/****** Object:  ForeignKey [FK_aHQIssueNoteMain_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssueNoteMain]  WITH CHECK ADD  CONSTRAINT [FK_aHQIssueNoteMain_aDepartmentMaster] FOREIGN KEY([departmentid], [companyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[aHQIssueNoteMain] CHECK CONSTRAINT [FK_aHQIssueNoteMain_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_aHQIssueNoteMain_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssueNoteMain]  WITH CHECK ADD  CONSTRAINT [FK_aHQIssueNoteMain_aShops] FOREIGN KEY([INMShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[aHQIssueNoteMain] CHECK CONSTRAINT [FK_aHQIssueNoteMain_aShops]
GO
/****** Object:  ForeignKey [fk_aHQIssueNoteMain_mosgoodsrequestheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssueNoteMain]  WITH CHECK ADD  CONSTRAINT [fk_aHQIssueNoteMain_mosgoodsrequestheader] FOREIGN KEY([INMRequestID], [INMShopID])
REFERENCES [dbo].[mosGoodsRequestHeader] ([GRHrequestID], [GRHshopID])
GO
ALTER TABLE [dbo].[aHQIssueNoteMain] CHECK CONSTRAINT [fk_aHQIssueNoteMain_mosgoodsrequestheader]
GO
/****** Object:  ForeignKey [fk_mosrequestinvdetail_mosgoodsrequestheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mosrequestinvdetail]  WITH CHECK ADD  CONSTRAINT [fk_mosrequestinvdetail_mosgoodsrequestheader] FOREIGN KEY([reqdid], [reqinvdshopid])
REFERENCES [dbo].[mosGoodsRequestHeader] ([GRHrequestID], [GRHshopID])
GO
ALTER TABLE [dbo].[mosrequestinvdetail] CHECK CONSTRAINT [fk_mosrequestinvdetail_mosgoodsrequestheader]
GO
/****** Object:  ForeignKey [FK_aHQIssuenoteHeader_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteHeader]  WITH CHECK ADD  CONSTRAINT [FK_aHQIssuenoteHeader_aGodown] FOREIGN KEY([INHGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[aHQIssuenoteHeader] CHECK CONSTRAINT [FK_aHQIssuenoteHeader_aGodown]
GO
/****** Object:  ForeignKey [FK_aHQIssuenoteHeader_aGodown1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteHeader]  WITH CHECK ADD  CONSTRAINT [FK_aHQIssuenoteHeader_aGodown1] FOREIGN KEY([INHTogodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[aHQIssuenoteHeader] CHECK CONSTRAINT [FK_aHQIssuenoteHeader_aGodown1]
GO
/****** Object:  ForeignKey [FK_aHQIssuenoteHeader_aHQIssueNoteMain]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteHeader]  WITH CHECK ADD  CONSTRAINT [FK_aHQIssuenoteHeader_aHQIssueNoteMain] FOREIGN KEY([INHIssuenotemainID])
REFERENCES [dbo].[aHQIssueNoteMain] ([INMIssuenoteID])
GO
ALTER TABLE [dbo].[aHQIssuenoteHeader] CHECK CONSTRAINT [FK_aHQIssuenoteHeader_aHQIssueNoteMain]
GO
/****** Object:  ForeignKey [FK_aHQIssuenoteHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteHeader]  WITH CHECK ADD  CONSTRAINT [FK_aHQIssuenoteHeader_aShops] FOREIGN KEY([INHToshopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[aHQIssuenoteHeader] CHECK CONSTRAINT [FK_aHQIssuenoteHeader_aShops]
GO
/****** Object:  ForeignKey [fk_aHQIssuenoteHeader_mosgoodsrequestheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQIssuenoteHeader]  WITH CHECK ADD  CONSTRAINT [fk_aHQIssuenoteHeader_mosgoodsrequestheader] FOREIGN KEY([INHShopReqId], [INHToshopID])
REFERENCES [dbo].[mosGoodsRequestHeader] ([GRHrequestID], [GRHshopID])
GO
ALTER TABLE [dbo].[aHQIssuenoteHeader] CHECK CONSTRAINT [fk_aHQIssuenoteHeader_mosgoodsrequestheader]
GO
/****** Object:  ForeignKey [fk_ashoptoolsdetails_ashops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopToolsDetails]  WITH CHECK ADD  CONSTRAINT [fk_ashoptoolsdetails_ashops] FOREIGN KEY([shopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[aShopToolsDetails] CHECK CONSTRAINT [fk_ashoptoolsdetails_ashops]
GO
/****** Object:  ForeignKey [fk_ashoptoolsdetails_fixedasset]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopToolsDetails]  WITH CHECK ADD  CONSTRAINT [fk_ashoptoolsdetails_fixedasset] FOREIGN KEY([toolsastid], [companyid])
REFERENCES [dbo].[FixedAsset] ([FixedAssetID], [CompanyID])
GO
ALTER TABLE [dbo].[aShopToolsDetails] CHECK CONSTRAINT [fk_ashoptoolsdetails_fixedasset]
GO
/****** Object:  ForeignKey [fk_assetexpensetrackingdetail_acompanymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[assetexpensetrackingdetail]  WITH CHECK ADD  CONSTRAINT [fk_assetexpensetrackingdetail_acompanymaster] FOREIGN KEY([aexcompanyid])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[assetexpensetrackingdetail] CHECK CONSTRAINT [fk_assetexpensetrackingdetail_acompanymaster]
GO
/****** Object:  ForeignKey [fk_assetexpensetrackingdetail_FixedAsset]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[assetexpensetrackingdetail]  WITH CHECK ADD  CONSTRAINT [fk_assetexpensetrackingdetail_FixedAsset] FOREIGN KEY([aexassetid], [aexcompanyid])
REFERENCES [dbo].[FixedAsset] ([FixedAssetID], [CompanyID])
GO
ALTER TABLE [dbo].[assetexpensetrackingdetail] CHECK CONSTRAINT [fk_assetexpensetrackingdetail_FixedAsset]
GO
/****** Object:  ForeignKey [fk_depreciationdetail_depreciationheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DepreciationDetail]  WITH NOCHECK ADD  CONSTRAINT [fk_depreciationdetail_depreciationheader] FOREIGN KEY([DepreciationID], [CompanyID])
REFERENCES [dbo].[DepreciationHeader] ([DepreciationID], [CompanyID])
GO
ALTER TABLE [dbo].[DepreciationDetail] CHECK CONSTRAINT [fk_depreciationdetail_depreciationheader]
GO
/****** Object:  ForeignKey [fk_depreciationdetail_fixedasset]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DepreciationDetail]  WITH CHECK ADD  CONSTRAINT [fk_depreciationdetail_fixedasset] FOREIGN KEY([FixedAssetID], [CompanyID])
REFERENCES [dbo].[FixedAsset] ([FixedAssetID], [CompanyID])
GO
ALTER TABLE [dbo].[DepreciationDetail] CHECK CONSTRAINT [fk_depreciationdetail_fixedasset]
GO
/****** Object:  ForeignKey [fk_AssetDisposalDetail_FixedAsset]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[assetdisposaldetail]  WITH CHECK ADD  CONSTRAINT [fk_AssetDisposalDetail_FixedAsset] FOREIGN KEY([dispdasstid], [dispdcompanyid])
REFERENCES [dbo].[FixedAsset] ([FixedAssetID], [CompanyID])
GO
ALTER TABLE [dbo].[assetdisposaldetail] CHECK CONSTRAINT [fk_AssetDisposalDetail_FixedAsset]
GO
/****** Object:  ForeignKey [FK_MOaJournalDetails_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOaJournalDetails]  WITH CHECK ADD  CONSTRAINT [FK_MOaJournalDetails_aAccountMaster] FOREIGN KEY([AccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[MOaJournalDetails] CHECK CONSTRAINT [FK_MOaJournalDetails_aAccountMaster]
GO
/****** Object:  ForeignKey [fk_MOaJournalDetails_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOaJournalDetails]  WITH CHECK ADD  CONSTRAINT [fk_MOaJournalDetails_acustomermaster] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[MOaJournalDetails] CHECK CONSTRAINT [fk_MOaJournalDetails_acustomermaster]
GO
/****** Object:  ForeignKey [fk_moajournaldetails_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOaJournalDetails]  WITH CHECK ADD  CONSTRAINT [fk_moajournaldetails_adepartmentmaster] FOREIGN KEY([DepartmentID], [CompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[MOaJournalDetails] CHECK CONSTRAINT [fk_moajournaldetails_adepartmentmaster]
GO
/****** Object:  ForeignKey [fk_MOaJournalDetails_avendormaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOaJournalDetails]  WITH CHECK ADD  CONSTRAINT [fk_MOaJournalDetails_avendormaster] FOREIGN KEY([VendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[MOaJournalDetails] CHECK CONSTRAINT [fk_MOaJournalDetails_avendormaster]
GO
/****** Object:  ForeignKey [FK_MOaJournalDetails_MOaJournalHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MOaJournalDetails]  WITH CHECK ADD  CONSTRAINT [FK_MOaJournalDetails_MOaJournalHeader] FOREIGN KEY([JournalID])
REFERENCES [dbo].[MOaJournalHeader] ([JournalID])
GO
ALTER TABLE [dbo].[MOaJournalDetails] CHECK CONSTRAINT [FK_MOaJournalDetails_MOaJournalHeader]
GO
/****** Object:  ForeignKey [FK_FlightOperatorMaster_aCustomerMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FlightOperatorMaster]  WITH CHECK ADD  CONSTRAINT [FK_FlightOperatorMaster_aCustomerMaster] FOREIGN KEY([FlghtOpid])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[FlightOperatorMaster] CHECK CONSTRAINT [FK_FlightOperatorMaster_aCustomerMaster]
GO
/****** Object:  ForeignKey [FK_FlightOperatorMaster_DishSegmentHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FlightOperatorMaster]  WITH CHECK ADD  CONSTRAINT [FK_FlightOperatorMaster_DishSegmentHeader] FOREIGN KEY([FlghtSegID], [companyid])
REFERENCES [dbo].[DishSegmentHeader] ([seg_header_id], [seg_header_companyID])
GO
ALTER TABLE [dbo].[FlightOperatorMaster] CHECK CONSTRAINT [FK_FlightOperatorMaster_DishSegmentHeader]
GO
/****** Object:  ForeignKey [FK_seg_detail_Theader_id_seg_detail_Tcompanyid]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[TempDishSegmentDetail]  WITH CHECK ADD  CONSTRAINT [FK_seg_detail_Theader_id_seg_detail_Tcompanyid] FOREIGN KEY([seg_detail_Theader_id], [seg_detail_Tcompanyid])
REFERENCES [dbo].[DishSegmentHeader] ([seg_header_id], [seg_header_companyID])
GO
ALTER TABLE [dbo].[TempDishSegmentDetail] CHECK CONSTRAINT [FK_seg_detail_Theader_id_seg_detail_Tcompanyid]
GO
/****** Object:  ForeignKey [FK_DishSegmentDetail_DishSegmentHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DishSegmentDetail]  WITH CHECK ADD  CONSTRAINT [FK_DishSegmentDetail_DishSegmentHeader] FOREIGN KEY([seg_detail_header_id], [seg_detail_companyid])
REFERENCES [dbo].[DishSegmentHeader] ([seg_header_id], [seg_header_companyID])
GO
ALTER TABLE [dbo].[DishSegmentDetail] CHECK CONSTRAINT [FK_DishSegmentDetail_DishSegmentHeader]
GO
/****** Object:  ForeignKey [FK_seg_detail_header_id_seg_detail_companyid]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[DishSegmentDetail]  WITH CHECK ADD  CONSTRAINT [FK_seg_detail_header_id_seg_detail_companyid] FOREIGN KEY([seg_detail_header_id], [seg_detail_companyid])
REFERENCES [dbo].[DishSegmentHeader] ([seg_header_id], [seg_header_companyID])
GO
ALTER TABLE [dbo].[DishSegmentDetail] CHECK CONSTRAINT [FK_seg_detail_header_id_seg_detail_companyid]
GO
/****** Object:  ForeignKey [FK_ashopcashaccountdetails_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ashopcashaccountdetails]  WITH CHECK ADD  CONSTRAINT [FK_ashopcashaccountdetails_aAccountMaster] FOREIGN KEY([CashAccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[ashopcashaccountdetails] CHECK CONSTRAINT [FK_ashopcashaccountdetails_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_ashopcashaccountdetails_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ashopcashaccountdetails]  WITH CHECK ADD  CONSTRAINT [FK_ashopcashaccountdetails_aShops] FOREIGN KEY([shopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[ashopcashaccountdetails] CHECK CONSTRAINT [FK_ashopcashaccountdetails_aShops]
GO
/****** Object:  ForeignKey [FK_LOspPurchaseBillOC_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillOC]  WITH CHECK ADD  CONSTRAINT [FK_LOspPurchaseBillOC_aAccountMaster] FOREIGN KEY([pboAccID], [pboCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOspPurchaseBillOC] CHECK CONSTRAINT [FK_LOspPurchaseBillOC_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_LOspPurchaseBillOC_LOspPurchaseBillHeader1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOspPurchaseBillOC]  WITH CHECK ADD  CONSTRAINT [FK_LOspPurchaseBillOC_LOspPurchaseBillHeader1] FOREIGN KEY([pboBillID])
REFERENCES [dbo].[LOspPurchaseBillHeader] ([pbhBillID])
GO
ALTER TABLE [dbo].[LOspPurchaseBillOC] CHECK CONSTRAINT [FK_LOspPurchaseBillOC_LOspPurchaseBillHeader1]
GO
/****** Object:  ForeignKey [FK_loalocalpurchaseCostingheader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loalocalpurchaseCostingheader]  WITH CHECK ADD  CONSTRAINT [FK_loalocalpurchaseCostingheader_aAccountMaster] FOREIGN KEY([lpchGoodsinTransitaccid], [lpchCompanyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[loalocalpurchaseCostingheader] CHECK CONSTRAINT [FK_loalocalpurchaseCostingheader_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_loalocalpurchaseCostingheader_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loalocalpurchaseCostingheader]  WITH CHECK ADD  CONSTRAINT [FK_loalocalpurchaseCostingheader_aAccountMaster1] FOREIGN KEY([lpchInventoryaccid], [lpchCompanyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[loalocalpurchaseCostingheader] CHECK CONSTRAINT [FK_loalocalpurchaseCostingheader_aAccountMaster1]
GO
/****** Object:  ForeignKey [FK_loalocalpurchaseCostingheader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loalocalpurchaseCostingheader]  WITH CHECK ADD  CONSTRAINT [FK_loalocalpurchaseCostingheader_aDepartmentMaster] FOREIGN KEY([lpchDepartmentid], [lpchCompanyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[loalocalpurchaseCostingheader] CHECK CONSTRAINT [FK_loalocalpurchaseCostingheader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_loalocalpurchaseCostingheader_LosLocalPurchaseHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loalocalpurchaseCostingheader]  WITH CHECK ADD  CONSTRAINT [FK_loalocalpurchaseCostingheader_LosLocalPurchaseHeader] FOREIGN KEY([lpchShopid], [lpchBillid])
REFERENCES [dbo].[LosLocalPurchaseHeader] ([lphShopID], [lphBillID])
GO
ALTER TABLE [dbo].[loalocalpurchaseCostingheader] CHECK CONSTRAINT [FK_loalocalpurchaseCostingheader_LosLocalPurchaseHeader]
GO
/****** Object:  ForeignKey [FK_LOsReceiptVoucherHeader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsReceiptVoucherHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsReceiptVoucherHeader_aAccountMaster] FOREIGN KEY([rhBankCashAccountID], [rhCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsReceiptVoucherHeader] CHECK CONSTRAINT [FK_LOsReceiptVoucherHeader_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_LOsReceiptVoucherHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsReceiptVoucherHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsReceiptVoucherHeader_aCompanyMaster] FOREIGN KEY([rhCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[LOsReceiptVoucherHeader] CHECK CONSTRAINT [FK_LOsReceiptVoucherHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_LOsReceiptVoucherHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsReceiptVoucherHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsReceiptVoucherHeader_aShops] FOREIGN KEY([rhShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LOsReceiptVoucherHeader] CHECK CONSTRAINT [FK_LOsReceiptVoucherHeader_aShops]
GO
/****** Object:  ForeignKey [FK_LOsPosOthercharges_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosOthercharges]  WITH CHECK ADD  CONSTRAINT [FK_LOsPosOthercharges_aAccountMaster] FOREIGN KEY([posoAccID], [posoCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsPosOthercharges] CHECK CONSTRAINT [FK_LOsPosOthercharges_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_LOsPosOthercharges_LOsPosHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosOthercharges]  WITH CHECK ADD  CONSTRAINT [FK_LOsPosOthercharges_LOsPosHeader] FOREIGN KEY([posoShopID], [posoBillID])
REFERENCES [dbo].[LOsPosHeader] ([poshShopID], [poshBillID])
GO
ALTER TABLE [dbo].[LOsPosOthercharges] CHECK CONSTRAINT [FK_LOsPosOthercharges_LOsPosHeader]
GO
/****** Object:  ForeignKey [FK_LOsLocalPurchaseOC_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsLocalPurchaseOC]  WITH CHECK ADD  CONSTRAINT [FK_LOsLocalPurchaseOC_aAccountMaster] FOREIGN KEY([lpoAccID], [lpoCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOsLocalPurchaseOC] CHECK CONSTRAINT [FK_LOsLocalPurchaseOC_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_LOsLocalPurchaseOC_LosLocalPurchaseHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsLocalPurchaseOC]  WITH CHECK ADD  CONSTRAINT [FK_LOsLocalPurchaseOC_LosLocalPurchaseHeader] FOREIGN KEY([lpoShopID], [lpoBillID])
REFERENCES [dbo].[LosLocalPurchaseHeader] ([lphShopID], [lphBillID])
GO
ALTER TABLE [dbo].[LOsLocalPurchaseOC] CHECK CONSTRAINT [FK_LOsLocalPurchaseOC_LosLocalPurchaseHeader]
GO
/****** Object:  ForeignKey [fk_InterDivisionBillsDetails_accountmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[InterDivisionBillsDetails]  WITH CHECK ADD  CONSTRAINT [fk_InterDivisionBillsDetails_accountmaster] FOREIGN KEY([AccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[InterDivisionBillsDetails] CHECK CONSTRAINT [fk_InterDivisionBillsDetails_accountmaster]
GO
/****** Object:  ForeignKey [FK_InterDivisionBillsDetails_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[InterDivisionBillsDetails]  WITH CHECK ADD  CONSTRAINT [FK_InterDivisionBillsDetails_aDepartmentMaster] FOREIGN KEY([DepartmentId], [CompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[InterDivisionBillsDetails] CHECK CONSTRAINT [FK_InterDivisionBillsDetails_aDepartmentMaster]
GO
/****** Object:  ForeignKey [fk_InterDivisionBillsDetails_InterDivisionBillsHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[InterDivisionBillsDetails]  WITH NOCHECK ADD  CONSTRAINT [fk_InterDivisionBillsDetails_InterDivisionBillsHeader] FOREIGN KEY([BillsID])
REFERENCES [dbo].[InterDivisionBillsHeader] ([BillsID])
GO
ALTER TABLE [dbo].[InterDivisionBillsDetails] CHECK CONSTRAINT [fk_InterDivisionBillsDetails_InterDivisionBillsHeader]
GO
/****** Object:  ForeignKey [FK_JournalTransDetails_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[JournalTransDetails]  WITH CHECK ADD  CONSTRAINT [FK_JournalTransDetails_aAccountMaster] FOREIGN KEY([AccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[JournalTransDetails] CHECK CONSTRAINT [FK_JournalTransDetails_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_LOaCostingHeader_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOaCostingHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOaCostingHeader_aAccountMaster] FOREIGN KEY([chInventoryaccid], [chCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOaCostingHeader] CHECK CONSTRAINT [FK_LOaCostingHeader_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_LOaCostingHeader_aAccountMaster1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOaCostingHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOaCostingHeader_aAccountMaster1] FOREIGN KEY([chGoodsinTransitaccid], [chCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[LOaCostingHeader] CHECK CONSTRAINT [FK_LOaCostingHeader_aAccountMaster1]
GO
/****** Object:  ForeignKey [FK_LOaCostingHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOaCostingHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOaCostingHeader_aCompanyMaster] FOREIGN KEY([chCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[LOaCostingHeader] CHECK CONSTRAINT [FK_LOaCostingHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_LOaCostingHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOaCostingHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOaCostingHeader_aDepartmentMaster] FOREIGN KEY([chDepartmentID], [chCompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[LOaCostingHeader] CHECK CONSTRAINT [FK_LOaCostingHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_LOaCostingHeader_LOspPurchaseBillHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOaCostingHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOaCostingHeader_LOspPurchaseBillHeader] FOREIGN KEY([chBillID])
REFERENCES [dbo].[LOspPurchaseBillHeader] ([pbhBillID])
GO
ALTER TABLE [dbo].[LOaCostingHeader] CHECK CONSTRAINT [FK_LOaCostingHeader_LOspPurchaseBillHeader]
GO
/****** Object:  ForeignKey [fk_Billsdebitdetails_accountmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[BillsDebitDetails]  WITH CHECK ADD  CONSTRAINT [fk_Billsdebitdetails_accountmaster] FOREIGN KEY([AccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[BillsDebitDetails] CHECK CONSTRAINT [fk_Billsdebitdetails_accountmaster]
GO
/****** Object:  ForeignKey [fk_Billsdebitdetails_bills]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[BillsDebitDetails]  WITH NOCHECK ADD  CONSTRAINT [fk_Billsdebitdetails_bills] FOREIGN KEY([BillsID])
REFERENCES [dbo].[Bills] ([BillsID])
GO
ALTER TABLE [dbo].[BillsDebitDetails] CHECK CONSTRAINT [fk_Billsdebitdetails_bills]
GO
/****** Object:  ForeignKey [FK_AdjustmentDetails_AccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AdjustmentDetails]  WITH CHECK ADD  CONSTRAINT [FK_AdjustmentDetails_AccountMaster] FOREIGN KEY([AccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[AdjustmentDetails] CHECK CONSTRAINT [FK_AdjustmentDetails_AccountMaster]
GO
/****** Object:  ForeignKey [FK_AdjustmentDetails_AdjustmentHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AdjustmentDetails]  WITH CHECK ADD  CONSTRAINT [FK_AdjustmentDetails_AdjustmentHeader] FOREIGN KEY([AdjustmentID], [CompanyID])
REFERENCES [dbo].[AdjustmentHeader] ([AdjustmentID], [CompanyID])
GO
ALTER TABLE [dbo].[AdjustmentDetails] CHECK CONSTRAINT [FK_AdjustmentDetails_AdjustmentHeader]
GO
/****** Object:  ForeignKey [FK_AdjustmentDetails_CustomerMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AdjustmentDetails]  WITH CHECK ADD  CONSTRAINT [FK_AdjustmentDetails_CustomerMaster] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[AdjustmentDetails] CHECK CONSTRAINT [FK_AdjustmentDetails_CustomerMaster]
GO
/****** Object:  ForeignKey [FK_AdjustmentDetails_VendorMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[AdjustmentDetails]  WITH CHECK ADD  CONSTRAINT [FK_AdjustmentDetails_VendorMaster] FOREIGN KEY([VendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[AdjustmentDetails] CHECK CONSTRAINT [FK_AdjustmentDetails_VendorMaster]
GO
/****** Object:  ForeignKey [FK_badBudgetHeadID_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[BudgetAllocationDetail]  WITH CHECK ADD  CONSTRAINT [FK_badBudgetHeadID_aAccountMaster] FOREIGN KEY([badBudgetHeadID], [badCompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[BudgetAllocationDetail] CHECK CONSTRAINT [FK_badBudgetHeadID_aAccountMaster]
GO
/****** Object:  ForeignKey [fk_AssetTransfer_aAccountMaster_1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[assettransfer]  WITH CHECK ADD  CONSTRAINT [fk_AssetTransfer_aAccountMaster_1] FOREIGN KEY([FromDeprAccId], [asttranscompanyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[assettransfer] CHECK CONSTRAINT [fk_AssetTransfer_aAccountMaster_1]
GO
/****** Object:  ForeignKey [fk_AssetTransfer_aAccountMaster_2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[assettransfer]  WITH CHECK ADD  CONSTRAINT [fk_AssetTransfer_aAccountMaster_2] FOREIGN KEY([ToDeprAccId], [asttranscompanyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[assettransfer] CHECK CONSTRAINT [fk_AssetTransfer_aAccountMaster_2]
GO
/****** Object:  ForeignKey [fk_AssetTransfer_aAccountMaster_3]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[assettransfer]  WITH CHECK ADD  CONSTRAINT [fk_AssetTransfer_aAccountMaster_3] FOREIGN KEY([FromACCDeprAccId], [asttranscompanyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[assettransfer] CHECK CONSTRAINT [fk_AssetTransfer_aAccountMaster_3]
GO
/****** Object:  ForeignKey [fk_AssetTransfer_aAccountMaster_4]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[assettransfer]  WITH CHECK ADD  CONSTRAINT [fk_AssetTransfer_aAccountMaster_4] FOREIGN KEY([ToACCDeprAccId], [asttranscompanyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[assettransfer] CHECK CONSTRAINT [fk_AssetTransfer_aAccountMaster_4]
GO
/****** Object:  ForeignKey [fk_assettransfer_acompanymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[assettransfer]  WITH CHECK ADD  CONSTRAINT [fk_assettransfer_acompanymaster] FOREIGN KEY([asttranscompanyid])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[assettransfer] CHECK CONSTRAINT [fk_assettransfer_acompanymaster]
GO
/****** Object:  ForeignKey [fk_assettransfer_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[assettransfer]  WITH CHECK ADD  CONSTRAINT [fk_assettransfer_adepartmentmaster] FOREIGN KEY([asttransfromdepid], [asttranscompanyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[assettransfer] CHECK CONSTRAINT [fk_assettransfer_adepartmentmaster]
GO
/****** Object:  ForeignKey [fk_assettransfer_adepartmentmaster2]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[assettransfer]  WITH CHECK ADD  CONSTRAINT [fk_assettransfer_adepartmentmaster2] FOREIGN KEY([asttranstodepid], [asttranscompanyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[assettransfer] CHECK CONSTRAINT [fk_assettransfer_adepartmentmaster2]
GO
/****** Object:  ForeignKey [fk_loPrePurchaseOrderHeader_aaccountmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader]  WITH CHECK ADD  CONSTRAINT [fk_loPrePurchaseOrderHeader_aaccountmaster] FOREIGN KEY([pohLCAccountid], [pohcompanyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] CHECK CONSTRAINT [fk_loPrePurchaseOrderHeader_aaccountmaster]
GO
/****** Object:  ForeignKey [fk_loPrePurchaseOrderHeader_aaccountmaster_lc]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader]  WITH CHECK ADD  CONSTRAINT [fk_loPrePurchaseOrderHeader_aaccountmaster_lc] FOREIGN KEY([pohLCAccountid], [pohcompanyid])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] CHECK CONSTRAINT [fk_loPrePurchaseOrderHeader_aaccountmaster_lc]
GO
/****** Object:  ForeignKey [fk_loPrePurchaseOrderHeader_acompanymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader]  WITH CHECK ADD  CONSTRAINT [fk_loPrePurchaseOrderHeader_acompanymaster] FOREIGN KEY([pohcompanyid])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] CHECK CONSTRAINT [fk_loPrePurchaseOrderHeader_acompanymaster]
GO
/****** Object:  ForeignKey [fk_loPrePurchaseOrderHeader_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader]  WITH CHECK ADD  CONSTRAINT [fk_loPrePurchaseOrderHeader_adepartmentmaster] FOREIGN KEY([pohDepartmentid], [pohcompanyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] CHECK CONSTRAINT [fk_loPrePurchaseOrderHeader_adepartmentmaster]
GO
/****** Object:  ForeignKey [FK_loPrePurchaseOrderHeader_aVendorMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loPrePurchaseOrderHeader]  WITH CHECK ADD  CONSTRAINT [FK_loPrePurchaseOrderHeader_aVendorMaster] FOREIGN KEY([pohVendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[loPrePurchaseOrderHeader] CHECK CONSTRAINT [FK_loPrePurchaseOrderHeader_aVendorMaster]
GO
/****** Object:  ForeignKey [FK_ReceiptVoucherCreditDetails_aAccountMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ReceiptVoucherCreditDetails]  WITH CHECK ADD  CONSTRAINT [FK_ReceiptVoucherCreditDetails_aAccountMaster] FOREIGN KEY([AccountID], [CompanyID])
REFERENCES [dbo].[aAccountMaster] ([AccountID], [CompanyID])
GO
ALTER TABLE [dbo].[ReceiptVoucherCreditDetails] CHECK CONSTRAINT [FK_ReceiptVoucherCreditDetails_aAccountMaster]
GO
/****** Object:  ForeignKey [FK_losInquiryHeader_aCustomerMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losInquiryHeader]  WITH CHECK ADD  CONSTRAINT [FK_losInquiryHeader_aCustomerMaster] FOREIGN KEY([ihcustid])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[losInquiryHeader] CHECK CONSTRAINT [FK_losInquiryHeader_aCustomerMaster]
GO
/****** Object:  ForeignKey [FK_losInquiryHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losInquiryHeader]  WITH CHECK ADD  CONSTRAINT [FK_losInquiryHeader_aShops] FOREIGN KEY([ihshopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losInquiryHeader] CHECK CONSTRAINT [FK_losInquiryHeader_aShops]
GO
/****** Object:  ForeignKey [fk_losSerMaintenanceContractHeader_acompanymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerMaintenanceContractHeader]  WITH CHECK ADD  CONSTRAINT [fk_losSerMaintenanceContractHeader_acompanymaster] FOREIGN KEY([mchCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[losSerMaintenanceContractHeader] CHECK CONSTRAINT [fk_losSerMaintenanceContractHeader_acompanymaster]
GO
/****** Object:  ForeignKey [fk_losSerMaintenanceContractHeader_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerMaintenanceContractHeader]  WITH CHECK ADD  CONSTRAINT [fk_losSerMaintenanceContractHeader_acustomermaster] FOREIGN KEY([mchCustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[losSerMaintenanceContractHeader] CHECK CONSTRAINT [fk_losSerMaintenanceContractHeader_acustomermaster]
GO
/****** Object:  ForeignKey [fk_losSerMaintenanceContractHeader_ashops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losSerMaintenanceContractHeader]  WITH CHECK ADD  CONSTRAINT [fk_losSerMaintenanceContractHeader_ashops] FOREIGN KEY([mchShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losSerMaintenanceContractHeader] CHECK CONSTRAINT [fk_losSerMaintenanceContractHeader_ashops]
GO
/****** Object:  ForeignKey [FK_LosShipmentbnheader_aCustomerMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosShipmentbnheader]  WITH CHECK ADD  CONSTRAINT [FK_LosShipmentbnheader_aCustomerMaster] FOREIGN KEY([bnhCustomerId])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[LosShipmentbnheader] CHECK CONSTRAINT [FK_LosShipmentbnheader_aCustomerMaster]
GO
/****** Object:  ForeignKey [FK_LOsPosHeader_aCustomerMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPosHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsPosHeader_aCustomerMaster] FOREIGN KEY([poshcustomerid])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[LOsPosHeader] CHECK CONSTRAINT [FK_LOsPosHeader_aCustomerMaster]
GO
/****** Object:  ForeignKey [fk_losLocalClearenceRequestHeader_aCustomerMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losLocalClearenceRequestHeader]  WITH CHECK ADD  CONSTRAINT [fk_losLocalClearenceRequestHeader_aCustomerMaster] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[losLocalClearenceRequestHeader] CHECK CONSTRAINT [fk_losLocalClearenceRequestHeader_aCustomerMaster]
GO
/****** Object:  ForeignKey [fk_losLocalClearenceRequestHeader_aVendorMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losLocalClearenceRequestHeader]  WITH CHECK ADD  CONSTRAINT [fk_losLocalClearenceRequestHeader_aVendorMaster] FOREIGN KEY([VendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[losLocalClearenceRequestHeader] CHECK CONSTRAINT [fk_losLocalClearenceRequestHeader_aVendorMaster]
GO
/****** Object:  ForeignKey [fk_LosKegReturnHeader_acustomermaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosKegReturnHeader]  WITH CHECK ADD  CONSTRAINT [fk_LosKegReturnHeader_acustomermaster] FOREIGN KEY([krhCustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[LosKegReturnHeader] CHECK CONSTRAINT [fk_LosKegReturnHeader_acustomermaster]
GO
/****** Object:  ForeignKey [FK_LosKegReturnHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosKegReturnHeader]  WITH CHECK ADD  CONSTRAINT [FK_LosKegReturnHeader_aDepartmentMaster] FOREIGN KEY([krhDepartmentid], [krCompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[LosKegReturnHeader] CHECK CONSTRAINT [FK_LosKegReturnHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_LosKegReturnHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosKegReturnHeader]  WITH CHECK ADD  CONSTRAINT [FK_LosKegReturnHeader_aShops] FOREIGN KEY([krhShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LosKegReturnHeader] CHECK CONSTRAINT [FK_LosKegReturnHeader_aShops]
GO
/****** Object:  ForeignKey [fk_loSExportHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losExportHeader]  WITH CHECK ADD  CONSTRAINT [fk_loSExportHeader] FOREIGN KEY([rehcustomerid])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[losExportHeader] CHECK CONSTRAINT [fk_loSExportHeader]
GO
/****** Object:  ForeignKey [fk_losexportheader_acompanymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losExportHeader]  WITH CHECK ADD  CONSTRAINT [fk_losexportheader_acompanymaster] FOREIGN KEY([rehCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[losExportHeader] CHECK CONSTRAINT [fk_losexportheader_acompanymaster]
GO
/****** Object:  ForeignKey [fk_losexportheader_ashops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losExportHeader]  WITH CHECK ADD  CONSTRAINT [fk_losexportheader_ashops] FOREIGN KEY([rehShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losExportHeader] CHECK CONSTRAINT [fk_losexportheader_ashops]
GO
/****** Object:  ForeignKey [FK_aShopCustomerDetails_aCustomerMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopCustomerDetails]  WITH CHECK ADD  CONSTRAINT [FK_aShopCustomerDetails_aCustomerMaster] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[aCustomerMaster] ([CustomerID])
GO
ALTER TABLE [dbo].[aShopCustomerDetails] CHECK CONSTRAINT [FK_aShopCustomerDetails_aCustomerMaster]
GO
/****** Object:  ForeignKey [FK_aShopCustomerDetails_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopCustomerDetails]  WITH CHECK ADD  CONSTRAINT [FK_aShopCustomerDetails_aShops] FOREIGN KEY([ShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[aShopCustomerDetails] CHECK CONSTRAINT [FK_aShopCustomerDetails_aShops]
GO
/****** Object:  ForeignKey [FK_Flights_FlightOperatorMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Flights]  WITH CHECK ADD  CONSTRAINT [FK_Flights_FlightOperatorMaster] FOREIGN KEY([companyid], [FlightOpid])
REFERENCES [dbo].[FlightOperatorMaster] ([companyid], [FlghtOpid])
GO
ALTER TABLE [dbo].[Flights] CHECK CONSTRAINT [FK_Flights_FlightOperatorMaster]
GO
/****** Object:  ForeignKey [FK_BudgetAllocationHeader_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[BudgetAllocationHeader]  WITH CHECK ADD  CONSTRAINT [FK_BudgetAllocationHeader_aDepartmentMaster] FOREIGN KEY([bahDepartmentId], [bahCompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[BudgetAllocationHeader] CHECK CONSTRAINT [FK_BudgetAllocationHeader_aDepartmentMaster]
GO
/****** Object:  ForeignKey [fk_losreplacerequestheader_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacerequestheader]  WITH CHECK ADD  CONSTRAINT [fk_losreplacerequestheader_adepartmentmaster] FOREIGN KEY([repreqhdepartmentid], [repreqhcompanyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[losreplacerequestheader] CHECK CONSTRAINT [fk_losreplacerequestheader_adepartmentmaster]
GO
/****** Object:  ForeignKey [FK_losreplacerequestheader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacerequestheader]  WITH CHECK ADD  CONSTRAINT [FK_losreplacerequestheader_aShops] FOREIGN KEY([repreqshopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losreplacerequestheader] CHECK CONSTRAINT [FK_losreplacerequestheader_aShops]
GO
/****** Object:  ForeignKey [fk_aLCRegisterDetails_acompanymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aLCRegisterDetails]  WITH CHECK ADD  CONSTRAINT [fk_aLCRegisterDetails_acompanymaster] FOREIGN KEY([LcCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aLCRegisterDetails] CHECK CONSTRAINT [fk_aLCRegisterDetails_acompanymaster]
GO
/****** Object:  ForeignKey [fk_aLCRegisterDetails_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aLCRegisterDetails]  WITH CHECK ADD  CONSTRAINT [fk_aLCRegisterDetails_adepartmentmaster] FOREIGN KEY([LcDepartmentID], [LcCompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[aLCRegisterDetails] CHECK CONSTRAINT [fk_aLCRegisterDetails_adepartmentmaster]
GO
/****** Object:  ForeignKey [fk_losservicebookingheader_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceBookingHeader]  WITH CHECK ADD  CONSTRAINT [fk_losservicebookingheader_adepartmentmaster] FOREIGN KEY([serbookhdepartmentid], [serbookhcompanyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[losServiceBookingHeader] CHECK CONSTRAINT [fk_losservicebookingheader_adepartmentmaster]
GO
/****** Object:  ForeignKey [fk_LosServiceBookingHeader_losCallBookingHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losServiceBookingHeader]  WITH CHECK ADD  CONSTRAINT [fk_LosServiceBookingHeader_losCallBookingHeader] FOREIGN KEY([serbookhRefId], [serbookhshopid], [serbookhcompanyid])
REFERENCES [dbo].[losCallBookingHeader] ([serCallBkhid], [serCallBkhshopid], [serCallBkhcompanyid])
GO
ALTER TABLE [dbo].[losServiceBookingHeader] CHECK CONSTRAINT [fk_LosServiceBookingHeader_losCallBookingHeader]
GO
/****** Object:  ForeignKey [FK_aHQDespatchNoteMain_aDepartmentMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchNoteMain]  WITH CHECK ADD  CONSTRAINT [FK_aHQDespatchNoteMain_aDepartmentMaster] FOREIGN KEY([departmentid], [companyid])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[aHQDespatchNoteMain] CHECK CONSTRAINT [FK_aHQDespatchNoteMain_aDepartmentMaster]
GO
/****** Object:  ForeignKey [FK_aHQDespatchNoteMain_LOspPurchaseBillHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQDespatchNoteMain]  WITH CHECK ADD  CONSTRAINT [FK_aHQDespatchNoteMain_LOspPurchaseBillHeader] FOREIGN KEY([dnmBillID])
REFERENCES [dbo].[LOspPurchaseBillHeader] ([pbhBillID])
GO
ALTER TABLE [dbo].[aHQDespatchNoteMain] CHECK CONSTRAINT [FK_aHQDespatchNoteMain_LOspPurchaseBillHeader]
GO
/****** Object:  ForeignKey [fk_aBouncedChequeDetails_acompanymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aBouncedChequeDetails]  WITH CHECK ADD  CONSTRAINT [fk_aBouncedChequeDetails_acompanymaster] FOREIGN KEY([BcCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aBouncedChequeDetails] CHECK CONSTRAINT [fk_aBouncedChequeDetails_acompanymaster]
GO
/****** Object:  ForeignKey [fk_aBouncedChequeDetails_adepartmentmaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aBouncedChequeDetails]  WITH CHECK ADD  CONSTRAINT [fk_aBouncedChequeDetails_adepartmentmaster] FOREIGN KEY([BcDepartmentID], [BcCompanyID])
REFERENCES [dbo].[aDepartmentMaster] ([DepartmentID], [CompanyID])
GO
ALTER TABLE [dbo].[aBouncedChequeDetails] CHECK CONSTRAINT [fk_aBouncedChequeDetails_adepartmentmaster]
GO
/****** Object:  ForeignKey [FK_aShopVendorDetails_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopVendorDetails]  WITH CHECK ADD  CONSTRAINT [FK_aShopVendorDetails_aShops] FOREIGN KEY([ShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[aShopVendorDetails] CHECK CONSTRAINT [FK_aShopVendorDetails_aShops]
GO
/****** Object:  ForeignKey [FK_aShopVendorDetails_aVendorMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aShopVendorDetails]  WITH CHECK ADD  CONSTRAINT [FK_aShopVendorDetails_aVendorMaster] FOREIGN KEY([VendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[aShopVendorDetails] CHECK CONSTRAINT [FK_aShopVendorDetails_aVendorMaster]
GO
/****** Object:  ForeignKey [fk_losPurchaseOrderHeader_acompanymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderHeader]  WITH CHECK ADD  CONSTRAINT [fk_losPurchaseOrderHeader_acompanymaster] FOREIGN KEY([pohCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[losPurchaseOrderHeader] CHECK CONSTRAINT [fk_losPurchaseOrderHeader_acompanymaster]
GO
/****** Object:  ForeignKey [FK_losPurchaseOrderHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderHeader]  WITH CHECK ADD  CONSTRAINT [FK_losPurchaseOrderHeader_aShops] FOREIGN KEY([pohShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losPurchaseOrderHeader] CHECK CONSTRAINT [FK_losPurchaseOrderHeader_aShops]
GO
/****** Object:  ForeignKey [fk_losPurchaseOrderHeader_avendormaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losPurchaseOrderHeader]  WITH CHECK ADD  CONSTRAINT [fk_losPurchaseOrderHeader_avendormaster] FOREIGN KEY([pohVendorID])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[losPurchaseOrderHeader] CHECK CONSTRAINT [fk_losPurchaseOrderHeader_avendormaster]
GO
/****** Object:  ForeignKey [FK_aHQPaymentVoucherVendorDetails_aHQPaymentVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherVendorDetails]  WITH CHECK ADD  CONSTRAINT [FK_aHQPaymentVoucherVendorDetails_aHQPaymentVoucherHeader] FOREIGN KEY([pvdPaymentid])
REFERENCES [dbo].[aHQPaymentVoucherHeader] ([phPaymentID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherVendorDetails] CHECK CONSTRAINT [FK_aHQPaymentVoucherVendorDetails_aHQPaymentVoucherHeader]
GO
/****** Object:  ForeignKey [FK_aHQPaymentVoucherVendorDetails_aVendorMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherVendorDetails]  WITH CHECK ADD  CONSTRAINT [FK_aHQPaymentVoucherVendorDetails_aVendorMaster] FOREIGN KEY([pvdVendorid])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherVendorDetails] CHECK CONSTRAINT [FK_aHQPaymentVoucherVendorDetails_aVendorMaster]
GO
/****** Object:  ForeignKey [FK_areprecvendorheader_aVendorMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[areprecvendorheader]  WITH CHECK ADD  CONSTRAINT [FK_areprecvendorheader_aVendorMaster] FOREIGN KEY([rrvhvendorid])
REFERENCES [dbo].[aVendorMaster] ([VendorID])
GO
ALTER TABLE [dbo].[areprecvendorheader] CHECK CONSTRAINT [FK_areprecvendorheader_aVendorMaster]
GO
/****** Object:  ForeignKey [FK_SCHEDULEDETAIL_ScheduleHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[SCHEDULEDETAIL]  WITH CHECK ADD  CONSTRAINT [FK_SCHEDULEDETAIL_ScheduleHeader] FOREIGN KEY([scdid])
REFERENCES [dbo].[ScheduleHeader] ([schid])
GO
ALTER TABLE [dbo].[SCHEDULEDETAIL] CHECK CONSTRAINT [FK_SCHEDULEDETAIL_ScheduleHeader]
GO
/****** Object:  ForeignKey [fk_ShipmentClearenceRequestDetails_ClearenceRequestHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ShipmentClearenceRequestDetails]  WITH CHECK ADD  CONSTRAINT [fk_ShipmentClearenceRequestDetails_ClearenceRequestHeader] FOREIGN KEY([ShopID], [ClearenceReqID])
REFERENCES [dbo].[ClearenceRequestHeader] ([ShopID], [ClearenceReqID])
GO
ALTER TABLE [dbo].[ShipmentClearenceRequestDetails] CHECK CONSTRAINT [fk_ShipmentClearenceRequestDetails_ClearenceRequestHeader]
GO
/****** Object:  ForeignKey [fk_ShipmentClearenceRequestDetails_ShipmentClearenceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ShipmentClearenceRequestDetails]  WITH CHECK ADD  CONSTRAINT [fk_ShipmentClearenceRequestDetails_ShipmentClearenceHeader] FOREIGN KEY([ShopID], [ClearenceID])
REFERENCES [dbo].[ShipmentClearenceHeader] ([ShopID], [ClearenceID])
GO
ALTER TABLE [dbo].[ShipmentClearenceRequestDetails] CHECK CONSTRAINT [fk_ShipmentClearenceRequestDetails_ShipmentClearenceHeader]
GO
/****** Object:  ForeignKey [fk_ShipmentClearenceOCDetails_ClearenceRequestHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ShipmentClearenceOCDetails]  WITH CHECK ADD  CONSTRAINT [fk_ShipmentClearenceOCDetails_ClearenceRequestHeader] FOREIGN KEY([ShopID], [ClearenceReqID])
REFERENCES [dbo].[ClearenceRequestHeader] ([ShopID], [ClearenceReqID])
GO
ALTER TABLE [dbo].[ShipmentClearenceOCDetails] CHECK CONSTRAINT [fk_ShipmentClearenceOCDetails_ClearenceRequestHeader]
GO
/****** Object:  ForeignKey [fk_ShipmentClearenceOCDetails_ShipmentClearenceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ShipmentClearenceOCDetails]  WITH CHECK ADD  CONSTRAINT [fk_ShipmentClearenceOCDetails_ShipmentClearenceHeader] FOREIGN KEY([ShopID], [ClearenceID])
REFERENCES [dbo].[ShipmentClearenceHeader] ([ShopID], [ClearenceID])
GO
ALTER TABLE [dbo].[ShipmentClearenceOCDetails] CHECK CONSTRAINT [fk_ShipmentClearenceOCDetails_ShipmentClearenceHeader]
GO
/****** Object:  ForeignKey [fk_ShipmentClearenceChequeDetails_ShipmentClearenceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ShipmentClearenceChequeDetails]  WITH CHECK ADD  CONSTRAINT [fk_ShipmentClearenceChequeDetails_ShipmentClearenceHeader] FOREIGN KEY([ShopID], [ClearenceID])
REFERENCES [dbo].[ShipmentClearenceHeader] ([ShopID], [ClearenceID])
GO
ALTER TABLE [dbo].[ShipmentClearenceChequeDetails] CHECK CONSTRAINT [fk_ShipmentClearenceChequeDetails_ShipmentClearenceHeader]
GO
/****** Object:  ForeignKey [FK_ServiceInvoiceDetails_AccountsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ServiceInvoiceDetails]  WITH CHECK ADD  CONSTRAINT [FK_ServiceInvoiceDetails_AccountsInvoiceHeader] FOREIGN KEY([InvoiceID])
REFERENCES [dbo].[AccountsInvoiceHeader] ([InvoiceID])
GO
ALTER TABLE [dbo].[ServiceInvoiceDetails] CHECK CONSTRAINT [FK_ServiceInvoiceDetails_AccountsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_LOsServiceInvoiceDetails_LOsAccountsInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsServiceInvoiceDetails]  WITH CHECK ADD  CONSTRAINT [FK_LOsServiceInvoiceDetails_LOsAccountsInvoiceHeader] FOREIGN KEY([siShopID], [siInvoiceID])
REFERENCES [dbo].[LOsAccountsInvoiceHeader] ([aiShopID], [aiInvoiceID])
GO
ALTER TABLE [dbo].[LOsServiceInvoiceDetails] CHECK CONSTRAINT [FK_LOsServiceInvoiceDetails_LOsAccountsInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_Fb_resttable_fb_resttablemaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[Fb_resttable]  WITH CHECK ADD  CONSTRAINT [FK_Fb_resttable_fb_resttablemaster] FOREIGN KEY([Fb_rt_companyid], [Fb_rt_outletid], [fb_rt_tablemasterid])
REFERENCES [dbo].[fb_resttablemaster] ([fb_rm_companyid], [fb_rm_outletid], [fb_rm_tablemasterid])
GO
ALTER TABLE [dbo].[Fb_resttable] CHECK CONSTRAINT [FK_Fb_resttable_fb_resttablemaster]
GO
/****** Object:  ForeignKey [FK_LOsPaymentVoucherDetails_LosLocalPurchaseHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherDetails]  WITH CHECK ADD  CONSTRAINT [FK_LOsPaymentVoucherDetails_LosLocalPurchaseHeader] FOREIGN KEY([pdShopID], [pdBillsID])
REFERENCES [dbo].[LosLocalPurchaseHeader] ([lphShopID], [lphBillID])
GO
ALTER TABLE [dbo].[LOsPaymentVoucherDetails] CHECK CONSTRAINT [FK_LOsPaymentVoucherDetails_LosLocalPurchaseHeader]
GO
/****** Object:  ForeignKey [FK_LOsPaymentVoucherDetails_LOsPaymentVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsPaymentVoucherDetails]  WITH CHECK ADD  CONSTRAINT [FK_LOsPaymentVoucherDetails_LOsPaymentVoucherHeader] FOREIGN KEY([pdPaymentID], [pdShopID])
REFERENCES [dbo].[LOsPaymentVoucherHeader] ([phPaymentID], [phShopID])
GO
ALTER TABLE [dbo].[LOsPaymentVoucherDetails] CHECK CONSTRAINT [FK_LOsPaymentVoucherDetails_LOsPaymentVoucherHeader]
GO
/****** Object:  ForeignKey [FK_fb_Tableoccupancy_Fb_resttable]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[fb_Tableoccupancy]  WITH CHECK ADD  CONSTRAINT [FK_fb_Tableoccupancy_Fb_resttable] FOREIGN KEY([Fb_to_companyid], [fb_to_Outletid], [fb_to_coverid])
REFERENCES [dbo].[Fb_resttable] ([Fb_rt_companyid], [Fb_rt_outletid], [Fb_rt_tableid])
GO
ALTER TABLE [dbo].[fb_Tableoccupancy] CHECK CONSTRAINT [FK_fb_Tableoccupancy_Fb_resttable]
GO
/****** Object:  ForeignKey [fk_ClearenceRequestDetail_ClearenceRequestHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ClearenceRequestDetail]  WITH CHECK ADD  CONSTRAINT [fk_ClearenceRequestDetail_ClearenceRequestHeader] FOREIGN KEY([ShopID], [ClearenceReqID])
REFERENCES [dbo].[ClearenceRequestHeader] ([ShopID], [ClearenceReqID])
GO
ALTER TABLE [dbo].[ClearenceRequestDetail] CHECK CONSTRAINT [fk_ClearenceRequestDetail_ClearenceRequestHeader]
GO
/****** Object:  ForeignKey [FK_losHPChequeRegisterDetail_losHPChequeRegisterHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losHPChequeRegisterDetail]  WITH NOCHECK ADD  CONSTRAINT [FK_losHPChequeRegisterDetail_losHPChequeRegisterHeader] FOREIGN KEY([HpdChqRegID])
REFERENCES [dbo].[losHPChequeRegisterHeader] ([HphChqRegID])
GO
ALTER TABLE [dbo].[losHPChequeRegisterDetail] CHECK CONSTRAINT [FK_losHPChequeRegisterDetail_losHPChequeRegisterHeader]
GO
/****** Object:  ForeignKey [fk_aHQPaymentVoucherSPDetails_HQSalesPromotionDetail]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherSPDetails]  WITH CHECK ADD  CONSTRAINT [fk_aHQPaymentVoucherSPDetails_HQSalesPromotionDetail] FOREIGN KEY([CompanyID], [PromotionID], [PromotionDetailID])
REFERENCES [dbo].[HQSalesPromotionDetail] ([spdCompanyID], [spdpromotionID], [spdDetailID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherSPDetails] CHECK CONSTRAINT [fk_aHQPaymentVoucherSPDetails_HQSalesPromotionDetail]
GO
/****** Object:  ForeignKey [fk_fb_dishsubgroup_fb_dishgroup]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[FB_Dishsubgroup]  WITH CHECK ADD  CONSTRAINT [fk_fb_dishsubgroup_fb_dishgroup] FOREIGN KEY([Fb_Ds_CompanyID], [Fb_Ds_DishGroupID])
REFERENCES [dbo].[FB_Dishgroup] ([FB_dg_companyid], [FB_dg_Dishgroupid])
GO
ALTER TABLE [dbo].[FB_Dishsubgroup] CHECK CONSTRAINT [fk_fb_dishsubgroup_fb_dishgroup]
GO
/****** Object:  ForeignKey [FK_losHpDummyQuotationDetails_losHpDummyQuotationHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losHpDummyQuotationDetails]  WITH NOCHECK ADD  CONSTRAINT [FK_losHpDummyQuotationDetails_losHpDummyQuotationHeader] FOREIGN KEY([hpqdQuotationID])
REFERENCES [dbo].[losHpDummyQuotationHeader] ([hpqhQuotationID])
GO
ALTER TABLE [dbo].[losHpDummyQuotationDetails] CHECK CONSTRAINT [FK_losHpDummyQuotationDetails_losHpDummyQuotationHeader]
GO
/****** Object:  ForeignKey [FK_losHpInvoiceDetailOthers_losHpInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losHpInvoiceDetailOthers]  WITH NOCHECK ADD  CONSTRAINT [FK_losHpInvoiceDetailOthers_losHpInvoiceHeader] FOREIGN KEY([hpqdQuotationID])
REFERENCES [dbo].[losHpInvoiceHeader] ([hpqhQuotationID])
GO
ALTER TABLE [dbo].[losHpInvoiceDetailOthers] CHECK CONSTRAINT [FK_losHpInvoiceDetailOthers_losHpInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_losHpInvoiceDetail_losHpInvoiceHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losHpInvoiceDetail]  WITH NOCHECK ADD  CONSTRAINT [FK_losHpInvoiceDetail_losHpInvoiceHeader] FOREIGN KEY([hpqdQuotationID])
REFERENCES [dbo].[losHpInvoiceHeader] ([hpqhQuotationID])
GO
ALTER TABLE [dbo].[losHpInvoiceDetail] CHECK CONSTRAINT [FK_losHpInvoiceDetail_losHpInvoiceHeader]
GO
/****** Object:  ForeignKey [FK_LosShipmentbndetail_LosShipmentbnheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LosShipmentbndetail]  WITH CHECK ADD  CONSTRAINT [FK_LosShipmentbndetail_LosShipmentbnheader] FOREIGN KEY([bndShopId], [bndboatnoteId])
REFERENCES [dbo].[LosShipmentbnheader] ([bnhShopId], [bnhboatnoteId])
GO
ALTER TABLE [dbo].[LosShipmentbndetail] CHECK CONSTRAINT [FK_LosShipmentbndetail_LosShipmentbnheader]
GO
/****** Object:  ForeignKey [fk_losBoatNoteConfirmHeader_losShipmentBNHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losBoatNoteConfirmHeader]  WITH CHECK ADD  CONSTRAINT [fk_losBoatNoteConfirmHeader_losShipmentBNHeader] FOREIGN KEY([ShopID], [BoatNoteID])
REFERENCES [dbo].[LosShipmentbnheader] ([bnhShopId], [bnhboatnoteId])
GO
ALTER TABLE [dbo].[losBoatNoteConfirmHeader] CHECK CONSTRAINT [fk_losBoatNoteConfirmHeader_losShipmentBNHeader]
GO
/****** Object:  ForeignKey [fk_losShipmentOCDetail_losShipmentBNHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losShipmentBNOCDetail]  WITH CHECK ADD  CONSTRAINT [fk_losShipmentOCDetail_losShipmentBNHeader] FOREIGN KEY([ShopID], [BoatNoteID])
REFERENCES [dbo].[LosShipmentbnheader] ([bnhShopId], [bnhboatnoteId])
GO
ALTER TABLE [dbo].[losShipmentBNOCDetail] CHECK CONSTRAINT [fk_losShipmentOCDetail_losShipmentBNHeader]
GO
/****** Object:  ForeignKey [fk_loilocationgroup_acompanymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LoilocationGroup]  WITH CHECK ADD  CONSTRAINT [fk_loilocationgroup_acompanymaster] FOREIGN KEY([Lgcompanyid])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[LoilocationGroup] CHECK CONSTRAINT [fk_loilocationgroup_acompanymaster]
GO
/****** Object:  ForeignKey [fk_loilocationgroup_agodwn]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LoilocationGroup]  WITH CHECK ADD  CONSTRAINT [fk_loilocationgroup_agodwn] FOREIGN KEY([Lggodownid])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[LoilocationGroup] CHECK CONSTRAINT [fk_loilocationgroup_agodwn]
GO
/****** Object:  ForeignKey [FK_METransLog_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsTransLog]  WITH CHECK ADD  CONSTRAINT [FK_METransLog_aGodown] FOREIGN KEY([GodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[MEsTransLog] CHECK CONSTRAINT [FK_METransLog_aGodown]
GO
/****** Object:  ForeignKey [FK_METransLog_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsTransLog]  WITH CHECK ADD  CONSTRAINT [FK_METransLog_aShops] FOREIGN KEY([ShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[MEsTransLog] CHECK CONSTRAINT [FK_METransLog_aShops]
GO
/****** Object:  ForeignKey [FK_loiexpiryarrivaldetails_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiexpiryarrivaldetails]  WITH CHECK ADD  CONSTRAINT [FK_loiexpiryarrivaldetails_aGodown] FOREIGN KEY([eadgodownid])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[loiexpiryarrivaldetails] CHECK CONSTRAINT [FK_loiexpiryarrivaldetails_aGodown]
GO
/****** Object:  ForeignKey [FK_loiStockVerificationHeader_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiStockVerificationHeader]  WITH CHECK ADD  CONSTRAINT [FK_loiStockVerificationHeader_aGodown] FOREIGN KEY([svhGodownid])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[loiStockVerificationHeader] CHECK CONSTRAINT [FK_loiStockVerificationHeader_aGodown]
GO
/****** Object:  ForeignKey [FK_MEsDespatchtoGodownHeader_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsDespatchtoGodownHeader]  WITH CHECK ADD  CONSTRAINT [FK_MEsDespatchtoGodownHeader_aGodown] FOREIGN KEY([dghGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[MEsDespatchtoGodownHeader] CHECK CONSTRAINT [FK_MEsDespatchtoGodownHeader_aGodown]
GO
/****** Object:  ForeignKey [FK_MEsDespatchtoGodownHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEsDespatchtoGodownHeader]  WITH CHECK ADD  CONSTRAINT [FK_MEsDespatchtoGodownHeader_aShops] FOREIGN KEY([dghShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[MEsDespatchtoGodownHeader] CHECK CONSTRAINT [FK_MEsDespatchtoGodownHeader_aShops]
GO
/****** Object:  ForeignKey [FK_MEiGodownTransferHeader_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiGodownTransferHeader]  WITH CHECK ADD  CONSTRAINT [FK_MEiGodownTransferHeader_aGodown] FOREIGN KEY([gthFromGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[MEiGodownTransferHeader] CHECK CONSTRAINT [FK_MEiGodownTransferHeader_aGodown]
GO
/****** Object:  ForeignKey [FK_MEiGodownTransferHeader_aGodown1]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MEiGodownTransferHeader]  WITH CHECK ADD  CONSTRAINT [FK_MEiGodownTransferHeader_aGodown1] FOREIGN KEY([gthToGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[MEiGodownTransferHeader] CHECK CONSTRAINT [FK_MEiGodownTransferHeader_aGodown1]
GO
/****** Object:  ForeignKey [fk_loisettings_agodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiSettings]  WITH CHECK ADD  CONSTRAINT [fk_loisettings_agodown] FOREIGN KEY([Godownid])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[LOiSettings] CHECK CONSTRAINT [fk_loisettings_agodown]
GO
/****** Object:  ForeignKey [FK_LOiDamageClearingHeader_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiDamageClearingHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOiDamageClearingHeader_aGodown] FOREIGN KEY([dchGodownid])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[LOiDamageClearingHeader] CHECK CONSTRAINT [FK_LOiDamageClearingHeader_aGodown]
GO
/****** Object:  ForeignKey [FK_LOiWriteOffHeader_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOiWriteOffHeader]  WITH NOCHECK ADD  CONSTRAINT [FK_LOiWriteOffHeader_aGodown] FOREIGN KEY([whGodownID])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[LOiWriteOffHeader] CHECK CONSTRAINT [FK_LOiWriteOffHeader_aGodown]
GO
/****** Object:  ForeignKey [FK_MeiGodownRequestHeader_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[MeiGodownRequestHeader]  WITH CHECK ADD  CONSTRAINT [FK_MeiGodownRequestHeader_aGodown] FOREIGN KEY([GRHGodownId])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[MeiGodownRequestHeader] CHECK CONSTRAINT [FK_MeiGodownRequestHeader_aGodown]
GO
/****** Object:  ForeignKey [FK_loiexpiryissuedetails_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[loiexpiryissuedetails]  WITH CHECK ADD  CONSTRAINT [FK_loiexpiryissuedetails_aGodown] FOREIGN KEY([eidgodownid])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[loiexpiryissuedetails] CHECK CONSTRAINT [FK_loiexpiryissuedetails_aGodown]
GO
/****** Object:  ForeignKey [FK_meiSpecialDespatchtoshopHeader_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoshopHeader]  WITH CHECK ADD  CONSTRAINT [FK_meiSpecialDespatchtoshopHeader_aGodown] FOREIGN KEY([dhgodownid])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[meiSpecialDespatchtoshopHeader] CHECK CONSTRAINT [FK_meiSpecialDespatchtoshopHeader_aGodown]
GO
/****** Object:  ForeignKey [FK_meiSpecialDespatchtoshopHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[meiSpecialDespatchtoshopHeader]  WITH CHECK ADD  CONSTRAINT [FK_meiSpecialDespatchtoshopHeader_aShops] FOREIGN KEY([dhShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[meiSpecialDespatchtoshopHeader] CHECK CONSTRAINT [FK_meiSpecialDespatchtoshopHeader_aShops]
GO
/****** Object:  ForeignKey [fk_losDeliveryNoteItemDetails_aGodown]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losDeliveryNoteItemDetails]  WITH CHECK ADD  CONSTRAINT [fk_losDeliveryNoteItemDetails_aGodown] FOREIGN KEY([dndCollectFromGodownId])
REFERENCES [dbo].[aGodown] ([GodownID])
GO
ALTER TABLE [dbo].[losDeliveryNoteItemDetails] CHECK CONSTRAINT [fk_losDeliveryNoteItemDetails_aGodown]
GO
/****** Object:  ForeignKey [fk_aHQPaymentVoucherSCDetails_aHQPaymentVoucherHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherSCDetails]  WITH CHECK ADD  CONSTRAINT [fk_aHQPaymentVoucherSCDetails_aHQPaymentVoucherHeader] FOREIGN KEY([PaymentID])
REFERENCES [dbo].[aHQPaymentVoucherHeader] ([phPaymentID])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherSCDetails] CHECK CONSTRAINT [fk_aHQPaymentVoucherSCDetails_aHQPaymentVoucherHeader]
GO
/****** Object:  ForeignKey [fk_aHQPaymentVoucherSCDetails_HQSalesCommisionHeader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHQPaymentVoucherSCDetails]  WITH CHECK ADD  CONSTRAINT [fk_aHQPaymentVoucherSCDetails_HQSalesCommisionHeader] FOREIGN KEY([SalesCommID], [CompanyID])
REFERENCES [dbo].[hqSalesCommisionHeader] ([schCommisionid], [schcompanyid])
GO
ALTER TABLE [dbo].[aHQPaymentVoucherSCDetails] CHECK CONSTRAINT [fk_aHQPaymentVoucherSCDetails_HQSalesCommisionHeader]
GO
/****** Object:  ForeignKey [fk_serCallBkhStatusId]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losCallBookingHeader]  WITH CHECK ADD  CONSTRAINT [fk_serCallBkhStatusId] FOREIGN KEY([serCallBkhcompanyid], [serCallBkhStatusId])
REFERENCES [dbo].[aservicestatus] ([serstatuscompanyid], [serStatusID])
GO
ALTER TABLE [dbo].[losCallBookingHeader] CHECK CONSTRAINT [fk_serCallBkhStatusId]
GO
/****** Object:  ForeignKey [FK_CashBox_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[CashBox]  WITH CHECK ADD  CONSTRAINT [FK_CashBox_aShops] FOREIGN KEY([CBShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[CashBox] CHECK CONSTRAINT [FK_CashBox_aShops]
GO
/****** Object:  ForeignKey [FK_losStockVerificationHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losStockVerificationHeader]  WITH CHECK ADD  CONSTRAINT [FK_losStockVerificationHeader_aShops] FOREIGN KEY([svhShopId])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losStockVerificationHeader] CHECK CONSTRAINT [FK_losStockVerificationHeader_aShops]
GO
/****** Object:  ForeignKey [FK_LOsShopDamageClearingHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LOsShopDamageClearingHeader]  WITH CHECK ADD  CONSTRAINT [FK_LOsShopDamageClearingHeader_aShops] FOREIGN KEY([dchShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LOsShopDamageClearingHeader] CHECK CONSTRAINT [FK_LOsShopDamageClearingHeader_aShops]
GO
/****** Object:  ForeignKey [fk_loslocationgroup_acompanymaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LoslocationGroup]  WITH CHECK ADD  CONSTRAINT [fk_loslocationgroup_acompanymaster] FOREIGN KEY([Lgcompanyid])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[LoslocationGroup] CHECK CONSTRAINT [fk_loslocationgroup_acompanymaster]
GO
/****** Object:  ForeignKey [fk_loslocationgroup_ashops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[LoslocationGroup]  WITH CHECK ADD  CONSTRAINT [fk_loslocationgroup_ashops] FOREIGN KEY([Lgshopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LoslocationGroup] CHECK CONSTRAINT [fk_loslocationgroup_ashops]
GO
/****** Object:  ForeignKey [FK_aHpReceiptVoucherHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHpReceiptVoucherHeader]  WITH CHECK ADD  CONSTRAINT [FK_aHpReceiptVoucherHeader_aCompanyMaster] FOREIGN KEY([hprhCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aHpReceiptVoucherHeader] CHECK CONSTRAINT [FK_aHpReceiptVoucherHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_aHpReceiptVoucherHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[aHpReceiptVoucherHeader]  WITH CHECK ADD  CONSTRAINT [FK_aHpReceiptVoucherHeader_aShops] FOREIGN KEY([hprhShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[aHpReceiptVoucherHeader] CHECK CONSTRAINT [FK_aHpReceiptVoucherHeader_aShops]
GO
/****** Object:  ForeignKey [FK_ashopsercategory_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ashopsercategory]  WITH CHECK ADD  CONSTRAINT [FK_ashopsercategory_aShops] FOREIGN KEY([sshopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[ashopsercategory] CHECK CONSTRAINT [FK_ashopsercategory_aShops]
GO
/****** Object:  ForeignKey [FK_ashopprintmessages_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[ashopprintmessages]  WITH CHECK ADD  CONSTRAINT [FK_ashopprintmessages_aShops] FOREIGN KEY([shopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[ashopprintmessages] CHECK CONSTRAINT [FK_ashopprintmessages_aShops]
GO
/****** Object:  ForeignKey [fk_losreplacereceiveheader_areprecvendorheader]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacereceiveheader]  WITH CHECK ADD  CONSTRAINT [fk_losreplacereceiveheader_areprecvendorheader] FOREIGN KEY([reprechcompanyid], [reprechqreceiveid])
REFERENCES [dbo].[areprecvendorheader] ([rrvhcompanyid], [rrvhreceiveid])
GO
ALTER TABLE [dbo].[losreplacereceiveheader] CHECK CONSTRAINT [fk_losreplacereceiveheader_areprecvendorheader]
GO
/****** Object:  ForeignKey [FK_losreplacereceiveheader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[losreplacereceiveheader]  WITH CHECK ADD  CONSTRAINT [FK_losreplacereceiveheader_aShops] FOREIGN KEY([reprechshopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losreplacereceiveheader] CHECK CONSTRAINT [FK_losreplacereceiveheader_aShops]
GO
/****** Object:  ForeignKey [FK_mosGoodsRequestHeader_aShops]    Script Date: 04/16/2012 10:32:36 ******/
ALTER TABLE [dbo].[mosGoodsRequestHeader]  WITH CHECK ADD  CONSTRAINT [FK_mosGoodsRequestHeader_aShops] FOREIGN KEY([GRHshopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[mosGoodsRequestHeader] CHECK CONSTRAINT [FK_mosGoodsRequestHeader_aShops]
GO
/****** Object:  ForeignKey [FK_mesRequesttoShopHeader_aShops]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[mesRequesttoShopHeader]  WITH CHECK ADD  CONSTRAINT [FK_mesRequesttoShopHeader_aShops] FOREIGN KEY([SRHshopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[mesRequesttoShopHeader] CHECK CONSTRAINT [FK_mesRequesttoShopHeader_aShops]
GO
/****** Object:  ForeignKey [FK_mesRequesttoShopHeader_aShops1]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[mesRequesttoShopHeader]  WITH CHECK ADD  CONSTRAINT [FK_mesRequesttoShopHeader_aShops1] FOREIGN KEY([SRHtoShopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[mesRequesttoShopHeader] CHECK CONSTRAINT [FK_mesRequesttoShopHeader_aShops1]
GO
/****** Object:  ForeignKey [fk_lossettings_ashops]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[LOsSettings]  WITH CHECK ADD  CONSTRAINT [fk_lossettings_ashops] FOREIGN KEY([ShopId])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[LOsSettings] CHECK CONSTRAINT [fk_lossettings_ashops]
GO
/****** Object:  ForeignKey [FK_losfuturetabheader_aShops]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[losfuturetabheader]  WITH CHECK ADD  CONSTRAINT [FK_losfuturetabheader_aShops] FOREIGN KEY([futhshopid])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losfuturetabheader] CHECK CONSTRAINT [FK_losfuturetabheader_aShops]
GO
/****** Object:  ForeignKey [FK_losWarrentyClaimHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[losWarrentyClaimHeader]  WITH CHECK ADD  CONSTRAINT [FK_losWarrentyClaimHeader_aCompanyMaster] FOREIGN KEY([wchCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[losWarrentyClaimHeader] CHECK CONSTRAINT [FK_losWarrentyClaimHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_losWarrentyClaimHeader_aShops]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[losWarrentyClaimHeader]  WITH CHECK ADD  CONSTRAINT [FK_losWarrentyClaimHeader_aShops] FOREIGN KEY([wchShopID])
REFERENCES [dbo].[aShops] ([ShopID])
GO
ALTER TABLE [dbo].[losWarrentyClaimHeader] CHECK CONSTRAINT [FK_losWarrentyClaimHeader_aShops]
GO
/****** Object:  ForeignKey [FK_losEDIConfirmation_losEDIRequest]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[losEDIConfirmation]  WITH CHECK ADD  CONSTRAINT [FK_losEDIConfirmation_losEDIRequest] FOREIGN KEY([ecshopid], [ecediid])
REFERENCES [dbo].[losEDIRequest] ([ershopid], [erediid])
GO
ALTER TABLE [dbo].[losEDIConfirmation] CHECK CONSTRAINT [FK_losEDIConfirmation_losEDIRequest]
GO
/****** Object:  ForeignKey [FK_ExchangeRateHistoryHeader]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[ExchangeRateHistoryHeader]  WITH CHECK ADD  CONSTRAINT [FK_ExchangeRateHistoryHeader] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[ExchangeRateHistoryHeader] CHECK CONSTRAINT [FK_ExchangeRateHistoryHeader]
GO
/****** Object:  ForeignKey [fk_aaccrepgroup_acompanymaster]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aaccrepgroup]  WITH CHECK ADD  CONSTRAINT [fk_aaccrepgroup_acompanymaster] FOREIGN KEY([companyid])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aaccrepgroup] CHECK CONSTRAINT [fk_aaccrepgroup_acompanymaster]
GO
/****** Object:  ForeignKey [fk_aaccrepformat_acompanymaster]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aaccrepformat]  WITH CHECK ADD  CONSTRAINT [fk_aaccrepformat_acompanymaster] FOREIGN KEY([companyid])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aaccrepformat] CHECK CONSTRAINT [fk_aaccrepformat_acompanymaster]
GO
/****** Object:  ForeignKey [FK_aHpProcessingHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aHpProcessingHeader]  WITH NOCHECK ADD  CONSTRAINT [FK_aHpProcessingHeader_aCompanyMaster] FOREIGN KEY([hphCompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aHpProcessingHeader] CHECK CONSTRAINT [FK_aHpProcessingHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_ExchangeRate_aCompanyMaster]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[ExchangeRate]  WITH CHECK ADD  CONSTRAINT [FK_ExchangeRate_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[ExchangeRate] CHECK CONSTRAINT [FK_ExchangeRate_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_aCountryMaster_aCompanyMaster]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aCountryMaster]  WITH CHECK ADD  CONSTRAINT [FK_aCountryMaster_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aCountryMaster] CHECK CONSTRAINT [FK_aCountryMaster_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_aAccRatioGroupMaster_aCompanyMaster]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aAccRatioGroupMaster]  WITH CHECK ADD  CONSTRAINT [FK_aAccRatioGroupMaster_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aAccRatioGroupMaster] CHECK CONSTRAINT [FK_aAccRatioGroupMaster_aCompanyMaster]
GO
/****** Object:  ForeignKey [fk_asalespersonmaster_acompanymaster]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[AsalesPersonmaster]  WITH CHECK ADD  CONSTRAINT [fk_asalespersonmaster_acompanymaster] FOREIGN KEY([Companyid])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[AsalesPersonmaster] CHECK CONSTRAINT [fk_asalespersonmaster_acompanymaster]
GO
/****** Object:  ForeignKey [fk_aletterformat_companyid]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aletterformat]  WITH CHECK ADD  CONSTRAINT [fk_aletterformat_companyid] FOREIGN KEY([companyid])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aletterformat] CHECK CONSTRAINT [fk_aletterformat_companyid]
GO
/****** Object:  ForeignKey [FK_aFinancialYear_aCompanyMaster]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aFinancialYear]  WITH CHECK ADD  CONSTRAINT [FK_aFinancialYear_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aFinancialYear] CHECK CONSTRAINT [FK_aFinancialYear_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_loaInhousePurchaseHeader_aCompanyMaster]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[loaInhousePurchaseHeader]  WITH CHECK ADD  CONSTRAINT [FK_loaInhousePurchaseHeader_aCompanyMaster] FOREIGN KEY([iphCompanyId])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[loaInhousePurchaseHeader] CHECK CONSTRAINT [FK_loaInhousePurchaseHeader_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_aGroupMaster_aCompanyMaster]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aGroupMaster]  WITH CHECK ADD  CONSTRAINT [FK_aGroupMaster_aCompanyMaster] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[aCompanyMaster] ([CompanyID])
GO
ALTER TABLE [dbo].[aGroupMaster] CHECK CONSTRAINT [FK_aGroupMaster_aCompanyMaster]
GO
/****** Object:  ForeignKey [FK_aGroupMaster_aGroupMaster]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[aGroupMaster]  WITH CHECK ADD  CONSTRAINT [FK_aGroupMaster_aGroupMaster] FOREIGN KEY([ParentGroupID], [CompanyID])
REFERENCES [dbo].[aGroupMaster] ([GroupID], [CompanyID])
GO
ALTER TABLE [dbo].[aGroupMaster] CHECK CONSTRAINT [FK_aGroupMaster_aGroupMaster]
GO
/****** Object:  ForeignKey [fk_hqsalescommisiondetail_hqsalescommisionheader]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[hqSalesCommisiondetail]  WITH CHECK ADD  CONSTRAINT [fk_hqsalescommisiondetail_hqsalescommisionheader] FOREIGN KEY([scdCommisionID], [scdcompanyid])
REFERENCES [dbo].[hqSalesCommisionHeader] ([schCommisionid], [schcompanyid])
GO
ALTER TABLE [dbo].[hqSalesCommisiondetail] CHECK CONSTRAINT [fk_hqsalescommisiondetail_hqsalescommisionheader]
GO
/****** Object:  ForeignKey [FK_Fb_processrecipedetail_Fb_processdetail1]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[Fb_processrecipedetail]  WITH CHECK ADD  CONSTRAINT [FK_Fb_processrecipedetail_Fb_processdetail1] FOREIGN KEY([fb_pr_companyid], [fb_pr_outletid], [fb_pr_Processid], [fb_pr_processdetailid])
REFERENCES [dbo].[Fb_processdetail] ([fb_pd_companyid], [fb_pd_outletid], [fb_pd_processid], [fb_pd_processdetailid])
GO
ALTER TABLE [dbo].[Fb_processrecipedetail] CHECK CONSTRAINT [FK_Fb_processrecipedetail_Fb_processdetail1]
GO
/****** Object:  ForeignKey [FK_losTenantUtilityBillDetail_losTenantServiceBillHeader]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[losTenantUtilityBillDetail]  WITH CHECK ADD  CONSTRAINT [FK_losTenantUtilityBillDetail_losTenantServiceBillHeader] FOREIGN KEY([utdBillId], [utdShopId], [utdCompanyId])
REFERENCES [dbo].[losTenantServiceBillHeader] ([tbhBillId], [tbhShopId], [tbhCompanyId])
GO
ALTER TABLE [dbo].[losTenantUtilityBillDetail] CHECK CONSTRAINT [FK_losTenantUtilityBillDetail_losTenantServiceBillHeader]
GO
/****** Object:  ForeignKey [FK_losTenantServiceBillDetail_losTenantServiceBillHeader]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[losTenantServiceBillDetail]  WITH CHECK ADD  CONSTRAINT [FK_losTenantServiceBillDetail_losTenantServiceBillHeader] FOREIGN KEY([tbdBillId], [tbdShopId], [tbdCompanyId])
REFERENCES [dbo].[losTenantServiceBillHeader] ([tbhBillId], [tbhShopId], [tbhCompanyId])
GO
ALTER TABLE [dbo].[losTenantServiceBillDetail] CHECK CONSTRAINT [FK_losTenantServiceBillDetail_losTenantServiceBillHeader]
GO
/****** Object:  ForeignKey [FK_Fb_kotdetails_FB_Dishdetails]    Script Date: 04/16/2012 10:32:37 ******/
ALTER TABLE [dbo].[Fb_kotdetails]  WITH CHECK ADD  CONSTRAINT [FK_Fb_kotdetails_FB_Dishdetails] FOREIGN KEY([fb_kd_Companyid], [fb_kd_dishid])
REFERENCES [dbo].[FB_Dishdetails] ([fb_dd_companyid], [fb_dd_dishid])
GO
ALTER TABLE [dbo].[Fb_kotdetails] CHECK CONSTRAINT [FK_Fb_kotdetails_FB_Dishdetails]
GO

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

Go

--exec Create_Login 'admin'
/****** Object:  Login [admin]    Script Date: 06/01/2012 11:29:40 ******/
IF  EXISTS (SELECT * FROM sys.server_principals WHERE name = N'admin')
DROP LOGIN [admin]
GO

CREATE LOGIN [admin] WITH PASSWORD=N'fiesadmin003', DEFAULT_DATABASE=[adminv2], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF

Go

--CREATE LOGIN admin 
--    WITH PASSWORD = 'fiesadmin003';
/*USE adminv2;
CREATE USER admin FOR LOGIN admin;*/

Go

sp_changedbowner admin

Go

/*exec sp_addrolemember N'db_owner', N'admin'*/

Go
---------- Default table values insertion


-------------------------[aInterface] START----------------------------------------------
DELETE FROM [adminv2].[dbo].[aInterface]

Go

INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1,'Country','hqadm',0,1,null,newid(),'')
Go
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2,'City','hqadm',0,1,null,newid(),'')
Go
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (3,'Department','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (4,'Currency','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5,'Group','accp',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1501,'Arrival To Shop','poscbRF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1001,'Goods Arrival','inv',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1002,'Despatch To Shop','inv',1,1,null,newid(),'D')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1503,'Goods Request To HQ','poscbRF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2001,'Purchase Order','P&C',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2005,'Dispatch statement to Godown','P&C',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2006,'Dispatch Statement Processing','P&C',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2004,'Costing','P&C',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2008,'Goods Issue Note Processing','P&C',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1005,'Godown Stock Verification','inv',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1509,'Stock Verification','poscbRF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1505,'Receipt','poscbRF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1507,'Goods Request To Shop','poscbRF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1510,'Damaged Goods Clearing','poscbRF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1512,'Goods Return Note','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1006,'Damage Clearing','INV',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1514,'Proforma Invoice','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1007,'Opening Stock Entry','inv',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1602,'Transfer In','poscbRF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1003,'Godown Stock Writeoff','INV',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1515,'Quotation','poscbRF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5001,'Bills','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5003,'Fixed Assets','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5005,'Payments','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (4001,'Exchange Rate','accp',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1603,'Despatch from shop to godown','poscbRF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (22,'Year Ending','acc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (502,'Shop Item Detail','pascbmlrf',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (504,'BackUp','adm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (26,'Settings','accp',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (10000,'Reports','acc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6,'Account','accp',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7,'Customer','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8,'Vendor','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (9,'Godown','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (10,'Shop','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (11,'Item','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (12,'Packing Type','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (13,'Item Category','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (14,'Customs','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (15,'Unit','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (16,'Color','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (17,'Size','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (19,'Financial Year','accp',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1601,'Transfer Out','poscbRF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1502,'Point of Sales','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2002,'Quotation','P&C',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2007,'Goods Issue Note Generation','P&C',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1004,'Despatch To Godown','inv',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1504,'Invoice for credit sales','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1506,'Petty cash Payments','poscbRF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1508,'Stock Writeoff','poscbRF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1511,'Local Purchase','poscbRF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1513,'Purchase Order','poscbRF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2003,'HQ Bills','P&C',1,1,null,newid(),'')
Go
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5002,'Contra','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5004,'Journal','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5006,'Receipts','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (501,'Godown Item Detail','invadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (503,'Users','adm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (505,'Restore','adm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5007,'Service Invoice','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (506,'Opening Stock Entry','invadm',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (507,'Stock Closing','invadm',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (508,'Prefix','invadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (509,'Settings','invadm',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (510,'Bar Code Printing','invadm',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (701,'Users','pascbmlr',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (702,'BackUp','pascmlr',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (703,'Restore','pascmlr',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (704,'Stock Closing','pascbmr',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (705,'Prefix','pascbmlr',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (706,'Settings','pascbmlr',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5008,'Special Invoice - Cash','poscbr',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5009,'Special Despatch','inv',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (555,'Opening stock','pascbmrf',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (556,'Despatchwise Barcode','invadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (557,'Selling price fixation','pascbmr',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (27,'Selling Price Fixation','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (30,'Change Package Date','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5010,'Debit/Credit Note','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1516,'Service Invoice','poscbmr',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1517,'Credit / Debit Note','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (50,'Post Ledgers','acc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1518,'Goods Exchange','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1604,'Shop Recovery','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1606,'Shop Reports','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (558,'Non Restricted Items','pascbmr',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (511,'Bar Code Printing','pascbmr',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5011,'Customer Settlement','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6001,'Opening Bills','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6006,'Opening Receipts','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (51,'Bank/Cash Details','sacc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (52,'Report Format','acc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1008,'Godown Recovery','inv',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1009,'Item splitting','inv',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2009,'Distribute/Writeoff','p&c',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1605,'Reports','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5012,'Vendor Settlement','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6005,'Opening Payments','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6007,'Opening Service Invoice','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2010,'Item Splitting Costing','P&C',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (31,'Cash Account Details','accp',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5013,'Shipment Projected Expenses','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2011,'Local Purchase Costing','P&C',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6008,'Opening Balance Entry','sacc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (53,'Bank Reconcilation','sacc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (55,'Opening Stock Costing','sacc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (54,'Freeze Opening Balance','sacc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2012,'Cancel Shop Transactions','sacc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (33,'Distributor','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (3000,'Employee Master','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (56,'Logging in to unclosed financial year','sacc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1801,'Estimaion/Inspection','pocR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (100,'Service Category Master','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1805,'Complaint Register','pocR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1802,'Service Booking Invoice - Cash','pocR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1803,'ReplacementRequest','pocR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1804,'Replacment Receive','pocR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (32,'Sales Person','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2013,'Item Analysis','P&C',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (101,'Service Master','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (102,'Condition Master','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (34,'Brand','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (559,'Free Items','pascbmr',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (3016,'Adjustment Entry','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1806,'Service Processing','pocR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1807,'Service Booking','pocR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1809,'Maintenance Contract','pocR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (999,'Power Users','sacc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (40,'Control Account Settings','accp',0,1,null,newid(),'')
Go
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5014,' Forex','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (60,'Alerts','acc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2014,'Replacement Request to Vendor','P&C',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2015,'Purchase Returns','P&C',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5015,'Depereciation','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5016,'SalesCommision','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5017,'AssetTransfer','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1519,'Re-exposrt Invoice','pobR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1608,'Delivery Note','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1520,'Purchase Request','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8002,'TargetFixation','bgt',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8003,'BudgetUtilization','bgt',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2016,'Replacement Receipt from Vendor','P&C',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5018,'Asset Disposal','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8001,'BudgetAllocation','bgt',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8004,'TargetAchieved','bgt',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2201,'Budget','bgt',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1522,'EDIApproval','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1810,'StandByMachines','pocR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1523,'Rebate Request','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1811,'StandByIssue','pocR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1525,'Tools Allocation','poscR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2020,'Customer Enquiry','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2021,'Forward Costing','sacc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1011,'asset Conversion','inv',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1526,'Consumption','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90001,'Department','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90003,'Deduction','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90005,'Savings','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90007,'Grade','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90009,'Employee','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90011,'Users','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90013,'Settings','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90015,'formula','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90017,'Currency','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90019,'Calendar','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90021,'Reimbursementmaster','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91001,'Loans Issue','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91003,'Department Transfer','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91005,'Leave Application','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91007,'Monthly Entry','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91011,'Loan Repayment','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91014,'Reports','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91017,'Facilty Tracking','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91019,'Asset Tracking','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91021,'Reimbursement','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91023,'Wisa - Work Permit','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91025,'Employee Performance','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91027,'Document Master','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91029,'DailyAttendanceRegister','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91031,'Employee Training','pay',1,1,null,newid(),'')
Go
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91033,'Reimbursement Limit','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91035,'Advance Issue','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (61,'Segments','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2000,'Purchase Request To Vendor','p&c',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2202,'Target','bgt',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1521,'EDI Request','PoscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1524,'Rebate Approval','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1812,'StandByReceipt','pocR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1808,'Tools Return','pocR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1010,'Purchase Return','inv',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5019,'Vacancy Request Accounts','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90002,'Allowance','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90004,'Loans','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90006,'Leaves','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90008,'Designation','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90010,'Change Password','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90012,'Prefix','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90014,'Memo','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90016,'Country','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90018,'Facility','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90020,'City','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90022,'Hardcodes','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91002,'Open Savings','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91004,'Grade Change','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91006,'Leave Cancellation','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91010,'PayRoll Processing','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91013,'Memo Issue','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91016,'Interview','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91018,'Job Application','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91020,'Leave Encashment','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91022,'Vacancy','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91024,'Payment Tracking','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91026,'Loan Application','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91028,'Advance Application','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91030,'Employee Exit','pay',1,1,null,newid(),'')
Go
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91032,'Handover Notes','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91034,'Company Work Time Settings','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92000,'Denomination','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91036,'Savings Details','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2019,'Reports','P&C',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (90023,'Employee Leaves','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1527,'Cusomer Purchase Order','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1528,'Location Verification','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1609,'Sales Out','poscR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1530,'Expiry Verification','inv',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2022,'Purchase order status','p&c',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5020,'Sales Promotion','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (105,'Agreement Register','admin',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (103,'Incoming Documents','admin',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (104,'Outgoing Documents','admin',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (106,'Administration Reports','admin',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (62,'Letter Format','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2500,'Clearence Request','pom',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2504,'Handling Debit Note','pom',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2508,'Medical Details','pom',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2511,'Boat Note Confirmation','pom',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2502,'Local Clearence Request','pom',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2505,'Boat Note Processing','pom',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2509,'Passport Details','pom',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (57,'Item Rate Editing','sacc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5022,'Government Loan/Fee','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2303,'Tenant Register','pol',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1815,'Packing List','pobRR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2024,'Facility Tracking','pol',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8009,'Trigger Merging in Locations','P&C',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1814,'Booking Cancell','pocRR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (109,'Rate Master','hqadm',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1610,'Purchases In','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1529,'Expiry Verification','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1531,'Location  Verification','inv',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5021,'Commision Invoice','pom',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2506,'Co-Mail Register','pom',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2510,'Work Permit/Visa','pom',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2501,'Clearence','pom',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2503,'Local Purchase Order','pom',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2507,'Ticketing','pom',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (110,'Service Master','hqadm',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1818,'Re-export Order','pobRR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1817,'Re-export Quotation','pobRR',1,1,null,newid(),'')
Go
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2023,'Facility Booking','pol',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8010,'Budget Accounts Entry','bgt',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2025,'Facility Tracking Check Out','pol',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7001,'Pos Alerts','poalt',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91037,'Payroll Accounts Linking','pay',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5025,'Return After Despatch','poscbr',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5023,'Special Invoice - Credit','poscbr',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2512,'Lead Time Stage/Divisions','accp',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2513,'Lead Time Entry','p&c',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8011,'Purchase and Sales Entry','p&c',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8012,'Fixed Cost','p&c',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8013,'EOQ Processing','p&c',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1012,'Enquiry','inv',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (112,'Asset handling','hqadm',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8007,'Item Merging','posRR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8005,'Budget Reports','bgt',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1816,'Re-export Request','pobRR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (111,'Apartment Details','pal',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2026,'Enquiry','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1813,'Estimation Approval','pocRR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (108,'Utility Master','hqadm',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2301,'Reservation','pol',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2018,'Enquiry','P&C',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2302,'Agreement','pol',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8006,'Item Merging','P&C',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8008,'Item Merging','Inv',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2304,'Room Billing','pol',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1819,'Keg Return','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (63,'Ratio Analysis Master','acc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (113,'Apartment Checkout','pol',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2305,'Utility Billing','pol',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1532,'POS Cash Denomination','poscbRRF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (107,'Faclity Master','hqadm',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (91038,'Payroll Accounts Linking Settings','pay',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1611,'Inter Division Sales Request','poscbr',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1820,'Service Booking Invoice - Credit','poc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5024,'Return Before Despatch','poscbr',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (20,'Parent Item Category','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (35,'Counter','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (64,'UserGroup','adm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (65,'Customer Group','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (66,'Vendor Group','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (67,'Brand Merge','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (68,'ParentItem Category Merge','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (69,'Item Category Merge','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (70,'Container','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (71,'Vessel','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (72,'Contacts','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (73,'Pos Message','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (74,'Enquiry','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (75,'Cancel Shop Transactions','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (76,'Shop Settings','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (77,'Cheque Details','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (78,'FeeMaster','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (114,'Item Image','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (115,'Update User Groups','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1013,'Total Stock Verification','inv',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1607,'Counter Reports','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1900,'Special Invoice Quotation','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2027,'Insert Queries','p&c',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2028,'Item Details','p&c',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2029,'Transaction Flow','p&c',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2031,'Customer Details','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5026,'Dummy Pos','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5027,'Item Image','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5028,'Set WallPaper','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6100,'Contact','CRM',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6101,'Account','CRM',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6102,'Activity','CRM',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6103,'Case','CRM',0,1,null,newid(),'')
Go
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6104,'Leads','CRM',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6106,'MIS','CRM',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6107,'DashBoard','CRM',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6200,'Cards','LMS',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7500,'HPItemDetails','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7501,'HP Quotation','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7502,'HPReceipts','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7503,'HP Processing','acc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7504,'HP Invoice','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7505,'HP Application','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7507,'HP DummyQuotation','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7508,'HP PD Cheque Register','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7509,'HP Agreement','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7510,'HP MC Transfer','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7511,'HP Payment','acc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7514,'HP Island','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7516,'HP Application','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7517,'Petty Cash Payments','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7518,'HP ChequeStatus','acc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7519,'HP Fee Payments ','acc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7520,'HP ReSales ','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8014,'PO Satus','p&c',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8015,'Item Image','p&c',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8016,'Item Image','inv',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8017,'Market Rate','p&c',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8018,'Post Dated Cheques Details','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8020,'Recurring Payments','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8021,'Credit Chasing','acc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1901,'Purchase Return','poscbr',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1902,'Price Level','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (708,'Shop Price Levels','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1903,'WarrentyClaim','poscbr',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2514,'Pre-Purchase Order','p&c',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (36,'Shift','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (2030,'Update Vendor Items','p&c',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6105,'Oppertunity','CRM',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6201,'CardRegistration','LMS',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7506,'HP Item Registration','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7512,'HP Recipts ','acc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7513,'HP Atoll','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7515,'HP Repossession ','poscbr',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8019,'Voucher tracking','acc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1904,'BussinessPromotion','poscbr',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8022,'List Item','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8023,'Kit Item','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8031,'Pos Date Edit','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7522,'ShopSerialNOVerification ','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (7523,'GodownSerialNoVerification ','inv',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8032,'In-house Purchase','P&C',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (116,'Service Status Master','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (10002,'Quick Item Inquiry','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (10003,'Quick Item Inquiry','P&C',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6108,'Quotation','CRM',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8034,'Bank Details','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (10006,'Re-initialize CRM contact','sacc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6111,'Emails','CRM',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6112,'UserHierarchy','CRM',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6113,'Custom Leads','CRM',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6114,'Settings','CRM',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (10005,'InHouse Return','poscbR',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92004,'Edit InhouseConsumption Account','ssur',0,1,null,newid(),'')
Go
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92006,'Verify InhouseConsumption','ssur',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6115,'CustomOppertunity','CRM',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (6116,'Enquiry','CRM',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92029,'Disable Amount Column in POS','ssur',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92031,'Confirm Business Promotion / Warranty Claim','ssur',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5030,'InterdivisionBill','acc',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (5029,'InterDivisionJournal','accp',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (8033,'Goods Request From Godown','inv',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92030,'Status','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (200,'Tax Category','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92007,'FlightOperator Master','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92028,'Special Discount','FAndB',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92022,'Voucher Master','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92023,'Till Header','PAF',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92017,'dish group','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92018,'Dish Sub group','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92019,'Dish Entry','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92020,'Recipe Entry','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92021,'Dish Entry Adds','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92024,'Dish    Segments','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92025,'SellingPrice DishSegment','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92026,'Manager User','FAndB',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92027,'Close Till','posF',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92008,'Flights','hqadm',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92009,'TillCurrentStatus','PAF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92010,'F & B Billing','posF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92011,'Dish Transfer In','posF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92012,'Dish Transfer Out','posF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92013,'KOT Order Entry','posF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92014,'Miscellanious Bill','posF',1,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92015,'Restaurant Table Entry','PAF',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92016,'Restaurant Cover Entry','PAF',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (10001,'LC Register Details','acc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (10004,'Bounced Cheque Details','acc',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1612,'Delivery Items Verification','poscbR',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (92032,'Un-Confirm Transactions','p&c',0,1,null,newid(),'')
INSERT INTO [adminv2].[dbo].[aInterface]   ([InterfaceID]  ,[InterfaceName]  ,[ModuleCode]  ,[PrefixNeeded]  ,[CompanyID]  ,[menuname]  ,[rowguid]  ,[customize])  VALUES (1541,'Shop Total Stock Verification','poscbR',1,1,null,newid(),'')
Go
-------------------------[aInterface] STOP----------------------------------------------

-------------------------[aTableColumns],[aTables] START----------------------------------------------
DELETE FROM [adminv2].[dbo].[aTableColumns]
DELETE FROM [adminv2].[dbo].[aTables]
Go
-------------------------[aTables] START----------------------------------------------

INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(78,'losserviceheader','Service Invoice','no comments',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(79,'Losreplacerequestheader','Replacement Request','Replacement Request',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(80,'losreplacereceiveheader','Replacement receive','losreplacereceiveheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(85,'losServiceBookingHeader','Booking','estimation booking',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(86,'losjobserviceheader','Job card','jobcardprocess',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(87,'Forex',' Foreign Exchange',' Foreign Exchange',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(90,'areprecvendorheader','areprecvendorheader','areprecvendorheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(95,'losdeliverynoteheader','losdeliverynoteheader','losdeliverynoteheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(103,'BudgetMaster','BudgetMaster','BudgetCreation',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(113,'losinquiryheader','losinquiryheader','losinquiryheader',1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(116,'posCosumption','posCosumption','posCosumption',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(98,'TargetFixationHeader','TargetFixationHeader','To fix the Various targets',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(100,'TargetCheckHeader','TargetChackHeader','To fix the Target Check',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(115,'InvAssetConversion','InvAssetConversion','InvAssetConversion',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(134,'losshipmentbnheader','Boat Note Processing','',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(135,'losdocument','Document Header','Document Header MOP',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(139,'losdocumentWorkPermit','WorkPermit Documents','WorkPermit Document MOP',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(154,'losfacilitybookingheader','losfacilitybookingheader','losfacilitybookingheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(156,'losfacilitytracking1','losfacilitytracking','losfacilitytracking',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(163,'losApartmentBillHeader','Room Billing','Room Billing',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(131,'ShipmentClearenceHeader','Clearence','Clearence',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(155,'losfacilitytracking','losfacilitytracking','losfacilitytracking',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(169,'loaFixedCostHeader','loaFixedCostHeader','Fixed Cost',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(6,'aPackingType','Packing Type','Packing Type',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(21,'LOaCostingHeader','Cost Fixing','Cost Fixing',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(36,'LosDummyReceiptHeader','LosDummyReceiptHeader','LosDummyReceiptHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(39,'LOStransferinheader','Lostransferinheader','Lostransferinheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(19,'aHQDespatchNoteMain','Despatch Note Generation','Despatch Note',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(57,'losposExchangeHeader','losposExchangeHeader','losposExchangeHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(59,'JournalTransHeader','JournalTransHeader','JournalTransHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(68,'loaItemsplitcostingHeader','Item Splitting','ItemSplit',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(93,'assettransfer','assettransfer','assettransfer',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(125,'iodocuments','For Documents in Admin Module','Documnets',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(142,'Faclitymaster','Faclitymaster','aservicemaster table using',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(151,'UtilityMaster','UtilityMaster','sam asservicemaster table',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(4,'aunit','Unit Master','Unit Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(47,'lospurchaseorderheader','lospurchaseorderheader','lospurchaseorderheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(76,'aproductconditionmaster','aproductconditionmaster','aproductconditionmaster',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(168,'LoaEoqprocessheader','LoaEoqProcessheader','EOQ Process',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(174,'aShiftMaster','Shift','Shift',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(191,'losHPCustomerDetails','Hp application Details','Save the cust details',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(192,'loshpReceiptHeader','Hire Purchase Receipts','Hire Purchase Receipts',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(196,'ahpPaymentHeader','HP Payment Header','HP Payment Header',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(204,'aFeeMaster','aFeeMaster','aFeeMaster',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(205,'ahpFeePaymentHeader','HP FeePayment Header','HP FeePayment Header',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(89,'loreplacereqtovendorheader','loreplacereqtovendorheader','loreplacereqtovendorheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(99,'BudgetCheckHeader','BudgetCheckHeader','To check the Targets Reached',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(118,'FixedAsset','FixedAsset','FixedAsset',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(122,'losExpiryVerificationHeader','losExpiryVerificationHeader','losExpiryVerificationHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(126,'losserestimateapproval','Estimation Approval','Estimation Approval',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(152,'Ratetypemaster','Ratetypemaster','same aservicemaster table',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(2,'acolor','Color Master','Color Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(3,'asize','Size Master','Size Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(35,'LosInvoiceHeader','LosInvoiceHeader','LosInvoiceHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(46,'mesTransferoutHeader a,mesRequesttoShopHeader b,ashops c','mesTransferoutHeader a,mesRequesttoShopHeader b,ashops c','mesTransferoutHeader a,mesRequesttoShopHeader b,ashops c',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(71,'adistributormaster','adistributormaster','adistributormaster',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(176,'aBrandMergeDetails','For Brand Merging','For Brand Merging',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(178,'aparentCategoryMergingDetails','For Parent Category Merging','For Parent Category Merging',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(195,'ahpAgreementDetail','HP Agreement','HP Agreement',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(199,'aIslandMaster','Island MAster','Ialnad Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(203,'aHqPettyCashPaymentHeader','aHqPettyCashPaymentHeader','aHqPettyCashPaymentHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(211,'LOsPurchaseReturnHeader','LOsPurchaseReturnHeader','LOsPurchaseReturnHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(212,'losWarrentyClaimHeader','WarrentyClaim','WarrentyClaim',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(213,'aListItemMaster','List Item','List Item',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(74,'aservicecategory','Service Category','Category of service',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(82,'AdjustmentHeader','Adjustment Entry Transaction','AdjustmentHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(91,'DepreciationHeader','Depreciationcalculation','Depreciation',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(105,'losEDIConfirmation','losEDIConfirmation','losEDIConfirmation',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(114,'Invpuchasereturn','Invpuchasereturn','Invpuchasereturn',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(117,'ASegmentMaster','ASegmentMaster','ASegmentMaster',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(120,'mesTransferoutHeader','mesTransferoutHeader','mesTransferoutHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(132,'losLocalClearenceRequestHeader','Local Clearence Request','Clearence Request',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(160,'losTenantServiceRegisterHeader','Tenant Register','Tenant Register',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(162,'LosTenantServiceBillHeader','LosTenantServiceBillHeader','LosTenantServiceBillHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(164,'losapartmentcheckout','losapartmentcheckout','losapartmentcheckout',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(129,'AgreementRegister','AgreementRegister','AgreementRegister',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(167,'LtimeHeader','Lead Time Entry','Lead Time',1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(8,'acountrymaster','Country Master','Country Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(13,'aGodown','Godown Master','Godown Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(15,'LOiArrivalHeader','Godown Goods Arrival','Godown',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(18,'LOsPosHeader','LOsPosHeader','LOsPosHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(23,'MEiGodownTransferHeader','MEiGodownTransferHeader','MEiGodownTransferHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(26,'aDepartmentMaster','Department Master','Department Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(29,'aCustomsMaster','Customs Master','Customs Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(30,'acity','City  Master','City Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(31,'LOiDamageClearingHeader','LOiDamageClearingHeader','LOiDamageClearingHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(38,'MEsDespatchtoGodownHeader','MEsDespatchtoGodownHeader','MEsDespatchtoGodownHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(48,'loiStockVerificationHeader','loiStockVerificationHeader','loiStockVerificationHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(32,'aitem','Items','Items',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(34,'LosGoodsReturnNoteHeader','Return Note Header','Return Note Header',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(45,'lopurchaseorderheader','lopurchaseorderheader','lopurchaseorderheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(50,'losStockVerificationHeader','losStockVerificationHeader','losStockVerificationHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(55,'losAccountsInvoiceHeader','losAccountsInvoiceHeader','losAccountsInvoiceHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(56,'losDebitCreditNote','losDebitCreditNote','LosDebitCreditNote',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(58,'contra','contra','contra',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(62,'Bills','Account Bills','Bills',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(65,'VendorSettlementHeader','','VendorSettlementHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(67,'LoiItemSplitHeader','Item Splitting','ItemSplit',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(70,'AsalesPersonmaster','Sales Person Master','Sales Person Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(83,'AdjustmentDetails','Adjustment Detail Transaction','AdjustmentDetails',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(92,'hqsalescommisionheader','SalesCommision','SalesCommision',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(107,'losrebaterequest','losrebaterequest','losrebaterequest',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(137,'losdocumentPassport','Passport Documents','Passport Document MOP',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(12,'aCurrencyMaster','Currency Master','Currency Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(28,'LosWriteoffHeader','LosWriteoffHeader','LosWriteoffHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(49,'mesRequesttoShopHeader,ashops','mesRequesttoShopHeader,ashops','mesRequesttoShopHeader,ashops',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(16,'MEiDespatchToShopHeader','Despatch To Shop','Despatch',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(73,'losCallBookingHeader','losservicebookingheader','servicebookings',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(173,'aCounterMaster','Counter','Counter',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(177,'aContainerMaster','Container Master','Container Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(183,'louserGroups','for user groups','for user groups',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(186,'aLoyaltyCardMaster','Loyalty Cards','Loyalty Cards',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(190,'vwHpItemRegistrationDetails','Item Registration','Item Registration',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(193,'loshpDummyQuotationHeader','HP Dummy Quotation Master','HP  DummyQuotation Details',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(200,'aDocumentTypeMaster','aDocumentTypeMaster','aDocumentTypeMaster',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(106,'losSerStandByRequestheader','losSerStandByRequestheader','losSerStandByRequestheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(109,'losSerStandByReceiptHeader','losSerStandByReceiptHeader','losSerStandByReceiptHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(130,'ClearenceRequestHeader','Clearence Request','Clearence Request',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(150,'Governloan','Government Fee and Loan','',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(1,'acustomscode','Customs Master','',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(9,'aPrefix','Prefix Name','Prefix Name',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(11,'aCustomerMaster','Customer Master','Customer Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(14,'aShops','Shop Master','Shop Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(41,'AHQPaymentVoucherHeader','AHQPaymentVoucherHeader','AHQPaymentVoucherHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(43,'mesRequesttoShopHeader',' mesRequesttoShopHeader',' mesRequesttoShopHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(60,'receiptvoucherheader','receiptvoucherheader','receiptvoucherheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(61,'exchangerate','exchangerate','exchangerate',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(175,'aUserGroups','For User Groups','For User Groups',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(182,'aContact','for Contacts','for Contacts',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(187,'aLoyaltyCardContactDetails','Loyalty Cards Contact Details','Loyalty Cards Contact Details',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(207,'aReccuringPaymentDetails','aReccuringPaymentDetails','aReccuringPaymentDetails',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(197,'ahpReceiptHeader','HP Receipt Header','HP Receipt Header',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(110,'lossertoolsallocationheader','lossertoolsallocationheader','lossertoolsallocationheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(102,'losrebateconfirmheader',' losrebateconfirmheader',' losrebateconfirmheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(104,'TargetMaster','TargetMaster','TargetCreation',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(119,'losLocationVerificationHeader','losLocationVerificationHeader','Location Verification',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(127,'HQSalesPromotionHeader','Sales Paromotion','Sales Promotion',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(133,'losLPHeader','Local Purchase Header','Local Purchase',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(140,'losBoatNoteConfirmHeader','Boat Note Confirmation','Boat Note Confirmation',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(165,'denominationheader','Denomination','',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(136,'losdocumentMedical','Medical Documents','Medical Document MOP',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(138,'losdocumentTicketing','Ticketing Documents','Ticketing Document MOP',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(157,'losApartmentAgreementHeader','Agreement','Agreement',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(159,'loskegreturnheader','loskegreturnheader','kegheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(161,'aHqMergingHeader','aHqMergingHeader','Merging',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(10,'aInterface','Interface Name','Interface Name',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(7,'aVendorMaster','Vendor Master','Vendor Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(24,'ausers','Users','Users',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(25,'lousers','Users','Users',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(27,'LoiWriteoffHeader','LoiWriteoffHeader','LoiWriteoffHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(37,'losLocalPurchaseHeader','losLocalPurchaseHeader','losLocalPurchaseHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(52,'meiSpecialDespatchtoShopHeader','meiSpecialDespatchtoShopHeader','meiSpecialDespatchtoShopHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(53,'DebitCreditNote','DebitCreditNote','DebitCreditNote',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(69,'loalocalpurchasecostingheader','Local Purchase Costing','Local Purchase',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(84,'losSerMaintenanceContractHeader','Maintenance Contract Header','Contract Header',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(112,'LosserToolsReturnHeader','LosserToolsReturnHeader','LosserToolsReturnHeader',1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(121,'Purchases IN','Purchases IN','Purchases IN',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(128,'losbookingcancellation','losbookingcancellation','losbookingcancellation',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(141,'lospackinglistheader','lospackinglist','',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(5,'aItemCategory','aItem Category Master',' aItem Category Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(40,'LosPaymentVoucherHeader','LosPaymentVoucherHeader','LosPaymentVoucherHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(75,'aservicemaster','Service Master','Service Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(77,'loscomplaints','Complaint Register','Complaint Register',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(166,'BudgetPlanHeader','BudgetPlanHeader','',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(172,'aParentItemCategory','Parent Item Category','ParentItemCategory',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(188,'aChequeReportDetails','aChequeReportDetails','aChequeReportDetails',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(189,'ahqPostDatedChequeDetails','ahqPostDatedChequeDetails','ahqPostDatedChequeDetails',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(210,'losSIQuotationHeader','losSIQuotationHeader','losSIQuotationHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(201,'loshpRepossessionHeader','HP Repossession','HP Repossession',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(202,'ahpItemTransferHeader','HP MC Transfer','HP Mc Transfer',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(72,'aletterformat','aletterformat','letterformats',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(81,'abrandmaster','brandmaster','table for keeping brand',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(88,'loPurchasereturnheader','loPurchasereturnheader','loPurchasereturnheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(94,'losexportheader','losexportheader','losexportheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(97,'BudgetAllocationHeader','BudgetAllocationHeader','To Handle the Budget Allocations',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(101,'losEDIRequest','losEDIRequest','losEDIRequest',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(108,'losSerStandByIssueHeader','losSerStandByIssueHeader','losSerStandByIssueHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(96,'AssetDisposalHeader','AssetDisposalHeader','To Handle Disposed Asset',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(123,'loiLocationVerificationHeader','loiLocationVerificationHeader','Godown Location Verification',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(124,'loiExpiryVerificationHeader','loiExpiryVerificationHeader','Expiry Date wise verification',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(153,'losReservationHeader','Reservation','Reservation',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(158,'ApartmentServiceMaster','ApartmentServiceMaster','same servicemaster',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(170,'budgetplanheaderacc','BudgetPlanHeader','',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(17,'LOsgoodsarrivaltoshopheader','Goods Arrival To Shop','Arrival to Shop',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(20,'aHQIssuenoteMain','Issue Note Generation To Shop','Issue Note Generation To Shop',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(33,'LOsShopDamageClearingHeader','LOsShopDamageClearingHeader','LOsShopDamageClearingHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(42,'mosGoodsRequestHeader','mosGoodsRequestHeader','mosGoodsRequestHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(22,'LOspPurchaseBillHeader','LOspPurchaseBillHeader','LOspPurchaseBillHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(51,'losSpecialInvoiceHeader','losSpecialInvoiceHeader','losSpecialInvoiceHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(54,'AccountsInvoiceHeader','AccountsInvoiceHeader','AccountsInvoiceHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(64,'CustomerSettlementHeader','','CustomerSettlementHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(66,'aaccrepformat','Report Format','P&LandBL',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(179,'aItemCategoryMergingDetails','For Item Category Merging','For Item Category Merging',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(180,'avesselmaster','Vessel Master','Vessel Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(185,'LOsPosdummyHeader','LOsPosdummyHeader','LOsPosdummyHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(194,'losHPChequeRegisterHeader','HP PD Cheque Register','HP PD Cheque Register',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(198,'aAtollMaster','Atoll MAster','Atoll Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(206,'losHpResaleHeader','HP Resale','HP Resale',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(214,'aKitItemMaster','Kit Item','Kit Item',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(217,'loPrePurchaseOrderHeader','loPrePurchaseOrderHeader','loPrePurchaseOrderHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(208,'losSerialNoVerificationHeader','losSerialNoVerificationHeader','losSerialNoVerificationHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(209,'loiSerialNoVerificationHeader','loiSerialNoVerificationHeader','loiSerialNoVerificationHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(218,'loaInhousePurchaseHeader','loaInhousePurchaseHeader','loaInhousePurchaseHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(219,'loaInhousePurchaseDetail','loaInhousePurchaseDetail','loaInhousePurchaseDetail',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(220,'aShopCustomerSetting','aShopCustomerSetting','aShopCustomerSetting',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(221,'aServiceStatus','Service Status','Service Status',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(247,'aBankMaster','Bank Detail','Bank Detail',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(245,'LOs_InHouseCons_ReturnHeader','LOs_InHouseCons_ReturnHeader','InHouseConsuption ReturnHeader',1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(246,'LOs_InHouseCons_ReturnDetail','LOs_InHouseCons_ReturnDetail','InHouseConsuption ReturnDetail',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(244,'MeiGodownRequestHeader','MeiGodownRequestHeader','MeiGodownRequestHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(232,'InterDivisionBillsHeader','InterDivisionBillsHeader','InterDivisionBillsHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(223,'aTaxCategoryMaster','Tax Category Master','Tax Category Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(225,'fb_resttablemaster','Restaurant Table  Entry','Restaurant Table  Entry',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(228,'fb_dishgroup','Dish Group','dish group',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(224,'FlightOperatorMaster','FlightOperator Master','FlightOperator Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(233,'fb_dishadds','Dish Adds','Dish Adds',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(234,'vouchermaster','Voucher Master','Voucher Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(235,'tillheader','Till Master','Till Master',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(241,'LOsPosFandBHeader','LOsPosFandBHeader','LOsPosFandBHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(236,'DishSegmentHeader','Dish Segment Master','Dish Segment',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(227,'Flights','Flights','Flights',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(237,'DishSegmentDetail','SellingPrice DishSegmentMaster','SellingPrice DishSegment',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(238,'TillCurrentStatus','Till Current Status','Till Current Status',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(229,'fb_dishsubgroup','Dish Sub Group','Dish Sub Group',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(226,'fb_resttable','Restaurant Cover  Entry','Restaurant Cover  Entry',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(230,'fb_dishdetails','Dish Details','Dish Details',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(222,'InterDivisionJournalTransHeader','InterDivisionJournalTransHeader','InterDivisionJournalTransHeader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(242,'aLCRegisterDetails','LC Register Details','LC Register Details',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(243,'aBouncedChequeDetails','Bounced Cheque Details','Bounced Cheque Details',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(239,'loshpInvoiceHeader','HP Quotation Master','HP Quotation Details',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(250,'aHpProcessingHeader','HpProcessingHeader','Hpprocessingheader',1,newid())
INSERT INTO [adminv2].[dbo].[aTables]  ([TableID],  [TableName]  ,[Description]  ,[Comments]  ,[Version1]  ,[rowguid])  VALUES(231,'fb_recipedetails','Recipe Details','Recipe Details',1,newid())
Go
-------------------------[aTables] STOP----------------------------------------------

-------------------------[aTableColumns] START----------------------------------------------

INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (45,2,'pono','pono','PO NO','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (45,4,'vendorname','vendorname','Vendor Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (70,2,'Spername','Sales Person Name','Sales Person Name','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (54,2,'Invoice No','InvoiceNo','InvoiceNo','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (121,1,'TIHID','TIHID','Purchase ID','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (38,3,'dghDate','dghDate','Despatch Date','Datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (8,2,'CountryName','Country Name','Country Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (21,3,'chcostingdate','costingdate','Date','date',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (22,1,'pbhBillID','pbhBillID','Bill ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (22,5,'pbhvendorBillNo','pbhVendorBillNo','Vendor Bill No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (22,6,'pohpono','puchaseorderno','Purchase Order No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (23,3,'gthDespatchdate','gthDespatchdate','Despatch Date','datetime',8,NULL,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (24,2,'username','User Name','User Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (27,2,'whno','whno','Writeoff No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (11,4,'faxno','Fax No','Fax No','',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (79,2,'repreqno','Request No','Request No','varchar',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (72,3,'Lettername','lettername','Letter Name','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (73,1,'serbookhid','bookingid','Booking ID','int',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (73,2,'serbookhno','BookingNo','Booking No','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (73,3,'serbookhdate','BookingDate','Booking Date','datetime',11,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (74,3,'sercatname','Categoryname','Category Name','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (75,4,'sercatname','sercatname','Service Category','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (76,1,'prodcndid','prodcndid','Conditoinid','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (76,3,'prodcndname','prodcndname','Condition Name','varchar',100,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (77,5,'cmpcancelled','Cancelled','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (78,2,'serinvno','Process No','Invoice No','varchar',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (78,3,'serinvhDate','Process Date','Invoice Date','datetime',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (78,4,'serinvhprocno','Invoice No','Process No','varchar',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (79,6,'repreqhcancelled','Cancelled','Cancelled','varchar',5,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (80,1,'reprechid','Receipt ID','Receipt ID','int',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (80,3,'reprechdate','Receipt Date','Receipt Date','datetime',11,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (80,4,'reprechremark','Remark','Remark','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (80,5,'reprechcancelled','Cancelled','Cancelled','bit',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (69,2,'lpchcostingno','Costing No','Costing No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (69,3,'lpchdate','Costing Date','Costing Date','Date',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (69,4,'lpchShopid','Shop Name','Shop Name','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (69,5,'lphBillNo','Bill No','Bill No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (69,6,'lphBillAmount','Bill Amount','Bill Amount','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (69,7,'lpchCancelled','Cancelled','Cancelled','bit',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (72,2,'lettercode','lettercode','Letter Code','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (73,4,'serbookhrecvdfrom','Customername','Customer Name','varchar',40,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (73,5,'serbookconfirmed','Confirmed','Confirmed','bit',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (73,6,'serbookhcancelled','Cancelled','Cancelled','bit',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (74,2,'sercatcode','Categorycode','Category Code','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (75,3,'sername','sername','Service Name','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (131,1,'ClearenceID','id','Clearence ID','int',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (76,2,'prodcndcode','prodcndcode','Condition Code','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (76,4,'sercatname','sercatname','Service Category','varchar',100,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (77,4,'cmpcustomername','Customer name','Complained by','varchar',100,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (78,5,'serinvhprocdate','Invoice Date','Process Date','datetime',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (78,6,'serbookhInspectionNo','Inspection No','Inspection No','varchar',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (78,7,'recfrom','Received From','Received From','varchar',40,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (85,7,'serbookhcancelled','Cancelled','Cancelled','bit',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (79,3,'repreqhdate','Request Date','Request Date','datetime',11,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (79,5,'repreqhremarks','Remarks','Remarks','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (80,2,'reprechno','Receipt No','Receipt No','varchar',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (113,1,'ihid','ihid','ihid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (114,1,'whid','whid','Purchase Return ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (142,1,'serid','serid','serid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (82,1,'Adjustmentid','AdjustmentId','AdjustmentId','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (81,1,'Brandid','Brandid','BrandId','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (81,2,'BrandName','BrandName','Brand Name','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (82,2,'AdjustmentNo','Adjustment No','AdjustmentNo','varchar',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (82,3,'AdjustmentDate','Adjustment Date','Adjustment Date','datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (82,4,'Posted','Posted','Posted','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (78,9,'serinvcancelled','Cancelled','Cancelled','bit',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (85,8,'serbookhposted','Posted','Posted','bit',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (19,6,'ConfirmFinished','To make the Transaction Finished','Confirmed','Bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (20,7,'ConfirmFinished','To make the Transaction finished','Confirmed','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (86,3,'recfrom','recfrom','Received From','varchar',40,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (16,7,'dhTransFinished','To confirm Finish','Confirmed','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (23,6,'gthTransFinished','To Make  Confirm Finished','Confirmed',' bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (86,5,'serbookhInspectionNo','Inspection No','Inspection No','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (78,8,'serbookhno','Booking No','Booking No','varchar',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (46,6,'TOHTransfinished','To Confirm Finished','Confirmed','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (42,6,'grhTransFinished','TO Confirm Finish','Confirmed','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (49,9,'SRHTransfinished','To Confirm Finished','Confirmed','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (38,6,'dghTransFinished','To Confirm Finished','Confirmed','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (86,7,'serinvhcancelled','Cancelled','Cancelled','bit',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (49,7,'srhUsed','Used','Used','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (87,1,'forexid','Forex Id','Forex Id','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (84,1,'mchNo','contract header','Contract No','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (87,3,'forexdate  ','forexdate  ','Date','datetime',12,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (87,6,'CurrencyName  ','CurrencyName  ','Currency','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (87,8,'posted  ','posted  ','Posted','bit',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (88,1,'prhreturnid','ID','ID',' int',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (88,3,'prhreturndate','prhreturndate','Return date','date',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (88,8,'prhremarks','Remarks','Remarks','varchar',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (88,9,'prhCancelled','Cancelled','Cancelled','bit',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (88,10,'prhPosted','posted','Posted','bit',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (87,4,'Type','Type','Type','char',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (89,1,'rrvrequestid','Reuest ID','RequstID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (89,3,'rrvrequestdate','Request Date','Request Date.','Datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (89,4,'VendorName','VendorName','Vendor Name.','Varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (89,6,'cancel','rrvcancelled','Cancel','Bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (90,2,'rrvhreceiveno','Receipt Number','Receipt No.','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (90,4,'vendorname','Vendor Name','Vendor','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (90,6,'rrvhcancelled','Deleted Yes nO','Cancel','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (91,1,'DepreciationID','DepreciationID','DepreciationID','int',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (91,3,'DepreciationDate','DepreciationDate','DepreciationDate','datatime',16,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (91,5,'Posted','Posted','Posted','bit',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (92,1,'schCommisionid','schCommisionid','schCommisionid','int',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (92,3,'schPaymentDate','schPaymentDate','Payment Date','datetime',16,0,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (84,2,'Customer Name','Customer Name','Customer Name','varchar',30,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (84,3,'mchCancelled','mchCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (150,1,'TrloanNo','TrloanNo','Loan/Fee id','Numeric',9,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (86,1,'serinvhid','invoiceid','InvoiceID','int',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (86,2,'serinvhprocno','serinvhprocno','Process No','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (86,4,'serinvhprocdate','Process Date','Process Date','datetime',12,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (45,6,'pohposted','Posted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (78,10,'serinvposted','posted','Posted','bit',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (87,2,'forexno  ','forexno','Forex No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (87,5,'salesorpurchaseamt  ','salesorpurchaseamt  ','Amount','numeric',9,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (87,7,'cancelled  ','cancelled  ','Cancelled','bit',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (88,2,'prhreturnno','prhreturnno','Return No','varchar',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (88,4,'VendorName','VendorName','Vendor','varchar',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (89,2,'rrvrequestno','Request No.','Requst No.','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (89,5,'ShopName','ShopName','Shop Name.','Varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (90,1,'rrvhreceiveid','Receipt ID','Receipt ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (90,3,'rrvhreceivedate','Receipt Date','Receipt Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (90,5,'rrvhvendorrefno','Vendor Reference Number','Vendor Ref. No.','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (91,2,'DepreciationNo','DepreciationNo','DepreciationNo','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (91,4,'Cancelled','Cancelled','Cancelled','bit',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (92,2,'schSalesCommisionNo','schSalesCommisionNo','Commision No','varchar',100,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (92,4,'schPaidAmount','schPaidAmount','Paid Amount','number',9,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (93,1,'asttransid','asttransid','asttransid','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (93,3,'asttransdate','asttransdate','Transfer Date','Datetime',16,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (93,5,'Transfer Type','Transfer Type','Transfer Type','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (93,7,'Cancelled ','Cancelled ','Cancelled ','bit',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (94,1,'rehExportID','rehExportID','rehExportID','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (94,3,'rehExportDate','rehExportDate','Export Date','Datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (94,7,'rehExportAmount','rehExportAmount','Export Amount','numeric',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (94,9,'rehPosted','rehPosted','Posted','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (95,2,'DndnNo','DndnNo','Delivery Note Number','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (95,4,'DnDeliveredBy','DnDeliveredBy','Delivered By','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (96,1,'disphID','','DisposalID','',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (96,3,'disphDate','','DisposalDate','',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (96,5,'disphCancelled','','Cancelled','',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (96,6,'disphPosted','','Posted','',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (97,1,'bahBudgetAllocID','bahBudgetAllocID','BudgetAllocID','int',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (97,3,'bahBudgetDate','bahBudgetDate','BudgetDate','datetime',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (97,5,'bahToDate','bahToDate','To Date','datetime',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (98,1,'tfhFixationID','tfhFixationID','FixationID','int',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (98,3,'tfhFixationDate','tfhFixationDate','Fixation Date','datetime',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (98,5,'tfhToDate','tfhToDate','To Date','datetime',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (99,1,'bchCheckID','bchCheckID','CheckID','int',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (99,3,'bchCheckDate','bchCheckDate','Check Date','datetime',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (99,5,'bchCancelled','bchCancelled','Cancelled','bit',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (100,2,'tchCheckNo','CheckNo','Check No','varchar',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (100,3,'tchCheckDate','tchCheckDate','Check date','datetime',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (100,4,'tchRemarks','tchRemarks','Remarks','varchar',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (100,5,'tchCancelled','tchCancelled','Cancelled','bit',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (101,1,'erediid','erediid','erediid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (101,3,'eredidate','eredidate','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (101,5,'ersentby','ersentby','Sent By','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (103,1,'BudgetID','BudgetID','BudgetID','int',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (103,3,'BudgetHead','BudgetHead','BudgetHead','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (104,2,'TargetIDCode','TargetIDCode','TargetIDCode','varchar',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (105,1,'ecconfirmid','ecconfirmid',' ecconfirmid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (105,3,'ecconfirmdate','ecconfirmdate','Confirmation Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (105,6,'ecconfirmedby','ecconfirmedby','Confirmation By','Varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (106,1,'reqhRequestID','reqhRequestID','reqhRequestID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (106,3,'reqhDate','date','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (106,7,'reqhCancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (107,1,'rrreqid','rrreqid','rrreqid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (107,3,'rrreqdate','rrreqdate','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (107,5,'rrsalespersonid','rrsalespersonid','Sales Person Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (102,1,'rcapprovedid','rcapprovedid',' rcapprovedid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (102,3,'rcapproveddate','rcapproveddate','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (102,5,'rcapprovedby','rcapprovedby','Approved By','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (108,1,'ishIssueID','ishIssueID','Issue Id','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (108,3,'ishDate','ishDate','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (108,5,'ishConfirmed','ishConfirmed','Confirmed','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (109,1,'rhReceiptID','rhReceiptID','Receipt ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (109,3,'rhDate','rhDate','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (109,6,'rhCancelled','rhCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (110,1,'alcid','alcid','alcid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (110,3,'alcdate','alcdate','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (110,4,'alctechnicianid','alctechnicianid','Technician Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (110,5,'Cancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (112,2,'tlrethno','tlrethnol','Return No.','Varchar',25,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (112,3,'tlrethdate','tlrethdate','Date','Datetime',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (112,6,'tlrethRemarks','tlrethRemarks','Remarks','Varchar',25,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (112,4,'Spername','Spername','Technician','Varchar',25,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (112,5,'alchno','alchno','Alocation No.','Varchar',25,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (112,7,'Cancelled','Cancelled','Cancel.','Bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (112,1,'tlrethid','tlrethid','Return ID.','int',4,NULL,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (114,3,'whdate','whdate','Return Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (114,5,'whcancelled','whcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (115,1,'whid','whid','Asset Convrsion ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (115,3,'whdate','whdate','Conversion Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (115,5,'whcancelled','whcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (151,1,'serid','serid','serid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (53,4,'DCNReferenceno','DCNReferenceno','ReferenceNo','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (53,5,'DCNAmount','DCNAmount','Amount','numeric',18,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (53,6,'DCNCancelled','DCNCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (53,7,'DCNPosted','DCNPosted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (54,1,'Invoice Id','InvoiceID','InvoiceID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (54,3,'Invoice Date','InvoiceDate','InvoiceDate','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (54,4,'CustomerID','CustomerID','Customer Name','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (141,1,' plhpacklistid','packlist','Packlistid','int',4,10,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (54,6,'Posted','Posted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (21,6,'chPosted','chPosted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (55,2,'aiinvoiceno','aiinvoiceno','InvoiceNo','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (56,2,'losDCNNo','losDCNNo','DebitCreditNo','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (56,4,'losreferenceno','losDCNBillId','Reference No','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (56,5,'losDCNAmount','losDCNAmount','Amount','numeric',18,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (85,1,'serbookhid','BookingID','BookingID','int',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (57,2,'sehExchangeNo','sehExchangeNo','ExchangeNo','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (57,4,'sehExchangerName','sehExchangerName','CustomerName','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (57,6,'sehCancelled','sehCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (58,2,'contrano','contrano','ContraNo','varchar',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (58,6,'contraamount','contraamount','Amount','numeric',18,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (58,8,'posted','posted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (59,2,'JournalNo','JournalNo','JournalNo','varchar',15,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (59,4,'Cancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (60,1,'ReceiptID','ReceiptID','ReceiptID','Receiptid',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (60,2,'ReceiptNo','Receipt No','Receipt No','varchar',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (60,3,'Receiptdate','Receipt Date','Receipt Date','Datetime',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (61,1,'exchangeID','exchangeID','exchangeID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (62,2,'Bills No','BillsNo','BillsNo','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (62,4,'Vendor Name','Vendor Name','Vendor Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (62,6,'Cancelled','Cancelled','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (59,5,'Posted','Posted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (85,2,'serbookhInspectionNo','Inspection No','Inspection No','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (64,1,'CSID','CSID','CSID','int',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (64,3,'CSDATE','CSDATE','Date','DateTime',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (64,5,'CustomerID','CustomerID','Customer Name','Varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (65,1,'VSID','VSID','VSID','int',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (65,3,'VSDATE','VSDATE','Date','DateTime',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (65,4,'PaymentID','PaymentID','Ref No','Varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (65,6,'Cancelled','Cancelled','Cancelled','bit',3,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (66,1,'Formatid','Formatid','Formatid','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (66,4,'UserCreated','User name','Created By','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (54,5,'Amount','Amount','Amount','numeric',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (64,2,'CSNO','CSNO','Settlment No','Varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (64,4,'ReceiptID','ReceiptID','Ref No','Varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (64,6,'Cancelled','Cancelled','Cancelled','bit',3,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (65,2,'VSNO','VSNO','Settlment No','Varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (65,5,'VendorID','VendorID','Vendor Name','Varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (66,3,'Format Name','Format Name','Format Name','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (66,5,'DefaultFormat','Default Format','Default Format','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (66,2,'Type','Report Type','Report Type','varchar',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (67,1,'ishid','ishid','ishid','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (22,10,'pbhposted','pbhposted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (20,4,'requestno','request no from shop','Request No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (21,7,'shipmentcost','shipmentcost','Shipment cost','int',18,6,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (21,9,'vendor name','vendor name','Vendor Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (60,4,'ReceivedFrom','Received From','Received From','ReceivedFrom',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (60,5,'ChequeDetails','Cheque No','Cheque No','ChequeDetails',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (67,2,'ishNo','Item Split No','Item Split No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (67,3,'ishdate','Split Date','Split Date','Date',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (67,4,'ishRemarks','Remarks','Remarks','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (67,5,'ishCancelled','Cancelled','Cancelled','bit',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (68,1,'scfhid','scfhid','scfhid','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (68,2,'scfhNo','Split Costing No','Split Costing No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (68,3,'scfhDate','Split Date','Split Date','Date',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (68,4,'scfhGodownid','Godown Name','Godown Name','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (68,5,'scfhRemarks','Remarks','Remarks','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (68,6,'scfCancelled','Cancelled','Cancelled','bit',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (20,5,'Shopname','shopnmae','Shop','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (85,3,'serbookhInspectionDate','InspectionDate','InspectionDate','datetime',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (69,1,'lpchcostingid','lpchcostingid','lpchcostingid','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (16,6,'dhCancelled','dhCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (52,7,'dhCarrier','Done By','Done By','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (48,7,'svhposted','Posted','Posted','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (15,7,'ahposted','ahposted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (17,8,'gahposted','Posted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (55,8,'aiCancelled','aiCancelled','Cancelled','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (28,6,'whposted','whposted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (72,1,'letterid','letterid','Letterid','int',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (74,1,'sercatid','Categoryid','Categoryid','integer',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (75,2,'sercode','Servicecode','Service Code','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (27,6,'whposted','whposted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (52,8,'dhposted','Posted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (50,7,'svhposted','svhposted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (39,7,'TIHPosted','TIHPosted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (71,1,'did','distributorid','did','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (71,2,'dcode','distributor code','Distributor Code','varchar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (71,3,'dname','distributor name','Distributor Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (75,1,'serid','serid','serid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (77,2,'cmpno','Complaint No','Complaint No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (77,3,'cmpdate','Complaint date','Complaint date','datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (77,1,'cmpid','cmpid','cmpid','int',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (78,1,'serinvhid','invoiceid','InvoiceID','int',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (79,1,'repreqhid','Request ID','Request ID','int',0,0,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (79,4,'VendorName','Manufacturer','Manufacturer','varchar',40,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (116,2,'WhNo','WhNo','Consumption No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (92,5,'schApprovedBy','schApprovedBy','Approved BY','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (92,6,'schCancelled','schCancelled','Cancelled','bit',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (93,2,'asttrransno','asttrransno','Transfer Number','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (93,4,'asttransassetid','asttransassetid','Asset Name','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (93,6,'Posted ','Posted ','Posted ','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (94,2,'rehExportNo','rehExportNo','Export No','Varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (94,4,'Name','Name','Name','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (94,8,'rehCancelled','rehCancelled','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (95,1,'DndnId','DndnId','Delivery Note ID','int',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (95,3,'DndnDate','DndnDate','Delivery Note Date','datatime',16,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (95,5,'Dncancelled','Cancelled','Cancelled','bit',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (96,2,'disphNo','','DisposalNo','',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (96,4,'disphRemarks','','Remarks','',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (97,2,'bahBudgetNo','bahBudgetNo','BudgetNo','varchar',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (97,4,'bahFromdate','bahFromdate','From Date','datetime',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (97,6,'bahCancelled','bahCancelled','Cancelled','bit',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (98,2,'tfhFixationNo','FixationNo','Fixation No','varchar',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (98,4,'tfhFromDate','tfhFromDate','From Date','datetime',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (98,6,'tfhCancelled','tfhCancelled','Cancelled','Bit',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (99,2,'bchCheckNo','bchCheckNo','Check No','varchar',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (99,4,'bchRemarks','bchRemarks','Remarks','varchar',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (100,1,'tchCheckID',' tchCheckID','CheckID','int',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (101,2,'eredino','eredino','EDI NO','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (101,4,'erpoid','erpoid','PO No','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (101,6,' ercancelled','ercancelled','Cancelled','Bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (103,2,'BudgetCode','BudgetCode','BudgetCode','varchar',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (104,1,'TargetID','TargetID','TargetID','int',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (104,3,'TargetIDHead','TargetIDHead','TargetIDHead','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (105,2,'ecconfirmno','ecconfirmno','Confirmation No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (105,5,'ecstatus','ecstatus','Status','Varchar',25,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (105,7,'eccancelled','eccancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (106,2,'reqhNo','Request No','Request No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (106,4,'reqhCustomerID','Customer Name','Customer Name','Int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (106,5,'reqhProcessedDate','Approved Date','Approved Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (105,4,'Invocieno','invocieno','PO No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (107,2,'rrreqno','rrreqno','Request No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (107,4,'rrpoid','rrpoid','PO No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (107,6,'rrcancelled','rrcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (102,2,'rcapprovedno','rcapprovedno','Approved No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (102,4,'rcreqid','rcreqid','Req.No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (102,6,'rccancelled','rccancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (108,2,'ishIssueNo','ishIssueNo','Issue No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (108,4,'ishIssuedByID','ishIssuedByID','Issued By','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (108,7,'ishCancelled','ishCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (109,2,'rhReceiptNo','rhReceiptNo','Receipt No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (109,4,'rhReceivedByID','rhReceivedByID','Received By','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (110,2,'alcno','alcno','Allocation No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (113,2,'ihno','ihno','Inquiry No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (113,3,'ihdate','ihdate','Inquiry Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (113,4,'ihcustname','ihcustname','Customer Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (113,5,'ihcancelled','ihcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (114,2,'whno','whno','Return No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (114,4,'whusername','whusername','User Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (114,6,'whposted','whposted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (115,2,'whno','whno','Conversion No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (115,4,'whusername','whusername','User Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (115,6,'whposted','whposted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (116,3,'WhDate','WhDate','Consumption Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (117,1,'Segmentid','Segmentid','Segmentid','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (17,6,'dhshopreqno','dhshopreqno','Request No','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (116,4,'WhUserName','WhUserName','User Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (116,5,'Whcancelled','Whcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (116,6,'whposted','whposted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (117,2,'SegmentName','SegmentName','SegmentName','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (60,6,'Amount','Amount','Amount','Amount',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (118,1,'FixedAssetID','FixedAssetID','FixedAssetId',' int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (118,4,'FixedAssetDate','FixedAssetDate','FixedAsset Date',' date',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (118,7,'CostPrce','CostPrice','Cost',' int',9,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (119,1,'lvhid','lvhid','Verification ID','int',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (119,3,'lvhDate','lvhDate','Verification Date','date',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (119,5,'lvhcancelled','lvhcancelled','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (119,7,'lvhposted','lvhposted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (119,4,'lvhVerificationby','lvhVerificationby','Verified By','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (118,6,'AccountDesc','AccountDesc','Account Name','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (120,1,'tohid','id','TransferID','int',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (120,3,'tohdate','Date','Transfer Date','datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (120,4,'ShopName','ShopName','Shop Name','Varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (120,6,'TOHTransfinished','To Confirm Finished','Confirmed','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (121,2,'TIHNO','TIHNO','Purchase NO','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (121,4,'TIHfromshopID','TIHfromshopID','From Shop','int',4,0,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (121,6,'TIHcancel','TIHcancel','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (121,8,'TIHConfirmed','TIHConfirmed','Confirmed','bit',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (82,5,'cancelled','cancelled','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (122,1,'evhId','evhId','Id','int',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (122,3,'evhDate','evhDate','Verification Date','date',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (84,4,'mchID','Maintenance Contract ID','Maintenance Contract ID','int',0,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (85,4,'serCallBkhNo','serCallBkhNo','Booking No','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (127,3,'Promotion Date','Date','Date','DateTime',8,0,0,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (50,2,'svhno','svhno','Verification No','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (159,2,'krhkegreturnno','krhkegreturnno','Keg Return No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (172,1,'PItemCategoryID','ItemCategory ID','ItemCategory ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (172,3,'PCategoryDescription','Category Description','Category Description','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (32,7,'Barcode','Barcode','Barcode','VARCHAR',30,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (45,5,'pohcancel','Cancel','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (46,1,'tohid','id','TransferID','int',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (46,4,'tohCancel','Cancel','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (48,2,'svhno','SV NO','SV NO','varchar',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (48,4,'svhVerifiedby','Verified By','Verified By','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (1,1,'CustomID','Customs ID','Customs ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (1,2,'CustomCategoryCode','Customs Category Code','Category Code','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (1,3,'CustomCategoryPercent','Tax Percent','Tax Percent','numeric',5,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (1,4,'Remarks','Remarks','Remarks','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (2,1,'ColorID','Color ID','Color ID','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (2,2,'ColorCode','Color Code','Color Code','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (2,3,'ColorName','Color Name','Color Name','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (3,1,'SizeID','Size ID','Size ID','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (3,2,'SizeCode','Size Code','Size Code','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (3,3,'SizeName','Size Name','Size Name','varchar',250,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (164,4,'chApartmentId','chApartmentId','Apartment No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (164,5,'chAgreementID','chAgreementID','Agreement No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (164,6,'chCancelled','chCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (5,1,'ItemCategoryID','Item Category ID','Item Category ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (8,1,'CountryId','Country Id','Country Id','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (9,1,'Prefix','Prefix','Prefix Name','varchar',5,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (11,1,'CustomerId','Customer ID','Customer ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (11,3,'PhoneNo','Phone No','Phone No','varchar',50,NULL,0,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (5,2,'ItemCategoryCode','Item Category Code','Item Category Code','varchar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (5,3,'CategoryNameDescription','Category Name Description','Category Name Description','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (6,1,'PackingTypeID','PackingTypeID','Packing Type ID','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (6,2,'PackingTypeCode','PackingTypeCode','Packing Type Code','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (6,3,'PackingTypeName','PackingTypeName','Packing Type Name','varchar',250,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (7,1,'VendorID','Vendor ID','Vendor ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (7,2,'VendorName','Vendor Name','Vendor Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (7,3,'PhoneNo','Telephone No.','Telephone No.','varchar',15,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (10,1,'Interface','Interface','Interface Name','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (11,2,'CustomerName','Customer Name','Customer Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (12,1,'CurrencyID','CurrencyID','Currency ID','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (13,1,'GodownID','Godown ID','Godown ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (13,3,'Godowntelephoneno','Godown Telephone No','Godown Telephone No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (14,2,'Shopname','Shop Name','Shop Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (14,4,'telephoneno','Telephone No','Telephone No','varchar',15,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (15,1,'ahArrivalID','ArrivalID','ahArrivalID','int',4,10,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (15,3,'ahArrivalDate','Arrival Date','Arrival Date','date',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (16,1,'dhDespatchID','Despatch ID','Despatch ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (16,2,'dhDespatchNo','Despatch No','Despatch No','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (17,1,'gaharrivalID','Arrival ID','Arrival ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (17,3,'gaharrivaldate','Arrival Date','Arrival Date','date',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (17,5,'gahdespatchedgodownID','godown Name','Godown Name','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (18,1,'poshBillID','poshBillID','Bill ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (18,3,'poshBillDate','poshBillDate','Bill Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (18,5,'poshBillAmount','poshBillAmount','Bill Amount','numeric',18,3,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (18,7,'poshposted','poshposted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (17,7,'gahcancelled','gahcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (16,3,'dhDespatchDate','Despatch Date','Despatch Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (15,6,'ahCancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (19,1,'dnmDespatchNoteID','DespatchNoteID','Despatch NoteID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (19,5,'dnmCancelled','Cancelled Bit','Cancelled','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (20,2,'inmissuenotenumber','inmissuenotenumber','Issue Note Number','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (20,6,'inmcancel','inmcancel','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (21,1,'chcostingid','costingid','Costing ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (22,2,'pbhBillNo','pbhBillNo','Bill No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (22,3,'pbhBillDate','pbhBillDate','Bill Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (22,4,'pbhVendorID','pbhVendorID','Vendor Name','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (19,3,'dnmDespatchNoteDate','Despatch Note Date','Despatch Note Date','date',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (23,1,'gthDespatchid','gthDespatchid','Despatch ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (23,5,'gthcancelled','gthcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (25,2,'username','User Name','User Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (26,2,'DepartmentName','Department Name','Department Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (26,3,'BudgetedAmount','Budgeted Amount','Budgeted Amount','numeric',18,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (27,4,'whusername','whusername','User Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (28,1,'whid','whid','Writeoff ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (28,3,'whdate','whdate','Writeoff Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (28,5,'whcancelled','whcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (29,3,'CustomCategoryPercent','CustomCategory  Percent','Custom Category Percent','numeric',5,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (30,1,'CityID','City ID','City ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (31,1,'dchClearingID','dchClearingID','Clearing ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (31,3,'dchClearingDate','dchClearingDate','Clearing Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (31,5,'dchCancelled','dchCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (30,4,'CityName','City Name','City Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (32,1,'itemid','Item ID','Item ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (32,3,'ItemDescription','ItemDescription','Item Description','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (70,1,'Sperid','Sales Person ID','Sales Person ID','int',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (70,3,'Speraddress','Address','Address','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (122,5,'evhCancelled','evhCancelled','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (122,7,'evhPosted','evhPosted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (123,1,'lvhId','lvhId','Verification Id','int',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (123,3,'lvhDate','lvhDate','Verification Date','date',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (123,5,'lvhCancelled','lvhCancelled','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (123,7,'lvhPosted','lvhPosted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (124,1,'evhId','evhId','Id','int',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (124,3,'evhDate','evhDate','Verification Date','date',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (60,7,'Cancelled','Cancelled','Cancelled','Cancelled',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (60,8,'posted','Posted','Posted','posted',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (118,3,'assetcode','AssetCode','Asset Code',' varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (118,5,'assetname','Assetname','Asset Name',' varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (120,2,'tohno','NO','Transfer NO','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (119,2,'lvhno','lvhno','Verification No','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (120,5,'tohCancel','Cancel','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (119,6,'lvhremarks','lvhremarks','Remarks','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (121,3,'TIHdate','TIHdate','Purchase Date','Datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (121,5,'TIHdespatchID','TIHdespatchID','Despatch NO','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (121,7,'TIHPosted','TIHPosted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (122,2,'evhNo','evhNo','Verification No','Varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (122,4,'evhVerificationBy','evhVerificationBy','Verified By','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (122,6,'evhRemarks','evhRemarks','Remarks','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (123,2,'lvhNo','lvhNo','Verification No','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (123,4,'lvhVerificationBy','lvhVerificationBy','Verified By','varchar',20,0,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (123,6,'lvhRemarks','lvhRemarks','Remarks','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (124,2,'evhNo','evhNo','Verification No','Varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (124,4,'evhVerificationBy','evhVerificationBy','Verified By','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (32,6,'Part_code','PartCode','PartCode','varchar',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (125,1,'DocId','DocId','DocId','int',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (125,3,'DocDate','Doc Date','DocDate','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (125,4,'External','External','External','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (125,6,'Cancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (126,1,'seaAppId','ApprovalID','ApprovalID','int',0,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (126,3,'seaAppDate','Appdate','Approval Date','varcahr',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (126,5,'seaApprovedBy','Approved By','Approved By','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (127,2,'Promotion No.','Promotion No.','Promotion No.','Varchar',20,0,0,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (127,4,'From Date','From Date','From Date','DateTime',8,0,0,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (127,6,'Tot Sales Amt','Tot Sales Amt','Tot Sales Amt','numeric',18,2,0,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (127,8,'Cancelled','Cancelled','Cancelled','bit',1,0,0,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (106,6,'reqhType','Type','Type','char',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (128,2,'bkcancellno','bkcancellno','Booking Cancel No','varchar',15,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (128,4,'bkcancellperson','bkcancellperson','Canelled By','varchar',15,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (108,6,'ishType','Type','Type','char',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (129,1,'Agreementid','Agreementid','Agreementid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (129,2,'AgreementNo','AgreementNo','AgreementNo','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (129,4,'agragreementdesc','agragreementdesc','Description','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (130,1,'ClearenceReqID','id','CR ID','int',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (130,3,'ClearenceReqDate','Date','CR Date','datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (130,5,'VendorName','Vendor','Vendor','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (130,7,'DeliveryDate','Date','Delivery Date','datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (130,9,'Cancelled','Cancel','Cancel','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (131,3,'ClearenceDate','Date','Clearence Date','datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (131,5,'ActualClearenceDate','ActualClearenceDate','Actual Clearence Date','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (129,5,'agragreementtype','agragreementtype','Type','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (132,1,'ClearenceReqID','id','Clearence Req. ID','int',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (132,2,'ClearenceReqNo','NO','Clearence Req. NO','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (132,3,'ClearenceReqDate','Date','Clearence Req. Date','datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (132,4,'CustomerName','Customer','Customer','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (132,5,'VendorName','Vendor','Vendor','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (132,6,'PONo','PONo','PO No','varchar',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (132,7,'DeliveryDate','Date','Delivery Date','datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (132,8,'Cancelled','Cancel','Cancel','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (133,1,'POID','id','PO ID','int',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (133,2,'PONo','NO','PO NO','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (133,3,'PODate','Date','PO Date','datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (133,4,'CustomerName','Customer','Customer','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (133,5,'VendorName','Vendor','Vendor','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (133,6,'ClearenceReqNo','ClearenceReqNo','Req. No','varchar',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (133,7,'Cancelled','Cancel','Cancel','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (134,1,'bnhboatnoteId','Boate NoteId','Boate Note ID','varchar',5,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (134,3,'bnhboatenotedate','Date','Date','varchar',15,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (134,5,'bnhcancelled','Cancelled','Cancelled','bit',5,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (135,2,'DocNo','Doc No','Doc No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (135,4,'CoMailIn','In/Out','In/Out','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (136,1,'DocID','DocID','DocID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (136,3,'DocDate','Doc Date','Doc Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (136,5,'MLastMedicalReportDate','Last Date','Last Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (137,2,'DocNo','Doc No','Doc No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (137,4,'EmpName','Employee Name','Employee Name','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (137,6,'PExpireyDate','Expiry Date','Expiry Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (138,2,'DocNo','Doc No','Doc No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (138,5,'RequestedBy','Requested By','Requested By','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (135,6,'Cancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (137,7,'Cancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (139,2,'DocNo','Doc No','Doc No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (139,4,'EmpName','Employee Name','Employee Name','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (139,5,'WWorkPermitNo','WorkPermit No','WorkPermit No','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (139,6,'WExpireyDate','Expiry Date','Expiry Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (139,7,'WFeeExpireyDate','Fee Expiry Date','Fee Expiry Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (139,8,'Cancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (140,1,'ConfirmID','id','BNC ID','int',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (140,3,'ConfirmDate','Date','BNC Date','datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (140,5,'InformedTime','Informed Time','Inf. Time','DateTime',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (140,7,'Cancelled','Cancel','Cancel','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (21,8,' Billno',' billno',' Bill No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (22,9,'pbhcancelled','pbhcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (118,8,'Posted','Posted','Posted','byte',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (118,2,'FixedAssetNo','Asset No','Asset No','Varchar',50,3,0,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (142,3,'sername','sername','Facility Name','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (150,2,'TrloanNo','TrloanNo','Loan/Fee Id','Numeric',9,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (150,4,'LoanName','LoanName','LoanName','Varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (150,5,' LoanAmount','LoanAmount','Loan Amount',' numeric',9,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (124,5,'evhCancelled','evhCancelled','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (124,6,'evhRemarks','evhRemarks','Remarks','Varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (124,7,'evhPosted','evhPosted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (58,5,'ChequeNo','ChequeNo','Cheque No','varchar',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (125,2,'DocNo','Doc No','DocNo','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (125,5,'Sender','Sender','Sender','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (126,2,'seaAppNo','seaAppNo','Approval No','int',15,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (126,4,'serbookhInspectionNo','Inspection No','Inspection No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (127,5,'To Date','To Date','To Date','DateTime',8,0,0,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (127,7,'Tot Profit Amt','Tot Profit Amt','Tot profit Amt','numeric',18,2,0,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (127,1,'Promotion ID','Promotion ID','Promotion ID','Varchar',20,0,0,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (128,1,'bkcancellId','bkcancellId','BookingCanelID','int',5,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (128,3,'bkcancelldate','bkcancelldate','Booking Cancel Date','varchar',11,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (128,5,'bkcancellcancelled','bkcancellcancelled','Canelled','varchar',5,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (128,6,'bkcancellposted','bkcancellposted','Posted','varchar',6,NULL,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (109,5,'rhType','Type','Type','char',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (129,3,'agragreementdate','agragreementdate','Date','Date',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (129,6,'agrapplicableTo','agrapplicableTo','ApplicableTo','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (129,7,'agragreementwith','agragreementwith','Agreement With','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (129,8,'agrcancelled','agrcancelled','Cancelled','char',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (130,2,'ClearenceReqNo','NO','CR No','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (130,4,'CustomerName','Customer','Customer','varchar',40,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (130,6,'PONo','PONo','PO No','varchar',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (130,8,'ExpectedArrivalDate','Date','Exp. Arr. Date','datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (131,2,'ClearenceNo','NO','Clearence NO','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (131,4,'ClearedBy','ClearedBy','Cleared By','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (131,6,'Cancelled','Cancel','Cancel','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (134,2,'bnhboateNoteNo','Boate Note No','Boate Note No','varchar',15,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (134,4,'bnhCustomerId','Customer Name','Customer Name','varchar',25,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (135,1,'DocID','DocID','DocID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (135,3,'DocDate','Doc Date','Doc Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (135,5,'CoMailHandledBy','Handled By','Handled By','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (136,2,'DocNo','Doc No','Doc No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (136,4,'EmpName','Employee Name','Employee Name','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (137,1,'DocID','DocID','DocID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (137,3,'DocDate','Doc Date','Doc Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (137,5,'PPassportNo','Passport No','Passport No','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (138,1,'DocID','DocID','DocID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (138,3,'DocDate','Doc Date','Doc Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (138,6,'Cancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (136,6,'Cancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (139,1,'DocID','DocID','DocID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (139,3,'DocDate','Doc Date','Doc Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (138,4,'CoMailHandledby','Approved By','Approved By','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (140,2,'ConfirmNo','NO','BNC NO','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (140,4,'BoatNoteNo','Boat Note No','Boat Note No','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (140,6,'InformedBy','Informed By','Inf. By','varchar',25,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (118,9,'Cancelled','Cancelled','Cancelled','bit',50,3,0,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (141,2,'plhno','no','No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (141,3,'plhdate','date','Date','datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (141,4,'exportid','exportid','ExportNo',' int',4,10,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (141,5,'plhremarks','remarks','Remarks','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (141,6,'plhcancelled','cancel','Cancelled','int',4,10,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (142,2,'sercode','Servicecode','Facility Code','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (150,3,'TrDate','TrDate','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (150,6,'TrCancelled','TrCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (151,2,'sercode','sercode','Utility Code','Varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (152,1,'serid','serid','serid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (153,1,'rhreservationid','rhreservationid','ID','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (164,1,'chid','chID','chID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (15,8,'ahTransFinished','Confirmed Finished','Confirmed','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (154,4,'mghAgreementNo','mghAgreementNo','Agmnt. No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (151,3,'sername','sername','Utility Name','Varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (152,2,'sercode','ratetypes','Rate Type','Varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (152,3,'serdetails','ratedesc','Description','Varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (153,2,'rhreservationno','rhreservationno','Resvn. No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (153,3,'rhreservationdate','rhreservationdate','Date','dateTime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (153,4,'CustomerName','CustomerName','Customer','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (153,5,'rhreservationstatus','rhreservationstatus','Status','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (153,6,'rcapartmentcategorydescription','rcapartmentcategorydescription','Apartment Type','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (153,7,'rhBookingType','rhBookingType','Booking Type','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (153,8,'rhRemarks','rhRemarks','Remarks','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (153,9,'rhcancellationcheck','rhcancellationcheck','Cancelled','Bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (154,1,'fphbookingid','fphbookingid','fphbookingid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (154,3,'fbhbookingdate','fbhbookingdate','Booking Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (154,2,'fbhbookingno','fbhbookingno','Booking No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (154,5,'fbhcancelled','fbhcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (155,1,'ftTrackId','ftTrackId','ftTrackId','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (155,2,'ftTrackNo','ftTrackNo','Track No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (155,3,'ftTrackDate','ftTrackDate','Track Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (155,4,'Booking No','Booking No','Booking No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (155,5,'Facility Name','Facility Name','Facility Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (155,6,'ftcheckinCancelled','ftcheckinCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (156,1,'ftTrackId','ftTrackId','ftTrackId','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (156,2,'ftTrackNo','ftTrackNo','Track No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (156,3,'ftTrackDate','ftTrackDate','Track Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (156,4,'Booking No','Booking No','Booking No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (156,5,'Facility Name','Facility Name','Facility Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (156,6,'ftcheckoutCancelled','ftcheckoutCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (158,1,'serid','serid','serid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (157,1,'mghAgreementID','mghAgreementID','ID','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (157,2,'mghAgreementno','mghAgreementno','Agmnt. No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (12,2,'CurrencyName','Currency Name','Currency Name','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (49,1,'srhrequestid','srhrequestid','Request ID','int',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (49,2,'srhrequestno','srhrequestno','Request No','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (49,3,'srhrequestdate','srhrequestdate','Request Date','date',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (49,4,'Shopname','Shopname','Shopname','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (49,5,'srhcancel','srhcancel','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (49,6,'srhremarks','srhremarks','Remarks','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (50,1,'svhid','svhid','Verification ID','int',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (50,3,'svhDate','svhDate','Verification Date','date',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (50,4,'svhVerificationby','svhVerificationby','Verificationby','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (50,5,'svhcancelled','svhcancelled','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (50,6,'svhremarks','svhremarks','Remarks','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (47,1,'poid','poid','PO ID','int',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (47,2,'pono','pono','PO NO','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (47,3,'podate','podate','PO Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (47,4,'vendorname','vendorname','Vendorname','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (47,5,'pohquotation','pohquotation','Quotation','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (47,6,'pohCancel','pohCancel','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (12,3,'Symbol','Symbol','Symbol','varchar',2,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (12,4,'CountryName','Country Name','Country Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (13,2,'GodownName','Godown Name','Godown Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (14,1,'Shopid','Shop id','Shop id','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (14,3,'Incharge','Incharge','Incharge','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (15,2,'ahArrivalNo','Arrival NUmber','Arrival No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (15,4,'ahDespatchNoteID','Despatch Note No','Despatch Note No','varchar',30,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (16,4,'dhissuenoteid','IssueNoteNo','IssueNoteNo','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (16,5,'dhRemarks','Remarks','Remarks','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (17,2,'gaharrivalno','Arrival No','Arrival No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (17,4,'gahgodowndespatchId','Despatch No','Despatch No','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (18,2,'poshBillNo','poshBillNo','Bill No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (18,4,'poshcustomername','poshcustomername','Customer Name','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (18,6,'poshcancelled','poshcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (19,2,'dnmDespatchNoteNo','dnmDespatch Note No','Despatch Note No','varchar',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (20,1,'inmissuenoteid','inmissuenoteid','Issue Note ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (20,3,'inmissuedate','inmissuedate','Issue Date','datetime',8,NULL,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (21,2,'chcostingNo','costingno','Costing No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (21,4,'chCostingDoneby','chCostingDoneby','Costing Done By','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (21,5,'chCancelled','chCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (22,7,'pbhBillAmount','pbhBillAmount','Bill Amount','numeric',18,3,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (85,6,'serbookconfirmed','Confirmed','Confirmed','bit',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (19,4,'pbhBillNo','pbhBillNo','Bill No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (23,2,'gthDespatchno','gthDespatchno','Despatch No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (23,4,'gthRemarks','gthRemarks','Remarks','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (24,1,'userid','User ID','User ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (25,1,'userid','User ID','User Name','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (26,1,'DepartmentID','Department ID','Department ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (27,1,'whid','whid','Writeoff ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (27,3,'whdate','whdate','Writeoff Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (27,5,'whcancelled','whcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (28,2,'whno','whno','Writeoff No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (28,4,'whusername','whusername','User Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (29,1,'CustomID','Customs ID','Customs ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (29,2,'CustomCategoryCode','Customs Category Code','Customs Category Code','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (11,5,'contactname','Contact Name','Contact Name','',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (30,2,'CountryName','Country Name','Country Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (31,2,'dchClearingNO','dchClearingNO','Clearing No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (31,4,'dchClearingDoneBy','dchClearingDoneBy','Clearing Done By','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (30,3,'CityCode','City Code','City Code','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (30,5,'AreaCode','Area Code','Area Code','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (7,4,'faxno','Fax No','Fax No','',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (32,2,'ItemCode','Item Code','Item Code','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (32,5,'Active','Active','Active','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (45,3,'podate','podate','PO Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (116,1,'WhID','WhID','ConsumptionID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (46,2,'tohno','NO','Transfer NO','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (46,3,'tohdate','Date','Transfer Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (55,3,'aiinvoicedate','aiinvoicedate','InvoiceDate','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (55,4,'aicustomerid','aicustomerid','Customer Name','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (55,6,'aiproforma','aiproforma','Proforma','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (55,7,'aiposted','aiposted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (56,3,'losDCNDate','losDCNDate','DebitCreditDate','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (8,3,'Nationality','Nationality','Nationality','',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (56,6,'losDCNCancelled','losDCNCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (57,1,'sehExchangeID','sehExchangeID','ExchangeID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (57,3,'sehExchangeDate','sehExchangeDate','ExchangeDate','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (57,5,'sehExchangeBillAmount','sehExchangeBillAmount','Amount','numeric',18,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (57,7,'sehPosted','sehPosted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (58,4,'contratype','contratype','Contra Type','varchar',3,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (58,7,'cancelled','cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (59,1,'JournalTransID','JournalTransID','JournalTransID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (59,3,'JournalTransDate','JournalTransDate','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (58,3,'contradate','contradate','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (41,6,'phamount','Amount','Amount','phamount',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (41,7,'phcancelled','Cancelled','Cancelled','phcancelled',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (41,8,'phposted','Posted','Posted','phposted',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (61,2,'exchangedate','exchangedate','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (243,3,'CustomerName','CustomerName','CustomerName','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (243,4,'BcReturnedDate','Returned Date','Returned Date','datetime',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (243,5,'BcBankAccName','Bank Account Name','Bank Account Name','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (243,6,'BcCancel','Cancelled','Cancelled','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (55,5,'Amount','Amount','Amount','numeric',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (239,1,'HPQuotationID','HPQuotationID','HPQuotationID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (239,2,'HPInstPrice','HPInstPrice','Intallment Price','numeric',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (239,3,'HPQuotationCustName','HPQuotationCustName','Customer Name','NVarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (239,4,'HPQuotationNO','HPQuotationNO','HPQuotationNO','NVarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (239,5,'HPQuotationDate','HPQuotationDate','Quotation Date','dateTime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (239,6,'HPInstMonthlyPay','HPInstMonthlyPay','Intallment Monthly Pay','numeric',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (239,7,'HPConfirm','HPConfirm','Confirmed','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (239,8,'HPCancell','HPCancell','Cancelled','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (239,9,'HPUser','HPUser','User','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (239,10,'HPUser','HPUpadatedUser','Updated User','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (239,11,'HPPosted','HPPosted','Posted','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (250,1,'hphProcessingID','Processing ID','Processing ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (250,2,'hphProcessingNO','Processing NO','Processing NO','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (250,3,'hphProcessingDate','Processing Date','Processing Date','DateTime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (250,4,'hpCustomer','Customer','Customer','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (250,5,'hphInvoiceNo','Invoice No','Invoice No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (250,6,'hphcancel','Cancelled','Cancelled','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (62,3,'Bills Date','BillsDate','BillsDate','varchar',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (196,6,'HPPaymentCancel','HPPaymentCancel','Cancelled','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (196,7,'HPPaymentPost','HPPaymentPost','Posted','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (197,1,'HPReceiptid','HPPaymentid','HPReceiptid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (197,2,'HPReceiptNO','HPReceiptNO','HPReceiptNo','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (197,3,'HPReceiptDate','HPReceiptDate','HPReceiptDate','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (197,4,'HPCustomer','HPCustomer','HP Customer','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (197,5,'HPReceiptAmount','HPReceiptAmount','HPReceipt Amount','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (197,6,'HPReceipttCancel','HPReceiptCancel','Cancelled','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (197,7,'HPReceiptPost','HPReceiptPost','Posted','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (200,1,'DocID','Doc ID','Doc ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (198,3,'Country Name','Country Name','Country Name','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (199,1,'IslandID','HPIslandID','IslandID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (199,2,'IslandName','HPIslandName','Island Name','nVarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (199,3,'Atoll Name','HPAtoll Name','Atoll Name','nVarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (198,1,'AtollID','HPAtollID','AtollID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (198,2,'Atoll Name','HPAtollName','Atoll Name','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (200,2,'DocTypeCode','Document TypeCode','Document TypeCode','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (200,3,'DocTypeName','Document TypeName','Document TypeName','numeric',5,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (192,7,'hpPosted','hpPosted','Posted','Bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (201,1,'HPRepossessionID','HPRepossessionID','HPRepossessionID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (201,2,'HPRepossessionINO','RepossessionID','RepossessionNO','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (201,3,'HPRepossessionDate','RepossessionDate','RepossessionDate','DateTime',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (201,4,'HPCustomer','HPCustomer','Customer Name','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (201,5,'HpAgreementNO','AgreementNO','Agreement No','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (201,6,'HPCancel','Canceled','Cancel','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (201,7,'HpPosted','Posted','Posted','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (202,1,'HPMCTransferID','HPMCTransferID','HPMCTransferID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (202,2,'HPMCTransferNo','HPMCTransferNo','MCTransfer No','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (202,3,'HPMCTransferDate','HPMCTransferDate','Transfer Date','DateTime',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (202,4,'MCCancel','McCaccel','Cancel','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (202,5,'UserName','UserName','User Name','NvarChar',4,NULL,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (202,6,'ModifiedUser','Modified User','Modified User','nVarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (202,7,'ModifiedTime','MOdifiedTime','Modified Time','DateTime',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (203,1,'PaymentID','Paymentid','Paymentid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (203,2,'PaymentNo','PaymentNO','PaymentNo','nvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (203,3,'PaymentDate','PaymentDate','PaymentDate','nvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (203,4,'PaymentPayee','PaymentPayee','Payeee','nvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (203,5,'PaymentAmount','PaymentAmount','Payment Amount','nvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (203,6,'PaymentCancel','PaymentCancel','Cancelled','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (203,7,'PaymentPost','PaymentPost','Posted','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (204,1,'FeeID','FeeID','Fee ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (204,2,'FeeID','FeeID','Fee Code','Varchar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (204,3,'FeeName','FeeName','Fee Name','Varchar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (205,1,'PaymentID','Paymentid','Paymentid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (205,2,'PaymentNo','PaymentNO','PaymentNo','nvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (205,3,'PaymentDate','PaymentDate','PaymentDate','nvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (205,4,'PaymentPayee','PaymentPayee','Payee','nvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (205,5,'PaymentAmount','PaymentAmount','Amount','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (205,6,'PaymentCancel','PaymentCancel','Cancel','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (205,7,'PaymentPosted','PaymentPosted','Posted','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (205,8,'User','User','User','nVarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (205,9,'UpdatedUser','UpdatedUser','Updated User','nVarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (205,10,'UpdatedTime','UpdatedTime','Updated Time','nVarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (206,1,'ResaleID','ResaleID','ResaleID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (206,2,'ResaleNo','ResaleNo','ResaleNo','nvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (206,3,'ResaleDate','ResaleDate','Resale Date','nvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (206,4,'CustomerName','CustomerName','Customer Name','nvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (206,5,'Cancel','Cancel','Cancelled','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (206,6,'Post','Post','Posted','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (206,7,'User','User','User','nVarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (206,8,'UpdatedUser','UpdatedUser','Updated User','nVarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (206,9,'UpdatedTime','UpdatedTime','Updated Time','nVarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (170,6,'bphcancelled','bphcancelled','Cancelled','varchar',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (172,2,'PItemCategoryCode','Item Category Code','Item Category Code','varchar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (36,5,'dramount','dramount','Amount','numeric',18,8,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (37,1,'lphBillID','lphBillID','Bill ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (37,2,'lphBillNo','lphBillNo','Bill No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (157,3,'mghAgreementdate','mghAgreementdate','Date','dateTime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (157,4,'rhReservationNo','rhReservationNo','Resvn. No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (157,5,'CustomerName','CustomerName','Customer','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (157,6,'mghsecurittyamount','mghsecurittyamount','Deposit Amt','numeric',18,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (157,7,'mghleasestatus','mghleasestatus','Status','varchar',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (157,8,'mghCancelled','mghCancelled','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (157,9,'mghPosted','mghPosted','Posted','Bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (158,2,'sercode','sercode','Service Code','Varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (158,3,'sername','sername','Service Name','Varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (159,1,'krhkegreturnid','krhkegreturnid','ID','int',4,10,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (159,3,'krhkegreturndate','krhkegreturndate','Date','datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (159,4,'customername','customername','Customer','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (159,5,'krhcancel','krhcancel','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (160,1,'trhTransId','trhTransId','ID','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (160,2,'trhTransno','trhTransno','Reg. No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (160,3,'trhTransdate','trhTransdate','Date','dateTime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (160,4,'apdApartmentNo','apdApartmentNo','Apartment No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (160,5,'mghAgreementNo','mghAgreementNo','Agmnt. No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (160,6,'sperName','sperName','Entered By','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (160,7,'trhStatus','trhStatus','Status','varchar',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (160,8,'trhCancelled','trhCancelled','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (161,1,'mghId','mghId','Id','int',0,NULL,1,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (161,3,'mghDate','mghDate','Date','DateTime',1,NULL,1,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (161,5,'mghRemarks','mghRemarks','Remarks','VarChar',10,NULL,0,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (161,7,'Confirmed','Confirmed','Confirmed','bit',1,NULL,1,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (161,2,'mghNo','mghNo','No','VarChar',1,NULL,1,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (161,4,'ItemCode','ItemCode','Code','VarChar',1,NULL,1,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (161,6,'CostPriceFixed','CostPriceFixed','Cost Price Fixed','bit',1,NULL,1,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (161,8,'Cancelled','Cancelled','Cancelled','bit',1,NULL,1,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (162,1,'tbhBillId','tbhBillId','tbhBillId','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (162,2,'tbhBillNo','tbhBillNo','Bill No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (162,3,'tbhBillDate','tbhBillDate','Bill Date','datetime',8,NULL,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (162,4,'tbhAgreementId','tbhAgreementId','Agreement No','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (162,5,'tbhCustomerId','tbhCustomerId','Customer Name','Varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (162,6,'tbhCancelled','tbhCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (162,7,'tbhPosted','tbhPosted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (163,1,'abhBillId','abhBillId','ID','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (163,2,'abhBillNo','abhBillNo','Bill No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (163,3,'abhBillDate','abhBillDate','Date','dateTime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (163,4,'apdApartmentNo','apdApartmentNo','Apartment','Varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (163,5,'mghAgreementNo','mghAgreementNo','Agmnt. No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (163,6,'CustomerName','CustomerName','Customer','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (163,7,'abhAmount','abhAmount','Amount','numeric',18,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (163,8,'abhCancelled','abhCancelled','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (163,9,'abhPosted','abhPosted','Posted','Bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (164,2,'chNo','chNo','Checkin No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (164,7,'chPosted','chPosted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (164,3,'chDate','chDate','Check Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (165,1,'denominationid','Denomination Id','Denomination Id','numeric',18,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (165,2,'denominationno','Denomination No','Denomination No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (165,3,'denomdate','Date','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (165,4,'remarks','Remarks','Remarks','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (165,5,'cancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (56,7,'dcnPosted','Posted','Posted','varchar',50,0,0,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (94,5,'Ref Trans No','Ref Trans No','Ref Trans No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (126,6,'Cancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (4,1,'UnitID','Unit ID','Unit ID','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (166,4,'bphplanname','bphplanname','Budget Name','varChar',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (52,4,'InvoiceNo','Invoice No','invoice No','Varchar',25,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (169,1,'Fixed Cost ID','Fixed Cost Id','Fixed Cost ID','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (166,7,'bphConfirmed','bphConfirmed','Confirmed','varchar',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (170,1,'bphBudgetPlanID','bphBudgetPlanID','Budget Plan Id','integer',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (94,6,'Ref Trans Date','Ref Trans Date','Ref Trans Date','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (166,1,'bphBudgetPlanID','bphBudgetPlanID','Budget Plan Id','integer',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (166,2,'bphBudgetNo','bphBudgetNo','Budget Plan No','varchar',30,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (166,3,'bphBudgetDate','bphBudgetDate','Budget Date','datetime',9,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (166,5,'bphRemarks','bphRemarks','Remarks','varchar',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (166,6,'bphcancelled','bphcancelled','Cancelled','varchar',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (167,1,'Ltimeid','LeadTime No','LeadtimeId','int',18,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (167,2,'Ltimedate','LeadTime Date','Leadtime Date','datetime',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (167,3,'Itemdesc','Item Description','Item Description','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (167,4,'Supplier Name','Supplier Name','Supplier Name','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (4,2,'UnitCode','Unit Code','Unit Code','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (4,3,'UnitName','Unit Name','Unit Name','varchar',250,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (169,2,'Fixed Cost No','Fixed Cost No','Fixed Cost No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (169,3,'Fixed Cost Date','Fixed Cost Date',' Date','datetime',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (169,4,'Fixed Cost Entered By','Fixed Cost Entered By',' Entered By','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (169,5,'FixedcostRemarks','FixedcostRemarks','Remarks','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (168,1,'EOQprocessid','EOQprocessid','EOQprocessid','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (168,2,'EOQProcessNo','EOQProcessNo','EOQProcessNo','Varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (168,3,'EoqProcessDate','EoqProcessDate','EoqProcessDate','Varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (168,4,'EOQprocessedBy','EOQprocessedBy','EOQprocessedBy','Varchar',50,0,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (168,5,'EOQprocessRemarks','EOQprocessRemarks','EOQprocessRemarks','Varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (170,2,'bphBudgetNo','bphBudgetNo','Budget Plan No','varchar',30,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (170,3,'bphBudgetDate','bphBudgetDate','Budget Date','datetime',9,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (170,4,'bphplanname','bphplanname','Budget Name','varChar',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (170,5,'bphRemarks','bphRemarks','Remarks','varchar',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (62,5,'Amount','Amount','Amount','numeric',18,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (62,7,'Posted','Posted','Posted','bit',3,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (53,2,'DCNNO','DCNNO','DebitCreditNo','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (53,3,'DCNDate','DCNNO','DebitCreditDate','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (7,5,'contactname','Contact Name','Contact Name','',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (33,2,'dchClearingNo','dchClearingNo','Clearing No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (33,4,'dchclearingdoneby','dchclearingdoneby','Clearing Done By','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (34,1,'grnhreturnnoteid','grnhreturnnoteid','Return Note ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (36,2,'drno','drno','Receipt No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (36,4,'drcustomerid','drcustomerid','Customer Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (36,6,'drcancelled','drcancelled','cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (37,3,'lphBillDate','lphBillDate','Bill Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (38,1,'dghID','dghID','Despatch ID','int',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (38,4,'dghgodownID','dghgodownID','Godown Name','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (38,5,'dghCancelled','dghCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (39,1,'TIHID','TIHID','Transfer ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (39,2,'TIHNO','TIHNO','Transfer NO','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (39,4,'TIHfromshopID','TIHfromshopID','From Shop','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (39,5,'TIHdespatchID','TIHdespatchID','Despatch NO','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (39,3,'TIHdate','TIHdate','Transfer Date','Datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (39,6,'TIHcancel','TIHcancel','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (40,1,'phpaymentid','phpaymentid','Payment ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (40,2,'phpaymentno','phpaymentno','Payment No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (40,3,'phpaymentdate','phpaymentdate','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (40,4,'phpayee','phpayee','Payee','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (40,5,'phcancelled','phcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (40,6,'phposted','phposted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (54,7,'Cancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (41,1,'phPaymentID','phPaymentID','PaymentID','int',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (41,2,'phPaymentno','Payment No','Payment No','varchar',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (42,1,'GRHrequestID',' Request ID','Request ID','int',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (42,3,'grhdate','date','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (42,5,'grhcancel','cancel','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (43,2,'grhrequestno','Requestno','Request No','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (43,4,'grhremarks','Remarks','Remarks','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (46,5,'tohRemarks','Remarks','Remakrs','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (48,3,'svhdate','SV Date','SV Date','date',8,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (48,5,'svhcancelled','Cancel','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (48,6,'svhremarks','Remarks','Remarks','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (37,4,'lphVendorID','lphVendorID','Vendor Name','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (37,5,'lphVendorBillNo','lphVendorBillNo','Vendor Bill No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (37,6,'lphBillAmount','lphBillAmount','Bill Amount','numeric',18,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (37,7,'lphCancelled','lphCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (85,5,'serbookhrecvdfrom','Customername','CustomerName','varchar',45,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (38,2,'dghNo','dghNo','Despatch No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (41,3,'phpaymentdate','Payment Date','Payment Date','Datetime',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (41,4,'phpayee','Payee','Payee','phpayee',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (41,5,'phChequeDetails','Cheque No','Cheque No','phChequeDetails',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (15,5,'ahArrivalType','Arrived From','Arrived From','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (42,2,'GRHrequestno','Requset No','Request No','Varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (42,4,'grhremarks','remarks','Remarks','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (43,1,'grhrequestid','Request Id','Request ID','int',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (43,3,'grhdate','date','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (43,5,'grhcancel','Cancel','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (51,1,'ihInvoiceId','Invoice Id','Invoice Id','int',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (51,4,'ihCustomerid','Customer Name','Customer Name','int',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (52,1,'dhdespatchid','Despatch ID','Despatch ID','int',10,NULL,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (52,3,'dhdespatchdate','Despatch Date','Despatch Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (52,6,'dhCancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (51,2,'ihInvoiceNo','Invoice No','Invoice No','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (51,3,'ihInvoiceDate','Invoice Date','Invoice Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (51,5,'ihInvoiceAmount','Invoice Amount','Invoice Amount','numeric',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (51,6,'ihCancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (51,7,'ihPosted','Posted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (52,2,'dhdespatchno','Despatch No','Despatch No','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (52,5,'dhRemarks','Remarks','Remarks','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (13,4,'godownincharge','Incharge','Incharge','',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (53,1,'DNCID','DCNID','DCNID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (55,1,'aiinvoiceid','invoiceid','InvoiceID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (56,1,'losDCNId','losDCNId','DCNID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (58,1,'contraid','contraid','ContraID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (62,1,'Bills Id','BillsID','BillsID','integer',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (32,4,'ItemCategoryID','Item Category ID','Item Category Name','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (45,1,'poid','poid','PO ID','int',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (34,7,'grnhposted','posted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (48,1,'svhid','SV ID','Verification ID','int',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (33,1,'dchClearingID','dchClearingID','Clearing ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (33,3,'dchclearingdate','dchclearingdate','Clearing Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (33,5,'dchcancelled','dchcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (34,2,'grnhgoodsreturnnoteno','grnhgoodsreturnnoteno','Return Note NO','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (34,3,'grnhgoodsreturnnotedate','grnhgoodsreturnnotedate','Return Note Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (34,4,'grnhcustomerid','grnhcustomerid','Customer Name',' int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (34,5,'grnhinvoiceid','grnhinvoiceid','Invoice No','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (34,6,'grnhcancel','grnhcancel','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (35,1,'ihInvoiceID','ihInvoiceID','InvoiceID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (35,2,'ihInvoiceNo','ihInvoiceNo','Invoice No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (35,3,'ihInvoiceDate','ihInvoiceDate','Invoice Date','datatime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (35,4,'ihCustomerID','ihCustomerID','Customer Name','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (35,5,'ihInvoiceAmount','ihInvoiceAmount','Invoice Amount','numeric',18,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (35,6,'ihCancelled','ihCancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (35,7,'ihPosted','ihPosted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (36,1,'drid','drid','Receipt ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (36,3,'drdate','drdate','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (173,1,'CounterId','CounterId','CounterId','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (174,1,'ShiftId','ShiftId','ShiftId','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (175,1,'UserGroupid','UserGroupID ','UserGroupID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (175,2,'UserGroupName','User Group Name ','User Group Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (175,3,'Description','Group Description ','Group Description','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (176,1,'MergeID','MergeID','MergeID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (176,2,'MergeNo','MergeNo','MergeNo','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (176,4,'New Brand Name','New Brand Name','New Brand Name','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (176,5,'MergeDate','MergeDate','Merge Date','Datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (176,7,'Cancelled','Cancelled','Cancelled','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (177,1,'ContainerID','ContainerID','Container ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (177,2,'ContainerCode','ContainerCode','Container Code','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (177,3,'ContainerDesc','ContainerDesc','Container Description','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (178,1,'MergeID','MergeID','MergeID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (178,3,'Old ParentCategory Name','Old ParentCategory Name','Old ParentCategory Name','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (178,4,'New ParentCategory Name','New ParentCategory Name','New ParentCategory Name','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (178,7,'Cancelled','Cancelled','Cancelled','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (179,1,'MergeID','MergeID','MergeID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (179,2,'MergeNo','MergeNo','MergeNo','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (179,5,'MergeDate','MergeDate','Merge Date','Datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (179,6,'Username','Username','User name','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (180,1,'VesselID','VesselID','Vessel ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (180,2,'VesselCode','VesselCode','Vessel Code','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (180,3,'VesselDes','VesselDes','Vessel Description','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (183,1,'UserGroupid','UserGroupID ','UserGroupID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (183,2,'UserGroupName','User Group Name ','User Group Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (183,3,'Description','Group Description ','Group Description','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (182,1,'ContactId','Contact ID','contact ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (182,2,'ContactName','Contact Name','Contact Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (182,3,'PhoneNo','Phone No','Phone No','varchar',50,NULL,0,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (45,7,'Remarks','Remarks','Remarks','varchar',1000,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (22,11,'QuotationNO','QuotationNO','Purchase Quotation NO','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (22,12,'HQRequestNo','HQRequestNo','Purchase HQRequest No','varchar',30,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (22,13,'ShopRequestNo','ShopRequestNo','Purchase ShopRequest No','varchar',30,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (19,8,'QuotationNO','QuotationNO','Purchase Quotation NO','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (19,9,'HQRequestNO','HQRequestNO','Purchase HQRequestNO','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (19,10,'ShopRequestNO','ShopRequestNO','Purchase Shop RequestNO','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (19,7,'PurchaseOrderNO','PurchaseOrderNO','Purchase OrderNO','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (25,3,'UserGroupID','User Group','User Group','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (24,3,'UserGroupID','User Group','User Group','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (173,3,'ShopName','Shop Name','Shop Name','Varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (173,2,'CounterName','CounterName','Counter Name','Varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (176,3,'Old Brand Name','Old Brand Name','Old Brand Name','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (178,2,'MergeNo','MergeNo','MergeNo','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (182,6,'DOB','DOB','DOB','',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (21,11,'HQRequestNO','QuotationNO','Purchase HQRequest NO','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (21,12,'ShopRequestNO','ShopRequestNO','Purchase ShopRequest NO','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (174,2,'ShiftName','ShiftName','Shift Name','Varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (176,6,'Username','Username','User name','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (178,5,'MergeDate','MergeDate','Merge Date','Datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (178,6,'Username','Username','User name','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (179,3,'Old Category Name','Old Category Name','Old Category Name','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (179,4,'New Category Name','New Category Name','New Category Name','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (179,7,'Cancelled','Cancelled','Cancelled','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (21,10,'QuotationNO','QuotationNO','Purchase Quotation NO','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (182,4,'CardNo','Card No','Card No','varchar',50,NULL,0,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (182,5,'ExpiryDate','Expiry Date','Expiry Date','',NULL,NULL,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (17,9,'gahconfirmed','gahconfirmed','Confirmed','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (17,10,'dhshopreqdate','dhshopreqdate','Request Date','Datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (39,8,'TIHconfirmed','TIHconfirmed','Confirmed','Int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (39,9,'TIHdespatchdate','TIHdespatchdate','Despatch Date','Datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (185,1,'dummyposhBillID','dummyposhBillID','Bill ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (185,2,'dummyposhBillNo','dummyposhBillNo','Bill No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (185,3,'dummyposhBillDate','dummyposhBillDate','Bill Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (185,4,'dummyposhcustomername','dummyposhcustomername','Customer Name','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (185,5,'dummyposhBillAmount','dummyposhBillAmount','Bill Amount','numeric',18,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (185,6,'dummyposhcancelled','dummyposhcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (185,7,'dummyposhposted','dummyposhposted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (185,8,'dummyposhconfirmed','dummyposhconfirmed','Comfirmed','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (186,1,'cardID','cardID','CardID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (186,2,'card Name','card Name','Card Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (187,1,'CompanyID','CompanyID','CompanyID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (187,2,'Contact Name','Contact Name','Contact Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (187,3,'card Name','card Name','Card Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (16,8,'Shop Request No','Shop Request No','Shop Request No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (188,1,'ChequeID','ChequeID','ChequeID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (188,2,'Bank Name','Bank Name','Bank Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (188,3,'Report Name','Report Name','Report Name','numeric',5,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (189,1,'TransID','TransID','TransID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (189,2,'TransNo','Registry No','Registry No','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (189,3,'ChDate','Registry Date','Registry Date','datetime',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (189,4,'CustomerName','Customer Name','Customer Name','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (189,5,'BankName','Bank Name','Bank Name','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (189,6,'ChequeNo','ChequeNo','ChequeNo','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (189,7,'Amount','Amount','Amount','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (189,8,'ChequeDate','ChequeDate','ChequeDate','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (189,9,'ShopName','ShopName','ShopName','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (189,10,'Status','Status','Status','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (189,11,'Cancel','Cancelled','Cancelled','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (207,1,'ReccuringID','ReccuringID','ReccuringID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (207,2,'ReccuringNo','Reccuring No','Reccuring No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (207,3,'ReccuringDate','Reccuring Date','Reccuring Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (207,4,'PaymentName','Payment Name','Payment Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (207,5,'PaymentDate','Payment Date','Payment Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (207,6,'Amount','Amount','Amount','numeric',18,3,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (207,7,'Cancelled','Cancelled','Cancelled','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (210,1,'ihInvoiceId','Invoice Id','Invoice Id','int',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (210,2,'ihInvoiceNo','Quotation No','Quotation No','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (210,3,'ihInvoiceDate','Quotation Date','Quotation Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (210,4,'ihCustomerid','Customer Name','Customer Name','int',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (210,5,'ihInvoiceAmount','Quotation Amount','Quotation Amount','numeric',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (210,6,'ihCancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (191,1,'HPCustID','HPCustID','HPCustID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (191,2,'HPCustName','HPCustName','Customer Name','nVarChar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (191,3,'hpNccNO','hpNccNO','NCC NO','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (191,4,'hpMobNO','hpMobNO','Customer MobNO','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (191,5,'hpUser','hpUser','User','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (191,6,'hpDate','hpDate','Application Date','DateTime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (191,7,'hpVerified','hpVerified','Verified','Bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,1,'IRRegistrationID','IRRegistrationIDo','IRRegistrationID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,2,'IRRegistrationNo','IRRegistrationNo','Registration No','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,9,'IRRegistrationDate','IRRegistrationDate','Registration Date','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,10,'IRShipment','IRShipment','Shipment','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,5,'IRMode','IRMode','Mode','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,6,'Itemdescription','Itemdescription','Model','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,7,'ColorName','ColorName','Color','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,8,'SoldColor','SoldColor','Sold Color','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,3,'IRFrameNo','IRFrameNo','FrameNo','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,4,'IrEngineNo','IrEngineNo','EngineNo','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,11,'IRModelNo','IRModelNo','ModelNo','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,12,'IRCase','IRCase','Case','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,13,'IRLocation','IRLocation','Location','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,14,'IRRegNo','IRRegNo','Reg No','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,15,'CustomerName','CustomerName','Customer Name','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,16,'IRRoadWorthiness','IRRoadWorthiness','Road Worthiness','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,17,'IRProduction','IRProduction','Production','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,18,'IRStatus','IRStatus','Status','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,19,'Remarks','Remarks','Remarks','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,20,'IRForSales','IRForSales','For Sales','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,21,'Cancel','Cancel','Cancel','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,22,'IRUserName','Entered By','Entered By','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,23,'IRUpdateUser','Modified By','Modified By','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (190,24,'IRUpdateUser','last Modified On','Last Modified On','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (192,1,'hprhReceiptID','hprhReceiptID','hprhReceiptID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (192,2,'hprhReceiptNo','Receipt No','Receipt No','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (192,3,'hprhReceiptDate','Receipt Date','Receipt Date','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (192,4,'Type','Type','Type','Varchar',50,NULL,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (192,5,'hpCustName','Customer Name','Customer Name','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (192,6,'hprhcancel','Cancelled','Cancelled','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (193,1,'HPQuotationID','HPQuotationID','HPQuotationID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (193,2,'HPQuotationNO','HPQuotationNO','HPQuotationNO','Nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (193,3,'HPQuotationDate','HPQuotationDate','Quotation Date','dateTime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (193,4,'HPQuotationCustName','HPQuotationCustName','Customer Name','NVarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (193,5,'HPInstPrice','HPInstPrice','Intallment Price','numeric',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (193,6,'HPInstMonthlyPay','HPInstMonthluPay','Intallment Monthly Pay','numeric',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (193,7,'HPConfirm','HPConfirm','Confirmed','Int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (193,8,'HPCancell','HPCancell','Cancelled','Int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (193,9,'HPUser','HPUser','User','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (193,10,'HPUser','HPUpadatedUser','Updated User','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (194,1,'HPChqRegID','HPChqRegID','HPChqRegID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (194,2,'HPChqRegNO','HPChqRegNO','PD Cheque Reg NO','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (194,3,'HPChqRegDate','HPChqRegDate','Cheque Reg.Date','DateTime',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (194,4,'HPCustName','HPCustName','Customer Name','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (194,5,'HPInvoiceNO','HPInvoiceNO','Hp Invoice NO','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (194,6,'HPVerified','HPVerified','Verified','Int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (194,7,'HPCancel','HPCancel','Cancel','Int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (194,8,'HPUser','HPUser','User Name','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (194,9,'HPModifiedUser','HPModifiedUser','Modified User','Varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (194,10,'HPModifiedTime','HPMOdifiedTime','Modified Date','Datetime',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (195,1,'HPAgreementID','HPAgreementID','HPAgreementID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (195,2,'HPAgreementNO','HPAgreementNo','HPAgreement No','Nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (195,3,'hpAgreementDate','hpAgreementDate','Agreement Date','dateTime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (195,4,'hpCustName','hpCustName','Customer Name','NVarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (195,6,'IRRegistrationNo','IRRegistrationNo','IremRegstation NO','NVarchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (195,7,'NVarchar','NVarchar','Cancel','Int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (195,8,'HPConfirm','HPConfirm','Confirm','Int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (195,9,'HPUser','HPUser','User','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (195,10,'HPUpdated User','HPUpadatedUser','Modified User','nvarchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (195,11,'HPUpdatedDate','HPUpadatedDAte','Modified Date','Datetime',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (195,5,'hpqhQuotationNO','hpqhQuotationNO','Quotation No','NVarchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (196,1,'HPPAYMENTid','HPPaymentid','HPPaymentid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (196,2,'HPPAYMENTNO','HPPaymentNO','HPPaymentNO','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (196,3,'HPPaymentDate','HPPaymentDate','HPPaymentDate','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (196,4,'HPCustomer','HPCustomer','HPCustomer','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (196,5,'HPPaymentAmount','HPPaymentAmount','HPPayment Amount','NvarChar',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (211,1,'whid','whid','Purchase Return ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (211,2,'whno','whno','Purchase Return No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (211,3,'whdate','whdate','Purchase Return Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (211,4,'whusername','whusername','User Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (211,5,'whcancelled','whcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (211,6,'whposted','whposted','Posted','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (88,7,'prhRefNo','Reference No','Reference No','Varchar',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (211,7,'whtransfinished','whtransfinished','Confirmed','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (51,8,'ihTransfinished','Confirmed','Confirmed','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (88,6,'prhRefNo','Reference No','Reference No','Varchar',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (212,1,'wchID','wchID','wchid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (212,2,'wchNO','N0','No','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (212,3,'wchDate','wchDate','Date','Datetime',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (212,4,'wchCustomerName','Customer Name','Customer Name','varchar',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (212,6,'Cancel','Cancelled','Cancelled','int',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (212,7,'Posted','Post','Posted','int',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (212,8,'wchUser','User','User','int',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (212,9,'wchUpdatedUser','Updated User','Updated User','varchar',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (212,10,'wchUpdatedTime','wchUpdatedTime','Updated Time','varchar',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (213,1,'ListID','ListID','ListID','int',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (213,2,'List Item Code','List Item Code','List Item Code','Varchar',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (213,3,'List Item Description','List Item Description','List Item Description','Varchar',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (214,1,'KitId','KitId','Kit ID','int',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (214,2,'KitCode','KitCode','Kit Code','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (214,3,'KitName','KitName','Kit Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (214,4,'SellingPrice','SellingPrice','Selling Price','numeric',18,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (214,5,'Active','Active','Active','bit',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (35,8,'ReferenceNo','ReferenceNo','ReferenceNo','varchar',50,NULL,0,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (35,9,'ihtransfinished','ihtransfinished','Confirmed','bit',1,NULL,0,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (217,1,'poid','poid','Pre-PO ID','int',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (217,2,'pono','pono','Pre-PO NO','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (217,3,'podate','podate','Pre-PO Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (217,4,'vendorname','vendorname','Vendor Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (217,5,'pohcancel','cancel','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (217,6,'pohposted','Posted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (217,7,'Remarks','Remarks','Remarks','varchar',1000,NULL,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (208,1,'SvID','SvID','SvID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (208,2,'Serial VerificationNo','Serial VerificationNo','Serial VerificationNo','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (208,3,'Verification Date','Verification Date','Verification Date','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (208,4,'VerifiedBy','Verified By','Verified By','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (208,5,'Cancel',' Cancel','Cancel','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (208,6,'Remarks',' Remarks','Remarks','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (209,1,'SvID','SvID','SvID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (209,2,'Serial VerificationNo','Verification No','Verification No','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (209,3,'Verification Date','Verification Date','Verification Date','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (209,4,'VerifiedBy','Verified By','Verified By','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (209,5,'Cancel',' Cancel','Cancel','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (209,6,'Remarks',' Remarks','Remarks','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (88,5,'prhRefNo','Reference No','Reference No','Varchar',NULL,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (218,1,'iphId','In-HousePurchaseId','In-House Purchase Id','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (218,2,'iphNo','In-HousePurchaseNo','In-House Purchase No','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (218,3,'iphDate','Date','Date','datetime',11,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (218,4,'iphVendorName','VendorName','Vendor Name','varchar',25,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (218,5,'iphRemarks','Remarks','Remarks','varchar',25,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (218,6,'iphCancel','Cancelled','Cancelled','varchar',10,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (218,7,'iphUserName','Username','Username','varchar',25,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (218,8,'iphUpdatedUserName','UpdatedUser','Updated User','varchar',25,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (86,6,'serCallBkhno','Booking No','Booking No','varchar',20,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (220,1,'ShopID','ShopID','ShopID','int',0,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (220,2,'ShopName','ShopName','Shop Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (221,1,'serStatusID','Service Status ID','Status ID','int',0,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (221,2,'serStatusName','Service Status Name','Status','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (37,8,'lphposted','lphposted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (37,9,'lphRemarks','lphRemarks','Remarks','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (95,6,'dnCustomerName','Customer Name','Customer Name','nvarchar',200,0,0,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (95,7,'dnContactNumber','Contact Number','Contact Number','nvarchar',100,0,0,0,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (86,8,'serinvhcompleted','Completed','Completed','bit',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (5,4,'Parent Item Catagory','Parent Item Catagory','Parent Item Catagory','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (37,10,'lphConfirmed','lphConfirmed','Confirmed','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (86,9,'TypeName','Type','Type','varchar',15,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (247,1,'BankID','Bank ID','Bank ID','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (247,2,'BankName','Bank Name','Bank Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (247,3,'Address1','Address','Address','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (245,1,'IHRHID','IHRHID','Return ID','INT',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (245,2,'IHRHNo','IHRHNo','Return No','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (59,6,'Confirmed','Confirmed','Confirmed','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (212,5,'Confirmed','Confirmed','Confirmed','int',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (116,8,'whotherdepid','whotherdepid','RequestDepartment','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (116,7,'whVerified','whVerified','Confirmed','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (244,1,'grhrequestid','Request Id','Request ID','int',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (244,2,'grhrequestno','Requestno','Request No','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (244,3,'grhdate','date','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (244,4,'grhShopName','ShopName/GodownName','ShopName/GodownName','varchar',40,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (244,5,'grhremarks','Remarks','Remarks','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (244,6,'grhcancel','Cancel','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (244,7,'grhconfirmed','Confirmed','Confirmed','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (232,2,'Bills No','BillsNo','BillsNo','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (232,4,'Vendor Name','Vendor Name','Vendor Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (232,6,'Cancelled','Cancelled','Cancelled','bit',1,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (232,3,'Bills Date','BillsDate','BillsDate','varchar',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (232,5,'Amount','Amount','Amount','numeric',18,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (232,7,'Posted','Posted','Posted','bit',3,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (232,1,'Bills Id','BillsID','BillsID','integer',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (165,6,'denoUserID','User Name','User Name','int',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (223,1,'TaxId','TaxId','Tax Id','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (223,2,'TaxCategoryCode','TaxCategoryCode','Tax Category Code','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (223,3,'TaxDescription','TaxDescription','Tax Description','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (47,7,'pohExcludeGST','pohExcludeGST','ExcludeGST','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (228,1,'FB_dg_Dishgroupid','FB_dg_Dishgroupid','FB_dg_Dishgroupid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (228,2,'FB_dg_Dishgroupcode','FB_dg_Dishgroupcode','Code','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (228,3,'FB_dg_Dishgroupname','FB_dg_Dishgroupname','Dishgroup Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (224,1,'FlghtOpid','FlghtOpid','FlightOperator ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (224,2,'FlghtOpName','FlghtOpName','FlightOperator Name','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (224,3,'FlghtSegName','FlghtSegName','Dish Segment Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (224,4,'Active','Active','Active','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (233,1,'Fb_dd_dishid','fb_dd_dishid','dish id','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (233,2,'fb_dd_dishcode','fb_dd_dishcode','Dish Code','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (233,3,'fb_dg_dishgroupname','FB_dg_Dishgroupname','Dish Group','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (233,4,'Fb_Ds_DishSubGroupName','Fb_Ds_DishSubGroupName','Dish Sub Group','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (233,5,'fb_dd_dishname','fb_dd_dishname','Dish Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (234,1,'voucherid','voucherid','voucherid','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (234,2,'vouchername','vouchername','Voucher Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (234,3,'voucheramount','voucheramount','Voucher Amount','numeric',9,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (234,4,'CurrencyName','CurrencyName','Currency Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (234,5,'Active','Active','Active','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (235,1,'till_th_tillid','till_th_tillid','Till ID','int',0,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (235,2,'till_th_tillname','till_th_tillname','Till Name','varchar',50,0,0,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (235,3,'till_th_active','till_th_active','Till Active','varchar',50,0,0,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (241,1,'poshBillID','poshBillID','Bill ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (241,2,'poshBillNo','poshBillNo','Bill No','VARCHAR',25,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (241,3,'poshBillDate','poshBillDate','Bill Date','DATETIME',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (241,4,'poshBillAmount','poshBillAmount','Amount','decimal',9,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (245,3,'IHRHDate','IHRHDate','Return Date','datetime',12,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (245,4,'shopname','shopname','Shop Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (245,5,'WhNo','WhNo','Inhouse No','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (245,6,'IHRHCancelled','IHRHCancelled','Cancelled','INT',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (245,7,'IHRHposted','IHRHposted','Posted','INT',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (245,8,'IHRHConfirmed','IHRHConfirmed','Confirmed','INT',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (245,9,'WhDate','WhDate','Inhouse Date','Inhouse Date',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (241,5,'poshRecModifyUser','poshRecModifyUser','Cancel/Edit','VARCHAR',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (241,6,'poshcancelled','poshcancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (241,7,'poshposted','poshposted','Posted','BIT',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (236,1,'seg_header_id','seg_header_id','seg_header_id','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (236,2,'seg_header_name','seg_header_name','Segment Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (227,1,'FlightID','FlightID','FlightID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (227,2,'FlightNo','FlightNo','FlightNo','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (227,3,'FlghtOpName','FlghtOpName','FlghtOperator Name','varchar',100,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (227,4,'WeekDays','WeekDays','Departure Day','varchar',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (227,5,'FlightDepTime','FlightDepTime','Departure Time','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (227,6,'Active','Active','Active','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (237,1,'DishCategoryID','DishCategoryID','DishCategoryID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (237,2,'DishID','DishID','DishID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (237,3,'DishCategoryName','DishCategoryName','DishCategoryName','int',4,NULL,1,1,newid())
Go
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (237,4,'Dish Name','Dish Name','Dish Name','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (237,5,'DishCP','DishCP','DishCP','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (238,1,'till_id','Till ID','Till ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (238,2,'till_th_tillname','Till Name','Till Name','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (238,3,'till_cashierid','User Name','User Name','varchar',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (238,4,'till_starttime','Start Time','Start Time','datetime',8,NULL,0,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (238,5,'till_endtime','End Time','End Time','datetime',8,NULL,0,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (238,6,'till_statusid','Till Status','Till Status','varchar',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (225,1,'fb_rm_tablemasterid','Table ID','Table ID','int',0,0,0,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (225,2,'fb_rm_tablemastercode','Table Code','Table Code','varchar',50,0,0,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (225,3,'fb_rm_tablemastername','Table Name','Table Name','varchar',250,0,0,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (226,1,'fb_rt_tableid','fb_rt_tableid','table id','int',4,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (226,2,'fb_rt_tablecode','fb_rt_tablecode','Cover Code','varchar',50,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (226,3,'fb_rt_tablename','fb_rt_tablename','Cover Name','varchar',250,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (226,4,'rm.fb_rt_tablename','rm.fb_rt_tablename','Table Name','varchar',250,0,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (230,1,'fb_dd_dishid','fb_dd_dishid','dish id','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (230,2,'fb_dd_dishcode','Dish Code','Dish Code','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (230,3,'FB_dg_Dishgroupname','FB_dg_Dishgroupname','Dish Group','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (230,4,'Fb_Ds_DishSubGroupName','Fb_Ds_DishSubGroupName','Dish Sub Group','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (230,5,'fb_dd_dishname','fb_dd_dishname','Dish Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (222,1,'JournalTransID','JournalTransID','JournalTransID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (222,2,'JournalNo','JournalNo','JournalNo','varchar',15,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (222,3,'JournalTransDate','JournalTransDate','Date','datetime',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (222,4,'Type','Type','Type','varchar',8,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (222,5,'TypeSerilNo','TypeSerilNo','TypeSerilNo','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (222,6,'Cancelled','Cancelled','Cancelled','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (222,7,'Posted','Posted','Posted','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (222,8,'Confirmed','Confirmed','Confirmed','bit',1,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (242,1,'LcID','LCRegID','RegID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (242,2,'LcNo','LC Registration No','LcRegNo','varchar',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (242,3,'vendorname','Vendor Name','vendor name','varchar',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (242,4,'LcBankName','Bank Account','Bank Account','int',500,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (242,5,'LcDueDate','Due Date','LcDueDate','datetime',15,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (242,6,'LcAmount','Amount','Amount','numeric',25,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (242,7,'LcEstDate','Established Date','Established Date','datetime',20,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (242,8,'LcCancel','Cancelled','Cancelled','int',4,2,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (243,1,'BcID','Bounced Cheque ID','Bounced Cheque ID','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (229,1,'fb_ds_dishsubgroupid','fb_ds_dishsubgroupid','Dish Sub Group','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (229,2,'fb_ds_dishgroupname','fb_ds_dishgroupname','Dish  Group','varchar',25,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (229,3,'fb_ds_dishsubgroupcode','fb_ds_dishsubgroupcode','Sub Group code','varchar',10,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (229,4,'fb_ds_dishsubgroupname','fb_ds_dishsubgroupname','Dish Sub Group','varchar',25,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (229,5,'fb_ds_printerpath','fb_ds_printerpath','Dish Sub Group Printer','varchar',25,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (231,1,'Fb_dd_dishid','fb_dd_dishid','dish id','int',4,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (231,2,'fb_dd_dishcode','fb_dd_dishcode','Dish Code','varchar',50,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (231,3,'fb_dg_dishgroupname','FB_dg_Dishgroupname','Dish Group','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (231,4,'Fb_Ds_DishSubGroupName','Fb_Ds_DishSubGroupName','Dish Sub Group','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (231,5,'fb_dd_dishname','fb_dd_dishname','Dish Name','varchar',250,NULL,1,1,newid())
INSERT INTO [adminv2].[dbo].[aTableColumns]  ([TableID]  ,[ColumnID]  ,[ColumnName]  ,[ColumnDescription]  ,[ColumnHeader]  ,[ColumnType]  ,[ColumnLength]  ,[ColumnDecimals]  ,[Mandatory]  ,[Version1]  ,[rowguid])  VALUES (243,2,'BcChequeNo','Cheque No','Cheque No','varchar',20,NULL,1,1,newid())
Go
-------------------------[aTableColumns] STOP----------------------------------------------
-------------------------[aTableColumns],[aTables] STOP----------------------------------------------


-------------------------[aReports] START----------------------------------------------
DELETE FROM [adminv2].[dbo].[aReports]
Go

INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(1,'Discount  Criteria List','inv1',1,1,'',1)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(2,'Inventory Valuation Summary','inv2',1,1,'',2)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(3,'Item Price List','inv3',1,1,'',3)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(4,'Sales Analysis','sale3',1,2,'',4)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(5,'Analysis of Sales By Customer','sale6',1,2,'',5)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(6,'Daily Sales Report','sale9',1,2,'',6)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7,'List of Items','inv4',1,1,'',7)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(8,'Items to be Recovered','inv5',1,1,'',8)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(9,'Stock out Items','inv6',1,1,'',9)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(10,'Items in stock','inv7',1,1,'',10)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(11,'Bin card Audit','inv8',1,1,'',11)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(12,'Item Flow Analysis','inv9',1,1,'',12)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(13,'Item Wise Movement','inv10',1,1,'',13)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(14,'Shop Locationwise Stock','shoplocwise',1,1,'',14)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(15,'Godown Locationwise Stock','Godownlocwise',1,1,'',15)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(16,'Shop Expiry Datewise Stock','ShopExpWise',1,1,'',16)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(17,'Godown Expiry Datewise Stock','GodownExpWise',1,1,'',17)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(18,'Sales and Collection Summary','sale10',1,2,'',18)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(19,'Analysis of Sales By Item','sale7',1,2,'',19)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(20,'Total Item Sales','sale5',1,2,'',20)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(21,'Daily Item Sales','sale8',1,2,'',21)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(22,'Item Movement (Fast/Slow)','sale11',1,2,'',22)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(23,'Product wise Sales','sale12',1,2,'',23)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(24,'Monthly Itemwise Sales','sale13',1,2,'',24)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(25,'Sales/Imports Analysis','sale14',1,2,'',25)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(26,'Comparative Sales','sale16',1,2,'',26)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(27,'Product wise sales & margin share','sale17',1,2,'',27)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(28,'Sales value year wise','sale18',1,2,'',28)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(29,'Sales Person Performance','sale19',1,2,'',29)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(30,'Countrywise Sales','Sale20',1,2,'',30)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(31,'Brandwise/Categorywise','sale21',1,2,'',31)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(32,'Import','purimport',1,3,'',32)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(33,'Local Purchase','purlocalpur',1,3,'',33)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(34,'Shipment wise price sheet','purprsheet',1,3,'',34)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(35,'Discount Per Supplier Bill','purbilldisc',1,3,'',35)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(36,'Pending Purchase Orders','purordpend',1,3,'',36)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(37,'Shop PO Request Status','purshoppo',1,3,'',37)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(38,'Service Done Customerwise','serv1',1,4,'poc',38)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(39,'Service Done Particular Brand/Model','serv2',1,4,'poc',39)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(40,'Service Done by Technician','serv3',1,4,'poc',40)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(41,'Product Serviced Frequently','serv4',1,4,'poc',41)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(42,'Customer Serviced Frequently','serv5',1,4,'poc',42)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(43,'Replacements Made from Manufacturer','serv6',1,4,'poc',43)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(44,'Parts Replaced for Each Service','serv7',1,4,'poc',44)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(46,'Service Done with Other Brands','serv9',1,4,'poc',46)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(47,'Parts Used in Services','serv10',1,4,'poc',47)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(48,'Short Services','serv11',1,4,'poc',48)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(49,'Customs price variation','oth2',1,5,'',49)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(50,'Damage Clearing Details','oth3',1,5,'',50)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(51,'Godown Shipment Arrival Difference','oth4',1,5,'',51)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(52,'Stock Verification Details','oth5',1,5,'',52)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(53,'Stock Write off Details','oth6',1,5,'',53)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(54,'Customer Profile','oth7',1,5,'',54)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(55,'Daily Shop Transaction Details','oth8',1,5,'',55)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(56,'Day End Report','oth9',1,5,'',56)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(57,'Item sold below cost price','oth10',1,5,'',57)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(58,'Shipment Related Expenses','oth11',1,5,'',58)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(59,'Import Item Details','oth12',1,5,'',59)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(60,'Location wise Bill Details','oth13',1,5,'',60)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(61,'Shipment wise Cost','oth14',1,5,'',61)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(62,'Import Excess_Shortage','oth15',1,5,'',62)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(63,'Status Information Report','misreprt1',1,5,'',63)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(64,'Transfer Out Summary','oth16',1,5,'',64)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(65,'Transfer In Summary','oth17',1,5,'',65)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(66,'Items in Transit','itemintrans',1,5,'',66)
Go
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(67,'Cash Collection','ChCol',3,1,'poscbRRR',67)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(68,'Customer List','CustList',3,1,'poscbRRR',68)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(69,'Daily Item Sales','DItemSales',3,1,'poscbRRR',69)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(70,'Service Done Customerwise','serv1',3,2,'pocRRR',70)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(71,'Service Done Particular Brand/Model','serv2',3,2,'pocRRR',71)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(72,'Service done by Technician','serv3',3,2,'pocRRR',72)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(73,'Item Flow Analysis','ItemFlowAnal',3,1,'poscbRRR',73)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(74,'Item Stock','ItemStock',3,1,'poscbRRR',74)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(75,'Item Wise Movement','ItemMove',3,1,'poscbRRR',75)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(76,'Items','Items',3,1,'poscbRRR',76)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(77,'Item Price List','ItemPriceList',3,1,'poscbRRR',77)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(78,'Shop BinCard Audit','ShopBinCard',3,1,'poscbRRR',78)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(79,'Stock Out Items','StkOutItem',3,1,'poscbRRR',79)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(80,'Vendor List','VendList',3,1,'poscbRRR',80)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(81,'Stock Writeoff Analysis','stkwrtoff',3,1,'poscbRRR',81)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(82,'Stock Verification Analysis','stkveroff',3,1,'poscbRRR',82)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(83,'Damage Clearing Analysis','DamClear',3,1,'poscbRRR',83)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(84,'Item Short Codes','shortcode',3,1,'poscbRRR',84)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(85,'Godown Items Not In Shop','Gdnnotinshop',3,1,'poscbRRR',85)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(86,'Shop PO Request Status','poreqstat',3,1,'poscbRRR',86)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(87,'Shop Locationwise Stock','shoplocwise',3,1,'poscbRRR',87)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(88,'Shop Expiry Datewise Stock','ShopExpWise',3,1,'poscbRRR',88)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(89,'Product Serviced Frequently','serv4',3,2,'pocRRR',89)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(90,'Customer Serviced Frequently','serv5',3,2,'pocRRR',90)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(91,'Replacements made from Manufacturer','serv6',3,2,'pocRRR',91)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(92,'Parts Replaced from Each Service','serv7',3,2,'pocRRR',92)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(94,'Service Done with Other Brands','serv9',3,2,'pocRRR',94)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(95,'Parts Used In Services','serv10',3,2,'pocRRR',95)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(96,'Short Services','serv11',3,2,'pocRRR',96)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(97,'Goods Arrival','Goodsarr',3,3,'poscbRRR',97)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(98,'Goods Request to Shop','Goodsreqtoshop',3,3,'poscbRRR',98)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(99,'Transfer In','Transferin',3,3,'poscbRRR',99)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(100,'Transfer Out','Transferout',3,3,'poscbRRR',100)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(101,'Inter Divisional Sales','InterDivSales',3,3,'poscbRRR',101)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(102,'Inter Divisional Purchases','InterDivPurch',3,3,'poscbRRR',102)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(103,'Despatch to Godown','DesptoGdn',3,3,'poscbRRR',103)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(104,'Goods Request to HQ','GoodsreqtoHQ',3,3,'poscbRRR',104)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(105,'Stock Write Off','Stockwriteoff',3,3,'poscbRRR',105)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(106,'Inhouse Consumption','Inhcons',3,3,'poscbRRR',106)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(107,'Stock Verification','StockVerification',3,3,'poscbRRR',107)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(108,'Damaged Quantity Clearing','DamQtyClear',3,3,'poscbRRR',108)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(109,'Goods Return','GoodsReturn',3,3,'poscbRRR',109)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(110,'POS','POS',3,3,'poscbRRR',110)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(111,'Purchase Request','purR',3,3,'poscbRRR',111)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(112,'Purchase Quotation','purq',3,3,'poscbRRR',112)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(113,'Purchase Order','puro',3,3,'poscbRRR',113)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(114,'Sales Confirmation','SalConf',3,3,'poscbRRR',114)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(115,'Delivery Note','delnote',3,3,'poscbRRR',115)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(116,'Invoice for Credit Sales','InvCrSales',3,3,'poscbRRR',116)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(117,'Goods Exchange','GoodsExch',3,3,'poscbRRR',117)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(118,'Godown Dispatch Invoice -Cash','SplInv',3,3,'poscbRRR',118)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(119,'Purchase Bill','PurBill',3,3,'poscbRRR',119)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(120,'Dummy Receipts','Dummyrec',3,3,'poscbRRR',120)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(121,'Payments','Payments',3,3,'poscbRRR',121)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(123,'Service Booking','BookSlp',3,3,'pocRRR',123)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(124,'Booking Invoice','InvSlp',3,3,'pocRRR',124)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(125,'Replacement Request','RepRq',3,3,'pocRRR',125)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(126,'Replacement Receive','RepRec',3,3,'pocRRR',126)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(127,'Stand-By Request','StnReq',3,3,'poscbRRR',127)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(128,'Stand-By Issue','Stnissu',3,3,'poscbRRR',128)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(129,'Stand-By Receipt','StnRec',3,3,'poscbRRR',129)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(130,'Godown Bincard Audit','GbincardAudit',2,1,'',130)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(131,'Item Flow Analysis','ItemFlowAnal',2,1,'',131)
Go
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(132,'Item Stock','Itemstock',2,1,'',132)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(134,'Items','Items',2,1,'',134)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(135,'Imports Arrival Stock Variation','ShipStockVar',2,1,'',135)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(136,'Stock Clearing Analysis','Stockclearanal',2,1,'',136)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(137,'Stock Out','Stockout',2,1,'',137)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(138,'Stock Verification Analysis','Stkveranal',2,1,'',138)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(139,'Stock WriteOff Analysis','StkWroffanal',2,1,'',139)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(141,'Godown Locationwise Stock','Godownlocwise',2,1,'',141)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(143,'Godown Expiry Datewise Stock','GodownExpWise',2,1,'',143)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(144,'Goods Arrival','GoodsArr',2,2,'',144)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(145,'Despatch to Shops','Desptoshop',2,2,'',145)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(146,'Stock Write Off','StkWriteoff',2,2,'',146)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(147,'Purchase Return','PurchaseReturn',2,2,'',147)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(148,'Asset Conversion','Assettransfer',2,2,'',148)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(149,'Despatch to Godown','DesptoGdn',2,2,'',149)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(150,'Stock Verification','StkVer',2,2,'',150)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(151,'Damage Clearing','Damclear',2,2,'',151)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(152,'Special Despatch to Shop','spldesptoshop',2,2,'',152)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(153,'Item Split','ItemSplit',2,2,'',153)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(154,'Outstanding Invoices','OUTINVOICE',4,1,'',154)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(155,'Debtor Age Analysis','DBAGEANALYSIS',4,1,'',155)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(156,'Customer Statement','CUSTLEDGER',4,1,'',156)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(157,'Outstanding Bills','OUTBILL',4,2,'',157)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(158,'Creditor Age Analysis','CRAGEANAL',4,2,'',158)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(159,'LC Outstanding Age Analysis','LCOUTAGEANAL',4,2,'',159)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(160,'Customer Summary','CUSTSUMMARY',4,1,'',160)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(161,'Letter/Remainder','LETTERREM',4,1,'',161)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(162,'Vendor Statement','VENDORLEDER',4,2,'',162)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(163,'Vendor Summary','VENDORSUMM',4,2,'',163)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(164,'Fixed Asset','FIXASSET',4,3,'',164)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(165,'Chart of Accounts','CHARTACC',4,4,'',165)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(166,'General Ledger','GENLEDGER',4,4,'',166)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(167,'Trial Balance','TRIALBAL',4,4,'',167)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(168,'Profit and Loss Account','PANDFACC',4,4,'',168)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(169,'Balance Sheet','BALSHEET',4,4,'',169)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(170,'Cash Book','CASHBOOK',4,4,'',170)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(171,'Bank Transaction Details','BNKRPT',4,4,'',171)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(172,'Bills','BILLS',4,5,'',172)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(173,'Contra','CONTRA',4,5,'',173)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(174,'Debit/Credit Note','DBCRNOTE',4,5,'',174)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(175,'Debit Note Listing','DBNOTELISTING',4,5,'',175)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(176,'Credit Note Listing','CRNOTELISTING',4,5,'',176)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(177,'Journals','JOURNAL',4,5,'',177)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(178,'Payments','PAYMENTS',4,5,'',178)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(179,'Receipts','RECEIPTS',4,5,'',179)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(180,'Service Invoice','SERVICEINVOICE',4,5,'',180)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(181,'Asset Transfer','Asset Transfer',4,5,'',181)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(182,'Asset Disposal','Asset Disposal',4,5,'',182)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(183,'Asset Tranfer History','ATH',4,5,'',183)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(184,'Receipts Unsettled','Unsettled Receipts',4,5,'',184)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(185,'Customer Price Offered','cuspriceof',3,1,'poscbRRR',185)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(186,'Customer Sales Brand/Item','cussalbrditem',1,2,'',186)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(187,'Payment With Cheque Details','PaymentChqDet',4,5,'',187)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(188,'Sales and Collection Report Date Wise','sale22',1,2,'',188)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(189,'Financial Performance Report','sale23',1,2,'',189)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(190,'Rebate Payment','RBTPMT',4,5,'',190)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(191,'Sales Commission Report','SALCOM',4,5,'',191)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(192,'Sales Commission Detail Report','SALCOMDET',1,2,'',192)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(193,'Customer Balance','ARCUSTBAL',4,1,'',193)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(194,'Vendor Balance','VENDBAL',4,2,'',194)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(195,'LC Register','LCREG',4,2,'',195)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(196,'Sales Commission Payment','SALCOMMPAY',4,5,'',196)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(197,'Sales Commission Eligibililty Report','SALCOMELG',4,5,'',197)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(198,'Customer Inquiry','customerinquiry',3,1,'poscbRRR',198)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(199,'Compalints Register','COMPREG',3,1,'poscbRRR',199)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(200,'Customer Inquiry','customerinquiry',1,5,'',200)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(201,'Complaints Register','ComplRegist',1,5,'poc',201)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(202,'Sales Promotion Details','SALPROMDET',4,5,'',202)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(203,'Incoming Documents','DOCIN',7,6,'',203)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(204,'Outgoing Documents','DOCOUT',7,6,'',204)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(205,'Agreement Register','AMTREG',7,6,'',205)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(206,'Ledger Postings','LEDGER_POSTINGS',4,4,'',206)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(207,'Sales Register','SALEREG',1,2,'',207)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(208,'Shipment Clearance Cheque Details','SHIPCLR',4,5,'',208)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(209,'Clearence Request','ClReq',3,3,'pom',209)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(210,'Clearence','Cle',3,3,'pom',210)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(211,'Local Clearence Request','LCR',3,3,'pom',211)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(212,'Local Purchase Order','LPO',3,3,'pom',212)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(213,'Co-Mail Register','Com',3,3,'pom',213)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(214,'Ticketing','Tkt',3,3,'pom',214)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(215,'Medical Details','Med',3,3,'pom',215)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(216,'Passport Details','Ppt',3,3,'pom',216)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(217,'Work/Permit Visa','Wpv',3,3,'pom',217)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(218,'Commission Invoice','COMINV',3,3,'pom',218)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(219,'Boat Note Processing','BNPROC',3,3,'pom',219)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(220,'Handling Debit Note','HANDBN',3,3,'pom',220)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(221,'Service Invoice','SERVINV',3,3,'poscbm',221)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(222,'Staff Performance','Staffper',3,2,'pocRRR',222)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(223,'Service History','Serhis',3,2,'pocRRR',223)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(224,'Service Call Booking','Sercallbooking',3,3,'pocRRR',224)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(225,'Service History','Serhis',1,4,'poc',225)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(226,'Staff Performance','Staffper',1,4,'poc',226)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(228,'Bank Position Report','BANKPOS',1,2,'',228)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(229,'Tools Allottment List','ToolsAllot',3,2,'pocRRR',229)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(230,'Tools List','ToolsList',3,2,'pocRRR',230)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(231,'Tools List','ToolsList',1,4,'poc',231)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(232,'Tools Allottment List','ToolsAllot',1,4,'poc',232)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(233,'Tools Allocation','ToolAllocation',3,3,'pocRRR',233)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(234,'Tools Return','Toolret',3,3,'pocRRR',234)
Go
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(237,'Maintenance Contract','Mcontract',3,3,'pocRRR',237)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(238,'Packing List','packlist',3,3,'pobRRR',238)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(239,'Goods Exportation Expense Report','GoodsExportation',3,1,'pob',239)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(240,'Facility Booking','facBook',3,3,'pol',240)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(241,'Facility Tracking','facTrack',3,3,'pol',241)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(242,'Item Merging','ItemMerging',1,6,'pol',242)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(243,'Agreement','AGMNT',3,3,'pol',243)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(244,'Reservation','RESVN',3,3,'pol',244)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(245,'Tenant Register','TENREG',3,3,'pol',245)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(246,'Kegs Return','kegsreturn',3,1,'pobRRR',246)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(247,'Kegs Return','kegreturn',1,2,'pobRRR',247)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(250,'Room Occupancy Details','ROD',3,4,'pol',250)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(251,'Room Occupancy Details','ROD',1,6,'pol',251)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(252,'Utility Billing','UTB',3,3,'pol',252)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(253,'Room Item List','RIL',1,6,'pol',253)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(254,'Room Item List','RIL',3,4,'pol',254)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(255,'Apartment Rent invoice','apartmentinvoice',3,3,'pol',255)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(257,'Occupancy Status','occupancy',3,1,'pol',257)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(258,'Occupancy Status','occupancy',1,6,'pol',258)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(259,'Utility Bill','utilitybill',3,1,'pol',259)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(260,'Utility Bill','utilitybill',1,6,'pol',260)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(261,'Aparmtent Room Checkout','APRC',3,3,'pol',261)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(262,'Aparmtent Room Checkout','APRC',1,6,'pol',262)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(263,'Apartment Check In','apartmentcheckin',3,1,'pol',263)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(264,'Apartment Check In','apartmentcheckin',1,6,'pol',264)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(265,'Apartment Check Out','apartmentcheckout',3,1,'pol',265)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(266,'Apartment Check Out','apartmentcheckout',1,6,'pol',266)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(267,'Machine Repair Register','serv12',1,4,'poc',267)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(268,'Machine Repair Register','serv13',3,2,'pocRRR',268)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(269,'Service Record','serv14',3,2,'pocRRR',269)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(270,'Service Record','serv15',1,4,'poc',270)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(271,'Porject Request','PROJECT_REQUEST',3,3,'PORRR',271)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(272,'Inter Division Sales Request','intersalesrequest',3,3,'poscbRRR',272)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(273,'Day End report','dayendreport',3,1,'poscbRR',273)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(274,'Ratio Analysis','RATIO',4,6,'',274)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(275,'Ratio Details','RATIODET',4,6,'',275)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(276,'Dummy Receipts','DumReceipt',1,5,'poscbRRR',276)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(277,'Daily Credit Sales','DailyCreditSales',1,5,'poscbRRR',277)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(278,'Payment Unsettled','Unsettled Payments',4,5,'',278)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(279,'Market Rates','marketrates',1,5,'poscbRRR',279)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(280,'User Auditing and Tracking','UserAudit',1,5,'',280)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(281,'Re-Export Request','ReexpReq',3,3,'pobRRR',281)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(282,'Re-Export Quotation','ReexpQuot',3,3,'pobRRR',282)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(283,'Re-Export Order','ReexpOrd',3,3,'pobRRR',283)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(284,'Re-Export Invoice','ReexpInv',3,3,'pobRRR',284)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(285,'Service Estimation','EstTrans',3,3,'poc',285)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(286,'Job Card','jbcd',3,3,'poc',286)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(288,'Agreement Summary','AMTSUM',7,6,'',288)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(289,'User auditing','UserInv',2,3,'',289)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(291,'Boat Note Period','BNPER',3,1,'pom',291)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(292,'Customer Sales Itemwise','csaleqty',1,2,'p&c',292)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(293,'Ticketing Details','TICKDET',3,1,'pom',293)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(294,'Godown Dispatch Invoice-Credit','SplInvCR',3,3,'poscbRRR',294)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(295,'Goods Return After Despatch','SInvRAD',3,3,'poscbRRR',295)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(297,'Inter Division Sales','IDivSales',1,7,'',297)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(298,'Inter Division Purchase','IDivPur',1,7,'',298)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(300,'Project Details Summary','PrjSumm',1,7,'',300)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(301,'Project Details Summary','PrjSumm',3,5,'poscbRR',301)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(302,'Tenant Wise Utility Bill','TENWUTILB',3,1,'pol',302)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(303,'Monthly Tenant Utility Report','MONTENUTIL',3,1,'pol',303)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(304,'HQ Admin Rights','AHQAR',1,5,'',304)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(305,'POS Admin Rights','APOSAR',3,5,'poscbRR',305)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(306,'Inventory Admin Rights','AINVAR',2,3,'',306)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(307,'UnConfirmed Transactions','UNCONTRANS',1,5,'',307)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(308,'Item Recovery','ItemRec',3,1,'poscbRRR',308)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(309,'Item Recovery','ItemRec',2,1,'',309)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(310,'Distribution Details','HqDist',1,5,'',310)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(311,'Goods Request/Despatch/Arrival Difference','GRDAD',1,5,'P&C',311)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(312,'Goods Request Status','GRSAT',1,5,'P&C',312)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(313,'Goods Request/Despatch/Arrival Difference','POSGRDAD',3,1,'poscbRRR',313)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(314,'Asset Flow Details','AssetDetails',4,3,'ACC',314)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(315,'Service Alerts','HQSERVALT',1,4,'P&C',315)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(316,'Service Alerts','POSSERVALT',3,2,'pocRRR',316)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(317,'Service Intimation','POSSERVint',3,2,'poc',317)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(318,'Export Flow Details','ExpSumm',3,5,'poscbRR',318)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(319,'Export Flow Details','ExpSumm',1,7,'',319)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(320,'Export Summary','ExpDet',1,7,'',320)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(321,'Export Summary','ExpDet',3,5,'poscbRR',321)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(325,'Item Sales Customerwise','isaleqty',1,2,'p&c',325)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(330,'Service/Sales Collection','sersls350',1,4,'p&C',330)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(332,'Service Agreement Details','POSSERVagree',3,2,'poc',332)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(333,'Export Cancellation','expcanc',3,1,'pob',333)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(334,'Export Item Sales History','expsaleh',3,1,'pob',334)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(335,'Sales Contract','expscont',3,3,'pob',335)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(336,'Technician wise Service Collection','techcoll',3,2,'poc',336)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(337,'Asset Summary','AstSumm',4,3,'Acc',337)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(338,'Fixed Asset Register','AstReg',4,3,'Acc',338)
Go
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(339,'Asset Addition','AstAdd',4,3,'Acc',339)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(340,'Asset Transfer','AstTrans',4,3,'Acc',340)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(341,'Asset Disposal','AstDis',4,3,'Acc',341)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(342,'Asset Depreciation','AstDep',4,3,'Acc',342)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(350,'Cash Flow Statement','cashflow',4,9,'acc',350)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(351,'Budget Plan','BudPlan',6,1,'',351)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(352,'Budget Actual/Planned','BudVar',6,1,'',352)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(353,'Budgeted Balance Sheet','PlanBsheet',6,1,'',353)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(354,'Budgeted Profit and Loss','PlanPL',6,1,'',354)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(355,'Budgeted Trial Balance','PlanTB',6,1,'',355)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(356,'Purchase History','PHist',1,3,'',356)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(357,'Budgeted Sales','BudSales',1,8,'',357)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(358,'Pending Controls Account Trans','PenControl',4,5,'',358)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(359,'Budgeted Purchase','BudPur',1,8,'',359)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(360,'Budgeted Sales and Cost variance','BudSalesV',1,8,'',360)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(361,'Budgeted Purchase variance','BudPurV',1,8,'',361)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(362,'Current Fixed Cost','CurFcost',1,8,'',362)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(363,'Fixed Cost','FcostList',1,8,'',363)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(364,'Budget Details','bdgdts',6,1,'bdg',364)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(365,'Discount Sales Summary','sale24',1,22,'',365)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(366,'Discount Sales Detailed','sale25',1,22,'',366)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(367,'PO Status','purordstatus',1,3,'',367)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(368,'Import Item Details (Advanced)','oth12Adv',1,5,'',368)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(369,'Shipment Costing Detail','scdetail',1,3,'',369)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(370,'Pending Bills For Costing','PendBills',1,3,'',370)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(371,'Customer Sales','custsales',1,5,'',371)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(372,'Point Of Sale User Auditing','POSUserAudit',1,5,'',372)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(373,'Sales and Collection Detailed','SalColDet',1,2,'',373)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(374,'Daily Sales and Returns','DalSalRet',1,2,'',374)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(375,'Sales And Stock','SalStock',1,2,'',375)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(376,'Import Details','purImportDet',1,3,'',376)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(396,'Daily Shop Transaction Details','dailyTrans',3,1,'poscbRR',396)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(397,'Petty Cash Payments','PCP',4,5,'',397)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(398,'HP Fee Payment','HPFP',4,5,'',398)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(399,'HP Processing','HPPR',4,8,'',399)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(400,'Stock Balancing','StockBal',1,1,'',400)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(401,'Inventory Age Analysis','InvAge',1,1,'',401)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(402,'Location Wise Stock','LocStock',1,1,'',402)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(403,'Shipment Expences','ShipExp',1,3,'',403)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(404,'Purchase Details','PurDet',1,3,'',404)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(405,'Customer Wise Item Sales','CustWiseItmSal',1,2,'',405)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(406,'POS AccountWise Details','posAccDet',3,1,'poscbRRR',406)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(407,'Unconfirmed Transactions','posUncon',3,1,'poscbRRR',407)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(408,'Internal Consumption Details','intConDet',1,5,'poscbRRR',408)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(409,'Post Dated Cheques','PtDtdCheque',4,5,'',409)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(410,'Purchased Items VendorWise','PurVenWise',1,3,'',410)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(412,'Import Details VendorWise','ImptVend',1,3,'',412)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(414,'Item Brochure','ItmBro',1,3,'',414)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(415,'Item Price List GodownWise','ItmPriceGdn',1,1,'',415)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(416,'Total Item Flow','TotItmFlow',1,1,'',416)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(417,'Cash Flow Statement','SPCashflow',4,4,'acc',417)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(420,'Godown Dispatch Invoice Quotaion','GdnDesQuot',3,3,'poscbRRR',420)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(421,'Monthly Itemwise Sales (Advanced)','MonSalesAdv',1,2,'',421)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(422,'Productwise Sales (Advanced)','ProdnSalesAdv',1,2,'',422)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(423,'Sales Register (Advanced)','SalesRegAdv',1,2,'',423)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(424,'Sales/Import Analysis (Advanced)','SalesImpAdv',1,2,'',424)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(426,'Stock Verification Details Shop Wise','StvShopWise',1,5,'',426)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(427,'Stock Verification Details Godown Wise','StvGdnWise',1,5,'',427)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(428,'Stock Write Off Details Shop Wise','WrtShopWise',1,5,'',428)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(429,'Stock Write Off Details Godown Wise','WrtGdnWise',1,5,'',429)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(430,'Damage Clearing Details Shop Wise','DCShopWise',1,5,'',430)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(431,'Damage Clearing Details Godown Wise','DCGdnWise',1,5,'',431)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(432,'Delivery Note Date-wise','DelNoteDateWise',3,1,'poscbRRR',432)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(433,'Pending Invoices To Be Delivered','PendingDelivery',3,1,'poscbRRR',433)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(434,'Delivery Note Customer-wise','DelNoteCustWise',3,1,'poscbRRR',434)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(435,'Delivery Note Item-wise','DelNoteItemWise',3,1,'poscbRRR',435)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(500,'Discount Given','DiscGiven',3,1,'poscbRRR',500)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(501,'User Auditing On RateEditing','UserAuditRate',1,5,'',501)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(502,'HP Advance Received','HPADVRECEIPT',4,8,'',502)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(503,'HP Financial Income Earned ','HPFININCOME',4,8,'',503)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(505,'HP Quotation','HPQuotation',3,3,'poscbRRR',505)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(506,'HP Invoice','HPInvoice',3,3,'poscbRRR',506)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(507,'HP Shop Receipts','HPShopReceipts',3,3,'poscbRRR',507)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(514,'Inhouse Return','IHRE',3,3,'poscbRRR',514)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(515,'Inhouse Return','IHRE',4,5,'',515)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(519,'Location Wise Stock-SSRS','LocStockSSRS',1,1,'',519)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7001,'Test Alert7001','testalert',8,1,'pobRRR',7001)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7002,'Test Alert7002','ABC',9,1,'pobRRR',7002)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7003,'Test Alert7003','AB',8,1,'pobRRR',7003)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7004,'Document Alerts','7003DA',10,1,'admalt',7004)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7005,'Agreements Alert','7005DA',10,1,'admalt',7005)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7006,'Debit Credit Note to Process','dcnp',11,2,'ACC',7006)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7007,'Journals to Process','jtp',11,2,'ACC',7007)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7008,'Payments to be Processed','ptp',11,2,'ACC',7008)
Go
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7009,'Receipts to be processed','rtp',11,2,'ACC',7009)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7010,'Bills to be Processed','btp',11,2,'ACC',7010)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7011,'Invoices to be Processed','itp',11,2,'ACC',7011)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7012,'Vendor Bills Pending To be Settled','vbptp',11,1,'ACC',7012)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7013,'Bills Pending To be Settled','bptp',11,1,'ACC',7013)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7014,'Opening Stock Costing not done','oscnd',12,1,'P&C',7014)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7015,'Opening Balances in Accounts not tallying. Pls Check','obat',12,1,'P&C',7015)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7016,'Godown Dispatch Invoice not Despatched','sind',12,1,'P&C',7016)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7017,'PO Generated but not billed','pspor',12,1,'P&C',7017)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7018,'Bills which are not costed','bwnc',12,1,'P&C',7018)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7019,'Pending PO held for item creation','ppohc',12,1,'P&C',7019)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7020,'Bills not despatched','blnd',12,1,'P&C',7020)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7022,'Request for new items','rfni',12,1,'P&C',7022)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7023,'Item Splitted not costed','isnc',12,1,'P&C',7023)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7024,'Local Purchase not costed','lpnc',12,1,'P&C',7024)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7025,'Pending Shop PO Requests','pspor',12,1,'P&C',7025)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7026,'Merging Completed, To be Costed','mctc',12,1,'P&C',7026)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7027,'Administrator Alert','admal',12,1,'P&C',7027)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7030,'Goods arrival from Head Quarters','gafhq',13,1,'inv',7030)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7031,'Goods arrival from Godown','gafgd',13,1,'inv',7031)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7032,'Goods arrival from Shop','gafsh',13,1,'inv',7032)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7033,'Issue note arrival notification','inan',13,1,'inv',7033)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7034,'Pending Godown Dispatch Invoices','psinv',13,1,'inv',7034)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7035,'Godown Dispatch Invoice Deleted which are despatched','spinvdd',13,1,'inv',7035)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7036,'Items without Packing Type','iwopt',13,1,'inv',7036)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7037,'Godown Dispatch Invoices Not Despatched From Godown','sindfgd',14,1,'posbRRR',7037)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7038,'Purchase Request Not Quoted','prnq',14,1,'posbRRR',7038)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7039,'Purchase Order not Invoiced','poninv',14,1,'posbRRR',7039)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7040,'Stockout Notification','sotn',14,1,'posbRRR',7040)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7041,'Pending Rebate Requests','prrq',14,1,'posbRRR',7041)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7042,'Medical Report Details','mrdtl',14,1,'pom',7042)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7043,'Passport Details','pasdtl',14,1,'pom',7043)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7044,'Tools pending to be returned','tlret',14,1,'pom',7044)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7045,'Work Permit Details','wpdtl',14,1,'pom',7045)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7046,'Goods Request From Shop Notification','grqfs',14,1,'posbRRR',7046)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7047,'Items Pending to be Recovered','iptr',14,1,'posbRRR',7047)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7048,'Shop items having selling price not fixed','sihspnf',14,1,'posbRRR',7048)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7049,'Goods Arrival From Godown Notification','gafs',14,1,'posbRRR',7049)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7050,'Goods Arrival From Shop Notification','gafsh',14,1,'posbRRR',7050)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7051,'Goverment Fee ALerts','GFA',11,1,'ACC',7051)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7052,'Expired Items Alert','sexpalt',14,1,'poscb',7052)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7053,'Expired Items Alert','sexpalt',13,1,'inv',7053)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7054,'Pending Dummy Receipt','DRS',11,1,'ACC',7054)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7055,'Ticketing Alerts','TICAL',14,1,'pom',7055)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7056,'Service Alerts','SERAL',14,1,'pocRRR',7056)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7057,'Contract Alerts','CONAL',14,1,'pocRRR',7057)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7058,'Stock Reordering','purstock',1,3,'',7058)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7059,'Goods Request/Godown Despatch/Arrival Difference','GRGDAD',1,5,'P&C',7059)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7060,'Agreement Details','HPAG',1,9,'P&C',7060)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7061,'Item Location Transfer Details','HPLTR',1,9,'P&C',7061)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7062,'Item sales Month wise','HPSALES',1,9,'P&C',7062)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7063,'Hire Purchase Advance Received','HPADVANCE',1,9,'P&C',7063)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7064,'Hire Purchase Application Received','HPAPP',1,9,'P&C',7064)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7065,'Hire Purchase Road Worthness','HPROAD',1,9,'P&C',7065)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7066,'Hire Purchase ItemStatus','HPITEMSTATUS',1,9,'P&C',7066)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7067,'Hire Purchase Cheque Received','HPCHQREC',1,9,'P&C',7067)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7068,'Hire Purchase Cheque Bounced','HPCHQBOU',1,9,'P&C',7068)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7070,'Shipmentwise Item Sale','SHIPSALE',1,3,'P&C',7070)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7100,'HP Outstanding Invoices','HPOUTINVOICE',4,7,'',7100)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7101,'HP Debtor Age Analysis','HPDBAGEANALYSIS',4,7,'',7101)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7102,'HP Customer Statement','HPCUSTLEDGER',4,7,'',7102)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7103,'HP Customer Summary','HPCUSTSUMMARY',4,7,'',7103)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7104,'Letter/Remainder','HPLETTERREM',4,7,'',7104)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7105,'HP Customer Balance','HPARCUSTBAL',4,7,'',7105)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7106,'Bin card Audit CustWise','inv11',1,1,'',7106)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7107,'Customer - Item Sold History','itemSaleCust',1,1,'',7107)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7108,'Inventory Forecastment','InvForeCast',1,1,'',7108)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7109,'Stock Items With Serial No','serialitemstock',1,1,'P&C',7109)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7110,'Issued Items Having Serial No ','serialitemissuestock',1,1,'P&C',7110)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7112,'Issued Items Having Serial No','serialitemissuestock',3,1,'poscbRRR',7112)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7113,'Stock Items Having Serial No','serialitemstock',2,1,'inv',7113)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7114,'Issued Items Having Serial No','serialitemissuestock',2,1,'inv',7114)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7121,'Item Expiry Details','ITEMEXPIRY',1,1,'P&C',7121)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7122,'Item Expiry Details','ITEMEXPIRY',3,1,'poscbRRR',7122)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7123,'Item Expiry Details','ITEMEXPIRY',2,1,'inv',7123)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7124,'HP Overdue Balance','HPOVERDUE',4,8,'',7124)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7126,'Warranty Claim','WC',1,2,'',7126)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7127,'Business Promotion','BP',1,2,'',7127)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7128,'HP Settled and Non settled Customers','HPSETTLEDCUST',4,8,'',7128)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7129,'Sales Register Month Wise','SALEREGMON',1,2,'',7129)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7130,'Purchase and Stock','PBAndStock',1,3,'P&C',7130)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7131,'Shop Sales Account wise','AccSale',1,2,'',7131)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7132,'Shipmentwise Item Sale Advanced','SHIPSALEADVANCED',1,3,'P&C',7132)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7133,'HP Nonperforming Customers','HPNONPERFORM',4,8,'',7133)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7134,'Cost Breakup','COSTBREAKUP',1,3,'',7134)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7135,'Warrenty Claim Between Dates','WARDATE',4,5,'',7135)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7136,'OverDue Outstanding Invoices','OUTDUEINVOICE',4,1,'',7136)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7137,'HP Performing Customers','HPPERFORM',4,8,'',7137)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7138,'HP Customer Advance Payment','HPCUSTADVPAY',4,8,'',7138)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7139,'HP Customer Reconcilation','HPCUSRECON',4,8,'',7139)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7140,'Stock Out Items Forecasting','STOCKOUTFORECASTING',3,1,'poscbRRR',7140)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7141,'Stock Out Items Forecasting','STOCKOUTFORECASTING',1,1,'',7141)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7143,'Sales Person performance item wise','sales22',1,2,'',7143)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7144,'Delivered Items','DeliItems',3,1,'poscbRRR',7144)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7148,'Dummy Pos','dummypos',3,3,'poscbRRR',7148)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7149,'Non-Buying Customer Itemwise','ItmNonCust',1,2,'PandC',7149)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7151,'Items DespatchToShop','ITEMDTS',2,1,'inv',7151)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7152,'PO VendorWise','purOrVWise',1,3,'',7152)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7153,'Daily Sales','DAILYSALES',3,1,'poscbRRR',7153)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7154,'Service Revenue','ServRevSep',3,2,'pocRRR',7154)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7155,'Sales Person Performance','SalesPersPerf',3,1,'poscbRR',7155)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7156,'Service Done Service Category Wise ','SercatServAmt',3,2,'pocRRR',7156)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7159,'Item Sale Serial Number Details','salesrno',3,1,'poscbRRR',7159)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7162,'HP Processing Details','HPPROCEDETAILS',4,8,'NULL',7162)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7166,'Hourly Sales Analysis','HrSaleAnlysis',3,1,'poscbRRR',7166)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7167,'Basket Value Analysis','BasValAnlysis',3,1,'poscbRRR',7167)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7168,'PO Item List','POItemList',1,3,'P&C',7168)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7169,'Purchase Status','PStatus',1,3,'P&C',7169)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7170,'Sales Margin Report','SalesMargin',3,6,'F&B',7170)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7171,'Day wise Average Quantity Sale Report','DaywiseAvgQtySale',3,6,'F&B',7171)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7172,'Sales Quantity Value Report','SalesQtyValue',3,6,'F&B',7172)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7173,'Till End Credit Sales Details','TillEndCrSalesDtls',3,6,'F&B',7173)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7174,'Till End Summary Report','TillEndSummary',3,6,'F&B',7174)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7175,'Till End Stock Verification  Report','TillEndStockVerf',3,6,'F&B',7175)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7176,'Day End Report-User wise','DayEndReportUserwise',3,1,'poscbRR',7176)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7177,'Dish Category Sales','DishCategorySales',3,6,'F&B',7177)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7181,'Tax Reports','taxrates',1,5,'',7181)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7182,'Account Receivable Audit','AccRecAudit',4,1,'',7182)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7184,'Account Wise Posting','ACCOUNTWISEPOSTING',4,9,'acc',7184)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7185,'Local Purchase Items Serial Numbers','LPIHSN',1,3,'P&C',7185)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7186,'Complimentary Item Value Report','CIVR',3,6,'F&B',7186)
INSERT INTO [adminv2].[dbo].[aReports]  ([ReportID]  ,[ReportName]  ,[Reportconst]  ,[ReportCatId]  ,[ReportDetailId]  ,[repModuleCode]  ,[ReportActive])  VALUES(7187,'Inventory Valuation Difference','invD',1,1,'',7187)

Go
-------------------------[reportcategorydetail],[reportcategoryheader] START----------------------------------------------

DELETE FROM [adminv2].[dbo].[reportcategorydetail]
DELETE FROM [adminv2].[dbo].[reportcategoryheader]

Go
-------------------------[reportcategorydetail] START----------------------------------------------
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(1,1,'Inventory','inv')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(1,2,'General','Root')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(1,3,'General','root')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(1,4,'Accounts Receivable','AccRec')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(1,6,'Budget','RBUDT')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(1,10,'General Alerts','10GL1')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(1,11,'General Alerts','Accalt')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(1,12,'General Alerts','Gen11')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(1,13,'General Alerts','Gen13')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(1,14,'General Alerts','Gen14')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(2,1,'Sales','sale')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(2,2,'Transactions','Trans')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(2,3,'Service','serv')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(2,4,'Accounts Payable','AccPay')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(2,6,'Target','RTAR')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(2,11,'Other Dept.Alerts','Accalt')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(3,1,'Purchase','pur')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(3,3,'Transaction Reports','Trans')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(3,4,'Fixed Asset','FASSET')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(4,1,'Service','serv')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(4,3,'Apartment Service','APser')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(4,4,'Ledger','LEDG')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(5,1,'Others','oth')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(5,4,'Edit Report','CHKLIST')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(6,1,'Apartment Service','APser')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(6,4,'Management Accounts','MGNTACC')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(6,7,'Documents','doc')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(7,1,'Transaction Summary','Transumm')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(3,2,'Others','Oth')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(5,3,'Others','oth')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(8,1,'MIS','BudMis')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(9,1,'Hire Purchase','HP')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(7,4,'HP Accounts Receivable','HPAccRec')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(8,4,'Hire Purchase','HP')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(6,3,'F and B Reports','F&B')
        INSERT INTO [adminv2].[dbo].[reportcategorydetail]             ([RepDetailId],[RepCatId],[RepDetailName],[RepConstant])       VALUES(9,4,'Other Reports','OTHER')
-------------------------[reportcategorydetail] STOP----------------------------------------------

Go

-------------------------[reportcategoryheader] START----------------------------------------------
        INSERT INTO [adminv2].[dbo].[reportcategoryheader]             ([repCatId],[repCatName],[repCatModCode],[Type])       VALUES(1,'PandC','HQADMIN','R')
        INSERT INTO [adminv2].[dbo].[reportcategoryheader]             ([repCatId],[repCatName],[repCatModCode],[Type])       VALUES(2,'Inventory','LOCALADMIN','R')
        INSERT INTO [adminv2].[dbo].[reportcategoryheader]             ([repCatId],[repCatName],[repCatModCode],[Type])       VALUES(3,'Pos','LOCALADMIN','R')
        INSERT INTO [adminv2].[dbo].[reportcategoryheader]             ([repCatId],[repCatName],[repCatModCode],[Type])       VALUES(4,'Accounts','HQADMIN','R')
        INSERT INTO [adminv2].[dbo].[reportcategoryheader]             ([repCatId],[repCatName],[repCatModCode],[Type])       VALUES(5,'Payroll','HQADMIN','R')
        INSERT INTO [adminv2].[dbo].[reportcategoryheader]             ([repCatId],[repCatName],[repCatModCode],[Type])       VALUES(6,'Budgetting','HQADMIN','R')
        INSERT INTO [adminv2].[dbo].[reportcategoryheader]             ([repCatId],[repCatName],[repCatModCode],[Type])       VALUES(7,'Admin','HQADMIN','R')
        INSERT INTO [adminv2].[dbo].[reportcategoryheader]             ([repCatId],[repCatName],[repCatModCode],[Type])       VALUES(10,'Administration','HQADMIN','A')
        INSERT INTO [adminv2].[dbo].[reportcategoryheader]             ([repCatId],[repCatName],[repCatModCode],[Type])       VALUES(11,'Accounts','HQADMIN','A')
        INSERT INTO [adminv2].[dbo].[reportcategoryheader]             ([repCatId],[repCatName],[repCatModCode],[Type])       VALUES(12,'pandc','HQADMIN','A')
        INSERT INTO [adminv2].[dbo].[reportcategoryheader]             ([repCatId],[repCatName],[repCatModCode],[Type])       VALUES(13,'Inventory','LOCALADMIN','A')
        INSERT INTO [adminv2].[dbo].[reportcategoryheader]             ([repCatId],[repCatName],[repCatModCode],[Type])       VALUES(14,'Pos','LOCALADMIN','A')
-------------------------[reportcategoryheader] STOP----------------------------------------------
-------------------------[reportcategorydetail],[reportcategoryheader] STOP----------------------------------------------


-------------------------[MiscInquiry] START----------------------------------------------
Go

DELETE FROM [adminv2].[dbo].[MiscInquiry]

Go

INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7006,'Debit Credit Note to Process','For Alerting Debit Credit Process','select distinct dcnno as [DC Number],dcndate [DC Date],departmentname as [Department],                  dcnremarks as [Remarks] From vwdcnwithcontrolaccdep where dcncompanyid=                  ?C? and maindepid=?D?','Debit Credit Note to Process',1,1,'A','acalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7008,'Payments to be Processed','For Alerting Payments to Process','select distinct phpaymentno as [Payment Number],phpaymentDate as [Date],departmentname   as [Department],phRemarks as [Remarks]  from vwpaymentswithcontrolaccs where    phcompanyid=?C?  and maindepid=?D?','Payments to be Processed',1,1,'A','acalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7010,'Bills to be Processed','For Alerting Bills','select distinct BillsNo as [Bill Number],BillDate as [Date],departmentname as   [Department],Remarks from vwBillsWithControlAccounts where companyid=?C?     and maindepid=?D?','Receipts to be Processed',1,1,'A','acalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7012,'Vendor Bills Pending To be Settled','For Alerting Vendor Bills Pending To be Settled','spvendoroutstanding ?D?,?DT?','Vendor Bills Pending To be Settled',1,1,'A','acalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7014,'Opening Stock Costing not done','For Alerting Opening Stock Costing','select count(*)[Total] from  vwopeningstock [op],vwitemdescription [vwitd],aitem [im] where op.itemid   not in ( select cd.cditemid from LOaCostingDetail [cd] where  cdcostingid = 0 ) and    vwitd.itemid = op.itemid And im.itemid = op.itemid And opstock <> 0 And opstock Is Not Null','Opening Stock Costing not done',1,1,'A','pcalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7019,'Pending PO held for item creation','For Alerting Pending PO held for item creation','select a.pohpoid[purch.order Id],a.pohpono[Purch.ordeer No],a.pohpodate[Date],b.vendorname[Vendor],           a.pohduedate[Due D,pohvalue[value],pohremarks[Remarks] from lopurchaseorderheader [a],           avendormaster [b] Where a.pohvendorid = b.vendorid And pohcancel = 0            and pohbillgenerated = 0 and pohQuotationid=0 and a.pohpoid<>0            and pohDepartmentid = ?D? and pohpoonhold=1 order by a.pohpoid','Pending PO held for item creation',1,1,'A','pcalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7013,'Pending Bills To be Settled','For Alerting Pending Bills To be Settled','spUnsettledAccBills ?C?,?D?,0,?DT?','Pending Bills To be Settled',1,1,'A','acalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7022,'Request for new items','For Alerting Request for new items','select m.godownid[Godown Id], godownname[Godown Name], itemcode[Item Code], itemdescription[Item Description] from meirqtohqforitem [m],    agodown [g] Where g.godownid = m.godownid and g.departmentid= ?D?  union all   select m.shopid, shopname, itemcode, itemdescription from mesrqtohqforitem [m],   ashops [s] Where s.shopid = m.shopid and s.departmentid=?D?','Request for new items',1,1,'A','pcalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7023,'Item Splitted not costed','For Alerting Item Splitted not costed','select ishno[Issue No],ishdate[Issue Date],gd.godownname[Godown],ishremarks from loiitemsplitheader       [loi] left outer join agodown [gd] on loi.ishgodownid=gd.godownid where       ishcostpricefixed=0 and ishcancelled=0 and gd.departmentid=?D? ','Item Splitted not costed',1,1,'A','pcalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7048,'Shop items having selling price not fixed','For Alerting Shop items having selling price not fixed','select aitem.itemcode[Item Code],vwitemdescription.itemdescription[Item Description],   sshipmentno[Shipment No] from losShopitemshipmentdetail,vwitemdescription,aitem,ashipment         where losShopitemshipmentdetail.itemid=aitem.itemid and vwitemdescription.itemid=         aitem.itemid and losShopitemshipmentdetail.shipmentid=ashipment.sShipmentid and          aitem.pricefixedathq=0 and losShopitemshipmentdetail.sellingprice +          losShopitemshipmentdetail.discountprice + losShopitemshipmentdetail.wholesaleprice          <=0 and losShopitemshipmentdetail.shopid=?S?','Shop items having selling price not fixed',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7034,'Pending Special Invoices','For Alerting Pending Special Invoices','select IhInvoicedate[Invoice Date], ihinvoiceno[Invoice NO], shopname[Shop Name], ihremarks[Remarks] from             losSpecialInvoiceHeader [a], losSpecialInvoicedetail [b], ashops [s]            where a.ihinvoiceid =b.idinvoiceid and   a.ihShopid=b.idShopid             and b.despatch=0 and b.reqqty>0 and idRateType =0  and a.ihCancelled = 0             and a.ihshopid=s.shopid and ihTransfinished = 1 and b.idGodownid=?G? group by              a.ihInvoiceid,a.ihInvoiceno,IhInvoicedate ,shopname, ihremarks','Pending Special Invoices',1,1,'A','inalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7036,'Items without Packing Type','For Alerting Items without Packing Type','select itemdescription[Item Description] from vwitemdescription v,   agodownDetail d where v.itemid = d.itemid and v.itemid not in           (select itemid from aitempackingdetail) and d.godownid = ?G?','Items without Packing Type',1,1,'A','inalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7015,'Opening Balances in Accounts not tallying. Pls Check','For Alerting Opening Balance Accounts Not Tallying','select openingbalancenottallying[Opening Balance Not Tallying] from miscsettings','',1,1,'A','pcalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7026,'Merging Completed, To be Costed','For Alerting Merging Completed, To be Costed','select * from aHqMergingHeader, aitem  where mghTransFinished =1 and    mghCostPriceFixed = ''r'' and mghCancelled=0 and mghItemid = itemid','Merging Completed, To be Costed',1,0,'A','pcalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7027,'Administrator Alert','For Administrator Alert','sp_helpmergearticleconflicts','Administrator Alert, To be Costed',1,0,'A','pcalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7024,'Local Purchase not costed','For Alerting Local Purchase not costed','select lphbillno[Bill No],lphBilldate[Bill Date],sd.shopname[Shop Name],lphremarks[Remarks] from loslocalpurchaseheader [loi]       left outer join ashops [sd] on loi.lphshopid=sd.shopid        where lphcosted=0 and lphcancelled=0 and lphDepartmentID=?D?','Local Purchase not costed',1,1,'A','pcalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7047,'Items Pending to be Recovered','For Alerting Items Pending to be Recovered','select aitem.itemcode[Item Code],vwitemdescription.itemdescription[Item Description],sshipmentno from losShopitemshipmentdetail,vwitemdescription,aitem,ashipment         where losShopitemshipmentdetail.itemid=aitem.itemid and vwitemdescription.itemid=aitem.itemid and losShopitemshipmentdetail.shipmentid=ashipment.sShipmentid and         aitem.pricefixedathq=0 and losShopitemshipmentdetail.sellingprice +    losShopitemshipmentdetail.discountprice + losShopitemshipmentdetail.wholesaleprice <=0 and losShopitemshipmentdetail.shopid=?S?','Items Pending to be Recovered',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7002,'Test 1','Test Comm 1','select * from aShops','',1,1,'a','inalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7003,'Test 1','Test Comm 1','select * from aShops','',1,1,'a','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7004,'Document Alerts','For InComing / Outgoing Documents','Select DocDate [Date], DocNo [Doc No], ReferenceNo [Ref No],  Sender,case Doctype when ''i'' then '' Incoming '' else '' Outgoing ''  end [Doc Type],alertremarks [Remarks] from iodocuments i, apackagesettings s   where s.companyid = 1 and (packagedate + alertnoofdays) >= alertdate and  depid =?d?','Document Alert',1,1,'A','adalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7005,'Agreement Alerts','For alerting different agreement registers',' Select agragreementNo [Agreement No], agragreementdate [Agreement Date],   agragreementdesc [Description],  alertremarks [Remarks]  from AgreementRegister i, apackagesettings s where s.companyid = 1 and  (packagedate + isnull(alertnoofdays,0)) >= agrValidTodate and agrDepartmentid=?d?','Aggreement Alert',1,1,'A','adalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7007,'Journals to Process','For Alerting Journals to Process','select distinct journalno as [Journal Number],JournalTransDate as [Date],departmentname    as [Department],Remarks From vwjournalswithcontrolaccs where companyid=?C?           and maindepid=?D?','Journals to Process',1,1,'A','acalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7009,'Receipts to be processed','For Alerting Receipts','select distinct receiptno as [Receipt Number],receiptDate as [Date],departmentname as [Department],   Remarks from vwreceiptswithcontrolaccs where companyid=?C? and    maindepid=?D?','Receipts to be Processed',1,1,'A','acalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7001,'Test 1','Test Comm 1','select * from aShops','',1,1,'a','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7038,'Purchase Request Not Quoted','For Alerting Purchase Request Not Quoted','select ih.ihinvoiceid[Invoice Id], ih.ihinvoiceno[Invoice No], ih.ihinvoicedate[Date], ih.ihreferenceno[Ref.No], ih.ihremarks[Remarks],    c.customername[Customer Name] from acustomermaster [c], losinvoiceheader [ih] left outer join    losinvoiceheader [q] on ih.ihshopid = q.ihshopid and ih.ihinvoiceid= q.ihproformaid    where c.customerid = ih.ihcustomerid and ih.ihshopid = ?S?     and ih.ihtype =''r'' and ih.ihcancelled =0 and isnull(q.ihproformaid,0) = 0','Purchase Request Not Quoted',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7039,'Purchase Order not Invoiced','For Alerting Purchase Order not Invoiced','select ih.ihinvoiceid[Invoice Id], ih.ihinvoiceno[Invoice No], ih.ihinvoicedate[Date], ih.ihreferenceno[Ref.No], ih.ihremarks[Remarks],    c.customername[Customer Name] from acustomermaster [c], losinvoiceheader [ih] left outer join    losinvoiceheader [q] on ih.ihshopid = q.ihshopid and ih.ihinvoiceid= q.ihproformaid    where c.customerid = ih.ihcustomerid and ih.ihshopid = ?S?     and ih.ihtype =''p'' and ih.ihcancelled =0 and isnull(q.ihproformaid,0) = 0','Purchase Order not Invoiced',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7040,'Items Having Stock Less Than Re-Order Level','For Alerting Items which went below Re-Order level','  SELECT i.ItemCode [Item Code],i.ItemDescription [Item Description],  st.stock [Shop Stock],sd.itemreorderlevel [Re-Order Level],sd.ReorderQuantity [Re-Order Quantity]  FROM ashopitemdetail [sd]   LEFT OUTER JOIN (SELECT shopid, itemid,      SUM(ISNULL(stock,0)) stock FROM vwinquiryshopstock [s]   GROUP BY s.shopid, s.itemid)             [st] ON  sd.shopid=st.shopid AND sd.itemid = st.itemid   INNER JOIN aItem i ON sd.itemid=i.ItemID  WHERE sd.shopid =?S?            AND sd.itemreorderlevel > stock AND sd.itemreorderlevel>0','Stockout Notification',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7041,'Pending Rebate Requests','For Alerting Pending Rebate Requests','select rr.rrreqdate[Req.Date],rr.rrRemarks[Remarks],ih.ihInvoiceNo[Invoice No],sm.Spername [SalesPerson],cm.CustomerName[Customer Name] From    losInvoiceHeader [ih], asalesPersonMaster [sm], aCustomerMaster [cm],          losrebaterequest [rr] left outer join (select rcShopid,rcreqid from    losrebateconfirmheader where rccancelled=0) [rc] on rr.rrshopid=rc.rcshopid and    rr.rrreqid = rc.rcreqid Where rr.rrshopid=ih.ihShopID and rr.rrpoid =ih.ihInvoiceID    and rr.rrsalespersonid = sm.Sperid And ih.ihCustomerID = cm.CustomerID           and isnull(rr.rrCancelled,0)=0 and isnull(rc.rcreqid,0)= 0 and ih.ihshopid=?S?','Pending Rebate Requests',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7042,'Medical Report Details','For Alerting Medical Report Details','select DocNo[DocNo],CustomerName[Customer] ,EmpName[Emp.Name] , MLastMedicalReportDate[Report Date], WExpireyDate[Exp.Date],Remarks[Remarks]           From losdocument [l], acustomermaster [ac] where l.CustomerID = ac.CustomerID and     doctype = ''ME'' and shopid =?S? and WExpireyDate - AlertBeforeDays <= ?DT? and WExpireyDate >= ?DT?','Medical Report Details',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7044,'Tools pending to be returned','For Alerting Tools pending to be returned','select distinct alchno[Allocation No],alchdate[Allocation Date],Spername[Sales Person],alchRemarks[Remarks] from  LosserToolsAllocationHeader [a]   left outer join aSalesPersonMaster [c] on a.alchtechnicianid = c.sperid and    a.alchCompanyId=c.CompanyId, LosserToolsAllocationDetail [b] where a.alchCompanyId = b.alcdCompanyId And a.alchShopid = b.alcdShopid and    a.alchid=b.alcdid and b.alcdreturned<>''Y'' and a.alchCancelled = 0 And    a.alchCompanyId = ?C? And a.alchShopid = ?S?','Tools pending to be returned',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7043,'Passport Details','For Alerting Passport Details','select DocNo ,CustomerName[Customer],EmpName[Emp.Name],PNationality[Nationality], PPassportNo[Passport No], PIssueDate[Issue Date],    PExpireyDate[Expiry Date], Remarks From losdocument [l] ,acustomermaster [ac] where l.CustomerID = ac.CustomerID   and doctype = ''PP'' and shopid = ?S? and PExpireyDate - AlertBeforeDays <= ?DT?          and PExpireyDate >= ?DT?','Passport Details',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7046,'Goods Request From Shop Notification','For Alerting Goods Request From Shop Notification','select srh.srhrequestdate[Req.Date], ashops.shopname[Shop Name], srh.srhrequestno[Req.No]    from MEsrequesttoshopheader [srh], ashops where srhtoshopid = ?S? and                     srhused = 0 and SRHcancelled=0 and srhshopid=ashops.shopid and srhTransfinished=1 and srhNoofDetails=(select count(*) from                     MEsrequesttoshopdetail [srd] where srh.srhRequestID=srd.srdRequestID and                     srh.srhShopid=srd.srdShopid) group by srh.srhrequestdate, ashops.shopname, srh.srhrequestno','Goods Request From Shop Notification',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7035,'Special Invoice Deleted which are despatched','For Alerting Special Invoice Deleted which are despatched','select ih.ihinvoiceno[Invoice No], ih.ihinvoicedate[Invoice Date], shopname, dh.dhdespatchno[Despatch No],              dh.dhdespatchdate[Date],ih.ihcancelledremarks[Remarks] from losspecialinvoiceheader [ih],       meispecialdespatchtoshopheader [dh], ashops [s] where        dh.dhissuenoteid = ih.ihinvoiceid and dh.dhshopid = ih.ihshopid and               ih.ihshopid=s.shopid and ih.ihcancelled=1 and dh.dhcancelled=0 and dhgodownid=?G?','Special Invoice Deleted which are despatched',1,1,'A','inalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7021,'Pending goods requests','For Alerting Pending goods requests','select GRHrequestID[Req.Id],GRHrequestNO[Req.No],GRHrequestDate[Req.Date],b.shopname[Shop Name],grhremarks[Remarks]            from mosGoodsRequestHeader [a], ashops [b] where a.grhshopid=b.shopid and            grhIssuenotegenerated = 0 And grhcancel = 0 and grhTransfinished=1 and            grhrequesttype=''g'' and b.departmentid= ?D?            and grhnoofdetails=(select count(*) from mosGoodsRequestdetail [grd] where            a.grhRequestid=grd.grdRequestID and a.grhshopid= grd.grdShopid)','Pending goods requests',1,1,'A','pcalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7025,'Pending Shop PO Requests','For Alerting Pending Shop PO Requests','select GRHrequestID[Req.Id],GRHrequestNO[Req.No],GRHrequestDate[Req.Date],b.shopname[Shop Name],grhremarks[Remarks]            from mosGoodsRequestHeader [a], ashops [b] where a.grhshopid=b.shopid and            grhIssuenotegenerated = 0 And grhcancel = 0 and grhTransfinished=1 and            grhTransfinished=1 and            grhrequesttype=''p'' and b.departmentid= ?D?  and            grhnoofdetails=(select count(*) from mosGoodsRequestdetail [grd] where            a.grhRequestid=grd.grdRequestID and a.grhshopid= grd.grdShopid)','Pending Shop PO Requests',1,1,'A','pcalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7055,'Ticketing Details','Ticketing Details','  select TravellerName,Department,Designation,TravelDate  Remark,TravelMode from losdocumenttravel,apackagesettings s where   s.companyid=?C? and shopid=?S? and arrivaldate<=dateadd(dd,alertdays,PAckageDate)','Ticketing Details',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7056,'Service Alerts','Service Alerts','SpServiceAlerts ?C?,?S?,'',''','Service Alert',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7011,'Invoices to be Processed','For Alerting Invoices','select distinct InvoiceNo as [Invoice Number],InvoiceDate as [Date],departmentname    as [Department],Remarks from vwInvoicesWithControlAccounts where companyid=?C?    and maindepid=?D?','Invoices to be Processed',1,1,'A','acalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7052,'Expired Items Alert','To list all items which have expired items','Select ItemCode, ItemDescription, ExpiryDate, Stock   from vwShopExpiryAlertItems where ShopId = ?s? ','',1,1,' ','posc')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7020,'Bills not despatched','For Alerting Bills not despatched','select distinct pbhbillid[Bill Id],pbhbillno[Bill No],pbhbilldate[Bill Date],pbhvendorbillno[Vendor Bill No],           pbhbillamount[Bill Amount],pbhdiscount[Discount],pbhduedateforpayment[Due Date],pbhremarks[Remarks]            from losppurchasebillheader [a] where pbhDespatched=0            and a.pbhDepartmentID=?D?             and  a.pbhcancelled=0 and pbhbillid<>0','Bills not despatched',1,1,'A','pcalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7017,'PO Generated but not billed','For Alerting PO Generated but not billed','select a.pohpoid[Purch.order Id],a.pohpono[Purch.order No],a.pohpodate[Purch.order Date],b.vendorname[Vendor], a.pohduedate[Due Date],pohvalue[Value],pohremarks[remarks] from lopurchaseorderheader [a],  avendormaster [b] Where a.pohvendorid = b.vendorid And pohtype = ''P'' and            pohcancel = 0 and pohDepartmentid =?D? and pohbillgenerated = 0 and pohQuotationid=0 and a.pohpoid<>0 and            pohpoonhold<>1 order by a.pohpoid','PO Generated but not billed',1,1,'A','pcalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7016,'Special Invoice not Despatched','For Alerting Special Invoice not Despatched','select a.ihInvoiceno[Invoice No], a.ihinvoicedate[Invoice Date], sh.shopname[Shop Name], g.godownname[Godown],   a.ihremarks[Remarks] from losSpecialInvoiceHeader [a],losSpecialInvoicedetail [b],   agodown [g], ashops [sh] where a.ihinvoiceid = b.idinvoiceid and a.ihShopid=b.idShopid    and b.idgodownid=g.godownid and b.despatch=0 and b.reqqty>0 and sh.shopid=ihshopid and a.ihCancelled = 0    and a.ihTransfinished=1 and a.IhDepartmentID=?D? group by a.ihInvoiceid,   a.ihInvoiceno, a.ihinvoicedate, g.godownname, a.ihremarks, sh.shopname','Special Invoice not Despatched',1,1,'A','pcalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7018,'Bills which are not costed','For Alerting Bills which are not costed','select distinct pbhbillid[Purch.bill Id],pbhbillno[Purch.bill No],pbhbilldate[Bill Date],pbhvendorbillno[Vendor Bill No],          pbhbillamount[Bill Amount], pbhdiscount[Discount], pbhduedateforpayment[Due Date for Payment],pbhremarks[Remarks]           from losppurchasebillheader [a] left outer join ashipment [b] on           a.pbhbillid=b.sbillid where b.scostingdone=0 and a.pbhcancelled=0           and a.pbhDepartmentID= ?D? and a.pbhbillid<>0 order by pbhbillid','Bills which are not costed',1,1,'A','pcalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7050,'Goods Arrival From Shop Notification','For Alerting Goods Arrival From Shop','select toh.tohdate[Transfer Date], ashops.shopname[Shop Name],                     toh.tohno[Transfer No] from mestransferoutheader [toh],ashops                     where toh.tohtoshopid= ?S? and toh.tohshopid = shopid and toh.tohused = 0 and toh.tohcancelled = 0                     and toh.tohTransfinished=1 and toh.tohNoofDetails =(Select count(*) from mestransferoutdetail tod where toh.tohid=tod.todid                     and toh.tohShopid=tod.todShopid) group by toh.tohdate,ashops.shopname,toh.tohno','Goods Arrival From Shop Notification',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7049,'Goods Arrival From Godown Notification','For Alerting Goods Arrival From Godown','select dsh.dhdespatchdate[Despatch date], agodown.godownname[Godown], dsh.dhdespatchno[Despatch No] from MEidespatchtoshopheader [dsh],   agodown where dhshopid = ?S? and dhselected = 0 and dhcancelled = 0 and    dhgodownid=agodown.godownid and dhTransfinished=1 and dhNoofDetails=(Select count(*)from    MEiDespatchToShopDetail [dsd] where dsh.dhDespatchID=dsd.ddDespatchID and    dsh.dhgodownid=dsd.ddgodownid)group by dsh.dhdespatchdate, agodown.godownname, dsh.dhdespatchno','Goods Arrival From Godown Notification',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7030,'Goods arrival from Head Quarters','For Alerting Goods arrival from Head Quarters','select dnmDespatchNoteDate[Despatch Date], dhDespatchNoteNo[Despatch Np], dnmRemarks[Remarks]               from aHQDespatchNoteHeader [dh],aHqDespatchNoteMain where        dhGodownID=?G?  and dhSelected=0 and                dhDespatchNoteMainID=dnmDespatchNoteID and dhCancelled=0 and dhTransFInished=1 and                dhNoofDetails=(Select count(*) from ahqdespatchnotedetails [dd] where                dh.dhDespatchNoteid=dd.dddespatchnoteid and dh.dhGodownid=dd.ddgodownid)','Goods arrival from Head Quarters',1,1,'A','inalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7045,'Work Permit Details','For Alerting Work Permit Details','select DocNo, CustomerName[Customer] ,EmpName[Emp.Name] ,PNationality[Nationality], WWorkPermitNo[Work Permit No], WIssueDate[Work Issue Date],    WExpireyDate[Work Expiry Date],WFeeExpireyDate[Work Fee Exp. Date] ,Remarks[Remarks] From losdocument [l], acustomermaster [ac]   where l.CustomerID = ac.CustomerID and doctype = ''WP''  and shopid = ?S? and WExpireyDate - AlertBeforeDays <= ?DT? and   WExpireyDate >= ?DT?','Work Permit Details',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7031,'Goods arrival from Godown','For Alerting Goods arrival from Godown','select gthDespatchDate[Despatch date],gthDespatchNo[Despatch No],GodownName[Godown],gthRemarks[Remarks]               from MEiGodownTransferHeader [gth],aGodown where gthToGodownID=?G?                and gthSelected=0 and gthCancelled=0 and gthFromGodownID=GodownID                and gthTransfinished=1 and gthNoofDetails=(Select count(*) from                meigodowntransferdetail [gtd] where gth.gthDespatchid=gtd.gtddespatchid                and gth.gthFromGodownid=gtd.gtdgodownid)','Goods arrival from Godown',1,1,'A','inalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7037,'Special Invoices Not Despatched From Godown','For Alerting Special Invoices Not Despatched From Godown','select a.ihInvoiceid[Invoice Id],a.ihInvoiceno[Invoice No], a.ihinvoicedate[Date], g.godownname[Godown], a.ihremarks[Remarks] from          losSpecialInvoiceHeader [a],losSpecialInvoicedetail [b], agodown [g] where    a.ihinvoiceid = b.idinvoiceid and a.ihShopid=b.idShopid and b.idgodownid=g.godownid   and b.despatch=0 and b.reqqty>0 and a.ihCancelled = 0  and b.idshopid=?S?          and a.ihTransfinished=1 group by a.ihInvoiceid,a.ihInvoiceno, a.ihinvoicedate, g.godownname, a.ihremarks','Special Invoices Not Despatched From Godown',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7053,'Expired Items Alert','To list all items which have expired items','Select ItemCode, ItemDescription, ExpiryDate,   Stock from sp_help vwGodownExpiryAlertItems where GodownId = ?g? ','',1,1,' ','invalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7032,'Goods arrival from Shop','For Alerting Goods arrival from Shop','select dghDate[Date],dghNo[No],ShopName[Shop Name],dghRemarks[remarks] from              MEsDespatchToGodownHeader [dgh], aShops where dghGodownID=?G?               and dghUsed=0 and dghCancelled=0 and dghShopID=ShopID and dghTransFinished=1               and dghNoofDetails=(Select count(*) from MEsDespatchToGodowndetail [dgd] where               dgh.dghID=dgd.dgDID and dgh.dghshopid=dgd.dgdshopid)','Goods arrival from Shop',1,1,'A','inalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7059,'Pending Transactions which are not  Confirmed','Lists the trasactions which are not   confirmed','Select TransactionType, TransactionNo, TransactionDate, LocationName from vwUnConfirmedTransactions  where locationid = ?S? and loctype=''s''','Un Confirmed Transations',1,1,'a','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7058,'Pending Transactions which are not Confirmed','Lists the trasactions which are not   confirmed','Select TransactionType, TransactionNo, TransactionDate, LocationName from vwUnConfirmedTransactions  where departmentid = ?D?','Un Confirmed Transations',1,1,'a','pcalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7060,'Pending Transactions which are not  Confirmed','Lists the trasactions which are not   confirmed','Select TransactionType, TransactionNo, TransactionDate, LocationName from vwUnConfirmedTransactions  where locationid = ?G? and loctype=''g''','Un Confirmed Transations',1,1,'a','inalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7072,'select shopname from ashops','','select shopname from ashops','select shopname from ashops',1,0,'I','p&c')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7033,'Issue note arrival notification','For Alerting Issue note arrival notification','select inhIssueDate[Issue Date], inhIssueNoteNo[Issue No], ShopName[Shop Name], inmRemarks[Remarks] from               aHqIssueNoteHeader [inh], ahqissuenotemain [inm], aShops where inhGodownID= ?G?                and inhused=0 and INHIssuenotemainID = INMIssuenoteID  and inhCancelled=0 and inhToShopID=ShopID               and inhTransfinished=1 and inhNoofDetails=(Select count(*) from                ahQissuenoteDetail [ind] where inh.inhIssuenoteid=ind.indissuenoteid                and inh.inhGodownid=ind.indGodownid)','Issue note arrival notification',1,1,'A','inalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7051,'Government Fee ALerts','For Alerting Government Fee','select GL.LoanName[Loan Name],GL.RangeFrom[Range From],       GL.RangeTo[Range To],   case when gl.customerid is not null then ACM.customername when   gl.vendorid is not null then AVM.vendorname   else Gl.trcusvendesc end  as "Name",   ACT.AccountDesc[Bank Name],   GL.PeriodicCharge[Periodic Charge] from  GovernLoan [GL] left outer join   acustomermaster[ACM]  on GL.customerid=ACM.customerid and   GL.companyid=ACM.companyid   left outer join avendormaster [AVM] on Gl.vendorid=AVM.vendorid and   GL.companyid=AVM.companyid  left outer join aaccountmaster [ACT] on   GL.bankid=ACT.Accountid and GL.companyid=ACT.companyid,apackagesettings   [APS]   where  gl.TrCancelled=0 and Gl.companyid=APS.companyid and  (APS.packagedate +   GL.alertDays)<=GL.NextPaymentDate','Goverment Fee ALerts',1,1,'A','acalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7057,'Contract Alerts','Contract Alerts','select mchNo [Contract No],mchdate [Contract date],Customername [Customer Name],  mchRemarks [Remark] from losSerMaintenanceContractHeader,  losSerMaintenanceContractDetail,acustomermaster,  apackagesettings s where mchCompanyID=mcdCompanyID and mchShopID=mcdshopid   and mchID=mcdID and mchCancelled=0 and (packagedate + mcdAlertdays)>=mcdtoDate and  mchCustomerID=customerid and mchCompanyID=?C? and mchShopID=?S?','Contract Alerts',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7054,'Pending Dummy Receipt Alert','Lists the dummy receipts entered from outlets   which are yet to be processed in HQ Receipts','Select drNo, drDate, ShopName from   losDummyreceiptheader left outer join receiptvoucherheader on drID = dummyReceiptid and   drShopId = recshopid, ashops s where dummyReceiptid is null and drshopid = shopid   and drCancelled = 0 and drdepartmentid = ?D?','Pending Dummy Receipt Alert',1,1,'A','acalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7070,'Machines sold which has to be registered in Machine Contract','Lists the machines sales details which are pending to be registered in the service center','Select cast(shopnos as varchar) [Trans No], Processdate [Trans Date], Itemdescription [Item Description],   serialno [Serial No], itemcode [Item Code], part_code [Part Code], CustomerName from  VwMaintenceContractOutletDtls  left outer join (Select mmdMCID, mmdShopID, mmdSerProcessid,    mmdMachineId, mmdSerProcessType, mmdSerShopid from  losSerMaintenanceMachineDetail,   losSerMaintenanceContractHeader where  mchCompanyID = mmdCompanyID     and mchID = mmdMCID and mchShopID = mmdShopID and  mchCancelled =0 ) ss on    mmdMachineID=itemid and  mmdSerShopid=shopid and mmdSerProcessid=shopprocessid and   mmdSerProcessType=type where mmdSerProcessid is null and mmdMCID is null   and CompanyId = ?C?','Machine Contract Pending',1,1,'A','poalt')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(2,'Purchases For Period Category wise','Purchases For Period Category wise','Select  i.ItemCategoryId,CategoryNameDescription [Category Name],   sum((cdCostingPrice * cdItemQuantity)/12.85) [Purchase Value]  from loaCostingHeader,   LoaCostingDetail, aItem i, aItemCategory Ic where chCostingId = cdCostingId and   cdItemId = ItemId and i.ItemCategoryId = ic.ItemCategoryId and chDepartmentid = fsms1c  and chCostingDate  BETWEEN fsms2d AND fsms3d  group By i.ItemCategoryId,   CategoryNameDescription','Purchases For Period Category wise',1,1,'I','p&c')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(4,'Pending Dummy Receipts','Pending Dummy Receipts','Select drid, drNo [Receipt No], drDate [Receipt Date], CustomerName [Customer Name],   ShopName [Shop Name], drAmount [Amount] from   losDummyreceiptheader left outer join receiptvoucherheader r on drID = r.dummyReceiptid and   drShopId = r.recshopid, ashops s, aCustomerMaster c where r.Customerid = c.CustomerId   and dummyReceiptid is null and drshopid = shopid   and drCancelled = 0 and drdepartmentid = fsms1c order by CustomerName, drDate','Pending Dummy Receipts',1,1,'I','acc')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(5,'Category Wise Purchase','Purchases For Period Item wise','Select  i.ItemcategoryId, Categorynamedescription [Category],   sum((cdCostingPrice * cdItemQuantity)/12.85) [Purchase Value] from loaCostingHeader,   LoaCostingDetail, aItem i, aitemcategory ic where chCostingId = cdCostingId and   cdItemId = ItemId and chDepartmentid = fsms1c and i.itemcategoryid = ic.itemcategoryid  and chCostingDate  BETWEEN fsms2d AND fsms3d group By i.ItemcategoryId,   Categorynamedescription','Purchases Item wise',1,1,'I','p&c')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(1,'Allocation details to customers','Enter the item code and press Execute in the Value 1','select h.ihInvoiceNo [PO NO], h.ihInvoiceDate [PO DATE], CustomerName [Customer Name],   idQuantity [Quantity] from losInvoiceHeader h left outer join losInvoiceHeader I   on h.ihinvoiceid = i.ihproformaid and h.ihshopid = i.ihshopid and 0 = i.ihcancelled,   losInvoiceDetail d, aitem ai, aCustomerMaster c where h.ihInvoiceid = idinvoiceid and   h.ihshopid = idshopid and h.ihcancelled = 0 and h.ihTransfinished = 1 and   isnull(i.ihinvoiceid,0) = 0  and   h.ihCustomerId = c.CustomerId and idItemiD = ai.ItemID  and ai.ItemCode = fsms1s and h.ihdepartmentid = 1 and h.ihType=''P''  order by h.ihinvoicedate  ','',1,1,'i','p&c')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(3,'Purchases For Period Item wise','Purchases For Period Item wise','Select  i.ItemId, ItemDescription [Item Name],   sum((cdCostingPrice * cdItemQuantity)/12.85) [Purchase Value] from loaCostingHeader,   LoaCostingDetail, aItem i where chCostingId = cdCostingId and   cdItemId = ItemId and chDepartmentid = fsms1c  and chCostingDate  BETWEEN fsms2d AND fsms3d  group By i.ItemId,   ItemDescription','Purchases Item wise',1,1,'I','p&c')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7073,'select * from ashops ','gfg','dfsdkgfmrsdlgjdfkghudatekfghlfghnklfgjh ','select * from ashops ',1,0,'I','p&c')
INSERT INTO [adminv2].[dbo].[MiscInquiry]  ([QueryID]  ,[QueryName]  ,[Comments]  ,[Query]  ,[ReportName]  ,[CompanyId]  ,[Active]  ,[Type]  ,[Modulecode])  VALUES(7074,'Insert','  Item Master','  select * from aitem','Insert',1,1,'I','p&c')
-------------------------[MiscInquiry] STOP----------------------------------------------
Go
USE [adminv2]
GO
/****** Object:  StoredProcedure [dbo].[spInsertDefaultValues]    Script Date: 03/22/2012 11:01:44 ******/
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
--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())
INSERT INTO [adminv2].[dbo].[aaccountmaster]  ([AccountID]  ,[CompanyID]  ,[AccountCode]  ,[Active]  ,[GroupID]  ,[AccountDesc]  ,[ControlledAccount]  ,[BudgetAmount]  ,[openingamount]  ,[openingactualamount]  ,[openingdepamount]  ,[OrderNo]  ,[CurrencyID]  ,[Misc]  ,[rowguid])  VALUES (59,1,'59',1,6,'HP SALES ACCOUNT',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

GO