Codeunit 8062 Billing Proposal
src/Apps/W1/Subscription Billing/App/Billing/Codeunits/BillingProposal.Codeunit.al1,174 lines, Copyright (c) Microsoft Corporation. MIT
namespace Microsoft.SubscriptionBilling;using Microsoft.Finance.Currency;using Microsoft.Finance.GeneralLedger.Setup;using Microsoft.Purchases.Document;using Microsoft.Sales.Document;using System.Security.User;using System.Utilities;codeunit 8062 "Billing Proposal"{ var SalesHeaderGlobal: Record "Sales Header"; PurchaseHeaderGlobal: Record "Purchase Header"; ProgressTracker: Codeunit "Sub. Billing Progress Tracker"; LastContractNo: Code[20]; LastPartnerNo: Code[20]; CreatingProposalLbl: Label 'Creating billing proposal...'; ContractDetailLbl: Label 'Contract %1', Comment = '%1 = Subscription Contract No.'; BillingToChangeNotAllowedErr: Label 'A change of Billing to field from %1 to %2 for %3 and %4 is not allowed because the Subscription Line has already been calculated up to %5.', Comment = '%1: Old Billing To Date, %2: New Billing To Date, %3: Subscription Contract No., %4: Subscription Contract Line No., %5: Last Billing To Date'; NoBillingDateErr: Label 'Please enter the Billing Date.'; BillingToChangeNotAllowedDocNoExistsErr: Label 'Billing to field is not allowed to change because an unposted invoice or credit memo exists.'; CreditMemoPreventsProposalCreationLbl: Label 'The credit memos listed here must be posted or deleted before further billing lines can be created.'; CreditMemoExistsForSubscriptionLineTxt: Label 'There is a credit memo that needs to be posted or deleted before an invoice can be created. Subscription: %1, Subscription Line Entry No.: %2', Comment = '%1: Subscription Header No., %2: Subscription Line Entry No.'; BillingLineWithoutInvoiceExistsQst: Label 'Billing lines without invoice exists. Contract line with existing billing line will not be considered when creating an invoice from the contract. Do you want to continue?'; BillingLineWithUnpostedSalesInvoiceExistsQst: Label 'Billing line with unposted Sales Invoice exists. New invoices cannot be created until the current invoice is posted. Do you want to open the invoice?'; BillingLineWithUnpostedPurchaseInvoiceExistsQst: Label 'Billing line with unposted Purchase Invoice exists. New invoices cannot be created until the current invoice is posted. Do you want to open the invoice?'; SalesCreditMemoExistsForBillingLineQst: Label 'There is a sales credit memo that needs to be posted before an invoice can be created. Do you want to open the credit memo?'; PurchaseCreditMemoExistsForBillingLineQst: Label 'There is a purchase credit memo that needs to be posted before an invoice can be created. Do you want to open the credit memo?'; BillingLinesForAllContractLinesExistsErr: Label 'There are billing lines for all contract lines. For contract lines with billing lines, the invoice must be created in recurring billing.'; NotAuthorizedToClearOrDeleteDocumentErr: Label 'You are not authorized to clear billing templates or delete billing documents. To perform these actions, you must be set up as an Auto Contract Billing user in the User Setup.'; ClearingBillingProposalLbl: Label 'Clearing billing proposal...'; DeletingBillingLinesLbl: Label 'Deleting billing lines...'; DeletingDocumentsLbl: Label 'Deleting billing documents...'; procedure InitTempTable(var TempBillingLine: Record "Billing Line" temporary; GroupBy: Enum "Contract Billing Grouping") var BillingLine: Record "Billing Line"; TempBillingLine2: Record "Billing Line" temporary; TempGroupBillingLine: Record "Billing Line" temporary; NextEntryNo: Integer; begin TempBillingLine2.CopyFilters(TempBillingLine); BillingLine.CopyFilters(TempBillingLine); TempBillingLine.Reset(); TempBillingLine.DeleteAll(false); SetKeysForGrouping(BillingLine, TempBillingLine, GroupBy); if BillingLine.FindSet() then repeat UpdateGroupingLine(TempGroupBillingLine, BillingLine, GroupBy); TempBillingLine := BillingLine; TempBillingLine.Indent := 1; TempBillingLine.Insert(false); until BillingLine.Next() = 0; if TempGroupBillingLine.FindSet() then repeat TempBillingLine := TempGroupBillingLine; NextEntryNo -= 1; TempBillingLine."Entry No." := NextEntryNo; TempBillingLine.Insert(false); until TempGroupBillingLine.Next() = 0; TempBillingLine.CopyFilters(TempBillingLine2); OnAfterInitTempTable(TempBillingLine, GroupBy); end; /// <summary> /// Rebuilds only the temporary rows of the groups touched by a selection-scoped action (for example Delete /// Billing Line or Change Billing To Date), instead of re-reading every Billing Line as InitTempTable does. /// Each affected group is dropped and rebuilt from the database, so the result is identical to a full rebuild /// for those groups - but the cost scales with the affected groups, not with the whole proposal. GroupKeys holds /// the Subscription Contract No. of each affected group, or the Partner No. when grouping by "Contract Partner". /// </summary> internal procedure RefreshGroupsInTempTable(var TempBillingLine: Record "Billing Line" temporary; GroupBy: Enum "Contract Billing Grouping"; GroupKeys: List of [Code[20]]) var PageFilterBillingLine: Record "Billing Line"; TempPageFilter: Record "Billing Line" temporary; GroupKey: Code[20]; NextHeaderEntryNo: Integer; begin if GroupKeys.Count = 0 then exit; TempPageFilter.CopyFilters(TempBillingLine); // remember the page view filters so they can be restored PageFilterBillingLine.CopyFilters(TempBillingLine); // page view filters (Partner, User ID) scope the DB read NextHeaderEntryNo := SmallestTempBillingLineEntryNo(TempBillingLine); foreach GroupKey in GroupKeys do begin DeleteTempRowsForGroup(TempBillingLine, GroupBy, GroupKey); RebuildTempRowsForGroup(TempBillingLine, PageFilterBillingLine, GroupBy, GroupKey, NextHeaderEntryNo); end; TempBillingLine.CopyFilters(TempPageFilter); end; local procedure SmallestTempBillingLineEntryNo(var TempBillingLine: Record "Billing Line" temporary): Integer begin // Group header rows use descending negative Entry No.; continue below the current minimum to avoid collisions. TempBillingLine.Reset(); if TempBillingLine.FindFirst() then // primary key ascending -> smallest Entry No. is first if TempBillingLine."Entry No." < 0 then exit(TempBillingLine."Entry No."); exit(0); end; local procedure DeleteTempRowsForGroup(var TempBillingLine: Record "Billing Line" temporary; GroupBy: Enum "Contract Billing Grouping"; GroupKey: Code[20]) begin TempBillingLine.Reset(); case GroupBy of GroupBy::"Contract Partner": TempBillingLine.SetRange("Partner No.", GroupKey); else TempBillingLine.SetRange("Subscription Contract No.", GroupKey); end; TempBillingLine.DeleteAll(false); TempBillingLine.Reset(); end; local procedure RebuildTempRowsForGroup(var TempBillingLine: Record "Billing Line" temporary; var PageFilterBillingLine: Record "Billing Line"; GroupBy: Enum "Contract Billing Grouping"; GroupKey: Code[20]; var NextHeaderEntryNo: Integer) var BillingLine: Record "Billing Line"; TempGroupBillingLine: Record "Billing Line" temporary; begin BillingLine.CopyFilters(PageFilterBillingLine); SetKeysForGrouping(BillingLine, TempBillingLine, GroupBy); // also resets Last* so the first row opens a new group case GroupBy of GroupBy::"Contract Partner": BillingLine.SetRange("Partner No.", GroupKey); else BillingLine.SetRange("Subscription Contract No.", GroupKey); end; if BillingLine.FindSet() then repeat UpdateGroupingLine(TempGroupBillingLine, BillingLine, GroupBy); TempBillingLine := BillingLine; TempBillingLine.Indent := 1; TempBillingLine.Insert(false); until BillingLine.Next() = 0; if TempGroupBillingLine.FindSet() then repeat TempBillingLine := TempGroupBillingLine; NextHeaderEntryNo -= 1; TempBillingLine."Entry No." := NextHeaderEntryNo; TempBillingLine.Insert(false); until TempGroupBillingLine.Next() = 0; end; local procedure SetKeysForGrouping(var BillingLine: Record "Billing Line"; var TempBillingLine: Record "Billing Line" temporary; GroupBy: Enum "Contract Billing Grouping") begin case GroupBy of GroupBy::Contract: begin BillingLine.SetCurrentKey("Subscription Contract No.", "Subscription Contract Line No.", "Billing from"); TempBillingLine.SetCurrentKey("Subscription Contract No.", "Subscription Contract Line No.", "Billing from"); LastContractNo := ''; end; GroupBy::"Contract Partner": begin BillingLine.SetCurrentKey("Partner No.", "Subscription Contract No.", "Subscription Contract Line No.", "Billing from"); TempBillingLine.SetCurrentKey("Partner No.", "Subscription Contract No.", "Subscription Contract Line No.", "Billing from"); LastPartnerNo := ''; end; GroupBy::None: TempBillingLine.SetCurrentKey("Partner No.", "Subscription Contract No.", "Subscription Contract Line No.", "Billing from"); end; end; local procedure UpdateGroupingLine(var TempGroupBillingLine: Record "Billing Line" temporary; BillingLine: Record "Billing Line"; GroupBy: Enum "Contract Billing Grouping") begin if GroupingLineShouldBeInserted(BillingLine, GroupBy) then begin TempGroupBillingLine.Init(); TempGroupBillingLine."User ID" := BillingLine."User ID"; TempGroupBillingLine."Entry No." := BillingLine."Entry No."; TempGroupBillingLine.Partner := BillingLine.Partner; TempGroupBillingLine."Partner No." := BillingLine."Partner No."; if GroupBy = GroupBy::Contract then TempGroupBillingLine."Subscription Contract No." := BillingLine."Subscription Contract No."; TempGroupBillingLine.Amount := GetServiceAmount(BillingLine, GroupBy); TempGroupBillingLine.Indent := 0; if BillingLine."Update Required" then TempGroupBillingLine."Update Required" := BillingLine."Update Required"; TempGroupBillingLine.Insert(false); end; if GroupBy = GroupBy::Contract then begin if (BillingLine."Billing from" < TempGroupBillingLine."Billing from") or (TempGroupBillingLine."Billing from" = 0D) then begin TempGroupBillingLine."Billing from" := BillingLine."Billing from"; TempGroupBillingLine.Modify(false); end; if BillingLine."Billing to" > TempGroupBillingLine."Billing to" then begin TempGroupBillingLine."Billing to" := BillingLine."Billing to"; TempGroupBillingLine.Modify(false); end; end; end; local procedure GetServiceAmount(BillingLine: Record "Billing Line"; GroupBy: Enum "Contract Billing Grouping"): Decimal var ContractBillingLine2: Record "Billing Line"; begin if GroupBy = GroupBy::None then exit; ContractBillingLine2.SetRange(Partner, BillingLine.Partner); case GroupBy of GroupBy::Contract: ContractBillingLine2.SetRange("Subscription Contract No.", BillingLine."Subscription Contract No."); GroupBy::"Contract Partner": ContractBillingLine2.SetRange("Partner No.", BillingLine."Partner No."); end; ContractBillingLine2.CalcSums(Amount); exit(ContractBillingLine2.Amount); end; local procedure GroupingLineShouldBeInserted(BillingLine: Record "Billing Line"; GroupBy: Enum "Contract Billing Grouping") InsertLine: Boolean begin case GroupBy of GroupBy::Contract: begin InsertLine := LastContractNo <> BillingLine."Subscription Contract No."; if InsertLine then LastContractNo := BillingLine."Subscription Contract No."; end; GroupBy::"Contract Partner": begin InsertLine := LastPartnerNo <> BillingLine."Partner No."; if InsertLine then LastPartnerNo := BillingLine."Partner No."; end; end; end; procedure CreateBillingProposal(BillingTemplateCode: Code[20]; BillingDate: Date; BillingToDate: Date) begin CreateBillingProposal(BillingTemplateCode, BillingDate, BillingToDate, false); end; procedure CreateBillingProposal(BillingTemplateCode: Code[20]; BillingDate: Date; BillingToDate: Date; AutomatedBilling: Boolean) var BillingTemplate: Record "Billing Template"; CustomerContract: Record "Customer Subscription Contract"; VendorContract: Record "Vendor Subscription Contract"; FilterText: Text; BillingRhythmFilterText: Text; ContractCounter: Integer; CommitBatchSize: Integer; begin SalesHeaderGlobal.Reset(); CommitBatchSize := 50; // Contracts processed per transaction checkpoint BillingTemplate.Get(BillingTemplateCode); if BillingDate = 0D then Error(NoBillingDateErr); if not DeleteUpdateRequiredBillingLines(BillingTemplateCode) then exit; if BillingTemplate.Filter.HasValue() then FilterText := BillingTemplate.ReadFilter(BillingTemplate.FieldNo(Filter)); OnCreateBillingProposalBeforeApplyFilterToContract(FilterText, BillingTemplate, BillingDate, BillingToDate); case BillingTemplate.Partner of "Service Partner"::Customer: begin if FilterText <> '' then CustomerContract.SetView(FilterText); BillingRhythmFilterText := CustomerContract.GetFilter("Billing Rhythm Filter"); this.ProgressTracker.StartActivity(CreatingProposalLbl, CustomerContract.Count()); if CustomerContract.FindSet() then repeat ContractCounter += 1; this.ProgressTracker.UpdateProgress(ContractCounter, StrSubstNo(ContractDetailLbl, CustomerContract."No.")); ProcessContractServiceCommitments(BillingTemplate, CustomerContract."No.", '', BillingDate, BillingToDate, BillingRhythmFilterText, AutomatedBilling); if ContractCounter mod CommitBatchSize = 0 then Commit(); until CustomerContract.Next() = 0; this.ProgressTracker.Finish(); end; "Service Partner"::Vendor: begin if FilterText <> '' then VendorContract.SetView(FilterText); BillingRhythmFilterText := VendorContract.GetFilter("Billing Rhythm Filter"); this.ProgressTracker.StartActivity(CreatingProposalLbl, VendorContract.Count()); if VendorContract.FindSet() then repeat ContractCounter += 1; this.ProgressTracker.UpdateProgress(ContractCounter, StrSubstNo(ContractDetailLbl, VendorContract."No.")); ProcessContractServiceCommitments(BillingTemplate, VendorContract."No.", '', BillingDate, BillingToDate, BillingRhythmFilterText, AutomatedBilling); if ContractCounter mod CommitBatchSize = 0 then Commit(); until VendorContract.Next() = 0; this.ProgressTracker.Finish(); end; end; // The remaining block only surfaces blocking credit memos to the user, so there is nothing to do // on the automated/background path or when no UI is available. if AutomatedBilling or not GuiAllowed() then exit; case BillingTemplate.Partner of Enum::"Service Partner"::Customer: begin SalesHeaderGlobal.MarkedOnly(true); if SalesHeaderGlobal.Count <> 0 then begin Page.Run(Page::"Sales Credit Memos", SalesHeaderGlobal); Message(CreditMemoPreventsProposalCreationLbl); end; end; Enum::"Service Partner"::Vendor: begin PurchaseHeaderGlobal.MarkedOnly(true); if PurchaseHeaderGlobal.Count <> 0 then begin Page.Run(Page::"Purchase Credit Memos", PurchaseHeaderGlobal); Message(CreditMemoPreventsProposalCreationLbl); end; end; end; end; local procedure ProcessContractServiceCommitments(BillingTemplate: Record "Billing Template"; ContractNo: Code[20]; ContractLineFilter: Text; BillingDate: Date; BillingToDate: Date; BillingRhythmFilterText: Text; AutomatedBilling: Boolean) var ServiceCommitment: Record "Subscription Line"; BillingLine: Record "Billing Line"; begin ServiceCommitment.SetRange(Partner, BillingTemplate.Partner); ServiceCommitment.SetRange("Subscription Contract No.", ContractNo); if ContractLineFilter <> '' then begin ServiceCommitment.SetRange("Usage Based Billing", true); ServiceCommitment.SetFilter("Subscription Contract Line No.", ContractLineFilter); end; ServiceCommitment.SetFilter("Next Billing Date", '<=%1&<>%2', BillingDate, 0D); if BillingRhythmFilterText <> '' then ServiceCommitment.SetFilter("Billing Rhythm", BillingRhythmFilterText); OnBeforeProcessContractSubscriptionLines(ServiceCommitment, BillingDate, BillingToDate, BillingRhythmFilterText, BillingTemplate); if ServiceCommitment.FindSet() then repeat ProcessServiceCommitment(ServiceCommitment, BillingLine, BillingTemplate, BillingDate, BillingToDate, AutomatedBilling); until ServiceCommitment.Next() = 0; OnAfterProcessContractSubscriptionLines(ServiceCommitment, BillingDate, BillingToDate, BillingRhythmFilterText); if BillingTemplate.IsPartnerCustomer() then RecalculateHarmonizedBillingFieldsBasedOnNextBillingDate(BillingLine, ContractNo); end; local procedure ProcessServiceCommitment(var ServiceCommitment: Record "Subscription Line"; var BillingLine: Record "Billing Line"; BillingTemplate: Record "Billing Template"; BillingDate: Date; BillingToDate: Date; AutomatedBilling: Boolean) var UsageDataBilling: Record "Usage Data Billing"; ContractBillingErrLog: Record "Contract Billing Err. Log"; SkipServiceCommitment: Boolean; BillingPeriodStart: Date; BillingPeriodEnd: Date; begin SkipServiceCommitment := false; FilterBillingLinesOnServiceCommitment(BillingLine, ServiceCommitment); case true of (ServiceCommitment."Subscription Line End Date" <> 0D) and (ServiceCommitment."Next Billing Date" > ServiceCommitment."Subscription Line End Date"): SkipServiceCommitment := true; BillingLine.FindFirst() and ((BillingLine."Document No." <> '') or (BillingTemplate.Code = '')): begin SkipServiceCommitment := true; case BillingLine.Partner of Enum::"Service Partner"::Customer: if SalesHeaderGlobal.Get(SalesHeaderGlobal."Document Type"::"Credit Memo", BillingLine."Document No.") then if AutomatedBilling or not GuiAllowed() then ContractBillingErrLog.InsertLogFromSubscriptionLine( BillingTemplate.Code, ServiceCommitment, CopyStr(StrSubstNo(CreditMemoExistsForSubscriptionLineTxt, ServiceCommitment."Subscription Header No.", ServiceCommitment."Entry No."), 1, 250)) else SalesHeaderGlobal.Mark(true); Enum::"Service Partner"::Vendor: if PurchaseHeaderGlobal.Get(PurchaseHeaderGlobal."Document Type"::"Credit Memo", BillingLine."Document No.") then if AutomatedBilling or not GuiAllowed() then ContractBillingErrLog.InsertLogFromSubscriptionLine( BillingTemplate.Code, ServiceCommitment, CopyStr(StrSubstNo(CreditMemoExistsForSubscriptionLineTxt, ServiceCommitment."Subscription Header No.", ServiceCommitment."Entry No."), 1, 250)) else PurchaseHeaderGlobal.Mark(true); end; end; ServiceCommitment."Usage Based Billing": begin UsageDataBilling.Reset(); UsageDataBilling.FilterOnServiceCommitment(ServiceCommitment); UsageDataBilling.SetRange("Document Type", "Usage Based Billing Doc. Type"::None); OnProcessSubscriptionLineOnAfterFilterUsageDataBilling(UsageDataBilling, ServiceCommitment); SkipServiceCommitment := UsageDataBilling.IsEmpty(); end; else OnCheckSkipSubscriptionLineOnElse(ServiceCommitment, SkipServiceCommitment); end; if not SkipServiceCommitment then begin CalculateBillingPeriod(ServiceCommitment, BillingDate, BillingToDate, BillingPeriodStart, BillingPeriodEnd); BillingLine.InitNewBillingLine(); UpdateBillingLine(BillingLine, ServiceCommitment, BillingTemplate, BillingPeriodStart, BillingPeriodEnd); end; end; local procedure FilterBillingLinesOnServiceCommitment(var BillingLine: Record "Billing Line"; ServiceCommitment: Record "Subscription Line") begin BillingLine.Reset(); BillingLine.SetRange("Subscription Line Entry No.", ServiceCommitment."Entry No."); end; local procedure DeleteUpdateRequiredBillingLines(BillingTemplateCode: Code[20]): Boolean var BillingLine: Record "Billing Line"; begin BillingLine.SetRange("Billing Template Code", BillingTemplateCode); BillingLine.SetRange("Update Required", true); if BillingLine.FindSet() then repeat DeleteBillingLinesForServiceObject(BillingLine); until BillingLine.Next() = 0; exit(true); end; local procedure UpdateBillingLine(var BillingLine: Record "Billing Line"; var ServiceCommitment: Record "Subscription Line"; BillingTemplate: Record "Billing Template"; BillingFrom: Date; BillingPeriodEnd: Date) var BillingLine2: Record "Billing Line"; NewBillingToDate, NewBillingToDate2, NewBillingFromDate2, SupplierChargeEndDate : Date; ServiceCommitmentNotEnded: Boolean; begin BillingLine."Billing from" := BillingFrom; if BillingLine."Billing from" > BillingPeriodEnd then exit; NewBillingToDate := CalculateNextBillingToDateForServiceCommitment(ServiceCommitment, BillingLine."Billing from"); if NewBillingToDate >= BillingPeriodEnd then BillingLine."Billing to" := BillingPeriodEnd else BillingLine."Billing to" := NewBillingToDate; UpdateBillingLineFromServiceCommitment(BillingLine, ServiceCommitment); CalculateBillingLineUnitAmountsAndServiceAmount(BillingLine, ServiceCommitment); BillingLine."Billing Template Code" := BillingTemplate.Code; BillingLine.Rebilling := BillingLine.RebillingUsageDataExist(); OnBeforeInsertBillingLineUpdateBillingLine(BillingLine, ServiceCommitment); if not BillingLine.Insert(false) then BillingLine.Modify(false); UpdateUsageDataBillingLineNoWhenBillingProposalIsCreated(BillingLine, ServiceCommitment); OnBeforeUpdateNextBillingDateInUpdateBillingLine(ServiceCommitment); ServiceCommitment.UpdateNextBillingDate(BillingLine."Billing to"); ServiceCommitment.Modify(false); NewBillingFromDate2 := ServiceCommitment.CalculateNextToDate(ServiceCommitment."Billing Rhythm", BillingLine."Billing from") + 1; if BillingLine.Rebilling then begin SupplierChargeEndDate := ServiceCommitment.GetSupplierChargeEndDateIfRebillingMetadataExist(BillingLine."Billing from"); if SupplierChargeEndDate <> 0D then NewBillingFromDate2 := SupplierChargeEndDate + 1; end; if NewBillingFromDate2 <= BillingLine."Billing to" then NewBillingFromDate2 := BillingLine."Billing to" + 1; NewBillingToDate2 := CalculateNextBillingToDateForServiceCommitment(ServiceCommitment, NewBillingFromDate2); if NewBillingToDate2 >= BillingPeriodEnd then NewBillingToDate2 := BillingPeriodEnd; ServiceCommitmentNotEnded := ServiceCommitment."Subscription Line End Date" = 0D; if not ServiceCommitmentNotEnded then ServiceCommitmentNotEnded := NewBillingFromDate2 <= ServiceCommitment."Subscription Line End Date"; if (NewBillingToDate <= BillingPeriodEnd) and ServiceCommitmentNotEnded then begin BillingLine2.InitNewBillingLine(); UpdateBillingLine(BillingLine2, ServiceCommitment, BillingTemplate, NewBillingFromDate2, BillingPeriodEnd);//recursion end; end; local procedure SetBillingLineUnitPriceAndServiceAmountsFromUsageDataBilling(var BillingLine: Record "Billing Line"; ServiceCommitment: Record "Subscription Line"): Boolean var UsageDataBilling: Record "Usage Data Billing"; CurrExchRate: Record "Currency Exchange Rate"; Currency: Record Currency; BaseAmount: Decimal; begin if not ServiceCommitment.IsUsageBasedBillingValid() then exit(false); if not ServiceCommitment.IsUsageDataBillingFound(UsageDataBilling, BillingLine."Billing from", BillingLine."Billing to") then exit(false); UsageDataBilling.CalcSums(Amount, "Cost Amount"); case BillingLine.Partner of Enum::"Service Partner"::Vendor: BaseAmount := UsageDataBilling."Cost Amount"; Enum::"Service Partner"::Customer: BaseAmount := UsageDataBilling.Amount; end; BillingLine.Amount := BaseAmount; UsageDataBilling.FindLast(); if UsageDataBilling.Rebilling or (UsageDataBilling."Usage Base Pricing" = Enum::"Usage Based Pricing"::"Usage Quantity") then BillingLine."Service Object Quantity" := UsageDataBilling.Quantity; if BillingLine."Service Object Quantity" <> 0 then BillingLine."Unit Price" := BillingLine.Amount / BillingLine."Service Object Quantity" else BillingLine."Unit Price" := UsageDataBilling."Unit Price"; BillingLine."Discount %" := ServiceCommitment."Discount %"; // Apply discount from Subscription Line BillingLine.Amount := BaseAmount * (1 - ServiceCommitment."Discount %" / 100); if UsageDataBilling.Quantity <> 0 then BillingLine."Unit Cost" := UsageDataBilling."Cost Amount" / UsageDataBilling.Quantity else BillingLine."Unit Cost" := UsageDataBilling."Unit Cost"; Currency.Initialize(ServiceCommitment."Currency Code"); Currency.TestField("Unit-Amount Rounding Precision"); BillingLine."Unit Cost (LCY)" := Round(CurrExchRate.ExchangeAmtFCYToLCY(ServiceCommitment."Currency Factor Date", ServiceCommitment."Currency Code", BillingLine."Unit Cost", ServiceCommitment."Currency Factor"), Currency."Unit-Amount Rounding Precision"); exit(true); end; local procedure CalculateBillingLineUnitAmountsAndServiceAmount(var BillingLine: Record "Billing Line"; ServiceCommitment: Record "Subscription Line") var Currency: Record Currency; GLSetup: Record "General Ledger Setup"; IsHandled: Boolean; begin OnBeforeCalculateBillingLineUnitAmountsAndServiceAmount(BillingLine, ServiceCommitment, IsHandled); if IsHandled then exit; if SetBillingLineUnitPriceAndServiceAmountsFromUsageDataBilling(BillingLine, ServiceCommitment) then exit; GLSetup.Get(); Currency.Initialize(ServiceCommitment."Currency Code"); ServiceCommitment.UnitPriceAndCostForPeriod(BillingLine."Billing Rhythm", BillingLine."Billing from", BillingLine."Billing to", BillingLine."Unit Price", BillingLine."Unit Cost", BillingLine."Unit Cost (LCY)", BillingLine."Billing Reference Date Changed"); BillingLine."Unit Price" := Round(BillingLine."Unit Price", Currency."Unit-Amount Rounding Precision"); BillingLine."Unit Cost" := Round(BillingLine."Unit Cost", Currency."Unit-Amount Rounding Precision"); BillingLine."Unit Cost (LCY)" := Round(BillingLine."Unit Cost (LCY)", GLSetup."Unit-Amount Rounding Precision"); BillingLine.Amount := Round(BillingLine."Unit Price" * BillingLine."Service Object Quantity" * (1 - BillingLine."Discount %" / 100), Currency."Amount Rounding Precision"); end; local procedure UpdateBillingLineFromServiceCommitment(var BillingLine: Record "Billing Line"; ServiceCommitment: Record "Subscription Line") var ServiceObject: Record "Subscription Header"; CustomerContract: Record "Customer Subscription Contract"; VendorContract: Record "Vendor Subscription Contract"; begin BillingLine."Subscription Header No." := ServiceCommitment."Subscription Header No."; BillingLine."Subscription Line Entry No." := ServiceCommitment."Entry No."; BillingLine."Subscription Line Description" := ServiceCommitment.Description; BillingLine."Subscription Line Start Date" := ServiceCommitment."Subscription Line Start Date"; BillingLine."Subscription Line End Date" := ServiceCommitment."Subscription Line End Date"; BillingLine."Billing Rhythm" := ServiceCommitment."Billing Rhythm"; BillingLine.Partner := ServiceCommitment.Partner; case ServiceCommitment.Partner of ServiceCommitment.Partner::Customer: begin CustomerContract.SetLoadFields("Sell-to Customer No.", "Detail Overview", "Currency Code"); CustomerContract.Get(ServiceCommitment."Subscription Contract No."); BillingLine."Partner No." := CustomerContract."Sell-to Customer No."; BillingLine."Detail Overview" := CustomerContract."Detail Overview"; BillingLine."Currency Code" := CustomerContract."Currency Code"; end; ServiceCommitment.Partner::Vendor: begin VendorContract.SetLoadFields("Pay-to Vendor No.", "Currency Code"); VendorContract.Get(ServiceCommitment."Subscription Contract No."); BillingLine."Partner No." := VendorContract."Pay-to Vendor No."; BillingLine."Currency Code" := VendorContract."Currency Code"; end; end; BillingLine."Subscription Contract No." := ServiceCommitment."Subscription Contract No."; BillingLine."Subscription Contract Line No." := ServiceCommitment."Subscription Contract Line No."; BillingLine."Discount %" := ServiceCommitment."Discount %"; BillingLine.Discount := ServiceCommitment.Discount; ServiceObject.SetLoadFields(Quantity); ServiceObject.Get(ServiceCommitment."Subscription Header No."); BillingLine."Service Object Quantity" := BillingLine.GetSign() * ServiceObject.Quantity; OnAfterUpdateBillingLineFromSubscriptionLine(BillingLine, ServiceCommitment); end; local procedure UpdateUsageDataBillingLineNoWhenBillingProposalIsCreated(BillingLine: Record "Billing Line"; SubscriptionLine: Record "Subscription Line") var UsageDataBilling: Record "Usage Data Billing"; begin if not SubscriptionLine.IsUsageBasedBillingValid() then exit; // Find all usage data billing records that overlap with the billing line period SubscriptionLine.SetUsageDataBillingFilters(UsageDataBilling, BillingLine."Billing from", BillingLine."Billing to"); UsageDataBilling.ModifyAll("Billing Line Entry No.", BillingLine."Entry No.", false); end; local procedure CalculateBillingPeriod(ServiceCommitment: Record "Subscription Line"; BillingDate: Date; BillToDate: Date; var BillingPeriodStart: Date; var BillingPeriodEnd: Date) var UsageDataBilling: Record "Usage Data Billing"; PreviousBillingPeriodEnd: Date; begin BillingPeriodEnd := 0D; BillingPeriodStart := ServiceCommitment."Next Billing Date"; if BillToDate <> 0D then begin BillingPeriodEnd := BillToDate; exit; end; if ServiceCommitment."Usage Based Billing" then begin UsageDataBilling.SetCurrentKey("Charge End Date"); UsageDataBilling.SetAscending("Charge End Date", true); UsageDataBilling.SetRange("Subscription Header No.", ServiceCommitment."Subscription Header No."); UsageDataBilling.SetRange("Subscription Line Entry No.", ServiceCommitment."Entry No."); UsageDataBilling.SetRange(Partner, ServiceCommitment.Partner); UsageDataBilling.SetRange("Document Type", "Usage Based Billing Doc. Type"::None); if UsageDataBilling.FindFirst() then BillingPeriodStart := UsageDataBilling."Charge Start Date"; if UsageDataBilling.FindLast() then BillingPeriodEnd := UsageDataBilling."Charge End Date"; exit; end; BillingPeriodEnd := CalculateNextBillingToDateForServiceCommitment(ServiceCommitment, BillingPeriodStart); PreviousBillingPeriodEnd := 0D; while (BillingPeriodEnd < BillingDate) and ((BillingPeriodEnd < ServiceCommitment."Subscription Line End Date") or (ServiceCommitment."Subscription Line End Date" = 0D)) and (BillingPeriodEnd > PreviousBillingPeriodEnd) do begin PreviousBillingPeriodEnd := BillingPeriodEnd; BillingPeriodEnd := CalculateNextBillingToDateForServiceCommitment(ServiceCommitment, BillingPeriodEnd + 1); end; end; procedure CalculateNextBillingToDateForServiceCommitment(ServiceCommitment: Record "Subscription Line"; BillingFromDate: Date) NextBillingToDate: Date var CustomerContract: Record "Customer Subscription Contract"; SupplierChargeEndDate: Date; CrossingChargeEndDate: Date; begin ServiceCommitment.TestField("Billing Rhythm"); NextBillingToDate := ServiceCommitment.CalculateNextToDate(ServiceCommitment."Billing Rhythm", BillingFromDate); if (NextBillingToDate >= ServiceCommitment."Subscription Line End Date") and (ServiceCommitment."Subscription Line End Date" <> 0D) then NextBillingToDate := ServiceCommitment."Subscription Line End Date"; SupplierChargeEndDate := ServiceCommitment.GetSupplierChargeEndDateIfRebillingMetadataExist(BillingFromDate); if SupplierChargeEndDate <> 0D then NextBillingToDate := SupplierChargeEndDate; CrossingChargeEndDate := ServiceCommitment.GetUsageDataChargeEndDateCrossingPeriodEnd(BillingFromDate, NextBillingToDate); while (CrossingChargeEndDate <> 0D) and (CrossingChargeEndDate > NextBillingToDate) do begin NextBillingToDate := CrossingChargeEndDate; CrossingChargeEndDate := ServiceCommitment.GetUsageDataChargeEndDateCrossingPeriodEnd(BillingFromDate, NextBillingToDate); end; if ServiceCommitment.IsPartnerCustomer() then begin CustomerContract.Get(ServiceCommitment."Subscription Contract No."); if CustomerContract.IsContractTypeSetAsHarmonizedBilling() then HarmonizeNextBillingTo(CustomerContract."Next Billing To", NextBillingToDate); end; OnAfterCalculateNextBillingToDateForSubscriptionLine(NextBillingToDate, ServiceCommitment, BillingFromDate); end; procedure DisplayErrorIfNotAuthorizedToClearProposalOrDeleteDocuments() var BillingTemplate: Record "Billing Template"; UserSetup: Record "User Setup"; begin BillingTemplate.SetFilter(Automation, '<>%1', BillingTemplate.Automation::None); if BillingTemplate.IsEmpty() then exit; if not UserSetup.AutoContractBillingAllowed() then Error(NotAuthorizedToClearOrDeleteDocumentErr); end; internal procedure DeleteBillingProposal(BillingTemplateCode: Code[20]) var BillingLine: Record "Billing Line"; BillingTemplate: Record "Billing Template"; ClearBillingProposalOptionsTxt: Label 'All billing proposals, Only current billing template proposal'; ClearBillingProposalOptionsMySuggestionsOnlyTxt: Label 'All billing proposals (user %1 only), Only current billing template proposal', Comment = '%1: User ID'; ClearBillingProposalQst: Label 'Which billing proposal(s) should be deleted?'; StrMenuResponse: Integer; Counter: Integer; begin DisplayErrorIfNotAuthorizedToClearProposalOrDeleteDocuments(); BillingTemplate.Get(BillingTemplateCode); if BillingTemplate."My Suggestions Only" then StrMenuResponse := Dialog.StrMenu(StrSubstNo(ClearBillingProposalOptionsMySuggestionsOnlyTxt, UserId()), 1, ClearBillingProposalQst) else StrMenuResponse := Dialog.StrMenu(ClearBillingProposalOptionsTxt, 1, ClearBillingProposalQst); BillingLine.SetCurrentKey("Subscription Header No.", "Subscription Line Entry No.", "Billing to"); BillingLine.SetAscending("Billing to", false); case StrMenuResponse of 0: Error(''); 1: begin BillingLine.SetRange(Partner, BillingTemplate.Partner); if BillingTemplate."My Suggestions Only" then BillingLine.SetRange("User ID", UserId()); this.ProgressTracker.StartActivity(ClearingBillingProposalLbl, BillingLine.Count()); if BillingLine.FindSet() then repeat Counter += 1; this.ProgressTracker.UpdateProgress(Counter, BillingLine."Subscription Contract No."); BillingLine.Delete(true); until BillingLine.Next() = 0; this.ProgressTracker.Finish(); end; 2: begin BillingLine.SetRange("Billing Template Code", BillingTemplate.Code); this.ProgressTracker.StartActivity(ClearingBillingProposalLbl, BillingLine.Count()); if BillingLine.FindSet() then repeat Counter += 1; this.ProgressTracker.UpdateProgress(Counter, BillingLine."Subscription Contract No."); BillingLine.Delete(true); until BillingLine.Next() = 0; this.ProgressTracker.Finish(); end; end; end; internal procedure DeleteBillingLines(var BillingLine: Record "Billing Line") var Counter: Integer; begin BillingLine.SetCurrentKey("Subscription Header No.", "Subscription Line Entry No.", "Billing to"); BillingLine.SetAscending("Billing to", false); this.ProgressTracker.StartActivity(DeletingBillingLinesLbl, BillingLine.Count()); if BillingLine.FindSet() then repeat Counter += 1; this.ProgressTracker.UpdateProgress(Counter, BillingLine."Subscription Contract No."); BillingLine.Delete(true); until BillingLine.Next() = 0; this.ProgressTracker.Finish(); end; local procedure DeleteBillingLinesForServiceObject(var BillingLine: Record "Billing Line") var BillingLine2: Record "Billing Line"; begin BillingLine2.SetCurrentKey("Subscription Header No.", "Subscription Line Entry No.", "Billing to"); BillingLine2.SetRange("Subscription Header No.", BillingLine."Subscription Header No."); BillingLine2.SetRange("Subscription Line Entry No.", BillingLine."Subscription Line Entry No."); BillingLine2.SetAscending("Billing to", false); if BillingLine2.FindSet() then repeat BillingLine2.Delete(true) until BillingLine2.Next() = 0; end; local procedure HarmonizeNextBillingTo(CustomerContractNextBillingTo: Date; var NextBillingToDate: Date) begin if CustomerContractNextBillingTo = 0D then exit; if NextBillingToDate < CustomerContractNextBillingTo then exit; NextBillingToDate := CustomerContractNextBillingTo end; local procedure BillingLinesForCustomerContractCreated(var BillingLine: Record "Billing Line"; CustomerContractNo: Code[20]): Boolean begin BillingLine.Reset(); BillingLine.SetRange("Subscription Contract No.", CustomerContractNo); exit(not BillingLine.IsEmpty()); end; local procedure RecalculateHarmonizedBillingFieldsBasedOnNextBillingDate(var BillingLines: Record "Billing Line"; CustomerContractNo: Code[20]) var CustomerContract: Record "Customer Subscription Contract"; begin if not BillingLinesForCustomerContractCreated(BillingLines, CustomerContractNo) then exit; if CustomerContractNo = '' then exit; CustomerContract.Get(CustomerContractNo); CustomerContract.RecalculateHarmonizedBillingFieldsBasedOnNextBillingDate(0); end; internal procedure UpdateBillingToDate(var BillingLine: Record "Billing Line"; NewBillingToDate: Date) var ServiceCommitment: Record "Subscription Line"; BillingTemplate: Record "Billing Template"; BillingPeriodStart: Date; BillingPeriodEnd: Date; begin if BillingLine.FindSet() then repeat if BillingLine."Document No." <> '' then Error(BillingToChangeNotAllowedDocNoExistsErr); ServiceCommitment.Get(BillingLine."Subscription Line Entry No."); OnAfterSubscriptionLineGetInUpdateBillingToDate(ServiceCommitment); if CalcDate('<+1D>', BillingLine."Billing to") = ServiceCommitment."Next Billing Date" then begin BillingTemplate.Get(BillingLine."Billing Template Code"); ServiceCommitment.UpdateNextBillingDate(BillingLine."Billing from" - 1); CalculateBillingPeriod(ServiceCommitment, 0D, NewBillingToDate, BillingPeriodStart, BillingPeriodEnd); UpdateBillingLine(BillingLine, ServiceCommitment, BillingTemplate, BillingPeriodStart, BillingPeriodEnd); end else Error(BillingToChangeNotAllowedErr, Format(BillingLine."Billing to"), Format(NewBillingToDate), BillingLine."Subscription Contract No.", BillingLine."Subscription Header No.", Format(CalcDate('<-1D>', ServiceCommitment."Next Billing Date"))); until BillingLine.Next() = 0; end; internal procedure CreateBillingProposalFromContract(ContractNo: Code[20]; BillingRhytmFilter: Text; ServicePartner: Enum "Service Partner") var CreateBillingDocumentPage: Page "Create Billing Document"; IsHandled: Boolean; begin OnBeforeCreateBillingProposalFromContract(ContractNo, BillingRhytmFilter, ServicePartner, IsHandled); if IsHandled then exit; if not BillingProposalCanBeCreatedForContract(ContractNo, ServicePartner) then exit; CreateBillingDocumentPage.SetContractData(ServicePartner, ContractNo, BillingRhytmFilter); CreateBillingDocumentPage.RunModal(); end; local procedure ErrorIfBillingLinesForAllContractLinesExist(ContractNo: Code[20]; ServicePartner: Enum "Service Partner"): Boolean var ContractLineWithoutBillingLineExists: Boolean; begin case ServicePartner of "Service Partner"::Customer: ContractLineWithoutBillingLineExists := CheckIfBillingLineForCustomerContractLineDoesNotExist(ContractNo); "Service Partner"::Vendor: ContractLineWithoutBillingLineExists := CheckIfBillingLineForVendorContractLineDoesNotExist(ContractNo); end; if ContractLineWithoutBillingLineExists then exit; Error(BillingLinesForAllContractLinesExistsErr); end; local procedure CheckIfBillingLineWithUnpostedDocumentExists(var BillingLine: Record "Billing Line"; ContractNo: Code[20]; ServicePartner: Enum "Service Partner"; BillingDocumentType: Enum "Rec. Billing Document Type"): Boolean begin BillingLine.FilterBillingLineOnContract(ServicePartner, ContractNo); BillingLine.SetRange("Document Type", BillingDocumentType); BillingLine.SetFilter("Document No.", '<>%1', ''); exit(not BillingLine.IsEmpty()); end; internal procedure CreateBillingProposalForContract(ServicePartner: Enum "Service Partner"; ContractNo: Code[20]; ContractLineFilter: Text; BillingRhythmFilter: Text; BillingDate: Date; BillingToDate: Date) var TempBillingTemplate: Record "Billing Template" temporary; begin CreateTempBillingTemplate(TempBillingTemplate, ServicePartner); ProcessContractServiceCommitments(TempBillingTemplate, ContractNo, ContractLineFilter, BillingDate, BillingToDate, BillingRhythmFilter, false); end; procedure CreateBillingProposalForPurchaseHeader(ServicePartner: Enum "Service Partner"; var TempServiceCommitment: Record "Subscription Line" temporary; BillingDate: Date; BillingToDate: Date) var DummyPurchaseLine: Record "Purchase Line"; begin CreateBillingProposalForPurchaseLine(ServicePartner, TempServiceCommitment, BillingDate, BillingToDate, DummyPurchaseLine); end; procedure CreateBillingProposalForPurchaseLine(ServicePartner: Enum "Service Partner"; var TempServiceCommitment: Record "Subscription Line" temporary; BillingDate: Date; BillingToDate: Date; var PurchaseLine: Record "Purchase Line") var TempBillingTemplate: Record "Billing Template" temporary; ServiceCommitment: Record "Subscription Line"; BillingLine: Record "Billing Line"; begin CreateTempBillingTemplate(TempBillingTemplate, ServicePartner); if TempServiceCommitment.FindSet() then repeat ProcessServiceCommitment(TempServiceCommitment, BillingLine, TempBillingTemplate, BillingDate, BillingToDate, false); if PurchaseLine."Document No." <> '' then SyncPurchaseLineAndBillingLine(BillingLine, PurchaseLine); if ServiceCommitment.Get(TempServiceCommitment."Entry No.") then begin ServiceCommitment."Next Billing Date" := TempServiceCommitment."Next Billing Date"; ServiceCommitment.Modify(); end; until TempServiceCommitment.Next() = 0; AddRecurringBillingFlagToExistingPurchaseHeader(PurchaseLine."Document Type", PurchaseLine."Document No."); end; procedure CreatePurchaseLines(PurchaseHeader: Record "Purchase Header") var BillingLine: Record "Billing Line"; CreateBillingDocuments: Codeunit "Create Billing Documents"; begin BillingLine.SetRange("Billing Template Code", ''); if BillingLine.IsEmpty() then exit; CreateBillingDocuments.SetPurchaseHeaderFromExistingPurchaseDocument(PurchaseHeader."Document Type", PurchaseHeader."No."); CreateBillingDocuments.SetSkipRequestPageSelection(true); CreateBillingDocuments.SetHideProcessingFinishedMessage(); CreateBillingDocuments.Run(BillingLine); end; local procedure SyncPurchaseLineAndBillingLine(var BillingLine: Record "Billing Line"; var PurchaseLine: Record "Purchase Line") begin if PurchaseLine."Document No." = '' then exit; BillingLine."Document Type" := BillingLine.GetBillingDocumentTypeFromPurchaseDocumentType(PurchaseLine."Document Type"); BillingLine."Document No." := PurchaseLine."Document No."; BillingLine."Document Line No." := PurchaseLine."Line No."; BillingLine.Modify(); PurchaseLine."Recurring Billing from" := BillingLine."Billing from"; PurchaseLine."Recurring Billing to" := BillingLine."Billing to"; PurchaseLine.Modify(false); end; local procedure AddRecurringBillingFlagToExistingPurchaseHeader(DocumentType: Enum "Purchase Document Type"; DocumentNo: Code[20]) begin if DocumentNo = '' then exit; PurchaseHeaderGlobal.Get(DocumentType, DocumentNo); PurchaseHeaderGlobal.SetRecurringBilling(); end; local procedure BillingProposalCanBeCreatedForContract(ContractNo: Code[20]; ServicePartner: Enum "Service Partner"): Boolean var BillingLine: Record "Billing Line"; ConfirmManagement: Codeunit "Confirm Management"; begin if CheckIfBillingLineWithUnpostedDocumentExists(BillingLine, ContractNo, ServicePartner, "Rec. Billing Document Type"::"Credit Memo") then begin if ConfirmManagement.GetResponse(GetCreditMemoExistsForBillingLineQst(ServicePartner), true) then begin BillingLine.FindFirst(); BillingLine.OpenDocumentCard(); end; exit(false); end; if CheckIfBillingLineWithUnpostedDocumentExists(BillingLine, ContractNo, ServicePartner, "Rec. Billing Document Type"::Invoice) then begin if ConfirmManagement.GetResponse(GetBillingLineWithUnpostedInvoiceExistsQst(ServicePartner), true) then begin BillingLine.FindFirst(); BillingLine.OpenDocumentCard(); end; exit(false); end; ErrorIfBillingLinesForAllContractLinesExist(ContractNo, ServicePartner); if CheckIfBillingLineForContractExists(ContractNo, ServicePartner) then if not ConfirmManagement.GetResponse(BillingLineWithoutInvoiceExistsQst, true) then exit(false); exit(true); end; local procedure CreateTempBillingTemplate(var TempBillingTemplate: Record "Billing Template" temporary; ServicePartner: Enum "Service Partner") begin TempBillingTemplate.Init(); TempBillingTemplate.Partner := ServicePartner; TempBillingTemplate.Insert(false); end; procedure CreateBillingDocument(ServicePartner: Enum "Service Partner"; ContractNo: Code[20]; DocumentDate: Date; PostingDate: Date; PostDocument: Boolean; OpenDocument: Boolean): Boolean var BillingLine: Record "Billing Line"; CreateBillingDocuments: Codeunit "Create Billing Documents"; begin BillingLine.SetRange("Billing Template Code", ''); if BillingLine.IsEmpty() then exit(false); CreateBillingDocuments.SetBillingGroupingPerContract(ServicePartner); CreateBillingDocuments.SetDocumentDataFromRequestPage(DocumentDate, PostingDate, PostDocument, true); CreateBillingDocuments.SetSkipRequestPageSelection(true); CreateBillingDocuments.Run(BillingLine); Commit(); // Commit before RunModal if OpenDocument then FindBillingLineAndOpenDocumentCard(ContractNo); exit(true); end; local procedure FindBillingLineAndOpenDocumentCard(ContractNo: Code[20]) var BillingLine: Record "Billing Line"; begin BillingLine.SetRange("Billing Template Code", ''); BillingLine.SetRange("Subscription Contract No.", ContractNo); BillingLine.FindLast(); BillingLine.OpenDocumentCard() end; local procedure GetCreditMemoExistsForBillingLineQst(ServicePartner: Enum "Service Partner"): Text begin case ServicePartner of "Service Partner"::Customer: exit(SalesCreditMemoExistsForBillingLineQst); "Service Partner"::Vendor: exit(PurchaseCreditMemoExistsForBillingLineQst); end; end; local procedure GetBillingLineWithUnpostedInvoiceExistsQst(ServicePartner: Enum "Service Partner"): Text begin case ServicePartner of "Service Partner"::Customer: exit(BillingLineWithUnpostedSalesInvoiceExistsQst); "Service Partner"::Vendor: exit(BillingLineWithUnpostedPurchaseInvoiceExistsQst); end; end; local procedure CheckIfBillingLineForCustomerContractLineDoesNotExist(ContractNo: Code[20]): Boolean var CustomerContractLine: Record "Cust. Sub. Contract Line"; BillingLine: Record "Billing Line"; begin CustomerContractLine.SetRange("Subscription Contract No.", ContractNo); CustomerContractLine.FilterOnServiceObjectContractLineType(); if CustomerContractLine.FindSet() then repeat BillingLine.FilterBillingLineOnContractLine("Service Partner"::Customer, ContractNo, CustomerContractLine."Line No."); if BillingLine.IsEmpty then exit(true); until CustomerContractLine.Next() = 0; end; local procedure CheckIfBillingLineForVendorContractLineDoesNotExist(ContractNo: Code[20]): Boolean var VendorContractLine: Record "Vend. Sub. Contract Line"; BillingLine: Record "Billing Line"; begin VendorContractLine.SetRange("Subscription Contract No.", ContractNo); VendorContractLine.FilterOnServiceObjectContractLineType(); if VendorContractLine.FindSet() then repeat BillingLine.FilterBillingLineOnContractLine("Service Partner"::Vendor, ContractNo, VendorContractLine."Line No."); if BillingLine.IsEmpty then exit(true); until VendorContractLine.Next() = 0; end; local procedure CheckIfBillingLineForContractExists(ContractNo: Code[20]; ServicePartner: Enum "Service Partner"): Boolean var BillingLine: Record "Billing Line"; begin BillingLine.FilterBillingLineOnContract(ServicePartner, ContractNo); exit(not BillingLine.IsEmpty()); end; internal procedure DeleteBillingDocuments(BillingTemplateCode: Code[20]) var BillingLine: Record "Billing Line"; BillingTemplate: Record "Billing Template"; DeleteBillingDocumentQst: Label 'Which contract billing documents should be deleted?'; DeleteBillingDocumentOptionsTxt: Label 'All Documents,Documents from current billing template only'; DeleteBillingDocumentOptionsMySuggestionsOnlyTxt: Label 'All Documents (user %1 only),Documents from current billing template only', Comment = '%1: User ID'; PreviousDocumentNo: Code[20]; StrMenuResponse: Integer; Counter: Integer; begin PreviousDocumentNo := ''; DisplayErrorIfNotAuthorizedToClearProposalOrDeleteDocuments(); BillingTemplate.Get(BillingTemplateCode); if BillingTemplate."My Suggestions Only" then StrMenuResponse := Dialog.StrMenu(StrSubstNo(DeleteBillingDocumentOptionsMySuggestionsOnlyTxt, UserId()), 1, DeleteBillingDocumentQst) else StrMenuResponse := Dialog.StrMenu(DeleteBillingDocumentOptionsTxt, 1, DeleteBillingDocumentQst); // Sort by document so same-document billing lines are adjacent; the loop skips duplicate document nos so each // document is deleted exactly once and the progress counter reflects documents, not billing lines. BillingLine.SetLoadFields("Document Type", "Document No.", "Partner", "User ID", "Billing Template Code"); BillingLine.SetCurrentKey("Document Type", "Document No."); BillingLine.SetFilter("Document No.", '<>%1', ''); case StrMenuResponse of 0: Error(''); 1: begin BillingLine.SetRange(Partner, BillingTemplate.Partner); if BillingTemplate."My Suggestions Only" then BillingLine.SetRange("User ID", UserId()); this.ProgressTracker.StartActivity(DeletingDocumentsLbl, this.CountDistinctDocuments(BillingLine)); if BillingLine.FindSet() then repeat if BillingLine."Document No." <> PreviousDocumentNo then begin Counter += 1; this.ProgressTracker.UpdateProgress(Counter, BillingLine."Document No."); this.DeleteBillingDocuments(BillingLine); PreviousDocumentNo := BillingLine."Document No."; end; until BillingLine.Next() = 0; this.ProgressTracker.Finish(); end; 2: begin BillingLine.SetRange("Billing Template Code", BillingTemplate.Code); this.ProgressTracker.StartActivity(DeletingDocumentsLbl, this.CountDistinctDocuments(BillingLine)); if BillingLine.FindSet() then repeat if BillingLine."Document No." <> PreviousDocumentNo then begin Counter += 1; this.ProgressTracker.UpdateProgress(Counter, BillingLine."Document No."); this.DeleteBillingDocuments(BillingLine); PreviousDocumentNo := BillingLine."Document No."; end; until BillingLine.Next() = 0; this.ProgressTracker.Finish(); end; end; end; local procedure CountDistinctDocuments(var BillingLine: Record "Billing Line"): Integer var PrevDocumentNo: Code[20]; DocCount: Integer; begin PrevDocumentNo := ''; if BillingLine.FindSet() then repeat if BillingLine."Document No." <> PrevDocumentNo then begin DocCount += 1; PrevDocumentNo := BillingLine."Document No."; end; until BillingLine.Next() = 0; exit(DocCount); end; local procedure DeleteBillingDocuments(BillingLine: Record "Billing Line") var SalesHeader: Record "Sales Header"; PurchaseHeader: Record "Purchase Header"; begin case BillingLine.Partner of BillingLine.Partner::Customer: if SalesHeader.Get(BillingLine.GetSalesDocumentTypeFromBillingDocumentType(), BillingLine."Document No.") then SalesHeader.Delete(true); BillingLine.Partner::Vendor: if PurchaseHeader.Get(BillingLine.GetPurchaseDocumentTypeFromBillingDocumentType(), BillingLine."Document No.") then PurchaseHeader.Delete(true); end; end; [IntegrationEvent(false, false)] local procedure OnAfterUpdateBillingLineFromSubscriptionLine(var BillingLine: Record "Billing Line"; SubscriptionLine: Record "Subscription Line") begin end; [IntegrationEvent(false, false)] local procedure OnBeforeProcessContractSubscriptionLines(var SubscriptionLine: Record "Subscription Line"; BillingDate: Date; BillingToDate: Date; BillingRhythmFilterText: Text; BillingTemplate: Record "Billing Template") begin end; [IntegrationEvent(false, false)] local procedure OnAfterProcessContractSubscriptionLines(var SubscriptionLine: Record "Subscription Line"; BillingDate: Date; BillingToDate: Date; BillingRhythmFilterText: Text) begin end; [IntegrationEvent(false, false)] local procedure OnBeforeCreateBillingProposalFromContract(ContractNo: Code[20]; BillingRhytmFilter: Text; ServicePartner: Enum "Service Partner"; var IsHandled: Boolean) begin end; [IntegrationEvent(false, false)] local procedure OnAfterCalculateNextBillingToDateForSubscriptionLine(var NextBillingToDate: Date; SubscriptionLine: Record "Subscription Line"; BillingFromDate: Date) begin end; [IntegrationEvent(false, false)] local procedure OnBeforeInsertBillingLineUpdateBillingLine(var BillingLine: Record "Billing Line"; SubscriptionLine: Record "Subscription Line") begin end; [IntegrationEvent(false, false)] local procedure OnAfterInitTempTable(var TempBillingLine: Record "Billing Line" temporary; GroupBy: Enum "Contract Billing Grouping") begin end; [IntegrationEvent(false, false)] local procedure OnBeforeUpdateNextBillingDateInUpdateBillingLine(var SubscriptionLine: Record "Subscription Line") begin end; [IntegrationEvent(false, false)] local procedure OnAfterSubscriptionLineGetInUpdateBillingToDate(var SubscriptionLine: Record "Subscription Line") begin end; [IntegrationEvent(false, false)] local procedure OnCheckSkipSubscriptionLineOnElse(SubscriptionLine: Record "Subscription Line"; var SkipSubscriptionLine: Boolean) begin end; [IntegrationEvent(false, false)] local procedure OnProcessSubscriptionLineOnAfterFilterUsageDataBilling(var UsageDataBilling: Record "Usage Data Billing"; SubscriptionLine: Record "Subscription Line") begin end; [IntegrationEvent(false, false)] local procedure OnCreateBillingProposalBeforeApplyFilterToContract(var FilterText: Text; var BillingTemplate: Record "Billing Template"; BillingDate: Date; BillingToDate: Date) begin end; [IntegrationEvent(false, false)] local procedure OnBeforeCalculateBillingLineUnitAmountsAndServiceAmount(var BillingLine: Record "Billing Line"; SubscriptionLine: Record "Subscription Line"; var IsHandled: Boolean) begin end;}