/* 07/06/06 VM - Modified per SWR UM-405 to use the BalFwd/Arrears description that has been added to ServiceTypes instead
of 'Balance Forward' or 'Arrears'. This description is only used if option to
'Print Separate Arrears' is checked. */
/* 05/30/06 VM - Modified per SPR UM-65 ISSUE: The new sorting feature to group barcoded and non-barcoded items is also
sorting the Final Bills this way. All of the Final Bills (barcoded and non-barcoded) should print
first if the option is checked to print final bills first.*/
/* 05/26/06 VM - Modified per SPR UM-63(CRM 15486) On budget bills the 'Ending Balance' amount is not correct unless
you set option to 'print addons separtely for budget customers'. If this option is not set the line
that prints for the service with the usages, etc. has an amount that includes taxes. When it prints
the ending balance line the amount was adding in the taxes again.*/
/* 08/02/04 JFK - modified for SWR UM-1102. W. Pulaski requires that Print Bill and Zip Code Summary be allowed to
print all cycles in a single batch. (It kind of defeats the entire purpose of cycles, but I just
work here). Based on their previous software they have each route in a separate cycle (20 in all).
They were offered the option to combine cycles on accounts via a stored proc but declined in
favor of this estimate. The Cycle is to be ignored for sorting purposes and only modifies
the selection criteria of accounts. */
/* 04/09/04 JFK - Added Landlord/Tenant functionality for SWR UM-1075. For the Both option it inserts a cloned bill
from the tenant into the table and changes the billing address to the landlord's information. If
"send bill to" or "send delinquent bill" is set to Landlord it clones the tenant's bill and changes
the name and address to the landlords and then deletes the tenant's bill. */
/* 02/25/04 JFK - Altered the # of days in the current period , previous period and same period last year to use Reading Date rather than ReadingID. See Testing Notes #300 */
/* 02/11/04 JFK - Altered the chart reading order to use Reading Date rather than ReadingID. See Testing Notes #281 */
/* 12/29/03 JFK - Corrected an error with inactives and service unapplied cash amounts. It was literally checking the service unapplied cash amounts rather than billed arrears < 0. */
/* 07/28/03 JFK - Testing Notes #87 - "Error" created by testing notes #237. The service's billed arrears does not
normally add to the totals on the bill when the amount isnegative so that service unapplied cash is not
distributed between services. However, due to some funky capabilities in DBL, the amount does print
in the totals, if there is only a single service for the account. SIGH. */
/* 07/10/03 JFK - Testing Notes #69 - fixed an error with the change out printing the same date for previous and
present reading dates due to the two readings. It uses the previous, previous :-) for the start
of the billing period.
- Testing Notes #70 - correct a problem with the changeout reading line no longer printing on the bills. */
/* 07/03/03 JFK - Added a changes to get the present/previous reading dates to print properly with the new "K9306 No Margin"
Bill style. */
/* 06/15/03 JFK - Testing Notes #267b. Corrected an error in the Zip Code Summary sort order. */
/* 06/03/03 JFK - Testing Notes #315. Error was caused by the fix for #237. Service Charges should not be included
in the check for a negative balance that was added to account for service unapplied cash. 237 was
designed to excluded services if the computed + billed arrears was < 0. In this case the computer
amount is negative and the arrears are 0, which makes the total < 0 and excludes the amounts from
the bill totals. The check for a negative amount now excludes service charges. */
/* 06/02/03 JFK - Testing Notes #314. Error with total other charges corrected. Amounts in print lines > 11 were being
counted in the "total amount due" twice. */
/* 05/21/03 JFK - Added the "Manually override the billing period dates" option. */
/* 05/08/03 JFK - Integrated the Zip Code Summary Report into Print Bill */
/* 04/29/03 JFK - UMS Testing Notes #237. Service unapplied cash was being spread across multiple services. If a
service for the account has a service unapplied cash amount that exceeds the amount to be billed
then the Billed Arrears Amount will be negative. When this occurs it needs to force the arrears
to print separately. Additionally, all service lines will not be added to the net amount due on
the bill. */
/* 04/29/03 JFK - UMS Testing Notes #256. The IsEstimated and IsFinal flags were not being set/cleared properly. Thus the
bills were printing "ESTIMATED" or "FINAL" based on the previous bill's setting.
The section that sets or clears the flag is contained with in a section of code for Metered services
only. In London's case they had one account with a metered service that is estimated, and then
there is a large number of accounts without metered services. Thus, it is set and then never
cleared. The flag is now being cleared after every service. A similar issue occur was occuring
with the final bill flag. This issue was corrected as well. */
/* 03/27/03 JFK - Corrected an error in the "print description on bill" when combining like charges. The error was for Local Taxes only. */
/* 03/04/03 JFK - An error existed for accounts that had all services set to not "Show Arrears In Billing When Inactive".
In DBL these accounts were excluded whether they had a customer unapplied cash amount or not. In
Windows it was still including accounts that had customer unapplied cash regardsless of whether or
not they had a service that would print on the bill. */
/* 02/07/03 JFK - Adjusted the length of the value being inserted in the total # of of bills field for the last bill
- Fixed a problem for meter changeouts with the previous reading date value not pulling from the actual
previous reading. It was incorrectly using the date from the initial reading on for the new meter. */
/* 01/30/03 JFK - If Print Separate Arrears is set it was printing the Budget Arrears regardless of the Track Budget Arrears option. */
/* 01/23/03 JFK - Correction to the Usages for the enhanced bill Chart. The Present and Previous reading dates and readings were correct, but the usage was backwards.
- Recreated DBL functionality - Testing Notes #58. Don't print addons if their amount is zero. */
/* 01/10/03 JFK - Added a new option "Print ending balance for budget customers" from the billing options. This feature was added to compensate
for a Paris Gas custom print bill in DBL. This option changes the wording on the balance forward/arrears record
to say "Beginning Balance". It sets the service line to include that actual service amount rather than
the budget payment, adds an "ending balance" line that is a calculated total of "beginning balance"
(balance forward/arrears) and the actual service balance, and a fourth line for the budget payment
amount. This option requires the "Print Seperate Arrears" to be set. */
/* 01/09/03 JFK - Added new fields and functionality for the Enhanced Bill features (comparisons and usage chart). */
/* 11/19/02 JFK - The 11/01/02 to customers with customer unapplied cash and no services was wrong. It should have
used the RemainingUnappliedCashWhenComputed not customerunappliedcash. */
/* 11/01/02 JFK - The proc was only selecting bills for inactive accounts that had at least one service with a balance.
Added a check to include inactive accounts with customer unapplied cash. */
/* 10/25/02 JFK - Added the PrintReadingAndUsageForInactiveServicesOnBills option that has existed in the
Billing Options since 2/11/02 but was never implemented. */
/* 10/04/02 JFK - Corrected the problem with the Present and Previous reading date not printing properly on the Bill Card.
Moved the Deduct usage line under the service line. */
/* 10/02/02 JFK - Made a correction to the Deduct Usage line. It was leaving the deduct usage as NULL.
Added the Service's bill code to the lines for Average, Demand and Deduct usage to
make it easier to associate the line items. */
/* 07/08/02 JFK - Added major changes to the calculations for the "Actual Service Balance" Line for Budgetted customers. */
/* 06/19/02 JFK - Added a flag (AddAmountToTotals) to prevent the "Actual Service Balance" and the addon amounts for
budgets from being added to the various calculated total amounts on the bill. A section was added to the WHERE
clause used to excluded these print lines from the SUM functions. */
/* 06/04/02 JFK - Added a field to store a single meter number for the bill card style. If they have the
BillingOptions.PrintMeterNumber set to true then it prints the meternumber for the first metered service
encountered. */
/* 12/03/01 JFK - added a sorting option to put final bills first. based on SWR UMS-967 */
/* vm 10/17/01 - I added a check to not select bank draft accounts unless they are prenotes.*/
/* This is FUN STUFF!!! Have fun debugging! -- JFK */
/* The method of my madness:
Currently this procedure starts by loading the basic information for accounts that will receive bills
in a temporary table (#TempPrintEntireBill). It then loads a cursor with the service/rate information that
is needed to generate the bills. As the proc loops through the cursor it writes out the data necessary to
generate the 11 lines of information located on the left side of the bill card in another temporary table
(#TempPrintBillServiceDetails). Once the cursor has finished, the proc then goes through the #TempPrintEntireBill
and begins filling in the service related information from the #TempPrintBillServiceDetails and generating
continuation bills as necessary. Once these two tables have been reconciled the proc returns a record set
where each record is a single bill.
If you can find a better or faster solution then by all means write your own code and go for it. :-p
JFK - faster methods that need to be implemented at some point:
--Rather than having separate tables for the account and service records and recombining them into one table at
the end simply start with the main table. Each time an insert is done for a service line it should contain
all of the account information. The table will be significantly larger, but the number of inserts, updates
and the extra cursor loop at the end will be reduced/removed.
--Don’t use the fixed number of columns, etc of 1-11. Insert indefinitely simply incrementing the line number.
Handle the continuation bills at the end of the proc. Summarize the records where line number >11 and update
record #11. When selecting the recordset to return simply return the records where line number <=11.
--Possible speed enhancement, particularly for larger customers: build a small table of add-ons for the account
at the start of the main cursor to prevent multiple hits to the large add-on table.
*/
IF EXISTS(SELECT name FROM sysobjects WHERE name = 'getPrintBill' AND type = 'P')
DROP PROCEDURE getPrintBill
GO
CREATE PROCEDURE getPrintBill
@CycleID INT,
@IncludeBankDrafts TINYINT,
@BeginningRoute INT,
@EndingRoute INT,
@BeginningAccount INT,
@EndingAccount INT,
@BeginningSequence INT,
@EndingSequence INT,
@SortWithFinalBillsFirst TINYINT,
@UseEnhancedBill TINYINT,
@BeginningBillingPeriodDate DATETIME = NULL,
@EndingBillingPeriodDate DATETIME = NULL,
@ForZipCodeSummaryReport TINYINT = 0, /* Added for the Zip Code Summary report */
@UseBillingAddress TINYINT = 1, /* Added for the Zip Code Summary report */
@SummarizeReport TINYINT = 1, /* Added for the Zip Code Summary report */
@PrintBreakdownForNonbarcodedBills INT = 0, /* Added for the Zip Code Summary report */
@IsWebBill INT = 0, /* Added for the the Web Bills; in reality this option simply prevents the total bill from printing. */
@IncludeDelinquents INT = 1, /* Added for SWR-391 */
@AutomaticallyPrintZipcodeSummaryReport TINYINT = 0, /* Only used when printing bills. */
@PrintOnlyBillsRemovedFromOutsourceBilling TINYINT = 0
AS
/* generic variables for the stored procedure */
DECLARE @Count INT
DECLARE @Index INT /* generic pointer used through to determine the location in a loop */
DECLARE @BillNumber INT /* the number of bills of the continuation bill. (i.e. one account gets 6 bills; the third bill is #3 ; hard math isn't it.) */
DECLARE @BillIndex INT /* used to determine location while looping through the Number of Bills to be printed */
DECLARE @NumberOfBills INT /* used to determine how many Bills to print */
DECLARE @LineCounter INT /* used to determine the line number to assign while writing lines into the "#TempPrintBillServiceDetails"
(i.e. tracking which detail line to print (Deposit Amount, Deduct Amount, Service Charges, Addon Charges, etc.) for WT */
DECLARE @NumberOfAccounts INT /* used when looping through "#TempPrintBillServiceDetails" in the final stages */
DECLARE @NumberOfServices INT /* used with the print separate arrears and negative billed arrears amounts. The service
billed arrears does not normally add to the totals on the report when negative so
that service unapplied cash is not distributed between services. However, due to
some funky capabilities in DBL, the amount does print in the totals, but only if
there is a single service for the account. SIGH. */
DECLARE @ErrorMessage VARCHAR(500)
DECLARE @FormattedAccountNumber VARCHAR(30)
DECLARE @SmallestMeteredServiceID INT /* the present and previous reading dates come from the first metered service created for the account. This value should be set to an unusally high number.*/
DECLARE @BillCode VARCHAR(3)
DECLARE @MeterNumber VARCHAR(20)
DECLARE @MeterNumberBillCard VARCHAR(20)
DECLARE @ServiceComputedTotal MONEY
DECLARE @BudgetServiceActualArrears MONEY /* Added 7/08/02 -- Recreation of DBL JUNK CODE: If the charges have been posted the total owed is simply the sum of Current,30,60,90
for a service and all if its add ons. If its unposted then you fake the posting by adding in the Computed
amounts. NOTE: This funky code is needed to determine the value inserted in the "Actual Service Balance" line. */
DECLARE @ServiceCompoundUsage INT
DECLARE @TotalOtherServices MONEY /* The total of all services except the one selected in the billing options */
DECLARE @ServiceTotalOnBillStub MONEY /* The total of the service selected in the billing options */
DECLARE @ServiceCodeToTotalOnBillStub VARCHAR(3) /* 2 is max # of characters that fit on the bill stub */
DECLARE @ServiceTypeCode VARCHAR(3)
DECLARE @AccountTotalArrears MONEY
DECLARE @PreviousAccountID INT
DECLARE @PreviousServiceID INT
DECLARE @PreviousServiceTypeID INT /* Used only for Combined with Like Charges; the lines created in the #TempPrintBillServiceDetails need the previous ServiceTypeID */
DECLARE @IncludeAllAccounts TINYINT
DECLARE @ArrearsBillCode VARCHAR(3) /* Prints either 'AR' or 'BF' based on the BillingOptions.ArrearsType option */
DECLARE @ArrearsName VARCHAR(20) /* Prints either 'Arrears' or 'Balance Forward' based on the BillingOptions.ArrearsType option */
DECLARE @RemainingServicesTotal MONEY /* This is used for to total the remaining amounts for all services and addons if Continuation bills are not being used */
DECLARE @CombinedServiceSurchargeAmount MONEY /* Used for the "Combine with Like Charges" option in Rates; This is loaded with the totals for each surcharge addon as the cursor loops through the services */
DECLARE @CombinedServiceLocalTaxAmount MONEY /* Used for the "Combine with Like Charges" option in Rates; This is loaded with the totals for each addon as the cursor loops through the services */
DECLARE @CombinedServiceStateTaxAmount MONEY /* Used for the "Combine with Like Charges" option in Rates; This is loaded with the totals for each addon as the cursor loops through the services */
DECLARE @IsEstimated INT
DECLARE @FinalOrEstimatedText VARCHAR(1) /* If the reading is estimated this is set to 'E '; if it is blank and the Service is a final bill it is set to 'F ' otherwise it is '' */
DECLARE @DecimalMultiplier INT /* Used to deteremine the number of decimal places in the usage.
@DecimalPlacesToUse is set to 0 unless the service is a Power Factor.
If the Service is a Power Factor it holds the number of decimal places specified in the Billing options
Rather than repeatedly test the number of decimal places to use when every usage print,
it is set when the service is loaded from the cursor and handled as each print line is built in STR() conversion of the Usage */
DECLARE @AddAmountToTotals TINYINT /* opposite of the IsBudget flag */
DECLARE @ForcePrintSeperateArrears TINYINT /* This variable is needed for the case in which they have print separate
arrears turned off, but a service for the account has a service
unapplied cash amount that exceeds the amount to be billed. If this
happens the Billed Arrears Amount will be negative and when added to the
net will adjust the balances of other services, which is incorrect. If
the billed arrears is negative and exceeds the computed amount for the
service then it needs to force the arrears to print separately.
Additionally, all service lines would not be added to the net amount
due on the bill. */
DECLARE @CurrentDate DATETIME
DECLARE @TotalFinalBillsNotMailed INT
/* Variables related to selecting Reading information from the database */
DECLARE @ReadingType INT
DECLARE @IsChangeout TINYINT
DECLARE @ChangeoutPresentReading DOUBLE PRECISION
DECLARE @ChangeoutPreviousReading DOUBLE PRECISION
DECLARE @ChangeoutUsage DOUBLE PRECISION
DECLARE @ChangeoutReadingDate DATETIME
DECLARE @ChangeoutPreviousReadingDate DATETIME
DECLARE @OldMeterID INT
DECLARE @OldMeterNumber VARCHAR(20)
DECLARE @PreviousReadingDate DATETIME
DECLARE @PresentReadingDate DATETIME
DECLARE @PresentReading DOUBLE PRECISION
DECLARE @PreviousReading DOUBLE PRECISION
DECLARE @Usage DOUBLE PRECISION
DECLARE @ActualUsage DOUBLE PRECISION
DECLARE @HoldPresentReadingId INT
DECLARE @HoldPresentReadingDate DATETIME
DECLARE @HoldPreviousReadingDate DATETIME
DECLARE @CurrentDays INT
DECLARE @LastMonthUsage DOUBLE PRECISION
DECLARE @LastMonthDays INT
DECLARE @SameMonthLastYearUsage DOUBLE PRECISION
DECLARE @SameMonthLastYearDays INT
DECLARE @AverageUsage DOUBLE PRECISION
DECLARE @DeductionAmount INT
DECLARE @DemandUsage DOUBLE PRECISION
DECLARE @ReadingCount INT
DECLARE @HoldReadingDate DATETIME
DECLARE @HoldUsage DOUBLE PRECISION
DECLARE @ChartVariablesLoaded TINYINT
DECLARE @DelinquentAmount MONEY
/* variables related to Addon information */
DECLARE @Surcharge1RateID INT
DECLARE @Surcharge2RateID INT
DECLARE @LocalTaxRateID INT
DECLARE @StateTaxRateID INT
DECLARE @ServiceComputedSurcharge1 MONEY
DECLARE @ServiceComputedSurcharge2 MONEY
DECLARE @ServiceComputedLocalTax MONEY
DECLARE @ServiceComputedStateTax MONEY
DECLARE @DelinquentAmountSurcharge1 MONEY
DECLARE @DelinquentAmountSurcharge2 MONEY
DECLARE @DelinquentAmountLocalTax MONEY
DECLARE @DelinquentAmountStateTax MONEY
DECLARE @DelinquentAmountPenalty MONEY
/* these items need to be saved if the CombineWithLikeCharges is used. The lines print
based on the first service/addon encountered. */
DECLARE @FirstSurchargeRateID INT
DECLARE @FirstSurchargeBillCode VARCHAR(3)
DECLARE @FirstSurchargePrintDescription TINYINT
DECLARE @FirstSurchargeRateDescription VARCHAR(29) /* 29 the maximum length of the readings/usage section */
DECLARE @FirstLocalTaxRateID INT
DECLARE @FirstLocalTaxBillCode VARCHAR(3)
DECLARE @FirstLocalTaxPrintDescription TINYINT
DECLARE @FirstLocalTaxRateDescription VARCHAR(29) /* 29 the maximum length of the readings/usage section */
DECLARE @FirstStateTaxRateID INT
DECLARE @FirstStateTaxBillCode VARCHAR(3)
DECLARE @FirstStateTaxPrintDescription TINYINT
DECLARE @FirstStateTaxRateDescription VARCHAR(29) /* 29 the maximum length of the readings/usage section */
/* these are counters to determine if at least one addon has CombinedWithLikeCharges. As it loops through
the ServiceCursor it may find 3 services and only 2 are CombinedWithLikeCharges. Each time it hits an addon
with the criteria it adds one to the counter. Using a boolean type check takes longer than the counter.
For some reason Surcharges combine into a single print line rather than two. */
DECLARE @SurchargeNumberCombined INT
DECLARE @LocalTaxNumberCombined INT
DECLARE @StateTaxNumberCombined INT
/* variables related to Addon Rate information */
DECLARE @Surcharge1Percentage DOUBLE PRECISION
DECLARE @Surcharge1BillCode VARCHAR(3)
DECLARE @Surcharge1PrintDescription TINYINT
DECLARE @Surcharge1DisplayMethod INT /* baSeparately=1 baCombinedWithLikeCharges=3 baCombinedWithServiceCharge=5 */
DECLARE @Surcharge1RateDescription VARCHAR(29) /* 29 the maximum length of the readings/usage section */
DECLARE @Surcharge1CommentsOnBill VARCHAR(45)
DECLARE @Surcharge2Percentage DOUBLE PRECISION
DECLARE @Surcharge2BillCode VARCHAR(3)
DECLARE @Surcharge2PrintDescription TINYINT
DECLARE @Surcharge2DisplayMethod INT /* baSeparately=1 baCombinedWithLikeCharges=3 baCombinedWithServiceCharge=5 */
DECLARE @Surcharge2RateDescription VARCHAR(29) /* 29 the maximum length of the readings/usage section */
DECLARE @Surcharge2CommentsOnBill VARCHAR(45)
DECLARE @LocalTaxBillCode VARCHAR(3)
DECLARE @LocalTaxPrintDescription TINYINT
DECLARE @LocalTaxDisplayMethod INT /* baSeparately=1 baCombinedWithLikeCharges=3 baCombinedWithServiceCharge=5 */
DECLARE @LocalTaxRateDescription VARCHAR(29) /* 29 the maximum length of the readings/usage section */
DECLARE @LocalTaxCommentsOnBill VARCHAR(45)
DECLARE @StateTaxBillCode VARCHAR(3)
DECLARE @StateTaxPrintDescription TINYINT
DECLARE @StateTaxDisplayMethod INT /* baSeparately=1 baCombinedWithLikeCharges=3 baCombinedWithServiceCharge=5 */
DECLARE @StateTaxRateDescription VARCHAR(29) /* 29 the maximum length of the readings/usage section */
DECLARE @StateTaxCommentsOnBill VARCHAR(45)
/* variables for the Cursor */
DECLARE @UseBankDrafts TINYINT
DECLARE @AccountID INT
DECLARE @ServiceID INT
DECLARE @ServiceBillCode VARCHAR(3)
DECLARE @RemainingUnappliedCashWhenComputed MONEY
DECLARE @CycleStatus INT
DECLARE @DeductFromAccountID INT
DECLARE @ServiceIsMetered TINYINT
DECLARE @PresentReadingID INT
DECLARE @PreviousReadingID INT
DECLARE @IsCompound TINYINT
DECLARE @ServiceAccountStat INT
DECLARE @IsFinalBill INT /* If service status = 7 then its set to 1 else its set to 0 */
DECLARE @ShowArrearsInBillingWhenInactive TINYINT
DECLARE @DepositPayable MONEY
DECLARE @ServiceBilledArrears MONEY
DECLARE @ServiceComputedAmount MONEY
DECLARE @ServiceIsBudget TINYINT
DECLARE @ServiceBudgetAmount MONEY
DECLARE @ServiceBudgetBalance MONEY
DECLARE @Cycle INT /* variable for the Cycle Number to print in the "Class" box on the bill */
DECLARE @CustomerType VARCHAR(2) /* variable for the CustomerType to print in the "Class" box on the bill */
DECLARE @ReadingFactor DOUBLE PRECISION
DECLARE @CalculationMethod INT
DECLARE @ServiceTypeID INT
DECLARE @ServiceTypeDescription VARCHAR(20)
DECLARE @ServiceTypeArrearsDescription VARCHAR(20)
DECLARE @RatePrintDescription TINYINT
DECLARE @RateDescription VARCHAR(20)
DECLARE @HoldServiceRateDescription VARCHAR(20)
DECLARE @HoldRateDescription VARCHAR(20)
DECLARE @IsServiceCharge TINYINT
/* Variables for the #TempPrintEntireBill */
DECLARE @CodeLine1 VARCHAR(3)
DECLARE @CodeLine2 VARCHAR(3)
DECLARE @CodeLine3 VARCHAR(3)
DECLARE @CodeLine4 VARCHAR(3)
DECLARE @CodeLine5 VARCHAR(3)
DECLARE @CodeLine6 VARCHAR(3)
DECLARE @CodeLine7 VARCHAR(3)
DECLARE @CodeLine8 VARCHAR(3)
DECLARE @CodeLine9 VARCHAR(3)
DECLARE @CodeLine10 VARCHAR(3)
DECLARE @CodeLine11 VARCHAR(3)
DECLARE @MeterNumberLine1 VARCHAR(20)
DECLARE @MeterNumberLine2 VARCHAR(20)
DECLARE @MeterNumberLine3 VARCHAR(20)
DECLARE @MeterNumberLine4 VARCHAR(20)
DECLARE @MeterNumberLine5 VARCHAR(20)
DECLARE @MeterNumberLine6 VARCHAR(20)
DECLARE @MeterNumberLine7 VARCHAR(20)
DECLARE @MeterNumberLine8 VARCHAR(20)
DECLARE @MeterNumberLine9 VARCHAR(20)
DECLARE @MeterNumberLine10 VARCHAR(20)
DECLARE @MeterNumberLine11 VARCHAR(20)
DECLARE @PresentReadingDateLine1 DATETIME
DECLARE @PresentReadingDateLine2 DATETIME
DECLARE @PresentReadingDateLine3 DATETIME
DECLARE @PresentReadingDateLine4 DATETIME
DECLARE @PresentReadingDateLine5 DATETIME
DECLARE @PresentReadingDateLine6 DATETIME
DECLARE @PresentReadingDateLine7 DATETIME
DECLARE @PresentReadingDateLine8 DATETIME
DECLARE @PresentReadingDateLine9 DATETIME
DECLARE @PresentReadingDateLine10 DATETIME
DECLARE @PresentReadingDateLine11 DATETIME
DECLARE @PreviousReadingDateLine1 DATETIME
DECLARE @PreviousReadingDateLine2 DATETIME
DECLARE @PreviousReadingDateLine3 DATETIME
DECLARE @PreviousReadingDateLine4 DATETIME
DECLARE @PreviousReadingDateLine5 DATETIME
DECLARE @PreviousReadingDateLine6 DATETIME
DECLARE @PreviousReadingDateLine7 DATETIME
DECLARE @PreviousReadingDateLine8 DATETIME
DECLARE @PreviousReadingDateLine9 DATETIME
DECLARE @PreviousReadingDateLine10 DATETIME
DECLARE @PreviousReadingDateLine11 DATETIME
DECLARE @PresentReadingLine1 DOUBLE PRECISION
DECLARE @PresentReadingLine2 DOUBLE PRECISION
DECLARE @PresentReadingLine3 DOUBLE PRECISION
DECLARE @PresentReadingLine4 DOUBLE PRECISION
DECLARE @PresentReadingLine5 DOUBLE PRECISION
DECLARE @PresentReadingLine6 DOUBLE PRECISION
DECLARE @PresentReadingLine7 DOUBLE PRECISION
DECLARE @PresentReadingLine8 DOUBLE PRECISION
DECLARE @PresentReadingLine9 DOUBLE PRECISION
DECLARE @PresentReadingLine10 DOUBLE PRECISION
DECLARE @PresentReadingLine11 DOUBLE PRECISION
DECLARE @PreviousReadingLine1 DOUBLE PRECISION
DECLARE @PreviousReadingLine2 DOUBLE PRECISION
DECLARE @PreviousReadingLine3 DOUBLE PRECISION
DECLARE @PreviousReadingLine4 DOUBLE PRECISION
DECLARE @PreviousReadingLine5 DOUBLE PRECISION
DECLARE @PreviousReadingLine6 DOUBLE PRECISION
DECLARE @PreviousReadingLine7 DOUBLE PRECISION
DECLARE @PreviousReadingLine8 DOUBLE PRECISION
DECLARE @PreviousReadingLine9 DOUBLE PRECISION
DECLARE @PreviousReadingLine10 DOUBLE PRECISION
DECLARE @PreviousReadingLine11 DOUBLE PRECISION
DECLARE @UsageLine1 DOUBLE PRECISION
DECLARE @UsageLine2 DOUBLE PRECISION
DECLARE @UsageLine3 DOUBLE PRECISION
DECLARE @UsageLine4 DOUBLE PRECISION
DECLARE @UsageLine5 DOUBLE PRECISION
DECLARE @UsageLine6 DOUBLE PRECISION
DECLARE @UsageLine7 DOUBLE PRECISION
DECLARE @UsageLine8 DOUBLE PRECISION
DECLARE @UsageLine9 DOUBLE PRECISION
DECLARE @UsageLine10 DOUBLE PRECISION
DECLARE @UsageLine11 DOUBLE PRECISION
DECLARE @CurrentDaysLine1 INT
DECLARE @CurrentDaysLine2 INT
DECLARE @CurrentDaysLine3 INT
DECLARE @CurrentDaysLine4 INT
DECLARE @CurrentDaysLine5 INT
DECLARE @CurrentDaysLine6 INT
DECLARE @CurrentDaysLine7 INT
DECLARE @CurrentDaysLine8 INT
DECLARE @CurrentDaysLine9 INT
DECLARE @CurrentDaysLine10 INT
DECLARE @CurrentDaysLine11 INT
DECLARE @LastMonthUsageLine1 DOUBLE PRECISION
DECLARE @LastMonthUsageLine2 DOUBLE PRECISION
DECLARE @LastMonthUsageLine3 DOUBLE PRECISION
DECLARE @LastMonthUsageLine4 DOUBLE PRECISION
DECLARE @LastMonthUsageLine5 DOUBLE PRECISION
DECLARE @LastMonthUsageLine6 DOUBLE PRECISION
DECLARE @LastMonthUsageLine7 DOUBLE PRECISION
DECLARE @LastMonthUsageLine8 DOUBLE PRECISION
DECLARE @LastMonthUsageLine9 DOUBLE PRECISION
DECLARE @LastMonthUsageLine10 DOUBLE PRECISION
DECLARE @LastMonthUsageLine11 DOUBLE PRECISION
DECLARE @LastMonthDaysLine1 INT
DECLARE @LastMonthDaysLine2 INT
DECLARE @LastMonthDaysLine3 INT
DECLARE @LastMonthDaysLine4 INT
DECLARE @LastMonthDaysLine5 INT
DECLARE @LastMonthDaysLine6 INT
DECLARE @LastMonthDaysLine7 INT
DECLARE @LastMonthDaysLine8 INT
DECLARE @LastMonthDaysLine9 INT
DECLARE @LastMonthDaysLine10 INT
DECLARE @LastMonthDaysLine11 INT
DECLARE @SameMonthLastYearUsageLine1 DOUBLE PRECISION
DECLARE @SameMonthLastYearUsageLine2 DOUBLE PRECISION
DECLARE @SameMonthLastYearUsageLine3 DOUBLE PRECISION
DECLARE @SameMonthLastYearUsageLine4 DOUBLE PRECISION
DECLARE @SameMonthLastYearUsageLine5 DOUBLE PRECISION
DECLARE @SameMonthLastYearUsageLine6 DOUBLE PRECISION
DECLARE @SameMonthLastYearUsageLine7 DOUBLE PRECISION
DECLARE @SameMonthLastYearUsageLine8 DOUBLE PRECISION
DECLARE @SameMonthLastYearUsageLine9 DOUBLE PRECISION
DECLARE @SameMonthLastYearUsageLine10 DOUBLE PRECISION
DECLARE @SameMonthLastYearUsageLine11 DOUBLE PRECISION
DECLARE @SameMonthLastYearDaysLine1 INT
DECLARE @SameMonthLastYearDaysLine2 INT
DECLARE @SameMonthLastYearDaysLine3 INT
DECLARE @SameMonthLastYearDaysLine4 INT
DECLARE @SameMonthLastYearDaysLine5 INT
DECLARE @SameMonthLastYearDaysLine6 INT
DECLARE @SameMonthLastYearDaysLine7 INT
DECLARE @SameMonthLastYearDaysLine8 INT
DECLARE @SameMonthLastYearDaysLine9 INT
DECLARE @SameMonthLastYearDaysLine10 INT
DECLARE @SameMonthLastYearDaysLine11 INT
DECLARE @ChargesLine1 MONEY
DECLARE @ChargesLine2 MONEY
DECLARE @ChargesLine3 MONEY
DECLARE @ChargesLine4 MONEY
DECLARE @ChargesLine5 MONEY
DECLARE @ChargesLine6 MONEY
DECLARE @ChargesLine7 MONEY
DECLARE @ChargesLine8 MONEY
DECLARE @ChargesLine9 MONEY
DECLARE @ChargesLine10 MONEY
DECLARE @ChargesLine11 MONEY
DECLARE @TextLine1 VARCHAR(29)
DECLARE @TextLine2 VARCHAR(29)
DECLARE @TextLine3 VARCHAR(29)
DECLARE @TextLine4 VARCHAR(29)
DECLARE @TextLine5 VARCHAR(29)
DECLARE @TextLine6 VARCHAR(29)
DECLARE @TextLine7 VARCHAR(29)
DECLARE @TextLine8 VARCHAR(29)
DECLARE @TextLine9 VARCHAR(29)
DECLARE @TextLine10 VARCHAR(29)
DECLARE @TextLine11 VARCHAR(29)
DECLARE @BillDescription1 VARCHAR(20)
DECLARE @BillDescription2 VARCHAR(20)
DECLARE @BillDescription3 VARCHAR(20)
DECLARE @BillDescription4 VARCHAR(20)
DECLARE @BillDescription5 VARCHAR(20)
DECLARE @BillDescription6 VARCHAR(20)
DECLARE @BillDescription7 VARCHAR(20)
DECLARE @BillDescription8 VARCHAR(20)
DECLARE @BillDescription9 VARCHAR(20)
DECLARE @BillDescription10 VARCHAR(20)
DECLARE @BillDescription11 VARCHAR(20)
DECLARE @RateDescription1 VARCHAR(20)
DECLARE @RateDescription2 VARCHAR(20)
DECLARE @RateDescription3 VARCHAR(20)
DECLARE @RateDescription4 VARCHAR(20)
DECLARE @RateDescription5 VARCHAR(20)
DECLARE @RateDescription6 VARCHAR(20)
DECLARE @RateDescription7 VARCHAR(20)
DECLARE @RateDescription8 VARCHAR(20)
DECLARE @RateDescription9 VARCHAR(20)
DECLARE @RateDescription10 VARCHAR(20)
DECLARE @RateDescription11 VARCHAR(20)
DECLARE @Line1IsForMeteredService TINYINT
DECLARE @Line2IsForMeteredService TINYINT
DECLARE @Line3IsForMeteredService TINYINT
DECLARE @Line4IsForMeteredService TINYINT
DECLARE @Line5IsForMeteredService TINYINT
DECLARE @Line6IsForMeteredService TINYINT
DECLARE @Line7IsForMeteredService TINYINT
DECLARE @Line8IsForMeteredService TINYINT
DECLARE @Line9IsForMeteredService TINYINT
DECLARE @Line10IsForMeteredService TINYINT
DECLARE @Line11IsForMeteredService TINYINT
DECLARE @ChartReadingDate1 DATETIME
DECLARE @ChartReadingDate2 DATETIME
DECLARE @ChartReadingDate3 DATETIME
DECLARE @ChartReadingDate4 DATETIME
DECLARE @ChartReadingDate5 DATETIME
DECLARE @ChartReadingDate6 DATETIME
DECLARE @ChartReadingDate7 DATETIME
DECLARE @ChartReadingDate8 DATETIME
DECLARE @ChartReadingDate9 DATETIME
DECLARE @ChartReadingDate10 DATETIME
DECLARE @ChartReadingDate11 DATETIME
DECLARE @ChartReadingDate12 DATETIME
DECLARE @ChartReadingDate13 DATETIME
DECLARE @ChartUsage1 DOUBLE PRECISION
DECLARE @ChartUsage2 DOUBLE PRECISION
DECLARE @ChartUsage3 DOUBLE PRECISION
DECLARE @ChartUsage4 DOUBLE PRECISION
DECLARE @ChartUsage5 DOUBLE PRECISION
DECLARE @ChartUsage6 DOUBLE PRECISION
DECLARE @ChartUsage7 DOUBLE PRECISION
DECLARE @ChartUsage8 DOUBLE PRECISION
DECLARE @ChartUsage9 DOUBLE PRECISION
DECLARE @ChartUsage10 DOUBLE PRECISION
DECLARE @ChartUsage11 DOUBLE PRECISION
DECLARE @ChartUsage12 DOUBLE PRECISION
DECLARE @ChartUsage13 DOUBLE PRECISION
DECLARE @ChartHighestUsage DOUBLE PRECISION
DECLARE @PriorBalance MONEY /* Total arrears that are > 0. */
DECLARE @PenaltyGrandTotal MONEY
DECLARE @PrintThisBill TINYINT
DECLARE @AmountDueTotal MONEY
DECLARE @AmountDueLateTotal MONEY /* @AmountDueTotal + @PenaltyGrandTotal */
DECLARE @AccountCommentLine VARCHAR(30) /* The Comment line (1-10) to print from the Account */
DECLARE @HasFinalBill TINYINT /* Passes 1 if a final bill exists; 0 if not; report hides or displays the '**FINAL BILL**' message as necessary */
DECLARE @IsMemoBill TINYINT /* Passes 1 if its a memo bill; 0 if not; report hides or displays the 'MEMO BILL - DO NOT PAY' message as necessary */
DECLARE @HasEstimatedReadings TINYINT /* Passes 1 if estimated readings exist; 0 if not; report hides or displays the '**ESTIMATED**' message as necessary */
DECLARE @NoticesSent INT
DECLARE @IsDelinquent TINYINT /* Passes 1 if bill that matches the delinquent notice criteria; 0 if not; Needed for the tenant/landlord SendDelinquentBillTo option */
DECLARE @IncludesMultipleMeters TINYINT /* Passes 1 if multiple meters exist; 0 if not; report hides or displays the 'INCLUDES MULTIPLE METERS' message as necessary */
/* compound service variables */
DECLARE @CompoundServiceID INT
DECLARE @CompoundMeterNumber VARCHAR(20)
DECLARE @CompoundUsage DOUBLE PRECISION
DECLARE @CompoundPresentReading DOUBLE PRECISION
DECLARE @CompoundPreviousReading DOUBLE PRECISION
DECLARE @CompoundPresentReadingDate DATETIME
DECLARE @CompoundPreviousReadingDate DATETIME
DECLARE @CompoundIsEstimated TINYINT
/* parameters from the Billing Options */
DECLARE @SurchargeRateForFuelAdjustmentsID INT
DECLARE @AddArrearsToNet TINYINT
DECLARE @PrintSeperateArrears TINYINT
DECLARE @ApplyDepositOnFinals TINYINT
DECLARE @UseReadingFactor TINYINT
DECLARE @ArrearsType TINYINT
DECLARE @BillSortOrder TINYINT
DECLARE @PrintPenalty TINYINT
DECLARE @PrintContinuation TINYINT
DECLARE @PrintMeterNumber TINYINT
DECLARE @PrintAverageUsage TINYINT
DECLARE @PrintZeroCredit INT
DECLARE @MinimumBalance MONEY
DECLARE @ServiceToTotalSeperatelyID INT
DECLARE @RemovePreviousInfoFromBill TINYINT
DECLARE @CommentLineToPrint INT
DECLARE @ImpliedDecimalPlaces INT /*Used for the consumptions on Power Factor Meters only; see comment for @DecimalPlacesToUse */
DECLARE @BillStyle INT
DECLARE @PrintReadingAndUsageForInactiveServicesOnBills TINYINT
DECLARE @PrintEndingBalanceForBudgets TINYINT
DECLARE @OverrideBillingPeriodDates TINYINT
DECLARE @PrintAddOnsSeparatelyForBudgetCustomers TINYINT
DECLARE @PrintCompoundReadingsOnBills TINYINT
DECLARE @MessageLine1 VARCHAR(30)
DECLARE @MessageLine2 VARCHAR(30)
DECLARE @MessageLine3 VARCHAR(30)
DECLARE @MessageLine4 VARCHAR(30)
DECLARE @PrintPostNetBarcode TINYINT
DECLARE @ZipcodeSummaryMinimumBarcodedBillsInGroup INT
DECLARE @MinimumNumberOfBarcodedBillsNeededForDiscount INT
DECLARE @PostageAutomationRateCarrierRoute MONEY
DECLARE @PostageAutomationRateFiveDigitZip MONEY
DECLARE @PostageAutomationRateThreeDigitZip MONEY
DECLARE @PostageAutomationRateAADC MONEY
DECLARE @PostageAutomationRateMixedAADC MONEY
DECLARE @PostageNonAutomationRatePresorted MONEY
DECLARE @PostageNonAutomationRateSinglePiece MONEY
DECLARE @NumberOfBillsPerOneFootTray INT
DECLARE @NumberOfBillsPerTwoFootTray INT
DECLARE @ZipcodeOfPostOfficeBillsAreMailedFrom VARCHAR(9)
/* DECLARE @LocalAADCId INT */
DECLARE @UseCarrierRouteSortation TINYINT
DECLARE @PrintActualUsageOnBills TINYINT
/* parameters from UMOptions */
DECLARE @TrackBudgetArrears TINYINT
/* Delinquent Option variables */
DECLARE @DelinquentCutoffDate DATETIME
DECLARE @DelinquentBalancesToInclude INT
DECLARE @MinimumDelinquentBalance MONEY
DECLARE @IncludeTotalInDelinquentAmount TINYINT
DECLARE @DelinquentDaysSinceLastPayment INT
/* Table of the reading ids that are initial readings for new meters. */
DECLARE @ChangeoutPreviousReadings TABLE
(PreviousChangeoutReadingId INT)
/* Table to hold the previous 12 readings for a service. (We already have current and previous,
we need the 12 before the previous reading.) */
DECLARE @ChartOfReadings TABLE
(ReadingId INT,
ReadingDate DATETIME,
Usage DOUBLE PRECISION)
/* Declare the #TempPrintBillServiceDetails */
CREATE TABLE #TempPrintBillServiceDetails
(AccountID INT,
ServiceID INT,
ServiceTypeID INT,
BillDescription VARCHAR(20),
RateDescription VARCHAR(20),
IsForMeteredService TINYINT,
IsArrears TINYINT, /* Passes 1 if line is for arrears; 0 if not; used when creating the #TempPrintEntireBill to determine whether to add the arrears to the net. */
LineNumber INT,
TextLine VARCHAR(29), /* 29 = the length of the Readings and usage field section */
BillCode VARCHAR(3),
MeterNumber VARCHAR(20),
PresentReadingDate DATETIME,
PreviousReadingDate DATETIME,
PresentReading DOUBLE PRECISION,
PreviousReading DOUBLE PRECISION,
Usage DOUBLE PRECISION,
CurrentDays INT,
LastMonthUsage DOUBLE PRECISION,
LastMonthDays INT,
SameMonthLastYearUsage DOUBLE PRECISION,
SameMonthLastYearDays INT,
BillAmount MONEY, /* a dumping ground for the amount that applies to the total bill per service detail line;
before the #TempPrintEntireBill record is created these totals are used to create the AmountDueTotal */
HasFinalBill TINYINT, /* Passes 1 if a final bill exists; 0 if not; report hides or displays the '**FINAL BILL**' message as necessary */
HasEstimatedReadings TINYINT, /* Passes 1 if estimated readings exist; 0 if not; report hides or displays the '**ESTIMATED**' message as necessary */
IncludesMultipleMeters TINYINT, /* Passes 1 if multiple meters exist; 0 if not; report hides or displays the 'INCLUDES MULTIPLE METERS' message as necessary */
AddAmountToTotals TINYINT) /* determines whether the amount contained in the print line gets added to the totals */
/* Add indexes for speed */
CREATE INDEX idxTempPrintBillServiceDetailsAccountID
ON #TempPrintBillServiceDetails (AccountID)
CREATE INDEX idxTempPrintBillServiceDetailsAddAmountToTotals
ON #TempPrintBillServiceDetails (AddAmountToTotals)
CREATE INDEX idxTempPrintBillServiceDetailsBillAmount
ON #TempPrintBillServiceDetails (BillAmount)
CREATE INDEX idxTempPrintBillServiceDetailsLineNumber
ON #TempPrintBillServiceDetails (LineNumber)
/* Declare the #TempPrintEntireBill */
CREATE TABLE #TempPrintEntireBill
(BillNumber INT, /* this is a manual tracked number to determine the Bill number should continuation bills be necessary */
NumberOfBills INT, /* the total Number of bills for the Account */
CycleID INT,
AccountID INT,
AccountsRoute INT,
AccountsAccountNumber INT,
AccountsSequence INT,
AccountsInCareOf VARCHAR(25),
AccountsSalutation VARCHAR(20),
AccountsFirstName VARCHAR(30),
AccountsMiddleName VARCHAR(30),
AccountsLastName VARCHAR(40),
AccountsNameSuffix VARCHAR(20),
AccountsDBAName VARCHAR(40),
AccountsCarrierRoute VARCHAR(7),
ServiceNumber VARCHAR(15),
ServiceName VARCHAR(25),
ServiceCity VARCHAR(40), /* Added 2/18/02--This field was added to be used in the flat text file for ADM */
ServiceState VARCHAR(2), /* Added 2/18/02--This field was added to be used in the flat text file for ADM */
ServiceZip VARCHAR(9), /* Added 2/18/02--This field was added to be used in the flat text file for ADM */
BillingAddress VARCHAR(40),
BillingCity VARCHAR(40),
BillingState VARCHAR(2),
BillingZip VARCHAR(9),
ForeignBillingAddress TINYINT,
DataPointBarCode VARCHAR(2),
BarCodeCheckDigit VARCHAR(1),
ZipCodeSummaryZip VARCHAR(9),
ZipCodeSummaryFiveDigitZip VARCHAR(5),
IsBarcodedBill TINYINT,
IsTenant TINYINT,
IsLandlord TINYINT,
LandlordAccountID INT,
LandlordName VARCHAR(40),
LandlordDBAName VARCHAR(40),
LandlordInCareOf VARCHAR(25),
LandlordAddress VARCHAR(40),
LandlordCity VARCHAR(40),
LandlordState VARCHAR(2),
LandlordZip VARCHAR(9),
ForeignLandlordAddress TINYINT,
LandlordCarrierRoute VARCHAR(7),
LandlordDataPointBarCode VARCHAR(2),
LandlordBarCodeCheckDigit VARCHAR(1),
LandlordBillIsBarcoded TINYINT,
SendBillTo INT,
SendDelinquentBillTo INT,
UsesBudgets TINYINT,
UseBankDrafts TINYINT, /* this field is used to determine if the account should get a Memobills */
RemainingUnappliedCashWhenComputed MONEY, /* used by by the Services cursor only; does not display on the bill */
CycleStatus INT,
PreviousReadingDate DATETIME,
PresentReadingDate DATETIME,
CodeLine1 VARCHAR(3), /* two digit Bill Code, plus a digit for 'E' if estimated OR 'F' if Final */
CodeLine2 VARCHAR(3), /* two digit Bill Code, plus a digit for 'E' if estimated OR 'F' if Final */
CodeLine3 VARCHAR(3), /* two digit Bill Code, plus a digit for 'E' if estimated OR 'F' if Final */
CodeLine4 VARCHAR(3), /* two digit Bill Code, plus a digit for 'E' if estimated OR 'F' if Final */
CodeLine5 VARCHAR(3), /* two digit Bill Code, plus a digit for 'E' if estimated OR 'F' if Final */
CodeLine6 VARCHAR(3), /* two digit Bill Code, plus a digit for 'E' if estimated OR 'F' if Final */
CodeLine7 VARCHAR(3), /* two digit Bill Code, plus a digit for 'E' if estimated OR 'F' if Final */
CodeLine8 VARCHAR(3), /* two digit Bill Code, plus a digit for 'E' if estimated OR 'F' if Final */
CodeLine9 VARCHAR(3), /* two digit Bill Code, plus a digit for 'E' if estimated OR 'F' if Final */
CodeLine10 VARCHAR(3), /* two digit Bill Code, plus a digit for 'E' if estimated OR 'F' if Final */
CodeLine11 VARCHAR(3), /* two digit Bill Code, plus a digit for 'E' if estimated OR 'F' if Final */
MeterNumberLine1 VARCHAR(20),
MeterNumberLine2 VARCHAR(20),
MeterNumberLine3 VARCHAR(20),
MeterNumberLine4 VARCHAR(20),
MeterNumberLine5 VARCHAR(20),
MeterNumberLine6 VARCHAR(20),
MeterNumberLine7 VARCHAR(20),
MeterNumberLine8 VARCHAR(20),
MeterNumberLine9 VARCHAR(20),
MeterNumberLine10 VARCHAR(20),
MeterNumberLine11 VARCHAR(20),
PresentReadingDateLine1 DATETIME,
PresentReadingDateLine2 DATETIME,
PresentReadingDateLine3 DATETIME,
PresentReadingDateLine4 DATETIME,
PresentReadingDateLine5 DATETIME,
PresentReadingDateLine6 DATETIME,
PresentReadingDateLine7 DATETIME,
PresentReadingDateLine8 DATETIME,
PresentReadingDateLine9 DATETIME,
PresentReadingDateLine10 DATETIME,
PresentReadingDateLine11 DATETIME,
PreviousReadingDateLine1 DATETIME,
PreviousReadingDateLine2 DATETIME,
PreviousReadingDateLine3 DATETIME,
PreviousReadingDateLine4 DATETIME,
PreviousReadingDateLine5 DATETIME,
PreviousReadingDateLine6 DATETIME,
PreviousReadingDateLine7 DATETIME,
PreviousReadingDateLine8 DATETIME,
PreviousReadingDateLine9 DATETIME,
PreviousReadingDateLine10 DATETIME,
PreviousReadingDateLine11 DATETIME,
PresentReadingLine1 DOUBLE PRECISION,
PresentReadingLine2 DOUBLE PRECISION,
PresentReadingLine3 DOUBLE PRECISION,
PresentReadingLine4 DOUBLE PRECISION,
PresentReadingLine5 DOUBLE PRECISION,
PresentReadingLine6 DOUBLE PRECISION,
PresentReadingLine7 INT,
PresentReadingLine8 DOUBLE PRECISION,
PresentReadingLine9 DOUBLE PRECISION,
PresentReadingLine10 DOUBLE PRECISION,
PresentReadingLine11 DOUBLE PRECISION,
PreviousReadingLine1 DOUBLE PRECISION,
PreviousReadingLine2 DOUBLE PRECISION,
PreviousReadingLine3 DOUBLE PRECISION,
PreviousReadingLine4 DOUBLE PRECISION,
PreviousReadingLine5 DOUBLE PRECISION,
PreviousReadingLine6 DOUBLE PRECISION,
PreviousReadingLine7 DOUBLE PRECISION,
PreviousReadingLine8 DOUBLE PRECISION,
PreviousReadingLine9 DOUBLE PRECISION,
PreviousReadingLine10 DOUBLE PRECISION,
PreviousReadingLine11 DOUBLE PRECISION,
UsageLine1 DOUBLE PRECISION,
UsageLine2 DOUBLE PRECISION,
UsageLine3 DOUBLE PRECISION,
UsageLine4 DOUBLE PRECISION,
UsageLine5 DOUBLE PRECISION,
UsageLine6 DOUBLE PRECISION,
UsageLine7 DOUBLE PRECISION,
UsageLine8 DOUBLE PRECISION,
UsageLine9 DOUBLE PRECISION,
UsageLine10 DOUBLE PRECISION,
UsageLine11 DOUBLE PRECISION,
CurrentDaysLine1 INT,
CurrentDaysLine2 INT,
CurrentDaysLine3 INT,
CurrentDaysLine4 INT,
CurrentDaysLine5 INT,
CurrentDaysLine6 INT,
CurrentDaysLine7 INT,
CurrentDaysLine8 INT,
CurrentDaysLine9 INT,
CurrentDaysLine10 INT,
CurrentDaysLine11 INT,
LastMonthUsageLine1 DOUBLE PRECISION,
LastMonthUsageLine2 DOUBLE PRECISION,
LastMonthUsageLine3 DOUBLE PRECISION,
LastMonthUsageLine4 DOUBLE PRECISION,
LastMonthUsageLine5 DOUBLE PRECISION,
LastMonthUsageLine6 DOUBLE PRECISION,
LastMonthUsageLine7 DOUBLE PRECISION,
LastMonthUsageLine8 DOUBLE PRECISION,
LastMonthUsageLine9 DOUBLE PRECISION,
LastMonthUsageLine10 DOUBLE PRECISION,
LastMonthUsageLine11 DOUBLE PRECISION,
LastMonthDaysLine1 INT,
LastMonthDaysLine2 INT,
LastMonthDaysLine3 INT,
LastMonthDaysLine4 INT,
LastMonthDaysLine5 INT,
LastMonthDaysLine6 INT,
LastMonthDaysLine7 INT,
LastMonthDaysLine8 INT,
LastMonthDaysLine9 INT,
LastMonthDaysLine10 INT,
LastMonthDaysLine11 INT,
SameMonthLastYearUsageLine1 DOUBLE PRECISION,
SameMonthLastYearUsageLine2 DOUBLE PRECISION,
SameMonthLastYearUsageLine3 DOUBLE PRECISION,
SameMonthLastYearUsageLine4 DOUBLE PRECISION,
SameMonthLastYearUsageLine5 DOUBLE PRECISION,
SameMonthLastYearUsageLine6 DOUBLE PRECISION,
SameMonthLastYearUsageLine7 DOUBLE PRECISION,
SameMonthLastYearUsageLine8 DOUBLE PRECISION,
SameMonthLastYearUsageLine9 DOUBLE PRECISION,
SameMonthLastYearUsageLine10 DOUBLE PRECISION,
SameMonthLastYearUsageLine11 DOUBLE PRECISION,
SameMonthLastYearDaysLine1 INT,
SameMonthLastYearDaysLine2 INT,
SameMonthLastYearDaysLine3 INT,
SameMonthLastYearDaysLine4 INT,
SameMonthLastYearDaysLine5 INT,
SameMonthLastYearDaysLine6 INT,
SameMonthLastYearDaysLine7 INT,
SameMonthLastYearDaysLine8 INT,
SameMonthLastYearDaysLine9 INT,
SameMonthLastYearDaysLine10 INT,
SameMonthLastYearDaysLine11 INT,
ChargesLine1 MONEY,
ChargesLine2 MONEY,
ChargesLine3 MONEY,
ChargesLine4 MONEY,
ChargesLine5 MONEY,
ChargesLine6 MONEY,
ChargesLine7 MONEY,
ChargesLine8 MONEY,
ChargesLine9 MONEY,
ChargesLine10 MONEY,
ChargesLine11 MONEY,
TextLine1 VARCHAR(29),
TextLine2 VARCHAR(29),
TextLine3 VARCHAR(29),
TextLine4 VARCHAR(29),
TextLine5 VARCHAR(29),
TextLine6 VARCHAR(29),
TextLine7 VARCHAR(29),
TextLine8 VARCHAR(29),
TextLine9 VARCHAR(29),
TextLine10 VARCHAR(29),
TextLine11 VARCHAR(29),
BillDescription1 VARCHAR(20),
BillDescription2 VARCHAR(20),
BillDescription3 VARCHAR(20),
BillDescription4 VARCHAR(20),
BillDescription5 VARCHAR(20),
BillDescription6 VARCHAR(20),
BillDescription7 VARCHAR(20),
BillDescription8 VARCHAR(20),
BillDescription9 VARCHAR(20),
BillDescription10 VARCHAR(20),
BillDescription11 VARCHAR(20),
RateDescription1 VARCHAR(20),
RateDescription2 VARCHAR(20),
RateDescription3 VARCHAR(20),
RateDescription4 VARCHAR(20),
RateDescription5 VARCHAR(20),
RateDescription6 VARCHAR(20),
RateDescription7 VARCHAR(20),
RateDescription8 VARCHAR(20),
RateDescription9 VARCHAR(20),
RateDescription10 VARCHAR(20),
RateDescription11 VARCHAR(20),
Line1IsForMeteredService TINYINT,
Line2IsForMeteredService TINYINT,
Line3IsForMeteredService TINYINT,
Line4IsForMeteredService TINYINT,
Line5IsForMeteredService TINYINT,
Line6IsForMeteredService TINYINT,
Line7IsForMeteredService TINYINT,
Line8IsForMeteredService TINYINT,
Line9IsForMeteredService TINYINT,
Line10IsForMeteredService TINYINT,
Line11IsForMeteredService TINYINT,
ChartReadingDate1 DATETIME,
ChartReadingDate2 DATETIME,
ChartReadingDate3 DATETIME,
ChartReadingDate4 DATETIME,
ChartReadingDate5 DATETIME,
ChartReadingDate6 DATETIME,
ChartReadingDate7 DATETIME,
ChartReadingDate8 DATETIME,
ChartReadingDate9 DATETIME,
ChartReadingDate10 DATETIME,
ChartReadingDate11 DATETIME,
ChartReadingDate12 DATETIME,
ChartReadingDate13 DATETIME,
ChartUsage1 DOUBLE PRECISION,
ChartUsage2 DOUBLE PRECISION,
ChartUsage3 DOUBLE PRECISION,
ChartUsage4 DOUBLE PRECISION,
ChartUsage5 DOUBLE PRECISION,
ChartUsage6 DOUBLE PRECISION,
ChartUsage7 DOUBLE PRECISION,
ChartUsage8 DOUBLE PRECISION,
ChartUsage9 DOUBLE PRECISION,
ChartUsage10 DOUBLE PRECISION,
ChartUsage11 DOUBLE PRECISION,
ChartUsage12 DOUBLE PRECISION,
ChartUsage13 DOUBLE PRECISION,
CurrentPeriodNumberofDays INT,
PreviousPeriodNumberofDays INT,
SameMonthLastYearNumberofDays INT,
ChartHighestUsage DOUBLE PRECISION,
CustomerType VARCHAR(2),
Cycle INT,
PriorBalance MONEY, /* Total Arrears that are > 0. */
PenaltyAmount MONEY,
PrintThisBill TINYINT,
AmountDueTotal MONEY,
AmountDueLateTotal MONEY, /* AmountDueTotal + PenaltyAmount */
ServiceCodeToTotalOnBillStub VARCHAR(3),/* The ServiceCode for the Service to total seperately and print on the Stub */
ServiceTotalOnBillStub MONEY, /* The Total charges for the Service to total seperately and print on the Stub */
AccountCommentLine1 VARCHAR(30), /* The Comment line 1 from the Account */
AccountCommentLine2 VARCHAR(30), /* The Comment line 2 from the Account */
HasFinalBill TINYINT, /* Passes 1 if a final bill exists; 0 if not; report hides or displays the '**FINAL BILL**' message as necessary */
IsMemoBill TINYINT, /* Passes 1 if its a memo bill; 0 if not; report hides or displays the 'MEMO BILL - DO NOT PAY' message as necessary */
NoticesSent INT, /* Added for SWR-391 */
DelinquentAmount MONEY, /* Needed for the tenant/landlord SendDelinquentBillTo option */
LastPaymentDate DATETIME, /* Needed for the tenant/landlord SendDelinquentBillTo option */
HasEstimatedReadings TINYINT, /* Passes 1 if estimated readings exist; 0 if not; report hides or displays the '**ESTIMATED**' message as necessary */
IncludesMultipleMeters TINYINT, /* Passes 1 if multiple meters exist; 0 if not; report hides or displays the 'INCLUDES MULTIPLE METERS' message as necessary */
MeterNumber VARCHAR(20), /* This is used to contain the first meter number encountered for the services on a particular bill. */
MessageLine1 VARCHAR(30),
MessageLine2 VARCHAR(30),
MessageLine3 VARCHAR(30),
MessageLine4 VARCHAR(30),
PenaltyDate DATETIME,
PostageRateType INT,
TrayNumber INT)
/* Add indexes for speed */
CREATE INDEX idxTempPrintEntireBillAccountID
ON #TempPrintEntireBill (AccountID)
CREATE INDEX idxTempPrintEntireBillBillNumber
ON #TempPrintEntireBill (BillNumber)
CREATE UNIQUE CLUSTERED INDEX idxTempPrintEntireBillClustered
ON #TempPrintEntireBill (AccountId, BillNumber)
DECLARE @USPSQualificationReport TABLE
(TrayNumber INT,
TraySize INT, /* 1' or 2' */
RateType INT, /* AutomationCarrierRoute = 1, AutomationFiveDigitZip = 2, AutomationThreeDigitZip = 3, AutomationAADC = 4, AutomationMixedAADC = 5, NonautomationPresorted = 6, NonautomationSinglePiece = 7 */
TraySortationLevel VARCHAR(5), /* CRD, 5DG, 3DG, AADC, or MAAD */
TrayZipcode VARCHAR(5), /* Destination Zipcode (Local Zip for Mixed AADC) */
GroupDestination VARCHAR(10), /* each Carrier Route per 5-digit zip, the 5-digit zip, the 3-digit zip, each 3-digit zip in AADC, each AADC Number in mixed AADC, Zipcode for Non-automation */
NumberOfBills INT)
/* Declarations for qualitication report cursor. */
DECLARE @PostageRateType INT
DECLARE @ThreeDigitZip VARCHAR(3)
DECLARE @FiveDigitZip VARCHAR(5)
DECLARE @CarrierRoute VARCHAR(7)
DECLARE @AADCNumber VARCHAR(5)
DECLARE @AADCId INT
DECLARE @CurrentPostageRateType INT
DECLARE @CurrentThreeDigitZip VARCHAR(3)
DECLARE @CurrentFiveDigitZip VARCHAR(5)
DECLARE @CurrentCarrierRoute VARCHAR(7)
DECLARE @CurrentAADCNumber VARCHAR(5)
DECLARE @CurrentAADCId INT
DECLARE @NumberOfBillsInTray INT
DECLARE @NumberOfBillsInTrayGroup INT
DECLARE @RemainingNumberOfBillsInRateGroup INT
DECLARE @TrayNumber INT
DECLARE @TraySize INT
DECLARE @UseOverflowTray TINYINT
SET NOCOUNT ON
/*Determine whether to pull all or a range of Accounts */
IF @BeginningRoute = -1 AND @EndingRoute = -1 AND
@BeginningAccount = -1 AND @EndingAccount = -1 AND
@BeginningSequence = -1 AND @EndingSequence = -1
BEGIN
SET @IncludeAllAccounts = 1
END
ELSE
BEGIN
SET @IncludeAllAccounts = 0
END
/* Load local variables with the necessary Delinquent Options. */
SELECT @DelinquentBalancesToInclude = ISNULL(DelinquentOptions.DelinquentBalance, 0),
@MinimumDelinquentBalance = ISNULL(DelinquentOptions.MinimumBalance, 0),
@IncludeTotalInDelinquentAmount = ISNULL(DelinquentOptions.IncludeTotalInDelinquentAmount, 0),
@DelinquentDaysSinceLastPayment = ISNULL(DelinquentOptions.DelinquentDaysSinceLastPayment, 0)
FROM DelinquentOptions
WHERE Deleted = 0
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR (' An error occurred while loading the data from the Delinquent Options.',16,1)
RETURN(99)
END
SET @CurrentDate = GETDATE()
/* Set up the date to use in selecting the accounts that are delinquent. */
SET @DelinquentCutoffDate = GETDATE()
/* Set the time on the date to midnight. */
SET @DelinquentCutoffDate = CAST(CAST(DATEPART(mm,@DelinquentCutoffDate) AS VARCHAR(2)) + '/' + CAST(DATEPART(dd,@DelinquentCutoffDate) AS VARCHAR(2)) + '/' + CAST(DATEPART(yyyy,@DelinquentCutoffDate) AS VARCHAR(4)) + ' 11:59:59 PM' AS DATETIME)
/* This is a "Calculated date"; it is the current system date - @DelinquentDaysSinceLastPayment */
SET @DelinquentCutoffDate = DATEADD(dd, (@DelinquentDaysSinceLastPayment * -1), @DelinquentCutoffDate)
SET @LineCounter = 0 /* Initialize it to zero */
SET @SmallestMeteredServiceID = 1999999999 /* close to the max allowed for the INT datatype. If they have more services than they would be more worried about the pond water speed of their database than an error in the bills. */
SET @PreviousAccountID = 0
SET @PreviousServiceID = 0
SET @PreviousServiceTypeID = 0
SET @FirstSurchargeRateID = 0
SET @FirstLocalTaxRateID = 0
SET @FirstStateTaxRateID = 0
SET @ServiceComputedSurcharge1 = 0
SET @ServiceComputedSurcharge2 = 0
SET @ServiceComputedLocalTax = 0
SET @ServiceComputedStateTax = 0
SET @SurchargeNumberCombined = 0
SET @LocalTaxNumberCombined = 0
SET @StateTaxNumberCombined = 0
SET @FinalOrEstimatedText = ''
/* load local variable with the necessary Billing Options */
SELECT @SurchargeRateForFuelAdjustmentsID = BillingOptions.SurchargeRateForFuelAdjustmentsID,
@AddArrearsToNet = BillingOptions.AddArrearsToNet,
@PrintSeperateArrears = BillingOptions.PrintSeparateArrearsForEachService,
@ApplyDepositOnFinals = BillingOptions.ApplyDepositOnFinals,
@UseReadingFactor = BillingOptions.UseReadingFactor,
@ArrearsType = BillingOptions.ArrearsType,
@BillSortOrder = BillingOptions.SortBills,
@PrintPenalty = BillingOptions.PrintPenalty,
@PrintContinuation = BillingOptions.PrintContinuation,
@PrintMeterNumber = 0, /*BillingOptions.PrintMeterNumber,;left out in the beta version, meter numbers do not fit on the K9306 bill style */
@PrintAverageUsage = BillingOptions.PrintAverageUsage,
@PrintZeroCredit = BillingOptions.ZeroBill,
@MinimumBalance = BillingOptions.MinimumBalance,
@ServiceToTotalSeperatelyID = BillingOptions.ServiceToTotalOnBillStubID,
@RemovePreviousInfoFromBill = BillingOptions.RemovePreviousInfoFromBill,
@CommentLineToPrint = BillingOptions.CommentLineToPrintOnStub,
@ImpliedDecimalPlaces = BillingOptions.ImpliedDecimalPlaces,
@BillStyle = BillingOptions.BillStyle,
@PrintReadingAndUsageForInactiveServicesOnBills = BillingOptions.PrintReadingAndUsageForInactiveServicesOnBills,
@PrintEndingBalanceForBudgets = BillingOptions.PrintEndingBalanceForBudgets,
@OverrideBillingPeriodDates = BillingOptions.OverrideBillingPeriodDates,
@PrintAddOnsSeparatelyForBudgetCustomers = BillingOptions.PrintAddOnsSeparatelyForBudgetCustomers,
@PrintCompoundReadingsOnBills = BillingOptions.PrintCompoundReadingsOnBills,
@MessageLine1 = BillingOptions.MessageLine1,
@MessageLine2 = BillingOptions.MessageLine2,
@MessageLine3 = BillingOptions.MessageLine3,
@MessageLine4 = BillingOptions.MessageLine4,
@PrintPostNetBarcode = BillingOptions.PrintPostNetBarcode,
@ZipcodeSummaryMinimumBarcodedBillsInGroup = BillingOptions.ZipcodeSummaryMinimumBarcodedBillsInGroup,
@MinimumNumberOfBarcodedBillsNeededForDiscount = BillingOptions.MinimumNumberOfBarcodedBillsNeededForDiscount,
@PostageAutomationRateCarrierRoute = BillingOptions.PostageAutomationRateCarrierRoute,
@PostageAutomationRateFiveDigitZip = BillingOptions.PostageAutomationRateFiveDigitZip,
@PostageAutomationRateThreeDigitZip = BillingOptions.PostageAutomationRateThreeDigitZip,
@PostageAutomationRateAADC = BillingOptions.PostageAutomationRateAADC,
@PostageAutomationRateMixedAADC = BillingOptions.PostageAutomationRateMixedAADC,
@PostageNonAutomationRatePresorted = BillingOptions.PostageNonAutomationRatePresorted,
@PostageNonAutomationRateSinglePiece = BillingOptions.PostageNonAutomationRateSinglePiece,
@NumberOfBillsPerOneFootTray = BillingOptions.NumberOfBillsPerOneFootTray,
@NumberOfBillsPerTwoFootTray = BillingOptions.NumberOfBillsPerTwoFootTray,
@ZipcodeOfPostOfficeBillsAreMailedFrom = BillingOptions.ZipcodeOfPostOfficeBillsAreMailedFrom,
@UseCarrierRouteSortation = BillingOptions.UseCarrierRouteSortation,
@PrintActualUsageOnBills = BillingOptions.PrintActualUsageOnBills
FROM BillingOptions
WHERE Deleted = 0
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR (' An error occurred while loading the data from the Billing Options.',16,1)
RETURN(99)
END
IF @ForZipCodeSummaryReport = 1 OR (@ForZipCodeSummaryReport <> 1 AND @BillSortOrder = 1)
BEGIN
/* If this table isn't used for the zipcode summary, its being used to order the bills and needs to be defined. */
CREATE TABLE #ZipcodeSummary
(Zipcode VARCHAR(5),
CarrierRoute VARCHAR(7),
ThreeDigitZipcode VARCHAR(5),
AADCId INT,
AADCNumber VARCHAR(5),
AADCCity VARCHAR(40),
AADCState VARCHAR(2),
RateType INT, /* AutomationCarrierRoute = 1, AutomationFiveDigitZip = 2, AutomationThreeDigitZip = 3, AutomationAADC = 4, AutomationMixedAADC = 5, NonautomationPresorted = 6, NonautomationSinglePiece = 7 */
RateTypeString VARCHAR(30),
IsDetailRecord TINYINT,
IsZipcodeMixedAADCRecord TINYINT,
NumberOfBills INT,
IsReportTotalsRecord TINYINT,
TotalCarrierRouteBills INT,
TotalNumberOfBillsInFiveDigitZips INT,
TotalNumberOfBillsInThreeDigitZips INT,
TotalAADCBills INT,
TotalMixedAADCBills INT,
TotalPresortedNonautomationBills INT,
TotalSinglePieceBills INT,
TotalFinalBillsNotMailed INT,
TotalBillsMailed INT,
TotalNumberOfBills INT,
NumberOfOneFootTraysUsed INT,
NumberOfTwoFootTraysUsed INT,
CarrierRouteRateAmount MONEY,
FiveDigitRateAmount MONEY,
ThreeDigitRateAmount MONEY,
AADCRateAmount MONEY,
MixedAADCRateAmount MONEY,
PresortedNonautomationRateAmount MONEY,
SinglePieceRateAmount MONEY,
TotalPostageAmount MONEY)
/* Add indexes for speed */
CREATE INDEX idxZipcodeSummaryZipcode
ON #ZipcodeSummary (Zipcode)
CREATE INDEX idxZipcodeSummaryCarrierRoute
ON #ZipcodeSummary (CarrierRoute)
CREATE INDEX idxZipcodeSummaryThreeDigitZipcode
ON #ZipcodeSummary (ThreeDigitZipcode)
CREATE INDEX idxZipcodeSummaryAADCId
ON #ZipcodeSummary (AADCId)
CREATE INDEX idxZipcodeSummaryRateType
ON #ZipcodeSummary (RateType)
END
/* load local variable with the necessary Billing Options */
SELECT @TrackBudgetArrears = UMOptions.TrackBudgetArrears
FROM UMOptions
WHERE Deleted = 0
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR (' An error occurred while loading the data from the General Options.',16,1)
RETURN(99)
END
/* Determine whether to print "Arrears" or "Balance Forward" on the bill */
IF @ArrearsType = 1
BEGIN
SET @ArrearsBillCode = 'AR'
SET @ArrearsName = 'Arrears'
END
ELSE
BEGIN
SET @ArrearsBillCode = 'BF'
SET @ArrearsName = 'Balance Forward'
END
/* If the parameters for the billing period dates are zero, set them to NULL so they appear as blank rather
than 12/30/YYYY on the bill. */
IF @BeginningBillingPeriodDate = 0
BEGIN
SET @BeginningBillingPeriodDate = NULL
END
IF @EndingBillingPeriodDate = 0
BEGIN
SET @EndingBillingPeriodDate = NULL
END
/* load the #TempPrintEntireBill */
INSERT INTO #TempPrintEntireBill
(BillNumber,
NumberOfBills,
CycleID,
AccountID,
AccountsRoute,
AccountsAccountNumber,
AccountsSequence,
AccountsInCareOf,
AccountsSalutation,
AccountsFirstName,
AccountsMiddleName,
AccountsLastName,
AccountsNameSuffix,
AccountsDBAName,
AccountsCarrierRoute,
ServiceNumber,
ServiceName,
ServiceCity, /* Added 2/18/02--This field was added to be used in the flat text file for ADM */
ServiceState, /* Added 2/18/02--This field was added to be used in the flat text file for ADM */
ServiceZip, /* Added 2/18/02--This field was added to be used in the flat text file for ADM */
BillingAddress,
BillingCity,
BillingState,
BillingZip,
ForeignBillingAddress,
DataPointBarCode,
BarCodeCheckDigit,
ZipCodeSummaryZip,
ZipCodeSummaryFiveDigitZip,
IsBarcodedBill,
IsTenant,
IsLandlord,
LandlordAccountID,
LandlordName,
LandlordDBAName,
LandlordInCareOf,
LandlordAddress,
LandlordCity,
LandlordState,
LandlordZip,
ForeignLandlordAddress,
LandlordCarrierRoute,
LandlordDataPointBarCode,
LandlordBarCodeCheckDigit,
LandlordBillIsBarcoded,
SendBillTo,
SendDelinquentBillTo,
UsesBudgets,
UseBankDrafts,
RemainingUnappliedCashWhenComputed,
CycleStatus,
PreviousReadingDate,
PresentReadingDate,
CodeLine1,
CodeLine2,
CodeLine3,
CodeLine4,
CodeLine5,
CodeLine6,
CodeLine7,
CodeLine8,
CodeLine9,
CodeLine10,
CodeLine11,
MeterNumberLine1,
MeterNumberLine2,
MeterNumberLine3,
MeterNumberLine4,
MeterNumberLine5,
MeterNumberLine6,
MeterNumberLine7,
MeterNumberLine8,
MeterNumberLine9,
MeterNumberLine10,
MeterNumberLine11,
PresentReadingDateLine1,
PresentReadingDateLine2,
PresentReadingDateLine3,
PresentReadingDateLine4,
PresentReadingDateLine5,
PresentReadingDateLine6,
PresentReadingDateLine7,
PresentReadingDateLine8,
PresentReadingDateLine9,
PresentReadingDateLine10,
PresentReadingDateLine11,
PreviousReadingDateLine1,
PreviousReadingDateLine2,
PreviousReadingDateLine3,
PreviousReadingDateLine4,
PreviousReadingDateLine5,
PreviousReadingDateLine6,
PreviousReadingDateLine7,
PreviousReadingDateLine8,
PreviousReadingDateLine9,
PreviousReadingDateLine10,
PreviousReadingDateLine11,
PresentReadingLine1,
PresentReadingLine2,
PresentReadingLine3,
PresentReadingLine4,
PresentReadingLine5,
PresentReadingLine6,
PresentReadingLine7,
PresentReadingLine8,
PresentReadingLine9,
PresentReadingLine10,
PresentReadingLine11,
PreviousReadingLine1,
PreviousReadingLine2,
PreviousReadingLine3,
PreviousReadingLine4,
PreviousReadingLine5,
PreviousReadingLine6,
PreviousReadingLine7,
PreviousReadingLine8,
PreviousReadingLine9,
PreviousReadingLine10,
PreviousReadingLine11,
UsageLine1,
UsageLine2,
UsageLine3,
UsageLine4,
UsageLine5,
UsageLine6,
UsageLine7,
UsageLine8,
UsageLine9,
UsageLine10,
UsageLine11,
CurrentDaysLine1,
CurrentDaysLine2,
CurrentDaysLine3,
CurrentDaysLine4,
CurrentDaysLine5,
CurrentDaysLine6,
CurrentDaysLine7,
CurrentDaysLine8,
CurrentDaysLine9,
CurrentDaysLine10,
CurrentDaysLine11,
LastMonthUsageLine1,
LastMonthUsageLine2,
LastMonthUsageLine3,
LastMonthUsageLine4,
LastMonthUsageLine5,
LastMonthUsageLine6,
LastMonthUsageLine7,
LastMonthUsageLine8,
LastMonthUsageLine9,
LastMonthUsageLine10,
LastMonthUsageLine11,
LastMonthDaysLine1,
LastMonthDaysLine2,
LastMonthDaysLine3,
LastMonthDaysLine4,
LastMonthDaysLine5,
LastMonthDaysLine6,
LastMonthDaysLine7,
LastMonthDaysLine8,
LastMonthDaysLine9,
LastMonthDaysLine10,
LastMonthDaysLine11,
SameMonthLastYearUsageLine1,
SameMonthLastYearUsageLine2,
SameMonthLastYearUsageLine3,
SameMonthLastYearUsageLine4,
SameMonthLastYearUsageLine5,
SameMonthLastYearUsageLine6,
SameMonthLastYearUsageLine7,
SameMonthLastYearUsageLine8,
SameMonthLastYearUsageLine9,
SameMonthLastYearUsageLine10,
SameMonthLastYearUsageLine11,
SameMonthLastYearDaysLine1,
SameMonthLastYearDaysLine2,
SameMonthLastYearDaysLine3,
SameMonthLastYearDaysLine4,
SameMonthLastYearDaysLine5,
SameMonthLastYearDaysLine6,
SameMonthLastYearDaysLine7,
SameMonthLastYearDaysLine8,
SameMonthLastYearDaysLine9,
SameMonthLastYearDaysLine10,
SameMonthLastYearDaysLine11,
ChargesLine1,
ChargesLine2,
ChargesLine3,
ChargesLine4,
ChargesLine5,
ChargesLine6,
ChargesLine7,
ChargesLine8,
ChargesLine9,
ChargesLine10,
ChargesLine11,
TextLine1,
TextLine2,
TextLine3,
TextLine4,
TextLine5,
TextLine6,
TextLine7,
TextLine8,
TextLine9,
TextLine10,
TextLine11,
BillDescription1,
BillDescription2,
BillDescription3,
BillDescription4,
BillDescription5,
BillDescription6,
BillDescription7,
BillDescription8,
BillDescription9,
BillDescription10,
BillDescription11,
RateDescription1,
RateDescription2,
RateDescription3,
RateDescription4,
RateDescription5,
RateDescription6,
RateDescription7,
RateDescription8,
RateDescription9,
RateDescription10,
RateDescription11,
Line1IsForMeteredService,
Line2IsForMeteredService,
Line3IsForMeteredService,
Line4IsForMeteredService,
Line5IsForMeteredService,
Line6IsForMeteredService,
Line7IsForMeteredService,
Line8IsForMeteredService,
Line9IsForMeteredService,
Line10IsForMeteredService,
Line11IsForMeteredService,
ChartReadingDate1,
ChartReadingDate2,
ChartReadingDate3,
ChartReadingDate4,
ChartReadingDate5,
ChartReadingDate6,
ChartReadingDate7,
ChartReadingDate8,
ChartReadingDate9,
ChartReadingDate10,
ChartReadingDate11,
ChartReadingDate12,
ChartReadingDate13,
ChartUsage1,
ChartUsage2,
ChartUsage3,
ChartUsage4,
ChartUsage5,
ChartUsage6,
ChartUsage7,
ChartUsage8,
ChartUsage9,
ChartUsage10,
ChartUsage11,
ChartUsage12,
ChartUsage13,
CurrentPeriodNumberofDays,
PreviousPeriodNumberofDays,
SameMonthLastYearNumberofDays,
ChartHighestUsage,
CustomerType,
Cycle,
PriorBalance,
PenaltyAmount,
PrintThisBill,
AmountDueTotal,
AmountDueLateTotal,
ServiceCodeToTotalOnBillStub,
ServiceTotalOnBillStub,
AccountCommentLine1,
AccountCommentLine2,
HasFinalBill,
IsMemoBill,
NoticesSent,
DelinquentAmount,
LastPaymentDate,
HasEstimatedReadings,
IncludesMultipleMeters,
MeterNumber,
MessageLine1,
MessageLine2,
MessageLine3,
MessageLine4,
PenaltyDate,
PostageRateType,
TrayNumber)
SELECT 1, /* initial BillNumber should be 1 */
1, /* initial number of bills */
Accounts.CycleID,
Accounts.AccountID,
Accounts.Route,
Accounts.AccountNumber,
Accounts.SequenceNumber,
Accounts.InCareOf,
Accounts.Salutation,
Accounts.FirstName,
Accounts.MiddleName,
Accounts.LastName,
Accounts.NameSuffix,
Accounts.DBAName,
SPACE(7 - LEN(LTRIM(RTRIM(Accounts.CarrierRoute)))) + LTRIM(RTRIM(Accounts.CarrierRoute)),
ISNULL(Accounts.ServiceAddressStreetNumber,''),
ISNULL(Accounts.ServiceAddressStreetName,''),
Accounts.ServiceCity, /* Added 2/18/02--This field was added to be used in the flat text file for ADM */
Accounts.ServiceState, /* Added 2/18/02--This field was added to be used in the flat text file for ADM */
Accounts.ServiceZip, /* Added 2/18/02--This field was added to be used in the flat text file for ADM */
Accounts.BillingAddress,
Accounts.BillingCity,
Accounts.BillingState,
Accounts.BillingZip,
Accounts.ForeignBillingAddress,
(CASE
WHEN LTRIM(RTRIM(ISNULL(Accounts.DataPointBarCode, ''))) = '' THEN ''
ELSE SPACE(2 - LEN(LTRIM(RTRIM(ISNULL(Accounts.DataPointBarCode, ''))))) + LTRIM(RTRIM(ISNULL(Accounts.DataPointBarCode, '')))
END) AS DataPointBarcode,
LTRIM(RTRIM(ISNULL(Accounts.BarCodeCheckDigit, ''))) AS BarcodeCheckDigit,
(CASE
WHEN @UseBillingAddress = 1 THEN ISNULL(Accounts.BillingZip, '00000')
ELSE ISNULL(Accounts.ServiceZip, '00000')
END) AS ZipCodeSummaryZip,
(CASE
WHEN @UseBillingAddress = 1 THEN LEFT(ISNULL(Accounts.BillingZip, '00000'), 5)
ELSE LEFT(ISNULL(Accounts.ServiceZip, '00000'), 5)
END) AS ZipCodeSummaryFiveDigitZip,
(CASE /* Print postnet and not printing dot matrix bills. */
WHEN @PrintPostNetBarcode = 1 AND @BillStyle <> 7 AND LEN(LTRIM(RTRIM(ISNULL(Accounts.BillingZip , '')))) = 9 AND
LTRIM(RTRIM(ISNULL(Accounts.DataPointBarCode, ''))) <> '' AND
LTRIM(RTRIM(ISNULL(Accounts.BarCodeCheckDigit, ''))) <> '' THEN 1
ELSE 0
END) AS IsBarcodedBill,
IsTenant,
IsLandlord,
LandlordAccountID,
LandlordName,
LandlordDBAName,
LandlordInCareOf,
LandlordAddress,
LandlordCity,
LandlordState,
LandlordZip,
ForeignLandlordAddress,
SPACE(7 - LEN(LTRIM(RTRIM(Accounts.LandlordCarrierRoute)))) + LTRIM(RTRIM(Accounts.LandlordCarrierRoute)),
(CASE
WHEN LTRIM(RTRIM(ISNULL(Accounts.LandlordDataPointBarcode, ''))) = '' THEN ''
ELSE SPACE(2 - LEN(LTRIM(RTRIM(ISNULL(Accounts.LandlordDataPointBarcode, ''))))) + LTRIM(RTRIM(ISNULL(Accounts.LandlordDataPointBarcode, '')))
END) AS LandlordDataPointBarcode,
LTRIM(RTRIM(ISNULL(Accounts.LandlordBarcodeCheckDigit, ''))) AS LandlordBarCodeCheckDigit,
(CASE /* Print postnet and not printing dot matrix bills. */
WHEN @PrintPostNetBarcode = 1 AND @BillStyle <> 7 AND LEN(LTRIM(RTRIM(ISNULL(Accounts.LandlordZip , '')))) = 9 AND
LTRIM(RTRIM(ISNULL(Accounts.LandlordDataPointBarcode, ''))) <> '' AND
LTRIM(RTRIM(ISNULL(Accounts.LandlordBarcodeCheckDigit, ''))) <> '' THEN 1
ELSE 0
END) AS LandlordBillIsBarcoded,
SendBillTo,
SendDelinquentBillTo,
0, /* UsesBudgets */
Accounts.UseBankDrafts,
Accounts.RemainingUnappliedCashWhenComputed,
Cycles.CycleStatus,
@BeginningBillingPeriodDate, /* Previous Reading Date = default it to the parameter passed to the proc. If they are using the Override Date option it will automatically be set. If they aren't using the option then it be Null anyway. */
@EndingBillingPeriodDate, /* Present Reading Date = default it to the parameter passed to the proc. If they are using the Override Date option it will automatically be set. If they aren't using the option then it be Null anyway. */
NULL, /* CodeLine1 */
NULL, /* CodeLine2 */
NULL, /* CodeLine3 */
NULL, /* CodeLine4 */
NULL, /* CodeLine5 */
NULL, /* CodeLine6 */
NULL, /* CodeLine7 */
NULL, /* CodeLine8 */
NULL, /* CodeLine9 */
NULL, /* CodeLine10 */
NULL, /* CodeLine11 */
'', /* MeterNumberLine1 */
'', /* MeterNumberLine2 */
'', /* MeterNumberLine3 */
'', /* MeterNumberLine4 */
'', /* MeterNumberLine5 */
'', /* MeterNumberLine6 */
'', /* MeterNumberLine7 */
'', /* MeterNumberLine8 */
'', /* MeterNumberLine9 */
'', /* MeterNumberLine10 */
'', /* MeterNumberLine11 */
NULL, /* PresentReadingDateLine1 */
NULL, /* PresentReadingDateLine2 */
NULL, /* PresentReadingDateLine3 */
NULL, /* PresentReadingDateLine4 */
NULL, /* PresentReadingDateLine5 */
NULL, /* PresentReadingDateLine6 */
NULL, /* PresentReadingDateLine7 */
NULL, /* PresentReadingDateLine8 */
NULL, /* PresentReadingDateLine9 */
NULL, /* PresentReadingDateLine10 */
NULL, /* PresentReadingDateLine11 */
NULL, /* PreviousReadingDateLine1 */
NULL, /* PreviousReadingDateLine2 */
NULL, /* PreviousReadingDateLine3 */
NULL, /* PreviousReadingDateLine4 */
NULL, /* PreviousReadingDateLine5 */
NULL, /* PreviousReadingDateLine6 */
NULL, /* PreviousReadingDateLine7 */
NULL, /* PreviousReadingDateLine8 */
NULL, /* PreviousReadingDateLine9 */
NULL, /* PreviousReadingDateLine10 */
NULL, /* PreviousReadingDateLine11 */
NULL, /* PresentReadingLine1 */
NULL, /* PresentReadingLine2 */
NULL, /* PresentReadingLine3 */
NULL, /* PresentReadingLine4 */
NULL, /* PresentReadingLine5 */
NULL, /* PresentReadingLine6 */
NULL, /* PresentReadingLine7 */
NULL, /* PresentReadingLine8 */
NULL, /* PresentReadingLine9 */
NULL, /* PresentReadingLine10 */
NULL, /* PresentReadingLine11 */
NULL, /* PreviousReadingLine1 */
NULL, /* PreviousReadingLine2 */
NULL, /* PreviousReadingLine3 */
NULL, /* PreviousReadingLine4 */
NULL, /* PreviousReadingLine5 */
NULL, /* PreviousReadingLine6 */
NULL, /* PreviousReadingLine7 */
NULL, /* PreviousReadingLine8 */
NULL, /* PreviousReadingLine9 */
NULL, /* PreviousReadingLine10 */
NULL, /* PreviousReadingLine11 */
NULL, /* UsageLine1 */
NULL, /* UsageLine2 */
NULL, /* UsageLine3 */
NULL, /* UsageLine4 */
NULL, /* UsageLine5 */
NULL, /* UsageLine6 */
NULL, /* UsageLine7 */
NULL, /* UsageLine8 */
NULL, /* UsageLine9 */
NULL, /* UsageLine10 */
NULL, /* UsageLine11 */
0, /* CurrentDaysLine1 */
0, /* CurrentDaysLine2 */
0, /* CurrentDaysLine3 */
0, /* CurrentDaysLine4 */
0, /* CurrentDaysLine5 */
0, /* CurrentDaysLine6 */
0, /* CurrentDaysLine7 */
0, /* CurrentDaysLine8 */
0, /* CurrentDaysLine9 */
0, /* CurrentDaysLine10 */
0, /* CurrentDaysLine11 */
0, /* LastMonthUsageLine1 */
0, /* LastMonthUsageLine2 */
0, /* LastMonthUsageLine3 */
0, /* LastMonthUsageLine4 */
0, /* LastMonthUsageLine5 */
0, /* LastMonthUsageLine6 */
0, /* LastMonthUsageLine7 */
0, /* LastMonthUsageLine8 */
0, /* LastMonthUsageLine9 */
0, /* LastMonthUsageLine10 */
0, /* LastMonthUsageLine11 */
0, /* LastMonthDaysLine1 */
0, /* LastMonthDaysLine2 */
0, /* LastMonthDaysLine3 */
0, /* LastMonthDaysLine4 */
0, /* LastMonthDaysLine5 */
0, /* LastMonthDaysLine6 */
0, /* LastMonthDaysLine7 */
0, /* LastMonthDaysLine8 */
0, /* LastMonthDaysLine9 */
0, /* LastMonthDaysLine10 */
0, /* LastMonthDaysLine11 */
0, /* SameMonthLastYearUsageLine1 */
0, /* SameMonthLastYearUsageLine2 */
0, /* SameMonthLastYearUsageLine3 */
0, /* SameMonthLastYearUsageLine4 */
0, /* SameMonthLastYearUsageLine5 */
0, /* SameMonthLastYearUsageLine6 */
0, /* SameMonthLastYearUsageLine7 */
0, /* SameMonthLastYearUsageLine8 */
0, /* SameMonthLastYearUsageLine9 */
0, /* SameMonthLastYearUsageLine10 */
0, /* SameMonthLastYearUsageLine11 */
0, /* SameMonthLastYearDaysLine1 */
0, /* SameMonthLastYearDaysLine2 */
0, /* SameMonthLastYearDaysLine3 */
0, /* SameMonthLastYearDaysLine4 */
0, /* SameMonthLastYearDaysLine5 */
0, /* SameMonthLastYearDaysLine6 */
0, /* SameMonthLastYearDaysLine7 */
0, /* SameMonthLastYearDaysLine8 */
0, /* SameMonthLastYearDaysLine9 */
0, /* SameMonthLastYearDaysLine10 */
0, /* SameMonthLastYearDaysLine11 */
NULL, /* ChargesLine1 */
NULL, /* ChargesLine2 */
NULL, /* ChargesLine3 */
NULL, /* ChargesLine4 */
NULL, /* ChargesLine5 */
NULL, /* ChargesLine6 */
NULL, /* ChargesLine7 */
NULL, /* ChargesLine8 */
NULL, /* ChargesLine9 */
NULL, /* ChargesLine10 */
NULL, /* ChargesLine11 */
NULL, /* TextLine1 */
NULL, /* TextLine2 */
NULL, /* TextLine3 */
NULL, /* TextLine4 */
NULL, /* TextLine5 */
NULL, /* TextLine6 */
NULL, /* TextLine7 */
NULL, /* TextLine8 */
NULL, /* TextLine9 */
NULL, /* TextLine10 */
NULL, /* TextLine11 */
NULL, /* BillDescription1 */
NULL, /* BillDescription2 */
NULL, /* BillDescription3 */
NULL, /* BillDescription4 */
NULL, /* BillDescription5 */
NULL, /* BillDescription6 */
NULL, /* BillDescription7 */
NULL, /* BillDescription8 */
NULL, /* BillDescription9 */
NULL, /* BillDescription10 */
NULL, /* BillDescription11 */
NULL, /* RateDescription1 */
NULL, /* RateDescription2 */
NULL, /* RateDescription3 */
NULL, /* RateDescription4 */
NULL, /* RateDescription5 */
NULL, /* RateDescription6 */
NULL, /* RateDescription7 */
NULL, /* RateDescription8 */
NULL, /* RateDescription9 */
NULL, /* RateDescription10 */
NULL, /* RateDescription11 */
0, /* Line1IsForMeteredService */
0, /* Line2IsForMeteredService */
0, /* Line3IsForMeteredService */
0, /* Line4IsForMeteredService */
0, /* Line5IsForMeteredService */
0, /* Line6IsForMeteredService */
0, /* Line7IsForMeteredService */
0, /* Line8IsForMeteredService */
0, /* Line9IsForMeteredService */
0, /* Line10IsForMeteredService */
0, /* Line11IsForMeteredService */
NULL, /* ChartReadingDate1 */
NULL, /* ChartReadingDate2 */
NULL, /* ChartReadingDate3 */
NULL, /* ChartReadingDate4 */
NULL, /* ChartReadingDate5 */
NULL, /* ChartReadingDate6 */
NULL, /* ChartReadingDate7 */
NULL, /* ChartReadingDate8 */
NULL, /* ChartReadingDate9 */
NULL, /* ChartReadingDate10 */
NULL, /* ChartReadingDate11 */
NULL, /* ChartReadingDate12 */
NULL, /* ChartReadingDate13 */
0, /* ChartUsage1 */
0, /* ChartUsage2 */
0, /* ChartUsage3 */
0, /* ChartUsage4 */
0, /* ChartUsage5 */
0, /* ChartUsage6 */
0, /* ChartUsage7 */
0, /* ChartUsage8 */
0, /* ChartUsage9 */
0, /* ChartUsage10 */
0, /* ChartUsage11 */
0, /* ChartUsage12 */
0, /* ChartUsage13 */
0, /* CurrentPeriodNumberofDays */
0, /* PreviousPeriodNumberofDays */
0, /* SameMonthLastYearNumberofDays */
0, /* ChartHighestUsage */
CustomerTypes.CustomerType,
Cycles.Cycle,
0, /* PriorBalance */
0, /* PenaltyAmount */
0, /* PrintThisBill */
0, /* AmountDueTotal */
0, /* AmountDueLateTotal */
NULL, /* ServiceCodeToTotalOnBillStub */
0, /* ServiceTotalOnBillStub */
Comment1, /* AccountCommentLine1 */
Comment2, /* AccountCommentLine2 */
0, /* HasFinalBill */
(CASE /* 10-17-01 print memo bill msg on draft customers that ARE NOT prenote */
WHEN Accounts.UseBankDrafts = 1 AND Accounts.ACHPrenotification = 0 Then 1
ELSE 0
End), /* IsMemoBill */
NULL /* NoticesSent */,
Accounts.RemainingUnappliedCashWhenComputed, /* DelinquentAmount */
Accounts.AccountLastPaymentDate, /* LastPaymentDate */
0, /* HasEstimatedReadings */
0, /* IncludesMultipleMeters */
'', /* MeterNumber */
(CASE WHEN LEN(ISNULL(RouteComments.MessageLine1, '')) <> 0 THEN RouteComments.MessageLine1
ELSE @MessageLine1
END) AS MessageLine1,
(CASE WHEN LEN(ISNULL(RouteComments.MessageLine2, '')) <> 0 THEN RouteComments.MessageLine2
ELSE @MessageLine2
END) AS MessageLine2,
(CASE WHEN LEN(ISNULL(RouteComments.MessageLine3, '')) <> 0 THEN RouteComments.MessageLine3
ELSE @MessageLine3
END) AS MessageLine3,
(CASE WHEN LEN(ISNULL(RouteComments.MessageLine4, '')) <> 0 THEN RouteComments.MessageLine4
ELSE @MessageLine4
END) AS MessageLine4,
NULL AS PenaltyDate,
/*vm 9/20/06 cmnt out the following..not used and causing error when cycle day is 31 and month can only have 30 days*/
/*CAST((CAST(MONTH(@CurrentDate) AS VARCHAR(2)) + '/' + CAST((CASE WHEN ISNULL(Cycles.DayOfMonthToIncurPenalty, 15) = 0 THEN 15 ELSE ISNULL(Cycles.DayOfMonthToIncurPenalty, 15) END) AS VARCHAR(2)) + '/' + CAST(YEAR(@CurrentDate) AS VARCHAR(4))) AS DATETIME) AS PenaltyDate,*/
0 AS PostageRateType,
0 AS TrayNumber
FROM ((Accounts JOIN Cycles ON Accounts.CycleID = Cycles.CycleID) JOIN CustomerTypes ON Accounts.CustomerTypeID = CustomerTypes.CustomerTypeID)
LEFT JOIN RouteComments ON Accounts.Route = RouteComments.Route AND RouteComments.Deleted = 0
WHERE (Accounts.Deleted = 0 OR Accounts.Deleted IS NULL)
AND ((@BillStyle <> 9 /* Not Outsource file */
AND (@PrintOnlyBillsRemovedFromOutsourceBilling <> 1
OR (@PrintOnlyBillsRemovedFromOutsourceBilling = 1 AND Accounts.RemoveAccountFromOutsourceBilling = 1)))
OR (@BillStyle = 9 AND Accounts.RemoveAccountFromOutsourceBilling <> 1))
AND (@IncludeAllAccounts = 1
OR (@IncludeAllAccounts <> 1
AND (Accounts.Route > @BeginningRoute
OR (Accounts.Route = @BeginningRoute
AND (Accounts.AccountNumber > @BeginningAccount
OR (Accounts.AccountNumber = @BeginningAccount
AND Accounts.SequenceNumber >= @BeginningSequence))))
AND (Accounts.Route < @EndingRoute
OR (Accounts.Route = @EndingRoute
AND (Accounts.AccountNumber < @EndingAccount
OR (Accounts.AccountNumber = @EndingAccount
AND Accounts.SequenceNumber <= @EndingSequence))))))
AND (Cycles.Deleted = 0 OR Cycles.Deleted IS NULL)
AND (Cycles.CycleID = @CycleID OR @CycleID = -1) /* SWR UM-1102 allows for all cycles on Print Bill and Zip Code summary. */
/* added this check for bank drafts - vm 10/17/01 */
AND ((Accounts.UseBankDrafts = 0 AND (@IncludeBankDrafts = 1 OR @IncludeBankDrafts = 3) /* 1 = YES; 3 = don't include bank drafts */)
OR (Accounts.UseBankDrafts = 1 AND (@IncludeBankDrafts = 1 OR @IncludeBankDrafts = 5 /* 1 = YES; 5 = bank drafts only */))) /* 3 = don't include bank drafts */
AND (CustomerTypes.Deleted = 0 OR CustomerTypes.Deleted IS NULL)
/* Joining in the Services and Rates is impossible at this point without creating multiple bills for the
accounts. Instead only pull the accounts that either have customer unapplied cash or have valid services
with the following criteria: */
AND (EXISTS (SELECT Services.ServiceID
FROM Services JOIN Rates ON Services.RateID = Rates.RateID
WHERE Services.AccountID = Accounts.AccountID
AND(Services.Deleted = 0 OR Services.Deleted IS NULL)
AND (Services.RemoveService = 0 OR Services.RemoveService IS NULL)
AND Services.AccountStat <> 1 /* 1 = Beginning */
AND Services.AccountStat <> 9 /* 9 = Bad Debt */
AND Services.AccountStat <> 13 /* 13 = Pending */
/* include all status that are not inactive and those inactive services with the ShowArrearsInBillingWhenInactive set to 1 */
AND (Services.AccountStat <> 11
OR (Services.AccountStat = 11 AND Services.ShowArrearsInBillingWhenInactive = 1
/* only inactive services with a balance other than zero in AR or in unapplied cash should be pulled */
AND ((Services.ComputedAmount + Services.BilledArrears +
Services.BudgetBalance + Services.BudgetAmount) <> 0
OR Services.BilledArrears < 0 OR Accounts.RemainingUnappliedCashWhenComputed <> 0
)
)
)
/* this line excludes all compound meters that are not compound primary;
Only the charges for the primary meter need to be pulled; the charges for secondary meters are stored in the Primary meter's charges during the compute process;
the usage for compound meters is calculated later in this procedure at the time a compound primary service is selected from the cursor (usage = sum of usages for the primary and all of its related secondary service(s)). */
AND ((Services.IsCompound = 0 OR Services.IsCompound IS NULL) OR (Services.IsCompound = 1 AND Services.IsCompoundPrimary = 1))
AND (Rates.Deleted = 0 OR Rates.Deleted IS NULL)
)
)
ORDER BY AccountID
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR (' An error occurred while inserting the initial records in #TempPrintEntireBill.',16,1)
RETURN(99)
END
UPDATE #TempPrintEntireBill
SET ZipCodeSummaryFiveDigitZip = SPACE(5 - LEN(LTRIM(RTRIM(ZipCodeSummaryFiveDigitZip)))) + LTRIM(RTRIM(ZipCodeSummaryFiveDigitZip))
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR (' An error occurred while updating the five digit zip code for the zip code summary.',16,1)
RETURN(99)
END
/* Setup the ServiceCursor */
DECLARE ServiceCursor INSENSITIVE CURSOR FOR
SELECT Tmp.AccountID,
(REPLACE(SPACE(4 - LEN(CAST(Tmp.AccountsRoute AS VARCHAR(4)))),' ', '0') + CAST(Tmp.AccountsRoute AS VARCHAR(4))) + '-' +
(REPLACE(SPACE(5 - LEN(CAST(Tmp.AccountsAccountNumber AS VARCHAR(5)))),' ', '0') + CAST(Tmp.AccountsAccountNumber AS VARCHAR(5))) + '-' +
(REPLACE(SPACE(3 - LEN(CAST(Tmp.AccountsSequence AS VARCHAR(3)))),' ', '0') + CAST(Tmp.AccountsSequence AS VARCHAR(3))),
Tmp.UseBankDrafts,
Tmp.RemainingUnappliedCashWhenComputed,
Tmp.CycleStatus,
Services.ServiceID,
ISNULL(Services.DeductFromAccountId,0),
Services.IsMetered,
ISNULL(Meters.MeterNumber, ''),
Services.PresentReadingID,
Services.PreviousReadingID,
Services.IsCompound,
Services.AccountStat,
(CASE /* Status 7 = final; do not include service charges, because they are always considered final (when not inactive) */
WHEN Services.AccountStat = 7 AND ServiceTypes.IsServiceCharge = 0 THEN 1
ELSE 0
END),
Services.ShowArrearsInBillingWhenInactive,
ISNULL(((ISNULL(Services.RefundableDepositAmount,0) + ISNULL(Services.DepositInterestPayable,0)) * -1),0), /* deposits need to be calculated as negative amounts. Once the total bill is calculated they are reset to display as positive on the bill in the final stages of the proc */
ISNULL((CASE Services.IsBudget
WHEN 1 THEN
/* If they are using the expanding budget billing options use
BilledArrears, otherwise use the budgetbalance.*/
(CASE @PrintEndingBalanceForBudgets
WHEN 1 THEN Services.BilledArrears
ELSE Services.BudgetBalance
END)
ELSE Services.BilledArrears
END),0),
Services.NoticesSent,
ISNULL(Services.ComputedAmount,0),
Services.IsBudget,
ISNULL(Services.BudgetAmount,0),
ISNULL(Services.BudgetBalance,0),
ISNULL((Services.CurrentAmount + Services.Amount30Day + Services.Amount60Day + Services.Amount90Day + Services.UnappliedCash + (dbo.fn_getAddonAmountOwed(Services.ServiceID, 9 /* 9 = Penalty */))),0), /* BudgetServiceActualArrears; intialize it to the arrears for the service and Penalty amount only. It will add the other AddOn balances and deposits later. Penalty is included because it is only used as a summarized total for all services later in the Bill */
(CASE WHEN Services.IsBudget = 1 THEN ISNULL(Services.BudgetBalance, 0)
/* if its not a budget account determine the balances to include */
ELSE (CASE WHEN @DelinquentBalancesToInclude = 1 /* 1 = All Charges */ THEN (Services.CurrentAmount + Services.Amount30Day + Services.Amount60Day + Services.Amount90Day)
WHEN @DelinquentBalancesToInclude = 3 /* 3 = All Arrears */ THEN (Services.Amount30Day + Services.Amount60Day + Services.Amount90Day)
WHEN @DelinquentBalancesToInclude = 5 /* 5 = Arrears Older Than One Period */ THEN (Services.Amount60Day + Services.Amount90Day)
WHEN @DelinquentBalancesToInclude = 7 /* 7 = All Arrears Older Than Two Periods */ THEN (Services.Amount90Day)
END)
END) + Services.UnappliedCash, /* DelinquentAmount is needed for the tenant/landlord SendDelinquentBillTo option */
ISNULL(Rates.BillCode, ''),
(CASE
WHEN ISNULL(Rates.ReadingFactor, 0) <= 0 THEN 1
ELSE Rates.ReadingFactor
END), /* The report will multiply by 1 and not zero if no reading factor exists. */
Rates.CalculationMethod,
Rates.ServiceTypeID,
ServiceTypes.ServiceDescription,
ServiceTypes.IsServiceCharge,
ISNULL(ServiceTypes.BalanceForwardArrearsDescription, ''),
Rates.PrintDescriptionOnBill,
Rates.Description
FROM (#TempPrintEntireBill AS Tmp LEFT JOIN (Services LEFT JOIN Meters ON Services.MeterID = Meters.MeterID)
ON Tmp.AccountID = Services.AccountID)
LEFT JOIN (Rates LEFT JOIN ServiceTypes ON Rates.ServiceTypeID = ServiceTypes.ServiceTypeID)
ON Services.RateID = Rates.RateID
WHERE ((Services.Deleted = 0 OR Services.Deleted IS NULL)
AND (Services.RemoveService = 0 OR Services.RemoveService IS NULL)
AND (Services.AccountStat <> 1 OR Services.AccountStat IS NULL) /* 1 = Beginning */
AND (Services.AccountStat <> 9 OR Services.AccountStat IS NULL) /* 9 = Bad Debt */
AND (Services.AccountStat <> 13 OR Services.AccountStat IS NULL) /* 13 = Pending */
/* include all status that are not inactive and those inactive services with the ShowArrearsInBillingWhenInactive set to 1 */
AND (Services.AccountStat IS NULL OR Services.AccountStat <> 11
OR (Services.AccountStat = 11 AND Services.ShowArrearsInBillingWhenInactive = 1
/* only inactive services with a balance other than zero in AR or in unapplied cash should be pulled */
AND ((Services.ComputedAmount + Services.BilledArrears +
Services.BudgetBalance + Services.BudgetAmount) <> 0
OR Services.BilledArrears < 0
))
)
/* this line excludes all compound meters that are not compound primary;
Only the charges for the primary meter need to be pulled; the charges for secondary meters are stored in the Primary meter's charges during the compute process;
the usage for compound meters is calculated later in this procedure at the time a compound primary service is selected from the cursor (usage = sum of usages for the primary and all of its related secondary service(s)). */
AND ((Services.IsCompound = 0 OR Services.IsCompound IS NULL) OR (Services.IsCompound = 1 AND Services.IsCompoundPrimary = 1))
AND (Rates.Deleted = 0 OR Rates.Deleted IS NULL)
)
OR ( Tmp.RemainingUnappliedCashWhenComputed <> 0
AND NOT EXISTS (SELECT ServiceID
FROM Services as sv LEFT JOIN Rates as rt ON sv.RateID = rt.RateID
WHERE Tmp.AccountID = sv.AccountID
AND (sv.Deleted = 0 OR sv.Deleted IS NULL)
AND (sv.RemoveService = 0 OR sv.RemoveService IS NULL)
AND (sv.AccountStat <> 1 OR sv.AccountStat IS NULL) /* 1 = Beginning */
AND (sv.AccountStat <> 9 OR sv.AccountStat IS NULL) /* 9 = Bad Debt */
AND (sv.AccountStat <> 13 OR sv.AccountStat IS NULL) /* 13 = Pending */
/* include all status that are not inactive and those inactive services with the ShowArrearsInBillingWhenInactive set to 1 */
AND (sv.AccountStat IS NULL OR sv.AccountStat <> 11
OR (sv.AccountStat = 11 AND sv.ShowArrearsInBillingWhenInactive = 1
/* only inactive services with a balance other than zero in AR or in unapplied cash should be pulled */
AND ((sv.ComputedAmount + sv.BilledArrears +
sv.BudgetBalance + sv.BudgetAmount) <> 0
OR sv.BilledArrears < 0
))
)
/* this line excludes all compound meters that are not compound primary;
Only the charges for the primary meter need to be pulled; the charges for secondary meters are stored in the Primary meter's charges during the compute process;
the usage for compound meters is calculated later in this procedure at the time a compound primary service is selected from the cursor (usage = sum of usages for the primary and all of its related secondary service(s)). */
AND ((sv.IsCompound = 0 OR sv.IsCompound IS NULL) OR (sv.IsCompound = 1 AND sv.IsCompoundPrimary = 1))
AND (rt.Deleted = 0 OR rt.Deleted IS NULL)
)
)
ORDER BY Tmp.AccountID, Rates.ServiceTypeID, ServiceID
FOR READ ONLY
OPEN ServiceCursor
WHILE 0=0
BEGIN
FETCH NEXT FROM ServiceCursor
INTO @AccountID, @FormattedAccountNumber, @UseBankDrafts, @RemainingUnappliedCashWhenComputed, @CycleStatus, @ServiceID, @DeductFromAccountID,
@ServiceIsMetered, @MeterNumber, @PresentReadingID, @PreviousReadingID, @IsCompound, @ServiceAccountStat,
@IsFinalBill, @ShowArrearsInBillingWhenInactive, @DepositPayable, @ServiceBilledArrears,
@NoticesSent, @ServiceComputedAmount, @ServiceIsBudget, @ServiceBudgetAmount, @ServiceBudgetBalance,
@BudgetServiceActualArrears, @DelinquentAmount, @ServiceBillCode,
@ReadingFactor, @CalculationMethod, @ServiceTypeID, @ServiceTypeDescription, @IsServiceCharge, @ServiceTypeArrearsDescription,
@RatePrintDescription, @RateDescription
IF (@@FETCH_STATUS <> 0) BREAK
SET @HoldServiceRateDescription = @RateDescription
IF @RatePrintDescription = 0 /* 0 = don't print the rate description then */
BEGIN
/* wipe out the rate Description selected */
SET @RateDescription = ''
END
IF @ServiceIsBudget = 1
BEGIN
UPDATE #TempPrintEntireBill
SET UsesBudgets = 1
WHERE AccountID = @AccountID
END
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
RAISERROR (' An error occurred while setting @UsesBudgets.',16,1)
RETURN(99)
END
IF @ServiceIsMetered = 1 /* if its not metered skip there is not point in loading readings */
BEGIN
/* If the service is inactive and they do not want to print readings and usage for inactive
customers set them to NULL to prevent them from printing on the bill. */
IF @PrintReadingAndUsageForInactiveServicesOnBills = 0 AND @ServiceAccountStat = 11
BEGIN
SET @ReadingType = NULL
SET @IsChangeout = NULL
SET @ChangeOutPresentReading = NULL
SET @ChangeOutPreviousReading = NULL
SET @ChangeoutReadingDate = NULL
SET @ChangeOutUsage = NULL
SET @OldMeterID = NULL
SET @PresentReading = NULL
SET @PresentReadingDate = NULL
SET @Usage = NULL
SET @ActualUsage = NULL
SET @ServiceCompoundUsage = NULL
SET @CurrentDays = NULL
SET @LastMonthUsage = NULL
SET @LastMonthDays = NULL
SET @SameMonthLastYearUsage = NULL
SET @SameMonthLastYearDays = NULL
SET @AverageUsage = NULL
SET @DeductionAmount = NULL
SET @DemandUsage = NULL
SET @PreviousReading = NULL
SET @PreviousReadingDate = NULL
SET @ChangeoutPreviousReadingDate = NULL
SET @ChangeoutReadingDate = NULL
END
ELSE
BEGIN
/* Pull all of the relevant Present info from Readings */
SELECT @ReadingType = ISNULL(Readings.ReadingType, 0),
@IsChangeout = ISNULL(Readings.IsChangeout, 0),
@ChangeOutPresentReading = ISNULL(Readings.ChangeOutPresentReading, 0),
@ChangeOutPreviousReading = ISNULL(Readings.ChangeOutPreviousReading, 0),
@ChangeOutUsage = ISNULL(Readings.ChangeoutUsage, 0),
@ChangeoutReadingDate = Readings.ChangeoutDate,
@OldMeterID = Readings.OldMeterId,
@PresentReading = ISNULL(Readings.Reading, 0),
@PresentReadingDate = Readings.ReadingDate,
@Usage = ISNULL(Readings.Usage, 0),
@ActualUsage = ISNULL(Readings.ActualUsage, 0),
@ServiceCompoundUsage = ISNULL(Readings.PrimaryCompoundUsage, 0),
@AverageUsage = ISNULL(Readings.AverageUsage, 0),
@DeductionAmount = ISNULL(Readings.DeductUsage, 0),
@DemandUsage = ISNULL(Readings.DemandUsage, 0)
FROM Readings
WHERE ReadingID = @PresentReadingID
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while finding the Present Reading information for the first Service for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
/* Pull all of the relevant previous reading info from Readings */
SELECT @PreviousReading = ISNULL(Readings.Reading, 0),
@PreviousReadingDate = Readings.ReadingDate,
@LastMonthUsage = (CASE
WHEN @IsCompound = 1 THEN Readings.PrimaryCompoundUsage
ELSE Readings.Usage + Readings.ChangeoutUsage + Readings.DemandUsage - Readings.DeductUsage
END)
FROM Readings
WHERE ReadingID = @PreviousReadingID
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while finding the Previous Reading information for the first Service for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
/* If the override billing period dates option is being used then replace the dates with
the parameters passed to the proc. If its not being used the parameter dates will be null.
Note that the dates are "backwards". The beginning date is actually the previous
period's date. */
IF NOT @EndingBillingPeriodDate IS NULL
BEGIN
SET @PresentReadingDate = @EndingBillingPeriodDate
END
IF NOT @BeginningBillingPeriodDate IS NULL
BEGIN
SET @PreviousReadingDate = @BeginningBillingPeriodDate
END
IF @IsChangeout = 1
BEGIN
/* find the preious meter number */
SET @OldMeterNumber = (SELECT MeterNumber FROM Meters WHERE MeterID = @OldMeterID)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while finding the Previous Meter Number for the Changeout Reading for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
/* Pull the Reading Date from the reading Prior to the previous reading */
SET @ChangeoutPreviousReadingDate = (SELECT TOP 1 Readings.ReadingDate
FROM Readings
WHERE Readings.Deleted = 0
AND Readings.ServiceId = @ServiceId
AND Readings.ReadingDate < @PreviousReadingDate
ORDER BY Readings.ReadingDate DESC)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while finding the Changeout Previous Reading Date for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
IF @PreviousReadingDate IS NULL SET @PreviousReadingDate = 0
IF @LastMonthUsage IS NULL SET @LastMonthUsage = 0
/* Get all of the changeout previous readings for the current service. */
INSERT INTO @ChangeoutPreviousReadings
(PreviousChangeoutReadingId)
SELECT Readings.ReadingId
FROM Readings
WHERE Readings.Deleted = 0
AND Readings.ServiceId = @ServiceId
AND ISNULL((SELECT ISNULL(rd1.IsChangeout, 0)
FROM Readings AS rd1
WHERE rd1.ReadingId = (SELECT MIN(rd2.ReadingId)
FROM Readings AS rd2
WHERE rd2.Deleted = 0
AND rd2.ServiceId = @ServiceId
AND rd2.ReadingId > Readings.ReadingId)), 0) = 1
/* Get the top 14 readings for the service. 1 year + 2 months to calculate the same month last year date period. */
INSERT INTO @ChartOfReadings
(ReadingId,
ReadingDate,
Usage)
SELECT TOP 14
Readings.ReadingId,
ISNULL(Readings.ReadingDate, 0),
(CASE
WHEN @IsCompound = 1 THEN Readings.PrimaryCompoundUsage
ELSE Readings.Usage + Readings.ChangeoutUsage + Readings.DemandUsage - Readings.DeductUsage
END)
FROM Readings
WHERE Readings.Deleted = 0
AND Readings.ServiceId = @ServiceId
AND Readings.ReadingId NOT IN (SELECT PreviousChangeoutReadingId FROM @ChangeoutPreviousReadings)
/*AND Readings.ReadingId < @PreviousReadingId */
ORDER BY Readings.ReadingDate DESC, Readings.ReadingId DESC
/* Set the billing period information. */
SET @HoldPresentReadingDate = @PresentReadingDate
SET @HoldPreviousReadingDate = ISNULL((SELECT MAX(ReadingDate) FROM @ChartOfReadings WHERE ReadingDate = (SELECT MAX(rd.ReadingDate) FROM @ChartOfReadings AS rd WHERE ReadingDate < @HoldPresentReadingDate)), 0)
IF @HoldPresentReadingDate > @HoldPreviousReadingDate SET @CurrentDays = DATEDIFF(DAY, @HoldPreviousReadingDate, @HoldPresentReadingDate)
ELSE SET @CurrentDays = 0
SET @HoldPresentReadingDate = @HoldPreviousReadingDate
SET @HoldPreviousReadingDate = ISNULL((SELECT MAX(ReadingDate) FROM @ChartOfReadings WHERE ReadingDate = (SELECT MAX(rd.ReadingDate) FROM @ChartOfReadings AS rd WHERE ReadingDate < @HoldPresentReadingDate)), 0)
IF @HoldPresentReadingDate > @HoldPreviousReadingDate SET @LastMonthDays = DATEDIFF(DAY, @HoldPreviousReadingDate, @HoldPresentReadingDate)
ELSE SET @LastMonthDays = 0
SET @ReadingCount = ISNULL((SELECT COUNT(*) FROM @ChartOfReadings) ,0)
/* find the usage and length of billing period for the same month last year */
IF @ReadingCount >= 13
BEGIN
SET @HoldPreviousReadingDate = ISNULL((SELECT MIN(ReadingDate) FROM @ChartOfReadings), 0)
SET @HoldPresentReadingDate = ISNULL((SELECT MIN(ReadingDate) FROM @ChartOfReadings WHERE ReadingDate > @HoldPreviousReadingDate), 0)
SET @HoldPresentReadingId = ISNULL((SELECT MIN(ReadingId) FROM @ChartOfReadings WHERE ReadingDate = @HoldPresentReadingDate), 0)
SET @SameMonthLastYearUsage = ISNULL((SELECT Usage
FROM @ChartOfReadings
WHERE ReadingId = (SELECT MIN(rd.ReadingID) FROM @ChartOfReadings AS rd)), 0)
IF @HoldPresentReadingDate > @HoldPreviousReadingDate SET @SameMonthLastYearDays = DATEDIFF(DAY, @HoldPreviousReadingDate, @HoldPresentReadingDate)
ELSE SET @SameMonthLastYearDays = 0
END
ELSE
BEGIN
SET @SameMonthLastYearUsage = 0
SET @SameMonthLastYearDays = 0
END
IF @ForZipCodeSummaryReport = 0 /* skip this section if its for the zip code summary report */
BEGIN
/* If the Billing Options are set to use reading factor multiple all reading related info by the
reading factor once so that repeat multiplication isn't performed. */
IF @UseReadingFactor = 1
BEGIN
SET @PresentReading = (@PresentReading * @ReadingFactor)
SET @PreviousReading = (@PreviousReading * @ReadingFactor)
SET @Usage = (@Usage * @ReadingFactor)
SET @ActualUsage = (@ActualUsage * @ReadingFactor)
SET @ServiceCompoundUsage = (@ServiceCompoundUsage * @ReadingFactor)
SET @ChangeoutPresentReading = (@ChangeoutPresentReading * @ReadingFactor)
SET @ChangeoutPreviousReading = (@ChangeoutPreviousReading * @ReadingFactor)
SET @ChangeoutUsage = (@ChangeoutUsage * @ReadingFactor)
SET @AverageUsage = (@AverageUsage * @ReadingFactor)
SET @DeductionAmount = (@DeductionAmount * @ReadingFactor)
SET @DemandUsage = (@DemandUsage * @ReadingFactor)
SET @LastMonthUsage = (@LastMonthUsage * @ReadingFactor)
SET @SameMonthLastYearUsage = (@SameMonthLastYearUsage * @ReadingFactor)
END
IF @UseEnhancedBill = 1
BEGIN
/* Load the reading dates and usages for the chart. These are pulled from the first metered service
encountered. Multiple metered serves will not be reflected in the chart */
IF @PreviousAccountID <> @AccountID
BEGIN
SET @ChartVariablesLoaded = 0
END
IF @ChartVariablesLoaded = 0
BEGIN
/* initialize the variables */
SET @Index = 13
SET @ChartHighestUsage = 0
/* The cursor contains the 14 readings prior to the previous reading,
but we only want the 13 most recent readings. */
DECLARE EnhancedBillingCursor INSENSITIVE CURSOR FOR
SELECT ReadingDate, Usage FROM @ChartOfReadings
ORDER BY ReadingDate DESC, ReadingID DESC
FOR READ ONLY
OPEN EnhancedBillingCursor
WHILE @Index >= 0
BEGIN
FETCH NEXT FROM EnhancedBillingCursor
INTO @HoldReadingDate, @HoldUsage
IF (@@FETCH_STATUS <> 0) BREAK
IF @UseReadingFactor = 1
BEGIN
SET @HoldUsage = CAST((@HoldUsage * @ReadingFactor) AS DOUBLE PRECISION)
END
/* check for the max usage */
IF @ChartHighestUsage < @HoldUsage
BEGIN
SET @ChartHighestUsage = @HoldUsage
END
IF @Index = 1
BEGIN
SET @ChartReadingDate1 = @HoldReadingDate
SET @ChartUsage1 = @HoldUsage
END
IF @Index = 2
BEGIN
SET @ChartReadingDate2 = @HoldReadingDate
SET @ChartUsage2 = @HoldUsage
END
IF @Index = 3
BEGIN
SET @ChartReadingDate3 = @HoldReadingDate
SET @ChartUsage3 = @HoldUsage
END
IF @Index = 4
BEGIN
SET @ChartReadingDate4 = @HoldReadingDate
SET @ChartUsage4 = @HoldUsage
END
IF @Index = 5
BEGIN
SET @ChartReadingDate5 = @HoldReadingDate
SET @ChartUsage5 = @HoldUsage
END
IF @Index = 6
BEGIN
SET @ChartReadingDate6 = @HoldReadingDate
SET @ChartUsage6 = @HoldUsage
END
IF @Index = 7
BEGIN
SET @ChartReadingDate7 = @HoldReadingDate
SET @ChartUsage7 = @HoldUsage
END
IF @Index = 8
BEGIN
SET @ChartReadingDate8 = @HoldReadingDate
SET @ChartUsage8 = @HoldUsage
END
IF @Index = 9
BEGIN
SET @ChartReadingDate9 = @HoldReadingDate
SET @ChartUsage9 = @HoldUsage
END
IF @Index = 10
BEGIN
SET @ChartReadingDate10 = @HoldReadingDate
SET @ChartUsage10 = @HoldUsage
END
IF @Index = 11
BEGIN
SET @ChartReadingDate11 = @HoldReadingDate
SET @ChartUsage11 = @HoldUsage
END
IF @Index = 12
BEGIN
SET @ChartReadingDate12 = @HoldReadingDate
SET @ChartUsage12 = @HoldUsage
END
IF @Index = 13
BEGIN
SET @ChartReadingDate13 = @HoldReadingDate
SET @ChartUsage13 = @HoldUsage
END
/* increment the counter */
SET @Index = @Index - 1
END
CLOSE EnhancedBillingCursor
DEALLOCATE EnhancedBillingCursor
/* update the bills table with the appropriate chart values */
UPDATE #TempPrintEntireBill
SET ChartReadingDate1 = @ChartReadingDate1,
ChartReadingDate2 = @ChartReadingDate2,
ChartReadingDate3 = @ChartReadingDate3,
ChartReadingDate4 = @ChartReadingDate4,
ChartReadingDate5 = @ChartReadingDate5,
ChartReadingDate6 = @ChartReadingDate6,
ChartReadingDate7 = @ChartReadingDate7,
ChartReadingDate8 = @ChartReadingDate8,
ChartReadingDate9 = @ChartReadingDate9,
ChartReadingDate10 = @ChartReadingDate10,
ChartReadingDate11 = @ChartReadingDate11,
ChartReadingDate12 = @ChartReadingDate12,
ChartReadingDate13 = @ChartReadingDate13,
ChartUsage1 = @ChartUsage1,
ChartUsage2 = @ChartUsage2,
ChartUsage3 = @ChartUsage3,
ChartUsage4 = @ChartUsage4,
ChartUsage5 = @ChartUsage5,
ChartUsage6 = @ChartUsage6,
ChartUsage7 = @ChartUsage7,
ChartUsage8 = @ChartUsage8,
ChartUsage9 = @ChartUsage9,
ChartUsage10 = @ChartUsage10,
ChartUsage11 = @ChartUsage11,
ChartUsage12 = @ChartUsage12,
ChartUsage13 = @ChartUsage13,
CurrentPeriodNumberofDays = @CurrentDays,
PreviousPeriodNumberofDays = @LastMonthDays,
SameMonthLastYearNumberofDays = @SameMonthLastYearDays,
ChartHighestUsage = @ChartHighestUsage
FROM #TempPrintEntireBill AS Tmp
WHERE Tmp.AccountID = @AccountID
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while updating the Enhanced Bill Information for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
SET @ChartVariablesLoaded = 1
END /* IF @ChartVariablesLoaded = 0 */
END /* @UseEnhancedBill = 1 */
END /* goes with IF @ForZipCodeSummaryReport = 0 */
DELETE FROM @ChangeoutPreviousReadings
DELETE FROM @ChartOfReadings
/* If the reading date for the bill card hasn't been updated yet and a reading exists it needs to be adjusted.
The reading dates that prints on the card come from the first metered service encounted. */
IF (@BillStyle = 1 /* 1 = K9306 Card */ OR @BillStyle = 11 /* 11 = K9306 No Margin Card */ OR @BillStyle = 7 /* 7 = Dot Matrix Cards */) AND @PresentReadingDate <> 0 AND @ServiceAccountStat <> 11
BEGIN
UPDATE #TempPrintEntireBill
SET PresentReadingDate = @PresentReadingDate
FROM #TempPrintEntireBill AS Tmp
WHERE Tmp.AccountID = @AccountID
AND Tmp.PresentReadingDate IS NULL
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while updating the Bill''s Present Reading Date for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
IF (@BillStyle = 1 /* 1 = K9306 Card */ OR @BillStyle = 11 /* 11 = K9306 No MarginCard */ OR @BillStyle = 7 /* 7 = Dot Matrix Cards */) AND @PreviousReadingDate <> 0 AND @ServiceAccountStat <> 11
BEGIN
/* update the previous reading date for the bill cards */
UPDATE #TempPrintEntireBill
SET PreviousReadingDate = (CASE @IsChangeout
WHEN 1 THEN @ChangeoutPreviousReadingDate
ELSE @PreviousReadingDate
END)
FROM #TempPrintEntireBill AS Tmp
WHERE Tmp.AccountID = @AccountID AND Tmp.PreviousReadingDate IS NULL
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while updating the Bill''s Previous Reading Date for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
/* Still inside the IF @ServiceIsMetered = 1 */
/* check to see if the reading is estimated */
IF @ReadingType = 5 /* 5 = Estimated */
BEGIN
SET @IsEstimated = 1
SET @FinalOrEstimatedText = 'E'
END
IF @ImpliedDecimalPlaces > 0 AND @CalculationMethod = 9 /* 9 = Power Factor */
BEGIN
/* Set the @DecimalPlacesToUse to the number specified in the Billing Options */
SET @DecimalMultiplier = 1
SET @Count = @ImpliedDecimalPlaces
WHILE @Count > 0
BEGIN
SET @DecimalMultiplier = (@DecimalMultiplier / 10)
SET @Count = @Count - 1
END
IF @DecimalMultiplier < 1
BEGIN
/* Format the decimal place for the Usages and Readings for Power factors */
IF @IsChangeout = 1
BEGIN
SET @ChangeOutPresentReading = @ChangeOutPresentReading * @DecimalMultiplier
SET @ChangeOutPreviousReading = @ChangeOutPreviousReading * @DecimalMultiplier
END
SET @PresentReading = @PresentReading * @DecimalMultiplier
SET @PreviousReading = @PreviousReading * @DecimalMultiplier
SET @Usage = @Usage * @DecimalMultiplier
SET @ActualUsage = @ActualUsage * @DecimalMultiplier
SET @AverageUsage = @AverageUsage * @DecimalMultiplier
SET @DeductionAmount = @DeductionAmount * @DecimalMultiplier
SET @DemandUsage = @DemandUsage * @DecimalMultiplier
END
END
END /* goes with IF @PrintReadingAndUsageForInactiveServicesOnBills = 0 AND @ServiceAccountStat = 11 */
END /* goes with: IF @ServiceIsMetered = 1 */
ELSE
BEGIN
SET @ReadingType = NULL
SET @IsChangeout = NULL
SET @ChangeOutPresentReading = NULL
SET @ChangeOutPreviousReading = NULL
SET @ChangeoutReadingDate = NULL
SET @ChangeOutUsage = NULL
SET @OldMeterID = NULL
SET @PresentReading = NULL
SET @PresentReadingDate = NULL
SET @Usage = NULL
SET @ActualUsage = NULL
SET @ServiceCompoundUsage = NULL
SET @CurrentDays = NULL
SET @LastMonthUsage = NULL
SET @LastMonthDays = NULL
SET @SameMonthLastYearUsage = NULL
SET @SameMonthLastYearDays = NULL
SET @AverageUsage = NULL
SET @DeductionAmount = NULL
SET @DemandUsage = NULL
SET @PreviousReading = NULL
SET @PreviousReadingDate = NULL
SET @ChangeoutPreviousReadingDate = NULL
SET @ChangeoutReadingDate = NULL
END
IF EXISTS(SELECT ServiceID
FROM Services JOIN (Rates JOIN ServiceTypes ON Rates.ServiceTypeId = ServiceTypes.ServiceTypeId) ON Services.RateId = Rates.RateId
WHERE Services.AccountID = @AccountID
AND Services.Deleted = 0
AND Rates.Deleted = 0
AND ServiceTypes.Deleted = 0
AND ((BilledArrears + ComputedAmount + dbo.fn_getAddonComputedAmount(Services.ServiceId, -1)) < 0)
AND ServiceTypes.IsServiceCharge <> 1)
BEGIN
SET @ForcePrintSeperateArrears = 1
SET @NumberOfServices = (SELECT COUNT(ServiceID) FROM Services
WHERE AccountID = @AccountID
AND Deleted = 0
AND (Services.RemoveService = 0 OR Services.RemoveService IS NULL)
AND (Services.AccountStat <> 1 OR Services.AccountStat IS NULL) /* 1 = Beginning */
AND (Services.AccountStat <> 9 OR Services.AccountStat IS NULL) /* 9 = Bad Debt */
AND (Services.AccountStat <> 13 OR Services.AccountStat IS NULL) /* 13 = Pending */
/* include all status that are not inactive and those inactive services with the ShowArrearsInBillingWhenInactive set to 1 */
AND (Services.AccountStat IS NULL OR Services.AccountStat <> 11
OR (Services.AccountStat = 11 AND Services.ShowArrearsInBillingWhenInactive = 1
/* only inactive services with a balance other than zero in AR or in unapplied cash should be pulled */
AND ((Services.ComputedAmount + Services.BilledArrears +
Services.BudgetBalance + Services.BudgetAmount) <> 0
OR Services.BilledArrears < 0
))
)
/* this line excludes all compound meters that are not compound primary;
Only the charges for the primary meter need to be pulled; the charges for secondary meters are stored in the Primary meter's charges during the compute process;
the usage for compound meters is calculated later in this procedure at the time a compound primary service is selected from the cursor (usage = sum of usages for the primary and all of its related secondary service(s)). */
AND ((Services.IsCompound = 0 OR Services.IsCompound IS NULL) OR (Services.IsCompound = 1 AND Services.IsCompoundPrimary = 1))
)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while counting the number of Services for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
ELSE
BEGIN
SET @ForcePrintSeperateArrears = 0
END
/* check for a final bill. */
IF @IsFinalBill = 1 AND @FinalOrEstimatedText = ''
BEGIN
SET @FinalOrEstimatedText = 'F'
END
/* the Surcharge1 Addon Info. */
SET @ServiceComputedSurcharge1 = 0
SET @DelinquentAmountSurcharge1 = 0
SET @Surcharge1RateId = 0
SET @Surcharge1BillCode = ''
SET @Surcharge1RateDescription = ''
SET @Surcharge1PrintDescription = 0
SET @Surcharge1DisplayMethod = 0
SET @Surcharge1CommentsOnBill = ''
SELECT @ServiceComputedSurcharge1 = ISNULL(Addons.ComputedAmount,0),
@DelinquentAmountSurcharge1 = (CASE
WHEN @ServiceIsBudget = 1 THEN 0 /* amount already included in the budgetbalance amount contained in the service's delinquent amount */
/* if its not a budget account determine the balances to include */
ELSE (CASE
WHEN @DelinquentBalancesToInclude = 1 /* 1 = All Charges */ THEN (CurrentAmount + Amount30Day + Amount60Day + Amount90Day)
WHEN @DelinquentBalancesToInclude = 3 /* 3 = All Arrears */ THEN (Amount30Day + Amount60Day + Amount90Day)
WHEN @DelinquentBalancesToInclude = 5 /* 5 = Arrears Older Than One Period */ THEN (Amount60Day + Amount90Day)
WHEN @DelinquentBalancesToInclude = 7 /* 7 = All Arrears Older Than Two Periods */ THEN (Amount90Day)
END)
END),
@BudgetServiceActualArrears = @BudgetServiceActualArrears + ISNULL((Addons.CurrentAmount + Addons.Amount30Day + Addons.Amount60Day + Addons.Amount90Day),0),
@Surcharge1RateID = ISNULL(Addons.AddOnRateID, 0),
@Surcharge1BillCode = ISNULL(AddOnRates.BillCode, ''),
@Surcharge1RateDescription = ISNULL(AddOnRates.Description, ''),
@Surcharge1PrintDescription = ISNULL(AddOnRates.PrintDescriptionOnBill, 0),
@Surcharge1DisplayMethod = ISNULL(AddOnRates.DisplayOnBillMethod, 0),
@Surcharge1CommentsOnBill = ISNULL(AddOnRates.CommentsOnBill, '')
FROM Addons JOIN AddonRates ON Addons.AddOnRateID = AddonRates.AddOnRateID
WHERE Addons.ServiceID = @ServiceID
AND (Addons.Deleted = 0 OR Addons.Deleted IS NULL)
AND ((Addons.IsInactive = 0 OR Addons.IsInactive IS NULL) OR (Addons.IsInactive = 1 AND @ShowArrearsInBillingWhenInactive = 1))
AND Addons.AdType = 1 /* 1 = Surcharge1 */
AND (AddonRates.Deleted = 0 OR AddonRates.Deleted IS NULL)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while finding the Surcharge1 information for a Service for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
/* the Surcharge2 Addon Info. */
SET @ServiceComputedSurcharge2 = 0
SET @DelinquentAmountSurcharge2 = 0
SET @Surcharge2RateId = 0
SET @Surcharge2BillCode = ''
SET @Surcharge2RateDescription = ''
SET @Surcharge2PrintDescription = 0
SET @Surcharge2DisplayMethod = 0
SET @Surcharge2CommentsOnBill = ''
SELECT @ServiceComputedSurcharge2 = ISNULL(Addons.ComputedAmount,0),
@DelinquentAmountSurcharge2 = (CASE
WHEN @ServiceIsBudget = 1 THEN 0 /* amount already included in the budgetbalance amount contained in the service's delinquent amount */
/* if its not a budget account determine the balances to include */
ELSE (CASE
WHEN @DelinquentBalancesToInclude = 1 /* 1 = All Charges */ THEN (CurrentAmount + Amount30Day + Amount60Day + Amount90Day)
WHEN @DelinquentBalancesToInclude = 3 /* 3 = All Arrears */ THEN (Amount30Day + Amount60Day + Amount90Day)
WHEN @DelinquentBalancesToInclude = 5 /* 5 = Arrears Older Than One Period */ THEN (Amount60Day + Amount90Day)
WHEN @DelinquentBalancesToInclude = 7 /* 7 = All Arrears Older Than Two Periods */ THEN (Amount90Day)
END)
END),
@BudgetServiceActualArrears = @BudgetServiceActualArrears + ISNULL((Addons.CurrentAmount + Addons.Amount30Day + Addons.Amount60Day + Addons.Amount90Day),0),
@Surcharge2RateID = ISNULL(Addons.AddOnRateID, 0),
@Surcharge2BillCode = ISNULL(AddOnRates.BillCode, ''),
@Surcharge2RateDescription = ISNULL(AddOnRates.Description, ''),
@Surcharge2PrintDescription = ISNULL(AddOnRates.PrintDescriptionOnBill, 0),
@Surcharge2DisplayMethod = ISNULL(AddOnRates.DisplayOnBillMethod, 0),
@Surcharge2CommentsOnBill = ISNULL(AddOnRates.CommentsOnBill, '')
FROM Addons JOIN AddonRates ON Addons.AddOnRateID = AddonRates.AddOnRateID
WHERE Addons.ServiceID = @ServiceID
AND (Addons.Deleted = 0 OR Addons.Deleted IS NULL)
AND ((Addons.IsInactive = 0 OR Addons.IsInactive IS NULL) OR (Addons.IsInactive = 1 AND @ShowArrearsInBillingWhenInactive = 1))
AND Addons.AdType = 3 /* 3 = Surcharge1 */
AND (AddonRates.Deleted = 0 OR AddonRates.Deleted IS NULL)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while finding the Surcharge2 information for a Service for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
/* the Local Tax Addon Info. */
SET @ServiceComputedLocalTax = 0
SET @DelinquentAmountLocalTax = 0
SET @LocalTaxRateId = 0
SET @LocalTaxBillCode = ''
SET @LocalTaxRateDescription = ''
SET @LocalTaxPrintDescription = 0
SET @LocalTaxDisplayMethod = 0
SET @LocalTaxCommentsOnBill = ''
SELECT @ServiceComputedLocalTax = ISNULL(Addons.ComputedAmount,0),
@DelinquentAmountLocalTax = (CASE
WHEN @ServiceIsBudget = 1 THEN 0 /* amount already included in the budgetbalance amount contained in the service's delinquent amount */
/* if its not a budget account determine the balances to include */
ELSE (CASE
WHEN @DelinquentBalancesToInclude = 1 /* 1 = All Charges */ THEN (CurrentAmount + Amount30Day + Amount60Day + Amount90Day)
WHEN @DelinquentBalancesToInclude = 3 /* 3 = All Arrears */ THEN (Amount30Day + Amount60Day + Amount90Day)
WHEN @DelinquentBalancesToInclude = 5 /* 5 = Arrears Older Than One Period */ THEN (Amount60Day + Amount90Day)
WHEN @DelinquentBalancesToInclude = 7 /* 7 = All Arrears Older Than Two Periods */ THEN (Amount90Day)
END)
END),
@BudgetServiceActualArrears = @BudgetServiceActualArrears + ISNULL((Addons.CurrentAmount + Addons.Amount30Day + Addons.Amount60Day + Addons.Amount90Day),0),
@LocalTaxRateID = ISNULL(Addons.AddOnRateID, 0),
@LocalTaxBillCode = ISNULL(AddOnRates.BillCode, ''),
@LocalTaxRateDescription = ISNULL(AddOnRates.Description, ''),
@LocalTaxPrintDescription = ISNULL(AddOnRates.PrintDescriptionOnBill, 0),
@LocalTaxDisplayMethod = ISNULL(AddOnRates.DisplayOnBillMethod, 0),
@LocalTaxCommentsOnBill = ISNULL(AddOnRates.CommentsOnBill, '')
FROM Addons JOIN AddonRates ON Addons.AddOnRateID = AddonRates.AddOnRateID
WHERE Addons.ServiceID = @ServiceID
AND (Addons.Deleted = 0 OR Addons.Deleted IS NULL)
AND ((Addons.IsInactive = 0 OR Addons.IsInactive IS NULL) OR (Addons.IsInactive = 1 AND @ShowArrearsInBillingWhenInactive = 1))
AND Addons.AdType = 5 /* 5 = Local Tax */
AND (AddonRates.Deleted = 0 OR AddonRates.Deleted IS NULL)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while finding the Local Tax information for a Service for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
/* the State Tax Addon Info. */
SET @ServiceComputedStateTax = 0
SET @DelinquentAmountStateTax = 0
SET @StateTaxRateId = 0
SET @StateTaxBillCode = ''
SET @StateTaxRateDescription = ''
SET @StateTaxPrintDescription = 0
SET @StateTaxDisplayMethod = 0
SET @StateTaxCommentsOnBill = ''
SELECT @ServiceComputedStateTax = ISNULL(Addons.ComputedAmount,0),
@DelinquentAmountStateTax = (CASE
WHEN @ServiceIsBudget = 1 THEN 0 /* amount already included in the budgetbalance amount contained in the service's delinquent amount */
/* if its not a budget account determine the balances to include */
ELSE (CASE
WHEN @DelinquentBalancesToInclude = 1 /* 1 = All Charges */ THEN (CurrentAmount + Amount30Day + Amount60Day + Amount90Day)
WHEN @DelinquentBalancesToInclude = 3 /* 3 = All Arrears */ THEN (Amount30Day + Amount60Day + Amount90Day)
WHEN @DelinquentBalancesToInclude = 5 /* 5 = Arrears Older Than One Period */ THEN (Amount60Day + Amount90Day)
WHEN @DelinquentBalancesToInclude = 7 /* 7 = All Arrears Older Than Two Periods */ THEN (Amount90Day)
END)
END),
@BudgetServiceActualArrears = @BudgetServiceActualArrears + ISNULL((Addons.CurrentAmount + Addons.Amount30Day + Addons.Amount60Day + Addons.Amount90Day),0),
@StateTaxRateID = ISNULL(Addons.AddOnRateID, 0),
@StateTaxBillCode = ISNULL(AddOnRates.BillCode, ''),
@StateTaxRateDescription = ISNULL(AddOnRates.Description, ''),
@StateTaxPrintDescription = ISNULL(AddOnRates.PrintDescriptionOnBill, 0),
@StateTaxDisplayMethod = ISNULL(AddOnRates.DisplayOnBillMethod, 0),
@StateTaxCommentsOnBill = ISNULL(AddOnRates.CommentsOnBill, '')
FROM Addons JOIN AddonRates ON Addons.AddOnRateID = AddonRates.AddOnRateID
WHERE Addons.ServiceID = @ServiceID
AND (Addons.Deleted = 0 OR Addons.Deleted IS NULL)
AND ((Addons.IsInactive = 0 OR Addons.IsInactive IS NULL) OR (Addons.IsInactive = 1 AND @ShowArrearsInBillingWhenInactive = 1))
AND Addons.AdType = 7 /* 7 = State Tax */
AND (AddonRates.Deleted = 0 OR AddonRates.Deleted IS NULL)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while finding the State Tax information for a Service for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
/* the Penalty Addon Info. */
SET @DelinquentAmountPenalty = 0
SELECT @DelinquentAmountPenalty = (CASE
WHEN @ServiceIsBudget = 1 THEN 0 /* amount already included in the budgetbalance amount contained in the service's delinquent amount */
/* if its not a budget account determine the balances to include */
ELSE (CASE
WHEN @DelinquentBalancesToInclude = 1 /* 1 = All Charges */ THEN (CurrentAmount + Amount30Day + Amount60Day + Amount90Day)
WHEN @DelinquentBalancesToInclude = 3 /* 3 = All Arrears */ THEN (Amount30Day + Amount60Day + Amount90Day)
WHEN @DelinquentBalancesToInclude = 5 /* 5 = Arrears Older Than One Period */ THEN (Amount60Day + Amount90Day)
WHEN @DelinquentBalancesToInclude = 7 /* 7 = All Arrears Older Than Two Periods */ THEN (Amount90Day)
END)
END)
FROM Addons JOIN AddonRates ON Addons.AddOnRateID = AddonRates.AddOnRateID
WHERE Addons.ServiceID = @ServiceID
AND (Addons.Deleted = 0 OR Addons.Deleted IS NULL)
AND ((Addons.IsInactive = 0 OR Addons.IsInactive IS NULL) OR (Addons.IsInactive = 1 AND @ShowArrearsInBillingWhenInactive = 1))
AND Addons.AdType = 9 /* 9 = Penalty */
AND (AddonRates.Deleted = 0 OR AddonRates.Deleted IS NULL)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while finding the Penalty information for a Service for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
/* If arrears have to be broken out force the addons to print separately as well.
Otherwide the service unapplied cash cannot be properly distributed. */
IF @ForcePrintSeperateArrears = 1
BEGIN
SET @Surcharge1DisplayMethod = 1
SET @Surcharge2DisplayMethod = 1
SET @LocalTaxDisplayMethod = 1
SET @StateTaxDisplayMethod = 1
END
/* Set the AddAmountToTotals to the opposite of the IsBudgetFlag, its used to determine whether or not
to exclude items from the totals for budget customers. */
IF @ServiceIsBudget = 1
BEGIN
SET @AddAmountToTotals = 0
END
ELSE
BEGIN
/* If the service's total is negative due to service unapplied cash then the arrears and computed
amounts should not be added to the bill's totals. However, there is an exception. Due to
some funky capabilities in DBL, the amount does print in the totals, but only if there is a single
service for the account. SIGH.*/
IF(@ServiceBilledArrears + @ServiceComputedAmount
+ @ServiceComputedSurcharge1 + @ServiceComputedSurcharge2
+ @ServiceComputedLocalTax + @ServiceComputedStateTax) < 0 AND @IsServiceCharge = 0 AND @NumberOfServices <> 1
BEGIN
SET @AddAmountToTotals = 0
END
ELSE
BEGIN
SET @AddAmountToTotals = 1
END
END
IF @PreviousAccountID <> @AccountID
BEGIN
/* The addons amounts are totalled as the cursor loops through the services; IF the combine with like
charges option is set, insert the appropriate Addon lines on the bill */
/* Surcharges */
IF @SurchargeNumberCombined >= 1 AND @CombinedServiceSurchargeAmount <> 0 /* There was at least one surcharge addon that had a rate with CombinedWithLikeCharges */
BEGIN
SET @LineCounter = @LineCounter + 1
SET @HoldRateDescription = LEFT(@FirstSurchargeRateDescription, 20)
IF @FirstSurchargePrintDescription = 0
BEGIN
/* Blank out the Description so that nothing prints on the bill */
SET @FirstSurchargeRateDescription = ''
END
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, BillAmount, AddAmountToTotals)
VALUES (@PreviousAccountID, @PreviousServiceID, @PreviousServiceTypeID, 'Surcharge', @HoldRateDescription, 0, 0, @LineCounter, @FirstSurchargeBillCode, @FirstSurchargeRateDescription, @CombinedServiceSurchargeAmount, 1)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the combined Surcharge amount into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
IF LEN(@Surcharge1CommentsOnBill) > 0 AND @ServiceComputedSurcharge1 <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, AddAmountToTotals)
VALUES (@PreviousAccountID, @PreviousServiceID, @PreviousServiceTypeID, 'Surcharge 1', @HoldRateDescription, 0, 0, @LineCounter, '', @Surcharge1CommentsOnBill, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Surcharge 1 Comments into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
IF LEN(@Surcharge2CommentsOnBill) > 0 AND @ServiceComputedSurcharge2 <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, AddAmountToTotals)
VALUES (@PreviousAccountID, @PreviousServiceID, @PreviousServiceTypeID, 'Surcharge 2', @HoldRateDescription, 0, 0, @LineCounter, '', @Surcharge2CommentsOnBill, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Surcharge 2 Comments into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
END
END
END /* goes with: IF @SurchargeNumberCombined > 1 */
/* Local Tax */
IF @LocalTaxNumberCombined >= 1 AND @CombinedServiceLocalTaxAmount <> 0 /* There is at least one addon of this type to print */
BEGIN
SET @LineCounter = @LineCounter + 1
SET @HoldRateDescription = LEFT(@FirstLocalTaxRateDescription, 20)
IF @FirstLocalTaxPrintDescription = 0
BEGIN
/* Blank out the Description so that nothing prints on the bill */
SET @FirstLocalTaxRateDescription = ''
END
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, BillAmount, AddAmountToTotals)
VALUES (@PreviousAccountID, @PreviousServiceID, @PreviousServiceTypeID, 'Local Tax', @HoldRateDescription, 0, 0, @LineCounter, @FirstLocalTaxBillCode, @FirstLocalTaxRateDescription, @CombinedServiceLocalTaxAmount, 1)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the combined Local Tax amounts into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
END
IF LEN(@LocalTaxCommentsOnBill) > 0 AND @ServiceComputedLocalTax <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, AddAmountToTotals)
VALUES (@PreviousAccountID, @PreviousServiceID, @PreviousServiceTypeID, 'Local Tax', @HoldRateDescription, 0, 0, @LineCounter, '', @LocalTaxCommentsOnBill, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Local Tax Comments into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
END /* goes with: IF @LocalTaxNumberCombined > 1 */
/* StateTax */
IF @StateTaxNumberCombined >= 1 AND @CombinedServiceStateTaxAmount <> 0 /* There is at least one addon of this type to print */
BEGIN
SET @LineCounter = @LineCounter + 1
SET @HoldRateDescription = LEFT(@FirstStateTaxRateDescription, 20)
IF @FirstStateTaxPrintDescription = 0
BEGIN
/* Blank out the Description so that nothing prints on the bill */
SET @FirstStateTaxRateDescription = ''
END
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, BillAmount, AddAmountToTotals)
VALUES (@PreviousAccountID, @PreviousServiceID, @PreviousServiceTypeID, 'State Tax', @HoldRateDescription, 0, 0, @LineCounter, @FirstStateTaxBillCode, @FirstStateTaxRateDescription, @CombinedServiceStateTaxAmount, 1)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the combined State Tax amounts into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
END
IF LEN(@StateTaxCommentsOnBill) > 0 AND @ServiceComputedStateTax <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, AddAmountToTotals)
VALUES (@PreviousAccountID, @PreviousServiceID, @PreviousServiceTypeID, 'State Tax', @HoldRateDescription, 0, 0, @LineCounter, '', @StateTaxCommentsOnBill, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the State Tax Comments into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
END
END
END /* goes with: IF @StateTaxNumberCombined > 1 */
/* The combine charges should be the last section of the Service Details to print */
/* Reset the LineCounter */
SET @LineCounter = 0
/* clear the FirstRateIDs and the other related fields for the new account */
SET @FirstSurchargeRateID = 0
SET @FirstLocalTaxRateID = 0
SET @FirstStateTaxRateID = 0
SET @FirstSurchargeBillCode = ''
SET @FirstLocalTaxBillCode = ''
SET @FirstStateTaxBillCode = ''
SET @FirstSurchargeRateDescription = ''
SET @FirstLocalTaxRateDescription = ''
SET @FirstStateTaxRateDescription = ''
SET @FirstSurchargePrintDescription = 0
SET @FirstLocalTaxPrintDescription = 0
SET @FirstStateTaxPrintDescription = 0
SET @CombinedServiceSurchargeAmount = 0
SET @CombinedServiceLocalTaxAmount = 0
SET @CombinedServiceStateTaxAmount = 0
SET @SurchargeNumberCombined = 0
SET @LocalTaxNumberCombined = 0
SET @StateTaxNumberCombined = 0
/* The last lines for the previous account have been entered and a new account's records are starting,
reset the LineCounter */
SET @LineCounter = 0
/* Its a "new" accountID; get the total Arrears for the Account */
SET @AccountTotalArrears = (@RemainingUnappliedCashWhenComputed /* +
Changed to be a single line item and not in the overall arrears per 7.0 TN#189
the Budget Balance Arrears
ISNULL((SELECT SUM(ISNULL(Services.BudgetBalance,0))
FROM Services
WHERE Services.AccountID = @AccountID
AND (Services.Deleted = 0 OR Services.Deleted IS NULL)
AND (Services.RemoveService = 0 OR Services.RemoveService IS NULL)
AND Services.AccountStat <> 1 / 1 = Beginning /
AND Services.AccountStat <> 9 / 9 = Bad Debt /
AND Services.AccountStat <> 13 / 13 = Pending /
AND (Services.AccountStat <> 11 / 11 = inactive /
OR (Services.AccountStat = 11 AND Services.ShowArrearsInBillingWhenInactive = 1))
AND ((Services.IsCompound = 0 OR Services.IsCompound IS NULL)
OR (Services.IsCompound = 1 AND Services.IsCompoundPrimary = 1))
AND Services.IsBudget = 1
AND @TrackBudgetArrears = 1
),0) */
/* the nonbudget billed Service Arrears */
+ ISNULL((SELECT SUM(ISNULL(Services.BilledArrears,0))
FROM Services
WHERE Services.AccountID = @AccountID
AND (Services.Deleted = 0 OR Services.Deleted IS NULL)
AND (Services.RemoveService = 0 OR Services.RemoveService IS NULL)
AND Services.AccountStat <> 1 /* 1 = Beginning */
AND Services.AccountStat <> 9 /* 9 = Bad Debt */
AND Services.AccountStat <> 13 /* 13 = Pending */
AND (Services.AccountStat <> 11 /* 11 = inactive */
OR (Services.AccountStat = 11 AND Services.ShowArrearsInBillingWhenInactive = 1))
AND ((Services.IsCompound = 0 OR Services.IsCompound IS NULL) OR (Services.IsCompound = 1 AND Services.IsCompoundPrimary = 1))
AND (Services.IsBudget = 0 OR Services.IsBudget IS NULL)),0))
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while calculating the total arrears for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
/* moved to the ELSE section of the check for @PrintSeperateArrears = 1 below - Commented out 4/17/02 JFK
IF @AccountTotalArrears <> 0 AND @LineCounter = 0 / the Account has some form of arrears and it is the first line of the bill; The @LineCounter check shouldn't be necessary since this loop is only entered if its a new account, but its a double check /
BEGIN
IF @PrintSeperateArrears = 0 / Unapplied cash is now automatically stored as negative, no need for a seperate section to flip the sign /
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, IsArrears, LineNumber, BillCode, TextLine, BillAmount)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 1, @LineCounter, @ArrearsBillCode, @ArrearsName, @AccountTotalArrears)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
RAISERROR ('An error occurred while inserting the Total Account Arrears into the #TempPrintBillServiceDetails.',16,1)
RETURN(99)
END
END
Commented out 4/17/02 JFK Unapplied cash is automatically stored as negative
ELSE / @PrintSeperateArrears = 1 /
BEGIN
/ Print the Customer Unapplied Cash as negative /
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, IsArrears, LineNumber, BillCode, TextLine, BillAmount)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 1, @LineCounter, @ArrearsBillCode, @ArrearsName, (@RemainingUnappliedCashWhenComputed * -1))
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
RAISERROR ('An error occurred while inserting the Customer Unapplied Cash into the #TempPrintBillServiceDetails.',16,1)
RETURN(99)
END
END / goes with: IF @PrintSeperateArrears = 0 /
END / goes with: IF @AccountTotalArrears <> 0 AND @LineCounter = 0 / */
END /* goes with: @PreviousAccountID <> @AccountID */
IF (@PrintSeperateArrears = 1 OR @ForcePrintSeperateArrears = 1) AND @RemainingUnappliedCashWhenComputed <> 0
BEGIN
/* If its the first line of the bill the customer unapplied cash needs to print. */
IF @LineCounter = 0 AND @RemainingUnappliedCashWhenComputed <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, BillAmount, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, -1, -1, @ArrearsName, 0, 0, @LineCounter, @ArrearsBillCode, @ArrearsName, @RemainingUnappliedCashWhenComputed, @IsFinalBill, 1)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Customer Unapplied Cash into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
END
/* If they are using the "Print ending balance for budget customers" Option change the wording on the
balance forward record to to say "Beginning Balance". This feature was added to compensate for a
Paris Gas custom print bill in DBL. */
IF @PrintEndingBalanceForBudgets = 1 AND @ServiceIsBudget = 1
BEGIN
SET @LineCounter = @LineCounter + 1
SET @BillCode = @ServiceBillCode + @FinalOrEstimatedText
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, BillAmount, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Beginning Balance', 0, 0, @LineCounter, @BillCode, 'Beginning Balance', @BudgetServiceActualArrears, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Individual Service Arrears (Beginning Balance) into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
SET @BillCode = ''
END
IF @AccountTotalArrears <> 0 OR @RemainingUnappliedCashWhenComputed <> 0 OR (@ServiceIsBudget = 0 AND @ServiceBilledArrears <> 0)
BEGIN
IF @PrintSeperateArrears = 1 OR @ForcePrintSeperateArrears = 1
BEGIN
/* print the individual arrears for the arrears for the current service from the cursor */
IF @ServiceIsBudget = 0 AND @ServiceBilledArrears <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
IF @ServiceTypeArrearsDescription = ''
BEGIN
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, BillAmount, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, @ServiceBillCode, 0, 1, @LineCounter, @ArrearsBillCode, @ServiceBillCode, @ServiceBilledArrears, @IsFinalBill, (CASE WHEN (@ForcePrintSeperateArrears = 1 AND @AddAmountToTotals = 0 AND @ServiceIsBudget = 0 /* YUCK */) THEN 0 ELSE 1 END))
END
ELSE
BEGIN
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, BillAmount, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, @ServiceTypeArrearsDescription, 0, 1, @LineCounter, @ArrearsBillCode, @ServiceTypeArrearsDescription, @ServiceBilledArrears, @IsFinalBill, (CASE WHEN (@ForcePrintSeperateArrears = 1 AND @AddAmountToTotals = 0 AND @ServiceIsBudget = 0 /* YUCK */) THEN 0 ELSE 1 END))
END
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Individual Service Arrears into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
END
ELSE /* goes with: IF @PrintSeperateArrears = 1 OR @ForcePrintSeperateArrears = 1 */
BEGIN
IF @LineCounter = 0 AND @AccountTotalArrears <> 0 /* the Account has some form of arrears and it is the first line of the bill; The @LineCounter check is necessary to determine if its a new account; the arrears is the first line to print on the bill */
BEGIN
SET @LineCounter = @LineCounter + 1
IF @ServiceTypeArrearsDescription = ''
BEGIN
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, BillAmount, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, @ArrearsName, 0, 1, @LineCounter, @ArrearsBillCode, @ArrearsName, @AccountTotalArrears, @IsFinalBill, 1)
END
ELSE
BEGIN
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, BillAmount, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, @ServiceTypeArrearsDescription, 0, 1, @LineCounter, @ArrearsBillCode, @ServiceTypeArrearsDescription, @AccountTotalArrears, @IsFinalBill, 1)
END
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Total Account Arrears into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
END /* goes with: IF @PrintSeperateArrears = 1 OR @ForcePrintSeperateArrears = 1 */
END /* goes with: IF @AccountTotalArrears <> 0 OR @RemainingUnappliedCashWhenComputed <> 0 OR (@ServiceIsBudget = 0 AND @ServiceBilledArrears <> 0) */
/* If its a final bill check for a deposit amount to print on the bill */
IF @IsFinalBill = 1
BEGIN
/* Applies Deposit Amounts if necessary */
IF @DepositPayable <> 0 AND @ApplyDepositOnFinals = 1
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, BillAmount, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Applied Deposit', 0, 0, @LineCounter, 'DP','Applied Deposit',@DepositPayable, @IsFinalBill, 1)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Applied Deposit into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
END
END /* goes with: IF @DepositPayable <> 0 AND @ApplyDepositOnFinals = 1 */
END /* goes with: IF @ServiceAccountStat = 7 */
SET @ServiceComputedTotal = ISNULL(@ServiceComputedAmount, 0)
/* The average usage, meter changeout, and demand meter lines were being inserted here.
They were moved so that they are inserted below the service line, where deduct usage is inserted. */
IF @Surcharge1DisplayMethod = 5 /* CombinedWithServiceCharge=5 */
BEGIN
SET @ServiceComputedTotal = @ServiceComputedTotal + ISNULL(@ServiceComputedSurcharge1, 0)
END
IF @Surcharge2DisplayMethod = 5 /* CombinedWithServiceCharge=5 */
BEGIN
SET @ServiceComputedTotal = @ServiceComputedTotal + ISNULL(@ServiceComputedSurcharge2, 0)
END
IF @LocalTaxDisplayMethod = 5 /* CombinedWithServiceCharge=5 */
BEGIN
SET @ServiceComputedTotal = @ServiceComputedTotal + ISNULL(@ServiceComputedLocalTax, 0)
END
IF @StateTaxDisplayMethod = 5 /* CombinedWithServiceCharge=5 */
BEGIN
SET @ServiceComputedTotal = @ServiceComputedTotal + ISNULL(@ServiceComputedStateTax, 0)
END
IF @ServiceIsBudget = 1
BEGIN
/* IF @CycleStatus <> 7 / 7 = Posted /
BEGIN
SET @BudgetServiceActualArrears = (@BudgetServiceActualArrears + @ServiceComputedTotal
+ (dbo.fn_getAddOnComputedAmount(@ServiceID, 9 / 9 = Penalty /))) / the computed penalty amounts aren't pulled anywhere else (except the final total as a summary section) get it from the function / */
IF @PrintAddOnsSeparatelyForBudgetCustomers = 1
BEGIN
SET @BudgetServiceActualArrears = @BudgetServiceActualArrears + @ServiceComputedTotal
END
ELSE
BEGIN
SET @BudgetServiceActualArrears = @BudgetServiceActualArrears + @ServiceComputedTotal
/*VM Took this part out because on a budget person that is NOT printing adds ons separately, the line that prints for
the svc with the usages, etc. includes the taxes in the amt it prints. The 'ending balance' line adds the taxes
in again before printing 'causing it to be incorrect.*/
/*+ ISNULL(@ServiceComputedSurcharge1, 0) + ISNULL(@ServiceComputedSurcharge2, 0)
+ ISNULL(@ServiceComputedLocalTax, 0) + ISNULL(@ServiceComputedStateTax, 0)*/
END
/* END */
IF @ServiceAccountStat = 11 /* 11 = Inactive */ AND (@BudgetServiceActualArrears) < @ServiceBudgetAmount /* if the total amount owed for the Service is less than the normal budget payment */
BEGIN
/* If the service is budgeted and is inactive the budget amount cannot exceed to total owed
for the account. (i.e. An account is budgeted for $50 a month and has paid off all but the
last $27 owed. The customer is only billed the remaining $27 on his account, not the full
$50 they would normally be budgeted.) Insert the Actual AR amounts rather than the budget
amount; leave the Actual Service balance line off since it would be a duplicate */
SET @LineCounter = @LineCounter + 1
SET @BillCode = @ServiceBillCode + @FinalOrEstimatedText
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, MeterNumber, PresentReadingDate, PreviousReadingDate, PresentReading, PreviousReading, Usage, CurrentDays, LastMonthUsage, LastMonthDays, SameMonthLastYearUsage, SameMonthLastYearDays, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, @ServiceTypeDescription, @HoldServiceRateDescription, 1, 0, @LineCounter, @BudgetServiceActualArrears, @BillCode, @RateDescription, @MeterNumber, @PresentReadingDate, @PreviousReadingDate, @PresentReading, @PreviousReading, @Usage, @CurrentDays, @LastMonthUsage, @LastMonthDays, @SameMonthLastYearUsage, @SameMonthLastYearDays, @IsEstimated, @IsFinalBill, 1)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Budget Billed Account Arrears into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
SET @BillCode = ''
END /* goes with: IF @ServiceAccountStat = 11 AND (@ServiceComputedTotal + @ServiceTotalArrears) < @ServiceBudgetAmount */
ELSE /* @ServiceAccountStat <> 11 OR (@ServiceAccountStat= 11 AND (@ServiceComputedTotal + @ServiceTotalArrears) > @ServiceBudgetAmount */
BEGIN
SET @BillCode = @ServiceBillCode + @FinalOrEstimatedText
/* invalid intrepretation originally. The Budget Arrears amount will print when the normal arrears print. There is no point in inserting another line. - JFK 06/19/02
IF @ServiceBudgetBalance > 0 AND @TrackBudgetArrears = 1 AND @PrintSeperateArrears = 0
BEGIN
/ Display the the Budget Billed Arrears if @TrackBudgetArrears = 1 regardless of the Print Seperate Arrears option (@PrintSeperateArrears = 0);
the budgeted arrears will already be entered in the #TempPrintBillServiceDetails in an above section if @PrintSeperateArrears = 1 /
SET @LineCounter = @LineCounter + 1
SET @BillCode = @ServiceBillCode + @FinalOrEstimatedText
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, IsArrears, LineNumber, BillAmount, BillCode, TextLine, MeterNumber, PresentReadingDate, PreviousReadingDate, PresentReading, PreviousReading, Usage, HasEstimatedReadings, HasFinalBill)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 0, @LineCounter, @ServiceBudgetBalance, @BillCode, @RateDescription, @MeterNumber, @PresentReadingDate, @PreviousReadingDate, @PresentReading, @PreviousReading, @Usage, @IsEstimated, @IsFinalBill)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
RAISERROR ('An error occurred while inserting the Budget Arrears for a Budget Billed Service into the #TempPrintBillServiceDetails.',16,1)
RETURN(99)
END
END / goes with: IF @ServiceBudgetBalance > 0 AND @TrackBudgetArrears = 1 AND @PrintSeperateArrears = 0 /
*/
/* Insert the Budget billed amount */
IF @PrintEndingBalanceForBudgets = 1
BEGIN
/* Insert the Actual AR amounts for the budgeted service */
SET @LineCounter = @LineCounter + 1
IF @PrintAddOnsSeparatelyForBudgetCustomers <> 1
BEGIN
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, MeterNumber, PresentReadingDate, PreviousReadingDate, PresentReading, PreviousReading, Usage, CurrentDays, LastMonthUsage, LastMonthDays, SameMonthLastYearUsage, SameMonthLastYearDays, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, @ServiceTypeDescription, @HoldServiceRateDescription, 1, 0, @LineCounter, (@ServiceComputedTotal + ISNULL(@ServiceComputedSurcharge1, 0) + ISNULL(@ServiceComputedSurcharge2, 0) + ISNULL(@ServiceComputedLocalTax, 0) + ISNULL(@ServiceComputedStateTax, 0)), @BillCode, @RateDescription, @MeterNumber, @PresentReadingDate, @PreviousReadingDate, @PresentReading, @PreviousReading, @Usage, @CurrentDays, @LastMonthUsage, @LastMonthDays, @SameMonthLastYearUsage, @SameMonthLastYearDays, @IsEstimated, @IsFinalBill, @AddAmountToTotals)
END
ELSE
BEGIN
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, MeterNumber, PresentReadingDate, PreviousReadingDate, PresentReading, PreviousReading, Usage, CurrentDays, LastMonthUsage, LastMonthDays, SameMonthLastYearUsage, SameMonthLastYearDays, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, @ServiceTypeDescription, @HoldServiceRateDescription, 1, 0, @LineCounter, @ServiceComputedTotal, @BillCode, @RateDescription, @MeterNumber, @PresentReadingDate, @PreviousReadingDate, @PresentReading, @PreviousReading, @Usage, @CurrentDays, @LastMonthUsage, @LastMonthDays, @SameMonthLastYearUsage, @SameMonthLastYearDays, @IsEstimated, @IsFinalBill, @AddAmountToTotals)
END
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Actual Charges, Readings & Usage for a Budget Billed Service into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
/* The remaining budget related lines will print after the addon lines are calculated and inserted. */
SET @BillCode = ''
END
ELSE /* use standard budget bill formatting */
BEGIN
/* insert the budget payment Amount */
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, MeterNumber, PresentReadingDate, PreviousReadingDate, PresentReading, PreviousReading, Usage, CurrentDays, LastMonthUsage, LastMonthDays, SameMonthLastYearUsage, SameMonthLastYearDays, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, @ServiceTypeDescription, @HoldServiceRateDescription, 1, 0, @LineCounter, @ServiceBudgetAmount, @BillCode, @RateDescription, @MeterNumber, @PresentReadingDate, @PreviousReadingDate, @PresentReading, @PreviousReading, @Usage, @CurrentDays, @LastMonthUsage, @LastMonthDays, @SameMonthLastYearUsage, @SameMonthLastYearDays, @IsEstimated, @IsFinalBill, 1)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Budget Billed Amount into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
SET @BillCode = ''
/* Insert the Actual AR amounts */
SET @LineCounter = @LineCounter + 1
/* Amount calculated above already.
IF @PrintAddOnsSeparatelyForBudgetCustomers <> 1
BEGIN
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Actual Svc Balance', 0, 0, @LineCounter, (@ServiceComputedTotal + ISNULL(@ServiceComputedSurcharge1, 0) + ISNULL(@ServiceComputedSurcharge2, 0) + ISNULL(@ServiceComputedLocalTax, 0) + ISNULL(@ServiceComputedStateTax, 0)), '', 'Actual Service Balance', @IsEstimated, @IsFinalBill, @AddAmountToTotals)
END
ELSE
BEGIN
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Actual Svc Balance', 0, 0, @LineCounter, @BudgetServiceActualArrears , '', 'Actual Service Balance', @IsEstimated, @IsFinalBill, @AddAmountToTotals)
END
*/
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Actual Svc Balance', 0, 0, @LineCounter, @BudgetServiceActualArrears , '', 'Actual Service Balance', @IsEstimated, @IsFinalBill, @AddAmountToTotals)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Actual Usage for a Budget Billed Service into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END /* goes with: IF @PrintEndingBalanceForBudgets = 1 */
END /* goes with: IF @ServiceAccountStat = 11 AND (@ServiceComputedTotal + @ServiceTotalArrears) < @ServiceBudgetAmount */
END
ELSE /* goes with: IF @ServiceIsBudget = 1 */
BEGIN
IF @IsCompound = 1 /* All of the select statements need to be for services of the same ServiceType not the Rate */
BEGIN
/* check to see if any of the services have an estimated reading */
(SELECT @IsEstimated = COUNT(Readings.ReadingID)
FROM (Services LEFT JOIN Readings ON Services.PresentReadingID = Readings.ReadingID) JOIN Rates ON Services.RateID = Rates.RateID
WHERE Services.AccountID = @AccountID
AND Services.IsCompound = 1
AND (Readings.Deleted = 0 OR Readings.Deleted IS NULL)
AND Readings.ReadingType = 5 /* 5 = Estimated */
AND Rates.ServiceTypeID = @ServiceTypeID)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while checking for estimated readings for services using a compound meter for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
IF @IsEstimated > 0
BEGIN
SET @FinalOrEstimatedText = 'E'
SET @IsEstimated = 1
END
SET @IncludesMultipleMeters = 1 /* Automatic for Compound meters */
IF @PrintCompoundReadingsOnBills = 1
BEGIN
/* insert the Compound Meter line */
SET @LineCounter = @LineCounter + 1
SET @BillCode = @ServiceBillCode + @FinalOrEstimatedText
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, MeterNumber, PresentReadingDate, PreviousReadingDate, PresentReading, PreviousReading, Usage, CurrentDays, LastMonthUsage, LastMonthDays, SameMonthLastYearUsage, SameMonthLastYearDays, HasEstimatedReadings, HasFinalBill, IncludesMultipleMeters, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, @ServiceTypeDescription, @HoldServiceRateDescription, 1, 0, @LineCounter, @ServiceComputedTotal, @BillCode, @MeterNumber, @PresentReadingDate, @PreviousReadingDate, @PresentReading, @PreviousReading, @Usage, @CurrentDays, @LastMonthUsage, @LastMonthDays, @SameMonthLastYearUsage, @SameMonthLastYearDays, @IsEstimated, @IsFinalBill, @IncludesMultipleMeters, @AddAmountToTotals)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Compound Meters Totals into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
/* insert the secondary Compound Meter readings */
DECLARE CompoundCursor INSENSITIVE CURSOR FOR
SELECT Services.ServiceID,
Meters.MeterNumber,
PresentReadings.Usage,
PresentReadings.Reading,
PreviousReadings.Reading,
PresentReadings.ReadingDate,
PreviousReadings.ReadingDate,
(CASE PresentReadings.ReadingType
WHEN 5 THEN 1 /* 5 = Estimated */
ELSE 0
END) IsEstimated
FROM ((Services LEFT JOIN Meters ON Services.MeterID = Meters.MeterID)
LEFT JOIN Readings AS PresentReadings ON Services.PresentReadingID = PresentReadings.ReadingID)
LEFT JOIN Readings AS PreviousReadings ON Services.PreviousReadingID = PreviousReadings.ReadingID
WHERE Services.AccountID = @AccountID
AND Services.IsCompound = 1
AND Services.IsCompoundPrimary = 0
FOR READ ONLY
OPEN CompoundCursor
WHILE 0=0
BEGIN
FETCH NEXT FROM CompoundCursor
INTO @CompoundServiceID, @CompoundMeterNumber, @CompoundUsage, @CompoundPresentReading, @CompoundPreviousReading,
@CompoundPresentReadingDate, @CompoundPreviousReadingDate, @CompoundIsEstimated
IF @@FETCH_STATUS <> 0 BREAK
SET @LineCounter = @LineCounter + 1
SET @BillCode = @ServiceBillCode + (CASE @CompoundIsEstimated
WHEN 1 THEN 'E' /* 5 = Estimated */
ELSE ''
END)
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, MeterNumber, PresentReadingDate, PreviousReadingDate, PresentReading, PreviousReading, Usage, HasEstimatedReadings, HasFinalBill, IncludesMultipleMeters, AddAmountToTotals)
VALUES (@AccountID, @CompoundServiceID, @ServiceTypeID, @ServiceTypeDescription, @HoldServiceRateDescription, 1, 0, @LineCounter, NULL, @BillCode, @CompoundMeterNumber, @CompoundPresentReadingDate, @CompoundPreviousReadingDate, @CompoundPresentReading, @CompoundPreviousReading, @CompoundUsage, @CompoundIsEstimated, @IsFinalBill, @IncludesMultipleMeters, 0)
IF @@ERROR <> 0
BEGIN
CLOSE CompoundCursor
DEALLOCATE CompoundCursor
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Compound Meters Totals into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
CLOSE CompoundCursor
DEALLOCATE CompoundCursor
END
ELSE
BEGIN
/* insert the Compound Meter line */
SET @LineCounter = @LineCounter + 1
SET @BillCode = @ServiceBillCode + @FinalOrEstimatedText
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, MeterNumber, PresentReadingDate, PreviousReadingDate, PresentReading, PreviousReading, Usage, CurrentDays, LastMonthUsage, LastMonthDays, SameMonthLastYearUsage, SameMonthLastYearDays, HasEstimatedReadings, HasFinalBill, IncludesMultipleMeters, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, @ServiceTypeDescription, @HoldServiceRateDescription, 1, 0, @LineCounter, @ServiceComputedTotal, @BillCode, @MeterNumber, @PresentReadingDate, @PreviousReadingDate, @PresentReading, @PreviousReading, @ServiceCompoundUsage, @CurrentDays, @LastMonthUsage, @LastMonthDays, @SameMonthLastYearUsage, @SameMonthLastYearDays, @IsEstimated, @IsFinalBill, @IncludesMultipleMeters, @AddAmountToTotals)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Compound Meters Totals line into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
SET @BillCode = ''
END
ELSE /* IF @IsCompound = 0 */
BEGIN
/* THIS IS ONE OF THE ONLY "NORMAL" LINES ON THE ENTIRE BILL. */
SET @BillCode = @ServiceBillCode + @FinalOrEstimatedText
/* added this (OR (@PrintZeroCredit IN(1,3) AND @IsFinalBill = 1)as part of the following IF statement because zero bal bills were not getting
flagged when final and printing FINAL on the stub. They also were not printing the Service
with a zero amount. See CRM SPR275*/
IF ((@ServiceIsMetered = 0 AND @ServiceComputedTotal <> 0) OR (@ServiceIsMetered = 1 AND (@ServiceComputedTotal <> 0 OR @Usage <> 0))) OR (@PrintZeroCredit IN(1,3) AND @IsFinalBill = 1) /* Added 03/28/03 JFK to match DBL See Testing Notes #171 */
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, MeterNumber, PresentReadingDate, PreviousReadingDate, PresentReading, PreviousReading, Usage, CurrentDays, LastMonthUsage, LastMonthDays, SameMonthLastYearUsage, SameMonthLastYearDays, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, @ServiceTypeDescription, @HoldServiceRateDescription, 1, 0, @LineCounter, @ServiceComputedTotal, @BillCode, @RateDescription, @MeterNumber, @PresentReadingDate, @PreviousReadingDate, @PresentReading, @PreviousReading, @Usage, @CurrentDays, @LastMonthUsage, @LastMonthDays, @SameMonthLastYearUsage, @SameMonthLastYearDays, @IsEstimated, @IsFinalBill, @AddAmountToTotals)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Service Readings and Charges into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
SET @BillCode = ''
END /* goes with: IF @IsCompound = 1 */
END /* goes with: IF @ServiceIsBudget = 1 */
IF @PrintActualUsageOnBills = 1 AND @ServiceIsMetered = 1
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, TextLine, BillCode, BillAmount, Usage, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Actual Usage', 0, 0, @LineCounter, 'Actual Usage', @ServiceBillCode, NULL, @ActualUsage, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the actual usage into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
IF @PrintAverageUsage = 1 AND @ServiceIsMetered = 1
AND ((@ServiceIsMetered = 0 AND @ServiceComputedTotal <> 0) OR (@ServiceIsMetered = 1 AND (@ServiceComputedTotal <> 0 OR @Usage <> 0))) AND @ServiceIsBudget <> 1 /* Added 03/28/03 JFK to match DBL See Testing Notes #171 */
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, TextLine, BillCode, BillAmount, Usage, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Average Usage', 0, 0, @LineCounter, 'Average Usage', @ServiceBillCode, NULL, @AverageUsage, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the average usage into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END /* goes with: IF @PrintAverageUsage = 1 AND @ServiceIsMetered = 1 */
IF @IsChangeout = 1
AND ((@ServiceIsMetered = 0 AND @ServiceComputedTotal <> 0) OR (@ServiceIsMetered = 1 AND (@ServiceComputedTotal <> 0 OR @Usage <> 0))) /* TN#281 AND @ServiceIsBudget <> 1 */ /* Added 03/28/03 JFK to match DBL See Testing Notes #171 */
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, TextLine, BillDescription, BillCode, IsForMeteredService, IsArrears, LineNumber, BillAmount, MeterNumber, PresentReadingDate, PreviousReadingDate, PresentReading, PreviousReading, Usage, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, (CASE
WHEN @BillStyle = 1 OR @BillStyle = 7 OR @BillStyle = 11 THEN NULL /* 1 = K9306; 7 = DotMatrixCard; 11 = K9306 No Margin */
ELSE 'Meter Changeout'
END),
(CASE
WHEN @BillStyle = 1 OR @BillStyle = 7 OR @BillStyle = 11 THEN NULL /* 1 = K9306; 7 = DotMatrixCard; 11 = K9306 No Margin */
ELSE 'Meter Changeout'
END), LEFT((@ServiceBillCode + 'C'),3), 0, 0, @LineCounter, NULL, @OldMeterNumber, @ChangeoutReadingDate, @ChangeoutPreviousReadingDate, @ChangeOutPresentReading, @ChangeOutPreviousReading, @ChangeOutUsage, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Meter Changeout Values into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END /* goes with: IF @IsChangeout = 1 */
IF @DemandUsage > 0 AND
((@ServiceIsMetered = 0 AND @ServiceComputedTotal <> 0) OR (@ServiceIsMetered = 1 AND (@ServiceComputedTotal <> 0 OR @DemandUsage <> 0))) AND @ServiceIsBudget <> 1 /* Added 03/28/03 JFK to match DBL See Testing Notes #171 */
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, TextLine, BillCode, BillAmount, Usage, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Demand Meter', 0, 0, @LineCounter, 'Demand Meter', @ServiceBillCode, NULL, @DemandUsage, 0)
END
/* if a deduct amount exists add a line item to the bill */
IF @DeductionAmount <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, TextLine, BillCode, BillAmount, Usage, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Deduct Usage', 0, 0, @LineCounter, 'Deduct Usage', @ServiceBillCode, NULL, @DeductionAmount, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the deduct usage into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END /* goes with: IF @DeductFromAccountID <> 0 */
/* generate lines for the addons if the DisplayOnBillMethod is set to 1 (1 = Seperately) */
IF @ServiceIsBudget <> 1 OR (@ServiceIsBudget = 1 AND @PrintAddOnsSeparatelyForBudgetCustomers = 1)
BEGIN
/* Surcharge1 */
IF @Surcharge1DisplayMethod = 1 AND (@Surcharge1RateID <> 0 AND NOT @Surcharge1RateID IS NULL) AND @ServiceComputedSurcharge1 <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
SET @HoldRateDescription = LEFT(@Surcharge1RateDescription, 20)
IF @Surcharge1PrintDescription = 0
BEGIN
/* Blank out the Description so that nothing prints on the bill */
SET @Surcharge1RateDescription = ''
END
ELSE /* @Surcharge1PrintDescription = 1 */
BEGIN
/* Adds the Fuel Factor to the Description if applicable */
IF @Surcharge1RateID = @SurchargeRateForFuelAdjustmentsID
BEGIN
SET @Surcharge1RateDescription = LEFT(LTRIM(RTRIM(CAST(ISNULL(@Surcharge1Percentage,0) AS VARCHAR(30)))) + ' ' + ISNULL(@Surcharge1RateDescription,''), 29) /* 29 = maximum printing width of field */
SET @HoldRateDescription = LEFT(@Surcharge1RateDescription, 20)
END
END
SET @BillCode = @Surcharge1BillCode + @FinalOrEstimatedText
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Surcharge', @HoldRateDescription, 0, 0, @LineCounter, @ServiceComputedSurcharge1, @BillCode, @Surcharge1RateDescription, @IsEstimated, @IsFinalBill, @AddAmountToTotals) /* add totals only if its not budget */
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the surcharge 1 amount into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
IF LEN(@Surcharge1CommentsOnBill) > 0 AND @ServiceComputedSurcharge1 <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Surcharge', @HoldRateDescription, 0, 0, @LineCounter, NULL, '', @Surcharge1CommentsOnBill, @IsEstimated, @IsFinalBill, 0) /* add totals only if its not budget */
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the surcharge 1 comment into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
SET @BillCode = ''
END /* goes with: IF @Surcharge1DisplayMethod = 1 AND (@Surcharge1RateID <> 0 AND NOT @Surcharge1RateID IS NULL) AND @ServiceComputedSurcharge1 <> 0 */
/* Surcharge2 */
IF @Surcharge2DisplayMethod = 1 AND (@Surcharge2RateID <> 0 AND NOT @Surcharge2RateID IS NULL) AND @ServiceComputedSurcharge2 <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
SET @HoldRateDescription = LEFT(@Surcharge2RateDescription, 20)
IF @Surcharge2PrintDescription = 0
BEGIN
/* Blank out the Description so that nothing prints on the bill */
SET @Surcharge2RateDescription = ''
END
ELSE /* @Surcharge2PrintDescription = 1 */
BEGIN
/* Adds the Fuel Factor to the Description if applicable */
IF @Surcharge2RateID = @SurchargeRateForFuelAdjustmentsID
BEGIN
SET @Surcharge2RateDescription = LEFT(LTRIM(RTRIM(CAST(ISNULL(@Surcharge2Percentage,0) AS VARCHAR(30)))) + ' ' + ISNULL(@Surcharge2RateDescription, ''), 29) /* 29 = maximum printing width of field */
SET @HoldRateDescription = LEFT(@Surcharge2RateDescription, 20)
END
END
SET @BillCode = @Surcharge2BillCode + @FinalOrEstimatedText
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Surcharge', @HoldRateDescription, 0, 0, @LineCounter, @ServiceComputedSurcharge2, @BillCode, @Surcharge2RateDescription, @IsEstimated, @IsFinalBill, @AddAmountToTotals) /* add totals only if its not budget */
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the surcharge 2 amount into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
IF LEN(@Surcharge2CommentsOnBill) > 0 AND @ServiceComputedSurcharge2 <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Surcharge', @HoldRateDescription, 0, 0, @LineCounter, NULL, '', @Surcharge2CommentsOnBill, @IsEstimated, @IsFinalBill, 0) /* add totals only if its not budget */
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the surcharge 1 comment line into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
SET @BillCode = ''
END /* goes with: IF @Surcharge2DisplayMethod = 1 AND (@Surcharge2RateID <> 0 AND NOT @Surcharge2RateID IS NULL) AND @ServiceComputedSurcharge2 <> 0 */
/* LocalTax */
IF @LocalTaxDisplayMethod = 1 AND (@LocalTaxRateID <> 0 AND NOT @LocalTaxRateID IS NULL) AND @ServiceComputedLocalTax <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
SET @HoldRateDescription = LEFT(@LocalTaxRateDescription, 20)
IF @LocalTaxPrintDescription = 0
BEGIN
/* Blank out the Description so that nothing prints on the bill */
SET @LocalTaxRateDescription = ''
END
SET @BillCode = @LocalTaxBillCode + @FinalOrEstimatedText
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Local Tax', @HoldRateDescription, 0, 0, @LineCounter, @ServiceComputedLocalTax, @BillCode, @LocalTaxRateDescription, @IsEstimated, @IsFinalBill, @AddAmountToTotals) /* add totals only if its not budget */
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Local Tax amount into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
IF LEN(@LocalTaxCommentsOnBill) > 0 AND @ServiceComputedLocalTax <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Local Tax', @HoldRateDescription, 0, 0, @LineCounter, NULL, '', @LocalTaxCommentsOnBill, @IsEstimated, @IsFinalBill, 0) /* add totals only if its not budget */
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Local Tax comment into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
SET @BillCode = ''
END /* goes with: IF @LocalTaxDisplayMethod = 1 AND (@LocalTaxRateID <> 0 AND NOT @LocalTaxRateID IS NULL) AND @ServiceComputedLocalTax <> */
/* StateTax */
IF @StateTaxDisplayMethod = 1 AND (@StateTaxRateID <> 0 AND NOT @StateTaxRateID IS NULL) AND @ServiceComputedStateTax <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
SET @HoldRateDescription = LEFT(@StateTaxRateDescription, 20)
IF @StateTaxPrintDescription = 0
BEGIN
/* Blank out the Description so that nothing prints on the bill */
SET @StateTaxRateDescription = ''
END
SET @BillCode = @StateTaxBillCode + @FinalOrEstimatedText
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'State Tax', @HoldRateDescription, 0, 0, @LineCounter, @ServiceComputedStateTax, @BillCode, @StateTaxRateDescription, @IsEstimated, @IsFinalBill, @AddAmountToTotals) /* add totals only if its not budget */
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the State Tax amount into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
END
IF LEN(@StateTaxCommentsOnBill) > 0 AND @ServiceComputedStateTax <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'State Tax', @HoldRateDescription, 0, 0, @LineCounter, NULL, '', @StateTaxCommentsOnBill, @IsEstimated, @IsFinalBill, 0) /* add totals only if its not budget */
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the State Tax comment into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
SET @BillCode = ''
END /* goes with: IF @StateTaxDisplayMethod = 1 AND (@StateTaxRateID <> 0 AND NOT @StateTaxRateID IS NULL) AND @ServiceComputedStateTax <> 0 */
END
/* -------------------------------1 */
/* Insert the "ending balance" line; it is the sum of the "beginning balance" (balance forward/arrears)
and the actual service amount */
IF @PrintEndingBalanceForBudgets = 1 AND @ServiceIsBudget = 1
BEGIN
SET @BillCode = @ServiceBillCode + @FinalOrEstimatedText
IF @BudgetServiceActualArrears <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
/* If the charges have already been posted don't include the compute amount; it has already been
added previously in the stored proc. */
/* IF @CycleStatus <> 7 / 7 = Posted /
BEGIN */
SET @BudgetServiceActualArrears = @BudgetServiceActualArrears +
+ ISNULL(@ServiceComputedSurcharge1, 0) + ISNULL(@ServiceComputedSurcharge2, 0)
+ ISNULL(@ServiceComputedLocalTax, 0) + ISNULL(@ServiceComputedStateTax, 0)
/* END */
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Ending Balance', 0, 0, @LineCounter, @BudgetServiceActualArrears, @BillCode, 'Ending Balance', @IsEstimated, @IsFinalBill, @AddAmountToTotals)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Ending Balance for a Budget Billed Service into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
SET @LineCounter = @LineCounter + 1
/* insert the Budget Payment Amount */
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, BillAmount, BillCode, TextLine, HasEstimatedReadings, HasFinalBill, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Budget Payment', 0, 0, @LineCounter, @ServiceBudgetAmount, @BillCode, 'Budget Payment', @IsEstimated, @IsFinalBill, 1)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Budget Billed Amount into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
IF @ServiceIsBudget = 1
BEGIN
IF @TrackBudgetArrears = 1 AND @ServiceBudgetBalance <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, BillAmount, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Budget Balance', 0, 1, @LineCounter, @BillCode, 'Budget Balance', @ServiceBudgetBalance, 1)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Budget Balance into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
END
/* -------------------------------1 */
IF @Surcharge1DisplayMethod = 5 /* CombinedWithServiceCharge=5 */
BEGIN
IF LEN(@Surcharge1CommentsOnBill) > 0 AND @ServiceComputedSurcharge1 <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Surcharge', @HoldRateDescription, 0, 0, @LineCounter, '', @Surcharge1CommentsOnBill, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Surcharge 1 Comments into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
END
IF @Surcharge2DisplayMethod = 5 /* CombinedWithServiceCharge=5 */
BEGIN
IF LEN(@Surcharge2CommentsOnBill) > 0 AND @ServiceComputedSurcharge2 <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Surcharge', @HoldRateDescription, 0, 0, @LineCounter, '', @Surcharge2CommentsOnBill, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Surcharge 2 Comments into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
END
IF @LocalTaxDisplayMethod = 5 /* CombinedWithServiceCharge=5 */
BEGIN
IF LEN(@LocalTaxCommentsOnBill) > 0 AND @ServiceComputedLocalTax <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'Local Tax', @HoldRateDescription, 0, 0, @LineCounter, '', @LocalTaxCommentsOnBill, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the Local Tax Comments into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
END
IF @StateTaxDisplayMethod = 5 /* CombinedWithServiceCharge=5 */
BEGIN
IF LEN(@StateTaxCommentsOnBill) > 0 AND @ServiceComputedStateTax <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, AddAmountToTotals)
VALUES (@AccountID, @ServiceID, @ServiceTypeID, 'State Tax', @HoldRateDescription, 0, 0, @LineCounter, '', @StateTaxCommentsOnBill, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while inserting the State Tax Comments into the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
END
END
/* calculate the running totals for the addons. The totals are entered in the #TempPrintBillServiceDetails
when the @PreviousAccountID <> @AccountID. When using CombineWithLikeCharges the addon information needs to be set to the info from the first
addon of the particular type. The rateIDs are set to zero when the procedure starts and after
entering the print lines for the combined charges in the #TempPrintBillServiceDetails */
IF (@Surcharge1DisplayMethod = 3 AND (@Surcharge1RateID <> 0 AND NOT @Surcharge1RateID IS NULL))
OR (@Surcharge2DisplayMethod = 3 AND (@Surcharge2RateID <> 0 AND NOT @Surcharge2RateID IS NULL)) /* 3 = Combine with like Charges */
BEGIN
/* only combine the charges if its a non-budget service */
IF @ServiceIsBudget <> 1
BEGIN
SET @SurchargeNumberCombined = @SurchargeNumberCombined + 1
SET @CombinedServiceSurchargeAmount = @CombinedServiceSurchargeAmount + ISNULL(@ServiceComputedSurcharge1, 0) + ISNULL(@ServiceComputedSurcharge2, 0)
END
/* if the first surcharge rate hasn't been encountered, load its values from the surcharge 1
when combining charges the descriptions, codes, etc. from the first Addon for th account are used */
IF @FirstSurchargeRateID = 0
BEGIN
SET @FirstSurchargeRateID = @Surcharge1RateID
SET @FirstSurchargeBillCode = @Surcharge1BillCode
SET @FirstSurchargePrintDescription = @Surcharge1PrintDescription
SET @FirstSurchargeRateDescription = @Surcharge1RateDescription
END
/* if the first surcharge rate still hasn't been encountered, load its values from the surcharge 2
when combining charges the descriptions, codes, etc. from the first Addon for the account are used */
IF @FirstSurchargeRateID = 0
BEGIN
SET @FirstSurchargeRateID = @Surcharge2RateID
SET @FirstSurchargeBillCode = @Surcharge2BillCode
SET @FirstSurchargePrintDescription = @Surcharge2PrintDescription
SET @FirstSurchargeRateDescription = @Surcharge2RateDescription
END
END
IF @LocalTaxDisplayMethod = 3 AND (@LocalTaxRateID <> 0 AND NOT @LocalTaxRateID IS NULL) /* 3 = Combine with like Charges */
BEGIN
/* only combine the chares if its a non-budget service */
IF @ServiceIsBudget <> 1
BEGIN
SET @LocalTaxNumberCombined = @LocalTaxNumberCombined + 1
SET @CombinedServiceLocalTaxAmount = @CombinedServiceLocalTaxAmount + ISNULL(@ServiceComputedLocalTax, 0)
END
/* if the first local tax rate still hasn't been encountered, load its values into variables;
when combining charges the descriptions, codes, etc. from the first Addon for th account are used */
IF @FirstLocalTaxRateID = 0
BEGIN
SET @FirstLocalTaxRateID = @LocalTaxRateID
SET @FirstLocalTaxBillCode = @LocalTaxBillCode
SET @FirstLocalTaxPrintDescription = @LocalTaxPrintDescription
SET @FirstLocalTaxRateDescription = @LocalTaxRateDescription
END
END
IF @StateTaxDisplayMethod = 3 AND (@StateTaxRateID <> 0 AND NOT @StateTaxRateID IS NULL) /* 3 = Combine with like Charges */
BEGIN
/* only combine the chares if its a non-budget service */
IF @ServiceIsBudget <> 1
BEGIN
SET @StateTaxNumberCombined = @StateTaxNumberCombined + 1
SET @CombinedServiceStateTaxAmount = @CombinedServiceStateTaxAmount + ISNULL(@ServiceComputedStateTax, 0)
END
/* if the first local tax rate still hasn't been encountered, load its values into variables;
when combining charges the descriptions, codes, etc. from the first Addon for th account are used */
IF @FirstStateTaxRateID = 0
BEGIN
SET @FirstStateTaxRateID = @StateTaxRateID
SET @FirstStateTaxBillCode = @StateTaxBillCode
SET @FirstStateTaxPrintDescription = @StateTaxPrintDescription
SET @FirstStateTaxRateDescription = @StateTaxRateDescription
END
END
UPDATE #TempPrintEntireBill
SET DelinquentAmount = DelinquentAmount + @DelinquentAmount + ISNULL(@DelinquentAmountSurcharge1, 0)
+ ISNULL(@DelinquentAmountSurcharge2, 0) + ISNULL(@DelinquentAmountLocalTax, 0)
+ ISNULL(@DelinquentAmountStateTax, 0) + ISNULL(@DelinquentAmountPenalty, 0),
NoticesSent = (CASE WHEN @NoticesSent > ISNULL(NoticesSent, 0) THEN @NoticesSent
ELSE ISNULL(NoticesSent, 0)
END) /* take the highest one in the list of services. */
WHERE AccountID = @AccountID
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
SET @ErrorMessage = ' An error occurred while updating the Delinquent Amounts on the #TempPrintBillServiceDetails for account ' + @FormattedAccountNumber
RAISERROR(@ErrorMessage,16,1)
RETURN(99)
END
/* clear the values for the next service */
SET @BillCode = ''
SET @Surcharge1BillCode = ''
SET @Surcharge2BillCode = ''
SET @LocalTaxBillCode = ''
SET @StateTaxBillCode = ''
SET @FinalOrEstimatedText = ''
SET @Usage = NULL
SET @ActualUsage = NULL
SET @MeterNumber = ''
SET @PreviousReadingDate = NULL
SET @PresentReadingDate = NULL
SET @ChangeoutPreviousReadingDate = NULL
SET @ChangeoutReadingDate = NULL
SET @PreviousReading = NULL
SET @PresentReading = NULL
SET @ReadingFactor = 0
SET @IsChangeout = 0
SET @IsEstimated = 0
SET @IsFinalBill = 0
SET @ServiceIsMetered = 0
SET @ForcePrintSeperateArrears = 0
SET @ChangeoutPreviousReading = NULL
SET @ChangeoutPresentReading = NULL
SET @ChangeoutUsage = NULL
SET @OldMeterID = NULL
SET @ServiceComputedAmount = 0
SET @ServiceComputedSurcharge1 = 0
SET @ServiceComputedSurcharge2 = 0
SET @ServiceComputedLocalTax = 0
SET @ServiceComputedStateTax = 0
SET @ServiceBudgetAmount = 0
SET @ServiceBudgetBalance = 0
SET @DelinquentAmount = 0
SET @Surcharge1RateID = 0
SET @Surcharge2RateID = 0
SET @LocalTaxRateID = 0
SET @StateTaxRateID = 0
SET @ReadingType = NULL
SET @Usage = NULL
SET @ActualUsage = NULL
SET @ServiceCompoundUsage = NULL
SET @CurrentDays = NULL
SET @LastMonthUsage = NULL
SET @LastMonthDays = NULL
SET @SameMonthLastYearUsage = NULL
SET @SameMonthLastYearDays = NULL
SET @AverageUsage = NULL
SET @DeductionAmount = NULL
SET @DemandUsage = NULL
SET @ChartReadingDate1 = NULL
SET @ChartReadingDate2 = NULL
SET @ChartReadingDate3 = NULL
SET @ChartReadingDate4 = NULL
SET @ChartReadingDate5 = NULL
SET @ChartReadingDate6 = NULL
SET @ChartReadingDate7 = NULL
SET @ChartReadingDate8 = NULL
SET @ChartReadingDate9 = NULL
SET @ChartReadingDate10 = NULL
SET @ChartReadingDate11 = NULL
SET @ChartReadingDate12 = NULL
SET @ChartReadingDate13 = NULL
SET @ChartUsage1 = 0
SET @ChartUsage2 = 0
SET @ChartUsage3 = 0
SET @ChartUsage4 = 0
SET @ChartUsage5 = 0
SET @ChartUsage6 = 0
SET @ChartUsage7 = 0
SET @ChartUsage8 = 0
SET @ChartUsage9 = 0
SET @ChartUsage10 = 0
SET @ChartUsage11 = 0
SET @ChartUsage12 = 0
SET @ChartUsage13 = 0
SET @ChartHighestUsage = 0
/* set the previous info equal to the current info */
SET @PreviousAccountID = @AccountID /* Set the PreviousAccountID equal to the current AccountID */
SET @PreviousServiceID = @ServiceID /* Set the PreviousServiceID equal to the current ServiceID */
SET @PreviousServiceTypeID = @ServiceTypeID /* Set the PreviousServiceTypeID equal to the current ServiceTypeID */
END /* Goes with cursor loop */
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
/* Combined charges only print if the PreviousAccountID <> AccountID this will not occur for the final record in the cursor.
therefore the very last account will not print properly if addonRate is set to "CombinedWithLikeCharges"
the following section will correct this problem. */
/* Surcharge 1 & 2 */
IF @SurchargeNumberCombined >= 1 AND @CombinedServiceSurchargeAmount <> 0 /* There was at least one surcharge addon that had a rate with CombinedWithLikeCharges */
BEGIN
SET @LineCounter = @LineCounter + 1
SET @HoldRateDescription = LEFT(@FirstSurchargePrintDescription, 20)
IF @FirstSurchargePrintDescription = 0
BEGIN
/* Blank out the Description so that nothing prints on the bill */
SET @FirstSurchargeRateDescription = ''
END
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, BillAmount, AddAmountToTotals)
VALUES (@PreviousAccountID, @PreviousServiceID, @PreviousServiceTypeID, 'Surcharge', @HoldRateDescription, 0, 0, @LineCounter, @FirstSurchargeBillCode, @FirstSurchargeRateDescription, @CombinedServiceSurchargeAmount, 1)
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR ('An error occurred while inserting the last combined Surcharge amount into the #TempPrintBillServiceDetails.',16,1)
RETURN(99)
END
/* Reset the value */
SET @CombinedServiceSurchargeAmount = 0
IF LEN(@Surcharge1CommentsOnBill) > 0 AND @ServiceComputedSurcharge1 <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, AddAmountToTotals)
VALUES (@PreviousAccountID, @PreviousServiceID, @PreviousServiceTypeID, 'Surcharge 1', @HoldRateDescription, 0, 0, @LineCounter, '', @Surcharge1CommentsOnBill, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
RAISERROR ('An error occurred while inserting the last Surcharge 1 comments line into the #TempPrintBillServiceDetails.',16,1)
RETURN(99)
END
END
IF LEN(@Surcharge2CommentsOnBill) > 0 AND @ServiceComputedSurcharge2 <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, AddAmountToTotals)
VALUES (@PreviousAccountID, @PreviousServiceID, @PreviousServiceTypeID, 'Surcharge 2', @HoldRateDescription, 0, 0, @LineCounter, '', @Surcharge2CommentsOnBill, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
RAISERROR ('An error occurred while inserting the last Surcharge 2 comments line into the #TempPrintBillServiceDetails.',16,1)
RETURN(99)
END
END
END /* goes with: IF @SurchargeNumberCombined > 1 AND @CombinedServiceSurchargeAmount <> 0 */
/* Local Tax */
IF @LocalTaxNumberCombined >= 1 AND @CombinedServiceLocalTaxAmount <> 0 /* There is at least one addon of this type to print */
BEGIN
SET @LineCounter = @LineCounter + 1
SET @HoldRateDescription = LEFT(@FirstLocalTaxPrintDescription, 20)
IF @FirstLocalTaxPrintDescription = 0
BEGIN
/* Blank out the Description so that nothing prints on the bill */
SET @FirstLocalTaxRateDescription = ''
END
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, BillAmount, AddAmountToTotals)
VALUES (@PreviousAccountID, @PreviousServiceID, @PreviousServiceTypeID, 'Local Tax', @HoldRateDescription, 0, 0, @LineCounter, @FirstLocalTaxBillCode, @FirstLocalTaxRateDescription, @CombinedServiceLocalTaxAmount, 1)
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR ('An error occurred while inserting the last combined Local Tax amount into the #TempPrintBillServiceDetails.',16,1)
RETURN(99)
END
SET @CombinedServiceLocalTaxAmount = 0
IF LEN(@LocalTaxCommentsOnBill) > 0 AND @ServiceComputedLocalTax <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, AddAmountToTotals)
VALUES (@PreviousAccountID, @PreviousServiceID, @PreviousServiceTypeID, 'Local Tax', @HoldRateDescription, 0, 0, @LineCounter, '', @LocalTaxCommentsOnBill, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
RAISERROR ('An error occurred while inserting the last Local Tax comments line into the #TempPrintBillServiceDetails.',16,1)
RETURN(99)
END
END
END /* goes with: IF @LocalTaxNumberCombined > 1 AND @CombinedServiceLocalTaxAmount <> 0 */
/* StateTax */
IF @StateTaxNumberCombined >= 1 AND @CombinedServiceStateTaxAmount <> 0 /* There is at least one addon of this type to print */
BEGIN
SET @LineCounter = @LineCounter + 1
SET @HoldRateDescription = LEFT(@FirstStateTaxRateDescription, 20)
IF @FirstStateTaxPrintDescription = 0
BEGIN
/* Blank out the Description so that nothing prints on the bill */
SET @FirstStateTaxRateDescription = ''
END
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, BillAmount, AddAmountToTotals)
VALUES (@PreviousAccountID, @PreviousServiceID, @PreviousServiceTypeID, 'State Tax', @HoldRateDescription, 0, 0, @LineCounter, @FirstStateTaxBillCode, @FirstStateTaxRateDescription, @CombinedServiceStateTaxAmount, 1)
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR ('An error occurred while inserting the last combined State Tax amount into the #TempPrintBillServiceDetails.',16,1)
RETURN(99)
END
/* Reset the value */
IF LEN(@StateTaxCommentsOnBill) > 0 AND @ServiceComputedStateTax <> 0
BEGIN
SET @LineCounter = @LineCounter + 1
INSERT INTO #TempPrintBillServiceDetails (AccountID, ServiceID, ServiceTypeID, BillDescription, RateDescription, IsForMeteredService, IsArrears, LineNumber, BillCode, TextLine, AddAmountToTotals)
VALUES (@PreviousAccountID, @PreviousServiceID, @PreviousServiceTypeID, 'State Tax', @HoldRateDescription, 0, 0, @LineCounter, '', @StateTaxCommentsOnBill, 0)
IF @@ERROR <> 0
BEGIN
CLOSE ServiceCursor
DEALLOCATE ServiceCursor
SET NOCOUNT OFF
RAISERROR ('An error occurred while inserting the last State Tax comments line into the #TempPrintBillServiceDetails.',16,1)
RETURN(99)
END
END
SET @CombinedServiceStateTaxAmount = 0
END /* goes with: IF @StateTaxNumberCombined > 1 AND @CombinedServiceStateTaxAmount <> 0*/
/* ---------- Done with the cursor and final record; begin generating bills from the Service temp table ------------*/
/* vvvvvvvvvv SWR UMS-391 vvvvvvvvv */
/* pdAllBills = 1 - Do nothing */
IF @IncludeDelinquents = 3 /* pdExportFile = 3; anyone that is not delinquent or is "habitually" delinquent */
BEGIN
DELETE FROM #TempPrintEntireBill
WHERE NoticesSent <= 2
AND DelinquentAmount > 0
END
ELSE
BEGIN
IF @IncludeDelinquents = 5 /* pdInHouseBills = 5 */
BEGIN
DELETE FROM #TempPrintEntireBill
WHERE NoticesSent > 2 /* they are habitually delinquent */
OR DelinquentAmount <= 0 /* they aren't delinquent */
END
END
/* ^^^^^^^^^^ SWR UMS-391 ^^^^^^^^^ */
/* combines the #TempPrintBillServiceDetails and the #TempPrintEntireBill */
SET @NumberOfAccounts = (SELECT COUNT(*)
FROM #TempPrintEntireBill)
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR ('An error occurred while determining the number of Accounts in the #TempPrintEntireBill.',16,1)
RETURN(99)
END
SET @PreviousAccountID = 0
/* loop through the entire #TempPrintBillServiceDetails and match it up with the appropriate bill record */
WHILE (@NumberOfAccounts > 0)
BEGIN
/* Start at the first account and select the next biggest account in the list. */
SET @AccountID = (SELECT MIN(AccountID)
FROM #TempPrintEntireBill
WHERE AccountID > @PreviousAccountID)
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR ('An error occurred while getting the next available Account from the #TempPrintBillServiceDetails.',16,1)
RETURN(99)
END
/* get the number of service detail lines for the account */
SET @Count = (SELECT COUNT(*)
FROM #TempPrintBillServiceDetails
WHERE AccountID = @AccountID)
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR ('An error occurred while determining the number of service detail lines that exist for the Account in the #TempPrintBillServiceDetails.',16,1)
RETURN(99)
END
IF @PrintContinuation = 0 AND @Count > 11 /* continuations are not allowed and its at the last line of the bill and there are still more sevices to print */
BEGIN
/* sum the amounts for all remaining charges services with a LineNumber >= 11 from the detail Table */
SET @RemainingServicesTotal = (SELECT SUM(ISNULL(BillAmount, 0))
FROM #TempPrintBillServiceDetails AS Tmp
WHERE Tmp.LineNumber >= 11
AND AccountID = @AccountID
AND NOT BillAmount IS NULL
AND AddAmountToTotals = 1) /* This is used to eliminate the unneeded Budget billed lines from the totals. */
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR ('An error occurred while calculating the Total Other Charges for the Account.',16,1)
RETURN(99)
END
UPDATE #TempPrintBillServiceDetails
SET ServiceID = -1,
ServiceTypeID = -1,
BillDescription = 'Total Other Charges',
RateDescription = '',
IsForMeteredService = 0,
IsArrears = 0,
TextLine = 'Total Other Charges',
BillCode = '',
MeterNumber = NULL,
PresentReadingDate = NULL,
PreviousReadingDate = NULL,
PresentReading = NULL,
PreviousReading = NULL,
Usage = NULL,
CurrentDays = NULL,
LastMonthUsage = NULL,
LastMonthDays = NULL,
SameMonthLastYearUsage = NULL,
SameMonthLastYearDays = NULL,
BillAmount = @RemainingServicesTotal,
HasFinalBill = NULL,
HasEstimatedReadings = NULL,
IncludesMultipleMeters = NULL,
AddAmountToTotals = 1
WHERE AccountID = @AccountID
AND LineNumber = 11
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR ('An error occurred while updating the 11th bill line in #TempPrintBillServiceDetails to be the total of all other charges.',16,1)
RETURN(99)
END
/* clear the remaining amounts to prevent them from being included in the @AmountDueTotal */
UPDATE #TempPrintBillServiceDetails
SET BillAmount = 0
WHERE AccountID = @AccountID
AND LineNumber > 11
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR ('An error occurred while clearing the charges after 11th bill line in #TempPrintBillServiceDetails.',16,1)
RETURN(99)
END
END
SET @PriorBalance = ISNULL((SELECT SUM(Services.BilledArrears)
FROM Services
WHERE Services.Deleted = 0
AND Services.AccountId = @AccountId
AND Services.RemoveService = 0
AND Services.AccountStat <> 1 /* 1 = Beginning */
AND Services.AccountStat <> 9 /* 9 = Bad Debt */
AND Services.AccountStat <> 13 /* 13 = Pending */
AND (Services.AccountStat <> 11 OR (Services.AccountStat = 11 AND Services.ShowArrearsInBillingWhenInactive = 1))
AND ((Services.IsCompound = 0 OR Services.IsCompound IS NULL) OR (Services.IsCompound = 1 AND Services.IsCompoundPrimary = 1))
AND Services.BilledArrears > 0), 0)
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while calculating the prior service balance for an account.',16,1)
RETURN(99)
END
/* the "SAVE THIS" field */
SET @PenaltyGrandTotal = ISNULL((SELECT SUM(ISNULL(Addons.ComputedAmount,0))
FROM Services JOIN Addons ON Services.ServiceID = Addons.ServiceID
WHERE Services.AccountID = @AccountID
AND (Services.Deleted = 0 OR Services.Deleted IS NULL)
AND (Services.RemoveService = 0 OR Services.RemoveService IS NULL)
AND (Services.IsBudget = 0 OR Services.IsBudget IS NULL)
AND Services.AccountStat <> 1 /* 1 = Beginning */
AND Services.AccountStat <> 9 /* 9 = Bad Debt */
AND Services.AccountStat <> 13 /* 13 = Pending */
/* include all status that are not inactive and those inactive services with the ShowArrearsInBillingWhenInactive set */
AND (Services.AccountStat <> 11 OR (Services.AccountStat = 11 AND Services.ShowArrearsInBillingWhenInactive = 1))
/* this line excludes all compound meters that are not compound primary;
Only the charges for the primary meter need to be pulled; the charges for secondary meters are stored in the Primary meter's charges during the compute process;
the usage for compound meters is calculated later in this procedure at the time a compound primary service is selected from the cursor (usage = sum of usages for the primary and all of its related secondary service(s)).*/
AND ((Services.IsCompound = 0 OR Services.IsCompound IS NULL) OR (Services.IsCompound = 1 AND Services.IsCompoundPrimary = 1))
AND (Addons.Deleted = 0 OR Addons.Deleted IS NULL)
AND ((Addons.IsInactive = 0 OR Addons.IsInactive IS NULL) OR (Addons.IsInactive = 1 AND Services.ShowArrearsInBillingWhenInactive = 1))
AND Addons.AdType = 9 /* 9 = Penalty */), 0)
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR (' An error occurred while calculating the Total Penalty for the Account.',16,1)
RETURN(99)
END
/* the "AMOUNT DUE ON OR BEFORE DUE DATE" field;
Sums the Bill Amounts with the arrears amounts that are created with each line in the #TempPrintBillServiceDetails */
IF @AddArrearsToNet = 1
BEGIN
SET @AmountDueTotal = ISNULL((SELECT SUM(BillAmount)
FROM #TempPrintBillServiceDetails
WHERE AccountID = @AccountID
AND NOT BillAmount IS NULL
AND AddAmountToTotals = 1),0) /* This is used to eliminate the unneeded Budget billed lines from the totals. */
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR (' An error occurred while calculating the Total Amount Due for the Account.',16,1)
RETURN(99)
END
END
ELSE
BEGIN
SET @AmountDueTotal = ISNULL((SELECT SUM(BillAmount)
FROM #TempPrintBillServiceDetails
WHERE AccountID = @AccountID
/* limit it to those amounts that are not arrears */
AND (IsArrears = 0 OR IsArrears IS NULL)
AND NOT BillAmount IS NULL
AND AddAmountToTotals = 1),0) /* This is used to eliminate the unneeded Budget billed lines from the totals. */
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR (' An error occurred while calculating the Total Amount Due for the Account.',16,1)
RETURN(99)
END
END
/* creates Total Other Services and Service to Total on Bill Stub line */
IF @ServiceToTotalSeperatelyID <> 0
BEGIN
SET @ServiceTotalOnBillStub = ISNULL((SELECT SUM(BillAmount)
FROM #TempPrintBillServiceDetails
WHERE AccountID = @AccountID
/* limit it to those amounts that are not arrears */
AND ServiceTypeID = @ServiceToTotalSeperatelyID
AND NOT BillAmount IS NULL
AND AddAmountToTotals = 1),0) /* This is used to eliminate the unneeded Budget billed lines from the totals. */
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR (' An error occurred while calculating the Service to Total Seperately for the Account.',16,1)
RETURN(99)
END
SET @ServiceCodeToTotalOnBillStub = ISNULL((SELECT ServiceCode
FROM ServiceTypes
WHERE ServiceTypeID = @ServiceToTotalSeperatelyID),'')
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR (' An error occurred while calculating the Total Amount Due for the Account.',16,1)
RETURN(99)
END
SET @TotalOtherServices = @AmountDueTotal - @ServiceTotalOnBillStub
END
ELSE
BEGIN
SET @ServiceCodeToTotalOnBillStub = ''
END /* goes with: IF @ServiceToTotalSeperatelyID <> 0 */
/* If they don't owe any money then their penalty amount should be zero */
IF @AmountDueTotal <= 0
BEGIN
SET @PenaltyGrandTotal = 0
END
/* the "AMOUNT DUE AFTER DUE DATE" field */
SET @AmountDueLateTotal = ISNULL(@AmountDueTotal, 0) + @PenaltyGrandTotal
/*****************************The switching of the signs is no longer needed. It should display as negative on the bill. */
/* once all of the amount due totals are calculated the figures for deposits need to be set back to positive amounts.
doing it in the SQL is much faster then testing every field in the report for a deposit record. */
/* UPDATE #TempPrintBillServiceDetails
SET BillAmount = (BillAmount * -1)
WHERE TextLine = 'Applied Deposit'
AND AccountID = @AccountID
AND NOT BillAmount IS NULL
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR (' An error occurred while resetting the Applied Deposit amounts.',16,1)
RETURN(99)
END
******************************/
/* Determines if a Final Service exists on the bill. */
SET @HasFinalBill = (CASE
WHEN EXISTS(SELECT Bills.ServiceId
FROM #TempPrintBillServiceDetails AS Bills
WHERE Bills.AccountId = @AccountId
AND ISNULL(Bills.HasFinalBill, 0) <> 0 ) THEN 1
ELSE 0
END)
/* Determines if an Estimated Reading exists on the bill. */
SET @HasEstimatedReadings = (CASE
WHEN EXISTS(SELECT Bills.ServiceId
FROM #TempPrintBillServiceDetails AS Bills
WHERE Bills.AccountId = @AccountId
AND ISNULL(Bills.HasEstimatedReadings, 0) <> 0 ) THEN 1
ELSE 0
END)
/* Determines if a Compound Meter exists on the bill */
SET @IncludesMultipleMeters = (CASE
WHEN EXISTS(SELECT Bills.ServiceId
FROM #TempPrintBillServiceDetails AS Bills
WHERE Bills.AccountId = @AccountId
AND ISNULL(Bills.IncludesMultipleMeters, 0) <> 0 ) THEN 1
ELSE 0
END)
IF @PrintContinuation = 0 /* 1 bill per customer */
BEGIN
SET @NumberOfBills = 1
END
ELSE /* Print "indefinitely" until all service detail lines print */
BEGIN
/* In testing the rounding function for SQL acted squirrelly when doing division; To compensate
the number of bills is calculated by dividing the print lines by 11 and if there is a remainder
simply addding 1 to the number of bills to print. */
SET @NumberOfBills = (@Count/11) /* Set it equal to the number of bills it would take to print all detail lines */
IF @Count%11 <> 0
BEGIN
SET @NumberOfBills = @NumberOfBills + 1
END
/* If there are going to be continuation bills create the bills with the account info from the first bill and "blank service" sections in #TempPrintEntireBill */
IF @NumberOfBills > 1
BEGIN
/* update the Number of Bills field so it matches in all the bills. It is used the report to
determine whether to print the "CONTINUED ON NEXT BILL" message */
UPDATE #TempPrintEntireBill
SET NumberofBills = @NumberOfBills
WHERE AccountID = @AccountID
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR (' An error occurred while updating the NumberofBills field.',16,1)
RETURN(99)
END
/* initial @BillIndex should be 2 because the first bill is created when the procedure first starts;
The bill being inserted here is the second bill */
SET @BillIndex = 2
WHILE (@BillIndex <= @NumberOfBills) /* index = current location in the loop; @NumberOfBills = number of bills that will print for the account */
BEGIN
INSERT INTO #TempPrintEntireBill
(BillNumber,
NumberofBills,
CycleID,
AccountID,
AccountsRoute,
AccountsAccountNumber,
AccountsSequence,
AccountsInCareOf,
AccountsSalutation,
AccountsFirstName,
AccountsMiddleName,
AccountsLastName,
AccountsNameSuffix,
AccountsDBAName,
AccountsCarrierRoute,
ServiceNumber,
ServiceName,
BillingAddress,
BillingCity,
BillingState,
BillingZip,
ForeignBillingAddress,
DataPointBarCode,
BarCodeCheckDigit,
ZipCodeSummaryZip,
ZipCodeSummaryFiveDigitZip,
IsBarcodedBill,
IsTenant,
IsLandlord,
LandlordAccountID,
LandlordName,
LandlordDBAName,
LandlordInCareOf,
LandlordAddress,
LandlordCity,
LandlordState,
LandlordZip,
ForeignLandlordAddress,
LandlordCarrierRoute,
LandlordDataPointBarCode,
LandlordBarCodeCheckDigit,
LandlordBillIsBarcoded,
SendBillTo,
SendDelinquentBillTo,
UsesBudgets,
UseBankDrafts,
RemainingUnappliedCashWhenComputed,
PreviousReadingDate,
PresentReadingDate,
CodeLine1,
CodeLine2,
CodeLine3,
CodeLine4,
CodeLine5,
CodeLine6,
CodeLine7,
CodeLine8,
CodeLine9,
CodeLine10,
CodeLine11,
MeterNumberLine1,
MeterNumberLine2,
MeterNumberLine3,
MeterNumberLine4,
MeterNumberLine5,
MeterNumberLine6,
MeterNumberLine7,
MeterNumberLine8,
MeterNumberLine9,
MeterNumberLine10,
MeterNumberLine11,
PresentReadingDateLine1,
PresentReadingDateLine2,
PresentReadingDateLine3,
PresentReadingDateLine4,
PresentReadingDateLine5,
PresentReadingDateLine6,
PresentReadingDateLine7,
PresentReadingDateLine8,
PresentReadingDateLine9,
PresentReadingDateLine10,
PresentReadingDateLine11,
PreviousReadingDateLine1,
PreviousReadingDateLine2,
PreviousReadingDateLine3,
PreviousReadingDateLine4,
PreviousReadingDateLine5,
PreviousReadingDateLine6,
PreviousReadingDateLine7,
PreviousReadingDateLine8,
PreviousReadingDateLine9,
PreviousReadingDateLine10,
PreviousReadingDateLine11,
PresentReadingLine1,
PresentReadingLine2,
PresentReadingLine3,
PresentReadingLine4,
PresentReadingLine5,
PresentReadingLine6,
PresentReadingLine7,
PresentReadingLine8,
PresentReadingLine9,
PresentReadingLine10,
PresentReadingLine11,
PreviousReadingLine1,
PreviousReadingLine2,
PreviousReadingLine3,
PreviousReadingLine4,
PreviousReadingLine5,
PreviousReadingLine6,
PreviousReadingLine7,
PreviousReadingLine8,
PreviousReadingLine9,
PreviousReadingLine10,
PreviousReadingLine11,
UsageLine1,
UsageLine2,
UsageLine3,
UsageLine4,
UsageLine5,
UsageLine6,
UsageLine7,
UsageLine8,
UsageLine9,
UsageLine10,
UsageLine11,
CurrentDaysLine1,
CurrentDaysLine2,
CurrentDaysLine3,
CurrentDaysLine4,
CurrentDaysLine5,
CurrentDaysLine6,
CurrentDaysLine7,
CurrentDaysLine8,
CurrentDaysLine9,
CurrentDaysLine10,
CurrentDaysLine11,
LastMonthUsageLine1,
LastMonthUsageLine2,
LastMonthUsageLine3,
LastMonthUsageLine4,
LastMonthUsageLine5,
LastMonthUsageLine6,
LastMonthUsageLine7,
LastMonthUsageLine8,
LastMonthUsageLine9,
LastMonthUsageLine10,
LastMonthUsageLine11,
LastMonthDaysLine1,
LastMonthDaysLine2,
LastMonthDaysLine3,
LastMonthDaysLine4,
LastMonthDaysLine5,
LastMonthDaysLine6,
LastMonthDaysLine7,
LastMonthDaysLine8,
LastMonthDaysLine9,
LastMonthDaysLine10,
LastMonthDaysLine11,
SameMonthLastYearUsageLine1,
SameMonthLastYearUsageLine2,
SameMonthLastYearUsageLine3,
SameMonthLastYearUsageLine4,
SameMonthLastYearUsageLine5,
SameMonthLastYearUsageLine6,
SameMonthLastYearUsageLine7,
SameMonthLastYearUsageLine8,
SameMonthLastYearUsageLine9,
SameMonthLastYearUsageLine10,
SameMonthLastYearUsageLine11,
SameMonthLastYearDaysLine1,
SameMonthLastYearDaysLine2,
SameMonthLastYearDaysLine3,
SameMonthLastYearDaysLine4,
SameMonthLastYearDaysLine5,
SameMonthLastYearDaysLine6,
SameMonthLastYearDaysLine7,
SameMonthLastYearDaysLine8,
SameMonthLastYearDaysLine9,
SameMonthLastYearDaysLine10,
SameMonthLastYearDaysLine11,
ChargesLine1,
ChargesLine2,
ChargesLine3,
ChargesLine4,
ChargesLine5,
ChargesLine6,
ChargesLine7,
ChargesLine8,
ChargesLine9,
ChargesLine10,
ChargesLine11,
TextLine1,
TextLine2,
TextLine3,
TextLine4,
TextLine5,
TextLine6,
TextLine7,
TextLine8,
TextLine9,
TextLine10,
TextLine11,
BillDescription1,
BillDescription2,
BillDescription3,
BillDescription4,
BillDescription5,
BillDescription6,
BillDescription7,
BillDescription8,
BillDescription9,
BillDescription10,
BillDescription11,
RateDescription1,
RateDescription2,
RateDescription3,
RateDescription4,
RateDescription5,
RateDescription6,
RateDescription7,
RateDescription8,
RateDescription9,
RateDescription10,
RateDescription11,
Line1IsForMeteredService,
Line2IsForMeteredService,
Line3IsForMeteredService,
Line4IsForMeteredService,
Line5IsForMeteredService,
Line6IsForMeteredService,
Line7IsForMeteredService,
Line8IsForMeteredService,
Line9IsForMeteredService,
Line10IsForMeteredService,
Line11IsForMeteredService,
ChartReadingDate1,
ChartReadingDate2,
ChartReadingDate3,
ChartReadingDate4,
ChartReadingDate5,
ChartReadingDate6,
ChartReadingDate7,
ChartReadingDate8,
ChartReadingDate9,
ChartReadingDate10,
ChartReadingDate11,
ChartReadingDate12,
ChartReadingDate13,
ChartUsage1,
ChartUsage2,
ChartUsage3,
ChartUsage4,
ChartUsage5,
ChartUsage6,
ChartUsage7,
ChartUsage8,
ChartUsage9,
ChartUsage10,
ChartUsage11,
ChartUsage12,
ChartUsage13,
CurrentPeriodNumberofDays,
PreviousPeriodNumberofDays,
SameMonthLastYearNumberofDays,
ChartHighestUsage,
CustomerType,
Cycle,
PriorBalance,
PenaltyAmount,
PrintThisBill,
AmountDueTotal,
AmountDueLateTotal,
ServiceCodeToTotalOnBillStub,
ServiceTotalOnBillStub,
AccountCommentLine1,
AccountCommentLine2,
HasFinalBill,
IsMemoBill,
DelinquentAmount,
LastPaymentDate,
HasEstimatedReadings,
IncludesMultipleMeters,
MessageLine1,
MessageLine2,
MessageLine3,
MessageLine4,
PenaltyDate,
PostageRateType,
TrayNumber)
SELECT @BillIndex, /* initial BillNumber should be 2 because the first bill is created when the procedure first starts */
NumberofBills,
CycleID,
AccountID,
AccountsRoute,
AccountsAccountNumber,
AccountsSequence,
AccountsInCareOf,
AccountsSalutation,
AccountsFirstName,
AccountsMiddleName,
AccountsLastName,
AccountsNameSuffix,
AccountsDBAName,
AccountsCarrierRoute,
ServiceNumber,
ServiceName,
BillingAddress,
BillingCity,
BillingState,
BillingZip,
ForeignBillingAddress,
DataPointBarCode,
BarCodeCheckDigit,
ZipCodeSummaryZip,
ZipCodeSummaryFiveDigitZip,
IsBarcodedBill,
IsTenant,
IsLandlord,
LandlordAccountID,
LandlordName,
LandlordDBAName,
LandlordInCareOf,
LandlordAddress,
LandlordCity,
LandlordState,
LandlordZip,
ForeignLandlordAddress,
LandlordCarrierRoute,
LandlordDataPointBarCode,
LandlordBarCodeCheckDigit,
LandlordBillIsBarcoded,
SendBillTo,
SendDelinquentBillTo,
UsesBudgets,
UseBankDrafts,
RemainingUnappliedCashWhenComputed,
PreviousReadingDate, /* Previous Reading Date */
PresentReadingDate, /* Present Reading Date */
NULL, /* CodeLine1 */
NULL, /* CodeLine2 */
NULL, /* CodeLine3 */
NULL, /* CodeLine4 */
NULL, /* CodeLine5 */
NULL, /* CodeLine6 */
NULL, /* CodeLine7 */
NULL, /* CodeLine8 */
NULL, /* CodeLine9 */
NULL, /* CodeLine10 */
NULL, /* CodeLine11 */
'', /* MeterNumberLine1 */
'', /* MeterNumberLine2 */
'', /* MeterNumberLine3 */
'', /* MeterNumberLine4 */
'', /* MeterNumberLine5 */
'', /* MeterNumberLine6 */
'', /* MeterNumberLine7 */
'', /* MeterNumberLine8 */
'', /* MeterNumberLine9 */
'', /* MeterNumberLine10 */
'', /* MeterNumberLine11 */
NULL, /* PresentReadingDateLine1 */
NULL, /* PresentReadingDateLine2 */
NULL, /* PresentReadingDateLine3 */
NULL, /* PresentReadingDateLine4 */
NULL, /* PresentReadingDateLine5 */
NULL, /* PresentReadingDateLine6 */
NULL, /* PresentReadingDateLine7 */
NULL, /* PresentReadingDateLine8 */
NULL, /* PresentReadingDateLine9 */
NULL, /* PresentReadingDateLine10 */
NULL, /* PresentReadingDateLine11 */
NULL, /* PreviousReadingDateLine1 */
NULL, /* PreviousReadingDateLine2 */
NULL, /* PreviousReadingDateLine3 */
NULL, /* PreviousReadingDateLine4 */
NULL, /* PreviousReadingDateLine5 */
NULL, /* PreviousReadingDateLine6 */
NULL, /* PreviousReadingDateLine7 */
NULL, /* PreviousReadingDateLine8 */
NULL, /* PreviousReadingDateLine9 */
NULL, /* PreviousReadingDateLine10 */
NULL, /* PreviousReadingDateLine11 */
NULL, /* PresentReadingLine1 */
NULL, /* PresentReadingLine2 */
NULL, /* PresentReadingLine3 */
NULL, /* PresentReadingLine4 */
NULL, /* PresentReadingLine5 */
NULL, /* PresentReadingLine6 */
NULL, /* PresentReadingLine7 */
NULL, /* PresentReadingLine8 */
NULL, /* PresentReadingLine9 */
NULL, /* PresentReadingLine10 */
NULL, /* PresentReadingLine11 */
NULL, /* PreviousReadingLine1 */
NULL, /* PreviousReadingLine2 */
NULL, /* PreviousReadingLine3 */
NULL, /* PreviousReadingLine4 */
NULL, /* PreviousReadingLine5 */
NULL, /* PreviousReadingLine6 */
NULL, /* PreviousReadingLine7 */
NULL, /* PreviousReadingLine8 */
NULL, /* PreviousReadingLine9 */
NULL, /* PreviousReadingLine10 */
NULL, /* PreviousReadingLine11 */
NULL, /* UsageLine1 */
NULL, /* UsageLine2 */
NULL, /* UsageLine3 */
NULL, /* UsageLine4 */
NULL, /* UsageLine5 */
NULL, /* UsageLine6 */
NULL, /* UsageLine7 */
NULL, /* UsageLine8 */
NULL, /* UsageLine9 */
NULL, /* UsageLine10 */
NULL, /* UsageLine11 */
0, /* CurrentDaysLine1 */
0, /* CurrentDaysLine2 */
0, /* CurrentDaysLine3 */
0, /* CurrentDaysLine4 */
0, /* CurrentDaysLine5 */
0, /* CurrentDaysLine6 */
0, /* CurrentDaysLine7 */
0, /* CurrentDaysLine8 */
0, /* CurrentDaysLine9 */
0, /* CurrentDaysLine10 */
0, /* CurrentDaysLine11 */
0, /* LastMonthUsageLine1 */
0, /* LastMonthUsageLine2 */
0, /* LastMonthUsageLine3 */
0, /* LastMonthUsageLine4 */
0, /* LastMonthUsageLine5 */
0, /* LastMonthUsageLine6 */
0, /* LastMonthUsageLine7 */
0, /* LastMonthUsageLine8 */
0, /* LastMonthUsageLine9 */
0, /* LastMonthUsageLine10 */
0, /* LastMonthUsageLine11 */
0, /* LastMonthDaysLine1 */
0, /* LastMonthDaysLine2 */
0, /* LastMonthDaysLine3 */
0, /* LastMonthDaysLine4 */
0, /* LastMonthDaysLine5 */
0, /* LastMonthDaysLine6 */
0, /* LastMonthDaysLine7 */
0, /* LastMonthDaysLine8 */
0, /* LastMonthDaysLine9 */
0, /* LastMonthDaysLine10 */
0, /* LastMonthDaysLine11 */
0, /* SameMonthLastYearUsageLine1 */
0, /* SameMonthLastYearUsageLine2 */
0, /* SameMonthLastYearUsageLine3 */
0, /* SameMonthLastYearUsageLine4 */
0, /* SameMonthLastYearUsageLine5 */
0, /* SameMonthLastYearUsageLine6 */
0, /* SameMonthLastYearUsageLine7 */
0, /* SameMonthLastYearUsageLine8 */
0, /* SameMonthLastYearUsageLine9 */
0, /* SameMonthLastYearUsageLine10 */
0, /* SameMonthLastYearUsageLine11 */
0, /* SameMonthLastYearDaysLine1 */
0, /* SameMonthLastYearDaysLine2 */
0, /* SameMonthLastYearDaysLine3 */
0, /* SameMonthLastYearDaysLine4 */
0, /* SameMonthLastYearDaysLine5 */
0, /* SameMonthLastYearDaysLine6 */
0, /* SameMonthLastYearDaysLine7 */
0, /* SameMonthLastYearDaysLine8 */
0, /* SameMonthLastYearDaysLine9 */
0, /* SameMonthLastYearDaysLine10 */
0, /* SameMonthLastYearDaysLine11 */
NULL, /* ChargesLine1 */
NULL, /* ChargesLine2 */
NULL, /* ChargesLine3 */
NULL, /* ChargesLine4 */
NULL, /* ChargesLine5 */
NULL, /* ChargesLine6 */
NULL, /* ChargesLine7 */
NULL, /* ChargesLine8 */
NULL, /* ChargesLine9 */
NULL, /* ChargesLine10 */
NULL, /* ChargesLine11 */
NULL, /* TextLine1 */
NULL, /* TextLine2 */
NULL, /* TextLine3 */
NULL, /* TextLine4 */
NULL, /* TextLine5 */
NULL, /* TextLine6 */
NULL, /* TextLine7 */
NULL, /* TextLine8 */
NULL, /* TextLine9 */
NULL, /* TextLine10 */
NULL, /* TextLine11 */
NULL, /* BillDescription1 */
NULL, /* BillDescription2 */
NULL, /* BillDescription3 */
NULL, /* BillDescription4 */
NULL, /* BillDescription5 */
NULL, /* BillDescription6 */
NULL, /* BillDescription7 */
NULL, /* BillDescription8 */
NULL, /* BillDescription9 */
NULL, /* BillDescription10 */
NULL, /* BillDescription11 */
NULL, /* RateDescription1 */
NULL, /* RateDescription2 */
NULL, /* RateDescription3 */
NULL, /* RateDescription4 */
NULL, /* RateDescription5 */
NULL, /* RateDescription6 */
NULL, /* RateDescription7 */
NULL, /* RateDescription8 */
NULL, /* RateDescription9 */
NULL, /* RateDescription10 */
NULL, /* RateDescription11 */
0, /* Line1IsForMeteredService */
0, /* Line2IsForMeteredService */
0, /* Line3IsForMeteredService */
0, /* Line4IsForMeteredService */
0, /* Line5IsForMeteredService */
0, /* Line6IsForMeteredService */
0, /* Line7IsForMeteredService */
0, /* Line8IsForMeteredService */
0, /* Line9IsForMeteredService */
0, /* Line10IsForMeteredService */
0, /* Line11IsForMeteredService */
ChartReadingDate1,
ChartReadingDate2,
ChartReadingDate3,
ChartReadingDate4,
ChartReadingDate5,
ChartReadingDate6,
ChartReadingDate7,
ChartReadingDate8,
ChartReadingDate9,
ChartReadingDate10,
ChartReadingDate11,
ChartReadingDate12,
ChartReadingDate13,
ChartUsage1,
ChartUsage2,
ChartUsage3,
ChartUsage4,
ChartUsage5,
ChartUsage6,
ChartUsage7,
ChartUsage8,
ChartUsage9,
ChartUsage10,
ChartUsage11,
ChartUsage12,
ChartUsage13,
CurrentPeriodNumberofDays,
PreviousPeriodNumberofDays,
SameMonthLastYearNumberofDays,
ChartHighestUsage,
CustomerType,
Cycle,
0, /* PriorBalance */
0, /* PenaltyAmount */
0, /* PrintThisBill */
0, /* AmountDueTotal */
0, /* AmountDueLateTotal */
0, /* ServiceToTotalOnBillStub */
0, /* ServiceTotalOnBillStub */
AccountCommentLine1,
AccountCommentLine2,
0, /* HasFinalBill */
IsMemoBill, /* IsMemoBill */
DelinquentAmount, /* DelinquentAmount */
LastPaymentDate,
0, /* HasEstimatedReadings */
0, /* IncludesMultipleMeters */
MessageLine1,
MessageLine2,
MessageLine3,
MessageLine4,
PenaltyDate,
0 AS PostageRateType,
0 AS TrayNumber
FROM #TempPrintEntireBill AS Tmp
WHERE Tmp.AccountID = @AccountID
AND Tmp.BillNumber = 1
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while creating continuation bills in the #TempPrintEntireBill.',16,1)
RETURN(99)
END
SET @BillIndex = @BillIndex + 1
END /* goes with: WHILE (@BillIndex <= @NumberOfBills) */
END /* goes with: IF @NumberOfBills > 1 */
END /* goes with: IF @PrintContinuation = 0 */
SET @LineCounter = 1 /* used to determine which detail line to print; It starts at 1 and increments by 11
each time a new bill is ready to print. As it inserts lines into the #TempPrintEntireBill
it selects the appropriate TextLine from the #TempPrintBillServiceDetails */
SET @BillIndex = 1 /* reset the @BillIndex to the first bill */
WHILE (@NumberOfBills > 0)
BEGIN
SELECT @CodeLine1 = BillCode,
@MeterNumberLine1 = MeterNumber,
@PresentReadingDateLine1 = PresentReadingDate,
@PreviousReadingDateLine1 = PreviousReadingDate,
@PresentReadingLine1 = PresentReading,
@PreviousReadingLine1 = PreviousReading,
@UsageLine1 = Usage,
@CurrentDaysLine1 = CurrentDays,
@LastMonthUsageLine1 = LastMonthUsage,
@LastMonthDaysLine1 = LastMonthDays,
@SameMonthLastYearUsageLine1 = SameMonthLastYearUsage,
@SameMonthLastYearDaysLine1 = SameMonthLastYearDays,
@ChargesLine1 = BillAmount,
@TextLine1 = TextLine,
@BillDescription1 = BillDescription,
@RateDescription1 = RateDescription,
@Line1IsForMeteredService = IsForMeteredService,
/* if the meter number for the Bill card isn't set yet then update it with the meter number from the curent service */
@MeterNumberBillCard = (CASE
WHEN (@MeterNumberBillCard = '' OR @MeterNumberBillCard IS NULL) THEN MeterNumber
ELSE @MeterNumberBillCard
END)
FROM #TempPrintBillServiceDetails
WHERE AccountID = @AccountID
AND LineNumber = @LineCounter
SELECT @CodeLine2 = BillCode,
@MeterNumberLine2 = MeterNumber,
@PresentReadingDateLine2 = PresentReadingDate,
@PreviousReadingDateLine2 = PreviousReadingDate,
@PresentReadingLine2 = PresentReading,
@PreviousReadingLine2 = PreviousReading,
@UsageLine2 = Usage,
@CurrentDaysLine2 = CurrentDays,
@LastMonthUsageLine2 = LastMonthUsage,
@LastMonthDaysLine2 = LastMonthDays,
@SameMonthLastYearUsageLine2 = SameMonthLastYearUsage,
@SameMonthLastYearDaysLine2 = SameMonthLastYearDays,
@ChargesLine2 = BillAmount,
@TextLine2 = TextLine,
@BillDescription2 = BillDescription,
@RateDescription2 = RateDescription,
@Line2IsForMeteredService = IsForMeteredService,
/* if the meter number for the Bill card isn't set yet then update it with the meter number from the curent service */
@MeterNumberBillCard = (CASE
WHEN (@MeterNumberBillCard = '' OR @MeterNumberBillCard IS NULL) THEN MeterNumber
ELSE @MeterNumberBillCard
END)
FROM #TempPrintBillServiceDetails
WHERE AccountID = @AccountID
AND LineNumber = (@LineCounter + 1)
SELECT @CodeLine3 = BillCode,
@MeterNumberLine3 = MeterNumber,
@PresentReadingDateLine3 = PresentReadingDate,
@PreviousReadingDateLine3 = PreviousReadingDate,
@PresentReadingLine3 = PresentReading,
@PreviousReadingLine3 = PreviousReading,
@UsageLine3 = Usage,
@CurrentDaysLine3 = CurrentDays,
@LastMonthUsageLine3 = LastMonthUsage,
@LastMonthDaysLine3 = LastMonthDays,
@SameMonthLastYearUsageLine3 = SameMonthLastYearUsage,
@SameMonthLastYearDaysLine3 = SameMonthLastYearDays,
@ChargesLine3 = BillAmount,
@TextLine3 = TextLine,
@BillDescription3 = BillDescription,
@RateDescription3 = RateDescription,
@Line3IsForMeteredService = IsForMeteredService,
/* if the meter number for the Bill card isn't set yet then update it with the meter number from the curent service */
@MeterNumberBillCard = (CASE
WHEN (@MeterNumberBillCard = '' OR @MeterNumberBillCard IS NULL) THEN MeterNumber
ELSE @MeterNumberBillCard
END)
FROM #TempPrintBillServiceDetails
WHERE AccountID = @AccountID
AND LineNumber = (@LineCounter + 2)
SELECT @CodeLine4 = BillCode,
@MeterNumberLine4 = MeterNumber,
@PresentReadingDateLine4 = PresentReadingDate,
@PreviousReadingDateLine4 = PreviousReadingDate,
@PresentReadingLine4 = PresentReading,
@PreviousReadingLine4 = PreviousReading,
@UsageLine4 = Usage,
@CurrentDaysLine4 = CurrentDays,
@LastMonthUsageLine4 = LastMonthUsage,
@LastMonthDaysLine4 = LastMonthDays,
@SameMonthLastYearUsageLine4 = SameMonthLastYearUsage,
@SameMonthLastYearDaysLine4 = SameMonthLastYearDays,
@ChargesLine4 = BillAmount,
@TextLine4 = TextLine,
@BillDescription4 = BillDescription,
@RateDescription4 = RateDescription,
@Line4IsForMeteredService = IsForMeteredService,
/* if the meter number for the Bill card isn't set yet then update it with the meter number from the curent service */
@MeterNumberBillCard = (CASE
WHEN (@MeterNumberBillCard = '' OR @MeterNumberBillCard IS NULL) THEN MeterNumber
ELSE @MeterNumberBillCard
END)
FROM #TempPrintBillServiceDetails
WHERE AccountID = @AccountID
AND LineNumber = (@LineCounter + 3)
SELECT @CodeLine5 = BillCode,
@MeterNumberLine5 = MeterNumber,
@PresentReadingDateLine5 = PresentReadingDate,
@PreviousReadingDateLine5 = PreviousReadingDate,
@PresentReadingLine5 = PresentReading,
@PreviousReadingLine5 = PreviousReading,
@UsageLine5 = Usage,
@CurrentDaysLine5 = CurrentDays,
@LastMonthUsageLine5 = LastMonthUsage,
@LastMonthDaysLine5 = LastMonthDays,
@SameMonthLastYearUsageLine5 = SameMonthLastYearUsage,
@SameMonthLastYearDaysLine5 = SameMonthLastYearDays,
@ChargesLine5 = BillAmount,
@TextLine5 = TextLine,
@BillDescription5 = BillDescription,
@RateDescription5 = RateDescription,
@Line5IsForMeteredService = IsForMeteredService,
/* if the meter number for the Bill card isn't set yet then update it with the meter number from the curent service */
@MeterNumberBillCard = (CASE
WHEN (@MeterNumberBillCard = '' OR @MeterNumberBillCard IS NULL) THEN MeterNumber
ELSE @MeterNumberBillCard
END)
FROM #TempPrintBillServiceDetails
WHERE AccountID = @AccountID
AND LineNumber = (@LineCounter + 4)
SELECT @CodeLine6 = BillCode,
@MeterNumberLine6 = MeterNumber,
@PresentReadingDateLine6 = PresentReadingDate,
@PreviousReadingDateLine6 = PreviousReadingDate,
@PresentReadingLine6 = PresentReading,
@PreviousReadingLine6 = PreviousReading,
@UsageLine6 = Usage,
@CurrentDaysLine6 = CurrentDays,
@LastMonthUsageLine6 = LastMonthUsage,
@LastMonthDaysLine6 = LastMonthDays,
@SameMonthLastYearUsageLine6 = SameMonthLastYearUsage,
@SameMonthLastYearDaysLine6 = SameMonthLastYearDays,
@ChargesLine6 = BillAmount,
@TextLine6 = TextLine,
@BillDescription6 = BillDescription,
@RateDescription6 = RateDescription,
@Line6IsForMeteredService = IsForMeteredService,
/* if the meter number for the Bill card isn't set yet then update it with the meter number from the curent service */
@MeterNumberBillCard = (CASE
WHEN (@MeterNumberBillCard = '' OR @MeterNumberBillCard IS NULL) THEN MeterNumber
ELSE @MeterNumberBillCard
END)
FROM #TempPrintBillServiceDetails
WHERE AccountID = @AccountID
AND LineNumber = (@LineCounter + 5)
SELECT @CodeLine7 = BillCode,
@MeterNumberLine7 = MeterNumber,
@PresentReadingDateLine7 = PresentReadingDate,
@PreviousReadingDateLine7 = PreviousReadingDate,
@PresentReadingLine7 = PresentReading,
@PreviousReadingLine7 = PreviousReading,
@UsageLine7 = Usage,
@CurrentDaysLine7 = CurrentDays,
@LastMonthUsageLine7 = LastMonthUsage,
@LastMonthDaysLine7 = LastMonthDays,
@SameMonthLastYearUsageLine7 = SameMonthLastYearUsage,
@SameMonthLastYearDaysLine7 = SameMonthLastYearDays,
@ChargesLine7 = BillAmount,
@TextLine7 = TextLine,
@BillDescription7 = BillDescription,
@RateDescription7 = RateDescription,
@Line7IsForMeteredService = IsForMeteredService,
/* if the meter number for the Bill card isn't set yet then update it with the meter number from the curent service */
@MeterNumberBillCard = (CASE
WHEN (@MeterNumberBillCard = '' OR @MeterNumberBillCard IS NULL) THEN MeterNumber
ELSE @MeterNumberBillCard
END)
FROM #TempPrintBillServiceDetails
WHERE AccountID = @AccountID
AND LineNumber = (@LineCounter + 6)
SELECT @CodeLine8 = BillCode,
@MeterNumberLine8 = MeterNumber,
@PresentReadingDateLine8 = PresentReadingDate,
@PreviousReadingDateLine8 = PreviousReadingDate,
@PresentReadingLine8 = PresentReading,
@PreviousReadingLine8 = PreviousReading,
@UsageLine8 = Usage,
@CurrentDaysLine8 = CurrentDays,
@LastMonthUsageLine8 = LastMonthUsage,
@LastMonthDaysLine8 = LastMonthDays,
@SameMonthLastYearUsageLine8 = SameMonthLastYearUsage,
@SameMonthLastYearDaysLine8 = SameMonthLastYearDays,
@ChargesLine8 = BillAmount,
@TextLine8 = TextLine,
@BillDescription8 = BillDescription,
@RateDescription8 = RateDescription,
@Line8IsForMeteredService = IsForMeteredService,
/* if the meter number for the Bill card isn't set yet then update it with the meter number from the curent service */
@MeterNumberBillCard = (CASE
WHEN (@MeterNumberBillCard = '' OR @MeterNumberBillCard IS NULL) THEN MeterNumber
ELSE @MeterNumberBillCard
END)
FROM #TempPrintBillServiceDetails
WHERE AccountID = @AccountID
AND LineNumber = (@LineCounter + 7)
SELECT @CodeLine9 = BillCode,
@MeterNumberLine9 = MeterNumber,
@PresentReadingDateLine9 = PresentReadingDate,
@PreviousReadingDateLine9 = PreviousReadingDate,
@PresentReadingLine9 = PresentReading,
@PreviousReadingLine9 = PreviousReading,
@UsageLine9 = Usage,
@CurrentDaysLine9 = CurrentDays,
@LastMonthUsageLine9 = LastMonthUsage,
@LastMonthDaysLine9 = LastMonthDays,
@SameMonthLastYearUsageLine9 = SameMonthLastYearUsage,
@SameMonthLastYearDaysLine9 = SameMonthLastYearDays,
@ChargesLine9 = BillAmount,
@TextLine9 = TextLine,
@BillDescription9 = BillDescription,
@RateDescription9 = RateDescription,
@Line9IsForMeteredService = IsForMeteredService,
/* if the meter number for the Bill card isn't set yet then update it with the meter number from the curent service */
@MeterNumberBillCard = (CASE
WHEN (@MeterNumberBillCard = '' OR @MeterNumberBillCard IS NULL) THEN MeterNumber
ELSE @MeterNumberBillCard
END)
FROM #TempPrintBillServiceDetails
WHERE AccountID = @AccountID
AND LineNumber = (@LineCounter + 8)
SELECT @CodeLine10 = BillCode,
@MeterNumberLine10 = MeterNumber,
@PresentReadingDateLine10 = PresentReadingDate,
@PreviousReadingDateLine10 = PreviousReadingDate,
@PresentReadingLine10 = PresentReading,
@PreviousReadingLine10 = PreviousReading,
@UsageLine10 = Usage,
@CurrentDaysLine10 = CurrentDays,
@LastMonthUsageLine10 = LastMonthUsage,
@LastMonthDaysLine10 = LastMonthDays,
@SameMonthLastYearUsageLine10 = SameMonthLastYearUsage,
@SameMonthLastYearDaysLine10 = SameMonthLastYearDays,
@ChargesLine10 = BillAmount,
@TextLine10 = TextLine,
@BillDescription10 = BillDescription,
@RateDescription10 = RateDescription,
@Line10IsForMeteredService = IsForMeteredService,
/* if the meter number for the Bill card isn't set yet then update it with the meter number from the curent service */
@MeterNumberBillCard = (CASE
WHEN (@MeterNumberBillCard = '' OR @MeterNumberBillCard IS NULL) THEN MeterNumber
ELSE @MeterNumberBillCard
END)
FROM #TempPrintBillServiceDetails
WHERE AccountID = @AccountID
AND LineNumber = (@LineCounter + 9)
SELECT @CodeLine11 = BillCode,
@MeterNumberLine11 = MeterNumber,
@PresentReadingDateLine11 = PresentReadingDate,
@PreviousReadingDateLine11 = PreviousReadingDate,
@PresentReadingLine11 = PresentReading,
@PreviousReadingLine11 = PreviousReading,
@UsageLine11 = Usage,
@CurrentDaysLine11 = CurrentDays,
@LastMonthUsageLine11 = LastMonthUsage,
@LastMonthDaysLine11 = LastMonthDays,
@SameMonthLastYearUsageLine11 = SameMonthLastYearUsage,
@SameMonthLastYearDaysLine11 = SameMonthLastYearDays,
@ChargesLine11 = BillAmount,
@TextLine11 = TextLine,
@BillDescription11 = BillDescription,
@RateDescription11 = RateDescription,
@Line11IsForMeteredService = IsForMeteredService,
/* if the meter number for the Bill card isn't set yet then update it with the meter number from the curent service */
@MeterNumberBillCard = (CASE
WHEN (@MeterNumberBillCard = '' OR @MeterNumberBillCard IS NULL) THEN MeterNumber
ELSE @MeterNumberBillCard
END)
FROM #TempPrintBillServiceDetails
WHERE AccountID = @AccountID
AND LineNumber = (@LineCounter + 10)
IF (@PrintZeroCredit = 1 OR /* 1 = both zero and credit balances */
(@PrintZeroCredit = 3 AND @AmountDueTotal >= 0) OR /* 3 = zero balances */
(@PrintZeroCredit = 5 AND @AmountDueTotal <> 0) OR /* 5 = Credit balances */
(@PrintZeroCredit = 7 AND @AmountDueTotal > 0 AND @AmountDueTotal >= @MinimumBalance)) /* 7 = neither */
BEGIN
SET @PrintThisBill = 1
END
ELSE
BEGIN
SET @PrintThisBill = 0
END
UPDATE #TempPrintEntireBill
SET CodeLine1 = @CodeLine1,
CodeLine2 = @CodeLine2,
CodeLine3 = @CodeLine3,
CodeLine4 = @CodeLine4,
CodeLine5 = @CodeLine5,
CodeLine6 = @CodeLine6,
CodeLine7 = @CodeLine7,
CodeLine8 = @CodeLine8,
CodeLine9 = @CodeLine9,
CodeLine10 = @CodeLine10,
CodeLine11 = @CodeLine11,
MeterNumberLine1 = ISNULL(@MeterNumberLine1,''),
MeterNumberLine2 = ISNULL(@MeterNumberLine2,''),
MeterNumberLine3 = ISNULL(@MeterNumberLine3,''),
MeterNumberLine4 = ISNULL(@MeterNumberLine4,''),
MeterNumberLine5 = ISNULL(@MeterNumberLine5,''),
MeterNumberLine6 = ISNULL(@MeterNumberLine6,''),
MeterNumberLine7 = ISNULL(@MeterNumberLine7,''),
MeterNumberLine8 = ISNULL(@MeterNumberLine8,''),
MeterNumberLine9 = ISNULL(@MeterNumberLine9,''),
MeterNumberLine10 = ISNULL(@MeterNumberLine10,''),
MeterNumberLine11 = ISNULL(@MeterNumberLine11,''),
PresentReadingDateLine1 = @PresentReadingDateLine1,
PresentReadingDateLine2 = @PresentReadingDateLine2,
PresentReadingDateLine3 = @PresentReadingDateLine3,
PresentReadingDateLine4 = @PresentReadingDateLine4,
PresentReadingDateLine5 = @PresentReadingDateLine5,
PresentReadingDateLine6 = @PresentReadingDateLine6,
PresentReadingDateLine7 = @PresentReadingDateLine7,
PresentReadingDateLine8 = @PresentReadingDateLine8,
PresentReadingDateLine9 = @PresentReadingDateLine9,
PresentReadingDateLine10 = @PresentReadingDateLine10,
PresentReadingDateLine11 = @PresentReadingDateLine11,
PreviousReadingDateLine1 = @PreviousReadingDateLine1,
PreviousReadingDateLine2 = @PreviousReadingDateLine2,
PreviousReadingDateLine3 = @PreviousReadingDateLine3,
PreviousReadingDateLine4 = @PreviousReadingDateLine4,
PreviousReadingDateLine5 = @PreviousReadingDateLine5,
PreviousReadingDateLine6 = @PreviousReadingDateLine6,
PreviousReadingDateLine7 = @PreviousReadingDateLine7,
PreviousReadingDateLine8 = @PreviousReadingDateLine8,
PreviousReadingDateLine9 = @PreviousReadingDateLine9,
PreviousReadingDateLine10 = @PreviousReadingDateLine10,
PreviousReadingDateLine11 = @PreviousReadingDateLine11,
PresentReadingLine1 = @PresentReadingLine1,
PresentReadingLine2 = @PresentReadingLine2,
PresentReadingLine3 = @PresentReadingLine3,
PresentReadingLine4 = @PresentReadingLine4,
PresentReadingLine5 = @PresentReadingLine5,
PresentReadingLine6 = @PresentReadingLine6,
PresentReadingLine7 = @PresentReadingLine7,
PresentReadingLine8 = @PresentReadingLine8,
PresentReadingLine9 = @PresentReadingLine9,
PresentReadingLine10 = @PresentReadingLine10,
PresentReadingLine11 = @PresentReadingLine11,
PreviousReadingLine1 = @PreviousReadingLine1,
PreviousReadingLine2 = @PreviousReadingLine2,
PreviousReadingLine3 = @PreviousReadingLine3,
PreviousReadingLine4 = @PreviousReadingLine4,
PreviousReadingLine5 = @PreviousReadingLine5,
PreviousReadingLine6 = @PreviousReadingLine6,
PreviousReadingLine7 = @PreviousReadingLine7,
PreviousReadingLine8 = @PreviousReadingLine8,
PreviousReadingLine9 = @PreviousReadingLine9,
PreviousReadingLine10 = @PreviousReadingLine10,
PreviousReadingLine11 = @PreviousReadingLine11,
UsageLine1 = @UsageLine1,
UsageLine2 = @UsageLine2,
UsageLine3 = @UsageLine3,
UsageLine4 = @UsageLine4,
UsageLine5 = @UsageLine5,
UsageLine6 = @UsageLine6,
UsageLine7 = @UsageLine7,
UsageLine8 = @UsageLine8,
UsageLine9 = @UsageLine9,
UsageLine10 = @UsageLine10,
UsageLine11 = @UsageLine11,
CurrentDaysLine1 = @CurrentDaysLine1,
CurrentDaysLine2 = @CurrentDaysLine2,
CurrentDaysLine3 = @CurrentDaysLine3,
CurrentDaysLine4 = @CurrentDaysLine4,
CurrentDaysLine5 = @CurrentDaysLine5,
CurrentDaysLine6 = @CurrentDaysLine6,
CurrentDaysLine7 = @CurrentDaysLine7,
CurrentDaysLine8 = @CurrentDaysLine8,
CurrentDaysLine9 = @CurrentDaysLine9,
CurrentDaysLine10 = @CurrentDaysLine10,
CurrentDaysLine11 = @CurrentDaysLine11,
LastMonthUsageLine1 = @LastMonthUsageLine1,
LastMonthUsageLine2 = @LastMonthUsageLine2,
LastMonthUsageLine3 = @LastMonthUsageLine3,
LastMonthUsageLine4 = @LastMonthUsageLine4,
LastMonthUsageLine5 = @LastMonthUsageLine5,
LastMonthUsageLine6 = @LastMonthUsageLine6,
LastMonthUsageLine7 = @LastMonthUsageLine7,
LastMonthUsageLine8 = @LastMonthUsageLine8,
LastMonthUsageLine9 = @LastMonthUsageLine9,
LastMonthUsageLine10 = @LastMonthUsageLine10,
LastMonthUsageLine11 = @LastMonthUsageLine11,
LastMonthDaysLine1 = @LastMonthDaysLine1,
LastMonthDaysLine2 = @LastMonthDaysLine2,
LastMonthDaysLine3 = @LastMonthDaysLine3,
LastMonthDaysLine4 = @LastMonthDaysLine4,
LastMonthDaysLine5 = @LastMonthDaysLine5,
LastMonthDaysLine6 = @LastMonthDaysLine6,
LastMonthDaysLine7 = @LastMonthDaysLine7,
LastMonthDaysLine8 = @LastMonthDaysLine8,
LastMonthDaysLine9 = @LastMonthDaysLine9,
LastMonthDaysLine10 = @LastMonthDaysLine10,
LastMonthDaysLine11 = @LastMonthDaysLine11,
SameMonthLastYearUsageLine1 = @SameMonthLastYearUsageLine1,
SameMonthLastYearUsageLine2 = @SameMonthLastYearUsageLine2,
SameMonthLastYearUsageLine3 = @SameMonthLastYearUsageLine3,
SameMonthLastYearUsageLine4 = @SameMonthLastYearUsageLine4,
SameMonthLastYearUsageLine5 = @SameMonthLastYearUsageLine5,
SameMonthLastYearUsageLine6 = @SameMonthLastYearUsageLine6,
SameMonthLastYearUsageLine7 = @SameMonthLastYearUsageLine7,
SameMonthLastYearUsageLine8 = @SameMonthLastYearUsageLine8,
SameMonthLastYearUsageLine9 = @SameMonthLastYearUsageLine9,
SameMonthLastYearUsageLine10 = @SameMonthLastYearUsageLine10,
SameMonthLastYearUsageLine11 = @SameMonthLastYearUsageLine11,
SameMonthLastYearDaysLine1 = @SameMonthLastYearDaysLine1,
SameMonthLastYearDaysLine2 = @SameMonthLastYearDaysLine2,
SameMonthLastYearDaysLine3 = @SameMonthLastYearDaysLine3,
SameMonthLastYearDaysLine4 = @SameMonthLastYearDaysLine4,
SameMonthLastYearDaysLine5 = @SameMonthLastYearDaysLine5,
SameMonthLastYearDaysLine6 = @SameMonthLastYearDaysLine6,
SameMonthLastYearDaysLine7 = @SameMonthLastYearDaysLine7,
SameMonthLastYearDaysLine8 = @SameMonthLastYearDaysLine8,
SameMonthLastYearDaysLine9 = @SameMonthLastYearDaysLine9,
SameMonthLastYearDaysLine10 = @SameMonthLastYearDaysLine10,
SameMonthLastYearDaysLine11 = @SameMonthLastYearDaysLine11,
ChargesLine1 = @ChargesLine1,
ChargesLine2 = @ChargesLine2,
ChargesLine3 = @ChargesLine3,
ChargesLine4 = @ChargesLine4,
ChargesLine5 = @ChargesLine5,
ChargesLine6 = @ChargesLine6,
ChargesLine7 = @ChargesLine7,
ChargesLine8 = @ChargesLine8,
ChargesLine9 = @ChargesLine9,
ChargesLine10 = @ChargesLine10,
ChargesLine11 = @ChargesLine11,
TextLine1 = @TextLine1,
TextLine2 = @TextLine2,
TextLine3 = @TextLine3,
TextLine4 = @TextLine4,
TextLine5 = @TextLine5,
TextLine6 = @TextLine6,
TextLine7 = @TextLine7,
TextLine8 = @TextLine8,
TextLine9 = @TextLine9,
TextLine10 = @TextLine10,
TextLine11 = @TextLine11,
BillDescription1 = @BillDescription1,
BillDescription2 = @BillDescription2,
BillDescription3 = @BillDescription3,
BillDescription4 = @BillDescription4,
BillDescription5 = @BillDescription5,
BillDescription6 = @BillDescription6,
BillDescription7 = @BillDescription7,
BillDescription8 = @BillDescription8,
BillDescription9 = @BillDescription9,
BillDescription10 = @BillDescription10,
BillDescription11 = @BillDescription11,
RateDescription1 = @RateDescription1,
RateDescription2 = @RateDescription2,
RateDescription3 = @RateDescription3,
RateDescription4 = @RateDescription4,
RateDescription5 = @RateDescription5,
RateDescription6 = @RateDescription6,
RateDescription7 = @RateDescription7,
RateDescription8 = @RateDescription8,
RateDescription9 = @RateDescription9,
RateDescription10 = @RateDescription10,
RateDescription11 = @RateDescription11,
Line1IsForMeteredService = @Line1IsForMeteredService,
Line2IsForMeteredService = @Line2IsForMeteredService,
Line3IsForMeteredService = @Line3IsForMeteredService,
Line4IsForMeteredService = @Line4IsForMeteredService,
Line5IsForMeteredService = @Line5IsForMeteredService,
Line6IsForMeteredService = @Line6IsForMeteredService,
Line7IsForMeteredService = @Line7IsForMeteredService,
Line8IsForMeteredService = @Line8IsForMeteredService,
Line9IsForMeteredService = @Line9IsForMeteredService,
Line10IsForMeteredService = @Line10IsForMeteredService,
Line11IsForMeteredService = @Line11IsForMeteredService,
PriorBalance = ISNULL(@PriorBalance, 0),
PenaltyAmount = ISNULL(@PenaltyGrandTotal, 0),
PrintThisBill = @PrintThisBill,
AmountDueTotal = ISNULL(@AmountDueTotal, 0),
AmountDueLateTotal = ISNULL(@AmountDueLateTotal, 0),
ServiceCodeToTotalOnBillStub = @ServiceCodeToTotalOnBillStub,
ServiceTotalOnBillStub = @ServiceTotalOnBillStub,
HasFinalBill = @HasFinalBill,
HasEstimatedReadings = @HasEstimatedReadings,
IncludesMultipleMeters = @IncludesMultipleMeters,
MeterNumber = ISNULL(@MeterNumberBillCard,'')
WHERE BillNumber = @BillIndex
AND AccountID = @AccountID
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while updating records in the #TempPrintEntireBill.',16,1)
RETURN(99)
END
SET @LineCounter = @LineCounter + 11 /* prep for the next set of 11 lines */
SET @NumberOfBills = @NumberOfBills - 1
SET @BillIndex = @BillIndex + 1
/* wipe out the values before creating the next bill */
SET @CodeLine1 = NULL
SET @CodeLine2 = NULL
SET @CodeLine3 = NULL
SET @CodeLine4 = NULL
SET @CodeLine5 = NULL
SET @CodeLine6 = NULL
SET @CodeLine7 = NULL
SET @CodeLine8 = NULL
SET @CodeLine9 = NULL
SET @CodeLine10 = NULL
SET @CodeLine11 = NULL
SET @MeterNumberLine1 = ''
SET @MeterNumberLine2 = ''
SET @MeterNumberLine3 = ''
SET @MeterNumberLine4 = ''
SET @MeterNumberLine5 = ''
SET @MeterNumberLine6 = ''
SET @MeterNumberLine7 = ''
SET @MeterNumberLine8 = ''
SET @MeterNumberLine9 = ''
SET @MeterNumberLine10 = ''
SET @MeterNumberLine11 = ''
SET @PresentReadingDateLine1 = NULL
SET @PresentReadingDateLine2 = NULL
SET @PresentReadingDateLine3 = NULL
SET @PresentReadingDateLine4 = NULL
SET @PresentReadingDateLine5 = NULL
SET @PresentReadingDateLine6 = NULL
SET @PresentReadingDateLine7 = NULL
SET @PresentReadingDateLine8 = NULL
SET @PresentReadingDateLine9 = NULL
SET @PresentReadingDateLine10 = NULL
SET @PresentReadingDateLine11 = NULL
SET @PreviousReadingDateLine1 = NULL
SET @PreviousReadingDateLine2 = NULL
SET @PreviousReadingDateLine3 = NULL
SET @PreviousReadingDateLine4 = NULL
SET @PreviousReadingDateLine5 = NULL
SET @PreviousReadingDateLine6 = NULL
SET @PreviousReadingDateLine7 = NULL
SET @PreviousReadingDateLine8 = NULL
SET @PreviousReadingDateLine9 = NULL
SET @PreviousReadingDateLine10 = NULL
SET @PreviousReadingDateLine11 = NULL
SET @PresentReadingLine1 = NULL
SET @PresentReadingLine2 = NULL
SET @PresentReadingLine3 = NULL
SET @PresentReadingLine4 = NULL
SET @PresentReadingLine5 = NULL
SET @PresentReadingLine6 = NULL
SET @PresentReadingLine7 = NULL
SET @PresentReadingLine8 = NULL
SET @PresentReadingLine9 = NULL
SET @PresentReadingLine10 = NULL
SET @PresentReadingLine11 = NULL
SET @PreviousReadingLine1 = NULL
SET @PreviousReadingLine2 = NULL
SET @PreviousReadingLine3 = NULL
SET @PreviousReadingLine4 = NULL
SET @PreviousReadingLine5 = NULL
SET @PreviousReadingLine6 = NULL
SET @PreviousReadingLine7 = NULL
SET @PreviousReadingLine8 = NULL
SET @PreviousReadingLine9 = NULL
SET @PreviousReadingLine10 = NULL
SET @PreviousReadingLine11 = NULL
SET @UsageLine1 = NULL
SET @UsageLine2 = NULL
SET @UsageLine3 = NULL
SET @UsageLine4 = NULL
SET @UsageLine5 = NULL
SET @UsageLine6 = NULL
SET @UsageLine7 = NULL
SET @UsageLine8 = NULL
SET @UsageLine9 = NULL
SET @UsageLine10 = NULL
SET @UsageLine11 = NULL
SET @CurrentDaysLine1 = NULL
SET @CurrentDaysLine2 = NULL
SET @CurrentDaysLine3 = NULL
SET @CurrentDaysLine4 = NULL
SET @CurrentDaysLine5 = NULL
SET @CurrentDaysLine6 = NULL
SET @CurrentDaysLine7 = NULL
SET @CurrentDaysLine8 = NULL
SET @CurrentDaysLine9 = NULL
SET @CurrentDaysLine10 = NULL
SET @CurrentDaysLine11 = NULL
SET @LastMonthUsageLine1 = NULL
SET @LastMonthUsageLine2 = NULL
SET @LastMonthUsageLine3 = NULL
SET @LastMonthUsageLine4 = NULL
SET @LastMonthUsageLine5 = NULL
SET @LastMonthUsageLine6 = NULL
SET @LastMonthUsageLine7 = NULL
SET @LastMonthUsageLine8 = NULL
SET @LastMonthUsageLine9 = NULL
SET @LastMonthUsageLine10 = NULL
SET @LastMonthUsageLine11 = NULL
SET @LastMonthDaysLine1 = NULL
SET @LastMonthDaysLine2 = NULL
SET @LastMonthDaysLine3 = NULL
SET @LastMonthDaysLine4 = NULL
SET @LastMonthDaysLine5 = NULL
SET @LastMonthDaysLine6 = NULL
SET @LastMonthDaysLine7 = NULL
SET @LastMonthDaysLine8 = NULL
SET @LastMonthDaysLine9 = NULL
SET @LastMonthDaysLine10 = NULL
SET @LastMonthDaysLine11 = NULL
SET @SameMonthLastYearUsageLine1 = NULL
SET @SameMonthLastYearUsageLine2 = NULL
SET @SameMonthLastYearUsageLine3 = NULL
SET @SameMonthLastYearUsageLine4 = NULL
SET @SameMonthLastYearUsageLine5 = NULL
SET @SameMonthLastYearUsageLine6 = NULL
SET @SameMonthLastYearUsageLine7 = NULL
SET @SameMonthLastYearUsageLine8 = NULL
SET @SameMonthLastYearUsageLine9 = NULL
SET @SameMonthLastYearUsageLine10 = NULL
SET @SameMonthLastYearUsageLine11 = NULL
SET @SameMonthLastYearDaysLine1 = NULL
SET @SameMonthLastYearDaysLine2 = NULL
SET @SameMonthLastYearDaysLine3 = NULL
SET @SameMonthLastYearDaysLine4 = NULL
SET @SameMonthLastYearDaysLine5 = NULL
SET @SameMonthLastYearDaysLine6 = NULL
SET @SameMonthLastYearDaysLine7 = NULL
SET @SameMonthLastYearDaysLine8 = NULL
SET @SameMonthLastYearDaysLine9 = NULL
SET @SameMonthLastYearDaysLine10 = NULL
SET @SameMonthLastYearDaysLine11 = NULL
SET @ChargesLine1 = NULL
SET @ChargesLine2 = NULL
SET @ChargesLine3 = NULL
SET @ChargesLine4 = NULL
SET @ChargesLine5 = NULL
SET @ChargesLine6 = NULL
SET @ChargesLine7 = NULL
SET @ChargesLine8 = NULL
SET @ChargesLine9 = NULL
SET @ChargesLine10 = NULL
SET @ChargesLine11 = NULL
SET @TextLine1 = NULL
SET @TextLine2 = NULL
SET @TextLine3 = NULL
SET @TextLine4 = NULL
SET @TextLine5 = NULL
SET @TextLine6 = NULL
SET @TextLine7 = NULL
SET @TextLine8 = NULL
SET @TextLine9 = NULL
SET @TextLine10 = NULL
SET @TextLine11 = NULL
SET @BillDescription1 = NULL
SET @BillDescription2 = NULL
SET @BillDescription3 = NULL
SET @BillDescription4 = NULL
SET @BillDescription5 = NULL
SET @BillDescription6 = NULL
SET @BillDescription7 = NULL
SET @BillDescription8 = NULL
SET @BillDescription9 = NULL
SET @BillDescription10 = NULL
SET @BillDescription11 = NULL
SET @RateDescription1 = NULL
SET @RateDescription2 = NULL
SET @RateDescription3 = NULL
SET @RateDescription4 = NULL
SET @RateDescription5 = NULL
SET @RateDescription6 = NULL
SET @RateDescription7 = NULL
SET @RateDescription8 = NULL
SET @RateDescription9 = NULL
SET @RateDescription10 = NULL
SET @RateDescription11 = NULL
SET @Line1IsForMeteredService = NULL
SET @Line2IsForMeteredService = NULL
SET @Line3IsForMeteredService = NULL
SET @Line4IsForMeteredService = NULL
SET @Line5IsForMeteredService = NULL
SET @Line6IsForMeteredService = NULL
SET @Line7IsForMeteredService = NULL
SET @Line8IsForMeteredService = NULL
SET @Line9IsForMeteredService = NULL
SET @Line10IsForMeteredService = NULL
SET @Line11IsForMeteredService = NULL
END /* ties to: WHILE (@NumberOfBills > 0) */
SET @NumberOfAccounts = @NumberOfAccounts - 1
SET @PreviousAccountID = @AccountID
SET @BillIndex = 0
SET @PriorBalance = 0
SET @PenaltyGrandTotal = 0
SET @AmountDueTotal = 0
SET @AmountDueLateTotal = 0
SET @ServiceTotalOnBillStub = 0
SET @HasFinalBill = 0
SET @HasEstimatedReadings = 0
SET @IncludesMultipleMeters = 0
SET @MeterNumberBillCard = ''
END /* ties to: WHILE (@NumberOfAccounts > 0) */
/* If there are any bills that need to be sent to the landlord insert them now. */
IF EXISTS (SELECT AccountID
FROM #TempPrintEntireBill AS Tmp
WHERE IsTenant = 1
AND (SendBillTo <> 1 OR SendDelinquentBillTo <> 1)) /* 1 = Tenant */
BEGIN
INSERT INTO #TempPrintEntireBill
(BillNumber,
NumberofBills,
CycleID,
AccountID,
AccountsRoute,
AccountsAccountNumber,
AccountsSequence,
AccountsInCareOf,
AccountsSalutation,
AccountsFirstName,
AccountsMiddleName,
AccountsLastName,
AccountsNameSuffix,
AccountsDBAName,
AccountsCarrierRoute,
ServiceNumber,
ServiceName,
BillingAddress,
BillingCity,
BillingState,
BillingZip,
ForeignBillingAddress,
DataPointBarCode,
BarCodeCheckDigit,
ZipCodeSummaryZip,
ZipCodeSummaryFiveDigitZip,
IsBarcodedBill,
IsTenant,
IsLandlord,
LandlordAccountID,
LandlordName,
LandlordDBAName,
LandlordInCareOf,
LandlordAddress,
LandlordCity,
LandlordState,
LandlordZip,
ForeignLandlordAddress,
LandlordCarrierRoute,
LandlordDataPointBarCode,
LandlordBarCodeCheckDigit,
LandlordBillIsBarcoded,
SendBillTo,
SendDelinquentBillTo,
UsesBudgets,
UseBankDrafts,
RemainingUnappliedCashWhenComputed,
PreviousReadingDate,
PresentReadingDate,
CodeLine1,
CodeLine2,
CodeLine3,
CodeLine4,
CodeLine5,
CodeLine6,
CodeLine7,
CodeLine8,
CodeLine9,
CodeLine10,
CodeLine11,
MeterNumberLine1,
MeterNumberLine2,
MeterNumberLine3,
MeterNumberLine4,
MeterNumberLine5,
MeterNumberLine6,
MeterNumberLine7,
MeterNumberLine8,
MeterNumberLine9,
MeterNumberLine10,
MeterNumberLine11,
PresentReadingDateLine1,
PresentReadingDateLine2,
PresentReadingDateLine3,
PresentReadingDateLine4,
PresentReadingDateLine5,
PresentReadingDateLine6,
PresentReadingDateLine7,
PresentReadingDateLine8,
PresentReadingDateLine9,
PresentReadingDateLine10,
PresentReadingDateLine11,
PreviousReadingDateLine1,
PreviousReadingDateLine2,
PreviousReadingDateLine3,
PreviousReadingDateLine4,
PreviousReadingDateLine5,
PreviousReadingDateLine6,
PreviousReadingDateLine7,
PreviousReadingDateLine8,
PreviousReadingDateLine9,
PreviousReadingDateLine10,
PreviousReadingDateLine11,
PresentReadingLine1,
PresentReadingLine2,
PresentReadingLine3,
PresentReadingLine4,
PresentReadingLine5,
PresentReadingLine6,
PresentReadingLine7,
PresentReadingLine8,
PresentReadingLine9,
PresentReadingLine10,
PresentReadingLine11,
PreviousReadingLine1,
PreviousReadingLine2,
PreviousReadingLine3,
PreviousReadingLine4,
PreviousReadingLine5,
PreviousReadingLine6,
PreviousReadingLine7,
PreviousReadingLine8,
PreviousReadingLine9,
PreviousReadingLine10,
PreviousReadingLine11,
UsageLine1,
UsageLine2,
UsageLine3,
UsageLine4,
UsageLine5,
UsageLine6,
UsageLine7,
UsageLine8,
UsageLine9,
UsageLine10,
UsageLine11,
CurrentDaysLine1,
CurrentDaysLine2,
CurrentDaysLine3,
CurrentDaysLine4,
CurrentDaysLine5,
CurrentDaysLine6,
CurrentDaysLine7,
CurrentDaysLine8,
CurrentDaysLine9,
CurrentDaysLine10,
CurrentDaysLine11,
LastMonthUsageLine1,
LastMonthUsageLine2,
LastMonthUsageLine3,
LastMonthUsageLine4,
LastMonthUsageLine5,
LastMonthUsageLine6,
LastMonthUsageLine7,
LastMonthUsageLine8,
LastMonthUsageLine9,
LastMonthUsageLine10,
LastMonthUsageLine11,
LastMonthDaysLine1,
LastMonthDaysLine2,
LastMonthDaysLine3,
LastMonthDaysLine4,
LastMonthDaysLine5,
LastMonthDaysLine6,
LastMonthDaysLine7,
LastMonthDaysLine8,
LastMonthDaysLine9,
LastMonthDaysLine10,
LastMonthDaysLine11,
SameMonthLastYearUsageLine1,
SameMonthLastYearUsageLine2,
SameMonthLastYearUsageLine3,
SameMonthLastYearUsageLine4,
SameMonthLastYearUsageLine5,
SameMonthLastYearUsageLine6,
SameMonthLastYearUsageLine7,
SameMonthLastYearUsageLine8,
SameMonthLastYearUsageLine9,
SameMonthLastYearUsageLine10,
SameMonthLastYearUsageLine11,
SameMonthLastYearDaysLine1,
SameMonthLastYearDaysLine2,
SameMonthLastYearDaysLine3,
SameMonthLastYearDaysLine4,
SameMonthLastYearDaysLine5,
SameMonthLastYearDaysLine6,
SameMonthLastYearDaysLine7,
SameMonthLastYearDaysLine8,
SameMonthLastYearDaysLine9,
SameMonthLastYearDaysLine10,
SameMonthLastYearDaysLine11,
ChargesLine1,
ChargesLine2,
ChargesLine3,
ChargesLine4,
ChargesLine5,
ChargesLine6,
ChargesLine7,
ChargesLine8,
ChargesLine9,
ChargesLine10,
ChargesLine11,
TextLine1,
TextLine2,
TextLine3,
TextLine4,
TextLine5,
TextLine6,
TextLine7,
TextLine8,
TextLine9,
TextLine10,
TextLine11,
BillDescription1,
BillDescription2,
BillDescription3,
BillDescription4,
BillDescription5,
BillDescription6,
BillDescription7,
BillDescription8,
BillDescription9,
BillDescription10,
BillDescription11,
RateDescription1,
RateDescription2,
RateDescription3,
RateDescription4,
RateDescription5,
RateDescription6,
RateDescription7,
RateDescription8,
RateDescription9,
RateDescription10,
RateDescription11,
Line1IsForMeteredService,
Line2IsForMeteredService,
Line3IsForMeteredService,
Line4IsForMeteredService,
Line5IsForMeteredService,
Line6IsForMeteredService,
Line7IsForMeteredService,
Line8IsForMeteredService,
Line9IsForMeteredService,
Line10IsForMeteredService,
Line11IsForMeteredService,
ChartReadingDate1,
ChartReadingDate2,
ChartReadingDate3,
ChartReadingDate4,
ChartReadingDate5,
ChartReadingDate6,
ChartReadingDate7,
ChartReadingDate8,
ChartReadingDate9,
ChartReadingDate10,
ChartReadingDate11,
ChartReadingDate12,
ChartReadingDate13,
ChartUsage1,
ChartUsage2,
ChartUsage3,
ChartUsage4,
ChartUsage5,
ChartUsage6,
ChartUsage7,
ChartUsage8,
ChartUsage9,
ChartUsage10,
ChartUsage11,
ChartUsage12,
ChartUsage13,
CurrentPeriodNumberofDays,
PreviousPeriodNumberofDays,
SameMonthLastYearNumberofDays,
ChartHighestUsage,
CustomerType,
Cycle,
PriorBalance,
PenaltyAmount,
PrintThisBill,
AmountDueTotal,
AmountDueLateTotal,
ServiceCodeToTotalOnBillStub,
ServiceTotalOnBillStub,
AccountCommentLine1,
AccountCommentLine2,
HasFinalBill,
IsMemoBill,
DelinquentAmount,
LastPaymentDate,
HasEstimatedReadings,
IncludesMultipleMeters,
MessageLine1,
MessageLine2,
MessageLine3,
MessageLine4,
PenaltyDate,
PostageRateType,
TrayNumber)
SELECT BillNumber * -1, /* Use a negative Bill Number as an easy flag for excluding cloned bills when calculating the total bill that prints at the end of the recordset. The proper solution would be to add another field, but I'm being lazy. JFK 5/6/04 */
NumberofBills,
CycleID,
AccountID,
AccountsRoute,
AccountsAccountNumber,
AccountsSequence,
(CASE
WHEN LTRIM(RTRIM(ISNULL(LandlordInCareOf, ''))) <> '' THEN LandlordInCareOf
ELSE LEFT(LTRIM(RTRIM((ISNULL(AccountsFirstName, '') + ' ' + ISNULL(AccountsMiddleName, '') + ' ' + ISNULL(AccountsLastName, '')))), 25)
END), /* AccountsInCareOf */
'', /* AccountsSalutation */
'', /* AccountsFirstName */
'', /* AccountsMiddleName */
LandlordName, /* AccountsLastName */
'', /* AccountsNameSuffix */
LandlordDBAName, /* AccountsDBAName */
LandlordCarrierRoute, /* AccountsCarrierRoute */
ServiceNumber,
ServiceName,
LandlordAddress, /* BillingAddress */
LandlordCity, /* BillingCity */
LandlordState, /* BillingState */
LandlordZip, /* BillingZip */
ForeignLandlordAddress, /* ForeignBillingAddress */
LandlordDataPointBarCode, /* DataPointBarCode */
LandlordBarCodeCheckDigit, /* BarCodeCheckDigit */
ISNULL(LandlordZip, '00000'), /* ZipCodeSummaryZip */
SPACE(5 - LEN(LTRIM(RTRIM(LEFT(ISNULL(LandlordZip, '00000'), 5))))) + LTRIM(RTRIM(LEFT(ISNULL(LandlordZip, '00000'), 5))), /* ZipCodeSummaryFiveDigitZip */
LandlordBillIsBarcoded AS IsBarcodedBill,
0, /* IsTenant */
1, /* IsLandlord */
LandlordAccountID,
LandlordName,
LandlordDBAName,
LandlordInCareOf,
LandlordAddress,
LandlordCity,
LandlordState,
LandlordZip,
ForeignLandlordAddress,
LandlordCarrierRoute,
LandlordDataPointBarCode,
LandlordBarCodeCheckDigit,
LandlordBillIsBarcoded,
SendBillTo,
SendDelinquentBillTo,
UsesBudgets,
UseBankDrafts,
RemainingUnappliedCashWhenComputed,
PreviousReadingDate, /* Previous Reading Date */
PresentReadingDate, /* Present Reading Date */
CodeLine1,
CodeLine2,
CodeLine3,
CodeLine4,
CodeLine5,
CodeLine6,
CodeLine7,
CodeLine8,
CodeLine9,
CodeLine10,
CodeLine11,
MeterNumberLine1,
MeterNumberLine2,
MeterNumberLine3,
MeterNumberLine4,
MeterNumberLine5,
MeterNumberLine6,
MeterNumberLine7,
MeterNumberLine8,
MeterNumberLine9,
MeterNumberLine10,
MeterNumberLine11,
PresentReadingDateLine1,
PresentReadingDateLine2,
PresentReadingDateLine3,
PresentReadingDateLine4,
PresentReadingDateLine5,
PresentReadingDateLine6,
PresentReadingDateLine7,
PresentReadingDateLine8,
PresentReadingDateLine9,
PresentReadingDateLine10,
PresentReadingDateLine11,
PreviousReadingDateLine1,
PreviousReadingDateLine2,
PreviousReadingDateLine3,
PreviousReadingDateLine4,
PreviousReadingDateLine5,
PreviousReadingDateLine6,
PreviousReadingDateLine7,
PreviousReadingDateLine8,
PreviousReadingDateLine9,
PreviousReadingDateLine10,
PreviousReadingDateLine11,
PresentReadingLine1,
PresentReadingLine2,
PresentReadingLine3,
PresentReadingLine4,
PresentReadingLine5,
PresentReadingLine6,
PresentReadingLine7,
PresentReadingLine8,
PresentReadingLine9,
PresentReadingLine10,
PresentReadingLine11,
PreviousReadingLine1,
PreviousReadingLine2,
PreviousReadingLine3,
PreviousReadingLine4,
PreviousReadingLine5,
PreviousReadingLine6,
PreviousReadingLine7,
PreviousReadingLine8,
PreviousReadingLine9,
PreviousReadingLine10,
PreviousReadingLine11,
UsageLine1,
UsageLine2,
UsageLine3,
UsageLine4,
UsageLine5,
UsageLine6,
UsageLine7,
UsageLine8,
UsageLine9,
UsageLine10,
UsageLine11,
CurrentDaysLine1,
CurrentDaysLine2,
CurrentDaysLine3,
CurrentDaysLine4,
CurrentDaysLine5,
CurrentDaysLine6,
CurrentDaysLine7,
CurrentDaysLine8,
CurrentDaysLine9,
CurrentDaysLine10,
CurrentDaysLine11,
LastMonthUsageLine1,
LastMonthUsageLine2,
LastMonthUsageLine3,
LastMonthUsageLine4,
LastMonthUsageLine5,
LastMonthUsageLine6,
LastMonthUsageLine7,
LastMonthUsageLine8,
LastMonthUsageLine9,
LastMonthUsageLine10,
LastMonthUsageLine11,
LastMonthDaysLine1,
LastMonthDaysLine2,
LastMonthDaysLine3,
LastMonthDaysLine4,
LastMonthDaysLine5,
LastMonthDaysLine6,
LastMonthDaysLine7,
LastMonthDaysLine8,
LastMonthDaysLine9,
LastMonthDaysLine10,
LastMonthDaysLine11,
SameMonthLastYearUsageLine1,
SameMonthLastYearUsageLine2,
SameMonthLastYearUsageLine3,
SameMonthLastYearUsageLine4,
SameMonthLastYearUsageLine5,
SameMonthLastYearUsageLine6,
SameMonthLastYearUsageLine7,
SameMonthLastYearUsageLine8,
SameMonthLastYearUsageLine9,
SameMonthLastYearUsageLine10,
SameMonthLastYearUsageLine11,
SameMonthLastYearDaysLine1,
SameMonthLastYearDaysLine2,
SameMonthLastYearDaysLine3,
SameMonthLastYearDaysLine4,
SameMonthLastYearDaysLine5,
SameMonthLastYearDaysLine6,
SameMonthLastYearDaysLine7,
SameMonthLastYearDaysLine8,
SameMonthLastYearDaysLine9,
SameMonthLastYearDaysLine10,
SameMonthLastYearDaysLine11,
ChargesLine1,
ChargesLine2,
ChargesLine3,
ChargesLine4,
ChargesLine5,
ChargesLine6,
ChargesLine7,
ChargesLine8,
ChargesLine9,
ChargesLine10,
ChargesLine11,
TextLine1,
TextLine2,
TextLine3,
TextLine4,
TextLine5,
TextLine6,
TextLine7,
TextLine8,
TextLine9,
TextLine10,
TextLine11,
BillDescription1,
BillDescription2,
BillDescription3,
BillDescription4,
BillDescription5,
BillDescription6,
BillDescription7,
BillDescription8,
BillDescription9,
BillDescription10,
BillDescription11,
RateDescription1,
RateDescription2,
RateDescription3,
RateDescription4,
RateDescription5,
RateDescription6,
RateDescription7,
RateDescription8,
RateDescription9,
RateDescription10,
RateDescription11,
Line1IsForMeteredService,
Line2IsForMeteredService,
Line3IsForMeteredService,
Line4IsForMeteredService,
Line5IsForMeteredService,
Line6IsForMeteredService,
Line7IsForMeteredService,
Line8IsForMeteredService,
Line9IsForMeteredService,
Line10IsForMeteredService,
Line11IsForMeteredService,
ChartReadingDate1,
ChartReadingDate2,
ChartReadingDate3,
ChartReadingDate4,
ChartReadingDate5,
ChartReadingDate6,
ChartReadingDate7,
ChartReadingDate8,
ChartReadingDate9,
ChartReadingDate10,
ChartReadingDate11,
ChartReadingDate12,
ChartReadingDate13,
ChartUsage1,
ChartUsage2,
ChartUsage3,
ChartUsage4,
ChartUsage5,
ChartUsage6,
ChartUsage7,
ChartUsage8,
ChartUsage9,
ChartUsage10,
ChartUsage11,
ChartUsage12,
ChartUsage13,
CurrentPeriodNumberofDays,
PreviousPeriodNumberofDays,
SameMonthLastYearNumberofDays,
ChartHighestUsage,
CustomerType,
Cycle,
PriorBalance,
PenaltyAmount,
PrintThisBill,
AmountDueTotal,
AmountDueLateTotal,
ServiceCodeToTotalOnBillStub,
ServiceTotalOnBillStub,
AccountCommentLine1,
AccountCommentLine2,
HasFinalBill,
IsMemoBill,
DelinquentAmount,
LastPaymentDate,
HasEstimatedReadings,
IncludesMultipleMeters,
MessageLine1,
MessageLine2,
MessageLine3,
MessageLine4,
PenaltyDate,
0 AS PostageRateType,
0 AS TrayNumber
FROM #TempPrintEntireBill AS Tmp
WHERE IsTenant = 1
AND (SendBillTo <> 1 /* 1 = Tenant; i.e. they are sending the bills to the landlord or both the tenant and landlord. */
OR (SendDelinquentBillTo <> 1 AND (DelinquentAmount > 0
/* Include accounts that exceed the days since last payment option in delinquent
options or if they have never made a payment (the LastPaymentDate value
will return as null). */
AND (@DelinquentDaysSinceLastPayment = 0
OR (@DelinquentDaysSinceLastPayment <> 0
AND (LastPaymentDate > @DelinquentCutoffDate AND NOT LastPaymentDate IS NULL))
)
)
))
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while inserting the landlord bills in the #TempPrintEntireBill.',16,1)
RETURN(99)
END
/* Remove any tenant bills that are being sent to the landlord only. */
DELETE
FROM #TempPrintEntireBill
WHERE IsTenant = 1
AND (SendBillTo = 3 /* 3 = landlord i.e. they are sending the bills to the landlord and not the tenant. */
OR (SendDelinquentBillTo = 3 AND (DelinquentAmount > 0
/* Include accounts that exceed the days since last payment option in delinquent
options or if they have never made a payment (the LastPaymentDate value
will return as null). */
AND (@DelinquentDaysSinceLastPayment = 0
OR (@DelinquentDaysSinceLastPayment <> 0
AND (LastPaymentDate > @DelinquentCutoffDate AND NOT LastPaymentDate IS NULL))
)
)
))
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while removing the tenant bills in the #TempPrintEntireBill.',16,1)
RETURN(99)
END
END
/********************************** ZIPCODE SUMMARY **********************************/
/* Indexes for speed - create here so initial inserts will be faster. */
CREATE INDEX idxTempPrintEntireBillPrintThisBill
ON #TempPrintEntireBill (PrintThisBill)
CREATE INDEX idxTempPrintEntireBillUsesBudgets
ON #TempPrintEntireBill (UsesBudgets)
IF @ForZipCodeSummaryReport = 1 OR (@ForZipCodeSummaryReport <> 1 AND @BillSortOrder = 1)
BEGIN
CREATE INDEX idxTempPrintEntireBillIsBarcodedBill
ON #TempPrintEntireBill (IsBarcodedBill)
CREATE INDEX idxTempPrintEntireBillZipCodeSummaryFiveDigitZip
ON #TempPrintEntireBill (ZipCodeSummaryFiveDigitZip)
IF @SortWithFinalBillsFirst <> 1
BEGIN
SET @TotalFinalBillsNotMailed = 0
END
ELSE
BEGIN
SET @TotalFinalBillsNotMailed = ISNULL((SELECT COUNT(*)
FROM #TempPrintEntireBill AS Bills
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.HasFinalBill = 1), 0)
END
IF (SELECT COUNT(*)
FROM #TempPrintEntireBill AS Bills
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))) < @MinimumNumberOfBarcodedBillsNeededForDiscount
BEGIN
INSERT INTO #ZipcodeSummary
(Zipcode,
CarrierRoute,
ThreeDigitZipcode,
AADCId,
AADCNumber,
AADCCity,
AADCState,
RateType,
RateTypeString,
IsDetailRecord,
IsZipcodeMixedAADCRecord,
NumberOfBills,
IsReportTotalsRecord,
TotalCarrierRouteBills,
TotalNumberOfBillsInFiveDigitZips,
TotalNumberOfBillsInThreeDigitZips,
TotalAADCBills,
TotalMixedAADCBills,
TotalPresortedNonautomationBills,
TotalSinglePieceBills,
TotalFinalBillsNotMailed,
TotalBillsMailed,
TotalNumberOfBills,
NumberOfOneFootTraysUsed,
NumberOfTwoFootTraysUsed,
CarrierRouteRateAmount,
FiveDigitRateAmount,
ThreeDigitRateAmount,
AADCRateAmount,
MixedAADCRateAmount,
PresortedNonautomationRateAmount,
SinglePieceRateAmount,
TotalPostageAmount)
SELECT NULL AS Zipcode,
NULL AS CarrierRoute,
NULL AS ThreeDigitZipcode,
0 AS AADCId,
NULL AS AADCNumber,
NULL AS AADCCity,
NULL AS AADCState,
(CASE
WHEN COUNT(*) >= @MinimumNumberOfBarcodedBillsNeededForDiscount THEN 6 /* Pre-Sorted Non-automation */
ELSE 7 /* Single-Piece */
END) AS RateType,
(CASE
WHEN COUNT(*) >= @MinimumNumberOfBarcodedBillsNeededForDiscount THEN 'Presorted Non-Automation'
ELSE 'Non-Automation Single Piece'
END) AS RateTypeString,
0 AS IsDetailRecord,
0 AS IsZipcodeMixedAADCRecord,
COUNT(*) AS NumberOfBills,
0 AS IsReportTotalsRecord,
0 AS TotalCarrierRouteBills,
0 AS TotalNumberOfBillsInFiveDigitZips,
0 AS TotalNumberOfBillsInThreeDigitZips,
0 AS TotalAADCBills,
0 AS TotalMixedAADCBills,
0 AS TotalPresortedNonautomationBills,
0 AS TotalSinglePieceBills,
0 AS TotalFinalBillsNotMailed,
0 AS TotalBillsMailed,
0 AS TotalNumberOfBills,
0 AS NumberOfOneFootTraysUsed,
0 AS NumberOfTwoFootTraysUsed,
0 AS CarrierRouteRateAmount,
0 AS FiveDigitRateAmount,
0 AS ThreeDigitRateAmount,
0 AS AADCRateAmount,
0 AS MixedAADCRateAmount,
0 AS PresortedNonautomationRateAmount,
0 AS SinglePieceRateAmount,
0 AS TotalPostageAmount
FROM #TempPrintEntireBill AS Bills
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while inserting all bills as presorted non-automation or single piece.',16,1)
RETURN(99)
END
UPDATE #TempPrintEntireBill
SET PostageRateType = (SELECT MAX(ZipcodeSummary.RateType)
FROM #ZipcodeSummary AS ZipcodeSummary)
FROM #TempPrintEntireBill AS Bills
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while updating the bill postage rate type when all bills are presorted non-automation or single piece.',16,1)
RETURN(99)
END
IF @PrintBreakdownForNonbarcodedBills = 1
BEGIN
/* Insert the pre-sorted automation or single piece detail records per zipcode. */
INSERT INTO #ZipcodeSummary
(Zipcode,
CarrierRoute,
ThreeDigitZipcode,
AADCId,
AADCNumber,
AADCCity,
AADCState,
RateType,
RateTypeString,
IsDetailRecord,
IsZipcodeMixedAADCRecord,
NumberOfBills,
IsReportTotalsRecord,
TotalCarrierRouteBills,
TotalNumberOfBillsInFiveDigitZips,
TotalNumberOfBillsInThreeDigitZips,
TotalAADCBills,
TotalMixedAADCBills,
TotalPresortedNonautomationBills,
TotalSinglePieceBills,
TotalFinalBillsNotMailed,
TotalBillsMailed,
TotalNumberOfBills,
NumberOfOneFootTraysUsed,
NumberOfTwoFootTraysUsed,
CarrierRouteRateAmount,
FiveDigitRateAmount,
ThreeDigitRateAmount,
AADCRateAmount,
MixedAADCRateAmount,
PresortedNonautomationRateAmount,
SinglePieceRateAmount,
TotalPostageAmount)
SELECT Bills.ZipCodeSummaryFiveDigitZip AS Zipcode,
NULL AS CarrierRoute,
NULL AS ThreeDigitZipcode,
0 AS AADCId,
NULL AS AADCNumber,
NULL AS AADCCity,
NULL AS AADCState,
(SELECT MAX(ZipcodeSummary.RateType)
FROM #ZipcodeSummary AS ZipcodeSummary) AS RateType,
(CASE
WHEN (SELECT MAX(ZipcodeSummary.RateType)
FROM #ZipcodeSummary AS ZipcodeSummary) = 6 THEN 'Presorted Non-Automation'
ELSE 'Non-Automation Single Piece'
END) AS RateTypeString,
1 AS IsDetailRecord,
0 AS IsZipcodeMixedAADCRecord,
COUNT(*) AS NumberOfBills,
0 AS IsReportTotalsRecord,
0 AS TotalCarrierRouteBills,
0 AS TotalNumberOfBillsInFiveDigitZips,
0 AS TotalNumberOfBillsInThreeDigitZips,
0 AS TotalAADCBills,
0 AS TotalMixedAADCBills,
0 AS TotalPresortedNonautomationBills,
0 AS TotalSinglePieceBills,
0 AS TotalFinalBillsNotMailed,
0 AS TotalBillsMailed,
0 AS TotalNumberOfBills,
0 AS NumberOfOneFootTraysUsed,
0 AS NumberOfTwoFootTraysUsed,
0 AS CarrierRouteRateAmount,
0 AS FiveDigitRateAmount,
0 AS ThreeDigitRateAmount,
0 AS AADCRateAmount,
0 AS MixedAADCRateAmount,
0 AS PresortedNonautomationRateAmount,
0 AS SinglePieceRateAmount,
0 AS TotalPostageAmount
FROM #TempPrintEntireBill AS Bills
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
GROUP BY Bills.ZipCodeSummaryFiveDigitZip
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while inserting the details per zipcode when all bills are presorted non-automation or single piece.',16,1)
RETURN(99)
END
END
INSERT INTO #ZipcodeSummary
(Zipcode,
CarrierRoute,
ThreeDigitZipcode,
AADCId,
AADCNumber,
AADCCity,
AADCState,
RateType,
RateTypeString,
IsDetailRecord,
IsZipcodeMixedAADCRecord,
NumberOfBills,
IsReportTotalsRecord,
TotalCarrierRouteBills,
TotalNumberOfBillsInFiveDigitZips,
TotalNumberOfBillsInThreeDigitZips,
TotalAADCBills,
TotalMixedAADCBills,
TotalPresortedNonautomationBills,
TotalSinglePieceBills,
TotalFinalBillsNotMailed,
TotalBillsMailed,
TotalNumberOfBills,
NumberOfOneFootTraysUsed,
NumberOfTwoFootTraysUsed,
CarrierRouteRateAmount,
FiveDigitRateAmount,
ThreeDigitRateAmount,
AADCRateAmount,
MixedAADCRateAmount,
PresortedNonautomationRateAmount,
SinglePieceRateAmount,
TotalPostageAmount)
SELECT NULL AS Zipcode,
NULL AS CarrierRoute,
NULL AS ThreeDigitZipcode,
0 AS AADCId,
NULL AS AADCNumber,
NULL AS AADCCity,
NULL AS AADCState,
0 AS RateType,
NULL AS RateTypeString,
0 AS IsDetailRecord,
0 AS IsZipcodeMixedAADCRecord,
0 AS NumberOfBills,
1 AS IsReportTotalsRecord,
0 AS TotalCarrierRouteBills,
0 AS TotalNumberOfBillsInFiveDigitZips,
0 AS TotalNumberOfBillsInThreeDigitZips,
0 AS TotalAADCBills,
0 AS TotalMixedAADCBills,
(CASE
WHEN ZipcodeSummary.RateType = 6 THEN ZipcodeSummary.NumberOfBills
ELSE 0
END) AS TotalPresortedNonautomationBills,
(CASE
WHEN ZipcodeSummary.RateType = 7 THEN ZipcodeSummary.NumberOfBills
ELSE 0
END) AS TotalSinglePieceBills,
@TotalFinalBillsNotMailed AS TotalFinalBillsNotMailed,
ZipcodeSummary.NumberOfBills AS TotalBillsMailed,
ZipcodeSummary.NumberOfBills + @TotalFinalBillsNotMailed AS TotalNumberOfBills,
0 AS NumberOfOneFootTraysUsed,
0 AS NumberOfTwoFootTraysUsed,
0 AS CarrierRouteRateAmount,
0 AS FiveDigitRateAmount,
0 AS ThreeDigitRateAmount,
0 AS AADCRateAmount,
0 AS MixedAADCRateAmount,
0 AS PresortedNonautomationRateAmount,
0 AS SinglePieceRateAmount,
0 AS TotalPostageAmount
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ZipcodeSummary.IsDetailRecord <> 1
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while inserting the report totals when all bills are presorted non-automation or single piece.',16,1)
RETURN(99)
END
END
ELSE
BEGIN
IF @UseCarrierRouteSortation = 1
BEGIN
CREATE INDEX idxTempPrintEntireBillCarrierRoute
ON #TempPrintEntireBill (AccountsCarrierRoute)
/* Insert all 5 digit zipcodes with their carrier routes for barcoded bills. */
INSERT INTO #ZipcodeSummary
(Zipcode,
CarrierRoute,
ThreeDigitZipcode,
AADCId,
AADCNumber,
AADCCity,
AADCState,
RateType,
RateTypeString,
IsDetailRecord,
IsZipcodeMixedAADCRecord,
NumberOfBills,
IsReportTotalsRecord,
TotalCarrierRouteBills,
TotalNumberOfBillsInFiveDigitZips,
TotalNumberOfBillsInThreeDigitZips,
TotalAADCBills,
TotalMixedAADCBills,
TotalPresortedNonautomationBills,
TotalSinglePieceBills,
TotalFinalBillsNotMailed,
TotalBillsMailed,
TotalNumberOfBills,
NumberOfOneFootTraysUsed,
NumberOfTwoFootTraysUsed,
CarrierRouteRateAmount,
FiveDigitRateAmount,
ThreeDigitRateAmount,
AADCRateAmount,
MixedAADCRateAmount,
PresortedNonautomationRateAmount,
SinglePieceRateAmount,
TotalPostageAmount)
SELECT Bills.ZipCodeSummaryFiveDigitZip AS Zipcode,
Bills.AccountsCarrierRoute AS CarrierRoute,
NULL AS ThreeDigitZipcode,
0 AS AADCId,
NULL AS AADCNumber,
NULL AS AADCCity,
NULL AS AADCState,
1 AS RateType, /* Automation Carrier Route */
'Automation Carrier Route' AS RateTypeString,
0 AS IsDetailRecord,
0 AS IsZipcodeMixedAADCRecord,
COUNT(*) AS NumberOfBills,
0 AS IsReportTotalsRecord,
0 AS TotalCarrierRouteBills,
0 AS TotalNumberOfBillsInFiveDigitZips,
0 AS TotalNumberOfBillsInThreeDigitZips,
0 AS TotalAADCBills,
0 AS TotalMixedAADCBills,
0 AS TotalPresortedNonautomationBills,
0 AS TotalSinglePieceBills,
0 AS TotalFinalBillsNotMailed,
0 AS TotalBillsMailed,
0 AS TotalNumberOfBills,
0 AS NumberOfOneFootTraysUsed,
0 AS NumberOfTwoFootTraysUsed,
0 AS CarrierRouteRateAmount,
0 AS FiveDigitRateAmount,
0 AS ThreeDigitRateAmount,
0 AS AADCRateAmount,
0 AS MixedAADCRateAmount,
0 AS PresortedNonautomationRateAmount,
0 AS SinglePieceRateAmount,
0 AS TotalPostageAmount
FROM #TempPrintEntireBill AS Bills
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND LTRIM(RTRIM(ISNULL(Bills.AccountsCarrierRoute, ''))) <> ''
GROUP BY Bills.ZipCodeSummaryFiveDigitZip, Bills.AccountsCarrierRoute
HAVING COUNT(*) >= @ZipcodeSummaryMinimumBarcodedBillsInGroup
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while summarizing the barcoded bills per carrier route.',16,1)
RETURN(99)
END
UPDATE #TempPrintEntireBill
SET PostageRateType = 1
FROM #TempPrintEntireBill AS Bills JOIN #ZipcodeSummary AS ZipcodeSummary ON Bills.ZipCodeSummaryFiveDigitZip = ZipcodeSummary.Zipcode AND Bills.AccountsCarrierRoute = ZipcodeSummary.CarrierRoute
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND LTRIM(RTRIM(ISNULL(Bills.AccountsCarrierRoute, ''))) <> ''
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while updating the bill postage rate type for carrier route pieces.',16,1)
RETURN(99)
END
END /* IF @UseCarrierRouteSortation = 1 */
/* Insert all 5 digit zipcode records for barcoded bills. */
INSERT INTO #ZipcodeSummary
(Zipcode,
CarrierRoute,
ThreeDigitZipcode,
AADCId,
AADCNumber,
AADCCity,
AADCState,
RateType,
RateTypeString,
IsDetailRecord,
IsZipcodeMixedAADCRecord,
NumberOfBills,
IsReportTotalsRecord,
TotalCarrierRouteBills,
TotalNumberOfBillsInFiveDigitZips,
TotalNumberOfBillsInThreeDigitZips,
TotalAADCBills,
TotalMixedAADCBills,
TotalPresortedNonautomationBills,
TotalSinglePieceBills,
TotalFinalBillsNotMailed,
TotalBillsMailed,
TotalNumberOfBills,
NumberOfOneFootTraysUsed,
NumberOfTwoFootTraysUsed,
CarrierRouteRateAmount,
FiveDigitRateAmount,
ThreeDigitRateAmount,
AADCRateAmount,
MixedAADCRateAmount,
PresortedNonautomationRateAmount,
SinglePieceRateAmount,
TotalPostageAmount)
SELECT Bills.ZipCodeSummaryFiveDigitZip AS Zipcode,
NULL AS CarrierRoute,
NULL AS ThreeDigitZipcode,
0 AS AADCId,
NULL AS AADCNumber,
NULL AS AADCCity,
NULL AS AADCState,
2 AS RateType, /* 5-digit zip */
'Automation 5-Digit Zip' AS RateTypeString,
0 AS IsDetailRecord,
0 AS IsZipcodeMixedAADCRecord,
COUNT(*) AS NumberOfBills,
0 AS IsReportTotalsRecord,
0 AS TotalCarrierRouteBills,
0 AS TotalNumberOfBillsInFiveDigitZips,
0 AS TotalNumberOfBillsInThreeDigitZips,
0 AS TotalAADCBills,
0 AS TotalMixedAADCBills,
0 AS TotalPresortedNonautomationBills,
0 AS TotalSinglePieceBills,
0 AS TotalFinalBillsNotMailed,
0 AS TotalBillsMailed,
0 AS TotalNumberOfBills,
0 AS NumberOfOneFootTraysUsed,
0 AS NumberOfTwoFootTraysUsed,
0 AS CarrierRouteRateAmount,
0 AS FiveDigitRateAmount,
0 AS ThreeDigitRateAmount,
0 AS AADCRateAmount,
0 AS MixedAADCRateAmount,
0 AS PresortedNonautomationRateAmount,
0 AS SinglePieceRateAmount,
0 AS TotalPostageAmount
FROM #TempPrintEntireBill AS Bills
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND (@UseCarrierRouteSortation <> 1
OR (@UseCarrierRouteSortation = 1
AND NOT EXISTS(SELECT ZipcodeSummary.CarrierRoute
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ZipcodeSummary.RateType = 1 /* Automation Carrier Route */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip
AND ZipcodeSummary.CarrierRoute = LTRIM(RTRIM(ISNULL(Bills.AccountsCarrierRoute, ''))))))
GROUP BY Bills.ZipCodeSummaryFiveDigitZip
HAVING COUNT(*) >= @ZipcodeSummaryMinimumBarcodedBillsInGroup
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while summarizing the barcoded bills per 5-digit zip.',16,1)
RETURN(99)
END
UPDATE #TempPrintEntireBill
SET PostageRateType = 2
FROM #TempPrintEntireBill AS Bills JOIN #ZipcodeSummary AS ZipcodeSummary ON Bills.ZipCodeSummaryFiveDigitZip = ZipcodeSummary.Zipcode AND ZipcodeSummary.RateType = 2
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND Bills.PostageRateType = 0
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while updating the bill postage rate type for 5-digit zip pieces.',16,1)
RETURN(99)
END
/* Insert all 3 digit zipcode records for barcoded bills where the individual 5 digit zipcode
does not meet the minimum number of bills by itself. */
INSERT INTO #ZipcodeSummary
(Zipcode,
CarrierRoute,
ThreeDigitZipcode,
AADCId,
AADCNumber,
AADCCity,
AADCState,
RateType,
RateTypeString,
IsDetailRecord,
IsZipcodeMixedAADCRecord,
NumberOfBills,
IsReportTotalsRecord,
TotalCarrierRouteBills,
TotalNumberOfBillsInFiveDigitZips,
TotalNumberOfBillsInThreeDigitZips,
TotalAADCBills,
TotalMixedAADCBills,
TotalPresortedNonautomationBills,
TotalSinglePieceBills,
TotalFinalBillsNotMailed,
TotalBillsMailed,
TotalNumberOfBills,
NumberOfOneFootTraysUsed,
NumberOfTwoFootTraysUsed,
CarrierRouteRateAmount,
FiveDigitRateAmount,
ThreeDigitRateAmount,
AADCRateAmount,
MixedAADCRateAmount,
PresortedNonautomationRateAmount,
SinglePieceRateAmount,
TotalPostageAmount)
SELECT LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3) + 'xx' AS Zipcode,
NULL AS CarrierRoute,
LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3) + 'xx' AS ThreeDigitZipcode,
0 AS AADCId,
NULL AS AADCNumber,
NULL AS AADCCity,
NULL AS AADCState,
3 AS RateType, /* 3-digit zip */
'Automation 3-Digit Zip' AS RateTypeString,
0 AS IsDetailRecord,
0 AS IsZipcodeMixedAADCRecord,
COUNT(*) AS NumberOfBills,
0 AS IsReportTotalsRecord,
0 AS TotalCarrierRouteBills,
0 AS TotalNumberOfBillsInFiveDigitZips,
0 AS TotalNumberOfBillsInThreeDigitZips,
0 AS TotalAADCBills,
0 AS TotalMixedAADCBills,
0 AS TotalPresortedNonautomationBills,
0 AS TotalSinglePieceBills,
0 AS TotalFinalBillsNotMailed,
0 AS TotalBillsMailed,
0 AS TotalNumberOfBills,
0 AS NumberOfOneFootTraysUsed,
0 AS NumberOfTwoFootTraysUsed,
0 AS CarrierRouteRateAmount,
0 AS FiveDigitRateAmount,
0 AS ThreeDigitRateAmount,
0 AS AADCRateAmount,
0 AS MixedAADCRateAmount,
0 AS PresortedNonautomationRateAmount,
0 AS SinglePieceRateAmount,
0 AS TotalPostageAmount
FROM #TempPrintEntireBill AS Bills
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND NOT EXISTS(SELECT ZipcodeSummary.CarrierRoute
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ((ZipcodeSummary.RateType = 1 /* Carrier Route */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip
AND ZipcodeSummary.CarrierRoute = LTRIM(RTRIM(ISNULL(Bills.AccountsCarrierRoute, ''))))
OR (ZipcodeSummary.RateType = 2 /* 5-digit zip */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip)))
GROUP BY LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3) + 'xx'
HAVING COUNT(*) >= @ZipcodeSummaryMinimumBarcodedBillsInGroup
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while summarizing the barcoded bills per three digit zip.',16,1)
RETURN(99)
END
UPDATE #TempPrintEntireBill
SET PostageRateType = 3
FROM #TempPrintEntireBill AS Bills JOIN #ZipcodeSummary AS ZipcodeSummary ON LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3) = LEFT(ZipcodeSummary.Zipcode, 3) AND ZipcodeSummary.RateType = 3
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND Bills.PostageRateType = 0
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while updating the bill postage rate type for 3-digit zip pieces.',16,1)
RETURN(99)
END
IF @SummarizeReport <> 1
BEGIN
/* Insert the 5-digit detail records per 3-digit zip if a detail report is selected. */
INSERT INTO #ZipcodeSummary
(Zipcode,
CarrierRoute,
ThreeDigitZipcode,
AADCId,
AADCNumber,
AADCCity,
AADCState,
RateType,
RateTypeString,
IsDetailRecord,
IsZipcodeMixedAADCRecord,
NumberOfBills,
IsReportTotalsRecord,
TotalCarrierRouteBills,
TotalNumberOfBillsInFiveDigitZips,
TotalNumberOfBillsInThreeDigitZips,
TotalAADCBills,
TotalMixedAADCBills,
TotalPresortedNonautomationBills,
TotalSinglePieceBills,
TotalFinalBillsNotMailed,
TotalBillsMailed,
TotalNumberOfBills,
NumberOfOneFootTraysUsed,
NumberOfTwoFootTraysUsed,
CarrierRouteRateAmount,
FiveDigitRateAmount,
ThreeDigitRateAmount,
AADCRateAmount,
MixedAADCRateAmount,
PresortedNonautomationRateAmount,
SinglePieceRateAmount,
TotalPostageAmount)
SELECT Bills.ZipCodeSummaryFiveDigitZip AS Zipcode,
NULL AS CarrierRoute,
LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3) + 'xx' AS ThreeDigitZipcode,
0 AS AADCId,
NULL AS AADCNumber,
NULL AS AADCCity,
NULL AS AADCState,
3 AS RateType, /* 3-digit zip */
'Automation 3-Digit Zip' AS RateTypeString,
1 AS IsDetailRecord,
0 AS IsZipcodeMixedAADCRecord,
COUNT(*) AS NumberOfBills,
0 AS IsReportTotalsRecord,
0 AS TotalCarrierRouteBills,
0 AS TotalNumberOfBillsInFiveDigitZips,
0 AS TotalNumberOfBillsInThreeDigitZips,
0 AS TotalAADCBills,
0 AS TotalMixedAADCBills,
0 AS TotalPresortedNonautomationBills,
0 AS TotalSinglePieceBills,
0 AS TotalFinalBillsNotMailed,
0 AS TotalBillsMailed,
0 AS TotalNumberOfBills,
0 AS NumberOfOneFootTraysUsed,
0 AS NumberOfTwoFootTraysUsed,
0 AS CarrierRouteRateAmount,
0 AS FiveDigitRateAmount,
0 AS ThreeDigitRateAmount,
0 AS AADCRateAmount,
0 AS MixedAADCRateAmount,
0 AS PresortedNonautomationRateAmount,
0 AS SinglePieceRateAmount,
0 AS TotalPostageAmount
FROM #TempPrintEntireBill AS Bills
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND NOT EXISTS(SELECT ZipcodeSummary.CarrierRoute
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ((ZipcodeSummary.RateType = 1 /* Carrier Route */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip
AND ZipcodeSummary.CarrierRoute = LTRIM(RTRIM(ISNULL(Bills.AccountsCarrierRoute, ''))))
OR (ZipcodeSummary.RateType = 2 /* 5-digit zip */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip)))
AND EXISTS (SELECT ZipcodeSummary.CarrierRoute
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ZipcodeSummary.RateType = 3 /* 3-digit zip */
AND LEFT(ZipcodeSummary.ThreeDigitZipcode, 3) = LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3))
GROUP BY Bills.ZipCodeSummaryFiveDigitZip
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while summarizing the 5-digit detail barcoded bills per 3-digit zip.',16,1)
RETURN(99)
END
END /* IF @SummarizeReport <> 1 */
/*
We found out that the criteria for disregarding the minimum number of pieces per group is not based on
whether its in the local AADC, but whether or not the post office that they're taking their mail to is
an SCF. If it is an SCF, then all mail within the SCF zipcodes get the AADC rate regardless of how many
there are. To do this though, we would have to add the SCFs and their zips. Until we have someone that
does this who needs it, we will ignore this special case.
IF LTRIM(RTRIM(ISNULL(@ZipcodeOfPostOfficeBillsAreMailedFrom, ''))) = ''
BEGIN
SET @LocalAADCId = 0
END
ELSE
BEGIN
SET @LocalAADCId = ISNULL((SELECT AADCDestinationZipcodes.AADCId
FROM AADCDestinationZipcodes
WHERE AADCDestinationZipcodes.Deleted = 0
AND AADCDestinationZipcodes.ThreeDigitZipcode = LEFT(@ZipcodeOfPostOfficeBillsAreMailedFrom, 3)), 0)
END
*/
/* Insert all AADC records for barcoded bills where the minimum number of bills has not yet been met. */
INSERT INTO #ZipcodeSummary
(Zipcode,
CarrierRoute,
ThreeDigitZipcode,
AADCId,
AADCNumber,
AADCCity,
AADCState,
RateType,
RateTypeString,
IsDetailRecord,
IsZipcodeMixedAADCRecord,
NumberOfBills,
IsReportTotalsRecord,
TotalCarrierRouteBills,
TotalNumberOfBillsInFiveDigitZips,
TotalNumberOfBillsInThreeDigitZips,
TotalAADCBills,
TotalMixedAADCBills,
TotalPresortedNonautomationBills,
TotalSinglePieceBills,
TotalFinalBillsNotMailed,
TotalBillsMailed,
TotalNumberOfBills,
NumberOfOneFootTraysUsed,
NumberOfTwoFootTraysUsed,
CarrierRouteRateAmount,
FiveDigitRateAmount,
ThreeDigitRateAmount,
AADCRateAmount,
MixedAADCRateAmount,
PresortedNonautomationRateAmount,
SinglePieceRateAmount,
TotalPostageAmount)
SELECT NULL AS Zipcode,
NULL AS CarrierRoute,
NULL AS ThreeDigitZipcode,
AADCs.AADCId AS AADCId,
AADCs.AADCNumber AS AADCNumber,
AADCs.City AS AADCCity,
AADCs.State AS AADCState,
4 AS RateType, /* AADC */
'Automation AADC' AS RateTypeString,
0 AS IsDetailRecord,
0 AS IsZipcodeMixedAADCRecord,
COUNT(*) AS NumberOfBills,
0 AS IsReportTotalsRecord,
0 AS TotalCarrierRouteBills,
0 AS TotalNumberOfBillsInFiveDigitZips,
0 AS TotalNumberOfBillsInThreeDigitZips,
0 AS TotalAADCBills,
0 AS TotalMixedAADCBills,
0 AS TotalPresortedNonautomationBills,
0 AS TotalSinglePieceBills,
0 AS TotalFinalBillsNotMailed,
0 AS TotalBillsMailed,
0 AS TotalNumberOfBills,
0 AS NumberOfOneFootTraysUsed,
0 AS NumberOfTwoFootTraysUsed,
0 AS CarrierRouteRateAmount,
0 AS FiveDigitRateAmount,
0 AS ThreeDigitRateAmount,
0 AS AADCRateAmount,
0 AS MixedAADCRateAmount,
0 AS PresortedNonautomationRateAmount,
0 AS SinglePieceRateAmount,
0 AS TotalPostageAmount
FROM (#TempPrintEntireBill AS Bills JOIN AADCDestinationZipcodes ON LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3) = AADCDestinationZipcodes.ThreeDigitZipcode) JOIN AADCs ON AADCDestinationZipcodes.AADCId = AADCs.AADCId
WHERE AADCDestinationZipcodes.Deleted = 0
AND AADCs.Deleted = 0
AND (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND NOT EXISTS(SELECT ZipcodeSummary.CarrierRoute
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ((ZipcodeSummary.RateType = 1 /* Carrier Route */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip
AND ZipcodeSummary.CarrierRoute = LTRIM(RTRIM(ISNULL(Bills.AccountsCarrierRoute, ''))))
OR (ZipcodeSummary.RateType = 2 /* 5-digit zip */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip)
OR (ZipcodeSummary.RateType = 3 /* 3-digit zip */
AND LEFT(ZipcodeSummary.ThreeDigitZipcode, 3) = LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3))))
GROUP BY AADCs.AADCNumber, AADCs.City, AADCs.State, AADCs.AADCId
HAVING COUNT(*) >= @ZipcodeSummaryMinimumBarcodedBillsInGroup
/*
We found out that the criteria for disregarding the minimum number of pieces per group is not based on
whether its in the local AADC, but whether or not the post office that they're taking their mail to is
an SCF. If it is an SCF, then all mail within the SCF zipcodes get the AADC rate regardless of how many
there are. To do this though, we would have to add the SCFs and their zips. Until we have someone that
does this who needs it, we will ignore this special case.
HAVING (AADCs.AADCId = @LocalAADCId OR
COUNT(*) >= @ZipcodeSummaryMinimumBarcodedBillsInGroup)
*/
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while summarizing the barcoded bills per AADC.',16,1)
RETURN(99)
END
UPDATE #TempPrintEntireBill
SET PostageRateType = 4
FROM (#TempPrintEntireBill AS Bills JOIN AADCDestinationZipcodes ON LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3) = AADCDestinationZipcodes.ThreeDigitZipcode) JOIN #ZipcodeSummary AS ZipcodeSummary ON AADCDestinationZipcodes.AADCId = ZipcodeSummary.AADCId AND ZipcodeSummary.RateType = 4
WHERE AADCDestinationZipcodes.Deleted = 0
AND (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND Bills.PostageRateType = 0
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while updating the bill postage rate type for AADC zip pieces.',16,1)
RETURN(99)
END
IF @SummarizeReport <> 1
BEGIN
/* Insert the 5-digit detail records per AADC if a detail report is selected. */
INSERT INTO #ZipcodeSummary
(Zipcode,
CarrierRoute,
ThreeDigitZipcode,
AADCId,
AADCNumber,
AADCCity,
AADCState,
RateType,
RateTypeString,
IsDetailRecord,
IsZipcodeMixedAADCRecord,
NumberOfBills,
IsReportTotalsRecord,
TotalCarrierRouteBills,
TotalNumberOfBillsInFiveDigitZips,
TotalNumberOfBillsInThreeDigitZips,
TotalAADCBills,
TotalMixedAADCBills,
TotalPresortedNonautomationBills,
TotalSinglePieceBills,
TotalFinalBillsNotMailed,
TotalBillsMailed,
TotalNumberOfBills,
NumberOfOneFootTraysUsed,
NumberOfTwoFootTraysUsed,
CarrierRouteRateAmount,
FiveDigitRateAmount,
ThreeDigitRateAmount,
AADCRateAmount,
MixedAADCRateAmount,
PresortedNonautomationRateAmount,
SinglePieceRateAmount,
TotalPostageAmount)
SELECT Bills.ZipCodeSummaryFiveDigitZip AS Zipcode,
NULL AS CarrierRoute,
NULL AS ThreeDigitZipcode,
AADCs.AADCId AS AADCId,
AADCs.AADCNumber AS AADCNumber,
AADCs.City AS AADCCity,
AADCs.State AS AADCState,
4 AS RateType, /* AADC */
'Automation AADC' AS RateTypeString,
1 AS IsDetailRecord,
0 AS IsZipcodeMixedAADCRecord,
COUNT(*) AS NumberOfBills,
0 AS IsReportTotalsRecord,
0 AS TotalCarrierRouteBills,
0 AS TotalNumberOfBillsInFiveDigitZips,
0 AS TotalNumberOfBillsInThreeDigitZips,
0 AS TotalAADCBills,
0 AS TotalMixedAADCBills,
0 AS TotalPresortedNonautomationBills,
0 AS TotalSinglePieceBills,
0 AS TotalFinalBillsNotMailed,
0 AS TotalBillsMailed,
0 AS TotalNumberOfBills,
0 AS NumberOfOneFootTraysUsed,
0 AS NumberOfTwoFootTraysUsed,
0 AS CarrierRouteRateAmount,
0 AS FiveDigitRateAmount,
0 AS ThreeDigitRateAmount,
0 AS AADCRateAmount,
0 AS MixedAADCRateAmount,
0 AS PresortedNonautomationRateAmount,
0 AS SinglePieceRateAmount,
0 AS TotalPostageAmount
FROM (#TempPrintEntireBill AS Bills JOIN AADCDestinationZipcodes ON LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3) = AADCDestinationZipcodes.ThreeDigitZipcode) JOIN AADCs ON AADCDestinationZipcodes.AADCId = AADCs.AADCId
WHERE AADCDestinationZipcodes.Deleted = 0
AND AADCs.Deleted = 0
AND (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND NOT EXISTS(SELECT ZipcodeSummary.CarrierRoute
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ((ZipcodeSummary.RateType = 1 /* Carrier Route */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip
AND ZipcodeSummary.CarrierRoute = LTRIM(RTRIM(ISNULL(Bills.AccountsCarrierRoute, ''))))
OR (ZipcodeSummary.RateType = 2 /* 5-digit zip */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip)
OR (ZipcodeSummary.RateType = 3 /* 3-digit zip */
AND LEFT(ZipcodeSummary.ThreeDigitZipcode, 3) = LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3))))
AND EXISTS (SELECT ZipcodeSummary.AADCId
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ZipcodeSummary.RateType = 4 /* AADC */
AND ZipcodeSummary.AADCId = AADCs.AADCId)
GROUP BY AADCs.AADCNumber, AADCs.City, AADCs.State, AADCs.AADCId, Bills.ZipCodeSummaryFiveDigitZip
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while summarizing the 5-digit detail barcoded bills per AADC.',16,1)
RETURN(99)
END
END /* IF @SummarizeReport <> 1 */
/* Insert all Mixed AADC records for barcoded bills where the minimum number of bills has not yet been met. */
INSERT INTO #ZipcodeSummary
(Zipcode,
CarrierRoute,
ThreeDigitZipcode,
AADCId,
AADCNumber,
AADCCity,
AADCState,
RateType,
RateTypeString,
IsDetailRecord,
IsZipcodeMixedAADCRecord,
NumberOfBills,
IsReportTotalsRecord,
TotalCarrierRouteBills,
TotalNumberOfBillsInFiveDigitZips,
TotalNumberOfBillsInThreeDigitZips,
TotalAADCBills,
TotalMixedAADCBills,
TotalPresortedNonautomationBills,
TotalSinglePieceBills,
TotalFinalBillsNotMailed,
TotalBillsMailed,
TotalNumberOfBills,
NumberOfOneFootTraysUsed,
NumberOfTwoFootTraysUsed,
CarrierRouteRateAmount,
FiveDigitRateAmount,
ThreeDigitRateAmount,
AADCRateAmount,
MixedAADCRateAmount,
PresortedNonautomationRateAmount,
SinglePieceRateAmount,
TotalPostageAmount)
SELECT NULL AS Zipcode,
NULL AS CarrierRoute,
NULL AS ThreeDigitZipcode,
0 AS AADCId,
NULL AS AADCNumber,
NULL AS AADCCity,
NULL AS AADCState,
5 AS RateType, /* Mixed AADC */
'Automation Mixed AADC' AS RateTypeString,
0 AS IsDetailRecord,
0 AS IsZipcodeMixedAADCRecord,
COUNT(*) AS NumberOfBills,
0 AS IsReportTotalsRecord,
0 AS TotalCarrierRouteBills,
0 AS TotalNumberOfBillsInFiveDigitZips,
0 AS TotalNumberOfBillsInThreeDigitZips,
0 AS TotalAADCBills,
0 AS TotalMixedAADCBills,
0 AS TotalPresortedNonautomationBills,
0 AS TotalSinglePieceBills,
0 AS TotalFinalBillsNotMailed,
0 AS TotalBillsMailed,
0 AS TotalNumberOfBills,
0 AS NumberOfOneFootTraysUsed,
0 AS NumberOfTwoFootTraysUsed,
0 AS CarrierRouteRateAmount,
0 AS FiveDigitRateAmount,
0 AS ThreeDigitRateAmount,
0 AS AADCRateAmount,
0 AS MixedAADCRateAmount,
0 AS PresortedNonautomationRateAmount,
0 AS SinglePieceRateAmount,
0 AS TotalPostageAmount
FROM #TempPrintEntireBill AS Bills JOIN AADCDestinationZipcodes ON LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3) = AADCDestinationZipcodes.ThreeDigitZipcode
WHERE AADCDestinationZipcodes.Deleted = 0
AND (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND NOT EXISTS(SELECT ZipcodeSummary.CarrierRoute
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ((ZipcodeSummary.RateType = 1 /* Carrier Route */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip
AND ZipcodeSummary.CarrierRoute = LTRIM(RTRIM(ISNULL(Bills.AccountsCarrierRoute, ''))))
OR (ZipcodeSummary.RateType = 2 /* 5-digit zip */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip)
OR (ZipcodeSummary.RateType = 3 /* 3-digit zip */
AND LEFT(ZipcodeSummary.ThreeDigitZipcode, 3) = LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3))
OR (ZipcodeSummary.RateType = 4 /* AADC */
AND ZipcodeSummary.AADCId = AADCDestinationZipcodes.AADCId)))
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while summarizing the barcoded bills for the mixed AADC.',16,1)
RETURN(99)
END
/* Insert the individual AADC records for the mixed AADC. */
INSERT INTO #ZipcodeSummary
(Zipcode,
CarrierRoute,
ThreeDigitZipcode,
AADCId,
AADCNumber,
AADCCity,
AADCState,
RateType,
RateTypeString,
IsDetailRecord,
IsZipcodeMixedAADCRecord,
NumberOfBills,
IsReportTotalsRecord,
TotalCarrierRouteBills,
TotalNumberOfBillsInFiveDigitZips,
TotalNumberOfBillsInThreeDigitZips,
TotalAADCBills,
TotalMixedAADCBills,
TotalPresortedNonautomationBills,
TotalSinglePieceBills,
TotalFinalBillsNotMailed,
TotalBillsMailed,
TotalNumberOfBills,
NumberOfOneFootTraysUsed,
NumberOfTwoFootTraysUsed,
CarrierRouteRateAmount,
FiveDigitRateAmount,
ThreeDigitRateAmount,
AADCRateAmount,
MixedAADCRateAmount,
PresortedNonautomationRateAmount,
SinglePieceRateAmount,
TotalPostageAmount)
SELECT NULL AS Zipcode,
NULL AS CarrierRoute,
NULL AS ThreeDigitZipcode,
AADCs.AADCId AS AADCId,
AADCs.AADCNumber AS AADCNumber,
AADCs.City AS AADCCity,
AADCs.State AS AADCState,
5 AS RateType, /* Mixed AADC */
'Automation Mixed AADC' AS RateTypeString,
1 AS IsDetailRecord,
0 AS IsZipcodeMixedAADCRecord,
COUNT(*) AS NumberOfBills,
0 AS IsReportTotalsRecord,
0 AS TotalCarrierRouteBills,
0 AS TotalNumberOfBillsInFiveDigitZips,
0 AS TotalNumberOfBillsInThreeDigitZips,
0 AS TotalAADCBills,
0 AS TotalMixedAADCBills,
0 AS TotalPresortedNonautomationBills,
0 AS TotalSinglePieceBills,
0 AS TotalFinalBillsNotMailed,
0 AS TotalBillsMailed,
0 AS TotalNumberOfBills,
0 AS NumberOfOneFootTraysUsed,
0 AS NumberOfTwoFootTraysUsed,
0 AS CarrierRouteRateAmount,
0 AS FiveDigitRateAmount,
0 AS ThreeDigitRateAmount,
0 AS AADCRateAmount,
0 AS MixedAADCRateAmount,
0 AS PresortedNonautomationRateAmount,
0 AS SinglePieceRateAmount,
0 AS TotalPostageAmount
FROM (#TempPrintEntireBill AS Bills JOIN AADCDestinationZipcodes ON LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3) = AADCDestinationZipcodes.ThreeDigitZipcode) JOIN AADCs ON AADCDestinationZipcodes.AADCId = AADCs.AADCId
WHERE AADCDestinationZipcodes.Deleted = 0
AND AADCs.Deleted = 0
AND (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND NOT EXISTS(SELECT ZipcodeSummary.CarrierRoute
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ((ZipcodeSummary.RateType = 1 /* Carrier Route */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip
AND ZipcodeSummary.CarrierRoute = LTRIM(RTRIM(ISNULL(Bills.AccountsCarrierRoute, ''))))
OR (ZipcodeSummary.RateType = 2 /* 5-digit zip */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip)
OR (ZipcodeSummary.RateType = 3 /* 3-digit zip */
AND LEFT(ZipcodeSummary.ThreeDigitZipcode, 3) = LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3))
OR (ZipcodeSummary.RateType = 4 /* AADC */
AND ZipcodeSummary.AADCId = AADCDestinationZipcodes.AADCId)))
GROUP BY AADCs.AADCNumber, AADCs.City, AADCs.State, AADCs.AADCId
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while summarizing the AADC detail barcoded bills for the mixed AADC.',16,1)
RETURN(99)
END
UPDATE #TempPrintEntireBill
SET PostageRateType = 5
FROM (#TempPrintEntireBill AS Bills JOIN AADCDestinationZipcodes ON LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3) = AADCDestinationZipcodes.ThreeDigitZipcode) JOIN #ZipcodeSummary AS ZipcodeSummary ON AADCDestinationZipcodes.AADCId = ZipcodeSummary.AADCId AND ZipcodeSummary.RateType = 5
WHERE AADCDestinationZipcodes.Deleted = 0
AND (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND Bills.PostageRateType = 0
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while updating the bill postage rate type for Mixed AADC zip pieces.',16,1)
RETURN(99)
END
IF @SummarizeReport <> 1
BEGIN
/* Insert the individual zipcode records for the mixed AADC. */
INSERT INTO #ZipcodeSummary
(Zipcode,
CarrierRoute,
ThreeDigitZipcode,
AADCId,
AADCNumber,
AADCCity,
AADCState,
RateType,
RateTypeString,
IsDetailRecord,
IsZipcodeMixedAADCRecord,
NumberOfBills,
IsReportTotalsRecord,
TotalCarrierRouteBills,
TotalNumberOfBillsInFiveDigitZips,
TotalNumberOfBillsInThreeDigitZips,
TotalAADCBills,
TotalMixedAADCBills,
TotalPresortedNonautomationBills,
TotalSinglePieceBills,
TotalFinalBillsNotMailed,
TotalBillsMailed,
TotalNumberOfBills,
NumberOfOneFootTraysUsed,
NumberOfTwoFootTraysUsed,
CarrierRouteRateAmount,
FiveDigitRateAmount,
ThreeDigitRateAmount,
AADCRateAmount,
MixedAADCRateAmount,
PresortedNonautomationRateAmount,
SinglePieceRateAmount,
TotalPostageAmount)
SELECT Bills.ZipCodeSummaryFiveDigitZip AS Zipcode,
NULL AS CarrierRoute,
NULL AS ThreeDigitZipcode,
AADCs.AADCId AS AADCId,
AADCs.AADCNumber AS AADCNumber,
AADCs.City AS AADCCity,
AADCs.State AS AADCState,
5 AS RateType, /* Mixed AADC */
'Automation Mixed AADC' AS RateTypeString,
1 AS IsDetailRecord,
1 AS IsZipcodeMixedAADCRecord,
COUNT(*) AS NumberOfBills,
0 AS IsReportTotalsRecord,
0 AS TotalCarrierRouteBills,
0 AS TotalNumberOfBillsInFiveDigitZips,
0 AS TotalNumberOfBillsInThreeDigitZips,
0 AS TotalAADCBills,
0 AS TotalMixedAADCBills,
0 AS TotalPresortedNonautomationBills,
0 AS TotalSinglePieceBills,
0 AS TotalFinalBillsNotMailed,
0 AS TotalBillsMailed,
0 AS TotalNumberOfBills,
0 AS NumberOfOneFootTraysUsed,
0 AS NumberOfTwoFootTraysUsed,
0 AS CarrierRouteRateAmount,
0 AS FiveDigitRateAmount,
0 AS ThreeDigitRateAmount,
0 AS AADCRateAmount,
0 AS MixedAADCRateAmount,
0 AS PresortedNonautomationRateAmount,
0 AS SinglePieceRateAmount,
0 AS TotalPostageAmount
FROM (#TempPrintEntireBill AS Bills JOIN AADCDestinationZipcodes ON LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3) = AADCDestinationZipcodes.ThreeDigitZipcode) JOIN AADCs ON AADCDestinationZipcodes.AADCId = AADCs.AADCId
WHERE AADCDestinationZipcodes.Deleted = 0
AND AADCs.Deleted = 0
AND (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND NOT EXISTS(SELECT ZipcodeSummary.CarrierRoute
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ((ZipcodeSummary.RateType = 1 /* Carrier Route */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip
AND ZipcodeSummary.CarrierRoute = LTRIM(RTRIM(ISNULL(Bills.AccountsCarrierRoute, ''))))
OR (ZipcodeSummary.RateType = 2 /* 5-digit zip */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip)
OR (ZipcodeSummary.RateType = 3 /* 3-digit zip */
AND LEFT(ZipcodeSummary.ThreeDigitZipcode, 3) = LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3))
OR (ZipcodeSummary.RateType = 4 /* AADC */
AND ZipcodeSummary.AADCId = AADCDestinationZipcodes.AADCId)))
GROUP BY AADCs.AADCNumber, AADCs.City, AADCs.State, AADCs.AADCId, Bills.ZipCodeSummaryFiveDigitZip
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while summarizing the AADC detail barcoded bills for the mixed AADC.',16,1)
RETURN(99)
END
END /* IF @SummarizeReport <> 1 */
/* Insert the pre-sorted automation or single piece records for non-barcoded bills or barcoded bills
where the minimum number of bills has not yet been met. */
INSERT INTO #ZipcodeSummary
(Zipcode,
CarrierRoute,
ThreeDigitZipcode,
AADCId,
AADCNumber,
AADCCity,
AADCState,
RateType,
RateTypeString,
IsDetailRecord,
IsZipcodeMixedAADCRecord,
NumberOfBills,
IsReportTotalsRecord,
TotalCarrierRouteBills,
TotalNumberOfBillsInFiveDigitZips,
TotalNumberOfBillsInThreeDigitZips,
TotalAADCBills,
TotalMixedAADCBills,
TotalPresortedNonautomationBills,
TotalSinglePieceBills,
TotalFinalBillsNotMailed,
TotalBillsMailed,
TotalNumberOfBills,
NumberOfOneFootTraysUsed,
NumberOfTwoFootTraysUsed,
CarrierRouteRateAmount,
FiveDigitRateAmount,
ThreeDigitRateAmount,
AADCRateAmount,
MixedAADCRateAmount,
PresortedNonautomationRateAmount,
SinglePieceRateAmount,
TotalPostageAmount)
SELECT NULL AS Zipcode,
NULL AS CarrierRoute,
NULL AS ThreeDigitZipcode,
0 AS AADCId,
NULL AS AADCNumber,
NULL AS AADCCity,
NULL AS AADCState,
(CASE
WHEN COUNT(*) >= @MinimumNumberOfBarcodedBillsNeededForDiscount THEN 6 /* Pre-Sorted Non-automation */
ELSE 7 /* Single-Piece */
END) AS RateType,
(CASE
WHEN COUNT(*) >= @MinimumNumberOfBarcodedBillsNeededForDiscount THEN 'Presorted Non-Automation'
ELSE 'Non-Automation Single Piece'
END) AS RateTypeString,
0 AS IsDetailRecord,
0 AS IsZipcodeMixedAADCRecord,
COUNT(*) AS NumberOfBills,
0 AS IsReportTotalsRecord,
0 AS TotalCarrierRouteBills,
0 AS TotalNumberOfBillsInFiveDigitZips,
0 AS TotalNumberOfBillsInThreeDigitZips,
0 AS TotalAADCBills,
0 AS TotalMixedAADCBills,
0 AS TotalPresortedNonautomationBills,
0 AS TotalSinglePieceBills,
0 AS TotalFinalBillsNotMailed,
0 AS TotalBillsMailed,
0 AS TotalNumberOfBills,
0 AS NumberOfOneFootTraysUsed,
0 AS NumberOfTwoFootTraysUsed,
0 AS CarrierRouteRateAmount,
0 AS FiveDigitRateAmount,
0 AS ThreeDigitRateAmount,
0 AS AADCRateAmount,
0 AS MixedAADCRateAmount,
0 AS PresortedNonautomationRateAmount,
0 AS SinglePieceRateAmount,
0 AS TotalPostageAmount
FROM #TempPrintEntireBill AS Bills LEFT JOIN AADCDestinationZipcodes ON LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3) = AADCDestinationZipcodes.ThreeDigitZipcode AND AADCDestinationZipcodes.Deleted = 0
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND (Bills.IsBarcodedBill <> 1
OR (Bills.IsBarcodedBill = 1
AND NOT EXISTS(SELECT ZipcodeSummary.CarrierRoute
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ((ZipcodeSummary.RateType = 1 /* Carrier Route */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip
AND ZipcodeSummary.CarrierRoute = LTRIM(RTRIM(ISNULL(Bills.AccountsCarrierRoute, ''))))
OR (ZipcodeSummary.RateType = 2 /* 5-digit zip */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip)
OR (ZipcodeSummary.RateType = 3 /* 3-digit zip */
AND LEFT(ZipcodeSummary.ThreeDigitZipcode, 3) = LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3))
OR (ZipcodeSummary.RateType = 4 /* AADC */
AND ZipcodeSummary.AADCId = ISNULL(AADCDestinationZipcodes.AADCId, 0))
OR (ZipcodeSummary.RateType = 5 /* Mixed AADC */
AND NOT AADCDestinationZipcodes.AADCId IS NULL)))))
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while summarizing the pre-sorted non-automation or single piece bills.',16,1)
RETURN(99)
END
UPDATE #TempPrintEntireBill
SET PostageRateType = (SELECT MAX(ZipcodeSummary.RateType)
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ZipcodeSummary.RateType IN (6, 7))
FROM #TempPrintEntireBill AS Bills
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND Bills.PostageRateType = 0
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while updating the bill postage rate type for presorted non-automation or single piece bills.',16,1)
RETURN(99)
END
IF @PrintBreakdownForNonbarcodedBills = 1
BEGIN
/* Insert the pre-sorted automation or single piece detail records per zipcode for non-barcoded
bills or barcoded bills where the minimum number of bills has not yet been met. */
INSERT INTO #ZipcodeSummary
(Zipcode,
CarrierRoute,
ThreeDigitZipcode,
AADCId,
AADCNumber,
AADCCity,
AADCState,
RateType,
RateTypeString,
IsDetailRecord,
IsZipcodeMixedAADCRecord,
NumberOfBills,
IsReportTotalsRecord,
TotalCarrierRouteBills,
TotalNumberOfBillsInFiveDigitZips,
TotalNumberOfBillsInThreeDigitZips,
TotalAADCBills,
TotalMixedAADCBills,
TotalPresortedNonautomationBills,
TotalSinglePieceBills,
TotalFinalBillsNotMailed,
TotalBillsMailed,
TotalNumberOfBills,
NumberOfOneFootTraysUsed,
NumberOfTwoFootTraysUsed,
CarrierRouteRateAmount,
FiveDigitRateAmount,
ThreeDigitRateAmount,
AADCRateAmount,
MixedAADCRateAmount,
PresortedNonautomationRateAmount,
SinglePieceRateAmount,
TotalPostageAmount)
SELECT Bills.ZipCodeSummaryFiveDigitZip AS Zipcode,
NULL AS CarrierRoute,
NULL AS ThreeDigitZipcode,
0 AS AADCId,
NULL AS AADCNumber,
NULL AS AADCCity,
NULL AS AADCState,
(SELECT MAX(ISNULL(ZipcodeSummary.RateType, 0))
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ZipcodeSummary.RateType IN (6, 7)) AS RateType,
(CASE
WHEN (SELECT MAX(ISNULL(ZipcodeSummary.RateType, 0))
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ZipcodeSummary.RateType IN (6, 7)) = 6 THEN 'Presorted Non-Automation'
ELSE 'Non-Automation Single Piece'
END) AS RateTypeString,
1 AS IsDetailRecord,
0 AS IsZipcodeMixedAADCRecord,
COUNT(*) AS NumberOfBills,
0 AS IsReportTotalsRecord,
0 AS TotalCarrierRouteBills,
0 AS TotalNumberOfBillsInFiveDigitZips,
0 AS TotalNumberOfBillsInThreeDigitZips,
0 AS TotalAADCBills,
0 AS TotalMixedAADCBills,
0 AS TotalPresortedNonautomationBills,
0 AS TotalSinglePieceBills,
0 AS TotalFinalBillsNotMailed,
0 AS TotalBillsMailed,
0 AS TotalNumberOfBills,
0 AS NumberOfOneFootTraysUsed,
0 AS NumberOfTwoFootTraysUsed,
0 AS CarrierRouteRateAmount,
0 AS FiveDigitRateAmount,
0 AS ThreeDigitRateAmount,
0 AS AADCRateAmount,
0 AS MixedAADCRateAmount,
0 AS PresortedNonautomationRateAmount,
0 AS SinglePieceRateAmount,
0 AS TotalPostageAmount
FROM #TempPrintEntireBill AS Bills LEFT JOIN AADCDestinationZipcodes ON LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3) = AADCDestinationZipcodes.ThreeDigitZipcode AND AADCDestinationZipcodes.Deleted = 0
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
AND (Bills.IsBarcodedBill <> 1
OR (Bills.IsBarcodedBill = 1
AND NOT EXISTS(SELECT ZipcodeSummary.CarrierRoute
FROM #ZipcodeSummary AS ZipcodeSummary
WHERE ((ZipcodeSummary.RateType = 1 /* Carrier Route */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip
AND ZipcodeSummary.CarrierRoute = LTRIM(RTRIM(ISNULL(Bills.AccountsCarrierRoute, ''))))
OR (ZipcodeSummary.RateType = 2 /* 5-digit zip */
AND ZipcodeSummary.Zipcode = Bills.ZipCodeSummaryFiveDigitZip)
OR (ZipcodeSummary.RateType = 3 /* 3-digit zip */
AND LEFT(ZipcodeSummary.ThreeDigitZipcode, 3) = LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3))
OR (ZipcodeSummary.RateType = 4 /* AADC */
AND ZipcodeSummary.AADCId = ISNULL(AADCDestinationZipcodes.AADCId, 0))
OR (ZipcodeSummary.RateType = 5 /* Mixed AADC */
AND NOT AADCDestinationZipcodes.AADCId IS NULL)))))
GROUP BY Bills.ZipCodeSummaryFiveDigitZip
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while summarizing the pre-sorted non-automation or single piece bills per zipcode.',16,1)
RETURN(99)
END
END
/* Insert the report bill totals record. */
INSERT INTO #ZipcodeSummary
(Zipcode,
CarrierRoute,
ThreeDigitZipcode,
AADCId,
AADCNumber,
AADCCity,
AADCState,
RateType,
RateTypeString,
IsDetailRecord,
IsZipcodeMixedAADCRecord,
NumberOfBills,
IsReportTotalsRecord,
TotalCarrierRouteBills,
TotalNumberOfBillsInFiveDigitZips,
TotalNumberOfBillsInThreeDigitZips,
TotalAADCBills,
TotalMixedAADCBills,
TotalPresortedNonautomationBills,
TotalSinglePieceBills,
TotalFinalBillsNotMailed,
TotalBillsMailed,
TotalNumberOfBills,
NumberOfOneFootTraysUsed,
NumberOfTwoFootTraysUsed,
CarrierRouteRateAmount,
FiveDigitRateAmount,
ThreeDigitRateAmount,
AADCRateAmount,
MixedAADCRateAmount,
PresortedNonautomationRateAmount,
SinglePieceRateAmount,
TotalPostageAmount)
SELECT NULL AS Zipcode,
NULL AS CarrierRoute,
NULL AS ThreeDigitZipcode,
0 AS AADCId,
NULL AS AADCNumber,
NULL AS AADCCity,
NULL AS AADCState,
0 AS RateType,
NULL AS RateTypeString,
0 AS IsDetailRecord,
0 AS IsZipcodeMixedAADCRecord,
0 AS NumberOfBills,
1 AS IsReportTotalsRecord,
SUM((CASE
WHEN ZipCodeSummary.RateType = 1 THEN ZipcodeSummary.NumberOfBills
ELSE 0
END)) AS TotalCarrierRouteBills,
SUM((CASE
WHEN ZipCodeSummary.RateType = 2 THEN ZipcodeSummary.NumberOfBills
ELSE 0
END)) AS TotalNumberOfBillsInFiveDigitZips,
SUM((CASE
WHEN ZipCodeSummary.RateType = 3 THEN ZipcodeSummary.NumberOfBills
ELSE 0
END)) AS TotalNumberOfBillsInThreeDigitZips,
SUM((CASE
WHEN ZipCodeSummary.RateType = 4 THEN ZipcodeSummary.NumberOfBills
ELSE 0
END)) AS TotalAADCBills,
SUM((CASE
WHEN ZipCodeSummary.RateType = 5 THEN ZipcodeSummary.NumberOfBills
ELSE 0
END)) AS TotalMixedAADCBills,
SUM((CASE
WHEN ZipCodeSummary.RateType = 6 THEN ZipcodeSummary.NumberOfBills
ELSE 0
END)) AS TotalPresortedNonautomationBills,
SUM((CASE
WHEN ZipCodeSummary.RateType = 7 THEN ZipcodeSummary.NumberOfBills
ELSE 0
END)) AS TotalSinglePieceBills,
@TotalFinalBillsNotMailed AS TotalFinalBillsNotMailed,
SUM(ZipCodeSummary.NumberOfBills) AS TotalBillsMailed,
SUM(ZipCodeSummary.NumberOfBills) + @TotalFinalBillsNotMailed AS TotalNumberOfBills,
0 AS NumberOfOneFootTraysUsed,
0 AS NumberOfTwoFootTraysUsed,
0 AS CarrierRouteRateAmount,
0 AS FiveDigitRateAmount,
0 AS ThreeDigitRateAmount,
0 AS AADCRateAmount,
0 AS MixedAADCRateAmount,
0 AS PresortedNonautomationRateAmount,
0 AS SinglePieceRateAmount,
0 AS TotalPostageAmount
FROM #ZipcodeSummary AS ZipCodeSummary
WHERE ZipCodeSummary.IsDetailRecord <> 1
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occured while summarizing the report totals record.',16,1)
RETURN(99)
END
END /* If total number of barcoded bills < @MinimumNumberOfBarcodedBillsNeededForDiscount else */
SET @TrayNumber = 1
SET @UseOverflowTray = 0
SET @TraySize = 1
SET @NumberOfBillsInTray = 0
SET @NumberOfBillsInTrayGroup = 0
SET @CurrentPostageRateType = 0
SET @CurrentThreeDigitZip = ''
SET @CurrentFiveDigitZip = ''
SET @CurrentCarrierRoute = ''
SET @CurrentAADCNumber = ''
SET @CurrentAADCId = 0
IF @NumberOfBillsPerOneFootTray < 1 SET @NumberOfBillsPerOneFootTray = 1
IF @NumberOfBillsPerTwoFootTray < 2 SET @NumberOfBillsPerTwoFootTray = 2
/* Go thru a cursor based on the rate for the bills to get the USPS qualitication report. */
DECLARE USPSQualificationCursor INSENSITIVE CURSOR FOR
SELECT Bills.PostageRateType, /* AutomationCarrierRoute = 1, AutomationFiveDigitZip = 2, AutomationThreeDigitZip = 3, AutomationAADC = 4, AutomationMixedAADC = 5, NonautomationPresorted = 6, NonautomationSinglePiece = 7 */
(CASE
WHEN Bills.PostageRateType IN (3, 4) THEN LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3)
ELSE ''
END),
Bills.ZipCodeSummaryFiveDigitZip,
(CASE
WHEN Bills.PostageRateType = 1 THEN LTRIM(RTRIM(ISNULL(Bills.AccountsCarrierRoute, '')))
ELSE ''
END),
(CASE
WHEN Bills.PostageRateType IN (4, 5) THEN ISNULL(AADCs.AADCNumber, '')
ELSE ''
END),
(CASE
WHEN Bills.PostageRateType IN (4, 5) THEN ISNULL(AADCs.AADCId, 0)
ELSE 0
END),
Bills.AccountId,
Bills.BillNumber
FROM #TempPrintEntireBill AS Bills LEFT JOIN (AADCDestinationZipcodes JOIN AADCs ON AADCDestinationZipcodes.AADCId = AADCs.AADCId AND AADCs.Deleted = 0) ON LEFT(Bills.ZipCodeSummaryFiveDigitZip, 3) = AADCDestinationZipcodes.ThreeDigitZipcode AND AADCDestinationZipcodes.Deleted = 0 AND PostageRateType IN (4, 5) /* AADC or Mixed AADC */
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
AND Bills.IsBarcodedBill = 1
AND Bills.PostageRateType NOT IN (6, 7)
AND (@SortWithFinalBillsFirst <> 1
OR (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill <> 1))
ORDER BY Bills.PostageRateType,
(CASE
WHEN Bills.PostageRateType IN (4, 5) THEN AADCs.AADCNumber
ELSE ''
END),
(CASE
WHEN Bills.PostageRateType IN (4, 5) THEN AADCs.AADCId
ELSE 0
END),
Bills.ZipCodeSummaryFiveDigitZip,
(CASE
WHEN Bills.PostageRateType = 1 THEN Bills.AccountsCarrierRoute
ELSE ''
END),
Bills.AccountId
FOR READ ONLY
OPEN USPSQualificationCursor
WHILE (0=0)
BEGIN
FETCH NEXT FROM USPSQualificationCursor
INTO @PostageRateType, @ThreeDigitZip, @FiveDigitZip, @CarrierRoute, @AADCNumber, @AADCId, @AccountId, @BillNumber
IF (@@FETCH_STATUS <> 0) BREAK
IF (@CurrentPostageRateType <> @PostageRateType OR
(@PostageRateType = 1 AND (@CurrentFiveDigitZip <> @FiveDigitZip OR @CurrentCarrierRoute <> @CarrierRoute)) OR
(@PostageRateType = 2 AND @CurrentFiveDigitZip <> @FiveDigitZip) OR
(@PostageRateType = 3 AND @CurrentThreeDigitZip <> @ThreeDigitZip) OR
(@PostageRateType = 4 AND @CurrentAADCId <> @AADCId))
BEGIN
SET @RemainingNumberOfBillsInRateGroup = (SELECT ZipCodeSummary.NumberOfBills
FROM #ZipcodeSummary AS ZipCodeSummary
WHERE ZipCodeSummary.RateType = @PostageRateType
AND ZipCodeSummary.IsDetailRecord = 0
AND ZipCodeSummary.IsReportTotalsRecord = 0
AND ((@PostageRateType = 1 /* Carrier Route */
AND ZipcodeSummary.Zipcode = @FiveDigitZip
AND ZipcodeSummary.CarrierRoute = @CarrierRoute
OR (@PostageRateType = 2 /* 5-digit zip */
AND ZipcodeSummary.Zipcode = @FiveDigitZip)
OR (@PostageRateType = 3 /* 3-digit zip */
AND LEFT(ZipcodeSummary.ThreeDigitZipcode, 3) = @ThreeDigitZip)
OR (@PostageRateType = 4 /* AADC */
AND ZipcodeSummary.AADCId = @AADCId)
OR (@PostageRateType = 5 /* Mixed AADC */
AND NOT @AADCId IS NULL))))
END
IF @CurrentPostageRateType <> 0 AND
(@CurrentPostageRateType <> @PostageRateType OR
(@PostageRateType = 1 AND (@CurrentFiveDigitZip <> @FiveDigitZip OR @CurrentCarrierRoute <> @CarrierRoute)) OR
(@PostageRateType = 2 AND @CurrentFiveDigitZip <> @FiveDigitZip) OR
(@PostageRateType = 3 AND @CurrentThreeDigitZip <> @ThreeDigitZip) OR
(@PostageRateType = 4 AND (@CurrentAADCId <> @AADCId OR @CurrentThreeDigitZip <> @ThreeDigitZip)) OR
(@PostageRateType = 5 AND @CurrentAADCId <> @AADCId) OR
(@TraySize = 2 AND @NumberOfBillsInTray >= @NumberOfBillsPerTwoFootTray) OR
(@TraySize = 1 AND @NumberOfBillsInTray >= @NumberOfBillsPerOneFootTray AND @UseOverflowTray = 1))
BEGIN
IF @TraySize = 1 AND @NumberOfBillsInTray >= @NumberOfBillsPerOneFootTray AND @UseOverflowTray = 1
BEGIN
/* Subtract 1 since we actually went over the number of bills and this bill needs to be
added into the next overflow tray. */
SET @NumberOfBillsInTrayGroup = @NumberOfBillsInTrayGroup - 1
END
INSERT INTO @USPSQualificationReport
(TrayNumber,
TraySize,
RateType,
TraySortationLevel,
TrayZipcode,
GroupDestination,
NumberOfBills)
SELECT @TrayNumber AS TrayNumber,
@TraySize AS TraySize,
@CurrentPostageRateType AS RateType,
(CASE
WHEN @CurrentPostageRateType = 1 THEN 'CRD'
WHEN @CurrentPostageRateType = 2 THEN '5DG'
WHEN @CurrentPostageRateType = 3 THEN '3DG'
WHEN @CurrentPostageRateType = 4 THEN 'AADC'
WHEN @CurrentPostageRateType = 5 THEN 'MAAD'
ELSE ''
END) AS TraySortationLevel,
(CASE
WHEN @CurrentPostageRateType = 1 THEN @CurrentFiveDigitZip
WHEN @CurrentPostageRateType = 2 THEN @CurrentFiveDigitZip
WHEN @CurrentPostageRateType = 3 THEN @CurrentThreeDigitZip
WHEN @CurrentPostageRateType = 4 THEN @CurrentAADCNumber
WHEN @CurrentPostageRateType = 5 THEN LEFT(@ZipcodeOfPostOfficeBillsAreMailedFrom, 3)
ELSE ''
END) AS TrayZipcode,
(CASE
WHEN @CurrentPostageRateType = 1 THEN @CurrentCarrierRoute
WHEN @CurrentPostageRateType = 2 THEN @CurrentFiveDigitZip
WHEN @CurrentPostageRateType = 3 THEN @CurrentThreeDigitZip
WHEN @CurrentPostageRateType = 4 THEN @CurrentThreeDigitZip
WHEN @CurrentPostageRateType = 5 THEN 'A' + @CurrentAADCNumber
ELSE ''
END) AS GroupDestination,
@NumberOfBillsInTrayGroup AS NumberOfBills
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
CLOSE USPSQualificationCursor
DEALLOCATE USPSQualificationCursor
RAISERROR('An error occurred while inserting a record into the USPS Qualification Report table.', 16, 1)
RETURN(99)
END
IF (@CurrentPostageRateType <> @PostageRateType OR
(@PostageRateType = 1 AND (@CurrentFiveDigitZip <> @FiveDigitZip OR @CurrentCarrierRoute <> @CarrierRoute)) OR
(@PostageRateType = 2 AND @CurrentFiveDigitZip <> @FiveDigitZip) OR
(@PostageRateType = 3 AND @CurrentThreeDigitZip <> @ThreeDigitZip) OR
(@PostageRateType = 4 AND @CurrentAADCId <> @AADCId) OR
(@TraySize = 2 AND @NumberOfBillsInTray >= @NumberOfBillsPerTwoFootTray) OR
(@TraySize = 1 AND @NumberOfBillsInTray >= @NumberOfBillsPerOneFootTray AND @UseOverflowTray = 1))
BEGIN
SET @TraySize = 1
SET @TrayNumber = @TrayNumber + 1
IF @TraySize = 1 AND @NumberOfBillsInTray >= @NumberOfBillsPerOneFootTray AND @UseOverflowTray = 1
BEGIN
SET @NumberOfBillsInTray = 1
SET @NumberOfBillsInTrayGroup = 1
SET @UseOverflowTray = 0
END
ELSE
BEGIN
SET @NumberOfBillsInTray = 0
SET @NumberOfBillsInTrayGroup = 0
END
END
ELSE
BEGIN
SET @NumberOfBillsInTrayGroup = 0
END
END
IF @CurrentPostageRateType <> @PostageRateType
BEGIN
SET @CurrentPostageRateType = @PostageRateType
END
IF @CurrentThreeDigitZip <> @ThreeDigitZip
BEGIN
SET @CurrentThreeDigitZip = @ThreeDigitZip
END
IF @CurrentCarrierRoute <> @CarrierRoute
BEGIN
SET @CurrentCarrierRoute = @CarrierRoute
END
IF @CurrentFiveDigitZip <> @FiveDigitZip
BEGIN
SET @CurrentFiveDigitZip = @FiveDigitZip
END
IF @CurrentAADCId <> @AADCId
BEGIN
SET @CurrentAADCNumber = @AADCNumber
SET @CurrentAADCId = @AADCId
END
SET @NumberOfBillsInTray = @NumberOfBillsInTray + 1
SET @NumberOfBillsInTrayGroup = @NumberOfBillsInTrayGroup + 1
SET @RemainingNumberOfBillsInRateGroup = @RemainingNumberOfBillsInRateGroup - 1
IF @TraySize = 1 AND @NumberOfBillsInTray > @NumberOfBillsPerOneFootTray
BEGIN
IF CAST(@RemainingNumberOfBillsInRateGroup AS DOUBLE PRECISION) / CAST(@NumberOfBillsPerOneFootTray AS DOUBLE PRECISION) >= .75
BEGIN
SET @TraySize = 2
END
ELSE
BEGIN
SET @UseOverflowTray = 1
END
END
UPDATE #TempPrintEntireBill
SET TrayNumber = (CASE
WHEN @UseOverflowTray = 1 THEN @TrayNumber + 1
ELSE @TrayNumber
END)
FROM #TempPrintEntireBill AS Bills
WHERE Bills.AccountId = @AccountId
AND Bills.BillNumber = @BillNumber
AND Bills.TrayNumber = 0
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
CLOSE USPSQualificationCursor
DEALLOCATE USPSQualificationCursor
RAISERROR('An error occurred while updating the tray number of the current bill.', 16, 1)
RETURN(99)
END
END
CLOSE USPSQualificationCursor
DEALLOCATE USPSQualificationCursor
IF @CurrentPostageRateType <> 0
BEGIN
/* Insert the last record for the last postage rate. */
INSERT INTO @USPSQualificationReport
(TrayNumber,
TraySize,
RateType,
TraySortationLevel,
TrayZipcode,
GroupDestination,
NumberOfBills)
SELECT @TrayNumber AS TrayNumber,
@TraySize AS TraySize,
@CurrentPostageRateType AS RateType,
(CASE
WHEN @CurrentPostageRateType = 1 THEN 'CRD'
WHEN @CurrentPostageRateType = 2 THEN '5DG'
WHEN @CurrentPostageRateType = 3 THEN '3DG'
WHEN @CurrentPostageRateType = 4 THEN 'AADC'
WHEN @CurrentPostageRateType = 5 THEN 'MAAD'
ELSE ''
END) AS TraySortationLevel,
(CASE
WHEN @CurrentPostageRateType = 1 THEN @CurrentFiveDigitZip
WHEN @CurrentPostageRateType = 2 THEN @CurrentFiveDigitZip
WHEN @CurrentPostageRateType = 3 THEN @CurrentThreeDigitZip
WHEN @CurrentPostageRateType = 4 THEN @CurrentAADCNumber
WHEN @CurrentPostageRateType = 5 THEN LEFT(@ZipcodeOfPostOfficeBillsAreMailedFrom, 3)
ELSE ''
END) AS TrayZipcode,
(CASE
WHEN @CurrentPostageRateType = 1 THEN @CurrentCarrierRoute
WHEN @CurrentPostageRateType = 2 THEN @CurrentFiveDigitZip
WHEN @CurrentPostageRateType = 3 THEN @CurrentThreeDigitZip
WHEN @CurrentPostageRateType = 4 THEN @CurrentThreeDigitZip
WHEN @CurrentPostageRateType = 5 THEN 'A' + @CurrentAADCNumber
ELSE ''
END) AS GroupDestination,
@NumberOfBillsInTrayGroup AS NumberOfBills
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while inserting the last record into the USPS Qualification Report table', 16, 1)
RETURN(99)
END
END
/* The postage rate type will be zero for final bills sorted first or bills not to be printed. */
UPDATE #TempPrintEntireBill
SET TrayNumber = 999999999
FROM #TempPrintEntireBill AS Bills
WHERE Bills.TrayNumber = 0
AND Bills.PostageRateType <> 0
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while updating the tray number of the presorted and single piece bills.', 16, 1)
RETURN(99)
END
UPDATE #ZipcodeSummary
SET NumberOfOneFootTraysUsed = (SELECT COUNT(DISTINCT TrayNumber)
FROM @USPSQualificationReport
WHERE TraySize = 1),
NumberOfTwoFootTraysUsed = (SELECT COUNT(DISTINCT TrayNumber)
FROM @USPSQualificationReport
WHERE TraySize = 2),
CarrierRouteRateAmount = CAST(ROUND(CAST(TotalCarrierRouteBills AS DOUBLE PRECISION) * @PostageAutomationRateCarrierRoute, 2) AS MONEY),
FiveDigitRateAmount = CAST(ROUND(CAST(TotalNumberOfBillsInFiveDigitZips AS DOUBLE PRECISION) * @PostageAutomationRateFiveDigitZip, 2) AS MONEY),
ThreeDigitRateAmount = CAST(ROUND(CAST(TotalNumberOfBillsInThreeDigitZips AS DOUBLE PRECISION) * @PostageAutomationRateThreeDigitZip, 2) AS MONEY),
AADCRateAmount = CAST(ROUND(CAST(TotalAADCBills AS DOUBLE PRECISION) * @PostageAutomationRateAADC, 2) AS MONEY),
MixedAADCRateAmount = CAST(ROUND(CAST(TotalMixedAADCBills AS DOUBLE PRECISION) * @PostageAutomationRateMixedAADC, 2) AS MONEY),
PresortedNonautomationRateAmount = CAST(ROUND(CAST(TotalPresortedNonautomationBills AS DOUBLE PRECISION) * @PostageNonAutomationRatePresorted, 2) AS MONEY),
SinglePieceRateAmount = CAST(ROUND(CAST(TotalSinglePieceBills AS DOUBLE PRECISION) * @PostageNonAutomationRateSinglePiece, 2) AS MONEY),
TotalPostageAmount = CAST(ROUND(CAST(TotalCarrierRouteBills AS DOUBLE PRECISION) * @PostageAutomationRateCarrierRoute, 2) AS MONEY) +
CAST(ROUND(CAST(TotalNumberOfBillsInFiveDigitZips AS DOUBLE PRECISION) * @PostageAutomationRateFiveDigitZip, 2) AS MONEY) +
CAST(ROUND(CAST(TotalNumberOfBillsInThreeDigitZips AS DOUBLE PRECISION) * @PostageAutomationRateThreeDigitZip, 2) AS MONEY) +
CAST(ROUND(CAST(TotalAADCBills AS DOUBLE PRECISION) * @PostageAutomationRateAADC, 2) AS MONEY) +
CAST(ROUND(CAST(TotalMixedAADCBills AS DOUBLE PRECISION) * @PostageAutomationRateMixedAADC, 2) AS MONEY) +
CAST(ROUND(CAST(TotalPresortedNonautomationBills AS DOUBLE PRECISION) * @PostageNonAutomationRatePresorted, 2) AS MONEY) +
CAST(ROUND(CAST(TotalSinglePieceBills AS DOUBLE PRECISION) * @PostageNonAutomationRateSinglePiece, 2) AS MONEY)
WHERE IsReportTotalsRecord = 1
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while updating the total amounts per rate in the zipcode summary report table.', 16, 1)
RETURN(99)
END
IF @ForZipCodeSummaryReport = 1
BEGIN
SELECT *
FROM #ZipcodeSummary
ORDER BY IsReportTotalsRecord, RateType, ThreeDigitZipcode, CarrierRoute, AADCNumber, AADCState, AADCCity, AADCId,
IsDetailRecord, IsZipcodeMixedAADCRecord, Zipcode
SELECT *
FROM @USPSQualificationReport
ORDER BY TrayNumber, TrayZipcode, GroupDestination
DROP TABLE #ZipcodeSummary
RETURN(0)
END
END
/********************************** END ZIPCODE SUMMARY **********************************/
IF @IsWebBill = 0 /* Web bills don't need a total bill page. */
BEGIN
UPDATE Accounts
SET BillNetDue = AmountDueTotal,
BillPenaltyAmount = PenaltyAmount,
BillNetDueAfterPenalty = AmountDueLateTotal,
BillDate = @CurrentDate
FROM #TempPrintEntireBill AS Tmp
WHERE Accounts.AccountID = Tmp.AccountID
/* create a "Total Bill" (an extra bill that prints at the end of the bill run that displays the number of bills
printed, total net billed (sum of Amount Due), and total gross billed (sum of amount due with the penalty) */
SET @NumberOfBills = ISNULL((SELECT COUNT(*)
FROM #TempPrintEntireBill AS Tmp
WHERE PrintThisBill = 1),0)
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while determining the total number of bills for the total bill.',16,1)
RETURN(99)
END
/* the amount due is duplicated if continuation bills print for single account, exclude continuation bills */
/* Select the minimum bill number since multiple bills may exist for landlord/tenants or delinquents. */
SET @AmountDueTotal = ISNULL((SELECT SUM(AmountDueTotal) FROM #TempPrintEntireBill AS tmp WHERE tmp.BillNumber = ISNULL((SELECT MIN(BillNumber) FROM #TempPrintEntireBill AS bills WHERE bills.AccountID = tmp.AccountID),0)),0)
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while determining the total Net Due Amount for the total bill.',16,1)
RETURN(99)
END
/* the amount due late is duplicated if continuation bills print for single account, exclude continuation bills */
/* Select the minimum bill number since multiple bills may exist for landlord/tenants or delinquents. */
SET @AmountDueLateTotal = ISNULL((SELECT SUM(AmountDueLateTotal) FROM #TempPrintEntireBill AS tmp WHERE tmp.BillNumber = ISNULL((SELECT MIN(BillNumber) FROM #TempPrintEntireBill AS bills WHERE bills.AccountID = tmp.AccountID),0)),0)
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while determining the total Gross Due Amount for the total bill.',16,1)
RETURN(99)
END
/* the final bill will have several fields that use huge numbers so that is will be selected last in the sort order */
INSERT INTO #TempPrintEntireBill
(BillNumber,
NumberofBills,
AccountID,
AccountsRoute,
AccountsAccountNumber,
AccountsSequence,
AccountsCarrierRoute,
BillingZip,
ChargesLine3,
ChargesLine4,
TextLine1,
TextLine2,
TextLine3,
TextLine4,
BillDescription1,
BillDescription2,
BillDescription3,
BillDescription4,
Line1IsForMeteredService,
Line2IsForMeteredService,
Line3IsForMeteredService,
Line4IsForMeteredService,
HasFinalBill,
PrintThisBill,
PostageRateType,
TrayNumber)
VALUES (
1, /* BillNumber */
1, /* NumberofBills */
999999999, /* AccountID */
9999, /* AccountsRoute */
99999, /* AccountsAccountNumber */
999, /* AccountsSequence */
'ZZZZZZZ', /* AccountsCarrierRoute */
999999999, /* BillingZip */
@AmountDueTotal, /* ChargesLine3 = total amount net due */
@AmountDueLateTotal, /* ChargesLine4 = total amount net due late */
'TOTAL BILL', /* TextLine1 */
'# of Bills:' + STR(@NumberOfBills, 8), /* TextLine2; length of number of bills maxes at 10 because of the max length of an INT value */
'Net Amount Billed', /* TextLine3 */
'Gross Amount Billed', /* TextLine4 */
'TOTAL BILL', /* BillDescription1 */
'# of Bills: ' + CAST(@NumberOfBills AS VARCHAR(8)), /* BillDescription2 */
'Net Amount Billed', /* BillDescription3 */
'Gross Amount Billed', /* BillDescription4 */
0, /* Line1IsForMeteredService */
0, /* Line2IsForMeteredService */
0, /* Line3IsForMeteredService */
0, /* Line4IsForMeteredService */
0, /* HasFinalBill; need for sorting */
1, /* PrintThisBill */
9, /* PostageRateType - set to an invalid value for the Totals Record */
999999999) /* Tray Number */
END
/* Select all the bill records from the temp table in the appropriate order. */
IF @BillSortOrder = 1 /* In Zipcode Summary Rate Order */
BEGIN
SELECT *
FROM #TempPrintEntireBill AS Bills
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
ORDER BY (CASE
WHEN @SortWithFinalBillsFirst = 1 THEN Bills.HasFinalBill
ELSE 0
END) DESC,
(CASE
WHEN @SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill = 1 THEN 0
ELSE Bills.PostageRateType
END),
(CASE
WHEN @SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill = 1 THEN 0
ELSE Bills.TrayNumber
END),
(CASE
WHEN @SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill = 1 THEN ''
ELSE Bills.ZipCodeSummaryFiveDigitZip
END),
(CASE
WHEN (@SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill = 1) OR Bills.PostageRateType <> 1 THEN ''
ELSE Bills.AccountsCarrierRoute
END),
(CASE
WHEN @SortWithFinalBillsFirst = 1 AND Bills.HasFinalBill = 1 THEN ''
ELSE Bills.ZipCodeSummaryZip
END), Bills.AccountsRoute, Bills.AccountsAccountNumber, Bills.AccountsSequence, Bills.AccountId, ABS(Bills.BillNumber)
END
ELSE /* By Account Number */
BEGIN
SELECT *
FROM #TempPrintEntireBill AS Bills
WHERE (Bills.PrintThisBill = 1 OR Bills.UsesBudgets = 1)
/* I have no idea why it is sorted this way... Its just the way the DBL works and I'm recreating it even if its junk code. */
/* the sorting for Final bills was added based on SWR UMS-967 */
ORDER BY (CASE
WHEN @SortWithFinalBillsFirst = 1 THEN Bills.HasFinalBill
ELSE 0
END) DESC,
Bills.AccountsRoute, Bills.AccountsAccountNumber, Bills.AccountsSequence, Bills.AccountID, ABS(Bills.BillNumber)
END
IF @AutomaticallyPrintZipcodeSummaryReport = 1
BEGIN
SELECT *
FROM #ZipcodeSummary
ORDER BY IsReportTotalsRecord, RateType, ThreeDigitZipcode, CarrierRoute, AADCCity, AADCState, AADCNumber, AADCId,
IsDetailRecord, IsZipcodeMixedAADCRecord, Zipcode
SELECT *
FROM @USPSQualificationReport
ORDER BY TrayNumber, TrayZipcode, GroupDestination
END
IF @BillSortOrder = 1
BEGIN
DROP TABLE #ZipcodeSummary
END
DROP TABLE #TempPrintBillServiceDetails
DROP TABLE #TempPrintEntireBill