feat: BD v2 — tablas clientes y suscripciones con migración

- BD versión 2 con onUpgrade automático desde v1
- Tabla clientes: nombre, teléfono, email, dirección
- Tabla suscripciones: cliente_id, servicio, tipo, plan, estado, fechas, monto
- Modelo Suscripcion con props calculadas vencida y activa
- SuscripcionesDao: getByCliente, getByEstado, getProximasAVencer, cambiarEstado
- Seed v2: 3 clientes y 5 suscripciones con estados variados

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Pablinux
2026-04-16 01:25:42 -05:00
co-authored by Claude Sonnet 4.6
parent 3e2294faf6
commit 4d3d298773
7 changed files with 444 additions and 7 deletions
+40
View File
@@ -0,0 +1,40 @@
import '../database_helper.dart';
import '../../models/cliente.dart';
class ClientesDao {
final _db = DatabaseHelper.instance;
Future<List<Cliente>> getAll() async {
final db = await _db.db;
final rows = await db.query('clientes', orderBy: 'nombre ASC');
return rows.map(Cliente.fromMap).toList();
}
Future<Cliente?> getById(int id) async {
final db = await _db.db;
final rows = await db.query('clientes', where: 'id = ?', whereArgs: [id]);
return rows.isEmpty ? null : Cliente.fromMap(rows.first);
}
Future<int> insert(Cliente c) async {
final db = await _db.db;
return db.insert('clientes', c.toMap());
}
Future<int> update(Cliente c) async {
final db = await _db.db;
return db.update('clientes', c.toMap(),
where: 'id = ?', whereArgs: [c.id]);
}
Future<int> delete(int id) async {
final db = await _db.db;
return db.delete('clientes', where: 'id = ?', whereArgs: [id]);
}
Future<List<Cliente>> getPendientes() async {
final db = await _db.db;
final rows = await db.query('clientes', where: 'sincronizado = 0');
return rows.map(Cliente.fromMap).toList();
}
}
+87
View File
@@ -0,0 +1,87 @@
import '../database_helper.dart';
import '../../models/suscripcion.dart';
class SuscripcionesDao {
final _db = DatabaseHelper.instance;
Future<List<Suscripcion>> getAll() async {
final db = await _db.db;
final rows = await db.query('suscripciones', orderBy: 'fecha_vencimiento ASC');
return rows.map(Suscripcion.fromMap).toList();
}
Future<List<Suscripcion>> getByCliente(int clienteId) async {
final db = await _db.db;
final rows = await db.query(
'suscripciones',
where: 'cliente_id = ?',
whereArgs: [clienteId],
orderBy: 'fecha_vencimiento ASC',
);
return rows.map(Suscripcion.fromMap).toList();
}
Future<List<Suscripcion>> getByEstado(String estado) async {
final db = await _db.db;
final rows = await db.query(
'suscripciones',
where: 'estado = ?',
whereArgs: [estado],
orderBy: 'fecha_vencimiento ASC',
);
return rows.map(Suscripcion.fromMap).toList();
}
/// Suscripciones próximas a vencer (dentro de N días)
Future<List<Suscripcion>> getProximasAVencer({int dias = 7}) async {
final db = await _db.db;
final limite = DateTime.now().add(Duration(days: dias)).toIso8601String();
final hoy = DateTime.now().toIso8601String();
final rows = await db.query(
'suscripciones',
where: "estado = 'activa' AND fecha_vencimiento <= ? AND fecha_vencimiento >= ?",
whereArgs: [limite, hoy],
orderBy: 'fecha_vencimiento ASC',
);
return rows.map(Suscripcion.fromMap).toList();
}
Future<Suscripcion?> getById(int id) async {
final db = await _db.db;
final rows = await db.query('suscripciones',
where: 'id = ?', whereArgs: [id]);
return rows.isEmpty ? null : Suscripcion.fromMap(rows.first);
}
Future<int> insert(Suscripcion s) async {
final db = await _db.db;
return db.insert('suscripciones', s.toMap());
}
Future<int> update(Suscripcion s) async {
final db = await _db.db;
return db.update('suscripciones', s.toMap(),
where: 'id = ?', whereArgs: [s.id]);
}
Future<int> cambiarEstado(int id, String nuevoEstado) async {
final db = await _db.db;
return db.update(
'suscripciones',
{'estado': nuevoEstado, 'sincronizado': 0},
where: 'id = ?',
whereArgs: [id],
);
}
Future<int> delete(int id) async {
final db = await _db.db;
return db.delete('suscripciones', where: 'id = ?', whereArgs: [id]);
}
Future<List<Suscripcion>> getPendientes() async {
final db = await _db.db;
final rows = await db.query('suscripciones', where: 'sincronizado = 0');
return rows.map(Suscripcion.fromMap).toList();
}
}
+121 -3
View File
@@ -5,7 +5,7 @@ import 'package:path/path.dart';
class DatabaseHelper {
static const _dbName = 'sentinel_one.db';
static const _dbVersion = 1;
static const _dbVersion = 2;
DatabaseHelper._();
static final DatabaseHelper instance = DatabaseHelper._();
@@ -27,12 +27,22 @@ class DatabaseHelper {
Future<Database> _initDb() async {
if (Platform.isLinux || Platform.isWindows) {
sqfliteFfiInit();
final dbPath = join(Directory.current.path, _dbName);
final String dbDir;
if (Platform.isLinux) {
final home = Platform.environment['HOME'] ?? Directory.current.path;
final dir = Directory(join(home, '.local', 'share', 'sentinel_one'));
if (!dir.existsSync()) dir.createSync(recursive: true);
dbDir = dir.path;
} else {
// Windows: junto al ejecutable
dbDir = Directory.current.path;
}
return databaseFactoryFfi.openDatabase(
dbPath,
join(dbDir, _dbName),
options: OpenDatabaseOptions(
version: _dbVersion,
onCreate: _onCreate,
onUpgrade: _onUpgrade,
),
);
}
@@ -41,6 +51,7 @@ class DatabaseHelper {
path,
version: _dbVersion,
onCreate: _onCreate,
onUpgrade: _onUpgrade,
);
}
@@ -190,9 +201,52 @@ class DatabaseHelper {
)
''');
await _createTablesV2(db);
await _seedData(db);
}
Future<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
if (oldVersion < 2) {
await _createTablesV2(db);
await _seedDataV2(db);
}
}
Future<void> _createTablesV2(Database db) async {
await db.execute('''
CREATE TABLE IF NOT EXISTS clientes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
nombre TEXT NOT NULL,
telefono TEXT,
email TEXT,
direccion TEXT,
sincronizado INTEGER NOT NULL DEFAULT 0
)
''');
await db.execute('''
CREATE TABLE IF NOT EXISTS suscripciones (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cliente_id INTEGER NOT NULL,
nombre_servicio TEXT NOT NULL,
tipo TEXT NOT NULL DEFAULT 'hogar',
plan TEXT NOT NULL DEFAULT 'basico',
estado TEXT NOT NULL DEFAULT 'activa',
fecha_inicio TEXT NOT NULL,
fecha_vencimiento TEXT NOT NULL,
monto REAL NOT NULL DEFAULT 0.0,
moneda TEXT NOT NULL DEFAULT 'USD',
notas TEXT,
sincronizado INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY (cliente_id) REFERENCES clientes(id)
)
''');
}
Future<void> _seedDataV2(Database db) async {
await _seedClientes(db);
}
// ─── Datos iniciales ──────────────────────────────────────────────────────
// PIN de seed: 123456 → SHA-256 hash real generado externamente
// echo -n "123456" | sha256sum → 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
@@ -408,5 +462,69 @@ class DatabaseHelper {
for (final c in config) {
await db.insert('configuracion', c);
}
await _seedClientes(db);
}
Future<void> _seedClientes(Database db) async {
final hoy = DateTime.now();
// ── Clientes de ejemplo ──
final clientes = [
{'id': 1, 'nombre': 'Pedro García', 'telefono': '5551-0001',
'email': 'pedro@email.com', 'direccion': 'Zona 10, Ciudad'},
{'id': 2, 'nombre': 'Empresa XYZ S.A.', 'telefono': '5552-0002',
'email': 'admin@xyz.com', 'direccion': 'Zona 4, Ciudad'},
{'id': 3, 'nombre': 'María López', 'telefono': '5553-0003',
'email': 'maria@email.com', 'direccion': 'Zona 15, Ciudad'},
];
for (final c in clientes) {
await db.insert('clientes', {...c, 'sincronizado': 1});
}
// ── Suscripciones de ejemplo ──
final suscripciones = [
// Pedro García — Casa activa, Negocio próximo a vencer
{
'cliente_id': 1, 'nombre_servicio': 'Casa Principal',
'tipo': 'hogar', 'plan': 'premium', 'estado': 'activa',
'fecha_inicio': hoy.subtract(const Duration(days: 180)).toIso8601String().substring(0, 10),
'fecha_vencimiento': hoy.add(const Duration(days: 30)).toIso8601String().substring(0, 10),
'monto': 49.99, 'moneda': 'USD', 'notas': null,
},
{
'cliente_id': 1, 'nombre_servicio': 'Negocio Centro',
'tipo': 'comercial', 'plan': 'estandar', 'estado': 'activa',
'fecha_inicio': hoy.subtract(const Duration(days: 90)).toIso8601String().substring(0, 10),
'fecha_vencimiento': hoy.add(const Duration(days: 5)).toIso8601String().substring(0, 10),
'monto': 35.00, 'moneda': 'USD', 'notas': 'Próximo a vencer',
},
// Empresa XYZ — Activa y suspendida
{
'cliente_id': 2, 'nombre_servicio': 'Oficinas Principales',
'tipo': 'comercial', 'plan': 'premium', 'estado': 'activa',
'fecha_inicio': hoy.subtract(const Duration(days: 365)).toIso8601String().substring(0, 10),
'fecha_vencimiento': hoy.add(const Duration(days: 60)).toIso8601String().substring(0, 10),
'monto': 120.00, 'moneda': 'USD', 'notas': null,
},
{
'cliente_id': 2, 'nombre_servicio': 'Bodega Norte',
'tipo': 'industrial', 'plan': 'basico', 'estado': 'suspendida',
'fecha_inicio': hoy.subtract(const Duration(days: 200)).toIso8601String().substring(0, 10),
'fecha_vencimiento': hoy.subtract(const Duration(days: 10)).toIso8601String().substring(0, 10),
'monto': 20.00, 'moneda': 'USD', 'notas': 'Suspendida por falta de pago',
},
// María López — Vencida
{
'cliente_id': 3, 'nombre_servicio': 'Residencia',
'tipo': 'hogar', 'plan': 'basico', 'estado': 'vencida',
'fecha_inicio': hoy.subtract(const Duration(days: 400)).toIso8601String().substring(0, 10),
'fecha_vencimiento': hoy.subtract(const Duration(days: 30)).toIso8601String().substring(0, 10),
'monto': 15.00, 'moneda': 'USD', 'notas': null,
},
];
for (final s in suscripciones) {
await db.insert('suscripciones', {...s, 'sincronizado': 1});
}
}
}