added local db
This commit is contained in:
263
lib/data/local/app_database.dart
Normal file
263
lib/data/local/app_database.dart
Normal file
@@ -0,0 +1,263 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
|
||||
/// SQLite database for the terminal.
|
||||
///
|
||||
/// This is the source of truth for everything the cashier produces. Orders are
|
||||
/// written here the moment a sale completes, so a crash, a power cut or a
|
||||
/// closed app cannot lose a bill that has not yet reached the server.
|
||||
class AppDatabase {
|
||||
AppDatabase._();
|
||||
|
||||
static final AppDatabase instance = AppDatabase._();
|
||||
|
||||
static const String _fileName = 'nearle_pos.db';
|
||||
static const int _version = 1;
|
||||
|
||||
Database? _db;
|
||||
|
||||
Database get db {
|
||||
final database = _db;
|
||||
if (database == null) {
|
||||
throw StateError('AppDatabase.open() must be called before use.');
|
||||
}
|
||||
return database;
|
||||
}
|
||||
|
||||
bool get isOpen => _db != null;
|
||||
|
||||
/// Opens the database, creating the schema on first run.
|
||||
///
|
||||
/// Desktop needs the FFI factory installed first; Android and iOS use the
|
||||
/// platform implementation that ships with sqflite.
|
||||
Future<void> open({String? overridePath}) async {
|
||||
if (_db != null) return;
|
||||
|
||||
if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
|
||||
sqfliteFfiInit();
|
||||
databaseFactory = databaseFactoryFfi;
|
||||
}
|
||||
|
||||
final path = overridePath ??
|
||||
p.join(await databaseFactory.getDatabasesPath(), _fileName);
|
||||
|
||||
_db = await databaseFactory.openDatabase(
|
||||
path,
|
||||
options: OpenDatabaseOptions(
|
||||
version: _version,
|
||||
onConfigure: (db) => db.execute('PRAGMA foreign_keys = ON'),
|
||||
onCreate: (db, version) async => _createSchema(db),
|
||||
onUpgrade: (db, from, to) async {
|
||||
// Single version so far; migrations land here as the schema grows.
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// In-memory database for tests.
|
||||
Future<void> openInMemory() async {
|
||||
if (_db != null) await close();
|
||||
sqfliteFfiInit();
|
||||
databaseFactory = databaseFactoryFfi;
|
||||
_db = await databaseFactory.openDatabase(
|
||||
inMemoryDatabasePath,
|
||||
options: OpenDatabaseOptions(
|
||||
version: _version,
|
||||
onConfigure: (db) => db.execute('PRAGMA foreign_keys = ON'),
|
||||
onCreate: (db, version) async => _createSchema(db),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> close() async {
|
||||
await _db?.close();
|
||||
_db = null;
|
||||
}
|
||||
|
||||
/// Drops every row without touching the schema. Used by tests.
|
||||
Future<void> clear() async {
|
||||
final batch = db.batch();
|
||||
for (final t in const [
|
||||
Tables.orderItems,
|
||||
Tables.orders,
|
||||
Tables.products,
|
||||
Tables.customers,
|
||||
Tables.parkedBills,
|
||||
Tables.syncLog,
|
||||
Tables.meta,
|
||||
]) {
|
||||
batch.delete(t);
|
||||
}
|
||||
await batch.commit(noResult: true);
|
||||
}
|
||||
|
||||
Future<void> _createSchema(Database db) async {
|
||||
// ------------------------------------------------------------ products
|
||||
await db.execute('''
|
||||
CREATE TABLE ${Tables.products} (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
barcode TEXT NOT NULL,
|
||||
sku TEXT NOT NULL,
|
||||
category TEXT NOT NULL,
|
||||
price REAL NOT NULL,
|
||||
mrp REAL,
|
||||
stock REAL NOT NULL DEFAULT 0,
|
||||
emoji TEXT,
|
||||
image_url TEXT,
|
||||
unit TEXT NOT NULL DEFAULT 'piece',
|
||||
gst_rate REAL NOT NULL DEFAULT 0.18,
|
||||
brand TEXT,
|
||||
is_active INTEGER NOT NULL DEFAULT 1,
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
''');
|
||||
// Barcode lookup is the hot path during scanning.
|
||||
await db.execute(
|
||||
'CREATE UNIQUE INDEX idx_products_barcode ON ${Tables.products}(barcode)',
|
||||
);
|
||||
await db.execute(
|
||||
'CREATE INDEX idx_products_category ON ${Tables.products}(category)',
|
||||
);
|
||||
|
||||
// ----------------------------------------------------------- customers
|
||||
await db.execute('''
|
||||
CREATE TABLE ${Tables.customers} (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
mobile TEXT NOT NULL,
|
||||
email TEXT,
|
||||
gender TEXT NOT NULL DEFAULT 'unspecified',
|
||||
date_of_birth INTEGER,
|
||||
loyalty_points INTEGER NOT NULL DEFAULT 0,
|
||||
lifetime_spend REAL NOT NULL DEFAULT 0,
|
||||
visit_count INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER,
|
||||
last_visit_at INTEGER
|
||||
)
|
||||
''');
|
||||
await db.execute(
|
||||
'CREATE UNIQUE INDEX idx_customers_mobile ON ${Tables.customers}(mobile)',
|
||||
);
|
||||
|
||||
// -------------------------------------------------------------- orders
|
||||
await db.execute('''
|
||||
CREATE TABLE ${Tables.orders} (
|
||||
id TEXT PRIMARY KEY,
|
||||
invoice_number TEXT NOT NULL UNIQUE,
|
||||
created_at INTEGER NOT NULL,
|
||||
business_date TEXT NOT NULL,
|
||||
cashier_name TEXT NOT NULL,
|
||||
terminal_id TEXT NOT NULL,
|
||||
customer_id TEXT,
|
||||
customer_mobile TEXT,
|
||||
customer_name TEXT,
|
||||
subtotal REAL NOT NULL,
|
||||
line_discount REAL NOT NULL DEFAULT 0,
|
||||
bill_discount REAL NOT NULL DEFAULT 0,
|
||||
loyalty_value REAL NOT NULL DEFAULT 0,
|
||||
taxable_amount REAL NOT NULL DEFAULT 0,
|
||||
tax_amount REAL NOT NULL DEFAULT 0,
|
||||
round_off REAL NOT NULL DEFAULT 0,
|
||||
total REAL NOT NULL,
|
||||
points_earned INTEGER NOT NULL DEFAULT 0,
|
||||
points_redeemed INTEGER NOT NULL DEFAULT 0,
|
||||
payments_json TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'completed',
|
||||
|
||||
-- 0 = held on this terminal, 1 = accepted by the server
|
||||
sync_status INTEGER NOT NULL DEFAULT 0,
|
||||
synced_at INTEGER,
|
||||
sync_attempts INTEGER NOT NULL DEFAULT 0,
|
||||
sync_error TEXT
|
||||
)
|
||||
''');
|
||||
// The end-of-day upload selects on this, so it must be indexed.
|
||||
await db.execute(
|
||||
'CREATE INDEX idx_orders_sync ON ${Tables.orders}(sync_status)',
|
||||
);
|
||||
await db.execute(
|
||||
'CREATE INDEX idx_orders_date ON ${Tables.orders}(business_date)',
|
||||
);
|
||||
|
||||
// --------------------------------------------------------- order items
|
||||
await db.execute('''
|
||||
CREATE TABLE ${Tables.orderItems} (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
order_id TEXT NOT NULL,
|
||||
product_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
barcode TEXT NOT NULL,
|
||||
sku TEXT NOT NULL,
|
||||
unit TEXT NOT NULL,
|
||||
unit_price REAL NOT NULL,
|
||||
quantity REAL NOT NULL,
|
||||
discount REAL NOT NULL DEFAULT 0,
|
||||
gst_rate REAL NOT NULL DEFAULT 0,
|
||||
tax_amount REAL NOT NULL DEFAULT 0,
|
||||
line_total REAL NOT NULL,
|
||||
FOREIGN KEY (order_id) REFERENCES ${Tables.orders}(id)
|
||||
ON DELETE CASCADE
|
||||
)
|
||||
''');
|
||||
await db.execute(
|
||||
'CREATE INDEX idx_items_order ON ${Tables.orderItems}(order_id)',
|
||||
);
|
||||
|
||||
// --------------------------------------------------------- parked bills
|
||||
await db.execute('''
|
||||
CREATE TABLE ${Tables.parkedBills} (
|
||||
id TEXT PRIMARY KEY,
|
||||
label TEXT,
|
||||
parked_at INTEGER NOT NULL,
|
||||
cart_json TEXT NOT NULL
|
||||
)
|
||||
''');
|
||||
|
||||
// -------------------------------------------------------------- syncLog
|
||||
await db.execute('''
|
||||
CREATE TABLE ${Tables.syncLog} (
|
||||
id TEXT PRIMARY KEY,
|
||||
type TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
synced_at INTEGER,
|
||||
summary TEXT NOT NULL,
|
||||
error TEXT,
|
||||
attempts INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
''');
|
||||
|
||||
// ----------------------------------------------------------------- meta
|
||||
await db.execute('''
|
||||
CREATE TABLE ${Tables.meta} (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
)
|
||||
''');
|
||||
}
|
||||
}
|
||||
|
||||
class Tables {
|
||||
const Tables._();
|
||||
|
||||
static const String products = 'products';
|
||||
static const String customers = 'customers';
|
||||
static const String orders = 'orders';
|
||||
static const String orderItems = 'order_items';
|
||||
static const String parkedBills = 'parked_bills';
|
||||
static const String syncLog = 'sync_log';
|
||||
static const String meta = 'app_meta';
|
||||
}
|
||||
|
||||
class MetaKeys {
|
||||
const MetaKeys._();
|
||||
|
||||
static const String lastImportAt = 'last_import_at';
|
||||
static const String catalogueRevision = 'catalogue_revision';
|
||||
static const String invoiceSequence = 'invoice_sequence';
|
||||
}
|
||||
248
lib/data/local/catalogue_dao.dart
Normal file
248
lib/data/local/catalogue_dao.dart
Normal file
@@ -0,0 +1,248 @@
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
|
||||
import '../../domain/entities/customer.dart';
|
||||
import '../../domain/entities/product.dart';
|
||||
import 'app_database.dart';
|
||||
|
||||
/// Reads and writes the imported catalogue.
|
||||
class CatalogueDao {
|
||||
const CatalogueDao(this._db);
|
||||
|
||||
final Database _db;
|
||||
|
||||
// --------------------------------------------------------------- Mapping
|
||||
static Map<String, Object?> productToRow(Product p) => {
|
||||
'id': p.id,
|
||||
'name': p.name,
|
||||
'barcode': p.barcode,
|
||||
'sku': p.sku,
|
||||
'category': p.category.name,
|
||||
'price': p.price,
|
||||
'mrp': p.mrp,
|
||||
'stock': p.stock,
|
||||
'emoji': p.emoji,
|
||||
'image_url': p.imageUrl,
|
||||
'unit': p.unit.name,
|
||||
'gst_rate': p.gstRate,
|
||||
'brand': p.brand,
|
||||
'is_active': p.isActive ? 1 : 0,
|
||||
'updated_at': DateTime.now().millisecondsSinceEpoch,
|
||||
};
|
||||
|
||||
static Product productFromRow(Map<String, Object?> r) => Product(
|
||||
id: r['id']! as String,
|
||||
name: r['name']! as String,
|
||||
barcode: r['barcode']! as String,
|
||||
sku: r['sku']! as String,
|
||||
category: ProductCategory.values.byName(r['category']! as String),
|
||||
price: (r['price']! as num).toDouble(),
|
||||
mrp: (r['mrp'] as num?)?.toDouble(),
|
||||
stock: (r['stock']! as num).toDouble(),
|
||||
emoji: (r['emoji'] as String?) ?? '📦',
|
||||
imageUrl: r['image_url'] as String?,
|
||||
unit: UnitOfMeasure.values.byName((r['unit'] as String?) ?? 'piece'),
|
||||
gstRate: (r['gst_rate']! as num).toDouble(),
|
||||
brand: r['brand'] as String?,
|
||||
isActive: (r['is_active']! as int) == 1,
|
||||
);
|
||||
|
||||
static Map<String, Object?> customerToRow(Customer c) => {
|
||||
'id': c.id,
|
||||
'name': c.name,
|
||||
'mobile': c.mobile,
|
||||
'email': c.email,
|
||||
'gender': c.gender.name,
|
||||
'date_of_birth': c.dateOfBirth?.millisecondsSinceEpoch,
|
||||
'loyalty_points': c.loyaltyPoints,
|
||||
'lifetime_spend': c.lifetimeSpend,
|
||||
'visit_count': c.visitCount,
|
||||
'created_at': c.createdAt?.millisecondsSinceEpoch,
|
||||
'last_visit_at': c.lastVisitAt?.millisecondsSinceEpoch,
|
||||
};
|
||||
|
||||
static Customer customerFromRow(Map<String, Object?> r) => Customer(
|
||||
id: r['id']! as String,
|
||||
name: r['name']! as String,
|
||||
mobile: r['mobile']! as String,
|
||||
email: r['email'] as String?,
|
||||
gender: Gender.values.byName((r['gender'] as String?) ?? 'unspecified'),
|
||||
dateOfBirth: _date(r['date_of_birth']),
|
||||
loyaltyPoints: (r['loyalty_points'] as int?) ?? 0,
|
||||
lifetimeSpend: (r['lifetime_spend'] as num?)?.toDouble() ?? 0,
|
||||
visitCount: (r['visit_count'] as int?) ?? 0,
|
||||
createdAt: _date(r['created_at']),
|
||||
lastVisitAt: _date(r['last_visit_at']),
|
||||
);
|
||||
|
||||
static DateTime? _date(Object? millis) => millis == null
|
||||
? null
|
||||
: DateTime.fromMillisecondsSinceEpoch(millis! as int);
|
||||
|
||||
// -------------------------------------------------------------- Products
|
||||
Future<List<Product>> allProducts() async {
|
||||
final rows = await _db.query(
|
||||
Tables.products,
|
||||
where: 'is_active = 1',
|
||||
orderBy: 'category, name',
|
||||
);
|
||||
return rows.map(productFromRow).toList();
|
||||
}
|
||||
|
||||
Future<Product?> productByBarcode(String barcode) async {
|
||||
final rows = await _db.query(
|
||||
Tables.products,
|
||||
where: 'barcode = ? AND is_active = 1',
|
||||
whereArgs: [barcode.trim()],
|
||||
limit: 1,
|
||||
);
|
||||
return rows.isEmpty ? null : productFromRow(rows.first);
|
||||
}
|
||||
|
||||
Future<Product?> productById(String id) async {
|
||||
final rows = await _db.query(
|
||||
Tables.products,
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
limit: 1,
|
||||
);
|
||||
return rows.isEmpty ? null : productFromRow(rows.first);
|
||||
}
|
||||
|
||||
Future<int> productCount() async {
|
||||
final r = await _db.rawQuery(
|
||||
'SELECT COUNT(*) AS c FROM ${Tables.products} WHERE is_active = 1',
|
||||
);
|
||||
return (r.first['c']! as int);
|
||||
}
|
||||
|
||||
Future<void> upsertProduct(Product p) async {
|
||||
await _db.insert(
|
||||
Tables.products,
|
||||
productToRow(p),
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
}
|
||||
|
||||
/// Writes the pulled catalogue in one transaction.
|
||||
///
|
||||
/// Stock already decremented by local sales is preserved for products that
|
||||
/// survive the import, so re-importing mid-shift cannot resurrect sold units.
|
||||
Future<void> replaceCatalogue({
|
||||
required List<Product> products,
|
||||
required List<Customer> customers,
|
||||
}) async {
|
||||
await _db.transaction((txn) async {
|
||||
final existing = await txn.query(
|
||||
Tables.products,
|
||||
columns: ['id', 'stock'],
|
||||
);
|
||||
final heldStock = {
|
||||
for (final r in existing) r['id']! as String: (r['stock']! as num).toDouble(),
|
||||
};
|
||||
|
||||
final batch = txn.batch();
|
||||
for (final p in products) {
|
||||
final held = heldStock[p.id];
|
||||
batch.insert(
|
||||
Tables.products,
|
||||
productToRow(held == null ? p : p.copyWith(stock: held)),
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
}
|
||||
|
||||
// Locally registered customers must survive a server pull, so this
|
||||
// ignores rows that already exist rather than replacing them.
|
||||
for (final c in customers) {
|
||||
batch.insert(
|
||||
Tables.customers,
|
||||
customerToRow(c),
|
||||
conflictAlgorithm: ConflictAlgorithm.ignore,
|
||||
);
|
||||
}
|
||||
|
||||
await batch.commit(noResult: true);
|
||||
});
|
||||
}
|
||||
|
||||
/// Applies stock movement after a sale, clamped at zero.
|
||||
Future<void> decrementStock(Map<String, double> quantities) async {
|
||||
if (quantities.isEmpty) return;
|
||||
await _db.transaction((txn) async {
|
||||
final batch = txn.batch();
|
||||
quantities.forEach((id, qty) {
|
||||
batch.rawUpdate(
|
||||
'UPDATE ${Tables.products} '
|
||||
'SET stock = MAX(0, stock - ?), updated_at = ? WHERE id = ?',
|
||||
[qty, DateTime.now().millisecondsSinceEpoch, id],
|
||||
);
|
||||
});
|
||||
await batch.commit(noResult: true);
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- Customers
|
||||
Future<List<Customer>> allCustomers({int limit = 500}) async {
|
||||
final rows = await _db.query(
|
||||
Tables.customers,
|
||||
orderBy: 'last_visit_at DESC',
|
||||
limit: limit,
|
||||
);
|
||||
return rows.map(customerFromRow).toList();
|
||||
}
|
||||
|
||||
Future<Customer?> customerByMobile(String mobile) async {
|
||||
final digits = mobile.replaceAll(RegExp(r'\D'), '');
|
||||
final rows = await _db.query(
|
||||
Tables.customers,
|
||||
where: 'mobile = ?',
|
||||
whereArgs: [digits],
|
||||
limit: 1,
|
||||
);
|
||||
return rows.isEmpty ? null : customerFromRow(rows.first);
|
||||
}
|
||||
|
||||
Future<Customer?> customerById(String id) async {
|
||||
final rows = await _db.query(
|
||||
Tables.customers,
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
limit: 1,
|
||||
);
|
||||
return rows.isEmpty ? null : customerFromRow(rows.first);
|
||||
}
|
||||
|
||||
Future<void> upsertCustomer(Customer c) async {
|
||||
await _db.insert(
|
||||
Tables.customers,
|
||||
customerToRow(c),
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Meta
|
||||
Future<String?> meta(String key) async {
|
||||
final rows = await _db.query(
|
||||
Tables.meta,
|
||||
where: 'key = ?',
|
||||
whereArgs: [key],
|
||||
limit: 1,
|
||||
);
|
||||
return rows.isEmpty ? null : rows.first['value'] as String?;
|
||||
}
|
||||
|
||||
Future<void> setMeta(String key, String value) async {
|
||||
await _db.insert(
|
||||
Tables.meta,
|
||||
{'key': key, 'value': value},
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
}
|
||||
|
||||
/// Monotonic invoice counter held in the meta table.
|
||||
Future<int> nextInvoiceSequence() async {
|
||||
final current = int.tryParse(await meta(MetaKeys.invoiceSequence) ?? '0') ?? 0;
|
||||
final next = current + 1;
|
||||
await setMeta(MetaKeys.invoiceSequence, '$next');
|
||||
return next;
|
||||
}
|
||||
}
|
||||
367
lib/data/local/order_dao.dart
Normal file
367
lib/data/local/order_dao.dart
Normal file
@@ -0,0 +1,367 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
|
||||
import '../../domain/entities/cart.dart';
|
||||
import '../../domain/entities/customer.dart';
|
||||
import '../../domain/entities/product.dart';
|
||||
import '../../domain/entities/transaction.dart';
|
||||
import 'app_database.dart';
|
||||
import 'catalogue_dao.dart';
|
||||
|
||||
/// Persists bills.
|
||||
///
|
||||
/// Every completed sale lands here with `sync_status = 0`. The end-of-day
|
||||
/// upload selects those rows, sends them, and flips the accepted ones to 1.
|
||||
/// Nothing is ever deleted as part of syncing.
|
||||
class OrderDao {
|
||||
const OrderDao(this._db);
|
||||
|
||||
final Database _db;
|
||||
|
||||
static const int pending = 0;
|
||||
static const int synced = 1;
|
||||
|
||||
static String businessDateOf(DateTime dt) =>
|
||||
'${dt.year.toString().padLeft(4, '0')}-'
|
||||
'${dt.month.toString().padLeft(2, '0')}-'
|
||||
'${dt.day.toString().padLeft(2, '0')}';
|
||||
|
||||
// ----------------------------------------------------------------- Write
|
||||
/// Writes the bill and its lines atomically.
|
||||
Future<void> insertOrder(SaleTransaction t) async {
|
||||
final cart = t.cart;
|
||||
|
||||
await _db.transaction((txn) async {
|
||||
await txn.insert(
|
||||
Tables.orders,
|
||||
{
|
||||
'id': t.id,
|
||||
'invoice_number': t.invoiceNumber,
|
||||
'created_at': t.createdAt.millisecondsSinceEpoch,
|
||||
'business_date': businessDateOf(t.createdAt),
|
||||
'cashier_name': t.cashierName,
|
||||
'terminal_id': t.terminalId,
|
||||
'customer_id': cart.customer?.id,
|
||||
'customer_mobile': cart.customer?.mobile,
|
||||
'customer_name': cart.customer?.name,
|
||||
'subtotal': cart.subtotal,
|
||||
'line_discount': cart.lineDiscountTotal,
|
||||
'bill_discount': cart.billDiscountTotal,
|
||||
'loyalty_value': cart.loyaltyRedemptionValue,
|
||||
'taxable_amount': cart.taxableAmount,
|
||||
'tax_amount': cart.taxAmount,
|
||||
'round_off': cart.roundOff,
|
||||
'total': t.total,
|
||||
'points_earned': cart.pointsEarned,
|
||||
'points_redeemed': cart.pointsRedeemed,
|
||||
'payments_json': jsonEncode([
|
||||
for (final p in t.payments)
|
||||
{
|
||||
'method': p.method.name,
|
||||
'amount': p.amount,
|
||||
'tendered': p.tendered,
|
||||
'reference': p.reference,
|
||||
},
|
||||
]),
|
||||
'status': t.status.name,
|
||||
'sync_status': pending,
|
||||
'sync_attempts': 0,
|
||||
},
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
|
||||
final batch = txn.batch();
|
||||
for (final line in cart.lines) {
|
||||
batch.insert(Tables.orderItems, {
|
||||
'order_id': t.id,
|
||||
'product_id': line.product.id,
|
||||
'name': line.product.name,
|
||||
'barcode': line.product.barcode,
|
||||
'sku': line.product.sku,
|
||||
'unit': line.product.unit.name,
|
||||
'unit_price': line.product.price,
|
||||
'quantity': line.quantity,
|
||||
'discount': line.discountAmount,
|
||||
'gst_rate': line.product.gstRate,
|
||||
'tax_amount': line.taxAmount,
|
||||
'line_total': line.payable,
|
||||
});
|
||||
}
|
||||
await batch.commit(noResult: true);
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Read
|
||||
Future<List<SaleTransaction>> recent({int limit = 100}) =>
|
||||
_query(orderBy: 'created_at DESC', limit: limit);
|
||||
|
||||
Future<List<SaleTransaction>> forBusinessDate(DateTime day) =>
|
||||
_query(where: 'business_date = ?', whereArgs: [businessDateOf(day)]);
|
||||
|
||||
/// The end-of-day upload set.
|
||||
Future<List<SaleTransaction>> unsynced({int limit = 500}) => _query(
|
||||
where: 'sync_status = ?',
|
||||
whereArgs: [pending],
|
||||
orderBy: 'created_at ASC',
|
||||
limit: limit,
|
||||
);
|
||||
|
||||
Future<SaleTransaction?> byInvoice(String invoiceNumber) async {
|
||||
final rows = await _query(
|
||||
where: 'invoice_number = ?',
|
||||
whereArgs: [invoiceNumber],
|
||||
limit: 1,
|
||||
);
|
||||
return rows.isEmpty ? null : rows.first;
|
||||
}
|
||||
|
||||
Future<int> unsyncedCount() async {
|
||||
final r = await _db.rawQuery(
|
||||
'SELECT COUNT(*) AS c FROM ${Tables.orders} WHERE sync_status = ?',
|
||||
[pending],
|
||||
);
|
||||
return r.first['c']! as int;
|
||||
}
|
||||
|
||||
Future<double> salesTotalForDay(DateTime day) async {
|
||||
final r = await _db.rawQuery(
|
||||
'SELECT COALESCE(SUM(total), 0) AS t FROM ${Tables.orders} '
|
||||
"WHERE business_date = ? AND status = 'completed'",
|
||||
[businessDateOf(day)],
|
||||
);
|
||||
return (r.first['t']! as num).toDouble();
|
||||
}
|
||||
|
||||
/// Sync state of an order, for display in the events log.
|
||||
Future<Map<String, Object?>?> syncRow(String orderId) async {
|
||||
final rows = await _db.query(
|
||||
Tables.orders,
|
||||
columns: [
|
||||
'id',
|
||||
'invoice_number',
|
||||
'total',
|
||||
'created_at',
|
||||
'sync_status',
|
||||
'synced_at',
|
||||
'sync_attempts',
|
||||
'sync_error',
|
||||
],
|
||||
where: 'id = ?',
|
||||
whereArgs: [orderId],
|
||||
limit: 1,
|
||||
);
|
||||
return rows.isEmpty ? null : rows.first;
|
||||
}
|
||||
|
||||
Future<List<Map<String, Object?>>> syncRows({int limit = 200}) => _db.query(
|
||||
Tables.orders,
|
||||
columns: [
|
||||
'id',
|
||||
'invoice_number',
|
||||
'total',
|
||||
'created_at',
|
||||
'sync_status',
|
||||
'synced_at',
|
||||
'sync_attempts',
|
||||
'sync_error',
|
||||
],
|
||||
orderBy: 'created_at DESC',
|
||||
limit: limit,
|
||||
);
|
||||
|
||||
// ----------------------------------------------------------------- Sync
|
||||
/// Flips accepted orders to `sync_status = 1`.
|
||||
Future<void> markSynced(List<String> orderIds) async {
|
||||
if (orderIds.isEmpty) return;
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
final placeholders = List.filled(orderIds.length, '?').join(',');
|
||||
|
||||
await _db.rawUpdate(
|
||||
'UPDATE ${Tables.orders} SET sync_status = ?, synced_at = ?, '
|
||||
'sync_error = NULL WHERE id IN ($placeholders)',
|
||||
[synced, now, ...orderIds],
|
||||
);
|
||||
}
|
||||
|
||||
/// Records a failed attempt. The rows stay at `sync_status = 0`.
|
||||
Future<void> markFailed(List<String> orderIds, String error) async {
|
||||
if (orderIds.isEmpty) return;
|
||||
final placeholders = List.filled(orderIds.length, '?').join(',');
|
||||
|
||||
await _db.rawUpdate(
|
||||
'UPDATE ${Tables.orders} SET sync_attempts = sync_attempts + 1, '
|
||||
'sync_error = ? WHERE id IN ($placeholders)',
|
||||
[error, ...orderIds],
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------- Parked bills
|
||||
Future<void> park(ParkedBill bill) async {
|
||||
await _db.insert(
|
||||
Tables.parkedBills,
|
||||
{
|
||||
'id': bill.id,
|
||||
'label': bill.label,
|
||||
'parked_at': bill.parkedAt.millisecondsSinceEpoch,
|
||||
'cart_json': jsonEncode(_cartToJson(bill.cart)),
|
||||
},
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
}
|
||||
|
||||
Future<List<ParkedBill>> parkedBills() async {
|
||||
final rows =
|
||||
await _db.query(Tables.parkedBills, orderBy: 'parked_at DESC');
|
||||
return rows
|
||||
.map((r) => ParkedBill(
|
||||
id: r['id']! as String,
|
||||
label: r['label'] as String?,
|
||||
parkedAt:
|
||||
DateTime.fromMillisecondsSinceEpoch(r['parked_at']! as int),
|
||||
cart: _cartFromJson(
|
||||
jsonDecode(r['cart_json']! as String) as Map<String, Object?>,
|
||||
),
|
||||
))
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<void> removeParked(String id) async {
|
||||
await _db.delete(Tables.parkedBills, where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- Internals
|
||||
Future<List<SaleTransaction>> _query({
|
||||
String? where,
|
||||
List<Object?>? whereArgs,
|
||||
String orderBy = 'created_at DESC',
|
||||
int? limit,
|
||||
}) async {
|
||||
final orders = await _db.query(
|
||||
Tables.orders,
|
||||
where: where,
|
||||
whereArgs: whereArgs,
|
||||
orderBy: orderBy,
|
||||
limit: limit,
|
||||
);
|
||||
if (orders.isEmpty) return const [];
|
||||
|
||||
final ids = orders.map((o) => o['id']! as String).toList();
|
||||
final placeholders = List.filled(ids.length, '?').join(',');
|
||||
final items = await _db.query(
|
||||
Tables.orderItems,
|
||||
where: 'order_id IN ($placeholders)',
|
||||
whereArgs: ids,
|
||||
);
|
||||
|
||||
final byOrder = <String, List<Map<String, Object?>>>{};
|
||||
for (final i in items) {
|
||||
byOrder.putIfAbsent(i['order_id']! as String, () => []).add(i);
|
||||
}
|
||||
|
||||
return orders
|
||||
.map((o) => _transactionFromRows(o, byOrder[o['id']] ?? const []))
|
||||
.toList();
|
||||
}
|
||||
|
||||
SaleTransaction _transactionFromRows(
|
||||
Map<String, Object?> o,
|
||||
List<Map<String, Object?>> items,
|
||||
) {
|
||||
// Lines are rebuilt from the snapshot taken at sale time, not from the
|
||||
// current catalogue, so a reprint always shows what was actually charged.
|
||||
final lines = items.map((i) {
|
||||
final product = Product(
|
||||
id: i['product_id']! as String,
|
||||
name: i['name']! as String,
|
||||
barcode: i['barcode']! as String,
|
||||
sku: i['sku']! as String,
|
||||
category: ProductCategory.grocery,
|
||||
price: (i['unit_price']! as num).toDouble(),
|
||||
stock: 0,
|
||||
unit: UnitOfMeasure.values.byName(i['unit']! as String),
|
||||
gstRate: (i['gst_rate']! as num).toDouble(),
|
||||
);
|
||||
return CartLine(
|
||||
product: product,
|
||||
quantity: (i['quantity']! as num).toDouble(),
|
||||
discount: (i['discount']! as num) > 0
|
||||
? Discount(
|
||||
type: DiscountType.flat,
|
||||
value: (i['discount']! as num).toDouble(),
|
||||
)
|
||||
: Discount.none,
|
||||
);
|
||||
}).toList();
|
||||
|
||||
final customerId = o['customer_id'] as String?;
|
||||
final customer = customerId == null
|
||||
? null
|
||||
: Customer(
|
||||
id: customerId,
|
||||
name: (o['customer_name'] as String?) ?? 'Customer',
|
||||
mobile: (o['customer_mobile'] as String?) ?? '',
|
||||
);
|
||||
|
||||
final payments = (jsonDecode(o['payments_json']! as String) as List)
|
||||
.cast<Map<String, Object?>>()
|
||||
.map((p) => PaymentSplit(
|
||||
method: PaymentMethod.values.byName(p['method']! as String),
|
||||
amount: (p['amount']! as num).toDouble(),
|
||||
tendered: (p['tendered'] as num?)?.toDouble(),
|
||||
reference: p['reference'] as String?,
|
||||
))
|
||||
.toList();
|
||||
|
||||
return SaleTransaction(
|
||||
id: o['id']! as String,
|
||||
invoiceNumber: o['invoice_number']! as String,
|
||||
cart: Cart(lines: lines, customer: customer),
|
||||
payments: payments,
|
||||
createdAt: DateTime.fromMillisecondsSinceEpoch(o['created_at']! as int),
|
||||
cashierName: o['cashier_name']! as String,
|
||||
terminalId: o['terminal_id']! as String,
|
||||
status: TransactionStatus.values.byName(o['status']! as String),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, Object?> _cartToJson(Cart cart) => {
|
||||
'customer': cart.customer == null
|
||||
? null
|
||||
: CatalogueDao.customerToRow(cart.customer!),
|
||||
'points_redeemed': cart.pointsRedeemed,
|
||||
'note': cart.note,
|
||||
'lines': [
|
||||
for (final l in cart.lines)
|
||||
{
|
||||
'product': CatalogueDao.productToRow(l.product),
|
||||
'quantity': l.quantity,
|
||||
'discount_type': l.discount.type.name,
|
||||
'discount_value': l.discount.value,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
Cart _cartFromJson(Map<String, Object?> j) {
|
||||
final customerRow = j['customer'] as Map<String, Object?>?;
|
||||
return Cart(
|
||||
customer: customerRow == null
|
||||
? null
|
||||
: CatalogueDao.customerFromRow(customerRow),
|
||||
pointsRedeemed: (j['points_redeemed'] as int?) ?? 0,
|
||||
note: j['note'] as String?,
|
||||
lines: (j['lines'] as List).cast<Map<String, Object?>>().map((l) {
|
||||
return CartLine(
|
||||
product: CatalogueDao.productFromRow(
|
||||
l['product']! as Map<String, Object?>,
|
||||
),
|
||||
quantity: (l['quantity']! as num).toDouble(),
|
||||
discount: Discount(
|
||||
type: DiscountType.values.byName(l['discount_type']! as String),
|
||||
value: (l['discount_value']! as num).toDouble(),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user