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:
464
lib/presentation/modules/widgets/promo_editor_dialog.dart
Normal file
464
lib/presentation/modules/widgets/promo_editor_dialog.dart
Normal 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),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user