Compare commits
24
Commits
4d7b0e13ef
..
v3.42
No files matched your search
+1
-1
Submodule bible updated: 52444350c1...1977730d93.
@@ -30,6 +30,8 @@ Pull-only:
|
||||
- pricelists and pricelist items;
|
||||
- partnumber books and partnumber book items.
|
||||
|
||||
Configuration feature flags — see [Configuration feature flags](#configuration-feature-flags).
|
||||
|
||||
Readiness guard:
|
||||
- every sync push/pull runs a preflight check;
|
||||
- blocked sync returns `423 Locked` with a machine-readable reason;
|
||||
@@ -62,13 +64,47 @@ Rules:
|
||||
## Pricing tab layout
|
||||
|
||||
The Pricing tab (Ценообразование) has two tables: Buy (Цена покупки) and Sale (Цена продажи).
|
||||
Their column sets differ (see below); the shared per-LOT row expansion/grouping rules apply to both.
|
||||
|
||||
Column order (both tables):
|
||||
Buy table column order:
|
||||
|
||||
```
|
||||
PN вендора | Описание | LOT | Кол-во | Estimate | Склад | Конкуренты | Ручная цена
|
||||
```
|
||||
|
||||
Sale table column order:
|
||||
|
||||
```
|
||||
PN вендора | Описание | LOT | Кол-во | Накидка, % | Цена
|
||||
```
|
||||
|
||||
Sale per-row pricing (`_saleRowPrice`/`recomputeSalePrices` in `index.html`,
|
||||
`applySaleRowPricing` in `internal/services/export.go`):
|
||||
- each row's base is its raw Estimate unit price × qty, unless the table-wide "Ручная
|
||||
цена" input is set — then the base is that row's proportional share of the manual
|
||||
total (same distribution as before this existed, last row absorbs the rounding
|
||||
remainder), overwriting the row's own base rather than filling a separate column;
|
||||
- `Цена = base × (Аплифт к estimate + row's own Накидка% / 100)` — Накидка is a
|
||||
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);
|
||||
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;
|
||||
- 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
|
||||
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
|
||||
`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));
|
||||
- the Sale table's own "Экспорт CSV" button additionally sends
|
||||
`minimal_sale_columns: true` + `sale_row_markups`, which collapses
|
||||
`POST /api/configs/:uuid/export/pricing` output to exactly `LOT;Описание;Кол-во;Цена`
|
||||
(`ProjectPricingExportOptions.MinimalSaleColumns` in `internal/services/export.go`).
|
||||
This is scoped to that one request: Buy export and the project-level bulk export
|
||||
never set it and are unaffected.
|
||||
|
||||
Per-LOT row expansion rules:
|
||||
- each `lot_mappings` entry in a BOM row becomes its own table row with its own quantity and prices;
|
||||
- `baseLot` (resolved LOT without an explicit mapping) is treated as the first sub-row with `quantity_per_pn` from `_getRowLotQtyPerPN`;
|
||||
@@ -85,6 +121,50 @@ Controls terminology:
|
||||
|
||||
CSV export reads PN вендора, Описание, and LOT from `data-vendor-pn`, `data-desc`, `data-lot` row attributes to bypass the rowspan cell offset problem.
|
||||
|
||||
In the colour-optional indicator mode (`app_settings.indicator_mode = "accessible"`, see
|
||||
[03-database.md](03-database.md) and [decisions/2026-08-31-accessible-indicator-mode.md](decisions/2026-08-31-accessible-indicator-mode.md))
|
||||
both tables gain a narrow leading price-quality meter column (per sub-row), the row background
|
||||
tint is removed, `world`-fallback cells show a `W` text marker instead of amber, and the footer
|
||||
total shows a `⚠` prefix instead of red. CSV output is unaffected.
|
||||
|
||||
## Configuration feature flags
|
||||
|
||||
A configuration records which data features it uses in `feature_flags`, so a client
|
||||
that does not know one of them refuses to write it instead of silently dropping data.
|
||||
Rationale: [decisions/2026-09-24-configuration-feature-flags.md](decisions/2026-09-24-configuration-feature-flags.md).
|
||||
|
||||
Storage:
|
||||
- `qt_configurations.feature_flags` / `local_configurations.feature_flags` — JSON array
|
||||
of strings, sorted, no duplicates; empty list is stored as `NULL`
|
||||
(e.g. `["sale_row_markups"]`);
|
||||
- carried in version snapshots; exposed on reads as `feature_flags`, plus
|
||||
`unsupported_features` when this build doesn't know some of them.
|
||||
|
||||
Flag name format:
|
||||
- `lower_snake_case`, ASCII `[a-z0-9_]`, starts with a letter, at most 64 chars;
|
||||
- names the **data** the configuration holds, not the UI or the release:
|
||||
`<area>_<data>` — e.g. `sale_row_markups`, not `new_pricing_tab` or `v3_42`;
|
||||
- a name is permanent: never renamed, never reused for different data, never removed
|
||||
from `configfeatures.known` while any configuration can still carry it;
|
||||
- a change in the *meaning* of existing data that old clients would mis-handle gets a
|
||||
new flag (e.g. `sale_row_markups_v2`), not a silent reinterpretation of the old one.
|
||||
|
||||
Lifecycle:
|
||||
- flags are derived from content on every local write (`configfeatures.Detect`), never
|
||||
sent by the UI; a flag disappears when its data does;
|
||||
- a client refuses any write (local save or sync push) to a configuration carrying a
|
||||
flag missing from its `configfeatures.known`, returns `409 unsupported_config_features`,
|
||||
and the configurator locks itself with a banner listing the raw flag names;
|
||||
- a new data feature that older clients would drop on save must add its flag — to
|
||||
`known`, to `Detect`, and to the registry below — in the same change. Data that old
|
||||
clients round-trip verbatim needs no flag.
|
||||
|
||||
Registry:
|
||||
|
||||
| Flag | Set when | Data | Since |
|
||||
| --- | --- | --- | --- |
|
||||
| `sale_row_markups` | `Notes.pricing_ui.sale_row_markups` has at least one non-zero value | per-row «Накидка, %» on the Sale table (negative = discount) | flag introduced 2026-09-24; data since v3.41 |
|
||||
|
||||
## Configuration versioning
|
||||
|
||||
Configuration revisions are append-only snapshots stored in `local_configuration_versions`.
|
||||
@@ -151,6 +231,34 @@ Rules:
|
||||
- `config_types[].categories` is an allowlist: a category absent from all types is shown everywhere;
|
||||
- `qt_categories.name` and `qt_categories.name_ru` are not used by QF runtime; do not depend on them.
|
||||
|
||||
## Article generation
|
||||
|
||||
`internal/article` builds the `article` string (`{MODEL}-{CPU}-{MEM}-{GPU}-{DISK}-{NET}-{PSU}-{SUPPORT}`)
|
||||
from the configuration's `items` + `server_model`.
|
||||
|
||||
- which segment a cart LOT belongs to is decided by its `lot_category`, resolved through
|
||||
`ResolveLotCategories` → `GetLocalComponentCategoriesByLotNames`, i.e. the **component
|
||||
universe** (latest active `world` ∪ `estimate`), the same source the configurator/BOM/pricing
|
||||
tab use. It must **not** be scoped to the configuration's pinned pricelist: a world-only LOT
|
||||
(e.g. `GPU_NV_RTX_PRO_6000D_...`, priced by the world fallback, never added to the estimate
|
||||
pricelist) is a legitimate cart member and still carries a real `lot_category` in `world`.
|
||||
Scoping to one pricelist silently dropped such LOTs from the article. See
|
||||
[decisions/2026-09-01-article-category-from-component-universe.md](decisions/2026-09-01-article-category-from-component-universe.md);
|
||||
- `BuildOptions` no longer takes a pricelist; `POST /api/configs/preview-article` still accepts
|
||||
`pricelist_id` but ignores it;
|
||||
- category comes only from real synced pricelist columns — never inferred from the `lot_name`
|
||||
prefix (the `SVC_` SUPPORT segment is the sole lot_name-pattern exception, see below);
|
||||
- within a segment the model/capacity/speed **token** is still parsed from the `lot_name` —
|
||||
that is the article text itself, not categorization;
|
||||
- when a token can't be parsed (the `lot_name` doesn't fit `{GROUP}_{VENDOR}_{MODEL}[_{SPEC}…]`)
|
||||
the segment carries the LOT's `lot_category` as the token — **never** a bare `UNK`. Such a
|
||||
segment comes back with `Recognized = false` in `BuildResult.Segments`, plus a `Warnings`
|
||||
entry naming the `lot_name`. The configurator highlights the segment (amber) and lists the
|
||||
warnings; create/update/rollback log `WARN "article generation degraded"`. No catalog of real
|
||||
lot_names / model names lives in the repo (`no-hardcoded-vendors`), so only *structural*
|
||||
parse failure is detected, not a wrong-but-well-formed token. See
|
||||
[decisions/2026-09-01-article-degraded-token-visibility.md](decisions/2026-09-01-article-degraded-token-visibility.md).
|
||||
|
||||
## Support as a BOM LOT
|
||||
|
||||
The Base tab's support-level picker adds/replaces a synthetic LOT in `cart` (e.g.
|
||||
|
||||
@@ -17,7 +17,7 @@ Main tables:
|
||||
| `local_partnumber_book_items` | PN -> LOT catalog payload |
|
||||
| `pending_changes` | sync queue |
|
||||
| `connection_settings` | encrypted MariaDB connection settings |
|
||||
| `app_settings` | local app state |
|
||||
| `app_settings` | local app state (key→value); includes `indicator_mode` = `color` \| `accessible`, a per-client display preference set on `/setup` |
|
||||
| `local_schema_migrations` | applied local migration markers |
|
||||
| `local_qt_settings` | server-pushed configurator settings cache (from `qt_settings`) |
|
||||
|
||||
@@ -195,6 +195,7 @@ PK: lot_name
|
||||
| vendor_spec | longtext JSON | |
|
||||
| rental_items | JSON | per-lot New/БУ condition for the Аренда tab; see [02-architecture.md](02-architecture.md#rental--paid-testing-pricing-contract) |
|
||||
| rental_uplift_percent | decimal(8,2) DEFAULT 0 | uplift applied to Estimate buy price for rental "Цена" |
|
||||
| feature_flags | JSON NULL | added by migration 034. Data features the configuration uses (`["sale_row_markups"]`); derived on save, a client refuses to write a config with a flag it doesn't know. See [decisions/2026-09-24-configuration-feature-flags.md](decisions/2026-09-24-configuration-feature-flags.md) |
|
||||
|
||||
### qt_lot_metadata
|
||||
PK: lot_name
|
||||
@@ -261,7 +262,9 @@ PK: lot_name
|
||||
| price | decimal(12,2) NOT NULL | |
|
||||
| price_quality | tinyint unsigned, nullable | added by migration 033. Set by the external pricelist-building tool, 0-9, based on quote recency/count per its own per-lot pricing-period settings — QF only reads and displays it, never computes it. |
|
||||
|
||||
`price_quality` is synced through `LocalPricelistItem` (pricelist detail page) and, separately, through `LocalComponent`/`services.ComponentView` (`/api/components`, used by the configurator's search dropdown and item table) — both read paths go through `pricelistItemRow`/`toLocalComponent()` in `internal/localdb/components.go`. The `/api/components` path reads the component universe (`world` ∪ `estimate`, see [decisions/2026-07-24-component-universe-world-union.md](decisions/2026-07-24-component-universe-world-union.md)), where a world-only LOT is forced to `price_quality = 0` — the only place QF writes this field rather than reading it. The color scale (red 0 → yellow 5 → green 9, gradient) lives in **one shared JS module**, `web/static/price-quality.js` (loaded by `base.html` for every page) — `priceQualityColor`/`qualityDotHtml`/`qualityBadgeHtml`/`qualityRowStyle`. Do not reimplement the color scale locally in a template; add a new helper to that module instead. Used in: pricelist detail "Качество" column, configurator search dropdown (colored dot), configurator table (leftmost quality-dot column), pricing tab (row background tint).
|
||||
`price_quality` is synced through `LocalPricelistItem` (pricelist detail page) and, separately, through `LocalComponent`/`services.ComponentView` (`/api/components`, used by the configurator's search dropdown and item table) — both read paths go through `pricelistItemRow`/`toLocalComponent()` in `internal/localdb/components.go`. The `/api/components` path reads the component universe (`world` ∪ `estimate`, see [decisions/2026-07-24-component-universe-world-union.md](decisions/2026-07-24-component-universe-world-union.md)), where a world-only LOT is forced to `price_quality = 0` — the only place QF writes this field rather than reading it. The visual scale lives in **one shared JS module**, `web/static/price-quality.js` (loaded by `base.html` for every page) — `priceQualityColor`/`priceQualityLevel`/`qualityMeterHtml`/`qualityDotHtml`/`qualityBadgeHtml`/`qualityRowStyle`. Do not reimplement the scale locally in a template; add a new helper to that module instead. Used in: pricelist detail "Качество" column, configurator search dropdown, configurator table (leftmost quality column), pricing tab.
|
||||
|
||||
The module has **two render modes**, chosen per client by `window.QF_INDICATOR_MODE` (injected by `base.html` from `app_settings.indicator_mode`, default `color`): `color` = hue scale red 0 → yellow 5 → green 9; `accessible` = colour-blind-safe 5-step signal-strength meter (`priceQualityLevel`: `0-1/2-3/4-5/6-7/8-9`), single neutral hue. In `accessible` mode the pricing tab drops the row background tint for a leading meter column, the `world`-fallback amber cell tint becomes a `W` text marker, and the "contaminated total" red becomes a `⚠` prefix — see [decisions/2026-08-31-accessible-indicator-mode.md](decisions/2026-08-31-accessible-indicator-mode.md). Any new colour-only signal must add a branch in this module keyed on `isAccessible()`, not a local one.
|
||||
|
||||
The real table also has `price_method`, `price_period_days`, `price_coefficient`, `manual_price`, `meta_prices` and `lead_time_weeks` columns, owned and written by the external pricing engine that maintains `qt_pricelist_items` — **keep them in the table for backward compatibility with that system; QF must never drop, rename, or write to them.** QF itself does not model, sync, or display any of them (tried once, removed as unused/dead in the client). Do not re-add them to `models.PricelistItem`/`LocalPricelistItem` without a concrete UI need.
|
||||
|
||||
|
||||
@@ -29,6 +29,17 @@
|
||||
|
||||
`POST /api/restart` exists only in `debug` mode.
|
||||
|
||||
## Settings
|
||||
|
||||
| Method | Path | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `GET` | `/api/settings/ui` | read per-client UI display preferences → `{ "indicator_mode": "color" \| "accessible" }` |
|
||||
| `PUT` | `/api/settings/ui` | set `indicator_mode` (body `{ "indicator_mode": ... }`); `422` on an unknown value |
|
||||
|
||||
Stored in `app_settings` (SQLite); no restart. Registered in both the normal and the setup-mode
|
||||
route sets. Consumed by `web/static/price-quality.js` and the pricing tab via a
|
||||
`window.QF_INDICATOR_MODE` global that `base.html` renders from the same setting.
|
||||
|
||||
## Reference data
|
||||
|
||||
| Method | Path | Purpose |
|
||||
@@ -83,6 +94,11 @@
|
||||
| `PUT` | `/api/configs/:uuid/rental` | persist Аренда tab state (per-lot New/БУ, weeks, uplift %, annual support) |
|
||||
| `POST` | `/api/configs/:uuid/rental/calculate` | compute rental/paid-testing pricing without persisting |
|
||||
|
||||
Configuration reads include `feature_flags` and, when this build doesn't know some of
|
||||
them, `unsupported_features`. Any write to such a configuration returns `409`
|
||||
`{"code":"unsupported_config_features","unsupported_features":[...],"error":"..."}`
|
||||
(see [decisions/2026-09-24-configuration-feature-flags.md](decisions/2026-09-24-configuration-feature-flags.md)).
|
||||
|
||||
## Projects
|
||||
|
||||
| Method | Path | Purpose |
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
# Decision: project-level DDP export uses each configuration's own sale uplift
|
||||
|
||||
**Date:** 2026-08-12
|
||||
**Status:** active
|
||||
|
||||
## Context
|
||||
|
||||
Two code paths produce the same "Ценообразование" (pricing) CSV: exporting a single
|
||||
configuration from `index.html` (`exportPricingCSV`), and exporting an entire project
|
||||
from `project_detail.html` (`exportProject` → `POST /api/projects/:uuid/export` →
|
||||
`ExportProjectPricingCSV`). Both end up in `ExportService.buildPricingExportBlock`.
|
||||
|
||||
Each configuration's "Аплифт к estimate" (`#pricing-uplift-sale` in the pricing tab) is
|
||||
saved per configuration, piggybacked into `Configuration.Notes` as
|
||||
`{"pricing_ui":{"sale_uplift":...}}` (see `serializeConfigNotes`/
|
||||
`restorePricingStateFromNotes` in `index.html`). The single-config export sends this value
|
||||
explicitly as `sale_markup` in the request, so it always applies the right uplift.
|
||||
|
||||
The project-level export modal never had an uplift input and never sent `sale_markup`, so
|
||||
`ProjectPricingExportOptions.SaleMarkup` was always `0`. `buildPricingExportBlock` used to
|
||||
fall back to a single hardcoded `defaultSaleMarkup` (1.3) for every configuration in the
|
||||
project, silently ignoring each configuration's own saved uplift — a bulk DDP export did
|
||||
not match what exporting those same configurations individually would produce.
|
||||
|
||||
## Decision
|
||||
|
||||
`buildPricingExportBlock` resolves the DDP estimate factor per configuration via
|
||||
`ProjectPricingExportOptions.effectiveSaleMarkupFactor(cfg)`:
|
||||
|
||||
- an explicit `opts.SaleMarkup` (only ever sent by the single-config pricing tab, which
|
||||
knows the live-edited value that may not be saved yet) always wins;
|
||||
- otherwise it reads that configuration's own saved uplift from `Notes`
|
||||
(`configSavedSaleUplift`);
|
||||
- otherwise it falls back to `defaultSaleMarkup` (1.3), same as before, for configurations
|
||||
that never had an uplift saved.
|
||||
|
||||
Both `applyDDPMarkup` call sites in `buildPricingExportBlock` (the BOM-driven branch and
|
||||
the plain-items fallback) use this per-configuration factor. Stock/Competitor keep using
|
||||
the fixed `stockCompetitorMarkupFactor` (1.3) — only the Estimate uplift is configurable.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Project-level DDP export now goes through the same "pipeline" as single-config export:
|
||||
each row's Estimate is scaled by that configuration's own saved uplift, not a
|
||||
project-wide constant.
|
||||
- If a future caller needs to force one uplift across an entire project export regardless
|
||||
of individual configs' saved settings, it must do so explicitly via `sale_markup` in the
|
||||
request — do not reintroduce a silent global default that overrides saved per-config
|
||||
values.
|
||||
- `configSavedSaleUplift` only reads `Notes`; it does not fail loudly on malformed/foreign
|
||||
JSON in that field — it just returns 0 and lets the 1.3 fallback apply.
|
||||
@@ -0,0 +1,63 @@
|
||||
# Decision: `indicator_mode` — a colour-optional rendering mode for UI signals
|
||||
|
||||
**Date:** 2026-08-31
|
||||
**Status:** active
|
||||
|
||||
## Context
|
||||
|
||||
Several UI signals were encoded by hue alone and unreadable with a colour-vision deficiency:
|
||||
|
||||
- `price_quality` (0–9) as a red→yellow→green gradient — a dot in the configurator search
|
||||
dropdown and inline before `lot_name`, a coloured number in the pricelist "Качество" column,
|
||||
a full-row background tint on the "Ценообразование" tab;
|
||||
- the amber `world`-fallback price cell tint
|
||||
([2026-07-10-world-pricelist-fallback.md](2026-07-10-world-pricelist-fallback.md));
|
||||
- the red "contaminated total" in the pricing footer
|
||||
([2026-07-24-pricing-total-world-share.md](2026-07-24-pricing-total-world-share.md)).
|
||||
|
||||
The bible has no dedicated accessibility contract, but `table-management` §Icon Semantics,
|
||||
`controls-selection` §Buttons, `go-code-style` §Business Logic Placement and `build-version-display`
|
||||
say the same thing: meaning is never carried by one ambiguous channel — back it with
|
||||
shape / number / explicit `title`+`aria-label`, and keep the indicator visually subordinate.
|
||||
|
||||
## Decision
|
||||
|
||||
One per-client preference, **`app_settings.indicator_mode`** = `color` (default) | `accessible`,
|
||||
set on `/setup` ("Настройки") via `GET`/`PUT /api/settings/ui` (`internal/handlers/settings.go`)
|
||||
— no restart. Deliberately named for the concern (how indicators are rendered), not for the
|
||||
current widget, so future colour-only signals attach to the same switch.
|
||||
|
||||
`internal/handlers/web.go` `render()` and `internal/handlers/setup.go` inject the mode for every
|
||||
page; `base.html` publishes it as `window.QF_INDICATOR_MODE`. `web/static/price-quality.js` is
|
||||
still the single source of the price-quality scale and branches on the mode internally, so its
|
||||
call sites do not change.
|
||||
|
||||
In `accessible` mode:
|
||||
|
||||
- `price_quality` renders as a **5-step signal-strength meter** (`priceQualityLevel` =
|
||||
`min(4, floor(score/2))` → `0-1 / 2-3 / 4-5 / 6-7 / 8-9`), five bars in one neutral hue, each
|
||||
instance carrying `title`/`aria-label` = `Качество цены: N/9`. `qualityDotHtml` and
|
||||
`qualityBadgeHtml` return the meter;
|
||||
- `qualityRowStyle` returns `''` — the pricing tab instead shows the meter in a narrow leading
|
||||
column (conditional `<th>` / `colspan` in `index.html`, per-sub-row `<td>`);
|
||||
- the `world`-fallback amber class is dropped for a `W` superscript text marker on the price
|
||||
(text, not a colour class — `applyCustomPrice`'s colour-stripping regex is a non-issue);
|
||||
- `_setPricingTotal` drops `text-red-600` for a leading `⚠` glyph, on the same trigger as the
|
||||
red (`worldShare > 0`). The hover popup — including the "prices for N of M positions" coverage
|
||||
line — is unchanged in both modes; per 2026-07-24 there is still no colour-coded coverage-only
|
||||
signal, and `accessible` mode does not add one.
|
||||
|
||||
`color` mode is byte-for-byte the previous behaviour.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Default unchanged; nothing moves until a user opts in on `/setup`.
|
||||
- `web/static/price-quality.js` stays the only place that knows the 0–9 scale. Any new
|
||||
colour-coded quality/price signal adds a branch there keyed on `isAccessible()`, never a local
|
||||
reimplementation, and its `accessible` form must be shape/text, not another hue.
|
||||
- The pricing-tab tables have a mode-dependent column count (8 / 9). `index.html` guards the
|
||||
`<th>`, the empty-state `colspan`, the `tfoot` "Итого:" `colspan` and the JS row template on
|
||||
`ACCESSIBLE_MODE` / `{{ eq .IndicatorMode "accessible" }}`. CSV export is untouched — it reads
|
||||
`data-*` row attributes, not cell positions.
|
||||
- New routes `GET`/`PUT /api/settings/ui`, registered in both the normal and setup-mode route
|
||||
sets in `cmd/qfs/main.go`. `render()` nil-guards `localDB` for tests.
|
||||
@@ -0,0 +1,62 @@
|
||||
# Decision: article generation reads lot_category from the component universe, not one pricelist
|
||||
|
||||
**Date:** 2026-09-01
|
||||
**Status:** active
|
||||
|
||||
## Context
|
||||
|
||||
`internal/article/generator.go` classifies each cart LOT into an article segment
|
||||
(CPU / MEM / GPU / DISK / NET / PSU) by its `lot_category`. That category was
|
||||
resolved by `ResolveLotCategories` → `GetLocalLotCategoriesByServerPricelistID`,
|
||||
which queries exactly **one** pricelist — the configuration's pinned
|
||||
`pricelist_id` (an `estimate` pricelist). A segment builder skips any LOT whose
|
||||
category is unknown, so a LOT absent from that one pricelist vanished from the
|
||||
article with no warning.
|
||||
|
||||
`GPU_NV_RTX_PRO_6000D_SERVER_84GB_PCIE` exposed this: it exists only in `world`
|
||||
pricelists (where it correctly carries `lot_category = GPU`) and in no `estimate`
|
||||
pricelist. It was priced (world fallback), exported, and shown in the cart, but
|
||||
dropped from the article.
|
||||
|
||||
This is the same class of bug as
|
||||
[2026-07-24-component-universe-world-union.md](2026-07-24-component-universe-world-union.md):
|
||||
the cart's LOT set is `world` ∪ `estimate`, and no read path may silently drop a
|
||||
LOT that only lives in `world`. Article generation was the one component-reading
|
||||
path still scoped to a single pricelist.
|
||||
|
||||
Deriving the category from the `lot_name` prefix was rejected — it is forbidden by
|
||||
the pricelist-contract rules (`02-architecture.md`, `bible/rules/patterns/`):
|
||||
category comes only from real synced pricelist columns.
|
||||
|
||||
## Decision
|
||||
|
||||
`ResolveLotCategories(local, lotNames)` now calls
|
||||
`LocalDB.GetLocalComponentCategoriesByLotNames`, which reads the component universe
|
||||
(`componentUniverse()` — latest active `world` ∪ `estimate`, estimate wins a
|
||||
collision). The server-pricelist parameter is gone.
|
||||
|
||||
- `article.BuildOptions` no longer has `ServerPricelist`.
|
||||
- `POST /api/configs/preview-article` and the create/update paths still accept
|
||||
`pricelist_id` but ignore it for article purposes.
|
||||
- The `lot_name`-token parsing inside a segment (CPU model, memory size, GPU model,
|
||||
disk capacity, port speed, wattage) still parses the token from the `lot_name` —
|
||||
that produces the article text, it does not categorize. One parser bug was fixed
|
||||
alongside: `parseGPUModel` required the model-number token to be all digits
|
||||
(`isNumeric`), so `RTX_PRO_6000D` lost its `D` and collapsed to `RTX_84GB` —
|
||||
indistinguishable from a real `RTX` card and different from its sibling
|
||||
`RTX_PRO_6000` → `RTX6000_96GB`. It now accepts a digit-first alphanumeric token
|
||||
(`isModelNumber`), giving `RTX6000D_84GB`.
|
||||
|
||||
## Consequences
|
||||
|
||||
- A world-only LOT lands in the article with its real category. Article generation
|
||||
no longer depends on which pricelist a LOT was added to.
|
||||
- The article can shift if the latest active `world`/`estimate` pricelist
|
||||
recategorizes a LOT — acceptable, and consistent with how the configurator's
|
||||
category tabs already behave.
|
||||
- `GetLocalLotCategoriesByServerPricelistID` still exists and is still used by
|
||||
`services/rental.go` and `services/export.go`. Those paths have the same
|
||||
single-pricelist blind spot for world-only LOTs; migrating them is out of scope
|
||||
here but should follow the same direction.
|
||||
- Covered by `TestResolveLotCategories_WorldOnlyLot` in
|
||||
`internal/article/categories_test.go`.
|
||||
@@ -0,0 +1,66 @@
|
||||
# Decision: unparsed article tokens degrade to a visible category placeholder, never "UNK"
|
||||
|
||||
**Date:** 2026-09-01
|
||||
**Status:** active
|
||||
|
||||
## Context
|
||||
|
||||
`internal/article` builds each segment by parsing a spec token out of the `lot_name`
|
||||
(CPU model, memory size, GPU model, disk capacity, port speed, wattage). When a
|
||||
`lot_name` did not match the expected shape the generator failed silently or
|
||||
misleadingly:
|
||||
|
||||
- `parseCPUModel` / `parseGPUModel` fell back to `normalizeModelToken` or a literal
|
||||
`"UNK"` with **no signal** — and a partial parse (`RTX_PRO_6000D` → `RTX_84GB`)
|
||||
produced a plausible but wrong token indistinguishable from a real result;
|
||||
- `NET` / `PSU` emitted `UNKNET` / `UNKPSU`;
|
||||
- `MEM` / `DISK` dropped the segment or the capacity and emitted only a terse
|
||||
`mem_unknown` / `disk_unknown` warning;
|
||||
- `BuildResult.Warnings` existed but **nothing consumed it**: the `preview-article`
|
||||
frontend ignored the field and the create/update paths discarded it.
|
||||
|
||||
So a new naming shape (a vendor renames a card family, moves memory ahead of the
|
||||
model, glues an architecture onto the token) would silently produce a wrong or
|
||||
truncated article and no one would notice.
|
||||
|
||||
A vendor/model catalog in the repo to validate tokens against was rejected — it
|
||||
violates `bible/rules/patterns/no-hardcoded-vendors` and needs constant upkeep.
|
||||
Detection is therefore limited to **structural** failure (the name doesn't fit
|
||||
`{GROUP}_{VENDOR}_{MODEL}[_{SPEC}…]`); semantic drift where a wrong token still
|
||||
parses cleanly cannot be caught automatically and is out of scope.
|
||||
|
||||
## Decision
|
||||
|
||||
1. `"UNK"` / `"UNKNET"` / `"UNKPSU"` are gone. When a spec token can't be parsed the
|
||||
article carries the LOT's `lot_category` as the token (`4xGPU`, `2xCPU`,
|
||||
`768G+MEM`, …) via `placeholderToken`.
|
||||
2. Each `build*Segment` returns a `segmentResult{value, degraded, warnings}`. Every
|
||||
degraded segment produces a warning that **names the offending `lot_name`** and
|
||||
states which category was written instead.
|
||||
3. `BuildResult` gains `Segments []ResultSegment{Group, Text, Recognized}`.
|
||||
`Recognized == false` marks a segment whose token is a placeholder.
|
||||
4. `parseCPUModel` / `parseGPUModel` return `(token, ok)`; `ok == false` on the
|
||||
last-ditch fallback path.
|
||||
5. Consumers surface it:
|
||||
- `POST /api/configs/preview-article` returns `segments` and `warnings`; the
|
||||
configurator's article line renders each not-`recognized` segment highlighted
|
||||
(amber) and lists the warnings beneath it (`renderArticleDisplay` in
|
||||
`web/templates/index.html`);
|
||||
- create / update / rollback log `WARN "article generation degraded"` with the
|
||||
`server_model`, article and warnings.
|
||||
6. No list of real `lot_name`s or model names is committed to the repo — not as a
|
||||
fixture, not as a golden table. Tests use synthetic names only.
|
||||
|
||||
## Consequences
|
||||
|
||||
- An unrecognised LOT is always visible in the UI (highlighted token + warning) and
|
||||
in server logs — never a silent drop or a bare `UNK`.
|
||||
- The stored `article` string still contains only the placeholder token; the
|
||||
`recognized` flags are not persisted (regenerated on next save / preview).
|
||||
- `compressArticle` now returns `[]namedSeg` (the caller re-joins) so the degraded
|
||||
flags survive compression.
|
||||
- Structural detection only: a wrong-but-well-formed token (e.g. a future `GTX`
|
||||
where `RTX` was expected) still passes. Closing that needs a validation source,
|
||||
deferred pending a server-side structured-attribute contract.
|
||||
- Covered by `TestBuild_UnparseableModel_CategoryPlaceholder` and
|
||||
`TestParseGPUModel_VendorLetterSuffix`.
|
||||
@@ -0,0 +1,69 @@
|
||||
# Decision: per-row "Накидка" on the Sale table + minimal Sale CSV columns
|
||||
|
||||
**Date:** 2026-09-15
|
||||
**Status:** active
|
||||
|
||||
## Context
|
||||
|
||||
The Sale (Цена продажи) table only had one table-wide "Аплифт к estimate" multiplier
|
||||
and one table-wide "Ручная цена" override. There was no way to push margin up on
|
||||
individual rows (e.g. scarce GPUs) without changing the uplift for every row, and the
|
||||
table showed Estimate/Склад/Конкуренты/Ручная-цена columns that a sales rep handing a
|
||||
quote to a customer never needed — the actual deliverable is just LOT, Описание, Кол-во,
|
||||
and a final price.
|
||||
|
||||
## Decision
|
||||
|
||||
- The Sale table gains a per-row "Накидка, %" input. Each row's final "Цена" is
|
||||
`base × (Аплифт к estimate + Накидка% / 100)`, where `base` is the row's raw Estimate
|
||||
unit price × qty, or — when the table-wide "Ручная цена" is set — that row's
|
||||
proportional share of the manual total (same last-row-absorbs-remainder distribution
|
||||
the table-wide manual price already used, now overwriting the row's base instead of
|
||||
filling a separate column).
|
||||
- The Sale table's visible/exported columns collapse to
|
||||
`PN вендора | Описание | LOT | Кол-во | Накидка, % | Цена` on screen, and exactly
|
||||
`LOT;Описание;Кол-во;Цена` in its own CSV export. Estimate, Склад, Конкуренты, and
|
||||
the old Ручная-цена column are no longer shown or exported for this table. The Buy
|
||||
table (Цена покупки) is untouched.
|
||||
- Per-row markup is keyed by `"<vendorPN>::<lot>"` (uppercased, `NONE` when there is no
|
||||
vendor PN) — not by `lot_name` alone, since the same LOT can appear under more than
|
||||
one vendor-PN BOM group (see "Per-LOT row expansion rules" in `02-architecture.md`).
|
||||
- Persistence is additive: `Configuration.Notes.pricing_ui` gains a new
|
||||
`sale_row_markups` map alongside the existing `sale_uplift`/`sale_custom_price`, the
|
||||
same JSON-blob-in-`Notes` mechanism established by
|
||||
[2026-08-12-project-export-per-config-sale-uplift.md](2026-08-12-project-export-per-config-sale-uplift.md).
|
||||
Zero/unset rows are omitted from the map entirely.
|
||||
- CSV export: `POST /api/configs/:uuid/export/pricing` gained `minimal_sale_columns`
|
||||
(bool) and `sale_row_markups` (map) request fields, read into
|
||||
`ProjectPricingExportOptions.MinimalSaleColumns`/`SaleRowMarkups`. These are wired
|
||||
**only** in `ExportConfigPricingCSV`, gated on `req.MinimalSaleColumns` being true —
|
||||
the Sale table's own "Экспорт CSV" button is the only caller that sets it. Buy export
|
||||
(basis=fob) and the project-level bulk export (`ExportProjectPricingCSV`) never send
|
||||
it and keep their full existing column sets/output unchanged.
|
||||
- `ProjectPricingExportOptions.ManualPrice`, previously parsed from the request but
|
||||
never actually read into the options struct (a pre-existing dead field), is now wired
|
||||
— but only inside the same `MinimalSaleColumns` gate, so this bug fix does not change
|
||||
Buy-table CSV output for anyone already relying on the old (broken) behavior.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Already-saved configurations are unaffected: `sale_row_markups` absent from `Notes`
|
||||
means every row's markup defaults to 0%, reproducing the exact totals the table
|
||||
produced before this change (uplift-only).
|
||||
- **Correction (2026-09-24):** the original claim that old clients "simply ignore" the
|
||||
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,
|
||||
it must do so explicitly — `MinimalSaleColumns` intentionally couples "reduced
|
||||
columns" and "per-row markup applied" as one request-level switch rather than two
|
||||
independent options, since the only current caller needs both together.
|
||||
@@ -0,0 +1,58 @@
|
||||
# Decision: per-configuration feature flags — clients refuse to write what they don't understand
|
||||
|
||||
**Date:** 2026-09-24
|
||||
**Status:** active
|
||||
|
||||
## Context
|
||||
|
||||
Configurations are synced last-write-wins, and every client rebuilds a configuration's
|
||||
content from what *it* knows before saving. When a newer client adds data (e.g. the
|
||||
per-row "Накидка" in `Notes.pricing_ui.sale_row_markups`, see
|
||||
[2026-09-15-sale-row-markup-and-minimal-csv.md](2026-09-15-sale-row-markup-and-minimal-csv.md)),
|
||||
an older client that opens and saves the same configuration silently drops it; the drop
|
||||
is pushed to the server and the next pull spreads it to every other client. This
|
||||
happened in the field (a markup pushed on 2026-09-22 came back `null` on the 09-23 pull).
|
||||
A global minimum-app-version gate was considered and rejected: it would block all sync
|
||||
for an outdated client, even for configurations that use no new feature.
|
||||
|
||||
## Decision
|
||||
|
||||
- `qt_configurations.feature_flags` (JSON array of strings, NULL = none; server
|
||||
migration `034`) and `local_configurations.feature_flags` (AutoMigrate) record which
|
||||
data features a configuration uses. Synced like any other column; carried in version
|
||||
snapshots.
|
||||
- `internal/configfeatures` is the single source of truth: `known` (flags this build
|
||||
understands), `Detect(notes)` (derive flags from content), `Unknown`, `Check`,
|
||||
`UnsupportedError`. Current flags: `sale_row_markups` (at least one non-zero row markup).
|
||||
- Flags are **derived** on every local write, never sent by the UI: `saveWithVersionAndPending`,
|
||||
`createWithVersionTx`, `rollbackToVersion`, `UpdateServerCount` first `Check` the flags
|
||||
*as stored* and refuse with `*configfeatures.UnsupportedError` if any is unknown, then set
|
||||
`FeatureFlags = Detect(notes)`. This covers update, rename, move, refresh prices,
|
||||
vendor-spec, rental, server count, deactivate/reactivate, rollback (current and target
|
||||
snapshot) and clone (the clone inherits the original's flags). Project line reorder is
|
||||
exempt: it only touches `line_no` and writes the row back with its flags and notes intact.
|
||||
- Every HTTP handler reports errors via `handlers.RespondError`, which turns an
|
||||
`UnsupportedError` into `409` `{"code":"unsupported_config_features","unsupported_features":[...],"error":"..."}`
|
||||
regardless of the status the caller picked.
|
||||
- Reads expose `unsupported_features` (computed in `LocalToConfiguration`). The
|
||||
configurator shows a red banner listing them, disables "Сохранить", skips the
|
||||
exit-save, and also locks itself when a save comes back with the 409.
|
||||
- Sync push (`pushConfigurationUpdate`) reads the server row first and refuses if its
|
||||
flags are unknown — a newer client may have written it after our last pull. Such a
|
||||
refused change is kept in the queue (it is exempt from the max-attempts abandon) so the
|
||||
local edit is pushed once the app is updated.
|
||||
- Until migration `034` runs, the server write retries without `feature_flags`
|
||||
(`withOptionalColumns` in `internal/repository/configuration.go`, same fallback as
|
||||
`line_no`) and logs a warning — sync keeps working, but flags are not stored on the server.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Rule:** any new data feature that an older client would lose on save must add a
|
||||
flag to `configfeatures.known` and to `Detect` in the same change. Features that old
|
||||
clients round-trip safely (e.g. data they carry verbatim) need no flag.
|
||||
- Flags only protect against clients that already contain this check. Clients older
|
||||
than this change ignore `feature_flags` and can still erase newer data — rollout must
|
||||
get every user onto a version with this check.
|
||||
- Order of rollout: apply server migration `034` before (or together with) releasing
|
||||
the client; otherwise flags silently stay local.
|
||||
- The UI shows raw flag ids (an old client, by definition, has no human names for them).
|
||||
+40
-22
@@ -581,6 +581,10 @@ func runSetupMode(local *localdb.LocalDB) {
|
||||
router.POST("/setup/test", setupHandler.TestConnection)
|
||||
router.GET("/setup/status", setupHandler.GetStatus)
|
||||
|
||||
settingsHandler := handlers.NewSettingsHandler(local)
|
||||
router.GET("/api/settings/ui", settingsHandler.GetUI)
|
||||
router.PUT("/api/settings/ui", settingsHandler.PutUI)
|
||||
|
||||
// Health check
|
||||
router.GET("/health", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
@@ -892,6 +896,11 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
router.POST("/setup/test", setupHandler.TestConnection)
|
||||
router.GET("/setup/status", setupHandler.GetStatus)
|
||||
|
||||
// Per-client UI display preferences
|
||||
settingsHandler := handlers.NewSettingsHandler(local)
|
||||
router.GET("/api/settings/ui", settingsHandler.GetUI)
|
||||
router.PUT("/api/settings/ui", settingsHandler.PutUI)
|
||||
|
||||
// Web pages
|
||||
router.GET("/", webHandler.Index)
|
||||
router.GET("/configs", webHandler.Configs)
|
||||
@@ -1077,6 +1086,7 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"article": result.Article,
|
||||
"segments": result.Segments,
|
||||
"warnings": result.Warnings,
|
||||
})
|
||||
})
|
||||
@@ -1574,31 +1584,43 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
|
||||
// Return simplified list of all projects (UUID + Name only)
|
||||
type ProjectSimple struct {
|
||||
UUID string `json:"uuid"`
|
||||
Code string `json:"code"`
|
||||
Variant string `json:"variant"`
|
||||
Name string `json:"name"`
|
||||
IsActive bool `json:"is_active"`
|
||||
RentalEnabled bool `json:"rental_enabled"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UUID string `json:"uuid"`
|
||||
Code string `json:"code"`
|
||||
Variant string `json:"variant"`
|
||||
Name string `json:"name"`
|
||||
IsActive bool `json:"is_active"`
|
||||
RentalEnabled bool `json:"rental_enabled"`
|
||||
ShowStockPrices bool `json:"show_stock_prices"`
|
||||
OnlyInStock bool `json:"only_in_stock"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
simplified := make([]ProjectSimple, 0, len(allProjects))
|
||||
for _, p := range allProjects {
|
||||
simplified = append(simplified, ProjectSimple{
|
||||
UUID: p.UUID,
|
||||
Code: p.Code,
|
||||
Variant: p.Variant,
|
||||
Name: derefString(p.Name),
|
||||
IsActive: p.IsActive,
|
||||
RentalEnabled: p.RentalEnabled,
|
||||
CreatedAt: p.CreatedAt,
|
||||
UUID: p.UUID,
|
||||
Code: p.Code,
|
||||
Variant: p.Variant,
|
||||
Name: derefString(p.Name),
|
||||
IsActive: p.IsActive,
|
||||
RentalEnabled: p.RentalEnabled,
|
||||
ShowStockPrices: p.ShowStockPrices,
|
||||
OnlyInStock: p.OnlyInStock,
|
||||
CreatedAt: p.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, simplified)
|
||||
})
|
||||
|
||||
// ProjectWithWarning flattens a project's fields (via embedding) alongside an
|
||||
// optional variant_warning, set when an invalid variant name (reserved "main" or
|
||||
// disallowed characters) was auto-converted into a valid one instead of rejected.
|
||||
type ProjectWithWarning struct {
|
||||
*models.Project
|
||||
VariantWarning string `json:"variant_warning,omitempty"`
|
||||
}
|
||||
|
||||
projects.POST("", func(c *gin.Context) {
|
||||
var req services.CreateProjectRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
@@ -1609,17 +1631,15 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "project code is required"})
|
||||
return
|
||||
}
|
||||
project, err := projectService.Create(dbUsername, &req)
|
||||
project, variantWarning, err := projectService.Create(dbUsername, &req)
|
||||
if err != nil {
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrReservedMainVariant, http.StatusBadRequest, "invalid request"},
|
||||
errCase{services.ErrProjectCodeInvalidChars, http.StatusBadRequest, "invalid request"},
|
||||
errCase{services.ErrProjectVariantInvalidChars, http.StatusBadRequest, "invalid request"},
|
||||
errCase{services.ErrProjectCodeExists, http.StatusConflict, "conflict detected"},
|
||||
)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, project)
|
||||
c.JSON(http.StatusCreated, ProjectWithWarning{Project: project, VariantWarning: variantWarning})
|
||||
})
|
||||
|
||||
projects.GET("/:uuid", func(c *gin.Context) {
|
||||
@@ -1640,20 +1660,18 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
respondError(c, http.StatusBadRequest, "invalid request", err)
|
||||
return
|
||||
}
|
||||
project, err := projectService.Update(c.Param("uuid"), dbUsername, &req)
|
||||
project, variantWarning, err := projectService.Update(c.Param("uuid"), dbUsername, &req)
|
||||
if err != nil {
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrReservedMainVariant, http.StatusBadRequest, "invalid request"},
|
||||
errCase{services.ErrCannotRenameMainVariant, http.StatusBadRequest, "invalid request"},
|
||||
errCase{services.ErrProjectCodeInvalidChars, http.StatusBadRequest, "invalid request"},
|
||||
errCase{services.ErrProjectVariantInvalidChars, http.StatusBadRequest, "invalid request"},
|
||||
errCase{services.ErrProjectCodeExists, http.StatusConflict, "conflict detected"},
|
||||
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
|
||||
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
|
||||
)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, project)
|
||||
c.JSON(http.StatusOK, ProjectWithWarning{Project: project, VariantWarning: variantWarning})
|
||||
})
|
||||
|
||||
projects.POST("/:uuid/archive", func(c *gin.Context) {
|
||||
|
||||
@@ -42,14 +42,17 @@ func GroupForLotCategory(cat string) (group Group, ok bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// ResolveLotCategories returns lot_category for each lotName found in local_pricelist_items
|
||||
// for the given server pricelist. Lots not found in the pricelist are omitted from the result —
|
||||
// callers must treat a missing key as "no category" and skip that lot.
|
||||
func ResolveLotCategories(local *localdb.LocalDB, serverPricelistID uint, lotNames []string) (map[string]string, error) {
|
||||
// ResolveLotCategories returns lot_category for each lotName, read from the component
|
||||
// universe (latest active world ∪ estimate pricelists — the same source the configurator,
|
||||
// BOM and pricing tab use, see bible-local/decisions/2026-07-24-component-universe-world-union.md).
|
||||
// It must NOT be scoped to a single pricelist: a world-only LOT is a legitimate cart member
|
||||
// and still carries a real lot_category in the world pricelist. LOTs present in neither
|
||||
// pricelist are omitted — callers treat a missing key as "no category" and skip that lot.
|
||||
func ResolveLotCategories(local *localdb.LocalDB, lotNames []string) (map[string]string, error) {
|
||||
if local == nil {
|
||||
return nil, fmt.Errorf("local db is nil")
|
||||
}
|
||||
cats, err := local.GetLocalLotCategoriesByServerPricelistID(serverPricelistID, lotNames)
|
||||
cats, err := local.GetLocalComponentCategoriesByLotNames(lotNames)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ func TestResolveLotCategories_MissingLotOmitted(t *testing.T) {
|
||||
Source: "estimate",
|
||||
Version: "S-2026-02-11-001",
|
||||
Name: "test",
|
||||
IsActive: true,
|
||||
CreatedAt: time.Now(),
|
||||
SyncedAt: time.Now(),
|
||||
}); err != nil {
|
||||
@@ -35,7 +36,7 @@ func TestResolveLotCategories_MissingLotOmitted(t *testing.T) {
|
||||
t.Fatalf("save local items: %v", err)
|
||||
}
|
||||
|
||||
cats, err := ResolveLotCategories(local, 1, []string{"CPU_A", "UNKNOWN"})
|
||||
cats, err := ResolveLotCategories(local, []string{"CPU_A", "UNKNOWN"})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
@@ -76,7 +77,7 @@ func TestResolveLotCategories_ReturnsKnownCategories(t *testing.T) {
|
||||
t.Fatalf("save items: %v", err)
|
||||
}
|
||||
|
||||
cats, err := ResolveLotCategories(local, 1, []string{"CPU_B", "MB_X", "NOT_IN_PL"})
|
||||
cats, err := ResolveLotCategories(local, []string{"CPU_B", "MB_X", "NOT_IN_PL"})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
@@ -91,6 +92,54 @@ func TestResolveLotCategories_ReturnsKnownCategories(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveLotCategories_WorldOnlyLot covers a LOT that exists only in the world
|
||||
// pricelist (never added to estimate) but is a legitimate cart member. Its real
|
||||
// lot_category must be resolved from the component universe, not dropped.
|
||||
func TestResolveLotCategories_WorldOnlyLot(t *testing.T) {
|
||||
local, err := localdb.New(filepath.Join(t.TempDir(), "local.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("init local db: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = local.Close() })
|
||||
|
||||
saved := func(serverID uint, source string, items []localdb.LocalPricelistItem) {
|
||||
if err := local.SaveLocalPricelist(&localdb.LocalPricelist{
|
||||
ServerID: serverID, Source: source, Version: source + "-v1", Name: source,
|
||||
IsActive: true, CreatedAt: time.Now(), SyncedAt: time.Now(),
|
||||
}); err != nil {
|
||||
t.Fatalf("save %s pricelist: %v", source, err)
|
||||
}
|
||||
pl, err := local.GetLocalPricelistByServerID(serverID)
|
||||
if err != nil {
|
||||
t.Fatalf("get %s pricelist: %v", source, err)
|
||||
}
|
||||
for i := range items {
|
||||
items[i].PricelistID = pl.ID
|
||||
}
|
||||
if err := local.SaveLocalPricelistItems(items); err != nil {
|
||||
t.Fatalf("save %s items: %v", source, err)
|
||||
}
|
||||
}
|
||||
|
||||
saved(1, "estimate", []localdb.LocalPricelistItem{
|
||||
{LotName: "CPU_INTEL_8358", LotCategory: "CPU", Price: 1},
|
||||
})
|
||||
saved(2, "world", []localdb.LocalPricelistItem{
|
||||
{LotName: "CPU_INTEL_8358", LotCategory: "CPU", Price: 1},
|
||||
{LotName: "GPU_NV_RTX_PRO_6000D_SERVER_84GB_PCIE", LotCategory: "GPU", Price: 9900},
|
||||
})
|
||||
|
||||
cats, err := ResolveLotCategories(local, []string{
|
||||
"CPU_INTEL_8358", "GPU_NV_RTX_PRO_6000D_SERVER_84GB_PCIE",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if cats["GPU_NV_RTX_PRO_6000D_SERVER_84GB_PCIE"] != "GPU" {
|
||||
t.Fatalf("world-only LOT category not resolved: %q", cats["GPU_NV_RTX_PRO_6000D_SERVER_84GB_PCIE"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupForLotCategory(t *testing.T) {
|
||||
if g, ok := GroupForLotCategory("cpu"); !ok || g != GroupCPU {
|
||||
t.Fatalf("expected cpu -> GroupCPU")
|
||||
|
||||
+192
-128
@@ -11,15 +11,25 @@ import (
|
||||
)
|
||||
|
||||
type BuildOptions struct {
|
||||
ServerModel string
|
||||
ServerPricelist *uint
|
||||
ServerModel string
|
||||
}
|
||||
|
||||
type BuildResult struct {
|
||||
Article string
|
||||
Segments []ResultSegment
|
||||
Warnings []string
|
||||
}
|
||||
|
||||
// ResultSegment is one dash-separated piece of the article, tagged so the UI can
|
||||
// highlight pieces the generator could not fully parse. Recognized is false when
|
||||
// the segment contains a category placeholder (e.g. "GPU" instead of a real model
|
||||
// token) because a lot_name did not match the expected naming shape.
|
||||
type ResultSegment struct {
|
||||
Group string `json:"group"`
|
||||
Text string `json:"text"`
|
||||
Recognized bool `json:"recognized"`
|
||||
}
|
||||
|
||||
var (
|
||||
reMemGiB = regexp.MustCompile(`(?i)(\d+)\s*(GB|G)`)
|
||||
reMemTiB = regexp.MustCompile(`(?i)(\d+)\s*(TB|T)`)
|
||||
@@ -33,6 +43,17 @@ var (
|
||||
type namedSeg struct {
|
||||
group string // "MODEL","CPU","MEM","GPU","DISK","NET","PSU","SUPPORT"
|
||||
value string
|
||||
// degraded marks a segment whose value contains a category placeholder instead
|
||||
// of a parsed spec token, because some lot_name did not match the expected shape.
|
||||
degraded bool
|
||||
}
|
||||
|
||||
// segmentResult is what each build*Segment helper returns: the rendered value, a
|
||||
// degraded flag, and human-readable warnings that name the offending lot_names.
|
||||
type segmentResult struct {
|
||||
value string
|
||||
degraded bool
|
||||
warnings []string
|
||||
}
|
||||
|
||||
func Build(local *localdb.LocalDB, items []models.ConfigItem, opts BuildOptions) (BuildResult, error) {
|
||||
@@ -43,71 +64,59 @@ func Build(local *localdb.LocalDB, items []models.ConfigItem, opts BuildOptions)
|
||||
if model == "" {
|
||||
return BuildResult{}, fmt.Errorf("server_model required")
|
||||
}
|
||||
segs = append(segs, namedSeg{"MODEL", model})
|
||||
segs = append(segs, namedSeg{group: "MODEL", value: model})
|
||||
|
||||
lotNames := make([]string, 0, len(items))
|
||||
for _, it := range items {
|
||||
lotNames = append(lotNames, it.LotName)
|
||||
}
|
||||
|
||||
if opts.ServerPricelist == nil || *opts.ServerPricelist == 0 {
|
||||
return BuildResult{}, fmt.Errorf("pricelist_id required for article")
|
||||
}
|
||||
|
||||
cats, err := ResolveLotCategories(local, *opts.ServerPricelist, lotNames)
|
||||
cats, err := ResolveLotCategories(local, lotNames)
|
||||
if err != nil {
|
||||
return BuildResult{}, err
|
||||
}
|
||||
|
||||
if cpuSeg := buildCPUSegment(items, cats); cpuSeg != "" {
|
||||
segs = append(segs, namedSeg{"CPU", cpuSeg})
|
||||
}
|
||||
memSeg, memWarn := buildMemSegment(items, cats)
|
||||
if memWarn != "" {
|
||||
warnings = append(warnings, memWarn)
|
||||
}
|
||||
if memSeg != "" {
|
||||
segs = append(segs, namedSeg{"MEM", memSeg})
|
||||
}
|
||||
if gpuSeg := buildGPUSegment(items, cats); gpuSeg != "" {
|
||||
segs = append(segs, namedSeg{"GPU", gpuSeg})
|
||||
}
|
||||
diskSeg, diskWarn := buildDiskSegment(items, cats)
|
||||
if diskWarn != "" {
|
||||
warnings = append(warnings, diskWarn)
|
||||
}
|
||||
if diskSeg != "" {
|
||||
segs = append(segs, namedSeg{"DISK", diskSeg})
|
||||
}
|
||||
netSeg, netWarn := buildNetSegment(items, cats)
|
||||
if netWarn != "" {
|
||||
warnings = append(warnings, netWarn)
|
||||
}
|
||||
if netSeg != "" {
|
||||
segs = append(segs, namedSeg{"NET", netSeg})
|
||||
}
|
||||
psuSeg, psuWarn := buildPSUSegment(items, cats)
|
||||
if psuWarn != "" {
|
||||
warnings = append(warnings, psuWarn)
|
||||
}
|
||||
if psuSeg != "" {
|
||||
segs = append(segs, namedSeg{"PSU", psuSeg})
|
||||
for _, sb := range []struct {
|
||||
group string
|
||||
build func([]models.ConfigItem, map[string]string) segmentResult
|
||||
}{
|
||||
{"CPU", buildCPUSegment},
|
||||
{"MEM", buildMemSegment},
|
||||
{"GPU", buildGPUSegment},
|
||||
{"DISK", buildDiskSegment},
|
||||
{"NET", buildNetSegment},
|
||||
{"PSU", buildPSUSegment},
|
||||
} {
|
||||
res := sb.build(items, cats)
|
||||
warnings = append(warnings, res.warnings...)
|
||||
if res.value != "" {
|
||||
segs = append(segs, namedSeg{group: sb.group, value: res.value, degraded: res.degraded})
|
||||
}
|
||||
}
|
||||
|
||||
if supportSeg := buildSupportSegment(items); supportSeg != "" {
|
||||
segs = append(segs, namedSeg{"SUPPORT", supportSeg})
|
||||
segs = append(segs, namedSeg{group: "SUPPORT", value: supportSeg})
|
||||
}
|
||||
|
||||
article := strings.Join(namedSegsValues(segs), "-")
|
||||
if len([]rune(article)) > 80 {
|
||||
article = compressArticle(segs)
|
||||
segs = compressArticle(segs)
|
||||
article = strings.Join(namedSegsValues(segs), "-")
|
||||
warnings = append(warnings, "compressed")
|
||||
}
|
||||
if len([]rune(article)) > 80 {
|
||||
return BuildResult{}, fmt.Errorf("article_overflow")
|
||||
}
|
||||
|
||||
return BuildResult{Article: article, Warnings: warnings}, nil
|
||||
result := BuildResult{Article: article, Warnings: warnings}
|
||||
for _, s := range segs {
|
||||
result.Segments = append(result.Segments, ResultSegment{
|
||||
Group: s.group,
|
||||
Text: s.value,
|
||||
Recognized: !s.degraded,
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func namedSegsValues(segs []namedSeg) []string {
|
||||
@@ -145,38 +154,43 @@ func buildSupportSegment(items []models.ConfigItem) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func buildCPUSegment(items []models.ConfigItem, cats map[string]string) string {
|
||||
type agg struct {
|
||||
qty int
|
||||
// placeholderToken returns the token used in the article when a lot's spec can't be
|
||||
// parsed: the lot_category itself (never a bare "UNK"), uppercased.
|
||||
func placeholderToken(cat string) string {
|
||||
t := strings.ToUpper(strings.TrimSpace(cat))
|
||||
if t == "" {
|
||||
return "X"
|
||||
}
|
||||
models := map[string]*agg{}
|
||||
return t
|
||||
}
|
||||
|
||||
func buildCPUSegment(items []models.ConfigItem, cats map[string]string) segmentResult {
|
||||
models := map[string]int{}
|
||||
res := segmentResult{}
|
||||
for _, it := range items {
|
||||
group, ok := GroupForLotCategory(cats[it.LotName])
|
||||
if !ok || group != GroupCPU {
|
||||
continue
|
||||
}
|
||||
model := parseCPUModel(it.LotName)
|
||||
if model == "" {
|
||||
model = "UNK"
|
||||
model, parsed := parseCPUModel(it.LotName)
|
||||
if !parsed {
|
||||
model = placeholderToken(cats[it.LotName])
|
||||
res.degraded = true
|
||||
res.warnings = append(res.warnings, fmt.Sprintf("CPU: не распознана модель LOT %q — в артикул записана категория %q", it.LotName, model))
|
||||
}
|
||||
if _, ok := models[model]; !ok {
|
||||
models[model] = &agg{}
|
||||
}
|
||||
models[model].qty += it.Quantity
|
||||
models[model] += it.Quantity
|
||||
}
|
||||
if len(models) == 0 {
|
||||
return ""
|
||||
return res
|
||||
}
|
||||
parts := make([]string, 0, len(models))
|
||||
for model, a := range models {
|
||||
parts = append(parts, fmt.Sprintf("%dx%s", a.qty, model))
|
||||
}
|
||||
sort.Strings(parts)
|
||||
return strings.Join(parts, "+")
|
||||
res.value = joinQtyTokens(models)
|
||||
return res
|
||||
}
|
||||
|
||||
func buildMemSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
|
||||
func buildMemSegment(items []models.ConfigItem, cats map[string]string) segmentResult {
|
||||
totalGiB := 0
|
||||
res := segmentResult{}
|
||||
unparsed := 0
|
||||
for _, it := range items {
|
||||
group, ok := GroupForLotCategory(cats[it.LotName])
|
||||
if !ok || group != GroupMEM {
|
||||
@@ -184,21 +198,31 @@ func buildMemSegment(items []models.ConfigItem, cats map[string]string) (string,
|
||||
}
|
||||
per := parseMemGiB(it.LotName)
|
||||
if per <= 0 {
|
||||
return "", "mem_unknown"
|
||||
unparsed++
|
||||
res.degraded = true
|
||||
res.warnings = append(res.warnings, fmt.Sprintf("MEM: не распознан объём LOT %q", it.LotName))
|
||||
continue
|
||||
}
|
||||
totalGiB += per * it.Quantity
|
||||
}
|
||||
if totalGiB == 0 {
|
||||
return "", ""
|
||||
parts := make([]string, 0, 2)
|
||||
if totalGiB > 0 {
|
||||
if totalGiB%1024 == 0 {
|
||||
parts = append(parts, fmt.Sprintf("%dT", totalGiB/1024))
|
||||
} else {
|
||||
parts = append(parts, fmt.Sprintf("%dG", totalGiB))
|
||||
}
|
||||
}
|
||||
if totalGiB%1024 == 0 {
|
||||
return fmt.Sprintf("%dT", totalGiB/1024), ""
|
||||
if unparsed > 0 {
|
||||
parts = append(parts, placeholderToken("MEM"))
|
||||
}
|
||||
return fmt.Sprintf("%dG", totalGiB), ""
|
||||
res.value = strings.Join(parts, "+")
|
||||
return res
|
||||
}
|
||||
|
||||
func buildGPUSegment(items []models.ConfigItem, cats map[string]string) string {
|
||||
func buildGPUSegment(items []models.ConfigItem, cats map[string]string) segmentResult {
|
||||
models := map[string]int{}
|
||||
res := segmentResult{}
|
||||
for _, it := range items {
|
||||
group, ok := GroupForLotCategory(cats[it.LotName])
|
||||
if !ok || group != GroupGPU {
|
||||
@@ -207,30 +231,28 @@ func buildGPUSegment(items []models.ConfigItem, cats map[string]string) string {
|
||||
if strings.HasPrefix(strings.ToUpper(it.LotName), "MB_") {
|
||||
continue
|
||||
}
|
||||
model := parseGPUModel(it.LotName)
|
||||
if model == "" {
|
||||
model = "UNK"
|
||||
model, parsed := parseGPUModel(it.LotName)
|
||||
if !parsed {
|
||||
model = placeholderToken(cats[it.LotName])
|
||||
res.degraded = true
|
||||
res.warnings = append(res.warnings, fmt.Sprintf("GPU: не распознана модель LOT %q — в артикул записана категория %q", it.LotName, model))
|
||||
}
|
||||
models[model] += it.Quantity
|
||||
}
|
||||
if len(models) == 0 {
|
||||
return ""
|
||||
return res
|
||||
}
|
||||
parts := make([]string, 0, len(models))
|
||||
for model, qty := range models {
|
||||
parts = append(parts, fmt.Sprintf("%dx%s", qty, model))
|
||||
}
|
||||
sort.Strings(parts)
|
||||
return strings.Join(parts, "+")
|
||||
res.value = joinQtyTokens(models)
|
||||
return res
|
||||
}
|
||||
|
||||
func buildDiskSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
|
||||
func buildDiskSegment(items []models.ConfigItem, cats map[string]string) segmentResult {
|
||||
type key struct {
|
||||
t string
|
||||
c string
|
||||
}
|
||||
groupQty := map[key]int{}
|
||||
warn := ""
|
||||
res := segmentResult{}
|
||||
for _, it := range items {
|
||||
group, ok := GroupForLotCategory(cats[it.LotName])
|
||||
if !ok || group != GroupDISK {
|
||||
@@ -238,14 +260,14 @@ func buildDiskSegment(items []models.ConfigItem, cats map[string]string) (string
|
||||
}
|
||||
capToken := parseCapacity(it.LotName)
|
||||
if capToken == "" {
|
||||
warn = "disk_unknown"
|
||||
res.degraded = true
|
||||
res.warnings = append(res.warnings, fmt.Sprintf("DISK: не распознан объём LOT %q", it.LotName))
|
||||
}
|
||||
typeCode := diskTypeCode(cats[it.LotName], it.LotName)
|
||||
k := key{t: typeCode, c: capToken}
|
||||
groupQty[k] += it.Quantity
|
||||
groupQty[key{t: typeCode, c: capToken}] += it.Quantity
|
||||
}
|
||||
if len(groupQty) == 0 {
|
||||
return "", ""
|
||||
return res
|
||||
}
|
||||
parts := make([]string, 0, len(groupQty))
|
||||
for k, qty := range groupQty {
|
||||
@@ -256,23 +278,25 @@ func buildDiskSegment(items []models.ConfigItem, cats map[string]string) (string
|
||||
}
|
||||
}
|
||||
sort.Strings(parts)
|
||||
return strings.Join(parts, "+"), warn
|
||||
res.value = strings.Join(parts, "+")
|
||||
return res
|
||||
}
|
||||
|
||||
func buildNetSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
|
||||
return buildProfileSegment(items, cats, GroupNET, parsePortSpeed, "UNKNET", "net_unknown")
|
||||
func buildNetSegment(items []models.ConfigItem, cats map[string]string) segmentResult {
|
||||
return buildProfileSegment(items, cats, GroupNET, parsePortSpeed, "NET")
|
||||
}
|
||||
|
||||
func buildPSUSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
|
||||
return buildProfileSegment(items, cats, GroupPSU, parseWatts, "UNKPSU", "psu_unknown")
|
||||
func buildPSUSegment(items []models.ConfigItem, cats map[string]string) segmentResult {
|
||||
return buildProfileSegment(items, cats, GroupPSU, parseWatts, "PSU")
|
||||
}
|
||||
|
||||
// buildProfileSegment groups items of the given category group by a profile token
|
||||
// parsed from their lot name (e.g. port speed, wattage rating), falling back to
|
||||
// unknownToken and warnCode when a lot's profile can't be determined.
|
||||
func buildProfileSegment(items []models.ConfigItem, cats map[string]string, group Group, parseProfile func(string) string, unknownToken, warnCode string) (string, string) {
|
||||
// parsed from their lot name (e.g. port speed, wattage rating). When a lot's profile
|
||||
// can't be determined it falls back to the category placeholder and flags the segment
|
||||
// as degraded, naming the lot in a warning.
|
||||
func buildProfileSegment(items []models.ConfigItem, cats map[string]string, group Group, parseProfile func(string) string, groupLabel string) segmentResult {
|
||||
groupQty := map[string]int{}
|
||||
warn := ""
|
||||
res := segmentResult{}
|
||||
for _, it := range items {
|
||||
g, ok := GroupForLotCategory(cats[it.LotName])
|
||||
if !ok || g != group {
|
||||
@@ -280,20 +304,27 @@ func buildProfileSegment(items []models.ConfigItem, cats map[string]string, grou
|
||||
}
|
||||
profile := parseProfile(it.LotName)
|
||||
if profile == "" {
|
||||
profile = unknownToken
|
||||
warn = warnCode
|
||||
profile = placeholderToken(groupLabel)
|
||||
res.degraded = true
|
||||
res.warnings = append(res.warnings, fmt.Sprintf("%s: не распознан профиль LOT %q — в артикул записана категория %q", groupLabel, it.LotName, profile))
|
||||
}
|
||||
groupQty[profile] += it.Quantity
|
||||
}
|
||||
if len(groupQty) == 0 {
|
||||
return "", ""
|
||||
return res
|
||||
}
|
||||
parts := make([]string, 0, len(groupQty))
|
||||
for profile, qty := range groupQty {
|
||||
parts = append(parts, fmt.Sprintf("%dx%s", qty, profile))
|
||||
res.value = joinQtyTokens(groupQty)
|
||||
return res
|
||||
}
|
||||
|
||||
// joinQtyTokens renders {token: qty} as a sorted "NxTOKEN+MxTOKEN" string.
|
||||
func joinQtyTokens(qty map[string]int) string {
|
||||
parts := make([]string, 0, len(qty))
|
||||
for token, n := range qty {
|
||||
parts = append(parts, fmt.Sprintf("%dx%s", n, token))
|
||||
}
|
||||
sort.Strings(parts)
|
||||
return strings.Join(parts, "+"), warn
|
||||
return strings.Join(parts, "+")
|
||||
}
|
||||
|
||||
func normalizeModelToken(lotName string) string {
|
||||
@@ -305,18 +336,27 @@ func normalizeModelToken(lotName string) string {
|
||||
return strings.ToUpper(strings.TrimSpace(token))
|
||||
}
|
||||
|
||||
func parseCPUModel(lotName string) string {
|
||||
// parseCPUModel extracts the model token from a CPU lot_name (shape
|
||||
// CPU_{VENDOR}_{MODEL}, e.g. "CPU_INTEL_8592+"). The bool is false when the name
|
||||
// has no parseable {VENDOR}_{MODEL} tail — a structural failure the caller surfaces.
|
||||
// It cannot validate that the token is a real CPU model (no vendor catalog is kept
|
||||
// in the repo by design), only that the name matched the expected shape.
|
||||
func parseCPUModel(lotName string) (string, bool) {
|
||||
parts := strings.Split(lotName, "_")
|
||||
if len(parts) >= 2 {
|
||||
last := strings.ToUpper(strings.TrimSpace(parts[len(parts)-1]))
|
||||
if last != "" {
|
||||
return last
|
||||
return last, true
|
||||
}
|
||||
}
|
||||
return normalizeModelToken(lotName)
|
||||
return normalizeModelToken(lotName), false
|
||||
}
|
||||
|
||||
func parseGPUModel(lotName string) string {
|
||||
// parseGPUModel extracts a "MODEL[_MEM]" token from a GPU lot_name. The bool is
|
||||
// false when no model token could be located and the result is only the last-ditch
|
||||
// last-underscore-segment fallback — a structural failure the caller surfaces.
|
||||
// Like parseCPUModel it does not validate the token against a catalog.
|
||||
func parseGPUModel(lotName string) (string, bool) {
|
||||
upper := strings.ToUpper(lotName)
|
||||
if idx := strings.Index(upper, "GPU_"); idx >= 0 {
|
||||
upper = upper[idx+4:]
|
||||
@@ -347,7 +387,7 @@ func parseGPUModel(lotName string) string {
|
||||
}
|
||||
if model == "" && i > 0 {
|
||||
model = p
|
||||
} else if model != "" && numSuffix == "" && isNumeric(p) {
|
||||
} else if model != "" && numSuffix == "" && isModelNumber(p) {
|
||||
numSuffix = p
|
||||
}
|
||||
}
|
||||
@@ -357,20 +397,24 @@ func parseGPUModel(lotName string) string {
|
||||
full = model + numSuffix
|
||||
}
|
||||
if full != "" && mem != "" {
|
||||
return full + "_" + mem
|
||||
return full + "_" + mem, true
|
||||
}
|
||||
if full != "" {
|
||||
return full
|
||||
return full, true
|
||||
}
|
||||
return normalizeModelToken(lotName)
|
||||
return normalizeModelToken(lotName), false
|
||||
}
|
||||
|
||||
func isNumeric(s string) bool {
|
||||
if s == "" {
|
||||
// isModelNumber reports whether s looks like a GPU/accelerator model number token:
|
||||
// it starts with a digit and contains only digits and uppercase letters. This keeps
|
||||
// vendor-suffixed names like "6000D" (RTX PRO 6000D) intact instead of dropping the
|
||||
// letter and collapsing two distinct models to the same token.
|
||||
func isModelNumber(s string) bool {
|
||||
if s == "" || s[0] < '0' || s[0] > '9' {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if r < '0' || r > '9' {
|
||||
if (r < '0' || r > '9') && (r < 'A' || r > 'Z') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -422,9 +466,28 @@ func parsePortSpeed(lotName string) string {
|
||||
if m := rePortFC.FindStringSubmatch(lotName); len(m) == 3 {
|
||||
return fmt.Sprintf("%spFC%s", m[1], m[2])
|
||||
}
|
||||
if model := parseDPUModel(lotName); model != "" {
|
||||
return model
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// parseDPUModel extracts the "{FAMILY}_{MODEL}" tail from a DPU lot_name (shape
|
||||
// DPU_{FAMILY}_{MODEL}, e.g. "DPU_BF3_B3220-32G" -> "BF3_B3220-32G"). DPU lots have
|
||||
// no port-speed suffix like NIC/HCA, so they fall through parsePortSpeed's regexes;
|
||||
// this keeps the family prefix (e.g. BF2 vs BF3) so distinct DPU generations sharing
|
||||
// a part-number suffix don't collapse into the same article token. Like parseCPUModel
|
||||
// it does not validate against a vendor catalog, only matches the expected shape.
|
||||
func parseDPUModel(lotName string) string {
|
||||
upper := strings.ToUpper(lotName)
|
||||
const prefix = "DPU_"
|
||||
if !strings.HasPrefix(upper, prefix) {
|
||||
return ""
|
||||
}
|
||||
rest := strings.TrimSpace(upper[len(prefix):])
|
||||
return rest
|
||||
}
|
||||
|
||||
func parseWatts(lotName string) string {
|
||||
if m := reWatts.FindStringSubmatch(lotName); len(m) == 2 {
|
||||
w := atoi(m[1])
|
||||
@@ -478,42 +541,43 @@ func atoi(v string) int {
|
||||
return n
|
||||
}
|
||||
|
||||
func compressArticle(segs []namedSeg) string {
|
||||
// compressArticle shortens an over-long article by progressively dropping/abbreviating
|
||||
// segments. It returns the (possibly shortened) segment list; the caller re-joins it.
|
||||
func compressArticle(segs []namedSeg) []namedSeg {
|
||||
if len(segs) == 0 {
|
||||
return ""
|
||||
return segs
|
||||
}
|
||||
fits := func() bool {
|
||||
return len([]rune(strings.Join(namedSegsValues(segs), "-"))) <= 80
|
||||
}
|
||||
for i, s := range segs {
|
||||
segs[i].value = strings.ReplaceAll(s.value, "GbE", "G")
|
||||
}
|
||||
article := strings.Join(namedSegsValues(segs), "-")
|
||||
if len([]rune(article)) <= 80 {
|
||||
return article
|
||||
if fits() {
|
||||
return segs
|
||||
}
|
||||
|
||||
// 1) remove PSU
|
||||
if i := findSegGroup(segs, "PSU"); i >= 0 {
|
||||
segs = append(segs[:i], segs[i+1:]...)
|
||||
article = strings.Join(namedSegsValues(segs), "-")
|
||||
if len([]rune(article)) <= 80 {
|
||||
return article
|
||||
if fits() {
|
||||
return segs
|
||||
}
|
||||
}
|
||||
|
||||
// 2) compress NET/HBA/HCA
|
||||
if i := findSegGroup(segs, "NET"); i >= 0 {
|
||||
segs[i].value = compressNetSegment(segs[i].value)
|
||||
article = strings.Join(namedSegsValues(segs), "-")
|
||||
if len([]rune(article)) <= 80 {
|
||||
return article
|
||||
if fits() {
|
||||
return segs
|
||||
}
|
||||
}
|
||||
|
||||
// 3) compress DISK
|
||||
if i := findSegGroup(segs, "DISK"); i >= 0 {
|
||||
segs[i].value = compressDiskSegment(segs[i].value)
|
||||
article = strings.Join(namedSegsValues(segs), "-")
|
||||
if len([]rune(article)) <= 80 {
|
||||
return article
|
||||
if fits() {
|
||||
return segs
|
||||
}
|
||||
}
|
||||
|
||||
@@ -521,7 +585,7 @@ func compressArticle(segs []namedSeg) string {
|
||||
if i := findSegGroup(segs, "GPU"); i >= 0 {
|
||||
segs[i].value = compressGPUSegment(segs[i].value)
|
||||
}
|
||||
return strings.Join(namedSegsValues(segs), "-")
|
||||
return segs
|
||||
}
|
||||
|
||||
func compressNetSegment(seg string) string {
|
||||
|
||||
@@ -47,8 +47,7 @@ func TestBuild_ParsesNetAndPSU(t *testing.T) {
|
||||
{LotName: "SVC_1yW_x86", Quantity: 1},
|
||||
}
|
||||
result, err := Build(local, items, BuildOptions{
|
||||
ServerModel: "DL380GEN11",
|
||||
ServerPricelist: &localPL.ServerID,
|
||||
ServerModel: "DL380GEN11",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("build article: %v", err)
|
||||
@@ -118,8 +117,7 @@ func TestBuild_CompressArticle_NoGPU_PSUNotNIC(t *testing.T) {
|
||||
{LotName: "PS_1500W_Platinum", Quantity: 2},
|
||||
}
|
||||
result, err := Build(local, items, BuildOptions{
|
||||
ServerModel: "NF5280M6",
|
||||
ServerPricelist: &localPL.ServerID,
|
||||
ServerModel: "NF5280M6",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("build article: %v", err)
|
||||
@@ -140,3 +138,122 @@ func TestBuild_CompressArticle_NoGPU_PSUNotNIC(t *testing.T) {
|
||||
func contains(s, sub string) bool {
|
||||
return strings.Contains(s, sub)
|
||||
}
|
||||
|
||||
func TestParsePortSpeed_DPUModel(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"DPU_BF3_B3220-32G": "BF3_B3220-32G",
|
||||
"DPU_BF2_B2220Q": "BF2_B2220Q",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := parsePortSpeed(in); got != want {
|
||||
t.Errorf("parsePortSpeed(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuild_ParsesDPU verifies a DPU lot (e.g. NVIDIA BlueField) resolves to its
|
||||
// family+model token instead of falling back to the "NET" category placeholder —
|
||||
// DPU lots don't carry a NIC/HCA-style port-speed suffix, so parsePortSpeed needs
|
||||
// its own DPU branch (parseDPUModel).
|
||||
func TestBuild_ParsesDPU(t *testing.T) {
|
||||
local, err := localdb.New(filepath.Join(t.TempDir(), "local.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("init local db: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = local.Close() })
|
||||
|
||||
if err := local.SaveLocalPricelist(&localdb.LocalPricelist{
|
||||
ServerID: 10, Source: "estimate", Version: "v1", Name: "t",
|
||||
IsActive: true, CreatedAt: time.Now(), SyncedAt: time.Now(),
|
||||
}); err != nil {
|
||||
t.Fatalf("save pricelist: %v", err)
|
||||
}
|
||||
pl, err := local.GetLocalPricelistByServerID(10)
|
||||
if err != nil {
|
||||
t.Fatalf("get pricelist: %v", err)
|
||||
}
|
||||
if err := local.SaveLocalPricelistItems([]localdb.LocalPricelistItem{
|
||||
{PricelistID: pl.ID, LotName: "DPU_BF3_B3220-32G", LotCategory: "DPU", Price: 1},
|
||||
}); err != nil {
|
||||
t.Fatalf("save items: %v", err)
|
||||
}
|
||||
|
||||
result, err := Build(local, models.ConfigItems{
|
||||
{LotName: "DPU_BF3_B3220-32G", Quantity: 1},
|
||||
}, BuildOptions{ServerModel: "X1"})
|
||||
if err != nil {
|
||||
t.Fatalf("build: %v", err)
|
||||
}
|
||||
if len(result.Warnings) != 0 {
|
||||
t.Fatalf("expected no warnings, got %v", result.Warnings)
|
||||
}
|
||||
if !contains(result.Article, "BF3_B3220-32G") {
|
||||
t.Fatalf("expected DPU model token in article: %s", result.Article)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseGPUModel_VendorLetterSuffix(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"GPU_NV_RTX_PRO_6000D_SERVER_84GB_PCIE": "RTX6000D_84GB",
|
||||
"GPU_NV_RTX_PRO_6000_SERVER_96GB_PCIE": "RTX6000_96GB",
|
||||
}
|
||||
for in, want := range cases {
|
||||
got, ok := parseGPUModel(in)
|
||||
if !ok || got != want {
|
||||
t.Errorf("parseGPUModel(%q) = %q, %v, want %q, true", in, got, ok, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuild_UnparseableModel_CategoryPlaceholder: a GPU LOT whose name does not
|
||||
// match the expected shape must not silently vanish or emit "UNK" — the article
|
||||
// carries the category token and the segment is flagged not-recognized with a
|
||||
// warning naming the lot.
|
||||
func TestBuild_UnparseableModel_CategoryPlaceholder(t *testing.T) {
|
||||
local, err := localdb.New(filepath.Join(t.TempDir(), "local.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("init local db: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = local.Close() })
|
||||
|
||||
if err := local.SaveLocalPricelist(&localdb.LocalPricelist{
|
||||
ServerID: 9, Source: "estimate", Version: "v1", Name: "t",
|
||||
IsActive: true, CreatedAt: time.Now(), SyncedAt: time.Now(),
|
||||
}); err != nil {
|
||||
t.Fatalf("save pricelist: %v", err)
|
||||
}
|
||||
pl, err := local.GetLocalPricelistByServerID(9)
|
||||
if err != nil {
|
||||
t.Fatalf("get pricelist: %v", err)
|
||||
}
|
||||
if err := local.SaveLocalPricelistItems([]localdb.LocalPricelistItem{
|
||||
{PricelistID: pl.ID, LotName: "WEIRDGPUNAME", LotCategory: "GPU", Price: 1},
|
||||
}); err != nil {
|
||||
t.Fatalf("save items: %v", err)
|
||||
}
|
||||
|
||||
result, err := Build(local, models.ConfigItems{
|
||||
{LotName: "WEIRDGPUNAME", Quantity: 4},
|
||||
}, BuildOptions{ServerModel: "X1"})
|
||||
if err != nil {
|
||||
t.Fatalf("build: %v", err)
|
||||
}
|
||||
if contains(result.Article, "UNK") {
|
||||
t.Fatalf("article must not contain UNK: %s", result.Article)
|
||||
}
|
||||
if !contains(result.Article, "4xGPU") {
|
||||
t.Fatalf("expected category placeholder 4xGPU in article: %s", result.Article)
|
||||
}
|
||||
var gpu *ResultSegment
|
||||
for i := range result.Segments {
|
||||
if result.Segments[i].Group == "GPU" {
|
||||
gpu = &result.Segments[i]
|
||||
}
|
||||
}
|
||||
if gpu == nil || gpu.Recognized {
|
||||
t.Fatalf("GPU segment must be present and not recognized: %+v", result.Segments)
|
||||
}
|
||||
if len(result.Warnings) == 0 || !contains(strings.Join(result.Warnings, "|"), "WEIRDGPUNAME") {
|
||||
t.Fatalf("expected a warning naming WEIRDGPUNAME, got %v", result.Warnings)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
// Package configfeatures holds the per-configuration feature flags: markers recording
|
||||
// which data features a configuration uses, so a client that does not know one of them
|
||||
// refuses to rewrite the configuration instead of silently dropping data it cannot see.
|
||||
//
|
||||
// Flags are derived from content on every save (Detect) and synced as
|
||||
// qt_configurations.feature_flags. A client checks a config's stored flags against the
|
||||
// set it knows (Known) before any write. See
|
||||
// bible-local/decisions/2026-09-24-configuration-feature-flags.md.
|
||||
package configfeatures
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SaleRowMarkups: Notes.pricing_ui.sale_row_markups has at least one row markup.
|
||||
const SaleRowMarkups = "sale_row_markups"
|
||||
|
||||
// known lists every flag this build understands. Adding a flag here is the contract for
|
||||
// "this client can round-trip the data behind it"; a new data feature that an older
|
||||
// client would lose on save must add a flag here and to Detect in the same change.
|
||||
var known = map[string]struct{}{
|
||||
SaleRowMarkups: {},
|
||||
}
|
||||
|
||||
// Known reports whether this build understands flag.
|
||||
func Known(flag string) bool {
|
||||
_, ok := known[flag]
|
||||
return ok
|
||||
}
|
||||
|
||||
// Unknown returns the flags this build does not understand, sorted and de-duplicated.
|
||||
func Unknown(flags []string) []string {
|
||||
seen := make(map[string]struct{}, len(flags))
|
||||
var out []string
|
||||
for _, f := range flags {
|
||||
f = strings.TrimSpace(f)
|
||||
if f == "" || Known(f) {
|
||||
continue
|
||||
}
|
||||
if _, dup := seen[f]; dup {
|
||||
continue
|
||||
}
|
||||
seen[f] = struct{}{}
|
||||
out = append(out, f)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// Detect derives the flags a configuration's content requires. Sorted; nil when none.
|
||||
func Detect(notes string) []string {
|
||||
var flags []string
|
||||
if notesHaveSaleRowMarkups(notes) {
|
||||
flags = append(flags, SaleRowMarkups)
|
||||
}
|
||||
sort.Strings(flags)
|
||||
return flags
|
||||
}
|
||||
|
||||
func notesHaveSaleRowMarkups(notes string) bool {
|
||||
if strings.TrimSpace(notes) == "" {
|
||||
return false
|
||||
}
|
||||
var parsed struct {
|
||||
PricingUI struct {
|
||||
SaleRowMarkups map[string]float64 `json:"sale_row_markups"`
|
||||
} `json:"pricing_ui"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(notes), &parsed); err != nil {
|
||||
return false
|
||||
}
|
||||
for _, pct := range parsed.PricingUI.SaleRowMarkups {
|
||||
if pct != 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// UnsupportedError is returned when a write is refused because the configuration
|
||||
// carries flags this build does not know.
|
||||
type UnsupportedError struct {
|
||||
Flags []string
|
||||
}
|
||||
|
||||
func (e *UnsupportedError) Error() string {
|
||||
return fmt.Sprintf(
|
||||
"конфигурация использует функции, неизвестные этой версии QuoteForge (%s) — обновите приложение, чтобы её изменять",
|
||||
strings.Join(e.Flags, ", "))
|
||||
}
|
||||
|
||||
// Check returns an *UnsupportedError when any of flags is unknown to this build.
|
||||
func Check(flags []string) error {
|
||||
if unknown := Unknown(flags); len(unknown) > 0 {
|
||||
return &UnsupportedError{Flags: unknown}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AsUnsupported unwraps err to an *UnsupportedError, if it is one.
|
||||
func AsUnsupported(err error) (*UnsupportedError, bool) {
|
||||
var ue *UnsupportedError
|
||||
if errors.As(err, &ue) {
|
||||
return ue, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package configfeatures
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDetectSaleRowMarkups(t *testing.T) {
|
||||
cases := []struct {
|
||||
notes string
|
||||
want []string
|
||||
}{
|
||||
{"", nil},
|
||||
{"not json", nil},
|
||||
{`{"pricing_ui":{"sale_uplift":1.5,"sale_row_markups":null}}`, nil},
|
||||
{`{"pricing_ui":{"sale_row_markups":{"NONE::A":0}}}`, nil},
|
||||
{`{"pricing_ui":{"sale_row_markups":{"NONE::A":-50}}}`, []string{SaleRowMarkups}},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := Detect(c.notes); !reflect.DeepEqual(got, c.want) {
|
||||
t.Errorf("Detect(%q) = %v, want %v", c.notes, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownAndCheck(t *testing.T) {
|
||||
got := Unknown([]string{"zeta", SaleRowMarkups, "alpha", "zeta", " "})
|
||||
if want := []string{"alpha", "zeta"}; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("Unknown = %v, want %v", got, want)
|
||||
}
|
||||
if err := Check([]string{SaleRowMarkups}); err != nil {
|
||||
t.Fatalf("Check(known) = %v", err)
|
||||
}
|
||||
ue, ok := AsUnsupported(Check([]string{"future_x"}))
|
||||
if !ok || !reflect.DeepEqual(ue.Flags, []string{"future_x"}) {
|
||||
t.Fatalf("Check(unknown) = %v, %v", ue, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// Flag names are permanent and follow bible-local/02-architecture.md
|
||||
// "Configuration feature flags": lower_snake_case, starts with a letter, ≤ 64 chars.
|
||||
func TestKnownFlagNamesFormat(t *testing.T) {
|
||||
valid := regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
|
||||
for flag := range known {
|
||||
if !valid.MatchString(flag) {
|
||||
t.Errorf("flag %q violates the naming format", flag)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,15 @@ type ProjectExportOptionsRequest struct {
|
||||
IncludeCompetitor bool `json:"include_competitor"`
|
||||
Basis string `json:"basis"` // "fob" or "ddp"
|
||||
SaleMarkup float64 `json:"sale_markup"` // DDP multiplier; 0 defaults to 1.3
|
||||
|
||||
ManualPrice *float64 `json:"manual_price"` // user-defined total price; distributed proportionally across rows
|
||||
|
||||
// MinimalSaleColumns/SaleRowMarkups are sent only by the single-config Sale-table
|
||||
// "Экспорт CSV" button (index.html exportPricingCSV('sale')) — never by the Buy
|
||||
// export or the project-level bulk export, which always leave these zero-valued so
|
||||
// their output stays unchanged. See services.ProjectPricingExportOptions.
|
||||
MinimalSaleColumns bool `json:"minimal_sale_columns"`
|
||||
SaleRowMarkups map[string]float64 `json:"sale_row_markups"` // "<vendorPN>::<lot>" -> markup percent
|
||||
}
|
||||
|
||||
func (h *ExportHandler) ExportCSV(c *gin.Context) {
|
||||
@@ -238,15 +247,31 @@ func (h *ExportHandler) ExportConfigPricingCSV(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var project *models.Project
|
||||
if config.ProjectUUID != nil && *config.ProjectUUID != "" {
|
||||
if p, err := h.projectService.GetByUUID(*config.ProjectUUID, h.dbUsername); err == nil {
|
||||
project = p
|
||||
}
|
||||
}
|
||||
|
||||
opts := services.ProjectPricingExportOptions{
|
||||
IncludeLOT: req.IncludeLOT,
|
||||
IncludeBOM: req.IncludeBOM,
|
||||
IncludeEstimate: req.IncludeEstimate,
|
||||
IncludeStock: req.IncludeStock,
|
||||
IncludeStock: req.IncludeStock && project != nil && project.ShowStockPrices,
|
||||
IncludeCompetitor: req.IncludeCompetitor,
|
||||
Basis: req.Basis,
|
||||
SaleMarkup: req.SaleMarkup,
|
||||
}
|
||||
// MinimalSaleColumns/SaleRowMarkups/ManualPrice are only ever sent by the Sale
|
||||
// table's own "Экспорт CSV" button (index.html exportPricingCSV('sale')) — gating
|
||||
// on the request's own flag keeps every other caller (Buy export, any other basis=
|
||||
// ddp caller) byte-identical to before this field existed.
|
||||
if req.MinimalSaleColumns {
|
||||
opts.MinimalSaleColumns = true
|
||||
opts.SaleRowMarkups = req.SaleRowMarkups
|
||||
opts.ManualPrice = req.ManualPrice
|
||||
}
|
||||
|
||||
data, err := h.exportService.ConfigToPricingExportData(config, opts)
|
||||
if err != nil {
|
||||
@@ -260,10 +285,8 @@ func (h *ExportHandler) ExportConfigPricingCSV(c *gin.Context) {
|
||||
}
|
||||
|
||||
projectCode := config.Name
|
||||
if config.ProjectUUID != nil && *config.ProjectUUID != "" {
|
||||
if project, err := h.projectService.GetByUUID(*config.ProjectUUID, h.dbUsername); err == nil && project != nil {
|
||||
projectCode = project.Code
|
||||
}
|
||||
if project != nil {
|
||||
projectCode = project.Code
|
||||
}
|
||||
|
||||
filename := fmt.Sprintf("%s (%s) %s %s SPEC.csv",
|
||||
@@ -309,7 +332,7 @@ func (h *ExportHandler) ExportProjectPricingCSV(c *gin.Context) {
|
||||
IncludeLOT: req.IncludeLOT,
|
||||
IncludeBOM: req.IncludeBOM,
|
||||
IncludeEstimate: req.IncludeEstimate,
|
||||
IncludeStock: req.IncludeStock,
|
||||
IncludeStock: req.IncludeStock && project.ShowStockPrices,
|
||||
IncludeCompetitor: req.IncludeCompetitor,
|
||||
Basis: req.Basis,
|
||||
SaleMarkup: req.SaleMarkup,
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -14,6 +15,16 @@ func RespondError(c *gin.Context, status int, fallback string, err error) {
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
}
|
||||
// A write refused over unknown configuration feature flags is a 409 with the flag list,
|
||||
// whatever status the caller picked — every config write path funnels through here.
|
||||
if ue, ok := configfeatures.AsUnsupported(err); ok {
|
||||
c.JSON(http.StatusConflict, gin.H{
|
||||
"error": ue.Error(),
|
||||
"code": "unsupported_config_features",
|
||||
"unsupported_features": ue.Flags,
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(status, gin.H{"error": clientFacingErrorMessage(status, fallback, err)})
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,13 @@ package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestClientFacingErrorMessageKeepsDomain4xx(t *testing.T) {
|
||||
@@ -39,3 +45,26 @@ type errString string
|
||||
func (e errString) Error() string {
|
||||
return string(e)
|
||||
}
|
||||
|
||||
func TestRespondErrorUnsupportedFeaturesIs409(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
|
||||
err := fmt.Errorf("wrapped: %w", configfeatures.Check([]string{"future_x"}))
|
||||
RespondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want 409", w.Code)
|
||||
}
|
||||
var body struct {
|
||||
Code string `json:"code"`
|
||||
Features []string `json:"unsupported_features"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode body: %v", err)
|
||||
}
|
||||
if body.Code != "unsupported_config_features" || len(body.Features) != 1 || body.Features[0] != "future_x" {
|
||||
t.Fatalf("unexpected body %s", w.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// SettingsHandler serves per-client UI display preferences stored in app_settings.
|
||||
type SettingsHandler struct {
|
||||
localDB *localdb.LocalDB
|
||||
}
|
||||
|
||||
func NewSettingsHandler(localDB *localdb.LocalDB) *SettingsHandler {
|
||||
return &SettingsHandler{localDB: localDB}
|
||||
}
|
||||
|
||||
type uiSettingsResponse struct {
|
||||
IndicatorMode string `json:"indicator_mode"`
|
||||
}
|
||||
|
||||
// GetUI returns the current UI display preferences.
|
||||
func (h *SettingsHandler) GetUI(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, uiSettingsResponse{
|
||||
IndicatorMode: h.localDB.GetIndicatorMode(),
|
||||
})
|
||||
}
|
||||
|
||||
// PutUI updates UI display preferences. Currently only indicator_mode.
|
||||
func (h *SettingsHandler) PutUI(c *gin.Context) {
|
||||
req, ok := BindJSON[struct {
|
||||
IndicatorMode string `json:"indicator_mode"`
|
||||
}](c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.localDB.SetIndicatorMode(req.IndicatorMode); err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid indicator_mode", err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, uiSettingsResponse{
|
||||
IndicatorMode: h.localDB.GetIndicatorMode(),
|
||||
})
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
qfassets "git.mchus.pro/mchus/quoteforge"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/appmeta"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/db"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -56,7 +57,9 @@ func (h *SetupHandler) ShowSetup(c *gin.Context) {
|
||||
settings, _ := h.localDB.GetSettings()
|
||||
|
||||
data := gin.H{
|
||||
"Settings": settings,
|
||||
"Settings": settings,
|
||||
"IndicatorMode": h.localDB.GetIndicatorMode(),
|
||||
"AppVersion": appmeta.Version(),
|
||||
}
|
||||
|
||||
tmpl := h.templates["setup.html"]
|
||||
@@ -207,4 +210,3 @@ func buildMySQLDSN(host string, port int, database, user, password string, timeo
|
||||
}
|
||||
return cfg.FormatDSN()
|
||||
}
|
||||
|
||||
@@ -114,6 +114,10 @@ func NewWebHandler(_ string, localDB *localdb.LocalDB) (*WebHandler, error) {
|
||||
|
||||
func (h *WebHandler) render(c *gin.Context, name string, data gin.H) {
|
||||
data["AppVersion"] = appmeta.Version()
|
||||
data["IndicatorMode"] = localdb.IndicatorModeColor
|
||||
if h.localDB != nil {
|
||||
data["IndicatorMode"] = h.localDB.GetIndicatorMode()
|
||||
}
|
||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||
tmpl, ok := h.templates[name]
|
||||
if !ok {
|
||||
|
||||
@@ -19,7 +19,6 @@ func TestConfigurationConvertersPreserveBusinessFields(t *testing.T) {
|
||||
WarehousePricelistID: &warehouseID,
|
||||
CompetitorPricelistID: &competitorID,
|
||||
DisablePriceRefresh: true,
|
||||
OnlyInStock: true,
|
||||
}
|
||||
|
||||
local := ConfigurationToLocal(cfg)
|
||||
@@ -57,7 +56,6 @@ func TestConfigurationSnapshotPreservesBusinessFields(t *testing.T) {
|
||||
WarehousePricelistID: &warehouseID,
|
||||
CompetitorPricelistID: &competitorID,
|
||||
DisablePriceRefresh: true,
|
||||
OnlyInStock: true,
|
||||
VendorSpec: VendorSpec{
|
||||
{
|
||||
SortOrder: 10,
|
||||
@@ -110,7 +108,6 @@ func TestConfigurationFingerprintIncludesPricingSelectorsAndVendorSpec(t *testin
|
||||
WarehousePricelistID: &warehouseID,
|
||||
CompetitorPricelistID: &competitorID,
|
||||
DisablePriceRefresh: true,
|
||||
OnlyInStock: true,
|
||||
VendorSpec: VendorSpec{
|
||||
{
|
||||
SortOrder: 10,
|
||||
|
||||
@@ -3,6 +3,7 @@ package localdb
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
)
|
||||
|
||||
@@ -62,6 +63,7 @@ func ConfigurationToLocal(cfg *models.Configuration) *LocalConfiguration {
|
||||
TotalPrice: cfg.TotalPrice,
|
||||
CustomPrice: cfg.CustomPrice,
|
||||
Notes: cfg.Notes,
|
||||
FeatureFlags: cfg.FeatureFlags,
|
||||
IsTemplate: cfg.IsTemplate,
|
||||
ServerCount: cfg.ServerCount,
|
||||
ServerModel: cfg.ServerModel,
|
||||
@@ -73,7 +75,6 @@ func ConfigurationToLocal(cfg *models.Configuration) *LocalConfiguration {
|
||||
ConfigType: cfg.ConfigType,
|
||||
VendorSpec: modelVendorSpecToLocal(cfg.VendorSpec),
|
||||
DisablePriceRefresh: cfg.DisablePriceRefresh,
|
||||
OnlyInStock: cfg.OnlyInStock,
|
||||
RentalItems: modelRentalItemsToLocal(cfg.RentalItems),
|
||||
RentalUpliftPercent: cfg.RentalUpliftPercent,
|
||||
Line: cfg.Line,
|
||||
@@ -113,6 +114,8 @@ func LocalToConfiguration(local *LocalConfiguration) *models.Configuration {
|
||||
TotalPrice: local.TotalPrice,
|
||||
CustomPrice: local.CustomPrice,
|
||||
Notes: local.Notes,
|
||||
FeatureFlags: local.FeatureFlags,
|
||||
UnsupportedFeatures: configfeatures.Unknown(local.FeatureFlags),
|
||||
IsTemplate: local.IsTemplate,
|
||||
ServerCount: local.ServerCount,
|
||||
ServerModel: local.ServerModel,
|
||||
@@ -124,7 +127,6 @@ func LocalToConfiguration(local *LocalConfiguration) *models.Configuration {
|
||||
ConfigType: local.ConfigType,
|
||||
VendorSpec: localVendorSpecToModel(local.VendorSpec),
|
||||
DisablePriceRefresh: local.DisablePriceRefresh,
|
||||
OnlyInStock: local.OnlyInStock,
|
||||
RentalItems: localRentalItemsToModel(local.RentalItems),
|
||||
RentalUpliftPercent: local.RentalUpliftPercent,
|
||||
Line: local.Line,
|
||||
@@ -259,18 +261,20 @@ func localRentalItemsToModel(items RentalItemConditions) models.RentalItemCondit
|
||||
|
||||
func ProjectToLocal(project *models.Project) *LocalProject {
|
||||
local := &LocalProject{
|
||||
UUID: project.UUID,
|
||||
OwnerUsername: project.OwnerUsername,
|
||||
Code: project.Code,
|
||||
Variant: project.Variant,
|
||||
Name: project.Name,
|
||||
TrackerURL: project.TrackerURL,
|
||||
IsActive: project.IsActive,
|
||||
IsSystem: project.IsSystem,
|
||||
RentalEnabled: project.RentalEnabled,
|
||||
CreatedAt: project.CreatedAt,
|
||||
UpdatedAt: project.UpdatedAt,
|
||||
SyncStatus: "pending",
|
||||
UUID: project.UUID,
|
||||
OwnerUsername: project.OwnerUsername,
|
||||
Code: project.Code,
|
||||
Variant: project.Variant,
|
||||
Name: project.Name,
|
||||
TrackerURL: project.TrackerURL,
|
||||
IsActive: project.IsActive,
|
||||
IsSystem: project.IsSystem,
|
||||
RentalEnabled: project.RentalEnabled,
|
||||
ShowStockPrices: project.ShowStockPrices,
|
||||
OnlyInStock: project.OnlyInStock,
|
||||
CreatedAt: project.CreatedAt,
|
||||
UpdatedAt: project.UpdatedAt,
|
||||
SyncStatus: "pending",
|
||||
}
|
||||
if project.ID > 0 {
|
||||
serverID := project.ID
|
||||
@@ -281,17 +285,19 @@ func ProjectToLocal(project *models.Project) *LocalProject {
|
||||
|
||||
func LocalToProject(local *LocalProject) *models.Project {
|
||||
project := &models.Project{
|
||||
UUID: local.UUID,
|
||||
OwnerUsername: local.OwnerUsername,
|
||||
Code: local.Code,
|
||||
Variant: local.Variant,
|
||||
Name: local.Name,
|
||||
TrackerURL: local.TrackerURL,
|
||||
IsActive: local.IsActive,
|
||||
IsSystem: local.IsSystem,
|
||||
RentalEnabled: local.RentalEnabled,
|
||||
CreatedAt: local.CreatedAt,
|
||||
UpdatedAt: local.UpdatedAt,
|
||||
UUID: local.UUID,
|
||||
OwnerUsername: local.OwnerUsername,
|
||||
Code: local.Code,
|
||||
Variant: local.Variant,
|
||||
Name: local.Name,
|
||||
TrackerURL: local.TrackerURL,
|
||||
IsActive: local.IsActive,
|
||||
IsSystem: local.IsSystem,
|
||||
RentalEnabled: local.RentalEnabled,
|
||||
ShowStockPrices: local.ShowStockPrices,
|
||||
OnlyInStock: local.OnlyInStock,
|
||||
CreatedAt: local.CreatedAt,
|
||||
UpdatedAt: local.UpdatedAt,
|
||||
}
|
||||
if local.ServerID != nil {
|
||||
project.ID = *local.ServerID
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package localdb
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newModeDB(t *testing.T) *LocalDB {
|
||||
t.Helper()
|
||||
local, err := New(filepath.Join(t.TempDir(), "mode.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open localdb: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = local.Close() })
|
||||
return local
|
||||
}
|
||||
|
||||
func TestIndicatorMode(t *testing.T) {
|
||||
local := newModeDB(t)
|
||||
|
||||
if got := local.GetIndicatorMode(); got != IndicatorModeColor {
|
||||
t.Fatalf("unset: got %q, want %q", got, IndicatorModeColor)
|
||||
}
|
||||
|
||||
if err := local.SetIndicatorMode(IndicatorModeAccessible); err != nil {
|
||||
t.Fatalf("set accessible: %v", err)
|
||||
}
|
||||
if got := local.GetIndicatorMode(); got != IndicatorModeAccessible {
|
||||
t.Fatalf("after set accessible: got %q, want %q", got, IndicatorModeAccessible)
|
||||
}
|
||||
|
||||
if err := local.SetIndicatorMode(IndicatorModeColor); err != nil {
|
||||
t.Fatalf("set color: %v", err)
|
||||
}
|
||||
if got := local.GetIndicatorMode(); got != IndicatorModeColor {
|
||||
t.Fatalf("after set color: got %q, want %q", got, IndicatorModeColor)
|
||||
}
|
||||
|
||||
if err := local.SetIndicatorMode("rainbow"); err == nil {
|
||||
t.Fatal("expected error for invalid mode, got nil")
|
||||
}
|
||||
if got := local.GetIndicatorMode(); got != IndicatorModeColor {
|
||||
t.Fatalf("after rejected set: got %q, want %q", got, IndicatorModeColor)
|
||||
}
|
||||
}
|
||||
@@ -212,6 +212,8 @@ CREATE TABLE local_projects (
|
||||
is_active INTEGER NOT NULL DEFAULT 1,
|
||||
is_system INTEGER NOT NULL DEFAULT 0,
|
||||
rental_enabled INTEGER NOT NULL DEFAULT 0,
|
||||
show_stock_prices INTEGER NOT NULL DEFAULT 0,
|
||||
only_in_stock INTEGER NOT NULL DEFAULT 0,
|
||||
created_at DATETIME,
|
||||
updated_at DATETIME,
|
||||
synced_at DATETIME NULL,
|
||||
@@ -1128,6 +1130,43 @@ func (l *LocalDB) upsertAppSetting(tx *gorm.DB, key, value string, updatedAt tim
|
||||
`, key, value, updatedAt.Format(time.RFC3339)).Error
|
||||
}
|
||||
|
||||
// Indicator display mode: how the UI renders signals that are otherwise carried
|
||||
// by colour alone (price-quality scale, world-fallback price cells, incomplete
|
||||
// pricing totals). "color" (default) keeps the hue coding; "accessible" swaps it
|
||||
// for shape/text so it stays readable with a colour-vision deficiency. Per-client
|
||||
// preference stored in app_settings; consumed by web/static/price-quality.js and
|
||||
// the pricing tab via base.html's window.QF_INDICATOR_MODE.
|
||||
const (
|
||||
IndicatorModeColor = "color"
|
||||
IndicatorModeAccessible = "accessible"
|
||||
)
|
||||
|
||||
// GetIndicatorMode returns the stored indicator display mode, falling back to
|
||||
// "color" when unset or invalid.
|
||||
func (l *LocalDB) GetIndicatorMode() string {
|
||||
value, ok := l.getAppSettingValue("indicator_mode")
|
||||
if !ok {
|
||||
return IndicatorModeColor
|
||||
}
|
||||
switch strings.TrimSpace(value) {
|
||||
case IndicatorModeAccessible:
|
||||
return IndicatorModeAccessible
|
||||
default:
|
||||
return IndicatorModeColor
|
||||
}
|
||||
}
|
||||
|
||||
// SetIndicatorMode stores the indicator display mode. Only the two known
|
||||
// literals are accepted.
|
||||
func (l *LocalDB) SetIndicatorMode(mode string) error {
|
||||
mode = strings.TrimSpace(mode)
|
||||
if mode != IndicatorModeColor && mode != IndicatorModeAccessible {
|
||||
return fmt.Errorf("invalid indicator mode %q", mode)
|
||||
}
|
||||
now := time.Now()
|
||||
return l.upsertAppSetting(l.db, "indicator_mode", mode, now)
|
||||
}
|
||||
|
||||
// SetLastSyncTime sets the last sync timestamp
|
||||
func (l *LocalDB) SetLastSyncTime(t time.Time) error {
|
||||
// Using raw SQL for upsert since SQLite doesn't have native UPSERT in all versions
|
||||
|
||||
@@ -139,6 +139,11 @@ var localMigrations = []localMigration{
|
||||
name: "Add price_quality to local_pricelist_items",
|
||||
run: addLocalPricelistItemPriceQuality,
|
||||
},
|
||||
{
|
||||
id: "2026_08_12_local_project_stock_settings",
|
||||
name: "Add show_stock_prices and only_in_stock to local_projects",
|
||||
run: addLocalProjectStockSettings,
|
||||
},
|
||||
}
|
||||
|
||||
func addLocalPricelistItemPriceQuality(tx *gorm.DB) error {
|
||||
@@ -249,6 +254,22 @@ func addLocalProjectRentalEnabled(tx *gorm.DB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func addLocalProjectStockSettings(tx *gorm.DB) error {
|
||||
stmts := []string{
|
||||
`ALTER TABLE local_projects ADD COLUMN show_stock_prices INTEGER NOT NULL DEFAULT 0`,
|
||||
`ALTER TABLE local_projects ADD COLUMN only_in_stock INTEGER NOT NULL DEFAULT 0`,
|
||||
}
|
||||
for _, stmt := range stmts {
|
||||
if err := tx.Exec(stmt).Error; err != nil {
|
||||
if !strings.Contains(strings.ToLower(err.Error()), "duplicate") &&
|
||||
!strings.Contains(strings.ToLower(err.Error()), "exists") {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type localPartnumberCatalogRow struct {
|
||||
Partnumber string
|
||||
LotsJSON LocalPartnumberBookLots
|
||||
|
||||
+18
-16
@@ -102,6 +102,7 @@ type LocalConfiguration struct {
|
||||
TotalPrice *float64 `json:"total_price"`
|
||||
CustomPrice *float64 `json:"custom_price"`
|
||||
Notes string `json:"notes"`
|
||||
FeatureFlags models.FeatureFlags `gorm:"type:text" json:"feature_flags,omitempty"`
|
||||
IsTemplate bool `gorm:"default:false" json:"is_template"`
|
||||
ServerCount int `gorm:"default:1" json:"server_count"`
|
||||
ServerModel string `gorm:"size:100" json:"server_model,omitempty"`
|
||||
@@ -111,7 +112,6 @@ type LocalConfiguration struct {
|
||||
WarehousePricelistID *uint `gorm:"index" json:"warehouse_pricelist_id,omitempty"`
|
||||
CompetitorPricelistID *uint `gorm:"index" json:"competitor_pricelist_id,omitempty"`
|
||||
DisablePriceRefresh bool `gorm:"default:false" json:"disable_price_refresh"`
|
||||
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
|
||||
RentalItems RentalItemConditions `gorm:"type:text" json:"rental_items,omitempty"`
|
||||
RentalUpliftPercent float64 `gorm:"default:0" json:"rental_uplift_percent"`
|
||||
VendorSpec VendorSpec `gorm:"type:text" json:"vendor_spec,omitempty"`
|
||||
@@ -133,21 +133,23 @@ func (LocalConfiguration) TableName() string {
|
||||
}
|
||||
|
||||
type LocalProject struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"uniqueIndex;not null" json:"uuid"`
|
||||
ServerID *uint `json:"server_id,omitempty"`
|
||||
OwnerUsername string `gorm:"not null;index" json:"owner_username"`
|
||||
Code string `gorm:"not null;index:idx_local_projects_code_variant,priority:1" json:"code"`
|
||||
Variant string `gorm:"default:'';index:idx_local_projects_code_variant,priority:2" json:"variant"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
TrackerURL string `json:"tracker_url"`
|
||||
IsActive bool `gorm:"default:true;index" json:"is_active"`
|
||||
IsSystem bool `gorm:"default:false;index" json:"is_system"`
|
||||
RentalEnabled bool `gorm:"default:false" json:"rental_enabled"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
SyncedAt *time.Time `json:"synced_at,omitempty"`
|
||||
SyncStatus string `gorm:"default:'local'" json:"sync_status"` // local/synced/pending
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"uniqueIndex;not null" json:"uuid"`
|
||||
ServerID *uint `json:"server_id,omitempty"`
|
||||
OwnerUsername string `gorm:"not null;index" json:"owner_username"`
|
||||
Code string `gorm:"not null;index:idx_local_projects_code_variant,priority:1" json:"code"`
|
||||
Variant string `gorm:"default:'';index:idx_local_projects_code_variant,priority:2" json:"variant"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
TrackerURL string `json:"tracker_url"`
|
||||
IsActive bool `gorm:"default:true;index" json:"is_active"`
|
||||
IsSystem bool `gorm:"default:false;index" json:"is_system"`
|
||||
RentalEnabled bool `gorm:"default:false" json:"rental_enabled"`
|
||||
ShowStockPrices bool `gorm:"default:false" json:"show_stock_prices"`
|
||||
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
SyncedAt *time.Time `json:"synced_at,omitempty"`
|
||||
SyncStatus string `gorm:"default:'local'" json:"sync_status"` // local/synced/pending
|
||||
}
|
||||
|
||||
func (LocalProject) TableName() string {
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
)
|
||||
|
||||
// BuildConfigurationSnapshot serializes the full local configuration state.
|
||||
@@ -21,6 +23,7 @@ func BuildConfigurationSnapshot(localCfg *LocalConfiguration) (string, error) {
|
||||
"total_price": localCfg.TotalPrice,
|
||||
"custom_price": localCfg.CustomPrice,
|
||||
"notes": localCfg.Notes,
|
||||
"feature_flags": localCfg.FeatureFlags,
|
||||
"is_template": localCfg.IsTemplate,
|
||||
"server_count": localCfg.ServerCount,
|
||||
"server_model": localCfg.ServerModel,
|
||||
@@ -30,7 +33,6 @@ func BuildConfigurationSnapshot(localCfg *LocalConfiguration) (string, error) {
|
||||
"warehouse_pricelist_id": localCfg.WarehousePricelistID,
|
||||
"competitor_pricelist_id": localCfg.CompetitorPricelistID,
|
||||
"disable_price_refresh": localCfg.DisablePriceRefresh,
|
||||
"only_in_stock": localCfg.OnlyInStock,
|
||||
"rental_items": localCfg.RentalItems,
|
||||
"rental_uplift_percent": localCfg.RentalUpliftPercent,
|
||||
"vendor_spec": localCfg.VendorSpec,
|
||||
@@ -54,30 +56,30 @@ func BuildConfigurationSnapshot(localCfg *LocalConfiguration) (string, error) {
|
||||
// DecodeConfigurationSnapshot returns editable fields from one saved snapshot.
|
||||
func DecodeConfigurationSnapshot(data string) (*LocalConfiguration, error) {
|
||||
var snapshot struct {
|
||||
ProjectUUID *string `json:"project_uuid"`
|
||||
IsActive *bool `json:"is_active"`
|
||||
Name string `json:"name"`
|
||||
Items LocalConfigItems `json:"items"`
|
||||
TotalPrice *float64 `json:"total_price"`
|
||||
CustomPrice *float64 `json:"custom_price"`
|
||||
Notes string `json:"notes"`
|
||||
IsTemplate bool `json:"is_template"`
|
||||
ServerCount int `json:"server_count"`
|
||||
ServerModel string `json:"server_model"`
|
||||
SupportCode string `json:"support_code"`
|
||||
Article string `json:"article"`
|
||||
PricelistID *uint `json:"pricelist_id"`
|
||||
WarehousePricelistID *uint `json:"warehouse_pricelist_id"`
|
||||
CompetitorPricelistID *uint `json:"competitor_pricelist_id"`
|
||||
ProjectUUID *string `json:"project_uuid"`
|
||||
IsActive *bool `json:"is_active"`
|
||||
Name string `json:"name"`
|
||||
Items LocalConfigItems `json:"items"`
|
||||
TotalPrice *float64 `json:"total_price"`
|
||||
CustomPrice *float64 `json:"custom_price"`
|
||||
Notes string `json:"notes"`
|
||||
FeatureFlags models.FeatureFlags `json:"feature_flags"`
|
||||
IsTemplate bool `json:"is_template"`
|
||||
ServerCount int `json:"server_count"`
|
||||
ServerModel string `json:"server_model"`
|
||||
SupportCode string `json:"support_code"`
|
||||
Article string `json:"article"`
|
||||
PricelistID *uint `json:"pricelist_id"`
|
||||
WarehousePricelistID *uint `json:"warehouse_pricelist_id"`
|
||||
CompetitorPricelistID *uint `json:"competitor_pricelist_id"`
|
||||
DisablePriceRefresh bool `json:"disable_price_refresh"`
|
||||
OnlyInStock bool `json:"only_in_stock"`
|
||||
RentalItems RentalItemConditions `json:"rental_items"`
|
||||
RentalUpliftPercent float64 `json:"rental_uplift_percent"`
|
||||
VendorSpec VendorSpec `json:"vendor_spec"`
|
||||
Line int `json:"line"`
|
||||
PriceUpdatedAt *time.Time `json:"price_updated_at"`
|
||||
OriginalUserID uint `json:"original_user_id"`
|
||||
OriginalUsername string `json:"original_username"`
|
||||
VendorSpec VendorSpec `json:"vendor_spec"`
|
||||
Line int `json:"line"`
|
||||
PriceUpdatedAt *time.Time `json:"price_updated_at"`
|
||||
OriginalUserID uint `json:"original_user_id"`
|
||||
OriginalUsername string `json:"original_username"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal([]byte(data), &snapshot); err != nil {
|
||||
@@ -97,6 +99,7 @@ func DecodeConfigurationSnapshot(data string) (*LocalConfiguration, error) {
|
||||
TotalPrice: snapshot.TotalPrice,
|
||||
CustomPrice: snapshot.CustomPrice,
|
||||
Notes: snapshot.Notes,
|
||||
FeatureFlags: snapshot.FeatureFlags,
|
||||
IsTemplate: snapshot.IsTemplate,
|
||||
ServerCount: snapshot.ServerCount,
|
||||
ServerModel: snapshot.ServerModel,
|
||||
@@ -106,7 +109,6 @@ func DecodeConfigurationSnapshot(data string) (*LocalConfiguration, error) {
|
||||
WarehousePricelistID: snapshot.WarehousePricelistID,
|
||||
CompetitorPricelistID: snapshot.CompetitorPricelistID,
|
||||
DisablePriceRefresh: snapshot.DisablePriceRefresh,
|
||||
OnlyInStock: snapshot.OnlyInStock,
|
||||
RentalItems: snapshot.RentalItems,
|
||||
RentalUpliftPercent: snapshot.RentalUpliftPercent,
|
||||
VendorSpec: snapshot.VendorSpec,
|
||||
@@ -126,7 +128,6 @@ type configurationSpecPriceFingerprint struct {
|
||||
WarehousePricelistID *uint `json:"warehouse_pricelist_id,omitempty"`
|
||||
CompetitorPricelistID *uint `json:"competitor_pricelist_id,omitempty"`
|
||||
DisablePriceRefresh bool `json:"disable_price_refresh"`
|
||||
OnlyInStock bool `json:"only_in_stock"`
|
||||
RentalItems RentalItemConditions `json:"rental_items,omitempty"`
|
||||
RentalUpliftPercent float64 `json:"rental_uplift_percent"`
|
||||
VendorSpec VendorSpec `json:"vendor_spec,omitempty"`
|
||||
@@ -174,7 +175,6 @@ func BuildConfigurationSpecPriceFingerprint(localCfg *LocalConfiguration) (strin
|
||||
WarehousePricelistID: localCfg.WarehousePricelistID,
|
||||
CompetitorPricelistID: localCfg.CompetitorPricelistID,
|
||||
DisablePriceRefresh: localCfg.DisablePriceRefresh,
|
||||
OnlyInStock: localCfg.OnlyInStock,
|
||||
RentalItems: rentalItems,
|
||||
RentalUpliftPercent: localCfg.RentalUpliftPercent,
|
||||
VendorSpec: localCfg.VendorSpec,
|
||||
|
||||
@@ -31,6 +31,40 @@ func (c *ConfigItems) Scan(value interface{}) error {
|
||||
return json.Unmarshal(bytes, c)
|
||||
}
|
||||
|
||||
// FeatureFlags lists the data features a configuration uses (see internal/configfeatures).
|
||||
// Stored as a JSON array; an empty list is stored as NULL.
|
||||
type FeatureFlags []string
|
||||
|
||||
func (f FeatureFlags) Value() (driver.Value, error) {
|
||||
if len(f) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
data, err := json.Marshal([]string(f))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
func (f *FeatureFlags) Scan(value interface{}) error {
|
||||
*f = nil
|
||||
var data []byte
|
||||
switch v := value.(type) {
|
||||
case nil:
|
||||
return nil
|
||||
case []byte:
|
||||
data = v
|
||||
case string:
|
||||
data = []byte(v)
|
||||
default:
|
||||
return errors.New("type assertion failed for FeatureFlags")
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(data, f)
|
||||
}
|
||||
|
||||
func (c ConfigItems) Total() float64 {
|
||||
var total float64
|
||||
for _, item := range c {
|
||||
@@ -126,38 +160,38 @@ func (v *VendorSpec) Scan(value interface{}) error {
|
||||
}
|
||||
|
||||
type Configuration struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"size:36;uniqueIndex;not null" json:"uuid"`
|
||||
UserID *uint `json:"user_id,omitempty"` // Legacy field, no longer required for ownership
|
||||
OwnerUsername string `gorm:"size:100;not null;default:'';index" json:"owner_username"`
|
||||
ProjectUUID *string `gorm:"size:36;index" json:"project_uuid,omitempty"`
|
||||
AppVersion string `gorm:"size:64" json:"app_version,omitempty"`
|
||||
Name string `gorm:"size:200;not null" json:"name"`
|
||||
Items ConfigItems `gorm:"type:json;not null" json:"items"`
|
||||
TotalPrice *float64 `gorm:"type:decimal(12,2)" json:"total_price"`
|
||||
CustomPrice *float64 `gorm:"type:decimal(12,2)" json:"custom_price"`
|
||||
Notes string `gorm:"type:text" json:"notes"`
|
||||
IsTemplate bool `gorm:"default:false" json:"is_template"`
|
||||
ServerCount int `gorm:"default:1" json:"server_count"`
|
||||
ServerModel string `gorm:"size:100" json:"server_model,omitempty"`
|
||||
SupportCode string `gorm:"size:20" json:"support_code,omitempty"`
|
||||
Article string `gorm:"size:80" json:"article,omitempty"`
|
||||
PricelistID *uint `gorm:"index" json:"pricelist_id,omitempty"`
|
||||
WarehousePricelistID *uint `gorm:"index" json:"warehouse_pricelist_id,omitempty"`
|
||||
CompetitorPricelistID *uint `gorm:"index" json:"competitor_pricelist_id,omitempty"`
|
||||
VendorSpec VendorSpec `gorm:"type:json" json:"vendor_spec,omitempty"`
|
||||
ConfigType string `gorm:"size:20;default:server" json:"config_type"` // "server" | "storage"
|
||||
DisablePriceRefresh bool `gorm:"default:false" json:"disable_price_refresh"`
|
||||
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"size:36;uniqueIndex;not null" json:"uuid"`
|
||||
UserID *uint `json:"user_id,omitempty"` // Legacy field, no longer required for ownership
|
||||
OwnerUsername string `gorm:"size:100;not null;default:'';index" json:"owner_username"`
|
||||
ProjectUUID *string `gorm:"size:36;index" json:"project_uuid,omitempty"`
|
||||
AppVersion string `gorm:"size:64" json:"app_version,omitempty"`
|
||||
Name string `gorm:"size:200;not null" json:"name"`
|
||||
Items ConfigItems `gorm:"type:json;not null" json:"items"`
|
||||
TotalPrice *float64 `gorm:"type:decimal(12,2)" json:"total_price"`
|
||||
CustomPrice *float64 `gorm:"type:decimal(12,2)" json:"custom_price"`
|
||||
Notes string `gorm:"type:text" json:"notes"`
|
||||
FeatureFlags FeatureFlags `gorm:"type:json" json:"feature_flags,omitempty"`
|
||||
UnsupportedFeatures []string `gorm:"-" json:"unsupported_features,omitempty"` // flags this build doesn't know; computed on read
|
||||
IsTemplate bool `gorm:"default:false" json:"is_template"`
|
||||
ServerCount int `gorm:"default:1" json:"server_count"`
|
||||
ServerModel string `gorm:"size:100" json:"server_model,omitempty"`
|
||||
SupportCode string `gorm:"size:20" json:"support_code,omitempty"`
|
||||
Article string `gorm:"size:80" json:"article,omitempty"`
|
||||
PricelistID *uint `gorm:"index" json:"pricelist_id,omitempty"`
|
||||
WarehousePricelistID *uint `gorm:"index" json:"warehouse_pricelist_id,omitempty"`
|
||||
CompetitorPricelistID *uint `gorm:"index" json:"competitor_pricelist_id,omitempty"`
|
||||
VendorSpec VendorSpec `gorm:"type:json" json:"vendor_spec,omitempty"`
|
||||
ConfigType string `gorm:"size:20;default:server" json:"config_type"` // "server" | "storage"
|
||||
DisablePriceRefresh bool `gorm:"default:false" json:"disable_price_refresh"`
|
||||
RentalItems RentalItemConditions `gorm:"type:json" json:"rental_items,omitempty"`
|
||||
RentalUpliftPercent float64 `gorm:"type:decimal(8,2);default:0" json:"rental_uplift_percent"`
|
||||
Line int `gorm:"column:line_no;index" json:"line"`
|
||||
PriceUpdatedAt *time.Time `gorm:"type:timestamp" json:"price_updated_at,omitempty"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
CurrentVersionNo int `gorm:"-" json:"current_version_no,omitempty"`
|
||||
RentalUpliftPercent float64 `gorm:"type:decimal(8,2);default:0" json:"rental_uplift_percent"`
|
||||
Line int `gorm:"column:line_no;index" json:"line"`
|
||||
PriceUpdatedAt *time.Time `gorm:"type:timestamp" json:"price_updated_at,omitempty"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
CurrentVersionNo int `gorm:"-" json:"current_version_no,omitempty"`
|
||||
}
|
||||
|
||||
func (Configuration) TableName() string {
|
||||
return "qt_configurations"
|
||||
}
|
||||
|
||||
+14
-12
@@ -3,18 +3,20 @@ package models
|
||||
import "time"
|
||||
|
||||
type Project struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"size:36;uniqueIndex;not null" json:"uuid"`
|
||||
OwnerUsername string `gorm:"size:100;not null;index" json:"owner_username"`
|
||||
Code string `gorm:"size:100;not null;index:idx_qt_projects_code_variant,priority:1" json:"code"`
|
||||
Variant string `gorm:"size:100;not null;default:'';index:idx_qt_projects_code_variant,priority:2" json:"variant"`
|
||||
Name *string `gorm:"size:200" json:"name,omitempty"`
|
||||
TrackerURL string `gorm:"size:500" json:"tracker_url"`
|
||||
IsActive bool `gorm:"default:true;index" json:"is_active"`
|
||||
IsSystem bool `gorm:"default:false;index" json:"is_system"`
|
||||
RentalEnabled bool `gorm:"default:false" json:"rental_enabled"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"size:36;uniqueIndex;not null" json:"uuid"`
|
||||
OwnerUsername string `gorm:"size:100;not null;index" json:"owner_username"`
|
||||
Code string `gorm:"size:100;not null;index:idx_qt_projects_code_variant,priority:1" json:"code"`
|
||||
Variant string `gorm:"size:100;not null;default:'';index:idx_qt_projects_code_variant,priority:2" json:"variant"`
|
||||
Name *string `gorm:"size:200" json:"name,omitempty"`
|
||||
TrackerURL string `gorm:"size:500" json:"tracker_url"`
|
||||
IsActive bool `gorm:"default:true;index" json:"is_active"`
|
||||
IsSystem bool `gorm:"default:false;index" json:"is_system"`
|
||||
RentalEnabled bool `gorm:"default:false" json:"rental_enabled"`
|
||||
ShowStockPrices bool `gorm:"default:false" json:"show_stock_prices"`
|
||||
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (Project) TableName() string {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
@@ -16,13 +18,9 @@ func NewConfigurationRepository(db *gorm.DB) *ConfigurationRepository {
|
||||
}
|
||||
|
||||
func (r *ConfigurationRepository) Create(config *models.Configuration) error {
|
||||
if err := r.db.Create(config).Error; err != nil {
|
||||
if isUnknownLineNoColumnError(err) {
|
||||
return r.db.Omit("line_no").Create(config).Error
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
return withOptionalColumns(func(omit []string) error {
|
||||
return r.db.Omit(omit...).Create(config).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *ConfigurationRepository) GetByID(id uint) (*models.Configuration, error) {
|
||||
@@ -44,21 +42,40 @@ func (r *ConfigurationRepository) GetByUUID(uuid string) (*models.Configuration,
|
||||
}
|
||||
|
||||
func (r *ConfigurationRepository) Update(config *models.Configuration) error {
|
||||
if err := r.db.Save(config).Error; err != nil {
|
||||
if isUnknownLineNoColumnError(err) {
|
||||
return r.db.Omit("line_no").Save(config).Error
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
return withOptionalColumns(func(omit []string) error {
|
||||
return r.db.Omit(omit...).Save(config).Error
|
||||
})
|
||||
}
|
||||
|
||||
func isUnknownLineNoColumnError(err error) bool {
|
||||
// optionalConfigColumns are qt_configurations columns added by server migrations that a
|
||||
// not-yet-migrated server may lack (line_no: 028, feature_flags: 034). A write that fails
|
||||
// on one of them is retried without it, so clients keep syncing until the migration runs.
|
||||
var optionalConfigColumns = []string{"line_no", "feature_flags"}
|
||||
|
||||
func withOptionalColumns(write func(omit []string) error) error {
|
||||
var omit []string
|
||||
for {
|
||||
err := write(omit)
|
||||
col := unknownOptionalColumn(err)
|
||||
if col == "" || slices.Contains(omit, col) {
|
||||
return err
|
||||
}
|
||||
slog.Warn("qt_configurations column missing on server — writing without it; run server migrations", "column", col)
|
||||
omit = append(omit, col)
|
||||
}
|
||||
}
|
||||
|
||||
func unknownOptionalColumn(err error) string {
|
||||
if err == nil {
|
||||
return false
|
||||
return ""
|
||||
}
|
||||
msg := strings.ToLower(err.Error())
|
||||
return strings.Contains(msg, "unknown column 'line_no'") || strings.Contains(msg, "no column named line_no")
|
||||
for _, col := range optionalConfigColumns {
|
||||
if strings.Contains(msg, "unknown column '"+col+"'") || strings.Contains(msg, "no column named "+col) {
|
||||
return col
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (r *ConfigurationRepository) Delete(id uint) error {
|
||||
|
||||
@@ -39,6 +39,8 @@ func (r *ProjectRepository) UpsertByUUID(project *models.Project) error {
|
||||
"is_active",
|
||||
"is_system",
|
||||
"rental_enabled",
|
||||
"show_stock_prices",
|
||||
"only_in_stock",
|
||||
"updated_at",
|
||||
}),
|
||||
}).Create(project).Error; err != nil {
|
||||
|
||||
@@ -34,12 +34,13 @@ type CreateConfigRequest struct {
|
||||
CompetitorPricelistID *uint `json:"competitor_pricelist_id,omitempty"`
|
||||
ConfigType string `json:"config_type,omitempty"` // "server" | "storage"
|
||||
DisablePriceRefresh bool `json:"disable_price_refresh"`
|
||||
OnlyInStock bool `json:"only_in_stock"`
|
||||
}
|
||||
|
||||
type ArticlePreviewRequest struct {
|
||||
Items models.ConfigItems `json:"items"`
|
||||
ServerModel string `json:"server_model"`
|
||||
SupportCode string `json:"support_code,omitempty"`
|
||||
PricelistID *uint `json:"pricelist_id,omitempty"`
|
||||
// PricelistID is accepted for backward compatibility but ignored: article
|
||||
// categories come from the component universe (world ∪ estimate), not one pricelist.
|
||||
PricelistID *uint `json:"pricelist_id,omitempty"`
|
||||
}
|
||||
+132
-21
@@ -3,6 +3,7 @@ package services
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
@@ -58,9 +59,16 @@ type ProjectPricingExportOptions struct {
|
||||
IncludeEstimate bool `json:"include_estimate"`
|
||||
IncludeStock bool `json:"include_stock"`
|
||||
IncludeCompetitor bool `json:"include_competitor"`
|
||||
Basis string `json:"basis"` // "fob" or "ddp"; empty defaults to "fob"
|
||||
SaleMarkup float64 `json:"sale_markup"` // DDP uplift applied to Estimate only; 0 defaults to 1.3
|
||||
ManualPrice *float64 `json:"manual_price"` // user-defined total price; distributed proportionally across rows
|
||||
Basis string `json:"basis"` // "fob" or "ddp"; empty defaults to "fob"
|
||||
SaleMarkup float64 `json:"sale_markup"` // DDP uplift applied to Estimate only; 0 defaults to 1.3
|
||||
ManualPrice *float64 `json:"manual_price"` // user-defined total price; distributed proportionally across rows
|
||||
|
||||
// MinimalSaleColumns/SaleRowMarkups back the Sale table's own per-row "Накидка"
|
||||
// feature (index.html renderPricingTab/_saleRowPrice). Only ever set by
|
||||
// ExportConfigPricingCSV when the request explicitly asks for it — the Buy export
|
||||
// and project-level bulk export never set these, so their output is unaffected.
|
||||
MinimalSaleColumns bool `json:"minimal_sale_columns"`
|
||||
SaleRowMarkups map[string]float64 `json:"sale_row_markups"` // "<vendorPN>::<lot>" -> markup percent
|
||||
}
|
||||
|
||||
// defaultSaleMarkup mirrors PricingMarkup.DEFAULT_SALE_UPLIFT in web/templates/index.html.
|
||||
@@ -68,13 +76,41 @@ type ProjectPricingExportOptions struct {
|
||||
// other API callers that omit sale_markup.
|
||||
const defaultSaleMarkup = 1.3
|
||||
|
||||
func (o ProjectPricingExportOptions) saleMarkupFactor() float64 {
|
||||
// effectiveSaleMarkupFactor resolves the DDP estimate uplift for one configuration.
|
||||
// An explicit opts.SaleMarkup (sent by the single-config pricing tab, which knows the
|
||||
// live-edited value) always wins. Otherwise each configuration's own saved uplift
|
||||
// (persisted in Notes by the "Ценообразование" tab, see index.html buildPricingState/
|
||||
// restorePricingStateFromNotes) is used, so bulk project export matches what exporting
|
||||
// that same configuration individually would produce — one pipeline, not a single
|
||||
// project-wide constant.
|
||||
func (o ProjectPricingExportOptions) effectiveSaleMarkupFactor(cfg *models.Configuration) float64 {
|
||||
if o.SaleMarkup > 0 {
|
||||
return o.SaleMarkup
|
||||
}
|
||||
if v := configSavedSaleUplift(cfg); v > 0 {
|
||||
return v
|
||||
}
|
||||
return defaultSaleMarkup
|
||||
}
|
||||
|
||||
// configSavedSaleUplift reads the per-configuration DDP estimate uplift persisted by the
|
||||
// pricing tab. Notes stores {"pricing_ui":{"sale_uplift":...}} as JSON — see
|
||||
// serializeConfigNotes/restorePricingStateFromNotes in index.html.
|
||||
func configSavedSaleUplift(cfg *models.Configuration) float64 {
|
||||
if cfg == nil || strings.TrimSpace(cfg.Notes) == "" {
|
||||
return 0
|
||||
}
|
||||
var parsed struct {
|
||||
PricingUI struct {
|
||||
SaleUplift float64 `json:"sale_uplift"`
|
||||
} `json:"pricing_ui"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(cfg.Notes), &parsed); err != nil {
|
||||
return 0
|
||||
}
|
||||
return parsed.PricingUI.SaleUplift
|
||||
}
|
||||
|
||||
func (o ProjectPricingExportOptions) isDDP() bool {
|
||||
return strings.EqualFold(strings.TrimSpace(o.Basis), "ddp")
|
||||
}
|
||||
@@ -265,10 +301,14 @@ func (s *ExportService) ToPricingCSV(w io.Writer, data *ProjectPricingExportData
|
||||
return fmt.Errorf("failed to write pricing header: %w", err)
|
||||
}
|
||||
|
||||
writeRows := opts.IncludeLOT || opts.IncludeBOM
|
||||
writeRows := opts.IncludeLOT || opts.IncludeBOM || opts.MinimalSaleColumns
|
||||
for _, cfg := range data.Configs {
|
||||
if err := csvWriter.Write(pricingConfigSummaryRow(cfg, opts)); err != nil {
|
||||
return fmt.Errorf("failed to write config summary row: %w", err)
|
||||
// Minimal mode (single-config Sale export) skips the per-config summary line —
|
||||
// it's just LOT/Описание/Кол-во/Цена item rows, see pricingCSVHeaders.
|
||||
if !opts.MinimalSaleColumns {
|
||||
if err := csvWriter.Write(pricingConfigSummaryRow(cfg, opts)); err != nil {
|
||||
return fmt.Errorf("failed to write config summary row: %w", err)
|
||||
}
|
||||
}
|
||||
if writeRows {
|
||||
for _, row := range cfg.Rows {
|
||||
@@ -456,12 +496,7 @@ func (s *ExportService) buildPricingExportBlock(cfg *models.Configuration, opts
|
||||
CompetitorWorld: priceMap[lot].CompetitorWorld,
|
||||
})
|
||||
}
|
||||
if opts.isDDP() {
|
||||
applyDDPMarkup(block.Rows, opts.saleMarkupFactor())
|
||||
}
|
||||
if opts.ManualPrice != nil && *opts.ManualPrice > 0 {
|
||||
distributeManualPrice(block.Rows, *opts.ManualPrice)
|
||||
}
|
||||
applySalePricing(block.Rows, cfg, opts)
|
||||
return block, nil
|
||||
}
|
||||
|
||||
@@ -493,16 +528,29 @@ func (s *ExportService) buildPricingExportBlock(cfg *models.Configuration, opts
|
||||
})
|
||||
}
|
||||
|
||||
if opts.isDDP() {
|
||||
applyDDPMarkup(block.Rows, opts.saleMarkupFactor())
|
||||
}
|
||||
if opts.ManualPrice != nil && *opts.ManualPrice > 0 {
|
||||
distributeManualPrice(block.Rows, *opts.ManualPrice)
|
||||
}
|
||||
applySalePricing(block.Rows, cfg, opts)
|
||||
|
||||
return block, nil
|
||||
}
|
||||
|
||||
// applySalePricing applies the DDP estimate uplift/manual-price/markup pipeline to a
|
||||
// pricing export block. MinimalSaleColumns (only ever set by the single-config Sale
|
||||
// export button) switches to applySaleRowPricing, which additionally folds in each
|
||||
// row's own "Накидка" percent; every other caller (Buy export, project bulk export)
|
||||
// keeps the original applyDDPMarkup + distributeManualPrice behavior unchanged.
|
||||
func applySalePricing(rows []ProjectPricingExportRow, cfg *models.Configuration, opts ProjectPricingExportOptions) {
|
||||
if opts.MinimalSaleColumns {
|
||||
applySaleRowPricing(rows, opts.effectiveSaleMarkupFactor(cfg), opts.ManualPrice, opts.SaleRowMarkups)
|
||||
return
|
||||
}
|
||||
if opts.isDDP() {
|
||||
applyDDPMarkup(rows, opts.effectiveSaleMarkupFactor(cfg))
|
||||
}
|
||||
if opts.ManualPrice != nil && *opts.ManualPrice > 0 {
|
||||
distributeManualPrice(rows, *opts.ManualPrice)
|
||||
}
|
||||
}
|
||||
|
||||
// sortConfigItemsByCategoryMap returns a copy of items sorted by category display order.
|
||||
// categories maps lot_name → category code; catOrder maps category code → display order.
|
||||
func sortConfigItemsByCategoryMap(items models.ConfigItems, catOrder map[string]int, categories map[string]string) models.ConfigItems {
|
||||
@@ -521,7 +569,8 @@ func sortConfigItemsByCategoryMap(items models.ConfigItems, catOrder map[string]
|
||||
|
||||
// stockCompetitorMarkupFactor is the fixed DDP multiplier applied to Stock and
|
||||
// Competitor columns, independent of the user-configurable estimate uplift.
|
||||
// Mirrors PricingMarkup.STOCK_COMPETITOR_FIXED in web/templates/index.html.
|
||||
// Only used by the non-minimal (full-column) DDP export path — the Sale table itself
|
||||
// no longer displays/exports Stock/Competitor, see applySaleRowPricing.
|
||||
const stockCompetitorMarkupFactor = 1.3
|
||||
|
||||
func applyDDPMarkup(rows []ProjectPricingExportRow, estimateFactor float64) {
|
||||
@@ -532,6 +581,58 @@ func applyDDPMarkup(rows []ProjectPricingExportRow, estimateFactor float64) {
|
||||
}
|
||||
}
|
||||
|
||||
// saleRowKey mirrors _saleRowKey in web/templates/index.html: a LOT can appear more
|
||||
// than once across different vendor-PN BOM groups, so lot_name alone isn't a safe key.
|
||||
// "—" is the row-builder's own placeholder for "no vendor PN" (see the VendorPN: "—"
|
||||
// literals in buildPricingExportBlock), matching the frontend's empty-string case.
|
||||
func saleRowKey(vendorPN, lot string) string {
|
||||
v := strings.ToUpper(strings.TrimSpace(vendorPN))
|
||||
if v == "" || v == "—" {
|
||||
v = "NONE"
|
||||
}
|
||||
return v + "::" + strings.ToUpper(strings.TrimSpace(lot))
|
||||
}
|
||||
|
||||
// applySaleRowPricing implements the per-row "Накидка" pricing pipeline for the
|
||||
// minimal Sale CSV export: each row's base (its raw Estimate, or a proportional share
|
||||
// of manualPrice when set — same last-row-absorbs-remainder distribution as
|
||||
// distributeManualPrice, but overwriting the base instead of a side field) is
|
||||
// multiplied by (saleUplift + that row's own markup percent / 100). Mirrors
|
||||
// _saleRowPrice/recomputeSalePrices in web/templates/index.html exactly.
|
||||
func applySaleRowPricing(rows []ProjectPricingExportRow, saleUplift float64, manualPrice *float64, rowMarkups map[string]float64) {
|
||||
rawTotal := 0.0
|
||||
lastPricedIdx := -1
|
||||
for i, row := range rows {
|
||||
if row.Estimate != nil && *row.Estimate > 0 {
|
||||
rawTotal += *row.Estimate
|
||||
lastPricedIdx = i
|
||||
}
|
||||
}
|
||||
useManual := manualPrice != nil && *manualPrice > 0 && rawTotal > 0
|
||||
|
||||
assigned := 0.0
|
||||
for i := range rows {
|
||||
if rows[i].Estimate == nil || *rows[i].Estimate <= 0 {
|
||||
continue
|
||||
}
|
||||
base := *rows[i].Estimate
|
||||
if useManual {
|
||||
if i == lastPricedIdx {
|
||||
base = math.Round((*manualPrice-assigned)*100) / 100
|
||||
} else {
|
||||
share := (*rows[i].Estimate / rawTotal) * (*manualPrice)
|
||||
base = math.Round(share*100) / 100
|
||||
assigned += base
|
||||
}
|
||||
}
|
||||
key := saleRowKey(rows[i].VendorPN, rows[i].LotDisplay)
|
||||
// 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
|
||||
rows[i].Estimate = floatPtr(price)
|
||||
}
|
||||
}
|
||||
|
||||
func scaleFloatPtr(v *float64, factor float64) *float64 {
|
||||
if v == nil {
|
||||
return nil
|
||||
@@ -832,6 +933,9 @@ func estimateOnlyTotal(estimatePrice *float64, fallbackUnitPrice float64, quanti
|
||||
}
|
||||
|
||||
func pricingCSVHeaders(opts ProjectPricingExportOptions) []string {
|
||||
if opts.MinimalSaleColumns {
|
||||
return []string{"LOT", "Описание", "Кол-во", "Цена"}
|
||||
}
|
||||
headers := make([]string, 0, 9)
|
||||
headers = append(headers, "Line Item")
|
||||
if opts.IncludeLOT {
|
||||
@@ -858,6 +962,14 @@ func pricingCSVHeaders(opts ProjectPricingExportOptions) []string {
|
||||
}
|
||||
|
||||
func pricingCSVRow(row ProjectPricingExportRow, opts ProjectPricingExportOptions) []string {
|
||||
if opts.MinimalSaleColumns {
|
||||
return []string{
|
||||
emptyDash(row.LotDisplay),
|
||||
emptyDash(row.Description),
|
||||
fmt.Sprintf("%d", exportPositiveInt(row.Quantity, 1)),
|
||||
formatMoneyValue(row.Estimate),
|
||||
}
|
||||
}
|
||||
record := make([]string, 0, 9)
|
||||
record = append(record, "")
|
||||
if opts.IncludeLOT {
|
||||
@@ -931,7 +1043,6 @@ func pricingConfigSummaryRow(cfg ProjectPricingExportConfig, opts ProjectPricing
|
||||
return record
|
||||
}
|
||||
|
||||
|
||||
func formatMoneyValue(value *float64) string {
|
||||
if value == nil {
|
||||
return "—"
|
||||
|
||||
@@ -561,3 +561,22 @@ type failingWriter struct{}
|
||||
func (fw *failingWriter) Write(p []byte) (int, error) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/appmeta"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/article"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/services/sync"
|
||||
@@ -70,13 +71,18 @@ func (s *LocalConfigurationService) Create(ownerUsername string, req *CreateConf
|
||||
|
||||
if strings.TrimSpace(req.ServerModel) != "" {
|
||||
articleResult, articleErr := article.Build(s.localDB, req.Items, article.BuildOptions{
|
||||
ServerModel: req.ServerModel,
|
||||
ServerPricelist: pricelistID,
|
||||
ServerModel: req.ServerModel,
|
||||
})
|
||||
if articleErr != nil {
|
||||
return nil, articleErr
|
||||
}
|
||||
req.Article = articleResult.Article
|
||||
if len(articleResult.Warnings) > 0 {
|
||||
slog.Warn("article generation degraded",
|
||||
"server_model", req.ServerModel,
|
||||
"article", articleResult.Article,
|
||||
"warnings", articleResult.Warnings)
|
||||
}
|
||||
}
|
||||
|
||||
total := req.Items.Total()
|
||||
@@ -103,7 +109,6 @@ func (s *LocalConfigurationService) Create(ownerUsername string, req *CreateConf
|
||||
CompetitorPricelistID: req.CompetitorPricelistID,
|
||||
ConfigType: req.ConfigType,
|
||||
DisablePriceRefresh: req.DisablePriceRefresh,
|
||||
OnlyInStock: req.OnlyInStock,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
if cfg.ConfigType == "" {
|
||||
@@ -167,13 +172,18 @@ func (s *LocalConfigurationService) Update(uuid string, ownerUsername string, re
|
||||
|
||||
if strings.TrimSpace(req.ServerModel) != "" {
|
||||
articleResult, articleErr := article.Build(s.localDB, req.Items, article.BuildOptions{
|
||||
ServerModel: req.ServerModel,
|
||||
ServerPricelist: pricelistID,
|
||||
ServerModel: req.ServerModel,
|
||||
})
|
||||
if articleErr != nil {
|
||||
return nil, articleErr
|
||||
}
|
||||
req.Article = articleResult.Article
|
||||
if len(articleResult.Warnings) > 0 {
|
||||
slog.Warn("article generation degraded",
|
||||
"server_model", req.ServerModel,
|
||||
"article", articleResult.Article,
|
||||
"warnings", articleResult.Warnings)
|
||||
}
|
||||
}
|
||||
|
||||
total := req.Items.Total()
|
||||
@@ -204,7 +214,6 @@ func (s *LocalConfigurationService) Update(uuid string, ownerUsername string, re
|
||||
localCfg.WarehousePricelistID = req.WarehousePricelistID
|
||||
localCfg.CompetitorPricelistID = req.CompetitorPricelistID
|
||||
localCfg.DisablePriceRefresh = req.DisablePriceRefresh
|
||||
localCfg.OnlyInStock = req.OnlyInStock
|
||||
localCfg.UpdatedAt = time.Now()
|
||||
localCfg.SyncStatus = "pending"
|
||||
|
||||
@@ -218,13 +227,10 @@ func (s *LocalConfigurationService) Update(uuid string, ownerUsername string, re
|
||||
|
||||
// BuildArticlePreview generates server article based on current items and server_model/support_code.
|
||||
func (s *LocalConfigurationService) BuildArticlePreview(req *ArticlePreviewRequest) (article.BuildResult, error) {
|
||||
pricelistID, err := s.resolvePricelistID(req.PricelistID)
|
||||
if err != nil {
|
||||
return article.BuildResult{}, err
|
||||
}
|
||||
// Categories for the article come from the component universe (world ∪ estimate),
|
||||
// not from a specific pricelist, so req.PricelistID is no longer needed here.
|
||||
return article.Build(s.localDB, req.Items, article.BuildOptions{
|
||||
ServerModel: req.ServerModel,
|
||||
ServerPricelist: pricelistID,
|
||||
ServerModel: req.ServerModel,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -319,6 +325,7 @@ func (s *LocalConfigurationService) CloneToProject(configUUID string, ownerUsern
|
||||
TotalPrice: &total,
|
||||
CustomPrice: original.CustomPrice,
|
||||
Notes: original.Notes,
|
||||
FeatureFlags: original.FeatureFlags,
|
||||
IsTemplate: false,
|
||||
ServerCount: original.ServerCount,
|
||||
ServerModel: original.ServerModel,
|
||||
@@ -328,7 +335,6 @@ func (s *LocalConfigurationService) CloneToProject(configUUID string, ownerUsern
|
||||
WarehousePricelistID: original.WarehousePricelistID,
|
||||
CompetitorPricelistID: original.CompetitorPricelistID,
|
||||
DisablePriceRefresh: original.DisablePriceRefresh,
|
||||
OnlyInStock: original.OnlyInStock,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
@@ -530,13 +536,18 @@ func (s *LocalConfigurationService) UpdateNoAuth(uuid string, req *CreateConfigR
|
||||
|
||||
if strings.TrimSpace(req.ServerModel) != "" {
|
||||
articleResult, articleErr := article.Build(s.localDB, req.Items, article.BuildOptions{
|
||||
ServerModel: req.ServerModel,
|
||||
ServerPricelist: pricelistID,
|
||||
ServerModel: req.ServerModel,
|
||||
})
|
||||
if articleErr != nil {
|
||||
return nil, articleErr
|
||||
}
|
||||
req.Article = articleResult.Article
|
||||
if len(articleResult.Warnings) > 0 {
|
||||
slog.Warn("article generation degraded",
|
||||
"server_model", req.ServerModel,
|
||||
"article", articleResult.Article,
|
||||
"warnings", articleResult.Warnings)
|
||||
}
|
||||
}
|
||||
|
||||
total := req.Items.Total()
|
||||
@@ -566,7 +577,6 @@ func (s *LocalConfigurationService) UpdateNoAuth(uuid string, req *CreateConfigR
|
||||
localCfg.WarehousePricelistID = req.WarehousePricelistID
|
||||
localCfg.CompetitorPricelistID = req.CompetitorPricelistID
|
||||
localCfg.DisablePriceRefresh = req.DisablePriceRefresh
|
||||
localCfg.OnlyInStock = req.OnlyInStock
|
||||
localCfg.UpdatedAt = time.Now()
|
||||
localCfg.SyncStatus = "pending"
|
||||
|
||||
@@ -676,6 +686,7 @@ func (s *LocalConfigurationService) CloneNoAuthToProjectFromVersion(configUUID s
|
||||
TotalPrice: &total,
|
||||
CustomPrice: original.CustomPrice,
|
||||
Notes: original.Notes,
|
||||
FeatureFlags: original.FeatureFlags,
|
||||
IsTemplate: false,
|
||||
ServerCount: original.ServerCount,
|
||||
ServerModel: original.ServerModel,
|
||||
@@ -685,7 +696,6 @@ func (s *LocalConfigurationService) CloneNoAuthToProjectFromVersion(configUUID s
|
||||
WarehousePricelistID: original.WarehousePricelistID,
|
||||
CompetitorPricelistID: original.CompetitorPricelistID,
|
||||
DisablePriceRefresh: original.DisablePriceRefresh,
|
||||
OnlyInStock: original.OnlyInStock,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
@@ -921,6 +931,9 @@ func (s *LocalConfigurationService) UpdateServerCount(configUUID string, serverC
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
|
||||
if err := applyFeatureFlags(localCfg.FeatureFlags, localCfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
localCfg.ServerCount = serverCount
|
||||
total := localCfg.Items.Total()
|
||||
if serverCount > 1 {
|
||||
@@ -1165,6 +1178,9 @@ func (s *LocalConfigurationService) createWithVersion(localCfg *localdb.LocalCon
|
||||
}
|
||||
|
||||
func (s *LocalConfigurationService) createWithVersionTx(tx *gorm.DB, localCfg *localdb.LocalConfiguration, createdBy string) error {
|
||||
if err := applyFeatureFlags(localCfg.FeatureFlags, localCfg); err != nil {
|
||||
return err
|
||||
}
|
||||
if localCfg.IsActive {
|
||||
if err := s.ensureConfigurationLineTx(tx, localCfg); err != nil {
|
||||
return err
|
||||
@@ -1210,6 +1226,9 @@ func (s *LocalConfigurationService) saveWithVersionAndPending(localCfg *localdb.
|
||||
}
|
||||
return fmt.Errorf("lock configuration row: %w", err)
|
||||
}
|
||||
if err := applyFeatureFlags(locked.FeatureFlags, localCfg); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if operation == "update" {
|
||||
currentVersion, err := s.loadCurrentVersionTx(tx, &locked)
|
||||
@@ -1290,6 +1309,7 @@ func hasNonRevisionConfigurationChanges(current *localdb.LocalConfiguration, nex
|
||||
}
|
||||
if current.Name != next.Name ||
|
||||
current.Notes != next.Notes ||
|
||||
strings.Join(current.FeatureFlags, ",") != strings.Join(next.FeatureFlags, ",") ||
|
||||
current.IsTemplate != next.IsTemplate ||
|
||||
current.ServerModel != next.ServerModel ||
|
||||
current.SupportCode != next.SupportCode ||
|
||||
@@ -1633,12 +1653,17 @@ func (s *LocalConfigurationService) rollbackToVersion(configurationUUID string,
|
||||
return fmt.Errorf("decode target rollback snapshot: %w", err)
|
||||
}
|
||||
|
||||
if err := configfeatures.Check(append(append([]string{}, current.FeatureFlags...), rollbackData.FeatureFlags...)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Keep stable identity/sync linkage; restore editable config content from target snapshot.
|
||||
current.Name = rollbackData.Name
|
||||
current.Items = rollbackData.Items
|
||||
current.TotalPrice = rollbackData.TotalPrice
|
||||
current.CustomPrice = rollbackData.CustomPrice
|
||||
current.Notes = rollbackData.Notes
|
||||
current.FeatureFlags = configfeatures.Detect(rollbackData.Notes)
|
||||
current.IsTemplate = rollbackData.IsTemplate
|
||||
current.ServerCount = rollbackData.ServerCount
|
||||
current.ServerModel = rollbackData.ServerModel
|
||||
@@ -1648,7 +1673,6 @@ func (s *LocalConfigurationService) rollbackToVersion(configurationUUID string,
|
||||
current.WarehousePricelistID = rollbackData.WarehousePricelistID
|
||||
current.CompetitorPricelistID = rollbackData.CompetitorPricelistID
|
||||
current.DisablePriceRefresh = rollbackData.DisablePriceRefresh
|
||||
current.OnlyInStock = rollbackData.OnlyInStock
|
||||
current.VendorSpec = rollbackData.VendorSpec
|
||||
if rollbackData.Line > 0 {
|
||||
current.Line = rollbackData.Line
|
||||
@@ -1853,3 +1877,14 @@ func (s *LocalConfigurationService) resolvePricelistID(pricelistID *uint) (*uint
|
||||
}
|
||||
return &latest.ServerID, nil
|
||||
}
|
||||
|
||||
// applyFeatureFlags refuses a write when the configuration as stored carries feature
|
||||
// flags this build doesn't know (it could not round-trip the data behind them), and
|
||||
// otherwise re-derives next's flags from its content.
|
||||
func applyFeatureFlags(stored models.FeatureFlags, next *localdb.LocalConfiguration) error {
|
||||
if err := configfeatures.Check(stored); err != nil {
|
||||
return err
|
||||
}
|
||||
next.FeatureFlags = configfeatures.Detect(next.Notes)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
)
|
||||
|
||||
const notesWithRowMarkup = `{"pricing_ui":{"sale_uplift":1.5,"sale_row_markups":{"NONE::CPU_A":-50}}}`
|
||||
|
||||
func TestSaveDerivesFeatureFlagsFromContent(t *testing.T) {
|
||||
service, local := newLocalConfigServiceForTest(t)
|
||||
|
||||
created, err := service.Create("tester", &CreateConfigRequest{
|
||||
Name: "cfg",
|
||||
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 1, UnitPrice: 1000}},
|
||||
Notes: notesWithRowMarkup,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
stored, _ := local.GetConfigurationByUUID(created.UUID)
|
||||
if want := (models.FeatureFlags{configfeatures.SaleRowMarkups}); !reflect.DeepEqual(stored.FeatureFlags, want) {
|
||||
t.Fatalf("flags after create = %v, want %v", stored.FeatureFlags, want)
|
||||
}
|
||||
|
||||
// Removing the markups clears the flag.
|
||||
if _, err := service.UpdateNoAuth(created.UUID, &CreateConfigRequest{
|
||||
Name: "cfg",
|
||||
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 1, UnitPrice: 1000}},
|
||||
Notes: `{"pricing_ui":{"sale_uplift":1.5}}`,
|
||||
}); err != nil {
|
||||
t.Fatalf("update: %v", err)
|
||||
}
|
||||
stored, _ = local.GetConfigurationByUUID(created.UUID)
|
||||
if len(stored.FeatureFlags) != 0 {
|
||||
t.Fatalf("flags after clearing markups = %v, want none", stored.FeatureFlags)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWritesRefusedForUnknownFeatureFlags(t *testing.T) {
|
||||
service, local := newLocalConfigServiceForTest(t)
|
||||
|
||||
created, err := service.Create("tester", &CreateConfigRequest{
|
||||
Name: "cfg",
|
||||
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 1, UnitPrice: 1000}},
|
||||
Notes: `{"pricing_ui":{},"future":{"x":1}}`,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
// Simulate a pull of a config last written by a newer client.
|
||||
if err := local.DB().Model(&localdb.LocalConfiguration{}).
|
||||
Where("uuid = ?", created.UUID).
|
||||
Update("feature_flags", models.FeatureFlags{"future_x", configfeatures.SaleRowMarkups}).Error; err != nil {
|
||||
t.Fatalf("set flags: %v", err)
|
||||
}
|
||||
|
||||
got, err := service.GetByUUIDNoAuth(created.UUID)
|
||||
if err != nil {
|
||||
t.Fatalf("get: %v", err)
|
||||
}
|
||||
if want := []string{"future_x"}; !reflect.DeepEqual(got.UnsupportedFeatures, want) {
|
||||
t.Fatalf("UnsupportedFeatures = %v, want %v", got.UnsupportedFeatures, want)
|
||||
}
|
||||
|
||||
assertRefused := func(name string, err error) {
|
||||
t.Helper()
|
||||
ue, ok := configfeatures.AsUnsupported(err)
|
||||
if !ok || !reflect.DeepEqual(ue.Flags, []string{"future_x"}) {
|
||||
t.Fatalf("%s: want UnsupportedError{future_x}, got %v", name, err)
|
||||
}
|
||||
}
|
||||
_, err = service.UpdateNoAuth(created.UUID, &CreateConfigRequest{
|
||||
Name: "cfg",
|
||||
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 2, UnitPrice: 1000}},
|
||||
})
|
||||
assertRefused("update", err)
|
||||
_, err = service.RenameNoAuth(created.UUID, "renamed")
|
||||
assertRefused("rename", err)
|
||||
_, err = service.UpdateServerCount(created.UUID, 3)
|
||||
assertRefused("server count", err)
|
||||
_, err = service.CloneNoAuthToProjectFromVersion(created.UUID, "copy", "tester", nil, 0)
|
||||
assertRefused("clone", err)
|
||||
_, err = service.RollbackToVersion(created.UUID, 1, "tester")
|
||||
assertRefused("rollback", err)
|
||||
|
||||
stored, _ := local.GetConfigurationByUUID(created.UUID)
|
||||
if stored.Name != "cfg" || stored.Items[0].Quantity != 1 || stored.ServerCount != 1 {
|
||||
t.Fatalf("refused writes must leave the row untouched, got %+v", stored)
|
||||
}
|
||||
}
|
||||
@@ -154,7 +154,6 @@ func TestUpdateNoAuthCreatesRevisionWhenPricingSettingsChanged(t *testing.T) {
|
||||
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 1, UnitPrice: 1000}},
|
||||
ServerCount: 1,
|
||||
DisablePriceRefresh: true,
|
||||
OnlyInStock: true,
|
||||
}); err != nil {
|
||||
t.Fatalf("update pricing settings: %v", err)
|
||||
}
|
||||
|
||||
@@ -17,19 +17,21 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrProjectNotFound = errors.New("project not found")
|
||||
ErrProjectForbidden = errors.New("access to project forbidden")
|
||||
ErrProjectCodeExists = errors.New("project code and variant already exist")
|
||||
ErrCannotDeleteMainVariant = errors.New("cannot delete main variant")
|
||||
ErrReservedMainVariant = errors.New("variant name 'main' is reserved")
|
||||
ErrCannotRenameMainVariant = errors.New("cannot rename main variant")
|
||||
ErrProjectCodeInvalidChars = errors.New("код опти содержит недопустимые символы (разрешены: буквы, цифры, дефис, точка, подчёркивание)")
|
||||
ErrProjectVariantInvalidChars = errors.New("имя варианта содержит недопустимые символы (разрешены: буквы, цифры, дефис, точка, подчёркивание)")
|
||||
ErrProjectNotFound = errors.New("project not found")
|
||||
ErrProjectForbidden = errors.New("access to project forbidden")
|
||||
ErrProjectCodeExists = errors.New("project code and variant already exist")
|
||||
ErrCannotDeleteMainVariant = errors.New("cannot delete main variant")
|
||||
ErrCannotRenameMainVariant = errors.New("cannot rename main variant")
|
||||
ErrProjectCodeInvalidChars = errors.New("код опти содержит недопустимые символы (разрешены: буквы, цифры, дефис, точка, подчёркивание)")
|
||||
)
|
||||
|
||||
// projectCodeRe allows only URL-path-safe characters so project codes can appear directly in URLs.
|
||||
var projectCodeRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
|
||||
|
||||
// invalidVariantCharsRe matches runs of characters not allowed in a variant name, so they
|
||||
// can be collapsed to a single separator by sanitizeProjectVariantName.
|
||||
var invalidVariantCharsRe = regexp.MustCompile(`[^A-Za-z0-9._-]+`)
|
||||
|
||||
type ProjectService struct {
|
||||
localDB *localdb.LocalDB
|
||||
}
|
||||
@@ -46,11 +48,13 @@ type CreateProjectRequest struct {
|
||||
}
|
||||
|
||||
type UpdateProjectRequest struct {
|
||||
Code *string `json:"code,omitempty"`
|
||||
Variant *string `json:"variant,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
TrackerURL *string `json:"tracker_url,omitempty"`
|
||||
RentalEnabled *bool `json:"rental_enabled,omitempty"`
|
||||
Code *string `json:"code,omitempty"`
|
||||
Variant *string `json:"variant,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
TrackerURL *string `json:"tracker_url,omitempty"`
|
||||
RentalEnabled *bool `json:"rental_enabled,omitempty"`
|
||||
ShowStockPrices *bool `json:"show_stock_prices,omitempty"`
|
||||
OnlyInStock *bool `json:"only_in_stock,omitempty"`
|
||||
}
|
||||
|
||||
type ProjectConfigurationsResult struct {
|
||||
@@ -59,7 +63,10 @@ type ProjectConfigurationsResult struct {
|
||||
Total float64 `json:"total"`
|
||||
}
|
||||
|
||||
func (s *ProjectService) Create(ownerUsername string, req *CreateProjectRequest) (*models.Project, error) {
|
||||
// Create creates a project. If req.Variant is not a valid variant name (reserved word
|
||||
// "main" or disallowed characters) it is auto-converted into a valid one instead of
|
||||
// rejecting the request; the returned warning is non-empty when that happened.
|
||||
func (s *ProjectService) Create(ownerUsername string, req *CreateProjectRequest) (*models.Project, string, error) {
|
||||
var namePtr *string
|
||||
if req.Name != nil {
|
||||
name := strings.TrimSpace(*req.Name)
|
||||
@@ -69,17 +76,14 @@ func (s *ProjectService) Create(ownerUsername string, req *CreateProjectRequest)
|
||||
}
|
||||
code := strings.TrimSpace(req.Code)
|
||||
if code == "" {
|
||||
return nil, fmt.Errorf("project code is required")
|
||||
return nil, "", fmt.Errorf("project code is required")
|
||||
}
|
||||
if !projectCodeRe.MatchString(code) {
|
||||
return nil, ErrProjectCodeInvalidChars
|
||||
}
|
||||
variant := strings.TrimSpace(req.Variant)
|
||||
if err := validateProjectVariantName(variant); err != nil {
|
||||
return nil, err
|
||||
return nil, "", ErrProjectCodeInvalidChars
|
||||
}
|
||||
variant, variantWarning := sanitizeProjectVariantName(strings.TrimSpace(req.Variant))
|
||||
if err := s.ensureUniqueProjectCodeVariant("", code, variant); err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
@@ -97,43 +101,44 @@ func (s *ProjectService) Create(ownerUsername string, req *CreateProjectRequest)
|
||||
SyncStatus: "pending",
|
||||
}
|
||||
if err := s.localDB.SaveProject(localProject); err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
if err := s.enqueueProjectPendingChange(localProject, "create"); err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
return localdb.LocalToProject(localProject), nil
|
||||
return localdb.LocalToProject(localProject), variantWarning, nil
|
||||
}
|
||||
|
||||
func (s *ProjectService) Update(projectUUID, ownerUsername string, req *UpdateProjectRequest) (*models.Project, error) {
|
||||
// Update updates a project. Like Create, an invalid req.Variant (reserved word "main" or
|
||||
// disallowed characters) is auto-converted into a valid one instead of rejecting the
|
||||
// request; the returned warning is non-empty when that happened.
|
||||
func (s *ProjectService) Update(projectUUID, ownerUsername string, req *UpdateProjectRequest) (*models.Project, string, error) {
|
||||
localProject, err := s.localDB.GetProjectByUUID(projectUUID)
|
||||
if err != nil {
|
||||
return nil, ErrProjectNotFound
|
||||
return nil, "", ErrProjectNotFound
|
||||
}
|
||||
|
||||
if req.Code != nil {
|
||||
code := strings.TrimSpace(*req.Code)
|
||||
if code == "" {
|
||||
return nil, fmt.Errorf("project code is required")
|
||||
return nil, "", fmt.Errorf("project code is required")
|
||||
}
|
||||
if !projectCodeRe.MatchString(code) {
|
||||
return nil, ErrProjectCodeInvalidChars
|
||||
return nil, "", ErrProjectCodeInvalidChars
|
||||
}
|
||||
localProject.Code = code
|
||||
}
|
||||
var variantWarning string
|
||||
if req.Variant != nil {
|
||||
newVariant := strings.TrimSpace(*req.Variant)
|
||||
// Block renaming of the main variant (empty Variant) — there must always be a main.
|
||||
if strings.TrimSpace(localProject.Variant) == "" && newVariant != "" {
|
||||
return nil, ErrCannotRenameMainVariant
|
||||
}
|
||||
localProject.Variant = newVariant
|
||||
if err := validateProjectVariantName(localProject.Variant); err != nil {
|
||||
return nil, err
|
||||
return nil, "", ErrCannotRenameMainVariant
|
||||
}
|
||||
localProject.Variant, variantWarning = sanitizeProjectVariantName(newVariant)
|
||||
}
|
||||
if err := s.ensureUniqueProjectCodeVariant(projectUUID, localProject.Code, localProject.Variant); err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
if req.Name != nil {
|
||||
@@ -152,15 +157,21 @@ func (s *ProjectService) Update(projectUUID, ownerUsername string, req *UpdatePr
|
||||
if req.RentalEnabled != nil {
|
||||
localProject.RentalEnabled = *req.RentalEnabled
|
||||
}
|
||||
if req.ShowStockPrices != nil {
|
||||
localProject.ShowStockPrices = *req.ShowStockPrices
|
||||
}
|
||||
if req.OnlyInStock != nil {
|
||||
localProject.OnlyInStock = *req.OnlyInStock
|
||||
}
|
||||
localProject.UpdatedAt = time.Now()
|
||||
localProject.SyncStatus = "pending"
|
||||
if err := s.localDB.SaveProject(localProject); err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
if err := s.enqueueProjectPendingChange(localProject, "update"); err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
return localdb.LocalToProject(localProject), nil
|
||||
return localdb.LocalToProject(localProject), variantWarning, nil
|
||||
}
|
||||
|
||||
func (s *ProjectService) ensureUniqueProjectCodeVariant(excludeUUID, code, variant string) error {
|
||||
@@ -195,14 +206,31 @@ func normalizeProjectVariant(variant string) string {
|
||||
return strings.ToLower(strings.TrimSpace(variant))
|
||||
}
|
||||
|
||||
func validateProjectVariantName(variant string) error {
|
||||
if normalizeProjectVariant(variant) == "main" {
|
||||
return ErrReservedMainVariant
|
||||
// sanitizeProjectVariantName converts an invalid variant name (the reserved word "main",
|
||||
// or a name containing characters outside [A-Za-z0-9._-]) into a valid one, returning a
|
||||
// warning describing the change. Empty input (the implicit main variant) always passes
|
||||
// through unchanged with no warning. Invalid characters are collapsed to a single "-";
|
||||
// if that empties the name, or the result collides with the reserved "main", a "-variant"
|
||||
// suffix is appended to guarantee a valid, non-reserved result.
|
||||
func sanitizeProjectVariantName(variant string) (sanitized string, warning string) {
|
||||
original := strings.TrimSpace(variant)
|
||||
if original == "" {
|
||||
return "", ""
|
||||
}
|
||||
if variant != "" && !projectCodeRe.MatchString(variant) {
|
||||
return ErrProjectVariantInvalidChars
|
||||
sanitized = original
|
||||
if !projectCodeRe.MatchString(sanitized) {
|
||||
sanitized = strings.Trim(invalidVariantCharsRe.ReplaceAllString(sanitized, "-"), "-")
|
||||
}
|
||||
return nil
|
||||
if sanitized == "" {
|
||||
sanitized = "variant"
|
||||
}
|
||||
if normalizeProjectVariant(sanitized) == "main" {
|
||||
sanitized += "-variant"
|
||||
}
|
||||
if sanitized == original {
|
||||
return sanitized, ""
|
||||
}
|
||||
return sanitized, fmt.Sprintf("имя варианта %q недопустимо — использовано %q", original, sanitized)
|
||||
}
|
||||
|
||||
func (s *ProjectService) Archive(projectUUID, ownerUsername string) error {
|
||||
|
||||
@@ -1,37 +1,47 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
)
|
||||
|
||||
func TestProjectServiceCreateRejectsReservedMainVariant(t *testing.T) {
|
||||
// TestProjectServiceCreateSanitizesReservedMainVariant verifies that naming a new
|
||||
// variant "main" no longer errors: the name is auto-converted to a valid one and a
|
||||
// warning is returned instead of the request being rejected.
|
||||
func TestProjectServiceCreateSanitizesReservedMainVariant(t *testing.T) {
|
||||
local, err := newProjectTestLocalDB(t)
|
||||
if err != nil {
|
||||
t.Fatalf("open localdb: %v", err)
|
||||
}
|
||||
service := NewProjectService(local)
|
||||
|
||||
_, err = service.Create("tester", &CreateProjectRequest{
|
||||
project, warning, err := service.Create("tester", &CreateProjectRequest{
|
||||
Code: "OPS-1",
|
||||
Variant: "main",
|
||||
})
|
||||
if !errors.Is(err, ErrReservedMainVariant) {
|
||||
t.Fatalf("expected ErrReservedMainVariant, got %v", err)
|
||||
if err != nil {
|
||||
t.Fatalf("create project: %v", err)
|
||||
}
|
||||
if warning == "" {
|
||||
t.Fatalf("expected a warning about the reserved variant name")
|
||||
}
|
||||
if project.Variant == "" || normalizeProjectVariant(project.Variant) == "main" {
|
||||
t.Fatalf("expected variant to be converted away from 'main', got %q", project.Variant)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectServiceUpdateRejectsReservedMainVariant(t *testing.T) {
|
||||
// TestProjectServiceUpdateSanitizesReservedMainVariant mirrors the create case for
|
||||
// renaming an existing (non-main) variant to "main".
|
||||
func TestProjectServiceUpdateSanitizesReservedMainVariant(t *testing.T) {
|
||||
local, err := newProjectTestLocalDB(t)
|
||||
if err != nil {
|
||||
t.Fatalf("open localdb: %v", err)
|
||||
}
|
||||
service := NewProjectService(local)
|
||||
|
||||
created, err := service.Create("tester", &CreateProjectRequest{
|
||||
created, _, err := service.Create("tester", &CreateProjectRequest{
|
||||
Code: "OPS-1",
|
||||
Variant: "Lenovo",
|
||||
})
|
||||
@@ -40,11 +50,41 @@ func TestProjectServiceUpdateRejectsReservedMainVariant(t *testing.T) {
|
||||
}
|
||||
|
||||
mainName := "main"
|
||||
_, err = service.Update(created.UUID, "tester", &UpdateProjectRequest{
|
||||
updated, warning, err := service.Update(created.UUID, "tester", &UpdateProjectRequest{
|
||||
Variant: &mainName,
|
||||
})
|
||||
if !errors.Is(err, ErrReservedMainVariant) {
|
||||
t.Fatalf("expected ErrReservedMainVariant, got %v", err)
|
||||
if err != nil {
|
||||
t.Fatalf("update project: %v", err)
|
||||
}
|
||||
if warning == "" {
|
||||
t.Fatalf("expected a warning about the reserved variant name")
|
||||
}
|
||||
if updated.Variant == "" || normalizeProjectVariant(updated.Variant) == "main" {
|
||||
t.Fatalf("expected variant to be converted away from 'main', got %q", updated.Variant)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSanitizeProjectVariantName_InvalidChars verifies disallowed characters are
|
||||
// stripped/replaced rather than rejected outright.
|
||||
func TestSanitizeProjectVariantName_InvalidChars(t *testing.T) {
|
||||
sanitized, warning := sanitizeProjectVariantName("Лендинг сервер!")
|
||||
if warning == "" {
|
||||
t.Fatalf("expected a warning for invalid characters")
|
||||
}
|
||||
if !projectCodeRe.MatchString(sanitized) {
|
||||
t.Fatalf("sanitized variant %q still fails projectCodeRe", sanitized)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSanitizeProjectVariantName_ValidPassesThrough ensures already-valid names are
|
||||
// left untouched with no warning.
|
||||
func TestSanitizeProjectVariantName_ValidPassesThrough(t *testing.T) {
|
||||
sanitized, warning := sanitizeProjectVariantName("lenovo-2u")
|
||||
if warning != "" {
|
||||
t.Fatalf("expected no warning, got %q", warning)
|
||||
}
|
||||
if sanitized != "lenovo-2u" {
|
||||
t.Fatalf("expected unchanged variant, got %q", sanitized)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/appmeta"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/db"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
@@ -218,6 +219,8 @@ func (s *Service) ImportProjectsToLocal() (*ProjectImportResult, error) {
|
||||
existing.IsActive = project.IsActive
|
||||
existing.IsSystem = project.IsSystem
|
||||
existing.RentalEnabled = project.RentalEnabled
|
||||
existing.ShowStockPrices = project.ShowStockPrices
|
||||
existing.OnlyInStock = project.OnlyInStock
|
||||
existing.CreatedAt = project.CreatedAt
|
||||
existing.UpdatedAt = project.UpdatedAt
|
||||
serverID := project.ID
|
||||
@@ -983,7 +986,10 @@ func (s *Service) PushPendingChanges() (int, error) {
|
||||
firstErr = err.Error()
|
||||
}
|
||||
failed++
|
||||
if newAttempts >= maxPendingChangeAttempts {
|
||||
// Refused over unknown feature flags: not a transient failure, and dropping it would
|
||||
// lose the local edit — keep it queued until the app is updated.
|
||||
_, unsupported := configfeatures.AsUnsupported(err)
|
||||
if newAttempts >= maxPendingChangeAttempts && !unsupported {
|
||||
slog.Error("abandoning pending change after max attempts",
|
||||
"id", change.ID, "type", change.EntityType, "op", change.Operation,
|
||||
"attempts", newAttempts, "last_error", err.Error())
|
||||
@@ -1299,6 +1305,15 @@ func (s *Service) pushConfigurationUpdate(change *localdb.PendingChange) error {
|
||||
}
|
||||
}
|
||||
|
||||
// A newer client may have written this config since our last pull, adding data this
|
||||
// build can't see (marked by a feature flag we don't know). Pushing our snapshot over
|
||||
// it would erase that data, so refuse; the change stays queued until the app is updated.
|
||||
if serverCfg, getErr := configRepo.GetByUUID(cfg.UUID); getErr == nil {
|
||||
if err := configfeatures.Check(serverCfg.FeatureFlags); err != nil {
|
||||
return fmt.Errorf("push of configuration %s refused: %w", cfg.UUID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Update on server
|
||||
if err := configRepo.Update(&cfg); err != nil {
|
||||
return fmt.Errorf("updating configuration on server: %w", err)
|
||||
|
||||
@@ -23,7 +23,7 @@ func TestPushPendingChangesProjectsBeforeConfigurations(t *testing.T) {
|
||||
projectService := services.NewProjectService(local)
|
||||
configService := services.NewLocalConfigurationService(local, localSync, &services.QuoteService{}, func() bool { return false })
|
||||
|
||||
project, err := projectService.Create("tester", &services.CreateProjectRequest{Name: ptrString("Project A"), Code: "PRJ-A"})
|
||||
project, _, err := projectService.Create("tester", &services.CreateProjectRequest{Name: ptrString("Project A"), Code: "PRJ-A"})
|
||||
if err != nil {
|
||||
t.Fatalf("create project: %v", err)
|
||||
}
|
||||
@@ -74,11 +74,11 @@ func TestPushPendingChangesProjectCreateThenUpdateBeforeFirstPush(t *testing.T)
|
||||
configService := services.NewLocalConfigurationService(local, localSync, &services.QuoteService{}, func() bool { return false })
|
||||
pushService := syncsvc.NewServiceWithDB(serverDB, local)
|
||||
|
||||
project, err := projectService.Create("tester", &services.CreateProjectRequest{Name: ptrString("Project v1"), Code: "PRJ-V1"})
|
||||
project, _, err := projectService.Create("tester", &services.CreateProjectRequest{Name: ptrString("Project v1"), Code: "PRJ-V1"})
|
||||
if err != nil {
|
||||
t.Fatalf("create project: %v", err)
|
||||
}
|
||||
if _, err := projectService.Update(project.UUID, "tester", &services.UpdateProjectRequest{Name: ptrString("Project v2")}); err != nil {
|
||||
if _, _, err := projectService.Update(project.UUID, "tester", &services.UpdateProjectRequest{Name: ptrString("Project v2")}); err != nil {
|
||||
t.Fatalf("update project: %v", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
-- Tables affected: qt_configurations
|
||||
-- recovery.not-started: safe to re-run; ADD COLUMN IF NOT EXISTS
|
||||
-- recovery.partial: ALTER TABLE qt_configurations DROP COLUMN feature_flags;
|
||||
-- recovery.completed: no action needed
|
||||
-- verify: feature_flags column missing | SELECT 1 FROM information_schema.COLUMNS WHERE table_schema=DATABASE() AND table_name='qt_configurations' AND column_name='feature_flags' HAVING COUNT(*)=0
|
||||
|
||||
-- Per-configuration feature flags (JSON array of strings, NULL = none). A client refuses
|
||||
-- to write a configuration carrying a flag it doesn't know. See
|
||||
-- bible-local/decisions/2026-09-24-configuration-feature-flags.md.
|
||||
ALTER TABLE qt_configurations
|
||||
ADD COLUMN IF NOT EXISTS feature_flags JSON NULL;
|
||||
@@ -0,0 +1,16 @@
|
||||
# QuoteForge v3.34
|
||||
|
||||
Дата релиза: 2026-08-10
|
||||
Тег: `v3.34`
|
||||
|
||||
Предыдущий релиз: `v3.33`
|
||||
|
||||
## Ключевые изменения
|
||||
|
||||
- CSV-экспорт цены продажи (DDP): колонка Estimate игнорировала пользовательский коэффициент «Аплифт к estimate» и всегда экспортировалась с x1,3 — фронтенд не передавал значение поля в бэкенд, а `applyDDPMarkup` применял один и тот же множитель ко всем трём колонкам сразу; теперь Estimate масштабируется по аплифту, Склад/Конкуренты — фиксированным x1,3;
|
||||
- рефакторинг дублирующегося кода без изменения поведения: в Go-хендлерах устранены повторяющиеся switch-конструкции обработки ошибок и bind-логика (`cmd/qfs/main.go`, `internal/handlers`, `internal/appstate`, `internal/article`); во фронтенде сведены в общие функции пять идентичных обработчиков клавиатурной навигации автокомплита и четыре функции сборки нового элемента корзины.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,16 @@
|
||||
# QuoteForge v3.35
|
||||
|
||||
Дата релиза: 2026-08-12
|
||||
Тег: `v3.35`
|
||||
|
||||
Предыдущий релиз: `v3.34`
|
||||
|
||||
## Ключевые изменения
|
||||
|
||||
- новый чекбокс «Складские цены» на уровне проекта (по аналогии с «Аренда») — включает/выключает показ складских цен во всех ценовых интерфейсах конфигураций проекта, включая CSV-экспорт; по умолчанию выключен;
|
||||
- чекбокс «Только наличие» перенесён из настроек цен конфигурации в настройки проекта и теперь активен только при включённых «Складские цены»; фильтрация компонентов по наличию работает как раньше.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,16 @@
|
||||
# QuoteForge v3.36
|
||||
|
||||
Дата релиза: 2026-08-12
|
||||
Тег: `v3.36`
|
||||
|
||||
Предыдущий релиз: `v3.35`
|
||||
|
||||
## Ключевые изменения
|
||||
|
||||
- исправлен DDP-экспорт CSV со страницы проекта: раньше всегда применялся коэффициент 1,3 ко всем конфигурациям, теперь используется собственный аплифт каждой конфигурации из раздела «Ценообразование» — экспорт с проекта идёт по тому же конвейеру, что и экспорт с конкретной конфигурации;
|
||||
- упрощена подпись DDP в модалке экспорта проекта.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,16 @@
|
||||
# QuoteForge v3.37
|
||||
|
||||
Дата релиза: 2026-08-24
|
||||
Тег: `v3.37`
|
||||
|
||||
Предыдущий релиз: `v3.36`
|
||||
|
||||
## Ключевые изменения
|
||||
|
||||
- исправлен баг конфигуратора: при изменении количества в таблицах с несколькими компонентами (диски, RAID-контроллеры и т.п.) поле «Кол-во» затиралось суммой в долларах, а «Стоимость» переставала пересчитываться корректно;
|
||||
- заодно ужесточён поиск строки в таблице при обновлении количества — теперь строго по LOT-коду, без риска задеть соседнюю строку с похожим названием.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,18 @@
|
||||
# QuoteForge v3.39
|
||||
|
||||
Дата релиза: 2026-08-31
|
||||
Тег: `v3.39`
|
||||
|
||||
Предыдущий релиз: `v3.37`
|
||||
|
||||
## Ключевые изменения
|
||||
|
||||
- новый режим индикаторов без цветовой кодировки (переключатель на странице «Настройки»): всё, что раньше передавалось только цветом, переходит на форму и текст — качество цены рисуется значком-«сигналом» из 5 столбиков вместо цветной точки/числа, на вкладке «Ценообразование» вместо заливки строк появляется отдельная колонка-индикатор слева, цены-заглушки из прайслиста WORLD помечаются буквой «W», а «загрязнённый» итог — значком «⚠» вместо красного цвета; подходит при нарушениях цветовосприятия, обычный цветовой режим остаётся по умолчанию;
|
||||
- страница «Настройки» переустроена: два блока («Подключение к базе данных» и «Индикаторы») в две колонки одной высоты, добавлена кнопка «Вернуться в приложение», поправлен заголовок вкладки браузера;
|
||||
- версия приложения теперь показывается в шапке рядом с логотипом (убрано дублирование «vv» и хардкод «v1.0» на странице настройки БД);
|
||||
- исправлена ошибка JavaScript из-за повторного объявления функции экранирования HTML.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,19 @@
|
||||
# QuoteForge v3.40
|
||||
|
||||
Дата релиза: 2026-09-01
|
||||
Тег: `v3.40`
|
||||
|
||||
Предыдущий релиз: `v3.39`
|
||||
|
||||
## Ключевые изменения
|
||||
|
||||
- артикул: категория LOT для сегмента берётся из component universe (`world ∪ estimate`), а не из привязанного к конфигурации прайслиста — LOT, который есть только в `world` (напр. `GPU_NV_RTX_PRO_6000D_SERVER_84GB_PCIE`), больше не выпадает из артикула;
|
||||
- артикул: нераспознанный токен больше не пишется как `UNK` — в артикул идёт категория LOT (`4xGPU`, `2xCPU`), сегмент помечается как нераспознанный;
|
||||
- конфигуратор подсвечивает нераспознанные части артикула (amber) и выводит список предупреждений с именами LOT; сохранение конфигурации пишет `WARN` в лог;
|
||||
- `POST /api/configs/preview-article` возвращает разбор артикула по сегментам (`segments[]`);
|
||||
- `parseGPUModel` сохраняет буквенный суффикс в номере модели (`6000D` → `RTX6000D`), раньше терял его и схлопывал до `RTX`.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,20 @@
|
||||
# QuoteForge v3.41
|
||||
|
||||
Дата релиза: 2026-09-17
|
||||
Тег: `v3.41`
|
||||
|
||||
Предыдущий релиз: `v3.40`
|
||||
|
||||
## Ключевые изменения
|
||||
|
||||
- накидка по строке в таблице «Цена продажи» + минимальный CSV-экспорт;
|
||||
- фикс: накидка по строке в «Цена продажи» не пересчитывала цену;
|
||||
- минимальная высота строк в таблицах вкладки «Ценообразование»;
|
||||
- артикул: распознавание DPU/BlueField-профиля (`DPU_BF3_...`, `DPU_BF2_...`) — больше не падает в заглушку категории NET;
|
||||
- имя варианта проекта с недопустимыми символами или зарезервированным словом `main` больше не блокирует создание/переименование — автоматически конвертируется в валидное, с предупреждением вместо ошибки;
|
||||
- длинное имя варианта больше не корёжит кнопки в хедере конфигуратора (усечение в хлебных крошках + защита вёрстки).
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -44,3 +44,42 @@
|
||||
visibility: visible;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Colour-blind-safe price-quality indicator (mono mode). 5-step signal meter,
|
||||
single neutral hue — magnitude reads from the number of lit bars, not colour. */
|
||||
.qf-quality-meter {
|
||||
display: inline-flex;
|
||||
align-items: flex-end;
|
||||
gap: 1px;
|
||||
height: 12px;
|
||||
vertical-align: middle;
|
||||
line-height: 0;
|
||||
}
|
||||
.qf-quality-meter > i {
|
||||
display: inline-block;
|
||||
width: 3px;
|
||||
background-color: #d1d5db;
|
||||
border-radius: 1px;
|
||||
}
|
||||
.qf-quality-meter > i.on {
|
||||
background-color: #374151;
|
||||
}
|
||||
.qf-quality-meter > i:nth-child(1) { height: 30%; }
|
||||
.qf-quality-meter > i:nth-child(2) { height: 45%; }
|
||||
.qf-quality-meter > i:nth-child(3) { height: 62%; }
|
||||
.qf-quality-meter > i:nth-child(4) { height: 80%; }
|
||||
.qf-quality-meter > i:nth-child(5) { height: 100%; }
|
||||
.qf-quality-meter[data-size="sm"] {
|
||||
height: 10px;
|
||||
gap: 1px;
|
||||
}
|
||||
.qf-quality-meter[data-size="sm"] > i {
|
||||
width: 2px;
|
||||
}
|
||||
|
||||
/* Leading meter column on the pricing tab tables (mono mode). */
|
||||
.pricing-quality-meter {
|
||||
width: 1%;
|
||||
white-space: nowrap;
|
||||
text-align: center;
|
||||
}
|
||||
@@ -1,16 +1,25 @@
|
||||
// Shared LOT price-quality color scale, used everywhere price_quality is
|
||||
// Shared LOT price-quality indicator, used everywhere price_quality is
|
||||
// displayed (pricelist detail page, configurator search dropdown, configurator
|
||||
// table, pricing tab). price_quality is a 0-9 score set by the external
|
||||
// pricing tool (see bible-local/03-database.md, qt_pricelist_items.price_quality)
|
||||
// — QF only displays it, never computes it. Single source of the color scale
|
||||
// so every view stays visually consistent.
|
||||
// table, pricing tab). price_quality is a 0-9 score set by the external pricing
|
||||
// tool (see bible-local/03-database.md, qt_pricelist_items.price_quality) — QF
|
||||
// only displays it, never computes it. Single source of the visual scale so
|
||||
// every view stays consistent.
|
||||
//
|
||||
// Gradient: 0 = red, 5 = yellow, 9 = green.
|
||||
// Two render modes, chosen per client via window.QF_INDICATOR_MODE (injected by
|
||||
// base.html from app_settings, key indicator_mode):
|
||||
// "color" (default) — hue scale, 0 = red, 5 = yellow, 9 = green.
|
||||
// "accessible" — colour-blind-safe 5-step signal-strength meter,
|
||||
// single neutral hue, magnitude encoded by bar count.
|
||||
// See bible-local/decisions/2026-08-31-accessible-indicator-mode.md.
|
||||
(function () {
|
||||
const RED = [220, 38, 38];
|
||||
const YELLOW = [234, 179, 8];
|
||||
const GREEN = [22, 163, 74];
|
||||
|
||||
function isAccessible() {
|
||||
return window.QF_INDICATOR_MODE === 'accessible';
|
||||
}
|
||||
|
||||
function lerp(c1, c2, t) {
|
||||
return c1.map((v, i) => Math.round(v + (c2[i] - v) * t));
|
||||
}
|
||||
@@ -28,27 +37,53 @@
|
||||
return rgb ? `rgb(${rgb})` : null;
|
||||
}
|
||||
|
||||
// Small colored dot for compact contexts (search dropdown, configurator table cell).
|
||||
// 0-9 score -> 0-4 meter level. 0-1 / 2-3 / 4-5 / 6-7 / 8-9.
|
||||
function priceQualityLevel(quality) {
|
||||
if (typeof quality !== 'number' || Number.isNaN(quality)) return null;
|
||||
const q = Math.max(0, Math.min(9, quality));
|
||||
return Math.min(4, Math.floor(q / 2));
|
||||
}
|
||||
|
||||
// Monochrome 5-step signal-strength meter. size: undefined | 'sm'.
|
||||
function qualityMeterHtml(quality, opts) {
|
||||
const level = priceQualityLevel(quality);
|
||||
if (level === null) return '';
|
||||
const size = opts && opts.size === 'sm' ? ' data-size="sm"' : '';
|
||||
const title = `Качество цены: ${quality}/9`;
|
||||
let bars = '';
|
||||
for (let i = 0; i < 5; i++) {
|
||||
bars += `<i class="${i <= level ? 'on' : ''}"></i>`;
|
||||
}
|
||||
return `<span class="qf-quality-meter"${size} role="img" aria-label="${title}" title="${title}">${bars}</span>`;
|
||||
}
|
||||
|
||||
// Small indicator for compact contexts (search dropdown, configurator table cell).
|
||||
function qualityDotHtml(quality) {
|
||||
if (isAccessible()) return qualityMeterHtml(quality, { size: 'sm' });
|
||||
const color = priceQualityColor(quality);
|
||||
if (!color) return '';
|
||||
return `<span class="inline-block w-2 h-2 rounded-full" style="background-color: ${color}" title="Качество цены: ${quality}/9"></span>`;
|
||||
}
|
||||
|
||||
// Colored number badge for a dedicated "quality" column/cell.
|
||||
// Indicator for a dedicated "quality" column/cell.
|
||||
function qualityBadgeHtml(quality) {
|
||||
if (typeof quality !== 'number') return '<span class="text-gray-400">-</span>';
|
||||
if (isAccessible()) return qualityMeterHtml(quality, { size: 'sm' });
|
||||
const color = priceQualityColor(quality);
|
||||
return `<span class="font-semibold" style="color: ${color}" title="Качество цены: ${quality}/9">${quality}</span>`;
|
||||
}
|
||||
|
||||
// Light row-tint background for table rows, e.g. the pricing tab.
|
||||
// Light row-tint background for table rows, e.g. the pricing tab. Suppressed
|
||||
// in accessible mode — the pricing tab carries its own leading meter column there.
|
||||
function qualityRowStyle(quality) {
|
||||
if (isAccessible()) return '';
|
||||
const rgb = priceQualityRgb(quality);
|
||||
return rgb ? `background-color: rgba(${rgb}, 0.10)` : '';
|
||||
}
|
||||
|
||||
window.priceQualityColor = priceQualityColor;
|
||||
window.priceQualityLevel = priceQualityLevel;
|
||||
window.qualityMeterHtml = qualityMeterHtml;
|
||||
window.qualityDotHtml = qualityDotHtml;
|
||||
window.qualityBadgeHtml = qualityBadgeHtml;
|
||||
window.qualityRowStyle = qualityRowStyle;
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
<link rel="stylesheet" href="/static/app.css">
|
||||
<script src="/static/vendor/tailwindcss.browser.js"></script>
|
||||
<script src="/static/vendor/htmx-1.9.10.min.js"></script>
|
||||
<script>window.QF_INDICATOR_MODE = "{{ .IndicatorMode }}";</script>
|
||||
<script src="/static/price-quality.js"></script>
|
||||
<style>
|
||||
.htmx-request { opacity: 0.5; }
|
||||
@@ -19,7 +20,7 @@
|
||||
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||
<div class="flex justify-between h-14">
|
||||
<div class="flex items-center space-x-8">
|
||||
<a href="/" class="text-xl font-bold text-blue-600">QuoteForge</a>
|
||||
<a href="/" class="text-xl font-bold text-blue-600">QuoteForge<span class="text-xs font-normal text-gray-400 align-middle ml-1">{{.AppVersion}}</span></a>
|
||||
<div class="hidden md:flex space-x-4">
|
||||
<a href="/projects" class="text-gray-600 hover:text-gray-900 px-3 py-2 text-sm">Мои проекты</a>
|
||||
<a href="/pricelists" class="text-gray-600 hover:text-gray-900 px-3 py-2 text-sm">Прайслисты</a>
|
||||
@@ -55,10 +56,6 @@
|
||||
{{template "content" .}}
|
||||
</main>
|
||||
|
||||
<footer class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3 text-right">
|
||||
<span class="text-xs text-gray-400">v{{.AppVersion}}</span>
|
||||
</footer>
|
||||
|
||||
<div id="toast" class="fixed bottom-4 right-4 z-50"></div>
|
||||
|
||||
<!-- Dead-man's switch overlay: shown when backend process stops responding -->
|
||||
|
||||
+360
-152
@@ -3,31 +3,31 @@
|
||||
{{define "content"}}
|
||||
<div class="space-y-4">
|
||||
<!-- Header with config name and back button -->
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex items-center space-x-4">
|
||||
<a href="/projects" class="text-gray-500 hover:text-gray-700" title="Все проекты">
|
||||
<div class="flex items-center justify-between gap-4 flex-wrap">
|
||||
<div class="flex items-center space-x-4 min-w-0">
|
||||
<a href="/projects" class="text-gray-500 hover:text-gray-700 shrink-0" title="Все проекты">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9.75L12 3l9 6.75v9A2.25 2.25 0 0118.75 21h-13.5A2.25 2.25 0 013 18.75v-9z"></path>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 21v-6h6v6"></path>
|
||||
</svg>
|
||||
</a>
|
||||
<div class="text-2xl font-bold flex items-center gap-2" id="config-breadcrumbs">
|
||||
<a id="breadcrumb-project-code-link" href="/projects" class="text-blue-700 hover:underline">
|
||||
<div class="text-2xl font-bold flex items-center gap-2 min-w-0" id="config-breadcrumbs">
|
||||
<a id="breadcrumb-project-code-link" href="/projects" class="text-blue-700 hover:underline shrink-0">
|
||||
<span id="breadcrumb-project-code">—</span>
|
||||
</a>
|
||||
<span class="text-gray-400">-</span>
|
||||
<a id="breadcrumb-project-variant-link" href="/projects" class="text-blue-700 hover:underline">
|
||||
<span class="text-gray-400 shrink-0">-</span>
|
||||
<a id="breadcrumb-project-variant-link" href="/projects" class="text-blue-700 hover:underline shrink-0">
|
||||
<span id="breadcrumb-project-variant">main</span>
|
||||
</a>
|
||||
<span class="text-gray-400">-</span>
|
||||
<a id="breadcrumb-config-name-link" href="#" class="text-blue-700 hover:underline">
|
||||
<span class="text-gray-400 shrink-0">-</span>
|
||||
<a id="breadcrumb-config-name-link" href="#" class="text-blue-700 hover:underline shrink-0">
|
||||
<span id="breadcrumb-config-name">Конфигуратор</span>
|
||||
</a>
|
||||
<span class="text-gray-400">-</span>
|
||||
<span id="breadcrumb-config-version">main</span>
|
||||
<span class="text-gray-400 shrink-0">-</span>
|
||||
<span id="breadcrumb-config-version" class="shrink-0">main</span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="save-buttons" class="hidden flex items-center space-x-2">
|
||||
<div id="save-buttons" class="hidden flex items-center space-x-2 shrink-0">
|
||||
<button id="refresh-prices-btn" onclick="refreshPrices()" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">
|
||||
Обновить цены
|
||||
</button>
|
||||
@@ -37,13 +37,24 @@
|
||||
title="Настройки цен">
|
||||
Цены
|
||||
</button>
|
||||
<button onclick="saveConfig()" class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700">
|
||||
<button id="save-config-btn" onclick="saveConfig()" class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed">
|
||||
Сохранить
|
||||
</button>
|
||||
<span id="price-update-date" class="text-sm text-gray-500"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Shown when the config carries feature flags this build doesn't know: saving is refused
|
||||
(see setConfigUnsupportedFeatures / internal/configfeatures). -->
|
||||
<div id="config-unsupported-banner" class="hidden bg-red-50 border border-red-200 text-red-800 rounded-lg px-4 py-3 text-sm" role="alert">
|
||||
<div class="font-semibold">Эта конфигурация создана в более новой версии QuoteForge</div>
|
||||
<div class="mt-1">
|
||||
Она использует функции, которых нет в вашей версии:
|
||||
<span id="config-unsupported-list" class="font-mono"></span>.
|
||||
Сохранение отключено, чтобы не потерять эти данные. Обновите приложение, чтобы редактировать конфигурацию.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Server count input -->
|
||||
<div class="bg-white rounded-lg shadow p-4 mb-4">
|
||||
<div class="flex items-center space-x-4">
|
||||
@@ -222,26 +233,27 @@
|
||||
<table class="w-full text-sm border-collapse">
|
||||
<thead class="bg-gray-50 text-gray-700">
|
||||
<tr>
|
||||
<th class="px-2 py-2 text-left border-b whitespace-nowrap">PN вендора</th>
|
||||
<th class="px-2 py-2 text-left border-b">Описание</th>
|
||||
<th class="px-2 py-2 text-left border-b">LOT</th>
|
||||
<th class="px-2 py-2 text-right border-b">Кол-во</th>
|
||||
<th class="px-2 py-2 text-right border-b">Estimate</th>
|
||||
<th class="px-2 py-2 text-right border-b">Склад</th>
|
||||
<th class="px-2 py-2 text-right border-b">Конкуренты</th>
|
||||
<th class="px-2 py-2 text-right border-b">Ручная цена</th>
|
||||
{{if eq .IndicatorMode "accessible"}}<th class="px-2 py-1 border-b" title="Качество цены"><span class="sr-only">Качество цены</span></th>{{end}}
|
||||
<th class="px-2 py-1 text-left border-b whitespace-nowrap">PN вендора</th>
|
||||
<th class="px-2 py-1 text-left border-b">Описание</th>
|
||||
<th class="px-2 py-1 text-left border-b">LOT</th>
|
||||
<th class="px-2 py-1 text-right border-b">Кол-во</th>
|
||||
<th class="px-2 py-1 text-right border-b">Estimate</th>
|
||||
<th class="px-2 py-1 text-right border-b stock-price-col">Склад</th>
|
||||
<th class="px-2 py-1 text-right border-b">Конкуренты</th>
|
||||
<th class="px-2 py-1 text-right border-b">Ручная цена</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="pricing-body-buy">
|
||||
<tr><td colspan="8" class="px-2 py-8 text-center text-gray-400">Загрузите BOM во вкладке «BOM»</td></tr>
|
||||
<tr><td colspan="{{if eq .IndicatorMode "accessible"}}9{{else}}8{{end}}" class="px-2 py-8 text-center text-gray-400">Загрузите BOM во вкладке «BOM»</td></tr>
|
||||
</tbody>
|
||||
<tfoot id="pricing-foot-buy" class="hidden bg-gray-50 font-semibold">
|
||||
<tr>
|
||||
<td colspan="4" class="px-2 py-2 text-right">Итого:</td>
|
||||
<td class="px-2 py-2 text-right" id="pricing-total-buy-estimate">—</td>
|
||||
<td class="px-2 py-2 text-right" id="pricing-total-buy-warehouse">—</td>
|
||||
<td class="px-2 py-2 text-right" id="pricing-total-buy-competitor">—</td>
|
||||
<td class="px-2 py-2 text-right font-bold" id="pricing-total-buy-vendor">—</td>
|
||||
<td colspan="{{if eq .IndicatorMode "accessible"}}5{{else}}4{{end}}" class="px-2 py-1 text-right">Итого:</td>
|
||||
<td class="px-2 py-1 text-right" id="pricing-total-buy-estimate">—</td>
|
||||
<td class="px-2 py-1 text-right stock-price-col" id="pricing-total-buy-warehouse">—</td>
|
||||
<td class="px-2 py-1 text-right" id="pricing-total-buy-competitor">—</td>
|
||||
<td class="px-2 py-1 text-right font-bold" id="pricing-total-buy-vendor">—</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
@@ -266,31 +278,26 @@
|
||||
<h3 class="text-base font-semibold text-gray-800">Цена продажи</h3>
|
||||
<span class="text-xs text-gray-400">Цены указаны за 1 шт.</span>
|
||||
</div>
|
||||
<p class="text-xs text-gray-500 mb-3">Склад и Конкуренты умножаются на 1,3</p>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm border-collapse">
|
||||
<thead class="bg-gray-50 text-gray-700">
|
||||
<tr>
|
||||
<th class="px-2 py-2 text-left border-b whitespace-nowrap">PN вендора</th>
|
||||
<th class="px-2 py-2 text-left border-b">Описание</th>
|
||||
<th class="px-2 py-2 text-left border-b">LOT</th>
|
||||
<th class="px-2 py-2 text-right border-b">Кол-во</th>
|
||||
<th class="px-2 py-2 text-right border-b">Estimate</th>
|
||||
<th class="px-2 py-2 text-right border-b">Склад</th>
|
||||
<th class="px-2 py-2 text-right border-b">Конкуренты</th>
|
||||
<th class="px-2 py-2 text-right border-b">Ручная цена</th>
|
||||
{{if eq .IndicatorMode "accessible"}}<th class="px-2 py-1 border-b" title="Качество цены"><span class="sr-only">Качество цены</span></th>{{end}}
|
||||
<th class="px-2 py-1 text-left border-b whitespace-nowrap">PN вендора</th>
|
||||
<th class="px-2 py-1 text-left border-b">Описание</th>
|
||||
<th class="px-2 py-1 text-left border-b">LOT</th>
|
||||
<th class="px-2 py-1 text-right border-b">Кол-во</th>
|
||||
<th class="px-2 py-1 text-right border-b w-20">Накидка, %</th>
|
||||
<th class="px-2 py-1 text-right border-b">Цена</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="pricing-body-sale">
|
||||
<tr><td colspan="8" class="px-2 py-8 text-center text-gray-400">Загрузите BOM во вкладке «BOM»</td></tr>
|
||||
<tr><td colspan="{{if eq .IndicatorMode "accessible"}}7{{else}}6{{end}}" class="px-2 py-8 text-center text-gray-400">Загрузите BOM во вкладке «BOM»</td></tr>
|
||||
</tbody>
|
||||
<tfoot id="pricing-foot-sale" class="hidden bg-gray-50 font-semibold">
|
||||
<tr>
|
||||
<td colspan="4" class="px-2 py-2 text-right">Итого:</td>
|
||||
<td class="px-2 py-2 text-right" id="pricing-total-sale-estimate">—</td>
|
||||
<td class="px-2 py-2 text-right" id="pricing-total-sale-warehouse">—</td>
|
||||
<td class="px-2 py-2 text-right" id="pricing-total-sale-competitor">—</td>
|
||||
<td class="px-2 py-2 text-right font-bold" id="pricing-total-sale-vendor">—</td>
|
||||
<td colspan="{{if eq .IndicatorMode "accessible"}}6{{else}}5{{end}}" class="px-2 py-1 text-right">Итого:</td>
|
||||
<td class="px-2 py-1 text-right font-bold" id="pricing-total-sale-price">—</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
@@ -395,10 +402,6 @@
|
||||
<input id="settings-disable-price-refresh" type="checkbox" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
|
||||
<span>Не обновлять цены</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-2 text-sm text-gray-700">
|
||||
<input id="settings-only-in-stock" type="checkbox" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
|
||||
<span>Только наличие</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="px-5 py-4 border-t flex justify-end gap-2">
|
||||
<button type="button" onclick="closePriceSettingsModal()" class="px-4 py-2 bg-gray-100 text-gray-700 rounded hover:bg-gray-200">Отмена</button>
|
||||
@@ -411,6 +414,9 @@
|
||||
<div id="autocomplete-dropdown" class="hidden absolute z-50 bg-white border rounded-lg shadow-lg max-h-96 overflow-y-auto w-96"></div>
|
||||
|
||||
<style>
|
||||
#top-section-pricing.hide-stock-prices .stock-price-col {
|
||||
display: none;
|
||||
}
|
||||
.autocomplete-item {
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
@@ -550,7 +556,8 @@ function updateConfigBreadcrumbs() {
|
||||
if (projectVariantLinkEl) projectVariantLinkEl.href = '/projects';
|
||||
}
|
||||
codeEl.textContent = code;
|
||||
variantEl.textContent = variant;
|
||||
variantEl.textContent = truncateBreadcrumbSpecName(variant);
|
||||
variantEl.title = variant;
|
||||
const fullConfigName = configName || 'Конфигурация';
|
||||
configEl.textContent = truncateBreadcrumbSpecName(fullConfigName);
|
||||
configEl.title = fullConfigName;
|
||||
@@ -594,6 +601,7 @@ let resolvedAutoPricelistIds = {
|
||||
};
|
||||
let disablePriceRefresh = false;
|
||||
let onlyInStock = false;
|
||||
let showStockPrices = false;
|
||||
let activePricelistsBySource = {
|
||||
estimate: [],
|
||||
warehouse: [],
|
||||
@@ -610,11 +618,9 @@ let componentPricesCache = {}; // { lot_name: price } - caches prices loaded via
|
||||
let componentPricesCacheLoading = new Map(); // { category: Promise } - tracks ongoing price loads
|
||||
|
||||
// ─── Sale (DDP) pricing markup — single source of truth for this file ───
|
||||
// Mirrors internal/services/export.go (saleMarkupFactor / stockCompetitorMarkupFactor).
|
||||
// Keep both sides in sync: Estimate scales by the user's uplift, Stock/Competitor by a fixed factor.
|
||||
// Mirrors internal/services/export.go effectiveSaleMarkupFactor/defaultSaleMarkup.
|
||||
const PricingMarkup = {
|
||||
DEFAULT_SALE_UPLIFT: 1.3,
|
||||
STOCK_COMPETITOR_FIXED: 1.3,
|
||||
// Reads the "Аплифт к estimate" input; falls back to DEFAULT_SALE_UPLIFT when empty/invalid.
|
||||
getSaleUplift() {
|
||||
const v = parseDecimalInput(document.getElementById('pricing-uplift-sale')?.value || '');
|
||||
@@ -622,6 +628,47 @@ const PricingMarkup = {
|
||||
},
|
||||
};
|
||||
|
||||
// Per-row "Накидка" (%) for the Sale table, keyed by _saleRowKey(vendorPN, lot).
|
||||
// Persisted in Configuration.Notes.pricing_ui.sale_row_markups (see buildPricingState/
|
||||
// restorePricingStateFromNotes); restored before the table exists, so renderPricingTab()
|
||||
// reads it live rather than relying on per-render input state.
|
||||
let saleRowMarkups = {};
|
||||
|
||||
// Feature flags of this configuration unknown to this build (server-computed
|
||||
// unsupported_features). Non-empty → saving is refused both here and by the backend.
|
||||
let configUnsupportedFeatures = [];
|
||||
|
||||
function setConfigUnsupportedFeatures(flags) {
|
||||
configUnsupportedFeatures = Array.isArray(flags) ? flags.filter(Boolean) : [];
|
||||
const blocked = configUnsupportedFeatures.length > 0;
|
||||
document.getElementById('config-unsupported-banner')?.classList.toggle('hidden', !blocked);
|
||||
const list = document.getElementById('config-unsupported-list');
|
||||
if (list) list.textContent = configUnsupportedFeatures.join(', ');
|
||||
const btn = document.getElementById('save-config-btn');
|
||||
if (btn) btn.disabled = blocked;
|
||||
}
|
||||
|
||||
function unsupportedFeaturesMessage() {
|
||||
return 'Сохранение невозможно: конфигурация использует функции, неизвестные этой версии ('
|
||||
+ configUnsupportedFeatures.join(', ') + '). Обновите приложение.';
|
||||
}
|
||||
|
||||
// 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
|
||||
// families since applyCustomPrice() strips those on vendor-price cells via regex.
|
||||
// Shared by renderPricingTab() (initial paint) and recomputeSalePrices() (re-paint on
|
||||
// input change), so both module-level functions rather than a closure in either one.
|
||||
const WORLD_CLS = 'bg-amber-50 text-amber-700';
|
||||
const worldCls = (w) => (window.QF_INDICATOR_MODE !== 'accessible' && w) ? WORLD_CLS : '';
|
||||
const worldMark = (w) => (window.QF_INDICATOR_MODE === 'accessible' && w)
|
||||
? '<sup class="text-gray-500 font-semibold" title="Цена-заглушка из прайслиста WORLD">W</sup>'
|
||||
: '';
|
||||
|
||||
// Autocomplete state
|
||||
let autocompleteInput = null;
|
||||
let autocompleteCategory = null;
|
||||
@@ -992,6 +1039,7 @@ document.addEventListener('DOMContentLoaded', async function() {
|
||||
await loadProjectIndex();
|
||||
updateConfigBreadcrumbs();
|
||||
applyRentalTabVisibility();
|
||||
applyStockPriceSettings();
|
||||
|
||||
rentalConditions = {};
|
||||
(config.rental_items || []).forEach(item => {
|
||||
@@ -1009,7 +1057,6 @@ document.addEventListener('DOMContentLoaded', async function() {
|
||||
selectedPricelistIds.warehouse = config.warehouse_pricelist_id || null;
|
||||
selectedPricelistIds.competitor = config.competitor_pricelist_id || null;
|
||||
disablePriceRefresh = Boolean(config.disable_price_refresh);
|
||||
onlyInStock = Boolean(config.only_in_stock);
|
||||
|
||||
if (config.items && config.items.length > 0) {
|
||||
cart = config.items.map(item => ({
|
||||
@@ -1026,6 +1073,7 @@ document.addEventListener('DOMContentLoaded', async function() {
|
||||
supportCode = parseSupportCodeFromLotName((cart.find(i => (i.lot_name || '').toUpperCase().startsWith('SVC_')) || {}).lot_name);
|
||||
currentArticle = config.article || '';
|
||||
restorePricingStateFromNotes(config.notes || '');
|
||||
setConfigUnsupportedFeatures(config.unsupported_features);
|
||||
|
||||
// Restore custom price if saved
|
||||
if (config.custom_price) {
|
||||
@@ -1203,10 +1251,6 @@ function syncPriceSettingsControls() {
|
||||
if (disableCheckbox) {
|
||||
disableCheckbox.checked = disablePriceRefresh;
|
||||
}
|
||||
const inStockCheckbox = document.getElementById('settings-only-in-stock');
|
||||
if (inStockCheckbox) {
|
||||
inStockCheckbox.checked = onlyInStock;
|
||||
}
|
||||
}
|
||||
|
||||
function getPricelistVersionById(source, id) {
|
||||
@@ -1223,7 +1267,8 @@ function renderPricelistSettingsSummary() {
|
||||
const competitor = selectedPricelistIds.competitor ? getPricelistVersionById('competitor', selectedPricelistIds.competitor) || `ID ${selectedPricelistIds.competitor}` : '—';
|
||||
const refreshState = disablePriceRefresh ? ' | Обновление цен: выкл' : '';
|
||||
const stockFilterState = onlyInStock ? ' | Только наличие: вкл' : '';
|
||||
summary.textContent = `Estimate: ${estimate}, Склад: ${warehouse}, Конкуренты: ${competitor}${refreshState}${stockFilterState}`;
|
||||
const stockPricesState = showStockPrices ? ' | Складские цены: вкл' : '';
|
||||
summary.textContent = `Estimate: ${estimate}, Склад: ${warehouse}, Конкуренты: ${competitor}${refreshState}${stockFilterState}${stockPricesState}`;
|
||||
}
|
||||
|
||||
function updateRefreshPricesButtonState() {
|
||||
@@ -1293,7 +1338,6 @@ function applyPriceSettings() {
|
||||
const warehouseVal = parseInt(document.getElementById('settings-pricelist-warehouse')?.value || '');
|
||||
const competitorVal = parseInt(document.getElementById('settings-pricelist-competitor')?.value || '');
|
||||
const disableVal = Boolean(document.getElementById('settings-disable-price-refresh')?.checked);
|
||||
const inStockVal = Boolean(document.getElementById('settings-only-in-stock')?.checked);
|
||||
|
||||
const prevWarehouseID = currentWarehousePricelistID();
|
||||
if (Number.isFinite(estimateVal) && estimateVal > 0) {
|
||||
@@ -1309,7 +1353,6 @@ function applyPriceSettings() {
|
||||
resolvedAutoPricelistIds.competitor = null;
|
||||
}
|
||||
disablePriceRefresh = disableVal;
|
||||
onlyInStock = inStockVal;
|
||||
|
||||
const nextWarehouseID = currentWarehousePricelistID();
|
||||
if (Number.isFinite(prevWarehouseID) && prevWarehouseID > 0 && prevWarehouseID !== nextWarehouseID) {
|
||||
@@ -1602,7 +1645,7 @@ function renderMultiSelectTab(components) {
|
||||
const total = getDisplayPrice(item) * item.quantity;
|
||||
|
||||
html += `
|
||||
<tr class="hover:bg-gray-50">
|
||||
<tr class="hover:bg-gray-50" data-lot-name="${escapeHtml(item.lot_name)}">
|
||||
<td class="px-2 py-2 text-center">${qualityDotHtml(comp?.price_quality)}</td>
|
||||
<td class="px-3 py-2 min-w-48">
|
||||
<div class="autocomplete-wrapper relative">
|
||||
@@ -1713,7 +1756,7 @@ function renderMultiSelectTabWithSections(sections) {
|
||||
const total = getDisplayPrice(item) * item.quantity;
|
||||
|
||||
html += `
|
||||
<tr class="hover:bg-gray-50">
|
||||
<tr class="hover:bg-gray-50" data-lot-name="${escapeHtml(item.lot_name)}">
|
||||
<td class="px-2 py-2 text-center">${qualityDotHtml(comp?.price_quality)}</td>
|
||||
<td class="px-3 py-2 min-w-48">
|
||||
<div class="autocomplete-wrapper relative">
|
||||
@@ -2234,9 +2277,9 @@ function updateMultiQuantity(lotName, value) {
|
||||
updateCartUI();
|
||||
triggerAutoSave();
|
||||
// Update total in the row
|
||||
const row = document.querySelector(`input[onchange*="${lotName}"]`)?.closest('tr');
|
||||
const row = document.querySelector(`tr[data-lot-name="${CSS.escape(lotName)}"]`);
|
||||
if (row) {
|
||||
const totalCell = row.querySelector('td:nth-child(5)');
|
||||
const totalCell = row.querySelector('td:nth-child(6)');
|
||||
if (totalCell) {
|
||||
totalCell.textContent = formatMoney(getDisplayPrice(item) * item.quantity);
|
||||
}
|
||||
@@ -2333,13 +2376,6 @@ function updateCartUI() {
|
||||
document.getElementById('cart-items').innerHTML = html;
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
if (!text) return '';
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function updateServerModelForQuote(value) {
|
||||
serverModelForQuote = value || '';
|
||||
scheduleArticlePreview();
|
||||
@@ -2547,13 +2583,40 @@ async function previewArticle() {
|
||||
}
|
||||
const data = await resp.json();
|
||||
currentArticle = data.article || '';
|
||||
el.textContent = currentArticle ? ('Артикул: ' + currentArticle) : 'Артикул: —';
|
||||
renderArticleDisplay(el, currentArticle, data.segments, data.warnings);
|
||||
} catch(e) {
|
||||
currentArticle = '';
|
||||
el.textContent = 'Артикул: —';
|
||||
}
|
||||
}
|
||||
|
||||
// renderArticleDisplay shows the article, colouring any segment the generator could
|
||||
// not fully parse (Recognized === false — its token is a category placeholder, not a
|
||||
// real spec) and listing the warnings that name the offending LOTs.
|
||||
function renderArticleDisplay(el, article, segments, warnings) {
|
||||
if (!article) { el.textContent = 'Артикул: —'; return; }
|
||||
let body;
|
||||
if (Array.isArray(segments) && segments.length) {
|
||||
body = segments.map(s => {
|
||||
const t = escapeHtml(s.text);
|
||||
return s.recognized === false
|
||||
? '<span class="text-amber-700 bg-amber-100 rounded px-0.5" title="не распознано — записана категория">' + t + '</span>'
|
||||
: t;
|
||||
}).join('-');
|
||||
} else {
|
||||
body = escapeHtml(article);
|
||||
}
|
||||
let html = 'Артикул: ' + body;
|
||||
if (Array.isArray(warnings) && warnings.length) {
|
||||
const list = warnings.filter(w => w !== 'compressed')
|
||||
.map(w => '<li>' + escapeHtml(w) + '</li>').join('');
|
||||
if (list) {
|
||||
html += '<ul class="mt-1 text-xs text-amber-700 list-disc list-inside font-sans">' + list + '</ul>';
|
||||
}
|
||||
}
|
||||
el.innerHTML = html;
|
||||
}
|
||||
|
||||
function getCurrentArticle() {
|
||||
return currentArticle || '';
|
||||
}
|
||||
@@ -2563,15 +2626,27 @@ function buildPricingState() {
|
||||
const saleUplift = parseDecimalInput(document.getElementById('pricing-uplift-sale')?.value || '');
|
||||
const saleCustom = parseDecimalInput(document.getElementById('pricing-custom-price-sale')?.value || '');
|
||||
|
||||
// Only non-zero entries are kept (negative = discount), so an untouched config
|
||||
// serializes exactly like before this feature.
|
||||
const rowMarkups = {};
|
||||
Object.entries(saleRowMarkups).forEach(([key, pct]) => {
|
||||
if (Number.isFinite(pct) && pct !== 0) rowMarkups[key] = pct;
|
||||
});
|
||||
|
||||
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,
|
||||
sale_uplift: saleUplift > 0 ? saleUplift : null,
|
||||
sale_custom_price: saleCustom > 0 ? saleCustom : null,
|
||||
sale_row_markups: Object.keys(rowMarkups).length ? rowMarkups : null,
|
||||
};
|
||||
}
|
||||
|
||||
function serializeConfigNotes() {
|
||||
return JSON.stringify({
|
||||
...loadedNotesExtra,
|
||||
pricing_ui: buildPricingState()
|
||||
});
|
||||
}
|
||||
@@ -2585,8 +2660,12 @@ function restorePricingStateFromNotes(notesRaw) {
|
||||
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;
|
||||
const { buy_custom_price, sale_uplift, sale_custom_price, sale_row_markups, ...pricingExtra } = pricing;
|
||||
loadedPricingUIExtra = pricingExtra;
|
||||
|
||||
const buyInput = document.getElementById('pricing-custom-price-buy');
|
||||
if (buyInput) {
|
||||
@@ -2608,6 +2687,17 @@ function restorePricingStateFromNotes(notesRaw) {
|
||||
? pricing.sale_custom_price.toFixed(2)
|
||||
: '';
|
||||
}
|
||||
|
||||
// Sale-table row is not rendered yet at this point — renderPricingTab() reads
|
||||
// saleRowMarkups live when it builds each row's Накидка input.
|
||||
saleRowMarkups = {};
|
||||
if (pricing.sale_row_markups && typeof pricing.sale_row_markups === 'object') {
|
||||
Object.entries(pricing.sale_row_markups).forEach(([key, pct]) => {
|
||||
if (typeof pct === 'number' && Number.isFinite(pct) && pct !== 0) {
|
||||
saleRowMarkups[key] = pct;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function getAutosaveStorageKey() {
|
||||
@@ -2631,8 +2721,7 @@ function buildSavePayload() {
|
||||
pricelist_id: selectedPricelistIds.estimate,
|
||||
warehouse_pricelist_id: selectedPricelistIds.warehouse,
|
||||
competitor_pricelist_id: selectedPricelistIds.competitor,
|
||||
disable_price_refresh: disablePriceRefresh,
|
||||
only_in_stock: onlyInStock
|
||||
disable_price_refresh: disablePriceRefresh
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2693,7 +2782,6 @@ function restoreAutosaveDraftIfAny() {
|
||||
supportCode = payload.support_code || supportCode;
|
||||
currentArticle = payload.article || currentArticle;
|
||||
selectedPricelistIds.estimate = payload.pricelist_id || selectedPricelistIds.estimate;
|
||||
onlyInStock = Boolean(payload.only_in_stock);
|
||||
|
||||
const customPriceInput = document.getElementById('custom-price-input');
|
||||
if (customPriceInput) {
|
||||
@@ -2713,7 +2801,7 @@ function restoreAutosaveDraftIfAny() {
|
||||
}
|
||||
|
||||
function saveConfigOnExit() {
|
||||
if (!configUUID || !hasUnsavedChanges || exitSaveStarted) return;
|
||||
if (!configUUID || !hasUnsavedChanges || exitSaveStarted || configUnsupportedFeatures.length) return;
|
||||
exitSaveStarted = true;
|
||||
try {
|
||||
fetch('/api/configs/' + configUUID, {
|
||||
@@ -2743,6 +2831,10 @@ function triggerAutoSave() {
|
||||
async function saveConfig(showNotification = true) {
|
||||
// RBAC disabled - no token check required
|
||||
if (!configUUID) return;
|
||||
if (configUnsupportedFeatures.length) {
|
||||
if (showNotification) showToast(unsupportedFeaturesMessage(), 'error');
|
||||
return;
|
||||
}
|
||||
if (priceLevelsRefreshTimer) {
|
||||
clearTimeout(priceLevelsRefreshTimer);
|
||||
priceLevelsRefreshTimer = null;
|
||||
@@ -2760,6 +2852,14 @@ async function saveConfig(showNotification = true) {
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
// 409 unsupported_config_features: a newer client added data this build can't
|
||||
// round-trip (possibly since this page was opened) — lock the page.
|
||||
const errBody = await resp.json().catch(() => null);
|
||||
if (errBody && errBody.code === 'unsupported_config_features') {
|
||||
setConfigUnsupportedFeatures(errBody.unsupported_features);
|
||||
if (showNotification) showToast(unsupportedFeaturesMessage(), 'error');
|
||||
return;
|
||||
}
|
||||
if (showNotification) {
|
||||
showToast('Ошибка сохранения', 'error');
|
||||
}
|
||||
@@ -3262,6 +3362,24 @@ function applyRentalTabVisibility() {
|
||||
}
|
||||
}
|
||||
|
||||
function applyStockPriceSettings() {
|
||||
const proj = projectUUID ? projectByUUID[projectUUID] : null;
|
||||
showStockPrices = !!(proj && proj.show_stock_prices);
|
||||
onlyInStock = !!(proj && proj.show_stock_prices && proj.only_in_stock);
|
||||
|
||||
const pricingSection = document.getElementById('top-section-pricing');
|
||||
if (pricingSection) {
|
||||
pricingSection.classList.toggle('hide-stock-prices', !showStockPrices);
|
||||
}
|
||||
|
||||
if (onlyInStock) {
|
||||
ensureWarehouseStockFilterLoaded().then(() => {
|
||||
renderTab();
|
||||
updateCartUI();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleRentalRecalc() {
|
||||
clearTimeout(rentalRecalcTimer);
|
||||
rentalRecalcTimer = setTimeout(renderRentalTab, 300);
|
||||
@@ -4484,9 +4602,6 @@ async function renderPricingTab() {
|
||||
} catch(e) { /* silent */ }
|
||||
}
|
||||
|
||||
// Sale uplift applied to estimate; Stock/Competitor use the fixed factor. See PricingMarkup.
|
||||
const saleUplift = PricingMarkup.getSaleUplift();
|
||||
const SALE_FIXED_MULT = PricingMarkup.STOCK_COMPETITOR_FIXED;
|
||||
|
||||
// Helper: returns unit prices from pricelist for a single LOT
|
||||
const _getUnitPrices = (pl) => ({
|
||||
@@ -4498,9 +4613,12 @@ async function renderPricingTab() {
|
||||
compWorld: !!(pl && pl.competitor_from_world),
|
||||
});
|
||||
|
||||
// Amber marker for world-fallback cells — must stay outside gray/green/red/blue
|
||||
// families since applyCustomPrice() strips those on vendor-price cells via regex.
|
||||
const WORLD_CLS = 'bg-amber-50 text-amber-700';
|
||||
// Colour-blind-safe mode: leading signal-meter column, no row tint, and the
|
||||
// amber world-fallback cell tint is replaced by a text marker.
|
||||
const ACCESSIBLE_MODE = window.QF_INDICATOR_MODE === 'accessible';
|
||||
const meterCell = (q, bt) => ACCESSIBLE_MODE
|
||||
? `<td class="pricing-quality-meter px-2 py-0.5 align-middle ${bt || ''}">${qualityMeterHtml(q)}</td>`
|
||||
: '';
|
||||
|
||||
// ─── Build shared row data (unit prices for display, totals for math) ────
|
||||
// Each BOM row is exploded into per-LOT sub-rows; grouped by vendor PN via groupStart/groupSize.
|
||||
@@ -4632,7 +4750,7 @@ async function renderPricingTab() {
|
||||
// ─── Populate Buy table ──────────────────────────────────────────────────
|
||||
tbodyBuy.innerHTML = '';
|
||||
if (!rowData.length) {
|
||||
tbodyBuy.innerHTML = '<tr><td colspan="8" class="px-2 py-8 text-center text-gray-400">Нет данных для отображения</td></tr>';
|
||||
tbodyBuy.innerHTML = `<tr><td colspan="${ACCESSIBLE_MODE ? 9 : 8}" class="px-2 py-8 text-center text-gray-400">Нет данных для отображения</td></tr>`;
|
||||
tfootBuy.classList.add('hidden');
|
||||
} else {
|
||||
let totEst = 0, totWh = 0, totComp = 0, totVendor = 0;
|
||||
@@ -4662,17 +4780,18 @@ async function renderPricingTab() {
|
||||
const borderTop = r.groupStart ? 'border-t border-gray-200' : '';
|
||||
const pnDescHtml = r.groupStart ? (() => {
|
||||
const rs = r.groupSize > 1 ? ` rowspan="${r.groupSize}"` : '';
|
||||
return `<td${rs} class="px-2 py-1.5 font-mono text-xs border-t border-gray-200 align-top whitespace-nowrap ${r.vendorPN == null ? 'text-gray-400' : ''}">${r.vendorPN != null ? escapeHtml(r.vendorPN) : '—'}</td>
|
||||
<td${rs} class="px-2 py-1.5 text-xs text-gray-500 truncate max-w-xs border-t border-gray-200 align-top">${escapeHtml(r.desc)}</td>`;
|
||||
return `<td${rs} class="px-2 py-0.5 font-mono text-xs border-t border-gray-200 align-top whitespace-nowrap ${r.vendorPN == null ? 'text-gray-400' : ''}">${r.vendorPN != null ? escapeHtml(r.vendorPN) : '—'}</td>
|
||||
<td${rs} class="px-2 py-0.5 text-xs text-gray-500 truncate max-w-xs border-t border-gray-200 align-top">${escapeHtml(r.desc)}</td>`;
|
||||
})() : '';
|
||||
tr.innerHTML = `
|
||||
${meterCell(r.priceQuality, borderTop)}
|
||||
${pnDescHtml}
|
||||
<td class="px-2 py-1.5 text-xs ${borderTop}">${r.lotCell}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop}">${r.qty}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${r.estWorld ? WORLD_CLS : ''}">${r.estUnit > 0 ? formatCurrency(r.estUnit) : '—'}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${r.whWorld ? WORLD_CLS : ''}">${r.warehouseUnit != null ? formatCurrency(r.warehouseUnit) : '—'}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${r.compWorld ? WORLD_CLS : ''}">${r.competitorUnit != null ? formatCurrency(r.competitorUnit) : '—'}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs pricing-vendor-price-buy ${borderTop} ${r.vendorOrigUnit == null ? 'text-gray-400' : ''}">${r.vendorOrigUnit != null ? formatCurrency(r.vendorOrigUnit) : '—'}</td>
|
||||
<td class="px-2 py-0.5 text-xs ${borderTop}">${r.lotCell}</td>
|
||||
<td class="px-2 py-0.5 text-right text-xs ${borderTop}">${r.qty}</td>
|
||||
<td class="px-2 py-0.5 text-right text-xs ${borderTop} ${worldCls(r.estWorld)}">${r.estUnit > 0 ? formatCurrency(r.estUnit) : '—'}${worldMark(r.estWorld)}</td>
|
||||
<td class="px-2 py-0.5 text-right text-xs stock-price-col ${borderTop} ${worldCls(r.whWorld)}">${r.warehouseUnit != null ? formatCurrency(r.warehouseUnit) : '—'}${worldMark(r.whWorld)}</td>
|
||||
<td class="px-2 py-0.5 text-right text-xs ${borderTop} ${worldCls(r.compWorld)}">${r.competitorUnit != null ? formatCurrency(r.competitorUnit) : '—'}${worldMark(r.compWorld)}</td>
|
||||
<td class="px-2 py-0.5 text-right text-xs pricing-vendor-price-buy ${borderTop} ${r.vendorOrigUnit == null ? 'text-gray-400' : ''}">${r.vendorOrigUnit != null ? formatCurrency(r.vendorOrigUnit) : '—'}</td>
|
||||
`;
|
||||
tbodyBuy.appendChild(tr);
|
||||
});
|
||||
@@ -4684,15 +4803,15 @@ async function renderPricingTab() {
|
||||
}
|
||||
|
||||
// ─── Populate Sale table ─────────────────────────────────────────────────
|
||||
// Sale rows show one final "Цена" per row: rawEstimate (or a proportional share
|
||||
// of the global "Ручная цена" when set) multiplied by (Аплифт к estimate + row's
|
||||
// own Накидка%). See recomputeSalePrices() / _saleRowPrice() for the shared math,
|
||||
// re-run on every input change and after every render.
|
||||
tbodySale.innerHTML = '';
|
||||
if (!rowData.length) {
|
||||
tbodySale.innerHTML = '<tr><td colspan="8" class="px-2 py-8 text-center text-gray-400">Нет данных для отображения</td></tr>';
|
||||
tbodySale.innerHTML = `<tr><td colspan="${ACCESSIBLE_MODE ? 7 : 6}" class="px-2 py-8 text-center text-gray-400">Нет данных для отображения</td></tr>`;
|
||||
tfootSale.classList.add('hidden');
|
||||
} else {
|
||||
let totEst = 0, totWh = 0, totComp = 0;
|
||||
let hasEst = false, hasWh = false, hasComp = false;
|
||||
let cntWh = 0, cntComp = 0;
|
||||
let worldEst = 0, worldWh = 0, worldComp = 0;
|
||||
rowData.forEach(r => {
|
||||
const tr = document.createElement('tr');
|
||||
tr.classList.add('pricing-row-sale');
|
||||
@@ -4701,48 +4820,122 @@ async function renderPricingTab() {
|
||||
} else if (r.isEstOnly) {
|
||||
tr.classList.add('bg-blue-50');
|
||||
}
|
||||
const saleEstUnit = r.estUnit > 0 ? r.estUnit * saleUplift : 0;
|
||||
const saleWhUnit = r.warehouseUnit != null ? r.warehouseUnit * SALE_FIXED_MULT : null;
|
||||
const saleCompUnit = r.competitorUnit != null ? r.competitorUnit * SALE_FIXED_MULT : null;
|
||||
const saleEstTotal = saleEstUnit * r.qty;
|
||||
const saleWhTotal = saleWhUnit != null ? saleWhUnit * r.qty : null;
|
||||
const saleCompTotal = saleCompUnit != null ? saleCompUnit * r.qty : null;
|
||||
tr.dataset.estSale = saleEstTotal;
|
||||
const rowKey = _saleRowKey(r.vendorPN, r.lotText);
|
||||
const markupPct = saleRowMarkups[rowKey] || 0;
|
||||
tr.dataset.rowKey = rowKey;
|
||||
tr.dataset.rawEst = r.est;
|
||||
tr.dataset.qty = r.qty;
|
||||
tr.dataset.groupStart = r.groupStart ? 'true' : 'false';
|
||||
tr.dataset.vendorPn = r.vendorPN || '';
|
||||
tr.dataset.desc = r.desc;
|
||||
tr.dataset.lot = r.lotText;
|
||||
if (saleEstTotal > 0) { totEst += saleEstTotal; hasEst = true; if (r.estWorld) worldEst += saleEstTotal; }
|
||||
if (saleWhTotal != null) { totWh += saleWhTotal; hasWh = true; cntWh++; if (r.whWorld) worldWh += saleWhTotal; }
|
||||
if (saleCompTotal != null) { totComp += saleCompTotal; hasComp = true; cntComp++; if (r.compWorld) worldComp += saleCompTotal; }
|
||||
tr.dataset.estWorld = r.estWorld ? 'true' : 'false';
|
||||
const borderTop = r.groupStart ? 'border-t border-gray-200' : '';
|
||||
const pnDescHtml = r.groupStart ? (() => {
|
||||
const rs = r.groupSize > 1 ? ` rowspan="${r.groupSize}"` : '';
|
||||
return `<td${rs} class="px-2 py-1.5 font-mono text-xs border-t border-gray-200 align-top whitespace-nowrap ${r.vendorPN == null ? 'text-gray-400' : ''}">${r.vendorPN != null ? escapeHtml(r.vendorPN) : '—'}</td>
|
||||
<td${rs} class="px-2 py-1.5 text-xs text-gray-500 truncate max-w-xs border-t border-gray-200 align-top">${escapeHtml(r.desc)}</td>`;
|
||||
return `<td${rs} class="px-2 py-0.5 font-mono text-xs border-t border-gray-200 align-top whitespace-nowrap ${r.vendorPN == null ? 'text-gray-400' : ''}">${r.vendorPN != null ? escapeHtml(r.vendorPN) : '—'}</td>
|
||||
<td${rs} class="px-2 py-0.5 text-xs text-gray-500 truncate max-w-xs border-t border-gray-200 align-top">${escapeHtml(r.desc)}</td>`;
|
||||
})() : '';
|
||||
tr.innerHTML = `
|
||||
${meterCell(r.priceQuality, borderTop)}
|
||||
${pnDescHtml}
|
||||
<td class="px-2 py-1.5 text-xs ${borderTop}">${r.lotCell}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop}">${r.qty}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${r.estWorld ? WORLD_CLS : ''}">${saleEstUnit > 0 ? formatCurrency(saleEstUnit) : '—'}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${r.whWorld ? WORLD_CLS : ''}">${saleWhUnit != null ? formatCurrency(saleWhUnit) : '—'}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${r.compWorld ? WORLD_CLS : ''}">${saleCompUnit != null ? formatCurrency(saleCompUnit) : '—'}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs pricing-vendor-price-sale ${borderTop} text-gray-400">—</td>
|
||||
<td class="px-2 py-0.5 text-xs ${borderTop}">${r.lotCell}</td>
|
||||
<td class="px-2 py-0.5 text-right text-xs ${borderTop}">${r.qty}</td>
|
||||
<td class="px-2 py-0.5 text-right ${borderTop}">
|
||||
<input type="text" inputmode="decimal" class="pricing-row-markup w-16 px-1 py-0.5 border rounded text-right text-xs"
|
||||
value="${formatMarkupInput(markupPct)}" data-row-key="${rowKey}"
|
||||
placeholder="0" oninput="onSaleRowMarkupInput(this)">
|
||||
</td>
|
||||
<td class="px-2 py-0.5 text-right text-xs pricing-sale-price ${borderTop} ${worldCls(r.estWorld)}">—${worldMark(r.estWorld)}</td>
|
||||
`;
|
||||
tbodySale.appendChild(tr);
|
||||
});
|
||||
document.getElementById('pricing-total-sale-vendor').textContent = '—';
|
||||
_setPricingTotal('pricing-total-sale-estimate', hasEst, totEst, worldEst, rowData.length, rowData.length);
|
||||
_setPricingTotal('pricing-total-sale-warehouse', hasWh, totWh, worldWh, cntWh, rowData.length);
|
||||
_setPricingTotal('pricing-total-sale-competitor', hasComp, totComp, worldComp, cntComp, rowData.length);
|
||||
tfootSale.classList.remove('hidden');
|
||||
}
|
||||
|
||||
// Restore custom prices after re-render
|
||||
applyCustomPrice('buy');
|
||||
applyCustomPrice('sale');
|
||||
recomputeSalePrices();
|
||||
}
|
||||
|
||||
// Composite key for a Sale-table row's per-row "Накидка": the same LOT can appear
|
||||
// under more than one vendor PN group (see bible-local/02-architecture.md "Per-LOT
|
||||
// row expansion rules"), so lot_name alone is not a safe map key.
|
||||
function _saleRowKey(vendorPN, lot) {
|
||||
const U = s => (s || '').toUpperCase();
|
||||
return `${U(vendorPN) || 'NONE'}::${U(lot)}`;
|
||||
}
|
||||
|
||||
// Single source of truth for a Sale row's final price: its base (raw estimate, or a
|
||||
// proportional share of the global "Ручная цена" when set) times (global uplift + this
|
||||
// row's own Накидка%).
|
||||
function _saleRowPrice(base, markupPct, saleUplift) {
|
||||
// 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;
|
||||
}
|
||||
|
||||
// Re-derives every Sale row's displayed price from its raw estimate, the global
|
||||
// uplift/manual-price inputs, and its own Накидка input. Called after render and on
|
||||
// every uplift/manual-price/row-markup change — the only place this math happens.
|
||||
function recomputeSalePrices() {
|
||||
const saleUplift = PricingMarkup.getSaleUplift();
|
||||
const customPrice = parseDecimalInput(document.getElementById('pricing-custom-price-sale')?.value || '');
|
||||
const rows = Array.from(document.querySelectorAll('#pricing-body-sale tr.pricing-row-sale'));
|
||||
|
||||
let estimateTotalRaw = 0;
|
||||
let lastPricedIdx = -1;
|
||||
rows.forEach((tr, i) => {
|
||||
const rawEst = parseFloat(tr.dataset.rawEst) || 0;
|
||||
if (rawEst > 0) { estimateTotalRaw += rawEst; lastPricedIdx = i; }
|
||||
});
|
||||
|
||||
// Same last-row-absorbs-remainder distribution as applyCustomPrice()/
|
||||
// distributeManualPrice() so the rows' bases sum to customPrice exactly.
|
||||
let assigned = 0;
|
||||
let total = 0, worldTotal = 0, hasAny = false, pricedCount = 0;
|
||||
rows.forEach((tr, i) => {
|
||||
const rawEst = parseFloat(tr.dataset.rawEst) || 0;
|
||||
const cell = tr.querySelector('.pricing-sale-price');
|
||||
if (!cell) return;
|
||||
if (rawEst <= 0) {
|
||||
cell.innerHTML = '—';
|
||||
return;
|
||||
}
|
||||
let base;
|
||||
if (customPrice > 0 && estimateTotalRaw > 0) {
|
||||
if (i === lastPricedIdx) {
|
||||
base = Math.round((customPrice - assigned) * 100) / 100;
|
||||
} else {
|
||||
base = Math.round((rawEst / estimateTotalRaw) * customPrice * 100) / 100;
|
||||
assigned += base;
|
||||
}
|
||||
} else {
|
||||
base = rawEst;
|
||||
}
|
||||
const markupPct = saleRowMarkups[tr.dataset.rowKey] || 0;
|
||||
const isWorld = tr.dataset.estWorld === 'true';
|
||||
const price = _saleRowPrice(base, markupPct, saleUplift);
|
||||
cell.innerHTML = formatCurrency(price) + worldMark(isWorld);
|
||||
total += price;
|
||||
hasAny = true;
|
||||
pricedCount++;
|
||||
if (isWorld) worldTotal += price;
|
||||
});
|
||||
|
||||
_setPricingTotal('pricing-total-sale-price', hasAny, total, worldTotal, pricedCount, rows.length);
|
||||
}
|
||||
|
||||
function onSaleRowMarkupInput(inputEl) {
|
||||
const key = inputEl.dataset.rowKey;
|
||||
const value = parseDecimalInput(inputEl.value || '');
|
||||
if (value !== 0) {
|
||||
saleRowMarkups[key] = value;
|
||||
} else {
|
||||
delete saleRowMarkups[key];
|
||||
}
|
||||
recomputeSalePrices();
|
||||
triggerAutoSave();
|
||||
}
|
||||
|
||||
// ─── Pricing helpers ─────────────────────────────────────────────────────────
|
||||
@@ -4775,10 +4968,15 @@ function _setPricingTotal(elId, has, total, worldTotal, count, totalRows) {
|
||||
parts.push(`Цены есть не для всех позиций: ${count} из ${totalRows}`);
|
||||
}
|
||||
|
||||
// Red is reserved for a sum that actually leans on world stand-in prices.
|
||||
el.className = `${el.className} ${share > 0 ? 'text-red-600' : ''} pricing-total-tip`
|
||||
// A sum that leans on world stand-in prices is flagged: by red in color
|
||||
// mode, by a leading ⚠ glyph in accessible mode. The hover popup carries the
|
||||
// exact share (and the coverage line, when some positions have no price) in
|
||||
// both modes.
|
||||
const accessible = window.QF_INDICATOR_MODE === 'accessible';
|
||||
el.className = `${el.className} ${share > 0 && !accessible ? 'text-red-600' : ''} pricing-total-tip`
|
||||
.replace(/\s+/g, ' ').trim();
|
||||
el.innerHTML = `${formatCurrency(total)}<span class="pricing-total-tip__body">${parts.join('<br>')}</span>`;
|
||||
const mark = share > 0 && accessible ? '<span title="Часть суммы — цена-заглушка WORLD">⚠</span> ' : '';
|
||||
el.innerHTML = `${mark}${formatCurrency(total)}<span class="pricing-total-tip__body">${parts.join('<br>')}</span>`;
|
||||
}
|
||||
|
||||
// One decimal, comma separator, no trailing ",0".
|
||||
@@ -4788,7 +4986,7 @@ function formatPercent(v) {
|
||||
|
||||
function parseDecimalInput(raw) {
|
||||
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);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
}
|
||||
@@ -4798,25 +4996,27 @@ function formatUpliftInput(value) {
|
||||
return value.toFixed(4).replace('.', ',');
|
||||
}
|
||||
|
||||
// One or two decimals, comma separator, no trailing zeros — for the per-row Накидка input.
|
||||
function formatMarkupInput(value) {
|
||||
if (!Number.isFinite(value) || value === 0) return '';
|
||||
return String(Math.round(value * 100) / 100).replace('.', ',');
|
||||
}
|
||||
|
||||
function _getPricingEstimateTotal(table) {
|
||||
const attr = table === 'sale' ? 'estSale' : 'est';
|
||||
const cls = table === 'sale' ? 'pricing-row-sale' : 'pricing-row-buy';
|
||||
let total = 0;
|
||||
document.querySelectorAll(`#pricing-body-${table} tr.${cls}`).forEach(tr => {
|
||||
total += parseFloat(tr.dataset[attr]) || 0;
|
||||
document.querySelectorAll(`#pricing-body-${table} tr.pricing-row-${table}`).forEach(tr => {
|
||||
total += parseFloat(tr.dataset.est) || 0;
|
||||
});
|
||||
return total;
|
||||
}
|
||||
|
||||
// Apply custom (own) price proportionally to Ручная цена column.
|
||||
// table: 'buy' | 'sale'
|
||||
// Apply custom (own) price proportionally to the Buy table's Ручная цена column.
|
||||
// The Sale table's own manual-price handling lives in recomputeSalePrices().
|
||||
function applyCustomPrice(table) {
|
||||
const inputId = `pricing-custom-price-${table}`;
|
||||
const totalElId = `pricing-total-${table}-vendor`;
|
||||
const rowClass = `pricing-row-${table}`;
|
||||
const cellClass = `.pricing-vendor-price-${table}`;
|
||||
const estAttr = table === 'sale' ? 'estSale' : 'est';
|
||||
const origAttr = table === 'buy' ? 'vendorOrig' : null;
|
||||
|
||||
const customPrice = parseFloat(document.getElementById(inputId)?.value) || 0;
|
||||
const estimateTotal = _getPricingEstimateTotal(table);
|
||||
@@ -4835,7 +5035,7 @@ function applyCustomPrice(table) {
|
||||
if (customPrice > 0 && estimateTotal > 0) {
|
||||
let assigned = 0;
|
||||
rows.forEach((tr, i) => {
|
||||
const rowEst = parseFloat(tr.dataset[estAttr]) || 0;
|
||||
const rowEst = parseFloat(tr.dataset.est) || 0;
|
||||
const qty = Math.max(1, parseFloat(tr.dataset.qty) || 1);
|
||||
const cell = vendorCells[i];
|
||||
if (!cell) return;
|
||||
@@ -4860,22 +5060,17 @@ function applyCustomPrice(table) {
|
||||
const cell = vendorCells[i];
|
||||
if (!cell) return;
|
||||
cell.className = cell.className.replace(/\btext-(?:gray|green|red|blue)-\d+\b/g, '').trim();
|
||||
if (origAttr && tr.dataset.vendorOrigUnit !== '') {
|
||||
if (tr.dataset.vendorOrigUnit !== '') {
|
||||
cell.textContent = formatCurrency(parseFloat(tr.dataset.vendorOrigUnit));
|
||||
} else {
|
||||
cell.textContent = '—';
|
||||
cell.classList.add('text-gray-400');
|
||||
}
|
||||
});
|
||||
// Recompute total from originals (buy) or clear (sale)
|
||||
if (origAttr) {
|
||||
let origTotal = 0; let hasOrig = false;
|
||||
rows.forEach(tr => { if (tr.dataset[origAttr] !== '') { origTotal += parseFloat(tr.dataset[origAttr]) || 0; hasOrig = true; } });
|
||||
totalVendorEl.textContent = hasOrig ? formatCurrency(origTotal) : '—';
|
||||
} else {
|
||||
// sale: reset to — already handled above
|
||||
totalVendorEl.textContent = '—';
|
||||
}
|
||||
// Recompute total from originals
|
||||
let origTotal = 0; let hasOrig = false;
|
||||
rows.forEach(tr => { if (tr.dataset.vendorOrig !== '') { origTotal += parseFloat(tr.dataset.vendorOrig) || 0; hasOrig = true; } });
|
||||
totalVendorEl.textContent = hasOrig ? formatCurrency(origTotal) : '—';
|
||||
totalVendorEl.className = totalVendorEl.className.replace(/\btext-(?:green|red)-\d+\b/g, '').trim();
|
||||
}
|
||||
}
|
||||
@@ -4886,7 +5081,7 @@ function onBuyCustomPriceInput() {
|
||||
}
|
||||
|
||||
function onSaleCustomPriceInput() {
|
||||
applyCustomPrice('sale');
|
||||
recomputeSalePrices();
|
||||
triggerAutoSave();
|
||||
}
|
||||
|
||||
@@ -4937,20 +5132,33 @@ async function exportPricingCSV(table) {
|
||||
const manualInputId = table === 'sale' ? 'pricing-custom-price-sale' : 'pricing-custom-price-buy';
|
||||
const manualPrice = parseDecimalInput(document.getElementById(manualInputId)?.value || '');
|
||||
const saleUplift = table === 'sale' ? PricingMarkup.getSaleUplift() : 0;
|
||||
// Sale export drops Estimate/Stock/Competitor and collapses to LOT/Описание/
|
||||
// Кол-во/Цена — see internal/services/export.go MinimalSaleColumns. Buy export is
|
||||
// untouched.
|
||||
const requestBody = table === 'sale'
|
||||
? {
|
||||
include_lot: true,
|
||||
basis: basis,
|
||||
sale_markup: saleUplift > 0 ? saleUplift : null,
|
||||
manual_price: manualPrice > 0 ? manualPrice : null,
|
||||
minimal_sale_columns: true,
|
||||
sale_row_markups: saleRowMarkups,
|
||||
}
|
||||
: {
|
||||
include_lot: true,
|
||||
include_bom: true,
|
||||
include_estimate: true,
|
||||
include_stock: !!showStockPrices,
|
||||
include_competitor: true,
|
||||
basis: basis,
|
||||
sale_markup: null,
|
||||
manual_price: manualPrice > 0 ? manualPrice : null,
|
||||
};
|
||||
try {
|
||||
const resp = await fetch(`/api/configs/${configUUID}/export/pricing`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({
|
||||
include_lot: true,
|
||||
include_bom: true,
|
||||
include_estimate: true,
|
||||
include_stock: true,
|
||||
include_competitor: true,
|
||||
basis: basis,
|
||||
sale_markup: saleUplift > 0 ? saleUplift : null,
|
||||
manual_price: manualPrice > 0 ? manualPrice : null,
|
||||
}),
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
if (!resp.ok) { showToast('Ошибка экспорта', 'error'); return; }
|
||||
const blob = await resp.blob();
|
||||
|
||||
@@ -178,7 +178,7 @@
|
||||
<label class="flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input type="radio" name="export-basis" value="ddp" class="border-gray-300">
|
||||
<span class="font-medium">DDP</span>
|
||||
<span class="text-gray-400">— Цена продажи ×1,3</span>
|
||||
<span class="text-gray-400">— Цена продажи</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
@@ -321,6 +321,20 @@
|
||||
</label>
|
||||
<div class="text-xs text-gray-500 mt-1">Добавляет вкладку «Аренда» (расчёт стоимости платного тестирования/аренды) на конфигурациях этого проекта.</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="flex items-center space-x-2">
|
||||
<input type="checkbox" id="project-settings-show-stock-prices" class="rounded border-gray-300" onchange="applyStockSettingsGating()">
|
||||
<span class="text-sm font-medium text-gray-700">Складские цены</span>
|
||||
</label>
|
||||
<div class="text-xs text-gray-500 mt-1">Показывает складские (Stock) цены во всех ценовых интерфейсах конфигураций этого проекта, включая экспорты CSV.</div>
|
||||
</div>
|
||||
<div id="project-settings-only-in-stock-wrap">
|
||||
<label class="flex items-center space-x-2">
|
||||
<input type="checkbox" id="project-settings-only-in-stock" class="rounded border-gray-300">
|
||||
<span class="text-sm font-medium text-gray-700">Только наличие</span>
|
||||
</label>
|
||||
<div class="text-xs text-gray-500 mt-1">При добавлении компонентов предлагает только позиции, доступные на складе. Активно только вместе со «Складские цены».</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end space-x-3 mt-6">
|
||||
<button onclick="closeProjectSettingsModal()" class="px-4 py-2 text-gray-600 hover:text-gray-800">Отмена</button>
|
||||
@@ -667,8 +681,8 @@ function closeVariantActionModal() {
|
||||
|
||||
function findUniqueVariantActionName(baseName, targetCode, excludeProjectUUID) {
|
||||
const cleanedBase = (baseName || '').trim();
|
||||
if (!cleanedBase || normalizeVariantLabel(cleanedBase).toLowerCase() === 'main') {
|
||||
return {error: 'Имя варианта не должно быть пустым и не может быть main'};
|
||||
if (!cleanedBase) {
|
||||
return {error: 'Имя варианта не должно быть пустым'};
|
||||
}
|
||||
|
||||
const code = (targetCode || '').trim();
|
||||
@@ -791,10 +805,6 @@ async function saveVariantAction() {
|
||||
})
|
||||
});
|
||||
if (!createResp.ok) {
|
||||
if (createResp.status === 400) {
|
||||
notify('Имя варианта не может быть main', 'error');
|
||||
return;
|
||||
}
|
||||
if (createResp.status === 409) {
|
||||
notify('Вариант с таким кодом и значением уже существует', 'error');
|
||||
return;
|
||||
@@ -815,7 +825,7 @@ async function saveVariantAction() {
|
||||
return;
|
||||
}
|
||||
closeVariantActionModal();
|
||||
notify('Копия варианта создана', 'success');
|
||||
notify(created.variant_warning ? 'Копия варианта создана. ' + created.variant_warning : 'Копия варианта создана', 'success');
|
||||
window.location.href = '/projects/' + created.uuid;
|
||||
return;
|
||||
}
|
||||
@@ -832,10 +842,6 @@ async function saveVariantAction() {
|
||||
body: JSON.stringify({code: code, variant: name})
|
||||
});
|
||||
if (!updateResp.ok) {
|
||||
if (updateResp.status === 400) {
|
||||
notify('Имя варианта не может быть main', 'error');
|
||||
return;
|
||||
}
|
||||
if (updateResp.status === 409) {
|
||||
notify('Вариант с таким кодом и значением уже существует', 'error');
|
||||
return;
|
||||
@@ -843,12 +849,13 @@ async function saveVariantAction() {
|
||||
notify('Не удалось сохранить вариант', 'error');
|
||||
return;
|
||||
}
|
||||
const updated = await updateResp.json().catch(() => null);
|
||||
|
||||
closeVariantActionModal();
|
||||
await loadProject();
|
||||
await loadConfigs();
|
||||
updateDeleteVariantButton();
|
||||
notify('Вариант обновлён', 'success');
|
||||
notify(updated && updated.variant_warning ? 'Вариант обновлён. ' + updated.variant_warning : 'Вариант обновлён', 'success');
|
||||
}
|
||||
|
||||
async function createNewVariant() {
|
||||
@@ -860,10 +867,6 @@ async function createNewVariant() {
|
||||
showToast('Укажите вариант', 'error');
|
||||
return;
|
||||
}
|
||||
if (!/^[A-Za-z0-9._-]+$/.test(variant)) {
|
||||
showToast('Имя варианта содержит недопустимые символы. Разрешены: буквы, цифры, дефис, точка, подчёркивание.', 'error');
|
||||
return;
|
||||
}
|
||||
const payload = {
|
||||
code: code,
|
||||
variant: variant,
|
||||
@@ -881,7 +884,11 @@ async function createNewVariant() {
|
||||
}
|
||||
const created = await resp.json().catch(() => null);
|
||||
closeNewVariantModal();
|
||||
showToast('Вариант создан', 'success');
|
||||
if (created && created.variant_warning) {
|
||||
showToast('Вариант создан. ' + created.variant_warning, 'info');
|
||||
} else {
|
||||
showToast('Вариант создан', 'success');
|
||||
}
|
||||
if (created && created.uuid) {
|
||||
window.location.href = '/projects/' + created.uuid;
|
||||
return;
|
||||
@@ -1261,10 +1268,24 @@ function openProjectSettingsModal() {
|
||||
document.getElementById('project-settings-name').value = project.name || '';
|
||||
document.getElementById('project-settings-tracker-url').value = (project.tracker_url || '').trim();
|
||||
document.getElementById('project-settings-rental-enabled').checked = !!project.rental_enabled;
|
||||
document.getElementById('project-settings-show-stock-prices').checked = !!project.show_stock_prices;
|
||||
document.getElementById('project-settings-only-in-stock').checked = !!project.only_in_stock;
|
||||
applyStockSettingsGating();
|
||||
document.getElementById('project-settings-modal').classList.remove('hidden');
|
||||
document.getElementById('project-settings-modal').classList.add('flex');
|
||||
}
|
||||
|
||||
function applyStockSettingsGating() {
|
||||
const showStockPrices = document.getElementById('project-settings-show-stock-prices').checked;
|
||||
const onlyInStock = document.getElementById('project-settings-only-in-stock');
|
||||
const wrap = document.getElementById('project-settings-only-in-stock-wrap');
|
||||
onlyInStock.disabled = !showStockPrices;
|
||||
if (!showStockPrices) {
|
||||
onlyInStock.checked = false;
|
||||
}
|
||||
wrap.classList.toggle('opacity-50', !showStockPrices);
|
||||
}
|
||||
|
||||
function closeProjectSettingsModal() {
|
||||
document.getElementById('project-settings-modal').classList.add('hidden');
|
||||
document.getElementById('project-settings-modal').classList.remove('flex');
|
||||
@@ -1277,6 +1298,8 @@ async function saveProjectSettings() {
|
||||
const name = document.getElementById('project-settings-name').value.trim();
|
||||
const trackerURL = document.getElementById('project-settings-tracker-url').value.trim();
|
||||
const rentalEnabled = document.getElementById('project-settings-rental-enabled').checked;
|
||||
const showStockPrices = document.getElementById('project-settings-show-stock-prices').checked;
|
||||
const onlyInStock = document.getElementById('project-settings-only-in-stock').checked;
|
||||
if (!code) {
|
||||
alert('Введите код проекта');
|
||||
return;
|
||||
@@ -1284,7 +1307,7 @@ async function saveProjectSettings() {
|
||||
const resp = await fetch('/api/projects/' + projectUUID, {
|
||||
method: 'PUT',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({code: code, variant: variant, name: name, tracker_url: trackerURL, rental_enabled: rentalEnabled})
|
||||
body: JSON.stringify({code: code, variant: variant, name: name, tracker_url: trackerURL, rental_enabled: rentalEnabled, show_stock_prices: showStockPrices, only_in_stock: onlyInStock})
|
||||
});
|
||||
if (!resp.ok) {
|
||||
if (resp.status === 409) {
|
||||
@@ -1521,6 +1544,12 @@ function openExportModal() {
|
||||
const modal = document.getElementById('project-export-modal');
|
||||
if (!modal) return;
|
||||
setProjectExportStatus('', '');
|
||||
const stockCheckbox = document.getElementById('export-col-stock');
|
||||
const showStockPrices = !!(project && project.show_stock_prices);
|
||||
stockCheckbox.disabled = !showStockPrices;
|
||||
if (!showStockPrices) {
|
||||
stockCheckbox.checked = false;
|
||||
}
|
||||
modal.classList.remove('hidden');
|
||||
modal.classList.add('flex');
|
||||
}
|
||||
|
||||
@@ -406,10 +406,6 @@ async function createProject() {
|
||||
alert('Код проекта содержит недопустимые символы.\nРазрешены: буквы, цифры, дефис, точка, подчёркивание.');
|
||||
return;
|
||||
}
|
||||
if (variant && !/^[A-Za-z0-9._-]+$/.test(variant)) {
|
||||
alert('Имя варианта содержит недопустимые символы.\nРазрешены: буквы, цифры, дефис, точка, подчёркивание.');
|
||||
return;
|
||||
}
|
||||
const resp = await fetch('/api/projects', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
@@ -433,7 +429,11 @@ async function createProject() {
|
||||
alert('Не удалось создать проект');
|
||||
return;
|
||||
}
|
||||
const created = await resp.json().catch(() => null);
|
||||
closeCreateProjectModal();
|
||||
if (created && created.variant_warning) {
|
||||
alert(created.variant_warning);
|
||||
}
|
||||
loadProjects();
|
||||
}
|
||||
|
||||
@@ -511,6 +511,9 @@ async function copyProject(projectUUID, projectName) {
|
||||
return;
|
||||
}
|
||||
const newProject = await createResp.json();
|
||||
if (newProject.variant_warning) {
|
||||
alert(newProject.variant_warning);
|
||||
}
|
||||
|
||||
const listResp = await fetch('/api/projects/' + projectUUID + '/configs');
|
||||
if (!listResp.ok) {
|
||||
|
||||
+104
-24
@@ -4,26 +4,39 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>OFS - Настройка подключения</title>
|
||||
<title>QuoteForge — Настройки</title>
|
||||
<link rel="stylesheet" href="/static/app.css">
|
||||
<script src="/static/vendor/tailwindcss.browser.js"></script>
|
||||
</head>
|
||||
<body class="bg-gray-100 min-h-screen flex items-center justify-center">
|
||||
<div class="max-w-md w-full mx-4">
|
||||
<div class="bg-white rounded-lg shadow-lg p-8">
|
||||
<div class="text-center mb-8">
|
||||
<h1 class="text-2xl font-bold text-blue-600">QuoteForge</h1>
|
||||
<p class="text-gray-600 mt-2">Настройка подключения к базе данных</p>
|
||||
</div>
|
||||
|
||||
<div class="bg-amber-50 border border-amber-300 rounded-md p-3 mb-4 flex items-start gap-2">
|
||||
<svg class="w-5 h-5 text-amber-500 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
|
||||
<body class="bg-gray-100 min-h-screen">
|
||||
<div class="max-w-4xl w-full mx-auto px-4 py-10">
|
||||
{{if .Settings}}
|
||||
<div class="mb-4">
|
||||
<a href="/" class="inline-flex items-center gap-1.5 text-sm text-blue-600 hover:text-blue-800">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/>
|
||||
</svg>
|
||||
<p class="text-sm text-amber-800"><span class="font-semibold">Важно:</span> не закрывайте консольное окно приложения — без него программа не работает.</p>
|
||||
</div>
|
||||
Вернуться в приложение
|
||||
</a>
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="text-center mb-6">
|
||||
<h1 class="text-2xl font-bold text-blue-600">QuoteForge</h1>
|
||||
<p class="text-gray-600 mt-1">Настройки</p>
|
||||
</div>
|
||||
|
||||
<form id="setup-form" class="space-y-4">
|
||||
<div class="bg-amber-50 border border-amber-300 rounded-md p-3 mb-6 flex items-start gap-2">
|
||||
<svg class="w-5 h-5 text-amber-500 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
|
||||
</svg>
|
||||
<p class="text-sm text-amber-800"><span class="font-semibold">Важно:</span> не закрывайте консольное окно приложения — без него программа не работает.</p>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-6 md:grid-cols-2">
|
||||
<div class="bg-white rounded-lg shadow-lg p-6 flex flex-col">
|
||||
<h2 class="text-lg font-semibold text-gray-800 mb-4">Подключение к базе данных</h2>
|
||||
|
||||
<form id="setup-form" class="space-y-4 flex flex-col flex-1">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Хост сервера</label>
|
||||
<input type="text" name="host" id="host"
|
||||
@@ -68,13 +81,7 @@
|
||||
|
||||
<div id="status" class="hidden p-3 rounded-md text-sm"></div>
|
||||
|
||||
<div class="flex space-x-3 pt-4">
|
||||
{{if .Settings}}
|
||||
<a href="/"
|
||||
class="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition text-center">
|
||||
Назад
|
||||
</a>
|
||||
{{end}}
|
||||
<div class="flex space-x-3 pt-4 mt-auto">
|
||||
<button type="button" onclick="testConnection()"
|
||||
class="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition">
|
||||
Проверить
|
||||
@@ -87,8 +94,56 @@
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<p class="text-center text-gray-500 text-sm mt-4">
|
||||
QuoteForge v1.0 - Конфигуратор серверов
|
||||
<div class="bg-white rounded-lg shadow-lg p-6 flex flex-col">
|
||||
<h2 class="text-lg font-semibold text-gray-800">Индикаторы</h2>
|
||||
<p class="text-sm text-gray-600 mt-1 mb-4">
|
||||
Часть подсказок в интерфейсе передаётся только цветом: качество цены в спецификации
|
||||
и на вкладке «Ценообразование», цены-заглушки, неполные итоги. Выберите режим без
|
||||
цветовой кодировки, если цвета трудно различать.
|
||||
</p>
|
||||
|
||||
<div class="space-y-3">
|
||||
<label class="flex items-start gap-3 p-3 border border-gray-200 rounded-md cursor-pointer hover:bg-gray-50">
|
||||
<input type="radio" name="indicator-mode" value="color" class="mt-1"
|
||||
{{if ne .IndicatorMode "accessible"}}checked{{end}}>
|
||||
<span class="flex-1">
|
||||
<span class="block text-sm font-medium text-gray-800">Цветовая индикация</span>
|
||||
<span class="block text-xs text-gray-500 mt-0.5">Шкала «красный → жёлтый → зелёный», подсветка ячеек.</span>
|
||||
<span class="inline-flex items-center gap-1.5 mt-2">
|
||||
<span class="inline-block w-2 h-2 rounded-full" style="background-color:rgb(220,38,38)"></span>
|
||||
<span class="inline-block w-2 h-2 rounded-full" style="background-color:rgb(234,179,8)"></span>
|
||||
<span class="inline-block w-2 h-2 rounded-full" style="background-color:rgb(22,163,74)"></span>
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label class="flex items-start gap-3 p-3 border border-gray-200 rounded-md cursor-pointer hover:bg-gray-50">
|
||||
<input type="radio" name="indicator-mode" value="accessible" class="mt-1"
|
||||
{{if eq .IndicatorMode "accessible"}}checked{{end}}>
|
||||
<span class="flex-1">
|
||||
<span class="block text-sm font-medium text-gray-800">Без цветовой кодировки</span>
|
||||
<span class="block text-xs text-gray-500 mt-0.5">Значок-«сигнал» из 5 столбиков и текстовые пометки вместо цвета.</span>
|
||||
<span class="inline-flex items-end gap-2 mt-2">
|
||||
<span class="qf-quality-meter"><i></i><i></i><i></i><i></i><i></i></span>
|
||||
<span class="qf-quality-meter"><i class="on"></i><i class="on"></i><i></i><i></i><i></i></span>
|
||||
<span class="qf-quality-meter"><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i></span>
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="mt-auto pt-4">
|
||||
<div id="indicator-status" class="hidden mb-3 p-2 rounded-md text-sm"></div>
|
||||
<button type="button" onclick="saveIndicatorMode()"
|
||||
class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition">
|
||||
Сохранить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="text-center text-gray-500 text-sm mt-8">
|
||||
QuoteForge {{.AppVersion}} — Конфигуратор серверов
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -159,6 +214,31 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function saveIndicatorMode() {
|
||||
const mode = document.querySelector('input[name="indicator-mode"]:checked')?.value || 'color';
|
||||
const box = document.getElementById('indicator-status');
|
||||
box.className = 'mb-3 p-2 rounded-md text-sm bg-blue-100 text-blue-800';
|
||||
box.textContent = 'Сохранение...';
|
||||
try {
|
||||
const resp = await fetch('/api/settings/ui', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ indicator_mode: mode }),
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (resp.ok) {
|
||||
box.className = 'mb-3 p-2 rounded-md text-sm bg-green-100 text-green-800';
|
||||
box.textContent = '✓ Сохранено. Изменения появятся при следующем открытии страниц.';
|
||||
} else {
|
||||
box.className = 'mb-3 p-2 rounded-md text-sm bg-red-100 text-red-800';
|
||||
box.textContent = data.error || 'Не удалось сохранить';
|
||||
}
|
||||
} catch (e) {
|
||||
box.className = 'mb-3 p-2 rounded-md text-sm bg-red-100 text-red-800';
|
||||
box.textContent = 'Ошибка сети: ' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
async function checkServerReady() {
|
||||
let attempts = 0;
|
||||
const maxAttempts = 30; // 30 seconds max
|
||||
|
||||
Reference in new issue
Block a user