untitled

Pasted Nov 18, 2026, 7:02 AM1 file907 lines

Scan to open on your phone

Point a camera at the QR code - it opens this exact paste, no app needed.

https://codepastes.com/zzgs2gv8w7e0vn6q
untitled

package com.negocio.desinfectantes.data

import android.content.Context
import androidx.room.withTransaction
import kotlinx.coroutines.CancellationException
import kotlinx.serialization.json.*
import java.time.Instant

class CatalogoDescargaProcessor(
    private val context: Context
) {

    private val service = CatalogoDescargaService()

    private val json = Json {
        ignoreUnknownKeys = true
    }

    /**
     * MOTOR CENTRAL DE DESCARGAS
     *
     * Cada módulo conserva su propio cursor.
     */
    suspend fun descargarCatalogo(
        database: PrestigeDatabase,
        usuarioId: String
    ) {
        descargarCatalogoInterno(database, usuarioId)
        descargarVentas(database, usuarioId)
        descargarInventario(database, usuarioId)
        descargarLotes(database, usuarioId)
    }

    // ---------------------------------------------------------
    // OBTENER CAMBIOS PAGINADOS
    // ---------------------------------------------------------

    private suspend fun obtenerCambiosModulo(
        database: PrestigeDatabase,
        usuarioId: String,
        modulo: String,
        entidades: Set<String>
    ): CambiosModulo {

        val estadoDao = database.estadoSincronizacionModuloDao()

        val ultimoCambio = estadoDao.obtenerUltimoCambio(
            usuarioId,
            modulo
        ) ?: 0L

        val cambios = mutableListOf<CambioSincronizacionDto>()
        var cursor = ultimoCambio

        while (true) {
            val pagina = service.obtenerCambios(cursor)

            if (pagina.isEmpty()) break

            cambios.addAll(pagina)
            cursor = pagina.last().id

            if (pagina.size < 500) break
        }

        val cambiosModulo = cambios
            .filter { it.entidad in entidades }
            .associateBy { Pair(it.entidad, it.entidadId) }
            .values
            .toList()

        return CambiosModulo(
            cambios = cambiosModulo,
            cursor = cursor
        )
    }

    // ---------------------------------------------------------
    // PROCESAMIENTO COMÚN DE CADA MÓDULO
    // ---------------------------------------------------------

    private suspend fun procesarCambios(
        database: PrestigeDatabase,
        usuarioId: String,
        modulo: String,
        resultado: CambiosModulo,
        registros: List<RegistroDescarga>,
        prioridadSubida: (String) -> Int,
        prioridadEliminacion: (String) -> Int,
        guardar: suspend (RegistroDescarga) -> Unit,
        eliminar: suspend (RegistroDescarga) -> Unit
    ) {

        val estadoDao = database.estadoSincronizacionModuloDao()

        database.withTransaction {

            val proteccion = obtenerProteccionPendientes(
                database,
                usuarioId
            )

            registros
                .filter { it.cambio.operacion != "DELETE" }
                .sortedBy {
                    prioridadSubida(it.cambio.entidad)
                }
                .forEach { registro ->

                    if (proteccion.debeOmitir(registro)) {
                        return@forEach
                    }

                    guardar(registro)
                }

            registros
                .filter { it.cambio.operacion == "DELETE" }
                .sortedBy {
                    prioridadEliminacion(it.cambio.entidad)
                }
                .forEach { registro ->

                    if (proteccion.debeOmitir(registro)) {
                        return@forEach
                    }

                    eliminar(registro)
                }

            // El cursor avanza solamente si la transacción termina bien.
            estadoDao.guardarEstado(
                EstadoSincronizacionModuloEntity(
                    usuarioId = usuarioId,
                    modulo = modulo,
                    ultimoCambioId = resultado.cursor
                )
            )
        }
    }

    // ---------------------------------------------------------
    // PROTEGER OPERACIONES LOCALES PENDIENTES
    // ---------------------------------------------------------

    private suspend fun obtenerProteccionPendientes(
        database: PrestigeDatabase,
        usuarioId: String
    ): ProteccionPendientes {

        val pendientes = database.operacionPendienteDao()
            .obtenerPendientes(usuarioId)

        val ids = mutableSetOf<Pair<String, String>>()
        val ventas = mutableSetOf<String>()

        var protegerVentasRelacionadas = false
        var protegerInventario = false

        pendientes.forEach { operacion ->

            try {
                val raiz = json.parseToJsonElement(
                    operacion.payload
                ).jsonObject

                // Operaciones genéricas: datos.id
                val datos = raiz["datos"]?.jsonObject

                datos?.get("id")
                    ?.jsonPrimitive
                    ?.contentOrNull
                    ?.let {
                        ids.add(Pair(operacion.entidad, it))
                    }

                // Pago pendiente: datos.venta_id
                datos?.get("venta_id")
                    ?.jsonPrimitive
                    ?.contentOrNull
                    ?.let {
                        ventas.add(it)
                    }

                // Venta creada localmente: venta.id
                raiz["venta"]?.jsonObject
                    ?.get("id")
                    ?.jsonPrimitive
                    ?.contentOrNull
                    ?.let {
                        ventas.add(it)
                        ids.add(Pair("ventas", it))
                    }

                // Detalles, pagos, movimientos y asignaciones
                val colecciones = listOf(
                    "detalles" to "detalles_venta",
                    "pagos" to "pagos_venta",
                    "movimientos" to "movimientos_inventario",
                    "asignacionesLote" to "lotes_ventas"
                )

                colecciones.forEach { (campo, entidad) ->

                    raiz[campo]?.jsonArray?.forEach { elemento ->

                        elemento.jsonObject["id"]
                            ?.jsonPrimitive
                            ?.contentOrNull
                            ?.let {
                                ids.add(Pair(entidad, it))
                            }
                    }
                }

                // Operaciones de reserva, entrega y cancelación.
                raiz["ventaId"]
                    ?.jsonPrimitive
                    ?.contentOrNull
                    ?.let {
                        ventas.add(it)
                        ids.add(Pair("ventas", it))
                    }

                val accion = raiz["accion"]
                    ?.jsonPrimitive
                    ?.contentOrNull

                if (
                    accion in listOf(
                        "RESERVAR_PEDIDO",
                        "ENTREGAR_PEDIDO",
                        "CANCELAR_PEDIDO"
                    )
                ) {
                    protegerVentasRelacionadas = true
                    protegerInventario = true
                }

                if (operacion.tipoOperacion == "CREAR_VENTA") {
                    protegerInventario = true
                }

            } catch (_: Exception) {
                // Un payload que no se pueda interpretar no detiene
                // la descarga de los demás registros.
            }
        }

        return ProteccionPendientes(
            ids = ids,
            ventas = ventas,
            protegerVentasRelacionadas = protegerVentasRelacionadas,
            protegerInventario = protegerInventario
        )
    }

    // ---------------------------------------------------------
    // CATÁLOGO
    // ---------------------------------------------------------

    private suspend fun descargarCatalogoInterno(
        database: PrestigeDatabase,
        usuarioId: String
    ) {

        val entidades = setOf(
            "productos",
            "aromas",
            "presentaciones"
        )

        val resultado = obtenerCambiosModulo(
            database,
            usuarioId,
            "catalogo",
            entidades
        )

        if (resultado.cursor == 0L && resultado.cambios.isEmpty()) {
            return
        }

        val registros = resultado.cambios.map { cambio ->

            val dato: Any? = if (cambio.operacion == "DELETE") {
                null
            } else {
                when (cambio.entidad) {
                    "productos" ->
                        service.obtenerProducto(cambio.entidadId)

                    "aromas" ->
                        service.obtenerAroma(cambio.entidadId)

                    "presentaciones" ->
                        service.obtenerPresentacion(cambio.entidadId)

                    else -> null
                }
            }

            RegistroDescarga(cambio, dato)
        }

        procesarCambios(
            database = database,
            usuarioId = usuarioId,
            modulo = "catalogo",
            resultado = resultado,
            registros = registros,
            prioridadSubida = {
                when (it) {
                    "productos" -> 1
                    "aromas" -> 2
                    "presentaciones" -> 3
                    else -> 0
                }
            },
            prioridadEliminacion = {
                when (it) {
                    "presentaciones" -> 1
                    "aromas" -> 2
                    "productos" -> 3
                    else -> 0
                }
            },
            guardar = { registro ->

                when (registro.cambio.entidad) {

                    "productos" -> {
                        val remoto = registro.dato as? ProductoSyncDto
                            ?: throw Exception("No se encontró el producto.")

                        val dao = database.productoDao()
                        val local = dao.buscarProducto(remoto.id)

                        dao.guardarProducto(
                            ProductoEntity(
                                id = remoto.id,
                                nombre = remoto.nombre,
                                tipo = remoto.tipo,
                                fotoUri = local?.fotoUri,
                                activo = remoto.activo,
                                fechaCreacion = Instant.parse(
                                    remoto.fechaCreacion
                                ).toEpochMilli()
                            )
                        )
                    }

                    "aromas" -> {
                        val remoto = registro.dato as? AromaSyncDto
                            ?: throw Exception("No se encontró el aroma.")

                        database.productoDao().guardarAroma(
                            AromaEntity(
                                id = remoto.id,
                                productoId = remoto.productoId,
                                nombre = remoto.nombre,
                                activo = remoto.activo,
                                fechaCreacion = Instant.parse(
                                    remoto.fechaCreacion
                                ).toEpochMilli()
                            )
                        )
                    }

                    "presentaciones" -> {
                        val remoto = registro.dato as? PresentacionSyncDto
                            ?: throw Exception("No se encontró la presentación.")

                        val dao = database.productoDao()
                        val local = dao.obtenerPresentacionPorId(remoto.id)

                        val fotoLocal = remoto.fotoStoragePath
                            ?.takeIf { it.isNotBlank() }
                            ?.let { ruta ->
                                FotoCatalogoService.descargarFotoPresentacion(
                                    context = context,
                                    idPresentacion = remoto.id,
                                    ruta = ruta
                                )
                            } ?: local?.fotoUri

                        dao.guardarPresentacion(
                            PresentacionEntity(
                                id = remoto.id,
                                aromaId = remoto.aromaId,
                                nombre = remoto.nombre,
                                contenidoMl = remoto.contenidoMl,
                                precio = remoto.precio,
                                fotoUri = fotoLocal,
                                activo = remoto.activo,
                                fechaCreacion = Instant.parse(
                                    remoto.fechaCreacion
                                ).toEpochMilli()
                            )
                        )
                    }
                }
            },
            eliminar = { registro ->

                when (registro.cambio.entidad) {
                    "presentaciones" ->
                        database.productoDao()
                            .eliminarPresentacion(registro.cambio.entidadId)

                    "aromas" ->
                        database.productoDao()
                            .eliminarAroma(registro.cambio.entidadId)

                    "productos" ->
                        database.productoDao()
                            .desactivarProducto(registro.cambio.entidadId)
                }
            }
        )
    }

    // ---------------------------------------------------------
    // VENTAS
    // ---------------------------------------------------------

    private suspend fun descargarVentas(
        database: PrestigeDatabase,
        usuarioId: String
    ) {

        val entidades = setOf(
            "ventas",
            "detalles_venta",
            "pagos_venta"
        )

        val resultado = obtenerCambiosModulo(
            database,
            usuarioId,
            "ventas",
            entidades
        )

        if (resultado.cursor == 0L && resultado.cambios.isEmpty()) {
            return
        }

        val registros = resultado.cambios.map { cambio ->

            val dato: Any? = if (cambio.operacion == "DELETE") {
                null
            } else {
                when (cambio.entidad) {
                    "ventas" ->
                        service.obtenerVenta(cambio.entidadId)

                    "detalles_venta" ->
                        service.obtenerDetalleVenta(cambio.entidadId)

                    "pagos_venta" ->
                        service.obtenerPagoVenta(cambio.entidadId)

                    else -> null
                }
            }

            RegistroDescarga(cambio, dato)
        }

        procesarCambios(
            database = database,
            usuarioId = usuarioId,
            modulo = "ventas",
            resultado = resultado,
            registros = registros,
            prioridadSubida = {
                when (it) {
                    "ventas" -> 1
                    "detalles_venta" -> 2
                    "pagos_venta" -> 3
                    else -> 0
                }
            },
            prioridadEliminacion = {
                when (it) {
                    "pagos_venta" -> 1
                    "detalles_venta" -> 2
                    "ventas" -> 3
                    else -> 0
                }
            },
            guardar = { registro ->

                when (registro.cambio.entidad) {

                    "ventas" -> {
                        val remoto = registro.dato as? VentaSyncDto
                            ?: throw Exception("No se encontró la venta.")

                        database.productoDao().guardarVentaDescargada(
                            VentaEntity(
                                id = remoto.id,
                                clienteId = remoto.clienteId,
                                sede = remoto.sede,
                                tipoVenta = remoto.tipoVenta,
                                estadoEntrega = remoto.estadoEntrega,
                                total = remoto.total,
                                descuento = remoto.descuento,
                                fechaCreacion = Instant.parse(
                                    remoto.fechaCreacion
                                ).toEpochMilli(),
                                vendedorId = remoto.vendedorId,
                                vendedorNombre = remoto.vendedorNombre
                            )
                        )
                    }

                    "detalles_venta" -> {
                        val remoto = registro.dato as? DetalleVentaSyncDto
                            ?: throw Exception("No se encontró el detalle de venta.")

                        database.productoDao().guardarDetalleVentaDescargado(
                            DetalleVentaEntity(
                                id = remoto.id,
                                ventaId = remoto.ventaId,
                                presentacionId = remoto.presentacionId,
                                cantidad = remoto.cantidad,
                                precioUnitario = remoto.precioUnitario,
                                subtotal = remoto.subtotal
                            )
                        )
                    }

                    "pagos_venta" -> {
                        val remoto = registro.dato as? PagoVentaSyncDto
                            ?: throw Exception("No se encontró el pago.")

                        database.productoDao().guardarPagoVentaDescargado(
                            PagoVentaEntity(
                                id = remoto.id,
                                ventaId = remoto.ventaId,
                                monto = remoto.monto,
                                metodoPago = remoto.metodoPago,
                                observacion = remoto.observacion,
                                fechaCreacion = Instant.parse(
                                    remoto.fechaCreacion
                                ).toEpochMilli()
                            )
                        )
                    }
                }
            },
            eliminar = { registro ->

                when (registro.cambio.entidad) {
                    "pagos_venta" ->
                        database.productoDao()
                            .eliminarPagoVentaDescargado(registro.cambio.entidadId)

                    "detalles_venta" ->
                        database.productoDao()
                            .eliminarDetalleVentaDescargado(registro.cambio.entidadId)

                    "ventas" ->
                        database.productoDao()
                            .eliminarVentaDescargada(registro.cambio.entidadId)
                }
            }
        )
    }

    // ---------------------------------------------------------
    // INVENTARIO
    // ---------------------------------------------------------

    private suspend fun descargarInventario(
        database: PrestigeDatabase,
        usuarioId: String
    ) {

        val entidades = setOf(
            "inventario",
            "movimientos_inventario"
        )

        val resultado = obtenerCambiosModulo(
            database,
            usuarioId,
            "inventario",
            entidades
        )

        if (resultado.cursor == 0L && resultado.cambios.isEmpty()) {
            return
        }

        val registros = resultado.cambios.map { cambio ->

            val dato: Any? = if (cambio.operacion == "DELETE") {
                null
            } else {
                when (cambio.entidad) {
                    "inventario" ->
                        service.obtenerInventario(cambio.entidadId)

                    "movimientos_inventario" ->
                        service.obtenerMovimientoInventario(cambio.entidadId)

                    else -> null
                }
            }

            RegistroDescarga(cambio, dato)
        }

        procesarCambios(
            database = database,
            usuarioId = usuarioId,
            modulo = "inventario",
            resultado = resultado,
            registros = registros,
            prioridadSubida = {
                when (it) {
                    "inventario" -> 1
                    "movimientos_inventario" -> 2
                    else -> 0
                }
            },
            prioridadEliminacion = {
                when (it) {
                    "movimientos_inventario" -> 1
                    "inventario" -> 2
                    else -> 0
                }
            },
            guardar = { registro ->

                when (registro.cambio.entidad) {

                    "inventario" -> {
                        val remoto = registro.dato as? InventarioSyncDto
                            ?: throw Exception("No se encontró el inventario.")

                        database.productoDao().guardarInventarioDescargado(
                            InventarioEntity(
                                id = remoto.id,
                                presentacionId = remoto.presentacionId,
                                sede = remoto.sede,
                                cantidadDisponible = remoto.cantidadDisponible,
                                cantidadReservada = remoto.cantidadReservada,
                                fechaActualizacion = Instant.parse(
                                    remoto.fechaActualizacion
                                ).toEpochMilli()
                            )
                        )
                    }

                    "movimientos_inventario" -> {
                        val remoto = registro.dato as? MovimientoInventarioSyncDto
                            ?: throw Exception("No se encontró el movimiento.")

                        database.productoDao().guardarMovimientoDescargado(
                            MovimientoInventarioEntity(
                                id = remoto.id,
                                presentacionId = remoto.presentacionId,
                                sede = remoto.sede,
                                tipoMovimiento = remoto.tipoMovimiento,
                                cantidad = remoto.cantidad,
                                referenciaId = remoto.referenciaId,
                                observacion = remoto.observacion,
                                fechaCreacion = Instant.parse(
                                    remoto.fechaCreacion
                                ).toEpochMilli()
                            )
                        )
                    }
                }
            },
            eliminar = { registro ->

                when (registro.cambio.entidad) {
                    "movimientos_inventario" ->
                        database.productoDao()
                            .eliminarMovimientoDescargado(registro.cambio.entidadId)

                    "inventario" ->
                        database.productoDao()
                            .eliminarInventarioDescargado(registro.cambio.entidadId)
                }
            }
        )
    }

    // ---------------------------------------------------------
    // LOTES
    // ---------------------------------------------------------

    private suspend fun descargarLotes(
        database: PrestigeDatabase,
        usuarioId: String
    ) {

        val entidades = setOf(
            "lotes_produccion",
            "lotes_inventario",
            "lotes_ventas"
        )

        val resultado = obtenerCambiosModulo(
            database,
            usuarioId,
            "lotes",
            entidades
        )

        if (resultado.cursor == 0L && resultado.cambios.isEmpty()) {
            return
        }

        val registros = resultado.cambios.map { cambio ->

            val dato: Any? = if (cambio.operacion == "DELETE") {
                null
            } else {
                when (cambio.entidad) {
                    "lotes_produccion" ->
                        service.obtenerLoteProduccion(cambio.entidadId)

                    "lotes_inventario" ->
                        service.obtenerLoteInventario(cambio.entidadId)

                    "lotes_ventas" ->
                        service.obtenerLoteVenta(cambio.entidadId)

                    else -> null
                }
            }

            RegistroDescarga(cambio, dato)
        }

        procesarCambios(
            database = database,
            usuarioId = usuarioId,
            modulo = "lotes",
            resultado = resultado,
            registros = registros,
            prioridadSubida = {
                when (it) {
                    "lotes_inventario" -> 1
                    "lotes_ventas" -> 2
                    else -> 0
                }
            },
            prioridadEliminacion = {
                when (it) {
                    "lotes_ventas" -> 1
                    "lotes_inventario" -> 2
                    else -> 0
                }
            },
            guardar = { registro ->

                when (registro.cambio.entidad) {
                    "lotes_produccion" -> {
                        val remoto = registro.dato as? LoteProduccionSyncDto
                            ?: throw Exception("No se pudo interpretar el lote de producción.")

                        database.productoDao().guardarLoteProduccionDescargado(
                            LoteProduccionEntity(
                                id = remoto.id,
                                productoId = remoto.productoId,
                                aromaId = remoto.aromaId,
                                numeroLote = remoto.numeroLote,
                                fechaCreacion = java.time.Instant.parse(remoto.fechaCreacion)
                                    .toEpochMilli()
                            )
                        )
                    }

                    "lotes_inventario" -> {
                        val remoto = registro.dato as? LoteInventarioSyncDto
                            ?: throw Exception("No se encontró el lote de inventario.")

                        database.productoDao().guardarLoteInventarioDescargado(
                            LoteInventarioEntity(
                                id = remoto.id,
                                loteId = remoto.loteId,
                                presentacionId = remoto.presentacionId,
                                sede = remoto.sede,
                                cantidadDisponible = remoto.cantidadDisponible,
                                cantidadReservada = remoto.cantidadReservada,
                                cantidadInicial = remoto.cantidadInicial
                            )
                        )
                    }

                    "lotes_ventas" -> {
                        val remoto = registro.dato as? LoteVentaSyncDto
                            ?: throw Exception("No se encontró la asignación del lote.")

                        database.productoDao().guardarLoteVentaDescargado(
                            LoteVentaEntity(
                                id = remoto.id,
                                ventaId = remoto.ventaId,
                                detalleVentaId = remoto.detalleVentaId,
                                loteInventarioId = remoto.loteInventarioId,
                                cantidad = remoto.cantidad,
                                estado = remoto.estado
                            )
                        )
                    }
                }
            },
            eliminar = { registro ->
                when (registro.cambio.entidad) {

                    "lotes_ventas" ->
                        database.productoDao()
                            .eliminarLoteVentaDescargado(registro.cambio.entidadId)

                    "lotes_inventario" ->
                        database.productoDao()
                            .eliminarLoteInventarioDescargado(registro.cambio.entidadId)

                    "lotes_produccion" ->
                        database.productoDao()
                            .eliminarLoteProduccionDescargado(registro.cambio.entidadId)
                }
            }
        )
    }

    // ---------------------------------------------------------
    // ESTRUCTURAS INTERNAS
    // ---------------------------------------------------------

    private data class CambiosModulo(
        val cambios: List<CambioSincronizacionDto>,
        val cursor: Long
    )

    private data class RegistroDescarga(
        val cambio: CambioSincronizacionDto,
        val dato: Any?
    )

    private data class ProteccionPendientes(
        val ids: Set<Pair<String, String>>,
        val ventas: Set<String>,
        val protegerVentasRelacionadas: Boolean,
        val protegerInventario: Boolean
    ) {

        fun debeOmitir(
            registro: RegistroDescarga
        ): Boolean {

            val cambio = registro.cambio

            if (
                Pair(cambio.entidad, cambio.entidadId) in ids
            ) {
                return true
            }

            if (
                cambio.entidad == "ventas" &&
                cambio.entidadId in ventas
            ) {
                return true
            }

            if (protegerInventario && cambio.entidad in setOf(
                    "inventario",
                    "lotes_inventario"
                )
            ) {
                return true
            }

            if (protegerVentasRelacionadas) {
                if (cambio.entidad in setOf(
                        "ventas",
                        "detalles_venta",
                        "pagos_venta",
                        "lotes_ventas"
                    )
                ) {
                    return true
                }
            }

            val ventaId = when (val dato = registro.dato) {
                is DetalleVentaSyncDto -> dato.ventaId
                is PagoVentaSyncDto -> dato.ventaId
                is LoteVentaSyncDto -> dato.ventaId
                else -> null
            }

            return ventaId != null && ventaId in ventas
        }
    }
}

30,493 chars · codepastes.com