Skip to content

fix(bills): preserve split-check tax attribution - #295

Merged
khaira777 merged 21 commits into
mainfrom
fm/flocafe-253-tax-followup
Aug 13, 2026
Merged

khaira777 merged 21 commits into
mainfrom
fm/flocafe-253-tax-followup

Conversation

@khaira777

Copy link
Copy Markdown
Contributor

Intent

Continue the existing FloCafe draft PR #269 in place on the existing remote branch fix/253-split-check-allocation; do not create a replacement PR, touch issue #241/Iran work, or change unrelated issues, and do not mark the PR ready or merge it. Preserve the current #253 transaction-boundary hardening, non-negative integer largest-remainder allocation, void_adjustment exclusion, and repeat/concurrency behavior. Fix the residual user-visible attribution defect where a split bill containing categorized item tax snapshots plus configured packaging/delivery/service charge-tax snapshots reconciles each child tax total but receipt/thermal components swap item tax and charge tax attribution. The accepted implementation may allocate and persist split-specific item and charge tax snapshots in integer minor units or make every per-bill resolver consume the already allocated child breakdown; this implementation persists child-specific minor-unit snapshots and makes backend/frontend resolvers consume the marked child snapshots. Add an executable regression that creates categorized item tax plus configured charge tax, splits the bill, resolves each child receipt/thermal tax component, asserts item/charge category attribution and exact aggregate reconciliation, and preserves legacy nested and flat tax_breakdown compatibility. Preserve signed snapshot reconciliation without weakening the non-negative largest-remainder allocator or void_adjustment exclusion. Keep the change scoped to #253. Before delivery, run focused split tests, the full suite, backend and frontend lint and builds, git diff --check, and complete no-mistakes validation against current main. Commit on the local branch that tracks origin/fix/253-split-check-allocation or explicitly push the final HEAD to origin:fix/253-split-check-allocation so PR #269 updates in place; never open another PR or merge.

What Changed

  • Added minor-unit split-check allocation for tax snapshots, tax breakdowns, bill totals, charges, discounts, and signed round-offs, persisting child-specific tax attribution while excluding void_adjustment items.
  • Updated bill hydration, receipt/thermal printing, payment UI, and tax reports to consume child-scoped tax data, reconcile item and charge taxes, and preserve legacy nested and flat tax_breakdown compatibility.
  • Centralized unpaid-bill synchronization for order edits and expanded documentation and regression coverage for split checks, tax attribution, reconciliation, and payment behavior.

Risk Assessment

⚠️ Medium: No concrete source-verifiable defect was found, but the change spans complex stateful tax allocation and resolver paths whose remaining validation is owned by later pipeline phases.

Testing

Restored missing locked dependencies with npm ci, ran the three targeted suites successfully, captured reviewer-visible CLI/thermal evidence, removed transient node_modules, and left the worktree clean. No screenshot was needed because this is a receipt/thermal data-path change rather than screen layout behavior.

Evidence: Split-tax end-to-end evidence

Live split route persisted child snapshots and preserved Item Tax/Charge Tax attribution; aggregate reconciliation and signed allocation passed. 187/187 passed.


> [email protected] test:payment-methods-split
> node tests/run-electron-node-test.cjs tests/payment-methods-split-checks.test.ts

