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:
@@ -9,9 +9,11 @@ import '../../../core/services/sound_service.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 '../../../domain/repositories/product_repository.dart';
|
||||
import '../../../domain/repositories/transaction_repository.dart';
|
||||
import '../../../domain/services/promo_engine.dart';
|
||||
|
||||
/// Transient feedback for the scan toast — never a blocking dialog.
|
||||
enum ScanOutcome { added, incremented, notFound, outOfStock }
|
||||
@@ -43,9 +45,13 @@ class CartController extends StateNotifier<Cart> {
|
||||
required TransactionRepository transactions,
|
||||
required SoundService sound,
|
||||
required this.onFeedback,
|
||||
List<Promo> promos = const [],
|
||||
DateTime Function()? clock,
|
||||
}) : _products = products,
|
||||
_transactions = transactions,
|
||||
_sound = sound,
|
||||
_promos = promos,
|
||||
_now = clock ?? DateTime.now,
|
||||
super(Cart.empty);
|
||||
|
||||
final ProductRepository _products;
|
||||
@@ -53,8 +59,29 @@ class CartController extends StateNotifier<Cart> {
|
||||
final SoundService _sound;
|
||||
final void Function(ScanFeedback) onFeedback;
|
||||
|
||||
/// Campaigns live right now. Re-evaluated after every change to the bill,
|
||||
/// because whether one fires depends on what is in it.
|
||||
final List<Promo> _promos;
|
||||
final DateTime Function() _now;
|
||||
|
||||
static const _uuid = Uuid();
|
||||
|
||||
/// Applies the campaign rules to [next] and stores the result.
|
||||
///
|
||||
/// Every mutation goes through here rather than assigning `state` directly,
|
||||
/// so a promo cannot be left applied after the line that earned it is
|
||||
/// removed — which is how a shopper gets a discount for an item they put
|
||||
/// back.
|
||||
void _commit(Cart next) {
|
||||
state = next.copyWith(
|
||||
appliedPromos: PromoEngine.evaluate(
|
||||
cart: next,
|
||||
promos: _promos,
|
||||
at: _now(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Snapshots for undo — capped so memory can't grow unbounded on a terminal
|
||||
/// that runs for days.
|
||||
final List<Cart> _undoStack = [];
|
||||
@@ -105,18 +132,18 @@ class CartController extends StateNotifier<Cart> {
|
||||
}
|
||||
|
||||
if (existing == null) {
|
||||
state = state.copyWith(lines: [
|
||||
_commit(state.copyWith(lines: [
|
||||
...state.lines,
|
||||
CartLine(
|
||||
product: product,
|
||||
quantity: quantity,
|
||||
addedAt: DateTime.now(),
|
||||
),
|
||||
],);
|
||||
],),);
|
||||
} else {
|
||||
state = state.copyWith(
|
||||
_commit(state.copyWith(
|
||||
lines: _replace(existing.copyWith(quantity: requested)),
|
||||
);
|
||||
),);
|
||||
}
|
||||
|
||||
_clampRedemption();
|
||||
@@ -171,7 +198,7 @@ class CartController extends StateNotifier<Cart> {
|
||||
}
|
||||
|
||||
_push();
|
||||
state = state.copyWith(lines: _replace(line.copyWith(quantity: capped)));
|
||||
_commit(state.copyWith(lines: _replace(line.copyWith(quantity: capped))));
|
||||
_clampRedemption();
|
||||
}
|
||||
|
||||
@@ -190,9 +217,9 @@ class CartController extends StateNotifier<Cart> {
|
||||
void removeLine(String productId) {
|
||||
if (!state.contains(productId)) return;
|
||||
_push();
|
||||
state = state.copyWith(
|
||||
_commit(state.copyWith(
|
||||
lines: state.lines.where((l) => l.product.id != productId).toList(),
|
||||
);
|
||||
),);
|
||||
_clampRedemption();
|
||||
}
|
||||
|
||||
@@ -200,14 +227,14 @@ class CartController extends StateNotifier<Cart> {
|
||||
final line = state.lineFor(productId);
|
||||
if (line == null) return;
|
||||
_push();
|
||||
state = state.copyWith(lines: _replace(line.copyWith(discount: discount)));
|
||||
_commit(state.copyWith(lines: _replace(line.copyWith(discount: discount))));
|
||||
_clampRedemption();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ Bill level
|
||||
void applyBillDiscount(Discount discount) {
|
||||
_push();
|
||||
state = state.copyWith(billDiscount: discount);
|
||||
_commit(state.copyWith(billDiscount: discount));
|
||||
_clampRedemption();
|
||||
}
|
||||
|
||||
@@ -215,9 +242,11 @@ class CartController extends StateNotifier<Cart> {
|
||||
|
||||
void attachCustomer(Customer? customer) {
|
||||
_push();
|
||||
state = customer == null
|
||||
? state.copyWith(clearCustomer: true, pointsRedeemed: 0)
|
||||
: state.copyWith(customer: customer);
|
||||
_commit(
|
||||
customer == null
|
||||
? state.copyWith(clearCustomer: true, pointsRedeemed: 0)
|
||||
: state.copyWith(customer: customer),
|
||||
);
|
||||
_clampRedemption();
|
||||
}
|
||||
|
||||
@@ -275,7 +304,9 @@ class CartController extends StateNotifier<Cart> {
|
||||
Future<void> resume(ParkedBill bill) async {
|
||||
await _transactions.removeParked(bill.id);
|
||||
_undoStack.clear();
|
||||
state = bill.cart;
|
||||
// Re-evaluated rather than restored: a campaign that has since ended must
|
||||
// not be honoured just because the bill was parked while it was running.
|
||||
_commit(bill.cart);
|
||||
}
|
||||
|
||||
List<CartLine> _replace(CartLine updated) => [
|
||||
@@ -293,6 +324,10 @@ final cartControllerProvider =
|
||||
products: ref.watch(productRepositoryProvider),
|
||||
transactions: ref.watch(transactionRepositoryProvider),
|
||||
sound: ref.watch(soundServiceProvider),
|
||||
// Watched, so editing a campaign in Settings takes effect at the till
|
||||
// without a restart. An empty list until they load is correct — no promo
|
||||
// is safer than a stale one.
|
||||
promos: ref.watch(activePromosProvider).value ?? const [],
|
||||
onFeedback: (feedback) =>
|
||||
ref.read(scanFeedbackProvider.notifier).state = feedback,
|
||||
);
|
||||
|
||||
@@ -242,6 +242,17 @@ class _Summary extends ConsumerWidget {
|
||||
valueColor: AppColors.success,
|
||||
),
|
||||
|
||||
// Named individually rather than lumped into one "Promotions" line:
|
||||
// a shopper who came in for a specific offer needs to see it applied,
|
||||
// and a cashier being asked "did the weekend deal come off?" needs to
|
||||
// answer without opening a report.
|
||||
for (final applied in cart.appliedPromos)
|
||||
_Row(
|
||||
label: applied.promo.name,
|
||||
value: '-${Formatters.money(applied.amount)}',
|
||||
valueColor: AppColors.success,
|
||||
),
|
||||
|
||||
_Row(
|
||||
label: 'GST',
|
||||
value: Formatters.money(cart.taxAmount),
|
||||
|
||||
Reference in New Issue
Block a user