Files
nearle_pos/lib/domain/services/promo_engine.dart
Suriya fe428931ec Upload shopper registrations, and charge GST to the lines that earned it
Two defects that share a shape: a figure landing on the wrong record.

Bill-level discounts were apportioned across every line by a single
factor, so "20% off Beverages" pulled tax out of the atta line as well.
The bill total was right either way, which is what made it easy to ship
— only the slab split on a filed return was wrong. Targeted campaigns
now reduce the lines they name, and bill-wide reductions still spread
pro rata, so the arithmetic is unchanged wherever it was already right.

Shoppers registered at a till only ever reached the back office as three
fields riding along on a bill. Somebody who signed up and bought nothing
existed on one terminal and nowhere else, and two tills registering the
same mobile each minted their own row. Customers are now an outbox of
their own on pos/{store}/{terminal}/customer, and the id is a UUIDv5
over the normalised mobile number — so a hundred terminals agree on who
a shopper is without talking to each other.

Registrations go up before bills, and a failure there cannot strand a
day's takings. No loyalty figures are sent: they belong to the bill
stream, which is idempotent and knows about every counter.

Two things found while building it. Numbers were keyed on raw digits, so
a cashier typing +91 forked a shopper as effectively as a random id
would. And the sale path wrote the customer with ConflictAlgorithm
.replace, which is a DELETE and an INSERT — every column absent from the
row reverts to its schema default, so the new sync flag would have been
cleared by the shopper's next purchase.

Schema v8. Existing customers are queued rather than assumed sent: the
terminal cannot tell an imported row from a locally registered one, and
only one of those mistakes loses somebody.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 11:34:27 +05:30

144 lines
5.2 KiB
Dart

import '../../core/utils/extensions.dart';
import '../entities/cart.dart';
import '../entities/promo.dart';
/// Decides which campaigns fire on a bill, and for how much.
///
/// Kept out of [Cart] on purpose. Cart owns arithmetic that must never be
/// wrong; this owns policy that a shop changes weekly. Mixing them would put a
/// marketing decision in the same class as the GST calculation.
class PromoEngine {
const PromoEngine._();
/// Evaluates [promos] against [cart] and returns what actually fires.
///
/// ### Stacking
///
/// All eligible **stackable** promos apply together. Of the **exclusive**
/// ones, only the single best applies — the one worth most to the shopper,
/// with [Promo.priority] breaking ties.
///
/// This is the conservative reading, and deliberately so. Letting two
/// percentages compound produces a discount nobody costed, and a shop finds
/// out at the end of the month rather than at the till.
///
/// The total is capped at the cart subtotal: no combination of campaigns can
/// make a bill negative, or turn a sale into a payout.
static List<AppliedPromo> evaluate({
required Cart cart,
required List<Promo> promos,
required DateTime at,
}) {
if (cart.isEmpty || promos.isEmpty) return const [];
final subtotal = cart.subtotal;
final eligible = <AppliedPromo>[];
for (final promo in promos) {
if (!promo.isLiveAt(at)) continue;
if (subtotal < promo.minBillValue) continue;
final amount = amountFor(promo: promo, cart: cart);
if (amount <= 0) continue;
eligible.add(AppliedPromo(promo: promo, amount: amount));
}
if (eligible.isEmpty) return const [];
final stackable = eligible.where((a) => a.promo.stackable).toList()
..sort((a, b) => a.promo.priority.compareTo(b.promo.priority));
final exclusive = eligible.where((a) => !a.promo.stackable).toList()
..sort((a, b) {
// Best for the shopper first; priority only breaks a genuine tie.
final byAmount = b.amount.compareTo(a.amount);
if (byAmount != 0) return byAmount;
return a.promo.priority.compareTo(b.promo.priority);
});
final chosen = <AppliedPromo>[
...stackable,
if (exclusive.isNotEmpty) exclusive.first,
]..sort((a, b) => a.promo.priority.compareTo(b.promo.priority));
return _capped(chosen, subtotal);
}
/// Trims the applied set so it can never exceed the bill.
///
/// Trimming the last one rather than scaling all of them keeps every other
/// figure on the receipt exactly what the campaign promised.
static List<AppliedPromo> _capped(List<AppliedPromo> applied, double ceiling) {
final result = <AppliedPromo>[];
var running = 0.0;
for (final entry in applied) {
final headroom = (ceiling - running).asMoney;
if (headroom <= 0) break;
final amount = entry.amount <= headroom ? entry.amount : headroom;
result.add(AppliedPromo(promo: entry.promo, amount: amount));
running = (running + amount).asMoney;
}
return result;
}
/// What one promo is worth on this cart, ignoring stacking rules.
static double amountFor({required Promo promo, required Cart cart}) {
final raw = switch (promo.type) {
PromoType.percentOffBill => cart.subtotal * (promo.value / 100),
PromoType.flatOffBill => promo.value,
// Both delegate the "does this line count?" question to the promo
// itself, because [Cart] asks the same question when it decides which
// lines carry the GST reduction. Answering it twice invites the two to
// drift apart.
PromoType.percentOffCategory =>
_percentOfMatching(cart, promo.value, promo),
PromoType.percentOffProduct =>
_percentOfMatching(cart, promo.value, promo),
PromoType.buyXGetY => _buyXGetY(cart, promo),
};
final capped = promo.maxDiscount == null
? raw
: (raw < promo.maxDiscount! ? raw : promo.maxDiscount!);
return capped.clamp(0, cart.subtotal).toDouble().asMoney;
}
static double _percentOfMatching(Cart cart, double percent, Promo promo) {
final base = cart.lines
.where((line) => promo.targets(line.product))
.fold(0.0, (sum, line) => sum + line.payable);
return base * (percent / 100);
}
/// Free units are the cheapest way to price this: for every group of
/// (buy + free), the shopper pays for `buy` of them.
///
/// Deliberately counts whole groups only. A "buy 2 get 1" on three items
/// gives one free; on five it still gives one, because the fifth has not
/// earned the second group.
static double _buyXGetY(Cart cart, Promo promo) {
if (promo.buyQuantity <= 0 || promo.freeQuantity <= 0) return 0;
final line = cart.lines.firstWhereOrNull(
(l) => l.product.id == promo.targetId,
);
if (line == null) return 0;
final groupSize = promo.buyQuantity + promo.freeQuantity;
final groups = line.quantity ~/ groupSize;
if (groups <= 0) return 0;
// Priced at the unit rate actually being charged, so a line that already
// carries a manual discount does not refund more than it took.
final unitPrice =
line.quantity <= 0 ? 0.0 : line.payable / line.quantity;
return groups * promo.freeQuantity * unitPrice;
}
}