Files
nearle_pos/lib/presentation/pos/widgets/cart_line_tile.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

242 lines
7.9 KiB
Dart

import 'package:flutter/material.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_typography.dart';
import '../../../core/utils/formatters.dart';
import '../../../domain/entities/cart.dart';
/// One row of the bill, with inline quantity stepper.
class CartLineTile extends StatelessWidget {
const CartLineTile({
super.key,
required this.line,
required this.onIncrement,
required this.onDecrement,
required this.onRemove,
this.onDiscount,
});
final CartLine line;
final VoidCallback onIncrement;
final VoidCallback onDecrement;
final VoidCallback onRemove;
final VoidCallback? onDiscount;
@override
Widget build(BuildContext context) {
final p = line.product;
return Dismissible(
key: ValueKey('dismiss_${p.id}'),
direction: DismissDirection.endToStart,
onDismissed: (_) => onRemove(),
background: Container(
alignment: Alignment.centerRight,
padding: const EdgeInsets.only(right: AppSpacing.xl),
decoration: const BoxDecoration(
color: AppColors.dangerSurface,
borderRadius: AppRadius.brMd,
),
child: const Icon(Icons.delete_outline_rounded,
color: AppColors.danger,),
),
child: Container(
padding: const EdgeInsets.all(AppSpacing.md),
decoration: BoxDecoration(
color: AppColors.surfaceAlt,
borderRadius: AppRadius.brMd,
border: Border.all(
color: line.exceedsStock ? AppColors.danger : AppColors.border,
),
),
child: Column(children: [
Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
Container(
width: 42,
height: 42,
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: AppRadius.brSm,
border: Border.all(color: AppColors.border),
),
alignment: Alignment.center,
child: Text(p.emoji, style: const TextStyle(fontSize: 21)),
),
const SizedBox(width: AppSpacing.md),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
p.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 14.5,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Row(children: [
Text(
Formatters.money(p.price),
style: AppTypography.money(13.5,
weight: FontWeight.w600,
color: AppColors.textSecondary,),
),
Text(' / ${p.unit.symbol}',
style: const TextStyle(
fontSize: 11.5,
color: AppColors.textTertiary,
),),
if (line.discount.isActive) ...[
const SizedBox(width: AppSpacing.sm),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 5, vertical: 1,),
decoration: BoxDecoration(
color: AppColors.successSurface,
borderRadius: BorderRadius.circular(4),
),
child: Text(
line.discount.label,
style: const TextStyle(
fontSize: 10,
color: AppColors.success,
fontWeight: FontWeight.w700,
),
),
),
],
],),
],
),
),
IconButton(
onPressed: onRemove,
icon: const Icon(Icons.close_rounded, size: 18),
color: AppColors.textTertiary,
constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
padding: EdgeInsets.zero,
tooltip: 'Remove',
),
],),
const SizedBox(height: AppSpacing.sm),
Row(children: [
_Stepper(
quantity: line.quantity,
unit: p.unit.symbol,
onIncrement: onIncrement,
onDecrement: onDecrement,
),
if (onDiscount != null) ...[
const SizedBox(width: AppSpacing.sm),
IconButton(
onPressed: onDiscount,
icon: const Icon(Icons.local_offer_outlined, size: 17),
color: AppColors.textSecondary,
constraints: const BoxConstraints(minWidth: 34, minHeight: 34),
padding: EdgeInsets.zero,
tooltip: 'Line discount',
),
],
const Spacer(),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
if (line.discountAmount > 0)
Text(
Formatters.money(line.grossAmount),
style: const TextStyle(
fontSize: 11.5,
color: AppColors.textTertiary,
decoration: TextDecoration.lineThrough,
),
),
Text(
Formatters.money(line.payable),
style: AppTypography.money(16),
),
],
),
],),
if (line.exceedsStock)
Padding(
padding: const EdgeInsets.only(top: AppSpacing.sm),
child: Row(children: [
const Icon(Icons.error_outline_rounded,
size: 14, color: AppColors.danger,),
const SizedBox(width: AppSpacing.xs),
Text(
'Only ${p.stock.toStringAsFixed(0)} ${p.unit.symbol} '
'available',
style: const TextStyle(
fontSize: 11.5,
color: AppColors.danger,
fontWeight: FontWeight.w600,
),
),
],),
),
],),
),
);
}
}
class _Stepper extends StatelessWidget {
const _Stepper({
required this.quantity,
required this.unit,
required this.onIncrement,
required this.onDecrement,
});
final double quantity;
final String unit;
final VoidCallback onIncrement;
final VoidCallback onDecrement;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: AppColors.surface,
borderRadius: AppRadius.brSm,
border: Border.all(color: AppColors.border),
),
child: Row(mainAxisSize: MainAxisSize.min, children: [
_btn(Icons.remove_rounded, onDecrement),
Container(
constraints: const BoxConstraints(minWidth: 42),
alignment: Alignment.center,
child: Text(
quantity % 1 == 0
? quantity.toStringAsFixed(0)
: quantity.toStringAsFixed(2),
style: AppTypography.money(15.5),
),
),
_btn(Icons.add_rounded, onIncrement),
],),
);
}
Widget _btn(IconData icon, VoidCallback onTap) => Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
borderRadius: AppRadius.brSm,
child: SizedBox(
width: 34,
height: 34,
child: Icon(icon, size: 17, color: AppColors.primary),
),
),
);
}