[DB] Opening database at: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-payment-methods-split-gzA1t2/flo.db
[DB] Schema: v0 → v66
[DB] Triggering auto-backup before migrating v0 → v66...
[DB] Auto-backup before migrating v0 → v66 created at /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-payment-methods-split-gzA1t2/backups/flo-backup-2026-08-13T22-31-05-665Z-pre-v0-to-v66.db
[DB] Applying migration v1: initial_schema
[DB] Install defaults loaded; first-run setup pending
[DB] Migration v1 complete
[DB] Applying migration v2: hash_plaintext_pins
[DB] Migration v2 complete
[DB] Applying migration v3: cloud_identity_and_outbox
[DB] Migration v3 complete
[DB] Applying migration v4: add_notes_limits_settings
[DB] Migration v4 complete
[DB] Applying migration v5: add_print_logs_table
[DB] Migration v5 complete
[DB] Applying migration v6: add_loyalty_settings
[DB] Migration v6 complete
[DB] Applying migration v7: add_discount_settings
[DB] Migration v7 complete
[DB] Applying migration v8: add_loyalty_index
[DB] Migration v8 complete
[DB] Applying migration v9: add_sequences_table
[DB] Migration v9 complete
[DB] Applying migration v10: fix_sequences_composite_key
[DB] Migration v10 complete
[DB] Applying migration v11: first_run_setup_uses_welcome_form
[DB] Migration v11 complete
[DB] Applying migration v12: fix_table_integer_ids
[DB] Migration v12 complete
[DB] Applying migration v13: fix_null_table_ids
[DB] Migration v13 complete
[DB] Applying migration v14: simplify_loyalty_settings
[DB] Migration v14 complete
[DB] Applying migration v15: add_instagram_handle_setting
[DB] Migration v15 complete
[DB] Applying migration v16: add_terms_accepted_at_to_users
[DB] Migration v16 complete
[DB] Applying migration v17: add_held_orders_table
[DB] Migration v17 complete
[DB] Applying migration v18: fix_null_category_ids
[DB] Migration v18 complete
[DB] Applying migration v19: backfill_product_cb_percent_and_tags
[DB] Migration v19 complete
[DB] Applying migration v20: add_tables_is_active
[DB] Migration v20 complete
[DB] Applying migration v21: clear_legacy_loyalty_expiry
[DB] Migration v21 complete
[DB] Applying migration v22: add_customers_phone_digits
[DB] Migration v22 complete
[DB] Applying migration v23: normalize_customer_phones
[MIGRATION v23] normalized: 0, unparseable: 0
[MIGRATION v23] merged 0 duplicate customer(s)
[MIGRATION v23] verification: 0 customers, 0 still non-E.164
[DB] Migration v23 complete
[DB] Applying migration v24: normalize_customer_phones_retry
[MIGRATION v24] normalized: 0, unparseable: 0
[DB] Migration v24 complete
[DB] Applying migration v25: add_order_item_addons_table
[MIGRATION v25] backfilled addons for 0 order items (0 unparseable, skipped)
[DB] Migration v25 complete
[DB] Applying migration v26: add_kds_default_view
[DB] Migration v26 complete
[DB] Applying migration v27: add_station_printer_link_and_user_stations
[DB] Migration v27 complete
[DB] Applying migration v28: seed_telemetry_settings
[DB] Migration v28 complete
[DB] Applying migration v29: whatsapp_messaging
[DB] Migration v29 complete
[DB] Applying migration v30: drop_order_items_addons_json_column
[MIGRATION v30] backfilled 0 order_item(s) still missing a normalized addons snapshot
[MIGRATION v30] Dropped order_items.addons — order_item_addons is now the only place selected addons live.
[DB] Migration v30 complete
[DB] Applying migration v31: add_customers_tag_counts_column
[DB] Migration v31 complete
[DB] Applying migration v32: add_kds_and_kot_printing_toggles
[DB] Migration v32 complete
[DB] Applying migration v33: add_addon_groups_allow_multiple_quantities
[DB] Migration v33 complete
[DB] Applying migration v34: add_order_items_voided_at
[DB] Migration v34 complete
[DB] Applying migration v35: add_tax_pack_configuration_tables
[DB] Migration v35 complete
[DB] Applying migration v36: add_product_and_addon_tax_categories
[DB] Migration v36 complete
[DB] Applying migration v37: add_transaction_tax_snapshots_and_charge_categories
[DB] Migration v37 complete
[DB] Applying migration v38: register_bundled_tax_pack_versions
[DB] Migration v38 complete
[DB] Applying migration v39: add_users_tokens_valid_after
[DB] Migration v39 complete
[DB] Applying migration v40: v2_cloud_defaults_and_tax_toggle
[DB] Migration v40 complete
[DB] Applying migration v41: support_ticket_outbox
[DB] Migration v41 complete
[DB] Applying migration v42: add_global_cashback_percent
[DB] Migration v42 complete
[DB] Applying migration v43: telemetry_default_on_for_new_installs
[DB] Migration v43 complete
[DB] Applying migration v44: store_diagnostics_outbox
[DB] Migration v44 complete
[DB] Applying migration v45: add_performance_indexes_and_normalize_timestamps
[DB] Migration v45 complete
[DB] Applying migration v46: normalize_cloud_enabled_flags_to_01
[DB] Migration v46 complete
[DB] Applying migration v47: store_diagnostics_enabled_by_default
[DB] Migration v47 complete
[DB] Applying migration v48: deactivate_reusable_demo_credentials
[DB] Migration v48 complete
[DB] Applying migration v49: add_payment_idempotency_records
[DB] Migration v49 complete
[DB] Applying migration v50: add_order_idempotency_records
[DB] Migration v50 complete
[DB] Applying migration v51: enforce_global_payment_transaction_refs
[DB] Migration v51 complete
[DB] Applying migration v52: restore_method_scoped_transaction_refs
[DB] Migration v52 complete
[DB] Applying migration v53: scope_idempotency_records_to_user
[DB] Migration v53 complete
[DB] Applying migration v54: repair_retry_ownership_and_payment_reference_history
[DB] Migration v54 complete
[DB] Applying migration v55: durable_token_revocations
[DB] Migration v55 complete
[DB] Applying migration v56: persist_station_assignment_scope
[DB] Migration v56 complete
[DB] Applying migration v57: rename_gstin_to_generic_tax_registration_number
[DB] Migration v57 complete
[DB] Applying migration v58: configurable_manual_payment_methods
[DB] Migration v58 complete
[DB] Applying migration v59: split_checks_by_item_quantity
[DB] Migration v59 complete
[DB] Applying migration v60: seed_split_checks_disabled_setting
[DB] Migration v60 complete
[DB] Applying migration v61: seed_server_app_enabled_setting
[DB] Migration v61 complete
[DB] Applying migration v62: normalize_cloud_last_error
[DB] Migration v62 complete
[DB] Applying migration v63: seed_printer_trim_decimals_setting
[DB] Migration v63 complete
[DB] Applying migration v64: drop_unused_printer_usb_device_path
[DB] Migration v64 complete
[DB] Applying migration v65: seed_bill_content_visibility_settings
[DB] Migration v65 complete
[DB] Applying migration v66: seed_bill_template_settings
[DB] Migration v66 complete
[DB] integrity_check: ok
[DB] foreign_key_check: clean
  ✓ negative round-off uses signed largest-remainder allocation
