Compare commits

..
13 Commits
Author SHA1 Message Date
Mikhail ChusavitinandClaude Sonnet 5 4d7b0e13ef refactor: устранить дублирование кода (Go-хендлеры, JS-автокомплит)
Найдено статическим анализом (dupl/jscpd) + проверено вручную:

Go:
- appstate/path.go: ResolveDBPath/ResolveConfigPath → общий resolvePath()
- handlers/respond.go: дженерик BindJSON[T] для bind+422-ошибки
- article/generator.go: buildNetSegment/buildPSUSegment → buildProfileSegment()
- cmd/qfs/main.go (+respond.go): 8 повторяющихся switch{case errors.Is(...)}
  → respondByErrCase(c, err, errCase{...}, ...)

Frontend (index.html):
- 5 идентичных обработчиков клавиатурной навигации автокомплита
  → handleAutocompleteKeyGeneric(event, onSelect)
- 4 функции сборки нового элемента корзины из автокомплита
  → buildNewCartItem()/commitCartChange()

Также: PricingMarkup — единая точка правды для аплифт-коэффициента
в JS (render + export), с cross-reference комментариями к Go-константам
в export.go (defaultSaleMarkup/stockCompetitorMarkupFactor).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-10 20:13:27 +03:00
Mikhail ChusavitinandClaude Sonnet 5 b087b7eb58 fix: CSV-экспорт Estimate игнорировал аплифт, всегда x1.3
Фронтенд не отправлял значение поля "Аплифт к estimate" в запрос
экспорта, из-за чего бэкенд всегда падал на дефолт 1.3. Кроме того,
applyDDPMarkup применял один и тот же коэффициент к Estimate, Склад
и Конкуренты — теперь Склад/Конкуренты всегда x1.3, а Estimate — по
пользовательскому аплифту.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-10 18:41:29 +03:00
Mikhail ChusavitinandClaude Sonnet 5 34cee5f874 docs: release notes v3.33
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 18:21:57 +03:00
Mikhail ChusavitinandClaude Sonnet 5 a321dab448 fix: третье место самоотравления ASSIGNED_CATEGORIES + сведение в одну функцию
applyConfigTypeToTabs() тоже пересобирал ASSIGNED_CATEGORIES из всех
вкладок, включая "other", и вызывался прямо внутри applyServerSettings —
из-за этого предыдущий фикс (два других места) перезатирался сразу же,
и SYS всё ещё не появлялся во вкладке «Прочее».

Свёл все 4 места пересчёта ASSIGNED_CATEGORIES в одну функцию
computeAssignedCategories(), которая по определению исключает "other" —
это устраняет класс бага целиком, а не по одному вхождению.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 18:21:09 +03:00
Mikhail ChusavitinandClaude Sonnet 5 dd70b6065b fix: не терять новые категории (SYS) на вкладке «Прочее»
ASSIGNED_CATEGORIES пересчитывался из всех вкладок TAB_CONFIG уже после
того, как неизвестные категории попадали в TAB_CONFIG.other — из-за
этого они сами себя исключали из фильтра "not assigned" на вкладке
«Прочее». Баг был в двух местах (loadCategoriesFromAPI и
applyServerSettings), второе не проявлялось только потому, что синк
qt_settings с сервера никогда не был подключён к воркеру.

Заодно подключил Service.SyncQtSettings к фоновому синку (был мёртвым
кодом), чтобы tab_config/config_types и т.п. реально доезжали с сервера
до локального кеша.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 18:14:46 +03:00
Mikhail ChusavitinandClaude Sonnet 5 e5aa1dfd38 fix: детерминированная сортировка при пагинации ListAll конфигов
Order by created_at DESC без вторичного ключа мог давать нестабильный
tie-break при OFFSET/LIMIT, из-за чего строки с одинаковым created_at
выпадали между страницами при импорте server→local (6 конфигов не
попадали в local_configurations).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 15:45:37 +03:00
Mikhail ChusavitinandClaude Opus 4.8 bc17c18943 docs: записать решения по итогам ценообразования и индексу decisions
Смысл красной подсветки итогов сменился с «цены есть не для всех
позиций» на «часть суммы посчитана по ценам-заглушкам world» —
оформлено отдельной записью в decision log. Журнал решений добавлен
в оглавление bible-local.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 17:16:36 +03:00
Mikhail ChusavitinandClaude Opus 4.8 97629a1441 docs: уточнить release notes v3.32 по красной подсветке итогов
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 17:14:03 +03:00
Mikhail ChusavitinandClaude Opus 4.8 513faaf9a4 fix: красный итог на вкладке «Ценообразование» только при подстановке из world
Красный цвет суммы означает, что она частично посчитана по ценам-заглушкам
из прайслиста world. Если подстановок не было, сумма показывается обычным
цветом; попап с пояснением остаётся в обоих случаях.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 17:11:55 +03:00
Mikhail ChusavitinandClaude Opus 4.8 0cd747c4b6 docs: release notes v3.32
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 17:09:38 +03:00
Mikhail ChusavitinandClaude Opus 4.8 905f9a4952 feat: PN code в импорте BOM, объединённый список LOT (world ∪ estimate)
Колонка «PN code» в таблице импорта BOM: HPE-спецификации хранят партномер
в двух столбцах, канонический вид — P52534-B21#B19. Склейка попадает
в vendor_partnumber и сравнивается с книгой партномеров как есть; при
загрузке разбирается обратно на две колонки. Схему БД менять не пришлось.

Список допустимых LOT собирается из world ∪ estimate (componentUniverse),
а не только из estimate. Прежняя область видимости молча теряла
lot_mappings: резолвер сопоставлял PN по книге, которая про прайслисты
не знает, а фронт отбрасывал LOT, которого нет в estimate — при этом
в корзину он всё равно попадал. World-only позиции отдают price_quality 0.

Кнопка «Пересопоставить» — перерешать BOM по актуальной книге, так как
при открытии конфигурации сопоставления остаются замороженными.

Итоги на вкладке «Ценообразование»: звёздочки убраны (переносились
на новую строку), все три суммы красные, при наведении — попап с долей
цен из прайслиста WORLD. Колонка «PN вендора» больше не переносится.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 17:01:31 +03:00
Mikhail ChusavitinandClaude Sonnet 5 0fa7b0b1b6 fix: индикатор качества цены во всех таблицах конфигуратора; убраны заголовки колонки
price_quality теперь показывается не только на вкладке Base (renderTab),
но и на остальных вкладках конфигуратора (renderMultiSelectTab,
renderMultiSelectTabWithSections) — раньше индикатор был виден только
в выпадающем списке поиска. Колонка-индикатор везде без текстового
заголовка (только тултип), включая колонку «Качество» в прайслисте.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 09:44:04 +03:00
Mikhail ChusavitinandClaude Sonnet 5 702b459fc0 docs: release notes v3.31
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 19:10:50 +03:00
24 changed files with 923 additions and 459 deletions

No files matched your search

