1/7/2010 12:56:12 PM v1.4477 - Column names in each table must be unique. Column name 'Category_Name' in table 'Resources' is specified more than once Continue or restart VDM - This error was queued for analysis, we apologize. -- -- Encryption -- --BACKUP SERVICE MASTER KEY TO FILE = 'C:\ServiceMasterKey.bak' --ENCRYPTI 0001:00233BEC axView.txView.UpdContact line 9428 0001:0021C654 axView.FormatResults line 7379 base: 00C41000 -- -- Encryption -- --BACKUP SERVICE MASTER KEY TO FILE = 'C:\ServiceMasterKey.bak' --ENCRYPTION BY PASSWORD = 'Replace_with_Strong_Password' --GO --RESTORE SERVICE MASTER KEY FROM FILE = 'C:\ServiceMasterKey.bak' --DECRYPTION BY PASSWORD = 'Replace_with_Strong_Password' --GO -- --CREATE MASTER KEY --ENCRYPTION BY PASSWORD = 'Replace_with_Strong_Password' --GO --BACKUP MASTER KEY TO FILE = 'C:\MasterKey.bak' --ENCRYPTION BY PASSWORD = 'Replace_with_Strong_Password' --GO --RESTORE MASTER KEY FROM FILE = 'C:\MasterKey.bak' --DECRYPTION BY PASSWORD = 'Replace_with_Strong_Password' --ENCRYPTION BY PASSWORD = 'Replace_with_Strong_Password' --GO -- --CREATE CERTIFICATE DefaultEncryptionCertificate --WITH SUBJECT = 'Default_Encryption_Certificate' --GO -- --CREATE SYMMETRIC KEY DefaultSymmetricKey --WITH ALGORITHM = TRIPLE_DES --ENCRYPTION BY CERTIFICATE DefaultEncryptionCertificate --GO -- --Identical Shared Keys on Multiple Servers -- --CREATE MASTER KEY --ENCRYPTION BY PASSWORD = 'Replace_with_Strong_Password' --GO --CREATE CERTIFICATE DefaultEncryptionCertificate --WITH SUBJECT = 'Default_Encryption_Certificate' --GO --CREATE SYMMETRIC KEY DefaultSymmetricKey WITH --KEY_SOURCE = 'My key generation bits. This is a shared secret!', --WITH ALGORITHM = TRIPLE_DES ENCRYPTION --IDENTITY_VALUE = 'Key Identity generation bits. Also a shared secret' --ENCRYPTION BY CERTIFICATE DefaultEncryptionCertificate --GO -- --OPEN SYMMETRIC KEY DefaultSymmetricKey DECRYPTION --BY CERTIFICATE DefaultEncryptionCertificate --UPDATE SomeTable --SET EncryptedColumn = ENCRYPTBYKEY( KEY_GUID( 'DefaultSymmetricKey' ), SourceColumnOrData ) --GO -- --OPEN SYMMETRIC KEY DefaultSymmetricKey DECRYPTION --BY CERTIFICATE DefaultEncryptionCertificate --SELECT CONVERT( VARCHAR( 50 ), DECRYPTBYKEY( EncryptedColumn ) ) AS DecryptedData --FROM SomeTable --GO -- --GRANT VIEW DEFINITION ON CERTIFICATE :: DefaultEncryptionCertificate TO SomeUserOrRole --GRANT CONTROL ON CERTIFICATE :: DefaultEncryptionCertificate TO SomeUserOrRole -- -- -- Void Orders must rollback the triggers -- grant update ( Date_Locked ) on OrderItems to VDM -- alter table OrderItems disable trigger all -- update OrderItems set Date_Locked = Null -- from Orders O join OrderItems I on O.ID = I.Order_ID where O.Date_Locked is Null AND I.Date_Locked is NOT Null -- alter table OrderItems enable trigger all -- deny update ( Date_Locked ) on OrderItems to VDM -- --exec sp_dropServer 'Laval' -- --exec sp_addlinkedserver 'Laval', '', 'SQLNCLI', 'laval.papex.ca' -- linked server updates -- update ediaccess.VDM_ACI.dbo.WebPages set Photo1 = ( select Photo1 from clearware.VDM_ACI.dbo.WebPages W where W.ID = M.ID ) -- from ediaccess.VDM_ACI.dbo.WebPages M where M.Use_As_Template = 1 --select destination_url, Cast( SubString( Cast( Photo2 as varbinary( max ) ), -- CharIndex( 'ejel-120', Cast( Photo2 as varbinary( max ) ) ) - 50, 100 ) as varchar( 4000 ) ) as Src from ediaccess.VDM_ACI.dbo.WebPages -- where Cast( Photo2 as varbinary( max ) ) like '%ejel-120%' -- Search and Replace Blobs -- update WebPages set Photo1 = cast( replace( Cast( Photo1 as varbinary( max ) ), -- 'old', -- 'new' -- ) as varbinary( max ) ) where Use_As_Template = 1 -- --@onlyOneColumnUpdated = 0 if not, otherwise @onlyOneColumnUpdated = 1 -- DECLARE @sqrtForOneColumn float -- DECLARE @onlyOneColumnUpdated bit -- SET @sqrtForOneColumn=(SELECT SQRT(CONVERT(int,COLUMNS_UPDATED()))) -- SET @onlyOneColumnUpdatacked = 0 -- IF POWER(CONVERT(int,COLUMNS_UPDATED()),0.5) = @sqrtForOneColumn -- SET @onlyOneColumnUpdated = 1 -- After then you test the column you want to know if it has been modified -- IF UPDATE(MyCOlumn) AND @onlyOneColumnUpdated = 1 -- PUT YOUR CODE HERE FOR THE COLUMN. ------------- -- Init -- ------------- if NOT exists( select [Name] from TaxProfiles where [Name] = 'GST' AND Date_Effective >= '2008-01-01' ) begin insert TaxProfiles (Date_Effective, [Name], Tax1_Percent ) values( '2008-01-01', 'GST', 5 ) insert TaxProfiles (Date_Effective, [Name], Tax1_Percent ) values( '2008-01-01', 'HST', 15 ) insert TaxProfiles (Date_Effective, [Name], Tax1_Percent, Tax2_Percent, Tax1_is_Taxable ) values( '2008-01-01', 'GST/BC', 5, 7, 1 ) insert TaxProfiles (Date_Effective, [Name], Tax1_Percent, Tax2_Percent ) values( '2008-01-01', 'GST/SK', 5, 5 ) insert TaxProfiles (Date_Effective, [Name], Tax1_Percent, Tax2_Percent ) values( '2008-01-01', 'GST/MA', 5, 7 ) insert TaxProfiles (Date_Effective, [Name], Tax1_Percent, Tax2_Percent ) values( '2008-01-01', 'GST/ON', 5, 8 ) insert TaxProfiles (Date_Effective, [Name], Tax1_Percent, Tax2_Percent, Tax1_is_Taxable ) values( '2008-01-01', 'GST/QC', 5, 7.5, 1 ) insert TaxProfiles (Date_Effective, [Name], Tax1_Percent, Tax2_Percent, Tax1_is_Taxable ) values( '2008-01-01', 'GST/PEI', 5, 10, 1 ) end GO if NOT exists( select [Type] from Numbers ) begin insert Numbers ([Type]) values('Sale') insert Numbers ([Type]) values('Purchase') insert Numbers ([Type]) values('Adjustment') insert Numbers ([Type]) values('Production') insert Numbers ([Type]) values('Estimate') insert Numbers ([Type]) values('Service') update Numbers set Last_Number = isNull( ( select top 1 Number from Orders where [Type] = 'Sale' AND Date_Locked is NOT Null order by Number desc ), 1000 ) where [Type] = 'Sale' update Numbers set Last_Number = isNull( ( select top 1 Number from Orders where [Type] = 'Purchase' order by Number desc ), 1000 ) where [Type] = 'Purchase' update Numbers set Last_Number = isNull( ( select top 1 Number from Orders where [Type] = 'Adjustment' order by Number desc ), 1000 ) where [Type] = 'Adjustment' update Numbers set Last_Number = isNull( ( select top 1 Number from Orders where [Type] = 'Production' order by Number desc ), 1000 ) where [Type] = 'Production' update Numbers set Last_Number = isNull( ( select top 1 Number from Orders where [Type] = 'Estimate' order by Number desc ), 1000 ) where [Type] = 'Estimate' update Numbers set Last_Number = isNull( ( select top 1 Number from Orders where [Type] = 'Service' AND Date_Locked is NOT Null order by Number desc ), 1000 ) where [Type] = 'Service' end GO ------------- -- Library -- ------------- if exists ( select * from sysobjects where [Name] = 'OpenKey' AND [Type] = 'P' ) drop procedure dbo.OpenKey GO create procedure dbo.OpenKey as begin if exists( select * from sys.certificates where name = 'DefaultEncryptionCertificate' ) open symmetric key DefaultSymmetricKey decryption by certificate DefaultEncryptionCertificate end GO if exists ( select * from sysobjects where [Name] = 'Encrypt' AND [Type] = 'FN' ) drop function dbo.Encrypt GO create function dbo.Encrypt( @Data varchar( 4000 ) ) returns varbinary( 8000 ) begin declare @@Result varbinary( 8000 ) set @@Result = EncryptbyKey( Key_GUID( 'DefaultSymmetricKey' ), @Data ) if @@Result is Null set @@Result = convert( varbinary( 8000 ), @Data ) return @@Result end GO if exists ( select * from sysobjects where [Name] = 'Decrypt' AND [Type] = 'FN' ) drop function dbo.Decrypt GO create function dbo.Decrypt( @Data varchar( 4000 ) ) returns varchar( 8000 ) begin declare @@Result varchar( 8000 ) set @@Result = Convert( varchar( 8000 ), DecryptByKey( @Data ) ) if @@Result is Null set @@Result = @Data return @@Result end GO if exists ( select * from sysobjects where [Name] = 'UnitConversion' AND [Type] = 'FN' ) drop function dbo.UnitConversion GO create function dbo.UnitConversion( @StockUnit varchar( 20 ), @SellingUnit varchar( 20 ), @ConversionList varchar( 100 ) ) returns decimal( 18, 4 ) -- varchar( 20 ) -- begin declare @P1 int, @P2 int, @Result decimal( 18, 4 ) set @Result = 1 set @StockUnit = rtrim( @StockUnit ) set @SellingUnit = rtrim( @SellingUnit ) --@Result varchar( 20 ) set @Result = '1' -- if @StockUnit <> @SellingUnit begin set @P1 = charindex( @SellingUnit + '*', @ConversionList ) if @P1 <> 0 begin set @P1 = charindex( '*', @ConversionList, @P1 ) set @P2 = charindex( ',', @ConversionList + ',', @P1 ) set @Result = substring( @ConversionList, @P1 + 1, @P2 - @P1 - 1 ) end end if @Result <= 0 set @Result = 1 return @Result end GO if exists ( select * from sysobjects where [Name] = 'FileAsString' AND [Type] = 'FN' ) drop function dbo.FileAsString GO create function dbo.FileAsString( @PathName varchar( 8000 ) ) returns varbinary( max ) begin -- set @PathName = replace( @PathName, '\', '\\' ) declare @OK int, @FileSystem int, @FileStream int, @Buffer varchar( 8000 ), @Result varbinary( max ) execute @OK = sp_OACreate 'Scripting.FileSystemObject' , @FileSystem output if @OK <> 0 set @Result = Cast( 'Create ' + cast( @OK as varchar( 100 ) ) as varbinary( max ) ) else begin execute @OK = sp_OAMethod @FileSystem, 'OpenTextFile', @FileStream output, @PathName, 1, false, 0 -- Read, NoCreate, ASCII if @OK <> 0 set @Result = Cast( 'Open ' + cast( @OK as varchar( 100 ) ) as varbinary( max ) ) else begin select @Result = cast( '' as varbinary( max ) ), @Buffer = ' ' while @OK = 0 AND @Buffer is NOT Null begin execute @OK = sp_OAMethod @FileStream, 'Read', @Buffer output, 4000 if @OK = 0 set @Result = @Result + cast( @Buffer as varbinary( max ) ) end end execute @OK = sp_OAMethod @FileStream, 'Close' end return @Result end GO --create function dbo.FileAsString( @PathName varchar( 8000 ) ) returns varbinary( 8000 ) --begin ---- set @PathName = replace( @PathName, '\', '\\' ) -- declare @OK int, @FileSystem int, @FileStream int, @Buffer varchar( 8000 ), @Result varbinary( 8000 ) -- execute @OK = sp_OACreate 'Scripting.FileSystemObject' , @FileSystem output -- if @OK <> 0 set @Result = Cast( 'Create ' + cast( @OK as varchar( 100 ) ) as varbinary( 8000 ) ) -- else begin -- execute @OK = sp_OAMethod @FileSystem, 'OpenTextFile', @FileStream output, @PathName, 1, false, 0 -- Read, NoCreate, ASCII -- if @OK <> 0 set @Result = Cast( 'Open ' + cast( @OK as varchar( 100 ) ) as varbinary( 8000 ) ) -- else begin -- select @Result = cast( '' as varbinary( 8000 ) ), @Buffer = ' ' -- while @OK = 0 AND @Buffer is NOT Null begin -- execute @OK = sp_OAMethod @FileStream, 'Read', @Buffer output, 4000 -- if @OK = 0 set @Result = @Result + cast( @Buffer as varbinary( 8000 ) ) -- end -- end -- execute @OK = sp_OAMethod @FileStream, 'Close' -- end -- return @Result --end --GO if exists ( select * from sysobjects where [Name] = 'InternetPath' AND [Type] = 'FN' ) drop function dbo.InternetPath GO create function dbo.InternetPath( @PathName varchar( 4000 ) ) returns varchar( 4000 ) begin declare @@LastSlash int, @@N int, @@Result varchar( 4000 ) select @@N = CharIndex( '/', @PathName ) select @@LastSlash = @@N while @@N <> 0 begin select @@LastSlash = @@N select @@N = CharIndex( '/', @PathName, @@N + 1 ) end if @@LastSlash = 0 select @@Result = '' else select @@Result = SubString( @PathName, 1, @@LastSlash ) return @@Result end GO if exists ( select * from sysobjects where [Name] = 'FilePath' AND [Type] = 'FN' ) drop function dbo.FilePath GO create function dbo.FilePath( @PathName varchar( 4000 ) ) returns varchar( 4000 ) begin declare @@LastSlash int, @@N int, @@Result varchar( 4000 ) select @@N = CharIndex( '\', @PathName ) select @@LastSlash = @@N while @@N <> 0 begin select @@LastSlash = @@N select @@N = CharIndex( '\', @PathName, @@N + 1 ) end if @@LastSlash = 0 select @@Result = '' else select @@Result = SubString( @PathName, 1, @@LastSlash ) return @@Result end GO if exists ( select * from sysobjects where [Name] = 'InternetName' AND [Type] = 'FN' ) drop function dbo.InternetName GO create function dbo.InternetName( @PathName varchar( 4000 ) ) returns varchar( 4000 ) begin declare @@LastSlash int, @@N int, @@Result varchar( 4000 ) select @@N = CharIndex( '/', @PathName ) select @@LastSlash = @@N while @@N <> 0 begin select @@LastSlash = @@N select @@N = CharIndex( '/', @PathName, @@N + 1 ) end if @@LastSlash = 0 select @@Result = @PathName else select @@Result = SubString( @PathName, @@LastSlash + 1, Len( @PathName ) - @@LastSlash ) return @@Result end GO if exists ( select * from sysobjects where [Name] = 'FileName' AND [Type] = 'FN' ) drop function dbo.Filename GO create function dbo.FileName( @PathName varchar( 4000 ) ) returns varchar( 4000 ) begin declare @@LastSlash int, @@N int, @@Result varchar( 4000 ) select @@N = CharIndex( '\', @PathName ) select @@LastSlash = @@N while @@N <> 0 begin select @@LastSlash = @@N select @@N = CharIndex( '\', @PathName, @@N + 1 ) end if @@LastSlash = 0 select @@Result = @PathName else select @@Result = SubString( @PathName, @@LastSlash + 1, Len( @PathName ) - @@LastSlash ) return @@Result end GO if exists ( select * from sysobjects where [Name] = 'DateRange' AND [Type] = 'FN' ) drop function dbo.DateRange GO create function dbo.DateRange( @Value varchar( 4000 ), @Index int ) returns varchar( 100 ) begin declare @Count int, @N int, @S varchar( 100 ) declare @Beg varchar( 100 ), @End varchar( 100 ), @Month varchar( 100 ), @Year varchar( 100 ) if Len( @Value ) > 0 begin set @Beg = '' set @End = '' set @Month = '' set @Year = '' set @Count = dbo.Tokens( ' ', @Value ) set @N = @Count while @N > 0 begin set @S = dbo.Token( ' ', @Value, @N ) set @N = @N - 1 if Len( @S ) > 3 AND SubString( @S, 1, 3 ) = '200' set @Year = @S if @Year <> '' AND @Year <> @S AND @Month = '' set @Month = @S if @Month <> '' AND @Month <> @S AND @End = '' begin if CharIndex( '-', @S ) = 0 set @End = SubString( @S, 1, 2 ) else begin set @Beg = SubString( dbo.Token( '-', @S, 1 ), 1, 2 ) set @End = SubString( dbo.Token( '-', @S, 2 ), 1, 2 ) end set @S = @End end if @End <> '' AND @End <> @S AND @Beg = '' AND @S <> 'and' set @Beg = SubString( @S, 1, 2 ) end if Len( @Beg ) > 1 AND SubString( @Beg, 2, 1 ) > '9' set @Beg = SubString( @Beg, 1, 1 ) if Len( @End ) > 1 AND SubString( @End, 2, 1 ) > '9' set @End = SubString( @End, 1, 1 ) if @Year = '' return '' if @Index > 1 return @Year + '-' + @Month + '-' + @End return @Year + '-' + @Month + '-' + @Beg end return '' end GO if exists ( select * from sysobjects where [Name] = 'TextAmount' AND [Type] = 'FN' ) drop function dbo.TextAmount GO create function dbo.TextAmount( @Value varchar( 100 ) ) returns varchar( 4000 ) begin declare @N int, @Length int, @Index int, @Dec varchar( 10 ), @Result varchar( 4000 ) declare @Ones varchar( 100 ), @Tens varchar( 100 ), @Teens varchar( 100 ) set @Ones = 'zero,one,two,three,four,five,six,seven,eight,nine' set @Tens = 'zero,ten,twenty,thirty,forty,fifty,sixty,seventy,eighty,ninety' set @Teens = 'ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen' set @N = CharIndex( '.', @Value ) if @N > 0 begin set @Dec = SubString( @Value, @N + 1, Len( @Value ) - @N ) set @Value = SubString( @Value, 1, @N - 1 ) end set @Length = Len( @Value ) set @N = @Length set @Result = '' while @N > 0 begin set @Index = Ascii( SubString( @Value, @N, 1 ) ) - Ascii( '0' ) if @Index > 0 OR @Length = 1 begin -- 1 OR SubString( @Value, @N - 1, 1 ) <> '0' begin if @N = @Length begin -- ones if @N > 1 AND SubString( @Value, @N - 1, 1 ) = '1' begin set @Result = dbo.Token( ',', @Teens, @Index + 1 ) + ' ' + @Result set @N = @N - 1 end else set @Result = dbo.Token( ',', @Ones, @Index + 1 ) + ' ' + @Result end else if @N = @Length - 1 begin -- tens set @Result = dbo.Token( ',', @Tens, @Index + 1 ) + ' ' + @Result end else if @N = @Length - 2 begin -- hundreds set @Result = dbo.Token( ',', @Ones, @Index + 1 ) + ' hundred ' + @Result end else if @N = @Length - 3 begin -- thousands if @N > 1 AND SubString( @Value, @N - 1, 1 ) = '1' begin set @Result = dbo.Token( ',', @Teens, @Index + 1 ) + ' thousand ' + @Result set @N = @N - 1 end else set @Result = dbo.Token( ',', @Ones, @Index + 1 ) + ' thousand ' + @Result end else if @N = @Length - 4 begin -- ten thousands if SubString( @Value, @N + 1, 1 ) = '0' set @Result = dbo.Token( ',', @Tens, @Index + 1 ) + ' thousand ' + @Result else set @Result = dbo.Token( ',', @Tens, @Index + 1 ) + ' ' + @Result end else if @N = @Length - 5 begin -- hundred thousands set @Result = dbo.Token( ',', @Ones, @Index + 1 ) + ' hundred ' + @Result end else if @N = @Length - 6 begin -- millions if @N > 1 AND SubString( @Value, @N - 1, 1 ) = '1' begin set @Result = dbo.Token( ',', @Teens, @Index + 1 ) + ' million ' + @Result set @N = @N - 1 end else set @Result = dbo.Token( ',', @Ones, @Index + 1 ) + ' million ' + @Result end end set @N = @N - 1 end return @Result end GO -- select dbo.TextAmount( 1390 ) if exists ( select * from sysobjects where [Name] = 'vGetDate' AND [Type] = 'V' ) drop view dbo.vGetDate GO create view dbo.vGetDate as select vGetDate = GetDate() GO if exists ( select * from sysobjects where [Name] = 'inMonth' AND [Type] = 'FN' ) drop function dbo.inMonth GO create function dbo.inMonth( @Month int, @Date datetime ) returns int begin if Month( @Date ) = @Month return 1 return 0 end GO if exists ( select * from sysobjects where [Name] = 'inYear' AND [Type] = 'FN' ) drop function dbo.inYear GO create function dbo.inYear( @Year int, @Date datetime ) returns int begin if @Year < 10 select @Year = Year( vGetDate ) + @Year from vGetDate if Year( @Date ) = @Year return 1 return 0 end GO if exists ( select * from sysobjects where [Name] = 'inPeriod' AND [Type] = 'FN' ) drop function dbo.inPeriod GO create function dbo.inPeriod( @Date datetime, @Month int, @Year int ) returns int begin if @Year < 10 select @Year = Year( vGetDate ) + @Year from vGetDate if @Month < 1 begin if @Month = 0 select @Month = Month( vGetDate ) from vGetDate if Month( @Date ) <= Abs( @Month ) AND Year( @Date ) = @Year return 1 end else begin if Month( @Date ) = @Month AND Year( @Date ) = @Year return 1 end return 0 end GO if exists ( select * from sysobjects where [Name] = 'ValueByDate' AND [Type] = 'FN' ) drop function dbo.ValueByDate GO if exists ( select * from sysobjects where [Name] = 'Mod' AND [Type] = 'FN' ) drop function dbo.Mod GO create function dbo.Mod( @Value1 decimal( 18, 4 ), @Value2 decimal( 18, 4 ) ) returns decimal( 18, 4 ) begin declare @Result Decimal( 18, 4 ) set @Result = Cast( @Value1 * 10000 as int ) % Cast( @Value2 * 10000 as int ) return @Result / 10000 end GO if exists ( select * from sysobjects where [Name] = 'Minimum' AND [Type] = 'FN' ) drop function dbo.Minimum GO create function dbo.Minimum( @Value1 decimal( 18, 4 ), @Value2 decimal( 18, 4 ) ) returns decimal( 18, 4 ) begin if @Value2 is Null OR @Value1 < @Value2 return @Value1 return @Value2 end GO if exists ( select * from sysobjects where [Name] = 'Maximum' AND [Type] = 'FN' ) drop function dbo.Maximum GO create function dbo.Maximum( @Value1 decimal( 18, 4 ), @Value2 decimal( 18, 4 ) ) returns decimal( 18, 4 ) begin if @Value2 is Null OR @Value1 > @Value2 return @Value1 return @Value2 end GO if exists ( select * from sysobjects where [Name] = 'MinDate' AND [Type] = 'FN' ) drop function dbo.MinDate GO create function dbo.MinDate( @Value1 datetime, @Value2 datetime ) returns datetime begin if @Value2 is Null OR @Value1 < @Value2 return @Value1 return @Value2 end GO if exists ( select * from sysobjects where [Name] = 'MaxDate' AND [Type] = 'FN' ) drop function dbo.MaxDate GO create function dbo.MaxDate( @Value1 datetime, @Value2 datetime ) returns datetime begin if @Value2 is Null OR @Value1 > @Value2 return @Value1 return @Value2 end GO if exists ( select * from sysobjects where [Name] = 'DateOnly' AND [Type] = 'FN' ) drop function dbo.DateOnly GO create function dbo.DateOnly( @Value datetime ) returns char( 10 ) begin return convert( char( 10 ), @Value, 120 ) end GO if exists ( select * from sysobjects where [Name] = 'TimeOnly' AND [Type] = 'FN' ) drop function dbo.TimeOnly GO create function dbo.TimeOnly( @Value datetime ) returns char( 8 ) begin return convert( char( 8 ), @Value, 108 ) end GO if exists ( select * from sysobjects where [Name] = 'PadLeft' AND [Type] = 'FN' ) drop function dbo.PadLeft GO create function dbo.PadLeft( @Value varchar( 4000 ), @Length int ) returns varchar( 4000 ) begin if Len( @Value ) < @Length return stuff( @Value, 1, 0, replicate( ' ', @Length - Len( @Value ) ) ) return SubString( @Value, 1, @Length ) end GO if exists ( select * from sysobjects where [Name] = 'PadCenter' AND [Type] = 'FN' ) drop function dbo.PadCenter GO create function dbo.PadCenter( @Value varchar( 4000 ), @Length int ) returns varchar( 4000 ) begin if Len( @Value ) < @Length return stuff( @Value + replicate( ' ', ceiling( ( @Length - Len( @Value ) ) / 2 ) ), 1, 0, replicate( ' ', floor( ( @Length - Len( @Value ) ) / 2 ) ) ) return SubString( @Value, 1, @Length ) end GO if exists ( select * from sysobjects where [Name] = 'FirstName' AND [Type] = 'FN' ) drop function dbo.FirstName GO create function dbo.FirstName( @Name varchar( 1000 ) ) returns varchar( 1000 ) begin set @Name = lTrim( rTrim( @Name ) ) declare @U varchar( 1000 ) set @U = Upper( @Name ) if CharIndex( 'INC.', @U ) > 0 OR CharIndex( 'LTD', @U ) > 0 OR CharIndex( 'CO.', @U ) > 0 OR CharIndex( 'ENR.', @U ) > 0 OR CharIndex( 'REG.', @U ) > 0 OR CharIndex( 'CORP', @U ) > 0 OR CharIndex( 'CIE.', @U ) > 0 OR CharIndex( 'INC', @U ) = Len( @U ) - 2 OR CharIndex( 'CO', @U ) = Len( @U ) - 1 OR CharIndex( 'ENR', @U ) = Len( @U ) - 2 OR CharIndex( 'CIE', @U ) = Len( @U ) - 2 return NULL declare @I int, @R varchar( 1000 ) set @R = NULL set @I = CharIndex( ',', @Name ) if @I > 0 AND @I < Len( @Name ) set @R = SubString( @Name, @I + 1, Len( @Name ) - @I ) else begin set @I = CharIndex( ' ', @Name ) if @I > 0 set @R = SubString( @Name, 1, @I - 1 ) end return lTrim( rTrim( @R ) ) end GO if exists ( select * from sysobjects where [Name] = 'LastName' AND [Type] = 'FN' ) drop function dbo.LastName GO create function dbo.LastName( @Name varchar( 1000 ) ) returns varchar( 1000 ) begin set @Name = lTrim( rTrim( @Name ) ) declare @U varchar( 1000 ) set @U = Upper( @Name ) if CharIndex( 'INC.', @U ) > 0 OR CharIndex( 'LTD', @U ) > 0 OR CharIndex( 'CO.', @U ) > 0 OR CharIndex( 'ENR.', @U ) > 0 OR CharIndex( 'REG.', @U ) > 0 OR CharIndex( 'CORP', @U ) > 0 OR CharIndex( 'CIE.', @U ) > 0 OR CharIndex( 'INC', @U ) = Len( @U ) - 2 OR CharIndex( 'CO', @U ) = Len( @U ) - 1 OR CharIndex( 'ENR', @U ) = Len( @U ) - 2 OR CharIndex( 'CIE', @U ) = Len( @U ) - 2 return '' declare @I int, @R varchar( 1000 ) set @R = @Name set @I = CharIndex( ',', @Name ) if @I > 0 set @R = SubString( @Name, 1, @I - 1 ) else begin set @I = CharIndex( ' ', @Name ) if @I > 0 AND @I < Len( @Name ) set @R = SubString( @Name, @I + 1, Len( @Name ) - @I ) end return lTrim( rTrim( @R ) ) end GO --if exists ( select * from sysobjects where [Name] = 'LongestWord' AND [Type] = 'FN' ) drop function dbo.LongestWord --GO --create function dbo.LongestWord( @Text varchar( 4000 ) ) returns varchar( 4000 ) --begin -- declare @@I int, @@N int, @@Len int, @@Result varchar( 4000 ), @@S varchar( 4000 ) -- set @@N = CharIndex( ' ', @Text ) -- if @@N = 0 set @@Result = @Text -- else set @@Result = SubString( @Text, 1, @@N - 1 ) -- while @@N <> 0 AND @@N < Len( @Text ) begin -- set @@I = CharIndex( ' ', @Text, @@N + 1 ) -- if @@I = 0 set @@S = SubString( @Text, @@N + 1, Len( @Text ) ) -- else set @@S = SubString( @Text, @@N + 1, @@I - @@N - 1 ) -- if Len( @@S ) > Len( @@Result ) set @@Result = @@S -- set @@N = @@I -- end -- return @@Result --end --GO if exists ( select * from sysobjects where [Name] = 'LongestWord' AND [Type] = 'FN' ) drop function dbo.LongestWord GO create function dbo.LongestWord( @Text varchar( 4000 ) ) returns varchar( 4000 ) begin declare @@I int, @@N int, @@Len int, @@Result varchar( 4000 ), @@S varchar( 4000 ) set @@N = CharIndex( ' ', @Text ) if @@N <> 0 set @@Result = SubString( @Text, 1, @@N - 1 ) else begin set @@N = CharIndex( '-', @Text ) if @@N <> 0 set @@Result = SubString( @Text, 1, @@N - 1 ) else begin set @@N = CharIndex( '#', @Text ) if @@N <> 0 set @@Result = SubString( @Text, 1, @@N - 1 ) else set @@Result = @Text end end while @@N <> 0 AND @@N < Len( @Text ) begin set @@I = CharIndex( ' ', @Text, @@N + 1 ) if @@I = 0 set @@S = SubString( @Text, @@N + 1, Len( @Text ) ) else set @@S = SubString( @Text, @@N + 1, @@I - @@N - 1 ) set @@I = CharIndex( '0', @@S ) if @@I <> 0 set @@S = '' else begin set @@I = CharIndex( '1', @@S ) if @@I <> 0 set @@S = '' else begin set @@I = CharIndex( '2', @@S ) if @@I <> 0 set @@S = '' else begin set @@I = CharIndex( '3', @@S ) if @@I <> 0 set @@S = '' else begin set @@I = CharIndex( '4', @@S ) if @@I <> 0 set @@S = '' else begin set @@I = CharIndex( '5', @@S ) if @@I <> 0 set @@S = '' else begin set @@I = CharIndex( '6', @@S ) if @@I <> 0 set @@S = '' else begin set @@I = CharIndex( '7', @@S ) if @@I <> 0 set @@S = '' else begin set @@I = CharIndex( '8', @@S ) if @@I <> 0 set @@S = '' else begin set @@I = CharIndex( '9', @@S ) if @@I <> 0 set @@S = '' end end end end end end end end end set @@I = CharIndex( '-', @@S ) if @@I <> 0 set @@S = SubString( @@S, 1, @@I - 1 ) set @@I = CharIndex( '#', @@S ) if @@I <> 0 set @@S = SubString( @@S, 1, @@I - 1 ) if Len( @@S ) > Len( @@Result ) set @@Result = @@S set @@N = CharIndex( ' ', @Text, @@N + 1 ) end set @@I = CharIndex( '0', @@Result ) if @@I <> 0 set @@Result = '' else begin set @@I = CharIndex( '1', @@Result ) if @@I <> 0 set @@Result = '' else begin set @@I = CharIndex( '2', @@Result ) if @@I <> 0 set @@Result = '' else begin set @@I = CharIndex( '3', @@Result ) if @@I <> 0 set @@Result = '' else begin set @@I = CharIndex( '4', @@Result ) if @@I <> 0 set @@Result = '' else begin set @@I = CharIndex( '5', @@Result ) if @@I <> 0 set @@Result = '' else begin set @@I = CharIndex( '6', @@Result ) if @@I <> 0 set @@Result = '' else begin set @@I = CharIndex( '7', @@Result ) if @@I <> 0 set @@Result = '' else begin set @@I = CharIndex( '8', @@Result ) if @@I <> 0 set @@Result = '' else begin set @@I = CharIndex( '9', @@Result ) if @@I <> 0 set @@Result = '' else begin set @@I = CharIndex( '%', @@Result ) if @@I <> 0 set @@Result = '' else begin set @@I = CharIndex( '$', @@Result ) if @@I <> 0 set @@Result = '' end end end end end end end end end end end if Len( @@Result ) < 4 set @@Result = 'Misc' return @@Result end GO if exists ( select * from sysobjects where [Name] = 'ValidWords' AND [Type] = 'FN' ) drop function dbo.ValidWords GO create function dbo.ValidWords( @Text varchar( 4000 ) ) returns varchar( 4000 ) begin declare @@I int, @@C char, @@Word varchar( 4000 ), @@Result varchar( 4000 ), @@inWord bit select @@I = 1, @@Word = '', @@Result = '', @@inWord = 0 while @@i < Len( @Text ) begin set @@C = SubString( @Text, @@I, 1 ) if @@C = ' ' begin set @@inWord = 0 if Len( @@Word ) > 2 set @@Result = @@Result + @@Word + ' ' set @@Word = '' -- add any valid word found end else if @@C >= 'A' AND @@C <= 'z' select @@inWord = 1, @@Word = @@Word + @@C -- build a valid word else select @@inWord = - 1, @@Word = '' -- erase any invalid word set @@I = @@I + 1 end set @@Result = @@Result + @@Word if @@Result = '' return 'Misc' return @@Result end GO --if exists ( select * from sysobjects where [Name] = 'Tokens' AND [Type] = 'FN' ) drop function dbo.Tokens --GO --create function dbo.Tokens( @Char char, @Str varchar( 4000 ) ) returns int --begin -- declare @Result int, @i int, @j int -- if rTrim( @Str ) = '' return 0 else select @Result = 1 -- set @j = Len( @Str ) set @i = 1 -- while @i <= @j begin -- if SubString( @Str, @i, 1 ) = @Char select @Result = @Result + 1 -- set @i = @i + 1 -- end -- return @Result --end --GO if exists ( select * from sysobjects where [Name] = 'Tokens' AND [Type] = 'FN' ) drop function dbo.Tokens GO create function dbo.Tokens( @Char char, @Str varchar( 4000 ) ) returns int begin declare @Result int, @i int if rTrim( @Str ) = '' return 0 else set @Result = 1 set @i = CharIndex( @Char, @Str ) while @i <> 0 begin set @Result = @Result + 1 set @i = CharIndex( @Char, @Str, @i + 1 ) end return @Result end GO if exists ( select * from sysobjects where [Name] = 'Token' AND [Type] = 'FN' ) drop function dbo.Token GO create function dbo.Token( @Char char, @Str varchar( 4000 ), @Index int ) returns varchar( 4000 ) begin declare @Result varchar( 4000 ), @i int, @Last int set @Result = '' set @i = 0 while @Index > 0 begin set @Index = @Index - 1 set @Last = @i set @i = CharIndex( @Char, @Str, @i + 1 ) if @i = 0 set @i = Len( @Str ) + 1 end if @i - @Last - 1 > 0 set @Result = SubString( @Str, @Last + 1, @i - @Last - 1 ) return @Result end GO if exists ( select * from sysobjects where [Name] = 'ListAsIntTable' AND [Type] = 'TF' ) drop function dbo.ListAsIntTable GO create function dbo.ListAsIntTable( @ID_List varchar( 8000 ) ) returns @Result table ( ID int NOT NULL ) as begin declare @P1 int, @P2 int, @Len int select @P1 = 0, @P2 = Len( @ID_list ) while @P2 > 0 begin select @P2 = charindex( ',', @ID_List, @P1 + 1 ) select @Len = case when @P2 > 0 then @P2 else Len( @ID_list ) + 1 end - @P1 - 1 if @Len > 0 insert @Result ( ID ) values( convert( int, substring( @ID_List, @P1 + 1, @Len ) ) ) select @P1 = @P2 end return end GO if exists ( select * from sysobjects where [Name] = 'Capitalize' AND [Type] = 'FN' ) drop function dbo.Capitalize GO create function dbo.Capitalize( @Text varchar( 4000 ) ) returns varchar( 4000 ) begin declare @Result varchar( 4000 ), @I int, @Count int, @C char( 1 ), @inWord bit select @Result = '' select @Text = Lower( @Text ) select @I = 1 select @Count = Len( @Text ) select @inWord = 0 while @I <= @Count begin select @C = SubString( @Text, @I, 1 ) if @C = ' ' select @inWord = 0 else begin if @inWord = 0 AND @I < @Count - 3 AND SubString( @Text, @I + 1, 1 ) <> ' ' AND SubString( @Text, @I + 2, 1 ) <> ' ' AND SubString( @Text, @I + 3, 1 ) <> ' ' select @C = Upper( @C ) -- if @inWord = 1 AND @I > 1 AND SubString( @Text, @I - 1, 1 ) >= '0' AND SubString( @Text, @I - 1, 1 ) <= '9' ) select @C = Upper( @C ) select @inWord = 1 end select @Result = @Result + @C select @I = @I + 1 end return @Result end GO if exists ( select * from sysobjects where [Name] = 'TrimNonAscii' AND [Type] = 'FN' ) drop function dbo.TrimNonAscii GO create function dbo.TrimNonAscii( @Text varchar( 4000 ) ) returns varchar( 4000 ) begin declare @C char( 1 ), @Result varchar( 4000 ), @I int set @I = 1 set @Result = '' while @I <= Len( @Text ) begin set @C = SubString( @Text, @I, 1 ) if @C >= Char( 32 ) AND @C <= Char( 255 ) set @Result = @Result + @C set @I = @I + 1 end return @Result end GO if exists ( select * from sysobjects where [Name] = 'TrimNonLetter' AND [Type] = 'FN' ) drop function dbo.TrimNonLetter GO create function dbo.TrimNonLetter( @Text varchar( 4000 ) ) returns varchar( 4000 ) begin declare @C char( 1 ), @Result varchar( 4000 ), @I int set @I = 1 set @Result = '' while @I <= Len( @Text ) begin set @C = SubString( @Text, @I, 1 ) if @C >= 'A' AND @C <= 'z' set @Result = @Result + @C set @I = @I + 1 end return @Result end GO if exists ( select * from sysobjects where [Name] = 'TrimNonNumber' AND [Type] = 'FN' ) drop function dbo.TrimNonNumber GO create function dbo.TrimNonNumber( @Text varchar( 4000 ) ) returns varchar( 4000 ) begin declare @C char( 1 ), @Result varchar( 4000 ), @I int set @I = 1 set @Result = '' while @I <= Len( @Text ) begin set @C = SubString( @Text, @I, 1 ) if @C >= '0' AND @C <= '9' set @Result = @Result + @C set @I = @I + 1 end return @Result end GO if exists ( select * from sysobjects where [Name] = 'ValidName' AND [Type] = 'FN' ) drop function dbo.ValidName GO create function dbo.ValidName( @Name varchar( 100 ) ) returns varchar( 100 ) begin declare @C char( 1 ), @Result varchar( 100 ), @I int select @I = 1 select @Result = '' while @I <= Len( @Name ) begin select @C = SubString( @Name, @I, 1 ) if NOT ( ( @C >= '0' AND @C <= '9' ) OR ( @C >= 'A' AND @C <= 'Z' ) OR ( @C >= 'a' AND @C <= 'z' ) ) select @C = '_' select @Result = @Result + @C select @I = @I + 1 end return rTrim( @Result ) end GO if exists ( select * from sysobjects where [Name] = 'SubstFileName' AND [Type] = 'FN' ) drop function dbo.SubstFileName GO create function dbo.SubstFileName( @Name varchar( 100 ) ) returns varchar( 100 ) begin declare @C char( 1 ), @Result varchar( 100 ), @I int select @I = 1 select @Result = '' while @I <= Len( @Name ) begin select @C = SubString( @Name, @I, 1 ) -- '.', '-', '_', '!', '(', ')', '[', ']' if NOT ( ( @C = '.' ) OR ( @C = '-' ) OR ( @C = '_' ) OR ( @C = '!' ) OR ( @C = '(' ) OR ( @C = ')' ) OR ( @C = '[' ) OR ( @C = ']' ) OR ( @C >= '0' AND @C <= '9' ) OR ( @C >= 'A' AND @C <= 'Z' ) OR ( @C >= 'a' AND @C <= 'z' ) ) select @C = '_' select @Result = @Result + @C select @I = @I + 1 end return rTrim( @Result ) end GO if exists ( select * from sysobjects where [Name] = 'ValidURL' AND [Type] = 'FN' ) drop function dbo.ValidURL GO create function dbo.ValidURL( @Name varchar( 100 ) ) returns varchar( 100 ) begin declare @C char( 1 ), @Result varchar( 100 ), @I int select @I = 1 select @Result = '' while @I <= Len( @Name ) begin select @C = SubString( @Name, @I, 1 ) if NOT ( ( @C >= '0' AND @C <= '9' ) OR ( @C >= 'A' AND @C <= 'Z' ) OR ( @C >= 'a' AND @C <= 'z' ) OR @C = '-' ) select @C = '_' select @Result = @Result + @C select @I = @I + 1 end return rTrim( @Result ) end GO if exists ( select * from sysobjects where [Name] = 'ColumnList' AND [Type] = 'FN' ) drop function dbo.ColumnList GO create function dbo.ColumnList( @Table varchar( 100 ) ) returns varchar( 4000 ) begin declare @Result varchar( 4000 ) select @Result = Coalesce( @Result + ',', '' ) + '[' + Column_Name + ']' from Information_Schema.Columns where Table_Name = @Table order by Ordinal_Position return @Result end GO if exists ( select * from sysobjects where [Name] = 'SetDefault' AND [Type] = 'P' ) drop procedure dbo.SetDefault GO create procedure dbo.SetDefault( @TableName sysname, @ColName sysname, @DefExpr varchar( 500 ) ) as begin set NOCOUNT ON if exists ( select * from INFORMATION_SCHEMA.TABLES where Table_Name = @TableName ) begin declare @@Cmd varchar( 500 ) if exists ( select * from INFORMATION_SCHEMA.COLUMNS where Table_Name = @TableName AND Column_Name = @ColName AND Column_Default IS NOT NULL ) begin select @@Cmd = isNull( SO.[Name], '' ) from sysObjects SO join sysColumns SC on SO.ID = SC.cDefault where SC.ID = OBJECT_ID( @TableName ) AND SC.[Name] = @ColName if @@Cmd <> '' begin select @@Cmd = 'alter table ' + @TableName + ' drop constraint ' + @@Cmd exec( @@Cmd ) end end if @DefExpr <> '' begin select @@Cmd = 'alter table ' + @TableName + ' add default ' + @DefExpr + ' for ' + @ColName exec( @@Cmd ) end end set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'DropDefault' AND [Type] = 'P' ) drop procedure dbo.DropDefault GO create procedure dbo.DropDefault( @TableName sysname, @ColName sysname ) as if exists ( select * from INFORMATION_SCHEMA.COLUMNS where Table_Name = @TableName AND Column_Name = @ColName AND Column_Default IS NOT NULL ) begin declare @@Cmd varchar( 500 ) select @@Cmd = isNull( SO.[Name], '' ) from sysObjects SO join sysColumns SC on SO.ID = SC.cDefault where SC.ID = OBJECT_ID( @TableName ) AND SC.[Name] = @ColName if @@Cmd <> '' begin select @@Cmd = 'alter table ' + @TableName + ' drop constraint ' + @@Cmd exec( @@Cmd ) end end GO if exists ( select * from sysobjects where [Name] = 'DropConstraint' AND [Type] = 'P' ) drop procedure dbo.DropConstraint GO create procedure dbo.DropConstraint( @TableName sysname, @ColName sysname ) as if exists ( select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where Table_Name = @TableName AND Column_Name = @ColName ) begin declare @@Cmd varchar( 500 ) select @@Cmd = isNull( Constraint_Name, '' ) from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where Table_Name = @TableName AND Column_Name = @ColName if @@Cmd <> '' begin select @@Cmd = 'alter table ' + @TableName + ' drop constraint ' + @@Cmd exec( @@Cmd ) end end GO if exists ( select * from sysobjects where [Name] = 'CopyChildren' AND [Type] = 'P' ) drop procedure dbo.CopyChildren GO create procedure dbo.CopyChildren( @TableName sysname, @OldID int, @NewID int ) as begin set NOCOUNT ON create table #fKeys( PKTABLE_QUALIFIER sysname collate database_default NULL, PKTABLE_OWNER sysname collate database_default NULL, PKTABLE_NAME sysname collate database_default NOT NULL, PKCOLUMN_NAME sysname collate database_default NOT NULL, FKTABLE_QUALIFIER sysname collate database_default NULL, FKTABLE_OWNER sysname collate database_default NULL, FKTABLE_NAME sysname collate database_default NOT NULL, FKCOLUMN_NAME sysname collate database_default NOT NULL, KEY_SEQ smallint NOT NULL, UPDATE_RULE smallint NULL, DELETE_RULE smallint NULL, FK_NAME sysname collate database_default NULL, PK_NAME sysname collate database_default NULL, DEFERRABILITY smallint null ) insert into #fKeys exec sp_fkeys @TableName delete #fKeys where Delete_Rule <> 0 declare @Cmd varchar( 4000 ), @FKTable sysname, @FKColumn sysname declare Children cursor local for select FKTable_Name, FKColumn_Name from #fKeys open Children fetch Children into @FKTable, @FKColumn while @@FETCH_STATUS = 0 begin select @Cmd = 'declare @OldChildID int, @NewChildID int ' + 'select * into #' + @FKTable + App_Name() + ' from ' + @FKTable + ' where ' + @FKColumn + ' = ' + rTrim( Convert( char( 20 ), @OldID ) ) + ' ' + 'if exists ( select * from #' + @FKTable + App_Name() + ' ) begin ' + 'update #' + @FKTable + App_Name() + ' set GUID = NewID(), ' + @FKColumn + ' = ' + rTrim( Convert( char( 20 ), @NewID ) ) + ' ' + 'select * into #' + @FKTable + App_Name() + '2 from #' + @FKTable + App_Name() + ' ' + 'alter table #' + @FKTable + App_Name() + '2 drop column ID ' + 'select * into #' + @FKTable + App_Name() + '3 from #' + @FKTable + App_Name() + '2 ' + 'declare Keys cursor local for select ID from #' + @FKTable + App_Name() + ' open Keys ' + 'declare Recs cursor local for select * from #' + @FKTable + App_Name() + '3 open Recs ' + 'fetch Keys into @OldChildID fetch Recs ' + 'while @@FETCH_STATUS = 0 begin ' + 'insert ' + @FKTable + ' select top 1 * from #' + @FKTable + App_Name() + '3 ' + 'select @NewChildID = Scope_Identity() ' + 'exec CopyChildren ''' + @FKTable + ''', @OldChildID, @NewChildID ' + 'delete #' + @FKTable + App_Name() + ' where current of Keys ' + 'delete #' + @FKTable + App_Name() + '3 where current of Recs ' + 'fetch Keys into @OldChildID fetch Recs ' + 'end ' + 'close Recs deallocate Recs ' + 'close Keys deallocate Keys ' + 'drop table #' + @FKTable + App_Name() + '2 drop table #' + @FKTable + App_Name() + '3 ' + 'end ' + 'drop table #' + @FKTable + App_Name() + ' ' exec( @Cmd ) fetch Children into @FKTable, @FKColumn end close Children deallocate Children set NOCOUNT OFF end GO ------------- -- Fixes -- ------------- if ( select [Value] from ::fn_listextendedproperty( 'Version', default, default, default, default, default, default ) ) < '2009-12-22' begin exec dbo.SetDefault 'Resources', 'Publish_This_Resource', '1' update Resources set Publish_This_Resource = 1 end GO if ( select [Value] from ::fn_listextendedproperty( 'Version', default, default, default, default, default, default ) ) < '2009-12-22.1' begin alter table Resources add Category_Name varchar( 100 ) NULL execute dbo.DropConstraint 'Resources', 'Type' alter table Resources add constraint CK_Resources_Type check( [Type] IN ( 'Product', 'Equipment', 'Task', 'Contact', 'Template', 'Category' ) ) end GO ------------- -- UndoLog -- ------------- if exists ( select * from sysobjects where [Name] = 'UpdColList' AND [Type] = 'FN' ) drop function dbo.UpdColList GO create function dbo.UpdColList( @Table varchar( 100 ), @Updated varbinary( 100 ) ) returns varchar( 8000 ) begin declare @Col int, @TID int, @Colname varchar( 100 ), @Result varchar( 8000 ) set @Col = 0 set @TID = Object_ID( @Table ) set @Result = '' while @Col < Len( @Updated ) * 8 + 8 begin -- LEN() returns one less??? ( 8 columns per byte and 256 columns or 32 bytes maximum ) if SubString( @Updated, Floor( @Col / 8 ) + 1, 1 ) & Power( 2, @Col % 8 ) <> 0 begin set @ColName = Col_Name( @TID, @Col + 1 ) if @ColName is NOT Null set @Result = @Result + '[' + @ColName + '],' end set @Col = @Col + 1 end if @Result <> '' set @Result = SubString( @Result, 1, Len( @Result ) - 1 ) return @Result end GO if exists ( select * from sysobjects where [Name] = 'UndoLog_Insert' AND [Type] = 'TR' ) drop trigger UndoLog_Insert GO create trigger UndoLog_Insert on UndoLog for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON declare @CmdTxt varchar( 8000 ) --select @CmdTxt = 'update UndoLog set New_Values = ( select ' + dbo.UpdColList( Table_Name, Cols_Updated ) + select @CmdTxt = 'update UndoLog set New_Updated = 1, New_Values = ( select ' + dbo.UpdColList( Table_Name, Cols_Updated ) + ' from ' + Table_Name + ' where ID = ' + cast( Table_ID as varchar( 20 ) ) + ' for xml auto ) where New_Updated <> 1' -- ' for xml auto ) where New_Values is Null' from Inserted exec( @CmdTxt ) set NOCOUNT OFF end GO ------------------- -- Notifications -- ------------------- if exists ( select * from sysobjects where [Name] = 'ModColList' AND [Type] = 'FN' ) drop function dbo.ModColList GO create function dbo.ModColList( @Table varchar( 100 ), @Updated varbinary( 100 ) ) returns varchar( 4000 ) begin declare @Col int, @TID int, @Result varchar( 4000 ), @ColName varchar( 100 ) select @Col = 0 select @TID = Object_ID( @Table ) select @Result = '' while @Col < 32 * 8 begin if SubString( @Updated, Floor( @Col / 8 ) + 1, 1 ) & Power( 2, @Col % 8 ) <> 0 begin select @ColName = Col_Name( @TID, @Col + 1 ) if ( select Data_Type from Information_Schema.Columns where Table_Name = @Table AND Column_Name = @ColName ) <> 'image' select @Result = @Result + '" ' + @ColName + ': " + ' + 'rTrim( Cast( [' + @ColName + '] as varchar( 100 ) ) ) + Char( 13 ) + Char( 10 ) +' -- select @Result = @Result + ''' ' + @ColName + ': '' + ' + 'rTrim( Cast( [' + @ColName + '] as varchar( 100 ) ) ) + Char( 13 ) + Char( 10 ) +' end select @Col = @Col + 1 end if @Result = '' return @Result return SubString( @Result, 1, Len( @Result ) - Len( '+ Char( 13 ) + Char( 10 ) +' ) ) end GO if exists ( select * from sysobjects where [Name] = 'CheckNotifications' AND [Type] = 'P' ) drop procedure dbo.CheckNotifications GO create procedure dbo.CheckNotifications as begin set NOCOUNT ON -- Add any Late Notifications insert Notifications ( Table_Name, Table_ID, Notification_List, Subject, Body ) select 'Orders', ID, Late_Notification_List, Cast( GetDate() as varchar( 100 ) ) + ' Late Alert on ' + rTrim( [Name] ), Cast( GetDate() as varchar( 100 ) ) + ' Late Alert on ' + rTrim( [Name] ) from Orders where Date_Locked is Null AND rTrim( Late_Notification_List ) <> '' AND isNull( Date_Required, GetDate() ) <= DateAdd( Hour, Floor( 24 * Notify_when_Late_by_Days ), GetDate() ) insert Notifications ( Table_Name, Table_ID, Notification_List, Subject, Body ) select 'Activities', ID, Late_Notification_List, Cast( GetDate() as varchar( 100 ) ) + ' Late Alert on ' + rTrim( [Name] ), Cast( GetDate() as varchar( 100 ) ) + ' Late Alert on ' + rTrim( [Name] ) from Activities where Date_Locked is Null AND rTrim( Late_Notification_List ) <> '' AND isNull( Date_Stop, GetDate() ) <= DateAdd( Hour, Floor( 24 * Notify_when_Late_by_Days ), GetDate() ) -- Add any Follow-Up Notifications insert Notifications ( Table_Name, Table_ID, Notification_List, Subject, Body ) select 'Orders', ID, [Follow-Up_Notification_List], Cast( GetDate() as varchar( 100 ) ) + ' Follow-Up on ' + rTrim( [Name] ), Cast( GetDate() as varchar( 100 ) ) + ' Follow-Up on ' + rTrim( [Name] ) from Orders where Date_Locked is Null AND rTrim( [Follow-Up_Notification_List] ) <> '' AND isNull( [Date_Last_Follow-Up_Done], DateAdd( Day, - [Follow-Up_every_Days], Date_Created ) ) < DateAdd( Day, - [Follow-Up_every_Days], GetDate() ) update Orders set [Date_Last_Follow-Up_Done] = GetDate() where Date_Locked is Null AND rTrim( [Follow-Up_Notification_List] ) <> '' AND isNull( [Date_Last_Follow-Up_Done], DateAdd( Day, - [Follow-Up_every_Days], Date_Created ) ) < DateAdd( Day, - [Follow-Up_every_Days], GetDate() ) insert Notifications ( Table_Name, Table_ID, Notification_List, Subject, Body ) select 'Activities', ID, [Follow-Up_Notification_List], Cast( GetDate() as varchar( 100 ) ) + ' Follow-Up on ' + rTrim( [Name] ), Cast( GetDate() as varchar( 100 ) ) + ' Follow-Up on ' + rTrim( [Name] ) from Activities where Date_Locked is Null AND rTrim( [Follow-Up_Notification_List] ) <> '' AND isNull( [Date_Last_Follow-Up_Done], DateAdd( Day, - [Follow-Up_every_Days], Date_Created ) ) < DateAdd( Day, - [Follow-Up_every_Days], GetDate() ) update Activities set [Date_Last_Follow-Up_Done] = GetDate() where Date_Locked is Null AND rTrim( [Follow-Up_Notification_List] ) <> '' AND isNull( [Date_Last_Follow-Up_Done], DateAdd( Day, - [Follow-Up_every_Days], Date_Created ) ) < DateAdd( Day, - [Follow-Up_every_Days], GetDate() ) set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Notifications_Insert' AND [Type] = 'TR' ) drop trigger Notifications_Insert GO create trigger Notifications_Insert on Notifications for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - Notifications_Insert' declare @Cmd varchar( 4000 ), @Body varchar( 4000 ), @Notify varchar( 1000 ), @Table varchar( 100 ), @ID varchar( 10 ), @TID varchar( 10 ) declare CurRec cursor local for select ID, Table_Name, Table_ID, Notification_List, Body from Inserted open CurRec fetch CurRec into @ID, @Table, @TID, @Notify, @Body while @@FETCH_STATUS = 0 begin if rTrim( @Body ) = '' delete Notifications where ID = @ID else begin -- -- print 'Debug - ' + @Body if NOT exists( select ID from Notifications where ID <> @ID AND Table_Name = @Table AND Table_ID = @TID AND Notification_List = @Notify AND Date_Sent is Null ) select @Cmd = 'update Notifications set Body = ''' + rTrim( @Body ) + ''' where ID = ' + @ID else begin select @Cmd = 'update Notifications set Body = rTrim( Body ) + Char( 13 ) + Char( 10 ) + ''' + rTrim( @Body ) + ''' where ID <> ' + @ID + ' AND Table_Name = ''' + @Table + ''' AND Table_ID = ' + @TID + ' AND Notification_List = ''' + @Notify + ''' AND Date_Sent is Null' delete Notifications where ID = @ID end exec( @Cmd ) end fetch CurRec into @ID, @Table, @TID, @Notify, @Body end close CurRec deallocate CurRec set NOCOUNT OFF end GO -------------- -- TaxProfiles -- -------------- if exists ( select * from sysobjects where [Name] = 'TaxProfiles_Insert' AND [Type] = 'TR' ) drop trigger TaxProfiles_Insert GO create trigger TaxProfiles_Insert on TaxProfiles for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - TaxProfiles_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'TaxProfiles', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update TaxProfiles set Date_Modified = I.Date_Modified from Inserted I join TaxProfiles T on T.ID = I.ID set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'TaxProfiles_Update' AND [Type] = 'TR' ) drop trigger TaxProfiles_Update GO create trigger TaxProfiles_Update on TaxProfiles for update as begin if exists( select ID from Inserted ) begin set NOCOUNT ON -- print 'Debug - TaxProfiles_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'TaxProfiles', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------ -- Update G/L Accounts Info -- ------------------------------ update TaxProfiles set Tax1_Account_ID = A.ID from Inserted I join TaxProfiles T on T.ID = I.ID join Accounts A on A.[Name] = I.Tax1_Account where T.Tax1_Account_ID is Null OR Update( Tax1_Account ) update TaxProfiles set Tax1_Account = A.[Name] from Inserted I join TaxProfiles T on T.ID = I.ID join Accounts A on A.ID = I.Tax1_Account_ID where T.Tax1_Account is Null OR T.Tax1_Account = '' OR Update( Tax1_Account_ID ) update TaxProfiles set Tax2_Account_ID = A.ID from Inserted I join TaxProfiles T on T.ID = I.ID join Accounts A on A.[Name] = I.Tax2_Account where T.Tax2_Account_ID is Null OR Update( Tax2_Account ) update TaxProfiles set Tax2_Account = A.[Name] from Inserted I join TaxProfiles T on T.ID = I.ID join Accounts A on A.ID = I.Tax2_Account_ID where T.Tax2_Account is Null OR T.Tax2_Account = '' OR Update( Tax2_Account_ID ) set NOCOUNT OFF end end GO -------------- -- Contacts -- -------------- -- exec dbo.CalcContactBal ''{990250AA-A8DB-470F-8F9D-7A870B2FEB1B}' -- select ID, Contact_ID, Amount from Ledger where Date_Locked is Null AND Contact_ID = 193 AND ( Account_is_AR = 1 OR Account_is_AP = 1 ) order by [Date], ID if exists ( select * from sysobjects where [Name] = 'CalcContactBal' AND [Type] = 'P' ) drop procedure dbo.CalcContactBal GO create procedure dbo.CalcContactBal( @GUID varchar( 4000 ) ) as begin set NOCOUNT ON -- print 'Debug - CalcContBalance ' + @GUID declare @ID int, @CID int, @BID int, @Amt decimal( 18,4 ), @CurBal decimal( 18,4 ) if @GUID = '' select @CID = - 1 else select @CID = isNull( ID, 0 ) from Contacts where GUID = @GUID set @CurBal = 0.0 set @BID = 0 -- -- print 'Debug - CalcContBalance ' + Cast( @CID as varchar( 10 ) ) if @CID = - 1 begin -- No GUID means do all Contacts LONG Process update Contacts set Balance = 0 declare TrxCursor cursor local for select ID, Contact_ID, Amount from Ledger where Date_Locked is Null AND ( Account_is_AR = 1 OR Account_is_AP = 1 ) order by Contact_ID, [Date], ID end else begin update Contacts set Balance = 0 where ID = @CID declare TrxCursor cursor local for select ID, Contact_ID, Amount from Ledger where Date_Locked is Null AND ( Account_is_AR = 1 OR Account_is_AP = 1 ) AND Contact_ID = @CID order by [Date], ID end open TrxCursor fetch TrxCursor into @ID, @CID, @Amt while @@FETCH_STATUS = 0 begin if @CID = @BID set @CurBal = @CurBal + @Amt else begin set @CurBal = @Amt set @BID = @CID end update Contacts set Balance = @CurBal where ID = @CID update Ledger set Contact_Balance = @CurBal where ID = @ID fetch TrxCursor into @ID, @CID, @Amt end close TrxCursor deallocate TrxCursor set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'CalcOrdContBal' AND [Type] = 'P' ) drop procedure dbo.CalcOrdContBal GO create procedure dbo.CalcOrdContBal( @GUID varchar( 4000 ) ) as begin declare @CID int, @CUID varchar( 100 ) select @CID = isNull( Contact_ID, 0 ) from Orders where GUID = @GUID select @CUID = isNull( GUID, '' ) from Contacts where ID = @CID execute dbo.CalcContactBal @CUID end GO if exists ( select * from sysobjects where [Name] = 'Contacts_Insert' AND [Type] = 'TR' ) drop trigger Contacts_Insert GO create trigger Contacts_Insert on Contacts for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - Contacts_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'Contacts', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update Contacts set Date_Modified = I.Date_Modified from Inserted I join Contacts C on C.ID = I.ID set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Contacts_Delete' AND [Type] = 'TR' ) drop trigger Contacts_Delete GO create trigger Contacts_Delete on Contacts for Delete as begin if NOT exists( select ID from Deleted ) return set NOCOUNT ON -- print 'Debug - Contacts_Delete' delete Relationships from Deleted D join Relationships R on R.Contact_ID = D.ID -- delete the links that do not have a CASCADE DELETE set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Contacts_Update' AND [Type] = 'TR' ) drop trigger Contacts_Update GO create trigger Contacts_Update on Contacts for update as begin if NOT exists( select ID from Inserted ) OR Update( Photo1 ) OR Update( Photo2 ) OR Update( Photo3 ) OR Update( Photo4 ) OR Update( Photo5 ) OR Update( Photo6 ) OR Update( Photo7 ) OR Update( Photo8 ) OR Update( Photo9 ) OR Update( Photo1Thumb ) OR Update( Photo2Thumb ) OR Update( Photo3Thumb ) OR Update( Photo4Thumb ) OR Update( Photo5Thumb ) OR Update( Photo6Thumb ) OR Update( Photo7Thumb ) OR Update( Photo8Thumb ) OR Update( Photo9Thumb ) set NOCOUNT OFF else begin set NOCOUNT ON if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'Contacts', I.ID, I.GUID, Columns_Updated() from Inserted I end -- print 'Debug - Contacts_Update' if Update( Password2 ) AND exists( select ID from Inserted where Password1 <> Password2 AND Password1 is NOT Null AND Password2 is NOT Null ) begin raiserror( 'Warning - Password restored since it did not match', 11, 1 ) rollback end else begin -- Make sure only one company configuration record -- if Update( Company_Configuration ) AND exists( select ID from Inserted where Company_Configuration = 1 ) begin update Contacts set Company_Configuration = 0 where ID NOT IN ( select ID from Inserted where Company_Configuration = 1 ) end -- Fix all the Names -- -- update Contacts set First_Name = dbo.FirstName( C.[Name] ), Last_Name = dbo.LastName( C.[Name] ) -- always try to update the minor names -- from Inserted I join Contacts C on C.ID = I.ID -- where Update( [Name] ) OR C.Last_Name is Null -- update Contacts set [Name] = isNull( I.Last_Name, '' ) + isNull( ', ' + NullIF( I.First_Name, '' ), '' ) -- only update major Name with valid minor names -- from Inserted I join Contacts C on C.ID = I.ID -- where ( Update( First_Name ) AND isNull( C.First_Name, '' ) <> '' OR C.[Name] is Null ) -- AND NOT exists( select ID from Contacts C where C.[Name] = isNull( I.Last_Name, '' ) + isNull( ', ' + NullIF( I.First_Name, '' ), '' ) ) -- update Contacts set [Name] = isNull( I.Last_Name, '' ) + isNull( ', ' + NullIF( I.First_Name, '' ), '' ) -- only update major Name with valid minor names -- from Inserted I join Contacts C on C.ID = I.ID -- where ( Update( Last_Name ) AND isNull( C.Last_Name, '' ) <> '' OR C.[Name] is Null ) -- AND NOT exists( select ID from Contacts C where C.[Name] = isNull( I.Last_Name, '' ) + isNull( ', ' + NullIF( I.First_Name, '' ), '' ) ) -- update Contacts set [Name] = isNull( I.Last_Name, '' ) + isNull( ', ' + NullIF( I.First_Name, '' ), '' ) -- only update major Name with valid minor names -- from Inserted I where isNull( I.Last_Name, '' ) + isNull( I.First_Name, '' ) <> '' AND -- ( Update( First_Name ) OR Update( Last_Name ) OR I.[Name] is Null ) AND -- NOT exists( select ID from Contacts C where C.[Name] = isNull( I.Last_Name, '' ) + isNull( ', ' + NullIF( I.First_Name, '' ), '' ) ) -- Auto-Add any Main Contact and Relationships -- if Update( Main_Contact_Name ) OR Update( Main_Contact_ID ) begin -- create a Main Contact record if it does not exist insert Contacts ( [Name], Address, City, State_or_Province, Postal_Code, Country, Phone, eMail ) select I.Main_Contact_Name, I.Address, I.City, I.State_or_Province, I.Postal_Code, I.Country, I.Phone, I.eMail from Inserted I join Deleted D on D.ID = I.ID where I.Main_Contact_Name <> '' AND I.Main_Contact_Name <> I.[Name] AND I.[Type] <> 'ShipTo' AND NOT Exists ( select ID from Contacts C where C.ID = I.Main_Contact_ID ) AND NOT Exists ( select ID from Contacts C where C.[Name] = I.Main_Contact_Name ) -- maintain link to the Main Contact record update Contacts set Main_Contact_ID = ( select ID from Contacts C where C.[Name] = I.Main_Contact_Name ) from Inserted I join Contacts O on O.ID = I.ID -- create a relationship if it does not exists or existed under the old name insert Relationships ( Contact_ID, Contact_Name ) select I.ID, I.Main_Contact_Name from Inserted I join Deleted D on D.ID = I.ID where I.Main_Contact_Name <> '' AND I.Main_Contact_Name <> I.[Name] AND I.[Type] <> 'ShipTo' AND NOT Exists ( select ID from Relationships R where R.Contact_ID = I.ID AND R.Contact_Name = I.Main_Contact_Name ) AND NOT Exists ( select ID from Relationships R where R.Contact_ID = I.ID AND R.Contact_Name = D.Main_Contact_Name ) end -- Update G/L Accounts Info -- update Contacts set AR_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.AR_Account where C.AR_Account_ID is Null OR Update( AR_Account ) update Contacts set AR_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.AR_Account_ID where C.AR_Account is Null OR Update( AR_Account_ID ) update Contacts set AP_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.AP_Account where C.AP_Account_ID is Null OR Update( AP_Account ) update Contacts set AP_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.AP_Account_ID where C.AP_Account is Null OR Update( AP_Account_ID ) update Contacts set Sales_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.Sales_Account where C.Sales_Account_ID is Null OR Update( Sales_Account ) update Contacts set Sales_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.Sales_Account_ID where C.Sales_Account is Null OR Update( Sales_Account_ID ) update Contacts set Expense_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.Expense_Account where C.Expense_Account_ID is Null OR Update( Expense_Account ) update Contacts set Expense_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.Expense_Account_ID where C.Expense_Account is Null OR Update( Expense_Account_ID ) update Contacts set Asset_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.Asset_Account where C.Asset_Account_ID is Null OR Update( Asset_Account ) update Contacts set Asset_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.Asset_Account_ID where C.Asset_Account is Null OR Update( Asset_Account_ID ) update Contacts set COGS_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.COGS_Account where C.COGS_Account_ID is Null OR Update( COGS_Account ) update Contacts set COGS_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.COGS_Account_ID where C.COGS_Account is Null OR Update( COGS_Account_ID ) update Contacts set Payment_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.Payment_Account where C.Payment_Account_ID is Null OR Update( Payment_Account ) update Contacts set Payment_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.Payment_Account_ID where C.Payment_Account is Null OR Update( Payment_Account_ID ) update Contacts set Payment1_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.Payment1_Account where C.Payment1_Account_ID is Null OR Update( Payment1_Account ) update Contacts set Payment1_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.Payment1_Account_ID where C.Payment1_Account is Null OR Update( Payment1_Account_ID ) update Contacts set Payment2_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.Payment2_Account where C.Payment2_Account_ID is Null OR Update( Payment2_Account ) update Contacts set Payment2_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.Payment2_Account_ID where C.Payment2_Account is Null OR Update( Payment2_Account_ID ) update Contacts set Payment3_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.Payment3_Account where C.Payment3_Account_ID is Null OR Update( Payment3_Account ) update Contacts set Payment3_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.Payment3_Account_ID where C.Payment3_Account is Null OR Update( Payment3_Account_ID ) update Contacts set Payment4_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.Payment4_Account where C.Payment4_Account_ID is Null OR Update( Payment4_Account ) update Contacts set Payment4_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.Payment4_Account_ID where C.Payment4_Account is Null OR Update( Payment4_Account_ID ) update Contacts set Payment5_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.Payment5_Account where C.Payment5_Account_ID is Null OR Update( Payment5_Account ) update Contacts set Payment5_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.Payment5_Account_ID where C.Payment5_Account is Null OR Update( Payment5_Account_ID ) update Contacts set Payment6_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.Payment6_Account where C.Payment6_Account_ID is Null OR Update( Payment6_Account ) update Contacts set Payment6_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.Payment6_Account_ID where C.Payment6_Account is Null OR Update( Payment6_Account_ID ) update Contacts set Payment7_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.Payment7_Account where C.Payment7_Account_ID is Null OR Update( Payment7_Account ) update Contacts set Payment7_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.Payment7_Account_ID where C.Payment7_Account is Null OR Update( Payment7_Account_ID ) update Contacts set Payment8_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.Payment8_Account where C.Payment8_Account_ID is Null OR Update( Payment8_Account ) update Contacts set Payment8_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.Payment8_Account_ID where C.Payment8_Account is Null OR Update( Payment8_Account_ID ) update Contacts set Payment9_Account_ID = A.ID from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.[Name] = C.Payment9_Account where C.Payment9_Account_ID is Null OR Update( Payment9_Account ) update Contacts set Payment9_Account = A.[Name] from Contacts C join Inserted I on I.ID = C.ID join Accounts A on A.ID = C.Payment9_Account_ID where C.Payment9_Account is Null OR Update( Payment9_Account_ID ) -- Update Hours data -- if Update( Regular_Days_List ) begin update Contacts set Sunday_Hours_List = C.Regular_Day_Hours_List from Inserted I join Contacts C on C.ID = I.ID where C.Regular_Days_List like '%sunday%' update Contacts set Monday_Hours_List = C.Regular_Day_Hours_List from Inserted I join Contacts C on C.ID = I.ID where C.Regular_Days_List like '%monday%' update Contacts set Tuesday_Hours_List = C.Regular_Day_Hours_List from Inserted I join Contacts C on C.ID = I.ID where C.Regular_Days_List like '%tuesday%' update Contacts set Wednesday_Hours_List = C.Regular_Day_Hours_List from Inserted I join Contacts C on C.ID = I.ID where C.Regular_Days_List like '%wednesday%' update Contacts set Thursday_Hours_List = C.Regular_Day_Hours_List from Inserted I join Contacts C on C.ID = I.ID where C.Regular_Days_List like '%thursday%' update Contacts set Friday_Hours_List = C.Regular_Day_Hours_List from Inserted I join Contacts C on C.ID = I.ID where C.Regular_Days_List like '%friday%' update Contacts set Saturday_Hours_List = C.Regular_Day_Hours_List from Inserted I join Contacts C on C.ID = I.ID where C.Regular_Days_List like '%saturday%' end -- Update Weighted Average Amount per Month when set to zero -- if Update( Avg_Amount_per_Month ) begin update Contacts set Avg_Amount_per_Month = 0.2 * ( select isNull( Sum( isNull( Total, 0 ) ), 0 ) from Orders where Contact_ID = C.ID AND [Type] IN ( 'Sale', 'Service' ) AND Date_Locked between GetDate() - 30 AND GetDate() ) + 0.5 * ( select isNull( Sum( isNull( Total, 0 ) ), 0 ) / 3 from Orders where Contact_ID = C.ID AND [Type] IN ( 'Sale', 'Service' ) AND Date_Locked between GetDate() - 90 AND GetDate() ) + 0.3 * ( select isNull( Sum( isNull( Total, 0 ) ), 0 ) / 12 from Orders where Contact_ID = C.ID AND [Type] IN ( 'Sale', 'Service' ) AND Date_Locked between GetDate() - 365 AND GetDate() ) from Contacts C join Inserted I on I.ID = C.ID where I.Avg_Amount_per_Month = 0 end if @@NestLevel = 1 begin update O set [Name] = case when isNull( O.[Name], '' ) = '' OR O.[Name] = D.[Name] then C.[Name] else O.[Name] end, Main_Contact_Name = case when isNull( O.Main_Contact_Name, '' ) = '' OR O.Main_Contact_Name = D.Main_Contact_Name then C.Main_Contact_Name else O.Main_Contact_Name end, Address = case when isNull( O.Address, '' ) = '' OR O.Address = D.Address then C.Address else O.Address end, City = case when isNull( O.City, '' ) = '' OR O.City = D.City then C.City else O.City end, State_or_Province = case when isNull( O.State_or_Province, '' ) = '' OR O.State_or_Province = D.State_or_Province then C.State_or_Province else O.State_or_Province end, Employee = case when isNull( O.Employee, '' ) = '' OR O.Employee = D.Employee then C.Employee else O.Employee end, Price_Level = case when O.Price_Level = D.Price_Level then C.Price_Level else O.Price_Level end, Currency = case when isNull( O.Currency, '' ) = '' OR O.Currency = D.Currency then C.Currency else O.Currency end, Note = case when isNull( O.Note, '' ) = '' OR O.Note = D.Note then C.Note else O.Note end, Postal_Code = case when isNull( O.Postal_Code, '' ) = '' OR O.Postal_Code = D.Postal_Code then C.Postal_Code else O.Postal_Code end, Country = case when isNull( O.Country, '' ) = '' OR O.Country = D.Country then C.Country else O.Country end, Phone = case when isNull( O.Phone, '' ) = '' OR O.Phone = D.Phone then C.Phone else O.Phone end, Fax = case when isNull( O.Fax, '' ) = '' OR O.Fax = D.Fax then C.Fax else O.Fax end, eMail = case when isNull( O.eMail, '' ) = '' OR O.eMail = D.eMail then C.eMail else O.eMail end, Tax_Profile = case when isNull( O.Tax_Profile, '' ) = '' OR O.Tax_Profile = D.Tax_Profile then C.Tax_Profile else O.Tax_Profile end, Credit_Card = case when isNull( O.Credit_Card, '' ) = '' OR O.Credit_Card = D.Credit_Card then C.Credit_Card else O.Credit_Card end, Card_Number = case when isNull( O.Card_Number, '' ) = '' OR O.Card_Number = D.Card_Number then C.Card_Number else O.Card_Number end, Card_Code = case when isNull( O.Card_Code, '' ) = '' OR O.Card_Code = D.Card_Code then C.Card_Code else O.Card_Code end, Card_Expiry = case when isNull( O.Card_Expiry, '' ) = '' OR O.Card_Expiry = D.Card_Expiry then C.Card_Expiry else O.Card_Expiry end, Late_Notification_List = case when isNull( O.Late_Notification_List, '' ) = '' OR O.Late_Notification_List = D.Late_Notification_List then C.Late_Notification_List else O.Late_Notification_List end, Notify_when_Late_by_Days = case when O.Notify_when_Late_by_Days = D.Notify_when_Late_by_Days then C.Notify_when_Late_by_Days else O.Notify_when_Late_by_Days end, [Group] = case when isNull( O.[Group], '' ) = '' OR O.[Group] = D.[Group] then C.[Group] else O.[Group] end, Late_Reminder_every_Hours = case when O.Late_Reminder_every_Hours = D.Late_Reminder_every_Hours then C.Late_Reminder_every_Hours else O.Late_Reminder_every_Hours end, [Follow-Up_Notification_List] = case when isNull( O.[Follow-Up_Notification_List], '' ) = '' OR O.[Follow-Up_Notification_List] = D.[Follow-Up_Notification_List] then C.[Follow-Up_Notification_List] else O.[Follow-Up_Notification_List] end, [Follow-Up_every_Days] = case when O.[Follow-Up_every_Days] = D.[Follow-Up_every_Days] then C.[Follow-Up_every_Days] else O.[Follow-Up_every_Days] end, [Late_Follow-Up_Reminder_every_Hours] = case when O.[Late_Follow-Up_Reminder_every_Hours] = D.[Late_Follow-Up_Reminder_every_Hours] then C.[Late_Follow-Up_Reminder_every_Hours] else O.[Late_Follow-Up_Reminder_every_Hours] end, AR_Account_ID = case when O.AR_Account_ID = D.AR_Account_ID then C.AR_Account_ID else O.AR_Account_ID end, AR_Account = case when isNull( O.AR_Account, '' ) = '' OR O.AR_Account = D.AR_Account then C.AR_Account else O.AR_Account end, AP_Account_ID = case when O.AP_Account_ID = D.AP_Account_ID then C.AP_Account_ID else O.AP_Account_ID end, AP_Account = case when isNull( O.AP_Account, '' ) = '' OR O.AP_Account = D.AP_Account then C.AP_Account else O.AP_Account end, Sales_Account_ID = case when O.Sales_Account_ID = D.Sales_Account_ID then C.Sales_Account_ID else O.Sales_Account_ID end, Sales_Account = case when isNull( O.Sales_Account, '' ) = '' OR O.Sales_Account = D.Sales_Account then C.Sales_Account else O.Sales_Account end, Asset_Account_ID = case when O.Asset_Account_ID = D.Asset_Account_ID then C.Asset_Account_ID else O.Asset_Account_ID end, Asset_Account = case when isNull( O.Asset_Account, '' ) = '' OR O.Asset_Account = D.Asset_Account then C.Asset_Account else O.Asset_Account end, COGS_Account_ID = case when O.COGS_Account_ID = D.COGS_Account_ID then C.COGS_Account_ID else O.COGS_Account_ID end, COGS_Account = case when isNull( O.COGS_Account, '' ) = '' OR O.COGS_Account = D.COGS_Account then C.COGS_Account else O.COGS_Account end, Expense_Account_ID = case when O.Expense_Account_ID = D.Expense_Account_ID then C.Expense_Account_ID else O.Expense_Account_ID end, Expense_Account = case when isNull( O.Expense_Account, '' ) = '' OR O.Expense_Account = D.Expense_Account then C.Expense_Account else O.Expense_Account end from Inserted I join Contacts C on C.ID = I.ID join Deleted D on D.ID = I.ID join Orders O on O.Contact_ID = I.ID where O.Date_Locked is Null end ------------------------------------------------------------------------------------------------ -- include( 'VDM_Contacts_Update.sql' ) VDM will include any special code found here ------------------------------------------------------------------------------------------------ -- Update Contact File when empty and the first Participant is filled in update Contacts set Address = I.Address, City = I.City, State_or_Province = I.State_or_Province, Postal_Code = I.Postal_Code, Country = I.Country, eMail = I.eMail from Inserted I join OrderItems L on L.ID = I.OrderItem_ID join Orders O on O.ID = L.Order_ID join Contacts C on C.ID = O.Contact_ID where isNull( O.eMail, '' ) = '' AND isNull( I.eMail, '' ) <> '' AND isNull( I.First_Name, '' ) <> '' AND isNull( I.Last_Name, '' ) <> '' -- Update Order data as well update Orders set [Name] = rTrim( I.First_Name ) + ' ' + rTrim( I.Last_Name ) from Inserted I join OrderItems L on L.ID = I.OrderItem_ID join Orders O on O.ID = L.Order_ID where isNull( O.eMail, '' ) = '' AND isNull( I.eMail, '' ) <> '' AND isNull( I.First_Name, '' ) <> '' AND isNull( I.Last_Name, '' ) <> '' -- Add any required Notifications -- if exists( select ID from Inserted where Change_Notification_List is NOT Null ) begin insert Notifications ( Table_Name, Table_ID, Notification_List, Subject, Body ) select 'Contacts', C.ID, C.Change_Notification_List, 'Alert on ' + C.[Name], 'select ' + dbo.ModColList( 'Contacts', Columns_Updated() ) + ' from Contacts where ID = ' + Cast( I.ID as varchar( 10 ) ) from Inserted I join Contacts C on C.ID = I.ID where C.Change_Notification_List is NOT Null AND C.Notification_Condition is Null if exists( select ID from Inserted where Notification_Condition is NOT Null ) begin declare @Cmd varchar( 4000 ), @CurID varchar( 10 ), @Name varchar( 50 ), @Notify varchar( 500 ), @Condition varchar( 500 ) declare CurRec cursor local for select ID, [Name], Change_Notification_List, Notification_Condition from Inserted where Change_Notification_List is NOT Null AND Notification_Condition is NOT Null open CurRec fetch CurRec into @CurID, @Name, @Notify, @Condition while @@FETCH_STATUS = 0 begin select @Cmd = 'if exists( select ID from Contacts where ID = ' + @CurID + ' AND ' + @Condition + ' ) ' + 'insert Notifications ( Table_Name, Table_ID, Notification_List, Subject, Body ) ' + 'values( ''Contacts'', ' + @CurID + ', ''' + @Notify + ''', ''' + @Condition + ' on ' + rTrim( @Name ) + ''', ' + '''select ' + Replace( dbo.ModColList( 'Contacts', Columns_Updated() ), '''', '''''' ) + ' from Contacts where ID = ' + @CurID + ''' )' exec( @Cmd ) fetch CurRec into @CurID, @Name, @Notify, @Condition end close CurRec deallocate CurRec end end -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- update Contacts set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Contacts C join Inserted I on I.ID = C.ID end set NOCOUNT OFF end end GO -------------- -- WebSites -- -------------- if exists ( select * from sysobjects where [Name] = 'HTML_Template' AND [Type] = 'FN' ) drop function dbo.HTML_Template GO if exists ( select * from sysobjects where [Name] = 'WebSites_Insert' AND [Type] = 'TR' ) drop trigger WebSites_Insert GO create trigger WebSites_Insert on WebSites for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - WebSites_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'WebSites', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update WebSites set Date_Modified = I.Date_Modified from Inserted I join WebSites W on W.ID = I.ID ------------------------------- -- Add all the default WebPages ------------------------------- insert WebPages ( WebSite_ID, Core_Page, Title, Destination_URL ) select I.ID, 1, 'Products', 'Products.htm' from Inserted I insert WebPages ( WebSite_ID, Core_Page, Title, Destination_URL ) select I.ID, 1, 'Services', 'Services.htm' from Inserted I insert WebPages ( WebSite_ID, Core_Page, Title, Destination_URL ) select I.ID, 1, 'Support', 'Support.htm' from Inserted I insert WebPages ( WebSite_ID, Core_Page, Title, Destination_URL ) select I.ID, 1, 'Our Location', 'Location.htm' from Inserted I insert WebPages ( WebSite_ID, Core_Page, Title, Destination_URL ) select I.ID, 1, 'Contact Us', 'mailto:info@ediaccess.com' from Inserted I insert WebPages ( WebSite_ID, Core_Page, Title, Destination_URL ) select I.ID, 1, 'About Us', 'About.htm' from Inserted I set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'WebSites_Update' AND [Type] = 'TR' ) drop trigger WebSites_Update GO create trigger WebSites_Update on WebSites for update as begin if NOT exists( select ID from Inserted ) OR Update( Photo1 ) OR Update( Photo2 ) OR Update( Photo3 ) OR Update( Photo4 ) OR Update( Photo5 ) OR Update( Photo6 ) OR Update( Photo7 ) OR Update( Photo8 ) OR Update( Photo9 ) OR Update( Photo1Thumb ) OR Update( Photo2Thumb ) OR Update( Photo3Thumb ) OR Update( Photo4Thumb ) OR Update( Photo5Thumb ) OR Update( Photo6Thumb ) OR Update( Photo7Thumb ) OR Update( Photo8Thumb ) OR Update( Photo9Thumb ) set NOCOUNT OFF else begin set NOCOUNT ON -- print 'Debug - WebSites_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'WebSites', I.ID, I.GUID, Columns_Updated() from Inserted I end update WebSites set Template_ID = T.ID from Inserted I join WebSites W on W.ID = I.ID join WebPages T on T.Title = I.Template_Name where W.Template_ID is Null OR Update( Template_Name ) OR I.Date_Modified is Null -- Null indicates a call from the Insert trigger update WebSites set Default_Template_ID = T.ID from Inserted I join WebSites W on W.ID = I.ID join WebPages T on T.Title = I.Default_Template_Name where W.Default_Template_ID is Null OR Update( Default_Template_Name ) OR I.Date_Modified is Null -- Null indicates a call from the Insert trigger update WebSites set Destination_URL = dbo.TrimNonAscii( isNull( W.Destination_URL, 'index.htm' ) ), Local_Path = 'HTML\' + dbo.SubstFileName( I.Title ) + '\' from Inserted I join WebSites W on W.ID = I.ID update WebSites set FTP_URL = 'ediaccess.com', FTP_Username = dbo.SubstFileName( W.Title ), FTP_Password = dbo.SubstFileName( W.Title ) + '.vdm' from Inserted I join WebSites W on W.ID = I.ID where W.FTP_URL is Null update WebSites set Photo2 = cast( '
Under Construction' + Char( 13 ) + Char( 10 ) as varbinary( max ) ), Photo2Name = cast( W.Local_Path + Replace( isNull( W.Destination_Path, '' ), '/', '\' ) + SubString( dbo.InternetName( W.Destination_URL ) + '.', 1, CharIndex( '.', dbo.InternetName( W.Destination_URL ) + '.' ) - 1 ) + '_content.htm' as varbinary( max ) ) from Inserted I join WebSites W on W.ID = I.ID where isNull( cast( W.Photo2 as varchar( max ) ), '' ) = '' ------------------------------------------------------------------------------------------------------------------ -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- ------------------------------------------------------------------------------------------------------------------ update WebSites set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Inserted I join WebSites S on S.ID = I.ID set NOCOUNT OFF end end GO -------------- -- WebPages -- -------------- if exists ( select * from sysobjects where [Name] = 'WebPages_Insert' AND [Type] = 'TR' ) drop trigger WebPages_Insert GO create trigger WebPages_Insert on WebPages for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - WebPages_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'WebPages', I.ID, I.GUID, Columns_Updated() from Inserted I end ---------------------- --fix grandchildren -- --------------------- update WebPages set WebSite_ID = ( select W.WebSite_ID from WebPages W where W.ID = P.WebPage_ID ) from Inserted I join WebPages P on P.ID = I.ID where P.WebSite_ID is Null ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update WebPages set Date_Modified = I.Date_Modified from Inserted I join WebPages W on W.ID = I.ID set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'WebPages_Delete' AND [Type] = 'TR' ) drop trigger WebPages_Delete GO if exists ( select * from sysobjects where [Name] = 'WebPages_Update' AND [Type] = 'TR' ) drop trigger WebPages_Update GO create trigger WebPages_Update on WebPages for update as begin update WebPages set Photo2 = P.Photo1 from Inserted I join WebPages P on P.ID = I.ID where Update( Photo1 ) AND P.Photo2 is Null AND P.Use_As_Template = 1 update WebPages set Photo1 = P.Photo2 from Inserted I join WebPages P on P.ID = I.ID where Update( Photo2 ) AND P.Photo1 is Null AND P.Use_As_Template = 1 if NOT exists( select ID from Inserted ) OR Update( Photo1 ) OR Update( Photo2 ) OR Update( Photo3 ) OR Update( Photo4 ) OR Update( Photo5 ) OR Update( Photo6 ) OR Update( Photo7 ) OR Update( Photo8 ) OR Update( Photo9 ) OR Update( Photo1Thumb ) OR Update( Photo2Thumb ) OR Update( Photo3Thumb ) OR Update( Photo4Thumb ) OR Update( Photo5Thumb ) OR Update( Photo6Thumb ) OR Update( Photo7Thumb ) OR Update( Photo8Thumb ) OR Update( Photo9Thumb ) set NOCOUNT OFF else begin set NOCOUNT ON -- print 'Debug - WebPages_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'WebPages', I.ID, I.GUID, Columns_Updated() from Inserted I end update WebPages set WebPage_ID = ( select top 1 P.ID from WebPages P where P.Destination_URL = W.Parent_URL order by P.ID desc ) from Inserted I join WebPages W on W.ID = I.ID where W.WebPage_ID is Null update WebPages set Template_ID = ( select top 1 ID from WebPages where Title = I.Template_Name AND WebSite_ID = I.WebSite_ID order by ID desc ) from Inserted I join WebPages W on W.ID = I.ID where Update( Template_Name ) OR I.Date_Modified is Null -- Null indicates a call from the Insert trigger ------------------ -- set defaults -- ------------------ update WebPages set [Sequence] = ( select Max( isNull( [Sequence], 0 ) ) + 1 from WebPages where WebSite_ID = I.WebSite_ID OR WebPage_ID = I.WebPage_ID ) from Inserted I join WebPages P on P.ID = I.ID where P.Sequence is Null update WebPages set Destination_URL = dbo.ValidURL( I.Title ) + '.htm' from Inserted I join WebPages P on P.ID = I.ID where P.Destination_URL is Null AND P.Use_as_Template = 0 update WebPages set Destination_URL = dbo.TrimNonAscii( P.Destination_URL ) from Inserted I join WebPages P on P.ID = I.ID update WebPages set Destination_Path = dbo.InternetPath( P.Destination_URL ) from Inserted I join WebPages P on P.ID = I.ID update WebPages set Local_Path = W.Local_Path from Inserted I join WebPages P on P.ID = I.ID join WebSites W on W.ID = P.WebSite_ID update WebPages set Photo2 = cast( 'Under Construction' + Char( 13 ) + Char( 10 ) as varbinary( max ) ), Photo2Name = cast( P.Local_Path + Replace( P.Destination_Path, '/', '\' ) + SubString( dbo.InternetName( P.Destination_URL ) + '.', 1, CharIndex( '.', dbo.InternetName( P.Destination_URL ) + '.' ) - 1 ) + '_content.htm' as varbinary( max ) ) from Inserted I join WebPages P on P.ID = I.ID where isNull( cast( P.Photo2 as varchar( max ) ), '' ) = '' AND P.Use_as_Template = 0 update WebPages set Photo2Name = P.Photo1Name from Inserted I join WebPages P on P.ID = I.ID where Update( Photo1Name ) AND P.Photo2Name is Null AND P.Use_As_Template = 1 update WebPages set Photo1Name = P.Photo2Name from Inserted I join WebPages P on P.ID = I.ID where Update( Photo2Name ) AND P.Photo1Name is Null AND P.Use_As_Template = 1 update WebSites set Template_Name = I.Title, Template_ID = I.ID from Inserted I join WebSites W on W.ID = I.WebSite_ID where Update( Title ) AND W.Template_Name is Null AND I.Use_As_Template = 1 update WebSites set Default_Template_Name = I.Title, Default_Template_ID = I.ID from Inserted I join WebSites W on W.ID = I.WebSite_ID where Update( Title ) AND W.Default_Template_Name is Null AND I.Use_As_Template = 1 ------------------------------------------------------------------ -- Force Templates and Content in their proper folder structure -- ------------------------------------------------------------------ update WebPages set Photo1Name = P.Local_Path + Replace( P.Destination_Path, '/', '\' ) + Replace( dbo.InternetName( P.Destination_URL ), '_Content.htm', '.htm' ) from Inserted I join WebPages P on P.ID = I.ID where P.Use_as_Template = 0 update WebPages set Photo2Name = P.Local_Path + Replace( P.Destination_Path, '/', '\' ) + Replace( dbo.InternetName( P.Destination_URL ), '.htm', '_Content.htm' ) from Inserted I join WebPages P on P.ID = I.ID where P.Use_as_Template = 0 update WebPages set Photo1Name = 'HTML\Templates\' + dbo.SubstFileName( S.Title ) + '\' + dbo.FileName( P.Photo1Name ) from Inserted I join WebPages P on P.ID = I.ID join WebSites S on S.ID = I.WebSite_ID where P.Use_as_Template = 1 AND P.Photo1Name NOT like 'HTML\Templates\%' ------------------------------------------------------------------------------------------------------------------ -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- ------------------------------------------------------------------------------------------------------------------ update WebPages set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Inserted I join WebPages P on P.ID = I.ID set NOCOUNT OFF end end GO ------------- -- Catalog -- ------------- if exists ( select * from sysobjects where [Name] = 'Catalog_Update' AND [Type] = 'TR' ) drop trigger Catalog_Update GO create trigger Catalog_Update on Catalog for update as begin if NOT exists( select ID from Inserted ) OR Update( Photo1 ) OR Update( Photo2 ) OR Update( Photo3 ) OR Update( Photo4 ) OR Update( Photo5 ) OR Update( Photo6 ) OR Update( Photo7 ) OR Update( Photo8 ) OR Update( Photo9 ) OR Update( Photo1Thumb ) OR Update( Photo2Thumb ) OR Update( Photo3Thumb ) OR Update( Photo4Thumb ) OR Update( Photo5Thumb ) OR Update( Photo6Thumb ) OR Update( Photo7Thumb ) OR Update( Photo8Thumb ) OR Update( Photo9Thumb ) set NOCOUNT OFF else begin set NOCOUNT ON -- print 'Debug - Catalog_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'Catalog', I.ID, I.GUID, Columns_Updated() from Inserted I end --declare @ID int, @Name char(50), @OldName char(50), @Cat char(50) -- select @ID = ( select ID from Inserted ) -- select @Name = ( select isNull( [Name], '' ) from Inserted ) -- select @OldName = ( select [Name] from Deleted ) -- select @Cat = ( select [Section_Title] from Inserted ) -- if rTrim( @Name ) = '' select @Name = ( select [Code] from Inserted ) -------------------------------------------- -- update from template if it was changed -- -------------------------------------------- update Catalog set Colours = T.Colours, Colours2 = T.Colours2, Colours3 = T.Colours3, Fabric_Name = T.Fabric_Name, Fabric_Name2 = T.Fabric_Name2, Fabric_Name3 = T.Fabric_Name3, Fabric_Care = T.Fabric_Care, Fabric_Care2 = T.Fabric_Care2, Fabric_Care3 = T.Fabric_Care3, Fabric_Composition = T.Fabric_Composition, Fabric_Composition2 = T.Fabric_Composition2, Fabric_Composition3 = T.Fabric_Composition3 from Catalog join Inserted I on I.ID = Catalog.ID join Catalog T on T.[Name] = Catalog.Template_Name where Update( Template_Name ) update Catalog set Photo1 = T.Photo1, Photo1Thumb = T.Photo1Thumb, Photo1Name = T.Photo1Name from Catalog join Inserted I on I.ID = Catalog.ID join Catalog T on T.[Name] = Catalog.Template_Name where Update( Template_Name ) AND T.Photo1 is NOT NULL update Catalog set Photo2 = T.Photo2, Photo2Thumb = T.Photo2Thumb, Photo2Name = T.Photo2Name from Catalog join Deleted D on D.ID = Catalog.ID join Catalog T on T.[Name] = Catalog.Template_Name where Update( Template_Name ) AND T.Photo2 is NOT NULL update Catalog set Photo3 = T.Photo3, Photo3Thumb = T.Photo3Thumb, Photo3Name = T.Photo3Name from Catalog join Inserted I on I.ID = Catalog.ID join Catalog T on T.[Name] = Catalog.Template_Name where Update( Template_Name ) AND T.Photo3 is NOT NULL update Catalog set Photo4 = T.Photo1, Photo4Thumb = T.Photo4Thumb, Photo4Name = T.Photo4Name from Catalog join Inserted I on I.ID = Catalog.ID join Catalog T on T.[Name] = Catalog.Template_Name where Update( Template_Name ) AND T.Photo4 is NOT NULL update Catalog set Photo5 = T.Photo1, Photo5Thumb = T.Photo5Thumb, Photo5Name = T.Photo5Name from Catalog join Inserted I on I.ID = Catalog.ID join Catalog T on T.[Name] = Catalog.Template_Name where Update( Template_Name ) AND T.Photo5 is NOT NULL update Catalog set Photo6 = T.Photo1, Photo6Thumb = T.Photo6Thumb, Photo6Name = T.Photo6Name from Catalog join Inserted I on I.ID = Catalog.ID join Catalog T on T.[Name] = Catalog.Template_Name where Update( Template_Name ) AND T.Photo6 is NOT NULL update Catalog set Photo7 = T.Photo1, Photo7Thumb = T.Photo7Thumb, Photo7Name = T.Photo7Name from Catalog join Inserted I on I.ID = Catalog.ID join Catalog T on T.[Name] = Catalog.Template_Name where Update( Template_Name ) AND T.Photo7 is NOT NULL update Catalog set Photo8 = T.Photo1, Photo8Thumb = T.Photo8Thumb, Photo8Name = T.Photo8Name from Catalog join Inserted I on I.ID = Catalog.ID join Catalog T on T.[Name] = Catalog.Template_Name where Update( Template_Name ) AND T.Photo8 is NOT NULL update Catalog set Photo9 = T.Photo1, Photo9Thumb = T.Photo9Thumb, Photo9Name = T.Photo9Name from Catalog join Inserted I on I.ID = Catalog.ID join Catalog T on T.[Name] = Catalog.Template_Name where Update( Template_Name ) AND T.Photo9 is NOT NULL if @@NESTLEVEL = 1 begin -- Synchronize other Tables --------------------------------------- -- update any found linked resources -- --------------------------------------- update Resources set Catalog_ID = I.ID, [Name] = I.[Name], [Code] = I.[Code], [Group] = I.[Group], Department = I.Department, Division = I.Division, Price = I.Price, Price2 = I.Price2, Price3 = I.Price3, Std_Cost = I.Std_Cost, Note = C.Note, Photo1Name = C.Photo1Name, Photo2Name = C.Photo2Name, Photo3Name = C.Photo3Name, Photo1 = C.Photo1, Photo1Thumb = C.Photo1Thumb, Photo2 = C.Photo2, Photo2Thumb = C.Photo2Thumb, Photo3 = C.Photo3, Photo3Thumb = C.Photo3Thumb from Inserted I join Catalog C on C.ID = I.ID join Resources R on R.[Name] = I.[Name] where I.Manage_this_Resource = 1 -------------------------------------- -- add any missing linked resources -- -------------------------------------- insert Resources ( Catalog_ID, [Name], [Code], [Group], Department, Division, Price, Price2, Price3, Std_Cost, Note, Photo1Name, Photo2Name, Photo3Name, Photo1, Photo1Thumb, Photo2, Photo2Thumb, Photo3, Photo3Thumb ) select I.ID, I.[Name], I.[Code], I.[Group], I.Department, I.Division, I.Price, I.Price2, I.Price3, I.Std_Cost, C.Note, C.Photo1Name, C.Photo2Name, C.Photo3Name, C.Photo1, C.Photo1Thumb, C.Photo2, C.Photo2Thumb, C.Photo3, C.Photo3Thumb from Inserted I join Catalog C on C.ID = I.ID left join Resources R on R.[Name] = I.[Name] where I.Manage_this_Resource = 1 AND isNull( R.[Name], '' ) = '' -- if ( select Update_eCommerce from Inserted ) = 1 begin -- if NOT exists ( select Category_ID from Category where Category_Name = @Cat ) begin -- insert Category (Category_ID,Category_Name,Category_SplashDisp,Category_ImgSM,Category_CatCount,Category_CatDisp, -- Category_SMCount,Category_SMDisp,Category_Active,Category_CurrPct,Category_Value) -- select @ID,Section_Title,'N','IMG.JPG','3','ste_cat_default','1','ste_prodsm_default','N','PCT','0' from Inserted -- end -- if NOT exists ( select [Product_ID] from Product where Product_ID = @ID ) begin -- insert Product (Product_ID,Product_Name,Product_Number,Product_PriceStatus,Product_RegPrice,Product_SalePrice,Product_RecurPrice, -- Product_RecurStatus,Product_Keywords,Product_UseCatDisc,Product_TaxStateProv,Product_TaxCountry,Product_UseInv, -- Product_Inv,Product_UseMax,Product_Max,Product_ImgXLGUse,Product_ImgXLG,Product_ImgLG,Product_ImgSM, -- Product_LGDisp,Product_SplashDisp,Product_New,Product_Special,Product_BestSell,Product_DescShort,Product_DescLong, -- Product_DelMethod,Product_ShipLocal,Product_ShipInt,Product_ShipWeight,Product_ShipLength, -- Product_ShipWidth,Product_ShipHeight,Product_ShipNumBox,Product_XOpt,Product_XCat) -- select @ID,@Name,[Code],'R',Convert(varchar(20),Price),'0','0','N',@Name,'Y','Y','Y','N','1000','N','1000','N', -- 'IMG.JPG','IMG.JPG','IMG.JPG','ste_prdlg_default','N','N','N','N',@Name,@Name,'N','UPSWEPAPI','UPSWEBAPI', -- '0','0','0','0','0','',Section_Title from Inserted -- end -- else begin -- update Product set Product_Name=@Name,Product_Number=I.[Code],Product_RegPrice=Convert(varchar(20),I.Price), -- Product_DescShort=@Name,Product_XCat=I.Section_Title -- from Inserted as I where Product_ID=@ID -- end -- end end ------------------------------------------------------------------------------------------------------------------ -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- ------------------------------------------------------------------------------------------------------------------ update Catalog set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Inserted I join Catalog C on C.ID = I.ID set NOCOUNT OFF end end GO --------------- -- Resources -- --------------- -- alter table Resources add Sequence float default( 0.0 ) -- with values UPDATE PERMISSION DENIED BUG do in Triggers as an update update Resources set Sequence = 0.0 where Sequence is Null -- with values UPDATE PERMISSION DENIED BU GO -- execute CalcBalance '254C7C7F-7152-45A7-9632-101EC2FE2499','9/30/2006' -- select GUID from Resources where ID = 7 -- select Date_Locked, ID, Resource_ID, [Type], Quantity, Balance from OrderItems where Date_Locked is NOT Null AND Resource_ID = 7 order by Resource_ID, Date_Locked, ID if exists ( select * from sysobjects where [Name] = 'CalcBalance' AND [Type] = 'P' ) drop procedure dbo.CalcBalance GO create procedure dbo.CalcBalance( @@GUID varchar( 4000 ), @@StartDate varchar( 100 ) ) as begin set NOCOUNT ON -- print 'Debug - CalcBalance ' + @@GUID + ' ' + @@StartDate if CharIndex( ',', @@GUID ) <> 0 begin declare @@N int, @@Count int, @@S varchar( 100 ) set @@Count = dbo.Tokens( ',', @@GUID ) set @@N = @@Count while @@N > 0 begin set @@S = dbo.Token( ',', @@GUID, @@N ) exec dbo.CalcBalance @@S, @@StartDate set @@N = @@N - 1 end end else begin begin transaction -- alter table OrderItems disable trigger all declare @@ID int, @@RID int, @@BID int, @@Type varchar( 100 ), @@Date datetime, @@Qty decimal( 18,4 ), @@Bal decimal( 18,4 ), @@CurBal decimal( 18,4 ), @@Conv decimal( 18,4 ) if @@GUID = '' select @@RID = 0 else select @@RID = isNull( ID, 0 ) from Resources where GUID = @@GUID select @@CurBal = 0.0 select @@BID = 0 if @@RID = 0 -- No GUID means do all Resources LONG Process declare TrxCursor cursor local for select ID, Resource_ID, [Type], Date_Locked, Quantity, Balance, Unit_Conversion from OrderItems where Date_Locked is NOT Null AND Made_to_Order = 0 order by Resource_ID, Date_Locked, ID else if isNull( @@StartDate, '' ) = '' declare TrxCursor cursor local for select ID, Resource_ID, [Type], Date_Locked, Quantity, Balance, Unit_Conversion from OrderItems where Date_Locked is NOT Null AND Made_to_Order = 0 AND Resource_ID = @@RID order by Resource_ID, Date_Locked, ID else begin declare TrxCursor cursor local for select ID, Resource_ID, [Type], Date_Locked, Quantity, Balance, Unit_Conversion from OrderItems where Date_Locked >= @@StartDate AND Made_to_Order = 0 AND Resource_ID = @@RID order by Resource_ID, Date_Locked, ID end open TrxCursor fetch TrxCursor into @@ID, @@RID, @@Type, @@Date, @@Qty, @@Bal, @@Conv while @@FETCH_STATUS = 0 begin if @@Type IN ( 'Sale', 'Manufacturing', 'Service' ) begin if @@RID = @@BID select @@CurBal = @@CurBal - @@Qty * @@Conv else if @@StartDate <> '' begin select @@CurBal = + @@Bal select @@BID = @@RID end else begin select @@CurBal = - @@Qty * @@Conv select @@BID = @@RID end end else if @@Type IN ( 'Purchase', 'Adjustment', 'Production' ) begin if @@RID = @@BID select @@CurBal = @@CurBal + @@Qty * @@Conv else if @@StartDate <> '' begin select @@CurBal = + @@Bal select @@BID = @@RID end else begin select @@CurBal = + @@Qty * @@Conv select @@BID = @@RID end end update OrderItems set Balance = @@CurBal where ID = @@ID update Resources set Units_on_Hand = @@CurBal * Track_Qty_on_Hand where ID = @@RID fetch TrxCursor into @@ID, @@RID, @@Type, @@Date, @@Qty, @@Bal, @@Conv end update Resources set Units_on_Hand = @@CurBal * Track_Qty_on_Hand, Units_Required = - 1, Units_Ordered = - 1 where ID = @@RID -- update even when no trx found and do the Required and Ordered sum as well close TrxCursor deallocate TrxCursor -- alter table OrderItems enable trigger all commit transaction end set NOCOUNT OFF end GO -- alter table orders disable trigger all -- alter table orderItems disable trigger all -- delete orderItems where type = 'Adjustment' -- delete orders where type = 'Adjustment' -- alter table orderItems enable trigger all -- alter table orders enable trigger all -- execute CountResources '[Name] like ''%cheese-p%''' -- update Resources set Snapshot_Quantity = 0, Quantity_Counted = 0, Last_Count_ID = Null, -- Date_Locked_for_Count = Null, Date_Released_from_Count = Null, Date_Quantity_Adjusted = Null where Track_Qty_On_Hand = 1 if exists ( select * from sysobjects where [Name] = 'CountResources' AND [Type] = 'P' ) drop procedure dbo.CountResources GO create procedure dbo.CountResources( @Where varchar( 4000 ) ) as begin set NOCOUNT ON declare @Cmd varchar( 4000 ), @Date varchar( 100 ), @ID varchar( 100 ) select @Date = GetDate() insert Orders ( Date_Locked, Type, [Name], Auto_Generated ) values( @Date, 'Adjustment', 'Counted on ' + @Date, 1 ) select @ID = Scope_Identity() if Len( @Where ) <> 0 select @Where = ' AND ' + @Where select @Cmd = 'update Resources set Last_Count_ID = ' + @ID + ' where Track_Qty_On_Hand = 1' + @Where exec( @Cmd ) -- mark the records declare @GUID varchar( 100 ), @StartDate varchar( 100 ) declare CountCursor cursor local for select cast( GUID as varchar( 100 ) ), isNull( cast( Date_Locked_for_Count as varchar( 100 ) ), '' ) from Resources where Last_Count_ID = @ID open CountCursor fetch CountCursor into @GUID, @StartDate while @@FETCH_STATUS = 0 begin exec CalcBalance @GUID, @StartDate fetch CountCursor into @GUID, @StartDate end close CountCursor deallocate CountCursor select @Cmd = 'update Resources set Snapshot_Quantity = Units_on_Hand, Quantity_Counted = Units_on_Hand, ' + 'Date_Locked_for_Count = ''' + @Date + ''', Date_Released_from_Count = Null, Date_Quantity_Adjusted = Null ' + 'where Track_Qty_On_Hand = 1 AND Last_Count_ID = ' + @ID exec( @Cmd ) set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'ReleaseResources' AND [Type] = 'P' ) drop procedure dbo.ReleaseResources GO create procedure dbo.ReleaseResources( @Where varchar( 4000 ) ) as begin set NOCOUNT ON declare @Cmd varchar( 4000 ) if Len( @Where ) <> 0 select @Where = ' AND ' + @Where select @Cmd = 'update Resources set Date_Released_from_Count = GetDate() ' + 'where Date_Locked_for_Count is NOT Null AND Date_Released_from_Count is Null' + @Where exec( @Cmd ) set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'AdjustResources' AND [Type] = 'P' ) drop procedure dbo.AdjustResources GO create procedure dbo.AdjustResources( @Where varchar( 4000 ) ) as begin set NOCOUNT ON declare @Cmd varchar( 4000 ) if Len( @Where ) <> 0 select @Where = ' AND ' + @Where select @Cmd = 'update Resources set Date_Quantity_Adjusted = GetDate() ' + 'where Date_Released_from_Count is NOT Null AND Date_Quantity_Adjusted is Null' + @Where exec( @Cmd ) set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Resources_Insert' AND [Type] = 'TR' ) drop trigger Resources_Insert GO create trigger Resources_Insert on Resources for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - Resources_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'Resources', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update Resources set Date_Modified = I.Date_Modified from Inserted I join Resources R on R.ID = I.ID set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Resources_Delete' AND [Type] = 'TR' ) drop trigger Resources_Delete GO create trigger Resources_Delete on Resources for Delete as begin if NOT exists( select ID from Deleted ) return if Update( Photo1 ) OR Update( Photo2 ) OR Update( Photo3 ) OR Update( Photo4 ) OR Update( Photo5 ) OR Update( Photo6 ) OR Update( Photo7 ) OR Update( Photo8 ) OR Update( Photo9 ) return if Update( Photo1Thumb ) OR Update( Photo2Thumb ) OR Update( Photo3Thumb ) OR Update( Photo4Thumb ) OR Update( Photo5Thumb ) OR Update( Photo6Thumb ) OR Update( Photo7Thumb ) OR Update( Photo8Thumb ) OR Update( Photo9Thumb ) return set NOCOUNT ON -- print 'Debug - Resources_Delete' delete Relationships from Deleted D where Resource_Name = D.[Name] -- delete the links that do not have a CASCADE DELETE set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Resources_Update' AND [Type] = 'TR' ) drop trigger Resources_Update GO create trigger Resources_Update on Resources for update as begin if NOT exists( select ID from Inserted ) OR Update( Photo1 ) OR Update( Photo2 ) OR Update( Photo3 ) OR Update( Photo4 ) OR Update( Photo5 ) OR Update( Photo6 ) OR Update( Photo7 ) OR Update( Photo8 ) OR Update( Photo9 ) OR Update( Photo1Thumb ) OR Update( Photo2Thumb ) OR Update( Photo3Thumb ) OR Update( Photo4Thumb ) OR Update( Photo5Thumb ) OR Update( Photo6Thumb ) OR Update( Photo7Thumb ) OR Update( Photo8Thumb ) OR Update( Photo9Thumb ) set NOCOUNT OFF else begin set NOCOUNT ON -- print 'Debug - Resource_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'Resources', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------ -- update defaults ------------------ -- update Resources set UPC = I.ID from Resources R join Inserted I on I.ID = R.ID where I.UPC is Null update Resources set Code = I.ID from Resources R join Inserted I on I.ID = R.ID where I.Code is Null update Resources set Sequence = I.ID from Resources R join Inserted I on I.ID = R.ID where I.Sequence is Null update Resources set Can_be_Sold = 0, Can_be_Purchased = 0, Track_Qty_on_Hand = 0 from Resources R join Inserted I on I.ID = R.ID where R.[Type] = 'Template' ---------------------------- -- custom papex code ---------------------------- update Resources set Price = 1.05 * 1.15 * R.Price2, Price1 = 1.05 * R.Price2 from Inserted I join Resources R on R.ID = I.ID join Deleted D on D.ID = I.ID join Contacts C on C.Company_Configuration = 1 where I.Price2 <> D.Price2 AND C.[Name] like '%Papiers%' ---------------------------- -- update counters when zero ---------------------------- update Resources set Avg_Cost = I.Std_Cost from Resources R join Inserted I on I.ID = R.ID where R.Avg_Cost = 0 OR Update( Std_Cost ) update Resources set Units_Required = isNull( ( select Sum( isNull( Quantity, 0 ) ) from OrderItems L where L.Resource_ID = I.ID AND L.Made_to_Order = 0 AND L.[Type] IN ( 'Sale', 'Manufacturing', 'Service' ) AND L.Date_Locked is Null ), 0 ) from Resources R join Inserted I on I.ID = R.ID where R.Units_Required < 0 update Resources set Units_Ordered = isNull( ( select Sum( isNull( Quantity, 0 ) ) from OrderItems L where L.Resource_ID = I.ID AND L.[Type] IN ( 'Purchase', 'Adjustment', 'Production' ) AND L.Date_Locked is Null ), 0 ) from Resources R join Inserted I on I.ID = R.ID where R.Units_Ordered < 0 update Resources set Mfg_Cost = ( select Sum( isNull( Total_Cost, 0 ) ) from Components C where C.Resource_ID = I.ID ) from Resources R join Inserted I on I.ID = R.ID where R.Mfg_Cost = 0 ------------------------- -- update inventory count ------------------------- update Resources set Quantity_Counted = D.Quantity_Counted -- no qty change when already Adjusted from Resources R join Deleted D on D.ID = R.ID where Update( Quantity_Counted ) AND R.Date_Quantity_Adjusted is NOT Null update Resources set Date_Quantity_Adjusted = D.Date_Quantity_Adjusted -- do not adjust when item is not released except CountResources() from Resources R join Deleted D on D.ID = R.ID where Update( Date_Quantity_Adjusted ) AND R.Date_Released_from_Count is Null AND NOT Update( Date_Released_from_Count ) -- Fix Balances of Items adjusted if exists( select I.ID from Inserted I join Deleted D on D.ID = I.ID where I.Date_Quantity_Adjusted is NOT Null AND D.Date_Quantity_Adjusted is Null AND I.Date_Released_from_Count is NOT Null ) begin insert OrderItems ( Date_Locked, Order_ID, Resource_ID, Quantity ) -- create an adjustment line item select I.Date_Locked_for_Count, I.Last_Count_ID, I.ID, I.Quantity_Counted - I.Snapshot_Quantity from Inserted I join Deleted D on D.ID = I.ID join Orders O on O.ID = I.Last_Count_ID where I.Date_Quantity_Adjusted is NOT Null AND D.Date_Quantity_Adjusted is Null AND D.Date_Released_from_Count is NOT Null AND O.Auto_Generated = 1 -- lines are already there when entering as a Sale from POS declare @GUID varchar( 100 ), @OldDate varchar( 100 ) declare BalanceCursor cursor local for -- recalculate balances select I.GUID, ( select top 1 L.Date_Locked from OrderItems L where L.Resource_ID = I.ID AND L.Date_Locked < I.Date_Locked_for_Count order by 1 desc ) from Inserted I join Deleted D on D.ID = I.ID where I.Date_Quantity_Adjusted is NOT Null AND D.Date_Quantity_Adjusted is Null AND I.Date_Released_from_Count is NOT Null open BalanceCursor fetch BalanceCursor into @GUID, @OldDate while @@FETCH_STATUS = 0 begin exec CalcBalance @GUID, @OldDate fetch BalanceCursor into @GUID, @OldDate end close BalanceCursor deallocate BalanceCursor end ------------------------------------------------------------------------------------ -- Update Weighted Average Usage per Month for Usage Order types when set to zero -- ------------------------------------------------------------------------------------ update Resources set Avg_Usage_per_Month = 0.2 * ( select isNull( Sum( isNull( Quantity, 0 ) ), 0 ) from OrderItems where Resource_ID = R.ID AND [Type] IN ( 'Sale', 'Manufacturing', 'Service' ) AND Date_Locked between GetDate() - 30 AND GetDate() ) + 0.5 * ( select isNull( Sum( isNull( Quantity, 0 ) ), 0 ) / 3 from OrderItems where Resource_ID = R.ID AND [Type] IN ( 'Sale', 'Manufacturing', 'Service' ) AND Date_Locked between GetDate() - 90 AND GetDate() ) + 0.3 * ( select isNull( Sum( isNull( Quantity, 0 ) ), 0 ) / 12 from OrderItems where Resource_ID = R.ID AND [Type] IN ( 'Sale', 'Manufacturing', 'Service' ) AND Date_Locked between GetDate() - 365 AND GetDate() ) - 0.2 * ( select isNull( Sum( isNull( Quantity, 0 ) ), 0 ) from OrderItems where Resource_ID = R.ID AND [Type] = 'Adjustment' AND Quantity < 0 AND Date_Locked between GetDate() - 30 AND GetDate() ) - 0.5 * ( select isNull( Sum( isNull( Quantity, 0 ) ), 0 ) / 3 from OrderItems where Resource_ID = R.ID AND [Type] = 'Adjustment' AND Quantity < 0 AND Date_Locked between GetDate() - 90 AND GetDate() ) - 0.3 * ( select isNull( Sum( isNull( Quantity, 0 ) ), 0 ) / 12 from OrderItems where Resource_ID = R.ID AND [Type] = 'Adjustment' AND Quantity < 0 AND Date_Locked between GetDate() - 365 AND GetDate() ) -- 0.2 * ( select isNull( Sum( Quantity ), 0 ) from OrderItems where Resource_ID = R.ID AND [Type] IN ( 'Sale', 'Manufacturing', 'Service' ) AND Date_Locked between GetDate() - 30 AND GetDate() ) + -- 0.5 * ( select isNull( Sum( Quantity ), 0 ) / 3 from OrderItems where Resource_ID = R.ID AND [Type] IN ( 'Sale', 'Manufacturing', 'Service' ) AND Date_Locked between GetDate() - 90 AND GetDate() ) + -- 0.3 * ( select isNull( Sum( Quantity ), 0 ) / 12 from OrderItems where Resource_ID = R.ID AND [Type] IN ( 'Sale', 'Manufacturing', 'Service' ) AND Date_Locked between GetDate() - 365 AND GetDate() ) - -- 0.2 * ( select isNull( Sum( Quantity ), 0 ) from OrderItems where Resource_ID = R.ID AND [Type] = 'Adjustment' AND Quantity < 0 AND Date_Locked between GetDate() - 30 AND GetDate() ) - -- 0.5 * ( select isNull( Sum( Quantity ), 0 ) / 3 from OrderItems where Resource_ID = R.ID AND [Type] = 'Adjustment' AND Quantity < 0 AND Date_Locked between GetDate() - 90 AND GetDate() ) - -- 0.3 * ( select isNull( Sum( Quantity ), 0 ) / 12 from OrderItems where Resource_ID = R.ID AND [Type] = 'Adjustment' AND Quantity < 0 AND Date_Locked between GetDate() - 365 AND GetDate() ) from Inserted I join Resources R on R.ID = I.ID where I.Avg_Usage_per_Month = 0 AND R.Track_Qty_on_Hand = 1 ------------------------------------------------------------- -- set Order Point and Order Quantity unless manually managed ------------------------------------------------------------- update Resources set Manual_Order_Point = 1 from Inserted I join Resources R on R.ID = I.ID join Deleted D on D.ID = I.ID where ( ( I.Order_Point <> 0 AND I.Order_Point <> D.Order_Point ) OR ( I.Order_Quantity <> 0 AND I.Order_Quantity <> D.Order_Quantity ) ) AND R.Track_Qty_on_Hand = 1 update Resources set Order_Point = R.Avg_Usage_per_Month / 30 * dbo.Maximum( 1, R.Avg_Days_to_Replenish ) * 1.5, Order_Quantity = dbo.Maximum( R.Avg_Usage_per_Month / 4, R.Avg_Usage_per_Month / 30 * dbo.Maximum( 1, R.Avg_Days_to_Replenish ) ) from Inserted I join Resources R on R.ID = I.ID where ( I.Order_Point = 0 OR I.Order_Quantity = 0 ) AND R.Track_Qty_on_Hand = 1 AND R.Manual_Order_Point <> 1 -------------------------------------------- -- update from template if it was changed -- -------------------------------------------- if @@NESTLEVEL = 1 begin update Resources set Std_Cost = T.Std_Cost, Price = T.Price, Price2 = T.Price2, Price3 = T.Price3, Taxable = T.Taxable, Update_eCommerce = T.Update_eCommerce, Can_be_Sold = T.Can_be_Sold, Can_be_Purchased = T.Can_be_Purchased, Can_be_Manufactured = T.Can_be_Manufactured, Can_be_a_Component = T.Can_be_a_Component, Variations_List = T.Variations_List, [Sub-Variations_List] = T.[Sub-Variations_List], Note = T.Note from Resources join Inserted I on I.ID = Resources.ID join Resources T on T.[Name] = Resources.Template_Name where Update( Template_Name ) declare @ID int, @TID int declare Changed cursor local for select R.ID, T.ID from Resources as R join Deleted as D on D.ID = R.ID join Resources as T on T.[Name] = R.[Template_Name] where Update( Template_Name ) open Changed fetch Changed into @ID, @TID while @@FETCH_STATUS = 0 begin exec CopyChildren 'Resources', @TID, @ID fetch Changed into @ID, @TID end close Changed deallocate Changed end ------------------------------ -- Update G/L Accounts Info -- ------------------------------ update Resources set Sales_Account_ID = A.ID from Resources R join Inserted I on I.ID = R.ID join Accounts A on A.[Name] = R.Sales_Account where R.Sales_Account_ID is Null OR Update( Sales_Account ) update Resources set Sales_Account = A.[Name] from Resources R join Inserted I on I.ID = R.ID join Accounts A on A.ID = R.Sales_Account_ID where R.Sales_Account is Null OR Update( Sales_Account_ID ) update Resources set Expense_Account_ID = A.ID from Resources R join Inserted I on I.ID = R.ID join Accounts A on A.[Name] = R.Expense_Account where R.Expense_Account_ID is Null OR Update( Expense_Account ) update Resources set Expense_Account = A.[Name] from Resources R join Inserted I on I.ID = R.ID join Accounts A on A.ID = R.Expense_Account_ID where R.Expense_Account is Null OR Update( Expense_Account_ID ) update Resources set Asset_Account_ID = A.ID from Resources R join Inserted I on I.ID = R.ID join Accounts A on A.[Name] = R.Asset_Account where R.Asset_Account_ID is Null OR Update( Asset_Account ) update Resources set Asset_Account = A.[Name] from Resources R join Inserted I on I.ID = R.ID join Accounts A on A.ID = R.Asset_Account_ID where R.Asset_Account is Null OR Update( Asset_Account_ID ) update Resources set COGS_Account_ID = A.ID from Resources R join Inserted I on I.ID = R.ID join Accounts A on A.[Name] = R.COGS_Account where R.COGS_Account_ID is Null OR Update( COGS_Account ) update Resources set COGS_Account = A.[Name] from Resources R join Inserted I on I.ID = R.ID join Accounts A on A.ID = R.COGS_Account_ID where R.COGS_Account is Null OR Update( COGS_Account_ID ) ---------------------------------------------------------------------------- -- update Catalog and avoid looping since Catalog will want to update us -- ---------------------------------------------------------------------------- if @@NESTLEVEL = 1 begin update Catalog set [Name] = I.[Name], [Code] = I.[Code], [Group] = I.[Group], Department = I.Department, Division = I.Division, Price = I.Price, Price2 = I.Price2, Price3 = I.Price3, Std_Cost = I.Std_Cost, Note = C.Note, Photo1Name = C.Photo1Name, Photo2Name = C.Photo2Name, Photo3Name = C.Photo3Name, Photo1 = R.Photo1, Photo1Thumb = R.Photo1Thumb, Photo2 = R.Photo2, Photo2Thumb = R.Photo2Thumb, Photo3 = R.Photo3, Photo3Thumb = R.Photo3Thumb from Inserted I join Catalog C on C.ID = I.Catalog_ID join Resources R on R.Catalog_ID = I.Catalog_ID end -- Update Specs and Components when Variations Changed -- if Update( Variations_List ) OR Update( [Sub-Variations_List] ) begin update Specs set Variations_List = R.Variations_List, [Sub-Variations_List] = R.[Sub-Variations_List] from Inserted I join Specs S on S.Resource_ID = I.ID join Resources R on R.ID = I.ID update Components set Variations_List = R.Variations_List, [Sub-Variations_List] = R.[Sub-Variations_List] from Inserted I join Components C on C.Component_ID = I.ID join Resources R on R.ID = I.ID end ---------------------------------------------- -- Update any Components of other Resources -- ---------------------------------------------- update Components set Avg_Cost = R.Avg_Cost, Total_Cost = isNull( NullIF( C.Units_Required, 0 ), isNull( NullIF( C.Hours_Required, 0 ), C.Percent_Required / 100 ) ) from Inserted I join Components C on C.Component_ID = I.ID join Resources R on R.ID = I.ID join Deleted D on D.ID = I.ID where R.Avg_Cost <> D.Avg_Cost -- Update Hours data -- if Update( Regular_Days_List ) begin update Resources set Sunday_Hours_List = R.Regular_Day_Hours_List from Inserted I join Resources R on R.ID = I.ID where R.Regular_Days_List like '%sunday%' update Resources set Monday_Hours_List = R.Regular_Day_Hours_List from Inserted I join Resources R on R.ID = I.ID where R.Regular_Days_List like '%monday%' update Resources set Tuesday_Hours_List = R.Regular_Day_Hours_List from Inserted I join Resources R on R.ID = I.ID where R.Regular_Days_List like '%tuesday%' update Resources set Wednesday_Hours_List = R.Regular_Day_Hours_List from Inserted I join Resources R on R.ID = I.ID where R.Regular_Days_List like '%wednesday%' update Resources set Thursday_Hours_List = R.Regular_Day_Hours_List from Inserted I join Resources R on R.ID = I.ID where R.Regular_Days_List like '%thursday%' update Resources set Friday_Hours_List = R.Regular_Day_Hours_List from Inserted I join Resources R on R.ID = I.ID where R.Regular_Days_List like '%friday%' update Resources set Saturday_Hours_List = R.Regular_Day_Hours_List from Inserted I join Resources R on R.ID = I.ID where R.Regular_Days_List like '%saturday%' end -- Add any required Notifications -- if exists( select ID from Inserted where Change_Notification_List is NOT Null ) begin insert Notifications ( Table_Name, Table_ID, Notification_List, Subject, Body ) select 'Resources', R.ID, R.Change_Notification_List, 'Alert on ' + R.[Name], 'select ' + dbo.ModColList( 'Resources', Columns_Updated() ) + ' from Resources where ID = ' + Cast( R.ID as varchar( 10 ) ) from Inserted I join Resources R on R.ID = I.ID where R.Change_Notification_List is NOT Null AND R.Notification_Condition is Null if exists( select ID from Inserted where Notification_Condition is NOT Null ) begin declare @Cmd varchar( 4000 ), @CurID varchar( 10 ), @Name varchar( 50 ), @Notify varchar( 500 ), @Condition varchar( 500 ) declare CurRec cursor local for select ID, [Name], Change_Notification_List, Notification_Condition from Inserted where Change_Notification_List is NOT Null AND Notification_Condition is NOT Null open CurRec fetch CurRec into @CurID, @Name, @Notify, @Condition while @@FETCH_STATUS = 0 begin select @Cmd = 'if exists( select ID from Resources where ID = ' + @CurID + ' AND ' + @Condition + ' ) ' + 'insert Notifications ( Table_Name, Table_ID, Notification_List, Subject, Body ) ' + 'values( ''Resources'', ' + @CurID + ', ''' + @Notify + ''', ''' + @Condition + ' on ' + rTrim( @Name ) + ''', ' + '''select ' + Replace( dbo.ModColList( 'Resources', Columns_Updated() ), '''', '''''' ) + ' from Resources where ID = ' + @CurID + ''' )' exec( @Cmd ) fetch CurRec into @CurID, @Name, @Notify, @Condition end close CurRec deallocate CurRec end end -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- update Resources set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Inserted I join Resources R on R.ID = I.ID set NOCOUNT OFF end end GO ----------- -- Specs -- ----------- if exists ( select * from sysobjects where [Name] = 'BaseColumn' AND [Type] = 'FN' ) drop function dbo.BaseColumn GO create function dbo.BaseColumn( @ID int ) returns int begin declare @Pos int, @Value varchar( 50 ) select @Value = Value_00 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 0 select @Value = Value_01 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 1 select @Value = Value_02 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 2 select @Value = Value_03 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 3 select @Value = Value_04 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 4 select @Value = Value_05 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 5 select @Value = Value_06 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 6 select @Value = Value_07 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 7 select @Value = Value_08 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 8 select @Value = Value_09 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 9 select @Value = Value_10 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 10 select @Value = Value_11 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 11 select @Value = Value_12 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 12 select @Value = Value_13 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 13 select @Value = Value_14 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 14 select @Value = Value_15 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 15 select @Value = Value_16 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 16 select @Value = Value_17 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 17 select @Value = Value_18 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 18 select @Value = Value_19 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 19 select @Value = Value_20 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 20 select @Value = Value_21 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 21 select @Value = Value_22 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 22 select @Value = Value_23 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 23 select @Value = Value_24 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 24 select @Value = Value_25 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 25 select @Value = Value_26 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 26 select @Value = Value_27 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 27 select @Value = Value_28 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 28 select @Value = Value_29 from Variations where Spec_ID = @ID select @Pos = CharIndex( '=', @Value ) if @Pos <> 0 select @Value = SubString( @Value, 1, @Pos - 1 ) if Len( @Value ) = 2 AND SubString( @Value, 2, 1 ) = '0' AND CharIndex( SubString( @Value, 1, 1 ), '+-*/' ) <> 0 return 29 return 0 end GO if exists ( select * from sysobjects where [Name] = 'ApplySpecs' AND [Type] = 'FN' ) drop function dbo.ApplySpecs GO create function dbo.ApplySpecs( @Old varchar( 50 ), @Value varchar( 50 ) ) returns varchar( 50 ) begin declare @Pos int if isNull( @Old, '' ) <> '' AND isNull( @Value, '' ) <> '' begin select @Pos = CharIndex( '=', @Old ) if @Pos <> 0 select @Old = SubString( @Old, 1, @Pos - 1 ) select @Old = rTrim( @Old ) select @Value = rTrim( @Value ) if Left( @Old, 1 ) = '+' select @Old = @Old + ' = ' + Cast( Cast( @Value as float ) + Cast( SubString( @Old, 2, Len( @Old ) - 1 ) as float ) as varchar( 50 ) ) else if Left( @Old, 1 ) = '-' select @Old = @Old + ' = ' + Cast( Cast( @Value as float ) - Cast( SubString( @Old, 2, Len( @Old ) - 1 ) as float ) as varchar( 50 ) ) else if Left( @Old, 1 ) = '*' select @Old = @Old + ' = ' + Cast( Cast( @Value as float ) * Cast( SubString( @Old, 2, Len( @Old ) - 1 ) as float ) as varchar( 50 ) ) else if Left( @Old, 1 ) = '/' select @Old = @Old + ' = ' + Cast( Cast( @Value as float ) / Cast( SubString( @Old, 2, Len( @Old ) - 1 ) as float ) as varchar( 50 ) ) else select @Old = @Old + ' = ' end return @Old end GO if exists ( select * from sysobjects where [Name] = 'NewBaseValue' AND [Type] = 'FN' ) drop function dbo.NewBaseValue GO create function dbo.NewBaseValue( @Old varchar( 50 ), @Value varchar( 50 ) ) returns varchar( 50 ) begin declare @Pos int if isNull( @Old, '' ) <> '' AND isNull( @Value, '' ) <> '' begin select @Pos = CharIndex( '=', @Old ) if @Pos <> 0 select @Old = SubString( @Old, 1, @Pos - 1 ) select @Old = rTrim( @Old ) select @Value = rTrim( @Value ) if Left( @Old, 1 ) = '+' select @Old = @Old + ' = ' + Cast( Cast( @Value as float ) + Cast( SubString( @Old, 2, Len( @Old ) - 1 ) as float ) as varchar( 50 ) ) else if Left( @Old, 1 ) = '-' select @Old = @Old + ' = ' + Cast( Cast( @Value as float ) - Cast( SubString( @Old, 2, Len( @Old ) - 1 ) as float ) as varchar( 50 ) ) else if Left( @Old, 1 ) = '*' select @Old = @Old + ' = ' + Cast( Cast( @Value as float ) * Cast( SubString( @Old, 2, Len( @Old ) - 1 ) as float ) as varchar( 50 ) ) else if Left( @Old, 1 ) = '/' select @Old = @Old + ' = ' + Cast( Cast( @Value as float ) / Cast( SubString( @Old, 2, Len( @Old ) - 1 ) as float ) as varchar( 50 ) ) else select @Old = @Old + ' = ' end select @Pos = CharIndex( '=', @Old ) if @Pos <> 0 select @Old = rTrim( SubString( @Old, @Pos + 1, Len( @Old ) - @Pos ) ) return @Old end GO if exists ( select * from sysobjects where [Name] = 'Specs_Insert' AND [Type] = 'TR' ) drop trigger Specs_Insert GO create trigger Specs_Insert on Specs for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - Specs_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'Specs', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update Specs set Date_Modified = I.Date_Modified from Inserted I join Specs S on S.ID = I.ID set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Specs_Update' AND [Type] = 'TR' ) drop trigger Specs_Update GO create trigger Specs_Update on Specs for update as begin if exists( select ID from Inserted ) begin set NOCOUNT ON -- print 'Debug - Specs_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'Specs', I.ID, I.GUID, Columns_Updated() from Inserted I end -------------------------------- -- Auto-Sequence when omitted -- -------------------------------- update Specs set [Sequence] = ( select Max( isNull( [Sequence], 0 ) ) + 1 from Specs where Resource_ID = I.Resource_ID ) from Inserted I join Specs S on S.ID = I.ID where I.Sequence is Null ------------------------------------------------ -- Update any Variations from parent Resource -- ------------------------------------------------ update Specs set [Variations_List] = R.[Variations_List], [Sub-Variations_List] = R.[Sub-Variations_List] from Inserted I join Specs S on S.ID = I.ID join Resources R on R.ID = I.Resource_ID update Variations set [Name] = I.[Name], [Variations_List] = R.[Variations_List], [Sub-Variations_List] = R.[Sub-Variations_List] from Inserted I join Variations V on V.Spec_ID = I.ID join Resources R on R.ID = I.Resource_ID ------------------------------------------------------- -- Process Application specific Specifications Rules -- ------------------------------------------------------- declare @ID int, @BaseNo int, @ColNo int, @Cmd varchar( 4000 ) declare SpecsChanged cursor local for select I.ID from Inserted I join Deleted D on D.ID = I.ID -- where I.Value <> D.Value open SpecsChanged fetch SpecsChanged into @ID while @@FETCH_STATUS = 0 begin select @Cmd = 'update Variations set Base_Value = ( select Value from Specs where ID = ' + Cast( @ID as varchar( 12 ) ) + ' )' exec( @Cmd ) select @BaseNo = dbo.BaseColumn( @ID ) select @ColNo = @BaseNo while @ColNo < 30 begin -- calculate equal and above base value select @Cmd = 'update Variations set Value_' + SubString( Cast( @ColNo + 100 as char( 3 ) ), 2, 2 ) + ' = dbo.ApplySpecs( Value_' + SubString( Cast( @ColNo + 100 as char( 3 ) ), 2, 2 ) + ' , Base_Value ), Base_Value' + ' = dbo.NewBaseValue( Value_' + SubString( Cast( @ColNo + 100 as char( 3 ) ), 2, 2 ) + ' , Base_Value )' + ' where Spec_ID = ' + Cast( @ID as varchar( 12 ) ) exec( @Cmd ) select @ColNo = @ColNo + 1 end select @Cmd = 'update Variations set Base_Value = ( select Value from Specs where ID = ' + Cast( @ID as varchar( 12 ) ) + ' )' exec( @Cmd ) select @ColNo = @BaseNo - 1 while @ColNo >= 0 begin -- calculate below base value select @Cmd = 'update Variations set Value_' + SubString( Cast( @ColNo + 100 as char( 3 ) ), 2, 2 ) + ' = dbo.ApplySpecs( Value_' + SubString( Cast( @ColNo + 100 as char( 3 ) ), 2, 2 ) + ' , Base_Value ), Base_Value' + ' = dbo.NewBaseValue( Value_' + SubString( Cast( @ColNo + 100 as char( 3 ) ), 2, 2 ) + ' , Base_Value )' + ' where Spec_ID = ' + Cast( @ID as varchar( 12 ) ) exec( @Cmd ) select @ColNo = @ColNo - 1 end fetch SpecsChanged into @ID end close SpecsChanged deallocate SpecsChanged ------------------------------------------------------------------------------------------------------------------ -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- ------------------------------------------------------------------------------------------------------------------ update Specs set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Inserted I join Specs S on S.ID = I.ID set NOCOUNT OFF end end GO if exists ( select * from sysobjects where [Name] = 'Specs_Delete' AND [Type] = 'TR' ) drop trigger Specs_Delete GO create trigger Specs_Delete on Specs for Delete as begin if NOT exists( select ID from Deleted ) return set NOCOUNT ON if @@NESTLEVEL = 1 begin -- print 'Debug - Specs_Delete' ----------------------------------------------------------------------- -- delete variations records since using foreign keys creates a loop -- ----------------------------------------------------------------------- delete Variations from Deleted D join Variations V on V.Spec_ID = D.ID end set NOCOUNT OFF end GO ---------------- -- Components -- ---------------- if exists ( select * from sysobjects where [Name] = 'Components_Insert' AND [Type] = 'TR' ) drop trigger Components_Insert GO create trigger Components_Insert on Components for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - Components_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'Components', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update Components set Date_Modified = I.Date_Modified from Inserted I join Components C on C.ID = I.ID set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Components_Update' AND [Type] = 'TR' ) drop trigger Components_Update GO create trigger Components_Update on Components for update as begin if exists( select ID from Inserted ) begin set NOCOUNT ON -- print 'Debug - Components_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'Components', I.ID, I.GUID, Columns_Updated() from Inserted I end -------------------------------- -- Auto-Sequence when omitted -- -------------------------------- update Components set [Sequence] = ( select Max( isNull( [Sequence], 0 ) ) + 1 from Components where Resource_ID = I.Resource_ID ) from Inserted I join Components C on C.ID = I.ID where I.Sequence is Null --------------------------------------- -- update self from selected Contact -- --------------------------------------- update Components set Contact_ID = S.ID from Inserted I join Components C on C.ID = I.ID join Contacts S on S.[Name] = I.Contact_Name -------------------------------------------------- -- update self from selected Component Resource -- -------------------------------------------------- update Components set Component_ID = R.ID, Resource_Code = R.Code, Resource_Name = R.[Name], Avg_Cost = R.Avg_Cost, -- Total_Cost = isNull( NullIF( C.Units_Required, 0 ), isNull( NullIF( C.Hours_Required, 0 ), C.Percent_Required / 100 ) ), Variations_List = R.Variations_List, [Sub-Variations_List] = R.[Sub-Variations_List] from Inserted I join Components C on C.ID = I.ID join Deleted D on D.ID = I.ID join Resources R on R.Code = I.Resource_Code where update( Resource_Code ) -- AND I.Date_Modified is Null -- when called from the Insert trigger update Components set Component_ID = R.ID, Resource_Code = R.Code, Resource_Name = R.[Name], Avg_Cost = R.Avg_Cost, -- Total_Cost = isNull( NullIF( C.Units_Required, 0 ), isNull( NullIF( C.Hours_Required, 0 ), C.Percent_Required / 100 ) ), Variations_List = R.Variations_List, [Sub-Variations_List] = R.[Sub-Variations_List] from Inserted I join Components C on C.ID = I.ID join Deleted D on D.ID = I.ID join Resources R on R.[Name] = I.[Resource_Name] where update( Resource_Name ) -- AND I.Date_Modified is Null -- when called from the Insert trigger ------------------------ -- Update Line Totals -- ------------------------ update Components set Total_Cost = C.Avg_Cost * isNull( NullIF( C.Units_Required, 0 ), isNull( NullIF( C.Hours_Required, 0 ), C.Percent_Required / 100 ) ) from Inserted I join Components C on C.ID = I.ID ------------------------------------- -- force update of Parent Counters -- ------------------------------------- update Resources set Mfg_Cost = 0 from Inserted I join Resources R on R.ID = I.Resource_ID ------------------------------------------------------------------------------------------------------------------ -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- ------------------------------------------------------------------------------------------------------------------ update Components set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Inserted I join Components C on C.ID = I.ID set NOCOUNT OFF end end GO if exists ( select * from sysobjects where [Name] = 'Components_Delete' AND [Type] = 'TR' ) drop trigger Components_Delete GO create trigger Components_Delete on Components for Delete as begin if NOT exists( select ID from Deleted ) return set NOCOUNT ON ----------------------------------- -- force update of parent totals -- ----------------------------------- if @@NESTLEVEL = 1 begin -- force update of parent totals -- print 'Debug - Components_Delete' ------------------------------------- -- force update of Parent Counters -- ------------------------------------- update Resources set Mfg_Cost = 0 from Deleted D join Resources R on R.ID = D.Resource_ID ----------------------------------------------------------------------- -- delete variations records since using foreign keys creates a loop -- ----------------------------------------------------------------------- delete Variations from Deleted D join Variations V on V.Component_ID = D.ID end set NOCOUNT OFF end GO ------------------- -- Relationships -- ------------------- if exists ( select * from sysobjects where [Name] = 'Relationships_Insert' AND [Type] = 'TR' ) drop trigger Relationships_Insert GO create trigger Relationships_Insert on Relationships for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - Relationships_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'Relationships', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update Relationships set Date_Modified = I.Date_Modified from Inserted I join Relationships R on R.ID = I.ID where I.Date_Modified is Null -- If it is not null then skip triggers set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Relationships_Delete' AND [Type] = 'TR' ) drop trigger Relationships_Delete GO create trigger Relationships_Delete on Relationships for delete as begin if NOT exists( select ID from Deleted ) return set NOCOUNT ON if @@NESTLEVEL = 1 begin -- print 'Debug - Relationships_Delete' ------------------------------------------------------------------- -- delete flipped duplicate for contact to contact relationships -- ------------------------------------------------------------------- delete Relationships from Deleted D join Contacts C1 on C1.ID = D.Contact_ID join Contacts C2 on C2.[Name] = D.Contact_Name join Relationships R on R.Contact_ID = C2.ID AND R.Contact_Name = C1.[Name] where D.Resource_Name is Null end set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Relationships_Update' AND [Type] = 'TR' ) drop trigger Relationships_Update GO create trigger Relationships_Update on Relationships for update as begin if exists( select ID from Inserted ) begin set NOCOUNT ON -- print 'Debug - Relationships_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'Relationships', I.ID, I.GUID, Columns_Updated() from Inserted I end -- if @@NESTLEVEL = 1 begin --------------------------------------------------------------------------------- -- resource to contact relationship must be owned by the contact name chosen -- --------------------------------------------------------------------------------- update Relationships set Contact_ID = C.ID from Inserted I join Relationships R on R.ID = I.ID join Contacts C on C.[Name] = I.Contact_Name where I.Contact_Name is NOT Null AND I.Resource_Name is NOT Null update Relationships set Contact_Name = C.[Name] from Inserted I join Relationships R on R.ID = I.ID join Contacts C on C.ID = I.Contact_ID where I.Contact_ID is NOT Null AND I.Resource_Name is NOT Null ------------------------------------------------------------------- -- delete flipped duplicate for contact to contact relationships -- ------------------------------------------------------------------- update Relationships set Related_ID = C.ID from Inserted I join Relationships R on R.ID = I.ID join Contacts C on C.[Name] = I.Contact_Name where I.Resource_Name is Null delete Relationships from Deleted D join Relationships R on R.Contact_ID = D.Related_ID AND R.Related_ID = D.Contact_ID where D.Resource_Name is Null -- delete Relationships from Deleted D join Contacts C1 on C1.ID = D.Contact_ID -- join Contacts C2 on C2.[Name] = D.Contact_Name -- join Relationships R on R.Contact_ID = C2.ID AND R.Contact_Name = C1.[Name] -- where isNull( D.Resource_Name, '' ) = '' ------------------------------------------------------------------------- -- create a new flipped duplicate for contact to contact relationships -- ------------------------------------------------------------------------- select R.* into #RelationshipTwin from Inserted I join Relationships R on R.ID = I.ID where R.Resource_Name is Null AND R.Related_ID is NOT Null update #RelationshipTwin set GUID = NewID(), Contact_ID = C2.ID, Related_ID = C1.ID, Contact_Name = C1.[Name], Date_Modified = GetDate() from Inserted I join Contacts C1 on C1.ID = I.Contact_ID join Contacts C2 on C2.[Name] = I.Contact_Name alter table #RelationshipTwin drop column ID select * into #RelationshipTwin2 from #RelationshipTwin insert Relationships select * from #RelationshipTwin2 drop table #RelationshipTwin drop table #RelationshipTwin2 -- end ------------------------------------------------------------------------------------------------------------------ -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- ------------------------------------------------------------------------------------------------------------------ update Relationships set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Inserted I join Relationships R on R.ID = I.ID set NOCOUNT OFF end end GO ------------ -- Orders -- ------------ if exists ( select * from sysobjects where [Name] = 'Sales_Tax_05' AND [Type] = 'FN' ) drop function dbo.Sales_Tax_05 GO --create function dbo.Sales_Tax( @Date datetime, @TaxProfile char( 50 ), @TaxableAmt money, @TaxIndex int ) returns money --begin -- declare @Result money, @GST_Rate decimal( 18, 4 ), @HST_Rate decimal( 18, 4 ), @SK_Rate decimal( 18, 4 ), @MA_Rate decimal( 18, 4 ), -- @ON_Rate decimal( 18, 4 ), @BC_Rate decimal( 18, 4 ), @QC_Rate decimal( 18, 4 ), @PEI_Rate decimal( 18, 4 ) -- select @Result = 0.0, @TaxableAmt = isNull( @TaxableAmt, 0 ), -- @SK_Rate = 0.05, @MA_Rate = 0.07, @ON_Rate = 0.08, @BC_Rate = 0.07, @QC_Rate = 0.075, @PEI_Rate = 0.10 -- if @Date < '2008-1-1' select @GST_Rate = 0.06, @HST_Rate = 0.14 -- else select @GST_Rate = 0.05, @HST_Rate = 0.13 -- if @TaxIndex = 0 begin -- if @TaxProfile = 'GST' select @Result = Round( @TaxableAmt * @GST_Rate, 2, 0 ) -- else if @TaxProfile = 'HST' select @Result = Round( @TaxableAmt * @HST_Rate, 2, 0 ) -- else if @TaxProfile = 'GST/SK' select @Result = Round( @TaxableAmt * @GST_Rate, 2, 0 ) + Round( @TaxableAmt * 0.05, 2, 0 ) -- else if @TaxProfile = 'GST/MA' select @Result = Round( @TaxableAmt * @GST_Rate, 2, 0 ) + Round( @TaxableAmt * 0.07, 2, 0 ) -- else if @TaxProfile = 'GST/ON' select @Result = Round( @TaxableAmt * @GST_Rate, 2, 0 ) + Round( @TaxableAmt * 0.08, 2, 0 ) -- else if @TaxProfile = 'GST/BC' select @Result = Round( @TaxableAmt * @GST_Rate, 2, 0 ) + Round( @TaxableAmt * 0.07, 2, 0 ) -- else if @TaxProfile = 'GST/QC' select @Result = Round( @TaxableAmt * @GST_Rate, 2, 0 ) + Round( ( @TaxableAmt + Round( @TaxableAmt * @GST_Rate, 2, 0 ) ) * 0.075, 2, 0 ) -- else if @TaxProfile = 'GST/PEI' select @Result = Round( @TaxableAmt * @GST_Rate, 2, 0 ) + Round( ( @TaxableAmt + Round( @TaxableAmt * @GST_Rate, 2, 0 ) ) * 0.10, 2, 0 ) -- end -- if @TaxIndex = 1 begin -- if @TaxProfile = 'GST' select @Result = Round( @TaxableAmt * @GST_Rate, 2, 0 ) -- else if @TaxProfile = 'HST' select @Result = Round( @TaxableAmt * @HST_Rate, 2, 0 ) -- else if @TaxProfile = 'GST/SK' select @Result = Round( @TaxableAmt * @GST_Rate, 2, 0 ) -- else if @TaxProfile = 'GST/MA' select @Result = Round( @TaxableAmt * @GST_Rate, 2, 0 ) -- else if @TaxProfile = 'GST/ON' select @Result = Round( @TaxableAmt * @GST_Rate, 2, 0 ) -- else if @TaxProfile = 'GST/BC' select @Result = Round( @TaxableAmt * @GST_Rate, 2, 0 ) -- else if @TaxProfile = 'GST/QC' select @Result = Round( @TaxableAmt * @GST_Rate, 2, 0 ) -- else if @TaxProfile = 'GST/PEI' select @Result = Round( @TaxableAmt * @GST_Rate, 2, 0 ) -- end -- if @TaxIndex = 2 begin -- if @TaxProfile = 'GST/SK' select @Result = Round( @TaxableAmt * 0.05, 2, 0 ) -- else if @TaxProfile = 'GST/MA' select @Result = Round( @TaxableAmt * 0.07, 2, 0 ) -- else if @TaxProfile = 'GST/ON' select @Result = Round( @TaxableAmt * 0.08, 2, 0 ) -- else if @TaxProfile = 'GST/BC' select @Result = Round( @TaxableAmt * 0.07, 2, 0 ) -- else if @TaxProfile = 'GST/QC' select @Result = Round( ( @TaxableAmt + Round( @TaxableAmt * @GST_Rate, 2, 0 ) ) * 0.075, 2, 0 ) -- else if @TaxProfile = 'GST/PEI' select @Result = Round( ( @TaxableAmt + Round( @TaxableAmt * @GST_Rate, 2, 0 ) ) * 0.10, 2, 0 ) -- end -- return @Result --end --GO if exists ( select * from sysobjects where [Name] = 'Sales_Tax' AND [Type] = 'FN' ) drop function dbo.Sales_Tax GO create function dbo.Sales_Tax( @Date datetime, @TaxProfile varchar( 50 ), @TaxableAmt money, @TaxIndex int ) returns money begin declare @Result money, @Tax1_Rate decimal( 18, 4 ), @Tax2_Rate decimal( 18, 4 ), @Tax1_is_Taxable bit select @Result = 0.0, @TaxableAmt = isNull( @TaxableAmt, 0 ) if isNull( @TaxProfile, '' ) <> '' AND exists( select ID from TaxProfiles where [Name] = @TaxProfile AND Date_Effective < @Date ) begin select top 1 @Tax1_Rate = isNull( Tax1_Percent / 100, 0 ), @Tax2_Rate = isNull( Tax2_Percent / 100, 0 ), @Tax1_is_Taxable = Tax1_is_Taxable from TaxProfiles where [Name] = @TaxProfile AND Date_Effective < @Date order by Date_Effective desc if @TaxIndex = 0 select @Result = Round( @TaxableAmt * @Tax1_Rate, 2, 0 ) + Round( ( @TaxableAmt + Round( @TaxableAmt * @Tax1_Rate * @Tax1_is_Taxable, 2, 0 ) ) * @Tax2_Rate, 2, 0 ) else if @TaxIndex = 1 select @Result = Round( @TaxableAmt * @Tax1_Rate, 2, 0 ) else if @TaxIndex = 2 select @Result = Round( ( @TaxableAmt + Round( @TaxableAmt * @Tax1_Rate * @Tax1_is_Taxable, 2, 0 ) ) * @Tax2_Rate, 2, 0 ) end return @Result end GO if exists ( select * from sysobjects where [Name] = 'FixTaxes_05' AND [Type] = 'P' ) drop procedure dbo.FixTaxes_05 GO if exists ( select * from sysobjects where [Name] = 'AddPayment' AND [Type] = 'P' ) drop procedure dbo.AddPayment GO create procedure dbo.AddPayment( @GUID varchar( 100 ), @Slot varchar( 100 ), @Amt varchar( 100 ) ) as begin set NOCOUNT ON declare @ID int select @ID = isNull( ID, 0 ) from Orders where GUID = @GUID alter table Orders disable trigger all if @Slot = '1' update Orders set Payment = Payment + @Amt, Paid = Paid + @Amt, Balance = Balance - @Amt where ID = @ID if @Slot = '2' update Orders set Payment1 = Payment1 + @Amt, Paid = Paid + @Amt, Balance = Balance - @Amt where ID = @ID if @Slot = '3' update Orders set Payment2 = Payment2 + @Amt, Paid = Paid + @Amt, Balance = Balance - @Amt where ID = @ID if @Slot = '4' update Orders set Payment3 = Payment3 + @Amt, Paid = Paid + @Amt, Balance = Balance - @Amt where ID = @ID if @Slot = '5' update Orders set Payment4 = Payment4 + @Amt, Paid = Paid + @Amt, Balance = Balance - @Amt where ID = @ID if @Slot = '6' update Orders set Payment5 = Payment5 + @Amt, Paid = Paid + @Amt, Balance = Balance - @Amt where ID = @ID if @Slot = '7' update Orders set Payment6 = Payment6 + @Amt, Paid = Paid + @Amt, Balance = Balance - @Amt where ID = @ID if @Slot = '8' update Orders set Payment7 = Payment7 + @Amt, Paid = Paid + @Amt, Balance = Balance - @Amt where ID = @ID if @Slot = '9' update Orders set Payment8 = Payment8 + @Amt, Paid = Paid + @Amt, Balance = Balance - @Amt where ID = @ID if @Slot = '10' update Orders set Payment9 = Payment9 + @Amt, Paid = Paid + @Amt, Balance = Balance - @Amt where ID = @ID alter table Orders enable trigger all set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'MovePayment' AND [Type] = 'P' ) drop procedure dbo.MovePayment GO create procedure dbo.MovePayment( @GUID varchar( 100 ), @Slot varchar( 100 ) ) as begin set NOCOUNT ON declare @ID int select @ID = isNull( ID, 0 ) from Orders where GUID = @GUID alter table Orders disable trigger all if @Slot = '1' update Orders set Payment = Paid,Payment1=0,Payment2=0,Payment3=0,Payment4=0,Payment5=0,Payment6=0,Payment7=0,Payment8=0,Payment9=0 where ID = @ID if @Slot = '2' update Orders set Payment1 = Paid,Payment =0,Payment2=0,Payment3=0,Payment4=0,Payment5=0,Payment6=0,Payment7=0,Payment8=0,Payment9=0 where ID = @ID if @Slot = '3' update Orders set Payment2 = Paid,Payment1=0,Payment =0,Payment3=0,Payment4=0,Payment5=0,Payment6=0,Payment7=0,Payment8=0,Payment9=0 where ID = @ID if @Slot = '4' update Orders set Payment3 = Paid,Payment1=0,Payment2=0,Payment =0,Payment4=0,Payment5=0,Payment6=0,Payment7=0,Payment8=0,Payment9=0 where ID = @ID if @Slot = '5' update Orders set Payment4 = Paid,Payment1=0,Payment2=0,Payment3=0,Payment =0,Payment5=0,Payment6=0,Payment7=0,Payment8=0,Payment9=0 where ID = @ID if @Slot = '6' update Orders set Payment5 = Paid,Payment1=0,Payment2=0,Payment3=0,Payment4=0,Payment =0,Payment6=0,Payment7=0,Payment8=0,Payment9=0 where ID = @ID if @Slot = '7' update Orders set Payment6 = Paid,Payment1=0,Payment2=0,Payment3=0,Payment4=0,Payment5=0,Payment =0,Payment7=0,Payment8=0,Payment9=0 where ID = @ID if @Slot = '8' update Orders set Payment7 = Paid,Payment1=0,Payment2=0,Payment3=0,Payment4=0,Payment5=0,Payment6=0,Payment =0,Payment8=0,Payment9=0 where ID = @ID if @Slot = '9' update Orders set Payment8 = Paid,Payment1=0,Payment2=0,Payment3=0,Payment4=0,Payment5=0,Payment6=0,Payment7=0,Payment =0,Payment9=0 where ID = @ID if @Slot = '0' update Orders set Payment9 = Paid,Payment1=0,Payment2=0,Payment3=0,Payment4=0,Payment5=0,Payment6=0,Payment7=0,Payment8=0,Payment =0 where ID = @ID if @Slot = '10' update Orders set Payment9 = Paid,Payment1=0,Payment2=0,Payment3=0,Payment4=0,Payment5=0,Payment6=0,Payment7=0,Payment8=0,Payment =0 where ID = @ID alter table Orders enable trigger all set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'PrintOrder' AND [Type] = 'P' ) drop procedure dbo.PrintOrder GO create procedure dbo.PrintOrder( @GUID varchar( 100 ), @Date varchar( 100 ) ) as begin set NOCOUNT ON declare @ID int select @ID = isNull( ID, 0 ) from Orders where GUID = @GUID if Lower( @Date ) = 'getdate()' select @Date = GetDate() update Orders set Date_Printed = @Date where [Type] IN ( 'Sale', 'Purchase', 'Adjustment', 'Production', 'Service' ) AND Date_Locked is Null AND ID = @ID -- update Orders set Number = isNull( ( select top 1 Number + 1 from Orders -- where ServerName = @ServerName AND [Type] = 'Purchase' order by Number desc ), 1000 ) -- where [Type] = 'Purchase' AND Date_Locked is Null AND isNull( Number, '' ) = '' AND [OrderItems_Count] > 0 AND ID = @ID set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'PrintOrderID' AND [Type] = 'P' ) drop procedure dbo.PrintOrderID GO create procedure dbo.PrintOrderID( @ID int ) as begin set NOCOUNT ON declare @GUID varchar( 100 ) select @GUID = isNull( GUID, '' ) from Orders where ID = @ID AND Date_Locked is Null if @GUID <> '' execute dbo.PrintOrder @GUID, 'GetDate()' set NOCOUNT OFF end GO --use master --grant execute on sp_OACreate to IUSR_WINDOWS2003 --grant execute on sp_OAMethod to IUSR_WINDOWS2003 --grant execute on sp_OACreate to VDM --grant execute on sp_OAMethod to VDM --use msdb --grant execute on sp_send_dbmail to IUSR_WINDOWS2003 --grant execute on sp_send_dbmail to VDM --execute msdb.dbo.sysmail_add_profile_sp 'Default_Profile', 'Default Profile' if exists ( select * from sysobjects where [Name] = 'eMailInvoiceID' AND [Type] = 'P' ) drop procedure dbo.eMailInvoiceID GO create procedure dbo.eMailInvoiceID( @ID int, @eMail varchar( 100 ) ) as begin set NOCOUNT ON declare @GUID varchar( 100 ) select @GUID = isNull( GUID, '' ) from Orders where ID = @ID AND Date_Locked is Null if @GUID <> '' execute dbo.PrintOrder @GUID, 'GetDate()' select @eMail = eMail + ';' + @eMail from Orders where ID = @ID declare @Sub varchar( 100 ) set @Sub = 'eMail Confirmation - ' + cast( @ID as varchar( 12 ) ) declare @Txt varchar( max ) set @Txt = dbo.FileAsString( 'e:\http\_ACI_invoice_ID_' + cast( @ID as varchar( 12 ) ) + '.htm' ) declare @Lst varchar( 4000 ) set @Lst = '' --'e:\http\ACI_style.css' -- declare @Lst varchar( 4000 ) set @Lst = 'e:\http\ACI_style.css;e:\http\images\aci-corner-155_w.gif;' + -- 'e:\http\images\header_e-cart_500x88.gif;e:\http\images\calendar30.gif;e:\http\images\gmail26.gif' exec msdb.dbo.sp_send_dbmail 'Main', @eMail, '', '', @Sub, @Txt, 'HTML', 'HIGH', 'PRIVATE', @Lst set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'eMailInvoiceID2' AND [Type] = 'P' ) drop procedure dbo.eMailInvoiceID2 GO create procedure dbo.eMailInvoiceID2( @ID int, @eMail varchar( 100 ) ) as begin set NOCOUNT ON declare @GUID varchar( 100 ) select @GUID = isNull( GUID, '' ) from Orders where ID = @ID AND Date_Locked is Null if @GUID <> '' execute dbo.PrintOrder @GUID, 'GetDate()' select @eMail = eMail + ';' + @eMail from Orders where ID = @ID declare @Sub varchar( 100 ) set @Sub = 'eMail Confirmation - ' + cast( @ID as varchar( 12 ) ) declare @Txt varchar( max ) set @Txt = dbo.FileAsString( 'E:\HTTP\Clearware.net\_ACI_invoice_ID_' + cast( @ID as varchar( 12 ) ) + '.htm' ) declare @Lst varchar( 4000 ) set @Lst = '' --'e:\http\ACI_style.css' -- declare @Lst varchar( 4000 ) set @Lst = 'e:\http\ACI_style.css;e:\http\images\aci-corner-155_w.gif;' + -- 'e:\http\images\header_e-cart_500x88.gif;e:\http\images\calendar30.gif;e:\http\images\gmail26.gif' exec msdb.dbo.sp_send_dbmail 'Main', @eMail, '', '', @Sub, @Txt, 'HTML', 'HIGH', 'PRIVATE', @Lst set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'WriteOrderGL' AND [Type] = 'P' ) drop procedure dbo.WriteOrderGL GO create procedure dbo.WriteOrderGL( @GUID varchar( 100 ) ) as begin set NOCOUNT ON declare @ID int, @LID int, @AID int, @SID int, @Date varchar( 100 ), @Type varchar( 100 ), @Number varchar( 100 ) select @ID = isNull( ID, 0 ), @Type = [Type], @Number = Number, @Date = Date_Locked from Orders where GUID = @GUID AND Date_Locked is NOT Null if @ID <> 0 begin begin transaction ----------------------------------------------------- -- write G/L distribution for document if required -- ----------------------------------------------------- insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Sales_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, @Type, @Number, O.ID, O.Total - O.Discount_Amount from Orders O where O.ID = @ID AND O.Total <> 0 AND O.AR_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AP_Account_ID, O.Asset_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, @Type, @Number, @Number, O.Total - O.Discount_Amount from Orders O where O.ID = @ID AND O.Total <> 0 AND O.AP_Account_ID is NOT Null AND O.Asset_Account_ID is NOT Null AND @Type = 'Purchase' insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AP_Account_ID, O.Expense_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, @Type, @Number, @Number, O.Total - O.Discount_Amount from Orders O where O.ID = @ID AND O.Total <> 0 AND O.AP_Account_ID is NOT Null AND O.Asset_Account_ID is Null AND O.Expense_Account_ID is NOT Null AND @Type = 'Purchase' select @LID = Scope_Identity() set @AID = @LID -- add taxes insert Ledger ( Ledger_ID, Account_ID, Order_ID, Amount ) select @LID, ( select top 1 T.Tax1_Account_ID from TaxProfiles T where T.[Name] = O.Tax_Profile AND T.Date_Effective < @Date order by T.Date_Effective desc ), O.ID, O.Taxes1 from Orders O where O.ID = @ID AND O.Taxes1 <> 0 AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Ledger_ID, Account_ID, Order_ID, Amount ) select @LID, ( select top 1 T.Tax2_Account_ID from TaxProfiles T where T.[Name] = O.Tax_Profile AND T.Date_Effective < @Date order by T.Date_Effective desc ), O.ID, O.Taxes2 from Orders O where O.ID = @ID AND O.Taxes2 <> 0 AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Ledger_ID, Account_ID, Order_ID, Amount ) select @LID, ( select top 1 T.Tax1_Account_ID from TaxProfiles T where T.[Name] = O.Tax_Profile AND T.Date_Effective < @Date order by T.Date_Effective desc ), O.ID, - O.Taxes1 from Orders O where O.ID = @ID AND O.Taxes1 <> 0 AND @Type = 'Purchase' insert Ledger ( Ledger_ID, Account_ID, Order_ID, Amount ) select @LID, ( select top 1 T.Tax2_Account_ID from TaxProfiles T where T.[Name] = O.Tax_Profile AND T.Date_Effective < @Date order by T.Date_Effective desc ), O.ID, - O.Taxes2 from Orders O where O.ID = @ID AND O.Taxes2 <> 0 AND @Type = 'Purchase' ----------------------------------------------------- -- write G/L distribution for payments if required -- ----------------------------------------------------- insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Cash', @Number, O.ID, - O.Payment + O.Change -- alwasy deduct change from any cash from Orders O where O.ID = @ID AND O.Payment <> 0 AND O.Payment_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Debit', @Number, O.ID, - O.Payment1 -- only deduct change when no cash from Orders O where O.ID = @ID AND O.Payment <> 0 AND O.Payment1 <> 0 AND O.Payment1_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment1_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Debit', @Number, O.ID, - O.Payment1 + O.Change -- only deduct change when no cash from Orders O where O.ID = @ID AND O.Payment = 0 AND O.Payment1 <> 0 AND O.Payment1_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment2_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Visa', @Number, O.ID, - O.Payment2 from Orders O where O.ID = @ID AND O.Payment2 <> 0 AND O.Payment2_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment3_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Mastercard', @Number, O.ID, - O.Payment3 from Orders O where O.ID = @ID AND O.Payment3 <> 0 AND O.Payment3_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment4_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Amex', @Number, O.ID, - O.Payment4 from Orders O where O.ID = @ID AND O.Payment4 <> 0 AND O.Payment4_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment5_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Check', @Number, O.ID, - O.Payment5 from Orders O where O.ID = @ID AND O.Payment5 <> 0 AND O.Payment5_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment6_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Other', @Number, O.ID, - O.Payment6 from Orders O where O.ID = @ID AND O.Payment6 <> 0 AND O.Payment6_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment7_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Payment', @Number, O.ID, - O.Payment7 from Orders O where O.ID = @ID AND O.Payment7 <> 0 AND O.Payment7_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment8_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Payment', @Number, O.ID, - O.Payment8 from Orders O where O.ID = @ID AND O.Payment8 <> 0 AND O.Payment8_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment9_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Payment', @Number, O.ID, - O.Payment9 from Orders O where O.ID = @ID AND O.Payment9 <> 0 AND O.Payment9_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) update Ledger set Apply_Sequence = L.Apply_Sequence -- Auto-Apply from Ledger L where ID = @AID commit transaction end set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'LockOrder' AND [Type] = 'P' ) drop procedure dbo.LockOrder GO create procedure dbo.LockOrder( @GUID varchar( 100 ), @Date varchar( 100 ), @Number varchar( 100 ) ) as begin set NOCOUNT ON declare @ID int, @CID int, @Bal decimal( 18, 4 ), @LID int, @AID int, @SID int, @Type varchar( 100 ), @Release int select @ID = isNull( ID, 0 ), @Type = [Type], @CID = isNull( Contact_ID, 0 ), @Bal = Balance from Orders where [GUID] = @GUID AND Date_Locked is Null -- select @Number = Number from Orders where ID = @ID if @ID <> 0 AND @Type <> 'Estimate' begin set @Release = 0 if @CID = 0 AND @Bal <> 0 AND @Type = 'Sale' begin raiserror( 'Error - No Balance Due for Onetime Contacts - Choose a valid Contact', 11, 1 ) rollback end else if isNull( @Number, '' ) = '' AND exists( select * from Numbers where Date_Locked > DateAdd( minute, - 5, GetDate() ) AND [Type] IN ( 'Sale', 'Service' ) ) begin raiserror( 'Warning - Numbers Locked - Try Again', 11, 1 ) rollback end else begin begin transaction if isNull( @Number, '' ) = '' AND @Type IN ( 'Sale', 'Service' ) begin set @Release = 1 update Numbers with( HOLDLOCK ) set Date_Locked = GetDate(), Last_Number = Last_Number + 1 where [Type] = @Type select @Number = Last_Number from Numbers where [Type] = @Type end if CharIndex( 'getdate', Lower( @Date ) ) > 0 select @Date = GetDate() update Orders set Date_Locked = @Date, Number = @Number, Deposit = - Locked_Deposits where ID = @ID ----------------------------------------------------- -- write G/L distribution for document if required -- ----------------------------------------------------- insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Sales_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, @Type, @Number, O.ID, O.Total - O.Discount_Amount from Orders O where O.ID = @ID AND O.Total <> 0 AND O.AR_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AP_Account_ID, O.Asset_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, @Type, @Number, @Number, O.Total - O.Discount_Amount from Orders O where O.ID = @ID AND O.Total <> 0 AND O.AP_Account_ID is NOT Null AND O.Asset_Account_ID is NOT Null AND @Type = 'Purchase' insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AP_Account_ID, O.Expense_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, @Type, @Number, @Number, O.Total - O.Discount_Amount from Orders O where O.ID = @ID AND O.Total <> 0 AND O.AP_Account_ID is NOT Null AND O.Asset_Account_ID is Null AND O.Expense_Account_ID is NOT Null AND @Type = 'Purchase' select @LID = Scope_Identity() set @AID = @LID -- add taxes insert Ledger ( Ledger_ID, Account_ID, Order_ID, Amount ) select @LID, ( select top 1 T.Tax1_Account_ID from TaxProfiles T where T.[Name] = O.Tax_Profile AND T.Date_Effective < @Date order by T.Date_Effective desc ), O.ID, O.Taxes1 from Orders O where O.ID = @ID AND O.Taxes1 <> 0 AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Ledger_ID, Account_ID, Order_ID, Amount ) select @LID, ( select top 1 T.Tax2_Account_ID from TaxProfiles T where T.[Name] = O.Tax_Profile AND T.Date_Effective < @Date order by T.Date_Effective desc ), O.ID, O.Taxes2 from Orders O where O.ID = @ID AND O.Taxes2 <> 0 AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Ledger_ID, Account_ID, Order_ID, Amount ) select @LID, ( select top 1 T.Tax1_Account_ID from TaxProfiles T where T.[Name] = O.Tax_Profile AND T.Date_Effective < @Date order by T.Date_Effective desc ), O.ID, - O.Taxes1 from Orders O where O.ID = @ID AND O.Taxes1 <> 0 AND @Type = 'Purchase' insert Ledger ( Ledger_ID, Account_ID, Order_ID, Amount ) select @LID, ( select top 1 T.Tax2_Account_ID from TaxProfiles T where T.[Name] = O.Tax_Profile AND T.Date_Effective < @Date order by T.Date_Effective desc ), O.ID, - O.Taxes2 from Orders O where O.ID = @ID AND O.Taxes2 <> 0 AND @Type = 'Purchase' ----------------------------------------------------- -- write G/L distribution for payments if required -- ----------------------------------------------------- insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Cash', @Number, O.ID, - O.Payment + O.Change -- alwasy deduct change from any cash from Orders O where O.ID = @ID AND O.Payment <> 0 AND O.Payment_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Debit', @Number, O.ID, - O.Payment1 -- only deduct change when no cash from Orders O where O.ID = @ID AND O.Payment <> 0 AND O.Payment1 <> 0 AND O.Payment1_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment1_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Debit', @Number, O.ID, - O.Payment1 + O.Change -- only deduct change when no cash from Orders O where O.ID = @ID AND O.Payment = 0 AND O.Payment1 <> 0 AND O.Payment1_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment2_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Visa', @Number, O.ID, - O.Payment2 from Orders O where O.ID = @ID AND O.Payment2 <> 0 AND O.Payment2_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment3_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Mastercard', @Number, O.ID, - O.Payment3 from Orders O where O.ID = @ID AND O.Payment3 <> 0 AND O.Payment3_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment4_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Amex', @Number, O.ID, - O.Payment4 from Orders O where O.ID = @ID AND O.Payment4 <> 0 AND O.Payment4_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment5_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Check', @Number, O.ID, - O.Payment5 from Orders O where O.ID = @ID AND O.Payment5 <> 0 AND O.Payment5_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment6_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Other', @Number, O.ID, - O.Payment6 from Orders O where O.ID = @ID AND O.Payment6 <> 0 AND O.Payment6_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment7_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Payment', @Number, O.ID, - O.Payment7 from Orders O where O.ID = @ID AND O.Payment7 <> 0 AND O.Payment7_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment8_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Payment', @Number, O.ID, - O.Payment8 from Orders O where O.ID = @ID AND O.Payment8 <> 0 AND O.Payment8_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment9_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Payment', @Number, O.ID, - O.Payment9 from Orders O where O.ID = @ID AND O.Payment9 <> 0 AND O.Payment9_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) update Ledger set Apply_Sequence = L.Apply_Sequence -- Auto-Apply from Ledger L where ID = @AID if @Release = 1 update Numbers with( HOLDLOCK ) set Date_Locked = Null where [Type] = @Type commit transaction end -- select @GUID = C.[GUID] from Contacts C join Orders O on C.ID = O.Contact_ID AND O.ID = @ID -- execute CalcContactBal @GUID end set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'LockOrderID' AND [Type] = 'P' ) drop procedure dbo.LockOrderID GO create procedure dbo.LockOrderID( @ID int ) as begin set NOCOUNT ON declare @GUID varchar( 100 ) select @GUID = isNull( GUID, '' ) from Orders where ID = @ID AND Date_Locked is Null if @GUID <> '' execute dbo.LockOrder @GUID, 'GetDate()', '' set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'PayLockOrder' AND [Type] = 'P' ) drop procedure dbo.PayLockOrder GO create procedure dbo.PayLockOrder( @GUID varchar( 100 ), @PayIndex int, @Amount decimal( 18, 4 ) ) as begin set NOCOUNT ON if @PayIndex = 0 update Orders set Payment = isNull( NullIF( @Amount, 0 ), Balance ) where [GUID] = @GUID AND Date_Locked is Null else if @PayIndex = 1 update Orders set Payment1 = isNull( NullIF( @Amount, 0 ), Balance ) where [GUID] = @GUID AND Date_Locked is Null else if @PayIndex = 2 update Orders set Payment2 = Balance where [GUID] = @GUID AND Date_Locked is Null else if @PayIndex = 2 update Orders set Payment3 = Balance where [GUID] = @GUID AND Date_Locked is Null else if @PayIndex = 4 update Orders set Payment4 = Balance where [GUID] = @GUID AND Date_Locked is Null else if @PayIndex = 5 update Orders set Payment5 = Balance where [GUID] = @GUID AND Date_Locked is Null else if @PayIndex = 6 update Orders set Payment6 = Balance where [GUID] = @GUID AND Date_Locked is Null else if @PayIndex = 7 update Orders set Payment7 = Balance where [GUID] = @GUID AND Date_Locked is Null else if @PayIndex = 8 update Orders set Payment8 = Balance where [GUID] = @GUID AND Date_Locked is Null else if @PayIndex = 9 update Orders set Payment9 = Balance where [GUID] = @GUID AND Date_Locked is Null execute dbo.LockOrder @GUID, 'GetDate()', '' set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'LockDeposit' AND [Type] = 'P' ) drop procedure dbo.LockDeposit GO create procedure dbo.LockDeposit( @GUID varchar( 100 ), @Date varchar( 100 ), @Number varchar( 100 ) ) as begin set NOCOUNT ON declare @ID int, @LID int, @Type varchar( 100 ), @Release int select @ID = isNull( ID, 0 ) from Orders where [GUID] = @GUID AND Date_Locked is Null select @Type = [Type] from Orders where ID = @ID if @ID <> 0 AND @Type <> 'Estimate' begin set @Release = 0 if isNull( @Number, '' ) = '' AND exists( select * from Numbers where Date_Locked > DateAdd( minute, - 5, GetDate() ) AND [Type] IN ( 'Sale', 'Service' ) ) begin raiserror( 'Warning - Numbers Locked - Try Again', 11, 1 ) rollback end else begin begin transaction if isNull( @Number, '' ) = '' AND @Type IN ( 'Sale', 'Service' ) begin set @Release = 1 update Numbers with( HOLDLOCK ) set Date_Locked = GetDate(), Last_Number = Last_Number + 1 where [Type] = @Type select @Number = Last_Number from Numbers where [Type] = @Type end if CharIndex( 'getdate', Lower( @Date ) ) > 0 select @Date = GetDate() update OrderItems set Back_Order = Quantity, Quantity = 0 --, Date_Locked = @Date where Order_ID = @ID update Orders set Deposit_ID = ID where ID = @ID AND Deposit_ID is Null update Orders set Date_Locked = @Date, Change = 0, Deposit = Paid, Locked_Deposits = Locked_Deposits + Paid, Number = @Number where ID = @ID ----------------------------------------------------- -- write G/L distribution for payments if required -- ----------------------------------------------------- insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Cash', @Number, O.ID, - O.Payment + O.Change -- alwasy deduct change from any cash from Orders O where O.ID = @ID AND O.Payment <> 0 AND O.Payment_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Debit', @Number, O.ID, - O.Payment1 -- only deduct change when no cash from Orders O where O.ID = @ID AND O.Payment <> 0 AND O.Payment1 <> 0 AND O.Payment1_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment1_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Debit', @Number, O.ID, - O.Payment1 + O.Change -- only deduct change when no cash from Orders O where O.ID = @ID AND O.Payment = 0 AND O.Payment1 <> 0 AND O.Payment1_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment2_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Visa', @Number, O.ID, - O.Payment2 from Orders O where O.ID = @ID AND O.Payment2 <> 0 AND O.Payment2_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment3_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Mastercard', @Number, O.ID, - O.Payment3 from Orders O where O.ID = @ID AND O.Payment3 <> 0 AND O.Payment3_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment4_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Amex', @Number, O.ID, - O.Payment4 from Orders O where O.ID = @ID AND O.Payment4 <> 0 AND O.Payment4_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment5_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Check', @Number, O.ID, - O.Payment5 from Orders O where O.ID = @ID AND O.Payment5 <> 0 AND O.Payment5_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment6_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Other', @Number, O.ID, - O.Payment6 from Orders O where O.ID = @ID AND O.Payment6 <> 0 AND O.Payment6_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment7_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Payment', @Number, O.ID, - O.Payment7 from Orders O where O.ID = @ID AND O.Payment7 <> 0 AND O.Payment7_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment8_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Payment', @Number, O.ID, - O.Payment8 from Orders O where O.ID = @ID AND O.Payment8 <> 0 AND O.Payment8_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) insert Ledger ( Account_ID, Cross_Account_ID, Contact_ID, Contact_Name, Order_ID, Date, Reference, Number, Apply_Sequence, Amount ) select O.AR_Account_ID, O.Payment9_Account_ID, O.Contact_ID, O.Name, O.ID, @Date, 'Payment', @Number, O.ID, - O.Payment9 from Orders O where O.ID = @ID AND O.Payment9 <> 0 AND O.Payment9_Account_ID is NOT Null AND @Type IN ( 'Sale', 'Service' ) if @Release = 1 update Numbers with( HOLDLOCK ) set Date_Locked = Null where [Type] = @Type commit transaction end -- select @GUID = C.[GUID] from Contacts C join Orders O on C.ID = O.Contact_ID AND O.ID = @ID -- execute CalcContactBal @GUID end set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'VoidOrder' AND [Type] = 'P' ) drop procedure dbo.VoidOrder GO create procedure dbo.VoidOrder( @GUID varchar( 100 ), @Date varchar( 100 ) ) as begin set NOCOUNT ON begin transaction declare @ID int, @NewID int select @ID = isNull( ID, 0 ) from Orders where GUID = @GUID if CharIndex( 'getdate', Lower( @Date ) ) > 0 select @Date = GetDate() select * into #OldOrder from Orders where Date_Locked is NOT Null AND ID = @ID if exists ( select * from #OldOrder ) begin update #OldOrder set Date_Locked = Null, Date_Voided = Null, GUID = NewID(), BackOrder_ID = @ID, Total = 0, Grand_Total = 0, Taxable_Amount = 0, Taxes = 0, Taxes1 = 0, Taxes2 = 0, Change = 0, Balance = 0, Deposit = 0, Payment = 0, Payment1 = 0, Payment2 = 0, Payment3 = 0, Payment4 = 0, Payment5 = 0, Payment6 = 0, Payment7 = 0, Payment8 = 0, Payment9 = 0, Paid = 0 alter table #OldOrder drop column ID select * into #NewOrder from #OldOrder insert Orders select * from #NewOrder select @NewID = Scope_Identity() drop table #NewOrder select * into #OldItems from OrderItems where Order_ID = @ID if exists ( select * from #OldItems ) begin update #OldItems set Date_Locked = Null, GUID = NewID(), Order_ID = @NewID, Back_Order = 0 alter table #OldItems drop column ID select * into #NewItems from #OldItems insert OrderItems select * from #NewItems drop table #NewItems end drop table #OldItems end drop table #OldOrder update Orders set Date_Voided = @Date, Total = 0, Grand_Total = 0, Taxable_Amount = 0, Taxes = 0, Taxes1 = 0, Taxes2 = 0, Change = 0, Balance = 0, Deposit = 0, Payment = 0, Payment1 = 0, Payment2 = 0, Payment3 = 0, Payment4 = 0, Payment5 = 0, Payment6 = 0, Payment7 = 0, Payment8 = 0, Payment9 = 0, Paid = 0 where Date_Locked is NOT Null AND ID = @ID update OrderItems set Back_Order = Quantity, Quantity = 0, Total = 0 where Date_Locked is NOT Null AND Order_ID = @ID commit transaction set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Orders_Insert' AND [Type] = 'TR' ) drop trigger Orders_Insert GO create trigger Orders_Insert on Orders for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - Orders_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'Orders', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update Orders set Date_Modified = I.Date_Modified from Inserted I join Orders O on O.ID = I.ID set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Orders_Delete' AND [Type] = 'TR' ) drop trigger Orders_Delete GO create trigger Orders_Delete on Orders for delete as begin if @@NESTLEVEL = 1 AND exists( select ID from Deleted where Date_Locked is NOT Null ) begin raiserror( 'Warning - Data is Locked', 11, 1 ) rollback end else if exists( select ID from Deleted where Locked_Deposits > 0 ) begin raiserror( 'Warning - Locked Deposits can not be deleted', 11, 1 ) rollback end -- print 'Debug - Orders_Delete' if exists( select ID from Deleted ) begin set NOCOUNT ON set NOCOUNT OFF end end GO if exists ( select * from sysobjects where [Name] = 'Orders_Update' AND [Type] = 'TR' ) drop trigger Orders_Update GO create trigger Orders_Update on Orders for update as begin if @@NestLevel = 1 AND NOT Update( Balance ) AND exists( select ID from Deleted where Date_Locked is NOT Null ) begin raiserror( 'Warning - Data is Locked', 11, 1 ) rollback end if exists( select ID from Inserted ) begin set NOCOUNT ON if NOT exists( select ID from Inserted where Date_Voided is NOT Null ) begin -- else if ( select Count( Date_Voided ) from Inserted ) = 0 begin -- print 'Debug - Orders_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'Orders', I.ID, I.GUID, Columns_Updated() from Inserted I end if exists( select ID from Numbers where Date_Locked > DateAdd( minute, - 5, GetDate() ) AND [Type] IN ( select distinct I.[Type] from Inserted I where I.[Type] IN ( 'Purchase', 'Adjustment', 'Production' ) AND I.Number is Null ) ) begin raiserror( 'Warning - Numbers Locked - Try Again', 11, 1 ) rollback end else if exists( select I.ID from Inserted I where I.[Type] IN ( 'Purchase', 'Adjustment', 'Production' ) AND I.Number is Null ) begin declare @ID int, @Type varchar( 100 ), @Number varchar( 100 ) declare curNumbers cursor local for select I.ID, I.[Type] from Inserted I where I.[Type] IN ( 'Purchase', 'Adjustment', 'Production' ) AND I.Number is Null open curNumbers fetch curNumbers into @ID, @Type while @@FETCH_STATUS = 0 begin update Numbers with( HOLDLOCK ) set Date_Locked = GetDate(), Last_Number = Last_Number + 1 where [Type] = @Type select @Number = Last_Number from Numbers where [Type] = @Type update Orders set Number = @Number where ID = @ID update Numbers with( HOLDLOCK ) set Date_Locked = Null where [Type] = @Type fetch curNumbers into @ID, @Type end close curNumbers deallocate curNumbers end -- update Orders set Contact_ID = Null where update( [Name] ) -- make sure onetimes don't have any old Contact_ID ------------------------------------------- -- update from Contact Name when changed -- ------------------------------------------- update Orders set Contact_ID = C.ID, [Name] = C.[Name], Main_Contact_Name = C.Main_Contact_Name, Address = C.Address, City = C.City, State_or_Province = C.State_or_Province, Employee = C.Employee, Price_Level = C.Price_Level, Currency = C.Currency, Note = C.Note, Postal_Code = C.Postal_Code, Country = C.Country, Phone = C.Phone, Fax = C.Fax, eMail = C.eMail, Tax_Profile = C.Tax_Profile, Credit_Card = C.Credit_Card, Card_Number = C.Card_Number, Card_Code = C.Card_Code, Card_Expiry = C.Card_Expiry, Late_Notification_List = C.Late_Notification_List, Notify_when_Late_by_Days = C.Notify_when_Late_by_Days, [Group] = C.[Group], Late_Reminder_every_Hours = C.Late_Reminder_every_Hours, [Follow-Up_Notification_List] = C.[Follow-Up_Notification_List], [Follow-Up_every_Days] = C.[Follow-Up_every_Days], [Late_Follow-Up_Reminder_every_Hours] = C.[Late_Follow-Up_Reminder_every_Hours], AR_Account_ID = C.AR_Account_ID, AR_Account = C.AR_Account, AP_Account_ID = C.AP_Account_ID, AP_Account = C.AP_Account, Sales_Account_ID = C.Sales_Account_ID, Sales_Account = C.Sales_Account, Asset_Account_ID = C.Asset_Account_ID, Asset_Account = C.Asset_Account, COGS_Account_ID = C.COGS_Account_ID, COGS_Account = C.COGS_Account, Expense_Account_ID = C.Expense_Account_ID, Expense_Account = C.Expense_Account from Inserted I join Orders O on O.ID = I.ID join Deleted D on D.ID = I.ID join Contacts C on C.[Name] = I.[Name] where ( update( [Name] ) AND NOT update( Phone ) ) OR O.Contact_ID is Null OR I.Date_Modified is Null -- Null indicates a call from the Insert trigger ------------------------------------------------ -- update from Main Contact Name if NOT found ------------------------------------------------ update Orders set Contact_ID = C.ID, [Name] = C.[Name], Main_Contact_Name = C.Main_Contact_Name, Address = C.Address, City = C.City, State_or_Province = C.State_or_Province, Employee = C.Employee, Price_Level = C.Price_Level, Currency = C.Currency, Note = C.Note, Postal_Code = C.Postal_Code, Country = C.Country, Phone = C.Phone, Fax = C.Fax, eMail = C.eMail, Tax_Profile = C.Tax_Profile, Credit_Card = C.Credit_Card, Card_Number = C.Card_Number, Card_Code = C.Card_Code, Card_Expiry = C.Card_Expiry, Late_Notification_List = C.Late_Notification_List, Notify_when_Late_by_Days = C.Notify_when_Late_by_Days, [Group] = C.[Group], Late_Reminder_every_Hours = C.Late_Reminder_every_Hours, [Follow-Up_Notification_List] = C.[Follow-Up_Notification_List], [Follow-Up_every_Days] = C.[Follow-Up_every_Days], [Late_Follow-Up_Reminder_every_Hours] = C.[Late_Follow-Up_Reminder_every_Hours], AR_Account_ID = C.AR_Account_ID, AR_Account = C.AR_Account, AP_Account_ID = C.AP_Account_ID, AP_Account = C.AP_Account, Sales_Account_ID = C.Sales_Account_ID, Sales_Account = C.Sales_Account, Asset_Account_ID = C.Asset_Account_ID, Asset_Account = C.Asset_Account, COGS_Account_ID = C.COGS_Account_ID, COGS_Account = C.COGS_Account, Expense_Account_ID = C.Expense_Account_ID, Expense_Account = C.Expense_Account from Inserted I join Orders O on O.ID = I.ID join Deleted D on D.ID = I.ID join Contacts C on C.Main_Contact_Name = I.[Name] where ( update( Main_Contact_Name ) AND NOT update( [Name] ) ) OR O.Contact_ID is Null ------------------------------------------- -- update from Contact Phone when changed -- ------------------------------------------- update Orders set Contact_ID = C.ID, [Name] = C.[Name], Main_Contact_Name = C.Main_Contact_Name, Address = C.Address, City = C.City, State_or_Province = C.State_or_Province, Employee = C.Employee, Price_Level = C.Price_Level, Currency = C.Currency, Note = C.Note, Postal_Code = C.Postal_Code, Country = C.Country, Phone = C.Phone, Fax = C.Fax, eMail = C.eMail, Tax_Profile = C.Tax_Profile, Credit_Card = C.Credit_Card, Card_Number = C.Card_Number, Card_Code = C.Card_Code, Card_Expiry = C.Card_Expiry, Late_Notification_List = C.Late_Notification_List, Notify_when_Late_by_Days = C.Notify_when_Late_by_Days, [Group] = C.[Group], Late_Reminder_every_Hours = C.Late_Reminder_every_Hours, [Follow-Up_Notification_List] = C.[Follow-Up_Notification_List], [Follow-Up_every_Days] = C.[Follow-Up_every_Days], [Late_Follow-Up_Reminder_every_Hours] = C.[Late_Follow-Up_Reminder_every_Hours], AR_Account_ID = C.AR_Account_ID, AR_Account = C.AR_Account, AP_Account_ID = C.AP_Account_ID, AP_Account = C.AP_Account, Sales_Account_ID = C.Sales_Account_ID, Sales_Account = C.Sales_Account, Asset_Account_ID = C.Asset_Account_ID, Asset_Account = C.Asset_Account, COGS_Account_ID = C.COGS_Account_ID, COGS_Account = C.COGS_Account, Expense_Account_ID = C.Expense_Account_ID, Expense_Account = C.Expense_Account from Inserted I join Orders O on O.ID = I.ID join Deleted D on D.ID = I.ID join Contacts C on C.[Phone] = I.[Phone] where ( update( Phone ) AND NOT update( [Name] ) ) OR O.Contact_ID is Null OR I.Date_Modified is Null -- Null indicates a call from the Insert trigger ------------------------------ -- Update G/L Accounts Info -- ------------------------------ update Orders set AR_Account_ID = ( select A.ID from Accounts A where A.[Name] = O.AR_Account ) from Inserted I join Orders O on O.ID = I.ID where O.AR_Account_ID is Null OR Update( AR_Account ) update Orders set AR_Account = ( select A.[Name] from Accounts A where A.ID = O.AR_Account_ID ) from Inserted I join Orders O on O.ID = I.ID where O.AR_Account is Null OR Update( AR_Account_ID ) update Orders set AP_Account_ID = ( select A.ID from Accounts A where A.[Name] = O.AP_Account ) from Inserted I join Orders O on O.ID = I.ID where O.AP_Account_ID is Null OR Update( AP_Account ) update Orders set AP_Account = ( select A.[Name] from Accounts A where A.ID = O.AP_Account_ID ) from Inserted I join Orders O on O.ID = I.ID where O.AP_Account is Null OR Update( AP_Account_ID ) update Orders set Sales_Account_ID = ( select A.ID from Accounts A where A.[Name] = O.Sales_Account ) from Inserted I join Orders O on O.ID = I.ID where O.Sales_Account_ID is Null OR Update( Sales_Account ) update Orders set Sales_Account = ( select A.[Name] from Accounts A where A.ID = O.Sales_Account_ID ) from Inserted I join Orders O on O.ID = I.ID where O.Sales_Account is Null OR Update( Sales_Account_ID ) update Orders set Expense_Account_ID = ( select A.ID from Accounts A where A.[Name] = O.Expense_Account ) from Inserted I join Orders O on O.ID = I.ID where O.Expense_Account_ID is Null OR Update( Expense_Account ) update Orders set Expense_Account = ( select A.[Name] from Accounts A where A.ID = O.Expense_Account_ID ) from Inserted I join Orders O on O.ID = I.ID where O.Expense_Account is Null OR Update( Expense_Account_ID ) update Orders set Asset_Account_ID = ( select A.ID from Accounts A where A.[Name] = O.Asset_Account ) from Inserted I join Orders O on O.ID = I.ID where O.Asset_Account_ID is Null OR Update( Asset_Account ) update Orders set Asset_Account = ( select A.[Name] from Accounts A where A.ID = O.Asset_Account_ID ) from Inserted I join Orders O on O.ID = I.ID where O.Asset_Account is Null OR Update( Asset_Account_ID ) update Orders set COGS_Account_ID = ( select A.ID from Accounts A where A.[Name] = O.COGS_Account ) from Inserted I join Orders O on O.ID = I.ID where O.COGS_Account_ID is Null OR Update( COGS_Account ) update Orders set COGS_Account = ( select A.[Name] from Accounts A where A.ID = O.COGS_Account_ID ) from Inserted I join Orders O on O.ID = I.ID where O.COGS_Account is Null OR Update( COGS_Account_ID ) ----------------------------------------- -- use default G/L accounts when empty -- ----------------------------------------- update Orders set AR_Account_ID = C.AR_Account_ID, AR_Account = C.AR_Account, AP_Account_ID = C.AP_Account_ID, AP_Account = C.AP_Account, Sales_Account_ID = C.Sales_Account_ID, Sales_Account = C.Sales_Account, Expense_Account_ID = C.Expense_Account_ID, Expense_Account = C.Expense_Account, Asset_Account_ID = C.Asset_Account_ID, Asset_Account = C.Asset_Account, COGS_Account_ID = C.COGS_Account_ID, COGS_Account = C.COGS_Account from Inserted I join Orders O on O.ID = I.ID join Contacts C on C.Company_Configuration = 1 where O.AR_Account_ID is Null AND O.AP_Account_ID is Null AND O.Sales_Account_ID is Null AND O.Expense_Account_ID is Null AND O.Asset_Account_ID is Null AND O.COGS_Account_ID is Null update Orders set Payment_Account_ID = C.Payment_Account_ID, Payment_Account = C.Payment_Account, Payment1_Account_ID = C.Payment1_Account_ID, Payment1_Account = C.Payment1_Account, Payment2_Account_ID = C.Payment2_Account_ID, Payment2_Account = C.Payment2_Account, Payment3_Account_ID = C.Payment3_Account_ID, Payment3_Account = C.Payment3_Account, Payment4_Account_ID = C.Payment4_Account_ID, Payment4_Account = C.Payment4_Account, Payment5_Account_ID = C.Payment5_Account_ID, Payment5_Account = C.Payment5_Account, Payment6_Account_ID = C.Payment6_Account_ID, Payment6_Account = C.Payment6_Account, Payment7_Account_ID = C.Payment7_Account_ID, Payment7_Account = C.Payment7_Account, Payment8_Account_ID = C.Payment8_Account_ID, Payment8_Account = C.Payment8_Account, Payment9_Account_ID = C.Payment9_Account_ID, Payment9_Account = C.Payment9_Account from Inserted I join Orders O on O.ID = I.ID join Contacts C on C.Company_Configuration = 1 where O.Payment_Account_ID is Null ------------------------------------------- -- update from Ship To when changed -- ------------------------------------------ update Orders set Ship_Address = C.Address, Ship_City = C.City, Ship_State_or_Province = C.State_or_Province, Ship_Postal_Code = C.Postal_Code, Ship_Country = C.Country, Ship_Phone = C.Phone, Ship_Fax = C.Fax, Ship_eMail = C.eMail from Inserted I join Orders O on O.ID = I.ID join Deleted D on D.ID = I.ID join Contacts C on C.[Name] = I.[Ship_Name] AND C.Contact_ID = O.Contact_ID where Update( Ship_Name ) OR I.Date_Modified is Null -- Null indicates a call from the Insert trigger -------------------------------- -- update Employee and Totals -- -------------------------------- update Orders set Employee_ID = C.ID from Inserted I join Orders O on O.ID = I.ID join Contacts C on C.[Name] = O.[Employee] update Orders set Total = isNull( ( select Sum( isNull( L.Total - L.Discount_Amount, 0 ) ) from OrderItems L where L.Order_ID = I.ID AND L.[Type] <> 'Manufacturing' ), 0 ) from Inserted I join Orders O on O.ID = I.ID where I.Date_Locked is NOT Null OR I.Total = 0 -- use as flag to recalc totals update Orders set Taxable_Amount = isNull( ( select Sum( isNull( L.Total - L.Discount_Amount, 0 ) ) from OrderItems L where L.Order_ID = I.ID AND L.[Type] <> 'Manufacturing' AND L.Taxable = 1 ), 0 ) from Inserted I join Orders O on O.ID = I.ID where I.Date_Locked is NOT Null OR I.Total = 0 -- use as flag to recalc totals update Orders set Percent_Discount = 0 from Inserted I join Orders O on O.ID = I.ID where Update( Discount_Amount ) update Orders set Discount_Amount = isNull( Round( O.Total * O.Percent_Discount / 100, 2 ), 0 ) from Inserted I join Orders O on O.ID = I.ID where I.Total = 0 OR Update( Percent_Discount ) OR O.Percent_Discount <> 0 update Orders set Taxes = dbo.Sales_Tax( isNull( O.Date_Locked, GetDate() ), isNull( O.Tax_Profile, '' ), O.Taxable_Amount - O.Discount_Amount, 0 ), Taxes1 = dbo.Sales_Tax( isNull( O.Date_Locked, GetDate() ), isNull( O.Tax_Profile, '' ), O.Taxable_Amount - O.Discount_Amount, 1 ), Taxes2 = dbo.Sales_Tax( isNull( O.Date_Locked, GetDate() ), isNull( O.Tax_Profile, '' ), O.Taxable_Amount - O.Discount_Amount, 2 ) from Inserted I join Orders O on O.ID = I.ID update Orders set Grand_Total = O.Total - O.Discount_Amount + O.Taxes, Paid = O.Payment + O.Payment1 + O.Payment2 + O.Payment3 + O.Payment4 + O.Payment5 + O.Payment6 + O.Payment7 + O.Payment8 + O.Payment9 from Inserted I join Orders O on O.ID = I.ID update Orders set Balance = O.Grand_Total - O.Locked_Deposits, Change = 0 from Inserted I join Orders O on O.ID = I.ID where O.Type IN ( 'Sale', 'Service' ) AND O.Paid = 0 -- when no payment allow a negative balance for credits update Orders set Balance = dbo.Maximum( 0.0, O.Grand_Total - O.Locked_Deposits - O.Paid ) from Inserted I join Orders O on O.ID = I.ID where O.Type IN ( 'Sale', 'Service' ) AND O.Paid <> 0 -- when a payment is entered then assume a negative balance is change update Orders set Change = dbo.Maximum( 0.0, - O.Grand_Total + O.Locked_Deposits + O.Paid ) from Inserted I join Orders O on O.ID = I.ID where O.Type IN ( 'Sale', 'Service' ) AND O.Paid <> 0 AND O.Locked_Deposits <> O.Paid AND ( O.Payment <> 0 OR O.Payment1 <> 0 ) AND O.Grand_Total <> 0 -- Give Change only on Cash or Debit payments if Total <> 0 --------------------------------------------------------------------------------- -- check for Onetime, Credit Limit, Inactive or Hold Status and Update Contact -- --------------------------------------------------------------------------------- if exists ( select C.ID from Inserted I join Orders O on O.ID = I.ID join Contacts C on C.ID = O.Contact_ID where I.Date_Locked is NOT Null AND O.Balance > 0 AND C.Credit_Limit > 0 AND C.Credit_Limit < C.Balance + O.Balance ) begin raiserror( 'Warning - Contact is over its Credit Limit', 11, 1 ) rollback -- print 'Contact is over its Credit Limit' end if exists ( select C.ID from Inserted I join Orders O on O.ID = I.ID join Contacts C on C.ID = O.Contact_ID where C.Active = 0 OR C.Hold_All_Activity = 1 ) begin raiserror( 'Warning - Contact is not Active or Hold All Activity is True', 11, 1 ) rollback end if @@NESTLEVEL = 1 update Contacts set Avg_Amount_per_Month = 0 from Inserted I join Orders O on O.ID = I.ID AND O.Date_Locked is NOT Null join Contacts C on C.ID = O.Contact_ID ---------------------------------- -- Update children when changed -- ---------------------------------- -- if @@NESTLEVEL = 1 begin if NOT Update( Date_Modified ) AND NOT Update( Total ) AND ( Update( Date_Locked ) OR Update( [Type] ) OR Update( [Name] ) OR Update( Number ) OR Update( Reference ) OR Update( Contact_ID ) ) begin update OrderItems set Date_Locked = I.Date_Locked, [Type] = I.[Type], Order_Name = I.[Name], Number = I.Number, Reference = I.Reference, Contact_ID = I.Contact_ID from Inserted I join OrderItems L on L.Order_ID = I.ID where L.[Type] <> 'Manufacturing' -- mfg level inherits from its parent line item end -- end ----------------------------------------------- -- create Back Orders when Locking the order -- ----------------------------------------------- update Orders set Has_Back_Orders = isNull( ( select Sum( isNull( Back_Order, 0 ) ) from OrderItems L where L.Order_ID = I.ID AND L.[Type] <> 'Manufacturing' ), 0 ) from Inserted I join Orders O on O.ID = I.ID if NOT Update( Total ) AND exists ( select I.ID from Inserted I join Orders O on O.ID = I.ID where O.Has_Back_Orders = 1 AND O.Date_Locked is NOT Null ) begin -- create back Orders SET IDENTITY_INSERT BackOrders ON insert BackOrders ( ID, GUID, BackOrder_ID, Deposit_ID, Contact_ID, Main_Contact_ID, Employee_ID, Sales_Account_ID, AR_Account_ID, AP_Account_ID, Asset_Account_ID, COGS_Account_ID, Expense_Account_ID, Payment_Account_ID, Payment1_Account_ID, Payment2_Account_ID, Payment3_Account_ID, Payment4_Account_ID, Payment5_Account_ID, Payment6_Account_ID, Payment7_Account_ID, Payment8_Account_ID, Payment9_Account_ID, Version, Date_Created, Date_Modified, Date_Locked, Date_Voided, Date_Printed, Date_Required, ServerName, WorkStation, UserName, [Type], [Group], Repeat_Frequency, Employee, Number, Reference, Referred_by, [Name], Main_Contact_Name, Address, City, State_or_Province, Postal_Code, Country, Phone, Fax, eMail, Ship_Name, Ship_Address, Ship_City, Ship_State_or_Province, Ship_Postal_Code, Ship_Country, Ship_Phone, Ship_Fax, Ship_eMail, Credit_Card, Card_Number, Card_Expiry, Card_Code, Sales_Account, AR_Account, AP_Account, Asset_Account, COGS_Account, Expense_Account, Payment_Account, Payment1_Account, Payment2_Account, Payment3_Account, Payment4_Account, Payment5_Account, Payment6_Account, Payment7_Account, Payment8_Account, Payment9_Account, Price_Level, Tax_Profile, Currency, Grand_Total, Total, Taxable_Amount, Taxes, Taxes1, Taxes2, Payment, Payment1, Payment2, Payment3, Payment4, Payment5, Payment6, Payment7, Payment8, Payment9, Paid, Change, Deposit, Locked_Deposits, Balance, Change_Notification_List, Notification_Condition, Late_Notification_List, Notify_when_Late_by_Days, Late_Reminder_every_Hours, [Follow-Up_Notification_List], [Follow-Up_every_Days], [Late_Follow-Up_Reminder_every_Hours], [Date_Last_Follow-Up_Done], Note, Has_Back_Orders, Auto_Generated, Audio, Video ) select O.ID, O.GUID, O.BackOrder_ID, O.Deposit_ID, O.Contact_ID, O.Main_Contact_ID, O.Employee_ID, O.Sales_Account_ID, O.AR_Account_ID, O.AP_Account_ID, O.Asset_Account_ID, O.COGS_Account_ID, O.Expense_Account_ID, O.Payment_Account_ID, O.Payment1_Account_ID, O.Payment2_Account_ID, O.Payment3_Account_ID, O.Payment4_Account_ID, O.Payment5_Account_ID, O.Payment6_Account_ID, O.Payment7_Account_ID, O.Payment8_Account_ID, O.Payment9_Account_ID, O.Version, O.Date_Created, O.Date_Modified, O.Date_Locked, O.Date_Voided, O.Date_Printed, O.Date_Required, O.ServerName, O.WorkStation, O.UserName, O.[Type], O.[Group], O.Repeat_Frequency, O.Employee, O.Number, O.Reference, O.Referred_by, O.[Name], O.Main_Contact_Name, O.Address, O.City, O.State_or_Province, O.Postal_Code, O.Country, O.Phone, O.Fax, O.eMail, O.Ship_Name, O.Ship_Address, O.Ship_City, O.Ship_State_or_Province, O.Ship_Postal_Code, O.Ship_Country, O.Ship_Phone, O.Ship_Fax, O.Ship_eMail, O.Credit_Card, O.Card_Number, O.Card_Expiry, O.Card_Code, O.Sales_Account, O.AR_Account, O.AP_Account, O.Asset_Account, O.COGS_Account, O.Expense_Account, O.Payment_Account, O.Payment1_Account, O.Payment2_Account, O.Payment3_Account, O.Payment4_Account, O.Payment5_Account, O.Payment6_Account, O.Payment7_Account, O.Payment8_Account, O.Payment9_Account, O.Price_Level, O.Tax_Profile, O.Currency, O.Grand_Total, O.Total, O.Taxable_Amount, O.Taxes, O.Taxes1, O.Taxes2, O.Payment, O.Payment1, O.Payment2, O.Payment3, O.Payment4, O.Payment5, O.Payment6, O.Payment7, O.Payment8, O.Payment9, O.Paid, O.Change, O.Deposit, O.Locked_Deposits, O.Balance, O.Change_Notification_List, O.Notification_Condition, O.Late_Notification_List, O.Notify_when_Late_by_Days, O.Late_Reminder_every_Hours, O.[Follow-Up_Notification_List], O.[Follow-Up_every_Days], O.[Late_Follow-Up_Reminder_every_Hours], O.[Date_Last_Follow-Up_Done], O.Note, O.Has_Back_Orders, O.Auto_Generated, O.Audio, O.Video from Orders O join Inserted I on O.ID = I.ID where O.Has_Back_Orders = 1 AND O.Date_Locked is NOT Null SET IDENTITY_INSERT BackOrders OFF update BackOrders set Number = Null where [Type] IN ( 'Sale', 'Service' ) update BackOrders set Date_Required = DateAdd( Year, 1, Date_Locked ) where Repeat_Frequency = 'Yearly' update BackOrders set Date_Required = DateAdd( Quarter, 1, Date_Locked ) where Repeat_Frequency = 'Quaterly' update BackOrders set Date_Required = DateAdd( Month, 1, Date_Locked ) where Repeat_Frequency = 'Monthly' update BackOrders set Date_Required = DateAdd( Week, 1, Date_Locked ) where Repeat_Frequency = 'Weekly' update BackOrders set Date_Required = DateAdd( Day, 1, Date_Locked ) where Repeat_Frequency = 'Daily' update BackOrders set Date_Locked = Null, GUID = NewID(), BackOrder_ID = ID, Change = 0, Balance = 0, Deposit = 0, Payment = 0, Payment1 = 0, Payment2 = 0, Payment3 = 0, Payment4 = 0, Payment5 = 0, Payment6 = 0, Payment7 = 0, Payment8 = 0, Payment9 = 0 insert Orders ( GUID, BackOrder_ID, Deposit_ID, Contact_ID, Main_Contact_ID, Employee_ID, Sales_Account_ID, AR_Account_ID, AP_Account_ID, Asset_Account_ID, COGS_Account_ID, Expense_Account_ID, Payment_Account_ID, Payment1_Account_ID, Payment2_Account_ID, Payment3_Account_ID, Payment4_Account_ID, Payment5_Account_ID, Payment6_Account_ID, Payment7_Account_ID, Payment8_Account_ID, Payment9_Account_ID, Version, Date_Created, Date_Modified, Date_Locked, Date_Voided, Date_Printed, Date_Required, ServerName, WorkStation, UserName, [Type], [Group], Repeat_Frequency, Employee, Number, Reference, Referred_by, [Name], Main_Contact_Name, Address, City, State_or_Province, Postal_Code, Country, Phone, Fax, eMail, Ship_Name, Ship_Address, Ship_City, Ship_State_or_Province, Ship_Postal_Code, Ship_Country, Ship_Phone, Ship_Fax, Ship_eMail, Credit_Card, Card_Number, Card_Expiry, Card_Code, Sales_Account, AR_Account, AP_Account, Asset_Account, COGS_Account, Expense_Account, Payment_Account, Payment1_Account, Payment2_Account, Payment3_Account, Payment4_Account, Payment5_Account, Payment6_Account, Payment7_Account, Payment8_Account, Payment9_Account, Price_Level, Tax_Profile, Currency, Grand_Total, Total, Taxable_Amount, Taxes, Taxes1, Taxes2, Payment, Payment1, Payment2, Payment3, Payment4, Payment5, Payment6, Payment7, Payment8, Payment9, Paid, Change, Deposit, Locked_Deposits, Balance, Change_Notification_List, Notification_Condition, Late_Notification_List, Notify_when_Late_by_Days, Late_Reminder_every_Hours, [Follow-Up_Notification_List], [Follow-Up_every_Days], [Late_Follow-Up_Reminder_every_Hours], [Date_Last_Follow-Up_Done], Note, Has_Back_Orders, Auto_Generated, Audio, Video ) select GUID, BackOrder_ID, Deposit_ID, Contact_ID, Main_Contact_ID, Employee_ID, Sales_Account_ID, AR_Account_ID, AP_Account_ID, Asset_Account_ID, COGS_Account_ID, Expense_Account_ID, Payment_Account_ID, Payment1_Account_ID, Payment2_Account_ID, Payment3_Account_ID, Payment4_Account_ID, Payment5_Account_ID, Payment6_Account_ID, Payment7_Account_ID, Payment8_Account_ID, Payment9_Account_ID, Version, Date_Created, Date_Modified, Date_Locked, Date_Voided, Date_Printed, Date_Required, ServerName, WorkStation, UserName, [Type], [Group], Repeat_Frequency, Employee, Number, Reference, Referred_by, [Name], Main_Contact_Name, Address, City, State_or_Province, Postal_Code, Country, Phone, Fax, eMail, Ship_Name, Ship_Address, Ship_City, Ship_State_or_Province, Ship_Postal_Code, Ship_Country, Ship_Phone, Ship_Fax, Ship_eMail, Credit_Card, Card_Number, Card_Expiry, Card_Code, Sales_Account, AR_Account, AP_Account, Asset_Account, COGS_Account, Expense_Account, Payment_Account, Payment1_Account, Payment2_Account, Payment3_Account, Payment4_Account, Payment5_Account, Payment6_Account, Payment7_Account, Payment8_Account, Payment9_Account, Price_Level, Tax_Profile, Currency, Grand_Total, Total, Taxable_Amount, Taxes, Taxes1, Taxes2, Payment, Payment1, Payment2, Payment3, Payment4, Payment5, Payment6, Payment7, Payment8, Payment9, Paid, Change, Deposit, Locked_Deposits, Balance, Change_Notification_List, Notification_Condition, Late_Notification_List, Notify_when_Late_by_Days, Late_Reminder_every_Hours, [Follow-Up_Notification_List], [Follow-Up_every_Days], [Late_Follow-Up_Reminder_every_Hours], [Date_Last_Follow-Up_Done], Note, Has_Back_Orders, Auto_Generated, Audio, Video from BackOrders -- create back Order Items SET IDENTITY_INSERT BackOrderItems ON insert BackOrderItems ( ID, GUID, Order_ID, Contact_ID, Mfg_Contact_ID, Employee_ID, Resource_ID, Template_ID, Serial_ID, OrderItem_ID, BackOrderItem_ID, Component_ID, Sales_Account_ID, Asset_Account_ID, COGS_Account_ID, Expense_Account_ID, Version, Date_Created, Date_Modified, Date_Locked, Date_Voided, Date_Required, ServerName, WorkStation, UserName, [Type], Order_Name, Number, Reference, Sequence, Resource_Name, Resource_Code, Resource_UPC, Reference_Code, Serial_or_Lot_Number, Template_Name, Contact_Name, Date_Start, Date_Stop, Unit, Unit_Conversion, Quantity, Unit_Quantity, Unit_Price, Back_Order, Hours, Price, Landed_Price, Taxable, Made_to_Order, Total, Balance, Avg_Cost, Variation, Variations_List, [Sub-Variations_List], Default_Index, Sales_Account, Asset_Account, COGS_Account, Expense_Account, Tree_Path, Note, Audio, Video, Photo1, Photo1Thumb, Photo1Name, Photo2, Photo2Thumb, Photo2Name, Photo3, Photo3Thumb, Photo3Name, Photo4, Photo4Thumb, Photo4Name, Photo5, Photo5Thumb, Photo5Name, Photo6, Photo6Thumb, Photo6Name, Photo7, Photo7Thumb, Photo7Name, Photo8, Photo8Thumb, Photo8Name, Photo9, Photo9Thumb, Photo9Name ) select L.ID, L.GUID, L.Order_ID, L.Contact_ID, L.Mfg_Contact_ID, L.Employee_ID, L.Resource_ID, L.Template_ID, L.Serial_ID, L.OrderItem_ID, L.BackOrderItem_ID, L.Component_ID, L.Sales_Account_ID, L.Asset_Account_ID, L.COGS_Account_ID, L.Expense_Account_ID, L.Version, L.Date_Created, L.Date_Modified, L.Date_Locked, L.Date_Voided, L.Date_Required, L.ServerName, L.WorkStation, L.UserName, L.[Type], L.Order_Name, L.Number, L.Reference, L.Sequence, L.Resource_Name, L.Resource_Code, L.Resource_UPC, L.Reference_Code, L.Serial_or_Lot_Number, L.Template_Name, L.Contact_Name, L.Date_Start, L.Date_Stop, L.Unit, L.Unit_Conversion, L.Quantity, L.Unit_Quantity, L.Unit_Price, L.Back_Order, L.Hours, L.Price, L.Landed_Price, L.Taxable, L.Made_to_Order, L.Total, L.Balance, L.Avg_Cost, L.Variation, L.Variations_List, L.[Sub-Variations_List], L.Default_Index, L.Sales_Account, L.Asset_Account, L.COGS_Account, L.Expense_Account, L.Tree_Path, L.Note, L.Audio, L.Video, L.Photo1, L.Photo1Thumb, L.Photo1Name, L.Photo2, L.Photo2Thumb, L.Photo2Name, L.Photo3, L.Photo3Thumb, L.Photo3Name, L.Photo4, L.Photo4Thumb, L.Photo4Name, L.Photo5, L.Photo5Thumb, L.Photo5Name, L.Photo6, L.Photo6Thumb, L.Photo6Name, L.Photo7, L.Photo7Thumb, L.Photo7Name, L.Photo8, L.Photo8Thumb, L.Photo8Name, L.Photo9, L.Photo9Thumb, L.Photo9Name from OrderItems L join Inserted I on I.ID = L.Order_ID AND L.Back_Order <> 0 SET IDENTITY_INSERT BackOrderItems OFF update BackOrderItems set BackOrderItem_ID = BackOrderItems.ID, GUID = NewID(), Order_ID = O.ID, Date_Locked = Null, Quantity = Back_Order, Back_Order = 0, Note = cast( O.Date_Locked as varchar( 100 ) ) from Orders O where O.BackOrder_ID = Order_ID insert OrderItems ( GUID, Order_ID, Contact_ID, Mfg_Contact_ID, Employee_ID, Resource_ID, Template_ID, Serial_ID, OrderItem_ID, BackOrderItem_ID, Component_ID, Sales_Account_ID, Asset_Account_ID, COGS_Account_ID, Expense_Account_ID, Version, Date_Created, Date_Modified, Date_Locked, Date_Voided, Date_Required, ServerName, WorkStation, UserName, [Type], Order_Name, Number, Reference, Sequence, Resource_Name, Resource_Code, Resource_UPC, Reference_Code, Serial_or_Lot_Number, Template_Name, Contact_Name, Date_Start, Date_Stop, Unit, Quantity, Back_Order, Hours, Price, Landed_Price, Taxable, Made_to_Order, Total, Balance, Avg_Cost, Variation, Variations_List, [Sub-Variations_List], Default_Index, Sales_Account, Asset_Account, COGS_Account, Expense_Account, Tree_Path, Note, Audio, Video, Photo1, Photo1Thumb, Photo1Name, Photo2, Photo2Thumb, Photo2Name, Photo3, Photo3Thumb, Photo3Name, Photo4, Photo4Thumb, Photo4Name, Photo5, Photo5Thumb, Photo5Name, Photo6, Photo6Thumb, Photo6Name, Photo7, Photo7Thumb, Photo7Name, Photo8, Photo8Thumb, Photo8Name, Photo9, Photo9Thumb, Photo9Name ) select GUID, Order_ID, Contact_ID, Mfg_Contact_ID, Employee_ID, Resource_ID, Template_ID, Serial_ID, OrderItem_ID, BackOrderItem_ID, Component_ID, Sales_Account_ID, Asset_Account_ID, COGS_Account_ID, Expense_Account_ID, Version, Date_Created, Date_Modified, Date_Locked, Date_Voided, Date_Required, ServerName, WorkStation, UserName, [Type], Order_Name, Number, Reference, Sequence, Resource_Name, Resource_Code, Resource_UPC, Reference_Code, Serial_or_Lot_Number, Template_Name, Contact_Name, Date_Start, Date_Stop, Unit, Quantity, Back_Order, Hours, Price, Landed_Price, Taxable, Made_to_Order, Total, Balance, Avg_Cost, Variation, Variations_List, [Sub-Variations_List], Default_Index, Sales_Account, Asset_Account, COGS_Account, Expense_Account, Tree_Path, Note, Audio, Video, Photo1, Photo1Thumb, Photo1Name, Photo2, Photo2Thumb, Photo2Name, Photo3, Photo3Thumb, Photo3Name, Photo4, Photo4Thumb, Photo4Name, Photo5, Photo5Thumb, Photo5Name, Photo6, Photo6Thumb, Photo6Name, Photo7, Photo7Thumb, Photo7Name, Photo8, Photo8Thumb, Photo8Name, Photo9, Photo9Thumb, Photo9Name from BackOrderItems delete BackOrders delete BackOrderItems end -- ---------------------------------- -- -- Update children when changed -- MOVED BEFORE BACK ORDER CODE -- ---------------------------------- -- -- if @@NESTLEVEL = 1 begin -- if NOT Update( Date_Modified ) AND -- ( Update( Date_Locked ) OR Update( [Type] ) OR Update( [Name] ) OR Update( Number ) OR -- Update( Reference ) OR Update( Contact_ID ) ) begin -- update OrderItems set Date_Locked = I.Date_Locked, [Type] = I.[Type], Order_Name = I.[Name], -- Number = I.Number, Reference = I.Reference, Contact_ID = I.Contact_ID -- from Inserted I join OrderItems L on L.Order_ID = I.ID where L.[Type] <> 'Manufacturing' -- mfg level inherits from its parent line item -- end -- -- end ------------------------------------------ -- Calculate Running Balances when Locked ------------------------------------------ declare @@GUID_List varchar( 4000 ), @@StartDate varchar( 100 ) select @@StartDate = Min( I.Date_Locked ) from Inserted I join OrderItems L on L.Order_ID = I.ID join Resources R on R.ID = L.Resource_ID where I.Date_Locked is NOT Null select @@GUID_List = Coalesce( @@GUID_List + ',', '' ) + Cast( R.GUID as varchar( 100 ) ) from Inserted I join OrderItems L on L.Order_ID = I.ID join Resources R on R.ID = L.Resource_ID where I.Date_Locked is NOT Null if @@GUID_List <> '' exec dbo.CalcBalance @@GUID_List, @@StartDate ------------------------------------ -- Add any required Notifications -- ------------------------------------ insert Notifications ( Table_Name, Table_ID, Notification_List, Subject, Body ) select 'Orders', O.ID, O.Change_Notification_List, 'Alert on ' + O.[Name], 'select ' + dbo.ModColList( 'Orders', Columns_Updated() ) + ' from Orders where ID = ' + Cast( I.ID as varchar( 10 ) ) from Inserted I join Orders O on O.ID = I.ID where O.Change_Notification_List is NOT Null AND O.Notification_Condition is Null AND O.Date_Locked is Null if ( select Count( ID ) from Inserted where Change_Notification_List is NOT Null AND Notification_Condition is NOT Null ) > 0 begin declare @Cmd varchar( 4000 ), @CurID varchar( 10 ), @Name varchar( 50 ), @Notify varchar( 500 ), @Condition varchar( 500 ) declare CurRec cursor local for select ID, [Name], Change_Notification_List, Notification_Condition from Inserted where Change_Notification_List is NOT Null AND Notification_Condition is NOT Null open CurRec fetch CurRec into @CurID, @Name, @Notify, @Condition while @@FETCH_STATUS = 0 begin select @Cmd = 'if exists( select ID from Orders where ID = ' + @CurID + ' AND ' + @Condition + ' ) ' + 'insert Notifications ( Table_Name, Table_ID, Notification_List, Subject, Body ) ' + 'values( ''Orders'', ' + @CurID + ', ''' + @Notify + ''', ''' + @Condition + ' on ' + rTrim( @Name ) + ''', ' + '''select ' + Replace( dbo.ModColList( 'Orders', Columns_Updated() ), '''', '''''' ) + ' from Orders where ID = ' + @CurID + ''' )' exec( @Cmd ) fetch CurRec into @CurID, @Name, @Notify, @Condition end close CurRec deallocate CurRec end ------------------------------------------------------------------------------------------------------------------ -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- ------------------------------------------------------------------------------------------------------------------ update Orders set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Inserted I join Orders O on O.ID = I.ID end set NOCOUNT OFF end end GO ---------------- -- OrderItems -- ---------------- if exists ( select * from sysobjects where [Name] = 'PriceLevel' AND [Type] = 'FN' ) drop function dbo.PriceLevel GO create function dbo.PriceLevel( @ID int, @Level char( 1 ) ) returns decimal( 18, 4 ) begin declare @Result decimal( 18, 4 ) select @Result = 0 if @Level = '1' select @Result = Price1 from Resources where ID = @ID else if @Level = '2' select @Result = Price2 from Resources where ID = @ID else if @Level = '3' select @Result = Price3 from Resources where ID = @ID else if @Level = '4' select @Result = Price4 from Resources where ID = @ID else if @Level = '5' select @Result = Price5 from Resources where ID = @ID else if @Level = '6' select @Result = Price6 from Resources where ID = @ID else if @Level = '7' select @Result = Price7 from Resources where ID = @ID else if @Level = '8' select @Result = Price8 from Resources where ID = @ID else if @Level = '9' select @Result = Price9 from Resources where ID = @ID return isNull( NullIF( @Result, 0 ), ( select Price from Resources where ID = @ID ) ) end GO if exists ( select * from sysobjects where [Name] = 'AddComponents' AND [Type] = 'P' ) drop procedure dbo.AddComponents GO if exists ( select * from sysobjects where [Name] = 'DefaultQty' AND [Type] = 'FN' ) drop function dbo.DefaultQty GO create function dbo.DefaultQty( @Index1 int, @Index2 int, @Qty decimal( 18, 4 ) ) returns decimal( 18, 4 ) begin declare @Result decimal( 18, 4 ) select @Result = 0.0 if @Index1 = @Index2 select @Result = @Qty return @Result end GO -- TODO WE CAN STILL ADD RECORDS TO A LOCKED PARENT if exists ( select * from sysobjects where [Name] = 'OrderItems_Insert' AND [Type] = 'TR' ) drop trigger OrderItems_Insert GO create trigger OrderItems_Insert on OrderItems for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON if exists( select O.ID from Inserted I join Orders O on O.ID = I.Order_ID where O.[Type] <> 'Adjustment' AND O.Date_Locked is NOT Null ) begin raiserror( 'Warning - Parent Order is Locked', 11, 1 ) rollback end else begin -- print 'Debug - OrderItems_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'OrderItems', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------- -- Make sure it has a parent order -- ------------------------------------- insert Orders ( Contact_ID, [Type], [Name] ) select I.Contact_ID, I.[Type], C.[Name] from Inserted I join Contacts C on C.ID = I.Contact_ID OR C.[Name] = I.Contact_Name where I.Order_ID is Null AND ( I.Contact_ID is NOT Null OR I.Contact_Name is NOT Null ) AND NOT exists( select O.ID from Orders O where ( O.Contact_ID = I.Contact_ID OR O.[Name] = I.Contact_Name ) AND O.[Type] = I.[Type] AND O.Date_Locked is Null AND O.Date_Printed is Null ) insert Orders ( [Type], [Name] ) select I.[Type], 'Onetime' from Inserted I where I.Order_ID is Null AND I.Contact_ID is Null AND I.Contact_Name is Null AND NOT exists( select O.ID from Orders O where ( O.[Name] = 'OneTime' ) AND O.[Type] = I.[Type] AND O.Date_Locked is Null AND O.Date_Printed is Null ) ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update OrderItems set Date_Modified = Null, Order_ID = O.ID from Inserted I join OrderItems L on L.ID = I.ID join Orders O on ( O.Contact_ID = I.Contact_ID OR O.[Name] = I.Contact_Name OR O.[Name] = 'OneTime' ) AND O.[Type] = I.[Type] AND O.Date_Locked is Null AND O.Date_Printed is Null where I.Order_ID is Null -- attach to order just added update OrderItems set Date_Modified = I.Date_Modified from Inserted I join OrderItems L on L.ID = I.ID where I.Order_ID is NOT Null -- already attached to an order ---------------------------------------------- -- add all Components necessary to manufacture -- DOES NOT WORK WHEN IDENTITY INSERT IS ON ??? ---------------------------------------------- insert OrderItems ( OrderItem_ID, Order_ID, Component_ID, Mfg_Contact_ID, Date_Required, [Type], Order_Name, [Sequence], Contact_Name, Quantity, Hours, Resource_ID, Resource_Name, Resource_Code, Resource_UPC, Avg_Cost, Variations_List, [Sub-Variations_List], Default_Index, Note, Audio, Video ) select L.ID, L.Order_ID, C.ID, C.Contact_ID, L.Date_Required, 'Manufacturing', L.Order_Name, C.[Sequence], C.Contact_Name, L.Quantity * isNull( NullIF( C.Units_Required, 0 ), isNull( NullIF( C.Hours_Required, 0 ), C.Percent_Required / 100 ) ), isNull( L.Quantity, 1 ) * C.Hours_Required, C.Component_ID, C.Resource_Name, R.[Code], R.[UPC], R.Avg_Cost, R.Variations_List, R.[Sub-Variations_List], L.Default_Index, C.Note, C.Audio, C.Video from Inserted I join OrderItems L on L.ID = I.ID join Components C on C.Resource_ID = L.Resource_ID left join Resources R on R.ID = C.Component_ID where L.[Type] IN ( 'Sale', 'Service', 'Production' ) ------------------------------------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire for the OrderItems just added -- ------------------------------------------------------------------------------------------- update OrderItems set Date_Modified = I.Date_Modified from Inserted I join OrderItems L on L.OrderItem_ID = I.ID end set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'OrderItems_Delete' AND [Type] = 'TR' ) drop trigger OrderItems_Delete GO create trigger OrderItems_Delete on OrderItems for Delete as begin if @@NestLevel = 1 AND exists( select ID from Deleted where Date_Locked is NOT Null ) begin raiserror( 'Warning - Data is Locked', 11, 1 ) rollback end if exists( select ID from Deleted ) begin set NOCOUNT ON -- print 'Debug - OrderItems_Delete' --------------------------------- -- delete any Order Item Contacts --------------------------------- delete Contacts from Deleted D join Contacts C on C.OrderItem_ID = D.ID ---------------------------------------------------------------- -- save Parent Order IDs and Resource IDs of Resources to update ---------------------------------------------------------------- declare @@OID_List varchar( 8000 ), @@RID_List varchar( 8000 ) select @@OID_List = Coalesce( @@OID_List + ',', '' ) + cast( O.ID as varchar( 20 ) ) from Deleted D join Orders O on O.ID = D.Order_ID select @@RID_List = Coalesce( @@RID_List + ',', '' ) + cast( R.ID as varchar( 20 ) ) from Deleted D join Resources R on R.ID = D.Resource_ID ---------------------------------------------------- -- save Order IDs then delete Auto-POs of Components ---------------------------------------------------- select @@OID_List = Coalesce( @@OID_List + ',', '' ) + cast( O.ID as varchar( 20 ) ) from Deleted D join OrderItems C on C.OrderItem_ID = D.ID AND C.Date_locked is Null join OrderItems L on L.OrderItem_ID = C.ID AND L.Date_locked is Null join Orders O on O.ID = L.Order_ID AND O.Date_locked is Null delete L from Deleted D join OrderItems C on C.OrderItem_ID = D.ID AND C.Date_Locked is Null join OrderItems L on L.OrderItem_ID = C.ID AND L.Date_Locked is Null ------------------------------------------------------------------------------------------------ -- save Order IDs of Auto-POs, and Resource IDs of Resources of Components then delete them both ------------------------------------------------------------------------------------------------ select @@OID_List = Coalesce( @@OID_List + ',', '' ) + cast( O.ID as varchar( 20 ) ) from Deleted D join OrderItems L on L.OrderItem_ID = D.ID AND L.Date_locked is Null join Orders O on O.ID = L.Order_ID AND O.Date_locked is Null where L.[Type] = 'Purchase' select @@RID_List = Coalesce( @@RID_List + ',', '' ) + cast( R.ID as varchar( 20 ) ) from Deleted D join OrderItems L on L.OrderItem_ID = D.ID AND L.Date_locked is Null join Resources R on R.ID = L.Resource_ID where L.[Type] = 'Manufacturing' delete OrderItems from Deleted D join OrderItems L on L.OrderItem_ID = D.ID AND L.Date_Locked is Null ------------------------------------------------------------------------ -- update Resource Counters and Orders Totals of Auto-POs and Components ------------------------------------------------------------------------ update Resources set Units_Required = - 1, Units_Ordered = - 1 from Resources R join dbo.ListAsIntTable( @@RID_List ) L on L.ID = R.ID update Orders set Total = 0, Taxable_Amount = 0 from Orders O join dbo.ListAsIntTable( @@OID_List ) L on L.ID = O.ID set NOCOUNT OFF end end GO if exists ( select * from sysobjects where [Name] = 'OrderItems_Update' AND [Type] = 'TR' ) drop trigger OrderItems_Update GO create trigger OrderItems_Update on OrderItems for update as begin if @@NestLevel = 1 AND NOT Update( Balance ) AND exists( select ID from Deleted where Date_Locked is NOT Null ) begin raiserror( 'Warning - Data is Locked', 11, 1 ) rollback end if NOT exists( select ID from Inserted ) OR ( Update( Balance ) AND exists( select ID from Deleted where Date_Locked is NOT Null ) ) OR Update( Photo1 ) OR Update( Photo2 ) OR Update( Photo3 ) OR Update( Photo4 ) OR Update( Photo5 ) OR Update( Photo6 ) OR Update( Photo7 ) OR Update( Photo8 ) OR Update( Photo9 ) OR Update( Photo1Thumb ) OR Update( Photo2Thumb ) OR Update( Photo3Thumb ) OR Update( Photo4Thumb ) OR Update( Photo5Thumb ) OR Update( Photo6Thumb ) OR Update( Photo7Thumb ) OR Update( Photo8Thumb ) OR Update( Photo9Thumb ) begin set NOCOUNT OFF end else begin set NOCOUNT ON if NOT exists( select ID from Inserted where Date_Voided is NOT NULL ) begin -- print 'Debug - OrderItems_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'OrderItems', I.ID, I.GUID, Columns_Updated() from Inserted I end -- if ( select Count( O.Date_Printed ) - Count( I.Date_Locked ) from Inserted I join Orders O on O.ID = Order_ID where O.[Type] = 'Purchase' ) > 0 begin -- raiserror( 'Warning - Purchase Order has been Printed', 11, 1 ) rollback -- end ------------------------------ -- update from parent order -- ------------------------------ update OrderItems set Employee_ID = O.Employee_ID, Contact_ID = O.Contact_ID, Order_Name = O.[Name], Number = O.Number, Reference = O.Reference from Inserted I join OrderItems L on L.ID = I.ID join Orders O on O.ID = L.Order_ID update OrderItems set [Type] = O.[Type] from Inserted I join OrderItems L on L.ID = I.ID join Orders O on O.ID = L.Order_ID where I.OrderItem_ID is Null -- skip Manufacturing Order Items ------------------------------------------------------------------------------------ -- update Grand Parent Order ID if it is a Manufacturing Sub-Detail manual insert -- ------------------------------------------------------------------------------------ update L set [Type] = 'Manufacturing', Order_ID = P.Order_ID from Inserted I join OrderItems L on L.ID = I.ID join OrderItems P on P.ID = L.OrderItem_ID where I.Order_ID is Null AND I.OrderItem_ID is Null -------------------------------- -- Auto-Sequence when omitted -- -------------------------------- update OrderItems set [Sequence] = ( select Max( isNull( [Sequence], 0 ) ) + 1 from OrderItems where Order_ID = I.Order_ID ) from Inserted I join OrderItems L on L.ID = I.ID where I.Sequence is Null -------------------------------------------------------------- -- Look up Resource by Reference_Code when Resource omitted -- -------------------------------------------------------------- update OrderItems set Resource_Name = R.Resource_Name from Inserted I join OrderItems L on L.ID = I.ID join Relationships R on R.Contact_ID = L.Contact_ID AND R.Reference_Code = L.Reference_Code where isNull( L.Reference_Code, '' ) <> '' AND isNull( L.Resource_Code, '' ) = '' AND isNull( L.Resource_Name, '' ) = '' AND isNull( L.Resource_UPC, '' ) = '' ----------------------------------------------- -- update when Name Changed - first priority -- ----------------------------------------------- update OrderItems set Resource_ID = R.ID, Resource_Code = R.Code, Resource_UPC = R.UPC, Unit = isNull( I.Unit, R.Unit ), -- Price = isNull( NullIF( I.Price, 0 ), R.Price ), Date_Start = R.Date_Start, Date_Stop = R.Date_Stop, Sales_Account_ID = R.Sales_Account_ID, Sales_Account = R.Sales_Account, Asset_Account_ID = R.Asset_Account_ID, Asset_Account = R.Asset_Account, COGS_Account_ID = R.COGS_Account_ID, COGS_Account = R.COGS_Account, Expense_Account_ID = R.Expense_Account_ID, Expense_Account = R.Expense_Account from Inserted I join OrderItems L on L.ID = I.ID join Deleted D on D.ID = I.ID join Resources R on R.Name = L.Resource_Name where I.Date_Modified is Null OR I.Resource_Name <> D.Resource_Name -- Called from Insert Trigger ----------------------------------------- -- update when ID, Code or UPC Changed -- ----------------------------------------- update OrderItems set Resource_ID = R.ID, Resource_Code = R.Code, Resource_UPC = R.UPC, Resource_Name = isNull( NullIF( I.Resource_Name, I.Resource_Code ), R.[Name] ), Unit = isNull( I.Unit, R.Unit ), -- Price = isNull( NullIF( I.Price, 0 ), R.Price ), Date_Start = R.Date_Start, Date_Stop = R.Date_Stop, Sales_Account_ID = R.Sales_Account_ID, Sales_Account = R.Sales_Account, Asset_Account_ID = R.Asset_Account_ID, Asset_Account = R.Asset_Account, COGS_Account_ID = R.COGS_Account_ID, COGS_Account = R.COGS_Account, Expense_Account_ID = R.Expense_Account_ID, Expense_Account = R.Expense_Account from Inserted I join OrderItems L on L.ID = I.ID join Deleted D on D.ID = I.ID join Resources R on R.ID = L.Resource_ID OR R.Code = L.Resource_Code OR R.UPC = L.Resource_UPC where I.Date_Modified is Null OR -- Called from Insert Trigger I.Resource_ID <> D.Resource_ID OR I.Resource_Code <> D.Resource_Code OR I.Resource_UPC <> D.Resource_UPC -------------------------------- -- always update these fields -- -------------------------------- update OrderItems set Avg_Cost = R.Avg_Cost, Taxable = R.Taxable, Variations_List = R.Variations_List, [Sub-Variations_List] = R.[Sub-Variations_List] from Inserted I join OrderItems L on L.ID = I.ID join Resources R on R.ID = L.Resource_ID -------------------------------------------- -- update Price from Resource when Changed -- -------------------------------------------- update OrderItems set Price = R.Price from Inserted I join OrderItems L on L.ID = I.ID join Deleted D on D.ID = I.ID join Resources R on R.ID = L.Resource_ID where L.[Type] IN ( 'Sale', 'Service' ) AND ( I.Resource_ID <> D.Resource_ID OR I.Resource_Code <> D.Resource_Code OR I.Resource_UPC <> D.Resource_UPC OR I.Resource_Name <> D.Resource_Name OR -- ( Update( Resource_ID ) OR Update( Resource_Code ) OR -- Update( Resource_Name ) OR Update( Resource_UPC ) OR ( Update( Price ) AND R.No_Price_Change = 1 ) OR I.Date_Modified is Null ) -- when called from the Insert trigger ------------------------------- -- check for inventory count -- ------------------------------- if exists( select R.ID from Inserted I join Resources R on R.ID = I.Resource_ID where I.Date_Locked is NOT Null AND R.Date_Locked_for_Count is NOT Null AND R.Date_Released_from_Count is Null ) begin raiserror( 'Warning - Some Items are Locked for Inventory Count - Try Again', 11, 1 ) rollback end --------------------------------------- -- use balance first for adjustments -- --------------------------------------- update OrderItems set Quantity = L.Balance - R.Units_on_Hand, Hours = - 1 from Inserted I join OrderItems L on L.ID = I.ID join Resources R on R.ID = L.Resource_ID where L.[Type] = 'Adjustment' AND Update( Balance ) update OrderItems set Balance = R.Units_on_Hand from Inserted I join OrderItems L on L.ID = I.ID join Resources R on R.ID = L.Resource_ID where L.Hours <> - 1 update OrderItems set Hours = 0, Quantity = L.Balance - isNull( ( select top 1 T.Balance from OrderItems T where T.Date_Locked is NOT Null AND T.Date_Locked < L.Date_Locked AND T.Resource_ID = L.Resource_ID order by T.Date_Locked desc ), R.Units_on_Hand ) from Inserted I join OrderItems L on L.ID = I.ID join Resources R on R.ID = L.Resource_ID where L.Date_Locked is NOT Null AND L.Hours = - 1 ------------------------------------------------------------------------------------------------ -- include( 'VDM_OrderItems_Update.sql' ) VDM will include any special code found here later ------------------------------------------------------------------------------------------------ -- combined packages are always 1 update OrderItems set Quantity = 1 from Inserted I join OrderItems L on L.ID = I.ID where L.Quantity <> 1 AND L.Type = 'Sale' AND L.Resource_Name + L.Note like '%combined supervisor%' -- set defaults when no group discount update OrderItems set Price = R.Price, Percent_Discount = 0, Discount_Amount = 0, Resource_Name = R.[Name] from Inserted I join OrderItems L on L.ID = I.ID join Resources R on R.ID = L.Resource_ID join Contacts C on C.Company_Configuration = 1 join Relationships T on T.Contact_ID = C.ID AND T.Reference_Code = 'Auto-Group' where L.Type = 'Sale' AND isNull( L.Reference, '' ) = '' AND L.Quantity < 4 AND L.Resource_Name + isNull( L.Note, '' ) like '%' + T.Type + '%' --AND -- isNull( T.Date_Start, GetDate() - 1 ) < GetDate() AND isNull( T.Date_Stop, GetDate() + 1 ) > GetDate() -- set defaults and add a group discount when 3 or more people update OrderItems set Price = R.Price, Percent_Discount = T.Percent_Discount, Resource_Name = R.[Name] + ' ' + isNull( T.Note, '' ) from Inserted I join OrderItems L on L.ID = I.ID join Resources R on R.ID = L.Resource_ID join Contacts C on C.Company_Configuration = 1 join Relationships T on T.Contact_ID = C.ID AND T.Reference_Code = 'Auto-Group' where L.Type = 'Sale' AND isNull( L.Reference, '' ) = '' AND L.Quantity >= 3 AND L.Resource_Name + isNull( L.Note, '' ) like '%' + T.Type + '%' --AND -- isNull( T.Date_Start, GetDate() - 1 ) < GetDate() AND isNull( T.Date_Stop, GetDate() + 1 ) > GetDate() -- first set the defaults and use the percent discount if not zero update OrderItems set Price = R.Price, Percent_Discount = T.Percent_Discount, Resource_Name = R.[Name] + ' ' + isNull( T.Note, '' ) from Inserted I join OrderItems L on L.ID = I.ID join Resources R on R.ID = L.Resource_ID join Contacts C on C.Company_Configuration = 1 join Relationships T on T.Contact_ID = C.ID AND T.Reference_Code = L.Reference where I.Type = 'Sale' AND L.Resource_Name + isNull( L.Note, '' ) like '%' + T.Type + '%' AND isNull( T.Percent_Discount, 0 ) <> 0 AND L.Quantity >= isNull( T.Minimum_Quantity, 0 ) AND L.Quantity <= isNull( NullIF( T.Maximum_Quantity, 0 ), L.Quantity ) AND isNull( T.Date_Start, GetDate() - 1 ) < GetDate() AND isNull( T.Date_Stop, GetDate() + 1 ) > GetDate() -- second set the defaults and use the price level if not zero update OrderItems set Price = dbo.PriceLevel( R.ID, T.Price_Level ), Percent_Discount = 0, Discount_Amount = 0, Resource_Name = R.[Name] + ' ' + isNull( T.Note, '' ) from Inserted I join OrderItems L on L.ID = I.ID join Resources R on R.ID = L.Resource_ID join Contacts C on C.Company_Configuration = 1 join Relationships T on T.Contact_ID = C.ID AND T.Reference_Code = L.Reference where I.Type = 'Sale' AND L.Resource_Name + isNull( L.Note, '' ) like '%' + T.Type + '%' AND isNull( NullIF( T.Price_Level, '' ), '0' ) <> '0' AND L.Quantity >= isNull( T.Minimum_Quantity, 0 ) AND L.Quantity <= isNull( NullIF( T.Maximum_Quantity, 0 ), L.Quantity ) AND isNull( T.Date_Start, GetDate() - 1 ) < GetDate() AND isNull( T.Date_Stop, GetDate() + 1 ) > GetDate() -- third set the defaults ands use the price if not zero update OrderItems set Price = T.Price, Percent_Discount = 0, Discount_Amount = 0, Resource_Name = R.[Name] + ' ' + isNull( T.Note, '' ) from Inserted I join OrderItems L on L.ID = I.ID join Resources R on R.ID = L.Resource_ID join Contacts C on C.Company_Configuration = 1 join Relationships T on T.Contact_ID = C.ID AND T.Reference_Code = L.Reference where I.Type = 'Sale' AND L.Resource_Name + isNull( L.Note, '' ) like '%' + T.Type + '%' AND isNull( T.Price, 0 ) <> 0 AND L.Quantity >= isNull( T.Minimum_Quantity, 0 ) AND L.Quantity <= isNull( NullIF( T.Maximum_Quantity, 0 ), L.Quantity ) AND isNull( T.Date_Start, GetDate() - 1 ) < GetDate() AND isNull( T.Date_Stop, GetDate() + 1 ) > GetDate() ---------------------------- -- Papiers FIX - move to custom triggers soon ---------------------------- update OrderItems set Quantity = 0 from Inserted I join OrderItems L on L.ID = I.ID join Contacts C on C.Company_Configuration = 1 where L.Resource_Code = 'P9999' AND C.[Name] like '%Papiers%' ------------------------------ -- Update G/L Accounts Info -- ------------------------------ update OrderItems set Sales_Account_ID = A.ID from OrderItems L join Inserted I on I.ID = L.ID join Accounts A on A.[Name] = L.Sales_Account where L.Sales_Account_ID is Null OR Update( Sales_Account ) update OrderItems set Sales_Account = A.[Name] from OrderItems L join Inserted I on I.ID = L.ID join Accounts A on A.ID = L.Sales_Account_ID where L.Sales_Account is Null OR Update( Sales_Account_ID ) update OrderItems set Expense_Account_ID = A.ID from OrderItems L join Inserted I on I.ID = L.ID join Accounts A on A.[Name] = L.Expense_Account where L.Expense_Account_ID is Null OR Update( Expense_Account ) update OrderItems set Expense_Account = A.[Name] from OrderItems L join Inserted I on I.ID = L.ID join Accounts A on A.ID = L.Expense_Account_ID where L.Expense_Account is Null OR Update( Expense_Account_ID ) update OrderItems set Asset_Account_ID = A.ID from OrderItems L join Inserted I on I.ID = L.ID join Accounts A on A.[Name] = L.Asset_Account where L.Asset_Account_ID is Null OR Update( Asset_Account ) update OrderItems set Asset_Account = A.[Name] from OrderItems L join Inserted I on I.ID = L.ID join Accounts A on A.ID = L.Asset_Account_ID where L.Asset_Account is Null OR Update( Asset_Account_ID ) update OrderItems set COGS_Account_ID = A.ID from OrderItems L join Inserted I on I.ID = L.ID join Accounts A on A.[Name] = L.COGS_Account where L.COGS_Account_ID is Null OR Update( COGS_Account ) update OrderItems set COGS_Account = A.[Name] from OrderItems L join Inserted I on I.ID = L.ID join Accounts A on A.ID = L.COGS_Account_ID where L.COGS_Account is Null OR Update( COGS_Account_ID ) -------------------------------------- -- Repeat orders are auto-back-ordered -------------------------------------- update OrderItems set Back_Order = L.Quantity from Inserted I join OrderItems L on L.ID = I.ID join Orders O on O.ID = I.Order_ID where O.Repeat_Frequency <> 'None' AND I.Date_Locked is NOT Null ---------------------------------------------- -- Use Price Levels if greater than Level 0 -- ---------------------------------------------- update OrderItems set Price = dbo.PriceLevel( L.Resource_ID, O.Price_Level ) from Inserted I join OrderItems L on L.ID = I.ID join Deleted D on D.ID = I.ID join Orders O on O.ID = L.Order_ID join Resources R on R.ID = L.Resource_ID where L.[Type] IN ( 'Sale', 'Service' ) AND O.Price_Level <> '0' AND ( Update( Resource_Code ) OR Update( Resource_Name ) OR Update( Resource_UPC ) OR I.Date_Modified is Null ) -- when called from the Insert trigger -------------------------------------------------- -- Make sure a Relationsships record exists -- -------------------------------------------------- insert Relationships ( Contact_ID, Resource_ID, [Type], Resource_Name, Reference_Code ) select L.Contact_ID, L.Resource_ID, L.[Type], L.Resource_Name, L.Reference_Code from Inserted I join OrderItems L on L.ID = I.ID where L.Contact_ID is NOT Null AND L.Resource_ID is NOT Null AND L.Reference_Code is NOT Null AND NOT exists( select R.ID from Relationships R where R.Contact_ID = L.Contact_ID AND R.Resource_ID = L.Resource_ID AND R.[Type] = L.[Type] ) -------------------------------- -- Update Relationship record -- -------------------------------- update Relationships set Resource_Name = L.Resource_Name, Reference_Code = L.Reference_Code from Inserted I join OrderItems L on L.ID = I.ID join Relationships R on R.Contact_ID = L.Contact_ID AND R.Resource_ID = L.Resource_ID AND R.[Type] = L.[Type] where L.Contact_ID is NOT Null AND L.Resource_ID is NOT Null AND L.Reference_Code is NOT Null ------------------------------------- -- Update from Relationship record -- ------------------------------------- update OrderItems set Reference_Code = R.Reference_Code from Inserted I join OrderItems L on L.ID = I.ID join Relationships R on R.Contact_ID = L.Contact_ID AND R.Resource_ID = L.Resource_ID AND R.[Type] = L.[Type] where L.Contact_ID is NOT Null AND L.Resource_ID is NOT Null AND isNull( L.Reference_Code, '' ) = '' AND isNull( R.Reference_Code, '' ) <> '' -------------------------------------------------- -- Make sure a Serial Transaction record exists -- -------------------------------------------------- insert Serials ( OrderItem_ID, Resource_ID, [Type], Order_Name, Contact_ID, Number, Quantity ) select L.ID, L.Resource_ID, L.[Type], L.Order_Name, L.Contact_ID, L.Serial_or_Lot_Number, L.Quantity from Inserted I join OrderItems L on L.ID = I.ID where L.Resource_ID is NOT Null AND L.Serial_or_Lot_Number is NOT Null AND NOT exists( select ID from Serials S where S.OrderItem_ID = L.ID AND S.Resource_ID = L.Resource_ID AND S.Number = L.Serial_or_Lot_Number ) -------------------------------------- -- Update Serial Transaction record -- -------------------------------------- update Serials set Resource_ID = L.Resource_ID, [Type] = L.[Type], Order_Name = L.Order_Name, Contact_ID = L.Contact_ID, Number = L.Serial_or_Lot_Number, Quantity = L.Quantity, Date_Locked = L.Date_Locked from Inserted I join OrderItems L on L.ID = I.ID join Deleted D on D.ID = I.ID join Serials S on S.OrderItem_ID = L.ID AND S.Resource_ID = D.Resource_ID AND S.Number = D.Serial_or_Lot_Number where L.Resource_ID <> D.Resource_ID OR L.[Type] = D.[Type] OR L.Order_Name = D.Order_Name OR L.Contact_ID = D.Contact_ID OR L.Serial_or_Lot_Number <> D.Serial_or_Lot_Number OR L.Quantity <> D.Quantity OR L.Date_Locked <> D.Date_Locked ----------------------------------------- -- Make sure a Variation record exists -- ----------------------------------------- insert Variations ( OrderItem_ID, [Name], Variations_List, [Sub-Variations_List], Date_Modified ) -- Date_Modified used to stop looping select L.ID, L.Resource_Name, L.Variations_List, L.[Sub-Variations_List], GetDate() from Inserted I join OrderItems L on L.ID = I.ID where L.Variations_List is NOT Null AND NOT exists ( select ID from Variations V where V.OrderItem_ID = L.ID ) -------------------------------------------------------- -- Update the default Variation when Quantity changed -- -------------------------------------------------------- update Variations set Quantity_00 = dbo.DefaultQty( 0, L.Default_Index, I.Quantity ), Quantity_01 = dbo.DefaultQty( 1, L.Default_Index, I.Quantity ), Quantity_02 = dbo.DefaultQty( 2, L.Default_Index, I.Quantity ), Quantity_03 = dbo.DefaultQty( 3, L.Default_Index, I.Quantity ), Quantity_04 = dbo.DefaultQty( 4, L.Default_Index, I.Quantity ), Quantity_05 = dbo.DefaultQty( 5, L.Default_Index, I.Quantity ), Quantity_06 = dbo.DefaultQty( 6, L.Default_Index, I.Quantity ), Quantity_07 = dbo.DefaultQty( 7, L.Default_Index, I.Quantity ), Quantity_08 = dbo.DefaultQty( 8, L.Default_Index, I.Quantity ), Quantity_09 = dbo.DefaultQty( 9, L.Default_Index, I.Quantity ), Quantity_10 = dbo.DefaultQty( 10, L.Default_Index, I.Quantity ), Quantity_11 = dbo.DefaultQty( 11, L.Default_Index, I.Quantity ), Quantity_12 = dbo.DefaultQty( 12, L.Default_Index, I.Quantity ), Quantity_13 = dbo.DefaultQty( 13, L.Default_Index, I.Quantity ), Quantity_14 = dbo.DefaultQty( 14, L.Default_Index, I.Quantity ), Quantity_15 = dbo.DefaultQty( 15, L.Default_Index, I.Quantity ), Quantity_16 = dbo.DefaultQty( 16, L.Default_Index, I.Quantity ), Quantity_17 = dbo.DefaultQty( 17, L.Default_Index, I.Quantity ), Quantity_18 = dbo.DefaultQty( 18, L.Default_Index, I.Quantity ), Quantity_19 = dbo.DefaultQty( 19, L.Default_Index, I.Quantity ), Quantity_20 = dbo.DefaultQty( 20, L.Default_Index, I.Quantity ), Quantity_21 = dbo.DefaultQty( 21, L.Default_Index, I.Quantity ), Quantity_22 = dbo.DefaultQty( 22, L.Default_Index, I.Quantity ), Quantity_23 = dbo.DefaultQty( 23, L.Default_Index, I.Quantity ), Quantity_24 = dbo.DefaultQty( 24, L.Default_Index, I.Quantity ), Quantity_25 = dbo.DefaultQty( 25, L.Default_Index, I.Quantity ), Quantity_26 = dbo.DefaultQty( 26, L.Default_Index, I.Quantity ), Quantity_27 = dbo.DefaultQty( 27, L.Default_Index, I.Quantity ), Quantity_28 = dbo.DefaultQty( 28, L.Default_Index, I.Quantity ), Quantity_29 = dbo.DefaultQty( 29, L.Default_Index, I.Quantity ) from Inserted I join OrderItems L on L.ID = I.ID join Deleted D on D.ID = I.ID join Variations V on V.OrderItem_ID = I.ID where I.Quantity <> 0 AND I.Quantity <> D.Quantity ------------------------------------------------- -- Update Variations records from the Resource -- ------------------------------------------------- update Variations set [Name] = L.Resource_Name, Price_00 = ( select top 1 Price_00 from Variations where Resource_ID = L.Resource_ID ), Price_01 = ( select top 1 Price_01 from Variations where Resource_ID = L.Resource_ID ), Price_02 = ( select top 1 Price_02 from Variations where Resource_ID = L.Resource_ID ), Price_03 = ( select top 1 Price_03 from Variations where Resource_ID = L.Resource_ID ), Price_04 = ( select top 1 Price_04 from Variations where Resource_ID = L.Resource_ID ), Price_05 = ( select top 1 Price_05 from Variations where Resource_ID = L.Resource_ID ), Price_06 = ( select top 1 Price_06 from Variations where Resource_ID = L.Resource_ID ), Price_07 = ( select top 1 Price_07 from Variations where Resource_ID = L.Resource_ID ), Price_08 = ( select top 1 Price_08 from Variations where Resource_ID = L.Resource_ID ), Price_09 = ( select top 1 Price_09 from Variations where Resource_ID = L.Resource_ID ), Price_10 = ( select top 1 Price_10 from Variations where Resource_ID = L.Resource_ID ), Price_11 = ( select top 1 Price_11 from Variations where Resource_ID = L.Resource_ID ), Price_12 = ( select top 1 Price_12 from Variations where Resource_ID = L.Resource_ID ), Price_13 = ( select top 1 Price_13 from Variations where Resource_ID = L.Resource_ID ), Price_14 = ( select top 1 Price_14 from Variations where Resource_ID = L.Resource_ID ), Price_15 = ( select top 1 Price_15 from Variations where Resource_ID = L.Resource_ID ), Price_16 = ( select top 1 Price_16 from Variations where Resource_ID = L.Resource_ID ), Price_17 = ( select top 1 Price_17 from Variations where Resource_ID = L.Resource_ID ), Price_18 = ( select top 1 Price_18 from Variations where Resource_ID = L.Resource_ID ), Price_19 = ( select top 1 Price_19 from Variations where Resource_ID = L.Resource_ID ), Price_20 = ( select top 1 Price_20 from Variations where Resource_ID = L.Resource_ID ), Price_21 = ( select top 1 Price_21 from Variations where Resource_ID = L.Resource_ID ), Price_22 = ( select top 1 Price_22 from Variations where Resource_ID = L.Resource_ID ), Price_23 = ( select top 1 Price_23 from Variations where Resource_ID = L.Resource_ID ), Price_24 = ( select top 1 Price_24 from Variations where Resource_ID = L.Resource_ID ), Price_25 = ( select top 1 Price_25 from Variations where Resource_ID = L.Resource_ID ), Price_26 = ( select top 1 Price_26 from Variations where Resource_ID = L.Resource_ID ), Price_27 = ( select top 1 Price_27 from Variations where Resource_ID = L.Resource_ID ), Price_28 = ( select top 1 Price_28 from Variations where Resource_ID = L.Resource_ID ), Price_29 = ( select top 1 Price_29 from Variations where Resource_ID = L.Resource_ID ) from Variations V join Deleted D on D.ID = V.OrderItem_ID join OrderItems L on L.ID = D.ID -- join Variations R on R.Resource_ID = L.Resource_ID where L.Resource_ID <> D.Resource_ID OR L.Date_Modified is Null -- Date_Modified is Null when called from the Insert trigger --------------------------------------- -- update the qty from the variation -- --------------------------------------- update OrderItems set Quantity = Quantity_00 + Quantity_01 + Quantity_02 + Quantity_03 + Quantity_04 + Quantity_05 + Quantity_06 + Quantity_07 + Quantity_08 + Quantity_09 + Quantity_10 + Quantity_11 + Quantity_12 + Quantity_13 + Quantity_14 + Quantity_15 + Quantity_16 + Quantity_17 + Quantity_18 + Quantity_19 + Quantity_20 + Quantity_21 + Quantity_22 + Quantity_23 + Quantity_24 + Quantity_25 + Quantity_26 + Quantity_27 + Quantity_28 + Quantity_29 from Inserted I join OrderItems L on L.ID = I.ID join Variations V on V.OrderItem_ID = I.ID where I.Quantity = 0 ------------------------------------------------ -- update the Average Price from the Variation ------------------------------------------------ update OrderItems set Price = ( Price_00 * Quantity_00 + Price_01 * Quantity_01 + Price_02 * Quantity_02 + Price_03 * Quantity_03 + Price_04 * Quantity_04 + Price_05 * Quantity_05 + Price_06 * Quantity_06 + Price_07 * Quantity_07 + Price_08 * Quantity_08 + Price_09 * Quantity_09 + Price_10 * Quantity_10 + Price_11 * Quantity_11 + Price_12 * Quantity_12 + Price_13 * Quantity_13 + Price_14 * Quantity_14 + Price_15 * Quantity_15 + Price_16 * Quantity_16 + Price_17 * Quantity_17 + Price_18 * Quantity_18 + Price_19 * Quantity_19 + Price_20 * Quantity_20 + Price_21 * Quantity_21 + Price_22 * Quantity_22 + Price_23 * Quantity_23 + Price_24 * Quantity_24 + Price_25 * Quantity_25 + Price_26 * Quantity_26 + Price_27 * Quantity_27 + Price_28 * Quantity_28 + Price_29 * Quantity_29 ) / L.Quantity from Inserted I join OrderItems L on L.ID = I.ID join Variations V on V.OrderItem_ID = I.ID where I.Price = 0 AND L.Quantity <> 0 ------------------------------------------- -- take care of selling unit conversions -- ------------------------------------------- update OrderItems set Unit_Conversion = dbo.UnitConversion( R.Unit, L.Unit, R.Unit_Conversion_List ) from Inserted I join OrderItems L on L.ID = I.ID join Resources R on R.ID = L.Resource_ID where I.Unit_Quantity is NOT Null AND ( Update( Unit ) OR Update( Date_Modified ) ) -- called from insert trigger update OrderItems set Quantity = isNull( L.Unit_Quantity / isNull( L.Unit_Conversion, 1 ), L.Quantity ) from Inserted I join OrderItems L on L.ID = I.ID where I.Unit_Quantity is NOT Null AND ( Update( Unit ) OR Update( Unit_Quantity ) OR Update( Date_Modified ) ) -- called from insert trigger update OrderItems set Unit_Price = L.Price / isNull( L.Unit_Conversion, 1 ), Unit_Quantity = L.Quantity * isNull( L.Unit_Conversion, 1 ) from Inserted I join OrderItems L on L.ID = I.ID where I.Unit_Quantity is NOT Null AND ( Update( Quantity ) OR Update( Price ) OR Update( Date_Modified ) ) -- called from insert trigger ----------------------------- -- set the Price and Total -- ----------------------------- -- reset or no price on any sales or purchases from one self update OrderItems set Price = 0 from Inserted I join OrderItems L on L.ID = I.ID join Contacts C on C.ID = L.Contact_ID where C.Company_Configuration = 1 OR C.[Name] like '%Papiers Experts%' -- reset or no price on these update OrderItems set Price = 0 from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] IN ( 'Adjustment', 'Manufacturing' ) -- Total up Manufacturing price update OrderItems set Price = ( select Sum( isNull( Total, 0 ) ) from OrderItems C where C.OrderItem_ID = L.ID ) / dbo.Maximum( 1, L.Quantity ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Production' if exists( select C.ID from Inserted I join OrderItems C on C.OrderItem_ID = I.ID where C.[Type] = 'Manufacturing' ) begin update OrderItems set Made_to_Order = 1, Avg_Cost = ( select Sum( isNull( Total, 0 ) ) from OrderItems C where C.OrderItem_ID = L.ID ) / dbo.Maximum( 1, L.Quantity ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] IN ( 'Sale', 'Service' ) end -- use Default Account Selling Prices update OrderItems set Price = isNull( ( select Min( R.Price ) from Relationships R where R.Contact_ID = ( select ID from Contacts where Company_Configuration = 1 ) AND R.Resource_Name = L.Resource_Name AND R.Price <> 0 AND L.Quantity >= R.Minimum_Quantity AND isNull( L.Date_Required, GetDate() ) >= isNull( R.Date_Start, '1/1/1900' ) AND isNull( L.Date_Required, GetDate() ) <= isNull( R.Date_Stop, '1/1/2200' ) ), L.Price ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] IN ( 'Sale', 'Service' ) -- use last price or standard cost if zero update OrderItems set Price = isNull( ( select top 1 Price from OrderItems where Resource_ID = L.Resource_ID AND Contact_ID = L.Contact_ID AND [Type] = L.[Type] AND Price <> 0 order by Date_Locked desc ), R.Std_Cost ) from Inserted I join Deleted D on D.ID = I.ID join OrderItems L on L.ID = I.ID join Orders O on O.ID = L.Order_ID join Resources R on R.ID = L.Resource_ID where L.[Type] IN ( 'Sale', 'Purchase', 'Service' ) AND L.Price = 0 AND D.Price = 0 AND O.Price_Level = '0' AND L.Date_Locked is Null AND R.Never_use_Last_Price = 0 -- Use any contract prices update OrderItems set Price = isNull( ( select Min( R.Price ) from Relationships R where R.Contact_ID = L.Contact_ID AND R.Resource_Name = L.Resource_Name AND R.Price <> 0 AND L.Quantity >= R.Minimum_Quantity AND isNull( L.Date_Required, GetDate() ) >= isNull( R.Date_Start, '1/1/1900' ) AND isNull( L.Date_Required, GetDate() ) <= isNull( R.Date_Stop, '1/1/2200' ) ), L.Price ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] IN ( 'Sale', 'Purchase', 'Service' ) AND L.Date_Locked is Null update OrderItems set Total = Round( L.Quantity * L.Price, 2 ) from Inserted I join OrderItems L on L.ID = I.ID update OrderItems set Percent_Discount = 0 from Inserted I join OrderItems L on L.ID = I.ID where Update( Discount_Amount ) update OrderItems set Discount_Amount = Round( L.Total * L.Percent_Discount / 100, 2 ) from Inserted I join OrderItems L on L.ID = I.ID where L.Percent_Discount <> 0 OR Update( Percent_Discount ) ------------------------------------------------------------------------- -- add any missing activities for equipment resources with no contacts -- ------------------------------------------------------------------------- insert Activities ( OrderItem_ID, Order_ID, Contact_ID, Resource_ID, [Sequence], [Name], Contact_Name, Resource_Name, Minutes, Note, Audio, Video ) select L.ID, L.Order_ID, L.Mfg_Contact_ID, L.Resource_ID, L.[Sequence], L.Order_Name, L.Contact_Name, L.Resource_Name, L.Quantity * 60, L.Note, L.Audio, L.Video from Inserted I join OrderItems L on L.ID = I.ID join Resources R on R.ID = L.Resource_ID where L.[Type] = 'Manufacturing' AND R.[Type] = 'Equipment' AND L.Mfg_Contact_ID is Null AND NOT exists ( select ID from Activities where OrderItem_ID = L.ID ) ----------------------------------------------------------- -- add any missing activities with non-supplier contacts -- ----------------------------------------------------------- insert Activities ( OrderItem_ID, Order_ID, Contact_ID, Resource_ID, [Sequence], [Name], Contact_Name, Resource_Name, Minutes, Note, Audio, Video ) select L.ID, L.Order_ID, L.Mfg_Contact_ID, L.Resource_ID, L.[Sequence], L.Order_Name, L.Contact_Name, L.Resource_Name, L.Quantity * 60, L.Note, L.Audio, L.Video from Inserted I join OrderItems L on L.ID = I.ID join Contacts C on C.ID = L.Mfg_Contact_ID where L.[Type] = 'Manufacturing' AND C.Can_be_a_Supplier = 0 AND NOT exists ( select ID from Activities where OrderItem_ID = L.ID ) ------------------------------------- -- update any generated activities -- ------------------------------------- update Activities set Minutes = L.Quantity * 60, [Name] = L.Order_Name, Contact_ID = L.Mfg_Contact_ID, Contact_Name = L.Contact_Name, Resource_ID = L.Resource_ID, Resource_Name = L.Resource_Name from Inserted I join OrderItems L on L.ID = I.ID join Deleted D on D.ID = I.ID join Activities A on A.OrderItem_ID = I.ID where L.[Type] = 'Manufacturing' AND ( I.Quantity <> D.Quantity OR L.Order_Name <> D.Order_Name OR L.Mfg_Contact_ID <> D.Mfg_Contact_ID OR L.Contact_Name <> D.Contact_Name OR L.Resource_ID <> D.Resource_ID OR L.Resource_Name <> D.Resource_Name ) ---------------------------------------------------------------------------------------------------- -- update all Component activities necessary to manufacture since triggers do not call themselves -- ---------------------------------------------------------------------------------------------------- update Activities set Minutes = L.Quantity * 60, [Name] = L.Order_Name, Contact_ID = L.Mfg_Contact_ID, Contact_Name = L.Contact_Name, Resource_ID = L.Resource_ID, Resource_Name = L.Resource_Name from Inserted I join OrderItems L on L.OrderItem_ID = I.ID join Deleted D on D.ID = I.ID join Activities A on A.OrderItem_ID = L.ID where L.[Type] = 'Manufacturing' AND ( I.Quantity <> D.Quantity OR L.Order_Name <> D.Order_Name OR L.Mfg_Contact_ID <> D.Mfg_Contact_ID OR L.Contact_Name <> D.Contact_Name OR L.Resource_ID <> D.Resource_ID OR L.Resource_Name <> D.Resource_Name ) --------------------------------------------------- -- setup Mfg_Contact_ID to add any missing Auto-POs --------------------------------------------------- update OrderItems set Mfg_Contact_ID = C.ID from Inserted I join OrderItems L on L.ID = I.ID join Contacts C on C.[Name] = L.Contact_Name where L.[Type] IN ( 'Sale', 'Service', 'Manufacturing' ) AND C.Can_be_a_Supplier = 1 ----------------------------------------------- -- Reconnect any back orders involving Auto-POs ----------------------------------------------- update OrderItems set OrderItem_ID = I.ID, Quantity = I.Quantity -- update L set OrderItem_ID = I.ID, Quantity = I.Quantity from Inserted I join OrderItems L on L.OrderItem_ID = I.BackOrderItem_ID where I.[Type] IN ( 'Sale', 'Service', 'Manufacturing' ) AND L.[Type] = 'Purchase' AND L.Date_Locked is Null --------------------------------------------------------------- -- add any missing PO's checking Date Printed to exclude any -- --------------------------------------------------------------- declare @Date datetime set @Date = GetDate() insert Orders ( Contact_ID, [Type], Auto_Generated, [Name], Date_Modified ) -- Date_Modified used to stop looping ????? select distinct L.Mfg_Contact_ID, 'Purchase', 1, L.Contact_Name, @Date -- mutiple similar lines add multiple PO's ??? from Inserted I join OrderItems L on L.ID = I.ID join Contacts C on C.ID = L.Mfg_Contact_ID where L.Date_Locked is Null AND L.[Type] IN ( 'Sale', 'Service', 'Manufacturing' ) AND C.Can_be_a_Supplier = 1 AND NOT exists ( select ID from Orders where Contact_ID = L.Mfg_Contact_ID AND [Type] = 'Purchase' AND Auto_Generated = 1 AND Date_Locked is Null AND Date_Printed is Null ) ------------------------------------------------------------------------------- -- add any missing lines to the PO's added or already there but not printed -- ------------------------------------------------------------------------------- insert OrderItems ( OrderItem_ID, Order_ID, Component_ID, Mfg_Contact_ID, Contact_Name, Number, Reference, [Type], Date_Required, [Sequence], Reference_Code, Quantity, Resource_ID, Resource_Name, Unit, Variation, Default_Index, Note, Audio, Video ) select L.ID, P.ID, L.Component_ID, L.Contact_ID, L.Order_Name, L.Number, L.Reference, 'Purchase', L.Date_Required, L.[Sequence], L.Reference_Code, isNull( NullIF( L.Back_Order, 0 ), L.Quantity ), L.Resource_ID, L.Resource_Name, L.Unit, L.Variation, L.Default_Index, L.Note, L.Audio, L.Video from Inserted I join OrderItems L on L.ID = I.ID join Contacts C on C.ID = L.Mfg_Contact_ID join Orders P on P.Contact_ID = L.Mfg_Contact_ID where P.[Type] = 'Purchase' AND P.Date_Locked is Null AND P.Date_Printed is Null AND P.Auto_Generated = 1 AND L.Date_Locked is Null AND L.[Type] IN ( 'Sale', 'Manufacturing', 'Service' ) AND C.Can_be_a_Supplier = 1 AND NOT exists ( select ID from OrderItems where OrderItem_ID = L.ID AND [Type] = 'Purchase' ) ----------------------------------------------------------------------------- -- add all activities and resources necessary to manufacture from template -- ----------------------------------------------------------------------------- update OrderItems set Template_ID = R.ID from Inserted I join OrderItems L on L.ID = I.ID join Deleted D on D.ID = I.ID join Resources R on R.[Name] = I.Template_Name where Update( Template_Name ) OR I.Date_Modified is Null -- when called from the Insert trigger insert OrderItems ( OrderItem_ID, Order_ID, Component_ID, Mfg_Contact_ID, Date_Required, [Type], Order_Name, Number, Reference, [Sequence], Contact_Name, Quantity, Hours, Resource_ID, Resource_Name, Resource_Code, Resource_UPC, Avg_Cost, Variations_List, [Sub-Variations_List], Default_Index, Note, Audio, Video ) select L.ID, L.Order_ID, C.ID, C.Contact_ID, L.Date_Required, 'Manufacturing', L.Order_Name, L.Number, L.Reference, C.[Sequence], C.Contact_Name, L.Quantity * isNull( NullIF( C.Units_Required, 0 ), isNull( NullIF( C.Hours_Required, 0 ), C.Percent_Required / 100 ) ), L.Quantity * C.Hours_Required, C.Component_ID, C.Resource_Name, R.[Code], R.[UPC], R.Avg_Cost, R.Variations_List, R.[Sub-Variations_List], L.Default_Index, C.Note, C.Audio, C.Video from Inserted I join OrderItems L on L.ID = I.ID join Deleted D on D.ID = I.ID join Components C on C.Resource_ID = L.Template_ID left join Resources R on R.ID = C.Component_ID where L.Date_Locked is Null AND L.[Type] IN ( 'Sale', 'Service' ) AND Update( Template_Name ) OR I.Date_Modified is Null -- when called from the Insert trigger --------------------------- -- update all components -- --------------------------- update L set Date_Required = S.Date_Required, Order_Name = S.Order_Name, Number = S.Number, Reference = S.Reference, Sequence = C.Sequence, Quantity = S.Quantity * isNull( NullIF( C.Units_Required, 0 ), isNull( NullIF( C.Hours_Required, 0 ), C.Percent_Required / 100 ) ), Hours = S.Quantity * C.Hours_Required, Total = L.Avg_Cost * S.Quantity * isNull( NullIF( C.Units_Required, 0 ), isNull( NullIF( C.Hours_Required, 0 ), C.Percent_Required / 100 ) ) from Inserted I join OrderItems L on L.OrderItem_ID = I.ID join OrderItems S on S.ID = I.ID join Deleted D on D.ID = I.ID join Components C on C.ID = L.Component_ID where S.[Type] IN ( 'Sale', 'Service', 'Production' ) AND L.[Type] = 'Manufacturing' AND L.Date_Locked is Null AND ( S.Resource_Name <> D.Resource_Name OR S.Unit <> D.Unit OR S.Variation <> D.Variation OR S.Quantity <> D.Quantity ) ------------------ -- update Auto-POs ------------------ update L set Resource_Name = S.Resource_Name, Unit = S.Unit, Variation = S.Variation, Reference_Code = S.Reference_Code, Quantity = S.Quantity, Total = S.Quantity * L.Price from Inserted I join OrderItems L on L.OrderItem_ID = I.ID join OrderItems S on S.ID = I.ID join Deleted D on D.ID = I.ID where S.[Type] IN ( 'Sale', 'Service', 'Manufacturing' ) AND L.[Type] = 'Purchase' AND L.Date_Locked is Null AND ( S.Resource_Name <> D.Resource_Name OR S.Unit <> D.Unit OR S.Variation <> D.Variation OR S.Reference_Code <> D.Reference_Code OR S.Quantity <> D.Quantity ) ---------------------------------- -- update Order Totals of Auto-POs ---------------------------------- update Orders set Total = 0, Taxable_Amount = 0 -- force update of order totals from Inserted I join OrderItems L on L.OrderItem_ID = I.ID join OrderItems S on S.ID = I.ID join Deleted D on D.ID = I.ID join Orders O on O.ID = L.Order_ID where S.[Type] IN ( 'Sale', 'Service', 'Manufacturing' ) AND L.[Type] = 'Purchase' AND O.Date_Locked is Null AND ( S.Resource_Name <> D.Resource_Name OR S.Unit <> D.Unit OR S.Variation <> D.Variation OR S.Quantity <> D.Quantity ) -------------------------------- -- update Auto-POs of components -------------------------------- update L set Quantity = C.Quantity, Total = C.Quantity * L.Price from Inserted I join OrderItems C on C.OrderItem_ID = I.ID join OrderItems L on L.OrderItem_ID = C.ID join OrderItems S on S.ID = I.ID join Deleted D on D.ID = I.ID where S.[Type] IN ( 'Sale', 'Service', 'Production' ) AND C.[Type] = 'Manufacturing' AND L.[Type] = 'Purchase' AND L.Date_Locked is Null AND ( S.Resource_Name <> D.Resource_Name OR S.Unit <> D.Unit OR S.Variation <> D.Variation OR S.Quantity <> D.Quantity ) ------------------------------------------------ -- update Order Totals of Auto-POs of Components ------------------------------------------------ update Orders set Total = 0, Taxable_Amount = 0 -- force update of order totals from Inserted I join OrderItems C on C.OrderItem_ID = I.ID join OrderItems L on L.OrderItem_ID = C.ID join OrderItems S on S.ID = I.ID join Deleted D on D.ID = I.ID join Orders O on O.ID = L.Order_ID where S.[Type] IN ( 'Sale', 'Service', 'Production' ) AND C.[Type] = 'Manufacturing' AND L.[Type] = 'Purchase' AND O.Date_Locked is Null AND ( S.Resource_Name <> D.Resource_Name OR S.Unit <> D.Unit OR S.Variation <> D.Variation OR S.Quantity <> D.Quantity ) ---------------------- -- Update Order totals ---------------------- -- update Orders set Total = O.Total + L.Total - D.Total, -- Taxable_Amount = O.Taxable_Amount + L.Total * L.Taxable - D.Total * D.Taxable, update Orders set Total = 0, Taxable_Amount = 0, -- force update of order totals Date_Required = dbo.MinDate( O.Date_Required, L.Date_required ) from Inserted I join OrderItems L on L.ID = I.ID join Orders O on O.ID = I.Order_ID join Deleted D on D.ID = I.ID -- where L.Total <> D.Total OR L.Taxable <> D.Taxable OR L.Discount_Amount <> D.Discount_Amount OR -- L.Date_Required <> D.Date_Required OR I.Date_Modified is Null -- Date_Modified is Null when called from the Insert trigger ----------------------------------------------- -- update Resources of Components when unlocked ----------------------------------------------- update Resources set Units_Required = - 1, Units_Ordered = - 1 from Inserted I join OrderItems L on L.OrderItem_ID = I.ID join Deleted D on D.ID = I.ID join Resources R on R.ID = L.Resource_ID where I.Date_Locked is Null AND L.[Type] = 'Manufacturing' AND ( I.Quantity <> D.Quantity OR I.[Type] <> D.[Type] ) -------------------------------------------- -- Update Resource of components when Locked -------------------------------------------- update Resources set Avg_Usage_per_Month = 0, Order_Point = 0, Order_Quantity = 0, -- Units_Required = - 1, Units_Ordered = - 1, Units_on_Hand = case when L.Made_to_Order = 1 then R.Units_on_Hand * R.Track_Qty_on_Hand else R.Units_on_Hand - L.Quantity * L.Unit_Conversion * R.Track_Qty_on_Hand end from Inserted I join OrderItems L on L.OrderItem_ID = I.ID join Resources R on R.ID = L.Resource_ID where I.Date_Locked is NOT Null AND L.[Type] = 'Manufacturing' -------------------------------- -- Update Resource when Unlocked -------------------------------- -- update Resources set Units_Required = R.Units_Required -- + L.Quantity * case when L.[Type] IN ( 'Sale', 'Manufacturing', 'Service' ) OR L.Made_to_Order = 1 then 1 else 0 end -- - D.Quantity * case when D.[Type] IN ( 'Sale', 'Manufacturing', 'Service' ) OR D.Made_to_Order = 1 AND I.Date_Modified is NOT Null then 1 else 0 end, -- Units_Ordered = R.Units_Ordered -- + L.Quantity * case when L.[Type] IN ( 'Purchase', 'Adjustment', 'Production' ) OR L.Made_to_Order = 1 then 1 else 0 end -- - D.Quantity * case when D.[Type] IN ( 'Purchase', 'Adjustment', 'Production' ) OR D.Made_to_Order = 1 AND I.Date_Modified is NOT Null then 1 else 0 end update Resources set Units_Required = - 1, Units_Ordered = - 1 from Inserted I join OrderItems L on L.ID = I.ID join Resources R on R.ID = L.Resource_ID join Deleted D on D.ID = I.ID where I.Date_Locked is Null AND ( L.Quantity <> D.Quantity OR L.[Type] <> D.[Type] OR I.Date_Modified is Null ) -- Date_Modified is Null when called from the Insert trigger ------------------------------ -- Update Resource when Locked ------------------------------ update Resources set Avg_Usage_per_Month = 0, Order_Point = 0, Order_Quantity = 0, -- Units_Required = R.Units_Required - ( select Sum( Quantity ) from Inserted where Resource_ID = R.ID ), -- Units_Ordered = case when L.Made_to_Order = 0 then R.Units_Ordered -- else R.Units_Ordered - ( select Sum( Quantity ) from Inserted where Resource_ID = R.ID ) end, Units_Required = - 1, Units_Ordered = - 1, Units_on_Hand = case when L.Made_to_Order = 1 then R.Units_on_Hand * R.Track_Qty_on_Hand else R.Units_on_Hand - ( select Sum( isNull( Quantity * Unit_Conversion, 0 ) ) from Inserted where Resource_ID = R.ID ) * R.Track_Qty_on_Hand end from Inserted I join OrderItems L on L.ID = I.ID join Resources R on R.ID = L.Resource_ID where I.Date_Locked is NOT Null AND L.[Type] IN ( 'Sale', 'Manufacturing', 'Service' ) update Resources set Avg_Usage_per_Month = 0, Order_Point = 0, Order_Quantity = 0, -- Units_Ordered = R.Units_Ordered - ( select Sum( Quantity ) from Inserted where Resource_ID = R.ID ), Units_Required = - 1, Units_Ordered = - 1, Units_on_Hand = R.Units_on_Hand + ( select Sum( isNull( Quantity * Unit_Conversion, 0 ) ) from Inserted where Resource_ID = R.ID ) * R.Track_Qty_on_Hand, Last_Supplier = case when L.[Type] = 'Purchase' then L.Order_Name else R.Last_Supplier end, Avg_Days_to_Replenish = case when L.[Type] = 'Adjustment' then R.Avg_Days_to_Replenish else 0.6 * isNull( NullIF( R.Avg_Days_to_Replenish, 0 ), DateDiff( Day, I.Date_Locked, I.Date_Created ) ) + 0.4 + DateDiff( Day, I.Date_Locked, I.Date_Created ) + 1 end, Avg_Cost = case when L.[Type] = 'Adjustment' then R.Avg_Cost else case when R.Units_on_Hand <= 0 OR R.Avg_Cost <= 0 OR L.Quantity <= 0 then isNull( NullIF( L.Landed_Price, 0 ), L.Price ) else ( R.Avg_Cost * R.Units_on_Hand + ( select Sum( isNull( Quantity * Unit_Conversion, 0 ) ) from Inserted where Resource_ID = R.ID ) * isNull( NullIF( L.Landed_Price, 0 ), L.Price ) ) / ( R.Units_on_Hand + ( select Sum( isNull( Quantity * Unit_Conversion, 0 ) ) from Inserted where Resource_ID = R.ID ) ) end end from Inserted I join OrderItems L on L.ID = I.ID join Resources R on R.ID = L.Resource_ID join Deleted D on D.ID = I.ID where I.Date_Locked is NOT Null AND L.[Type] IN ( 'Purchase', 'Production', 'Adjustment' ) ------------------------------------------ -- Update the Balance and Cost when Locked ------------------------------------------ update OrderItems set Balance = R.Units_on_Hand, Avg_Cost = R.Avg_Cost from Inserted I join OrderItems L on L.ID = I.ID join Resources R on R.ID = L.Resource_ID where I.Date_Locked is NOT Null --------------------------------------------------------------------- -- lock all Mfg Steps, Variations, Serial/Lot children and Activities --------------------------------------------------------------------- if Update( Date_Locked ) begin -- Update The balance and Cost of Mfg Steps when locked update OrderItems set Date_Locked = I.Date_Locked, Balance = R.Units_on_Hand, Avg_Cost = R.Avg_Cost from Inserted I join OrderItems L on L.OrderItem_ID = I.ID join Resources R on R.ID = L.Resource_ID where I.Date_Locked is NOT Null AND L.[Type] = 'Manufacturing' update Resources set Units_Required = - 1, Units_Ordered = - 1 -- recalculate totals once Mfg Steps are Locked from Inserted I join OrderItems L on L.OrderItem_ID = I.ID join Resources R on R.ID = L.Resource_ID where I.Date_Locked is NOT Null AND L.[Type] = 'Manufacturing' update Variations set Date_Locked = I.Date_Locked from Inserted I join Variations V on V.[OrderItem_ID] = I.ID where I.Date_Locked is NOT Null update Serials set Date_Locked = I.Date_Locked from Inserted I join Serials S on S.OrderItem_ID = I.ID where I.Date_Locked is NOT Null update Activities set Date_Locked = I.Date_Locked from Inserted I join Activities A on A.OrderItem_ID = I.ID where I.Date_Locked is NOT Null update Activities set Date_Locked = I.Date_Locked from Inserted I join OrderItems L on L.OrderItem_ID = I.ID join Activities A on A.OrderItem_ID = L.ID where I.Date_Locked is NOT Null end ----------------------------------------------------- -- Update Tree_Path to jump to the source document -- ----------------------------------------------------- update OrderItems set Tree_Path = '\\Sales\Estimates\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Estimate' AND L.Date_Locked is Null update OrderItems set Tree_Path = '\\Sales\Open Sales Orders\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Sale' AND L.Date_Locked is Null update OrderItems set Tree_Path = '\\Sales\Open Sales Orders\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Manufacturing' AND L.Date_Locked is Null AND ( select [Type] from OrderItems where ID = L.OrderItem_ID ) = 'Sale' update OrderItems set Tree_Path = '\\Sales\Locked Invoices\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Sale' AND L.Date_Locked is NOT Null update OrderItems set Tree_Path = '\\Sales\Locked Invoices\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Manufacturing' AND L.Date_Locked is NOT Null AND ( select [Type] from OrderItems where ID = L.OrderItem_ID ) = 'Sale' update OrderItems set Tree_Path = '\\Sales\Open Service Orders\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Service' AND L.Date_Locked is Null update OrderItems set Tree_Path = '\\Sales\Open Service Orders\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Manufacturing' AND L.Date_Locked is Null AND ( select [Type] from OrderItems where ID = L.OrderItem_ID ) = 'Service' update OrderItems set Tree_Path = '\\Sales\Locked Service Invoices\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Service' AND L.Date_Locked is NOT Null update OrderItems set Tree_Path = '\\Sales\Locked Service Invoices\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Manufacturing' AND L.Date_Locked is NOT Null AND ( select [Type] from OrderItems where ID = L.OrderItem_ID ) = 'Service' update OrderItems set Tree_Path = '\\Purchases\Open Purchases\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Purchase' AND L.Date_Locked is Null update OrderItems set Tree_Path = '\\Purchases\Locked Purchases\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Purchase' AND L.Date_Locked is NOT Null update OrderItems set Tree_Path = '\\Adjustments\Open Adjustments\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Adjustment' AND L.Date_Locked is Null update OrderItems set Tree_Path = '\\Adjustments\Locked Adjustments\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Adjustment' AND L.Date_Locked is NOT Null update OrderItems set Tree_Path = '\\Manufacturing\Open Production Orders\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Production' AND L.Date_Locked is Null update OrderItems set Tree_Path = '\\Manufacturing\Open Production Orders\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Manufacturing' AND L.Date_Locked is Null AND ( select [Type] from OrderItems where ID = L.OrderItem_ID ) = 'Production' update OrderItems set Tree_Path = '\\Manufacturing\Locked Productions\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Production' AND L.Date_Locked is NOT Null update OrderItems set Tree_Path = '\\Manufacturing\Locked Productions\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join OrderItems L on L.ID = I.ID where L.[Type] = 'Manufacturing' AND L.Date_Locked is NOT Null AND ( select [Type] from OrderItems where ID = L.OrderItem_ID ) = 'Production' ------------------------------------------------------------------------------------------------------------------ -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- ------------------------------------------------------------------------------------------------------------------ update OrderItems set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Inserted I join OrderItems L on L.ID = I.ID end set NOCOUNT OFF end end GO -------------- -- Serials -- -------------- if exists ( select * from sysobjects where [Name] = 'Serials_Insert' AND [Type] = 'TR' ) drop trigger Serials_Insert GO create trigger Serials_Insert on Serials for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - Serials_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'Serials', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------------- -- Initialize any manually added records -- ------------------------------------------- update Serials set Resource_ID = L.Resource_ID, [Type] = L.[Type], Order_Name = L.Order_Name, Contact_ID = L.Contact_ID from Inserted I join Serials S on S.ID = I.ID join OrderItems L on L.ID = I.OrderItem_ID where I.Resource_ID is Null ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update Serials set Date_Modified = I.Date_Modified from Inserted I join Serials S on S.ID = I.ID set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Serials_Update' AND [Type] = 'TR' ) drop trigger Serials_Update GO create trigger Serials_Update on Serials for update as begin if @@NestLevel = 1 AND exists( select ID from Deleted where Date_Locked is NOT Null ) begin raiserror( 'Warning - Data is Locked', 11, 1 ) rollback end if exists( select ID from Inserted ) begin set NOCOUNT ON -- print 'Debug - Serials_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'Serials', I.ID, I.GUID, Columns_Updated() from Inserted I end update Serials set Number = S.ID from Inserted I join Serials S on S.ID = I.ID where I.Number is Null ---------------------------------------------- -- Set the Balance when the Serial is added -- ---------------------------------------------- update Serials set Balance = S.Quantity from Inserted I join Serials S on S.ID = I.ID where S.[Type] IN ( 'Purchase', 'Production' ) AND S.Date_Locked is NOT Null ----------------------------------------------- -- Decrease the Balance when the Lot is used -- ----------------------------------------------- update Serials set Balance = dbo.Maximum( 0, S.Balance - S.Quantity ) from Inserted I join Serials S on S.Resource_ID = I.Resource_ID AND S.Number = I.Number AND S.Balance > 0 where I.[Type] IN ( 'Sale', 'Service', 'Manufacturing' ) AND I.Date_Locked is NOT Null ------------------------------------------------------------------------------------------------------------------ -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- ------------------------------------------------------------------------------------------------------------------ update Serials set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Inserted I join Serials S on S.ID = I.ID set NOCOUNT OFF end end GO ---------------- -- Variations -- ---------------- if exists ( select * from sysobjects where [Name] = 'Variations_Insert' AND [Type] = 'TR' ) drop trigger Variations_Insert GO create trigger Variations_Insert on Variations for Insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - Variations_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'Variations', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update Variations set Date_Modified = I.Date_Modified from Inserted I join Variations V on V.ID = I.ID where I.Date_Modified is Null -- If it is not null then skip triggers set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Variations_Update' AND [Type] = 'TR' ) drop trigger Variations_Update GO create trigger Variations_Update on Variations for update as begin if @@NestLevel = 1 AND exists( select ID from Deleted where Date_Locked is NOT Null ) begin raiserror( 'Warning - Data is Locked', 11, 1 ) rollback end if exists( select ID from Inserted ) begin set NOCOUNT ON -- print 'Debug - Variations_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'Variations', I.ID, I.GUID, Columns_Updated() from Inserted I end update Variations set [Name] = R.[Name] from Inserted I join Variations V on V.ID = I.ID join Resources R on R.ID = V.Resource_ID update Variations set [Name] = O.Resource_Name from Inserted I join Variations V on V.ID = I.ID join OrderItems O on O.ID = V.OrderItem_ID update Variations set [Name] = R.Resource_Name from Inserted I join Variations V on V.ID = I.ID join Relationships R on R.ID = V.Relationship_ID update Variations set [Name] = C.Resource_Name from Inserted I join Variations V on V.ID = I.ID join Components C on C.ID = V.Component_ID update Variations set [Name] = S.[Name] from Inserted I join Variations V on V.ID = I.ID join Specs S on S.ID = V.Spec_ID if @@NESTLEVEL = 1 begin ----------------------------------- -- Force update of Parent OrderItem ----------------------------------- update OrderItems set Quantity = 0, Price = 0 -- force update of qty and price from the Order Item instead from Inserted I join OrderItems L on L.ID = I.OrderItem_ID end ------------------------------------------- -- Update Variations records of Resource -- ------------------------------------------- insert Variations ( Resource_ID, [Name], Variations_List, [Sub-Variations_List], Date_Modified ) -- Use Date_Modified to stop looping select R.ID, R.[Name], R.Variations_List, R.[Sub-Variations_List], GetDate() from Inserted I join OrderItems L on L.ID = I.OrderItem_ID join Resources R on R.ID = L.Resource_ID where I.Date_Locked is NOT Null AND R.Track_Qty_on_Hand = 1 AND NOT exists ( select ID from Variations V where V.Resource_ID = R.ID ) update Variations set [Name] = R.[Name], Quantity_00 = ( select top 1 Quantity_00 from Variations where Resource_ID = R.ID ) - I.Quantity_00, Quantity_01 = ( select top 1 Quantity_01 from Variations where Resource_ID = R.ID ) - I.Quantity_01, Quantity_02 = ( select top 1 Quantity_02 from Variations where Resource_ID = R.ID ) - I.Quantity_02, Quantity_03 = ( select top 1 Quantity_03 from Variations where Resource_ID = R.ID ) - I.Quantity_03, Quantity_04 = ( select top 1 Quantity_04 from Variations where Resource_ID = R.ID ) - I.Quantity_04, Quantity_05 = ( select top 1 Quantity_05 from Variations where Resource_ID = R.ID ) - I.Quantity_05, Quantity_06 = ( select top 1 Quantity_06 from Variations where Resource_ID = R.ID ) - I.Quantity_06, Quantity_07 = ( select top 1 Quantity_07 from Variations where Resource_ID = R.ID ) - I.Quantity_07, Quantity_08 = ( select top 1 Quantity_08 from Variations where Resource_ID = R.ID ) - I.Quantity_08, Quantity_09 = ( select top 1 Quantity_09 from Variations where Resource_ID = R.ID ) - I.Quantity_09, Quantity_10 = ( select top 1 Quantity_10 from Variations where Resource_ID = R.ID ) - I.Quantity_10, Quantity_11 = ( select top 1 Quantity_11 from Variations where Resource_ID = R.ID ) - I.Quantity_11, Quantity_12 = ( select top 1 Quantity_12 from Variations where Resource_ID = R.ID ) - I.Quantity_12, Quantity_13 = ( select top 1 Quantity_13 from Variations where Resource_ID = R.ID ) - I.Quantity_13, Quantity_14 = ( select top 1 Quantity_14 from Variations where Resource_ID = R.ID ) - I.Quantity_14, Quantity_15 = ( select top 1 Quantity_15 from Variations where Resource_ID = R.ID ) - I.Quantity_15, Quantity_16 = ( select top 1 Quantity_16 from Variations where Resource_ID = R.ID ) - I.Quantity_16, Quantity_17 = ( select top 1 Quantity_17 from Variations where Resource_ID = R.ID ) - I.Quantity_17, Quantity_18 = ( select top 1 Quantity_18 from Variations where Resource_ID = R.ID ) - I.Quantity_18, Quantity_19 = ( select top 1 Quantity_19 from Variations where Resource_ID = R.ID ) - I.Quantity_19, Quantity_20 = ( select top 1 Quantity_20 from Variations where Resource_ID = R.ID ) - I.Quantity_20, Quantity_21 = ( select top 1 Quantity_21 from Variations where Resource_ID = R.ID ) - I.Quantity_21, Quantity_22 = ( select top 1 Quantity_22 from Variations where Resource_ID = R.ID ) - I.Quantity_22, Quantity_23 = ( select top 1 Quantity_23 from Variations where Resource_ID = R.ID ) - I.Quantity_23, Quantity_24 = ( select top 1 Quantity_24 from Variations where Resource_ID = R.ID ) - I.Quantity_24, Quantity_25 = ( select top 1 Quantity_25 from Variations where Resource_ID = R.ID ) - I.Quantity_25, Quantity_26 = ( select top 1 Quantity_26 from Variations where Resource_ID = R.ID ) - I.Quantity_26, Quantity_27 = ( select top 1 Quantity_27 from Variations where Resource_ID = R.ID ) - I.Quantity_27, Quantity_28 = ( select top 1 Quantity_28 from Variations where Resource_ID = R.ID ) - I.Quantity_28, Quantity_29 = ( select top 1 Quantity_29 from Variations where Resource_ID = R.ID ) - I.Quantity_29 from Inserted I join OrderItems L on L.ID = I.OrderItem_ID join Resources R on R.ID = L.Resource_ID join Variations V on V.Resource_ID = L.Resource_ID where L.[Type] IN ( 'Sale', 'Manufacturing', 'Service' ) AND I.Date_Locked is NOT Null AND R.Track_Qty_on_Hand = 1 update Variations set [Name] = R.[Name], Quantity_00 = ( select top 1 Quantity_00 from Variations where Resource_ID = R.ID ) + I.Quantity_00, Quantity_01 = ( select top 1 Quantity_01 from Variations where Resource_ID = R.ID ) + I.Quantity_01, Quantity_02 = ( select top 1 Quantity_02 from Variations where Resource_ID = R.ID ) + I.Quantity_02, Quantity_03 = ( select top 1 Quantity_03 from Variations where Resource_ID = R.ID ) + I.Quantity_03, Quantity_04 = ( select top 1 Quantity_04 from Variations where Resource_ID = R.ID ) + I.Quantity_04, Quantity_05 = ( select top 1 Quantity_05 from Variations where Resource_ID = R.ID ) + I.Quantity_05, Quantity_06 = ( select top 1 Quantity_06 from Variations where Resource_ID = R.ID ) + I.Quantity_06, Quantity_07 = ( select top 1 Quantity_07 from Variations where Resource_ID = R.ID ) + I.Quantity_07, Quantity_08 = ( select top 1 Quantity_08 from Variations where Resource_ID = R.ID ) + I.Quantity_08, Quantity_09 = ( select top 1 Quantity_09 from Variations where Resource_ID = R.ID ) + I.Quantity_09, Quantity_10 = ( select top 1 Quantity_10 from Variations where Resource_ID = R.ID ) + I.Quantity_10, Quantity_11 = ( select top 1 Quantity_11 from Variations where Resource_ID = R.ID ) + I.Quantity_11, Quantity_12 = ( select top 1 Quantity_12 from Variations where Resource_ID = R.ID ) + I.Quantity_12, Quantity_13 = ( select top 1 Quantity_13 from Variations where Resource_ID = R.ID ) + I.Quantity_13, Quantity_14 = ( select top 1 Quantity_14 from Variations where Resource_ID = R.ID ) + I.Quantity_14, Quantity_15 = ( select top 1 Quantity_15 from Variations where Resource_ID = R.ID ) + I.Quantity_15, Quantity_16 = ( select top 1 Quantity_16 from Variations where Resource_ID = R.ID ) + I.Quantity_16, Quantity_17 = ( select top 1 Quantity_17 from Variations where Resource_ID = R.ID ) + I.Quantity_17, Quantity_18 = ( select top 1 Quantity_18 from Variations where Resource_ID = R.ID ) + I.Quantity_18, Quantity_19 = ( select top 1 Quantity_19 from Variations where Resource_ID = R.ID ) + I.Quantity_19, Quantity_20 = ( select top 1 Quantity_20 from Variations where Resource_ID = R.ID ) + I.Quantity_20, Quantity_21 = ( select top 1 Quantity_21 from Variations where Resource_ID = R.ID ) + I.Quantity_21, Quantity_22 = ( select top 1 Quantity_22 from Variations where Resource_ID = R.ID ) + I.Quantity_22, Quantity_23 = ( select top 1 Quantity_23 from Variations where Resource_ID = R.ID ) + I.Quantity_23, Quantity_24 = ( select top 1 Quantity_24 from Variations where Resource_ID = R.ID ) + I.Quantity_24, Quantity_25 = ( select top 1 Quantity_25 from Variations where Resource_ID = R.ID ) + I.Quantity_25, Quantity_26 = ( select top 1 Quantity_26 from Variations where Resource_ID = R.ID ) + I.Quantity_26, Quantity_27 = ( select top 1 Quantity_27 from Variations where Resource_ID = R.ID ) + I.Quantity_27, Quantity_28 = ( select top 1 Quantity_28 from Variations where Resource_ID = R.ID ) + I.Quantity_28, Quantity_29 = ( select top 1 Quantity_29 from Variations where Resource_ID = R.ID ) + I.Quantity_29 from Inserted I join OrderItems L on L.ID = I.OrderItem_ID join Resources R on R.ID = L.Resource_ID join Variations V on V.Resource_ID = L.Resource_ID where L.[Type] IN ( 'Purchase', 'Adjustment', 'Production' ) AND I.Date_Locked is NOT Null AND R.Track_Qty_on_Hand = 1 ------------------------------------------------------------------------------------------------------------------ -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- ------------------------------------------------------------------------------------------------------------------ update Variations set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Inserted I join Variations V on V.ID = I.ID set NOCOUNT OFF end end GO ---------------- -- Activities -- ---------------- -- unused does not work ??? if exists ( select * from sysobjects where [Name] = 'SumActivities' AND [Type] = 'P' ) drop procedure dbo.SumActivities GO create procedure dbo.SumActivities( @ID varchar( 100 ) ) as begin set NOCOUNT ON update Activities set Minutes = ( select Sum( isNull( C.Minutes, 0 ) ) from Activities C where C.Activity_ID = ID ), Hours = ( select Sum( isNull( C.Hours, 0 ) ) from Activities C where C.Activity_ID = ID ), Days = ( select Sum( isNull( C.Days, 0 ) ) from Activities C where C.Activity_ID = ID ), Date_Start = ( select Min( isNull( C.Date_Start, 0 ) ) from Activities C where C.Activity_ID = ID ), Date_Stop = ( select Max( isNull( C.Date_Stop, 0 ) ) from Activities C where C.Activity_ID = ID ) where ID = @ID set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'ActualMinutes' AND [Type] = 'FN' ) drop function dbo.ActualMinutes GO create function dbo.ActualMinutes( @ID int, @Start datetime, @Stop datetime ) returns int begin return DateDiff( minute, @Start, @Stop ) end GO if exists ( select * from sysobjects where [Name] = 'AvailMinutes' AND [Type] = 'FN' ) drop function dbo.AvailMinutes GO create function dbo.AvailMinutes( @Day varchar( 100 ), @Stop_Time datetime ) returns int begin declare @S varchar( 100 ), @T varchar( 100 ), @Z varchar( 100 ), @Pos int declare @Result int select @Result = 0 declare @Count int select @Count = dbo.Tokens( ',', @Day ) while @Count > 0 begin select @S = dbo.Token( ',', @Day, @Count ) select @T = dbo.Token( '-', @S, 2 ) select @S = dbo.Token( '-', @S, 1 ) select @Pos = CharIndex( ':', @S ) if @Pos <> 0 select @S = SubString( @S, 1, @Pos - 1 ) + '.' + cast( Round( 1000 * cast( SubString( @S, @Pos + 1, 2 ) as int ) / 60, 0 ) as varchar( 10 ) ) select @Pos = CharIndex( ':', @T ) if @Pos <> 0 select @T = SubString( @T, 1, @Pos - 1 ) + '.' + cast( Round( 1000 * cast( SubString( @T, @Pos + 1, 2 ) as int ) / 60, 0 ) as varchar( 10 ) ) if @Stop_Time = Null select @Z = @T else select @Z = cast( DatePart( hh, @Stop_Time ) + DatePart( mi, @Stop_Time ) / 60 as varchar( 10 ) ) select @Result = @Result + Round( 60 * ( dbo.Minimum( cast( @T as float ), cast( @T as float ) ) - cast( @S as float ) ), 0 ) select @Count = @Count - 1 end return @Result end GO if exists ( select * from sysobjects where [Name] = 'EndOfMinutes' AND [Type] = 'FN' ) drop function dbo.EndOfMinutes GO create function dbo.EndOfMinutes( @ID int, @Start datetime, @Minutes int ) returns datetime begin return @Start end GO if exists ( select * from sysobjects where [Name] = 'EndOfActivity' AND [Type] = 'FN' ) drop function dbo.EndOfActivity GO create function dbo.EndOfActivity( @ID int, @Start datetime, @Minutes int ) returns datetime begin declare @Result dateTime, @WeekDay int declare @Day varchar( 100 ), @Sun varchar( 100 ), @Mon varchar( 100 ), @Tue varchar( 100 ) declare @Wed varchar( 100 ), @Thu varchar( 100 ), @Fri varchar( 100 ), @Sat varchar( 100 ) declare @Next_ID int, @Next_Start datetime, @Next_Stop datetime declare @Contact varchar( 100 ), @Resource varchar( 100 ) select @Result = DateAdd( minute, @Minutes, @Start ) -- default old way select @Contact = Contact_Name from Activities where ID = @ID select @Resource = Resource_Name from Activities where ID = @ID ------------------------------------------- -- load the available hours for each day -- ------------------------------------------- if @Contact <> '' begin select @Sun = Sunday_Hours_List from Contacts where [Name] = @Contact select @Mon = Monday_Hours_List from Contacts where [Name] = @Contact select @Tue = Tuesday_Hours_List from Contacts where [Name] = @Contact select @Wed = Wednesday_Hours_List from Contacts where [Name] = @Contact select @Thu = Thursday_Hours_List from Contacts where [Name] = @Contact select @Fri = Friday_Hours_List from Contacts where [Name] = @Contact select @Sat = Saturday_Hours_List from Contacts where [Name] = @Contact end else if @Resource <> '' begin select @Sun = Sunday_Hours_List from Resources where [Name] = @Resource select @Mon = Monday_Hours_List from Resources where [Name] = @Resource select @Tue = Tuesday_Hours_List from Resources where [Name] = @Resource select @Wed = Wednesday_Hours_List from Resources where [Name] = @Resource select @Thu = Thursday_Hours_List from Resources where [Name] = @Resource select @Fri = Friday_Hours_List from Resources where [Name] = @Resource select @Sat = Saturday_Hours_List from Resources where [Name] = @Resource end else begin select @Sun = Sunday_Hours_List from Contacts where Company_Configuration = 1 select @Mon = Monday_Hours_List from Contacts where Company_Configuration = 1 select @Tue = Tuesday_Hours_List from Contacts where Company_Configuration = 1 select @Wed = Wednesday_Hours_List from Contacts where Company_Configuration = 1 select @Thu = Thursday_Hours_List from Contacts where Company_Configuration = 1 select @Fri = Friday_Hours_List from Contacts where Company_Configuration = 1 select @Sat = Saturday_Hours_List from Contacts where Company_Configuration = 1 end -------------------------------------------------- -- continue until all Minutes have been used up -- -------------------------------------------------- while @Minutes > 0 begin select @Next_ID = ( select top 1 ID from Activities where Contact_Name = @Contact AND ID <> @ID AND Resource_Name = @Resource AND Activities_Count = 0 AND Date_Start > @Start order by Date_Start ) select @Next_Start = isNull( ( select Date_Start from Activities where ID = @Next_ID ), DateAdd( year, 5, @Start ) ) select @Next_Stop = isNull( ( select Date_Stop from Activities where ID = @Next_ID ), DateAdd( year, 5, @Start ) ) ---------------------------------------------------------------------- -- remove Minutes each day while no conflict with the next activity -- ---------------------------------------------------------------------- while @Minutes > 0 AND @Next_Start > @Start begin select @WeekDay = DatePart( weekday, @Start ) if @WeekDay = 1 select @Day = @Sun else if @WeekDay = 2 select @Day = @Mon else if @WeekDay = 3 select @Day = @Tue else if @WeekDay = 4 select @Day = @Wed else if @WeekDay = 5 select @Day = @Thu else if @WeekDay = 6 select @Day = @Fri else if @WeekDay = 7 select @Day = @Sat ------------------------------------------------------------------------------- -- catch possible hourly conflicts with the next activity if on the same day -- ------------------------------------------------------------------------------- if DatePart( dy, @Next_Start ) = DatePart( dy, @Start ) begin select @Minutes = dbo.Maximum( 0, @Minutes - dbo.AvailMinutes( @Day, @Next_Start ) ) if @Minutes > 0 select @Start = @Next_Stop end else begin select @Minutes = dbo.Maximum( 0, @Minutes - dbo.AvailMinutes( @Day, Null ) ) if @Minutes > 0 select @Start = dbo.DateOnly( @Start ) + 1 end end end return @Result end GO if exists ( select * from sysobjects where [Name] = 'FirstAvailableDate' AND [Type] = 'FN' ) drop function dbo.FirstAvailableDate GO create function dbo.FirstAvailableDate( @ID int, @Start datetime ) returns datetime begin declare @Count int, @Minutes int, @GapMinutes int, @OldDay int, @WeekDay int declare @Sun varchar( 100 ), @Mon varchar( 100 ), @Tue varchar( 100 ) declare @Wed varchar( 100 ), @Thu varchar( 100 ), @Fri varchar( 100 ), @Sat varchar( 100 ) declare @Next_Start datetime, @Contact varchar( 100 ), @Resource varchar( 100 ) select @Count = Activities_Count from Activities where ID = @ID select @Minutes = Minutes from Activities where ID = @ID select @Contact = Contact_Name from Activities where ID = @ID select @Resource = Resource_Name from Activities where ID = @ID ------------------------------------------- -- load the available hours for each day -- ------------------------------------------- if @Contact <> '' begin select @Sun = Sunday_Hours_List from Contacts where [Name] = @Contact select @Mon = Monday_Hours_List from Contacts where [Name] = @Contact select @Tue = Tuesday_Hours_List from Contacts where [Name] = @Contact select @Wed = Wednesday_Hours_List from Contacts where [Name] = @Contact select @Thu = Thursday_Hours_List from Contacts where [Name] = @Contact select @Fri = Friday_Hours_List from Contacts where [Name] = @Contact select @Sat = Saturday_Hours_List from Contacts where [Name] = @Contact end else if @Resource <> '' begin select @Sun = Sunday_Hours_List from Resources where [Name] = @Resource select @Mon = Monday_Hours_List from Resources where [Name] = @Resource select @Tue = Tuesday_Hours_List from Resources where [Name] = @Resource select @Wed = Wednesday_Hours_List from Resources where [Name] = @Resource select @Thu = Thursday_Hours_List from Resources where [Name] = @Resource select @Fri = Friday_Hours_List from Resources where [Name] = @Resource select @Sat = Saturday_Hours_List from Resources where [Name] = @Resource end else begin select @Sun = Sunday_Hours_List from Contacts where Company_Configuration = 1 select @Mon = Monday_Hours_List from Contacts where Company_Configuration = 1 select @Tue = Tuesday_Hours_List from Contacts where Company_Configuration = 1 select @Wed = Wednesday_Hours_List from Contacts where Company_Configuration = 1 select @Thu = Thursday_Hours_List from Contacts where Company_Configuration = 1 select @Fri = Friday_Hours_List from Contacts where Company_Configuration = 1 select @Sat = Saturday_Hours_List from Contacts where Company_Configuration = 1 end select @WeekDay = 1 select @OldDay = 0 -------------------------------------------------------------- -- if it has not changed then the activity fits in the slot -- -------------------------------------------------------------- while @WeekDay <> @OldDay begin -- find first day with non-empty hours select @WeekDay = DatePart( weekday, @Start ) select @OldDay = @WeekDay if @WeekDay = 1 AND isNull( @Sun, '' ) = '' select @Weekday = @WeekDay + 1 if @WeekDay = 2 AND isNull( @Mon, '' ) = '' select @Weekday = @WeekDay + 1 if @WeekDay = 3 AND isNull( @Tue, '' ) = '' select @Weekday = @WeekDay + 1 if @WeekDay = 4 AND isNull( @Wed, '' ) = '' select @Weekday = @WeekDay + 1 if @WeekDay = 5 AND isNull( @Thu, '' ) = '' select @Weekday = @WeekDay + 1 if @WeekDay = 6 AND isNull( @Fri, '' ) = '' select @Weekday = @WeekDay + 1 if @WeekDay = 7 AND isNull( @Sat, '' ) = '' select @Weekday = @WeekDay + 1 ---------------------------------------------------------------- -- if it has children then let them worry about an exact slot -- ---------------------------------------------------------------- if @Count <> 0 select @Start = @Start + @WeekDay - @OldDay else begin ------------------------------------------------------------------------------------------------------------------ -- use the end of the last activity found or the default date from above as the potential start of the activity -- ------------------------------------------------------------------------------------------------------------------ select @Start = isNull( ( select top 1 Date_Stop from Activities where Contact_Name = @Contact AND ID <> @ID AND Resource_Name = @Resource AND Activities_Count = 0 AND Date_Start < @Start + @WeekDay - @OldDay AND Date_Stop > @Start + @WeekDay - @OldDay order by Date_Stop desc ), @Start + @WeekDay - @OldDay ) select @GapMinutes = 0 while @Minutes > @GapMinutes begin --------------------------------------------------------------------------------------------------------- -- look for the start of the next activity or the default 5 years later to caluclate the gap available -- --------------------------------------------------------------------------------------------------------- select @Next_Start = isNull( ( select top 1 Date_Start from Activities where Contact_Name = @Contact AND ID <> @ID AND Resource_Name = @Resource AND Activities_Count = 0 AND Date_Start > @Start order by Date_Start ), DateAdd( year, 5, @Start ) ) select @GapMinutes = DateDiff( minute, @Start, @Next_Start ) if @Minutes <= @GapMinutes return @Start -- EXIT WHEN IT FITS ---------------------------------------------------------------------------------------- -- if not enough room then use the end of the next activity found that is interfering -- ---------------------------------------------------------------------------------------- select @Start = ( select top 1 Date_Stop from Activities where Contact_Name = @Contact AND ID <> @ID AND Resource_Name = @Resource AND Activities_Count = 0 AND Date_Start > @Start order by Date_Start ) end end end return @Start end GO -- update each child in sequence to reschedule if exists ( select * from sysobjects where [Name] = 'UpdChildActivities' AND [Type] = 'P' ) drop procedure dbo.UpdChildActivities GO create procedure dbo.UpdChildActivities( @ID_List varchar( 4000 ) ) as begin set NOCOUNT ON -- print 'Debug - UpdChildren: ' + @ID_LIST declare @I int, @Count int, @PID int, @ID int, @Start datetime set @I = 1 set @Count = dbo.Tokens( ',', @ID_List ) while @I <= @Count begin set @PID = dbo.Token( ',', @ID_List, @I ) declare CurRec cursor local for select ID from Activities where Activity_ID = @PID order by Sequence, ID open CurRec fetch CurRec into @ID if @@FETCH_STATUS = 0 begin -- process the first select @Start = ( select Date_Start from Activities where ID = @PID ) update Activities set Date_Start = dbo.FirstAvailableDate( @ID, @Start ), Date_Stop = dbo.EndOfActivity( @ID, @Start, Minutes ) where ID = @ID select @Start = ( select Date_Stop from Activities where ID = @ID ) fetch CurRec into @ID while @@FETCH_STATUS = 0 begin -- then process all the rest update Activities set Date_Start = dbo.FirstAvailableDate( @ID, @Start ), Date_Stop = dbo.EndOfActivity( @ID, @Start, Minutes ) where ID = @ID select @Start = ( select Date_Stop from Activities where ID = @ID ) fetch CurRec into @ID end end close CurRec deallocate CurRec select @I = @I + 1 end set NOCOUNT OFF end GO -- update each sibling in sequence to reschedule if exists ( select * from sysobjects where [Name] = 'UpdSiblingActivities' AND [Type] = 'P' ) drop procedure dbo.UpdSiblingActivities GO create procedure dbo.UpdSiblingActivities( @ID_List varchar( 4000 ) ) as begin set NOCOUNT ON -- print 'Debug - UpdSiblings: ' + @ID_LIST declare @I int, @Count int, @ID int, @PID int, @Seq int, @Start datetime select @I = 1 select @Count = dbo.Tokens( ',', @ID_List ) while @I <= @Count begin select @ID = dbo.Token( ',', @ID_List, @I ) select @PID = Activity_ID from Activities where ID = @ID select @Seq = [Sequence] from Activities where ID = @ID select @Start = Date_Stop from Activities where ID = @ID declare CurRec cursor local for select ID, Activities_Count from Activities where Activity_ID = @PID AND ( [Sequence] > @Seq OR [Sequence] = @Seq AND ID > @ID ) order by [Sequence], ID open CurRec fetch CurRec into @ID, @Count if @@FETCH_STATUS = 0 begin update Activities set Date_Start = dbo.FirstAvailableDate( @ID, dbo.MaxDate( @Start, Date_Start ) ), Date_Stop = dbo.EndOfActivity( @ID, dbo.MaxDate( @Start, Date_Start ), Minutes ) where ID = @ID select @Start = Date_Stop from Activities where ID = @ID fetch CurRec into @ID, @Count while @@FETCH_STATUS = 0 begin update Activities set Date_Start = dbo.FirstAvailableDate( @ID, dbo.MaxDate( @Start, Date_Start ) ), Date_Stop = dbo.EndOfActivity( @ID, dbo.MaxDate( @Start, Date_Start ), Minutes ) where ID = @ID if @Count > 0 exec dbo.UpdChildActivities @ID select @Start = Date_Stop from Activities where ID = @ID fetch CurRec into @ID, @Count end end close CurRec deallocate CurRec select @I = @I + 1 end set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Activities_Insert' AND [Type] = 'TR' ) drop trigger Activities_Insert GO create trigger Activities_Insert on Activities for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - Activities_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'Activities', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update Activities set Date_Modified = I.Date_Modified from Inserted I join Activities A on A.ID = I.ID set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Activities_Update' AND [Type] = 'TR' ) drop trigger Activities_Update GO create trigger Activities_Update on Activities for update as begin if @@NestLevel = 1 AND exists( select ID from Deleted where Date_Locked is NOT Null ) begin raiserror( 'Warning - Data is Locked', 11, 1 ) rollback end if NOT exists( select ID from Inserted ) OR Update( Photo1 ) OR Update( Photo2 ) OR Update( Photo3 ) OR Update( Photo4 ) OR Update( Photo5 ) OR Update( Photo6 ) OR Update( Photo7 ) OR Update( Photo8 ) OR Update( Photo9 ) OR Update( Photo1Thumb ) OR Update( Photo2Thumb ) OR Update( Photo3Thumb ) OR Update( Photo4Thumb ) OR Update( Photo5Thumb ) OR Update( Photo6Thumb ) OR Update( Photo7Thumb ) OR Update( Photo8Thumb ) OR Update( Photo9Thumb ) set NOCOUNT OFF else begin set NOCOUNT ON -- print 'Debug - Activities_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'Activities', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------- -- Update all Related Fields -- ------------------------------- update Activities set Contact_Name = C.[Name], Late_Notification_List = C.Late_Notification_List, Notify_when_Late_by_Days = C.Notify_when_Late_by_Days, Late_Reminder_every_Hours = C.Late_Reminder_every_Hours, [Follow-Up_Notification_List] = C.[Follow-Up_Notification_List], [Follow-Up_every_Days] = C.[Follow-Up_every_Days], [Late_Follow-Up_Reminder_every_Hours] = C.[Late_Follow-Up_Reminder_every_Hours] from Inserted I join Activities A on A.ID = I.ID join Contacts C on C.ID = A.Contact_ID where A.Contact_Name is Null OR Update( Contact_ID ) update Activities set Catalog_Name = C.[Name] from Inserted I join Activities A on A.ID = I.ID join Catalog C on C.ID = A.Catalog_ID where A.Catalog_Name is Null OR Update( Catalog_ID ) update Activities set Resource_Name = R.[Name], Late_Notification_List = R.Late_Notification_List, Notify_when_Late_by_Days = R.Notify_when_Late_by_Days, Late_Reminder_every_Hours = R.Late_Reminder_every_Hours, [Follow-Up_Notification_List] = R.[Follow-Up_Notification_List], [Follow-Up_every_Days] = R.[Follow-Up_every_Days], [Late_Follow-Up_Reminder_every_Hours] = R.[Late_Follow-Up_Reminder_every_Hours] from Inserted I join Activities A on A.ID = I.ID join Deleted D on D.ID = I.ID join Resources R on R.ID = A.Resource_ID where A.Resource_Name is Null OR Update( Resource_ID ) update Activities set Contact_ID = C.ID, Late_Notification_List = C.Late_Notification_List, Notify_when_Late_by_Days = C.Notify_when_Late_by_Days, Late_Reminder_every_Hours = C.Late_Reminder_every_Hours, [Follow-Up_Notification_List] = C.[Follow-Up_Notification_List], [Follow-Up_every_Days] = C.[Follow-Up_every_Days], [Late_Follow-Up_Reminder_every_Hours] = C.[Late_Follow-Up_Reminder_every_Hours] from Inserted I join Activities A on A.ID = I.ID join Deleted D on D.ID = I.ID join Contacts C on C.[Name] = A.Contact_Name where A.Contact_ID is Null OR Update( Contact_Name ) update Activities set Catalog_ID = C.ID from Inserted I join Activities A on A.ID = I.ID join Deleted D on D.ID = I.ID join [Catalog] C on C.[Name] = A.Catalog_Name where A.Catalog_ID is Null OR Update( Catalog_Name ) update Activities set Resource_ID = R.ID, Late_Notification_List = R.Late_Notification_List, Notify_when_Late_by_Days = R.Notify_when_Late_by_Days, Late_Reminder_every_Hours = R.Late_Reminder_every_Hours, [Follow-Up_Notification_List] = R.[Follow-Up_Notification_List], [Follow-Up_every_Days] = R.[Follow-Up_every_Days], [Late_Follow-Up_Reminder_every_Hours] = R.[Late_Follow-Up_Reminder_every_Hours] from Inserted I join Activities A on A.ID = I.ID join Deleted D on D.ID = I.ID join Resources R on R.[Name] = A.Resource_Name where A.Resource_ID is Null OR Update( Resource_Name ) ---------------------------------------- -- Hold any activities when necessary -- ---------------------------------------- if exists( select C.ID from Inserted I join Activities A on A.ID = I.ID join Contacts C on C.ID = A.Contact_ID where C.Active = 0 OR C.Hold_All_Activity = 1 ) begin raiserror( 'Warning - Contact is not Active or Hold All Activity is True', 11, 1 ) rollback end else if exists( select R.ID from Inserted I join Activities A on A.ID = I.ID join Resources R on R.ID = I.Resource_ID where R.Active = 0 OR R.Hold_All_Activity = 1 ) begin raiserror( 'Warning - Resource is not Active or Hold All Activity is True', 11, 1 ) rollback end else begin ----------------------------------------------------- -- Update Tree_Path to jump to the source document -- ----------------------------------------------------- update Activities set Tree_Path = '\\Sales\Open Sales Orders\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join Activities A on A.ID = I.ID join OrderItems L on L.ID = A.OrderItem_ID where L.[Type] = 'Sale' AND L.Date_Locked is Null update Activities set Tree_Path = '\\Sales\Locked Invoices\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join Activities A on A.ID = I.ID join OrderItems L on L.ID = A.OrderItem_ID where L.[Type] = 'Sale' AND L.Date_Locked is NOT Null update Activities set Tree_Path = '\\Sales\Open Service Orders\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join Activities A on A.ID = I.ID join OrderItems L on L.ID = A.OrderItem_ID where L.[Type] = 'Service' AND L.Date_Locked is Null update Activities set Tree_Path = '\\Sales\Locked Service Invoices\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join Activities A on A.ID = I.ID join OrderItems L on L.ID = A.OrderItem_ID where L.[Type] = 'Service' AND L.Date_Locked is NOT Null update Activities set Tree_Path = '\\Manufacturing\Open Production Orders\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join Activities A on A.ID = I.ID join OrderItems L on L.ID = A.OrderItem_ID where L.[Type] = 'Production' AND L.Date_Locked is Null update Activities set Tree_Path = '\\Manufacturing\Locked Productions\Search\' + Cast( L.Order_ID as varchar( 20 ) ) from Inserted I join Activities A on A.ID = I.ID join OrderItems L on L.ID = A.OrderItem_ID where L.[Type] = 'Production' AND L.Date_Locked is NOT Null -------------------------------------------- -- update from template if it was changed -- -------------------------------------------- update Activities set Contact_Name = T.Contact_Name, Resource_Name = T.Resource_Name, Note = T.Note, Audio = T.Audio, Video = T.Video, Change_Notification_List = T.Change_Notification_List, Notification_Condition = T.Notification_Condition, Late_Notification_List = T.Late_Notification_List, Notify_when_Late_by_Days = T.Notify_when_Late_by_Days, Late_Reminder_every_Hours = T.Late_Reminder_every_Hours, [Follow-Up_Notification_List] = T.[Follow-Up_Notification_List], [Late_Follow-Up_Reminder_every_Hours] = T.[Late_Follow-Up_Reminder_every_Hours], Photo1 = T.Photo1, Photo1Thumb = T.Photo1Thumb, Photo1Name = T.Photo1Name, Photo2 = T.Photo2, Photo2Thumb = T.Photo2Thumb, Photo2Name = T.Photo2Name, Photo3 = T.Photo3, Photo3Thumb = T.Photo3Thumb, Photo3Name = T.Photo3Name from Activities join Deleted D on D.ID = Activities.ID join Activities T on T.[Name] = Activities.Template_Name where Activities.Template_Name <> D.Template_Name if exists( select I.ID from Inserted I join Deleted D on D.ID = I.ID where I.Template_Name <> D.Template_Name ) begin declare @ID int, @TID int declare Changed cursor local for select A.ID, T.ID from Activities as A join Deleted as D on D.ID = A.ID join Activities as T on T.[Name] = A.[Template_Name] where A.Template_Name <> D.Template_Name open Changed fetch Changed into @ID, @TID while @@FETCH_STATUS = 0 begin exec CopyChildren 'Activities', @TID, @ID fetch Changed into @ID, @TID end close Changed deallocate Changed end -------------------------------- -- Auto-Sequence when omitted -- -------------------------------- update Activities set [Sequence] = ( select Max( isNull( [Sequence], 0 ) ) + 1 from Activities where Activity_ID = I.Activity_ID ) from Inserted I join Activities A on A.ID = I.ID where A.Sequence is Null -- ------------------------------------------------------------------- -- -- first get default start date from parent for Inserted records -- -- ------------------------------------------------------------------- -- update Activities set Date_Start = isNull( ( select Date_Start from Activities where ID = I.Activity_ID ), A.Date_Start ) -- from Inserted I join Activities A on A.ID = I.ID -- where I.Activity_ID is NOT Null AND I.Date_Modified is Null -- Date_Modified is Null when called from Insert trigger -- ------------------------------------------------------------------------------- -- -- update start date from previous sibling if it exists for Inserted records -- -- ------------------------------------------------------------------------------- -- update Activities set Date_Start = isNull( ( select top 1 Date_Stop from Activities where Activity_ID = I.Activity_ID AND -- ( [Sequence] < A.[Sequence] OR [Sequence] = A.[Sequence] AND ID < I.ID ) -- order by [Sequence] desc, ID desc ), A.Date_Start ) -- from Inserted I join Activities A on A.ID = I.ID -- where I.Activity_ID is NOT Null AND I.Date_Modified is Null -- Date_Modified is Null when called from Insert trigger -- ------------------------------------------------------------------------ -- -- handle changes to the period by fixing the Minutes, Hours and Days -- -- ------------------------------------------------------------------------ -- update Activities set Date_Stop = dbo.EndOfActivity( A.ID, A.Date_Start, A.Minutes ), Hours = Round( A.Minutes / 60, 0 ) -- from Inserted I join Activities A on A.ID = I.ID -- join Deleted D on D.ID = I.ID where I.Minutes <> D.Minutes -- update Activities set Date_Stop = dbo.EndOfActivity( A.ID, A.Date_Start, A.Hours * 60 ), Minutes = A.Hours * 60 -- from Inserted I join Activities A on A.ID = I.ID -- join Deleted D on D.ID = I.ID where I.Hours <> D.Hours -- update Activities set Date_Stop = DateAdd( day, A.Days, A.Date_Start ) -- from Inserted I join Activities A on A.ID = I.ID -- join Deleted D on D.ID = I.ID where I.Days <> D.Days -- update Activities set Minutes = dbo.ActualMinutes( A.ID, A.Date_Start, A.Date_Stop ) -- from Inserted I join Activities A on A.ID = I.ID -- join Deleted D on D.ID = I.ID where I.Days <> D.Days -- update Activities set Hours = Round( A.Minutes / 60, 0 ) -- from Inserted I join Activities A on A.ID = I.ID -- join Deleted D on D.ID = I.ID where I.Days <> D.Days -- ---------------------------------------------------------------------------------------- -- -- handle changes to start date by validating the Start date and fixing the Stop date -- -- ---------------------------------------------------------------------------------------- -- update Activities set Date_Start = dbo.FirstAvailableDate( A.ID, A.Date_Start ) -- from Inserted I join Activities A on A.ID = I.ID -- join Deleted D on D.ID = I.ID where I.Date_Start <> D.Date_Start -- update Activities set Date_Stop = dbo.EndOfActivity( A.ID, A.Date_Start, A.Minutes ) -- from Inserted I join Activities A on A.ID = I.ID -- join Deleted D on D.ID = I.ID where I.Date_Start <> D.Date_Start -- ----------------------------------------------------------------------- -- -- handle changes to stop date by fixing the Minutes, Hours and Days -- -- ----------------------------------------------------------------------- -- update Activities set Minutes = dbo.ActualMinutes( A.ID, A.Date_Start, A.Date_Stop ) -- from Inserted I join Activities A on A.ID = I.ID -- join Deleted D on D.ID = I.ID where I.Date_Stop <> D.Date_Stop -- update Activities set Hours = Round( A.Minutes / 60, 0 ), Days = DateDiff( day, A.Date_Start, A.Date_Stop ) -- from Inserted I join Activities A on A.ID = I.ID -- join Deleted D on D.ID = I.ID where I.Date_Stop <> D.Date_Stop -- if @@NESTLEVEL = 1 begin ----------------------------------------- -- update Child Activities dates first -- ----------------------------------------- -- declare @ID_List varchar( 4000 ) -- select @ID_List = Coalesce( @ID_List + ',', '' ) + cast( I.ID as varchar( 10 ) ) -- from Inserted I join Deleted D on D.ID = I.ID -- where I.Date_Start <> D.Date_Start AND I.Activities_Count > 0 -- select @ID_List = Coalesce( @ID_List + ',', '' ) + cast( C.ID as varchar( 10 ) ) -- from Inserted I join Deleted D on D.ID = I.ID -- join Activities C on C.Activity_ID = I.ID -- where I.Date_Start <> D.Date_Start AND I.Activities_Count > 0 AND C.Activities_Count > 0 -- exec dbo.UpdChildActivities @ID_List -- ------------------------------------------------ -- -- update next Siblings Activities dates next -- -- ------------------------------------------------ -- select @ID_List = Null -- select @ID_List = Coalesce( @ID_List + ',', '' ) + cast( I.ID as varchar( 10 ) ) -- from Inserted I join Deleted D on D.ID = I.ID -- where I.Date_Start <> D.Date_Start AND I.Activity_ID is NOT Null -- exec dbo.UpdSiblingActivities @ID_List ---------------------------------- -- update all parent Activities -- ---------------------------------- update Activities set Minutes = ( select Sum( isNull( C.Minutes, 0 ) ) from Activities C where C.Activity_ID = A.ID ), Hours = ( select Sum( isNull( C.Hours, 0 ) ) from Activities C where C.Activity_ID = A.ID ), Days = ( select Sum( isNull( C.Days, 0 ) ) from Activities C where C.Activity_ID = A.ID ), Date_Start = ( select Min( isNull( C.Date_Start, 0 ) ) from Activities C where C.Activity_ID = A.ID ), Date_Stop = ( select Max( isNull( C.Date_Stop, 0 ) ) from Activities C where C.Activity_ID = A.ID ), Activities_Count = ( select Count( C.ID ) from Activities C where C.Activity_ID = A.ID ) from Activities A where A.ID IN ( select Activity_ID from Inserted ) -- ------------------------------------------------------------------------------ -- -- update next Siblings of all Parent Activities when we are Sub-Activities -- -- ------------------------------------------------------------------------------ -- select @ID_List = Null -- select @ID_List = Coalesce( @ID_List + ',', '' ) + cast( I.Activity_ID as varchar( 10 ) ) -- from Inserted I join Deleted D on D.ID = I.ID -- where I.Date_Start <> D.Date_Start AND I.Activity_ID is NOT Null -- exec dbo.UpdSiblingActivities @ID_List ---------------------------------------- -- update all grand parent Activities -- ---------------------------------------- update Activities set Minutes = ( select Sum( isNull( C.Minutes, 0 ) ) from Activities C where C.Activity_ID = A.ID ), Hours = ( select Sum( isNull( C.Hours, 0 ) ) from Activities C where C.Activity_ID = A.ID ), Days = ( select Sum( isNull( C.Days, 0 ) ) from Activities C where C.Activity_ID = A.ID ), Date_Start = ( select Min( isNull( C.Date_Start, 0 ) ) from Activities C where C.Activity_ID = A.ID ), Date_Stop = ( select Max( isNull( C.Date_Stop, 0 ) ) from Activities C where C.Activity_ID = A.ID ) from Activities A where A.ID IN ( select P.Activity_ID from Inserted I join Activities P on P.ID = I.Activity_ID ) -- end ------------------------------------ -- Add any required Notifications -- ------------------------------------ insert Notifications ( Table_Name, Table_ID, Notification_List, Subject, Body ) select 'Activities', A.ID, A.Change_Notification_List, 'Alert on ' + A.[Name], 'select ' + dbo.ModColList( 'Activities', Columns_Updated() ) + ' from Activities where ID = ' + Cast( I.ID as varchar( 10 ) ) from Inserted I join Activities A on A.ID = I.ID where A.Change_Notification_List is NOT Null AND A.Notification_Condition is Null AND A.Date_Locked is Null if ( select Count( ID ) from Inserted where Change_Notification_List is NOT Null AND Notification_Condition is NOT Null ) > 0 begin declare @Cmd varchar( 4000 ), @CurID varchar( 10 ), @Name varchar( 50 ), @Notify varchar( 500 ), @Condition varchar( 500 ) declare CurRec cursor local for select ID, [Name], Change_Notification_List, Notification_Condition from Inserted where Change_Notification_List is NOT Null AND Notification_Condition is NOT Null open CurRec fetch CurRec into @CurID, @Name, @Notify, @Condition while @@FETCH_STATUS = 0 begin select @Cmd = 'if exists( select ID from Activities where ID = ' + @CurID + ' AND ' + @Condition + ' ) ' + 'insert Notifications ( Table_Name, Table_ID, Notification_List, Subject, Body ) ' + 'values( ''Activities'', ' + @CurID + ', ''' + @Notify + ''', ''' + @Condition + ' on ' + rTrim( @Name ) + ''', ' + '''select ' + Replace( dbo.ModColList( 'Activities', Columns_Updated() ), '''', '''''' ) + ' from Activities where ID = ' + @CurID + ''' )' exec( @Cmd ) fetch CurRec into @CurID, @Name, @Notify, @Condition end close CurRec deallocate CurRec end ------------------------------------------------------------------------------------------------------------------ -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- ------------------------------------------------------------------------------------------------------------------ update Activities set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Inserted I join Activities A on A.ID = I.ID end set NOCOUNT OFF end end GO if exists ( select * from sysobjects where [Name] = 'Activities_Delete' AND [Type] = 'TR' ) drop trigger Activities_Delete GO create trigger Activities_Delete on Activities for delete as begin if @@NestLevel = 1 AND exists( select ID from Deleted where Date_Locked is NOT Null ) begin raiserror( 'Warning - Data is Locked', 11, 1 ) rollback end if exists( select ID from Deleted ) begin set NOCOUNT ON -- print 'Debug - Activities_Delete' delete Notes where Activity_ID IN ( select ID from Deleted ) delete Notes where Activity_ID IN ( select C.ID from Deleted D join Activities C on C.Activity_ID = D.ID ) -- delete Notes where Activity_ID IN ( select C.ID from Deleted D join Activities C on C.Activity_ID = D.ID ) delete Activities where Activity_ID IN ( select ID from Deleted ) delete Activities where Activity_ID IN ( select C.ID from Deleted D join Activities C on C.Activity_ID = D.ID ) set NOCOUNT OFF end end GO -------------- -- Accounts -- -------------- if exists ( select * from sysobjects where [Name] = 'Accounts_Insert' AND [Type] = 'TR' ) drop trigger Accounts_Insert GO create trigger Accounts_Insert on Accounts for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - Accounts_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'Accounts', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update Accounts set Date_Modified = I.Date_Modified from Inserted I join Accounts A on A.ID = I.ID set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Accounts_Delete' AND [Type] = 'TR' ) drop trigger Accounts_Delete GO create trigger Accounts_Delete on Accounts for delete as begin if NOT exists( select ID from Deleted ) return set NOCOUNT ON if exists( select ID from Deleted where Account_is_Total = 1 ) begin raiserror( 'Warning - Account is Totalled to', 11, 1 ) rollback end else if exists( select ID from Ledger where Account_ID IN ( select ID from Deleted ) ) begin raiserror( 'Warning - Account has Transactions', 11, 1 ) rollback end -- print 'Debug - Accounts_Delete' set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Accounts_Update' AND [Type] = 'TR' ) drop trigger Accounts_Update GO create trigger Accounts_Update on Accounts for update as begin if exists( select ID from Inserted ) begin set NOCOUNT ON -- print 'Debug - Accounts_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'Accounts', I.ID, I.GUID, Columns_Updated() from Inserted I end -------------------------------- -- Auto-Sequence when omitted -- -------------------------------- update Accounts set [Sequence] = ( select Max( isNull( [Sequence], 0 ) ) + 1 from Accounts ) from Inserted I join Accounts A on A.ID = I.ID where isNull( I.[Sequence], 0 ) = 0 ------------------------------total -- Setup Total To Accounts -- ------------------------------ update Accounts set Total_Account_ID = ( select T.ID from Accounts T where T.[Name] = I.Total_to_Account ) from Inserted I join Accounts A on A.ID = I.ID where I.Total_Account_ID is Null OR update( Total_to_Account ) update Accounts set Total_to_Account = ( select T.[Name] from Accounts T where T.ID = I.Total_Account_ID ) from Inserted I join Accounts A on A.ID = I.ID where I.Total_to_Account is Null OR Update( Total_Account_ID ) update Accounts set Account_is_Total = ( select dbo.Minimum( 1, Count( B.ID ) ) from Accounts B where B.Total_Account_ID = A.ID ) from Inserted I join Deleted D on D.ID = I.ID join Accounts A on A.ID = D.Total_Account_ID -- update old one update Accounts set Account_is_Total = 1 from Inserted I join Accounts A on A.ID = I.Total_Account_ID -- update new one where I.Total_to_Account is Null OR Update( Total_Account_ID ) update Accounts set Account_is_Total = 1 from Inserted I join Accounts A on A.[Name] = I.Total_to_Account -- update new one where I.Total_Account_ID is Null OR update( Total_to_Account ) ------------------------------------------- -- Update 5 levels of Total Tos' for now -- ------------------------------------------- update Accounts set Balance = A.Balance + I.Balance - D.Balance from Inserted I join Deleted D on D.ID = I.ID join Accounts A on A.ID = I.Total_Account_ID where I.[Type] = A.[Type] update Accounts set Balance = A.Balance - I.Balance + D.Balance from Inserted I join Deleted D on D.ID = I.ID join Accounts A on A.ID = I.Total_Account_ID where I.[Type] <> A.[Type] update Accounts set Balance = A.Balance + I.Balance - D.Balance from Inserted I join Deleted D on D.ID = I.ID join Accounts A on A.ID = ( select B.Total_Account_ID from Accounts B where B.ID = I.Total_Account_ID ) where I.[Type] = A.[Type] update Accounts set Balance = A.Balance - I.Balance + D.Balance from Inserted I join Deleted D on D.ID = I.ID join Accounts A on A.ID = ( select B.Total_Account_ID from Accounts B where B.ID = I.Total_Account_ID ) where I.[Type] <> A.[Type] update Accounts set Balance = A.Balance + I.Balance - D.Balance from Inserted I join Deleted D on D.ID = I.ID join Accounts A on A.ID = ( select B.Total_Account_ID from Accounts B where B.ID = ( select C.Total_Account_ID from Accounts C where C.ID = I.Total_Account_ID ) ) where I.[Type] = A.[Type] update Accounts set Balance = A.Balance - I.Balance + D.Balance from Inserted I join Deleted D on D.ID = I.ID join Accounts A on A.ID = ( select B.Total_Account_ID from Accounts B where B.ID = ( select C.Total_Account_ID from Accounts C where C.ID = I.Total_Account_ID ) ) where I.[Type] <> A.[Type] update Accounts set Balance = A.Balance + I.Balance - D.Balance from Inserted I join Deleted D on D.ID = I.ID join Accounts A on A.ID = ( select B.Total_Account_ID from Accounts B where B.ID = ( select C.Total_Account_ID from Accounts C where C.ID = ( select E.Total_Account_ID from Accounts E where E.ID = I.Total_Account_ID ) ) ) where I.[Type] = A.[Type] update Accounts set Balance = A.Balance - I.Balance + D.Balance from Inserted I join Deleted D on D.ID = I.ID join Accounts A on A.ID = ( select B.Total_Account_ID from Accounts B where B.ID = ( select C.Total_Account_ID from Accounts C where C.ID = ( select E.Total_Account_ID from Accounts E where E.ID = I.Total_Account_ID ) ) ) where I.[Type] <> A.[Type] update Accounts set Balance = A.Balance + I.Balance - D.Balance from Inserted I join Deleted D on D.ID = I.ID join Accounts A on A.ID = ( select B.Total_Account_ID from Accounts B where B.ID = ( select C.Total_Account_ID from Accounts C where C.ID = ( select E.Total_Account_ID from Accounts E where E.ID = ( select F.Total_Account_ID from Accounts F where F.ID = I.Total_Account_ID ) ) ) ) where I.[Type] = A.[Type] update Accounts set Balance = A.Balance - I.Balance + D.Balance from Inserted I join Deleted D on D.ID = I.ID join Accounts A on A.ID = ( select B.Total_Account_ID from Accounts B where B.ID = ( select C.Total_Account_ID from Accounts C where C.ID = ( select E.Total_Account_ID from Accounts E where E.ID = ( select F.Total_Account_ID from Accounts F where F.ID = I.Total_Account_ID ) ) ) ) where I.[Type] <> A.[Type] ------------------------------------------------------------------------------------------------------------------ -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- ------------------------------------------------------------------------------------------------------------------ update Accounts set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Inserted I join Accounts A on A.ID = I.ID set NOCOUNT OFF end end GO set NOCOUNT ON --alter table Accounts disable trigger all --delete Ledger --update Accounts set Balance = 0 --update Accounts set Balance = 0 --update Accounts set Balance = 0 --update Accounts set Balance = 0 --update Contacts set Balance = 0 --alter table Accounts enable trigger all if ( select Count( ID ) from Accounts ) = 0 begin declare @ID int, @PID int insert Accounts ([Type],[Sequence],[Group],[Name]) values('Debit', 100,'1 - Assets', 'Total Assets') select @ID = Scope_Identity() insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID) values('Debit', 110,'1 - Assets', '110 - Cash', @ID) insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID,Account_is_Bank) values('Debit', 120,'1 - Assets', '120 - Bank', @ID,1) insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID) values('Debit', 130,'1 - Assets', '130 - Inventory', @ID) insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID) values('Debit', 140,'1 - Assets', '140 - Equipment', @ID) insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID,Account_is_AR) values('Debit', 150,'1 - Assets', '150 - Receivables', @ID,1) insert Accounts ([Type],[Sequence],[Group],[Name]) values('Credit',300,'3 - Equity', 'Total Equity & Liabilities') select @PID = Scope_Identity() insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID) values('Credit',200,'2 - Liabilities','Total Liabilities', @PID) select @ID = Scope_Identity() insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID,Account_is_AP) values('Credit',210,'2 - Liabilities','210 - Payables', @ID,1) insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID) values('Credit',220,'2 - Liabilities','220 - GST Payable', @ID) insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID) values('Credit',230,'2 - Liabilities','230 - PST Payable', @ID) insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID) values('Credit',310,'3 - Equity', '310 - Owners Equity',@PID) insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID) values('Credit',320,'3 - Equity', '320 - Retained Earnings',@PID) select @ID = Scope_Identity() insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID) values('Credit',700,'4 - Profit/Loss','700 - Net Profit', @ID) select @ID = Scope_Identity() insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID) values('Debit', 600,'4 - Profit/Loss','600 - Expenses', @ID) insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID) values('Credit',500,'4 - Profit/Loss','500 - Gross Profit', @ID) select @ID = Scope_Identity() insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID) values('Credit',400,'4 - Profit/Loss','400 - Sales', @ID) insert Accounts ([Type],[Sequence],[Group],[Name],Total_Account_ID) values('Debit', 410,'4 - Profit/Loss','410 - Cost of Goods',@ID) end set NOCOUNT OFF GO -------------- -- Ledger -- -------------- if exists ( select * from sysobjects where [Name] = 'Ledger_Insert' AND [Type] = 'TR' ) drop trigger Ledger_Insert GO create trigger Ledger_Insert on Ledger for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - Ledger_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'Ledger', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update Ledger set Date_Modified = I.Date_Modified from Inserted I join Ledger L on L.ID = I.ID set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Ledger_Delete' AND [Type] = 'TR' ) drop trigger Ledger_Delete GO create trigger Ledger_Delete on Ledger for delete as begin if @@NESTLEVEL = 1 AND exists( select ID from Deleted where Date_Locked is NOT Null ) begin raiserror( 'Warning - Data is Locked', 11, 1 ) rollback end if @@NESTLEVEL = 1 AND exists( select ID from Deleted where Order_ID is NOT Null ) begin raiserror( 'Warning - Can not delete Ledger generated from a Document', 11, 1 ) rollback end if exists( select ID from Deleted ) begin set NOCOUNT ON -- print 'Debug - Ledger_Delete' --------------------- -- update Balances -- --------------------- update Accounts set Balance = A.Balance - D.Amount from Deleted D join Accounts A on A.ID = D.Account_ID update Contacts set Balance = C.Balance - D.Amount from Deleted D join Contacts C on C.ID = D.Contact_ID where D.Account_is_AR = 1 OR D.Account_is_AP = 1 ------------------------------------------------ -- delete all Distributions when its a Parent -- ------------------------------------------------ declare @ID int, @Amt decimal( 18, 4 ) declare ActCursor cursor local for select L.Account_ID, L.Amount from Deleted D join Ledger L on L.Ledger_ID = D.ID open ActCursor fetch ActCursor into @ID, @Amt while @@FETCH_STATUS = 0 begin update Accounts set Balance = Balance - @Amt where ID = @ID fetch ActCursor into @ID, @Amt end close ActCursor deallocate ActCursor -- update Accounts set Balance = A.Balance - L.Amount -- from Deleted D join Ledger L on L.Ledger_ID = D.ID -- join Accounts A on A.ID = L.Account_ID delete Ledger from Deleted D join Ledger L on L.Ledger_ID = D.ID ------------------------------------------- -- Update Parent when its a Distribution -- ------------------------------------------- update Ledger set Amount = L.Amount + D.Amount from Deleted D join Ledger L on L.ID = D.Ledger_ID where L.Account_Type = D.Account_Type -- remove old amount update Ledger set Amount = L.Amount - D.Amount from Deleted D join Ledger L on L.ID = D.Ledger_ID where L.Account_Type <> D.Account_Type -- remove old amount set NOCOUNT OFF end end GO if exists ( select * from sysobjects where [Name] = 'Ledger_Update' AND [Type] = 'TR' ) drop trigger Ledger_Update GO create trigger Ledger_Update on Ledger for update as begin if NOT exists( select ID from Inserted ) OR @@NESTLEVEL = 1 AND exists( select D.ID from Deleted D join Inserted I on I.ID = D.ID where D.Date_Locked is NOT Null AND I.Date_Locked is NOT Null ) set NOCOUNT OFF else begin set NOCOUNT ON -- print 'Debug - Ledger_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'Ledger', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------------------ -- update from Parent when its a Distribution -- ------------------------------------------------ update L set Cross_Account_ID = P.Account_ID, Cross_Account = P.Account_Name, Contact_ID = P.Contact_ID, Contact_Name = P.Contact_Name, Order_ID = P.Order_ID, Date = P.Date, Reference = P.Reference, Number = P.Number from Inserted I join Ledger L on L.ID = I.ID join Ledger P on P.ID = L.Ledger_ID where L.Ledger_ID is NOT Null ------------------------- -- Update Contact Info -- ------------------------- update Ledger set Contact_ID = C.ID from Inserted I join Ledger L on L.ID = I.ID join Contacts C on C.[Name] = I.Contact_Name where L.Contact_ID is Null OR Update( Contact_Name ) update Ledger set Contact_Name = C.[Name] from Inserted I join Ledger L on L.ID = I.ID join Contacts C on C.ID = I.Contact_ID where L.Contact_Name is Null OR Update( Contact_ID ) update Ledger set Contact_ID = C.ID -- Any missing Contacts fall into the Main Company file for processing from Inserted I join Ledger L on L.ID = I.ID join Contacts C on C.Company_Configuration = 1 where L.Contact_ID is Null AND L.Order_ID is NOT Null -------------------------- -- Update Accounts Info -- -------------------------- update Ledger set Account_ID = A.ID, Account_Type = A.[Type], Account_is_Total = A.Account_Is_Total, Account_is_AR = A.Account_is_AR, Account_is_AP = A.Account_is_AP, Account_is_Bank = A.Account_is_Bank from Inserted I join Ledger L on L.ID = I.ID join Accounts A on A.[Name] = I.Account_Name where L.Account_ID is Null OR Update( Account_Name ) update Ledger set Account_Name = A.[Name], Account_Type = A.[Type], Account_is_Total = A.Account_Is_Total, Account_is_AR = A.Account_is_AR, Account_is_AP = A.Account_is_AP, Account_is_Bank = A.Account_is_Bank from Inserted I join Ledger L on L.ID = I.ID join Accounts A on A.ID = I.Account_ID where L.Account_Name is Null OR Update( Account_ID ) update Ledger set Cross_Account_ID = A.ID from Inserted I join Ledger L on L.ID = I.ID join Accounts A on A.[Name] = I.Cross_Account where L.Cross_Account_ID is Null OR Update( Cross_Account ) update Ledger set Cross_Account = A.[Name] from Inserted I join Ledger L on L.ID = I.ID join Accounts A on A.ID = I.Cross_Account_ID where L.Cross_Account is Null OR Update( Cross_Account_ID ) -- use default A/R account when none is set and contact can be a client update Ledger set Account_ID = A.ID, Account_Name = A.[Name], Account_Type = A.[Type], Account_is_Total = A.Account_Is_Total, Account_is_AR = A.Account_is_AR, Account_is_AP = A.Account_is_AP, Account_is_Bank = A.Account_is_Bank from Inserted I join Ledger L on L.ID = I.ID join Contacts C on C.ID = L.Contact_ID join Accounts A on A.Account_is_AR = 1 where L.Account_ID is Null AND C.Can_be_a_Client = 1 -- use default A/P account when none is set and contact can not be a client update Ledger set Account_ID = A.ID, Account_Name = A.[Name], Account_Type = A.[Type], Account_is_Total = A.Account_Is_Total, Account_is_AR = A.Account_is_AR, Account_is_AP = A.Account_is_AP, Account_is_Bank = A.Account_is_Bank from Inserted I join Ledger L on L.ID = I.ID join Contacts C on C.ID = L.Contact_ID join Accounts A on A.Account_is_AP = 1 where L.Account_ID is Null AND C.Can_be_a_Client = 0 -- use default Bank cross account when none is set update Ledger set Cross_Account_ID = A.ID, Cross_Account = A.[Name] from Inserted I join Ledger L on L.ID = I.ID join Accounts A on A.Account_is_Bank = 1 where L.Cross_Account_ID is Null AND L.Contact_ID is NOT Null AND L.Date_Modified is Null -- only default to bank on inserts -- Bank transactions in A/R and A/P must have a negative amount to reduce contact balance update Ledger set Amount = - Abs( L.Amount ) from Inserted I join Ledger L on L.ID = I.ID where L.Contact_ID is NOT Null AND ( select D.Account_is_Bank from Ledger D where D.ID = L.Cross_Account_ID ) = 1 -------------------------------- -- Auto-Sequence when omitted -- -------------------------------- update Ledger set [Sequence] = ( select Max( isNull( [Sequence], 0 ) ) + 1 from Ledger where Account_ID = I.Account_ID ) from Inserted I join Ledger L on L.ID = I.ID where I.Sequence is Null AND I.Ledger_ID is Null update Ledger set [Sequence] = ( select Max( isNull( [Sequence], 0 ) ) + 1 from Ledger where Ledger_ID = I.Ledger_ID ) from Inserted I join Ledger L on L.ID = I.ID where I.Sequence is Null AND I.Ledger_ID is NOT Null --------------------------------- -- Check for Total to Accounts -- --------------------------------- if exists( select * from Inserted I join Ledger L on L.ID = I.ID where L.Account_is_Total = 1 ) begin raiserror( 'Total to Accounts can not have Transactions', 11, 1 ) rollback end else begin --------------------------------------------------------- -- no changes to a Parent when it has no Cross Account -- --------------------------------------------------------- if @@NESTLEVEL = 1 begin -- calls from insert or delete are ok update Ledger set Cross_Account_ID = Null, Cross_Account = Null -- no cross accounts on a Parent with distribution Amount from Inserted I join Ledger L on L.ID = I.ID join Deleted D on D.ID = I.ID where L.Ledger_ID is Null AND D.Amount <> 0 AND D.Cross_Account_ID is Null update Ledger set Amount = D.Amount -- no change to distribution Amount when no Cross Account from Inserted I join Ledger L on L.ID = I.ID join Deleted D on D.ID = I.ID where L.Ledger_ID is Null AND L.Cross_Account_ID is Null end ----------------------------------------------------- -- create a Default Distribution when its a Parent -- ----------------------------------------------------- insert Ledger ( Ledger_ID, Account_ID, Account_Type, Cross_Account_ID, Order_ID, Date, Number, Reference, Contact_ID, Contact_Name ) select L.ID, L.Cross_Account_ID, A.[Type], L.Account_ID, L.Order_ID, L.Date, L.Number, L.Reference, L.Contact_ID, L.Contact_Name from Inserted I join Ledger L on L.ID = I.ID join Accounts A on A.ID = L.Cross_Account_ID where L.Ledger_ID is Null AND NOT exists( select D.ID from Ledger D where D.Ledger_ID = L.ID ) update Ledger set Amount = - I.Amount from Inserted I join Ledger L on L.Ledger_ID = I.ID AND L.Account_ID = I.Cross_Account_ID where I.Ledger_ID is Null AND L.Account_Type = I.Account_Type update Ledger set Amount = I.Amount from Inserted I join Ledger L on L.Ledger_ID = I.ID AND L.Account_ID = I.Cross_Account_ID where I.Ledger_ID is Null AND L.Account_Type <> I.Account_Type -------------------------------------------------------- -- Update all of the Distributions when its a Parent -- -------------------------------------------------------- update L set Cross_Account_ID = P.Account_ID, Cross_Account = P.Account_Name, Contact_ID = P.Contact_ID, Contact_Name = P.Contact_Name, Date = P.Date, Reference = P.Reference, Number = P.Number from Inserted I join Ledger L on L.Ledger_ID = I.ID join Ledger P on P.ID = L.Ledger_ID ------------------------- -- Update All Balances -- ------------------------- update Accounts set Balance = A.Balance - D.Amount from Inserted I join Ledger L on L.ID = I.ID join Deleted D on D.ID = I.ID join Accounts A on A.ID = D.Account_ID where I.Date_Modified is NOT Null -- remove from old account but not on inserts update Accounts set Balance = A.Balance + L.Amount from Inserted I join Ledger L on L.ID = I.ID join Accounts A on A.ID = L.Account_ID -- add to new account update Accounts set Balance = A.Balance - D.Amount from Inserted I join Ledger L on L.ID = I.ID join Deleted D on D.ID = I.ID join Accounts A on A.ID = D.Cross_Account_ID where I.Date_Modified is NOT Null AND D.Account_Type <> A.[Type] -- remove from old cross account update Accounts set Balance = A.Balance + D.Amount from Inserted I join Ledger L on L.ID = I.ID join Deleted D on D.ID = I.ID join Accounts A on A.ID = D.Cross_Account_ID where I.Date_Modified is NOT Null AND D.Account_Type = A.[Type] -- remove from old cross account update Accounts set Balance = A.Balance + L.Amount from Inserted I join Ledger L on L.ID = I.ID join Accounts A on A.ID = L.Cross_Account_ID where L.Account_Type <> A.[Type] -- add to new cross account update Accounts set Balance = A.Balance - L.Amount from Inserted I join Ledger L on L.ID = I.ID join Accounts A on A.ID = L.Cross_Account_ID where L.Account_Type = A.[Type] -- add to new cross account update Contacts set Balance = C.Balance - D.Amount from Inserted I join Ledger L on L.ID = I.ID join Deleted D on D.ID = I.ID join Contacts C on C.ID = D.Contact_ID where D.Account_is_AR = 1 OR D.Account_is_AP = 1 update Contacts set Balance = C.Balance + L.Amount from Inserted I join Ledger L on L.ID = I.ID join Contacts C on C.ID = L.Contact_ID where L.Account_is_AR = 1 OR L.Account_is_AP = 1 update Ledger set Balance = A.Balance from Inserted I join Ledger L on L.ID = I.ID join Accounts A on A.ID = L.Account_ID update Ledger set Contact_Balance = C.Balance from Inserted I join Ledger L on L.ID = I.ID join Contacts C on C.ID = L.Contact_ID where L.Account_is_AR = 1 OR L.Account_is_AP = 1 -------------------------------------------------------------------- -- set all credit amounts to zero or the unapplied credit balance -- -------------------------------------------------------------------- update Ledger set Date_Locked = Null, Apply_Balance = dbo.Minimum( 0, ( select Sum( isNull( A.Amount, 0 ) ) from Ledger A where L.Contact_ID = A.Contact_ID AND L.Apply_Sequence = A.Apply_Sequence AND A.Date_Locked is Null ) ) from Inserted I join Ledger L on L.Contact_ID = I.Contact_ID AND L.Apply_Sequence = I.Apply_Sequence AND L.Date_Locked is Null AND L.Amount < 0 ------------------------------------------------------------------ -- set all debit amounts to zero or the unapplied debit balance -- ------------------------------------------------------------------ update Ledger set Date_Locked = Null, Apply_Balance = dbo.Maximum( 0, ( select Sum( isNull( A.Amount, 0 ) ) from Ledger A where L.Contact_ID = A.Contact_ID AND L.Apply_Sequence = A.Apply_Sequence AND A.Date_Locked is Null ) ) from Inserted I join Ledger L on L.Contact_ID = I.Contact_ID AND L.Apply_Sequence = I.Apply_Sequence AND L.Date_Locked is Null AND L.Amount > 0 ------------------------------------------------------------------------------ -- lock apply sequences that total to zero only when apply sequence changed -- ------------------------------------------------------------------------------ update Ledger set Date_Locked = GetDate(), Apply_Balance = 0 from Inserted I join Ledger L on L.Contact_ID = I.Contact_ID AND L.Apply_Sequence = I.Apply_Sequence where Update( Apply_Sequence ) AND L.Date_Locked is Null AND L.Amount <> 0 AND ( select Sum( isNull( A.Amount, 0 ) ) from Ledger A where L.Contact_ID = A.Contact_ID AND L.Apply_Sequence = A.Apply_Sequence AND A.Date_Locked is Null ) = 0 ---------------------------------------------------------- -- unlock apply sequences only when Date_Locked changed -- ---------------------------------------------------------- update Ledger set Date_Locked = Null from Inserted I join Ledger L on L.Contact_ID = I.Contact_ID AND L.Apply_Sequence = I.Apply_Sequence where Update( Date_Locked ) AND I.Date_Locked is Null --------------------------------------------------- -- Update default distribution when its a Parent -- --------------------------------------------------- update Contacts set Balance = C.Balance - D.Amount from Inserted I join Ledger L on L.Ledger_ID = I.ID AND L.Account_ID = I.Cross_Account_ID join Deleted D on D.ID = I.ID join Contacts C on C.ID = L.Contact_ID where I.Date_Modified is NOT Null AND L.Account_Type <> D.Account_Type AND ( L.Account_is_AR = 1 OR L.Account_is_AP = 1 ) -- remove old amount except on inserts update Contacts set Balance = C.Balance + D.Amount from Inserted I join Ledger L on L.Ledger_ID = I.ID AND L.Account_ID = I.Cross_Account_ID join Deleted D on D.ID = I.ID join Contacts C on C.ID = L.Contact_ID where I.Date_Modified is NOT Null AND L.Account_Type = D.Account_Type AND ( L.Account_is_AR = 1 OR L.Account_is_AP = 1 ) -- remove old amount except on inserts update Contacts set Balance = C.Balance + I.Amount from Inserted I join Ledger L on L.Ledger_ID = I.ID AND L.Account_ID = I.Cross_Account_ID join Contacts C on C.ID = L.Contact_ID where ( L.Account_is_AR = 1 OR L.Account_is_AP = 1 ) AND L.Account_Type <> ( select D.Account_Type from Ledger D where D.ID = I.ID ) -- add new amount update Contacts set Balance = C.Balance - I.Amount from Inserted I join Ledger L on L.Ledger_ID = I.ID AND L.Account_ID = I.Cross_Account_ID join Contacts C on C.ID = L.Contact_ID where ( L.Account_is_AR = 1 OR L.Account_is_AP = 1 ) AND L.Account_Type = ( select D.Account_Type from Ledger D where D.ID = I.ID ) -- add new amount update Ledger set Balance = A.Balance from Inserted I join Ledger L on L.Ledger_ID = I.ID AND L.Account_ID = I.Cross_Account_ID join Accounts A on A.ID = L.Account_ID update Ledger set Contact_Balance = C.Balance from Inserted I join Ledger L on L.Ledger_ID = I.ID AND L.Account_ID = I.Cross_Account_ID join Contacts C on C.ID = L.Contact_ID where L.Account_is_AR = 1 OR L.Account_is_AP = 1 ------------------------------------------- -- Update Parent when its a distribution -- ------------------------------------------- update L set Cross_Account_ID = Null, Cross_Account = Null -- clear cross acoount when it is not self implying a distribution from Inserted I join Ledger L on L.ID = I.Ledger_ID join Ledger D on D.ID = I.ID where L.Cross_Account_ID <> D.Account_ID update Ledger set Amount = L.Amount - D.Amount, Balance = A.Balance from Inserted I join Ledger L on L.ID = I.Ledger_ID join Deleted D on D.ID = I.ID join Accounts A on A.ID = L.Account_ID where I.Date_Modified is NOT Null AND L.Account_Type <> D.Account_Type -- remove old amount except on inserts update Ledger set Amount = L.Amount + D.Amount, Balance = A.Balance from Inserted I join Ledger L on L.ID = I.Ledger_ID join Deleted D on D.ID = I.ID join Accounts A on A.ID = L.Account_ID where I.Date_Modified is NOT Null AND L.Account_Type = D.Account_Type -- remove old amount except on inserts update L set Amount = L.Amount + I.Amount, Balance = A.Balance from Inserted I join Ledger L on L.ID = I.Ledger_ID join Ledger D on D.ID = I.ID join Accounts A on A.ID = L.Account_ID where L.Account_Type <> D.Account_Type -- add new amount update L set Amount = L.Amount - I.Amount , Balance = A.Balance from Inserted I join Ledger L on L.ID = I.Ledger_ID join Ledger D on D.ID = I.ID join Accounts A on A.ID = L.Account_ID where L.Account_Type = D.Account_Type -- add new amount update Contacts set Balance = C.Balance - D.Amount from Inserted I join Ledger L on L.ID = I.Ledger_ID join Deleted D on D.ID = I.ID join Contacts C on C.ID = L.Contact_ID where I.Date_Modified is NOT Null AND L.Account_Type <> D.Account_Type AND ( L.Account_is_AR = 1 OR L.Account_is_AP = 1 ) -- remove old amount except on inserts update Contacts set Balance = C.Balance + D.Amount from Inserted I join Ledger L on L.ID = I.Ledger_ID join Deleted D on D.ID = I.ID join Contacts C on C.ID = L.Contact_ID where I.Date_Modified is NOT Null AND L.Account_Type = D.Account_Type AND ( L.Account_is_AR = 1 OR L.Account_is_AP = 1 ) -- remove old amount except on inserts update Contacts set Balance = C.Balance + I.Amount from Inserted I join Ledger L on L.ID = I.Ledger_ID join Ledger D on D.ID = I.ID join Contacts C on C.ID = L.Contact_ID where ( L.Account_is_AR = 1 OR L.Account_is_AP = 1 ) AND L.Account_Type <> D.Account_Type -- add new amount update Contacts set Balance = C.Balance - I.Amount from Inserted I join Ledger L on L.ID = I.Ledger_ID join Ledger D on D.ID = I.ID join Contacts C on C.ID = L.Contact_ID where ( L.Account_is_AR = 1 OR L.Account_is_AP = 1 ) AND L.Account_Type = D.Account_Type -- add new amount update Ledger set Balance = A.Balance from Inserted I join Ledger L on L.ID = I.Ledger_ID join Accounts A on A.ID = L.Account_ID update Ledger set Contact_Balance = C.Balance from Inserted I join Ledger L on L.ID = I.Ledger_ID join Contacts C on C.ID = L.Contact_ID where L.Account_is_AR = 1 OR L.Account_is_AP = 1 ------------------------------------------------------------------------------------------------------------------ -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- ------------------------------------------------------------------------------------------------------------------ update Ledger set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Inserted I join Ledger L on L.ID = I.ID end set NOCOUNT OFF end end GO ----------- -- Notes -- ----------- if exists ( select * from sysobjects where [Name] = 'Notes_Insert' AND [Type] = 'TR' ) drop trigger Notes_Insert GO create trigger Notes_Insert on Notes for insert as begin if NOT exists( select ID from Inserted ) return set NOCOUNT ON -- print 'Debug - Notes_Insert' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 1, 'Notes', I.ID, I.GUID, Columns_Updated() from Inserted I end ------------------------------------------------------------- -- Force the Business Rules in the Update triggers to fire -- ------------------------------------------------------------- update Notes set Date_Modified = I.Date_Modified from Inserted I join Notes N on N.ID = I.ID set NOCOUNT OFF end GO if exists ( select * from sysobjects where [Name] = 'Notes_Delete' AND [Type] = 'TR' ) drop trigger Notes_Delete GO if exists ( select * from sysobjects where [Name] = 'Notes_Update' AND [Type] = 'TR' ) drop trigger Notes_Update GO create trigger Notes_Update on Notes for update as begin if NOT exists( select ID from Inserted ) OR Update( Photo1 ) OR Update( Photo2 ) OR Update( Photo3 ) OR Update( Photo4 ) OR Update( Photo5 ) OR Update( Photo6 ) OR Update( Photo7 ) OR Update( Photo8 ) OR Update( Photo9 ) OR Update( Photo1Thumb ) OR Update( Photo2Thumb ) OR Update( Photo3Thumb ) OR Update( Photo4Thumb ) OR Update( Photo5Thumb ) OR Update( Photo6Thumb ) OR Update( Photo7Thumb ) OR Update( Photo8Thumb ) OR Update( Photo9Thumb ) set NOCOUNT OFF else begin set NOCOUNT ON -- print 'Debug - Notes_Update' if @@NestLevel = 1 begin insert UndoLog ( SQL_Operation, Table_Name, Table_ID, Table_GUID, Cols_Updated ) select 0, 'Notes', I.ID, I.GUID, Columns_Updated() from Inserted I end -------------------------------- -- Auto-Sequence when omitted -- -------------------------------- update Notes set [Sequence] = ( select Max( isNull( [Sequence], 0 ) ) + 1 from Notes where WebSite_ID = I.WebSite_ID AND Resource_ID = I.Resource_ID AND Contact_ID = I.Contact_ID AND Order_ID = I.Order_ID AND Catalog_ID = I.Catalog_ID AND Activity_ID = I.Activity_ID ) from Inserted I join Notes N on N.ID = I.ID where I.Sequence is Null ------------------------------------------------------- -- make sure attachments are stored in the proper place ------------------------------------------------------- update Notes set Photo9Name = dbo.FileName( N.Photo1Name ), Photo1Name = S.Local_Path + Replace ( Replace ( dbo.FilePath( N.Photo1Name ), S.Local_Path, '' ), 'HTML\', '' ) + dbo.FileName( N.Photo1Name ) from Inserted I join Notes N on N.ID = I.ID join WebSites S on S.ID = I.WebSite_ID where Update( Photo1Name ) update Notes set [Name] = substring( N.Photo1Name, 1, 900 ) from Inserted I join Notes N on N.ID = I.ID ------------------------------------------------------------------------------------------------------------------ -- Update the Date_Modified last since when it is Null it is used to detect Inserted records in Update triggers -- ------------------------------------------------------------------------------------------------------------------ update Notes set Date_Modified = GetDate(), WorkStation = App_Name(), UserName = System_User from Inserted I join Notes N on N.ID = I.ID set NOCOUNT OFF end end GO execute sp_updateextendedproperty 'Version', '2009-12-22.1' GO 1/7/2010 12:25:26 PM v1.4477 - Column names in each table must be unique. Column name 'Category_Name' in table 'Resources' is specified more than once Continue or restart VDM - This error was queued for analysis, we apologize. -- -- Encryption -- --BACKUP SERVICE MASTER KEY TO FILE = 'C:\ServiceMasterKey.bak' --ENCRYPTI 0001:00233BEC axView.txView.UpdContact line 9428 0001:0021C654 axView.FormatResults line 7379 base: 00C41000 -- -- Encryption -- --BACKUP SERVICE MASTER KEY TO FILE = 'C:\ServiceMasterKey.bak' --ENCRYPTION BY PASSWORD = 'Replace_with_Strong_Password' --GO --RESTORE SERVICE MASTER KEY FROM FILE = 'C:\ServiceMasterKey.bak' --DECRYPTION BY PASSWORD = 'Replace_with_Strong_Password' --GO -- --CREATE MASTER KEY --ENCRYPTION BY PASSWORD = 'Replace_with_Strong_Password' --GO --BACKUP MASTER KEY TO FILE = 'C:\MasterKey.bak' --ENCRYPTION BY PASSWORD = 'Replace_with_Strong_Password' --GO --RESTORE MASTER KEY FROM FILE = 'C:\MasterKey.bak' --DECRYPTION BY PASSWORD = 'Replace_with_Strong_Password' --ENCRYPTION BY PASSWORD = 'Replace_with_Strong_Password' --GO -- --CREATE CERTIFICATE DefaultEncryptionCertificate --WITH SUBJECT = 'Default_Encryption_Certificate' --GO -- --CREATE SYMMETRIC KEY DefaultSymmetricKey --WITH ALGORITHM = TRIPLE_DES --ENCRYPTION BY CERTIFICATE DefaultEncryptionCertificate --GO -- --Identical Shared Keys on Multiple Servers -- --CREATE MASTER KEY --ENCRYPTION BY PASSWORD = 'Replace_with_Strong_Password' --GO --CREATE CERTIFICATE DefaultEncryptionCertificate --WITH SUBJECT = 'Default_Encryption_Certificate' --GO --CREATE SYMMETRIC KEY DefaultSymmetricKey WITH --KEY_SOURCE = 'My key generation bits. This is a shared secret!', --WITH ALGORITHM = TRIPLE_DES ENCRYPTION --IDENTITY_VALUE = 'Key Identity generation bits. Also a shared secret' --ENCRYPTION BY CERTIFICATE DefaultEncryptionCertificate --GO -- --OPEN SYMMETRIC KEY DefaultSymmetricKey DECRYPTION --BY CERTIFICATE DefaultEncryptionCertificate --UPDATE SomeTable --SET EncryptedColumn = ENCRYPTBYKEY( KEY_GUID( 'DefaultSymmetricKey' ), SourceColumnOrData ) --GO -- --OPEN SYMMETRIC KEY DefaultSymmetricKey DECRYPTION --BY CERTIFICATE DefaultEncryptionCertificate --SELECT CONVERT( VARCHAR( 50 ), DECRYPTBYKEY( EncryptedColumn ) ) AS DecryptedData --FROM SomeTable --GO -- --GRANT VIEW DEFINITION ON CERTIFICATE :: DefaultEncryptionCertificate TO SomeUserOrRole --GRANT CONTROL ON CERTIFICATE :: DefaultEncryptionCertificate TO SomeUserOrRole -- -- -- Void Orders must rollback the triggers -- grant update ( Date_Locked ) on OrderItems to VDM -- alter table OrderItems disable trigger all -- update OrderItems set Date_Locked = Null -- from Orders O join OrderItems I on O.ID = I.Order_ID where O.Date_Locked is Null AND I.Date_Locked is NOT Null -- alter table OrderItems enable trigger all -- deny update ( Date_Locked ) on OrderItems to VDM -- --exec sp_dropServer 'Laval' -- --exec sp_addlinkedserver 'Laval', '', 'SQLNCLI', 'laval.papex.ca' -- linked server updates -- update ediaccess.VDM_ACI.dbo.WebPages set Photo1 = ( select Photo1 from clearware.VDM_ACI.dbo.WebPages W where W.ID = M.ID ) -- from ediaccess.VDM_ACI.dbo.WebPages M where M.Use_As_Template = 1 --select destination_url, Cast( SubString( Cast( Photo2 as varbinary( max ) ), -- CharIndex( 'ejel-120', Cast( Photo2 as varbinary( max ) ) ) - 50, 100 ) as varchar( 4000 ) ) as Src from ediaccess.VDM_ACI.dbo.WebPages -- where Cast( Photo2 as varbinary( max ) ) like '%ejel-120%' -- Search and Replace Blobs -- update WebPages set Photo1 = cast( replace( Cast( Photo1 as varbinary( max ) ), -- 'old', -- 'new' -- ) as varbinary( max ) ) where Use_As_Template = 1 -- --@onlyOneColumnUpdated = 0 if not, otherwise @onlyOneColumnUpdated = 1 -- DECLARE @sqrtForOneColumn float -- DECLARE @onlyOneColumnUpdated bit -- SET @sqrtForOneColumn=(SELECT SQRT(CONVERT(int,COLUMNS_UPDATED()))) -- SET @onlyOneColumnUpdatacked = 0 -- IF POWER(CONVERT(int,COLUMNS_UPDATED()),0.5) = @sqrtForOneColumn -- SET @onlyOneColumnUpdated = 1 -- After then you test the column you want to know if it has been modified -- IF UPDATE(MyCOlumn) AND @onlyOneColumnUpdated = 1 -- PUT YOUR CODE HERE FOR THE COLUMN. ------------- -- Init -- ------------- if NOT exists( select [Name] from TaxProfiles where [Name] = 'GST' AND Date_Effective >= '2008-01-01' ) begin insert TaxProfiles (Date_Effective, [Name], Tax1_Percent ) values( '2008-01-01', 'GST', 5 ) insert TaxProfiles (Date_Effective, [Name], Tax1_Percent ) values( '2008-01-01', 'HST', 15 ) insert TaxProfiles (Date_Effective, [Name], Tax1_Percent, Tax2_Percent, Tax1_is_Taxable ) values( '2008-01-01', 'GST/BC', 5, 7, 1 ) insert TaxProfiles (Date_Effective, [Name], Tax1_Percent, Tax2_Percent ) values( '2008-01-01', 'GST/SK', 5, 5 ) insert TaxProfiles (Date_Effective, [Name], Tax1_Percent, Tax2_Percent ) values( '2008-01-01', 'GST/MA', 5, 7 ) insert TaxProfiles (Date_Effective, [Name], Tax1_Percent, Tax2_Percent ) values( '2008-01-01', 'GST/ON', 5, 8 ) insert TaxProfiles (Date_Effective, [Name], Tax1_Percent, Tax2_Percent, Tax1_is_Taxable ) values( '2008-01-01', 'GST/QC', 5, 7.5, 1 ) insert TaxProfiles (Date_Effective, [Name], Tax1_Percent, Tax2_Percent, Tax1_is_Taxable ) values( '2008-01-01', 'GST/PEI', 5, 10, 1 ) end GO if NOT exists( select [Type] from Numbers ) begin insert Numbers ([Type]) values('Sale') insert Numbers ([Type]) values('Purchase') insert Numbers ([Type]) values('Adjustment') insert Numbers ([Type]) values('Production') insert Numbers ([Type]) values('Estimate') insert Numbers ([Type]) values('Service') update Numbers set Last_Number = isNull( ( select top 1 Number from Orders where [Type] = 'Sale' AND Date_Locked is NOT Null order by Number desc ), 1000 ) where [Type] = 'Sale' update Numbers set Last_Number = isNull( ( select top 1 Number from Orders where [Type] = 'Purchase' order by Number desc ), 1000 ) where [Type] = 'Purchase' update Numbers set Last_Number = isNull( ( select top 1 Number from Orders where [Type] = 'Adjustment' order by Number desc ), 1000 ) where [Type] = 'Adjustment' update Numbers set Last_Number = isNull( ( select top 1 Number from Orders where [Type] = 'Production' order by Number desc ), 1000 ) where [Type] = 'Production' update Numbers set Last_Number = isNull( ( select top 1 Number from Orders where [Type] = 'Estimate' order by Number desc ), 1000 ) where [Type] = 'Estimate' update Numbers set Last_Number = isNull( ( select top 1 Number from Orders where [Type] = 'Service' AND Date_Locked is NOT Null order by Number desc ), 1000 ) where [Type] = 'Service' end GO ------------- -- Library -- ------------- if exists ( select * from sysobjects where [Name] = 'OpenKey' AND [Type] = 'P' ) drop procedure dbo.OpenKey GO create procedure dbo.OpenKey as begin if exists( select * from sys.certificates where name = 'DefaultEncryptionCertificate' ) open symmetric key DefaultSymmetricKey decryption by certificate DefaultEncryptionCertificate end GO if exists ( select * from sysobjects where [Name] = 'Encrypt' AND [Type] = 'FN' ) drop function dbo.Encrypt GO create function dbo.Encrypt( @Data varchar( 4000 ) ) returns varbinary( 8000 ) begin declare @@Result varbinary( 8000 ) set @@Result = EncryptbyKey( Key_GUID( 'DefaultSymmetricKey' ), @Data ) if @@Result is Null set @@Result = convert( varbinary( 8000 ), @Data ) return @@Result end GO if exists ( select * from sysobjects where [Name] = 'Decrypt' AND [Type] = 'FN' ) drop function dbo.Decrypt GO create function dbo.Decrypt( @Data varchar( 4000 ) ) returns varchar( 8000 ) begin declare @@Result varchar( 8000 ) set @@Result = Convert( varchar( 8000 ), DecryptByKey( @Data ) ) if @@Result is Null set @@Result = @Data return @@Result end GO if exists ( select * from sysobjects where [Name] = 'UnitConversion' AND [Type] = 'FN' ) drop function dbo.UnitConversion GO create function dbo.UnitConversion( @StockUnit varchar( 20 ), @SellingUnit varchar( 20 ), @ConversionList varchar( 100 ) ) returns decimal( 18, 4 ) -- varchar( 20 ) -- begin declare @P1 int, @P2 int, @Result decimal( 18, 4 ) set @Result = 1 set @StockUnit = rtrim( @StockUnit ) set @SellingUnit = rtrim( @SellingUnit ) --@Result varchar( 20 ) set @Result = '1' -- if @StockUnit <> @SellingUnit begin set @P1 = charindex( @SellingUnit + '*', @ConversionList ) if @P1 <> 0 begin set @P1 = charindex( '*', @ConversionList, @P1 ) set @P2 = charindex( ',', @ConversionList + ',', @P1 ) set @Result = substring( @ConversionList, @P1 + 1, @P2 - @P1 - 1 ) end end if @Result <= 0 set @Result = 1 return @Result end GO if exists ( select * from sysobjects where [Name] = 'FileAsString' AND [Type] = 'FN' ) drop function dbo.FileAsString GO create function dbo.FileAsString( @PathName varchar( 8000 ) ) returns varbinary( max ) begin -- set @PathName = replace( @PathName, '\', '\\' ) declare @OK int, @FileSystem int, @FileStream int, @Buffer varchar( 8000 ), @Result varbinary( max ) execute @OK = sp_OACreate 'Scripting.FileSystemObject' , @FileSystem output if @OK <> 0 set @Result = Cast( 'Create ' + cast( @OK as varchar( 100 ) ) as varbinary( max ) ) else begin execute @OK = sp_OAMethod @FileSystem, 'OpenTextFile', @FileStream output, @PathName, 1, false, 0 -- Read, NoCreate, ASCII if @OK <> 0 set @Result = Cast( 'Open ' + cast( @OK as varchar( 100 ) ) as varbinary( max ) ) else begin select @Result = cast(