[Auth] Generated new JWT secret for this install
  ✓ fresh database seeds split checks disabled
  ✓ missing split-check setting reads as a safe default
  ✓ fallback keeps split checks disabled
  ✓ fresh database seeds printer decimal trimming disabled
  ✓ missing printer decimal-trim setting reads as a safe default
  ✓ fallback keeps printer decimal trimming disabled
  ✓ fresh database seeds the classic bill template
  ✓ fresh database seeds an empty bill footer
  ✓ bill-template migration preserves an existing template choice
  ✓ bill-template migration preserves an existing footer
  ✓ missing bill template reads as a safe default
  ✓ missing bill template falls back to classic
  ✓ missing bill footer reads as a safe default
  ✓ missing bill footer falls back to an empty message
  ✓ fresh database shows restaurant name by default
  ✓ fresh database hides tax ID by default
  ✓ fresh database shows tax breakdown by default
  ✓ fresh database shows customer name by default
  ✓ fresh database shows customer number by default
  ✓ fresh database shows table number by default
  ✓ bill template setting can be saved for backend invoice printing
  ✓ bill footer setting can be saved for backend in

... [5025 bytes truncated] ...

st returns 409 Conflict
  ✓ splitting child bill returns 409 Conflict
  ✓ only one split group exists in database for order
  ✓ concurrent HTTP request: exactly one request returns 201
  ✓ concurrent HTTP request: duplicate request returns 409
  ✓ concurrent HTTP request: exactly one split group exists in database
  ✓ nested tax breakdown split returns 201
  ✓ returns 2 split bills
  ✓ persisted DB tax_breakdown is an array
  ✓ persisted DB tax_breakdown outer array preserved as nested array
  ✓ API response tax_breakdown is an array
  ✓ sum of check component amounts equals bill tax_amount exactly
  ✓ persisted DB tax_breakdown is an array
  ✓ persisted DB tax_breakdown outer array preserved as nested array
  ✓ API response tax_breakdown is an array
  ✓ sum of check component amounts equals bill tax_amount exactly
  ✓ sum of split tax_amounts equals source tax_amount 0.02
  ✓ Tax A reconciles across checks to 0.01
  ✓ Tax B reconciles across checks to 0.01
  ✓ flat tax breakdown split returns 201
  ✓ flat tax_breakdown is an array
  ✓ flat tax_breakdown elements are objects, not nested arrays
  ✓ sum of flat component amounts equals bill tax_amount exactly
  ✓ flat tax_breakdown is an array
  ✓ flat tax_breakdown elements are objects, not nested arrays
  ✓ sum of flat component amounts equals bill tax_amount exactly
  ✓ partial-quantity legacy tax split returns 201
  ✓ partial-quantity child exposes only its billed quantity
  ✓ partial-quantity child scales nested legacy tax evidence to its tax target
  ✓ backend and frontend split resolvers agree for partial legacy tax
  ✓ partial legacy tax components reconcile to each child tax amount
  ✓ partial-quantity child exposes only its billed quantity
  ✓ partial-quantity child scales nested legacy tax evidence to its tax target
  ✓ backend and frontend split resolvers agree for partial legacy tax
  ✓ partial legacy tax components reconcile to each child tax amount
  ✓ partial-quantity legacy tax reconciles across children
  ✓ categorized items plus configured packaging charge order is created
  ✓ source tax includes two item taxes and one packaging tax
  ✓ snapshot-tax split returns 201
  ✓ discounting a split child is rejected before overwriting its tax snapshot
  ✓ rejected split-child discount preserves the marked tax snapshot
  ✓ rejected split-child discount preserves tax attribution
  ✓ preserved split-child discount snapshot still reconciles to tax_amount
  ✓ backend thermal receipt tax components keep item and charge attribution per child
  ✓ frontend receipt tax components keep item and charge attribution per child
  ✓ resolved child tax components reconcile to child tax_amount
  ✓ split child total composes from allocated exclusive tax and bill fields
  ✓ backend thermal receipt tax components keep item and charge attribution per child
  ✓ frontend receipt tax components keep item and charge attribution per child
  ✓ resolved child tax components reconcile to child tax_amount
  ✓ split child total composes from allocated exclusive tax and bill fields
  ✓ item tax components reconcile across split children
  ✓ configured charge tax components reconcile across split children
  ✓ aggregate resolved snapshot tax equals source order tax exactly
  ✓ backend split resolver preserves legacy item tax beside marked snapshots
  ✓ frontend split resolver preserves legacy item tax beside marked snapshots
  ✓ discounting an unsplit mixed-tax bill succeeds
  ✓ discount scales mixed snapshot and legacy tax together
  ✓ mixed snapshot and legacy tax split returns 201
  ✓ persisted child breakdown preserves mixed item and legacy ownership
  ✓ mixed split backend resolver preserves item and legacy ownership
  ✓ mixed split frontend resolver preserves item and legacy ownership
  ✓ mixed split tax components reconcile to each child tax amount
  ✓ persisted child breakdown preserves mixed item and legacy ownership
  ✓ mixed split backend resolver preserves item and legacy ownership
  ✓ mixed split frontend resolver preserves item and legacy ownership
  ✓ mixed split tax components reconcile to each child tax amount
  ✓ mixed split item tax remains with its categorized owner after discount
  ✓ mixed split legacy tax remains scaled across item quantities
  ✓ mixed split tax categories reconcile to the discounted source tax
  ✓ tax component report keeps mixed legacy tax additive after splitting
  ✓ discounted sub-cent legacy tax remains split-compatible
  ✓ discounted sub-cent legacy tax keeps the aggregate source cent
  ✓ discounted sub-cent legacy split returns 201
  ✓ discounted sub-cent legacy tax stays with its owning child
  ✓ discounted sub-cent legacy components reconcile exactly
  ✓ discounted sub-cent legacy tax stays with its owning child
  ✓ discounted sub-cent legacy components reconcile exactly
  ✓ nested owner-local legacy split returns 201
  ✓ child tax totals use the same owner-local rounding as nested legacy evidence
  ✓ nested owner-local breakdown reconciles to its child tax total
  ✓ nested legacy component cents remain with their owner allocation
  ✓ nested owner-local breakdown reconciles to its child tax total
  ✓ nested legacy component cents remain with their owner allocation
  ✓ legacy tax split for void ownership returns 201
  ✓ legacy tax item can enter preparing before void
  ✓ voiding legacy tax item remains supported after splitting
  ✓ void adjustment legacy tax stays with its original owner
  ✓ void adjustment legacy components reconcile exactly
  ✓ void adjustment legacy tax stays with its original owner
  ✓ void adjustment legacy components reconcile exactly
  ✓ snapshot-tax split for void regression returns 201
  ✓ snapshot item moves to preparing before the void regression
  ✓ voiding a split snapshot item keeps the mutation supported
  ✓ voided split child keeps item and charge tax categories
  ✓ void evidence is not allocated to the sibling child
  ✓ voided split child tax components reconcile exactly
  ✓ void sync preserves marked child tax snapshots
  ✓ voided split child keeps item and charge tax categories
  ✓ void evidence is not allocated to the sibling child
  ✓ voided split child tax components reconcile exactly
  ✓ void sync preserves marked child tax snapshots
  ✓ voided split child tax totals reconcile to the updated order
  ✓ uneven split snapshot components reconcile within their owner
  ✓ uneven split snapshot components remain additive across children
  ✓ snapshot allocations preserve item ownership for tax and line bases
  ✓ cancelling an item after splitting keeps the order mutation supported
  ✓ cancel sync preserves exact item and charge tax attribution
  ✓ cancel sync preserves exact frontend item and charge tax attribution
  ✓ cancel sync preserves marked child tax snapshots
  ✓ cancel sync keeps backend and frontend tax attribution aligned
  ✓ cancel sync resolved tax reconciles to each child tax amount
  ✓ cancel sync preserves exact item and charge tax attribution
  ✓ cancel sync preserves exact frontend item and charge tax attribution
  ✓ cancel sync preserves marked child tax snapshots
  ✓ cancel sync keeps backend and frontend tax attribution aligned
  ✓ cancel sync resolved tax reconciles to each child tax amount
  ✓ cancel sync item tax reconciles across children
  ✓ cancel sync charge tax reconciles across children
  ✓ cancel sync aggregate tax attribution reconciles to the updated order
  ✓ restoring an item after splitting keeps the order mutation supported
  ✓ restore sync recomputes child item and charge tax attribution
  ✓ restore sync resolved tax reconciles to each child tax amount
  ✓ restore sync recomputes child item and charge tax attribution
  ✓ restore sync resolved tax reconciles to each child tax amount
  ✓ signed tax snapshot allocation keeps each child non-duplicated
  ✓ signed tax snapshot allocations reconcile exactly to the source
