Files
nearle_pos/lib/presentation/sync/widgets/sign_out_dialog.dart
Suriya af3933092f Fix billing data integrity, sale atomicity and stock safety
Bills were persisted correctly but read back wrong. The read path rebuilt a
cart from its lines alone, dropping bill-level discounts and loyalty, so every
figure derived from a stored bill was overstated: the upload payload, the day
archive and the shift report. A discounted 529 bill read back as 620.

Money and data integrity
- order_dao: restore bill_discount and points_redeemed when rebuilding a cart;
  keep the reconstruction tier-less so the membership discount is not applied
  twice. Trust the recorded total and points via SaleTransaction.storedTotal.
- checkout_sale + order_dao.commitSale: write the bill, its stock movement and
  the loyalty update in one transaction. Previously a failure part-way through
  left a persisted bill the cashier believed had failed, inviting a duplicate.
- checkout_sale: re-check every line against live stock. A parked bill resumed
  after its stock was sold passed validation and oversold.
- catalogue_dao: allocate the invoice sequence in one transaction; the previous
  read-modify-write could hand two sales the same number and fail UNIQUE.
- local_store: replay unsynced sales after a catalogue import, so a mid-shift
  re-import cannot restore stock that has already been sold.
- payment_controller: stamp the signed-in operator on the bill instead of the
  hardcoded seed session, and pass the terminal id through.
- cart: reconcile per-slab GST against the bill total so the parts sum to the
  whole on a tax invoice.

Sync and reporting
- sync_repository: drain unsynced bills in a loop rather than silently capping
  at one page; stop on rejection so rejected rows cannot loop forever.
- sync_log_dao (new): persist the sync history to the sync_log table, which the
  schema already defined but nothing used. It was in memory, so the only record
  that bills had been uploaded died at restart.
- Scope shift reports by cashier. day_archive is re-keyed to
  (business_date, cashier_name) so a till stays settleable after its bills are
  uploaded and deleted. Schema v4 with a migration that carries v3 rows across.

Input and UI
- barcode_service: consume machine-paced keystrokes so a scan cannot also land
  in the focused field, and raise the bar to 60ms/char while a text field has
  focus so typing a mobile number is not read as a scan. Clock and focus check
  injected so the behaviour is testable.
- primary_button: make the label flexible; label plus trailing total overflowed
  the Charge button by up to 131px.
- app_router: redirect instead of null-casting when the receipt route is
  entered without its transaction.
- customer_repository: reduce the search query to digits so a punctuated mobile
  number matches.

Cleanup
- Remove TransactionRepository.save, CustomerRepository.recordSale and
  OrderDao.insertOrder, all superseded by commitSale.
- dart fix across the tree; 251 analyzer issues down to 3 info-level.

Tests: 23 passing / 15 failing -> 90 passing. Fixed the two defects that broke
the existing suite (containsAll type argument, reset() needing a catalogue) and
deleted the leftover template test. Added coverage for the order round trip,
the day archive after a real sync, stock safety, checkout atomicity, the v3->v4
migration, scanner-versus-human input, and an app-level smoke test that renders
every module.

Note: bills already uploaded with a discount went up overstated. This stops it
happening again but does not correct historical server data.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 18:34:10 +05:30

