fix: отрицательная накидка и сохранность накидок в notes

Отрицательная «Накидка, %» отбрасывалась в четырёх местах (ввод, сохранение,
восстановление, отображение) — теперь любое ненулевое значение сохраняется,
отрицательное работает как скидка. Коэффициент (аплифт + накидка/100)
ограничен снизу нулём и в UI, и в CSV-экспорте. Принимается «−» (U+2212).

Накидки пропадали после синхронизации: клиент до v3.41 собирает notes заново
из трёх старых полей и при сохранении стирает sale_row_markups на сервере,
а следующий pull перезаписывает локальную копию. Клиент теперь переносит
незнакомые ключи notes/pricing_ui как есть, чтобы будущие поля не терялись.
ADL исправлен (неверное утверждение «старые клиенты игнорируют ключ»).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Mikhail ChusavitinandClaude Opus 5.5 committed 2026-09-24 10:08:34 +03:00
1 parent 4501193423
commit 6b9652e3ac
5 files changed
+66 -16

No files matched your search

+5 -1
View File
@@ -85,12 +85,16 @@ Sale per-row pricing (`_saleRowPrice`/`recomputeSalePrices` in `index.html`,
- `Цена = base × (Аплифт к estimate + row's own Накидка% / 100)` — Накидка is a - `Цена = base × (Аплифт к estimate + row's own Накидка% / 100)` — Накидка is a
per-row percentage, additive to the table-wide uplift, entered directly in the per-row percentage, additive to the table-wide uplift, entered directly in the
row's own input; unset rows default to 0% (no change to older configs' totals); row's own input; unset rows default to 0% (no change to older configs' totals);
negative values are discounts, and the factor is floored at 0 so no price goes
negative (`_saleRowPrice` / `applySaleRowPricing`);
Склад/Конкуренты are not shown or exported for the Sale table; Склад/Конкуренты are not shown or exported for the Sale table;
- per-row Накидка is keyed by `"<vendorPN>::<lot>"` (uppercased, "NONE" when there's - per-row Накидка is keyed by `"<vendorPN>::<lot>"` (uppercased, "NONE" when there's
no vendor PN) — plain `lot_name` isn't a safe key since the same LOT can appear no vendor PN) — plain `lot_name` isn't a safe key since the same LOT can appear
under more than one vendor-PN group (see row expansion rules below) — and persisted under more than one vendor-PN group (see row expansion rules below) — and persisted
as an additive key, `Notes.pricing_ui.sale_row_markups`, alongside the existing as an additive key, `Notes.pricing_ui.sale_row_markups`, alongside the existing
`sale_uplift`/`sale_custom_price` (see `sale_uplift`/`sale_custom_price`; unknown `Notes` / `pricing_ui` keys are carried
through verbatim on save (`loadedNotesExtra` / `loadedPricingUIExtra`) so a client
never erases fields added by a newer version (see
[decisions/2026-09-15-sale-row-markup-and-minimal-csv.md](decisions/2026-09-15-sale-row-markup-and-minimal-csv.md)); [decisions/2026-09-15-sale-row-markup-and-minimal-csv.md](decisions/2026-09-15-sale-row-markup-and-minimal-csv.md));
- the Sale table's own "Экспорт CSV" button additionally sends - the Sale table's own "Экспорт CSV" button additionally sends
`minimal_sale_columns: true` + `sale_row_markups`, which collapses `minimal_sale_columns: true` + `sale_row_markups`, which collapses
@@ -47,11 +47,22 @@ and a final price.
## Consequences ## Consequences
- Old clients / already-saved configurations are unaffected: `sale_row_markups` absent - Already-saved configurations are unaffected: `sale_row_markups` absent from `Notes`
from `Notes` means every row's markup defaults to 0%, reproducing the exact totals means every row's markup defaults to 0%, reproducing the exact totals the table
the table produced before this change (uplift-only). Old clients that don't know the produced before this change (uplift-only).
new `Notes` key simply ignore it, exactly like `sale_uplift` is ignored by even older - **Correction (2026-09-24):** the original claim that old clients "simply ignore" the
code. new key was wrong. A pre-v3.41 client rebuilds `Notes` from scratch on save
(only `buy_custom_price`/`sale_uplift`/`sale_custom_price`), so opening and saving a
config in an old client — including the best-effort save on page exit — erases
`sale_row_markups` on the server, and the next pull overwrites every other client's
local copy. Observed in the field: a markup saved and pushed on 09-22 came back as
`null` on the 09-23 pull. From this fix on the client carries unknown `Notes` /
`pricing_ui` keys through verbatim, so future additive keys survive a save by the
current version; nothing can protect against clients older than this fix — all users
must upgrade.
- Negative Накидка is allowed (a per-row discount). The factor
`uplift + pct/100` is floored at 0 on both client and CSV export, so a large discount
gives a zero price instead of a negative one.
- If a future caller needs the full-column DDP CSV format with per-row markup applied, - If a future caller needs the full-column DDP CSV format with per-row markup applied,
it must do so explicitly — `MinimalSaleColumns` intentionally couples "reduced it must do so explicitly — `MinimalSaleColumns` intentionally couples "reduced
columns" and "per-row markup applied" as one request-level switch rather than two columns" and "per-row markup applied" as one request-level switch rather than two
+2 -1
View File
@@ -626,7 +626,8 @@ func applySaleRowPricing(rows []ProjectPricingExportRow, saleUplift float64, man
} }
} }
key := saleRowKey(rows[i].VendorPN, rows[i].LotDisplay) key := saleRowKey(rows[i].VendorPN, rows[i].LotDisplay)
factor := saleUplift + (rowMarkups[key] / 100) // Negative markup is a discount; floored at 0 like _saleRowPrice so a price never goes negative.
factor := math.Max(0, saleUplift+(rowMarkups[key]/100))
price := math.Round(base*factor*100) / 100 price := math.Round(base*factor*100) / 100
rows[i].Estimate = floatPtr(price) rows[i].Estimate = floatPtr(price)
} }
+19
View File
@@ -561,3 +561,22 @@ type failingWriter struct{}
func (fw *failingWriter) Write(p []byte) (int, error) { func (fw *failingWriter) Write(p []byte) (int, error) {
return 0, io.EOF return 0, io.EOF
} }
func TestApplySaleRowPricingNegativeMarkup(t *testing.T) {
rows := []ProjectPricingExportRow{
{LotDisplay: "GPU_A", Estimate: floatPtr(1000)},
{LotDisplay: "GPU_B", Estimate: floatPtr(1000)},
{LotDisplay: "GPU_C", Estimate: floatPtr(1000)},
}
applySaleRowPricing(rows, 1.5, nil, map[string]float64{
"NONE::GPU_A": -50, // discount: 1.5 - 0.5 = 1.0
"NONE::GPU_B": 25, // 1.5 + 0.25 = 1.75
"NONE::GPU_C": -300, // would be -1.5 — floored at 0
})
want := []float64{1000, 1750, 0}
for i, w := range want {
if rows[i].Estimate == nil || *rows[i].Estimate != w {
t.Fatalf("row %d: got %v, want %v", i, rows[i].Estimate, w)
}
}
}
+24 -9
View File
@@ -623,6 +623,12 @@ const PricingMarkup = {
// reads it live rather than relying on per-render input state. // reads it live rather than relying on per-render input state.
let saleRowMarkups = {}; let saleRowMarkups = {};
// Notes keys this client doesn't understand (top-level and inside pricing_ui), kept from
// the last restorePricingStateFromNotes() and written back verbatim on save — otherwise
// an older client re-saving a config silently drops fields added by a newer one.
let loadedNotesExtra = {};
let loadedPricingUIExtra = {};
// Amber marker for world-fallback cells — must stay outside gray/green/red/blue // Amber marker for world-fallback cells — must stay outside gray/green/red/blue
// families since applyCustomPrice() strips those on vendor-price cells via regex. // families since applyCustomPrice() strips those on vendor-price cells via regex.
// Shared by renderPricingTab() (initial paint) and recomputeSalePrices() (re-paint on // Shared by renderPricingTab() (initial paint) and recomputeSalePrices() (re-paint on
@@ -2589,14 +2595,17 @@ function buildPricingState() {
const saleUplift = parseDecimalInput(document.getElementById('pricing-uplift-sale')?.value || ''); const saleUplift = parseDecimalInput(document.getElementById('pricing-uplift-sale')?.value || '');
const saleCustom = parseDecimalInput(document.getElementById('pricing-custom-price-sale')?.value || ''); const saleCustom = parseDecimalInput(document.getElementById('pricing-custom-price-sale')?.value || '');
// Only non-zero entries are kept, so an untouched config serializes exactly like // Only non-zero entries are kept (negative = discount), so an untouched config
// before this feature (additive key — old clients simply ignore it). // serializes exactly like before this feature.
const rowMarkups = {}; const rowMarkups = {};
Object.entries(saleRowMarkups).forEach(([key, pct]) => { Object.entries(saleRowMarkups).forEach(([key, pct]) => {
if (pct > 0) rowMarkups[key] = pct; if (Number.isFinite(pct) && pct !== 0) rowMarkups[key] = pct;
}); });
return { return {
// Keys this client doesn't know (added by a newer version) are carried through
// untouched, so saving here never wipes them — see restorePricingStateFromNotes.
...loadedPricingUIExtra,
buy_custom_price: buyCustom > 0 ? buyCustom : null, buy_custom_price: buyCustom > 0 ? buyCustom : null,
sale_uplift: saleUplift > 0 ? saleUplift : null, sale_uplift: saleUplift > 0 ? saleUplift : null,
sale_custom_price: saleCustom > 0 ? saleCustom : null, sale_custom_price: saleCustom > 0 ? saleCustom : null,
@@ -2606,6 +2615,7 @@ function buildPricingState() {
function serializeConfigNotes() { function serializeConfigNotes() {
return JSON.stringify({ return JSON.stringify({
...loadedNotesExtra,
pricing_ui: buildPricingState() pricing_ui: buildPricingState()
}); });
} }
@@ -2619,8 +2629,12 @@ function restorePricingStateFromNotes(notesRaw) {
return; return;
} }
const pricing = parsed?.pricing_ui; if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return;
const { pricing_ui: pricing, ...notesExtra } = parsed;
loadedNotesExtra = notesExtra;
if (!pricing || typeof pricing !== 'object') return; if (!pricing || typeof pricing !== 'object') return;
const { buy_custom_price, sale_uplift, sale_custom_price, sale_row_markups, ...pricingExtra } = pricing;
loadedPricingUIExtra = pricingExtra;
const buyInput = document.getElementById('pricing-custom-price-buy'); const buyInput = document.getElementById('pricing-custom-price-buy');
if (buyInput) { if (buyInput) {
@@ -2648,7 +2662,7 @@ function restorePricingStateFromNotes(notesRaw) {
saleRowMarkups = {}; saleRowMarkups = {};
if (pricing.sale_row_markups && typeof pricing.sale_row_markups === 'object') { if (pricing.sale_row_markups && typeof pricing.sale_row_markups === 'object') {
Object.entries(pricing.sale_row_markups).forEach(([key, pct]) => { Object.entries(pricing.sale_row_markups).forEach(([key, pct]) => {
if (typeof pct === 'number' && Number.isFinite(pct) && pct > 0) { if (typeof pct === 'number' && Number.isFinite(pct) && pct !== 0) {
saleRowMarkups[key] = pct; saleRowMarkups[key] = pct;
} }
}); });
@@ -4813,7 +4827,8 @@ function _saleRowKey(vendorPN, lot) {
// proportional share of the global "Ручная цена" when set) times (global uplift + this // proportional share of the global "Ручная цена" when set) times (global uplift + this
// row's own Накидка%). // row's own Накидка%).
function _saleRowPrice(base, markupPct, saleUplift) { function _saleRowPrice(base, markupPct, saleUplift) {
const factor = saleUplift + ((markupPct || 0) / 100); // Negative Накидка is a discount; floored at 0 so a large one can't make a price negative.
const factor = Math.max(0, saleUplift + ((markupPct || 0) / 100));
return base * factor; return base * factor;
} }
@@ -4871,7 +4886,7 @@ function recomputeSalePrices() {
function onSaleRowMarkupInput(inputEl) { function onSaleRowMarkupInput(inputEl) {
const key = inputEl.dataset.rowKey; const key = inputEl.dataset.rowKey;
const value = parseDecimalInput(inputEl.value || ''); const value = parseDecimalInput(inputEl.value || '');
if (value > 0) { if (value !== 0) {
saleRowMarkups[key] = value; saleRowMarkups[key] = value;
} else { } else {
delete saleRowMarkups[key]; delete saleRowMarkups[key];
@@ -4928,7 +4943,7 @@ function formatPercent(v) {
function parseDecimalInput(raw) { function parseDecimalInput(raw) {
if (raw == null) return 0; if (raw == null) return 0;
const cleaned = String(raw).trim().replace(/\s/g, '').replace(',', '.'); const cleaned = String(raw).trim().replace(/\s/g, '').replace(',', '.').replace(/\u2212/g, '-');
const n = parseFloat(cleaned); const n = parseFloat(cleaned);
return Number.isFinite(n) ? n : 0; return Number.isFinite(n) ? n : 0;
} }
@@ -4940,7 +4955,7 @@ function formatUpliftInput(value) {
// One or two decimals, comma separator, no trailing zeros — for the per-row Накидка input. // One or two decimals, comma separator, no trailing zeros — for the per-row Накидка input.
function formatMarkupInput(value) { function formatMarkupInput(value) {
if (!Number.isFinite(value) || value <= 0) return ''; if (!Number.isFinite(value) || value === 0) return '';
return String(Math.round(value * 100) / 100).replace('.', ','); return String(Math.round(value * 100) / 100).replace('.', ',');
} }