second commit

This commit is contained in:
2026-07-29 11:41:53 +05:30
parent fcccf22bac
commit d72522e737
211 changed files with 19260 additions and 0 deletions

View File

@@ -0,0 +1,156 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app/providers.dart';
import '../../../domain/entities/shift_report.dart';
import '../../../domain/entities/sync_event.dart';
import '../../auth/providers/auth_controller.dart';
import '../../pos/providers/catalog_providers.dart';
/// Progress of a catalogue pull.
sealed class ImportState {
const ImportState();
}
class ImportIdle extends ImportState {
const ImportIdle();
}
class ImportRunning extends ImportState {
const ImportRunning(this.progress, this.stage);
final double progress;
final String stage;
}
class ImportDone extends ImportState {
const ImportDone(this.event);
final SyncEvent event;
}
class ImportFailed extends ImportState {
const ImportFailed(this.message);
final String message;
}
/// Bumped after every successful import so catalogue providers refetch.
final catalogueVersionProvider = StateProvider<int>((ref) => 0);
/// Whether the terminal has products to sell. The POS is gated on this.
final catalogueReadyProvider = Provider<bool>((ref) {
ref.watch(catalogueVersionProvider);
return ref.watch(syncRepositoryProvider).hasCatalogue;
});
final lastImportAtProvider = Provider<DateTime?>((ref) {
ref.watch(catalogueVersionProvider);
return ref.watch(syncRepositoryProvider).lastImportAt;
});
class CatalogueImportController extends StateNotifier<ImportState> {
CatalogueImportController(this._ref) : super(const ImportIdle());
final Ref _ref;
Future<bool> run() async {
if (state is ImportRunning) return false;
state = const ImportRunning(0, 'Starting…');
final event = await _ref.read(syncRepositoryProvider).importCatalogue(
onProgress: (progress, stage) {
if (mounted) state = ImportRunning(progress, stage);
},
);
if (event.status == SyncStatus.synced) {
// Force every catalogue-backed provider to refetch.
_ref.read(catalogueVersionProvider.notifier).state++;
_ref.invalidate(allProductsProvider);
_ref.invalidate(visibleProductsProvider);
_ref.invalidate(categoryCountsProvider);
_ref.invalidate(lowStockProductsProvider);
state = ImportDone(event);
return true;
}
state = ImportFailed(event.error ?? 'Import failed.');
return false;
}
void reset() => state = const ImportIdle();
}
final catalogueImportProvider =
StateNotifierProvider<CatalogueImportController, ImportState>(
(ref) => CatalogueImportController(ref),
);
// ------------------------------------------------------------------ Events
/// Bumped whenever the event log changes.
final syncVersionProvider = StateProvider<int>((ref) => 0);
final syncEventsProvider = Provider<List<SyncEvent>>((ref) {
ref.watch(syncVersionProvider);
ref.watch(catalogueVersionProvider);
return ref.watch(syncRepositoryProvider).events;
});
final hasUnsyncedProvider = Provider<bool>((ref) {
ref.watch(syncVersionProvider);
ref.watch(catalogueVersionProvider);
return ref.watch(syncRepositoryProvider).hasUnsyncedEvents;
});
/// Today's takings, recomputed from local sales on every change.
final shiftReportProvider = Provider<ShiftReport>((ref) {
ref.watch(syncVersionProvider);
final session = ref.watch(cashierSessionProvider);
final user = ref.watch(currentUserProvider);
return ref.watch(syncRepositoryProvider).buildShiftReport(
businessDate: DateTime.now(),
terminalId: session.terminalId,
cashierName: user?.name ?? session.name,
);
});
/// Drives the push button and the sign-out dialog.
class ReportPushController extends StateNotifier<bool> {
ReportPushController(this._ref) : super(false);
final Ref _ref;
/// Pushes today's report. Returns the resulting event so the caller can
/// tell the cashier whether it landed.
Future<SyncEvent> pushToday() async {
state = true;
try {
final report = _ref.read(shiftReportProvider);
final event =
await _ref.read(syncRepositoryProvider).pushShiftReport(report);
_ref.read(syncVersionProvider.notifier).state++;
return event;
} finally {
if (mounted) state = false;
}
}
Future<SyncEvent> retry(String eventId) async {
state = true;
try {
final event = await _ref.read(syncRepositoryProvider).retry(eventId);
_ref.read(syncVersionProvider.notifier).state++;
return event;
} finally {
if (mounted) state = false;
}
}
}
final reportPushProvider =
StateNotifierProvider<ReportPushController, bool>(
(ref) => ReportPushController(ref),
);

View File

@@ -0,0 +1,233 @@
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 '../../../domain/entities/sync_event.dart';
import '../../auth/providers/auth_controller.dart';
import '../../pos/providers/cart_controller.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> {
SyncEvent? _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 event = await ref.read(reportPushProvider.notifier).pushToday();
if (!mounted) return;
setState(() => _result = event);
if (event.status == SyncStatus.synced) {
await Future<void>.delayed(const Duration(milliseconds: 700));
if (mounted) _finish();
}
}
@override
Widget build(BuildContext context) {
final report = ref.watch(shiftReportProvider);
final cart = ref.watch(cartControllerProvider);
final pushing = ref.watch(reportPushProvider);
final failed = _result?.status == SyncStatus.failed;
return AlertDialog(
title: const Text('End shift'),
contentPadding: const EdgeInsets.fromLTRB(
AppSpacing.xxl,
AppSpacing.lg,
AppSpacing.xxl,
AppSpacing.sm,
),
content: SizedBox(
width: 420,
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 (report.isEmpty)
const _Banner(
icon: Icons.info_outline_rounded,
color: AppColors.textSecondary,
background: AppColors.surfaceAlt,
message: 'No sales were recorded today, so there is nothing '
'to push.',
)
else ...[
const Text(
"Today's takings",
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: AppColors.textSecondary,
),
),
const SizedBox(height: AppSpacing.sm),
_row('Bills', '${report.billCount}'),
_row('Items sold', report.itemCount.toStringAsFixed(0)),
_row('Gross sales', Formatters.money(report.grossSales)),
_row('GST collected', Formatters.money(report.taxCollected)),
_row('Average basket',
Formatters.money(report.averageBasket)),
],
if (failed) ...[
const SizedBox(height: AppSpacing.md),
_Banner(
icon: Icons.wifi_off_rounded,
color: AppColors.danger,
background: AppColors.dangerSurface,
message: _result?.error ??
'The push failed. The report is still saved 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(
report.isEmpty ? 'Sign out' : 'Sign out without pushing',
),
),
if (!report.isEmpty)
SizedBox(
width: 190,
child: PrimaryButton(
label: failed ? 'Retry push' : 'Push & 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),
),
),
],
),
);
}
}