feat: add SQLite data layer, local auth and security settings
- Add offline-first SQLite architecture with DatabaseHelper singleton, 12 CREATE TABLE statements and full seed data on first launch - Add 10 models (fromMap/toMap) and 12 DAOs with CRUD + getPendientes() - Add ApiAuthService (JWT via SharedPreferences) and Sincronizador skeleton - Move login auth from SQLite to SharedPreferences with SHA-256 PIN hash; default PIN 123456, platform-independent (no native plugin required) - Add seguridad_page.dart: change PIN form (current → new → confirm) - Add Cerrar Sesión with confirmation dialog and full stack clear - Redesign settings_page.dart with AppColors dark theme; add Sistema section with "Inicializar base de datos" and "Inicializar sincronización" - Fix Linux desktop: sqflite_common_ffi with platform detection in DatabaseHelper - Fix ScrollController conflict on Linux: primary: false on all IndexedStack pages - Update plan_proyecto.md with session 2–3 progress and auth roadmap Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
8f13d57839
commit
1184ab5fe2
@@ -0,0 +1,246 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'api_auth_service.dart';
|
||||
import '../db/dao/alarmas_dao.dart';
|
||||
import '../db/dao/accesos_dao.dart';
|
||||
import '../db/dao/usuarios_dao.dart';
|
||||
import '../db/dao/zonas_dao.dart';
|
||||
import '../db/dao/mensajes_dao.dart';
|
||||
import '../db/dao/banners_dao.dart';
|
||||
import '../db/dao/sync_log_dao.dart';
|
||||
import '../db/dao/configuracion_dao.dart';
|
||||
import '../models/alarma.dart';
|
||||
import '../models/acceso.dart';
|
||||
import '../models/usuario.dart';
|
||||
import '../models/zona.dart';
|
||||
import '../models/mensaje.dart';
|
||||
import '../models/banner_item.dart';
|
||||
|
||||
/// Orquesta la sincronización entre la API y SQLite.
|
||||
/// Las páginas nunca llaman a la API directamente — solo leen SQLite.
|
||||
class Sincronizador {
|
||||
Sincronizador._();
|
||||
static final Sincronizador instance = Sincronizador._();
|
||||
|
||||
final _auth = ApiAuthService.instance;
|
||||
final _syncLog = SyncLogDao();
|
||||
final _config = ConfiguracionDao();
|
||||
|
||||
// ── Punto de entrada principal ─────────────────────────────────────────────
|
||||
Future<void> sincronizar() async {
|
||||
final autenticado = await _auth.isAuthenticated();
|
||||
if (!autenticado) {
|
||||
await _syncLog.registrar(
|
||||
tipo: 'full',
|
||||
estado: 'error',
|
||||
detalle: 'Sin token válido — sincronización omitida',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await sincronizarZonas();
|
||||
await sincronizarUsuarios();
|
||||
await sincronizarAlarmas();
|
||||
await sincronizarAccesos();
|
||||
await sincronizarMensajes();
|
||||
await sincronizarBanners();
|
||||
await pushPendientes();
|
||||
|
||||
await _syncLog.registrar(
|
||||
tipo: 'full',
|
||||
estado: 'ok',
|
||||
detalle: 'Sincronización completa',
|
||||
);
|
||||
} catch (e) {
|
||||
await _syncLog.registrar(
|
||||
tipo: 'full',
|
||||
estado: 'error',
|
||||
detalle: e.toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Métodos específicos ────────────────────────────────────────────────────
|
||||
|
||||
Future<void> sincronizarZonas() async {
|
||||
final data = await _get('/zonas');
|
||||
if (data == null) return;
|
||||
final dao = ZonasDao();
|
||||
for (final item in data) {
|
||||
final z = Zona.fromMap({...item, 'sincronizado': 1});
|
||||
final existente = await dao.getById(z.id);
|
||||
if (existente == null) {
|
||||
await dao.insert(z);
|
||||
} else {
|
||||
await dao.update(z);
|
||||
}
|
||||
}
|
||||
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
||||
detalle: 'zonas: ${data.length} registros');
|
||||
}
|
||||
|
||||
Future<void> sincronizarUsuarios() async {
|
||||
final data = await _get('/usuarios');
|
||||
if (data == null) return;
|
||||
final dao = UsuariosDao();
|
||||
for (final item in data) {
|
||||
final u = Usuario.fromMap({...item, 'sincronizado': 1});
|
||||
final existente = await dao.getById(u.id);
|
||||
if (existente == null) {
|
||||
await dao.insert(u);
|
||||
} else {
|
||||
await dao.update(u);
|
||||
}
|
||||
}
|
||||
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
||||
detalle: 'usuarios: ${data.length} registros');
|
||||
}
|
||||
|
||||
Future<void> sincronizarAlarmas() async {
|
||||
final data = await _get('/alarmas');
|
||||
if (data == null) return;
|
||||
final dao = AlarmasDao();
|
||||
for (final item in data) {
|
||||
final a = Alarma.fromMap({...item, 'sincronizado': 1});
|
||||
final existente = await dao.getById(a.id);
|
||||
if (existente == null) {
|
||||
await dao.insert(a);
|
||||
} else {
|
||||
await dao.update(a);
|
||||
}
|
||||
}
|
||||
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
||||
detalle: 'alarmas: ${data.length} registros');
|
||||
}
|
||||
|
||||
Future<void> sincronizarAccesos() async {
|
||||
final data = await _get('/accesos');
|
||||
if (data == null) return;
|
||||
final dao = AccesosDao();
|
||||
for (final item in data) {
|
||||
final a = Acceso.fromMap({...item, 'sincronizado': 1});
|
||||
await dao.insert(a);
|
||||
}
|
||||
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
||||
detalle: 'accesos: ${data.length} registros');
|
||||
}
|
||||
|
||||
Future<void> sincronizarMensajes() async {
|
||||
final data = await _get('/mensajes');
|
||||
if (data == null) return;
|
||||
final dao = MensajesDao();
|
||||
for (final item in data) {
|
||||
final m = Mensaje.fromMap({...item, 'sincronizado': 1});
|
||||
await dao.insert(m);
|
||||
}
|
||||
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
||||
detalle: 'mensajes: ${data.length} registros');
|
||||
}
|
||||
|
||||
Future<void> sincronizarBanners() async {
|
||||
final data = await _get('/banners');
|
||||
if (data == null) return;
|
||||
final dao = BannersDao();
|
||||
for (final item in data) {
|
||||
final b = BannerItem.fromMap({...item, 'sincronizado': 1});
|
||||
final existente = await dao.getById(b.id);
|
||||
if (existente == null) {
|
||||
await dao.insert(b);
|
||||
} else {
|
||||
await dao.update(b);
|
||||
}
|
||||
}
|
||||
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
||||
detalle: 'banners: ${data.length} registros');
|
||||
}
|
||||
|
||||
// ── Push de pendientes (local → API) ───────────────────────────────────────
|
||||
Future<void> pushPendientes() async {
|
||||
await _pushAlarmasPendientes();
|
||||
await _pushAccesosPendientes();
|
||||
await _pushMensajesPendientes();
|
||||
await _syncLog.registrar(tipo: 'push', estado: 'ok',
|
||||
detalle: 'Push de pendientes completado');
|
||||
}
|
||||
|
||||
Future<void> _pushAlarmasPendientes() async {
|
||||
final pendientes = await AlarmasDao().getPendientes();
|
||||
if (pendientes.isEmpty) return;
|
||||
final baseUrl = await _config.get('api_base_url') ?? '';
|
||||
final token = await _auth.getToken();
|
||||
if (baseUrl.isEmpty || token == null) return;
|
||||
for (final a in pendientes) {
|
||||
try {
|
||||
await http.put(
|
||||
Uri.parse('$baseUrl/alarmas/${a.id}'),
|
||||
headers: _headers(token),
|
||||
body: jsonEncode(a.toMap()),
|
||||
).timeout(const Duration(seconds: 8));
|
||||
} catch (_) {
|
||||
// Continúa con el siguiente — se reintentará en el próximo ciclo
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _pushAccesosPendientes() async {
|
||||
final pendientes = await AccesosDao().getPendientes();
|
||||
if (pendientes.isEmpty) return;
|
||||
final baseUrl = await _config.get('api_base_url') ?? '';
|
||||
final token = await _auth.getToken();
|
||||
if (baseUrl.isEmpty || token == null) return;
|
||||
for (final a in pendientes) {
|
||||
try {
|
||||
await http.post(
|
||||
Uri.parse('$baseUrl/accesos'),
|
||||
headers: _headers(token),
|
||||
body: jsonEncode(a.toMap()),
|
||||
).timeout(const Duration(seconds: 8));
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _pushMensajesPendientes() async {
|
||||
final pendientes = await MensajesDao().getPendientes();
|
||||
if (pendientes.isEmpty) return;
|
||||
final baseUrl = await _config.get('api_base_url') ?? '';
|
||||
final token = await _auth.getToken();
|
||||
if (baseUrl.isEmpty || token == null) return;
|
||||
for (final m in pendientes) {
|
||||
try {
|
||||
await http.post(
|
||||
Uri.parse('$baseUrl/mensajes'),
|
||||
headers: _headers(token),
|
||||
body: jsonEncode(m.toMap()),
|
||||
).timeout(const Duration(seconds: 8));
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────
|
||||
Future<List<Map<String, dynamic>>?> _get(String endpoint) async {
|
||||
final baseUrl = await _config.get('api_base_url') ?? '';
|
||||
final token = await _auth.getToken();
|
||||
if (baseUrl.isEmpty || token == null) return null;
|
||||
|
||||
try {
|
||||
final resp = await http.get(
|
||||
Uri.parse('$baseUrl$endpoint'),
|
||||
headers: _headers(token),
|
||||
).timeout(const Duration(seconds: 10));
|
||||
|
||||
if (resp.statusCode == 200) {
|
||||
final body = jsonDecode(resp.body);
|
||||
if (body is List) return body.cast<Map<String, dynamic>>();
|
||||
}
|
||||
return null;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, String> _headers(String token) => {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer $token',
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user