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:
@@ -4,6 +4,7 @@ import '../../domain/entities/sync_event.dart';
|
||||
import '../local/app_database.dart';
|
||||
import '../local/catalogue_dao.dart';
|
||||
import '../local/order_dao.dart';
|
||||
import '../local/promo_dao.dart';
|
||||
import '../local/staff_dao.dart';
|
||||
import '../local/sync_config_store.dart';
|
||||
import '../local/sync_log_dao.dart';
|
||||
@@ -24,6 +25,7 @@ class LocalStore {
|
||||
late OrderDao orders;
|
||||
late SyncLogDao syncLog;
|
||||
late StaffDao staff;
|
||||
late PromoDao promos;
|
||||
late SyncConfigStore syncConfig;
|
||||
late TerminalIdentityStore identityStore;
|
||||
|
||||
@@ -54,6 +56,7 @@ class LocalStore {
|
||||
orders = OrderDao(AppDatabase.instance.db);
|
||||
syncLog = SyncLogDao(AppDatabase.instance.db);
|
||||
staff = StaffDao(AppDatabase.instance.db);
|
||||
promos = PromoDao(AppDatabase.instance.db);
|
||||
syncConfig = SyncConfigStore(catalogue);
|
||||
identityStore = TerminalIdentityStore(catalogue);
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ class AppDatabase {
|
||||
static final AppDatabase instance = AppDatabase._();
|
||||
|
||||
static const String _fileName = 'nearle_pos.db';
|
||||
static const int _version = 5;
|
||||
static const int _version = 7;
|
||||
|
||||
Database? _db;
|
||||
|
||||
@@ -71,6 +71,12 @@ class AppDatabase {
|
||||
}
|
||||
if (from < 4) await _upgradeToV4(db, from: from);
|
||||
if (from < 5) await db.execute(_createStaff);
|
||||
if (from < 6) await db.execute(_createPromos);
|
||||
if (from < 7) {
|
||||
await db.execute(
|
||||
'ALTER TABLE ${Tables.orders} ADD COLUMN promos_json TEXT',
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -131,6 +137,7 @@ class AppDatabase {
|
||||
Tables.parkedBills,
|
||||
Tables.syncLog,
|
||||
Tables.staff,
|
||||
Tables.promos,
|
||||
Tables.meta,
|
||||
]) {
|
||||
batch.delete(t);
|
||||
@@ -211,6 +218,10 @@ class AppDatabase {
|
||||
points_earned INTEGER NOT NULL DEFAULT 0,
|
||||
points_redeemed INTEGER NOT NULL DEFAULT 0,
|
||||
payments_json TEXT NOT NULL,
|
||||
-- Which campaigns fired, and for how much. Stored as amounts rather
|
||||
-- than ids: a bill read back next year must show what was actually
|
||||
-- given, not what today's rules would give.
|
||||
promos_json TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'completed',
|
||||
|
||||
-- 0 = held on this terminal, 1 = accepted by the server
|
||||
@@ -268,6 +279,7 @@ class AppDatabase {
|
||||
// ------------------------------------------------------------- archive
|
||||
await db.execute(_createDayArchive);
|
||||
await db.execute(_createStaff);
|
||||
await db.execute(_createPromos);
|
||||
|
||||
// ----------------------------------------------------------------- meta
|
||||
await db.execute('''
|
||||
@@ -351,6 +363,34 @@ const String _createStaff = '''
|
||||
)
|
||||
''';
|
||||
|
||||
/// Campaigns the till applies automatically.
|
||||
///
|
||||
/// Kept local like everything else: a shop mid-promotion with a dead line still
|
||||
/// has to honour the price on the shelf edge.
|
||||
const String _createPromos = '''
|
||||
CREATE TABLE promos (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
value REAL NOT NULL DEFAULT 0,
|
||||
target_id TEXT,
|
||||
target_label TEXT,
|
||||
buy_quantity INTEGER NOT NULL DEFAULT 0,
|
||||
free_quantity INTEGER NOT NULL DEFAULT 0,
|
||||
min_bill_value REAL NOT NULL DEFAULT 0,
|
||||
max_discount REAL,
|
||||
valid_from INTEGER,
|
||||
valid_to INTEGER,
|
||||
-- Comma-separated DateTime.weekday values. Empty means every day.
|
||||
days_of_week TEXT NOT NULL DEFAULT '',
|
||||
stackable INTEGER NOT NULL DEFAULT 0,
|
||||
priority INTEGER NOT NULL DEFAULT 100,
|
||||
is_active INTEGER NOT NULL DEFAULT 1,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
''';
|
||||
|
||||
const String _createDayArchive = '''
|
||||
CREATE TABLE day_archive (
|
||||
business_date TEXT NOT NULL,
|
||||
@@ -383,6 +423,7 @@ class Tables {
|
||||
static const String parkedBills = 'parked_bills';
|
||||
static const String syncLog = 'sync_log';
|
||||
static const String staff = 'staff';
|
||||
static const String promos = 'promos';
|
||||
static const String meta = 'app_meta';
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
185
lib/data/local/promo_dao.dart
Normal file
185
lib/data/local/promo_dao.dart
Normal file
@@ -0,0 +1,185 @@
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../../domain/entities/promo.dart';
|
||||
import 'app_database.dart';
|
||||
|
||||
/// Raised when a campaign would be saved in a state the till cannot apply.
|
||||
class PromoException implements Exception {
|
||||
const PromoException(this.message);
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// Stores campaigns on the terminal.
|
||||
///
|
||||
/// Local like everything else the till needs: a shop mid-promotion with a dead
|
||||
/// line still has to honour the price on the shelf edge.
|
||||
class PromoDao {
|
||||
const PromoDao(this._db);
|
||||
|
||||
final Database _db;
|
||||
|
||||
static const _uuid = Uuid();
|
||||
|
||||
Future<List<Promo>> all({bool activeOnly = false}) async {
|
||||
final rows = await _db.query(
|
||||
Tables.promos,
|
||||
where: activeOnly ? 'is_active = 1' : null,
|
||||
orderBy: 'priority ASC, created_at ASC',
|
||||
);
|
||||
return rows.map(_fromRow).toList();
|
||||
}
|
||||
|
||||
Future<Promo?> findById(String id) async {
|
||||
final rows = await _db.query(
|
||||
Tables.promos,
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
limit: 1,
|
||||
);
|
||||
return rows.isEmpty ? null : _fromRow(rows.first);
|
||||
}
|
||||
|
||||
/// Inserts or updates. Returns the stored campaign, with its id.
|
||||
Future<Promo> save(Promo promo) async {
|
||||
_validate(promo);
|
||||
|
||||
final id = promo.id.isEmpty ? _uuid.v4() : promo.id;
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
final existing = await findById(id);
|
||||
|
||||
await _db.insert(
|
||||
Tables.promos,
|
||||
{
|
||||
'id': id,
|
||||
'name': promo.name.trim(),
|
||||
'type': promo.type.name,
|
||||
'value': promo.value,
|
||||
'target_id': promo.targetId,
|
||||
'target_label': promo.targetLabel,
|
||||
'buy_quantity': promo.buyQuantity,
|
||||
'free_quantity': promo.freeQuantity,
|
||||
'min_bill_value': promo.minBillValue,
|
||||
'max_discount': promo.maxDiscount,
|
||||
'valid_from': promo.validFrom?.millisecondsSinceEpoch,
|
||||
'valid_to': promo.validTo?.millisecondsSinceEpoch,
|
||||
'days_of_week': (promo.daysOfWeek.toList()..sort()).join(','),
|
||||
'stackable': promo.stackable ? 1 : 0,
|
||||
'priority': promo.priority,
|
||||
'is_active': promo.isActive ? 1 : 0,
|
||||
// Preserved on update so the list keeps a stable order.
|
||||
'created_at': existing == null ? now : await _createdAt(id) ?? now,
|
||||
'updated_at': now,
|
||||
},
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
|
||||
// Read back rather than echoing the input, so the caller gets exactly what
|
||||
// the database holds — including the id minted for a new campaign.
|
||||
return (await findById(id))!;
|
||||
}
|
||||
|
||||
Future<int?> _createdAt(String id) async {
|
||||
final rows = await _db.query(
|
||||
Tables.promos,
|
||||
columns: ['created_at'],
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
limit: 1,
|
||||
);
|
||||
return rows.isEmpty ? null : rows.first['created_at'] as int?;
|
||||
}
|
||||
|
||||
Future<void> setActive(String id, {required bool active}) async {
|
||||
await _db.update(
|
||||
Tables.promos,
|
||||
{
|
||||
'is_active': active ? 1 : 0,
|
||||
'updated_at': DateTime.now().millisecondsSinceEpoch,
|
||||
},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
}
|
||||
|
||||
/// Hard delete. Unlike staff, nothing already recorded points at a promo row
|
||||
/// — a bill stores the amount it was given, not a reference to the campaign,
|
||||
/// so deleting one cannot change a past total.
|
||||
Future<void> delete(String id) async {
|
||||
await _db.delete(Tables.promos, where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- Internals
|
||||
static void _validate(Promo promo) {
|
||||
if (promo.name.trim().isEmpty) {
|
||||
throw const PromoException('A campaign needs a name.');
|
||||
}
|
||||
|
||||
if (promo.type.needsTarget &&
|
||||
(promo.targetId == null || promo.targetId!.isEmpty)) {
|
||||
throw const PromoException(
|
||||
'This campaign needs a product or category to apply to.',
|
||||
);
|
||||
}
|
||||
|
||||
if (promo.type == PromoType.buyXGetY) {
|
||||
if (promo.buyQuantity < 1 || promo.freeQuantity < 1) {
|
||||
throw const PromoException(
|
||||
'Buy and free quantities must both be at least one.',
|
||||
);
|
||||
}
|
||||
} else if (promo.value <= 0) {
|
||||
throw const PromoException('A campaign must give something away.');
|
||||
}
|
||||
|
||||
if (promo.type.isPercentage && promo.value > 100) {
|
||||
// Over 100% is a refund with extra steps.
|
||||
throw const PromoException('A percentage cannot exceed 100.');
|
||||
}
|
||||
|
||||
final from = promo.validFrom;
|
||||
final to = promo.validTo;
|
||||
if (from != null && to != null && to.isBefore(from)) {
|
||||
throw const PromoException('The end date is before the start date.');
|
||||
}
|
||||
|
||||
if (promo.daysOfWeek.any((d) => d < 1 || d > 7)) {
|
||||
throw const PromoException('Days of the week must be 1 (Mon) to 7 (Sun).');
|
||||
}
|
||||
}
|
||||
|
||||
static Promo _fromRow(Map<String, Object?> row) {
|
||||
final days = (row['days_of_week'] as String? ?? '')
|
||||
.split(',')
|
||||
.where((s) => s.isNotEmpty)
|
||||
.map(int.parse)
|
||||
.toSet();
|
||||
|
||||
return Promo(
|
||||
id: row['id']! as String,
|
||||
name: row['name']! as String,
|
||||
type: PromoType.values.byName(row['type']! as String),
|
||||
value: (row['value'] as num? ?? 0).toDouble(),
|
||||
targetId: row['target_id'] as String?,
|
||||
targetLabel: row['target_label'] as String?,
|
||||
buyQuantity: (row['buy_quantity'] as int?) ?? 0,
|
||||
freeQuantity: (row['free_quantity'] as int?) ?? 0,
|
||||
minBillValue: (row['min_bill_value'] as num? ?? 0).toDouble(),
|
||||
maxDiscount: (row['max_discount'] as num?)?.toDouble(),
|
||||
validFrom: row['valid_from'] == null
|
||||
? null
|
||||
: DateTime.fromMillisecondsSinceEpoch(row['valid_from']! as int),
|
||||
validTo: row['valid_to'] == null
|
||||
? null
|
||||
: DateTime.fromMillisecondsSinceEpoch(row['valid_to']! as int),
|
||||
daysOfWeek: days,
|
||||
stackable: (row['stackable'] as int? ?? 0) == 1,
|
||||
priority: (row['priority'] as int?) ?? 100,
|
||||
isActive: (row['is_active'] as int? ?? 1) == 1,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -333,6 +333,15 @@ class SyncRepositoryImpl implements SyncRepository {
|
||||
},
|
||||
'subtotal': t.cart.subtotal,
|
||||
'discount': t.cart.billDiscountTotal + t.cart.lineDiscountTotal,
|
||||
'promos': [
|
||||
for (final applied in t.cart.appliedPromos)
|
||||
{
|
||||
'id': applied.promo.id,
|
||||
'name': applied.promo.name,
|
||||
'type': applied.promo.type.name,
|
||||
'amount': applied.amount,
|
||||
},
|
||||
],
|
||||
'tax': t.cart.taxAmount,
|
||||
'round_off': t.cart.roundOff,
|
||||
'total': t.total,
|
||||
|
||||
Reference in New Issue
Block a user