[DB] Database closed

187/187 passed
Evidence: Thermal rendering evidence

Source: Thermal rendering evidence (local file: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/no-mistakes-evidence/01KZWQ7K5ZMR9WD9HTXH4H3P9S/printer-rendering.log)

Rendered thermal receipt checks passed: categorized VAT and legacy levy labels rendered, categorized item legacy copy was omitted. 110 passed, 0 failed.
- Outcome: 🔧 3 issues found → auto-fixed ✅ across 2 runs (22m56s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 2 issues found → auto-fixed (14) ✅
  • 🚨 main/routes/bills.ts:366 - Snapshot components are allocated independently, but child tax totals are allocated separately. Largest-remainder allocation is not additive: with two 0.01 components and child weights 1:2, components allocate as [0,1]¢ each while total tax allocates [1,1]¢. The first child then has a marked snapshot totaling 0 but tax_amount 0.01, causing the resolver to emit generic Tax or distort item/charge attribution. Reconcile component allocations against each allocated child tax minor target at this shared boundary, preserving signed handling.
  • ⚠️ main/services/tax-components.ts:181 - The resolver now depends on the split marker, but supported item cancel/restore flows can overwrite one unpaid split child with the unmarked aggregate tax snapshot (main/routes/index.ts updates a bill selected only by order_id). That child then misses this fast path and falls back to shared item snapshots plus the full charge snapshot, making the original attribution swap reachable again. Preserve/recompute child-specific snapshots at that bill-sync boundary or prevent these mutations after splitting.

🔧 Fix: Fixed tax snapshot attribution and post-split bill resync
2 issues (1 error, 1 warning) still open:

  • 🚨 main/routes/bills.ts:432 - Required criterion: “Fix the residual user-visible attribution defect ... asserts item/charge category attribution.” Each source snapshot is first allocated with owner-specific weights, but the new global reconciliation at this boundary transfers cents across independent item/charge snapshot entries. For example, 1¢ of item A on child 1 and 1¢ of item B on child 2 can reconcile to a bill-weight target of [0,2], moving item A’s cent to child 2. The marked snapshot then makes receipt/thermal resolvers show the wrong attribution. Reconcile within ownership-preserving boundaries or derive child totals from owner-aware component allocations.
  • ⚠️ main/routes/bills.ts:450 - Required criterion: “persists child-specific minor-unit snapshots.” Component allocations use per-snapshot weights, but grossAmount and taxableBase are allocated using aggregate bill weights. An item snapshot owned by child 1 can therefore have its persisted gross value spread onto child 2, making child snapshot evidence internally inconsistent. Allocate these fields with the corresponding local snapshot weights and preserve signed minor-unit reconciliation.

🔧 Fix: Preserve owner-local split tax snapshot allocation
2 errors still open:

  • 🚨 main/routes/bills.ts:1445 - Required criterion: “Preserve or recompute marked child-specific tax snapshots across supported post-split unpaid bill/order mutation paths so receipt and thermal resolvers cannot regress to shared source snapshots.” The unpaid split-child POST /api/bills/:id/applyDiscount path remains reachable and writes the unallocated aggregate taxRollup.snapshotJson at main/routes/bills.ts:1445, removing the split marker and recreating the attribution swap. Reject this operation for split children or apply an owner-aware child allocation.
  • 🚨 main/routes/bills.ts:678 - Required criterion: “Preserve signed snapshot reconciliation without weakening the non-negative largest-remainder allocator or void_adjustment exclusion.” After a split, voiding a prepared item creates a voided original plus a void_adjustment; snapshotWeights includes both because this filter excludes only cancelled items. The adjustment has no bill_items, so it falls back to aggregate weights and distributes its negative snapshot across sibling checks, while ordinary total allocation excludes both statuses. This can show negative tax on a child that owns no voided item and make child tax inconsistent with its allocated total. Exclude void evidence from child snapshots or preserve the original owner for the adjustment pair at this shared boundary.

🔧 Fix: Preserve split tax snapshots through mutation paths
4 issues (3 errors, 1 warning) still open:

  • 🚨 main/services/tax-components.ts:181 - The any-marked-snapshot fast path ignores legacy item tax. Mixed orders can contain categorized snapshots plus legacy tax_breakdown entries; the snapshot sum then does not cover tax_amount, but marked child snapshots still make both resolvers skip legacy components and scale the remaining snapshot components to the full tax total. This contradicts the required “preserves legacy nested and flat tax_breakdown compatibility.” Preserve residual legacy tax or only use the fast path when snapshots cover the complete tax.
  • 🚨 main/routes/bills.ts:758 - When snapshot tax allocation matches, this replaces each child tax_amount with owner-local snapshot tax, while total/subtotal/charge fields were already allocated using aggregate bill weights. For example, exclusive items totaling 20+2 tax and 40+2 tax split into weights 22:42 produce child totals 22.00/42.00, subtotals 20.63/39.37, but owner-local tax 2.00/2.00; the child financial fields no longer add to their displayed totals. Derive totals from consistent child financial allocations, accounting for exclusive versus inclusive tax, or keep tax_amount allocation aligned with total.
  • 🚨 main/routes/bills.ts:1331 - The new split-child discount rejection is checked before the withTxn block, and the transaction re-reads neither the bill nor split_group_id before writing taxRollup.snapshotJson. If applyDiscount reads an unsplit bill, split-check commits, and applyDiscount then enters its transaction, it overwrites the newly split child and removes the marker. Revalidate split_group_id inside the transaction before the UPDATE; apply the same lock-boundary recheck to sibling order-discount paths.
  • ⚠️ tests/payment-methods-split-checks.test.ts:515 - The acceptance requires executable coverage that asserts item/charge attribution and exact reconciliation, but the post-split cancel regression only checks backend/frontend equality and that their sum matches each child tax_amount (lines 512-516). Two resolvers returning the same incorrect attribution would pass. Assert concrete Item Tax and Charge Tax amounts per child and aggregate them after cancellation, as the restore/void cases do.

🔧 Fix: Preserve legacy tax and compositional split totals
2 errors still open:

  • 🚨 main/services/tax-components.ts:194 - Required criterion: “preserves legacy nested and flat tax_breakdown compatibility.” The marked-snapshot branch merges legacy item tax without ensuring items belong to the child bill. Reports pass all order items to every split-bill document, duplicating legacy tax across children; partial-quantity bill items also retain unscaled tax_breakdown. Scope legacy evidence to bill_items and child quantity before merging.
  • 🚨 main/routes/bills.ts:796 - The helper allocates across every split bill, then skips paid rows. Item cancellation remains allowed when another split child is paid; cancelling the only item on an unpaid child can allocate the surviving order/charge total to the paid child while leaving it unchanged, producing inconsistent bill and order totals. Reject such mutations or protect paid-child allocations before updating unpaid children.

🔧 Fix: Scope partial legacy tax and protect paid split siblings
4 issues (2 errors, 2 warnings) still open:

  • 🚨 main/services/tax-components.ts:194 - The required “preserves legacy nested and flat tax_breakdown compatibility” is still violated because this branch merges legacy evidence from whatever document.items the caller supplies. /api/reports/tax-components passes all order items to every split bill, duplicating legacy tax across children; the printer path filters by bill but scales only subtotal/tax_amount/total, leaving partial-quantity legacy tax unscaled. Scope items and quantities at a shared bill-hydration boundary before this merge.
  • 🚨 main/routes/bills.ts:917 - Mixed marked-snapshot plus legacy orders still lose ownership attribution. With marked item tax 1.00, legacy item tax 0.50, and two equal children, snapshot totals do not equal source tax, so this falls back to aggregate child tax targets of 0.75 each; the marked snapshot remains [1.00, 0], legacy breakdown becomes [0.25, 0.25], and resolver reconciliation changes the visible categories to approximately [Item 0.60, Legacy 0.15] and [Item 0.00, Legacy 0.75]. This contradicts the required exact item/charge attribution and legacy compatibility. Allocate the residual legacy tax owner-locally or only use the marked path when it covers the complete tax.
  • ⚠️ main/routes/bills.ts:48 - scaleTaxBreakdown rounds each legacy component independently. A quantity-2 legacy item with two 0.01 components and 0.02 total tax split one unit per child produces child tax_amount 0.01 but child breakdown 0.01 + 0.01 = 0.02; the backend resolver may rescale this while the frontend legacy path does not, so receipt/thermal outputs diverge. Use owner-local minor-unit/remainder reconciliation for legacy breakdowns before rendering.
  • ⚠️ main/routes/bills.ts:830 - The new split-sync guard rejects only fully paid siblings, and the update loop skips only payment_status === 'paid'. A split child can be partial; cancelling an item can reduce its allocated total below its existing paid_amount, after which this writes total and balance while retaining the old paid_amount/status, creating an overpaid partial bill and inconsistent settlement state. Reject mutations after any split-child payment or preserve the paid child allocation explicitly.

🔧 Fix: Scope legacy tax ownership and block paid split mutations
2 issues (1 error, 1 warning) still open:

  • 🚨 main/routes/bills.ts:980 - The split legacy residual compares scaled bill tax/snapshots with raw pre-discount order_items.tax_amount. A mixed categorized+legacy order discounted before splitting therefore falls back to aggregate child tax targets, while both resolvers merge unscaled child legacy evidence; item-versus-legacy attribution becomes incorrect despite totals reconciling. This contradicts the required preservation of legacy nested/flat breakdown compatibility and exact category attribution. Derive the residual from the already scaled source breakdown or apply the same discount scaling before child resolution.
  • ⚠️ main/routes/reports.ts:212 - The tax-components report now calls getOrderWithItems once per bill, and that helper performs multiple database queries plus repeated split-group scans. This replaces the previous batched item query with an N+1 path for long date ranges. Batch or cache hydration by order/split group.

🔧 Fix: Fix discount-scaled tax and batch report hydration
3 issues (2 errors, 1 warning) still open:

  • 🚨 main/routes/bills.ts:1018 - Per-item legacy tax is rounded before reconciliation (line 959), and a mismatch falls back to aggregate child tax targets at line 1018. Example: two legacy rows with 0.01 tax each and a 66.67% discount produce source tax 0.01, but each child-scoped row rounds to 0.00; backend/frontend resolution then loses legacy attribution and can disagree. This contradicts the required preservation of legacy nested/flat tax_breakdown compatibility. Reconcile legacy allocations against the aggregate source minor total before fallback.
  • 🚨 main/routes/bills.ts:1037 - The breakdown-owner mapper skips only cancelled items, so voided and void_adjustment evidence is still processed. A voided legacy item retains its bill_items owner, but its synthetic adjustment has no bill_items row and therefore falls back to active sibling weights in allocateTaxBreakdown; on a split legacy-only order this can persist positive tax on the original child and negative tax on the sibling, which the unmarked resolvers display. Exclude void evidence or preserve the original owner for the adjustment pair, maintaining the required void_adjustment exclusion.
  • ⚠️ main/routes/bills.ts:853 - allocateTaxBreakdown still performs a global reconciliation across independent source entries at lines 853-856. In an uneven mixed snapshot/legacy split, this can transfer a cent from a marked item entry to a legacy owner to match child totals. The receipt/thermal resolver uses marked snapshots, but the frontend payment UI renders bill.tax_breakdown directly (frontend/src/components/pos/PaymentModal.tsx:371), so the cashier can see the item/legacy category on the wrong child. Reconcile within ownership boundaries or make this consumer use the marked-snapshot resolver.

🔧 Fix: Preserve legacy split tax ownership and void attribution
2 errors still open:

  • 🚨 frontend/src/lib/printer/tax-components.ts:150 - Required criterion: “makes backend/frontend resolvers consume the marked child snapshots” while preserving legacy attribution. The resolver merges document.order?.items at this line, but the Orders page overwrites fresh child data with the unscoped list order ({ ...latestBill, order }). Printing a split child with mixed marked and legacy tax therefore includes the sibling’s full legacy tax, then rescales categories to the child total, producing incorrect attribution.
  • 🚨 frontend/src/lib/printer/tax-components.ts:135 - Required criterion: “Preserve signed snapshot reconciliation without weakening the non-negative largest-remainder allocator or void_adjustment exclusion.” Both frontend item filters omit void_adjustment. A legacy-only split after a prepared-item void can therefore include the synthetic negative tax line in browser/thermal resolution, diverging from the backend and showing shifted or negative tax.

🔧 Fix: Preserve child-scoped frontend printing and void-tax filtering
3 issues (2 errors, 1 warning) still open:

  • 🚨 main/routes/bills.ts:1035 - The required “preserves legacy nested and flat tax_breakdown compatibility” is violated for bill-level legacy tax with no legacy item rows. The residual is allocated into legacyTaxMinors, but this branch returns zero legacyExclusiveTaxMinors; composeSplitTotals then omits that exclusive tax from each child total while tax_amount includes it. Derive exclusivity from the legacy breakdown or preserve compositional totals.
  • 🚨 main/services/tax-components.ts:194 - The required “preserves legacy nested and flat tax_breakdown compatibility” is violated when a marked child snapshot coexists with legacy document-level tax. This fast path merges only marked snapshots and legacy item rows, never document.tax_breakdown, so a legacy charge component is dropped and reconcileTotal relabels its amount as item tax. The frontend resolver has the same defect at frontend/src/lib/printer/tax-components.ts:163.
  • ⚠️ main/routes/bills.ts:1245 - The requirement to preserve non-negative integer largest-remainder allocation is undermined because roundOff is passed to allocateMinorUnits even though applyPayableRounding can produce negative values. For a -2¢ adjustment with child weights 1:3, this allocator yields [0,-2] instead of signed largest-remainder allocation [-1,-1], shifting the child total distribution. Allocate signed round-off separately while keeping ordinary fields on the non-negative allocator.

🔧 Fix: Preserve legacy tax and signed split allocations
3 issues (2 errors, 1 warning) still open:

  • 🚨 main/services/tax-components.ts:217 - The required behavior is to “make backend/frontend resolvers consume the marked child snapshots” while preserving legacy breakdown compatibility. The split fast path merges the child snapshot with documentLegacyComponents, which re-adds the child’s normal item/charge tax_breakdown mirror. A child with snapshot Item Tax 1.00 + Charge Tax 0.50 and the same persisted breakdown merges to 3.00, then rescales to 1.50, displaying 0.75/0.375 instead of 1.00/0.50. The frontend has the same defect at frontend/src/lib/printer/tax-components.ts:175-178. Include only residual document-level legacy entries not represented by the marked snapshot.
  • 🚨 main/routes/bills.ts:1035 - The required nested legacy tax compatibility and exact child reconciliation are still violated because child tax totals and persisted breakdowns use different rounding boundaries. allocateLegacyTaxContribution aggregates all legacy owner weights and allocates the residual once (lines 1003-1035), while allocateTaxBreakdown allocates each nested owner group independently (lines 919-923). With two 1¢ legacy rows each split 1:2, tax_amount allocates [1¢,1¢] but both per-row breakdown cents allocate to child 2, so child 1 loses the named legacy component and the resolver falls back to generic/scaled tax. Derive child tax totals from the same owner-local breakdown allocations or reconcile at each owner boundary.
  • ⚠️ main/routes/bills.ts:920 - The required flat tax_breakdown compatibility is incomplete. Flat entries are treated as one global group and reconciled against checkTaxMinors at lines 920-923, so cents can move between independent item/charge owners when flat legacy data coexists with child-specific snapshots. PaymentModal renders bill.tax_breakdown directly, allowing cashier-visible attribution to differ from the marked-snapshot receipt/thermal resolver. Preserve owner-local allocations where ownership is known or make this consumer use the marked child resolver.

🔧 Fix: Preserve owner-local split tax attribution
1 error still open:

  • 🚨 frontend/src/components/pos/PaymentModal.tsx:372 - This changed hunk passes the bare /bills/generate response to resolveTaxComponents. For a non-split mixed legacy bill, it has no order.items; the resolver therefore selects tax_snapshot and skips tax_breakdown, hiding the residual legacy components in the payment modal. This contradicts the required “preserves legacy nested and flat tax_breakdown compatibility.” In the no-items snapshot path, merge residual document legacy components after subtracting mirrored snapshot components (as the marked-child path does).

🔧 Fix: Preserve residual legacy tax in generated bills
1 error still open:

  • 🚨 main/services/tax-components.ts:265 - The required criterion “preserves legacy nested and flat tax_breakdown compatibility” remains violated when active item snapshots coexist with document-level legacy tax and no charge snapshot. At main/services/tax-components.ts:265 (and frontend frontend/src/lib/printer/tax-components.ts:238), the resolver reconciles only item snapshot components to the full tax_amount, relabeling the legacy residual as item tax; e.g. Item Tax 1.00 plus Legacy Charge Tax 0.50 renders Item Tax 1.50. Include residual document-level legacy components in this active-item path, or only take the snapshot fast path when item evidence covers the document total.

🔧 Fix: Preserve active-item legacy tax attribution
1 error still open:

  • 🚨 main/services/tax-components.ts:220 - Required criterion: “preserves legacy nested and flat tax_breakdown compatibility.” The split fast path merges child-scoped legacy item evidence with residual entries from the globally allocated flat bill breakdown. With two distinct legacy item taxes of 1.00 split across weights 1:2, the flat breakdown is allocated roughly 0.67/0.33 per child, then reconciliation scales the merged results, visibly moving part of each item’s tax to the other child. Preserve flat-entry ownership during allocation or exclude already represented child item evidence from this residual merge; the frontend path has the same defect at frontend/src/lib/printer/tax-components.ts:183.

🔧 Fix: Preserve flat legacy tax ownership across split children
✅ Re-checked - no issues remain.

🔧 **Test** - 3 issues found → auto-fixed ✅
  • 🚨 main/routes/bills.ts:1532 - The split-check endpoint returns HTTP 500 (Cannot read properties of undefined (reading '0')) even for a basic two-check dine-in order, so child bills are not created.
  • 🚨 main/services/tax-components.ts:230 - The backend marked split-snapshot resolver passes number components into Decimal-only merge logic, throwing component.amount.toDecimalPlaces is not a function for Item Tax plus Charge Tax.
  • 🚨 main/services/tax-components.ts:288 - A categorized item snapshot still leaks stale document-level legacy tax (WRONG) into resolved components instead of suppressing it.
  • npm run test:tax-components
  • npm run test:payment-methods-split
  • node tests/run-electron-node-test.cjs /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/no-mistakes-evidence/01KZWQ7K5ZMR9WD9HTXH4H3P9S/split-diagnostic.test.ts
  • git diff --check ae4c31e... a815e70...
  • Final worktree status check; repository-local node_modules removed after testing

🔧 Fix: Fixed split tax attribution regressions
✅ Re-checked - no issues remain.

  • npm run test:tax-components
  • npm run test:payment-methods-split
  • npm run test:printer
  • git status --short --branch after cleanup
✅ **Document** - passed

✅ No issues found.

⚠️ **Lint** - 1 error
  • 🚨 Targeted backend and frontend ESLint checks could not start because required dependencies are not installed; git diff --check passes.
✅ **Push** - passed

✅ No issues found.

@khaira777
khaira777 requested a review from itsbkm as a code owner August 13, 2026 22:49
@khaira777
khaira777 force-pushed the fm/flocafe-253-tax-followup branch from c2c9eab to 893000e Compare August 13, 2026 22:52
@khaira777 khaira777 self-assigned this Aug 13, 2026
@khaira777
khaira777 merged commit de207ae into main Aug 13, 2026
6 checks passed
@khaira777
khaira777 deleted the fm/flocafe-253-tax-followup branch August 13, 2026 23:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant