[W1][Codeunit][1303][CorrectPostedSalesInvoice] Add OnBefore IsHandled event to UpdateSalesOrderLinesFromCreditMemo
Why do you need this change?
When a sales credit memo is posted in Business Central, Codeunit 1303 "Correct Posted Sales Invoice" reaches back into the originating Sales Order and mutates it ; decrements "Quantity Invoiced" / "Qty. Invoiced (Base)" and "Quantity Shipped" / "Qty. Shipped (Base)", re-runs InitOutstanding / InitQtyToShip / UpdateWithWarehouseShip, reverses prepayment fields, flips Warehouse Request."Completely Handled" from true to false, and undoes posted item tracking via UndoPostingManagement.RevertPostedItemTracking.
For many partner verticals (wholesale, retail, logistics, manufacturing) this behavior is unwanted. A fully shipped, fully invoiced sales order represents a closed historical transaction: the goods physically left the warehouse and reached the customer, and the credit memo is a new accounting event (refund, price correction) ; not a rewind of the order. The current behavior causes orders to visibly "reopen" with outstanding quantities in planning and BI, warehouse requests to reappear in warehouse pages as incomplete, lot/serial tracking to be undone on shipments that already physically departed, and prepayment balances on closed orders to shift unexpectedly.
Three of the four entry paths into this behavior already have top-level OnBefore* IsHandled events partners can subscribe to ;OnBeforeUpdateSalesOrderLineIfExist on the Sales Header table (paths 1 & 2: Sales Credit Memo page Post, Posted Sales Credit Memos page action), and OnBeforeUpdateSalesOrderLinesFromCancelledInvoice in CU 1303 at line 1013 (path 3: Cancel / Correct / Create Corrective Credit Memo from Posted Sales Invoice).
The fourth path ÔÇö Sales Return Order posting (CU 80 Sales-Post line 3274) ; has no top-level event. It enters UpdateSalesOrderLinesFromCreditMemo (CU 1303 line 987) directly, bypassing the Sales Header wrapper, and the only event it reaches is the deeply nested OnBeforeUpdateSalesOrderLineInvoicedQuantity ; which covers only the quantity mutation and leaves prepayment, warehouse request, and item tracking side-effects untouched. Partners are left with either partial coverage (semantically wrong: qty preserved but the other three mutations still applied) or a session-state workaround that spans multiple tables and platform-level OnBeforeModifyEvent subscribers, which is fragile, invasive, and hard to reason about.
Adding a single OnBefore IsHandled event at the start of UpdateSalesOrderLinesFromCreditMemo closes this gap symmetrically with zero breaking change, matches the exact pattern already used by the sibling procedure in the same codeunit, and lets partners opt out of the Sales Order write-back cleanly on all four paths with a single subscriber.
Describe the request
Base App version reviewed: 27.5.46862.47988
Problem statement
Codeunit 1303 "Correct Posted Sales Invoice" has a sub-procedure UpdateSalesOrderLinesFromCreditMemo (line 987) that mutates the originating Sales Order whenever a credit memo is posted. Four entry paths reach it; three have top-level IsHandled events, the fourth does not:
| # | User action | Call chain | Existing top-level seam |
|---|---|---|---|
| 1 | Sales Credit Memo page  Post | SalesCreditMemo.Page.al:1740  Sales Header.UpdateSalesOrderLineIfExist  CU 1303.UpdateSalesOrderLineIfExist  UpdateSalesOrderLinesFromCreditMemo |
OnBeforeUpdateSalesOrderLineIfExist on table Sales Header Ô£ô |
| 2 | Posted Sales Credit Memos page action | SalesCreditMemos.Page.al:853  same Sales Header wrapper |
Same event as path 1 Ô£ô |
| 3 | Posted Sales Invoice  Cancel / Correct / Create Corrective Credit Memo | CU 1303.OnRun  UpdateSalesOrderLinesFromCancelledInvoice (line 1004) |
OnBeforeUpdateSalesOrderLinesFromCancelledInvoice in CU 1303 line 1013 Ô£ô |
| 4 | Sales Return Order posting | CU 80 Sales-Post.Codeunit.al:3274  local UpdateSalesOrderLineIfExist (CU 80 line 8870)  CU 1303.UpdateSalesOrderLineIfExist (directly, bypassing the Sales Header wrapper)  UpdateSalesOrderLinesFromCreditMemo |
No top-level event. Only the deeply-nested OnBeforeUpdateSalesOrderLineInvoicedQuantity (CU 1303 line 1052), which covers only step (1) of four. |
The gap is real: partners cannot cleanly opt out of the Sales Order revert on path 4 without invasive session-state workarounds.
Alternatives evaluated
-
Subscribe to
OnBeforeUpdateSalesOrderLineInvoicedQuantity(CU 1303 line 1052) and setIsHandled := true. Rejected ÔÇö blocks only the quantity mutation (step 1 of 4). The three remaining operations still execute, leaving the Sales Order in an inconsistent state: quantities preserved, but prepayment reversed, warehouse request reopened, and posted item tracking reverted. Semantically wrong. -
Session-scoped workaround with
SingleInstancecodeunit +OnBeforePostSalesDoc/OnAfterPostSalesDocsetting a flag, plus platform-levelOnBeforeModifyEventsubscribers onSales LineandWarehouse RequestandOnBeforeRevertPostedItemTrackingonUndo Posting Management, each gated by the flag. Rejected ÔÇö theSales Line OnBeforeModifyEventsubscriber fires for every Sales Line modify in the session; if the flag gets stuck (errored post, exception beforeOnAfterPostSalesDoc) the subscriber silently reverts prepayment modifications on unrelated orders. Spans multiple tables and codeunits, fragile, hard to reason about, invasively impacts the posting code path for what should be a single IsHandled subscription. -
Subscribe to
OnBeforeModifyEventonSales Line/Warehouse Request/Reservation Entrywithout a session flag. Rejected ÔÇö far too wide, catches every modification anywhere in BC, not usable in production. -
Do not support Sales Return Order posting in the partner extension. Rejected ÔÇö functional regression, not acceptable to our customer.
Proposed publisher location
- Object: Codeunit 1303
"Correct Posted Sales Invoice" - Procedure:
UpdateSalesOrderLinesFromCreditMemo(line 987) - Placement: at the very start of the procedure body, before the existing
if SalesLine.Get(...)block. - Placement rationale: matches the exact pattern of the sibling
OnBeforeUpdateSalesOrderLinesFromCancelledInvoiceat line 1013 insideUpdateSalesOrderLinesFromCancelledInvoice(line 1004). Publisher declaration lives alongside the existingOnBeforeUpdateSalesOrderLinesFromCancelledInvoicedeclaration (CU 1303 line 1347). Symmetric pair.
Proposed code snippet (before  after)
Before ÔÇö CU 1303 line 987 (today)
local procedure UpdateSalesOrderLinesFromCreditMemo(SalesInvoiceLine: Record "Sales Invoice Line"; SalesCrMemoLine: Record "Sales Cr.Memo Line")
var
TempItemLedgerEntry: Record "Item Ledger Entry" temporary;
SalesLine: Record "Sales Line";
UndoPostingManagement: Codeunit "Undo Posting Management";
begin
if SalesLine.Get(SalesLine."Document Type"::Order, SalesInvoiceLine."Order No.", SalesInvoiceLine."Order Line No.") then begin
SalesInvoiceLine.GetItemLedgEntries(TempItemLedgerEntry, false);
UpdateSalesOrderLineInvoicedQuantity(SalesLine, SalesCrMemoLine.Quantity, SalesCrMemoLine."Quantity (Base)");
UpdateSalesOrderLinePrepmtAmount(SalesInvoiceLine);
if SalesLine."Qty. to Ship" = 0 then
UpdateWhseRequest(Database::"Sales Line", SalesLine."Document Type".AsInteger(), SalesLine."Document No.", SalesLine."Location Code");
TempItemLedgerEntry.SetFilter("Item Tracking", '<>%1', TempItemLedgerEntry."Item Tracking"::None.AsInteger());
UndoPostingManagement.RevertPostedItemTracking(TempItemLedgerEntry, SalesInvoiceLine."Shipment Date", true);
end;
end;
After ÔÇö proposed change
local procedure UpdateSalesOrderLinesFromCreditMemo(SalesInvoiceLine: Record "Sales Invoice Line"; SalesCrMemoLine: Record "Sales Cr.Memo Line")
var
TempItemLedgerEntry: Record "Item Ledger Entry" temporary;
SalesLine: Record "Sales Line";
UndoPostingManagement: Codeunit "Undo Posting Management";
IsHandled: Boolean;
begin
IsHandled := false;
OnBeforeUpdateSalesOrderLinesFromCreditMemo(SalesInvoiceLine, SalesCrMemoLine, IsHandled);
if IsHandled then
exit;
if SalesLine.Get(SalesLine."Document Type"::Order, SalesInvoiceLine."Order No.", SalesInvoiceLine."Order Line No.") then begin
SalesInvoiceLine.GetItemLedgEntries(TempItemLedgerEntry, false);
UpdateSalesOrderLineInvoicedQuantity(SalesLine, SalesCrMemoLine.Quantity, SalesCrMemoLine."Quantity (Base)");
UpdateSalesOrderLinePrepmtAmount(SalesInvoiceLine);
if SalesLine."Qty. to Ship" = 0 then
UpdateWhseRequest(Database::"Sales Line", SalesLine."Document Type".AsInteger(), SalesLine."Document No.", SalesLine."Location Code");
TempItemLedgerEntry.SetFilter("Item Tracking", '<>%1', TempItemLedgerEntry."Item Tracking"::None.AsInteger());
UndoPostingManagement.RevertPostedItemTracking(TempItemLedgerEntry, SalesInvoiceLine."Shipment Date", true);
end;
end;
New publisher declaration (to add near the existing sibling at line 1347)
[IntegrationEvent(false, false)]
local procedure OnBeforeUpdateSalesOrderLinesFromCreditMemo(var SalesInvoiceLine: Record "Sales Invoice Line"; var SalesCrMemoLine: Record "Sales Cr.Memo Line"; var IsHandled: Boolean)
begin
end;
Parameter choice rationale:
var SalesInvoiceLine: Record "Sales Invoice Line"ÔÇö lets subscribers inspect the invoice line being reverted.var SalesCrMemoLine: Record "Sales Cr.Memo Line"ÔÇö lets subscribers inspect the cr. memo line that triggered the revert (gating on Return Reason Code, customer, etc.).var IsHandled: BooleanÔÇö standard BC IsHandled pattern.
All three parameters are var to match the convention of OnBeforeUpdateSalesOrderLineInvoicedQuantity (line 1267) and the sibling OnBeforeUpdateSalesOrderLinesFromCancelledInvoice (line 1347).
Subscriber example (illustrative)
[EventSubscriber(ObjectType::Codeunit, Codeunit::"Correct Posted Sales Invoice", OnBeforeUpdateSalesOrderLinesFromCreditMemo, '', false, false)]
local procedure Codeunit1303_OnBeforeUpdateSalesOrderLinesFromCreditMemo(var SalesInvoiceLine: Record "Sales Invoice Line"; var SalesCrMemoLine: Record "Sales Cr.Memo Line"; var IsHandled: Boolean)
var
SalesReceivablesSetup: Record "Sales & Receivables Setup";
begin
if not SalesReceivablesSetup.Get() then
exit;
if not SalesReceivablesSetup."Reopen SO on Credit Memo" then
IsHandled := true;
end;
Combined with the existing OnBeforeUpdateSalesOrderLineIfExist (Sales Header, paths 1/2) and OnBeforeUpdateSalesOrderLinesFromCancelledInvoice (path 3), this single new subscriber closes path 4 and gives full symmetric coverage with no session state and no platform-level table event subscriptions.
Performance & data considerations
- Frequency: the event fires once per invoice line being credited, inside an existing posting transaction. Same frequency as the sibling
OnBeforeUpdateSalesOrderLinesFromCancelledInvoice, which has been in production for years with no reported performance concerns. - Dataset size: no loops, no large-scale record enumeration introduced by the event itself. The event is published at the top of an already-executing line-level procedure.
- Locking / transactions: no change. The event fires inside the same transaction scope as the existing code. Subscribers that set
IsHandled := truecause less work to be done (theSalesLine.Get, the four updates, and theRevertPostedItemTrackingcall are all skipped), so the worst case is a minor speedup. - External calls: none introduced by the event itself.
Data sensitivity review
The event exposes two records (Sales Invoice Line, Sales Cr.Memo Line) that contain standard sales transaction data ÔÇö item numbers, quantities, amounts, customer order references. No personally identifiable information beyond what is already exposed by every existing event on these same record types (e.g., OnAfterInsertEvent, OnBeforeModifyEvent, or the sibling OnBeforeUpdateSalesOrderLinesFromCancelledInvoice which takes SalesInvoiceHeader.No.). No credentials, tokens, password hashes, or similar sensitive fields. No exposure beyond the BC standard surface for these tables.
Multi-extension interaction
Standard IsHandled semantics apply: the event fires once, all subscribers run in order, and the first subscriber to set IsHandled := true wins (subsequent subscribers still execute but cannot un-set it in any way that matters, since the check is performed once at the call site after all subscribers have returned). Conflict handling:
- If two partners both want to block the revert: both set
IsHandled := true, behavior is the same as one ÔÇö revert skipped. No conflict. - If one partner wants to block and another wants to preserve standard behavior: the blocker wins. This is the standard IsHandled trade-off across all BC IsHandled events and is well-understood by partners. If the non-blocking partner needs the revert, they can subscribe with
Skip = falseand run their own replacement logic whenIsHandled = true. - Idempotence: the existing code path this event protects is already idempotent (Sales Order lookup + mutation with
Modify), so re-entry is not a concern.
These are the same multi-extension characteristics the sibling OnBeforeUpdateSalesOrderLinesFromCancelledInvoice already exhibits.
Justification for using IsHandled (Handled event) over alternatives
I acknowledge Microsoft's Types of events for extensibility ranks Handled events as "Low Value" and recommends considering Skip events. I've evaluated each alternative against our specific scenario:
-
A non-IsHandled
OnBeforeevent (inspection only, novar IsHandled) doesn't solve the scenario. Partners need to skip the Sales Order mutation entirely on path 4, not merely observe it. -
A Skip event with multiple granular skip parameters ÔÇö e.g.,
OnBeforeUpdateSalesOrderLinesFromCreditMemo(...; var SkipInvoicedQuantity; var SkipPrepmtAmount; var SkipWhseRequest; var SkipItemTracking)ÔÇö would be Microsoft's preferred "Medium Value" pattern, and I seriously considered it. I reject it for this specific procedure because the four mutations insideUpdateSalesOrderLinesFromCreditMemoare not independently meaningful to partners:- Skipping invoiced-quantity revert but keeping prepayment revert = inconsistent financial state
- Skipping warehouse-request flip but keeping item-tracking revert = inconsistent logistics state
- The real partner question is binary: "does this credit memo reopen the originating sales order, yes or no?". Granular skips expose internal implementation detail (that there happen to be four side-effects) to partners, who would always set all four booleans identically. A single IsHandled at the top of the procedure matches the actual extensibility shape of the problem.
-
A new procedure variant / interface redesign would be a larger breaking change than a single IsHandled publisher and would require partners and Microsoft to coordinate broader updates.
-
Consistency with existing sibling: the procedure
UpdateSalesOrderLinesFromCancelledInvoiceÔÇö which sits immediately belowUpdateSalesOrderLinesFromCreditMemoin the same codeunit (CU 1303 line 1004) and performs the same conceptual operation on a different code path ÔÇö already uses the Handled pattern (OnBeforeUpdateSalesOrderLinesFromCancelledInvoice, declaration at line 1347). Microsoft chose IsHandled for that sibling. Adding the symmetric IsHandled event onUpdateSalesOrderLinesFromCreditMemopreserves consistency with Microsoft's existing pattern in the same codeunit family rather than introducing a second, differently-shaped extensibility point for the same class of operation. -
Contribution via PR: I would happily submit a PR, but the change touches internal Microsoft conventions (event naming, placement within existing publisher groups, helper method ordering) that are easier for Microsoft to get right in one pass.
Submission quality checklist
- Minimal, self-contained diff: yes ÔÇö 5 lines added inside
UpdateSalesOrderLinesFromCreditMemo, 3-line publisher declaration, one local variable. - Naming follows BC conventions:
OnBefore+<ProcedureName>+IsHandledsignature, PascalCase, no abbreviations. Exactly mirrorsOnBeforeUpdateSalesOrderLinesFromCancelledInvoice. - Test adjustments: none expected. Existing tests for CU 1303 cover behavior when no subscriber is registered, and
IsHandleddefaults tofalse. Additional partner-side tests live in the partner extension. - Base code evolution: the new publisher is scoped as narrowly as possible, does not wrap any large block, and doesn't constrain future refactors of the surrounding code any more than the existing sibling event already does.
Reproduction scenario (baseline BC 27.5 behavior, no partner extension)
- Create a Sales Order with 1 item line, quantity 2, for any item with available stock.
- Post the Sales Order with Ship and Invoice. The Sales Line now shows
Quantity Shipped = 2,Quantity Invoiced = 2,Outstanding Quantity = 0, and the Warehouse Request isCompletely Handled = true. - Create a Sales Return Order for the same customer.
- Use
Prepare  Copy Document  Posted Sales Shipmentand pick the shipment from step 2. This populatesAppl.-from Item Entryon the return order line. - Post the Return Order with Receive and Invoice. A return receipt and a credit memo are created.
- Reload the Sales Order from step 1. Observe that
Quantity Shippedis now0,Quantity Invoicedis now0,Outstanding Quantityis back to2, and the Warehouse Request'sCompletely Handledflag has been flipped tofalse.
With the proposed event in place, a partner subscribing and setting IsHandled := true would leave the Sales Order exactly as it was at the end of step 2 ÔÇö unchanged by step 5 ÔÇö while the credit memo still posts cleanly (G/L, customer ledger, item ledger all move as expected).
Summary
| Item | Value |
|---|---|
| Affected object | Codeunit 1303 "Correct Posted Sales Invoice" |
| Affected procedure | UpdateSalesOrderLinesFromCreditMemo (line 987) |
| New publisher | OnBeforeUpdateSalesOrderLinesFromCreditMemo(var SalesInvoiceLine; var SalesCrMemoLine; var IsHandled) |
| Pattern to match | Existing OnBeforeUpdateSalesOrderLinesFromCancelledInvoice (call site line 1013, declaration line 1347) |
| Estimated effort | ~10 lines added, no tests to change, no breaking change |
| Base App version reviewed | 27.5.46862.47988 |
| Partner scenarios unblocked | All four credit memo / return order entry paths (full symmetric coverage) |
Submitted by Francesco (Deltanexx BV) during implementation of a Sales Order protection feature for One of our customers. Reviewed Base App 27.5.46862.47988 source and verified the 4 entry paths against that code. Available to answer follow-up questions, provide additional context, or rework the proposed diff if Microsoft prefers a different signature or placement.
Internal work item: AB#631820
✅ Analysis complete - approved for implementation
Implementation:
Add a new IsHandled integration event at the start of UpdateSalesOrderLinesFromCreditMemo so extensions can bypass the full sales-order rollback logic for this path.
Location in UpdateSalesOrderLinesFromCreditMemo() (around line 1040):
local procedure UpdateSalesOrderLinesFromCreditMemo(SalesInvoiceLine: Record "Sales Invoice Line"; SalesCrMemoLine: Record "Sales Cr.Memo Line")
var
TempItemLedgerEntry: Record "Item Ledger Entry" temporary;
SalesLine: Record "Sales Line";
UndoPostingManagement: Codeunit "Undo Posting Management";
IsHandled: Boolean;
begin
IsHandled := false;
OnBeforeUpdateSalesOrderLinesFromCreditMemo(SalesInvoiceLine, SalesCrMemoLine, IsHandled);
if IsHandled then
exit;
if SalesLine.Get(SalesLine."Document Type"::Order, SalesInvoiceLine."Order No.", SalesInvoiceLine."Order Line No.") then begin
SalesInvoiceLine.GetItemLedgEntries(TempItemLedgerEntry, false);
UpdateSalesOrderLineInvoicedQuantity(SalesLine, SalesCrMemoLine.Quantity, SalesCrMemoLine."Quantity (Base)");
UpdateSalesOrderLinePrepmtAmount(SalesInvoiceLine);
if SalesLine."Qty. to Ship" = 0 then
UpdateWhseRequest(Database::"Sales Line", SalesLine."Document Type".AsInteger(), SalesLine."Document No.", SalesLine."Location Code");
TempItemLedgerEntry.SetFilter("Item Tracking", '<>%1', TempItemLedgerEntry."Item Tracking"::None.AsInteger());
UndoPostingManagement.RevertPostedItemTracking(TempItemLedgerEntry, SalesInvoiceLine."Shipment Date", true);
end;
end;
Event Publisher (add at the end of the codeunit with other events):
[IntegrationEvent(false, false)]
local procedure OnBeforeUpdateSalesOrderLinesFromCreditMemo(var SalesInvoiceLine: Record "Sales Invoice Line"; var SalesCrMemoLine: Record "Sales Cr.Memo Line"; var IsHandled: Boolean)
begin
end;
File: CorrectPostedSalesInvoice.Codeunit.al
Hi @tomasevicst thanks for the approval. Since I was recently accepted into the BusinessCentralApps repository, I'd be happy to submit the PR for this myself if that's useful. Two questions:
- Do you want me to take it on, or will the SCM team implement it as part of normal scheduling?
- If I should do it, what's the right process given that BusinessCentralApps' CONTRIBUTING.md requires an approved issue linked on that repo? Should I open a mirror issue there referencing #29949, or is there a different flow for extensibility requests that originate on ALAppExtensions? Either path works for me ,happy to contribute or happy to wait for the Microsoft implementation.
SCM team will do implementation.
Thanks for reporting this. We agree, and we’ll publish a fix asap, either in an update for the current version or in the next major release. Please do not reply to this, as we do not monitor closed issues. If you have follow-up questions or requests, please create a new issue where you reference this one.
Build ID: 50086.