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:
@@ -1,5 +1,3 @@
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../../core/utils/extensions.dart';
|
||||
import '../../domain/entities/customer.dart';
|
||||
import '../../domain/repositories/customer_repository.dart';
|
||||
@@ -9,15 +7,15 @@ class CustomerRepositoryImpl implements CustomerRepository {
|
||||
CustomerRepositoryImpl(this._store);
|
||||
|
||||
final LocalStore _store;
|
||||
static const _uuid = Uuid();
|
||||
|
||||
String _digits(String v) => v.replaceAll(RegExp(r'\D'), '');
|
||||
|
||||
@override
|
||||
Future<Customer?> findByMobile(String mobile) async {
|
||||
final needle = _digits(mobile);
|
||||
return _store.customers
|
||||
.firstWhereOrNull((c) => _digits(c.mobile) == needle);
|
||||
// Normalised on both sides, so a shopper stored from `9840012345` is still
|
||||
// found when a cashier at the next till types `+91 98400 12345`.
|
||||
final needle = Customer.normaliseMobile(mobile);
|
||||
return _store.customers.firstWhereOrNull(
|
||||
(c) => Customer.normaliseMobile(c.mobile) == needle,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -30,9 +28,14 @@ class CustomerRepositoryImpl implements CustomerRepository {
|
||||
throw StateError('A customer with this mobile number already exists.');
|
||||
}
|
||||
final created = Customer(
|
||||
id: _uuid.v4(),
|
||||
// Derived from the number, not random — see [Customer.idForMobile].
|
||||
// Two tills registering the same shopper independently produce the same
|
||||
// row rather than a duplicate the back office has to reconcile.
|
||||
id: Customer.idForMobile(customer.mobile),
|
||||
name: customer.name.trim(),
|
||||
mobile: _digits(customer.mobile),
|
||||
// Stored normalised, so the unique index on `mobile` actually catches a
|
||||
// second attempt to register the same shopper.
|
||||
mobile: Customer.normaliseMobile(customer.mobile),
|
||||
email: customer.email?.trim().isEmpty ?? true
|
||||
? null
|
||||
: customer.email!.trim(),
|
||||
@@ -60,11 +63,15 @@ class CustomerRepositoryImpl implements CustomerRepository {
|
||||
|
||||
// Stored numbers are digits only, so the query has to be reduced the same
|
||||
// way — otherwise a cashier typing "98765 43210" or "98-76" matches nothing.
|
||||
final digits = _digits(q);
|
||||
//
|
||||
// Raw digits rather than the normalised form on purpose: this is a partial
|
||||
// match on whatever has been typed so far, and a half-entered number is not
|
||||
// a number to be normalised.
|
||||
final digits = Customer.digitsOf(q);
|
||||
|
||||
return _store.customers.where((c) {
|
||||
if (c.name.toLowerCase().contains(q)) return true;
|
||||
return digits.isNotEmpty && _digits(c.mobile).contains(digits);
|
||||
return digits.isNotEmpty && Customer.digitsOf(c.mobile).contains(digits);
|
||||
}).toList();
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'dart:convert';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../../core/utils/formatters.dart';
|
||||
import '../../domain/entities/customer.dart';
|
||||
import '../../domain/entities/shift_report.dart';
|
||||
import '../../domain/entities/sync_event.dart';
|
||||
import '../../domain/entities/transaction.dart';
|
||||
@@ -333,6 +334,109 @@ class SyncRepositoryImpl implements SyncRepository {
|
||||
DateTime.now().subtract(OrderDao.retentionWindow),
|
||||
);
|
||||
|
||||
// ------------------------------------------------- Registrations: uplink
|
||||
@override
|
||||
Future<int> unsyncedCustomerCount() =>
|
||||
_store.catalogue.unsyncedCustomerCount();
|
||||
|
||||
@override
|
||||
Future<SyncOutcome> syncCustomers() async {
|
||||
final started = DateTime.now();
|
||||
var attempted = 0;
|
||||
var uploaded = 0;
|
||||
|
||||
while (true) {
|
||||
final batch = await _store.catalogue.unsyncedCustomers(limit: batchSize);
|
||||
if (batch.isEmpty) break;
|
||||
|
||||
attempted += batch.length;
|
||||
|
||||
PushReceipt receipt;
|
||||
try {
|
||||
receipt = await _transport.pushCustomers(
|
||||
batch.map(_customerToPayload).toList(),
|
||||
);
|
||||
} on Object catch (e) {
|
||||
// Nothing is marked sent when the outcome is unknown. Unlike a bill,
|
||||
// a registration is safe to send twice, so this simply waits for the
|
||||
// next pass rather than needing a per-row attempt counter.
|
||||
if (attempted > batch.length || uploaded > 0) {
|
||||
await _store.refreshUnsyncedCustomerCount();
|
||||
}
|
||||
return SyncOutcome(
|
||||
attempted: attempted,
|
||||
uploaded: uploaded,
|
||||
error: e.toString(),
|
||||
isRetryable: e is! TransportException || e.retryable,
|
||||
);
|
||||
}
|
||||
|
||||
final acceptedIds = receipt.accepted.toSet();
|
||||
await _store.catalogue.markCustomersSynced(acceptedIds.toList());
|
||||
uploaded += acceptedIds.length;
|
||||
|
||||
// Nothing moved, so the next page would hand back the same rows for
|
||||
// ever. Stop and let the events log show why.
|
||||
if (acceptedIds.isEmpty) {
|
||||
final reasons = receipt.rejected.values.toSet().join('; ');
|
||||
await _log(SyncEvent(
|
||||
id: _uuid.v4(),
|
||||
type: SyncEventType.catalogueImport,
|
||||
status: SyncStatus.failed,
|
||||
createdAt: started,
|
||||
summary: '${batch.length} registrations were not accepted',
|
||||
error:
|
||||
reasons.isEmpty ? 'Not confirmed by the back office' : reasons,
|
||||
attempts: 1,
|
||||
),);
|
||||
await _store.refreshUnsyncedCustomerCount();
|
||||
return SyncOutcome(
|
||||
attempted: attempted,
|
||||
uploaded: uploaded,
|
||||
rejected: batch.length,
|
||||
error: 'No registration in this batch was accepted'
|
||||
'${reasons.isEmpty ? '' : ': $reasons'}',
|
||||
isRetryable: false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await _store.refreshUnsyncedCustomerCount();
|
||||
|
||||
if (uploaded > 0) {
|
||||
await _log(SyncEvent(
|
||||
id: _uuid.v4(),
|
||||
type: SyncEventType.catalogueImport,
|
||||
status: SyncStatus.synced,
|
||||
createdAt: started,
|
||||
syncedAt: DateTime.now(),
|
||||
summary: '$uploaded shopper registrations uploaded '
|
||||
'via ${_transport.label}',
|
||||
attempts: 1,
|
||||
),);
|
||||
}
|
||||
|
||||
return SyncOutcome(attempted: attempted, uploaded: uploaded);
|
||||
}
|
||||
|
||||
/// The JSON body sent per registration.
|
||||
///
|
||||
/// Identity and profile only. Points, spend and visit counts are deliberately
|
||||
/// left out: they are derived from the bill stream, which is authoritative and
|
||||
/// idempotent. Uploading a terminal's local balance would make the last till
|
||||
/// to sync win, and a shopper who bought something at two counters on the same
|
||||
/// day would end up with whichever figure arrived second.
|
||||
Map<String, Object?> _customerToPayload(Customer c) => {
|
||||
'id': c.id,
|
||||
'mobile': c.mobile,
|
||||
'name': c.name,
|
||||
'email': c.email,
|
||||
'gender': c.gender.name,
|
||||
'date_of_birth': c.dateOfBirth?.toIso8601String(),
|
||||
'registered_at': c.createdAt?.toIso8601String(),
|
||||
'registered_by_terminal': _store.terminal.code,
|
||||
};
|
||||
|
||||
/// The JSON body sent per order.
|
||||
Map<String, Object?> _orderToPayload(SaleTransaction t) => {
|
||||
'id': t.id,
|
||||
|
||||
Reference in New Issue
Block a user