saveDetalleEspecie method

Future<void> saveDetalleEspecie(
  1. Map<String, dynamic> detalle,
  2. BuildContext context
)

Implementation

Future<void> saveDetalleEspecie(
  Map<String, dynamic> detalle,
  BuildContext context,
) async {
  // Generar ID único alfanumérico y asignar
  final generatedId = _generateAlphanumericId();
  detalle['id'] = generatedId;

  // Guardar en local
  try {
    await _dbHelper.insertDetalleEspecieExpedienteBatch([detalle]);
    print('✅ Detalle guardado localmente');
  } catch (e) {
    print('❌ Error guardando localmente: $e');
    await _sendNotification('Error local', 'No se pudo guardar localmente');
    showMessage(context, 'Error local: $e');
    return;
  }

  final conectado =
      await Connectivity().checkConnectivity() != ConnectivityResult.none;

  if (conectado) {
    final success = await uploadDetalle(detalle);
    if (success) {
      await _sendNotification(
        'Detalle Guardado',
        'Detalle sincronizado con éxito',
      );
      showMessage(context, 'Sincronizado con éxito');
      // No hay registro pendiente que eliminar aquí
    } else {
      await _storePendingDetalle(detalle);
      await _sendNotification(
        'Fallo API',
        'Guardado en pendientes',
      );
      showMessage(context, 'Guardado en pendientes para reintento');
    }
  } else {
    await _storePendingDetalle(detalle);
    await _sendNotification(
      'Modo Offline',
      'Guardado hasta conexión',
    );
    showMessage(context, 'Guardado offline');
  }
}