Pull the catalogue from a real endpoint, with delta sync

Replaces the last simulation on the inbound side. RemoteCatalogueSource
returned SeedData after a fake progress bar; there was no wire format, no
endpoint, and no way to receive an update short of reinstalling.

Wire format (data/remote/catalogue_wire.dart)
- Tolerant where it should be: a catalogue of 4,000 products must not fail to
  import over one absent emoji, so optional fields take defaults and an
  unrecognised category files under Grocery — the item still scans, prices and
  bills.
- Strict where it matters: no id, name, barcode or price and the import fails.
  A silently dropped product is a shelf item that scans to nothing, discovered
  with a queue waiting.
- GST accepts 18 or 0.18 and reads both the same. Back offices disagree about
  which they mean, and getting it wrong silently changes the tax on every line.

HTTP source with paging and deltas
- GET {base}/catalogue?since={revision}&page={n}. Paged because a supermarket
  catalogue is tens of thousands of rows: one response times out on a shop's
  line and stalls the UI decoding it. Capped at 200 pages so a bad deployment
  cannot become an infinite request loop against a shop's connection.
- `since` carries the revision already held, so a normal morning fetches a
  handful of price changes rather than the whole book. A server that cannot do
  deltas ignores it and answers is_delta:false — the terminal reads the flag
  rather than assuming, so both work.
- A bad credential is non-retryable and says so, leaving the working catalogue
  in place so billing continues.

Applying deltas without losing local state
- A full snapshot withdraws what it omits; a delta must not. Read as a
  snapshot, the first morning price change would empty the shelf.
- Retired products are marked inactive, not deleted — order lines already
  recorded point at them, and a hard delete would orphan a bill's history.
- Locally registered shoppers survive a pull, as before.
- The unsynced-stock replay is now scoped to the products the pull actually
  overwrote. It exists because a server count predates local sales; running it
  over a delta that never carried that product would subtract those units a
  second time and quietly empty a shelf that is full. Both halves of that rule
  are tested.

MQTT stays the nudge, not the transport: a catalogue push on
pos/{store}/catalogue makes every terminal pull immediately, but the rows come
over HTTP, because a broker is the wrong shape for tens of thousands of them.

Tests: 210 -> 234. docs/sync-contract.md now covers both directions, including
a field-by-field table of what happens when something is missing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Suriya
2026-08-01 15:37:42 +05:30
parent 46d354ced1
commit fbfc02d140
13 changed files with 1259 additions and 111 deletions

View File

@@ -149,13 +149,41 @@ class LocalStore {
required List<Customer> customers,
required String revision,
required DateTime at,
bool isDelta = false,
List<String> retiredProductIds = const [],
}) async {
await catalogue.replaceCatalogue(products: products, customers: customers);
if (isDelta) {
// A change set must not withdraw what it does not mention. Applied as a
// full snapshot, the first morning price change would empty the shelf.
await catalogue.applyCatalogueDelta(
products: products,
customers: customers,
retiredProductIds: retiredProductIds,
);
} else {
await catalogue.replaceCatalogue(
products: products,
customers: customers,
);
}
// The server's stock figure predates any sale this terminal has made but
// not yet uploaded, so those units would reappear on the shelf. Replay them
// before anyone can bill against the inflated count.
final committed = await orders.unsyncedStockCommitments();
//
// Scoped to the products the pull actually overwrote. A full snapshot
// rewrites every row, so the replay covers everything; a delta rewrites
// only what it carried, and replaying the rest would subtract those units a
// second time from a count that was never reset — quietly emptying a shelf
// that is full.
var committed = await orders.unsyncedStockCommitments();
if (isDelta) {
final touched = products.map((p) => p.id).toSet();
committed = {
for (final entry in committed.entries)
if (touched.contains(entry.key)) entry.key: entry.value,
};
}
if (committed.isNotEmpty) {
await catalogue.decrementStock(committed);
}

View File

@@ -1,86 +0,0 @@
import '../../domain/entities/customer.dart';
import '../../domain/entities/product.dart';
import 'local_store.dart';
import 'seed_data.dart';
/// What one catalogue pull returns.
class CatalogueSnapshot {
const CatalogueSnapshot({
required this.products,
required this.customers,
required this.fetchedAt,
required this.revision,
});
final List<Product> products;
final List<Customer> customers;
final DateTime fetchedAt;
/// Server-side catalogue version, shown so the cashier can tell whether a
/// re-import actually changed anything.
final String revision;
}
/// Raised when the catalogue cannot be pulled.
class CatalogueSyncException implements Exception {
const CatalogueSyncException(this.message);
final String message;
@override
String toString() => message;
}
/// Stands in for the back-office catalogue API.
///
/// The real implementation would issue an HTTP request; the contract is the
/// same, so only this class changes.
class RemoteCatalogueSource {
RemoteCatalogueSource({required this.isOffline}) {
LocalStore.registerSeed(
products: SeedData.products,
customers: SeedData.customers,
);
}
/// Reads the Settings switch on every call.
///
/// Deliberately a callback rather than a stored bool: a copied flag can fall
/// out of step with the switch, which makes the terminal behave as offline
/// while showing that it is not.
final bool Function() isOffline;
/// Streams progress so the import screen can show a real bar rather than an
/// indeterminate spinner.
Future<CatalogueSnapshot> fetch({
void Function(double progress, String stage)? onProgress,
}) async {
const stages = [
(0.15, 'Contacting server…'),
(0.35, 'Authorising terminal…'),
(0.60, 'Downloading products…'),
(0.85, 'Downloading customers…'),
(1.00, 'Writing to local storage…'),
];
for (final (progress, stage) in stages) {
await Future<void>.delayed(const Duration(milliseconds: 320));
if (isOffline()) {
throw const CatalogueSyncException(
'Simulate offline is ON in Settings, so the catalogue pull was '
'failed on purpose. Turn it off to import.',
);
}
onProgress?.call(progress, stage);
}
return CatalogueSnapshot(
products: SeedData.products(),
customers: SeedData.customers(),
fetchedAt: DateTime.now(),
revision: 'rev-${DateTime.now().millisecondsSinceEpoch % 100000}',
);
}
}