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});
}
}
}
+35
View File
@@ -0,0 +1,35 @@
class Cliente {
final int? id;
final String nombre;
final String? telefono;
final String? email;
final String? direccion;
final bool sincronizado;
const Cliente({
this.id,
required this.nombre,
this.telefono,
this.email,
this.direccion,
this.sincronizado = false,
});
factory Cliente.fromMap(Map<String, dynamic> m) => Cliente(
id: m['id'] as int?,
nombre: m['nombre'] as String,
telefono: m['telefono'] as String?,
email: m['email'] as String?,
direccion: m['direccion'] as String?,
sincronizado: (m['sincronizado'] as int) == 1,
);
Map<String, dynamic> toMap() => {
if (id != null) 'id': id,
'nombre': nombre,
'telefono': telefono,
'email': email,
'direccion': direccion,
'sincronizado': sincronizado ? 1 : 0,
};
}
+67
View File
@@ -0,0 +1,67 @@
class Suscripcion {
final int? id;
final int clienteId;
final String nombreServicio;
final String tipo; // hogar / comercial / industrial
final String plan; // basico / estandar / premium
final String estado; // activa / suspendida / vencida / cancelada
final String fechaInicio;
final String fechaVencimiento;
final double monto;
final String moneda;
final String? notas;
final bool sincronizado;
const Suscripcion({
this.id,
required this.clienteId,
required this.nombreServicio,
required this.tipo,
required this.plan,
required this.estado,
required this.fechaInicio,
required this.fechaVencimiento,
required this.monto,
this.moneda = 'USD',
this.notas,
this.sincronizado = false,
});
factory Suscripcion.fromMap(Map<String, dynamic> m) => Suscripcion(
id: m['id'] as int?,
clienteId: m['cliente_id'] as int,
nombreServicio: m['nombre_servicio'] as String,
tipo: m['tipo'] as String,
plan: m['plan'] as String,
estado: m['estado'] as String,
fechaInicio: m['fecha_inicio'] as String,
fechaVencimiento: m['fecha_vencimiento'] as String,
monto: (m['monto'] as num).toDouble(),
moneda: m['moneda'] as String? ?? 'USD',
notas: m['notas'] as String?,
sincronizado: (m['sincronizado'] as int) == 1,
);
Map<String, dynamic> toMap() => {
if (id != null) 'id': id,
'cliente_id': clienteId,
'nombre_servicio': nombreServicio,
'tipo': tipo,
'plan': plan,
'estado': estado,
'fecha_inicio': fechaInicio,
'fecha_vencimiento': fechaVencimiento,
'monto': monto,
'moneda': moneda,
'notas': notas,
'sincronizado': sincronizado ? 1 : 0,
};
bool get vencida {
final venc = DateTime.tryParse(fechaVencimiento);
if (venc == null) return false;
return DateTime.now().isAfter(venc);
}
bool get activa => estado == 'activa' && !vencida;
}
+84
View File
@@ -1,6 +1,20 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
archive:
dependency: transitive
description:
name: archive
url: "https://pub.dartlang.org"
source: hosted
version: "3.4.2"
args:
dependency: transitive
description:
name: args
url: "https://pub.dartlang.org"
source: hosted
version: "2.3.1"
async:
dependency: transitive
description:
@@ -29,6 +43,20 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "1.3.1"
checked_yaml:
dependency: transitive
description:
name: checked_yaml
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.1"
cli_util:
dependency: transitive
description:
name: cli_util
url: "https://pub.dartlang.org"
source: hosted
version: "0.3.5"
clock:
dependency: transitive
description:
@@ -43,6 +71,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "1.15.0"
convert:
dependency: transitive
description:
name: convert
url: "https://pub.dartlang.org"
source: hosted
version: "3.1.0"
crypto:
dependency: "direct main"
description:
@@ -83,6 +118,13 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
flutter_launcher_icons:
dependency: "direct dev"
description:
name: flutter_launcher_icons
url: "https://pub.dartlang.org"
source: hosted
version: "0.11.0"
flutter_lints:
dependency: "direct dev"
description:
@@ -121,6 +163,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "4.0.2"
image:
dependency: transitive
description:
name: image
url: "https://pub.dartlang.org"
source: hosted
version: "3.1.3"
js:
dependency: transitive
description:
@@ -128,6 +177,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "0.6.4"
json_annotation:
dependency: transitive
description:
name: json_annotation
url: "https://pub.dartlang.org"
source: hosted
version: "4.6.0"
lints:
dependency: transitive
description:
@@ -212,6 +268,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.7"
petitparser:
dependency: transitive
description:
name: petitparser
url: "https://pub.dartlang.org"
source: hosted
version: "4.4.0"
platform:
dependency: transitive
description:
@@ -226,6 +289,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.3"
pointycastle:
dependency: transitive
description:
name: pointycastle
url: "https://pub.dartlang.org"
source: hosted
version: "3.7.3"
process:
dependency: transitive
description:
@@ -392,6 +462,20 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "0.2.0+3"
xml:
dependency: transitive
description:
name: xml
url: "https://pub.dartlang.org"
source: hosted
version: "5.3.1"
yaml:
dependency: transitive
description:
name: yaml
url: "https://pub.dartlang.org"
source: hosted
version: "3.1.1"
sdks:
dart: ">=2.17.0-69.2.beta <3.0.0"
flutter: ">=2.10.0"
+10 -4
View File
@@ -49,6 +49,14 @@ dev_dependencies:
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^1.0.0
flutter_launcher_icons: ^0.11.0
flutter_icons:
android: true
ios: true
image_path: "lib/recursos/logo_app.png"
adaptive_icon_background: "#0A0E14"
adaptive_icon_foreground: "lib/recursos/logo_app.png"
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
@@ -61,10 +69,8 @@ flutter:
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
assets:
- lib/recursos/logo_app.png
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.