Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

docs(specs): RMA / customer returns module — spec and research (#1354)

Siddharth Gaikwad18795ab68cab
diff --git a/.ai/research/2026-08-07-rma-module.md b/.ai/research/2026-08-07-rma-module.md
new file mode 100644
index 0000000000..c6d7255014
--- /dev/null
+++ b/.ai/research/2026-08-07-rma-module.md
@@ -0,0 +1,151 @@
+# How Manufacturing ERPs Model RMAs (Customer Returns)
+
+**Date:** 2026-08-07
+**Question:** How do manufacturing ERPs model RMAs / customer returns — document model, lifecycle, reasons/dispositions, receiving, costing, credit, replacements, serial/lot — to inform the design of a Carbon RMA module?
+
+Sources are official vendor documentation unless flagged. Epicor's Kinetic help is behind a customer login (EpicWeb/doc.epicor.com); for Epicor, claims come from Epicor-authored pages plus Epicor "Contextual Help" text republished verbatim by a licensee, flagged below. Anything that couldn't be verified against a primary page is marked **unverified**.
+
+---
+
+## Microsoft Dynamics 365 Business Central
+
+**Two tiers of return processing.** A plain **Sales Credit Memo** handles a return/cancellation with no receipt tracking. A **Sales Return Order** is the heavier document, used "if you need more control of the sales return process, such as warehouse documents for the item handling, or a better overview when receiving items from multiple sales documents with one sales return" — and it "automatically issues the related sales credit memo and other return-related documents, such as a replacement sales order, if needed" ([Process sales returns or cancellations](https://learn.microsoft.com/en-us/dynamics365/business-central/sales-how-process-sales-returns-cancellations)).
+
+**Document model & linking.** Header + lines. Lines can be entered manually (blind return — linking is optional) or pulled from history two ways ([Process sales return orders](https://learn.microsoft.com/en-us/dynamics365/business-central/sales-how-process-sales-returns-orders)):
+- **Get Posted Document Lines to Reverse** — copies lines from one or *more* posted documents (shipments, invoices, return receipts, credit memos); "always exactly reverses the costs from the posted document line". A **Show Reversible Lines Only** filter shows only quantities not yet returned (works for posted shipment/invoice lines only). If part of a line's quantity was already returned/sold/consumed, only the remaining quantity is copied; fully-reversed lines aren't copied at all.
+- **Copy Document** — copies one whole document; exact cost reversing only if **Exact Cost Reversing Mandatory** is enabled on **Sales & Receivables Setup**.
+
+**Exact cost reversing (the flag that matters).** "To preserve correct inventory valuation, you typically want to put returned items back in inventory at the unit cost that they were sold at, not at their current unit cost." Mechanically, the return line's **Appl.-from Item Entry** field points at the original item ledger entry; the copy functions fill it automatically, or a user sets it manually on any return line ([inventory costing section](https://learn.microsoft.com/en-us/dynamics365/business-central/sales-how-process-sales-returns-cancellations#inventory-costing)).
+
+**Serial/lot.** When copied lines carry item tracking, "the **Appl.-from Item Entry** field on the item tracking lines is filled with the appropriate item ledger entry numbers from the posted item tracking lines" — i.e. the same serial/lot identity re-enters, cost-linked to its original outbound entry ([Process sales return orders](https://learn.microsoft.com/en-us/dynamics365/business-central/sales-how-process-sales-returns-orders)).
+
+**Return reasons.** A per-line **Return Reason Code** (user-defined table, shared by sales and purchase return orders). Each code carries two behavior hooks, documented in the (archived but still-accurate NAV) [Return Reasons window reference](https://learn.microsoft.com/en-us/previous-versions/dynamicsnav-2015/hh173680(v=nav.80)): a **Default Location Code** ("specify that the returned items belong to the customer and should not affect the availability and value of your inventory") and **Inventory Value Zero** — checked, "the item can then enter into inventory to be repaired, but its value will be set to zero"; cleared, "return the item to inventory at its original cost". Current BC docs reference the field but no longer enumerate these hooks on a dedicated page.
+
+**Lifecycle / order of operations.** Return order → post **Receive** (creates **Posted Return Receipts**; warehouse receive/put-away documents can drive it) → post **Invoice** (creates the posted **Sales Credit Memo**, applied to customer ledger entries). Receipt and credit are separable: **Get Return Receipt Lines** on a credit memo, or the **Combine Return Receipts** batch job, credit many return orders' receipts in one memo; **Quantity Invoiced** flows back to the originating return order, which survives until deleted (manually or via **Delete Invoiced Sales Return Orders**) ([combine return receipts](https://learn.microsoft.com/en-us/dynamics365/business-central/sales-how-process-sales-returns-cancellations#to-combine-return-receipts)).
+
+**Restock charge & allowances.** A restock fee is just another line: "in the **Type** field, select **Charge (Item)**", fill amount, and assign the charge to the posted shipment; "when you post the sales return order, the restock charge is added to the relevant sales entry amount" (keeps valuation right). Sales allowances (price reductions) use the same Charge (Item) mechanism ([Process sales return orders](https://learn.microsoft.com/en-us/dynamics365/business-central/sales-how-process-sales-returns-orders#to-create-a-restock-charge)).
+
+**Replacements.** Enter the replacement as a *negative-quantity* line on the return order, then **Move Negative Lines** deletes it and creates a new **Sales Order**. **Create Return-Related Documents** goes further: for one vendor number it can auto-create a replacement **Sales Order**, a **Purchase Return Order**, and/or a replacement **Purchase Order** — the documented use case is vendor-warranty items ([Process sales return orders](https://learn.microsoft.com/en-us/dynamics365/business-central/sales-how-process-sales-returns-orders#to-create-return-related-documents-from-a-sales-return-order)).
+
+**Financials.** Credit memo must be applied to customer ledger entries (**Apply Entries**, partial **Amount to Apply** allowed); refund is a separate payables/receivables step. Posting a credit memo also reverts item charges assigned to the posted document. Unpaid invoices get the lighter **Correct**/**Cancel** actions, which "don't support partial returns or cancellations" ([Process sales returns or cancellations](https://learn.microsoft.com/en-us/dynamics365/business-central/sales-how-process-sales-returns-cancellations)).
+
+**Supplier side is a mirror image.** **Purchase Return Order** → post Ship (creates **Posted Return Shipments**) → **Purchase Credit Memo**; same **Get Posted Document Lines to Reverse**, its own **Exact Cost Reversing Mandatory** flag on **Purchases & Payables Setup**, **Combine Return Shipments**, **Move Negative Lines** → replacement purchase order, same **Return Reason Code** field ([Process purchase returns or cancellations](https://learn.microsoft.com/en-us/dynamics365/business-central/purchasing-how-process-purchase-returns-cancellations)).
+
+## Oracle NetSuite
+
+**Document model.** A **Return Authorization (RA/RMA)** is "a record of expected customer returns" and — key semantic — "a non-posting transaction": nothing hits inventory or GL until receipt/credit. It records item, quantity, and price, which "determine amounts to be credited or refunded" ([RA Forms](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1304530.html), [Return Authorization record](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N3688557.html)). Two entry modes: **standalone** (not linked to a sale) and **linked** (created from a cash sale or invoice, lines pre-populated); the record API can also initialize from a sales order. For serialized items on a standalone RA, the UI lets you "select the serial number sold to this customer" ([Entering a Standalone Return Authorization](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1305354.html)).
+
+**Lifecycle.** The documented process order: enter RA → **approve** ("approves the customer to be credited or refunded upon receipt of the item") → **receive** (item receipt) → **issue credit memo** → **refund** → **close line items** for quantities no longer expected ([Customer Returns Process](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1303799.html)). Statuses are quantity-derived and differ by feature set ([Customer Return Authorization Status](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1310133.html)):
+- With Advanced Receiving: **Pending Approval → Pending Receipt → Partially Received → Pending Refund → Refunded**, plus **Canceled** and **Closed** ("all lines on the return have been closed").
+- Without Advanced Receiving: **Pending Approval → Pending Refund → Partially Refunded → Refunded / Canceled / Closed** (receipt and refund collapse into one step).
+A preference sets the default status of new RAs: "Select **Pending Approval** if your company uses the approval process… Select **Pending Fulfillment** if your company doesn't" (sic — the RA lifecycle page then shows approved RAs as Pending Receipt) ([Preferences for Customer Returns](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1305008.html)).
+
+**Receiving & the restock decision.** Receiving reuses the standard **Item Receipt** transaction, opened from the RA (**Receive**) or from *Transactions > Customers > Receive Returned Order*. Per line: **Receive** checkbox, **Quantity**, mandatory **Location** under Multi-Location Inventory, and the pivotal **Restock** checkbox — checked, "inventory count increases… inventory value increases"; cleared, the item is "logged as an expense" and the "income loss posted as a loss" (scrap/write-off at receipt, no disposition document). Posting updates RA received quantities, inventory records, and inventory asset accounts. **Save & Refund** jumps straight to a cash refund, and "you credit customers only for what was received" ([Receiving a Customer Return](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1307628.html), [Handling Returned Items](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1308274.html)). What *cost* a restocked item re-enters at is not stated on these pages (**unverified** here; NetSuite has costing-preference docs this research did not reach).
+
+**Financials.** Which money document comes out is form-driven: "**Standard Return Authorization - Credit**" generates a **credit memo** (apply to balance or refund later); "**Standard Return Authorization - Cash**" generates a direct **refund** and "cannot later be processed as a credit memo". With Advanced Receiving you "must credit a return before refunding" (credit memo from RA, then refund from the credit); without it, refund can come straight from the RA. A **Refund in Advance of Return** preference allows crediting before goods arrive; otherwise "the company waits until the return is received back into stock before crediting or refunding" ([RA Forms](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1304530.html), [Preferences](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1305008.html)).
+
+**Return reasons.** No dedicated return-reason code table appears in the core RA docs (memo fields and customization cover it) — an explicit gap versus BC/Infor.
+
+**Replacements.** From the RA, after an item receipt exists, a **Create Replacement Sales Order** button spawns a new sales order pre-populated from the RA lines ([Returning and Replacing Fulfillable Items](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_40150958866.html)). RAs can also be generated from **warranty claims**, with serial/lot entered via the **Inventory Details** subrecord ([Creating Return Authorizations for Warranty Claims](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_4391869751.html)).
+
+**Quality tie-in (supplier side).** NetSuite Quality Management's "Enhanced Receipt Return Authorization Workflow" auto-creates vendor returns from inspection: quality inspection evaluates each lot/serial on a PO receipt, and with Action = **Return to Vendor** and **Return Only Failed Inventory** checked, "the system generates the vendor return for the failed lot or serial number" ([Enhanced Receipt Return Authorization Workflow](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/article_0222101726.html)).
+
+**Supplier side.** **Vendor Return Authorization** is the mirror: "a non-posting purchase transaction record", carrying both NetSuite's return number and the vendor's own RMA number, with a four-step flow — enter → approve → **ship** authorized return → **credit** (log vendor credit/refund) ([Vendor Return Authorization Overview](https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2386202.html)). Note the symmetry: customer side *receives*, vendor side *ships*.
+
+## Odoo (v18)
+
+**No RMA document at all.** A return is an inventory operation: on a validated delivery order, click **Return** → a **Reverse Transfer** pop-up pre-fills products/quantities from the delivery → edit quantities / delete lines → **Return** "generates a new warehouse operation for the incoming returned product(s)" which the warehouse validates like any receipt. The reverse transfer is inherently linked to (and quantity-bounded by) the originating delivery; on validation "the **Delivered** quantity on the sales order updates" so a later invoice only bills kept goods ([Returns and refunds](https://www.odoo.com/documentation/18.0/applications/sales/sales/products_prices/returns.html)).
+
+**After invoicing: reverse transfer + credit note.** "Validated… invoices cannot be changed", so the physical return (reverse transfer) is paired with a **Credit Note** created from the invoice. The credit-note dialog takes a **Reason**, **Journal**, **Reversal Date** and two modes: **Reverse** (draft credit note, editable — this is how partial credits happen) and **Reverse and Create Invoice** (validated credit note auto-reconciled against the invoice, plus a new draft invoice). Credit notes are "a reverse entry that cancels out the journal items from the original invoice", numbered `R` + invoice number ([Credit notes and refunds](https://www.odoo.com/documentation/18.0/applications/finance/accounting/customer_invoices/credit_notes.html)).
+
+**Lifecycle & semantics.** There is no authorize/approve stage, no return-reason code on the transfer (the only "Reason" lives on the credit note), and no restock-vs-scrap decision at receipt — returned stock lands in inventory and scrapping is a separate inventory operation. Statuses are just transfer states (draft/waiting/done).
+
+**Repairs.** The Repair app links to returns: a repair order has a **Return** field to "select the return order from which the product to be repaired comes from"; parts lines carry **Add / Remove / Recycle** types; states run **Confirmed → Under Repair → Repaired**; for billable repairs, **Create Quotation** generates a sales order carrying the parts/costs, and the fixed product ships back on a delivery created by reversing the return receipt ([Process repair orders](https://www.odoo.com/documentation/18.0/applications/inventory_and_mrp/repairs/repair_orders.html)).
+
+**Costing / serials.** Returned goods re-enter through the standard incoming-move valuation; no exact-cost-reversal flag is documented. Lot/serial selection on a reverse transfer follows normal transfer lot entry (no special return doc); Odoo 18 documents a separate [reassign lot/serial](https://www.odoo.com/documentation/18.0/applications/inventory_and_mrp/inventory/product_management/product_tracking/reassign.html) tool. **Not documented / unverified:** any original-cost reversing behavior.
+
+## Epicor Kinetic
+
+*(Primary Kinetic help is login-gated. Claims below cite Epicor-authored contextual help republished verbatim by licensee WCI, plus epicor.com pages; community sources flagged.)*
+
+**Document model.** **RMA Processing** (Sales Management > Order Management > General Operations) has four areas: the **RMA** header (number/search), **Details** — "indicate what invoice and line of invoice an RMA is being created for along with the qty to be returned and reason for return", **Receipts** — "when returned goods arrive at the facility the receipt must be recorded here", and **Credits** — "after receipt of goods credits can be created directly from the credits area" ([RMA Processing, Epicor contextual help mirror](https://wcibags.atlassian.net/wiki/spaces/ECH/pages/843743245/RMA+Processing)). So: line-level link to invoice + invoice line, reason captured at authorization, credit only after receipt. Kinetic 2024.1 added "the ability to create an RMA from an order, invoice, or shipment pack" ([Epicor: What's New in 2024.1](https://www.epicor.com/en-us/blog/industries/whats-new-in-release-2024-of-kinetic/)). Epicor's product page confirms org-wide "returns and disposition processes… using unique returned materials authorization (RMA) numbers" ([Kinetic Service Management](https://www.epicor.com/en/products/enterprise-resource-planning-erp/kinetic/service-management/)).
+
+**Receive → inspect → disposition (the distinctive part).** "After RMA receipt is performed… the material enters an inspection state awaiting disposition handling." Disposition happens in **RMA Disposition** with four options ([Disposing of RMA Product, Epicor contextual help mirror](https://wcibags.atlassian.net/wiki/spaces/ECH/pages/843481202/), [RMA Dispositions](https://wcibags.atlassian.net/wiki/spaces/ECH/pages/843481174/RMA+Dispositions)):
+- **Stock** — back to inventory; prompts for warehouse and bin; creates an **INS-STK** (inspection-to-stock) part transaction.
+- **Job** — issue the returned material to a job (rework/repair on a work order).
+- **Fail** — reject from the system, reason required; failed material flows to **DMR Processing** (Discrepant Material Report), the same non-conformance machinery used for failed purchases, from which supplier return/scrap follow ([community corroboration](https://www.epiusers.help/t/how-do-i-process-a-supplier-return-dmr-via-rma-disposition-without-the-qa-module/67390) — flagged community).
+- **Return Shipment** — send back to the customer; "automatically creates a Miscellaneous Shipment Pack ID" and an **INS-CUS** transaction.
+Partial dispositions are allowed — one RMA quantity can split across Stock and Fail, each its own disposition record.
+
+**Financials.** Credit memos are generated from the RMA's Credits area post-receipt; "if an Apply To Invoice number was assigned to the original RMA, the credit memo created will be applied to the invoice; if no number is entered, an open credit memo will be created" ([epiusers, describing Epicor help text](https://www.epiusers.help/t/rma-generated-credit-memo-does-not-grab-product-group-from-invoice-right/120093) — community). Costing: when the RMA line specifies invoice and line, Epicor walks back to the original shipment's **PartFIFOTran** FIFO layers, and layers returned via disposition to Job or Fail "will be processed as individual or distinct FIFO layers" — i.e. exact original-cost layers follow the return ([epiusers](https://www.epiusers.help/t/rma-disposition-costs-table/115190) — community; **not verified against gated official docs**).
+
+**Serial/lot.** Not covered by the accessible mirrored pages (**unverified**; community threads indicate serial selection at RMA receipt).
+
+## Infor CloudSuite Industrial (SyteLine)
+
+**Document model.** An RMA "creates the document that authorizes a customer to reject material" with an **RMA header** (customer, problem info; its **Status** field "tracks this authorization through its life cycle… serving as the historical record after all material has been returned and the customer has been credited") and **RMA Line Items** (material, expected return, compensation, disposition) ([Return Material Authorization Overview](https://docs.infor.com/csi/9.01.x/en-us/csbiolh/mergedprojects/sl_custvend/other/overview/return_material_authorization_overview.htm)).
+
+**Reasons and dispositions as separate code tables.** A **Problem Code** "best describes the problem that led to the return" (reporting on why customers reject material); a three-character **Disposition Code** "identifies what action should be taken with the material when it is returned", trackable via the RMA Status Report (same overview page — values are user-defined, not enumerated by the docs).
+
+**Lifecycle.** Documented [RMA Steps](https://docs.infor.com/csi/9.01.x/en-us/csbiolh/lsm1454144038357.html): create RMA header → create RMA line items → receive via the **RMA Return Transaction** form → optional rework (**Creating a Rework Order** — repair the returned item on a rework order) → **Issuing a Credit** / **Sending a Replacement** / **Generating Replacement Orders**. Replacements can be "new items from inventory or… the same items after a repair step" ([About Returns](https://docs.infor.com/csi/9.01.x/en-us/csbiolh/mergedprojects/sl_custvend/other/overview/about_returns.htm)).
+
+**Financials.** The **RMA Credit Memo** form generates credits; "if an item is to be returned by the customer, the return must take place before the credit memo can be created." Line selection is rule-driven: lines qualify when "the Return flag is selected and the quantity returned is greater than the quantity credited thus far", or "the Return flag is cleared and an amount remains to be credited" (credit-without-physical-return is a first-class case), for lines with **Open**/**Filled** status under an **Open** RMA header. **Apply To Invoice number** applies the credit to a specific invoice, else an open credit memo; a **Reversing an RMA Credit Memo** procedure exists ([Processing an RMA Credit Memo](https://docs.infor.com/csi/10.x/en-us/csbiolh/customer_svc_user_cl_sl/qxm1529518824289.html)).
+
+## SAP Business One
+
+**Three-document chain.** ([SAP Learning: Solving Issues in Sales](https://learning.sap.com/courses/managing-logistics-in-sap-business-one/solving-issues-in-sales))
+- **Return Request** — optional authorization document (issuable as an RMA number), created from a **Delivery** or **A/R Invoice**; non-posting. Its advantage: "the system will automatically determine the appropriate correction document to follow" on Copy To.
+- **Return** — the goods-movement correction *before invoicing*: "reverses the effects of a delivery, either partially or fully"; increases warehouse stock, posting to a **Sales Returns** account separate from the original stock account.
+- **A/R Credit Memo** — the correction *after invoicing*: "reverses an A/R invoice's journal entry either partially or fully" and "increases the stocks of the credited items" (inventory + GL in one document). A **Without Qty Posting** row option credits money without any inventory movement (price adjustments, goods not coming back).
+Exchanges are handled with **negative rows** directly on sales documents rather than a replacement document. Paid/closed invoices require reopening before the chain applies. Supplier mirror: **Goods Returns** and **A/P Credit Memo** in purchasing ([SAP TB1000 courseware on help.sap.com](https://help.sap.com/doc/saphelpiis_hc_b1_image_repository_consultant_training_basic_b1_90_tb1000_02_06_pdf/9.0/en-US/B1_90_TB1000_02_06.pdf)).
+
+## Katana MRP (light pass)
+
+**Return orders** are created from *completed* sales orders (Sell > Sales orders > Done); "each return connected to its original sales order to ensure traceability". Three statuses: **Not Returned** ("customer initiated a return… inventory levels remain unaffected") → **Returned** (received, "may be in quality control or awaiting assessment", still not in stock) → **Restocked** (inventory adjusted, "stock is now available again"). Item-level add/remove/edit with **reasons for return**; restocking is per-item with a **Restock location** column and a batch-info pop-up for batch-tracked products; a return's status change can "automatically trigger credit notes in QuickBooks Online"; Shopify-initiated returns sync in ([Returns overview](https://support.katanamrp.com/en/articles/11094886-returns-overview), [How to restock return orders](https://support.katanamrp.com/en/articles/11130510-how-to-restock-return-orders)). Costing basis on restock is **not documented**. Notable: even a lightweight MRP separates *received* from *restocked* — the two-phase receipt is table stakes.
+
+## Fulcrum (light pass)
+
+Public docs are thin: the returns workflow is initiated from the refund flow — "when you are refunding an item, you can also indicate a return, which will create a receiving record for the item being returned" ([Fulcrum product update: Returns workflow](https://fulcrumpro.com/product-update/returns-workflow)). Inspection/disposition and costing behavior are **not publicly documented**.
+
+---
+
+## Synthesis
+
+### The common core (table stakes)
+
+1. **An authorization document distinct from money and inventory documents.** Every document-first system (BC, NetSuite, Epicor, Infor, SAP B1's Return Request, Katana) has an RMA header + lines that is *non-posting*: it records intent (what's expected back, at what price/qty) and accumulates state, while inventory moves on a receipt document and money moves on a credit memo/refund. NetSuite states the non-posting semantic outright.
+2. **Optional line-level linkage to the original transaction.** Lines link to the original invoice line / shipment / order (BC `Appl.-from Item Entry`, Epicor invoice+line, NetSuite linked RA, SAP Copy To). Linking is always *optional* — standalone/blind returns are supported everywhere — but when present it drives three things: reversible-quantity validation (BC "Show Reversible Lines Only"), credit pricing (copied prices/discounts), and cost reversal (below).
+3. **Lifecycle = authorize → (approve) → receive → disposition → credit/refund/replace → close**, with statuses derived from quantities (NetSuite: Pending Receipt / Partially Received / Pending Refund / Refunded; Infor: Open/Filled per line; Katana: Not Returned / Returned / Restocked). Cancel/close-line escape hatches exist at every stage (NetSuite "Closing Line Items", BC delete-invoiced-return-orders).
+4. **Receiving reuses the normal receiving machinery.** NetSuite opens a standard Item Receipt; BC posts return receipts through the same warehouse receive/put-away documents; Odoo literally creates an incoming transfer; Epicor records receipts on the RMA; Infor has an RMA Return Transaction form. No system invents a parallel receiving stack.
+5. **A restock-vs-not decision after physical receipt.** Modeled either as a binary flag at receipt (NetSuite **Restock**: unchecked = write-off as expense/loss) or as an explicit inspect-then-disposition stage (Epicor: receipt lands in inspection, then **Stock / Job / Fail(DMR) / Return Shipment**; Infor disposition codes; Katana's Returned→Restocked gate).
+6. **Credit memo generated from the return, applied to the original invoice or left on account.** Epicor/Infor: "Apply To Invoice… else an open credit memo". Default order is receive-then-credit (NetSuite "credit customers only for what was received"; Infor "the return must take place before the credit memo can be created"), with an explicit override (NetSuite **Refund in Advance of Return**; Infor's no-return credit lines). Credit ≠ refund: credit-on-account first, refund as a follow-on payment document (NetSuite makes the ordering configurable; BC handles refund in payables).
+7. **Cost: returned goods re-enter at their original outbound cost, not current cost.** BC's exact cost reversing (item-ledger-entry application, `Exact Cost Reversing Mandatory`), Epicor's FIFO-layer walk-back from the original shipment. With a documented degrade path for damaged goods: BC **Inventory Value Zero** per return reason; NetSuite's no-restock write-off.
+8. **Replacements spawn a linked sales order.** NetSuite **Create Replacement Sales Order** (post-receipt), Infor replacement orders (from stock or after repair), BC **Move Negative Lines** / **Create Return-Related Documents** (which also spawns the vendor-warranty purchase return + replacement PO). Repair is a distinct flow: Odoo repair orders and Infor rework orders link the returned unit to a work/rework order; Epicor's **Job** disposition issues returned material to a job.
+9. **Return reasons are a small user-defined code table on the line.** BC Return Reason Code (with behavior hooks: default location, zero value), Epicor reason on the RMA detail + reason on Fail, Infor Problem Code (why) *separate from* Disposition Code (what to do), Katana free-form reasons. NetSuite and Odoo are the outliers (reason only on the credit note in Odoo; none native in NetSuite).
+10. **The supplier side mirrors the customer side** with direction flipped (customer RMA *receives*, vendor return *ships*): BC purchase return orders/posted return shipments, NetSuite Vendor RA (enter→approve→ship→credit), SAP B1 Goods Returns/A-P Credit Memo. Epicor and NetSuite additionally *bridge* the two: a failed customer return (Epicor Fail→DMR; NetSuite quality-inspection workflow) becomes a return-to-vendor.
+
+### Divergences worth noting
+
+- **Document-first vs operation-first.** Odoo has no RMA object — return = reverse transfer + credit note, linkage via the delivery. Cheap to build, but there is no place to hang authorization state, reasons, dispositions, or expected-vs-received tracking; Katana (similar market) added a return-order object anyway.
+- **Approval as a first-class stage** (NetSuite, Infor status; Epicor via workflow) vs absent (BC, Odoo, SAP B1 — the Return Request itself is the authorization).
+- **Where the damaged-goods decision lives:** at receipt (NetSuite flag), at disposition after inspection (Epicor/Infor — manufacturing-grade), or encoded in the reason code (BC's location + zero-value hooks — clever, low-ceremony).
+- **Restock fee:** only BC documents a concrete mechanism (a Charge (Item) line assigned to the posted shipment, folded into the sales entry amount); others handle it as manual credit-memo line edits.
+- **One credit document per RMA vs many:** BC can combine many return orders' receipts into one credit memo (statement-style), and conversely partially credit; NetSuite/Epicor generate credits per-RMA (multiple credits per RMA allowed in Epicor).
+- **Exchange semantics:** linked replacement SO (NetSuite/Infor) vs negative lines moved off the return (BC, SAP B1). The negative-line approach is documented but clunky.
+
+### Implications for Carbon
+
+Carbon already has: sales order → shipment → sales invoice; a receipts system whose `receiptSourceDocument` enum already contains an unused **"Sales Return Order"** value; an AR credit-memo table (header-level amount, Draft/Posted/Voided, direction Credit|Debit, posts to a journal); a quality Issues module with dispositions (Use As Is, Rework, Scrap, Return to Supplier, Quarantine…) and MRB approvals; `trackedEntity` lot/serial rows (Available/Reserved/On Hold/Consumed/Rejected); item/cost ledger posting via edge functions.
+
+1. **Build the RMA as a non-posting header+lines document** (`salesRma` or `salesReturnOrder`), separate from receipt and credit memo. Statuses quantity-derived, NetSuite-style: `Draft → Authorized → Partially Received → Received → Dispositioned → Credited/Closed`, plus `Voided`; per-line close for never-coming-back quantities.
+2. **Line linkage optional but rich:** nullable FKs to `salesOrderLine` / shipment line / `salesInvoiceLine` (+ itemId, qty, uom). When linked: validate against already-returned quantity (BC's reversible-lines check), copy pricing for the credit, and resolve the original cost. Blind returns (no link) are table stakes.
+3. **Receive through the existing receipts system** — this is exactly what the unused `"Sales Return Order"` `receiptSourceDocument` value is for. One receipt per arrival, partial receipts natural, item ledger posting through the existing edge functions. Default the receiving location to a quarantine/inspection location (BC's per-reason **Default Location Code** is the pattern to steal).
+4. **Disposition via the quality Issues module, not a new subsystem.** Epicor's receive→inspect→disposition is the manufacturing-grade model, and Carbon already owns the vocabulary: map RMA disposition to the existing enum — restock (Use As Is), Rework (→ job/rework), Scrap (write-off posting), Return to Supplier (spawns purchase-return flow — Epicor's Fail→DMR bridge), Quarantine (hold). Support partial, per-quantity dispositions (one RMA line splitting Stock/Scrap), optionally gated by MRB approval for high-value returns.
+5. **Costing policy per line, decided at receipt/disposition:** (a) original cost via the linked outbound ledger entry (BC exact cost reversing — requires resolving the shipment's cost-ledger entry), (b) zero value (BC Inventory Value Zero: unit exists for rework, worth nothing), or (c) no restock = expense write-off (NetSuite). Scrap disposition posts the write-off through the existing cost-ledger edge functions.
+6. **Credit memo:** generate from the RMA on demand (not auto), defaulting to received-and-dispositioned quantities × original invoice pricing, minus restocking fee. Carbon's AR credit memo is header-amount-only — either add credit-memo lines or store the line-level credit breakdown (qty credited per RMA line, fee) on the RMA and post the total; the per-line `quantityCredited` is needed regardless for status derivation and partial credits. Keep credit (posted memo on account) separate from refund (payment-side, out of scope initially). Restock fee as an explicit signed component, BC-style.
+7. **Replacements: spawn a linked sales order** from the RMA (NetSuite's post-receipt `Create Replacement Sales Order`), carrying `rmaId` provenance — not BC's negative-line dance. Repair-and-return can start as a disposition note + manual job, later formalized (Odoo repair orders / Infor rework orders show the shape: link returned unit → work order → outbound shipment).
+8. **Serial/lot: same entity re-enters.** On RMA lines for tracked items, let users pick from trackedEntities actually shipped to that customer (NetSuite's "serial number sold to this customer"; BC's item-tracking application). On receipt, reactivate the same `trackedEntity` in **On Hold** (or Quarantine) until disposition flips it to Available/Rejected/Consumed — this preserves genealogy across the round trip, which none of the lightweight systems manage.
+9. **Return reasons: company-scoped code table** referenced per RMA line (why), kept separate from disposition (what we did) — Infor's Problem Code vs Disposition Code split. Optional per-reason behavior hooks (default location, zero-value) are cheap and proven in BC.
+10. **Design for symmetry now, build supplier side later.** Keep naming/shape such that a purchase-return document can mirror (direction flipped: ship instead of receive), and let the Return-to-Supplier disposition be the bridge between the two — the Epicor/NetSuite pattern.
+
+**Verification gaps:** Epicor official Kinetic docs are gated — disposition/credit details rest on Epicor-authored mirrored help + community corroboration as flagged. NetSuite's restocked-item cost basis and Katana's costing basis are not documented on the pages reached. Fulcrum's public documentation is minimal.
diff --git a/.ai/specs/2026-08-07-rma-module.md b/.ai/specs/2026-08-07-rma-module.md
new file mode 100644
index 0000000000..3a9a7584df
--- /dev/null
+++ b/.ai/specs/2026-08-07-rma-module.md
@@ -0,0 +1,366 @@
+# Returns — Customer RMAs (`salesReturnOrder`) + Supplier Returns (`purchaseReturnOrder`)
+
+> Status: draft
+> Author: Claude (with Sid)
+> Date: 2026-08-07
+> Research: `.ai/research/2026-08-07-rma-module.md` (BC, NetSuite, Epicor, Infor, SAP B1, Odoo, Katana — primary-source cited)
+
+## TLDR
+
+Add a Return Merchandise Authorization document to the Sales module: a **non-posting `salesReturnOrder` header + lines** that authorizes a customer return, receives goods through the **existing receipts system** (the unused `"Sales Return Order"` value in `receiptSourceDocument` was built for exactly this), re-enters inventory at **original outbound cost** (exact cost reversing), reactivates the **same `trackedEntity`** for serialized/batch goods (genealogy survives the round trip), routes complex dispositions through the **existing quality Issues module**, and settles money by generating the **existing AR credit `memo`** and/or a linked **replacement sales order**. No parallel receiving, costing, quality, or credit subsystem is built — the RMA document is the connective tissue between machinery Carbon already has.
+
+The purchasing side is the mirror image (added per PR #1354 review): a **`purchaseReturnOrder`** authorizes returns TO suppliers, ships through the **existing shipments system** (`"Purchase Return Order"` was pre-plumbed there too), relieves inventory at carried cost, and settles via a **supplier credit `memo`** — same table shapes, direction flipped, with the quality Issue `'Return to Supplier'` disposition as the bridge that drafts one (Epicor's DMR→vendor-return pattern).
+
+## Problem Statement
+
+Carbon has no way to process a customer return. Today a shop that gets a defective part back must fake it: a manual inventory adjustment (wrong cost, no provenance), a hand-created credit memo (no linkage to what came back), no authorization number to give the customer, no reversible-quantity control (nothing stops crediting more than was sold), no inspection/disposition trail, and a broken genealogy chain for serialized goods.
+
+The schema shows this was always intended: `receiptSourceDocument` and `shipmentSourceDocument` already contain **both** `"Sales Return Order"` and `"Purchase Return Order"` (commented out in `inventory.models.ts` pickers), `itemLedgerDocumentType` already contains `"Sales Return Receipt"` and `"Purchase Return Shipment"`, `salesInvoiceStatus` has unused `"Return"` / `"Credit Note Issued"` values, and the glossary describes shipment sources as "a sales order, an outbound transfer, or an RMA return". None of it is wired to anything.
+
+The supplier direction is equally unserved: today the quality module's `'Return to Supplier'` disposition writes inventory out directly at issue close (`post-nonconformance`) with no authorization document, no paperwork for the supplier, no supplier-RMA-number tracking, and no linkage to the AP credit that should follow.
+
+Every document-first ERP surveyed (Business Central, NetSuite, Epicor, Infor, SAP B1, Katana) models this the same way — a non-posting authorization document distinct from the receipt and the credit memo (research §Synthesis 1–10). Odoo, the one system without an RMA object, is the cautionary tale: nowhere to hang authorization state, reasons, dispositions, or expected-vs-received tracking.
+
+## Proposed Solution
+
+### Workflow
+
+```
+Draft ──confirm──▶ Confirmed ──receive──▶ Partially Received ──▶ Received ──complete──▶ Completed
+ │ │ (guard: no Pending
+ └──cancel──▶ Cancelled (only while nothing received) dispositions on
+ received qty)
+```
+
+1. **Authorize.** CSR creates an RMA for a customer — standalone (blind return) or from a sales order / shipment / invoice, which pre-fills lines and enforces reversible quantities (can't authorize more than was shipped minus already returned). Lines carry item, quantity, unit price (credit basis), a **return reason** (why — company-defined code table), optional links to the originating `salesOrderLine` / `shipmentLine` / `salesInvoiceLine`, and for tracked items the specific `trackedEntity` rows the customer is sending back. Confirming assigns the readable `RMA000001` id's terminal state and produces a PDF to send to the customer.
+2. **Receive.** Goods arrive → a **receipt** with `sourceDocument = 'Sales Return Order'` (the existing receipts UI + `create` edge function, new source branch). Partial receipts are natural. Posting the receipt (`post-receipt` extension): positive `itemLedger` rows (`entryType 'Sale'`, `documentType 'Sales Return Receipt'`), cost layer at the **original outbound cost** when linked (walk the shipment's `costLedger` consumption), current cost for blind returns, **zero** when the line's return reason has `inventoryValueZero` (BC's damaged-goods pattern); journal `Dr Inventory / Cr COGS` at the re-entry value (gated on `accountingEnabled`). Tracked goods **reactivate the same `trackedEntity`** (status `On Hold`) with a `'Return Receipt'` `trackedActivity`; blind tracked returns create a new entity, also `On Hold`.
+3. **Disposition** (per line, after receipt). Lightweight outcomes execute directly on the RMA:
+ - **Use As Is** → restock: tracked entity flips `Available`; untracked stock is already on hand — no GL.
+ - **Return to Customer** (claim rejected) → shipment with `sourceDocument 'Sales Return Order'` ships it back; negative ledger at carried cost.
+ - **Scrap / Rework / anything needing MRB** → escalate to a **quality Issue** (new `'Sales Return Order'` association). The Issue owns the disposition, approvals, and GL write-off via the existing `post-nonconformance` machinery — Epicor's Fail→DMR bridge, using Carbon's own non-conformance system (research §Epicor, §Implications 4).
+4. **Settle.** From the RMA: **Issue Credit** generates an AR `memo` (direction `Credit`, existing table + `post-memo` posting) from received-not-yet-credited quantities × unit price, minus per-line restocking fee; per-line breakdown is stored in `salesReturnOrderCreditLine` (the memo itself stays header-level — schema unchanged). Multiple partial credits per RMA are allowed; application to invoices / refunds ride the existing credit-application-via-payment flow. **Create Replacement Order** spawns a draft sales order pre-filled from RMA lines (NetSuite's post-receipt pattern), linked via `replacementSalesOrderId`.
+5. **Complete.** Manual action, guarded: every non-closed line fully received and no received quantity still `Pending` disposition (mirrors `closeIssue`'s guard). Lines the customer will never send can be short-closed (`closedComplete`, the PO short-close pattern).
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Document model | New non-posting `salesReturnOrder` + `salesReturnOrderLine`; NOT a quality-issue flavor, NOT negative SO lines | Unanimous competitor pattern (research §Synthesis 1); Carbon's enums were pre-plumbed for exactly this document; Issues lack logistics/credit machinery. Odoo's no-document approach leaves state homeless |
+| Module home / permissions | Sales module: code in `modules/sales/`, routes `handle.module: "sales"`, gated by existing `sales_*` scopes. Receiving stays `inventory_*`, credit stays `invoicing_*` | Lesson "Features live inside existing permission modules"; permission scopes are FROZEN surfaces — adding none. Epicor files RMA under Sales Management too |
+| Naming | Tables `salesReturnOrder` / `salesReturnOrderLine`; UI label "RMAs"; sequence prefix `RMA` | Matches the pre-existing enum literal `"Sales Return Order"` and `salesOrder` symmetry; the mirrored `purchaseReturnOrder` is specced in the Purchasing Side section (research §Synthesis 10) |
+| Line linkage | Nullable FKs to `salesOrderLine`, `shipmentLine`, `salesInvoiceLine`; blind returns fully supported | Optional-but-rich linkage is table stakes (research §Synthesis 2): link drives reversible-qty validation, credit pricing, and cost reversal |
+| Status lifecycle | Enum `salesReturnOrderStatus`: `Draft`, `Confirmed`, `Partially Received`, `Received`, `Completed`, `Cancelled` — receipt-driven transitions, manual guarded Complete | Quantity-derived statuses are the NetSuite/Infor/Katana consensus (research §Synthesis 3); Carbon precedent: receipt/shipment posting already flips source-doc statuses. No approval stage in v1 (only NetSuite/Infor make it first-class) |
+| Receiving | Reuse receipts end-to-end: activate `"Sales Return Order"` in `receiptSourceDocumentType`, extend `create` + `post-receipt` edge functions | No surveyed system invents a parallel receiving stack (research §Synthesis 4); inspection hook (`requiresInspection` → `On Hold`) already sits in `post-receipt` |
+| Ledger identity | `itemLedger.entryType 'Sale'` (positive qty), `documentType 'Sales Return Receipt'` | Symmetric with shipments (`'Sale'` negative, `'Sales Shipment'`); the document type value already exists unused |
+| Costing | Linked lines re-enter at original outbound cost (reverse the shipment's `costLedger` consumption); blind at current cost; `returnReason.inventoryValueZero` forces a 0-value layer | BC exact cost reversing + Epicor FIFO walk-back (research §Synthesis 7); zero-value is BC's per-reason damaged-goods hook |
+| Disposition split | RMA line `disposition` uses the **existing `disposition` enum** (+ additive `'Return to Customer'` value); picker subset `Pending / Use As Is / Return to Customer / Scrap / Rework`; Scrap/Rework/MRB **execute** via an escalated quality Issue | Research §Implications 4: reuse the quality vocabulary, don't build a second disposition subsystem. Quality already owns MRB, non-tracked quantity rows, and scrap GL (`post-nonconformance`) |
+| Reason vs disposition | Separate code sets: `returnReason` (why, set at authorization) vs `disposition` (what we did, set after receipt) | Infor's Problem Code / Disposition Code split (research §Infor, §Synthesis 9) |
+| Credit | Generate existing AR `memo` (header-level, unchanged shape) + per-line `salesReturnOrderCreditLine` breakdown; `quantityCredited` **derived** from credit lines joined to Posted memos, not stored | Carbon's memo has no lines; the breakdown table gives partial credits, void-safety (voided memo drops out of the derivation), and status guards without denormalized counters |
+| Restocking fee | `restockFeePercent` NUMERIC fraction 0–1 per line, default 0, applied at credit generation | Only BC documents a mechanism (per-line charge); fraction-0–1 matches Carbon's `discountPercent` convention |
+| Credit GL account | New nullable `accountDefault.salesReturnsAccount` (contra-revenue), fallback `salesAccount`; passed as the memo's `reasonAccount` | Lesson: control accounts resolve via `accountDefault` by id, never by number; `post-memo` already journals off `reasonAccount` — zero posting changes |
+| Replacement | `Create Replacement Order` action → draft SO from RMA lines (prices via `resolvePrice`, user adjusts, e.g. to zero for warranty); link stored as `salesReturnOrder.replacementSalesOrderId` | NetSuite post-receipt replacement SO (research §Synthesis 8); link lives on the NEW table so `salesOrder` is untouched |
+| Serial/lot | Expected entities picked per line (`salesReturnOrderLineTrackedEntity`) from entities shipped to that customer; receipt **reactivates the same entity** `On Hold`; disposition flips it | BC re-applies the same tracking identity; NetSuite picks "serial sold to this customer"; same-entity re-entry preserves genealogy — a differentiator no lightweight competitor manages (research §Implications 8) |
+| Multi-tenancy (heuristic 1) | Every new table: `companyId`, composite PK `("id","companyId")`, `id('prefix')`/`xid()` defaults, audit columns, `customFields` | House convention (`conventions-database.md`) |
+| Service shape (heuristic 2) | All new functions in `sales.service.ts`: client first arg, return `{data, error}`, never throw, `companyId`-scoped | House convention |
+| RLS (heuristic 3) | Policies named exactly `SELECT/INSERT/UPDATE/DELETE`; SELECT via `get_companies_with_employee_role()`, writes via `get_companies_with_employee_permission('sales_*')` (credit-line table: `invoicing_*` writes) | Post-rls-refactor convention; v1 is employee-only (no portal SELECT) |
+| Permission scoping (heuristic 4) | RMA routes `{action}: "sales"`; receipt routes unchanged (`inventory`); credit generation `create: "invoicing"` (same as `x+/credits+/new`) | Matches the owning machinery of each step |
+| Forms (heuristic 5) | `ValidatedForm` + `validator(zodSchema)` + route actions; business dates default via `useCompanyToday()` | House convention; date-handling rule |
+| Module layout (heuristic 6) | Extends `sales.models.ts` / `sales.service.ts` / `modules/sales/ui/SalesReturnOrders/`; no new module folder | One service/models file per module (root AGENTS.md "Never") |
+| Backward compat (heuristic 7) | Everything additive: new tables, new enum values, new nullable columns (`memo.salesReturnOrderId`, `accountDefault.salesReturnsAccount`). No renames, no drops, no scope changes | `BACKWARD_COMPATIBILITY.md`: DB schema is ADDITIVE-ONLY; permission scopes FROZEN (none added) |
+
+## Data Model Changes
+
+One migration (`pnpm db:migrate:new sales-return-orders`), all additive. `pnpm run generate:types` after.
+
+### Enums
+
+```sql
+CREATE TYPE "salesReturnOrderStatus" AS ENUM (
+ 'Draft', 'Confirmed', 'Partially Received', 'Received', 'Completed', 'Cancelled'
+);
+ALTER TYPE "disposition" ADD VALUE 'Return to Customer'; -- mirrors 'Return to Supplier'
+ALTER TYPE "nonConformanceAssociationType" ADD VALUE 'Sales Return Order';
+```
+
+### `returnReason` (why — company-defined, `noQuoteReason` pattern)
+
+```sql
+CREATE TABLE "returnReason" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "name" TEXT NOT NULL,
+ "inventoryValueZero" BOOLEAN NOT NULL DEFAULT FALSE, -- BC hook: item re-enters at zero value
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "customFields" JSONB,
+ PRIMARY KEY ("id", "companyId"),
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ UNIQUE ("companyId", "name")
+);
+```
+
+Seed per company (migration backfill + `seed.data.ts` + `seed-company`): `Defective`, `Wrong Item Shipped`, `Damaged in Transit`, `No Longer Needed`, `Warranty`, `Other`.
+
+### `salesReturnOrder` (header)
+
+```sql
+CREATE TABLE "salesReturnOrder" (
+ "id" TEXT NOT NULL DEFAULT id('sro'),
+ "salesReturnOrderId" TEXT NOT NULL, -- readable RMA000001 via get_next_sequence
+ "status" "salesReturnOrderStatus" NOT NULL DEFAULT 'Draft',
+ "customerId" TEXT NOT NULL, -- → customer
+ "customerLocationId" TEXT,
+ "customerContactId" TEXT,
+ "customerReference" TEXT, -- the customer's claim / PO number
+ "locationId" TEXT, -- receiving site
+ "salesOrderId" TEXT, -- convenience header link (lines are authoritative)
+ "replacementSalesOrderId" TEXT, -- → salesOrder, SET NULL on delete
+ "currencyCode" TEXT NOT NULL,
+ "exchangeRate" NUMERIC(10,5) NOT NULL DEFAULT 1,
+ "orderDate" DATE NOT NULL, -- company-calendar day (useCompanyToday)
+ "expirationDate" DATE, -- informational authorization window
+ "internalNotes" JSON,
+ "externalNotes" JSON,
+ "assignee" TEXT REFERENCES "user"("id"),
+ "companyId" TEXT NOT NULL,
+ -- audit columns + customFields as per template
+ PRIMARY KEY ("id", "companyId"),
+ UNIQUE ("salesReturnOrderId", "companyId")
+);
+```
+
+FKs: `customerId` → `customer`, `locationId` → `location`, `salesOrderId`/`replacementSalesOrderId` → `salesOrder` (ON DELETE SET NULL). Indexes on `companyId`, `customerId`, `status`.
+
+### `salesReturnOrderLine`
+
+```sql
+CREATE TABLE "salesReturnOrderLine" (
+ "id" TEXT NOT NULL DEFAULT id('srol'),
+ "salesReturnOrderId" TEXT NOT NULL, -- → salesReturnOrder ON DELETE CASCADE
+ "lineNumber" INTEGER NOT NULL DEFAULT 1,
+ "itemId" TEXT NOT NULL, -- required: receipts need an item
+ "quantity" NUMERIC NOT NULL, -- authorized to return
+ "quantityReceived" NUMERIC NOT NULL DEFAULT 0, -- maintained by post-receipt (void-safe)
+ "unitOfMeasureCode" TEXT,
+ "unitPrice" NUMERIC NOT NULL DEFAULT 0, -- credit basis (copied from linked line when present)
+ "restockFeePercent" NUMERIC NOT NULL DEFAULT 0, -- fraction 0–1, like discountPercent
+ "returnReasonId" TEXT, -- → returnReason
+ "salesOrderLineId" TEXT, -- all three nullable: blind returns allowed
+ "shipmentLineId" TEXT,
+ "salesInvoiceLineId" TEXT,
+ "disposition" "disposition" NOT NULL DEFAULT 'Pending',
+ "closedComplete" BOOLEAN NOT NULL DEFAULT FALSE, -- short-close: stop expecting remainder
+ "companyId" TEXT NOT NULL,
+ -- audit columns + customFields
+ PRIMARY KEY ("id", "companyId")
+);
+```
+
+### `salesReturnOrderLineTrackedEntity` (expected serials/batches)
+
+```sql
+CREATE TABLE "salesReturnOrderLineTrackedEntity" (
+ "salesReturnOrderLineId" TEXT NOT NULL,
+ "trackedEntityId" TEXT NOT NULL, -- → trackedEntity (picked from entities shipped to this customer)
+ "quantity" NUMERIC NOT NULL DEFAULT 1,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ PRIMARY KEY ("salesReturnOrderLineId", "trackedEntityId", "companyId")
+);
+```
+
+### `salesReturnOrderCreditLine` (per-line credit breakdown; the memo stays header-level)
+
+```sql
+CREATE TABLE "salesReturnOrderCreditLine" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "memoId" TEXT NOT NULL, -- → memo ON DELETE CASCADE
+ "salesReturnOrderLineId" TEXT NOT NULL, -- → salesReturnOrderLine
+ "quantity" NUMERIC NOT NULL,
+ "unitPrice" NUMERIC NOT NULL,
+ "restockFee" NUMERIC NOT NULL DEFAULT 0, -- computed amount, stored for audit
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ PRIMARY KEY ("id", "companyId")
+);
+```
+
+`quantityCredited` per RMA line = `SUM(quantity)` over credit lines whose memo is `Posted` — derived in the views, never stored. Deleting/voiding a memo automatically un-credits.
+
+### Quality association junction (mirrors the existing 10)
+
+```sql
+CREATE TABLE "nonConformanceSalesReturnOrderLine" (
+ "nonConformanceId" TEXT NOT NULL,
+ "salesReturnOrderLineId" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ PRIMARY KEY ("nonConformanceId", "salesReturnOrderLineId", "companyId")
+);
+```
+
+### Additive columns on existing tables
+
+```sql
+ALTER TABLE "memo" ADD COLUMN "salesReturnOrderId" TEXT; -- nullable FK → salesReturnOrder, SET NULL
+ALTER TABLE "accountDefault" ADD COLUMN "salesReturnsAccount" TEXT; -- nullable; fallback = salesAccount
+```
+
+Seed a `Sales Returns` contra-revenue posting account under the Income group for existing companies — resolve the parent group by `"isGroup" = TRUE AND name`, **never by number** (lesson; `20260630093809_ar-ap-payments.sql` is the precedent), plus `seed.data.ts`/`seed-company` for new companies.
+
+### Sequence + view
+
+- `sequence` seed rows per company: `("table","name","prefix","next","size","step","companyId")` = `('salesReturnOrder','Sales Return Order','RMA',…)` — same INSERT shape as `20260630093809`.
+- `salesReturnOrders` view (`SECURITY_INVOKER=true`): header + customer name + aggregate `linesCount`, `quantityReceived`, `quantityCredited` (derived as above) — the `issues` view precedent, read by the list table.
+
+### RLS
+
+All new tables: policies named exactly `SELECT` / `INSERT` / `UPDATE` / `DELETE`. `SELECT` via `(SELECT get_companies_with_employee_role())::text[]`; writes via `(SELECT get_companies_with_employee_permission('sales_<action>'))::text[]` — except `salesReturnOrderCreditLine` writes gated on `invoicing_<action>` (it is created by the credit flow). Junction tables derive visibility from their parents per the standard pattern. v1 has **no** customer-portal SELECT arm.
+
+## API / Service Changes
+
+### `sales.models.ts`
+`salesReturnOrderValidator`, `salesReturnOrderLineValidator`, `returnReasonValidator`, `salesReturnOrderStatusType` const array, `salesReturnDispositionType` picker subset (`Pending`, `Use As Is`, `Return to Customer`, `Scrap`, `Rework`) — same commented-subset technique `quality.models.ts` uses on `disposition`.
+
+### `sales.service.ts` (client-first, `{data, error}`, `companyId`-scoped)
+`getSalesReturnOrders` (view + generic filters), `getSalesReturnOrder`, `getSalesReturnOrderLines`, `upsertSalesReturnOrder`, `upsertSalesReturnOrderLine`, `deleteSalesReturnOrder(Line)`, `confirmSalesReturnOrder`, `cancelSalesReturnOrder`, `completeSalesReturnOrder` (guard: all non-closed lines received; no received qty `Pending`), `getReturnReasons` + CRUD, `getReturnableLinesForCustomer` (reversible-quantity source: shipped/invoiced minus already authorized/returned — BC "Show Reversible Lines Only"), `getShippedTrackedEntitiesForCustomer` (entity picker source), `createReplacementSalesOrder`, `createSalesReturnOrderCredit`.
+
+**Quantity caps are transactional invariants (both directions).** The reversible cap (shipped/received minus already authorized+returned) and the credit cap (received minus already credited) are enforced inside a Kysely transaction that row-locks the governing rows (`SELECT … FOR UPDATE` on the return line and its linked source line) and re-reads the aggregates before writing. Confirm, receipt/shipment posting, and credit creation/posting all pass through this check — two concurrent partial returns (or partial credits) against the same source line cannot jointly exceed the cap. Voided memos re-enter the creditable pool automatically since `quantityCredited` derives from `Posted` memos only.
+
+### Edge functions (extensions, no new functions except disposition posting decision below)
+- **`create`** — new branch in the `receipt` case: `sourceDocument: "Sales Return Order"` builds `receiptLine`s from open RMA lines (`quantity − quantityReceived`, skipping `closedComplete`), copying location/uom; `sourceDocumentReadableId = salesReturnOrder.salesReturnOrderId`.
+- **`post-receipt`** — return branch: positive `itemLedger` (`'Sale'` / `'Sales Return Receipt'`); `costLedger` layer at resolved cost (linked → original outbound cost from the shipment's consumed layers; blind → current item cost; `returnReason.inventoryValueZero` → 0); journal `Dr resolveInventoryAccount / Cr accountDefault.costOfGoodsSoldAccount` at layer value when `accountingEnabled`; tracked entities: reactivate the SAME `trackedEntity` (`status 'On Hold'`) when the receipt line maps to an expected entity, else create new `On Hold`; write a `'Return Receipt'` `trackedActivity` (+output links); bump `quantityReceived` and transition header status (`Confirmed → Partially Received → Received`). Receipt **void** reverses all of it (existing void pattern).
+- **Dispositions**: `Use As Is` flips entity → `Available` (service-level, no GL). `Return to Customer` creates a shipment `sourceDocument 'Sales Return Order'` (activate the value in `shipmentSourceDocumentType`; `post-shipment` branch posts the negative ledger at carried cost). `Scrap`/`Rework` are **not executed by the RMA**: the line action creates/links a quality Issue pre-associated via `nonConformanceSalesReturnOrderLine` (+ tracked entities), and the Issue's existing close flow (`post-nonconformance`) posts the write-off. The RMA line's `disposition` field records the outcome.
+- **Credit**: `createSalesReturnOrderCredit` inserts one `memo` (`direction 'Credit'`, `customerId`, RMA currency/exchange, `reasonAccount = accountDefault.salesReturnsAccount ?? salesAccount`, `salesReturnOrderId`) + `salesReturnOrderCreditLine` rows; amount = Σ qty × unitPrice × (1 − restockFeePercent). Posting/voiding stays entirely in the existing `x+/credits+` routes + `post-memo` — no changes there.
+
+### Routes (`path.to` additions)
+- List `x+/sales+/rmas.tsx`; reasons CRUD quartet `x+/sales+/return-reasons(.new/.$id/.delete.$id).tsx` (clone the `no-quote-reasons` quartet).
+- Detail tree `x+/sales-return-order+/`: `_layout.tsx` (`handle.module: "sales"`), `$id.tsx` (+`details`), `new.tsx`, POST-only `$id.confirm/cancel/complete.tsx`, `$id.lines.*`, `$id.credit.tsx` (`create: "invoicing"`), `$id.replacement.tsx`, `$id.delete.tsx`, PDF at `$id[.]pdf.tsx`.
+- All RMA routes `requirePermissions` with `"sales"`; receipt/shipment routes unchanged.
+
+### Documents
+RMA PDF in `packages/documents` (header, customer, lines, reasons, return-to address, expiration) following the sales-order PDF pattern; wired to the `[.]pdf` route and the Confirm flow.
+
+## UI Changes
+
+- **Nav**: "RMAs" item in the Sales sidebar group.
+- **List** (`ui/SalesReturnOrders/SalesReturnOrdersTable.tsx`): readable id, customer, status badge, order date, received/credited progress, assignee; standard table conventions (CSV export, filters, saved views).
+- **Detail**: header card (status flow Confirm/Cancel/Complete actions, customer, dates, replacement-order link) + lines table (item, qty authorized/received/credited, unit price, restock fee, reason, disposition select using the picker subset, linkage chips to SO/shipment/invoice, tracked-entity chips) + panels for related **Receipts**, **Credits** (memos via `memo.salesReturnOrderId`), and **Issues** (via the association).
+- **New RMA form**: customer select → optional "from document" picker (`getReturnableLinesForCustomer`) pre-filling lines with reversible quantities, prices, and links; line editor with `TrackedEntityPicker` filtered to entities shipped to that customer; `orderDate` defaults via `useCompanyToday()`.
+- **Receipts UI**: uncomment `"Sales Return Order"` in `receiptSourceDocumentType` (and `shipmentSourceDocumentType` for return-to-customer) in `inventory.models.ts`; the source-document select then lists open RMAs — no other receipts UI work.
+- **Credit dialog**: per-line quantity (default received − credited), fee preview, total; submits to `$id.credit`.
+- **Quality**: `IssueAssociations` gains the Sales Return Order association type (render + create like the existing ten).
+- **MES**: no changes.
+
+## Purchasing Side — `purchaseReturnOrder` (Supplier Returns)
+
+Added per review on PR #1354. A direction-flipped mirror of the customer side: the customer RMA **receives**, the supplier return **ships** (research §Synthesis 10; NetSuite Vendor RA: enter → approve → ship → credit; BC purchase return orders → posted return shipments → purchase credit memo). Everything below reuses the sales-side design verbatim unless a delta is called out — same conventions (multi-tenancy, RLS naming, service shape, additive-only) apply.
+
+### Workflow
+
+`Draft → Confirmed → Partially Shipped → Shipped → Completed / Cancelled` (enum `purchaseReturnOrderStatus`). Authorize lines (optionally from a PO / receipt / purchase invoice, with reversible-quantity validation against received-minus-already-returned) → confirm (assigns readable id, PDF for the supplier's RMA process; header `supplierReference` carries the **supplier's own RMA number** — NetSuite records both numbers) → ship through the existing shipments system (`shipmentSourceDocument 'Purchase Return Order'`, pre-plumbed) → generate supplier credit memo(s) → optional replacement PO → guarded Complete with `closedComplete` short-close.
+
+There is **no disposition stage** — goods leave; the decision of *what* to send back was already made (usually by a quality Issue). There is no `inventoryValueZero` analog either: outbound relief is always at carried cost.
+
+**Source lineage & units.** The three line links have distinct jobs: `receiptLineId` is the **physical** lineage — it anchors the reversible-quantity base, the tracked-entity pick, and the receipt posting the shipment journal reverses; `purchaseOrderLineId` / `purchaseInvoiceLineId` are **commercial** context (credit pricing). An invoice- or PO-linked line must resolve to a posted receipt allocation to claim linked lineage; when it can't (invoice-only, goods not yet received into a resolvable receipt), the line is explicitly a **blind return** — carried-cost relief with a manual entity pick, same as a link-free line. Return lines store quantities and `unitPrice` in the item's **inventory unit of measure**, always: purchase lines live in purchase UOM (`purchaseQuantity` × `conversionFactor` → inventory units), so authoring from a PO/invoice line converts quantity and price through that line's `conversionFactor` once, at authoring time — validation, shipment posting, and credit math all run in inventory units (the unit `receiptLine` and `itemLedger` already post in).
+
+### Deltas vs the sales side
+
+| Aspect | Sales side | Purchase side |
+|--------|-----------|---------------|
+| Physical flow | Receipt (`receiptSourceDocument 'Sales Return Order'`) | Shipment (`shipmentSourceDocument 'Purchase Return Order'`), `post-shipment` branch |
+| Ledger identity | `entryType 'Sale'`, positive, `'Sales Return Receipt'` | `entryType 'Purchase'`, **negative**, `'Purchase Return Shipment'` (pre-existing unused value) |
+| Cost | Original outbound cost / current / zero | Carried layer cost (standard consumption math — no policy choice) |
+| Journal | `Dr Inventory / Cr COGS` | `Cr Inventory / Dr goodsReceivedNotInvoicedAccount` (reverses the receipt posting); credit-vs-cost delta → `purchaseVarianceAccount` |
+| Tracked entities | Same entity re-enters `On Hold`; disposition flips it | Entities picked from on-hand stock received from that supplier; shipping marks them `Consumed` + `'Return Shipment'` activity (genealogy closed, not broken) |
+| Money | AR memo (`customerId`, `reasonAccount = salesReturnsAccount ?? salesAccount`) | AP memo (`supplierId`, direction `Credit`, `reasonAccount = goodsReceivedNotInvoicedAccount` so `post-memo` nets GRNI against payables) |
+| Replacement | `replacementSalesOrderId` → draft SO | `replacementPurchaseOrderId` → draft PO |
+| Reason codes | `returnReason` | **Same table** — shared across both directions (BC precedent); `inventoryValueZero` is simply ignored outbound |
+| Module home | Sales (`sales_*`) | Purchasing (`purchasing.models.ts` / `purchasing.service.ts` / `modules/purchasing/ui/PurchaseReturnOrders/`, `purchasing_*` perms); credit generation `create: "invoicing"` |
+| Quality relationship | RMA escalates TO an Issue | An Issue's `'Return to Supplier'` disposition **drafts** a `purchaseReturnOrder` |
+
+### Data model (mirror tables, all additive)
+
+- `purchaseReturnOrder` — same shape as `salesReturnOrder` with: `id('pro')`, readable `purchaseReturnOrderId` (sequence prefix `RTS`, e.g. `RTS000001`), `supplierId` (NOT NULL), `supplierLocationId`/`supplierContactId`, **`supplierReference`** (the supplier's RMA number), `purchaseOrderId` convenience link, `replacementPurchaseOrderId`, status `purchaseReturnOrderStatus`; no reason-hook columns beyond the sales twin.
+- `purchaseReturnOrderLine` — same shape as `salesReturnOrderLine` with `id('prol')`, `quantityShipped` (not `quantityReceived`), links `purchaseOrderLineId` / `receiptLineId` / `purchaseInvoiceLineId` (all nullable — blind supplier returns allowed), `unitPrice` = expected credit basis (copied from the linked PO/invoice line), `restockFeePercent` (supplier-charged fee reduces our credit), **no `disposition` column**.
+- `purchaseReturnOrderLineTrackedEntity` — expected entities to send back, picked from on-hand entities whose genealogy traces to that supplier.
+- `purchaseReturnOrderCreditLine` — mirror of the sales twin (`memoId`, `purchaseReturnOrderLineId`, quantity/unitPrice/fee); `quantityCredited` derived from `Posted` memos the same way.
+- `nonConformancePurchaseReturnOrderLine` + `nonConformanceAssociationType` value `'Purchase Return Order'` — Issue ↔ supplier-return linkage for the bridge.
+- `ALTER TABLE "memo" ADD COLUMN "purchaseReturnOrderId" TEXT` (nullable, SET NULL).
+- `CREATE TYPE "purchaseReturnOrderStatus" AS ENUM ('Draft','Confirmed','Partially Shipped','Shipped','Completed','Cancelled');`
+- Sequence seed rows (`'purchaseReturnOrder'`, prefix `RTS`) + a `purchaseReturnOrders` list view mirroring `salesReturnOrders`.
+- RLS: identical pattern with `purchasing_*` permissions (`invoicing_*` for the credit-line table). No portal arm.
+
+### Flows
+
+- **Ship**: `create` edge function gains a `shipment` branch for `sourceDocument 'Purchase Return Order'` (lines from open return lines, `quantity − quantityShipped`); `post-shipment` gains the return branch — negative `itemLedger` at carried cost via the existing consumption math, journal per the deltas table, entity flips + `'Return Shipment'` `trackedActivity`, `quantityShipped` bump + status transition, void reverses.
+- **Credit**: `createPurchaseReturnOrderCredit` mirrors the sales twin — one AP `memo` + credit lines; posting/voiding untouched in `x+/credits+`.
+- **Replacement**: draft PO from return lines (prices from the linked PO line or `supplierPart` pricing; user adjusts for warranty).
+- **Quality bridge**: on an Issue whose disposition is `'Return to Supplier'`, a **Create Supplier Return** action drafts a `purchaseReturnOrder`. *Supplier resolution:* exactly one `nonConformanceSupplier` association → that supplier; otherwise derived from the selected receipt lines' parent receipts; missing or conflicting → the dialog requires an explicit supplier and source-line selection (an Issue spanning suppliers yields one draft per supplier). Every selected line and tracked entity is validated to belong to the resolved supplier before the draft is written. *Ownership is per quantity:* each `nonConformancePurchaseReturnOrderLine` association row records the quantity it covers, and the action is **idempotent** — quantities already covered by a non-cancelled linked return are excluded from a new draft (re-invoking with nothing uncovered returns the existing draft). *Close rule (atomic):* `closeIssue` is **blocked** while a linked supplier return is open (`Draft`/`Confirmed`/`Partially Shipped`) — ship, short-close, or cancel it first; at close, `post-nonconformance` writes off only `issue quantity − Σ quantities shipped via linked returns` (covered-and-shipped relief already came from the return shipment; cancelling a return releases its unshipped covered quantities back to the write-off pool).
+- **Routes/UI**: list `x+/purchasing+/supplier-returns.tsx` + nav "Supplier Returns" (Purchasing group); detail tree `x+/purchase-return-order+/` mirroring the sales twin (confirm/cancel/complete, lines, credit, replacement, PDF); shipments UI uncomment for `'Purchase Return Order'`; entity picker `getReturnableEntitiesForSupplier`.
+
+## Acceptance Criteria
+
+- [ ] Creating an RMA from a shipped+invoiced sales order pre-fills lines with the shipped quantities, prices, and line links; authorizing more than shipped-minus-already-returned is rejected with a validation error.
+- [ ] A standalone (blind) RMA with no document links can be created, confirmed, received, and credited end-to-end.
+- [ ] Confirming assigns `RMA000001`-style ids from the company sequence and produces a downloadable PDF.
+- [ ] A receipt with source "Sales Return Order" against a confirmed RMA receives a partial quantity; the RMA flips to `Partially Received`, then `Received` when the remainder posts; voiding the receipt restores prior quantities and status.
+- [ ] Receiving a linked line for an item shipped at cost X while current cost is Y ≠ X creates the inventory layer at **X** and journals `Dr Inventory / Cr COGS` for X × qty (accounting enabled); a blind line uses current cost; a line whose reason has `inventoryValueZero` posts a 0-value layer and no journal.
+- [ ] Returning a serialized item picked on the RMA line reactivates the SAME `trackedEntity` id in `On Hold`, with a `Return Receipt` activity visible in the traceability graph connecting its original shipment history.
+- [ ] `Use As Is` disposition flips the returned entity to `Available` and it appears in on-hand quantities; `Return to Customer` creates a postable shipment that removes it again.
+- [ ] `Scrap` on a line opens/links a quality Issue carrying the item, quantity, and tracked entities; closing that Issue with a Scrap disposition posts the write-off through `post-nonconformance` (no GL posted by the RMA itself).
+- [ ] Issuing credit for 2 of 5 received units at unit price 100 with a 10% restock fee creates a Draft memo for 180 linked to the RMA; after posting, the RMA shows `quantityCredited = 2`; voiding the memo returns it to 0.
+- [ ] `Create Replacement Order` produces a draft sales order pre-filled from the RMA lines and both documents show the cross-link.
+- [ ] `Complete` is blocked while any received quantity is `Pending` disposition or any non-closed line is short of authorized quantity; short-closing the line unblocks it.
+- [ ] A supplier return created from a posted PO receipt pre-fills lines with reversible quantities, prices, and links; authorizing more than received-minus-already-returned is rejected.
+- [ ] Shipping a partial quantity against a confirmed supplier return flips it `Confirmed → Partially Shipped → Shipped`; posting relieves inventory at carried layer cost (`Cr Inventory / Dr GRNI`), marks the shipped tracked entities `Consumed` with a `Return Shipment` activity, and voiding the shipment reverses all of it.
+- [ ] Issuing supplier credit creates a Draft AP memo (`supplierId`, direction `Credit`, `reasonAccount = goodsReceivedNotInvoicedAccount`) linked via `memo.purchaseReturnOrderId`; posting updates the return's credited quantities; voiding reverts them.
+- [ ] Closing a quality Issue with a `'Return to Supplier'` disposition offers **Create Supplier Return**, which drafts a `purchaseReturnOrder` pre-filled with the resolved supplier, items, and tracked entities; re-invoking it drafts nothing new for already-covered quantities; Issue close is blocked while the linked return is open; and after the return shipment posts, closing the Issue writes off only the uncovered remainder (no double relief).
+- [ ] A supplier return authored from a purchase-invoice line with `conversionFactor ≠ 1` against a partially received PO stores inventory-unit quantity and price (converted once at authoring), caps authorization at received-minus-already-returned, and an invoice-only line with no resolvable posted receipt allocation is explicitly flagged as a blind return.
+- [ ] Two concurrent confirms (or two concurrent credit creations) against the same source line cannot jointly exceed the reversible/creditable cap — the second transaction re-reads under row lock and fails validation.
+- [ ] All new tables enforce RLS (cross-company reads return nothing); every route 403s without the corresponding `sales`/`purchasing`/`invoicing` permission.
+- [ ] `pnpm run generate:types`, scoped typecheck, lint, and existing inventory/receipt/shipment tests pass.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Original-cost resolution from shipment cost layers is subtle (partial shipments, corrections, multi-layer consumption) | High | Reuse `calculateCOGS`'s layer math in reverse; fall back to current cost with a flagged variance note when layers can't be resolved; unit-test against multi-layer fixtures |
+| `post-receipt` is load-bearing for PO receiving; a regression breaks daily receiving | High | Return branch is additive and switched on `sourceDocument`; existing PO/transfer paths untouched; run existing receipt tests + new return fixtures |
+| `post-shipment` is equally load-bearing for daily sales shipping (purchase-return branch) | High | Same additive-branch discipline; existing shipment tests + supplier-return fixtures |
+| Issue `'Return to Supplier'` + linked return shipment could double-relieve inventory | Med | Per-quantity ownership on the association rows; Issue close blocked while a linked return is open; write-off = issue qty − shipped-via-return qty (see Quality bridge) |
+| `ALTER TYPE … ADD VALUE` cannot run inside a transaction block on older Postgres patterns | Med | Follow the existing enum-addition migrations in the repo (`database-migration-patterns.md`); keep enum additions in their own statements |
+| Reactivating a `Consumed`/shipped tracked entity may collide with status assumptions elsewhere (`get_inventory_quantities`, pickers) | Med | Re-entry uses `On Hold` (already excluded from available); audit the status-aware reads before implementation; the disposition step is the only path to `Available` |
+| Credit derivation joins (creditLine × memo status) on hot list views | Low | Aggregate inside the `salesReturnOrders` view; index `salesReturnOrderCreditLine(memoId)` and `(salesReturnOrderLineId)` |
+| Users expect refunds, not just credits | Low | Credit-application + payment flows already exist (`credit-applications-via-payment`); the RMA stops at the posted memo by design; document the handoff |
+
+## Open Questions
+
+> All resolved autonomously (fully-autonomous feature run — no human was available mid-run; resolutions follow codebase precedent first, then research consensus, per spec-writing autonomous mode). **Review these at spec review — they are decisions, not facts.**
+
+- [x] Standalone document vs quality-issue extension vs Odoo-style operation-only? — **Autonomous:** standalone non-posting `salesReturnOrder` document. Pre-plumbed enums are codebase intent; unanimous competitor pattern (research §Synthesis 1); Odoo's documentless model leaves state homeless.
+- [x] Which module/permission family owns it? — **Autonomous:** Sales (`sales_*`), no new `module` enum value or permission scope. Lesson "Features live inside existing permission modules"; scopes are FROZEN.
+- [x] Table naming? — **Autonomous:** `salesReturnOrder`, matching the existing enum literal and `salesOrder` symmetry; UI says "RMA".
+- [x] Are original-document links required? — **Autonomous:** optional (blind returns are table stakes everywhere); when present they drive reversible-qty validation, pricing, and exact cost reversal.
+- [x] Status model — explicit workflow states or quantity-derived? — **Autonomous:** small explicit enum with receipt-driven transitions and a guarded manual Complete; mirrors NetSuite's quantity-derived semantics without computed-status complexity.
+- [x] Reuse receipts or build return-receiving? — **Autonomous:** reuse receipts (`sourceDocument 'Sales Return Order'`); no surveyed system builds a parallel receiving stack; the enum value and `post-receipt` inspection hook already exist.
+- [x] Same `trackedEntity` re-entry or new entity per return? — **Autonomous:** same entity, `On Hold`, with a `Return Receipt` genealogy activity (new entity only for blind returns). Preserves round-trip traceability; BC re-applies the same tracking identity.
+- [x] What cost do returns re-enter at? — **Autonomous:** original outbound cost when linked (BC exact cost reversing / Epicor layer walk-back); current cost blind; zero when the reason flags `inventoryValueZero`.
+- [x] New disposition subsystem or reuse quality? — **Autonomous:** reuse: the line's `disposition` uses the existing enum (+ additive `Return to Customer`); Scrap/Rework/MRB execute through an escalated quality Issue (Epicor Fail→DMR pattern) so GL and approvals stay in one place.
+- [x] How does credit work against a header-only memo? — **Autonomous:** keep memo header-only; add `salesReturnOrderCreditLine` breakdown + nullable `memo.salesReturnOrderId`; `quantityCredited` derived from Posted memos (void-safe), multiple partial credits allowed.
+- [x] Restocking fee shape? — **Autonomous:** per-line `restockFeePercent` fraction 0–1 applied at credit generation (BC per-line charge precedent; only vendor-documented mechanism).
+- [x] Credit GL account? — **Autonomous:** additive `accountDefault.salesReturnsAccount` (contra-revenue, seeded account, fallback `salesAccount`) passed as the memo `reasonAccount` — the `accountDefault` lesson pattern; `post-memo` unchanged.
+- [x] Replacement mechanics? — **Autonomous:** action spawns a draft SO from RMA lines with `resolvePrice` pricing (user zeroes for warranty); link on `salesReturnOrder.replacementSalesOrderId`; BC's negative-line dance rejected.
+- [x] v1 scope boundaries? — **Autonomous:** OUT: customer-portal-initiated returns, approval workflow stage, formal repair/rework job linkage (quality Issue covers it), refunds beyond the posted memo, MES surfaces. IN: PDF, return reasons, partial everything. (Supplier-side `purchaseReturnOrder` was originally deferred; pulled into scope per review — next question.)
+- [x] Supplier-side shape? — **Review (PR #1354, changes requested: "Let's do the purchasing side as part of the spec too"):** included as a direction-flipped mirror — authorize → **ship** → credit (NetSuite Vendor RA order of operations), shared `returnReason` table (BC shares the reason codes across sales and purchase returns), no disposition stage (goods leave; nothing to disposition), the supplier's own RMA number on the header (`supplierReference`), and a "Create Supplier Return" bridge on the quality Issue `'Return to Supplier'` disposition. See the Purchasing Side section.
+
+## Changelog
+
+- 2026-08-11 (b): Review hardening from the automated review on PR #1354, all four findings verified against schema: (1) supplier-return source-lineage contract — `receiptLineId` = physical lineage, PO/invoice links = commercial, explicit blind-return fallback; canonical inventory-unit quantities with one-time `conversionFactor` conversion (verified: `purchaseOrderLine.purchaseQuantity`/`conversionFactor`/`inventoryUnitOfMeasureCode` are real dual-unit columns); (2) quantity caps stated as row-locked transactional invariants for concurrent returns/credits; (3) quality bridge: supplier resolution rules (multiple `nonConformanceSupplier` rows are possible — no unique constraint), per-quantity ownership, idempotent Create Supplier Return, close blocked while a linked return is open. Acceptance criteria + risks updated.
+- 2026-08-11: Purchasing side added — `purchaseReturnOrder` supplier-returns mirror (authorize → ship → credit, shared `returnReason`, Issue `'Return to Supplier'` bridge, double-relief close guard) per review on PR #1354 ("Let's do the purchasing side as part of the spec too"). Title, TLDR, problem statement, scope resolution, acceptance criteria, and risks updated to match.
+- 2026-08-07: Created. Research at `.ai/research/2026-08-07-rma-module.md`; internal recon + run record at `.ai/runs/2026-08-07-rma-module.md`. All 14 open questions resolved autonomously (fully-autonomous run) — flagged for human review at spec review, especially: additive enum values (`disposition`, `nonConformanceAssociationType`), additive columns on `memo` + `accountDefault` (+ seeded contra-revenue account), and the decision to route Scrap/Rework GL through quality Issues rather than RMA-native posting.