Coupon on a Sales Order is validated and counted again on its invoice: single-use coupons can't be invoiced
Information about bug
A coupon on a Sales Order is validated and counted when the order is submitted. Because coupon_code is not no_copy, make_sales_invoice copies it onto the invoice, which validates it again in validate and counts it again in on_submit. The same happens on credit notes (make_return_doc) and on POS closing, where merge_pos_invoice_into copies coupon_code onto the consolidated Sales Invoice with map_doc.
- A single-use coupon (every Gift Card coupon is forced to
maximum_use = 1) blocks its own invoice, credit note or POS Closing Entry with "Sorry, this coupon code is no longer valid". - A multi-use coupon is counted twice per order.
We hit this in production on a portal checkout: the Sales Order was paid online, PaymentRequest.make_invoice then failed, and the customer was charged with no invoice or payment entry recorded.
Steps to reproduce:
- Create a Pricing Rule with "Coupon Code Based" checked.
- Create a Gift Card Coupon Code for a customer, linked to that rule.
- Create a Sales Order for that customer with the coupon, submit it. The coupon shows used 1/1.
- Sales Order → Create → Sales Invoice, then save.
Expected: the invoice saves and submits, and the coupon stays at 1/1. Actual: "Sorry, this coupon code is no longer valid".
With a Promotional coupon allowing 5 uses, step 4 succeeds but the coupon ends at 2/5 for one order.
The coupon handling on Sales Invoice came with #40504, and #43761 made the maximum_use check reachable. version-15 is not affected, since its Sales Invoice has no coupon handling.
Proposed fix
Let the document that first takes the coupon own the count. The Sales Invoice, and POS Invoice through inheritance, skips the coupon validation and count when it is a return or a consolidated invoice, or when a submitted linked Sales Order already carries the same coupon. Direct invoices behave as before.
Making coupon_code no_copy would be shorter, but the invoice would lose the discount, since pricing rules are re-applied on validate.
Commit: https://github.com/maasanto/erpnext/commit/41c10de9e49269a16841cb07fb637c50e2f19574 (one commit on develop 213284cfa20)
It adds three tests: an invoice from a Sales Order with a single-use coupon and its cancellation, a credit note against a coupon invoice, and a POS closing with a single-use coupon. All three fail without the change and pass with it on our fork, whose coupon code is identical to develop.
Would you accept this fix from the community? If so, feel free to cherry-pick the commit.
Module
accounts, selling
Version
ERPNext develop (213284cfa20), version-16
Source: frappe/erpnext