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

@@ -1,202 +1,304 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/utils/formatters.dart';
import '../../../domain/entities/promo.dart';
import '../../../domain/entities/store_account.dart';
import '../../auth/providers/auth_controller.dart';
import '../../../core/widgets/empty_state.dart';
import '../widgets/module_widgets.dart';
import '../widgets/promo_editor_dialog.dart';
/// Discount rules and campaigns.
class PromosView extends StatefulWidget {
///
/// This was a mockup: three hardcoded rows with a toggle that changed nothing,
/// and no promo code anywhere in the domain or data layers. A cashier looking
/// at it would reasonably conclude promotions were running. They were not.
class PromosView extends ConsumerWidget {
const PromosView({super.key});
@override
State<PromosView> createState() => _PromosViewState();
}
Widget build(BuildContext context, WidgetRef ref) {
final promosAsync = ref.watch(promosProvider);
final isAdmin = ref.watch(currentUserProvider)?.role == StaffRole.admin;
class _PromosViewState extends State<PromosView> {
final Set<String> _enabled = {'WEEKEND10', 'DAIRY5', 'FESTIVE'};
static const _campaigns = [
(
'WEEKEND10',
'Weekend Saver',
'10% off bills above ₹500',
'SatSun',
412,
AppColors.primary,
),
(
'DAIRY5',
'Dairy Days',
'5% off all dairy products',
'Ends 31 Aug',
286,
AppColors.info,
),
(
'FESTIVE',
'Festive Bonus',
'Double loyalty points',
'Ends 15 Sep',
178,
AppColors.tierGold,
),
(
'NEWCUST',
'First Purchase',
'₹50 off the first bill',
'Always on',
94,
AppColors.success,
),
];
@override
Widget build(BuildContext context) {
return ModulePage(
children: [
Wrap(
spacing: AppSpacing.lg,
runSpacing: AppSpacing.lg,
children: [
StatTile(
label: 'Active Campaigns',
value: '${_enabled.length}',
icon: Icons.campaign_rounded,
caption: 'of ${_campaigns.length} configured',
),
const StatTile(
label: 'Redemptions',
value: '970',
icon: Icons.confirmation_number_rounded,
color: AppColors.info,
caption: 'this month',
),
const StatTile(
label: 'Discount Given',
value: '₹48,240',
icon: Icons.local_offer_rounded,
color: AppColors.warning,
caption: '2.6% of sales',
),
const StatTile(
label: 'Incremental Sales',
value: '₹2.14L',
icon: Icons.trending_up_rounded,
color: AppColors.success,
delta: '+18%',
caption: 'attributed',
),
],
),
const SizedBox(height: AppSpacing.lg),
PanelCard(
title: 'Campaigns',
subtitle: 'Toggle a rule to apply it at the till immediately',
action: FilledButton.icon(
onPressed: () {},
icon: const Icon(Icons.add_rounded, size: 18),
label: const Text('New campaign'),
style: FilledButton.styleFrom(
backgroundColor: AppColors.primary,
minimumSize: const Size(0, 40),
),
promosAsync.when(
loading: () => const Padding(
padding: EdgeInsets.all(AppSpacing.xxl),
child: Center(child: CircularProgressIndicator()),
),
child: Column(
mainAxisSize: MainAxisSize.min,
error: (e, _) => Text('Could not load campaigns: $e'),
data: (promos) => Column(
children: [
for (final c in _campaigns)
Container(
margin: const EdgeInsets.only(bottom: AppSpacing.sm),
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: AppColors.surfaceAlt,
borderRadius: AppRadius.brMd,
border: Border.all(color: AppColors.border),
),
// Wrap prevents collision when the panel is narrow.
child: Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: AppSpacing.md,
runSpacing: AppSpacing.sm,
children: [
SizedBox(
width: 320,
child: Row(
children: [
Container(
width: 38,
height: 38,
decoration: BoxDecoration(
color: c.$6.withValues(alpha: 0.12),
borderRadius: AppRadius.brSm,
),
child: Icon(Icons.sell_rounded,
size: 18, color: c.$6,),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
c.$2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
Text(
c.$3,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12.5,
color: AppColors.textSecondary,
),
),
],
),
),
],
),
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
TagChip(c.$1, color: c.$6),
const SizedBox(width: AppSpacing.sm),
TagChip(c.$4, color: AppColors.textSecondary),
const SizedBox(width: AppSpacing.sm),
Text(
'${c.$5} used',
style: const TextStyle(
fontSize: 12,
color: AppColors.textTertiary,
),
),
const SizedBox(width: AppSpacing.sm),
Switch(
value: _enabled.contains(c.$1),
onChanged: (v) => setState(() {
if (v) {
_enabled.add(c.$1);
} else {
_enabled.remove(c.$1);
}
}),
),
],
),
],
),
),
_summary(promos),
const SizedBox(height: AppSpacing.lg),
_campaignList(context, ref, promos, isAdmin: isAdmin),
],
),
),
],
);
}
Widget _summary(List<Promo> promos) {
final live = promos.where((p) => p.isLiveAt(DateTime.now())).length;
final scheduled = promos
.where((p) =>
p.isActive &&
p.validFrom != null &&
p.validFrom!.isAfter(DateTime.now()),)
.length;
return Row(
children: [
Expanded(
child: StatTile(
label: 'Running now',
value: '$live',
icon: Icons.play_circle_outline_rounded,
color: AppColors.success,
),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: StatTile(
label: 'Scheduled',
value: '$scheduled',
icon: Icons.schedule_rounded,
color: AppColors.info,
),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: StatTile(
label: 'Paused',
value: '${promos.where((p) => !p.isActive).length}',
icon: Icons.pause_circle_outline_rounded,
color: AppColors.textTertiary,
),
),
],
);
}
Widget _campaignList(
BuildContext context,
WidgetRef ref,
List<Promo> promos, {
required bool isAdmin,
}) {
return PanelCard(
title: 'Campaigns',
subtitle: promos.isEmpty
? 'Nothing running. Add a campaign and the till applies it '
'automatically.'
: 'Applied automatically at the till, in priority order',
action: isAdmin
? FilledButton.icon(
onPressed: () => showPromoEditor(context),
icon: const Icon(Icons.add_rounded, size: 18),
label: const Text('New campaign'),
style: FilledButton.styleFrom(
backgroundColor: AppColors.primary,
minimumSize: const Size(0, 40),
),
)
: null,
child: promos.isEmpty
? const EmptyState(
title: 'No campaigns yet',
message: 'A campaign here is applied to every bill that '
'qualifies, without the cashier doing anything.',
emoji: '🏷️',
compact: true,
)
: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final promo in promos)
_PromoRow(promo: promo, isAdmin: isAdmin),
],
),
);
}
}
class _PromoRow extends ConsumerWidget {
const _PromoRow({required this.promo, required this.isAdmin});
final Promo promo;
final bool isAdmin;
@override
Widget build(BuildContext context, WidgetRef ref) {
final live = promo.isLiveAt(DateTime.now());
return Container(
margin: const EdgeInsets.only(bottom: AppSpacing.sm),
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: AppColors.surfaceAlt,
borderRadius: AppRadius.brMd,
border: Border.all(color: AppColors.border),
),
// Wrap prevents collision when the panel is narrow.
child: Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: AppSpacing.md,
runSpacing: AppSpacing.sm,
children: [
SizedBox(
width: 360,
child: Row(
children: [
Container(
width: 38,
height: 38,
decoration: BoxDecoration(
color: (live ? AppColors.success : AppColors.textTertiary)
.withValues(alpha: 0.12),
borderRadius: AppRadius.brSm,
),
child: Icon(
Icons.sell_rounded,
size: 18,
color: live ? AppColors.success : AppColors.textTertiary,
),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
promo.name,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontWeight: FontWeight.w700),
),
Text(
promo.summary,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12.5,
color: AppColors.textSecondary,
),
),
],
),
),
],
),
),
Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: AppSpacing.sm,
children: [
if (promo.stackable)
const TagChip('Stacks', color: AppColors.info),
// The distinction a shop actually needs: switched on, but out of
// its date range or wrong day, is not the same as switched off.
if (promo.isActive && !live)
const TagChip('Not today', color: AppColors.warning),
Text(
_window(promo),
style: const TextStyle(
fontSize: 12,
color: AppColors.textTertiary,
),
),
if (isAdmin) ...[
Switch(
value: promo.isActive,
onChanged: (v) async {
await ref
.read(localStoreProvider)
.promos
.setActive(promo.id, active: v);
ref
..invalidate(promosProvider)
..invalidate(activePromosProvider);
},
),
IconButton(
tooltip: 'Edit',
icon: const Icon(Icons.edit_outlined, size: 17),
onPressed: () => showPromoEditor(context, existing: promo),
),
IconButton(
tooltip: 'Delete',
icon: const Icon(Icons.delete_outline_rounded, size: 17),
color: AppColors.danger,
onPressed: () => _confirmDelete(context, ref),
),
],
],
),
],
),
);
}
String _window(Promo promo) {
final from = promo.validFrom;
final to = promo.validTo;
if (from == null && to == null) {
return promo.daysOfWeek.isEmpty ? 'Always' : _days(promo.daysOfWeek);
}
final range = [
if (from != null) 'from ${Formatters.date(from)}',
if (to != null) 'to ${Formatters.date(to)}',
].join(' ');
return promo.daysOfWeek.isEmpty
? range
: '$range · ${_days(promo.daysOfWeek)}';
}
static String _days(Set<int> days) {
const names = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
final sorted = days.toList()..sort();
return sorted.map((d) => names[d - 1]).join(', ');
}
Future<void> _confirmDelete(BuildContext context, WidgetRef ref) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text('Delete "${promo.name}"?'),
content: const Text(
'Bills already rung keep the discount they were given — a bill '
'stores the amount, not a link to the campaign. Only future sales '
'are affected.',
),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
style: TextButton.styleFrom(foregroundColor: AppColors.danger),
child: const Text('Delete'),
),
],
),
);
if (confirmed != true) return;
await ref.read(localStoreProvider).promos.delete(promo.id);
ref
..invalidate(promosProvider)
..invalidate(activePromosProvider);
}
}

