@blamejs/blamejs-shop 0.4.115 → 0.4.117
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/lib/asset-manifest.json +1 -1
- package/lib/cost-layers.js +33 -14
- package/lib/sales-tax-filings.js +87 -19
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,10 @@ upgrading across more than a few patches at a time.
|
|
|
8
8
|
|
|
9
9
|
## v0.4.x
|
|
10
10
|
|
|
11
|
+
- v0.4.117 (2026-06-26) — **Weighted-average COGS reports reconstruct each sale's cost exactly, with no penny drift.** The weighted-average cost-of-goods-sold attribution stored a per-unit cost rounded to the nearest minor unit on each attribution row. The COGS reports (per-order and per-period) recover each line's cost as quantity times that per-unit price — there is no stored line total — so the residual attribution row, whose quantity does not always divide its cost evenly, reconstructed a total that differed from the cost the sale itself recorded, by up to one minor unit per multi-unit residual row. The drift could be a gain or a loss and accumulated across every weighted-average sale into the per-order profit figure and the period COGS report. Each attribution now splits a debit whose cost does not divide evenly into a floor-priced remainder and a ceil-priced sliver, so quantity times unit price summed over the rows reproduces the sale's cost exactly. FIFO and LIFO costing, and weighted-average debits that divide evenly, are unchanged. **Fixed:** *Weighted-average COGS attribution no longer drifts from the sale's recorded cost* — A weighted-average sale records the cost it consumes, then writes per-layer attribution rows the COGS reports sum back up. The attribution stored a single integer per-unit price, rounded — and because the reports reconstruct each row as quantity times that price (there is no stored line-total column), the residual-bearing row reconstructed quantity-times-rounded-unit, which differs from the attributed cost whenever the quantity does not divide it evenly (for example three units carrying a cost of 23 stored 8 per unit and reconstructed 24). A debit whose cost does not divide evenly across its units is now split into a floor-priced remainder and a ceil-priced sliver — (quantity minus r) units at the floor price and r units at the floor-plus-one price, where r is the leftover — so the rows reconstruct the attributed cost exactly. The per-order and per-period COGS reports now equal the cost each sale recorded; layer reversal restores the same quantity and value.
|
|
12
|
+
|
|
13
|
+
- v0.4.116 (2026-06-26) — **Sales-tax filings net partial refunds and derive owed tax from the jurisdiction's default rate.** Two correctness fixes to the sales-tax filing computation. A partial refund leaves its order in a paid / fulfilling / shipped / delivered status (there is no partially-refunded state), so the order still counts toward the filing for the period it sold in — but the filing counted the order's FULL tax and subtotal, ignoring the refunded portion, which over-stated collected tax and the amount remitted to the authority. A partial refund recorded inside the filing window now reduces that order's contribution to net taxable sales and net collected tax, apportioned across tax and subtotal by the order's own grand-total structure. Separately, the owed re-derivation attributed every order to the first rate row covering its date regardless of category, so a reduced category rate (e.g. food) defined alongside the jurisdiction's default rate in the same window could be applied to all revenue — and which rate won depended on the database's row order, making the owed figure wrong and non-deterministic. The owed re-derivation now models the jurisdiction's default (category-less) rate only; the collected figure still reflects the actual per-order tax each order was charged at its own rate. **Fixed:** *Partial refunds are netted out of a sales-tax filing instead of counting full tax* — A partial refund is recorded as a same-status order transition that does not change the order's status, subtotal, or tax columns, so the order remained in the filing with its pre-refund tax and subtotal counted in full — over-stating collected tax and over-remitting. computeFiling now sums the partial refunds recorded inside the filing window per order and nets each order's taxable subtotal and collected tax by the refunded share, apportioned across tax and subtotal by the order's grand total (half-even, integer minor units). Refunds are attributed to the period they occur in; an order with no in-window refund is unaffected, and recomputing a filing is idempotent. · *Owed tax is re-derived from the jurisdiction's default rate, deterministically* — The owed re-derivation took the first tax-rate row covering an order's date with no regard for category. Because a category-specific rate (such as a reduced food rate) can legally coexist with the jurisdiction's default rate in the same window, whichever row the database returned first claimed all revenue — yielding a wrong owed figure that flipped with the database's row order. The re-derivation now selects only the jurisdiction's default (category-less) rate, so the owed figure is deterministic and modelled on the jurisdiction's primary rate. The collected figure is unchanged: it remains the sum of the actual tax each order was charged at its own category-aware rate at order time.
|
|
14
|
+
|
|
11
15
|
- v0.4.115 (2026-06-26) — **Adding a bundle with a multi-quantity member no longer charges above the advertised bundle price.** A bundle's discounted price is split across its members and stored as a single integer per-unit price on each cart line, so a member's realized cost is its quantity times that per-unit price. When a member's quantity is greater than one and its allocated share is not divisible by that quantity, the leftover cents could not be returned without raising the per-unit price by a whole quantity-step — and the allocator did exactly that, pushing the realized cart subtotal a few cents ABOVE the bundle price the customer saw on the product page. The allocation now returns leftover cents only in whole quantity-steps and leaves any final sub-step residual off, so the realized subtotal is at most the advertised bundle price, never above it (a residual of fewer than the member's quantity in cents is dropped in the customer's favour in the cases a single integer per-unit price cannot represent exactly). Bundles whose members are all single-unit, and bundles whose discounted allocation divides evenly, are unaffected. **Fixed:** *Bundle with a quantity-greater-than-one member never charges above the quoted price* — The bundle-to-cart allocation converts each member's share of the discounted bundle price into a single integer per-unit price (floor) and returns the cents lost to that floor. A single-unit member absorbs the shortfall exactly; otherwise the cents are returned in whole quantity-sized steps. The final sub-step residual — strictly fewer cents than any remaining member's quantity — was being recovered by bumping a multi-unit member's per-unit price up by one, which raised that line's total by a whole quantity-step and pushed the realized subtotal above the quoted bundle price. That residual is now left off instead: the realized subtotal is at most the advertised price (a sub-quantity-cent undercharge in the customer's favour when an integer per-unit price cannot land on the quote exactly), and never exceeds it.
|
|
12
16
|
|
|
13
17
|
- v0.4.114 (2026-06-26) — **A mid-cycle subscription downgrade now issues the proration credit the customer is owed instead of dropping it.** When a subscription plan changed mid-billing-period to a cheaper plan, the credit for the outgoing plan's unused time exceeded the incoming plan's partial-period charge — and that net credit was silently discarded. The proration adjustment is recorded as a single invoice whose amount is the net of charge minus credit, and a negative net (the downgrade case) was clamped to zero with no mechanism to apply the remainder, so the customer lost the money they were owed. A mid-cycle downgrade now issues that owed credit to the customer's store-credit ledger. The plan-change component takes an optional storeCredit handle for this; when a downgrade owes a credit and no handle is wired, the change is refused (an immediate change throws before any state changes) or left pending (a scheduled change is skipped and retried on a later sweep) rather than applied with the credit lost. Upgrades and same-price changes are unchanged. **Fixed:** *Mid-cycle plan downgrade credit is issued to store credit, not dropped* — A subscription plan change splits the proration into a charge (billed through the invoice ledger) and a credit (the unused remainder of the outgoing plan). For a downgrade the credit exceeds the charge, and the invoice — which can only carry a charge — clamped the negative net to zero, so the owed remainder was silently lost. The plan-change component now issues that remainder (proration credit minus the partial-period charge) to the customer's hash-chained store-credit ledger, correlated to the change that produced it and gated on the same atomic transition claim that prevents double application. The credit is settled as part of winning that claim: if the store-credit write fails (a transient error), the plan transition is rolled back and the change is left reclaimable so a retry settles it cleanly — the credit is never finalized as lost. The proration invoice still records the (zero) charge, so a downgrade never overcharges. · *A downgrade with no credit vehicle is refused, not applied with the credit lost* — The plan-change component accepts an optional storeCredit handle. When a downgrade owes a credit but no handle is wired, an immediate change is refused before any row is written or plan transition is applied (the call throws), and a scheduled change is left pending and retried on a later sweep once a handle is available — never transitioned with the credit dropped. Operators composing the plan-change component should wire the store-credit handle to enable mid-cycle downgrades.
|
package/lib/asset-manifest.json
CHANGED
package/lib/cost-layers.js
CHANGED
|
@@ -493,24 +493,43 @@ function create(opts) {
|
|
|
493
493
|
if (attrCogs > residual) attrCogs = residual;
|
|
494
494
|
residual -= attrCogs;
|
|
495
495
|
}
|
|
496
|
-
|
|
496
|
+
// Debit the layer by the full consumed quantity (one update).
|
|
497
497
|
await query(
|
|
498
498
|
"UPDATE cost_layers SET quantity_remaining = quantity_remaining - ?1 WHERE id = ?2",
|
|
499
499
|
[dRow.qty, dRow.layer.id],
|
|
500
500
|
);
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
)
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
501
|
+
// Attribute the debit's cost so `qty * unit_cost_minor` summed over
|
|
502
|
+
// its attribution rows reconstructs attrCogs EXACTLY — the COGS
|
|
503
|
+
// reports (cogsForOrder / cogsForPeriod) recover each line's cost
|
|
504
|
+
// that way and have no line-total column to read instead. A single
|
|
505
|
+
// integer per-unit price cannot represent attrCogs when the debit
|
|
506
|
+
// quantity does not divide it (e.g. 23 over 3 units), so split the
|
|
507
|
+
// debit into a floor-priced remainder and a ceil-priced sliver:
|
|
508
|
+
// (qty - r) units at floor, r units at floor+1, where
|
|
509
|
+
// r = attrCogs - floor*qty. (qty-r)*floor + r*(floor+1) =
|
|
510
|
+
// qty*floor + r = attrCogs — no penny drift between the sale's COGS
|
|
511
|
+
// and the persisted attributions (the prior single rounded per-unit
|
|
512
|
+
// drifted by up to qty-1 minor units on the residual-bearing row).
|
|
513
|
+
var floorUnit = dRow.qty > 0 ? Math.floor(attrCogs / dRow.qty) : avgUnitCost;
|
|
514
|
+
var rem = dRow.qty > 0 ? attrCogs - (floorUnit * dRow.qty) : 0;
|
|
515
|
+
var parts = [];
|
|
516
|
+
if (dRow.qty - rem > 0) parts.push({ qty: dRow.qty - rem, unit: floorUnit });
|
|
517
|
+
if (rem > 0) parts.push({ qty: rem, unit: floorUnit + 1 });
|
|
518
|
+
for (var p = 0; p < parts.length; p += 1) {
|
|
519
|
+
var attrId = b.uuid.v7();
|
|
520
|
+
await query(
|
|
521
|
+
"INSERT INTO cogs_attributions " +
|
|
522
|
+
"(id, order_id, line_id, sku, layer_id, qty, unit_cost_minor, " +
|
|
523
|
+
"currency, reversed, reversal_reason, occurred_at) " +
|
|
524
|
+
"VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 0, NULL, ?9)",
|
|
525
|
+
[attrId, orderId, lineId, sku, dRow.layer.id, parts[p].qty, parts[p].unit, currency, attributionTs],
|
|
526
|
+
);
|
|
527
|
+
consumed.push({
|
|
528
|
+
layer_id: dRow.layer.id,
|
|
529
|
+
qty: parts[p].qty,
|
|
530
|
+
unit_cost_minor: parts[p].unit,
|
|
531
|
+
});
|
|
532
|
+
}
|
|
514
533
|
totalCogs += attrCogs;
|
|
515
534
|
}
|
|
516
535
|
// Edge case: residual unspent (impossible given the math
|
package/lib/sales-tax-filings.js
CHANGED
|
@@ -356,7 +356,7 @@ function create(opts) {
|
|
|
356
356
|
// without changing the primitive's contract.
|
|
357
357
|
async function _ordersInWindow(jurisdiction, periodStart, periodEnd) {
|
|
358
358
|
var sql =
|
|
359
|
-
"SELECT id, customer_id, currency, subtotal_minor, tax_minor, " +
|
|
359
|
+
"SELECT id, customer_id, currency, subtotal_minor, tax_minor, grand_total_minor, " +
|
|
360
360
|
" ship_to_json, status, created_at " +
|
|
361
361
|
"FROM orders " +
|
|
362
362
|
"WHERE created_at >= ?1 AND created_at < ?2 " +
|
|
@@ -370,30 +370,84 @@ function create(opts) {
|
|
|
370
370
|
catch (_e) { shipTo = null; }
|
|
371
371
|
if (!_shipToMatches(shipTo, jurisdiction)) continue;
|
|
372
372
|
out.push({
|
|
373
|
-
id:
|
|
374
|
-
customer_id:
|
|
375
|
-
currency:
|
|
376
|
-
subtotal_minor:
|
|
377
|
-
tax_minor:
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
373
|
+
id: row.id,
|
|
374
|
+
customer_id: row.customer_id,
|
|
375
|
+
currency: row.currency,
|
|
376
|
+
subtotal_minor: Number(row.subtotal_minor),
|
|
377
|
+
tax_minor: Number(row.tax_minor),
|
|
378
|
+
grand_total_minor: row.grand_total_minor == null ? 0 : Number(row.grand_total_minor),
|
|
379
|
+
status: row.status,
|
|
380
|
+
created_at: Number(row.created_at),
|
|
381
|
+
ship_to: shipTo,
|
|
381
382
|
});
|
|
382
383
|
}
|
|
383
384
|
return out;
|
|
384
385
|
}
|
|
385
386
|
|
|
387
|
+
// Total partial-refund cash refunded per order INSIDE the window. A
|
|
388
|
+
// partial refund is an `on_event = 'refund'` self-loop transition that
|
|
389
|
+
// leaves the order in its paid/fulfilling/shipped/delivered status (no
|
|
390
|
+
// partially_refunded state exists), so the order still counts toward the
|
|
391
|
+
// filing — its tax must be netted by the refunded portion or the filing
|
|
392
|
+
// over-states collected tax and over-remits. Refunds are attributed to
|
|
393
|
+
// the period they occur (occurred_at in-window), the standard
|
|
394
|
+
// returns-reduce-the-current-period convention; `amount_minor` is the
|
|
395
|
+
// refunded cash (grand-total terms), apportioned to tax vs subtotal at
|
|
396
|
+
// accumulation time using the order's own structure.
|
|
397
|
+
async function _refundsInWindow(periodStart, periodEnd) {
|
|
398
|
+
var byOrder = Object.create(null);
|
|
399
|
+
var r = await query(
|
|
400
|
+
"SELECT order_id, metadata_json FROM order_transitions " +
|
|
401
|
+
"WHERE on_event = 'refund' AND occurred_at >= ?1 AND occurred_at < ?2",
|
|
402
|
+
[periodStart, periodEnd],
|
|
403
|
+
);
|
|
404
|
+
for (var i = 0; i < r.rows.length; i += 1) {
|
|
405
|
+
var meta;
|
|
406
|
+
try { meta = JSON.parse(r.rows[i].metadata_json); }
|
|
407
|
+
catch (_e) { meta = null; }
|
|
408
|
+
var amt = meta && meta.amount_minor;
|
|
409
|
+
if (typeof amt === "number" && isFinite(amt) && amt > 0) {
|
|
410
|
+
byOrder[r.rows[i].order_id] = (byOrder[r.rows[i].order_id] || 0) + amt;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
return byOrder;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// Apportion `refunded` cash to the `part` (tax or subtotal) component of
|
|
417
|
+
// an order whose grand total is `total`, half-even, BigInt-safe (a
|
|
418
|
+
// window's order count times minor units can exceed 2^53). Returns the
|
|
419
|
+
// refunded share of `part`, never more than `part`.
|
|
420
|
+
function _apportionMinor(refunded, part, total) {
|
|
421
|
+
if (total <= 0 || refunded <= 0 || part <= 0) return 0;
|
|
422
|
+
var share = Number(
|
|
423
|
+
b.money.fromMinorUnits(BigInt(refunded), "USD")
|
|
424
|
+
.multiply([BigInt(part), BigInt(total)], { rounding: "half-even" })
|
|
425
|
+
.toMinorUnits()
|
|
426
|
+
);
|
|
427
|
+
return share > part ? part : share;
|
|
428
|
+
}
|
|
429
|
+
|
|
386
430
|
async function _ratesInWindow(jurisdiction, periodStart, periodEnd) {
|
|
387
|
-
// Pull
|
|
388
|
-
// window. The
|
|
389
|
-
//
|
|
390
|
-
//
|
|
431
|
+
// Pull the jurisdiction's DEFAULT (category IS NULL) rate rows that
|
|
432
|
+
// overlap the window. The owed re-derivation models the jurisdiction
|
|
433
|
+
// fallback rate only: an order carries no category here (orders are
|
|
434
|
+
// selected without a line-item/product join), so a category-specific
|
|
435
|
+
// rate could not be attributed to the right orders — and pulling
|
|
436
|
+
// category rows alongside the fallback let whichever row the DB
|
|
437
|
+
// returned first claim ALL revenue (a category rate is keyed per
|
|
438
|
+
// (jurisdiction, category) so it can legally coexist with the
|
|
439
|
+
// fallback in the same window), making owed both wrong and
|
|
440
|
+
// order-dependent. Restricting to the fallback rate makes owed
|
|
441
|
+
// deterministic; tax_collected_minor still reflects the actual
|
|
442
|
+
// per-order tax each order was charged at its own (category-aware)
|
|
443
|
+
// rate at order time.
|
|
391
444
|
if (!taxRatesApi) return [];
|
|
392
445
|
try {
|
|
393
446
|
var r = await query(
|
|
394
447
|
"SELECT id, jurisdiction, category, rate_bps, effective_from, effective_until " +
|
|
395
448
|
"FROM tax_rates " +
|
|
396
449
|
"WHERE jurisdiction = ?1 AND archived_at IS NULL " +
|
|
450
|
+
" AND category IS NULL " +
|
|
397
451
|
" AND effective_from < ?2 " +
|
|
398
452
|
" AND (effective_until IS NULL OR effective_until > ?3)",
|
|
399
453
|
[jurisdiction, periodEnd, periodStart],
|
|
@@ -486,6 +540,7 @@ function create(opts) {
|
|
|
486
540
|
|
|
487
541
|
var orders = await _ordersInWindow(raw.jurisdiction, Number(raw.period_start), Number(raw.period_end));
|
|
488
542
|
var rates = await _ratesInWindow(raw.jurisdiction, Number(raw.period_start), Number(raw.period_end));
|
|
543
|
+
var refunds = await _refundsInWindow(Number(raw.period_start), Number(raw.period_end));
|
|
489
544
|
|
|
490
545
|
// Resolve exemption per unique customer in a single pass so
|
|
491
546
|
// multiple orders from the same exempt customer don't refire the
|
|
@@ -528,13 +583,26 @@ function create(opts) {
|
|
|
528
583
|
|
|
529
584
|
for (var i = 0; i < orders.length; i += 1) {
|
|
530
585
|
var o = orders[i];
|
|
531
|
-
|
|
532
|
-
|
|
586
|
+
// Net any partial refund recorded inside the window. A refund of
|
|
587
|
+
// grand-total cash is apportioned to the order's subtotal and tax
|
|
588
|
+
// by its own structure, so the filing reflects NET taxable sales
|
|
589
|
+
// and NET collected tax — not the pre-refund figures.
|
|
590
|
+
var netSub = o.subtotal_minor;
|
|
591
|
+
var netTax = o.tax_minor;
|
|
592
|
+
var refunded = refunds[o.id] || 0;
|
|
593
|
+
if (refunded > 0 && o.grand_total_minor > 0) {
|
|
594
|
+
netSub = o.subtotal_minor - _apportionMinor(refunded, o.subtotal_minor, o.grand_total_minor);
|
|
595
|
+
netTax = o.tax_minor - _apportionMinor(refunded, o.tax_minor, o.grand_total_minor);
|
|
596
|
+
if (netSub < 0) netSub = 0;
|
|
597
|
+
if (netTax < 0) netTax = 0;
|
|
598
|
+
}
|
|
599
|
+
gross += netSub;
|
|
600
|
+
collected += netTax;
|
|
533
601
|
var isExempt = o.customer_id && exemptByCustomer[o.customer_id] === true;
|
|
534
602
|
if (isExempt) {
|
|
535
|
-
exempt +=
|
|
603
|
+
exempt += netSub;
|
|
536
604
|
} else {
|
|
537
|
-
taxable +=
|
|
605
|
+
taxable += netSub;
|
|
538
606
|
}
|
|
539
607
|
|
|
540
608
|
// Per-rate breakdown — only taxable contributions land in the
|
|
@@ -552,8 +620,8 @@ function create(opts) {
|
|
|
552
620
|
if (isExempt) {
|
|
553
621
|
bkt.taxable_minor += 0;
|
|
554
622
|
} else {
|
|
555
|
-
bkt.taxable_minor +=
|
|
556
|
-
bkt.tax_minor +=
|
|
623
|
+
bkt.taxable_minor += netSub;
|
|
624
|
+
bkt.tax_minor += netTax;
|
|
557
625
|
}
|
|
558
626
|
bkt.order_count += 1;
|
|
559
627
|
}
|
package/package.json
CHANGED