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:
Pablinux
2026-06-17 09:26:59 -05:00
co-authored by Claude Sonnet 4.6
parent abe310699d
commit eb081f3ea4
6 changed files with 324 additions and 35 deletions
+60 -4
View File
@@ -1,4 +1,6 @@
import 'dart:convert';
import 'dart:io' show Platform; import 'dart:io' show Platform;
import 'package:crypto/crypto.dart';
import 'package:path/path.dart'; import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart'; import 'package:sqflite/sqflite.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart'; import 'package:sqflite_common_ffi/sqflite_ffi.dart';
@@ -30,12 +32,24 @@ class DatabaseHelper {
final path = join(dbPath, 'telcotronics.db'); final path = join(dbPath, 'telcotronics.db');
return databaseFactoryFfi.openDatabase( return databaseFactoryFfi.openDatabase(
path, path,
options: OpenDatabaseOptions(version: 1, onCreate: _createTables), options: OpenDatabaseOptions(
version: 2,
onCreate: _createTables,
onUpgrade: _onUpgrade,
),
); );
} }
final dbPath = await getDatabasesPath(); final dbPath = await getDatabasesPath();
final path = join(dbPath, 'telcotronics.db'); 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 { Future<void> _createTables(Database db, int version) async {
@@ -112,6 +126,7 @@ class DatabaseHelper {
fecha TEXT NOT NULL, fecha TEXT NOT NULL,
notas TEXT, notas TEXT,
firma_base64 TEXT, firma_base64 TEXT,
sync_estado TEXT NOT NULL DEFAULT 'PENDIENTE',
FOREIGN KEY (cliente_id) REFERENCES clientes(id) FOREIGN KEY (cliente_id) REFERENCES clientes(id)
) )
'''); ''');
@@ -131,16 +146,50 @@ class DatabaseHelper {
// ── Usuarios ──────────────────────────────────────────────── // ── Usuarios ────────────────────────────────────────────────
static String _sha256(String input) =>
sha256.convert(utf8.encode(input)).toString();
Future<void> insertUsuario(Vendedor v, String password) async { Future<void> insertUsuario(Vendedor v, String password) async {
final db = await database; final db = await database;
await db.insert('usuarios', {...v.toMap(), 'password': password}, await db.insert('usuarios', {...v.toMap(), 'password': _sha256(password)},
conflictAlgorithm: ConflictAlgorithm.ignore); 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 { Future<Map<String, dynamic>?> loginUsuario(String email, String password) async {
final db = await database; final db = await database;
final rows = await db.query('usuarios', // 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]); where: 'email = ? AND password = ?', whereArgs: [email, password]);
}
return rows.isEmpty ? null : rows.first; return rows.isEmpty ? null : rows.first;
} }
@@ -320,6 +369,7 @@ class DatabaseHelper {
fecha: DateTime.parse(row['fecha'] as String), fecha: DateTime.parse(row['fecha'] as String),
notas: row['notas'] as String? ?? '', notas: row['notas'] as String? ?? '',
firmaBase64: row['firma_base64'] as String?, firmaBase64: row['firma_base64'] as String?,
syncEstado: row['sync_estado'] as String? ?? 'PENDIENTE',
items: items, items: items,
)); ));
} }
@@ -342,6 +392,12 @@ class DatabaseHelper {
where: 'id = ?', whereArgs: [pedidoId]); 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 { Future<void> updateFirmaPedido(String pedidoId, String firma) async {
final db = await database; final db = await database;
await db.update('pedidos', {'firma_base64': firma, 'estado': 'confirmado'}, await db.update('pedidos', {'firma_base64': firma, 'estado': 'confirmado'},
+6 -3
View File
@@ -17,13 +17,16 @@ void main() async {
)); ));
final notifService = NotificationService(navigatorKey: _navigatorKey); final notifService = NotificationService(navigatorKey: _navigatorKey);
final appProvider = AppProvider(notifService: notifService);
// Fire-and-forget: restaura sesión guardada si existe JWT válido.
// AppProvider._loading se activa internamente, la UI muestra _LoadingScreen.
appProvider.tryAutoLogin();
runApp( runApp(
MultiProvider( MultiProvider(
providers: [ providers: [
ChangeNotifierProvider( ChangeNotifierProvider.value(value: appProvider),
create: (_) => AppProvider(notifService: notifService),
),
ChangeNotifierProvider.value(value: notifService), ChangeNotifierProvider.value(value: notifService),
], ],
child: PedidosApp(navigatorKey: _navigatorKey), child: PedidosApp(navigatorKey: _navigatorKey),
+9
View File
@@ -22,4 +22,13 @@ class ItemPedido {
'cantidad': cantidad, 'cantidad': cantidad,
'precio_unitario': precioUnitario, 'precio_unitario': precioUnitario,
}; };
/// Payload de un ítem para POST /api/documentos/pedidos — campo names del gateway.
Map<String, dynamic> toCloudDetalle() => {
'PedUsoPrdctDet_codigoProducto': producto.sku,
'PedUsoPrdct_cant': cantidad.toDouble(),
'PedUsoPrdct_costo': precioUnitario,
'PedUsoPrdct_desct': 0.0,
'PedUsoPrdct_iva': 0.0,
};
} }
+21
View File
@@ -31,6 +31,7 @@ class Pedido {
final DateTime fecha; final DateTime fecha;
String notas; String notas;
String? firmaBase64; String? firmaBase64;
String syncEstado; // 'PENDIENTE' | 'SINCRONIZADO' | 'ERROR'
Pedido({ Pedido({
required this.id, required this.id,
@@ -40,6 +41,7 @@ class Pedido {
required this.fecha, required this.fecha,
this.notas = '', this.notas = '',
this.firmaBase64, this.firmaBase64,
this.syncEstado = 'PENDIENTE',
}); });
double get subtotal => items.fold(0, (s, i) => s + i.subtotal); double get subtotal => items.fold(0, (s, i) => s + i.subtotal);
@@ -53,5 +55,24 @@ class Pedido {
'fecha': fecha.toIso8601String(), 'fecha': fecha.toIso8601String(),
'notas': notas, 'notas': notas,
'firma_base64': firmaBase64, 'firma_base64': firmaBase64,
'sync_estado': syncEstado,
}; };
/// Payload para POST /api/documentos/pedidos — campo names del gateway SIGMA.
/// El número es el sufijo numérico del id local (TTC-0001 → 1).
Map<String, dynamic> toCloudEncabezado(String usuario) {
final num = int.tryParse(id.replaceAll(RegExp(r'[^0-9]'), '')) ?? 0;
return {
'PedUsoPrdct_Num': num,
'PedUsoPrdct_idClient': cliente.nit.isNotEmpty ? cliente.nit : cliente.id,
'PedUsoPrdct_reg': fecha.toIso8601String(),
'PedUsoPrdct_estado': 'PENDIENTE',
'PedUsoPrdct_plataforma': 'AGENTE_VENTAS',
'PedUsoPrdct_usuario': usuario,
'PedUsoPrdct_valor': total,
'PedUsoPrdct_iva': 0.0,
'PedUsoPrdct_origen': 'app',
'PedUsoPrdct_OBSERVACION': notas,
};
}
} }
+192 -20
View File
@@ -1,4 +1,5 @@
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../database/database_helper.dart'; import '../database/database_helper.dart';
import '../database/db_seeder.dart'; import '../database/db_seeder.dart';
import '../models/vendedor.dart'; import '../models/vendedor.dart';
@@ -21,6 +22,7 @@ class AppProvider extends ChangeNotifier {
// ── Estado de sesión ───────────────────────────────────────── // ── Estado de sesión ─────────────────────────────────────────
bool _isLoggedIn = false; bool _isLoggedIn = false;
bool _loading = false; bool _loading = false;
bool _autoLoginAttempted = false;
String? _loginError; String? _loginError;
Vendedor? _vendedor; Vendedor? _vendedor;
@@ -29,6 +31,10 @@ class AppProvider extends ChangeNotifier {
String _apiKey = ''; String _apiKey = '';
String _dbTenant = ''; String _dbTenant = '';
bool _modoOnline = false; bool _modoOnline = false;
// Contadores de última sincronización
int _itemsSynced = 0;
int _clientesSynced = 0;
Ruta? _ruta; Ruta? _ruta;
List<Pedido> _pedidos = []; List<Pedido> _pedidos = [];
List<Producto> _productos = []; List<Producto> _productos = [];
@@ -51,6 +57,11 @@ class AppProvider extends ChangeNotifier {
String get jwt => _jwt; String get jwt => _jwt;
String get apiKey => _apiKey; String get apiKey => _apiKey;
String get dbTenant => _dbTenant; String get dbTenant => _dbTenant;
int get itemsSynced => _itemsSynced;
int get clientesSynced => _clientesSynced;
int get pedidosPendientesSync =>
_pedidos.where((p) => p.syncEstado == 'PENDIENTE').length;
Vendedor get vendedor => _vendedor!; Vendedor get vendedor => _vendedor!;
Ruta get ruta => _ruta!; Ruta get ruta => _ruta!;
@@ -83,44 +94,120 @@ class AppProvider extends ChangeNotifier {
p.estado != EstadoPedido.cancelado; p.estado != EstadoPedido.cancelado;
}).fold(0, (s, p) => s + p.total); }).fold(0, (s, p) => s + p.total);
// ── Auto-login ───────────────────────────────────────────────
/// Intenta restaurar la sesión guardada al abrir la app.
/// Mismo patrón que sigmac_app/login_screen.dart → _checkAutoLogin().
/// Se llama una sola vez desde main() antes de runApp().
Future<void> tryAutoLogin() async {
if (_autoLoginAttempted || _isLoggedIn) return;
_autoLoginAttempted = true;
_loading = true;
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
final remember = prefs.getBool('pref_remember_me') ?? false;
final usuario = prefs.getString('auth_usuario') ?? '';
if (!remember || usuario.isEmpty) { _loading = false; notifyListeners(); return; }
final esCloud = prefs.getBool('auth_es_cloud') ?? false;
final nombre = prefs.getString('auth_nombre') ?? '';
final email = prefs.getString('auth_email') ?? '';
final empresa = prefs.getString('auth_empresa') ?? '';
if (!esCloud) {
// Sesión local guardada — restaurar sin validar JWT
if (empresa.isEmpty) { _loading = false; notifyListeners(); return; }
_modoOnline = false;
final displayName = nombre.isNotEmpty ? nombre : usuario;
final initials = _buildInitials(displayName, email);
_vendedor = Vendedor(
id: usuario, nombre: displayName, email: email,
telefono: '', zona: '',
avatarInitials: initials,
);
final seeded = await _db.isSeeded();
if (!seeded) await DbSeeder(_db).seed();
await _loadAllData();
_isLoggedIn = true;
_loading = false;
notifyListeners();
return;
}
final token = prefs.getString('auth_token') ?? '';
final apiKey = prefs.getString('auth_api_key') ?? '';
if (!AuthService.isJwtVigente(token)) {
await AuthService.clearSession();
_loading = false;
notifyListeners();
return;
}
if (empresa.isEmpty) { _loading = false; notifyListeners(); return; }
_jwt = token;
_apiKey = apiKey;
_dbTenant = empresa;
_modoOnline = true;
final displayName = nombre.isNotEmpty ? nombre : usuario;
_vendedor = Vendedor(
id: usuario, nombre: displayName, email: email,
telefono: '', zona: '',
avatarInitials: _buildInitials(displayName, email),
);
final seeded = await _db.isSeeded();
if (!seeded) await DbSeeder(_db).seed();
await _syncCloudData();
await _loadAllData();
await _uploadPendingPedidos();
_isLoggedIn = true;
} catch (e) {
debugPrint('[AutoLogin] error: $e');
}
_loading = false;
notifyListeners();
}
// ── Login / Logout ─────────────────────────────────────────── // ── Login / Logout ───────────────────────────────────────────
Future<bool> login(String email, String password) async { Future<bool> login(String email, String password,
{bool rememberMe = true}) async {
_loginError = null; _loginError = null;
_loading = true; _loading = true;
notifyListeners(); notifyListeners();
try { try {
// 1. Autenticación real: POST https://api.siax-system.net/api/auth/login
// Body: {email, paswd} — campo es "paswd" (igual que sigmac_app)
final session = await AuthService.login(email.trim(), password); final session = await AuthService.login(email.trim(), password);
if (session != null) { if (session != null) {
// Auth cloud exitosa — guardar tokens en SharedPreferences await AuthService.saveSession(session, email.trim(),
await AuthService.saveSession(session, email.trim()); rememberMe: rememberMe);
_apiKey = session.apiKey; _apiKey = session.apiKey;
_dbTenant = session.dbTenant; _dbTenant = session.dbTenant;
_jwt = session.token; _jwt = session.token;
_modoOnline = true; _modoOnline = true;
// Construir Vendedor desde los datos de sesión
_vendedor = _vendedorFromSession(session, email.trim()); _vendedor = _vendedorFromSession(session, email.trim());
// Seed demo si la BD está vacía (primer uso)
final seeded = await _db.isSeeded(); final seeded = await _db.isSeeded();
if (!seeded) await DbSeeder(_db).seed(); if (!seeded) await DbSeeder(_db).seed();
// Sincronizar catálogo y clientes desde API-SIGMA-CLOUD
await _syncCloudData(); await _syncCloudData();
await _loadAllData(); await _loadAllData();
await _uploadPendingPedidos();
_loading = false; _loading = false;
_isLoggedIn = true; _isLoggedIn = true;
notifyListeners(); notifyListeners();
return true; return true;
} }
// 2. Fallback offline — API no respondió (timeout / sin red) // Fallback offline — sin red o timeout
final seeded = await _db.isSeeded(); final seeded = await _db.isSeeded();
if (!seeded) await DbSeeder(_db).seed(); if (!seeded) await DbSeeder(_db).seed();
@@ -147,12 +234,59 @@ class AppProvider extends ChangeNotifier {
} }
} }
/// Login exclusivamente local — sin intentar cloud.
/// Usado cuando el toggle está en "Cuenta local".
Future<bool> loginLocal(String usuario, String password,
{bool rememberMe = true}) async {
_loginError = null;
_loading = true;
notifyListeners();
try {
final seeded = await _db.isSeeded();
if (!seeded) await DbSeeder(_db).seed();
final row = await _db.loginUsuario(usuario.trim(), password);
if (row == null) {
_loginError = 'Usuario o contraseña incorrectos';
_loading = false;
notifyListeners();
return false;
}
_vendedor = Vendedor.fromMap(row);
_modoOnline = false;
await AuthService.saveLocalSession(
usuario: _vendedor!.id,
nombre: _vendedor!.nombre,
email: _vendedor!.email,
empresa: 'local',
rol: 'vendedor',
rememberMe: rememberMe,
);
await _loadAllData();
_loading = false;
_isLoggedIn = true;
notifyListeners();
return true;
} catch (e) {
_loginError = 'Error inesperado: $e';
_loading = false;
notifyListeners();
return false;
}
}
/// Sincroniza items y clientes desde API-SIGMA-CLOUD hacia SQLite local. /// Sincroniza items y clientes desde API-SIGMA-CLOUD hacia SQLite local.
/// Si falla el sync (sin red, error API) no interrumpe el login — la app /// Si falla el sync (sin red, error API) no interrumpe el login — la app
/// continúa con los datos locales que ya tenga en SQLite. /// continúa con los datos locales que ya tenga en SQLite.
Future<void> _syncCloudData() async { Future<void> _syncCloudData() async {
_itemsSynced = 0;
_clientesSynced = 0;
try { try {
// Sync catálogo
final items = await CloudSyncService.downloadItems(); final items = await CloudSyncService.downloadItems();
for (final item in items) { for (final item in items) {
final productoExistente = await _db.getProductoBySku(item.codigo); final productoExistente = await _db.getProductoBySku(item.codigo);
@@ -164,20 +298,19 @@ class AppProvider extends ChangeNotifier {
categoria: item.grupo, categoria: item.grupo,
unidad: item.unidad, unidad: item.unidad,
stock: item.stock.toInt(), stock: item.stock.toInt(),
// Preservar precio local si el producto ya existe; 0.0 si es nuevo
precio: productoExistente?.precio ?? 0.0, precio: productoExistente?.precio ?? 0.0,
precioMayorista: productoExistente?.precioMayorista ?? 0.0, precioMayorista: productoExistente?.precioMayorista ?? 0.0,
emoji: productoExistente?.emoji ?? '📦', emoji: productoExistente?.emoji ?? '📦',
); );
await _db.insertProducto(p); // ConflictAlgorithm.replace await _db.insertProducto(p);
} }
_itemsSynced = items.length;
debugPrint('[Sync] items: ${items.length}'); debugPrint('[Sync] items: ${items.length}');
} catch (e) { } catch (e) {
debugPrint('[Sync] items error: $e'); debugPrint('[Sync] items error: $e');
} }
try { try {
// Sync clientes
final clientes = await CloudSyncService.downloadClientes(); final clientes = await CloudSyncService.downloadClientes();
for (final c in clientes) { for (final c in clientes) {
final cliente = Cliente( final cliente = Cliente(
@@ -191,29 +324,56 @@ class AppProvider extends ChangeNotifier {
lng: 0.0, lng: 0.0,
categoria: 'Cliente', categoria: 'Cliente',
); );
await _db.insertCliente(cliente); // ConflictAlgorithm.replace await _db.insertCliente(cliente);
} }
_clientesSynced = clientes.length;
debugPrint('[Sync] clientes: ${clientes.length}'); debugPrint('[Sync] clientes: ${clientes.length}');
} catch (e) { } catch (e) {
debugPrint('[Sync] clientes error: $e'); debugPrint('[Sync] clientes error: $e');
} }
} }
/// Sube al cloud todos los pedidos con sync_estado=PENDIENTE.
/// Silencioso — los errores no interrumpen el flujo.
Future<void> _uploadPendingPedidos() async {
if (!_modoOnline || _apiKey.isEmpty) return;
final pendientes = _pedidos.where((p) => p.syncEstado == 'PENDIENTE').toList();
for (final pedido in pendientes) {
try {
await CloudSyncService.uploadPedido(pedido, _vendedor?.id ?? '');
await _db.updateSyncEstadoPedido(pedido.id, 'SINCRONIZADO');
pedido.syncEstado = 'SINCRONIZADO';
debugPrint('[Sync] pedido ${pedido.id} subido');
} catch (e) {
await _db.updateSyncEstadoPedido(pedido.id, 'ERROR');
pedido.syncEstado = 'ERROR';
debugPrint('[Sync] pedido ${pedido.id} error: $e');
}
}
}
Vendedor _vendedorFromSession(AuthSession session, String email) { Vendedor _vendedorFromSession(AuthSession session, String email) {
final nombre = session.nombre.isNotEmpty ? session.nombre : session.usuario; final nombre = session.nombre.isNotEmpty ? session.nombre : session.usuario;
final initials = nombre.trim().isNotEmpty
? nombre.trim().split(' ').take(2).map((w) => w[0].toUpperCase()).join()
: email[0].toUpperCase();
return Vendedor( return Vendedor(
id: session.usrSesionId?.toString() ?? session.usuario, id: session.usrSesionId?.toString() ?? session.usuario,
nombre: nombre, nombre: nombre,
email: email, email: email,
telefono: '', telefono: '',
zona: '', zona: '',
avatarInitials: initials, avatarInitials: _buildInitials(nombre, email),
); );
} }
String _buildInitials(String nombre, String email) {
final trimmed = nombre.trim();
if (trimmed.isNotEmpty) {
return trimmed.split(' ').take(2)
.map((w) => w.isNotEmpty ? w[0].toUpperCase() : '')
.join();
}
return email.isNotEmpty ? email[0].toUpperCase() : 'U';
}
Future<void> _loadAllData() async { Future<void> _loadAllData() async {
// 1. catálogo y clientes (base para joins) // 1. catálogo y clientes (base para joins)
_productos = await _db.getProductos(); _productos = await _db.getProductos();
@@ -396,6 +556,18 @@ class AppProvider extends ChangeNotifier {
); );
await _db.insertPedido(pedido); await _db.insertPedido(pedido);
_pedidos.insert(0, pedido); _pedidos.insert(0, pedido);
// Intento de upload inmediato; si falla queda PENDIENTE y se sube en el próximo login
if (_modoOnline && _apiKey.isNotEmpty) {
try {
await CloudSyncService.uploadPedido(pedido, _vendedor?.id ?? '');
await _db.updateSyncEstadoPedido(pedido.id, 'SINCRONIZADO');
pedido.syncEstado = 'SINCRONIZADO';
} catch (_) {
// sin conexión o error de API — permanece PENDIENTE
}
}
_notifService?.notifPedidoConfirmado(id, _clienteSeleccionado!.nombre); _notifService?.notifPedidoConfirmado(id, _clienteSeleccionado!.nombre);
limpiarCarrito(); limpiarCarrito();
notifyListeners(); notifyListeners();
+28
View File
@@ -1,6 +1,7 @@
import 'dart:convert'; import 'dart:convert';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import '../models/pedido.dart';
// URL idéntica a sigmac_app/gateway_cloud_api.dart // URL idéntica a sigmac_app/gateway_cloud_api.dart
const _kBase = 'https://api-gateway-cloud.telcotronics.net'; const _kBase = 'https://api-gateway-cloud.telcotronics.net';
@@ -159,6 +160,33 @@ class CloudSyncService {
.toList(); .toList();
} }
// ── Upload Pedidos ─────────────────────────────────────────────────────────
/// Sube un pedido al cloud.
/// Endpoint: POST /api/documentos/pedidos?db={db}
/// Body: { encabezado: {...}, detalles: [...] }
static Future<void> uploadPedido(Pedido pedido, String usuario) async {
final db = await _requireDb();
final headers = await _headers();
headers['Content-Type'] = 'application/json';
final uri = Uri.parse('$_kBase/api/documentos/pedidos')
.replace(queryParameters: {'db': db});
final res = await http
.post(
uri,
headers: headers,
body: jsonEncode({
'encabezado': pedido.toCloudEncabezado(usuario),
'detalles': pedido.items.map((i) => i.toCloudDetalle()).toList(),
}),
)
.timeout(const Duration(seconds: 20));
_checkStatus(res);
}
// ── Helper ───────────────────────────────────────────────────────────────── // ── Helper ─────────────────────────────────────────────────────────────────
static void _checkStatus(http.Response res) { static void _checkStatus(http.Response res) {