85 lines
2.6 KiB
Dart
85 lines
2.6 KiB
Dart
import 'package:sqflite/sqflite.dart';
|
|
|
|
/// Accès à la base SQLite locale (persistée sur la tablette).
|
|
class LocalDb {
|
|
LocalDb._();
|
|
static final LocalDb instance = LocalDb._();
|
|
|
|
Database? _db;
|
|
|
|
Future<Database> get database async {
|
|
return _db ??= await _ouvrir();
|
|
}
|
|
|
|
Future<Database> _ouvrir() async {
|
|
final dir = await getDatabasesPath();
|
|
final chemin = '$dir/gestion_prix.db';
|
|
return openDatabase(
|
|
chemin,
|
|
version: 7,
|
|
onCreate: (db, version) async {
|
|
await _creerTable(db);
|
|
await _creerCache(db);
|
|
},
|
|
onUpgrade: (db, ancienne, nouvelle) async {
|
|
if (ancienne < 2) {
|
|
// Ancien schéma (prix HT/TTC) → refonte complète.
|
|
await db.execute('DROP TABLE IF EXISTS produits');
|
|
await _creerTable(db);
|
|
}
|
|
if (ancienne < 3) {
|
|
// Ajout quantité + unité pour le prix au kilo/litre.
|
|
await db.execute('ALTER TABLE produits ADD COLUMN quantite REAL');
|
|
await db.execute('ALTER TABLE produits ADD COLUMN unite TEXT');
|
|
}
|
|
if (ancienne < 4) {
|
|
// Ajout du nombre de contenants (packs).
|
|
await db.execute('ALTER TABLE produits ADD COLUMN nb_contenants INTEGER');
|
|
}
|
|
if (ancienne < 5) {
|
|
// Ajout du stock (inventaire).
|
|
await db.execute(
|
|
'ALTER TABLE produits ADD COLUMN stock INTEGER NOT NULL DEFAULT 0');
|
|
}
|
|
if (ancienne < 6) {
|
|
// Ajout du prix d'achat (marge).
|
|
await db.execute(
|
|
'ALTER TABLE produits ADD COLUMN prix_achat REAL NOT NULL DEFAULT 0');
|
|
}
|
|
if (ancienne < 7) {
|
|
// Cache local des produits du serveur (lecture hors ligne).
|
|
await _creerCache(db);
|
|
}
|
|
},
|
|
);
|
|
}
|
|
|
|
/// Cache des produits du serveur (clé = id serveur, valeur = JSON du produit).
|
|
Future<void> _creerCache(Database db) async {
|
|
await db.execute('''
|
|
CREATE TABLE IF NOT EXISTS cache_produits(
|
|
id TEXT PRIMARY KEY,
|
|
json TEXT NOT NULL
|
|
)
|
|
''');
|
|
}
|
|
|
|
Future<void> _creerTable(Database db) async {
|
|
await db.execute('''
|
|
CREATE TABLE produits(
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
code_barres TEXT UNIQUE,
|
|
nom TEXT NOT NULL,
|
|
image_url TEXT,
|
|
prix REAL NOT NULL DEFAULT 0,
|
|
prix_achat REAL NOT NULL DEFAULT 0,
|
|
quantite REAL,
|
|
unite TEXT,
|
|
nb_contenants INTEGER,
|
|
stock INTEGER NOT NULL DEFAULT 0,
|
|
cree_le INTEGER NOT NULL DEFAULT 0
|
|
)
|
|
''');
|
|
}
|
|
}
|