View File

@@ -0,0 +1,464 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/widgets/primary_button.dart';
import '../../../data/local/promo_dao.dart';
import '../../../domain/entities/product.dart';
import '../../../domain/entities/promo.dart';
import '../../pos/providers/catalog_providers.dart';
/// Creates or edits a campaign.
Future<void> showPromoEditor(BuildContext context, {Promo? existing}) =>
showDialog<void>(
context: context,
builder: (_) => _PromoEditor(existing: existing),
);
class _PromoEditor extends ConsumerStatefulWidget {
const _PromoEditor({this.existing});
final Promo? existing;
@override
ConsumerState<_PromoEditor> createState() => _PromoEditorState();
}
class _PromoEditorState extends ConsumerState<_PromoEditor> {
final _formKey = GlobalKey<FormState>();
late final TextEditingController _name;
late final TextEditingController _value;
late final TextEditingController _minBill;
late final TextEditingController _maxDiscount;
late final TextEditingController _buy;
late final TextEditingController _free;
late PromoType _type;
String? _targetId;
String? _targetLabel;
DateTime? _from;
DateTime? _to;
late Set<int> _days;
late bool _stackable;
bool _saving = false;
String? _error;
bool get _isNew => widget.existing == null;
@override
void initState() {
super.initState();
final p = widget.existing;
_name = TextEditingController(text: p?.name ?? '');
_value = TextEditingController(text: p == null ? '' : _num(p.value));
_minBill = TextEditingController(
text: (p == null || p.minBillValue == 0) ? '' : _num(p.minBillValue),
);
_maxDiscount = TextEditingController(
text: p?.maxDiscount == null ? '' : _num(p!.maxDiscount!),
);
_buy = TextEditingController(text: '${p?.buyQuantity ?? 2}');
_free = TextEditingController(text: '${p?.freeQuantity ?? 1}');
_type = p?.type ?? PromoType.percentOffBill;
_targetId = p?.targetId;
_targetLabel = p?.targetLabel;
_from = p?.validFrom;
_to = p?.validTo;
_days = {...?p?.daysOfWeek};
_stackable = p?.stackable ?? false;
}
static String _num(double v) =>
v == v.roundToDouble() ? v.toStringAsFixed(0) : v.toStringAsFixed(2);
@override
void dispose() {
for (final c in [_name, _value, _minBill, _maxDiscount, _buy, _free]) {
c.dispose();
}
super.dispose();
}
Future<void> _save() async {
if (!(_formKey.currentState?.validate() ?? false)) return;
if (_type.needsTarget && (_targetId ?? '').isEmpty) {
setState(() => _error = 'Choose what this campaign applies to.');
return;
}
setState(() {
_saving = true;
_error = null;
});
final promo = Promo(
id: widget.existing?.id ?? '',
name: _name.text,
type: _type,
value: double.tryParse(_value.text.trim()) ?? 0,
targetId: _targetId,
targetLabel: _targetLabel,
buyQuantity: int.tryParse(_buy.text.trim()) ?? 0,
freeQuantity: int.tryParse(_free.text.trim()) ?? 0,
minBillValue: double.tryParse(_minBill.text.trim()) ?? 0,
maxDiscount: double.tryParse(_maxDiscount.text.trim()),
validFrom: _from,
validTo: _to,
daysOfWeek: _days,
stackable: _stackable,
priority: widget.existing?.priority ?? 100,
isActive: widget.existing?.isActive ?? true,
);
try {
await ref.read(localStoreProvider).promos.save(promo);
ref
..invalidate(promosProvider)
..invalidate(activePromosProvider);
if (mounted) Navigator.of(context).pop();
} on PromoException catch (e) {
setState(() {
_saving = false;
_error = e.message;
});
}
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(_isNew ? 'New campaign' : 'Edit campaign'),
content: SizedBox(
width: 540,
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextFormField(
controller: _name,
autofocus: true,
decoration: const InputDecoration(
labelText: 'Campaign name',
hintText: 'Weekend Saver',
helperText: 'Shown on the bill when it applies',
),
validator: (v) => (v == null || v.trim().isEmpty)
? 'A campaign needs a name'
: null,
),
const SizedBox(height: AppSpacing.md),
DropdownButtonFormField<PromoType>(
initialValue: _type,
isExpanded: true,
decoration: const InputDecoration(labelText: 'What it does'),
items: [
for (final type in PromoType.values)
DropdownMenuItem(
value: type,
child: Text(type.label, overflow: TextOverflow.ellipsis),
),
],
onChanged: (v) => setState(() {
_type = v ?? _type;
// The old target is meaningless under a different type — a
// category id on a product promo would silently never fire.
_targetId = null;
_targetLabel = null;
}),
),
const SizedBox(height: AppSpacing.md),
if (_type.needsTarget) ...[
_targetField(),
const SizedBox(height: AppSpacing.md),
],
if (_type == PromoType.buyXGetY)
_buyGetFields()
else
_valueField(),
const SizedBox(height: AppSpacing.md),
Row(
children: [
Expanded(
child: TextFormField(
controller: _minBill,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Minimum bill',
hintText: '0',
prefixText: '',
isDense: true,
),
),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: TextFormField(
controller: _maxDiscount,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Cap the discount',
hintText: 'No cap',
prefixText: '',
isDense: true,
),
),
),
],
),
if (_type.isPercentage)
const Padding(
padding: EdgeInsets.only(top: AppSpacing.xs),
child: Text(
'A cap is worth setting on a percentage: without one, an '
'unusually large trolley gives away more than the '
'campaign was costed for.',
style: TextStyle(
fontSize: 11.5,
color: AppColors.textTertiary,
height: 1.4,
),
),
),
const SizedBox(height: AppSpacing.lg),
_dateRange(),
const SizedBox(height: AppSpacing.md),
_dayPicker(),
const SizedBox(height: AppSpacing.sm),
SwitchListTile(
contentPadding: EdgeInsets.zero,
value: _stackable,
onChanged: (v) => setState(() => _stackable = v),
title: const Text('Can combine with other campaigns'),
subtitle: const Text(
'Off by default. Only the best non-combining campaign '
'applies to a bill — two percentages compounding produce a '
'discount nobody costed.',
style: TextStyle(fontSize: 11.5, height: 1.4),
),
),
if (_error != null) ...[
const SizedBox(height: AppSpacing.md),
Text(
_error!,
style: const TextStyle(
color: AppColors.danger,
fontSize: 12.5,
),
),
],
],
),
),
),
),
actions: [
TextButton(
onPressed: _saving ? null : () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
PrimaryButton(
label: _isNew ? 'Create' : 'Save',
expanded: false,
busy: _saving,
onPressed: _save,
),
],
);
}
Widget _valueField() => TextFormField(
controller: _value,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: _type.isPercentage ? 'Percentage off' : 'Amount off',
suffixText: _type.isPercentage ? '%' : null,
prefixText: _type.isPercentage ? null : '',
),
validator: (v) {
final parsed = double.tryParse((v ?? '').trim());
if (parsed == null || parsed <= 0) {
return 'A campaign must give something away';
}
if (_type.isPercentage && parsed > 100) {
// Over 100% is a refund with extra steps.
return 'A percentage cannot exceed 100';
}
return null;
},
);
Widget _buyGetFields() => Row(
children: [
Expanded(
child: TextFormField(
controller: _buy,
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
decoration: const InputDecoration(labelText: 'Buy', isDense: true),
validator: (v) => (int.tryParse(v ?? '') ?? 0) < 1
? 'At least one'
: null,
),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: TextFormField(
controller: _free,
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
decoration:
const InputDecoration(labelText: 'Get free', isDense: true),
validator: (v) => (int.tryParse(v ?? '') ?? 0) < 1
? 'At least one'
: null,
),
),
],
);
Widget _targetField() {
if (_type == PromoType.percentOffCategory) {
return DropdownButtonFormField<String>(
initialValue: _targetId,
isExpanded: true,
decoration: const InputDecoration(labelText: 'Category'),
items: [
for (final category in ProductCategory.values)
DropdownMenuItem(
value: category.name,
child: Text('${category.emoji} ${category.label}'),
),
],
onChanged: (v) => setState(() {
_targetId = v;
_targetLabel = ProductCategory.values
.where((c) => c.name == v)
.map((c) => c.label)
.firstOrNull;
}),
);
}
// Product picker, for both the product promo and buy-X-get-Y.
final products = ref.watch(allProductsProvider).value ?? const <Product>[];
return DropdownButtonFormField<String>(
initialValue:
products.any((p) => p.id == _targetId) ? _targetId : null,
isExpanded: true,
decoration: InputDecoration(
labelText: 'Product',
helperText: products.isEmpty
? 'Import the catalogue first — there is nothing to pick'
: null,
),
items: [
for (final product in products)
DropdownMenuItem(
value: product.id,
child: Text(product.name, overflow: TextOverflow.ellipsis),
),
],
onChanged: (v) => setState(() {
_targetId = v;
_targetLabel =
products.where((p) => p.id == v).map((p) => p.name).firstOrNull;
}),
);
}
Widget _dateRange() => Row(
children: [
Expanded(child: _dateButton('Starts', _from, (d) => _from = d)),
const SizedBox(width: AppSpacing.md),
Expanded(child: _dateButton('Ends', _to, (d) => _to = d)),
],
);
Widget _dateButton(String label, DateTime? value, void Function(DateTime?) set) {
return OutlinedButton(
onPressed: () async {
final picked = await showDatePicker(
context: context,
initialDate: value ?? DateTime.now(),
firstDate: DateTime(2024),
lastDate: DateTime(2100),
);
if (picked != null) setState(() => set(picked));
},
onLongPress: () => setState(() => set(null)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: const TextStyle(
fontSize: 11,
color: AppColors.textTertiary,
),
),
Text(
value == null
? 'Any time'
: '${value.day}/${value.month}/${value.year}',
style: const TextStyle(fontWeight: FontWeight.w600),
),
],
),
);
}
Widget _dayPicker() {
const names = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Days it runs',
style: TextStyle(fontSize: 12, color: AppColors.textSecondary),
),
const SizedBox(height: AppSpacing.xs),
Wrap(
spacing: AppSpacing.xs,
children: [
for (var day = 1; day <= 7; day++)
FilterChip(
label: Text(names[day - 1]),
selected: _days.contains(day),
onSelected: (on) => setState(() {
on ? _days.add(day) : _days.remove(day);
}),
),
],
),
const Padding(
padding: EdgeInsets.only(top: AppSpacing.xs),
child: Text(
'Pick none to run every day.',
style: TextStyle(fontSize: 11.5, color: AppColors.textTertiary),
),
),
],
);
}
}

View File

@@ -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,
);

View File

@@ -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),