Build promos for real: engine, storage, editor, and application at the till

The Promo module was a mockup. Three hardcoded rows, a toggle that changed
nothing, and no promo code anywhere in lib/domain or lib/data. A cashier
looking at it would reasonably conclude promotions were running.

Engine (domain/services/promo_engine.dart)
- Five campaign types: percent or flat off the bill, percent off a category
  or a product, and buy-X-get-Y.
- Conditions: date range (inclusive of the closing day), days of the week,
  minimum bill value, and a cap on what a percentage can take off — without
  one an unusually large trolley gives away more than the campaign was costed
  for.
- Stacking is conservative by default. All stackable campaigns apply together;
  of the exclusive ones only the single best does, chosen by what it is worth
  to the shopper with priority breaking ties. Two percentages compounding
  produce a discount nobody signed off, and the shop finds out at the end of
  the month.
- The total is capped at the subtotal, so no combination of campaign, tier and
  manual discount can turn a sale into a payout.
- buy-X-get-Y counts whole groups only, and prices the free unit at what is
  actually being charged — a line already carrying a manual discount must not
  refund more than it took.

Kept out of Cart deliberately: Cart owns arithmetic that must never be wrong,
this owns policy a shop changes weekly.

Storage (schema v6, plus promos_json on orders at v7)
- Campaigns persist locally, because a shop mid-promotion with a dead line
  still has to honour the price on the shelf edge.
- A bill records the campaign name and the amount given, not a link to the
  row. A campaign edited or deleted later cannot change what a past sale
  shows, and a reprinted receipt still names what the shopper was given.
- On read-back the promo amounts are subtracted from the manual discount,
  because bill_discount already contains them. Restoring both at full value
  would discount the bill twice — the same shape as the bug that used to
  overstate synced totals.

At the till
- Every cart mutation re-evaluates, so a promo cannot survive the line that
  earned it being removed.
- A resumed parked bill is re-evaluated rather than restored: a campaign that
  has since ended must not be honoured because the bill was parked while it
  was running.
- Campaigns are named individually on the billing panel and the printed
  receipt, so a shopper who came in for an advertised offer can see it applied.

Editor
- Full CRUD, admin-only, with validation for the cases that would save happily
  and then silently never fire — a targeted campaign with no target, a
  percentage over 100, an end date before the start.

Tests: 199 -> 210. Covers each campaign type, the eligibility conditions, the
stacking rules, the impossible-to-go-negative guarantee, GST recomputation
against the reduced total, round-tripping, and the double-count guard.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Suriya
2026-08-01 13:36:50 +05:30
parent fdd90f28d9
commit 46d354ced1
18 changed files with 2239 additions and 199 deletions

View File

@@ -5,6 +5,7 @@ import 'package:sqflite/sqflite.dart';
import '../../domain/entities/cart.dart';
import '../../domain/entities/customer.dart';
import '../../domain/entities/product.dart';
import '../../domain/entities/promo.dart';
import '../../domain/entities/transaction.dart';
import 'app_database.dart';
import 'catalogue_dao.dart';
@@ -92,6 +93,17 @@ class OrderDao {
'subtotal': cart.subtotal,
'line_discount': cart.lineDiscountTotal,
'bill_discount': cart.billDiscountTotal,
'promos_json': cart.appliedPromos.isEmpty
? null
: jsonEncode([
for (final applied in cart.appliedPromos)
{
'id': applied.promo.id,
'name': applied.promo.name,
'type': applied.promo.type.name,
'amount': applied.amount,
},
]),
'loyalty_value': cart.loyaltyRedemptionValue,
'taxable_amount': cart.taxableAmount,
'tax_amount': cart.taxAmount,
@@ -438,6 +450,36 @@ class OrderDao {
await _db.delete(Tables.parkedBills, where: 'id = ?', whereArgs: [id]);
}
/// Rebuilds the campaigns recorded against a bill.
///
/// The stored rows carry the promo's name and amount rather than a live
/// lookup, so a campaign that has since been edited or deleted still prints
/// on a reissued receipt exactly as it was given.
static List<AppliedPromo> _promosFromRow(String? json) {
if (json == null || json.isEmpty) return const [];
try {
return (jsonDecode(json) as List)
.cast<Map<String, Object?>>()
.map((p) => AppliedPromo(
promo: Promo(
id: (p['id'] as String?) ?? '',
name: (p['name'] as String?) ?? 'Promotion',
type: PromoType.values
.where((t) => t.name == p['type'])
.firstOrNull ??
PromoType.flatOffBill,
),
amount: (p['amount'] as num?)?.toDouble() ?? 0,
),)
.toList();
} on Object {
// A bill that cannot name its campaigns is still a valid bill; the total
// is on the row itself and does not depend on this.
return const [];
}
}
// -------------------------------------------------------------- Internals
Future<List<SaleTransaction>> _query({
String? where,
@@ -530,19 +572,28 @@ class OrderDao {
// payload, the day archive, the shift report — is overstated.
final billDiscount = (o['bill_discount']! as num).toDouble();
// Campaigns are restored so a reprinted receipt still names what the
// shopper was given. Their amounts are then *subtracted* from the manual
// discount, because `bill_discount` already contains them — restoring both
// at full value would discount the bill twice on the way back in.
final promos = _promosFromRow(o['promos_json'] as String?);
final promoTotal = promos.fold<double>(0, (sum, p) => sum + p.amount);
final manualDiscount = (billDiscount - promoTotal).clamp(0, billDiscount);
return SaleTransaction(
id: o['id']! as String,
invoiceNumber: o['invoice_number']! as String,
cart: Cart(
lines: lines,
customer: customer,
billDiscount: billDiscount > 0
billDiscount: manualDiscount > 0
? Discount(
type: DiscountType.flat,
value: billDiscount,
value: manualDiscount.toDouble(),
reason: 'Bill discount',
)
: Discount.none,
appliedPromos: promos,
pointsRedeemed: (o['points_redeemed'] as int?) ?? 0,
),
payments: payments,