+1 -1
View File
@@ -261,7 +261,7 @@ 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`, still scoped to the currently selected pricelist. 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 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).
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.
+27
View File
@@ -25,6 +25,33 @@ Rules:
- QuoteForge does not use legacy BOM tables;
- apply flow rebuilds cart rows from `lot_mappings[]`.
## Split partnumbers (HPE option codes)
HPE specs carry the partnumber in two columns: base PN plus an option code
(`P52534-B21` + `B19`). The canonical partnumber is the concatenation
`P52534-B21#B19`, and it is what gets compared against the partnumber book.
Rules:
- the import grid has a `PN code` column type in addition to `P/N`; it is optional
and at most one column may carry it;
- an empty code cell keeps the bare PN — no trailing `#`;
- the composed value is stored in `vendor_partnumber`. There is **no separate
`pn_code` field**: no DDL and no new JSON key, and the stored string is exactly
the string the resolver looks up;
- the column layout of the import grid is not persisted. On load the grid is
re-derived from `vendor_spec`, and the `PN code` column reappears only when at
least one stored partnumber contains `#`, split on the first `#`.
## Re-resolving an existing BOM
Opening a configuration does **not** re-resolve its BOM: `loadVendorSpec` renders the
`lot_mappings[]` frozen at save time, so a configuration keeps the mapping it was
saved with even after the partnumber book changes.
Book entries added later are picked up only through the `Пересопоставить` button,
which calls the resolve endpoint for every row. Book matches win over the stored
mapping (resolver step 1 beats step 2); rows the book does not know keep theirs.
## Partnumber books
Partnumber books are pull-only snapshots from PriceForge.
+1
View File
@@ -16,6 +16,7 @@ Project-specific architecture and operational contracts.
| [09-vendor-spec.md](09-vendor-spec.md) | Vendor BOM and CFXML import contract |
| [10-agent-api-guide.md](10-agent-api-guide.md) | End-to-end API guide for agents pricing servers from a TZ |
| [11-lot-suggestions.md](11-lot-suggestions.md) | lot_suggestion column in qt_vendor_partnumber_seen — write/read contract for manual UI mappings |
| [decisions/](decisions/README.md) | Architectural decision log, one file per decision |
## Rules
@@ -43,3 +43,7 @@ is missing or ≤ 0:
"latest active `world` pricelist," not a per-configuration pin.
- If no `world` pricelist exists locally, behavior is unchanged (missing prices stay "—",
no error).
- How the footer totals surface this fallback is decided separately in
[2026-07-24-pricing-total-world-share.md](2026-07-24-pricing-total-world-share.md);
membership of world LOTs in the configurator's LOT set is decided in
[2026-07-24-component-universe-world-union.md](2026-07-24-component-universe-world-union.md).
@@ -0,0 +1,57 @@
# Decision: the component universe is `world` ∪ `estimate`, not `estimate` alone
**Date:** 2026-07-24
**Status:** active
## Context
Every component read path in `internal/localdb/components.go` was scoped to the latest
active `estimate` pricelist. That pricelist is therefore what defined the set of LOTs the
configurator considers to exist, and the frontend used it as its validation list
(`_bomLotValid` in `index.html`, fed by `/api/components`).
That silently broke BOM mappings. The resolver matches a vendor partnumber against the
partnumber book, which knows nothing about pricelists, so it legitimately returns LOTs the
estimate pricelist does not carry. The frontend then displayed such a row as mapped —
`_getRowBaseLot` does not validate `resolved_lot` — and `applyBOMToEstimate` pushed the LOT
into the cart, but `_getRowCanonicalLotMappings` filtered it out through `_bomLotValid`, so
the mapping vanished on save. Result: the LOT sat in the cart while its BOM row showed
"н/д", and the pricing tab listed it at the bottom as an orphan with an empty vendor PN.
Prices for such LOTs were already available — see
[2026-07-10-world-pricelist-fallback.md](2026-07-10-world-pricelist-fallback.md) — only
membership was missing.
## Decision
`componentUniverse()` in `internal/localdb/components.go` is the single source of the LOT
set, and every component read path goes through it: `ListComponents`,
`SearchLocalComponents`, `SearchLocalComponentsByCategory`, `GetLocalComponent`,
`GetLocalComponentCategories`, `GetLocalComponentCategoriesByLotNames`, `CountComponents`.
- The universe is the latest active `world` pricelist — the widest list available — plus
the latest active `estimate` pricelist as a safety net.
- Deduplication is on `UPPER(lot_name)`. The estimate row wins a collision, so its
category, description and `price_quality` stay authoritative and nothing changes for
LOTs that were already visible.
- A world-only row reports `price_quality = 0`, rendering at the red end of the shared
scale in `web/static/price-quality.js`. This is the **one** place QF sets that field
instead of only reading it (contrast `bible-local/03-database.md`), and it deliberately
overrides whatever the external pricing tool wrote on the world row.
- The helper always returns a derived table (`(?) AS c`), so callers apply their own
`Select`/`Count`/`Where` without knowing which pricelists exist.
- Either pricelist may be absent; only both missing is an error.
On the frontend, `_bomLotPersistable` additionally lets a LOT with
`resolution_source === 'book'` be persisted into `lot_mappings[]` even when it is in
neither pricelist. Hand-typed LOTs stay validated against the universe.
## Consequences
- The configurator's pickers, category list and search now surface world-only LOTs. They
are selectable and appear in the reddest quality colour.
- `CountComponents` — the "is there data" check — counts the union.
- A LOT present in neither pricelist (nothing to price it with) still resolves from the
book and now survives a save, instead of being dropped without a message.
- Covered by `internal/localdb/component_universe_test.go`: union and dedup, estimate
winning a collision, forced quality 0, and each single-source / empty case.
@@ -0,0 +1,47 @@
# Decision: pricing totals signal the world-fallback share, not row coverage
**Date:** 2026-07-24
**Status:** active
## Context
The footer totals of both "Ценообразование" tables used to mean one thing: a red number
with a trailing `*` said "prices are missing for some positions (N of M)". Two problems:
- the asterisk was a separate `<span>` after the number and wrapped onto its own line,
pushing the footer layout around;
- coverage was the wrong thing to warn about. Since
[2026-07-10-world-pricelist-fallback.md](2026-07-10-world-pricelist-fallback.md) a
missing price is silently filled from the `world` pricelist, so the total is rarely
incomplete — it is *contaminated*. A sum resting on world stand-in prices looked exactly
like a sum of real ones.
## Decision
`_setPricingTotal` in `web/templates/index.html` renders every footer total for Estimate,
Склад and Конкуренты in both tables (buy and sale):
- No asterisk, ever. The number stands alone.
- The total is red **if and only if** part of it was computed from `world` prices — that
is, `worldTotal > 0`. A clean sum is not coloured. Red is a contamination signal, not a
coverage signal.
- The world share per column is accumulated from the same per-row flags that tint the
cells amber (`estWorld` / `whWorld` / `compWorld`), summed over line totals, not unit
prices.
- Hovering the total opens a styled popup (`.pricing-total-tip` in `web/static/app.css`),
not a `title=` tooltip — the native one appears too late to notice on a number the user
is meant to distrust. It states the exact percentage and, when prices are genuinely
missing for some rows, adds the coverage line that the asterisk used to carry.
- "Ручная цена" is not part of this: it is user input, never world-derived.
## Consequences
- Red in the pricing footer means "part of this sum is a stand-in price", nothing else.
Do not reuse it for coverage, staleness or any other condition.
- The colour and popup classes are re-applied on every render and stripped first, so they
never accumulate across re-renders.
- The totals are written with `innerHTML` (number plus popup element). Nothing may read
`textContent` off `#pricing-total-*-estimate|warehouse|competitor`; the vendor-price
column and row `data-` attributes remain the read path for `applyCustomPrice` and
`_getPricingEstimateTotal`.
- The old `_setPartialTotal` helper is gone; do not reintroduce a coverage-only signal.
+52 -99
View File
@@ -1101,16 +1101,11 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
config, err := configService.UpdateNoAuth(uuid, &req)
if err != nil {
switch {
case errors.Is(err, services.ErrConfigNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
@@ -1217,16 +1212,11 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
}
updated, err := configService.SetProjectNoAuth(uuid, req.ProjectUUID)
if err != nil {
switch {
case errors.Is(err, services.ErrConfigNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, updated)
@@ -1354,12 +1344,9 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
}
config, err := configService.UpdateRentalNoAuth(c.Param("uuid"), &req)
if err != nil {
switch {
case errors.Is(err, services.ErrConfigNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
)
return
}
c.JSON(http.StatusOK, config)
@@ -1373,12 +1360,9 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
}
result, err := rentalService.Calculate(c.Param("uuid"), &req)
if err != nil {
switch {
case errors.Is(err, services.ErrConfigNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
)
return
}
c.JSON(http.StatusOK, result)
@@ -1627,16 +1611,12 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
}
project, err := projectService.Create(dbUsername, &req)
if err != nil {
switch {
case errors.Is(err, services.ErrReservedMainVariant),
errors.Is(err, services.ErrProjectCodeInvalidChars),
errors.Is(err, services.ErrProjectVariantInvalidChars):
respondError(c, http.StatusBadRequest, "invalid request", err)
case errors.Is(err, services.ErrProjectCodeExists):
respondError(c, http.StatusConflict, "conflict detected", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
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)
@@ -1645,14 +1625,10 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
projects.GET("/:uuid", func(c *gin.Context) {
project, err := projectService.GetByUUID(c.Param("uuid"), dbUsername)
if err != nil {
switch {
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, project)
@@ -1666,21 +1642,15 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
}
project, err := projectService.Update(c.Param("uuid"), dbUsername, &req)
if err != nil {
switch {
case errors.Is(err, services.ErrReservedMainVariant),
errors.Is(err, services.ErrCannotRenameMainVariant),
errors.Is(err, services.ErrProjectCodeInvalidChars),
errors.Is(err, services.ErrProjectVariantInvalidChars):
respondError(c, http.StatusBadRequest, "invalid request", err)
case errors.Is(err, services.ErrProjectCodeExists):
respondError(c, http.StatusConflict, "conflict detected", err)
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
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)
@@ -1688,14 +1658,10 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
projects.POST("/:uuid/archive", func(c *gin.Context) {
if err := projectService.Archive(c.Param("uuid"), dbUsername); err != nil {
switch {
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, gin.H{"message": "project archived"})
@@ -1703,14 +1669,10 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
projects.POST("/:uuid/reactivate", func(c *gin.Context) {
if err := projectService.Reactivate(c.Param("uuid"), dbUsername); err != nil {
switch {
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, gin.H{"message": "project reactivated"})
@@ -1718,16 +1680,11 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
projects.DELETE("/:uuid", func(c *gin.Context) {
if err := projectService.DeleteVariant(c.Param("uuid"), dbUsername); err != nil {
switch {
case errors.Is(err, services.ErrCannotDeleteMainVariant):
respondError(c, http.StatusBadRequest, "invalid request", err)
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrCannotDeleteMainVariant, http.StatusBadRequest, "invalid request"},
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, gin.H{"message": "variant deleted"})
@@ -1744,14 +1701,10 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
result, err := projectService.ListConfigurations(c.Param("uuid"), dbUsername, status)
if err != nil {
switch {
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
+31
View File
@@ -0,0 +1,31 @@
package main
import (
"errors"
"net/http"
"git.mchus.pro/mchus/quoteforge/internal/handlers"
"github.com/gin-gonic/gin"
)
// errCase maps a sentinel error to the HTTP status/message respondByErrCase
// should use when errors.Is matches it.
type errCase struct {
err error
status int
message string
}
// respondByErrCase responds with the status/message of the first matching
// case (checked in order), or a 500 "internal server error" fallback when
// none match. Centralizes the switch-on-sentinel-error pattern repeated
// across the config/project HTTP handlers in this file.
func respondByErrCase(c *gin.Context, err error, cases ...errCase) {
for _, cs := range cases {
if errors.Is(err, cs.err) {
handlers.RespondError(c, cs.status, cs.message, err)
return
}
}
handlers.RespondError(c, http.StatusInternalServerError, "internal server error", err)
}
+9 -16
View File
@@ -21,30 +21,23 @@ const (
// ResolveDBPath returns the local SQLite path using priority:
// explicit CLI path > QFS_DB_PATH > OS-specific user state directory.
func ResolveDBPath(explicitPath string) (string, error) {
if explicitPath != "" {
return filepath.Clean(explicitPath), nil
}
if fromEnv := os.Getenv(envDBPath); fromEnv != "" {
return filepath.Clean(fromEnv), nil
}
dir, err := defaultStateDir()
if err != nil {
return "", err
}
return filepath.Join(dir, defaultDB), nil
return resolvePath(explicitPath, envDBPath, defaultDB)
}
// ResolveConfigPath returns the config path using priority:
// explicit CLI path > QFS_CONFIG_PATH > OS-specific user state directory.
func ResolveConfigPath(explicitPath string) (string, error) {
return resolvePath(explicitPath, envCfgPath, defaultCfg)
}
// resolvePath returns a path using priority: explicit CLI path > envVar > OS-specific
// user state directory joined with defaultFilename.
func resolvePath(explicitPath, envVar, defaultFilename string) (string, error) {
if explicitPath != "" {
return filepath.Clean(explicitPath), nil
}
if fromEnv := os.Getenv(envCfgPath); fromEnv != "" {
if fromEnv := os.Getenv(envVar); fromEnv != "" {
return filepath.Clean(fromEnv), nil
}
@@ -53,7 +46,7 @@ func ResolveConfigPath(explicitPath string) (string, error) {
return "", err
}
return filepath.Join(dir, defaultCfg), nil
return filepath.Join(dir, defaultFilename), nil
}
// ResolveConfigPathNearDB returns config path using priority:
+16 -31
View File
@@ -260,17 +260,28 @@ func buildDiskSegment(items []models.ConfigItem, cats map[string]string) (string
}
func buildNetSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
return buildProfileSegment(items, cats, GroupNET, parsePortSpeed, "UNKNET", "net_unknown")
}
func buildPSUSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
return buildProfileSegment(items, cats, GroupPSU, parseWatts, "UNKPSU", "psu_unknown")
}
// 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) {
groupQty := map[string]int{}
warn := ""
for _, it := range items {
group, ok := GroupForLotCategory(cats[it.LotName])
if !ok || group != GroupNET {
g, ok := GroupForLotCategory(cats[it.LotName])
if !ok || g != group {
continue
}
profile := parsePortSpeed(it.LotName)
profile := parseProfile(it.LotName)
if profile == "" {
profile = "UNKNET"
warn = "net_unknown"
profile = unknownToken
warn = warnCode
}
groupQty[profile] += it.Quantity
}
@@ -285,32 +296,6 @@ func buildNetSegment(items []models.ConfigItem, cats map[string]string) (string,
return strings.Join(parts, "+"), warn
}
func buildPSUSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
groupQty := map[string]int{}
warn := ""
for _, it := range items {
group, ok := GroupForLotCategory(cats[it.LotName])
if !ok || group != GroupPSU {
continue
}
rating := parseWatts(it.LotName)
if rating == "" {
rating = "UNKPSU"
warn = "psu_unknown"
}
groupQty[rating] += it.Quantity
}
if len(groupQty) == 0 {
return "", ""
}
parts := make([]string, 0, len(groupQty))
for rating, qty := range groupQty {
parts = append(parts, fmt.Sprintf("%dx%s", qty, rating))
}
sort.Strings(parts)
return strings.Join(parts, "+"), warn
}
func normalizeModelToken(lotName string) string {
if idx := strings.Index(lotName, "_"); idx >= 0 && idx+1 < len(lotName) {
lotName = lotName[idx+1:]
+9 -12
View File
@@ -16,13 +16,12 @@ func NewQuoteHandler(quoteService *services.QuoteService) *QuoteHandler {
}
func (h *QuoteHandler) Validate(c *gin.Context) {
var req services.QuoteRequest
if err := c.ShouldBindJSON(&req); err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
req, ok := BindJSON[services.QuoteRequest](c)
if !ok {
return
}
result, err := h.quoteService.ValidateAndCalculate(&req)
result, err := h.quoteService.ValidateAndCalculate(req)
if err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
return
@@ -32,13 +31,12 @@ func (h *QuoteHandler) Validate(c *gin.Context) {
}
func (h *QuoteHandler) Calculate(c *gin.Context) {
var req services.QuoteRequest
if err := c.ShouldBindJSON(&req); err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
req, ok := BindJSON[services.QuoteRequest](c)
if !ok {
return
}
result, err := h.quoteService.ValidateAndCalculate(&req)
result, err := h.quoteService.ValidateAndCalculate(req)
if err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
return
@@ -51,13 +49,12 @@ func (h *QuoteHandler) Calculate(c *gin.Context) {
}
func (h *QuoteHandler) PriceLevels(c *gin.Context) {
var req services.PriceLevelsRequest
if err := c.ShouldBindJSON(&req); err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
req, ok := BindJSON[services.PriceLevelsRequest](c)
if !ok {
return
}
result, err := h.quoteService.CalculatePriceLevels(&req)
result, err := h.quoteService.CalculatePriceLevels(req)
if err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
return
+12
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"github.com/gin-gonic/gin"
@@ -16,6 +17,17 @@ func RespondError(c *gin.Context, status int, fallback string, err error) {
c.JSON(status, gin.H{"error": clientFacingErrorMessage(status, fallback, err)})
}
// BindJSON decodes the request body into T, responding with a 422 and writing
// the error via RespondError on failure. The second return value reports success.
func BindJSON[T any](c *gin.Context) (*T, bool) {
var req T
if err := c.ShouldBindJSON(&req); err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
return nil, false
}
return &req, true
}
func clientFacingErrorMessage(status int, fallback string, err error) string {
if err == nil {
return fallback
+176
View File
@@ -0,0 +1,176 @@
package localdb
import (
"path/filepath"
"testing"
"time"
)
// seedUniversePricelist stores one active pricelist of the given source with the
// supplied items and returns its local id.
func seedUniversePricelist(t *testing.T, local *LocalDB, serverID uint, source, version string, created time.Time, items []LocalPricelistItem) uint {
t.Helper()
pl := &LocalPricelist{
ServerID: serverID,
Source: source,
Version: version,
Name: version,
CreatedAt: created,
SyncedAt: created,
IsActive: true,
}
if err := local.SaveLocalPricelist(pl); err != nil {
t.Fatalf("save %s pricelist: %v", source, err)
}
stored, err := local.GetLocalPricelistByServerID(serverID)
if err != nil {
t.Fatalf("load %s pricelist: %v", source, err)
}
for i := range items {
items[i].PricelistID = stored.ID
}
if err := local.SaveLocalPricelistItems(items); err != nil {
t.Fatalf("save %s items: %v", source, err)
}
return stored.ID
}
func quality(v int) *int { return &v }
func newUniverseDB(t *testing.T, name string) *LocalDB {
t.Helper()
local, err := New(filepath.Join(t.TempDir(), name))
if err != nil {
t.Fatalf("open localdb: %v", err)
}
t.Cleanup(func() { _ = local.Close() })
return local
}
// The component universe is world ∪ estimate: a LOT the estimate pricelist does not
// carry must still be selectable, otherwise BOM lot_mappings resolved from the
// partnumber book get silently dropped on save.
func TestComponentUniverseUnionsWorldAndEstimate(t *testing.T) {
local := newUniverseDB(t, "universe_union.db")
base := time.Now().Add(-time.Minute)
seedUniversePricelist(t, local, 1, "estimate", "E-1", base, []LocalPricelistItem{
{LotName: "CPU_A", LotCategory: "CPU", LotDescription: "from estimate", Price: 100, PriceQuality: quality(8)},
{LotName: "SHARED_LOT", LotCategory: "MEM", LotDescription: "from estimate", Price: 50, PriceQuality: quality(9)},
})
seedUniversePricelist(t, local, 2, "world", "W-1", base, []LocalPricelistItem{
{LotName: "SHARED_LOT", LotCategory: "WRONG", LotDescription: "from world", Price: 55, PriceQuality: quality(1)},
{LotName: "NIC_WORLD_ONLY", LotCategory: "NIC", LotDescription: "from world", Price: 70, PriceQuality: quality(7)},
})
components, total, err := local.ListComponents(ComponentFilter{}, 0, 100)
if err != nil {
t.Fatalf("ListComponents: %v", err)
}
if total != 3 {
t.Fatalf("expected 3 components (dedup on SHARED_LOT), got %d", total)
}
byLot := make(map[string]LocalComponent, len(components))
for _, c := range components {
if _, dup := byLot[c.LotName]; dup {
t.Fatalf("duplicate lot in universe: %s", c.LotName)
}
byLot[c.LotName] = c
}
worldOnly, ok := byLot["NIC_WORLD_ONLY"]
if !ok {
t.Fatal("world-only LOT missing from the component universe")
}
if worldOnly.PriceQuality == nil || *worldOnly.PriceQuality != 0 {
t.Fatalf("world-only LOT must report price_quality 0, got %v", worldOnly.PriceQuality)
}
// The estimate row wins a collision, so its metadata stays authoritative.
shared := byLot["SHARED_LOT"]
if shared.Category != "MEM" || shared.LotDescription != "from estimate" {
t.Fatalf("estimate row must win a collision, got category=%q description=%q", shared.Category, shared.LotDescription)
}
if shared.PriceQuality == nil || *shared.PriceQuality != 9 {
t.Fatalf("estimate price_quality must survive a collision, got %v", shared.PriceQuality)
}
if got := local.CountComponents(); got != 3 {
t.Fatalf("CountComponents: expected 3, got %d", got)
}
single, err := local.GetLocalComponent("nic_world_only")
if err != nil {
t.Fatalf("GetLocalComponent for a world-only LOT: %v", err)
}
if single.LotName != "NIC_WORLD_ONLY" {
t.Fatalf("GetLocalComponent returned %q", single.LotName)
}
categories, err := local.GetLocalComponentCategories()
if err != nil {
t.Fatalf("GetLocalComponentCategories: %v", err)
}
if len(categories) != 3 {
t.Fatalf("expected CPU/MEM/NIC, got %v", categories)
}
cats, err := local.GetLocalComponentCategoriesByLotNames([]string{"NIC_WORLD_ONLY", "SHARED_LOT"})
if err != nil {
t.Fatalf("GetLocalComponentCategoriesByLotNames: %v", err)
}
if cats["NIC_WORLD_ONLY"] != "NIC" || cats["SHARED_LOT"] != "MEM" {
t.Fatalf("unexpected categories: %v", cats)
}
found, err := local.SearchLocalComponents("world_only", 10)
if err != nil || len(found) != 1 {
t.Fatalf("SearchLocalComponents: got %d rows, err=%v", len(found), err)
}
inCategory, err := local.SearchLocalComponentsByCategory("NIC", "", 10)
if err != nil || len(inCategory) != 1 {
t.Fatalf("SearchLocalComponentsByCategory: got %d rows, err=%v", len(inCategory), err)
}
}
// Only one of the two pricelists existing must not break the universe.
func TestComponentUniverseWithSingleSource(t *testing.T) {
t.Run("estimate only", func(t *testing.T) {
local := newUniverseDB(t, "universe_estimate_only.db")
seedUniversePricelist(t, local, 1, "estimate", "E-1", time.Now(), []LocalPricelistItem{
{LotName: "CPU_A", LotCategory: "CPU", Price: 100, PriceQuality: quality(8)},
})
if got := local.CountComponents(); got != 1 {
t.Fatalf("expected 1 component, got %d", got)
}
})
t.Run("world only", func(t *testing.T) {
local := newUniverseDB(t, "universe_world_only.db")
seedUniversePricelist(t, local, 2, "world", "W-1", time.Now(), []LocalPricelistItem{
{LotName: "CPU_A", LotCategory: "CPU", Price: 100, PriceQuality: quality(8)},
})
components, _, err := local.ListComponents(ComponentFilter{}, 0, 10)
if err != nil {
t.Fatalf("ListComponents: %v", err)
}
if len(components) != 1 {
t.Fatalf("expected 1 component, got %d", len(components))
}
if components[0].PriceQuality == nil || *components[0].PriceQuality != 0 {
t.Fatalf("world-only LOT must report price_quality 0, got %v", components[0].PriceQuality)
}
})
t.Run("neither", func(t *testing.T) {
local := newUniverseDB(t, "universe_empty.db")
if _, _, err := local.ListComponents(ComponentFilter{}, 0, 10); err == nil {
t.Fatal("expected an error when no estimate and no world pricelist exists")
}
if got := local.CountComponents(); got != 0 {
t.Fatalf("expected 0, got %d", got)
}
})
}
+84 -36
View File
@@ -4,6 +4,8 @@ import (
"fmt"
"strings"
"time"
"gorm.io/gorm"
)
// ComponentFilter for searching with filters
@@ -40,6 +42,60 @@ func (l *LocalDB) latestActivePricelistID(source string) (uint, error) {
return id, nil
}
// componentUniverse returns a query over the set of LOTs the configurator is allowed
// to choose from. That set is the latest active `world` pricelist — the widest list we
// have — plus, as a safety net, the latest active `estimate` pricelist, deduplicated by
// UPPER(lot_name).
//
// Scoping this to `estimate` alone used to silently drop BOM lot_mappings: the resolver
// matches a partnumber against the book, which knows nothing about pricelists, and the
// frontend then rejected any LOT the estimate pricelist did not carry. Prices for
// world-only LOTs already come from the world fallback (see
// decisions/2026-07-10-world-pricelist-fallback.md).
//
// The estimate row wins a collision, so its category/description/price_quality stay
// authoritative. A world-only row reports price_quality 0 so it renders at the red end of
// the quality scale — the one place QF sets this field rather than only reading it.
// Either pricelist may be absent; only both missing is an error.
func (l *LocalDB) componentUniverse() (*gorm.DB, error) {
estimateID, estimateErr := l.latestActivePricelistID("estimate")
worldID, worldErr := l.latestActivePricelistID("world")
if estimateErr != nil && worldErr != nil {
return nil, fmt.Errorf("no active estimate or world pricelist")
}
// Always a derived table, so every caller can apply its own Select/Count/Where
// uniformly and none of them has to know which pricelists actually exist.
const estimateSelect = `
SELECT lot_name, lot_category, lot_description, price_quality
FROM local_pricelist_items
WHERE pricelist_id = ?`
const worldSelect = `
SELECT w.lot_name, w.lot_category, w.lot_description, 0 AS price_quality
FROM local_pricelist_items w
WHERE w.pricelist_id = ?`
const worldOnlyTail = `
AND NOT EXISTS (
SELECT 1 FROM local_pricelist_items e
WHERE e.pricelist_id = ?
AND UPPER(e.lot_name) = UPPER(w.lot_name)
)`
var inner *gorm.DB
switch {
case worldErr != nil:
inner = l.db.Raw(estimateSelect, estimateID)
case estimateErr != nil:
inner = l.db.Raw(worldSelect, worldID)
default:
inner = l.db.Raw(
estimateSelect+"\nUNION ALL"+worldSelect+worldOnlyTail,
estimateID, worldID, estimateID)
}
return l.db.Table("(?) AS c", inner), nil
}
// pricelistItemRow is used for scanning rows from local_pricelist_items.
type pricelistItemRow struct {
LotName string `gorm:"column:lot_name"`
@@ -57,25 +113,23 @@ func (r pricelistItemRow) toLocalComponent() LocalComponent {
}
}
// SearchLocalComponents searches components in the latest active estimate
// pricelist by lot_name.
// SearchLocalComponents searches the component universe by lot_name.
func (l *LocalDB) SearchLocalComponents(query string, limit int) ([]LocalComponent, error) {
if limit <= 0 {
limit = 50
}
pricelistID, err := l.latestActivePricelistID("estimate")
db, err := l.componentUniverse()
if err != nil {
return nil, err
}
db := l.db.Table("local_pricelist_items").
Where("pricelist_id = ?", pricelistID)
if query != "" {
db = db.Where("LOWER(lot_name) LIKE ?", "%"+strings.ToLower(query)+"%")
}
var rows []pricelistItemRow
if err := db.Select("lot_name, lot_category, lot_description, price_quality").Order("lot_name").Limit(limit).Scan(&rows).Error; err != nil {
if err := db.Select("lot_name, lot_category, lot_description, price_quality").
Order("lot_name").Limit(limit).Scan(&rows).Error; err != nil {
return nil, err
}
components := make([]LocalComponent, len(rows))
@@ -85,25 +139,24 @@ func (l *LocalDB) SearchLocalComponents(query string, limit int) ([]LocalCompone
return components, nil
}
// SearchLocalComponentsByCategory searches components in the latest active
// estimate pricelist filtered by category.
// SearchLocalComponentsByCategory searches the component universe filtered by category.
func (l *LocalDB) SearchLocalComponentsByCategory(category, query string, limit int) ([]LocalComponent, error) {
if limit <= 0 {
limit = 50
}
pricelistID, err := l.latestActivePricelistID("estimate")
db, err := l.componentUniverse()
if err != nil {
return nil, err
}
db := l.db.Table("local_pricelist_items").
Where("pricelist_id = ? AND UPPER(lot_category) = ?", pricelistID, strings.ToUpper(category))
db = db.Where("UPPER(lot_category) = ?", strings.ToUpper(category))
if query != "" {
db = db.Where("LOWER(lot_name) LIKE ?", "%"+strings.ToLower(query)+"%")
}
var rows []pricelistItemRow
if err := db.Select("lot_name, lot_category, lot_description, price_quality").Order("lot_name").Limit(limit).Scan(&rows).Error; err != nil {
if err := db.Select("lot_name, lot_category, lot_description, price_quality").
Order("lot_name").Limit(limit).Scan(&rows).Error; err != nil {
return nil, err
}
components := make([]LocalComponent, len(rows))
@@ -113,17 +166,14 @@ func (l *LocalDB) SearchLocalComponentsByCategory(category, query string, limit
return components, nil
}
// ListComponents returns components from the latest active estimate pricelist
// with optional category/search filtering and pagination.
// ListComponents returns components from the component universe with optional
// category/search filtering and pagination.
func (l *LocalDB) ListComponents(filter ComponentFilter, offset, limit int) ([]LocalComponent, int64, error) {
pricelistID, err := l.latestActivePricelistID("estimate")
db, err := l.componentUniverse()
if err != nil {
return nil, 0, err
}
db := l.db.Table("local_pricelist_items").
Where("pricelist_id = ?", pricelistID)
if filter.Category != "" {
db = db.Where("UPPER(lot_category) = ?", strings.ToUpper(filter.Category))
}
@@ -147,18 +197,17 @@ func (l *LocalDB) ListComponents(filter ComponentFilter, offset, limit int) ([]L
return components, total, nil
}
// GetLocalComponent returns a single component by lot_name from the latest
// active estimate pricelist.
// GetLocalComponent returns a single component by lot_name from the component universe.
func (l *LocalDB) GetLocalComponent(lotName string) (*LocalComponent, error) {
pricelistID, err := l.latestActivePricelistID("estimate")
db, err := l.componentUniverse()
if err != nil {
return nil, err
}
var row pricelistItemRow
if err := l.db.Table("local_pricelist_items").
if err := db.
Select("lot_name, lot_category, lot_description, price_quality").
Where("pricelist_id = ? AND UPPER(lot_name) = ?", pricelistID, strings.ToUpper(lotName)).
Where("UPPER(lot_name) = ?", strings.ToUpper(lotName)).
First(&row).Error; err != nil {
return nil, err
}
@@ -167,13 +216,13 @@ func (l *LocalDB) GetLocalComponent(lotName string) (*LocalComponent, error) {
}
// GetLocalComponentCategoriesByLotNames returns category for each lot_name
// from the latest active estimate pricelist.
// from the component universe.
func (l *LocalDB) GetLocalComponentCategoriesByLotNames(lotNames []string) (map[string]string, error) {
result := make(map[string]string, len(lotNames))
if len(lotNames) == 0 {
return result, nil
}
pricelistID, err := l.latestActivePricelistID("estimate")
db, err := l.componentUniverse()
if err != nil {
return result, nil
}
@@ -187,9 +236,9 @@ func (l *LocalDB) GetLocalComponentCategoriesByLotNames(lotNames []string) (map[
upperToOrig[u] = n
}
var rows []pricelistItemRow
if err := l.db.Table("local_pricelist_items").
if err := db.
Select("lot_name, lot_category").
Where("pricelist_id = ? AND UPPER(lot_name) IN ?", pricelistID, upper).
Where("UPPER(lot_name) IN ?", upper).
Scan(&rows).Error; err != nil {
return nil, err
}
@@ -203,17 +252,16 @@ func (l *LocalDB) GetLocalComponentCategoriesByLotNames(lotNames []string) (map[
return result, nil
}
// GetLocalComponentCategories returns distinct categories from the latest
// active estimate pricelist.
// GetLocalComponentCategories returns distinct categories from the component universe.
func (l *LocalDB) GetLocalComponentCategories() ([]string, error) {
pricelistID, err := l.latestActivePricelistID("estimate")
db, err := l.componentUniverse()
if err != nil {
return nil, err
}
var categories []string
if err := l.db.Table("local_pricelist_items").
Where("pricelist_id = ? AND lot_category != ''", pricelistID).
if err := db.
Where("lot_category != ''").
Distinct("lot_category").
Order("lot_category").
Pluck("lot_category", &categories).Error; err != nil {
@@ -222,14 +270,14 @@ func (l *LocalDB) GetLocalComponentCategories() ([]string, error) {
return categories, nil
}
// CountComponents returns the number of distinct lot names in the latest
// active estimate pricelist (used to check if data is available).
// CountComponents returns the number of lot names in the component universe
// (used to check if data is available).
func (l *LocalDB) CountComponents() int64 {
pricelistID, err := l.latestActivePricelistID("estimate")
db, err := l.componentUniverse()
if err != nil {
return 0
}
var count int64
l.db.Table("local_pricelist_items").Where("pricelist_id = ?", pricelistID).Count(&count)
db.Count(&count)
return count
}
+1 -1
View File
@@ -104,7 +104,7 @@ func (r *ConfigurationRepository) ListAll(offset, limit int) ([]models.Configura
r.db.Model(&models.Configuration{}).Count(&total)
err := r.db.
Order("created_at DESC").
Order("created_at DESC, id DESC").
Offset(offset).
Limit(limit).
Find(&configs).Error
+16 -6
View File
@@ -59,15 +59,20 @@ type ProjectPricingExportOptions struct {
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 multiplier; 0 defaults to 1.3
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
}
// defaultSaleMarkup mirrors PricingMarkup.DEFAULT_SALE_UPLIFT in web/templates/index.html.
// Keep both in sync; the frontend always sends an explicit value, this is a fallback for
// other API callers that omit sale_markup.
const defaultSaleMarkup = 1.3
func (o ProjectPricingExportOptions) saleMarkupFactor() float64 {
if o.SaleMarkup > 0 {
return o.SaleMarkup
}
return 1.3
return defaultSaleMarkup
}
func (o ProjectPricingExportOptions) isDDP() bool {
@@ -514,11 +519,16 @@ func sortConfigItemsByCategoryMap(items models.ConfigItems, catOrder map[string]
return sorted
}
func applyDDPMarkup(rows []ProjectPricingExportRow, factor float64) {
// 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.
const stockCompetitorMarkupFactor = 1.3
func applyDDPMarkup(rows []ProjectPricingExportRow, estimateFactor float64) {
for i := range rows {
rows[i].Estimate = scaleFloatPtr(rows[i].Estimate, factor)
rows[i].Stock = scaleFloatPtr(rows[i].Stock, factor)
rows[i].Competitor = scaleFloatPtr(rows[i].Competitor, factor)
rows[i].Estimate = scaleFloatPtr(rows[i].Estimate, estimateFactor)
rows[i].Stock = scaleFloatPtr(rows[i].Stock, stockCompetitorMarkupFactor)
rows[i].Competitor = scaleFloatPtr(rows[i].Competitor, stockCompetitorMarkupFactor)
}
}
+15
View File
@@ -0,0 +1,15 @@
package sync
import "fmt"
// SyncQtSettings pulls qt_settings (tab_config, config_types, etc.) from
// MariaDB into the local cache so the configurator picks up server-driven
// category/tab changes without requiring a client rebuild.
func (s *Service) SyncQtSettings() error {
mariaDB, err := s.getDB()
if err != nil {
return fmt.Errorf("database not available: %w", err)
}
return s.localDB.SyncQtSettings(mariaDB)
}
+5
View File
@@ -100,5 +100,10 @@ func (w *Worker) runSync() {
w.logger.Warn("background sync: failed to pull partnumber books", "error", err)
}
// Pull configurator settings (tab_config, categories, etc.)
if err := w.service.SyncQtSettings(); err != nil {
w.logger.Warn("background sync: failed to sync qt_settings", "error", err)
}
w.logger.Info("background sync cycle completed")
}
+21
View File
@@ -0,0 +1,21 @@
# QuoteForge v3.31
Дата релиза: 2026-07-22
Тег: `v3.31`
Предыдущий релиз: `v2.30`
## Ключевые изменения
- поддержка импорта CSV из customer-facing формата pricing-экспорта (не только из round-trip формата) — колонки резолвятся по имени;
- список вариантов конфигурации в выпадающем меню нумеруется и сортируется по дате создания (старый сверху);
- новая вкладка «Аренда» в конфигураторе (для проектов с флагом rental_enabled): расчёт разового и еженедельного платежа по регламенту платного тестирования/аренды GPU-серверов, с колонками Estimate/Цена продажи и чекбоксом «БУ»;
- техподдержка (support_code) на вкладке Base теперь добавляется как обычный LOT через autocomplete-пикер вместо выпадающего списка;
- прайслисты: local_pricelist_items получает lot_description напрямую из qt_pricelist_items.lot_description (вместо устаревших неиспользуемых available_qty/partnumbers) — описание LOT теперь берётся из одного места везде в проекте, включая экспорт цен (там раньше подстановка описания молча не работала);
- добавлено price_quality — качество цены LOT (0-9), проставляется внешней утилитой ценообразования; показывается цветным индикатором (градиент красный → жёлтый → зелёный) в прайслисте, в поиске компонентов конфигуратора, в таблице конфигуратора и на вкладке «Ценообразование» (подсветка строки);
- из контракта прайслиста убраны неиспользуемые в клиенте поля (price_method, price_period_days, price_coefficient, manual_price, meta_prices) — сами колонки в базе не тронуты, оставлены для обратной совместимости с внешним движком ценообразования.
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+21
View File
@@ -0,0 +1,21 @@
# QuoteForge v3.32
Дата релиза: 2026-07-24
Тег: `v3.32`
Предыдущий релиз: `v3.31`
## Ключевые изменения
- колонка «PN code» в таблице импорта BOM: HPE-спецификации хранят партномер в двух столбцах (базовый P/N и код опции), теперь они склеиваются в канонический вид `P52534-B21#B19` прямо в интерфейсе — раньше это приходилось делать через CONCATENATE в Excel. Склеенное значение сохраняется в `vendor_partnumber` и сравнивается с книгой партномеров как есть, а при повторном открытии конфигурации разбирается обратно на две колонки; схема БД не менялась;
- список допустимых LOT конфигуратора собирается из объединения прайслистов `world` и `estimate`, а не только из `estimate`. Прежняя область видимости молча теряла сопоставления BOM: резолвер находил LOT по книге партномеров, которая про прайслисты ничего не знает, а фронт отбрасывал всё, чего нет в estimate — при этом в корзину такой LOT всё равно попадал, и строка BOM оставалась с «н/д». Дедупликация по имени LOT без учёта регистра, при совпадении выигрывает запись из estimate; позиции, найденные только в world, показываются с качеством цены 0 (самый красный);
- LOT, сопоставленный по книге партномеров, сохраняется в спецификации, даже если его нет ни в одном прайслисте — раньше такое сопоставление пропадало без предупреждения. LOT, введённые руками, по-прежнему проверяются по списку;
- кнопка «Пересопоставить» на вкладке BOM — заново прогоняет строки через актуальную книгу партномеров. При открытии конфигурации сопоставления намеренно остаются такими, какими были сохранены, поэтому записи, добавленные в книгу позже, подхватываются только этой кнопкой;
- вкладка «Ценообразование»: убраны звёздочки у итогов (переносились на отдельную строку и разъезжались). Итог по столбцам Estimate, Склад и Конкуренты подсвечивается красным тогда и только тогда, когда часть суммы посчитана по ценам-заглушкам из прайслиста `world`; при наведении всплывает подсказка с точной долей таких цен и с покрытием по позициям;
- колонка «PN вендора» на вкладке «Ценообразование» больше не переносит партномер на две строки;
- индикатор качества цены показывается во всех таблицах конфигуратора, а не только на вкладке Base; колонка-индикатор везде без текстового заголовка, только с тултипом.
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+17
View File
@@ -0,0 +1,17 @@
# QuoteForge v3.33
Дата релиза: 2026-07-30
Тег: `v3.33`
Предыдущий релиз: `v3.32`
## Ключевые изменения
- новые категории прайслиста (например `SYS`), не входящие ни в одну известную вкладку конфигуратора, больше не пропадают из «Прочее» — устранены три места самоотравления `ASSIGNED_CATEGORIES`, сведены в одну функцию;
- фоновая синхронизация `qt_settings` (tab_config, config_types, required_categories, поддержка) подключена к воркеру — раньше была мёртвым кодом, и правки в центральной таблице не доезжали до клиентов;
- детерминированная сортировка при постраничной выдаче конфигураций (`ListAll`).
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+37
View File
@@ -7,3 +7,40 @@
-webkit-box-orient: vertical;
overflow: hidden;
}
/* Pricing footer totals: instant hover popup explaining how much of the sum rests on
world-pricelist stand-in prices. A native title= tooltip was too slow and too easy to
miss on a number the user is meant to distrust. */
.pricing-total-tip {
position: relative;
cursor: help;
}
.pricing-total-tip > .pricing-total-tip__body {
visibility: hidden;
opacity: 0;
position: absolute;
right: 0;
bottom: calc(100% + 6px);
z-index: 30;
width: max-content;
max-width: 20rem;
padding: 0.5rem 0.625rem;
border-radius: 0.375rem;
background: #1f2937;
color: #f9fafb;
font-size: 0.75rem;
font-weight: 400;
line-height: 1.35;
text-align: left;
white-space: normal;
box-shadow: 0 4px 12px rgb(0 0 0 / 0.18);
transition: opacity 0.1s ease-in;
pointer-events: none;
}
.pricing-total-tip:hover > .pricing-total-tip__body,
.pricing-total-tip:focus-visible > .pricing-total-tip__body {
visibility: visible;
opacity: 1;
}
+263 -256
View File
@@ -194,6 +194,9 @@
<button onclick="clearBOM()" class="px-3 py-1 bg-gray-100 text-gray-600 rounded hover:bg-gray-200 border border-gray-300">
Очистить
</button>
<button onclick="reresolveBOM()" title="Заново сопоставить строки BOM по актуальной книге партномеров" class="px-3 py-1 bg-gray-100 text-gray-600 rounded hover:bg-gray-200 border border-gray-300">
Пересопоставить
</button>
<button onclick="saveBOM()" class="px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-700">
Сохранить BOM
</button>
@@ -219,26 +222,26 @@
<table class="w-full text-sm border-collapse">
<thead class="bg-gray-50 text-gray-700">
<tr>
<th class="px-3 py-2 text-left border-b">PN вендора</th>
<th class="px-3 py-2 text-left border-b">Описание</th>
<th class="px-3 py-2 text-left border-b">LOT</th>
<th class="px-3 py-2 text-right border-b">Кол-во</th>
<th class="px-3 py-2 text-right border-b">Estimate</th>
<th class="px-3 py-2 text-right border-b">Склад</th>
<th class="px-3 py-2 text-right border-b">Конкуренты</th>
<th class="px-3 py-2 text-right border-b">Ручная цена</th>
<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>
</tr>
</thead>
<tbody id="pricing-body-buy">
<tr><td colspan="8" class="px-3 py-8 text-center text-gray-400">Загрузите BOM во вкладке «BOM»</td></tr>
<tr><td colspan="8" 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-3 py-2 text-right">Итого:</td>
<td class="px-3 py-2 text-right" id="pricing-total-buy-estimate">—</td>
<td class="px-3 py-2 text-right" id="pricing-total-buy-warehouse">—</td>
<td class="px-3 py-2 text-right" id="pricing-total-buy-competitor">—</td>
<td class="px-3 py-2 text-right font-bold" id="pricing-total-buy-vendor">—</td>
<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>
</tr>
</tfoot>
</table>
@@ -268,26 +271,26 @@
<table class="w-full text-sm border-collapse">
<thead class="bg-gray-50 text-gray-700">
<tr>
<th class="px-3 py-2 text-left border-b">PN вендора</th>
<th class="px-3 py-2 text-left border-b">Описание</th>
<th class="px-3 py-2 text-left border-b">LOT</th>
<th class="px-3 py-2 text-right border-b">Кол-во</th>
<th class="px-3 py-2 text-right border-b">Estimate</th>
<th class="px-3 py-2 text-right border-b">Склад</th>
<th class="px-3 py-2 text-right border-b">Конкуренты</th>
<th class="px-3 py-2 text-right border-b">Ручная цена</th>
<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>
</tr>
</thead>
<tbody id="pricing-body-sale">
<tr><td colspan="8" class="px-3 py-8 text-center text-gray-400">Загрузите BOM во вкладке «BOM»</td></tr>
<tr><td colspan="8" 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-3 py-2 text-right">Итого:</td>
<td class="px-3 py-2 text-right" id="pricing-total-sale-estimate">—</td>
<td class="px-3 py-2 text-right" id="pricing-total-sale-warehouse">—</td>
<td class="px-3 py-2 text-right" id="pricing-total-sale-competitor">—</td>
<td class="px-3 py-2 text-right font-bold" id="pricing-total-sale-vendor">—</td>
<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>
</tr>
</tfoot>
</table>
@@ -471,9 +474,17 @@ let TAB_CONFIG = {
}
};
let ASSIGNED_CATEGORIES = Object.values(TAB_CONFIG)
.flatMap(t => t.categories)
.map(c => ciStr(c));
// Categories belonging to any real tab (everything except "other").
// "other" is defined as "whatever isn't in this set" — it must never
// contribute to it, or its own contents would exclude themselves.
function computeAssignedCategories() {
return Object.entries(TAB_CONFIG)
.filter(([key]) => key !== 'other')
.flatMap(([, t]) => t._allCategories || t.categories)
.map(c => ciStr(c));
}
let ASSIGNED_CATEGORIES = computeAssignedCategories();
// State
let configUUID = '{{.ConfigUUID}}';
@@ -598,6 +609,19 @@ let warehouseStockLoadsByPricelist = new Map();
let componentPricesCache = {}; // { lot_name: price } - caches prices loaded via API
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.
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 || '');
return v > 0 ? v : this.DEFAULT_SALE_UPLIFT;
},
};
// Autocomplete state
let autocompleteInput = null;
let autocompleteCategory = null;
@@ -819,23 +843,20 @@ async function loadCategoriesFromAPI() {
categoryOrderMap[ciStr(cat.code)] = cat.display_order;
});
// Build list of unassigned categories
const knownCodes = Object.values(TAB_CONFIG)
.flatMap(t => t.categories)
.map(c => ciStr(c));
// Build list of unassigned categories (excludes "other" itself, so
// this stays correct even if it's re-run after "other" was already
// populated by a previous call).
const knownCodes = computeAssignedCategories();
const unassignedCategories = cats
.filter(cat => !knownCodes.includes(ciStr(cat.code)))
.sort((a, b) => a.display_order - b.display_order)
.map(cat => cat.code);
ASSIGNED_CATEGORIES = knownCodes;
// Update "other" tab with unassigned categories
TAB_CONFIG.other.categories = unassignedCategories;
// Rebuild ASSIGNED_CATEGORIES
ASSIGNED_CATEGORIES = Object.values(TAB_CONFIG)
.flatMap(t => t.categories)
.map(c => ciStr(c));
} catch(e) {
console.error('Failed to load categories, using defaults', e);
// Will use default configuration if API fails
@@ -879,8 +900,12 @@ function applyServerSettings(settings) {
sections: tab.sections || undefined
};
});
// Rebuild ASSIGNED_CATEGORIES from the known (non-"other") tabs only,
// before restoring .other — otherwise categories already parked in
// .other (e.g. by loadCategoriesFromAPI) get counted as "assigned"
// and immediately excluded from the "other" tab again.
ASSIGNED_CATEGORIES = computeAssignedCategories();
TAB_CONFIG.other = otherTab || { categories: [], singleSelect: false, label: 'Other' };
ASSIGNED_CATEGORIES = Object.values(TAB_CONFIG).flatMap(t => t.categories).map(c => ciStr(c));
}
// always_visible_tabs
@@ -1391,11 +1416,10 @@ function applyConfigTypeToTabs() {
}
});
// Rebuild assigned categories index using the full static list (_allCategories),
// not the filtered one — hidden categories still belong to their tab, not to Other.
ASSIGNED_CATEGORIES = Object.values(TAB_CONFIG)
.flatMap(t => t._allCategories || t.categories)
.map(c => ciStr(c));
// Rebuild assigned categories index using the full static list
// (_allCategories), not the filtered one — hidden categories still
// belong to their tab, not to Other.
ASSIGNED_CATEGORIES = computeAssignedCategories();
}
function updateTabVisibility() {
@@ -1560,6 +1584,7 @@ function renderMultiSelectTab(components) {
<table class="w-full">
<thead class="bg-gray-50">
<tr>
<th class="px-2 py-2 w-6" title="Качество цены"></th>
<th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">LOT</th>
<th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Описание</th>
<th class="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase w-24">Estimate</th>
@@ -1578,6 +1603,7 @@ function renderMultiSelectTab(components) {
html += `
<tr class="hover:bg-gray-50">
<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">
<input type="text"
@@ -1610,7 +1636,7 @@ function renderMultiSelectTab(components) {
// Add empty row for new item
html += `
<tr class="hover:bg-gray-50 bg-gray-50">
<td class="px-3 py-2" colspan="2">
<td class="px-3 py-2" colspan="3">
<div class="autocomplete-wrapper relative">
<input type="text"
id="input-new-item"
@@ -1665,6 +1691,7 @@ function renderMultiSelectTabWithSections(sections) {
<table class="w-full">
<thead class="bg-gray-50">
<tr>
<th class="px-2 py-2 w-6" title="Качество цены"></th>
<th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">LOT</th>
<th class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase">Описание</th>
<th class="px-3 py-2 text-right text-xs font-medium text-gray-500 uppercase w-24">Estimate</th>
@@ -1687,6 +1714,7 @@ function renderMultiSelectTabWithSections(sections) {
html += `
<tr class="hover:bg-gray-50">
<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">
<input type="text"
@@ -1720,7 +1748,7 @@ function renderMultiSelectTabWithSections(sections) {
// Add empty row for new item in this section
html += `
<tr class="hover:bg-gray-50 bg-gray-50">
<td class="px-3 py-2" colspan="2">
<td class="px-3 py-2" colspan="3">
<div class="autocomplete-wrapper relative">
<input type="text"
id="input-section-${sectionId}"
@@ -1870,7 +1898,10 @@ function renderAutocomplete() {
dropdown.classList.remove('hidden');
}
function handleAutocompleteKey(event, category) {
// Shared ArrowUp/ArrowDown/Enter/Escape navigation for all autocomplete dropdown
// variants (single-select, multi-select, section, edit-item, BOM row); onSelect
// receives the chosen autocompleteFiltered index and applies it to that context.
function handleAutocompleteKeyGeneric(event, onSelect) {
if (event.key === 'ArrowDown') {
event.preventDefault();
autocompleteIndex = Math.min(autocompleteIndex + 1, autocompleteFiltered.length - 1);
@@ -1882,27 +1913,23 @@ function handleAutocompleteKey(event, category) {
} else if (event.key === 'Enter') {
event.preventDefault();
if (autocompleteIndex >= 0 && autocompleteIndex < autocompleteFiltered.length) {
selectAutocompleteItem(autocompleteIndex);
onSelect(autocompleteIndex);
}
} else if (event.key === 'Escape') {
hideAutocomplete();
}
}
function selectAutocompleteItem(index) {
const comp = autocompleteFiltered[index];
if (!comp || !autocompleteCategory) return;
function handleAutocompleteKey(event, category) {
handleAutocompleteKeyGeneric(event, (index) => selectAutocompleteItem(index));
}
// Remove existing item of this category
cart = cart.filter(item =>
ciStr(item.category) !== ciStr(autocompleteCategory)
);
const qtyInput = document.getElementById('qty-' + autocompleteCategory);
const qty = parseInt(qtyInput?.value) || 1;
// Builds a fresh cart entry for a component picked from an autocomplete dropdown.
// Warehouse/competitor prices and their deltas start unknown (null) until the
// next price-levels refresh fills them in.
function buildNewCartItem(comp, qty) {
const price = componentPricesCache[comp.lot_name] || 0;
cart.push({
return {
lot_name: comp.lot_name,
quantity: qty,
unit_price: price,
@@ -1918,15 +1945,35 @@ function selectAutocompleteItem(index) {
price_missing: ['warehouse', 'competitor'],
description: comp.description || '',
category: getComponentCategory(comp)
});
};
}
hideAutocomplete();
// Re-renders the tab/cart and kicks off autosave + a price-levels refresh
// after a cart mutation from an autocomplete selection.
function commitCartChange() {
renderTab();
updateCartUI();
triggerAutoSave();
schedulePriceLevelsRefresh({ delay: 80, rerender: true, autosave: false });
}
function selectAutocompleteItem(index) {
const comp = autocompleteFiltered[index];
if (!comp || !autocompleteCategory) return;
// Remove existing item of this category
cart = cart.filter(item =>
ciStr(item.category) !== ciStr(autocompleteCategory)
);
const qtyInput = document.getElementById('qty-' + autocompleteCategory);
const qty = parseInt(qtyInput?.value) || 1;
cart.push(buildNewCartItem(comp, qty));
hideAutocomplete();
commitCartChange();
}
function hideAutocomplete() {
document.getElementById('autocomplete-dropdown').classList.add('hidden');
autocompleteInput = null;
@@ -1971,22 +2018,7 @@ function filterAutocompleteMulti(search) {
}
function handleAutocompleteKeyMulti(event) {
if (event.key === 'ArrowDown') {
event.preventDefault();
autocompleteIndex = Math.min(autocompleteIndex + 1, autocompleteFiltered.length - 1);
renderAutocomplete();
} else if (event.key === 'ArrowUp') {
event.preventDefault();
autocompleteIndex = Math.max(autocompleteIndex - 1, -1);
renderAutocomplete();
} else if (event.key === 'Enter') {
event.preventDefault();
if (autocompleteIndex >= 0 && autocompleteIndex < autocompleteFiltered.length) {
selectAutocompleteItemMulti(autocompleteIndex);
}
} else if (event.key === 'Escape') {
hideAutocomplete();
}
handleAutocompleteKeyGeneric(event, (index) => selectAutocompleteItemMulti(index));
}
function selectAutocompleteItemMulti(index) {
@@ -1995,31 +2027,10 @@ function selectAutocompleteItemMulti(index) {
const qtyInput = document.getElementById('new-qty');
const qty = parseInt(qtyInput?.value) || 1;
const price = componentPricesCache[comp.lot_name] || 0;
cart.push({
lot_name: comp.lot_name,
quantity: qty,
unit_price: price,
estimate_price: price,
warehouse_price: null,
competitor_price: null,
delta_wh_estimate_abs: null,
delta_wh_estimate_pct: null,
delta_comp_estimate_abs: null,
delta_comp_estimate_pct: null,
delta_comp_wh_abs: null,
delta_comp_wh_pct: null,
price_missing: ['warehouse', 'competitor'],
description: comp.description || '',
category: getComponentCategory(comp)
});
cart.push(buildNewCartItem(comp, qty));
hideAutocomplete();
renderTab();
updateCartUI();
triggerAutoSave();
schedulePriceLevelsRefresh({ delay: 80, rerender: true, autosave: false });
commitCartChange();
}
// Autocomplete for sectioned tabs (like storage with RAID and Disks sections)
@@ -2076,22 +2087,7 @@ function filterAutocompleteSection(sectionId, search, inputElement) {
}
function handleAutocompleteKeySection(event, sectionId) {
if (event.key === 'ArrowDown') {
event.preventDefault();
autocompleteIndex = Math.min(autocompleteIndex + 1, autocompleteFiltered.length - 1);
renderAutocomplete();
} else if (event.key === 'ArrowUp') {
event.preventDefault();
autocompleteIndex = Math.max(autocompleteIndex - 1, -1);
renderAutocomplete();
} else if (event.key === 'Enter') {
event.preventDefault();
if (autocompleteIndex >= 0 && autocompleteIndex < autocompleteFiltered.length) {
selectAutocompleteItemSection(autocompleteIndex, sectionId);
}
} else if (event.key === 'Escape') {
hideAutocomplete();
}
handleAutocompleteKeyGeneric(event, (index) => selectAutocompleteItemSection(index, sectionId));
}
function selectAutocompleteItemSection(index, sectionId) {
@@ -2100,25 +2096,7 @@ function selectAutocompleteItemSection(index, sectionId) {
const qtyInput = document.getElementById('new-qty-' + sectionId);
const qty = parseInt(qtyInput?.value) || 1;
const price = componentPricesCache[comp.lot_name] || 0;
cart.push({
lot_name: comp.lot_name,
quantity: qty,
unit_price: price,
estimate_price: price,
warehouse_price: null,
competitor_price: null,
delta_wh_estimate_abs: null,
delta_wh_estimate_pct: null,
delta_comp_estimate_abs: null,
delta_comp_estimate_pct: null,
delta_comp_wh_abs: null,
delta_comp_wh_pct: null,
price_missing: ['warehouse', 'competitor'],
description: comp.description || '',
category: getComponentCategory(comp)
});
cart.push(buildNewCartItem(comp, qty));
hideAutocomplete();
@@ -2128,10 +2106,7 @@ function selectAutocompleteItemSection(index, sectionId) {
// Reset quantity to 1
if (qtyInput) qtyInput.value = '1';
renderTab();
updateCartUI();
triggerAutoSave();
schedulePriceLevelsRefresh({ delay: 80, rerender: true, autosave: false });
commitCartChange();
}
// Autocomplete for editing an existing cart item's LOT (multi/section tabs)
@@ -2165,22 +2140,7 @@ function filterAutocompleteEditItem(search) {
}
function handleAutocompleteKeyEditItem(event) {
if (event.key === 'ArrowDown') {
event.preventDefault();
autocompleteIndex = Math.min(autocompleteIndex + 1, autocompleteFiltered.length - 1);
renderAutocomplete();
} else if (event.key === 'ArrowUp') {
event.preventDefault();
autocompleteIndex = Math.max(autocompleteIndex - 1, -1);
renderAutocomplete();
} else if (event.key === 'Enter') {
event.preventDefault();
if (autocompleteIndex >= 0 && autocompleteIndex < autocompleteFiltered.length) {
selectAutocompleteEditItem(autocompleteIndex);
}
} else if (event.key === 'Escape') {
hideAutocomplete();
}
handleAutocompleteKeyGeneric(event, (index) => selectAutocompleteEditItem(index));
}
function selectAutocompleteEditItem(index) {
@@ -2190,29 +2150,10 @@ function selectAutocompleteEditItem(index) {
const oldItem = cart.find(i => i.lot_name === lotName);
const qty = oldItem?.quantity || 1;
cart = cart.filter(i => i.lot_name !== lotName);
const price = componentPricesCache[comp.lot_name] || 0;
cart.push({
lot_name: comp.lot_name,
quantity: qty,
unit_price: price,
estimate_price: price,
warehouse_price: null,
competitor_price: null,
delta_wh_estimate_abs: null,
delta_wh_estimate_pct: null,
delta_comp_estimate_abs: null,
delta_comp_estimate_pct: null,
delta_comp_wh_abs: null,
delta_comp_wh_pct: null,
price_missing: ['warehouse', 'competitor'],
description: comp.description || '',
category: getComponentCategory(comp)
});
cart.push(buildNewCartItem(comp, qty));
hideAutocomplete();
renderTab();
updateCartUI();
triggerAutoSave();
schedulePriceLevelsRefresh({ delay: 80, rerender: true, autosave: false });
commitCartChange();
}
// Autocomplete for BOM LOT mapping
@@ -2248,22 +2189,7 @@ function filterAutocompleteBOM(rowIdx, search) {
}
function handleAutocompleteKeyBOM(event, rowIdx) {
if (event.key === 'ArrowDown') {
event.preventDefault();
autocompleteIndex = Math.min(autocompleteIndex + 1, autocompleteFiltered.length - 1);
renderAutocomplete();
} else if (event.key === 'ArrowUp') {
event.preventDefault();
autocompleteIndex = Math.max(autocompleteIndex - 1, -1);
renderAutocomplete();
} else if (event.key === 'Enter') {
event.preventDefault();
if (autocompleteIndex >= 0 && autocompleteIndex < autocompleteFiltered.length) {
selectAutocompleteItemBOM(autocompleteIndex, rowIdx);
}
} else if (event.key === 'Escape') {
hideAutocomplete();
}
handleAutocompleteKeyGeneric(event, (index) => selectAutocompleteItemBOM(index, rowIdx));
}
function selectAutocompleteItemBOM(index, rowIdx) {
@@ -3476,6 +3402,7 @@ let bomImportRaw = null; // { mode:'raw'|'parsed', rows, columnTypes, ignoredRow
const BOM_COL_TYPES = [
{ value: 'ignore', label: 'Не использовать' },
{ value: 'pn', label: 'P/N' },
{ value: 'pn_code', label: 'PN code' },
{ value: 'qty', label: 'Кол-во' },
{ value: 'price', label: 'Цена' },
{ value: 'description', label: 'Описание' }
@@ -3486,6 +3413,7 @@ function _bomRawHeaderWidthClass(colType) {
case 'qty': return 'w-24 min-w-24';
case 'price': return 'w-32 min-w-32';
case 'pn': return 'min-w-40';
case 'pn_code': return 'w-28 min-w-28';
case 'description': return 'min-w-48';
default: return 'min-w-28';
}
@@ -3495,10 +3423,32 @@ function _bomRawCellWidthClass(colType) {
switch (colType) {
case 'qty': return 'w-24 min-w-24';
case 'price': return 'w-32 min-w-32';
case 'pn_code': return 'w-28 min-w-28';
default: return '';
}
}
// HPE specs split the partnumber across two columns (PN + option CODE): the
// canonical partnumber is "P52534-B21#B19". A row with an empty code column
// keeps the bare PN.
function _bomComposePN(cols, idx) {
const pn = ((cols[idx.pn[0]] || '') + '').trim();
if (!pn) return '';
const codeCol = idx.pn_code.length ? idx.pn_code[0] : -1;
if (codeCol === -1) return pn;
const code = ((cols[codeCol] || '') + '').trim();
return code ? `${pn}#${code}` : pn;
}
// Inverse of _bomComposePN: splits a stored partnumber back into [pn, code].
// Only the first '#' separates the option code, so a code containing '#' round-trips.
function _bomSplitPN(vendorPN) {
const s = (vendorPN || '').trim();
const at = s.indexOf('#');
if (at === -1) return [s, ''];
return [s.slice(0, at), s.slice(at + 1)];
}
function parsePastePrice(s) {
if (!s) return null;
let v = String(s).replace(/[$\s]/g, '');
@@ -3645,7 +3595,7 @@ async function handleBOMPaste(event) {
function _getBomColumnTypeIndexes() {
if (!bomImportRaw || !Array.isArray(bomImportRaw.columnTypes)) return null;
const idx = { ignore: [], pn: [], qty: [], price: [], description: [] };
const idx = { ignore: [], pn: [], pn_code: [], qty: [], price: [], description: [] };
bomImportRaw.columnTypes.forEach((t, i) => { (idx[t] || idx.ignore).push(i); });
return idx;
}
@@ -3655,6 +3605,7 @@ function _validateBomColumnTypes() {
const idx = _getBomColumnTypeIndexes();
if (!idx) return { ok: false, message: 'Нет данных BOM' };
if (idx.pn.length !== 1) return { ok: false, message: 'Выберите ровно один столбец P/N.' };
if (idx.pn_code.length > 1) return { ok: false, message: 'Можно выбрать только один столбец PN code.' };
if (idx.qty.length !== 1) return { ok: false, message: 'Выберите ровно один столбец Кол-во.' };
if (idx.price.length > 1) return { ok: false, message: 'Можно выбрать только один столбец Цена.' };
if (idx.description.length > 1) return { ok: false, message: 'Можно выбрать только один столбец Описание.' };
@@ -3797,10 +3748,20 @@ function _getRowBaseLot(row) {
if (manual && _bomLotValid(manual)) return manual.toUpperCase();
return '';
}
// A LOT resolved from the partnumber book is authoritative even when it is absent
// from the component list: that list is the active estimate pricelist only
// (localdb.ListComponents), so a LOT the pricelist does not carry would otherwise be
// dropped from lot_mappings on save while still reaching the cart via _getRowBaseLot.
// Hand-typed LOTs stay validated.
function _bomLotPersistable(row, lot) {
if (!lot) return false;
return row?.resolution_source === 'book' || _bomLotValid(lot);
}
function _getRowCanonicalLotMappings(row) {
const out = [];
const baseLot = _getRowBaseLot(row);
if (baseLot && _bomLotValid(baseLot)) {
if (baseLot && _bomLotPersistable(row, baseLot)) {
out.push({
lot_name: baseLot,
quantity_per_pn: _getRowLotQtyPerPN(row)
@@ -3976,7 +3937,6 @@ function rebuildBOMRowsFromRaw() {
_setBomUIError('');
const idx = validation.idx;
const pnCol = idx.pn[0];
const qtyCol = idx.qty[0];
const priceCol = idx.price.length ? idx.price[0] : -1;
const descCol = idx.description.length ? idx.description[0] : -1;
@@ -3984,7 +3944,7 @@ function rebuildBOMRowsFromRaw() {
const nextRows = [];
bomImportRaw.rows.forEach((cols, rowIdx) => {
if (bomImportRaw.ignoredRows?.[rowIdx]) return;
const pn = ((cols[pnCol] || '') + '').trim();
const pn = _bomComposePN(cols, idx);
if (!pn) return;
const qtyRaw = ((cols[qtyCol] || '') + '').trim();
if (!/^\d+$/.test(qtyRaw) || parseInt(qtyRaw, 10) < 1) {
@@ -4063,13 +4023,12 @@ async function resolveBOM() {
if (bomImportRaw && bomImportRaw.mode === 'raw') {
const validation = _validateBomColumnTypes();
if (validation.ok) {
const pnCol = validation.idx.pn[0];
const descCol = validation.idx.description.length ? validation.idx.description[0] : -1;
ignoredSeen = (bomImportRaw.rows || [])
.map((cols, rowIdx) => ({ cols, rowIdx }))
.filter(x => bomImportRaw.ignoredRows?.[x.rowIdx])
.map(({ cols }) => ({
partnumber: ((cols[pnCol] || '') + '').trim(),
partnumber: _bomComposePN(cols, validation.idx),
description: descCol !== -1 ? ((cols[descCol] || '') + '').trim() : '',
ignored: true
}))
@@ -4241,6 +4200,21 @@ function renderBOMTable() {
if (currentTopTab === 'pricing') renderPricingTab();
}
// Manual re-resolve against the current partnumber book. loadVendorSpec deliberately
// does not re-resolve on open — a configuration keeps the mappings frozen at save time —
// so this is the way to pick up book entries added since. Book matches win over the
// stored mapping (resolver step 1 > step 2); rows the book does not know keep theirs.
async function reresolveBOM() {
if (!bomRows.length) return;
const before = bomRows.map(r => _getRowBaseLot(r));
await resolveBOM();
const changed = bomRows.reduce((n, r, i) => n + (_getRowBaseLot(r) !== before[i] ? 1 : 0), 0);
const stillUnresolved = bomRows.filter(r => !_getRowBaseLot(r)).length;
showToast(changed
? `Пересопоставлено строк: ${changed}. Без LOT: ${stillUnresolved}`
: `Изменений нет. Без LOT: ${stillUnresolved}`, changed ? 'success' : 'info');
}
let _resolveBOMTimer = null;
function debouncedResolveBOM() {
clearTimeout(_resolveBOMTimer);
@@ -4412,16 +4386,22 @@ async function loadVendorSpec(configUUID) {
});
// Reconstruct editable raw table from normalized vendor_spec (not original Excel paste).
// Columns: Qty | P/N | Description | Price
// Columns: Qty | P/N | Description | Price, plus PN code when any saved
// partnumber carries an HPE option code ("P52534-B21#B19"). The column layout
// itself is not persisted, so it is re-derived from the stored partnumbers.
const hasPNCode = bomRows.some(r => (r.vendor_pn || '').includes('#'));
bomImportRaw = {
mode: 'raw',
rows: bomRows.map(r => ([
String(r.quantity ?? 1),
r.vendor_pn || '',
r.description || '',
r.unit_price != null ? String(r.unit_price) : ''
])),
columnTypes: ['qty', 'pn', 'description', 'price'],
rows: bomRows.map(r => {
const [pn, code] = _bomSplitPN(r.vendor_pn || '');
const cells = [String(r.quantity ?? 1), pn];
if (hasPNCode) cells.push(code);
cells.push(r.description || '', r.unit_price != null ? String(r.unit_price) : '');
return cells;
}),
columnTypes: hasPNCode
? ['qty', 'pn', 'pn_code', 'description', 'price']
: ['qty', 'pn', 'description', 'price'],
ignoredRows: {},
rowErrors: {},
uiError: ''
@@ -4504,12 +4484,9 @@ async function renderPricingTab() {
} catch(e) { /* silent */ }
}
// Sale uplift applied to estimate (default 1.3)
const saleUplift = (() => {
const v = parseDecimalInput(document.getElementById('pricing-uplift-sale')?.value || '');
return v > 0 ? v : 1.3;
})();
const SALE_FIXED_MULT = 1.3;
// 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) => ({
@@ -4655,12 +4632,13 @@ async function renderPricingTab() {
// ─── Populate Buy table ──────────────────────────────────────────────────
tbodyBuy.innerHTML = '';
if (!rowData.length) {
tbodyBuy.innerHTML = '<tr><td colspan="8" class="px-3 py-8 text-center text-gray-400">Нет данных для отображения</td></tr>';
tbodyBuy.innerHTML = '<tr><td colspan="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;
let hasEst = false, hasWh = false, hasComp = false, hasVendor = 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-buy');
@@ -4677,43 +4655,44 @@ async function renderPricingTab() {
tr.dataset.vendorPn = r.vendorPN || '';
tr.dataset.desc = r.desc;
tr.dataset.lot = r.lotText;
if (r.est > 0) { totEst += r.est; hasEst = true; }
if (r.warehouse != null) { totWh += r.warehouse; hasWh = true; cntWh++; }
if (r.competitor != null) { totComp += r.competitor; hasComp = true; cntComp++; }
if (r.est > 0) { totEst += r.est; hasEst = true; if (r.estWorld) worldEst += r.est; }
if (r.warehouse != null) { totWh += r.warehouse; hasWh = true; cntWh++; if (r.whWorld) worldWh += r.warehouse; }
if (r.competitor != null) { totComp += r.competitor; hasComp = true; cntComp++; if (r.compWorld) worldComp += r.competitor; }
if (r.vendorOrig != null) { totVendor += r.vendorOrig; hasVendor = true; }
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-3 py-1.5 font-mono text-xs border-t border-gray-200 align-top ${r.vendorPN == null ? 'text-gray-400' : ''}">${r.vendorPN != null ? escapeHtml(r.vendorPN) : '—'}</td>
<td${rs} class="px-3 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-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>`;
})() : '';
tr.innerHTML = `
${pnDescHtml}
<td class="px-3 py-1.5 text-xs ${borderTop}">${r.lotCell}</td>
<td class="px-3 py-1.5 text-right text-xs ${borderTop}">${r.qty}</td>
<td class="px-3 py-1.5 text-right text-xs ${borderTop} ${r.estWorld ? WORLD_CLS : ''}">${r.estUnit > 0 ? formatCurrency(r.estUnit) : '—'}</td>
<td class="px-3 py-1.5 text-right text-xs ${borderTop} ${r.whWorld ? WORLD_CLS : ''}">${r.warehouseUnit != null ? formatCurrency(r.warehouseUnit) : '—'}</td>
<td class="px-3 py-1.5 text-right text-xs ${borderTop} ${r.compWorld ? WORLD_CLS : ''}">${r.competitorUnit != null ? formatCurrency(r.competitorUnit) : '—'}</td>
<td class="px-3 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-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>
`;
tbodyBuy.appendChild(tr);
});
document.getElementById('pricing-total-buy-estimate').textContent = hasEst ? formatCurrency(totEst) : '—';
document.getElementById('pricing-total-buy-vendor').textContent = hasVendor ? formatCurrency(totVendor) : '—';
_setPartialTotal('pricing-total-buy-warehouse', hasWh, totWh, cntWh, rowData.length);
_setPartialTotal('pricing-total-buy-competitor', hasComp, totComp, cntComp, rowData.length);
document.getElementById('pricing-total-buy-vendor').textContent = hasVendor ? formatCurrency(totVendor) : '—';
_setPricingTotal('pricing-total-buy-estimate', hasEst, totEst, worldEst, rowData.length, rowData.length);
_setPricingTotal('pricing-total-buy-warehouse', hasWh, totWh, worldWh, cntWh, rowData.length);
_setPricingTotal('pricing-total-buy-competitor', hasComp, totComp, worldComp, cntComp, rowData.length);
tfootBuy.classList.remove('hidden');
}
// ─── Populate Sale table ─────────────────────────────────────────────────
tbodySale.innerHTML = '';
if (!rowData.length) {
tbodySale.innerHTML = '<tr><td colspan="8" class="px-3 py-8 text-center text-gray-400">Нет данных для отображения</td></tr>';
tbodySale.innerHTML = '<tr><td colspan="8" 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');
@@ -4734,30 +4713,30 @@ async function renderPricingTab() {
tr.dataset.vendorPn = r.vendorPN || '';
tr.dataset.desc = r.desc;
tr.dataset.lot = r.lotText;
if (saleEstTotal > 0) { totEst += saleEstTotal; hasEst = true; }
if (saleWhTotal != null) { totWh += saleWhTotal; hasWh = true; cntWh++; }
if (saleCompTotal != null) { totComp += saleCompTotal; hasComp = true; cntComp++; }
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; }
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-3 py-1.5 font-mono text-xs border-t border-gray-200 align-top ${r.vendorPN == null ? 'text-gray-400' : ''}">${r.vendorPN != null ? escapeHtml(r.vendorPN) : '—'}</td>
<td${rs} class="px-3 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-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>`;
})() : '';
tr.innerHTML = `
${pnDescHtml}
<td class="px-3 py-1.5 text-xs ${borderTop}">${r.lotCell}</td>
<td class="px-3 py-1.5 text-right text-xs ${borderTop}">${r.qty}</td>
<td class="px-3 py-1.5 text-right text-xs ${borderTop} ${r.estWorld ? WORLD_CLS : ''}">${saleEstUnit > 0 ? formatCurrency(saleEstUnit) : '—'}</td>
<td class="px-3 py-1.5 text-right text-xs ${borderTop} ${r.whWorld ? WORLD_CLS : ''}">${saleWhUnit != null ? formatCurrency(saleWhUnit) : '—'}</td>
<td class="px-3 py-1.5 text-right text-xs ${borderTop} ${r.compWorld ? WORLD_CLS : ''}">${saleCompUnit != null ? formatCurrency(saleCompUnit) : '—'}</td>
<td class="px-3 py-1.5 text-right text-xs pricing-vendor-price-sale ${borderTop} text-gray-400">—</td>
<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>
`;
tbodySale.appendChild(tr);
});
document.getElementById('pricing-total-sale-estimate').textContent = hasEst ? formatCurrency(totEst) : '—';
document.getElementById('pricing-total-sale-vendor').textContent = '—';
_setPartialTotal('pricing-total-sale-warehouse', hasWh, totWh, cntWh, rowData.length);
_setPartialTotal('pricing-total-sale-competitor', hasComp, totComp, cntComp, rowData.length);
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');
}
@@ -4768,17 +4747,43 @@ async function renderPricingTab() {
// ─── Pricing helpers ─────────────────────────────────────────────────────────
// Sets a footer total cell. If has prices but coverage < totalRows, marks red with a hover asterisk.
function _setPartialTotal(elId, has, total, count, totalRows) {
// Sets a footer total cell. The total is always red — it is a sum the user must not read
// as a firm number — and hovering it pops up how much of that sum rests on world-pricelist
// stand-in prices (see decisions/2026-07-10-world-pricelist-fallback.md), plus the row
// coverage when some positions have no price at all. The popup is a styled element rather
// than title=, which appears too late to notice. No asterisk: it wrapped onto its own line
// and pushed the footer around.
function _setPricingTotal(elId, has, total, worldTotal, count, totalRows) {
const el = document.getElementById(elId);
if (!el) return;
el.className = el.className.replace(/\btext-red-\d+\b/g, '').trim();
if (!has) { el.textContent = '—'; return; }
if (count < totalRows) {
el.innerHTML = `<span class="text-red-600">${formatCurrency(total)}</span> <span class="text-red-400 cursor-help" title="Цены указаны не для всех позиций (${count} из ${totalRows})">*</span>`;
} else {
el.textContent = formatCurrency(total);
el.className = el.className
.replace(/\btext-red-\d+\b/g, '')
.replace(/\bpricing-total-tip\b/g, '')
.trim();
if (!has) {
el.textContent = '—';
return;
}
const share = total > 0 ? (worldTotal / total) * 100 : 0;
const parts = [
share > 0
? `<b>${formatPercent(share)}%</b> от этой суммы посчитано по ценам прайслиста WORLD — это заглушка, а не реальная цена`
: 'Цены прайслиста WORLD в этой сумме не использованы'
];
if (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`
.replace(/\s+/g, ' ').trim();
el.innerHTML = `${formatCurrency(total)}<span class="pricing-total-tip__body">${parts.join('<br>')}</span>`;
}
// One decimal, comma separator, no trailing ",0".
function formatPercent(v) {
return v.toFixed(1).replace(/\.0$/, '').replace('.', ',');
}
function parseDecimalInput(raw) {
@@ -4931,6 +4936,7 @@ async function exportPricingCSV(table) {
const basis = table === 'sale' ? 'ddp' : 'fob';
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;
try {
const resp = await fetch(`/api/configs/${configUUID}/export/pricing`, {
method: 'POST',
@@ -4942,6 +4948,7 @@ async function exportPricingCSV(table) {
include_stock: true,
include_competitor: true,
basis: basis,
sale_markup: saleUplift > 0 ? saleUplift : null,
manual_price: manualPrice > 0 ? manualPrice : null,
}),
});
+1 -1
View File
@@ -59,7 +59,7 @@
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Категория</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Описание</th>
<th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">Цена, $</th>
<th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">Качество</th>
<th class="px-6 py-3 w-6" title="Качество цены"></th>
</tr>
</thead>
<tbody id="items-body" class="bg-white divide-y divide-gray-200">