feat: integración cloud real — JWT auto-login, upload pedidos y sync
- tryAutoLogin: restaura sesión cloud y local desde SharedPreferences - uploadPedido: sube pedidos al gateway con toCloudEncabezado/Detalle - _uploadPendingPedidos: sube PENDIENTE en silencio al iniciar sesión - _syncCloudData: actualiza contadores itemsSynced/clientesSynced - loginLocal(): auth explícita sin cloud para el toggle "Cuenta local" - DB v2: migración onUpgrade agrega columna sync_estado, SHA-256 en passwords - Pedido.syncEstado: campo mutable PENDIENTE|SINCRONIZADO|ERROR - ItemPedido.toCloudDetalle() + Pedido.toCloudEncabezado(usuario) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
abe310699d
commit
eb081f3ea4
@@ -1,4 +1,6 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io' show Platform;
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:path/path.dart';
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
@@ -30,12 +32,24 @@ class DatabaseHelper {
|
||||
final path = join(dbPath, 'telcotronics.db');
|
||||
return databaseFactoryFfi.openDatabase(
|
||||
path,
|
||||
options: OpenDatabaseOptions(version: 1, onCreate: _createTables),
|
||||
options: OpenDatabaseOptions(
|
||||
version: 2,
|
||||
onCreate: _createTables,
|
||||
onUpgrade: _onUpgrade,
|
||||
),
|
||||
);
|
||||
}
|
||||
final dbPath = await getDatabasesPath();
|
||||
final path = join(dbPath, 'telcotronics.db');
|
||||
return openDatabase(path, version: 1, onCreate: _createTables);
|
||||
return openDatabase(path, version: 2,
|
||||
onCreate: _createTables, onUpgrade: _onUpgrade);
|
||||
}
|
||||
|
||||
Future<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
|
||||
if (oldVersion < 2) {
|
||||
await db.execute(
|
||||
"ALTER TABLE pedidos ADD COLUMN sync_estado TEXT NOT NULL DEFAULT 'PENDIENTE'");
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _createTables(Database db, int version) async {
|
||||
@@ -112,6 +126,7 @@ class DatabaseHelper {
|
||||
fecha TEXT NOT NULL,
|
||||
notas TEXT,
|
||||
firma_base64 TEXT,
|
||||
sync_estado TEXT NOT NULL DEFAULT 'PENDIENTE',
|
||||
FOREIGN KEY (cliente_id) REFERENCES clientes(id)
|
||||
)
|
||||
''');
|
||||
@@ -131,16 +146,50 @@ class DatabaseHelper {
|
||||
|
||||
// ── Usuarios ────────────────────────────────────────────────
|
||||
|
||||
static String _sha256(String input) =>
|
||||
sha256.convert(utf8.encode(input)).toString();
|
||||
|
||||
Future<void> insertUsuario(Vendedor v, String password) async {
|
||||
final db = await database;
|
||||
await db.insert('usuarios', {...v.toMap(), 'password': password},
|
||||
await db.insert('usuarios', {...v.toMap(), 'password': _sha256(password)},
|
||||
conflictAlgorithm: ConflictAlgorithm.ignore);
|
||||
}
|
||||
|
||||
/// Registra un usuario nuevo. Retorna false si el email ya existe.
|
||||
Future<bool> registerUsuario({
|
||||
required String nombre,
|
||||
required String email,
|
||||
required String telefono,
|
||||
required String empresa,
|
||||
required String ruc,
|
||||
required String password,
|
||||
}) async {
|
||||
final db = await database;
|
||||
final exists = await db.query('usuarios',
|
||||
where: 'email = ?', whereArgs: [email.toLowerCase()]);
|
||||
if (exists.isNotEmpty) return false;
|
||||
final id = 'local_${DateTime.now().millisecondsSinceEpoch}';
|
||||
await db.insert('usuarios', {
|
||||
'id': id,
|
||||
'nombre': nombre,
|
||||
'email': email.toLowerCase(),
|
||||
'telefono': telefono,
|
||||
'zona': empresa,
|
||||
'password': _sha256(password),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>?> loginUsuario(String email, String password) async {
|
||||
final db = await database;
|
||||
final rows = await db.query('usuarios',
|
||||
where: 'email = ? AND password = ?', whereArgs: [email, password]);
|
||||
// Acepta hash SHA-256 o texto plano (compatibilidad con seeder viejo)
|
||||
final hash = _sha256(password);
|
||||
var rows = await db.query('usuarios',
|
||||
where: 'email = ? AND password = ?', whereArgs: [email, hash]);
|
||||
if (rows.isEmpty) {
|
||||
rows = await db.query('usuarios',
|
||||
where: 'email = ? AND password = ?', whereArgs: [email, password]);
|
||||
}
|
||||
return rows.isEmpty ? null : rows.first;
|
||||
}
|
||||
|
||||
@@ -320,6 +369,7 @@ class DatabaseHelper {
|
||||
fecha: DateTime.parse(row['fecha'] as String),
|
||||
notas: row['notas'] as String? ?? '',
|
||||
firmaBase64: row['firma_base64'] as String?,
|
||||
syncEstado: row['sync_estado'] as String? ?? 'PENDIENTE',
|
||||
items: items,
|
||||
));
|
||||
}
|
||||
@@ -342,6 +392,12 @@ class DatabaseHelper {
|
||||
where: 'id = ?', whereArgs: [pedidoId]);
|
||||
}
|
||||
|
||||
Future<void> updateSyncEstadoPedido(String pedidoId, String syncEstado) async {
|
||||
final db = await database;
|
||||
await db.update('pedidos', {'sync_estado': syncEstado},
|
||||
where: 'id = ?', whereArgs: [pedidoId]);
|
||||
}
|
||||
|
||||
Future<void> updateFirmaPedido(String pedidoId, String firma) async {
|
||||
final db = await database;
|
||||
await db.update('pedidos', {'firma_base64': firma, 'estado': 'confirmado'},
|
||||
|
||||
Reference in New Issue
Block a user