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>
This commit is contained in:
@@ -177,13 +177,113 @@ class Cart extends Equatable {
|
||||
return v.clamp(0, double.infinity).toDouble().asMoney;
|
||||
}
|
||||
|
||||
/// Proportion of the bill remaining after bill-level reductions. Used to
|
||||
/// spread those reductions fairly across lines when apportioning GST.
|
||||
double get _billFactor => subtotal <= 0 ? 1 : netAmount / subtotal;
|
||||
/// Bill-level reductions, allocated to the lines that earned them.
|
||||
///
|
||||
/// Returns one figure per line, in [lines] order, summing to exactly
|
||||
/// `subtotal - netAmount`.
|
||||
///
|
||||
/// This exists because GST is charged per line at that line's own slab, so
|
||||
/// *which* line a discount lands on changes the tax. A bill-wide reduction —
|
||||
/// a tier discount, a manual markdown, points redeemed — genuinely belongs to
|
||||
/// every line, and spreading it pro rata is right. A campaign that names a
|
||||
/// category or a product does not: taking "20% off Beverages" out of the
|
||||
/// atta line as well understates the 18% slab and overstates the 5% one. The
|
||||
/// bill total is identical either way, which is exactly why the error is easy
|
||||
/// to ship — it only shows up in the slab split on a filed return.
|
||||
List<double> get _lineReductions {
|
||||
final result = List<double>.filled(lines.length, 0);
|
||||
if (lines.isEmpty) return result;
|
||||
|
||||
// What the shopper actually saved at bill level, after the clamps in
|
||||
// [billDiscountTotal] and [netAmount] have had their say.
|
||||
final ceiling = (subtotal - netAmount).asMoney;
|
||||
if (ceiling <= 0) return result;
|
||||
|
||||
void spread(double amount, bool Function(CartLine) targets) {
|
||||
if (amount <= 0) return;
|
||||
|
||||
final matched = <int>[];
|
||||
var base = 0.0;
|
||||
for (var i = 0; i < lines.length; i++) {
|
||||
if (!targets(lines[i])) continue;
|
||||
matched.add(i);
|
||||
base += lines[i].payable;
|
||||
}
|
||||
if (base <= 0) return;
|
||||
|
||||
for (final i in matched) {
|
||||
result[i] += amount * (lines[i].payable / base);
|
||||
}
|
||||
}
|
||||
|
||||
for (final applied in appliedPromos) {
|
||||
spread(applied.amount, (l) => applied.promo.targets(l.product));
|
||||
}
|
||||
spread(membershipDiscountAmount, (_) => true);
|
||||
spread(manualBillDiscountAmount, (_) => true);
|
||||
spread(loyaltyRedemptionValue, (_) => true);
|
||||
|
||||
return _fitToCeiling(result, ceiling);
|
||||
}
|
||||
|
||||
/// Scales [raw] so it sums to [ceiling], with no line reduced below zero.
|
||||
///
|
||||
/// The components arrive individually clamped and then clamped again as a
|
||||
/// group, so their raw sum is only approximately what came off the bill.
|
||||
/// Scaling reconciles the two. Capping is a separate pass because a targeted
|
||||
/// campaign can take a line to zero on its own, and the tier discount layered
|
||||
/// on top would otherwise push it negative — which would show up as a
|
||||
/// *credit* in that line's GST slab.
|
||||
List<double> _fitToCeiling(List<double> raw, double ceiling) {
|
||||
final out = List<double>.filled(raw.length, 0);
|
||||
final open = [for (var i = 0; i < raw.length; i++) i];
|
||||
var pool = ceiling;
|
||||
|
||||
// Loops because capping one line hands its excess back to the pool, which
|
||||
// can in turn push another line past its own value.
|
||||
while (open.isNotEmpty && pool > 0) {
|
||||
final weight = open.fold(0.0, (sum, i) => sum + raw[i]);
|
||||
if (weight <= 0) break;
|
||||
|
||||
final capped = open
|
||||
.where((i) => pool * (raw[i] / weight) >= lines[i].payable)
|
||||
.toList();
|
||||
|
||||
if (capped.isEmpty) {
|
||||
for (final i in open) {
|
||||
out[i] = pool * (raw[i] / weight);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
for (final i in capped) {
|
||||
out[i] = lines[i].payable;
|
||||
pool -= lines[i].payable;
|
||||
open.remove(i);
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/// What each line is worth after its share of the bill-level reductions.
|
||||
List<double> get _lineNetAmounts {
|
||||
final reductions = _lineReductions;
|
||||
return [
|
||||
for (var i = 0; i < lines.length; i++)
|
||||
(lines[i].payable - reductions[i]).clamp(0, double.infinity).toDouble(),
|
||||
];
|
||||
}
|
||||
|
||||
/// GST payable across the bill, after apportioning bill-level discounts.
|
||||
double get taxAmount =>
|
||||
lines.fold(0.0, (sum, l) => sum + l.taxAmount * _billFactor).asMoney;
|
||||
double get taxAmount {
|
||||
final nets = _lineNetAmounts;
|
||||
var total = 0.0;
|
||||
for (var i = 0; i < lines.length; i++) {
|
||||
total += nets[i] - nets[i] / (1 + lines[i].product.gstRate);
|
||||
}
|
||||
return total.asMoney;
|
||||
}
|
||||
|
||||
double get cgst => (taxAmount / 2).asMoney;
|
||||
double get sgst => (taxAmount / 2).asMoney;
|
||||
@@ -198,10 +298,11 @@ class Cart extends Equatable {
|
||||
/// side of the total printed on the same bill, which a tax invoice cannot
|
||||
/// show; the residue is absorbed by the largest slab.
|
||||
Map<double, double> get taxBreakdown {
|
||||
final nets = _lineNetAmounts;
|
||||
final raw = <double, double>{};
|
||||
for (final line in lines) {
|
||||
final rate = line.product.gstRate;
|
||||
raw[rate] = (raw[rate] ?? 0) + line.taxAmount * _billFactor;
|
||||
for (var i = 0; i < lines.length; i++) {
|
||||
final rate = lines[i].product.gstRate;
|
||||
raw[rate] = (raw[rate] ?? 0) + (nets[i] - nets[i] / (1 + rate));
|
||||
}
|
||||
if (raw.isEmpty) return const {};
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../../core/constants/app_constants.dart';
|
||||
import '../../core/utils/extensions.dart';
|
||||
@@ -74,6 +75,51 @@ class Customer extends Equatable {
|
||||
final DateTime? createdAt;
|
||||
final DateTime? lastVisitAt;
|
||||
|
||||
/// Fixed namespace for customer ids. Must never change: it is half the
|
||||
/// input to [idForMobile], so a new one renames every shopper in the fleet.
|
||||
static const _namespace = '9f2b7c14-3d6e-5a80-b1f7-2c4e8a05d913';
|
||||
|
||||
static const _uuid = Uuid();
|
||||
|
||||
/// The id for the shopper reachable on [mobile].
|
||||
///
|
||||
/// Derived from the number rather than minted at random, which is what lets
|
||||
/// a hundred terminals agree without talking to each other. A shopper who
|
||||
/// registers at counter 2 in Anna Nagar and shops at counter 5 in T Nagar
|
||||
/// gets the same id both times, so the back office collapses them on a
|
||||
/// primary key instead of guessing at a merge later.
|
||||
static String idForMobile(String mobile) =>
|
||||
_uuid.v5(_namespace, normaliseMobile(mobile));
|
||||
|
||||
/// Every digit in [mobile], in order. Used for matching what a cashier types
|
||||
/// against what is stored, where a partial number should still find a row.
|
||||
static String digitsOf(String mobile) => mobile.replaceAll(RegExp(r'\D'), '');
|
||||
|
||||
/// Reduces a number to the ten-digit national one identity is keyed on.
|
||||
///
|
||||
/// One cashier types `+91 98400 12345`, another `098400 12345`, a third
|
||||
/// `9840012345`. Keyed on raw digits those are three different shoppers,
|
||||
/// which is precisely the duplication [idForMobile] exists to prevent — the
|
||||
/// country code would fork a customer just as effectively as a random id.
|
||||
///
|
||||
/// Only the two prefixes an Indian number actually carries are stripped, and
|
||||
/// only at the exact lengths that make them unambiguous. Anything else is
|
||||
/// left alone: mangling a number this rule was not written for is worse than
|
||||
/// storing it verbatim.
|
||||
static String normaliseMobile(String mobile) {
|
||||
final digits = digitsOf(mobile);
|
||||
|
||||
// +91 98400 12345
|
||||
if (digits.length == 12 && digits.startsWith('91')) {
|
||||
return digits.substring(2);
|
||||
}
|
||||
// 0 98400 12345 — the old STD trunk prefix, still muscle memory for many.
|
||||
if (digits.length == 11 && digits.startsWith('0')) {
|
||||
return digits.substring(1);
|
||||
}
|
||||
return digits;
|
||||
}
|
||||
|
||||
MembershipTier get tier => MembershipTier.forSpend(lifetimeSpend);
|
||||
|
||||
/// Cash value of the points currently held.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
import '../../core/constants/app_constants.dart';
|
||||
import 'product.dart';
|
||||
|
||||
/// What a promo does to a bill.
|
||||
enum PromoType {
|
||||
@@ -115,6 +116,28 @@ class Promo extends Equatable {
|
||||
static DateTime _endOfDay(DateTime day) =>
|
||||
DateTime(day.year, day.month, day.day, 23, 59, 59, 999);
|
||||
|
||||
/// Whether this campaign is aimed at [product] in particular.
|
||||
///
|
||||
/// A bill-wide promo targets everything; a category or product one targets
|
||||
/// only what it names. Two things read this and they must never disagree:
|
||||
/// `PromoEngine` uses it to price the discount, and [Cart] uses it to decide
|
||||
/// which lines carry the GST reduction. A campaign priced against one set of
|
||||
/// lines and taxed against another puts the wrong figure in a slab on a
|
||||
/// filed return, so the rule lives here once rather than in both callers.
|
||||
bool targets(Product product) => switch (type) {
|
||||
PromoType.percentOffBill || PromoType.flatOffBill => true,
|
||||
|
||||
// Matched on the enum name, which is stable across a label change —
|
||||
// renaming "Personal Care" must not silently switch off a campaign.
|
||||
PromoType.percentOffCategory => product.category.name == targetId,
|
||||
|
||||
PromoType.percentOffProduct || PromoType.buyXGetY =>
|
||||
product.id == targetId,
|
||||
};
|
||||
|
||||
/// Whether the discount lands on named lines rather than the whole bill.
|
||||
bool get isTargeted => type.needsTarget;
|
||||
|
||||
/// One-line description for the campaign list.
|
||||
String get summary => switch (type) {
|
||||
PromoType.percentOffBill => '${_trim(value)}% off the whole bill',
|
||||
|
||||
@@ -90,6 +90,17 @@ abstract class SyncRepository {
|
||||
void Function(double progress, String stage)? onProgress,
|
||||
});
|
||||
|
||||
/// How many shoppers registered at this till are still waiting to go up.
|
||||
Future<int> unsyncedCustomerCount();
|
||||
|
||||
/// Uploads shoppers registered at this till.
|
||||
///
|
||||
/// Deliberately separate from [syncOrders]. A registration is not a financial
|
||||
/// record: it can be replayed safely, and it must not be stuck behind a bill
|
||||
/// the back office has refused. Run it first so a bill referring to a new
|
||||
/// shopper arrives after the shopper does.
|
||||
Future<SyncOutcome> syncCustomers();
|
||||
|
||||
/// Retires confirmed bills past their retention window. Archived totals are
|
||||
/// untouched.
|
||||
Future<int> purgeExpired();
|
||||
|
||||
@@ -90,18 +90,14 @@ class PromoEngine {
|
||||
final raw = switch (promo.type) {
|
||||
PromoType.percentOffBill => cart.subtotal * (promo.value / 100),
|
||||
PromoType.flatOffBill => promo.value,
|
||||
PromoType.percentOffCategory => _percentOfMatching(
|
||||
cart,
|
||||
promo.value,
|
||||
// Stored by enum name, which is stable across a label change —
|
||||
// renaming "Personal Care" must not silently switch off a campaign.
|
||||
(line) => line.product.category.name == promo.targetId,
|
||||
),
|
||||
PromoType.percentOffProduct => _percentOfMatching(
|
||||
cart,
|
||||
promo.value,
|
||||
(line) => line.product.id == promo.targetId,
|
||||
),
|
||||
// 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),
|
||||
};
|
||||
|
||||
@@ -112,13 +108,9 @@ class PromoEngine {
|
||||
return capped.clamp(0, cart.subtotal).toDouble().asMoney;
|
||||
}
|
||||
|
||||
static double _percentOfMatching(
|
||||
Cart cart,
|
||||
double percent,
|
||||
bool Function(CartLine) matches,
|
||||
) {
|
||||
static double _percentOfMatching(Cart cart, double percent, Promo promo) {
|
||||
final base = cart.lines
|
||||
.where(matches)
|
||||
.where((line) => promo.targets(line.product))
|
||||
.fold(0.0, (sum, line) => sum + line.payable);
|
||||
return base * (percent / 100);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user