239 lines
7.5 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/router/app_router.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/utils/formatters.dart';
import '../../../core/widgets/primary_button.dart';
import '../../auth/providers/auth_controller.dart';
import '../../pos/providers/cart_controller.dart';
import '../../../domain/repositories/sync_repository.dart';
import '../providers/sync_controller.dart';
/// End-of-shift flow.
///
/// The day's takings are pushed here — the second and last moment this
/// terminal needs a connection. Signing out without pushing is allowed, but
/// the report stays queued locally rather than being discarded.
Future<void> showSignOutDialog(BuildContext context, WidgetRef ref) {
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => const _SignOutDialog(),
);
}
class _SignOutDialog extends ConsumerStatefulWidget {
const _SignOutDialog();
@override
ConsumerState<_SignOutDialog> createState() => _SignOutDialogState();
}
class _SignOutDialogState extends ConsumerState<_SignOutDialog> {
SyncOutcome? _result;
void _finish() {
ref.read(cartControllerProvider.notifier).reset();
ref.read(authControllerProvider.notifier).signOut();
Navigator.of(context).pop();
context.go(AppRoutes.login);
}
Future<void> _pushThenFinish() async {
final outcome = await ref.read(orderSyncProvider.notifier).run();
if (!mounted) return;
setState(() => _result = outcome);
if (outcome.isSuccess) {
await Future<void>.delayed(const Duration(milliseconds: 700));
if (mounted) _finish();
}
}
@override
Widget build(BuildContext context) {
// The operator is settling their own till, so this covers only their bills.
final report = ref.watch(myShiftReportProvider).value;
final pending = ref.watch(unsyncedCountProvider).value ?? 0;
final cart = ref.watch(cartControllerProvider);
final pushing = ref.watch(orderSyncProvider) is SyncRunning;
final failed = _result != null && !_result!.isSuccess;
return AlertDialog(
title: const Text('End shift'),
contentPadding: const EdgeInsets.fromLTRB(
AppSpacing.xxl,
AppSpacing.lg,
AppSpacing.xxl,
AppSpacing.sm,
),
content: SizedBox(
// Never wider than the viewport allows.
width: (MediaQuery.sizeOf(context).width - 96).clamp(280.0, 420.0),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (cart.isNotEmpty)
_Banner(
icon: Icons.warning_amber_rounded,
color: AppColors.warning,
background: AppColors.warningSurface,
message: 'The current bill has ${cart.lineCount} item(s) '
'and will be cleared. Park it first if you need it.',
),
if (pending == 0)
const _Banner(
icon: Icons.check_circle_outline_rounded,
color: AppColors.success,
background: AppColors.successSurface,
message: 'Every bill has already been uploaded. Nothing is '
'waiting on this terminal.',
)
else ...[
const Text(
'Waiting to upload',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: AppColors.textSecondary,
),
),
const SizedBox(height: AppSpacing.sm),
_row('Bills pending sync', '$pending'),
if (report != null) ...[
_row('Bills today', '${report.billCount}'),
_row('Items sold', report.itemCount.toStringAsFixed(0)),
_row('Gross sales', Formatters.money(report.grossSales)),
_row('GST collected',
Formatters.money(report.taxCollected),),
],
],
if (failed) ...[
const SizedBox(height: AppSpacing.md),
_Banner(
icon: Icons.wifi_off_rounded,
color: AppColors.danger,
background: AppColors.dangerSurface,
message: _result?.error ??
'Upload failed. Every bill is still stored on this '
'terminal and can be retried from Events.',
),
],
],
),
),
),
actionsPadding: const EdgeInsets.fromLTRB(
AppSpacing.xxl,
0,
AppSpacing.xxl,
AppSpacing.lg,
),
actions: [
// Wrap keeps three actions from overflowing a narrow dialog.
Wrap(
alignment: WrapAlignment.end,
spacing: AppSpacing.sm,
runSpacing: AppSpacing.sm,
children: [
TextButton(
onPressed: pushing ? null : () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
TextButton(
onPressed: pushing ? null : _finish,
style: TextButton.styleFrom(
foregroundColor: AppColors.textSecondary,
),
child: Text(
pending == 0 ? 'Sign out' : 'Sign out without syncing',
),
),
if (pending > 0)
SizedBox(
width: 190,
child: PrimaryButton(
label: failed ? 'Retry sync' : 'Sync & sign out',
icon: Icons.cloud_upload_rounded,
busy: pushing,
onPressed: _pushThenFinish,
),
),
],
),
],
);
}
Widget _row(String label, String value) => Padding(
padding: const EdgeInsets.symmetric(vertical: 3),
child: Row(
children: [
Expanded(
child: Text(
label,
style: const TextStyle(
fontSize: 13.5,
color: AppColors.textSecondary,
),
),
),
Text(
value,
style: const TextStyle(
fontSize: 13.5,
fontWeight: FontWeight.w700,
),
),
],
),
);
}
class _Banner extends StatelessWidget {
const _Banner({
required this.icon,
required this.color,
required this.background,
required this.message,
});
final IconData icon;
final Color color;
final Color background;
final String message;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(bottom: AppSpacing.md),
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: background,
borderRadius: AppRadius.brSm,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, size: 18, color: color),
const SizedBox(width: AppSpacing.sm),
Expanded(
child: Text(
message,
style: TextStyle(fontSize: 12.5, color: color, height: 1.45),
),
),
],
),
);
}
}