diff --git a/.github/workflows/android-tests-coverage.yml b/.github/workflows/android-tests-coverage.yml index 87f7729b..cca14d01 100644 --- a/.github/workflows/android-tests-coverage.yml +++ b/.github/workflows/android-tests-coverage.yml @@ -7,12 +7,16 @@ on: - master - develop - Core2 + - Core3 + - Core4 pull_request: branches: - main - master - develop - Core2 + - Core3 + - Core4 workflow_dispatch: permissions: diff --git a/.github/workflows/ci-android-client.yml b/.github/workflows/ci-android-client.yml index 4215c2ed..59639dd8 100644 --- a/.github/workflows/ci-android-client.yml +++ b/.github/workflows/ci-android-client.yml @@ -3,7 +3,7 @@ name: CI Android Cliente on: push: - branches: [master, main, Core2, Core3] + branches: [master, main, Core2, Core3, Core4] paths: - "app/**" - "shared-*/**" @@ -16,7 +16,7 @@ on: - "gradle.properties" - ".github/workflows/ci-android-client.yml" pull_request: - branches: [master, main, Core2, Core3] + branches: [master, main, Core2, Core3, Core4] paths: - "app/**" - "shared-*/**" @@ -32,7 +32,6 @@ on: concurrency: group: ci-android-client-${{ github.ref }} - # false: pushes rápidos ya no cancelan el job a mitad (mensaje «operación cancelada») cancel-in-progress: false permissions: @@ -65,7 +64,6 @@ jobs: - name: Placeholder local.properties run: | echo "sdk.dir=$ANDROID_HOME" > local.properties - # Agent keys opcionales (vacías en CI; BuildConfig las inyecta como "") echo "MISTRAL_API_KEY=" >> local.properties echo "MISTRAL_AGENT_ID=" >> local.properties echo "MISTRAL_MODEL_ID=mistral-medium-latest" >> local.properties diff --git a/.github/workflows/ci-android-operator.yml b/.github/workflows/ci-android-operator.yml index 6e1d4e22..d45e739b 100644 --- a/.github/workflows/ci-android-operator.yml +++ b/.github/workflows/ci-android-operator.yml @@ -3,7 +3,7 @@ name: CI Android Operador on: push: - branches: [master, main, Core2, Core3] + branches: [master, main, Core2, Core3, Core4] paths: - "alejotallerscan/**" - "shared-*/**" @@ -16,7 +16,7 @@ on: - "gradle.properties" - ".github/workflows/ci-android-operator.yml" pull_request: - branches: [master, main, Core2, Core3] + branches: [master, main, Core2, Core3, Core4] paths: - "alejotallerscan/**" - "shared-*/**" diff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.yml index b98e6f2b..3e60c559 100644 --- a/.github/workflows/ci-mcp.yml +++ b/.github/workflows/ci-mcp.yml @@ -3,13 +3,13 @@ name: CI MCP on: push: - branches: [master, main, Core2, Core3] + branches: [master, main, Core2, Core3, Core4] paths: - "mcp/**" - ".github/workflows/ci-mcp.yml" - ".github/workflows/ci-gate.yml" pull_request: - branches: [master, main, Core2, Core3] + branches: [master, main, Core2, Core3, Core4] paths: - "mcp/**" - ".github/workflows/ci-mcp.yml" @@ -79,5 +79,3 @@ jobs: MCP_SMOKE_URL: https://alejotaller-mcp.daniel-imbert96.workers.dev MCP_SMOKE_TIMEOUT_MS: "20000" run: node scripts/smoke-health.mjs - # If deploy lags behind master, this can fail until wrangler deploy runs. - # workflow_dispatch allows re-run after deploy. diff --git a/.github/workflows/ci-web.yml b/.github/workflows/ci-web.yml index 0aa9707f..8c9c6da0 100644 --- a/.github/workflows/ci-web.yml +++ b/.github/workflows/ci-web.yml @@ -3,12 +3,12 @@ name: CI Web on: push: - branches: [master, main, Core2, Core3] + branches: [master, main, Core2, Core3, Core4] paths: - "web/**" - ".github/workflows/ci-web.yml" pull_request: - branches: [master, main, Core2, Core3] + branches: [master, main, Core2, Core3, Core4] paths: - "web/**" - ".github/workflows/ci-web.yml" @@ -39,8 +39,6 @@ jobs: cache: npm cache-dependency-path: web/package-lock.json - # npm ci requires package-lock in sync with package.json. - # Use npm install if lock is stale (still installs deterministic-enough for CI). - name: Install dependencies run: | if npm ci; then diff --git a/.roadmap/Core4/CORE4_UNIFIED_CHECKLIST.md b/.roadmap/Core4/CORE4_UNIFIED_CHECKLIST.md new file mode 100644 index 00000000..33f85fe6 --- /dev/null +++ b/.roadmap/Core4/CORE4_UNIFIED_CHECKLIST.md @@ -0,0 +1,25 @@ +# Core 4 — Checklist (AlejoTaller) + +**Última actualización:** 2026-09-02 +**Rama:** `Core4` +**PR:** https://github.com/danielitoCode/AlejoTaller/pull/28 +**Canónico:** [dash checklist](https://github.com/danielitoCode/dash_alejo_taller/blob/Core4/.roadmap/Core4/CORE4_UNIFIED_CHECKLIST.md) + +## B0–B5 + +- [x] Baseline, contrato, write operador, B4 no-reescritura, paridad docs + +## B6 + +- [x] MCP prohíbe `sale_finance_event` (SCOPE/DATA_CONTRACT) +- [x] Web sin create finance +- [x] Unit operador: DELETED sin finance; createIdempotent B4 +- [ ] Smoke device (opcional) +- [ ] CI verde PR #28 +- [ ] Merge coordinado con dash PR #21 + +## Registro + +| Fecha | Nota | +|---|---| +| 2026-09-02 | B6: PR #28 abierto | diff --git a/.roadmap/Core4/MVP_CORE4_STATUS.md b/.roadmap/Core4/MVP_CORE4_STATUS.md new file mode 100644 index 00000000..4e63f28b --- /dev/null +++ b/.roadmap/Core4/MVP_CORE4_STATUS.md @@ -0,0 +1,17 @@ +# MVP Core 4 — Estado vivo (AlejoTaller) + +**Última actualización:** 2026-09-02 +**Rama:** `Core4` +**PR:** https://github.com/danielitoCode/AlejoTaller/pull/28 +**Core 4:** B0–B5 hecho; B6 código/frontera OK — CI + merge pendientes + +| Bloque | Estado | +|--------|--------| +| B0–B5 | **Cerrado** | +| B6 frontera (MCP/web sin write finance) | **Documentado** | +| B6 smoke device | Opcional | +| B6 CI + merge | **Pendiente** PR #28 | + +### Acción + +Esperar CI verde en PR #28 y coordinar merge con dash PR #21. diff --git a/.roadmap/Core4/PARITY_PANEL_OPERATOR.md b/.roadmap/Core4/PARITY_PANEL_OPERATOR.md new file mode 100644 index 00000000..b37f303a --- /dev/null +++ b/.roadmap/Core4/PARITY_PANEL_OPERATOR.md @@ -0,0 +1,21 @@ +# Core 4 — Paridad panel (dash) vs operador (AlejoTaller scan) + +**Fecha:** 2026-09-02 · rama `Core4` +**Canónico completo:** [dash PARITY](https://github.com/danielitoCode/dash_alejo_taller/blob/Core4/.roadmap/Core4/PARITY_PANEL_OPERATOR.md) + +## Escritura operador + +| Campo Appwrite | Origen AT | +|----------------|-----------| +| `sale_id` | `SaleFinanceWrite.saleId` | +| `revenue` | `sale.amount` | +| `cogs` | Σ `unitCostSnapshot × qty` | +| `margin` | `revenue − cogs` | +| `user_id` | operador actual | +| `at` | ISO now | +| `currency` | `sale.currency.name` | +| `lines_json` | JSON camelCase (`productId`, `unitCostSnapshot`, …) | + +`createIdempotent`: si ya hay doc por `sale_id`, devolver existente (B4). + +Cliente web / MCP: **sin** write a finance. diff --git a/.roadmap/Core4/README.md b/.roadmap/Core4/README.md new file mode 100644 index 00000000..2a8c773f --- /dev/null +++ b/.roadmap/Core4/README.md @@ -0,0 +1,42 @@ +# Core 4 — Finanzas de Ventas (AlejoTaller) + +**Estado:** abierto · rama `Core4` +**Dependencia:** Core 2 cerrado · Core 3 (espejo / costos en panel) +**Canónico de orden / política:** [dash_alejo_taller/.roadmap/Core4](https://github.com/danielitoCode/dash_alejo_taller/tree/Core4/.roadmap/Core4) + +## Rol de este monorepo + +Core 4 es **paridad financiera** al confirmar ventas. El contrato lo define el panel; aquí se implementa el **write del operador** y se protege la frontera B2C. + +| Superficie | Qué hacer en Core 4 | +|------------|---------------------| +| **alejotallerscan (operador)** | Al VERIFIED: `sale_finance_event` con **snapshot por línea** (mismo contrato que el panel); idempotente por `sale_id` | +| **web / app (cliente)** | **Nada** de write finance; solo crea `UNVERIFIED` | +| **mcp** | Sin tools que escriban `sale_finance_event` | +| **docs / policies** | Espejo de checklist y notas de paridad | + +## Qué ya resolvió Core 2 (no repetir desde cero) + +- Operador: `salida_venta` + `sale_finance_event` agregado (revenue / cogs / margin) al confirm +- COGS = Σ `last_unit_cost × qty` leído en el momento del confirm +- Idempotencia básica por `sale_id` +- DELETED sin finance + +## Objetivo de este espejo + +1. Alinear el write del operador al contrato Core 4 (líneas + `unit_cost_snapshot`) +2. Garantizar que un reintento o un cambio posterior de `last_unit_cost` **no** duplique ni reescriba el evento +3. Mantener cliente/MCP sin capacidad de crear ingresos + +## Documentos + +| Doc | Rol | +|------|-----| +| [CORE4_UNIFIED_CHECKLIST.md](./CORE4_UNIFIED_CHECKLIST.md) | Ítems **AT** del orden B0–B6 | +| [MVP_CORE4_STATUS.md](./MVP_CORE4_STATUS.md) | Estado vivo de este monorepo | + +## Criterio de merge a `master` + +- Código operador + frontera + docs alineados al checklist AT. +- Coordinar con el PR de `dash_alejo_taller` `Core4` → `master`. +- No merge a producción hasta CI verde en ambos. diff --git a/.roadmap/README.md b/.roadmap/README.md index aa1e1dbe..d34d9be7 100644 --- a/.roadmap/README.md +++ b/.roadmap/README.md @@ -7,11 +7,13 @@ Estructura por núcleo de entrega: | [`Core1/`](./Core1/) | Auth visitante, Sale UNVERIFIED + soft-hold, Warehouse, operador confirm/reject, QA | **Cerrado** (2026-08-12) | | [`Core2/`](./Core2/) | `salida_venta` + finance al VERIFIED (operador); factura/movements/COGS/reservas en **dash** | **Cerrado** (2026-08-24) | | [`Core3/`](./Core3/) | Compras y abastecimiento (espejo; UI en dash) | **Listo para merge** · rama `Core3` | +| [`Core4/`](./Core4/) | Finanzas de ventas — paridad operador (snapshot COGS / líneas) + frontera cliente | **Abierto** · rama `Core4` | **Cómo usar** - Marca checkboxes `[x]` cuando verifiques. - Core 1 y Core 2 cerrados a nivel ecosistema. - **Core 3:** release mínimo del panel (B3.1) listo; este monorepo solo docs/frontera — PR `Core3` → `master`. +- **Core 4:** trabajo en `Core4`; canónico de política/checklist en dash; aquí B3 operador + frontera. **Políticas de producto:** [`.policies/`](../.policies/) diff --git a/alejotallerscan/src/main/java/com/elitec/alejotallerscan/feature/finance/data/repository/AppwriteOperatorSaleFinanceRepository.kt b/alejotallerscan/src/main/java/com/elitec/alejotallerscan/feature/finance/data/repository/AppwriteOperatorSaleFinanceRepository.kt index 09e0dbfb..dfb557a1 100644 --- a/alejotallerscan/src/main/java/com/elitec/alejotallerscan/feature/finance/data/repository/AppwriteOperatorSaleFinanceRepository.kt +++ b/alejotallerscan/src/main/java/com/elitec/alejotallerscan/feature/finance/data/repository/AppwriteOperatorSaleFinanceRepository.kt @@ -2,12 +2,15 @@ package com.elitec.alejotallerscan.feature.finance.data.repository import android.util.Log import com.elitec.alejotallerscan.BuildConfig +import com.elitec.alejotallerscan.feature.finance.domain.entity.SaleFinanceLineWrite import com.elitec.alejotallerscan.feature.finance.domain.entity.SaleFinanceRecord import com.elitec.alejotallerscan.feature.finance.domain.entity.SaleFinanceWrite import com.elitec.alejotallerscan.feature.finance.domain.repository.OperatorSaleFinanceRepository import io.appwrite.ID import io.appwrite.Query import io.appwrite.services.Databases +import org.json.JSONArray +import org.json.JSONObject class AppwriteOperatorSaleFinanceRepository( private val databases: Databases @@ -34,7 +37,8 @@ class AppwriteOperatorSaleFinanceRepository( saleId = (data["sale_id"] as? String).orEmpty(), revenue = (data["revenue"] as? Number)?.toDouble() ?: 0.0, cogs = (data["cogs"] as? Number)?.toDouble() ?: 0.0, - margin = (data["margin"] as? Number)?.toDouble() ?: 0.0 + margin = (data["margin"] as? Number)?.toDouble() ?: 0.0, + lines = parseLinesJson(data["lines_json"] as? String) ) } @@ -55,6 +59,9 @@ class AppwriteOperatorSaleFinanceRepository( "at" to event.atIso ) event.currency?.takeIf { it.isNotBlank() }?.let { data["currency"] = it } + if (event.lines.isNotEmpty()) { + data["lines_json"] = serializeLines(event.lines) + } val doc = databases.createDocument( databaseId = BuildConfig.APPWRITE_DATABASE_ID, @@ -65,17 +72,72 @@ class AppwriteOperatorSaleFinanceRepository( Log.i( TAG, "event=operator_finance_created id=${doc.id} saleId=${event.saleId} " + - "revenue=${event.revenue} cogs=${event.cogs} margin=${event.margin}" + "revenue=${event.revenue} cogs=${event.cogs} margin=${event.margin} lines=${event.lines.size}" ) return SaleFinanceRecord( id = doc.id, saleId = event.saleId, revenue = event.revenue, cogs = event.cogs, - margin = event.margin + margin = event.margin, + lines = event.lines ) } + private fun serializeLines(lines: List): String { + val arr = JSONArray() + for (l in lines) { + arr.put( + JSONObject() + .put("productId", l.productId) + .put("quantity", l.quantity) + .put("unitPrice", l.unitPrice) + .put("unitCostSnapshot", l.unitCostSnapshot) + .put("lineRevenue", l.lineRevenue) + .put("lineCogs", l.lineCogs) + .put("lineMargin", l.lineMargin) + ) + } + return arr.toString() + } + + private fun parseLinesJson(raw: String?): List { + if (raw.isNullOrBlank()) return emptyList() + return runCatching { + val arr = JSONArray(raw) + buildList { + for (i in 0 until arr.length()) { + val o = arr.optJSONObject(i) ?: continue + val productId = o.optString("productId").ifBlank { + o.optString("product_id") + } + if (productId.isBlank()) continue + val quantity = o.optInt("quantity", 0) + if (quantity <= 0) continue + val unitPrice = o.optDouble("unitPrice", o.optDouble("unit_price", 0.0)) + val unitCostSnapshot = o.optDouble( + "unitCostSnapshot", + o.optDouble("unit_cost_snapshot", 0.0) + ) + val lineRevenue = o.optDouble("lineRevenue", unitPrice * quantity) + val lineCogs = o.optDouble("lineCogs", unitCostSnapshot * quantity) + val lineMargin = o.optDouble("lineMargin", lineRevenue - lineCogs) + add( + SaleFinanceLineWrite( + productId = productId, + quantity = quantity, + unitPrice = unitPrice, + unitCostSnapshot = unitCostSnapshot, + lineRevenue = lineRevenue, + lineCogs = lineCogs, + lineMargin = lineMargin + ) + ) + } + } + }.getOrDefault(emptyList()) + } + companion object { private const val TAG = "OperatorFinanceRepo" } diff --git a/alejotallerscan/src/main/java/com/elitec/alejotallerscan/feature/finance/domain/entity/SaleFinanceWrite.kt b/alejotallerscan/src/main/java/com/elitec/alejotallerscan/feature/finance/domain/entity/SaleFinanceWrite.kt index a4085773..af58860e 100644 --- a/alejotallerscan/src/main/java/com/elitec/alejotallerscan/feature/finance/domain/entity/SaleFinanceWrite.kt +++ b/alejotallerscan/src/main/java/com/elitec/alejotallerscan/feature/finance/domain/entity/SaleFinanceWrite.kt @@ -1,8 +1,24 @@ package com.elitec.alejotallerscan.feature.finance.domain.entity +/** + * Línea de sale_finance_event (Core 4). + * unitCostSnapshot = last_unit_cost congelado al confirm. + * Paridad con dash SaleFinanceLine / lines_json. + */ +data class SaleFinanceLineWrite( + val productId: String, + val quantity: Int, + val unitPrice: Double, + val unitCostSnapshot: Double, + val lineRevenue: Double, + val lineCogs: Double, + val lineMargin: Double +) + /** * Evento financiero al VERIFIED. UNVERIFIED / DELETED no generan documento. - * COGS = sum(last_unit_cost × qty). margin = revenue − cogs. + * COGS = sum(unitCostSnapshot × qty). margin = revenue − cogs. + * Core 4: [lines] se serializa a lines_json en Appwrite (Opción A). */ data class SaleFinanceWrite( val saleId: String, @@ -11,7 +27,8 @@ data class SaleFinanceWrite( val margin: Double, val userId: String, val atIso: String, - val currency: String? + val currency: String?, + val lines: List = emptyList() ) data class SaleFinanceRecord( @@ -19,5 +36,6 @@ data class SaleFinanceRecord( val saleId: String, val revenue: Double, val cogs: Double, - val margin: Double + val margin: Double, + val lines: List = emptyList() ) diff --git a/alejotallerscan/src/main/java/com/elitec/alejotallerscan/feature/product/domain/caseuse/ApplyOperatorStockDecisionCaseUse.kt b/alejotallerscan/src/main/java/com/elitec/alejotallerscan/feature/product/domain/caseuse/ApplyOperatorStockDecisionCaseUse.kt index 12664cf8..9047e3fc 100644 --- a/alejotallerscan/src/main/java/com/elitec/alejotallerscan/feature/product/domain/caseuse/ApplyOperatorStockDecisionCaseUse.kt +++ b/alejotallerscan/src/main/java/com/elitec/alejotallerscan/feature/product/domain/caseuse/ApplyOperatorStockDecisionCaseUse.kt @@ -1,6 +1,7 @@ package com.elitec.alejotallerscan.feature.product.domain.caseuse import android.util.Log +import com.elitec.alejotallerscan.feature.finance.domain.entity.SaleFinanceLineWrite import com.elitec.alejotallerscan.feature.finance.domain.entity.SaleFinanceWrite import com.elitec.alejotallerscan.feature.finance.domain.repository.OperatorSaleFinanceRepository import com.elitec.alejotallerscan.feature.inventory.domain.entity.StockMovementWrite @@ -11,12 +12,12 @@ import com.elitec.shared.sale.feature.sale.domain.entity.Sale import java.time.Instant /** - * WAREHOUSE_POLICY + Core 2 B2 — soft-hold y traza al decidir el operador. + * WAREHOUSE_POLICY + Core 2 B2 + Core 4 B3 — soft-hold, traza y finance al decidir el operador. * * VERIFIED: * - existence -= qty, reserved -= qty * - stock_movements tipo salida_venta (balance_after, sale_id, user_id) - * - sale_finance_event (revenue, cogs = Σ last_unit_cost×qty, margin) + * - sale_finance_event (revenue, cogs, margin + lines con unitCostSnapshot) * * DELETED: * - reserved -= qty @@ -52,6 +53,7 @@ class ApplyOperatorStockDecisionCaseUse( .toSet() var totalCogs = 0.0 + val financeLines = mutableListOf() for (item in sale.products) { val qty = item.quantity.coerceAtLeast(0) @@ -76,7 +78,19 @@ class ApplyOperatorStockDecisionCaseUse( if (!confirmed) continue val unitCost = snapshot.lastUnitCost?.takeIf { it.isFinite() && it >= 0.0 } ?: 0.0 - totalCogs += unitCost * qty + val unitPrice = item.unitPrice?.takeIf { it.isFinite() && it >= 0.0 } ?: 0.0 + val lineRevenue = unitPrice * qty + val lineCogs = unitCost * qty + totalCogs += lineCogs + financeLines += SaleFinanceLineWrite( + productId = item.productId, + quantity = qty, + unitPrice = unitPrice, + unitCostSnapshot = unitCost, + lineRevenue = lineRevenue, + lineCogs = lineCogs, + lineMargin = lineRevenue - lineCogs + ) if (item.productId in alreadyMovedProductIds) { Log.i( @@ -111,12 +125,14 @@ class ApplyOperatorStockDecisionCaseUse( margin = margin, userId = operatorUserId, atIso = Instant.now().toString(), - currency = sale.currency.name + currency = sale.currency.name, + lines = financeLines ) ) Log.i( TAG, - "event=operator_finance_done saleId=${sale.id} revenue=$revenue cogs=$cogs margin=$margin" + "event=operator_finance_done saleId=${sale.id} revenue=$revenue cogs=$cogs " + + "margin=$margin lines=${financeLines.size}" ) } } diff --git a/alejotallerscan/src/test/java/com/elitec/alejotallerscan/feature/product/domain/caseuse/ApplyOperatorStockDecisionCaseUseTest.kt b/alejotallerscan/src/test/java/com/elitec/alejotallerscan/feature/product/domain/caseuse/ApplyOperatorStockDecisionCaseUseTest.kt index 092f1fd5..3052cfc1 100644 --- a/alejotallerscan/src/test/java/com/elitec/alejotallerscan/feature/product/domain/caseuse/ApplyOperatorStockDecisionCaseUseTest.kt +++ b/alejotallerscan/src/test/java/com/elitec/alejotallerscan/feature/product/domain/caseuse/ApplyOperatorStockDecisionCaseUseTest.kt @@ -1,5 +1,6 @@ package com.elitec.alejotallerscan.feature.product.domain.caseuse +import com.elitec.alejotallerscan.feature.finance.domain.entity.SaleFinanceLineWrite import com.elitec.alejotallerscan.feature.finance.domain.entity.SaleFinanceRecord import com.elitec.alejotallerscan.feature.finance.domain.entity.SaleFinanceWrite import com.elitec.alejotallerscan.feature.finance.domain.repository.OperatorSaleFinanceRepository @@ -33,9 +34,17 @@ class ApplyOperatorStockDecisionCaseUseTest { userId = "client-1" ) + private fun costTriple(existence: Int, reserved: Int, cost: Double?): Triple = + Triple(existence, reserved, cost) + @Test - fun verified_writes_salida_venta_and_finance() = runBlocking { - val stock = FakeStockRepo(mapOf("p1" to Triple(10, 2, 5.0), "p2" to Triple(20, 1, 3.0))) + fun verified_writes_salida_venta_and_finance_with_lines() = runBlocking { + val stock = FakeStockRepo( + mutableMapOf( + "p1" to costTriple(10, 2, 5.0), + "p2" to costTriple(20, 1, 3.0) + ) + ) val movements = FakeMovementRepo() val finance = FakeFinanceRepo() val useCase = ApplyOperatorStockDecisionCaseUse( @@ -63,11 +72,22 @@ class ApplyOperatorStockDecisionCaseUseTest { assertEquals(13.0, fin.cogs, 0.001) assertEquals(87.0, fin.margin, 0.001) assertEquals("sale-1", fin.saleId) + assertEquals(2, fin.lines.size) + val lineP1 = fin.lines.first { it.productId == "p1" } + assertEquals(2, lineP1.quantity) + assertEquals(40.0, lineP1.unitPrice, 0.001) + assertEquals(5.0, lineP1.unitCostSnapshot, 0.001) + assertEquals(80.0, lineP1.lineRevenue, 0.001) + assertEquals(10.0, lineP1.lineCogs, 0.001) + assertEquals(70.0, lineP1.lineMargin, 0.001) + val lineP2 = fin.lines.first { it.productId == "p2" } + assertEquals(3.0, lineP2.unitCostSnapshot, 0.001) + assertEquals(3.0, lineP2.lineCogs, 0.001) } @Test fun deleted_only_releases_reserved_no_movement_no_finance() = runBlocking { - val stock = FakeStockRepo(mapOf("p1" to Triple(10, 2, 5.0))) + val stock = FakeStockRepo(mutableMapOf("p1" to costTriple(10, 2, 5.0))) val movements = FakeMovementRepo() val finance = FakeFinanceRepo() val useCase = ApplyOperatorStockDecisionCaseUse( @@ -88,14 +108,31 @@ class ApplyOperatorStockDecisionCaseUseTest { @Test fun verified_idempotent_skips_existing_movement_and_finance() = runBlocking { - val stock = FakeStockRepo(mapOf("p1" to Triple(10, 1, 4.0))) + val stock = FakeStockRepo(mutableMapOf("p1" to costTriple(10, 1, 4.0))) val movements = FakeMovementRepo( existing = listOf( StockMovementRecord("m1", "p1", "salida_venta", 1, 9, "sale-1") ) ) val finance = FakeFinanceRepo( - existing = SaleFinanceRecord("f1", "sale-1", 50.0, 4.0, 46.0) + seed = SaleFinanceRecord( + id = "f1", + saleId = "sale-1", + revenue = 50.0, + cogs = 4.0, + margin = 46.0, + lines = listOf( + SaleFinanceLineWrite( + productId = "p1", + quantity = 1, + unitPrice = 50.0, + unitCostSnapshot = 4.0, + lineRevenue = 50.0, + lineCogs = 4.0, + lineMargin = 46.0 + ) + ) + ) ) val useCase = ApplyOperatorStockDecisionCaseUse( stock, movements, finance, FakeAccountRepo("op-1") @@ -107,12 +144,122 @@ class ApplyOperatorStockDecisionCaseUseTest { assertTrue(movements.created.isEmpty()) assertEquals(1, finance.createCalls) assertEquals(0, finance.created.size) + val stored = finance.getBySaleId("sale-1")!! + assertEquals(4.0, stored.cogs, 0.001) + assertEquals(4.0, stored.lines.single().unitCostSnapshot, 0.001) + } + + @Test + fun verified_missing_cost_uses_zero_snapshot() = runBlocking { + val stock = FakeStockRepo(mutableMapOf("p1" to costTriple(5, 1, null))) + val movements = FakeMovementRepo() + val finance = FakeFinanceRepo() + val useCase = ApplyOperatorStockDecisionCaseUse( + stock, movements, finance, FakeAccountRepo("op-1") + ) + + val result = useCase( + sale(listOf(SaleItem("p1", 1, unitPrice = 30.0)), amount = 30.0), + confirmed = true + ) + + assertTrue(result.isSuccess) + val fin = finance.created.single() + assertEquals(0.0, fin.cogs, 0.001) + assertEquals(0.0, fin.lines.single().unitCostSnapshot, 0.001) + assertEquals(30.0, fin.margin, 0.001) + } + + /** + * Core 4 B4 — tras el primer finance, un last_unit_cost vivo distinto + * no muta cogs ni unitCostSnapshot del event almacenado. + */ + @Test + fun b4_second_confirm_does_not_rewrite_finance_when_cost_changes() = runBlocking { + val stock = FakeStockRepo( + mutableMapOf("p1" to costTriple(10, 2, 5.0)) + ) + val movements = FakeMovementRepo() + val finance = FakeFinanceRepo() + val useCase = ApplyOperatorStockDecisionCaseUse( + stock, movements, finance, FakeAccountRepo("op-1") + ) + val s = sale(listOf(SaleItem("p1", 2, unitPrice = 40.0)), amount = 80.0) + + val first = useCase(s, confirmed = true) + assertTrue(first.isSuccess) + assertEquals(1, finance.created.size) + assertEquals(10.0, finance.created.single().cogs, 0.001) + assertEquals(5.0, finance.created.single().lines.single().unitCostSnapshot, 0.001) + + // Costo vivo cambia (p.ej. nueva compra); reintento de confirm + stock.state["p1"] = costTriple(8, 0, 99.0) + val second = useCase(s, confirmed = true) + assertTrue(second.isSuccess) + + assertEquals(2, finance.createCalls) + assertEquals(1, finance.created.size) // no segundo documento + val stored = finance.getBySaleId("sale-1")!! + assertEquals(10.0, stored.cogs, 0.001) + assertEquals(5.0, stored.lines.single().unitCostSnapshot, 0.001) + assertTrue(stored.lines.none { it.unitCostSnapshot == 99.0 }) } + /** Core 4 B4 — createIdempotent a nivel repo: payload nuevo no sobrescribe. */ + @Test + fun b4_createIdempotent_returns_frozen_event_ignoring_new_payload() = runBlocking { + val finance = FakeFinanceRepo() + val firstWrite = SaleFinanceWrite( + saleId = "sale-x", + revenue = 100.0, + cogs = 20.0, + margin = 80.0, + userId = "op-1", + atIso = "2026-09-02T00:00:00Z", + currency = "USD", + lines = listOf( + SaleFinanceLineWrite( + productId = "p1", + quantity = 2, + unitPrice = 50.0, + unitCostSnapshot = 10.0, + lineRevenue = 100.0, + lineCogs = 20.0, + lineMargin = 80.0 + ) + ) + ) + val first = finance.createIdempotent(firstWrite) + assertEquals(10.0, first.lines.single().unitCostSnapshot, 0.001) + + val rewritten = finance.createIdempotent( + firstWrite.copy( + cogs = 999.0, + margin = -899.0, + lines = listOf( + SaleFinanceLineWrite( + productId = "p1", + quantity = 2, + unitPrice = 50.0, + unitCostSnapshot = 999.0, + lineRevenue = 100.0, + lineCogs = 1998.0, + lineMargin = -1898.0 + ) + ) + ) + ) + + assertEquals(2, finance.createCalls) + assertEquals(1, finance.created.size) + assertEquals(first.id, rewritten.id) + assertEquals(20.0, rewritten.cogs, 0.001) + assertEquals(10.0, rewritten.lines.single().unitCostSnapshot, 0.001) + } + + /** Un solo constructor primario: evita platform declaration clash Map/MutableMap en JVM. */ private class FakeStockRepo( - // Triple es invariante: mapOf(... to Triple(..., 5.0)) infiere Triple - // y no es asignable a Triple → CompilationErrorException en CI - private val state: Map> + val state: MutableMap> ) : OperatorStockRepository { val lastExistence = mutableMapOf() val lastReserved = mutableMapOf() @@ -122,9 +269,10 @@ class ApplyOperatorStockDecisionCaseUseTest { existenceDelta: Int, reservedDelta: Int ): OperatorStockSnapshot { - val (ex, res, cost) = state[productId] ?: Triple(0, 0, 0.0) + val (ex, res, cost) = state[productId] ?: Triple(0, 0, null as Double?) val nextEx = (ex + existenceDelta).coerceAtLeast(0) val nextRes = (res + reservedDelta).coerceAtLeast(0) + state[productId] = Triple(nextEx, nextRes, cost) lastExistence[productId] = nextEx lastReserved[productId] = nextRes return OperatorStockSnapshot(nextEx, nextRes, cost) @@ -134,7 +282,6 @@ class ApplyOperatorStockDecisionCaseUseTest { private class FakeMovementRepo( existing: List = emptyList() ) : OperatorStockMovementRepository { - // mapValues → Map inmutable; getOrPut requiere MutableMap private val bySale = existing .groupBy { it.saleId.orEmpty() } .mapValues { it.value.toMutableList() } @@ -159,21 +306,39 @@ class ApplyOperatorStockDecisionCaseUseTest { } } + /** + * Paridad con AppwriteOperatorSaleFinanceRepository.createIdempotent: + * guarda el primer event por sale_id y lo devuelve en reintentos. + */ private class FakeFinanceRepo( - private val existing: SaleFinanceRecord? = null + seed: SaleFinanceRecord? = null ) : OperatorSaleFinanceRepository { + private val bySaleId = mutableMapOf() val created = mutableListOf() var createCalls = 0 + init { + if (seed != null) bySaleId[seed.saleId] = seed + } + override suspend fun getBySaleId(saleId: String): SaleFinanceRecord? = - existing?.takeIf { it.saleId == saleId } + bySaleId[saleId] override suspend fun createIdempotent(event: SaleFinanceWrite): SaleFinanceRecord { createCalls++ - val found = getBySaleId(event.saleId) + val found = bySaleId[event.saleId] if (found != null) return found created += event - return SaleFinanceRecord("new", event.saleId, event.revenue, event.cogs, event.margin) + val rec = SaleFinanceRecord( + id = "new-${created.size}", + saleId = event.saleId, + revenue = event.revenue, + cogs = event.cogs, + margin = event.margin, + lines = event.lines + ) + bySaleId[event.saleId] = rec + return rec } } diff --git a/web/src/core/feature/product/presentation/components/UnifiedCatalogBar.svelte b/web/src/core/feature/product/presentation/components/UnifiedCatalogBar.svelte new file mode 100644 index 00000000..64cc624a --- /dev/null +++ b/web/src/core/feature/product/presentation/components/UnifiedCatalogBar.svelte @@ -0,0 +1,679 @@ + + + + + diff --git a/web/src/core/feature/product/presentation/screens/InternalProductScreen.svelte b/web/src/core/feature/product/presentation/screens/InternalProductScreen.svelte index 90352d3f..4cab4c79 100644 --- a/web/src/core/feature/product/presentation/screens/InternalProductScreen.svelte +++ b/web/src/core/feature/product/presentation/screens/InternalProductScreen.svelte @@ -22,6 +22,8 @@ let searchQuery = ""; let selectedCategoryId: string | null = null; + let minPrice: number | null = null; + let maxPrice: number | null = null; let selectedProduct: any = null; let pendingProductId: string | null = null; let resolvingPendingProductId: string | null = null; @@ -106,6 +108,10 @@ const handleCategorySelected = (categoryId: string | null) => { selectedCategoryId = categoryId; }; + const handlePriceRangeChanged = (min: number | null, max: number | null) => { + minPrice = min; + maxPrice = max; + }; const handleProductClick = (productId: string) => { const product = products.find((p) => p.id === productId); if (product) selectedProduct = product; @@ -162,12 +168,15 @@ {categories} {searchQuery} {selectedCategoryId} + {minPrice} + {maxPrice} loading={isLoading} {stockSyncing} {realtimeUpdating} {syncMessage} onSearchQueryChanged={handleSearchQueryChanged} onCategorySelected={handleCategorySelected} + onPriceRangeChanged={handlePriceRangeChanged} onProductClick={handleProductClick} onFavoriteClick={handleFavoriteClick} /> @@ -175,12 +184,7 @@ {#if selectedProduct}
- +