Compare commits
23
Commits
v2.29
...
4d7b0e13ef
No files matched your search
@@ -132,7 +132,7 @@ Rules:
|
||||
|
||||
## Server-driven configurator settings (`qt_settings`)
|
||||
|
||||
QF reads four settings from `qt_settings` (MariaDB) and caches them in `local_qt_settings` (SQLite).
|
||||
QF reads settings from `qt_settings` (MariaDB) and caches them in `local_qt_settings` (SQLite).
|
||||
They are synced during every component sync. See `bible-local/server-contract-qt-settings.md` for the
|
||||
full contract and JSON schemas.
|
||||
|
||||
@@ -142,6 +142,7 @@ full contract and JSON schemas.
|
||||
| `tab_config` | Configurator tab structure, sections, singleSelect |
|
||||
| `always_visible_tabs` | Which tabs are shown even when empty |
|
||||
| `required_categories` | Per-config-type badge on tabs with unfilled required categories |
|
||||
| `support_pricing` | Price data for the Base tab's support-level picker (see below) |
|
||||
|
||||
Rules:
|
||||
- sync runs as part of the pricelist pull; failure is non-fatal (Warn log only);
|
||||
@@ -150,6 +151,68 @@ Rules:
|
||||
- `config_types[].categories` is an allowlist: a category absent from all types is shown everywhere;
|
||||
- `qt_categories.name` and `qt_categories.name_ru` are not used by QF runtime; do not depend on them.
|
||||
|
||||
## Support as a BOM LOT
|
||||
|
||||
The Base tab's support-level picker adds/replaces a synthetic LOT in `cart` (e.g.
|
||||
`SVC_3yB_HGX-H200`, quantity 1) exactly like adding any other component — not a separate
|
||||
mechanism. This means support flows through `total_price`, the Pricing tab, exports, and the
|
||||
rental calc the same way any BOM line does, with no special-casing needed in those paths.
|
||||
|
||||
- lot_name shape: `SVC_{years}y{level}_{platform}` (e.g. `SVC_3yB_HGX-H200`); `internal/article
|
||||
/generator.go`'s `buildSupportSegment` detects it by the `SVC_` lot_name prefix (support LOTs
|
||||
aren't in the pricelist catalog, so there's no `lot_category` to key off — same lot_name-pattern
|
||||
approach the generator already uses for GPU/CPU/memory parsing) and emits the `{years}y{level}`
|
||||
token as the article's SUPPORT segment, replacing the old separate `BuildOptions.SupportCode`
|
||||
field/`isSupportCodeValid` check;
|
||||
- `Configuration.SupportCode` (the DB column) is no longer read by article generation; it's
|
||||
inert legacy metadata now — the LOT in `items` is the source of truth;
|
||||
- the picker's displayed price is computed client-side per "Регламент расчёта стоимости
|
||||
технической поддержки серверов": x86 is a percent of the rest of the cart's total (proxy for
|
||||
"цена продажи"), HGX platforms use a fixed multi-year price by chip generation. The pricing
|
||||
table itself lives in `qt_settings["support_pricing"]` so it can be edited in MariaDB without
|
||||
a QuoteForge release — see `bible-local/server-contract-qt-settings.md` for the schema; the
|
||||
fixed list of offerable level×duration codes stays in the frontend, only the price is
|
||||
server-driven;
|
||||
- platform (x86 vs HGX-H100/H200 vs HGX-B200 vs HGX-B300) is auto-detected client-side from the
|
||||
cart's GPU components, the same chip-generation classification used by the rental
|
||||
depreciation calc (`internal/services/rental.go`), so the picker only offers combinations
|
||||
valid for the current configuration;
|
||||
- the support LOT has no `lot_category` (not in the pricelist), so it renders under the
|
||||
"Other" category tab like any other uncategorized item — no new tab/category was added for it.
|
||||
|
||||
## Rental / paid-testing pricing contract
|
||||
|
||||
QuoteForge can quote paid testing / short-to-mid-term rental of a configuration's hardware, per the draft
|
||||
regulation "Регламент расчёта стоимости платного тестирования и аренды GPU-серверов" (methodology may still
|
||||
change; buyout/Step 9 of the regulation is intentionally not implemented).
|
||||
|
||||
Rules:
|
||||
- rental is enabled per **project** via `Project.RentalEnabled` (`qt_projects.rental_enabled`); when set, the
|
||||
configurator shows a 4th top-level tab ("Аренда") for every configuration in that project;
|
||||
- New/БУ condition per component lives only on the configuration, in `Configuration.RentalItems`
|
||||
(`RentalItemCondition{LotName, Condition}`) — it is not a property of the lot/pricelist and does not touch
|
||||
`ConfigItem`/BOM; the same lot_name can be "new" in one configuration and "used" in another;
|
||||
- the "Цена" the methodology depreciates against is `Estimate buy price × (1 + RentalUpliftPercent/100)` —
|
||||
QuoteForge has no per-component sale price, so a single project-configuration-wide uplift percentage stands
|
||||
in for it;
|
||||
- pricing is always quoted per week — Разовый (one-time layer-1 hit) + Еженедельный (recurring); there is no
|
||||
term/weeks input, a sales rep multiplies the weekly rate by however many weeks are needed;
|
||||
- annual BASE support price is **computed automatically**, never entered manually, per "Регламент расчёта
|
||||
стоимости технической поддержки серверов": any GPU component present classifies the configuration as HGX and
|
||||
uses the regulation's fixed per-platform price (H100/H200, B200, B300, by lot_name substring); no GPU present
|
||||
falls back to 5% of the uplifted price sum as an x86 sale-price proxy — `support_code` is pure
|
||||
article-formatting metadata (see `internal/article/generator.go`) and is never resolved to a price, so there
|
||||
is no SVC_-catalog lookup to reuse;
|
||||
- GPU "actual vs stabilized generation" classification for depreciation life (2yr vs 3yr) and the separate
|
||||
GPU "support platform" classification (H100/H200 vs B200 vs B300) are both hardcoded lot_name substring
|
||||
lists in `internal/services/rental.go`, not sourced from `lot_category`;
|
||||
- `RentalItems` and `RentalUpliftPercent` are included in the revision dedup fingerprint
|
||||
(`BuildConfigurationSpecPriceFingerprint`), so rental edits create new revisions like other spec/price-affecting
|
||||
changes;
|
||||
- `internal/services/rental.go` (`RentalService.Calculate`) is stateless: it re-derives categories via
|
||||
`GetLocalLotCategoriesByServerPricelistID` and computes pricing (including the auto support price) from the
|
||||
request body, so calculate calls do not require saving first.
|
||||
|
||||
## Vendor BOM contract
|
||||
|
||||
Vendor BOM is stored in `vendor_spec` on the configuration row.
|
||||
|
||||
@@ -26,6 +26,7 @@ Rules:
|
||||
- user-authored tables must not be dropped as a recovery shortcut;
|
||||
- `local_pricelist_items` is the only valid runtime source of prices and component catalog; do not add a separate component cache table;
|
||||
- `local_pricelist_items.lot_category` is the single source of a LOT's category at runtime (populated by sync from `qt_pricelist_items.lot_category`); do not derive category from a lot_name prefix or from `qt_categories`/`qt_lot_metadata`;
|
||||
- `local_pricelist_items.lot_description` is the single source of a LOT's description at runtime (populated by sync from `qt_pricelist_items.lot_description`); do not join the legacy `lot` table for it. Every read path resolves it through the currently selected pricelist (active estimate, or the configuration's own `PricelistID` where applicable) — see `LocalDB.GetLocalComponent`/`ListComponents` (component views, quote line descriptions) and `LocalDB.GetLocalDescriptionsForLots` (export pricing rows in `internal/services/export.go`). Do not add a second description source (e.g. `VendorSpecItem.Description` from BOM import is a distinct, separate field — it's only ever used as a display fallback in front of the LOT description, never merged back into it);
|
||||
- configuration `items` and `vendor_spec` are stored as JSON payloads inside configuration rows;
|
||||
- `local_components` table has been removed; any reference to it is dead code.
|
||||
|
||||
@@ -80,7 +81,7 @@ These tables are retained for historical data. QuoteForge does not read or write
|
||||
|
||||
Rules:
|
||||
- QuoteForge runtime must not depend on any legacy RFQ tables;
|
||||
- QuoteForge sync reads prices and categories from `qt_pricelists` / `qt_pricelist_items` only;
|
||||
- QuoteForge sync reads prices, categories and descriptions from `qt_pricelists` / `qt_pricelist_items` only;
|
||||
- QuoteForge does not enrich local pricelist rows from `parts_log` or any other raw supplier log table;
|
||||
- normal UI requests must not query MariaDB tables directly;
|
||||
- `qt_client_local_migrations` exists in the 2026-04-15 schema dump, but runtime sync does not depend on it.
|
||||
@@ -192,6 +193,8 @@ PK: lot_name
|
||||
| line_no | int | position within project |
|
||||
| price_updated_at | timestamp | |
|
||||
| vendor_spec | longtext JSON | |
|
||||
| rental_items | JSON | per-lot New/БУ condition for the Аренда tab; see [02-architecture.md](02-architecture.md#rental--paid-testing-pricing-contract) |
|
||||
| rental_uplift_percent | decimal(8,2) DEFAULT 0 | uplift applied to Estimate buy price for rental "Цена" |
|
||||
|
||||
### qt_lot_metadata
|
||||
PK: lot_name
|
||||
@@ -254,12 +257,15 @@ PK: lot_name
|
||||
| pricelist_id | bigint UNSIGNED NOT NULL | FK → qt_pricelists.id |
|
||||
| lot_name | varchar(255) NOT NULL | INDEX with pricelist_id |
|
||||
| lot_category | varchar(50) | |
|
||||
| lot_description | varchar(10000) | added by migration 032; backfilled once from `lot.lot_description`. QF syncs this column directly — do not join `lot` per-row to get a description |
|
||||
| price | decimal(12,2) NOT NULL | |
|
||||
| price_method | varchar(20) | |
|
||||
| price_period_days | bigint DEFAULT 90 | |
|
||||
| price_coefficient | decimal(5,2) DEFAULT 0 | |
|
||||
| manual_price | decimal(12,2) | |
|
||||
| meta_prices | varchar(1000) | |
|
||||
| price_quality | tinyint unsigned, nullable | added by migration 033. Set by the external pricelist-building tool, 0-9, based on quote recency/count per its own per-lot pricing-period settings — QF only reads and displays it, never computes it. |
|
||||
|
||||
`price_quality` is synced through `LocalPricelistItem` (pricelist detail page) and, separately, through `LocalComponent`/`services.ComponentView` (`/api/components`, used by the configurator's search dropdown and item table) — both read paths go through `pricelistItemRow`/`toLocalComponent()` in `internal/localdb/components.go`. The `/api/components` path reads the component universe (`world` ∪ `estimate`, see [decisions/2026-07-24-component-universe-world-union.md](decisions/2026-07-24-component-universe-world-union.md)), where a world-only LOT is forced to `price_quality = 0` — the only place QF writes this field rather than reading it. The color scale (red 0 → yellow 5 → green 9, gradient) lives in **one shared JS module**, `web/static/price-quality.js` (loaded by `base.html` for every page) — `priceQualityColor`/`qualityDotHtml`/`qualityBadgeHtml`/`qualityRowStyle`. Do not reimplement the color scale locally in a template; add a new helper to that module instead. Used in: pricelist detail "Качество" column, configurator search dropdown (colored dot), configurator table (leftmost quality-dot column), pricing tab (row background tint).
|
||||
|
||||
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.
|
||||
|
||||
Fields QF never populates and does not model: `AvailableQty`/`Partnumbers` (removed from `models.PricelistItem` and `LocalPricelistItem` — no writer ever set them; always empty).
|
||||
|
||||
### qt_pricelist_sync_status
|
||||
PK: username
|
||||
@@ -294,6 +300,7 @@ PK: username
|
||||
| tracker_url | varchar(500) | |
|
||||
| is_active | tinyint(1) DEFAULT 1 | |
|
||||
| is_system | tinyint(1) DEFAULT 0 | |
|
||||
| rental_enabled | tinyint(1) DEFAULT 0 | shows the Аренда tab on this project's configurations |
|
||||
| created_at | timestamp | |
|
||||
| updated_at | timestamp ON UPDATE | |
|
||||
|
||||
|
||||
@@ -80,6 +80,8 @@
|
||||
| `PUT` | `/api/configs/:uuid/vendor-spec` | replace vendor BOM |
|
||||
| `POST` | `/api/configs/:uuid/vendor-spec/resolve` | resolve PN -> LOT |
|
||||
| `POST` | `/api/configs/:uuid/vendor-spec/apply` | apply BOM to cart |
|
||||
| `PUT` | `/api/configs/:uuid/rental` | persist Аренда tab state (per-lot New/БУ, weeks, uplift %, annual support) |
|
||||
| `POST` | `/api/configs/:uuid/rental/calculate` | compute rental/paid-testing pricing without persisting |
|
||||
|
||||
## Projects
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
@@ -148,6 +148,55 @@ badge on the tab label when required categories are missing.
|
||||
|
||||
---
|
||||
|
||||
### `support_pricing`
|
||||
|
||||
Price data from "Регламент расчёта стоимости технической поддержки серверов", used by the
|
||||
Base tab's support-level picker to display a computed price next to the chosen support code.
|
||||
This is reference/quoting data only — QF never adds it as a cart line or configuration cost;
|
||||
see [02-architecture.md](02-architecture.md#support-pricing-reference-not-a-cart-item).
|
||||
|
||||
x86 is a percent of sale price (QF approximates sale price as the configuration's Estimate
|
||||
total). HGX platforms (any GPU category component present, classified by chip generation via
|
||||
lot_name substring) use a fixed multi-year price instead. Both are keyed `level -> duration in
|
||||
years (as a JSON string key) -> value`; a combination absent from the table is not offered by
|
||||
the regulation and the picker won't show it.
|
||||
|
||||
**Value format:**
|
||||
|
||||
```json
|
||||
{
|
||||
"x86_percent": {
|
||||
"W": {"3": 0.06},
|
||||
"B": {"1": 0.05, "3": 0.10, "5": 0.14},
|
||||
"S": {"1": 0.07, "3": 0.13, "5": 0.18},
|
||||
"P": {"1": 0.12, "3": 0.20, "5": 0.45}
|
||||
},
|
||||
"hgx_price": {
|
||||
"HGX-H200": {
|
||||
"B": {"1": 20000, "3": 55000, "5": 80000},
|
||||
"S": {"1": 28000, "3": 70000, "5": 100000},
|
||||
"P": {"1": 63000, "3": 105000}
|
||||
},
|
||||
"HGX-B200": {
|
||||
"B": {"1": 40000, "3": 100000, "5": 145000},
|
||||
"S": {"1": 55000, "3": 130000, "5": 185000},
|
||||
"P": {"1": 101000, "3": 176000}
|
||||
},
|
||||
"HGX-B300": {
|
||||
"B": {"1": 40000, "3": 100000, "5": 145000},
|
||||
"S": {"1": 55000, "3": 130000, "5": 185000},
|
||||
"P": {"1": 112000, "3": 187000}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Editing this setting in MariaDB (no QF release needed) changes the price shown by the picker
|
||||
immediately on the next component sync — this is the intended way to keep support pricing
|
||||
current as the regulation evolves.
|
||||
|
||||
---
|
||||
|
||||
## Backward compatibility
|
||||
|
||||
- If `qt_settings` does not exist (old server): QF logs `Warn` during sync and
|
||||
|
||||
+94
-97
@@ -697,6 +697,7 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
// Local-first configuration service (replaces old ConfigurationService)
|
||||
projectService = services.NewProjectService(local)
|
||||
configService := services.NewLocalConfigurationService(local, syncService, quoteService, isOnline)
|
||||
rentalService := services.NewRentalService(local)
|
||||
|
||||
// Data hygiene: remove empty nameless projects and ensure every configuration is attached to a project.
|
||||
if removed, err := local.ConsolidateSystemProjects(); err == nil && removed > 0 {
|
||||
@@ -1100,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
|
||||
}
|
||||
|
||||
@@ -1216,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)
|
||||
@@ -1344,6 +1335,39 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
configs.POST("/:uuid/vendor-spec/resolve", vendorSpecHandler.ResolveVendorSpec)
|
||||
configs.POST("/:uuid/vendor-spec/apply", vendorSpecHandler.ApplyVendorSpec)
|
||||
|
||||
// Rental / paid-testing pricing endpoints (Аренда tab)
|
||||
configs.PUT("/:uuid/rental", func(c *gin.Context) {
|
||||
var req services.RentalUpdateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
respondError(c, http.StatusBadRequest, "invalid request", err)
|
||||
return
|
||||
}
|
||||
config, err := configService.UpdateRentalNoAuth(c.Param("uuid"), &req)
|
||||
if err != nil {
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
|
||||
)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, config)
|
||||
})
|
||||
|
||||
configs.POST("/:uuid/rental/calculate", func(c *gin.Context) {
|
||||
var req services.RentalUpdateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
respondError(c, http.StatusBadRequest, "invalid request", err)
|
||||
return
|
||||
}
|
||||
result, err := rentalService.Calculate(c.Param("uuid"), &req)
|
||||
if err != nil {
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
|
||||
)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, result)
|
||||
})
|
||||
|
||||
configs.PATCH("/:uuid/server-count", func(c *gin.Context) {
|
||||
uuid := c.Param("uuid")
|
||||
var req struct {
|
||||
@@ -1550,21 +1574,25 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
|
||||
// Return simplified list of all projects (UUID + Name only)
|
||||
type ProjectSimple struct {
|
||||
UUID string `json:"uuid"`
|
||||
Code string `json:"code"`
|
||||
Variant string `json:"variant"`
|
||||
Name string `json:"name"`
|
||||
IsActive bool `json:"is_active"`
|
||||
UUID string `json:"uuid"`
|
||||
Code string `json:"code"`
|
||||
Variant string `json:"variant"`
|
||||
Name string `json:"name"`
|
||||
IsActive bool `json:"is_active"`
|
||||
RentalEnabled bool `json:"rental_enabled"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
simplified := make([]ProjectSimple, 0, len(allProjects))
|
||||
for _, p := range allProjects {
|
||||
simplified = append(simplified, ProjectSimple{
|
||||
UUID: p.UUID,
|
||||
Code: p.Code,
|
||||
Variant: p.Variant,
|
||||
Name: derefString(p.Name),
|
||||
IsActive: p.IsActive,
|
||||
UUID: p.UUID,
|
||||
Code: p.Code,
|
||||
Variant: p.Variant,
|
||||
Name: derefString(p.Name),
|
||||
IsActive: p.IsActive,
|
||||
RentalEnabled: p.RentalEnabled,
|
||||
CreatedAt: p.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1583,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)
|
||||
@@ -1601,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)
|
||||
@@ -1622,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)
|
||||
@@ -1644,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"})
|
||||
@@ -1659,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"})
|
||||
@@ -1674,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"})
|
||||
@@ -1700,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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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:
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
|
||||
type BuildOptions struct {
|
||||
ServerModel string
|
||||
SupportCode string
|
||||
ServerPricelist *uint
|
||||
}
|
||||
|
||||
@@ -95,12 +94,8 @@ func Build(local *localdb.LocalDB, items []models.ConfigItem, opts BuildOptions)
|
||||
segs = append(segs, namedSeg{"PSU", psuSeg})
|
||||
}
|
||||
|
||||
if strings.TrimSpace(opts.SupportCode) != "" {
|
||||
code := strings.TrimSpace(opts.SupportCode)
|
||||
if !isSupportCodeValid(code) {
|
||||
return BuildResult{}, fmt.Errorf("invalid_support_code")
|
||||
}
|
||||
segs = append(segs, namedSeg{"SUPPORT", code})
|
||||
if supportSeg := buildSupportSegment(items); supportSeg != "" {
|
||||
segs = append(segs, namedSeg{"SUPPORT", supportSeg})
|
||||
}
|
||||
|
||||
article := strings.Join(namedSegsValues(segs), "-")
|
||||
@@ -132,28 +127,22 @@ func findSegGroup(segs []namedSeg, group string) int {
|
||||
return -1
|
||||
}
|
||||
|
||||
func isSupportCodeValid(code string) bool {
|
||||
if len(code) < 3 {
|
||||
return false
|
||||
}
|
||||
if !strings.Contains(code, "y") {
|
||||
return false
|
||||
}
|
||||
parts := strings.Split(code, "y")
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
return false
|
||||
}
|
||||
for _, r := range parts[0] {
|
||||
if r < '0' || r > '9' {
|
||||
return false
|
||||
// buildSupportSegment finds a support LOT in items (added to the spec via the
|
||||
// Base tab's support picker, e.g. "SVC_3yB_HGX-H200") and returns its
|
||||
// duration+level token ("3yB") for the article. Support is a regular BOM
|
||||
// LOT, not pricelist-backed, so it's detected by lot_name prefix like the
|
||||
// other lot_name-pattern parsers in this file, rather than by lot_category.
|
||||
func buildSupportSegment(items []models.ConfigItem) string {
|
||||
for _, it := range items {
|
||||
if !strings.HasPrefix(strings.ToUpper(it.LotName), "SVC_") {
|
||||
continue
|
||||
}
|
||||
parts := strings.SplitN(it.LotName, "_", 3)
|
||||
if len(parts) >= 2 && parts[1] != "" {
|
||||
return parts[1]
|
||||
}
|
||||
}
|
||||
switch parts[1] {
|
||||
case "W", "B", "S", "P":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func buildCPUSegment(items []models.ConfigItem, cats map[string]string) string {
|
||||
@@ -271,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
|
||||
}
|
||||
@@ -296,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:]
|
||||
|
||||
@@ -44,10 +44,10 @@ func TestBuild_ParsesNetAndPSU(t *testing.T) {
|
||||
{LotName: "NIC_2p25G_MCX512A-AC", Quantity: 1},
|
||||
{LotName: "HBA_2pFC32_Gen6", Quantity: 1},
|
||||
{LotName: "PS_1000W_Platinum", Quantity: 2},
|
||||
{LotName: "SVC_1yW_x86", Quantity: 1},
|
||||
}
|
||||
result, err := Build(local, items, BuildOptions{
|
||||
ServerModel: "DL380GEN11",
|
||||
SupportCode: "1yW",
|
||||
ServerPricelist: &localPL.ServerID,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -59,6 +59,9 @@ func TestBuild_ParsesNetAndPSU(t *testing.T) {
|
||||
if contains(result.Article, "UNKNET") || contains(result.Article, "UNKPSU") {
|
||||
t.Fatalf("unexpected UNK in article: %s", result.Article)
|
||||
}
|
||||
if !contains(result.Article, "1yW") {
|
||||
t.Fatalf("expected support segment 1yW in article: %s", result.Article)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuild_CompressArticle_NoGPU_PSUNotNIC reproduces the bug where 2 PSUs produced
|
||||
|
||||
@@ -51,6 +51,7 @@ func (h *ComponentHandler) List(c *gin.Context) {
|
||||
Category: lc.Category,
|
||||
CategoryName: lc.Category,
|
||||
Model: lc.Model,
|
||||
PriceQuality: lc.PriceQuality,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,6 +82,7 @@ func (h *ComponentHandler) Get(c *gin.Context) {
|
||||
Category: component.Category,
|
||||
CategoryName: component.Category,
|
||||
Model: component.Model,
|
||||
PriceQuality: component.PriceQuality,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -134,10 +136,46 @@ func (h *ComponentHandler) GetConfiguratorSettings(c *gin.Context) {
|
||||
if len(s.RequiredCategories) == 0 {
|
||||
s.RequiredCategories = map[string][]string{"server": {"CPU", "MEM", "BB"}}
|
||||
}
|
||||
if s.SupportPricing == nil {
|
||||
s.SupportPricing = defaultSupportPricing()
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, s)
|
||||
}
|
||||
|
||||
// defaultSupportPricing mirrors "Регламент расчёта стоимости технической
|
||||
// поддержки серверов" (BASE/STANDARD/PREMIUM tiers, x86 % of sale price /
|
||||
// HGX fixed multi-year price by chip generation). Used only when the
|
||||
// qt_settings "support_pricing" key is absent so it can be edited in
|
||||
// MariaDB without a QuoteForge release.
|
||||
func defaultSupportPricing() *localdb.SupportPricingTable {
|
||||
return &localdb.SupportPricingTable{
|
||||
X86Percent: map[string]map[string]float64{
|
||||
"W": {"3": 0.06},
|
||||
"B": {"1": 0.05, "3": 0.10, "5": 0.14},
|
||||
"S": {"1": 0.07, "3": 0.13, "5": 0.18},
|
||||
"P": {"1": 0.12, "3": 0.20, "5": 0.45},
|
||||
},
|
||||
HGXPrice: map[string]map[string]map[string]float64{
|
||||
"HGX-H200": {
|
||||
"B": {"1": 20000, "3": 55000, "5": 80000},
|
||||
"S": {"1": 28000, "3": 70000, "5": 100000},
|
||||
"P": {"1": 63000, "3": 105000},
|
||||
},
|
||||
"HGX-B200": {
|
||||
"B": {"1": 40000, "3": 100000, "5": 145000},
|
||||
"S": {"1": 55000, "3": 130000, "5": 185000},
|
||||
"P": {"1": 101000, "3": 176000},
|
||||
},
|
||||
"HGX-B300": {
|
||||
"B": {"1": 40000, "3": 100000, "5": 145000},
|
||||
"S": {"1": 55000, "3": 130000, "5": 185000},
|
||||
"P": {"1": 112000, "3": 187000},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func defaultConfigTypes() []localdb.ConfigTypeDef {
|
||||
return []localdb.ConfigTypeDef{
|
||||
{
|
||||
|
||||
@@ -180,16 +180,12 @@ func (h *PricelistHandler) GetItems(c *gin.Context) {
|
||||
resultItems := make([]gin.H, 0, len(items))
|
||||
for _, item := range items {
|
||||
resultItems = append(resultItems, gin.H{
|
||||
"id": item.ID,
|
||||
"lot_name": item.LotName,
|
||||
"lot_description": "",
|
||||
"price": item.Price,
|
||||
"category": item.LotCategory,
|
||||
"available_qty": item.AvailableQty,
|
||||
"partnumbers": []string(item.Partnumbers),
|
||||
"partnumber_qtys": map[string]interface{}{},
|
||||
"competitor_names": []string{},
|
||||
"price_spread_pct": nil,
|
||||
"id": item.ID,
|
||||
"lot_name": item.LotName,
|
||||
"lot_description": item.LotDescription,
|
||||
"price": item.Price,
|
||||
"category": item.LotCategory,
|
||||
"price_quality": item.PriceQuality,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ComponentFilter for searching with filters
|
||||
@@ -40,39 +42,94 @@ 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"`
|
||||
Category string `gorm:"column:lot_category"`
|
||||
LotName string `gorm:"column:lot_name"`
|
||||
Category string `gorm:"column:lot_category"`
|
||||
Description string `gorm:"column:lot_description"`
|
||||
PriceQuality *int `gorm:"column:price_quality"`
|
||||
}
|
||||
|
||||
func (r pricelistItemRow) toLocalComponent() LocalComponent {
|
||||
return LocalComponent{
|
||||
LotName: r.LotName,
|
||||
Category: r.Category,
|
||||
LotName: r.LotName,
|
||||
Category: r.Category,
|
||||
LotDescription: r.Description,
|
||||
PriceQuality: r.PriceQuality,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 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").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))
|
||||
@@ -82,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").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))
|
||||
@@ -110,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))
|
||||
}
|
||||
@@ -134,7 +187,7 @@ func (l *LocalDB) ListComponents(filter ComponentFilter, offset, limit int) ([]L
|
||||
}
|
||||
|
||||
var rows []pricelistItemRow
|
||||
if err := db.Select("lot_name, lot_category").Order("lot_name").Offset(offset).Limit(limit).Scan(&rows).Error; err != nil {
|
||||
if err := db.Select("lot_name, lot_category, lot_description, price_quality").Order("lot_name").Offset(offset).Limit(limit).Scan(&rows).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
components := make([]LocalComponent, len(rows))
|
||||
@@ -144,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").
|
||||
Select("lot_name, lot_category").
|
||||
Where("pricelist_id = ? AND UPPER(lot_name) = ?", pricelistID, strings.ToUpper(lotName)).
|
||||
if err := db.
|
||||
Select("lot_name, lot_category, lot_description, price_quality").
|
||||
Where("UPPER(lot_name) = ?", strings.ToUpper(lotName)).
|
||||
First(&row).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -164,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
|
||||
}
|
||||
@@ -184,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
|
||||
}
|
||||
@@ -200,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 {
|
||||
@@ -219,15 +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
|
||||
}
|
||||
|
||||
@@ -74,6 +74,8 @@ func ConfigurationToLocal(cfg *models.Configuration) *LocalConfiguration {
|
||||
VendorSpec: modelVendorSpecToLocal(cfg.VendorSpec),
|
||||
DisablePriceRefresh: cfg.DisablePriceRefresh,
|
||||
OnlyInStock: cfg.OnlyInStock,
|
||||
RentalItems: modelRentalItemsToLocal(cfg.RentalItems),
|
||||
RentalUpliftPercent: cfg.RentalUpliftPercent,
|
||||
Line: cfg.Line,
|
||||
PriceUpdatedAt: cfg.PriceUpdatedAt,
|
||||
CreatedAt: cfg.CreatedAt,
|
||||
@@ -123,6 +125,8 @@ func LocalToConfiguration(local *LocalConfiguration) *models.Configuration {
|
||||
VendorSpec: localVendorSpecToModel(local.VendorSpec),
|
||||
DisablePriceRefresh: local.DisablePriceRefresh,
|
||||
OnlyInStock: local.OnlyInStock,
|
||||
RentalItems: localRentalItemsToModel(local.RentalItems),
|
||||
RentalUpliftPercent: local.RentalUpliftPercent,
|
||||
Line: local.Line,
|
||||
PriceUpdatedAt: local.PriceUpdatedAt,
|
||||
CreatedAt: local.CreatedAt,
|
||||
@@ -231,6 +235,28 @@ func localVendorSpecToModel(spec VendorSpec) models.VendorSpec {
|
||||
return out
|
||||
}
|
||||
|
||||
func modelRentalItemsToLocal(items models.RentalItemConditions) RentalItemConditions {
|
||||
if len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make(RentalItemConditions, len(items))
|
||||
for i, item := range items {
|
||||
out[i] = RentalItemCondition{LotName: item.LotName, Condition: item.Condition}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func localRentalItemsToModel(items RentalItemConditions) models.RentalItemConditions {
|
||||
if len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make(models.RentalItemConditions, len(items))
|
||||
for i, item := range items {
|
||||
out[i] = models.RentalItemCondition{LotName: item.LotName, Condition: item.Condition}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func ProjectToLocal(project *models.Project) *LocalProject {
|
||||
local := &LocalProject{
|
||||
UUID: project.UUID,
|
||||
@@ -241,6 +267,7 @@ func ProjectToLocal(project *models.Project) *LocalProject {
|
||||
TrackerURL: project.TrackerURL,
|
||||
IsActive: project.IsActive,
|
||||
IsSystem: project.IsSystem,
|
||||
RentalEnabled: project.RentalEnabled,
|
||||
CreatedAt: project.CreatedAt,
|
||||
UpdatedAt: project.UpdatedAt,
|
||||
SyncStatus: "pending",
|
||||
@@ -262,6 +289,7 @@ func LocalToProject(local *LocalProject) *models.Project {
|
||||
TrackerURL: local.TrackerURL,
|
||||
IsActive: local.IsActive,
|
||||
IsSystem: local.IsSystem,
|
||||
RentalEnabled: local.RentalEnabled,
|
||||
CreatedAt: local.CreatedAt,
|
||||
UpdatedAt: local.UpdatedAt,
|
||||
}
|
||||
@@ -303,30 +331,25 @@ func LocalToPricelist(local *LocalPricelist) *models.Pricelist {
|
||||
|
||||
// PricelistItemToLocal converts models.PricelistItem to LocalPricelistItem
|
||||
func PricelistItemToLocal(item *models.PricelistItem, localPricelistID uint) *LocalPricelistItem {
|
||||
partnumbers := make(LocalStringList, 0, len(item.Partnumbers))
|
||||
partnumbers = append(partnumbers, item.Partnumbers...)
|
||||
return &LocalPricelistItem{
|
||||
PricelistID: localPricelistID,
|
||||
LotName: models.NormalizeLotName(item.LotName),
|
||||
LotCategory: item.LotCategory,
|
||||
Price: item.Price,
|
||||
AvailableQty: item.AvailableQty,
|
||||
Partnumbers: partnumbers,
|
||||
PricelistID: localPricelistID,
|
||||
LotName: models.NormalizeLotName(item.LotName),
|
||||
LotCategory: item.LotCategory,
|
||||
LotDescription: item.LotDescription,
|
||||
Price: item.Price,
|
||||
PriceQuality: item.PriceQuality,
|
||||
}
|
||||
}
|
||||
|
||||
// LocalToPricelistItem converts LocalPricelistItem to models.PricelistItem
|
||||
func LocalToPricelistItem(local *LocalPricelistItem, serverPricelistID uint) *models.PricelistItem {
|
||||
partnumbers := make([]string, 0, len(local.Partnumbers))
|
||||
partnumbers = append(partnumbers, local.Partnumbers...)
|
||||
return &models.PricelistItem{
|
||||
ID: local.ID,
|
||||
PricelistID: serverPricelistID,
|
||||
LotName: local.LotName,
|
||||
LotCategory: local.LotCategory,
|
||||
Price: local.Price,
|
||||
AvailableQty: local.AvailableQty,
|
||||
Partnumbers: partnumbers,
|
||||
ID: local.ID,
|
||||
PricelistID: serverPricelistID,
|
||||
LotName: local.LotName,
|
||||
LotCategory: local.LotCategory,
|
||||
LotDescription: local.LotDescription,
|
||||
Price: local.Price,
|
||||
PriceQuality: local.PriceQuality,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,6 +211,7 @@ CREATE TABLE local_projects (
|
||||
tracker_url TEXT NULL,
|
||||
is_active INTEGER NOT NULL DEFAULT 1,
|
||||
is_system INTEGER NOT NULL DEFAULT 0,
|
||||
rental_enabled INTEGER NOT NULL DEFAULT 0,
|
||||
created_at DATETIME,
|
||||
updated_at DATETIME,
|
||||
synced_at DATETIME NULL,
|
||||
@@ -1629,6 +1630,51 @@ func (l *LocalDB) GetLocalLotCategoriesByServerPricelistID(serverPricelistID uin
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetLocalDescriptionsForLots returns lot_description for each lot_name from a local
|
||||
// pricelist resolved by server ID. Missing lots are not included in the map.
|
||||
func (l *LocalDB) GetLocalDescriptionsForLots(serverPricelistID uint, lotNames []string) (map[string]string, error) {
|
||||
result := make(map[string]string, len(lotNames))
|
||||
if serverPricelistID == 0 || len(lotNames) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
localPL, err := l.GetLocalPricelistByServerID(serverPricelistID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
type row struct {
|
||||
LotName string `gorm:"column:lot_name"`
|
||||
LotDescription string `gorm:"column:lot_description"`
|
||||
}
|
||||
// Build uppercase → original mapping so result keys match what the caller passed.
|
||||
upperToOrig := make(map[string]string, len(lotNames))
|
||||
upper := make([]string, len(lotNames))
|
||||
for i, n := range lotNames {
|
||||
u := strings.ToUpper(n)
|
||||
upper[i] = u
|
||||
upperToOrig[u] = n
|
||||
}
|
||||
var rows []row
|
||||
if err := l.db.Model(&LocalPricelistItem{}).
|
||||
Select("lot_name, lot_description").
|
||||
Where("pricelist_id = ? AND UPPER(lot_name) IN ?", localPL.ID, upper).
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, r := range rows {
|
||||
if r.LotDescription == "" {
|
||||
continue
|
||||
}
|
||||
orig := upperToOrig[strings.ToUpper(r.LotName)]
|
||||
if orig == "" {
|
||||
orig = r.LotName
|
||||
}
|
||||
result[orig] = r.LotDescription
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// MarkPricelistAsUsed marks a pricelist as used by a configuration
|
||||
func (l *LocalDB) MarkPricelistAsUsed(pricelistID uint, isUsed bool) error {
|
||||
return l.db.Model(&LocalPricelist{}).Where("id = ?", pricelistID).
|
||||
|
||||
@@ -124,6 +124,129 @@ var localMigrations = []localMigration{
|
||||
name: "Deduplicate local_pricelist_items and add unique index on (pricelist_id, lot_name)",
|
||||
run: deduplicatePricelistItemsAndAddUniqueIndex,
|
||||
},
|
||||
{
|
||||
id: "2026_07_22_local_project_rental_enabled",
|
||||
name: "Add rental_enabled to local_projects",
|
||||
run: addLocalProjectRentalEnabled,
|
||||
},
|
||||
{
|
||||
id: "2026_07_22_pricelist_items_add_description_drop_unused",
|
||||
name: "Add lot_description to local_pricelist_items, drop unused available_qty/partnumbers",
|
||||
run: addPricelistItemDescriptionDropUnused,
|
||||
},
|
||||
{
|
||||
id: "2026_07_22_pricelist_items_price_quality",
|
||||
name: "Add price_quality to local_pricelist_items",
|
||||
run: addLocalPricelistItemPriceQuality,
|
||||
},
|
||||
}
|
||||
|
||||
func addLocalPricelistItemPriceQuality(tx *gorm.DB) error {
|
||||
type columnInfo struct {
|
||||
Name string `gorm:"column:name"`
|
||||
}
|
||||
|
||||
var columns []columnInfo
|
||||
if err := tx.Raw(`
|
||||
SELECT name FROM pragma_table_info('local_pricelist_items')
|
||||
WHERE name = 'price_quality'
|
||||
`).Scan(&columns).Error; err != nil {
|
||||
return fmt.Errorf("check local_pricelist_items(price_quality) existence: %w", err)
|
||||
}
|
||||
|
||||
if len(columns) > 0 {
|
||||
slog.Info("price_quality already present on local_pricelist_items")
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := tx.Exec(`ALTER TABLE local_pricelist_items ADD COLUMN price_quality INTEGER`).Error; err != nil {
|
||||
return fmt.Errorf("add local_pricelist_items.price_quality: %w", err)
|
||||
}
|
||||
|
||||
slog.Info("added price_quality to local_pricelist_items")
|
||||
return nil
|
||||
}
|
||||
|
||||
func addPricelistItemDescriptionDropUnused(tx *gorm.DB) error {
|
||||
type columnInfo struct {
|
||||
Name string `gorm:"column:name"`
|
||||
}
|
||||
|
||||
var columns []columnInfo
|
||||
if err := tx.Raw(`
|
||||
SELECT name FROM pragma_table_info('local_pricelist_items')
|
||||
WHERE name IN ('lot_description', 'available_qty', 'partnumbers')
|
||||
`).Scan(&columns).Error; err != nil {
|
||||
return fmt.Errorf("check local_pricelist_items columns: %w", err)
|
||||
}
|
||||
|
||||
have := make(map[string]bool, len(columns))
|
||||
for _, c := range columns {
|
||||
have[c.Name] = true
|
||||
}
|
||||
|
||||
if have["lot_description"] && !have["available_qty"] && !have["partnumbers"] {
|
||||
slog.Info("local_pricelist_items already migrated to description-only schema")
|
||||
return nil
|
||||
}
|
||||
|
||||
// SQLite: recreate table without the never-populated available_qty/partnumbers
|
||||
// columns, adding lot_description (synced from qt_pricelist_items.lot_description).
|
||||
if err := tx.Exec(`
|
||||
CREATE TABLE local_pricelist_items_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
pricelist_id INTEGER NOT NULL,
|
||||
lot_name TEXT NOT NULL,
|
||||
lot_category TEXT,
|
||||
lot_description TEXT,
|
||||
price REAL NOT NULL
|
||||
)
|
||||
`).Error; err != nil {
|
||||
return fmt.Errorf("create new local_pricelist_items table: %w", err)
|
||||
}
|
||||
|
||||
if err := tx.Exec(`
|
||||
INSERT INTO local_pricelist_items_new (id, pricelist_id, lot_name, lot_category, price)
|
||||
SELECT id, pricelist_id, lot_name, lot_category, price
|
||||
FROM local_pricelist_items
|
||||
`).Error; err != nil {
|
||||
return fmt.Errorf("copy data to new local_pricelist_items table: %w", err)
|
||||
}
|
||||
|
||||
if err := tx.Exec(`DROP TABLE local_pricelist_items`).Error; err != nil {
|
||||
return fmt.Errorf("drop old local_pricelist_items table: %w", err)
|
||||
}
|
||||
|
||||
if err := tx.Exec(`ALTER TABLE local_pricelist_items_new RENAME TO local_pricelist_items`).Error; err != nil {
|
||||
return fmt.Errorf("rename new local_pricelist_items table: %w", err)
|
||||
}
|
||||
|
||||
if err := tx.Exec(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_local_pricelist_items_pricelist_lot_unique
|
||||
ON local_pricelist_items(pricelist_id, lot_name)
|
||||
`).Error; err != nil {
|
||||
return fmt.Errorf("recreate unique index on local_pricelist_items: %w", err)
|
||||
}
|
||||
|
||||
if err := tx.Exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_local_pricelist_items_lot_category
|
||||
ON local_pricelist_items(lot_category)
|
||||
`).Error; err != nil {
|
||||
return fmt.Errorf("recreate idx_local_pricelist_items_lot_category: %w", err)
|
||||
}
|
||||
|
||||
slog.Info("added lot_description to local_pricelist_items and dropped available_qty/partnumbers")
|
||||
return nil
|
||||
}
|
||||
|
||||
func addLocalProjectRentalEnabled(tx *gorm.DB) error {
|
||||
if err := tx.Exec(`ALTER TABLE local_projects ADD COLUMN rental_enabled INTEGER NOT NULL DEFAULT 0`).Error; err != nil {
|
||||
if !strings.Contains(strings.ToLower(err.Error()), "duplicate") &&
|
||||
!strings.Contains(strings.ToLower(err.Error()), "exists") {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type localPartnumberCatalogRow struct {
|
||||
@@ -1120,4 +1243,3 @@ func deduplicatePricelistItemsAndAddUniqueIndex(tx *gorm.DB) error {
|
||||
slog.Info("deduplicated local_pricelist_items and added unique index")
|
||||
return nil
|
||||
}
|
||||
|
||||
+51
-11
@@ -112,13 +112,15 @@ type LocalConfiguration struct {
|
||||
CompetitorPricelistID *uint `gorm:"index" json:"competitor_pricelist_id,omitempty"`
|
||||
DisablePriceRefresh bool `gorm:"default:false" json:"disable_price_refresh"`
|
||||
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
|
||||
RentalItems RentalItemConditions `gorm:"type:text" json:"rental_items,omitempty"`
|
||||
RentalUpliftPercent float64 `gorm:"default:0" json:"rental_uplift_percent"`
|
||||
VendorSpec VendorSpec `gorm:"type:text" json:"vendor_spec,omitempty"`
|
||||
Line int `gorm:"column:line_no;index" json:"line"`
|
||||
PriceUpdatedAt *time.Time `gorm:"type:timestamp" json:"price_updated_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
SyncedAt *time.Time `json:"synced_at"`
|
||||
ConfigType string `gorm:"default:server" json:"config_type"` // "server" | "storage"
|
||||
ConfigType string `gorm:"default:server" json:"config_type"` // "server" | "storage"
|
||||
SyncStatus string `gorm:"default:'local'" json:"sync_status"` // 'local', 'synced', 'modified'
|
||||
OriginalUserID uint `json:"original_user_id"` // UserID from MariaDB for reference
|
||||
OriginalUsername string `gorm:"not null;default:'';index" json:"original_username"`
|
||||
@@ -141,6 +143,7 @@ type LocalProject struct {
|
||||
TrackerURL string `json:"tracker_url"`
|
||||
IsActive bool `gorm:"default:true;index" json:"is_active"`
|
||||
IsSystem bool `gorm:"default:false;index" json:"is_system"`
|
||||
RentalEnabled bool `gorm:"default:false" json:"rental_enabled"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
SyncedAt *time.Time `json:"synced_at,omitempty"`
|
||||
@@ -177,7 +180,7 @@ type LocalPricelist struct {
|
||||
Name string `json:"name"`
|
||||
CreatedAt time.Time `gorm:"index:idx_local_pricelists_source_created_at,priority:2,sort:desc" json:"created_at"`
|
||||
SyncedAt time.Time `json:"synced_at"`
|
||||
IsUsed bool `gorm:"default:false" json:"is_used"` // Used by any local configuration
|
||||
IsUsed bool `gorm:"default:false" json:"is_used"` // Used by any local configuration
|
||||
IsActive bool `gorm:"not null;default:true;index" json:"is_active"` // Mirrors qt_pricelists.is_active
|
||||
}
|
||||
|
||||
@@ -187,13 +190,16 @@ func (LocalPricelist) TableName() string {
|
||||
|
||||
// LocalPricelistItem stores pricelist items
|
||||
type LocalPricelistItem struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
PricelistID uint `gorm:"not null;index" json:"pricelist_id"`
|
||||
LotName string `gorm:"not null" json:"lot_name"`
|
||||
LotCategory string `gorm:"column:lot_category" json:"lot_category,omitempty"`
|
||||
Price float64 `gorm:"not null" json:"price"`
|
||||
AvailableQty *float64 `json:"available_qty,omitempty"`
|
||||
Partnumbers LocalStringList `gorm:"type:text" json:"partnumbers,omitempty"`
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
PricelistID uint `gorm:"not null;index" json:"pricelist_id"`
|
||||
LotName string `gorm:"not null" json:"lot_name"`
|
||||
LotCategory string `gorm:"column:lot_category" json:"lot_category,omitempty"`
|
||||
LotDescription string `gorm:"column:lot_description" json:"lot_description,omitempty"`
|
||||
Price float64 `gorm:"not null" json:"price"`
|
||||
|
||||
// PriceQuality mirrors qt_pricelist_items.price_quality: a 0-9 score set by
|
||||
// the external pricing tool. 7-9 good, 4-6 warning, 0-3 poor.
|
||||
PriceQuality *int `gorm:"column:price_quality" json:"price_quality,omitempty"`
|
||||
}
|
||||
|
||||
func (LocalPricelistItem) TableName() string {
|
||||
@@ -207,6 +213,7 @@ type LocalComponent struct {
|
||||
LotDescription string `json:"lot_description"`
|
||||
Category string `json:"category"`
|
||||
Model string `json:"model"`
|
||||
PriceQuality *int `json:"price_quality,omitempty"`
|
||||
}
|
||||
|
||||
func (LocalComponent) TableName() string {
|
||||
@@ -298,6 +305,39 @@ func (LocalPartnumberBookItem) TableName() string {
|
||||
return "local_partnumber_book_items"
|
||||
}
|
||||
|
||||
// RentalItemCondition tracks New/БУ condition per component for a single
|
||||
// configuration's Аренда (rental) tab. Independent of the lot's catalog data.
|
||||
type RentalItemCondition struct {
|
||||
LotName string `json:"lot_name"`
|
||||
Condition string `json:"condition"` // "new" or "used"
|
||||
}
|
||||
|
||||
type RentalItemConditions []RentalItemCondition
|
||||
|
||||
func (r RentalItemConditions) Value() (driver.Value, error) {
|
||||
if r == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return json.Marshal(r)
|
||||
}
|
||||
|
||||
func (r *RentalItemConditions) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
*r = nil
|
||||
return nil
|
||||
}
|
||||
var bytes []byte
|
||||
switch v := value.(type) {
|
||||
case []byte:
|
||||
bytes = v
|
||||
case string:
|
||||
bytes = []byte(v)
|
||||
default:
|
||||
return errors.New("type assertion failed for RentalItemConditions")
|
||||
}
|
||||
return json.Unmarshal(bytes, r)
|
||||
}
|
||||
|
||||
// VendorSpecItem represents a single row in a vendor BOM specification
|
||||
type VendorSpecItem struct {
|
||||
SortOrder int `json:"sort_order"`
|
||||
@@ -329,8 +369,8 @@ type VendorSpecLotMapping struct {
|
||||
// SyncLogEntry records the outcome of a single sync operation for diagnostics.
|
||||
type SyncLogEntry struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
SyncType string `gorm:"not null;index;size:32" json:"sync_type"` // components | pricelists | push | full
|
||||
Status string `gorm:"not null;size:16" json:"status"` // ok | error | skipped
|
||||
SyncType string `gorm:"not null;index;size:32" json:"sync_type"` // components | pricelists | push | full
|
||||
Status string `gorm:"not null;size:16" json:"status"` // ok | error | skipped
|
||||
ErrorText string `gorm:"size:1000" json:"error_text,omitempty"`
|
||||
SyncedCount int `gorm:"default:0" json:"synced_count"`
|
||||
StartedAt time.Time `gorm:"not null;index" json:"started_at"`
|
||||
|
||||
@@ -31,14 +31,25 @@ type TabDef struct {
|
||||
Sections []TabSection `json:"sections,omitempty"`
|
||||
}
|
||||
|
||||
// ConfiguratorSettings holds all four server-driven settings consumed by the configurator.
|
||||
// SupportPricingTable holds the price data from "Регламент расчёта стоимости
|
||||
// технической поддержки серверов": x86 is a percent of sale price, HGX
|
||||
// platforms (by chip generation) are a fixed multi-year price. Both are
|
||||
// keyed level -> duration-in-years (as a string, since JSON object keys are
|
||||
// strings) -> value. Missing combos are not offered by the regulation.
|
||||
type SupportPricingTable struct {
|
||||
X86Percent map[string]map[string]float64 `json:"x86_percent"`
|
||||
HGXPrice map[string]map[string]map[string]float64 `json:"hgx_price"` // platform -> level -> years -> USD
|
||||
}
|
||||
|
||||
// ConfiguratorSettings holds all server-driven settings consumed by the configurator.
|
||||
// Fields are nil/empty when the corresponding qt_settings key is absent or unparseable;
|
||||
// callers are expected to apply hardcoded fallbacks in that case.
|
||||
type ConfiguratorSettings struct {
|
||||
ConfigTypes []ConfigTypeDef `json:"config_types"`
|
||||
TabConfig []TabDef `json:"tab_config"`
|
||||
AlwaysVisibleTabs []string `json:"always_visible_tabs"`
|
||||
RequiredCategories map[string][]string `json:"required_categories"`
|
||||
ConfigTypes []ConfigTypeDef `json:"config_types"`
|
||||
TabConfig []TabDef `json:"tab_config"`
|
||||
AlwaysVisibleTabs []string `json:"always_visible_tabs"`
|
||||
RequiredCategories map[string][]string `json:"required_categories"`
|
||||
SupportPricing *SupportPricingTable `json:"support_pricing,omitempty"`
|
||||
}
|
||||
|
||||
// SyncQtSettings reads all rows from qt_settings on MariaDB and replaces the
|
||||
@@ -93,7 +104,7 @@ func (l *LocalDB) GetQtSetting(name string) (value string, found bool, err error
|
||||
func (l *LocalDB) GetConfiguratorSettings() (*ConfiguratorSettings, error) {
|
||||
out := &ConfiguratorSettings{}
|
||||
|
||||
keys := []string{"config_types", "tab_config", "always_visible_tabs", "required_categories"}
|
||||
keys := []string{"config_types", "tab_config", "always_visible_tabs", "required_categories", "support_pricing"}
|
||||
for _, key := range keys {
|
||||
raw, found, err := l.GetQtSetting(key)
|
||||
if err != nil {
|
||||
@@ -119,6 +130,13 @@ func (l *LocalDB) GetConfiguratorSettings() (*ConfiguratorSettings, error) {
|
||||
if err := json.Unmarshal([]byte(raw), &out.RequiredCategories); err != nil {
|
||||
slog.Warn("failed to parse required_categories setting", "error", err)
|
||||
}
|
||||
case "support_pricing":
|
||||
var table SupportPricingTable
|
||||
if err := json.Unmarshal([]byte(raw), &table); err != nil {
|
||||
slog.Warn("failed to parse support_pricing setting", "error", err)
|
||||
} else {
|
||||
out.SupportPricing = &table
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +31,8 @@ func BuildConfigurationSnapshot(localCfg *LocalConfiguration) (string, error) {
|
||||
"competitor_pricelist_id": localCfg.CompetitorPricelistID,
|
||||
"disable_price_refresh": localCfg.DisablePriceRefresh,
|
||||
"only_in_stock": localCfg.OnlyInStock,
|
||||
"rental_items": localCfg.RentalItems,
|
||||
"rental_uplift_percent": localCfg.RentalUpliftPercent,
|
||||
"vendor_spec": localCfg.VendorSpec,
|
||||
"line": localCfg.Line,
|
||||
"price_updated_at": localCfg.PriceUpdatedAt,
|
||||
@@ -67,8 +69,10 @@ func DecodeConfigurationSnapshot(data string) (*LocalConfiguration, error) {
|
||||
PricelistID *uint `json:"pricelist_id"`
|
||||
WarehousePricelistID *uint `json:"warehouse_pricelist_id"`
|
||||
CompetitorPricelistID *uint `json:"competitor_pricelist_id"`
|
||||
DisablePriceRefresh bool `json:"disable_price_refresh"`
|
||||
OnlyInStock bool `json:"only_in_stock"`
|
||||
DisablePriceRefresh bool `json:"disable_price_refresh"`
|
||||
OnlyInStock bool `json:"only_in_stock"`
|
||||
RentalItems RentalItemConditions `json:"rental_items"`
|
||||
RentalUpliftPercent float64 `json:"rental_uplift_percent"`
|
||||
VendorSpec VendorSpec `json:"vendor_spec"`
|
||||
Line int `json:"line"`
|
||||
PriceUpdatedAt *time.Time `json:"price_updated_at"`
|
||||
@@ -103,6 +107,8 @@ func DecodeConfigurationSnapshot(data string) (*LocalConfiguration, error) {
|
||||
CompetitorPricelistID: snapshot.CompetitorPricelistID,
|
||||
DisablePriceRefresh: snapshot.DisablePriceRefresh,
|
||||
OnlyInStock: snapshot.OnlyInStock,
|
||||
RentalItems: snapshot.RentalItems,
|
||||
RentalUpliftPercent: snapshot.RentalUpliftPercent,
|
||||
VendorSpec: snapshot.VendorSpec,
|
||||
Line: snapshot.Line,
|
||||
PriceUpdatedAt: snapshot.PriceUpdatedAt,
|
||||
@@ -121,6 +127,8 @@ type configurationSpecPriceFingerprint struct {
|
||||
CompetitorPricelistID *uint `json:"competitor_pricelist_id,omitempty"`
|
||||
DisablePriceRefresh bool `json:"disable_price_refresh"`
|
||||
OnlyInStock bool `json:"only_in_stock"`
|
||||
RentalItems RentalItemConditions `json:"rental_items,omitempty"`
|
||||
RentalUpliftPercent float64 `json:"rental_uplift_percent"`
|
||||
VendorSpec VendorSpec `json:"vendor_spec,omitempty"`
|
||||
}
|
||||
|
||||
@@ -151,6 +159,12 @@ func BuildConfigurationSpecPriceFingerprint(localCfg *LocalConfiguration) (strin
|
||||
return items[i].UnitPrice < items[j].UnitPrice
|
||||
})
|
||||
|
||||
rentalItems := make(RentalItemConditions, len(localCfg.RentalItems))
|
||||
copy(rentalItems, localCfg.RentalItems)
|
||||
sort.Slice(rentalItems, func(i, j int) bool {
|
||||
return rentalItems[i].LotName < rentalItems[j].LotName
|
||||
})
|
||||
|
||||
payload := configurationSpecPriceFingerprint{
|
||||
Items: items,
|
||||
ServerCount: localCfg.ServerCount,
|
||||
@@ -161,6 +175,8 @@ func BuildConfigurationSpecPriceFingerprint(localCfg *LocalConfiguration) (strin
|
||||
CompetitorPricelistID: localCfg.CompetitorPricelistID,
|
||||
DisablePriceRefresh: localCfg.DisablePriceRefresh,
|
||||
OnlyInStock: localCfg.OnlyInStock,
|
||||
RentalItems: rentalItems,
|
||||
RentalUpliftPercent: localCfg.RentalUpliftPercent,
|
||||
VendorSpec: localCfg.VendorSpec,
|
||||
}
|
||||
|
||||
|
||||
@@ -64,6 +64,41 @@ type VendorSpecItem struct {
|
||||
LotMappings []VendorSpecLotMapping `json:"lot_mappings,omitempty"`
|
||||
}
|
||||
|
||||
// RentalItemCondition tracks whether a component is being rented/tested as
|
||||
// new or used hardware, for a single configuration's Аренда tab. This is
|
||||
// independent of the lot's catalog data: the same lot_name can be "new" in
|
||||
// one configuration and "used" in another.
|
||||
type RentalItemCondition struct {
|
||||
LotName string `json:"lot_name"`
|
||||
Condition string `json:"condition"` // "new" or "used"
|
||||
}
|
||||
|
||||
type RentalItemConditions []RentalItemCondition
|
||||
|
||||
func (r RentalItemConditions) Value() (driver.Value, error) {
|
||||
if r == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return json.Marshal(r)
|
||||
}
|
||||
|
||||
func (r *RentalItemConditions) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
*r = nil
|
||||
return nil
|
||||
}
|
||||
var bytes []byte
|
||||
switch v := value.(type) {
|
||||
case []byte:
|
||||
bytes = v
|
||||
case string:
|
||||
bytes = []byte(v)
|
||||
default:
|
||||
return errors.New("type assertion failed for RentalItemConditions")
|
||||
}
|
||||
return json.Unmarshal(bytes, r)
|
||||
}
|
||||
|
||||
type VendorSpec []VendorSpecItem
|
||||
|
||||
func (v VendorSpec) Value() (driver.Value, error) {
|
||||
@@ -114,6 +149,8 @@ type Configuration struct {
|
||||
ConfigType string `gorm:"size:20;default:server" json:"config_type"` // "server" | "storage"
|
||||
DisablePriceRefresh bool `gorm:"default:false" json:"disable_price_refresh"`
|
||||
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
|
||||
RentalItems RentalItemConditions `gorm:"type:json" json:"rental_items,omitempty"`
|
||||
RentalUpliftPercent float64 `gorm:"type:decimal(8,2);default:0" json:"rental_uplift_percent"`
|
||||
Line int `gorm:"column:line_no;index" json:"line"`
|
||||
PriceUpdatedAt *time.Time `gorm:"type:timestamp" json:"price_updated_at,omitempty"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
|
||||
@@ -7,14 +7,3 @@ import "strings"
|
||||
func NormalizeLotName(s string) string {
|
||||
return strings.ToUpper(strings.TrimSpace(s))
|
||||
}
|
||||
|
||||
// Lot represents existing lot table
|
||||
type Lot struct {
|
||||
LotName string `gorm:"column:lot_name;primaryKey;size:255" json:"lot_name"`
|
||||
LotDescription string `gorm:"column:lot_description;size:10000" json:"lot_description"`
|
||||
LotCategory *string `gorm:"column:lot_category;size:50" json:"lot_category"`
|
||||
}
|
||||
|
||||
func (Lot) TableName() string {
|
||||
return "lot"
|
||||
}
|
||||
@@ -55,24 +55,17 @@ func (Pricelist) TableName() string {
|
||||
|
||||
// PricelistItem represents a single item in a pricelist
|
||||
type PricelistItem struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
PricelistID uint `gorm:"not null;index:idx_pricelist_lot" json:"pricelist_id"`
|
||||
LotName string `gorm:"size:255;not null;index:idx_pricelist_lot" json:"lot_name"`
|
||||
LotCategory string `gorm:"column:lot_category;size:50" json:"lot_category,omitempty"`
|
||||
Price float64 `gorm:"type:decimal(12,2);not null" json:"price"`
|
||||
PriceMethod string `gorm:"size:20" json:"price_method"`
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
PricelistID uint `gorm:"not null;index:idx_pricelist_lot" json:"pricelist_id"`
|
||||
LotName string `gorm:"size:255;not null;index:idx_pricelist_lot" json:"lot_name"`
|
||||
LotCategory string `gorm:"column:lot_category;size:50" json:"lot_category,omitempty"`
|
||||
LotDescription string `gorm:"column:lot_description;size:10000" json:"lot_description,omitempty"`
|
||||
Price float64 `gorm:"type:decimal(12,2);not null" json:"price"`
|
||||
|
||||
// Price calculation settings (snapshot from qt_lot_metadata)
|
||||
PricePeriodDays int `gorm:"default:90" json:"price_period_days"`
|
||||
PriceCoefficient float64 `gorm:"type:decimal(5,2);default:0" json:"price_coefficient"`
|
||||
ManualPrice *float64 `gorm:"type:decimal(12,2)" json:"manual_price,omitempty"`
|
||||
MetaPrices string `gorm:"size:1000" json:"meta_prices,omitempty"`
|
||||
|
||||
// Virtual fields for display
|
||||
LotDescription string `gorm:"-" json:"lot_description,omitempty"`
|
||||
Category string `gorm:"-" json:"category,omitempty"`
|
||||
AvailableQty *float64 `gorm:"-" json:"available_qty,omitempty"`
|
||||
Partnumbers []string `gorm:"-" json:"partnumbers,omitempty"`
|
||||
// PriceQuality is a 0-9 score set by the external pricing tool that builds
|
||||
// the pricelist (based on quote recency/count per its own per-lot settings).
|
||||
// 7-9 = good, 4-6 = warning, 0-3 = poor. QF only displays it, never computes it.
|
||||
PriceQuality *int `gorm:"column:price_quality" json:"price_quality,omitempty"`
|
||||
}
|
||||
|
||||
func (PricelistItem) TableName() string {
|
||||
|
||||
@@ -12,6 +12,7 @@ type Project struct {
|
||||
TrackerURL string `gorm:"size:500" json:"tracker_url"`
|
||||
IsActive bool `gorm:"default:true;index" json:"is_active"`
|
||||
IsSystem bool `gorm:"default:false;index" json:"is_system"`
|
||||
RentalEnabled bool `gorm:"default:false" json:"rental_enabled"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -234,15 +234,6 @@ func (r *PricelistRepository) GetItems(pricelistID uint, offset, limit int, sear
|
||||
return nil, 0, fmt.Errorf("listing pricelist items: %w", err)
|
||||
}
|
||||
|
||||
// Enrich with lot descriptions
|
||||
for i := range items {
|
||||
var lot models.Lot
|
||||
if err := r.db.Where("lot_name = ?", items[i].LotName).First(&lot).Error; err == nil {
|
||||
items[i].LotDescription = lot.LotDescription
|
||||
}
|
||||
items[i].Category = strings.TrimSpace(items[i].LotCategory)
|
||||
}
|
||||
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -177,7 +177,7 @@ func newTestPricelistRepository(t *testing.T) *PricelistRepository {
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&models.Pricelist{}, &models.PricelistItem{}, &models.Lot{}); err != nil {
|
||||
if err := db.AutoMigrate(&models.Pricelist{}, &models.PricelistItem{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
return NewPricelistRepository(db)
|
||||
|
||||
@@ -38,6 +38,7 @@ func (r *ProjectRepository) UpsertByUUID(project *models.Project) error {
|
||||
"tracker_url",
|
||||
"is_active",
|
||||
"is_system",
|
||||
"rental_enabled",
|
||||
"updated_at",
|
||||
}),
|
||||
}).Create(project).Error; err != nil {
|
||||
|
||||
@@ -14,4 +14,5 @@ type ComponentView struct {
|
||||
Category string `json:"category"`
|
||||
CategoryName string `json:"category_name"`
|
||||
Model string `json:"model"`
|
||||
PriceQuality *int `json:"price_quality,omitempty"`
|
||||
}
|
||||
+48
-11
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -687,8 +697,35 @@ func (s *ExportService) batchLookupPrices(serverPricelistID *uint, lots []string
|
||||
return prices
|
||||
}
|
||||
|
||||
func (s *ExportService) resolveLotDescriptions(_ *models.Configuration, _ *localdb.LocalConfiguration) map[string]string {
|
||||
return map[string]string{}
|
||||
// resolveLotDescriptions returns each LOT's description from the configuration's
|
||||
// currently selected estimate pricelist (falling back to the latest active one),
|
||||
// mirroring the pricelist resolution in resolvePricingTotals. This is the single
|
||||
// source of LOT description across the project — see bible-local/03-database.md.
|
||||
func (s *ExportService) resolveLotDescriptions(cfg *models.Configuration, localCfg *localdb.LocalConfiguration) map[string]string {
|
||||
if s.localDB == nil {
|
||||
return map[string]string{}
|
||||
}
|
||||
|
||||
lots := collectPricingLots(cfg, localCfg, true)
|
||||
if len(lots) == 0 {
|
||||
return map[string]string{}
|
||||
}
|
||||
|
||||
estimateID := cfg.PricelistID
|
||||
if estimateID == nil || *estimateID == 0 {
|
||||
if latest, err := s.localDB.GetLatestLocalPricelistBySource("estimate"); err == nil && latest != nil {
|
||||
estimateID = &latest.ServerID
|
||||
}
|
||||
}
|
||||
if estimateID == nil || *estimateID == 0 {
|
||||
return map[string]string{}
|
||||
}
|
||||
|
||||
descriptions, err := s.localDB.GetLocalDescriptionsForLots(*estimateID, lots)
|
||||
if err != nil {
|
||||
return map[string]string{}
|
||||
}
|
||||
return descriptions
|
||||
}
|
||||
|
||||
func collectPricingLots(cfg *models.Configuration, localCfg *localdb.LocalConfiguration, includeBOM bool) []string {
|
||||
@@ -847,13 +884,13 @@ func pricingCSVRow(row ProjectPricingExportRow, opts ProjectPricingExportOptions
|
||||
record = append(record, formatMoneyValue(row.ManualPrice))
|
||||
}
|
||||
var worldCols []string
|
||||
if row.EstimateWorld {
|
||||
if opts.IncludeEstimate && row.EstimateWorld {
|
||||
worldCols = append(worldCols, "Estimate")
|
||||
}
|
||||
if row.StockWorld {
|
||||
if opts.IncludeStock && row.StockWorld {
|
||||
worldCols = append(worldCols, "Stock")
|
||||
}
|
||||
if row.CompetitorWorld {
|
||||
if opts.IncludeCompetitor && row.CompetitorWorld {
|
||||
worldCols = append(worldCols, "Конкуренты")
|
||||
}
|
||||
comment := ""
|
||||
|
||||
@@ -71,7 +71,6 @@ func (s *LocalConfigurationService) Create(ownerUsername string, req *CreateConf
|
||||
if strings.TrimSpace(req.ServerModel) != "" {
|
||||
articleResult, articleErr := article.Build(s.localDB, req.Items, article.BuildOptions{
|
||||
ServerModel: req.ServerModel,
|
||||
SupportCode: req.SupportCode,
|
||||
ServerPricelist: pricelistID,
|
||||
})
|
||||
if articleErr != nil {
|
||||
@@ -169,7 +168,6 @@ func (s *LocalConfigurationService) Update(uuid string, ownerUsername string, re
|
||||
if strings.TrimSpace(req.ServerModel) != "" {
|
||||
articleResult, articleErr := article.Build(s.localDB, req.Items, article.BuildOptions{
|
||||
ServerModel: req.ServerModel,
|
||||
SupportCode: req.SupportCode,
|
||||
ServerPricelist: pricelistID,
|
||||
})
|
||||
if articleErr != nil {
|
||||
@@ -226,7 +224,6 @@ func (s *LocalConfigurationService) BuildArticlePreview(req *ArticlePreviewReque
|
||||
}
|
||||
return article.Build(s.localDB, req.Items, article.BuildOptions{
|
||||
ServerModel: req.ServerModel,
|
||||
SupportCode: req.SupportCode,
|
||||
ServerPricelist: pricelistID,
|
||||
})
|
||||
}
|
||||
@@ -534,7 +531,6 @@ func (s *LocalConfigurationService) UpdateNoAuth(uuid string, req *CreateConfigR
|
||||
if strings.TrimSpace(req.ServerModel) != "" {
|
||||
articleResult, articleErr := article.Build(s.localDB, req.Items, article.BuildOptions{
|
||||
ServerModel: req.ServerModel,
|
||||
SupportCode: req.SupportCode,
|
||||
ServerPricelist: pricelistID,
|
||||
})
|
||||
if articleErr != nil {
|
||||
@@ -1325,6 +1321,40 @@ func (s *LocalConfigurationService) UpdateVendorSpecNoAuth(uuid string, spec loc
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// RentalUpdateRequest carries the editable fields of a configuration's
|
||||
// Аренда (rental) tab. Persisted independently of the BOM/pricing tabs.
|
||||
type RentalUpdateRequest struct {
|
||||
Items []models.RentalItemCondition `json:"items"`
|
||||
UpliftPercent float64 `json:"uplift_percent"`
|
||||
}
|
||||
|
||||
// UpdateRentalNoAuth updates only the rental fields of a configuration without ownership check.
|
||||
func (s *LocalConfigurationService) UpdateRentalNoAuth(uuid string, req *RentalUpdateRequest) (*models.Configuration, error) {
|
||||
localCfg, err := s.localDB.GetConfigurationByUUID(uuid)
|
||||
if err != nil {
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
|
||||
conditions := make(localdb.RentalItemConditions, 0, len(req.Items))
|
||||
for _, item := range req.Items {
|
||||
conditions = append(conditions, localdb.RentalItemCondition{
|
||||
LotName: models.NormalizeLotName(item.LotName),
|
||||
Condition: item.Condition,
|
||||
})
|
||||
}
|
||||
|
||||
localCfg.RentalItems = conditions
|
||||
localCfg.RentalUpliftPercent = req.UpliftPercent
|
||||
localCfg.UpdatedAt = time.Now()
|
||||
localCfg.SyncStatus = "pending"
|
||||
|
||||
cfg, err := s.saveWithVersionAndPending(localCfg, "update", "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("update rental fields without auth with version: %w", err)
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (s *LocalConfigurationService) ApplyVendorSpecItemsNoAuth(uuid string, items localdb.LocalConfigItems) (*models.Configuration, error) {
|
||||
localCfg, err := s.localDB.GetConfigurationByUUID(uuid)
|
||||
if err != nil {
|
||||
|
||||
@@ -46,10 +46,11 @@ type CreateProjectRequest struct {
|
||||
}
|
||||
|
||||
type UpdateProjectRequest struct {
|
||||
Code *string `json:"code,omitempty"`
|
||||
Variant *string `json:"variant,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
TrackerURL *string `json:"tracker_url,omitempty"`
|
||||
Code *string `json:"code,omitempty"`
|
||||
Variant *string `json:"variant,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
TrackerURL *string `json:"tracker_url,omitempty"`
|
||||
RentalEnabled *bool `json:"rental_enabled,omitempty"`
|
||||
}
|
||||
|
||||
type ProjectConfigurationsResult struct {
|
||||
@@ -148,6 +149,9 @@ func (s *ProjectService) Update(projectUUID, ownerUsername string, req *UpdatePr
|
||||
} else if strings.TrimSpace(localProject.TrackerURL) == "" {
|
||||
localProject.TrackerURL = normalizeProjectTrackerURL(localProject.Code, "")
|
||||
}
|
||||
if req.RentalEnabled != nil {
|
||||
localProject.RentalEnabled = *req.RentalEnabled
|
||||
}
|
||||
localProject.UpdatedAt = time.Now()
|
||||
localProject.SyncStatus = "pending"
|
||||
if err := s.localDB.SaveProject(localProject); err != nil {
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
)
|
||||
|
||||
// RentalService computes paid-testing/rental pricing for a configuration,
|
||||
// per the draft "Регламент расчёта стоимости платного тестирования и аренды
|
||||
// GPU-серверов" methodology (Steps 1-8 and 10; buyout/Step 9 is out of scope).
|
||||
//
|
||||
// Pricing is always quoted per week (Разовый + Еженедельный): the methodology
|
||||
// prices in multiples of a week, and there is no separate "term" input — a
|
||||
// sales rep multiplies the weekly rate by however many weeks are needed.
|
||||
//
|
||||
// The "Цена" the methodology depreciates against is derived from the
|
||||
// configuration's existing Estimate buy price via a single project-wide
|
||||
// uplift percentage — QuoteForge has no per-component sale price today.
|
||||
//
|
||||
// Support is out of scope here: this calc covers BOM component depreciation
|
||||
// only. If a deal needs support priced in, that is handled outside the
|
||||
// Аренда tab (e.g. via the Estimate tab / support pricing elsewhere) rather
|
||||
// than being computed or added here.
|
||||
type RentalService struct {
|
||||
localDB *localdb.LocalDB
|
||||
}
|
||||
|
||||
func NewRentalService(localDB *localdb.LocalDB) *RentalService {
|
||||
return &RentalService{localDB: localDB}
|
||||
}
|
||||
|
||||
const (
|
||||
daysPerYear = 365
|
||||
rentalMarginFactor = 1.03
|
||||
rentalVATFactor = 1.22
|
||||
rentalWeekDays = 7
|
||||
)
|
||||
|
||||
// rentalCoeffs holds the depreciation coefficients for one methodology category.
|
||||
type rentalCoeffs struct {
|
||||
KNew float64 // one-time layer-1 hit, new hardware only
|
||||
LifeNewDays float64
|
||||
LifeUsedDays float64
|
||||
}
|
||||
|
||||
var (
|
||||
chassisCoeffs = rentalCoeffs{KNew: 0.30, LifeNewDays: 5 * daysPerYear, LifeUsedDays: 3 * daysPerYear}
|
||||
cpuDramCoeffs = rentalCoeffs{KNew: 0.075, LifeNewDays: 5 * daysPerYear, LifeUsedDays: 3 * daysPerYear}
|
||||
diskCoeffs = rentalCoeffs{KNew: 0.50, LifeNewDays: 5 * daysPerYear, LifeUsedDays: 3 * daysPerYear}
|
||||
cardsCoeffs = rentalCoeffs{KNew: 0.30, LifeNewDays: 5 * daysPerYear, LifeUsedDays: 3 * daysPerYear}
|
||||
gpuActualCoeffs = rentalCoeffs{KNew: 0.20, LifeNewDays: 2 * daysPerYear, LifeUsedDays: 1 * daysPerYear}
|
||||
gpuStabilizedCoeffs = rentalCoeffs{KNew: 0.20, LifeNewDays: 3 * daysPerYear, LifeUsedDays: 1 * daysPerYear}
|
||||
)
|
||||
|
||||
// categoryCoeffMap maps existing lot_category codes (models.DefaultCategories)
|
||||
// to their methodology category. Categories absent here (including "Other")
|
||||
// fall back to cardsCoeffs as the closest generic fit.
|
||||
var categoryCoeffMap = map[string]rentalCoeffs{
|
||||
"BB": chassisCoeffs,
|
||||
"MB": chassisCoeffs,
|
||||
"PSU": chassisCoeffs,
|
||||
"PS": chassisCoeffs,
|
||||
|
||||
"CPU": cpuDramCoeffs,
|
||||
"MEM": cpuDramCoeffs,
|
||||
|
||||
"SSD": diskCoeffs,
|
||||
"HDD": diskCoeffs,
|
||||
"M2": diskCoeffs,
|
||||
"EDSFF": diskCoeffs,
|
||||
"HHHL": diskCoeffs,
|
||||
|
||||
"NIC": cardsCoeffs,
|
||||
"HCA": cardsCoeffs,
|
||||
"DPU": cardsCoeffs,
|
||||
"HBA": cardsCoeffs,
|
||||
"RAID": cardsCoeffs,
|
||||
"RISERS": cardsCoeffs,
|
||||
"CARD": cardsCoeffs,
|
||||
"ACC": cardsCoeffs,
|
||||
}
|
||||
|
||||
// gpuActualGenSubstrings identifies "actual generation" GPUs per the
|
||||
// regulation's model list (H200, RTX PRO 6000 Blackwell SE, B200/B300).
|
||||
// Update manually as new GPU generations ship.
|
||||
var gpuActualGenSubstrings = []string{"H200", "B200", "B300", "BLACKWELL SE"}
|
||||
|
||||
func rentalCoeffsFor(category, lotName string) rentalCoeffs {
|
||||
cat := strings.ToUpper(strings.TrimSpace(category))
|
||||
if cat == "GPU" {
|
||||
upperLot := strings.ToUpper(lotName)
|
||||
for _, s := range gpuActualGenSubstrings {
|
||||
if strings.Contains(upperLot, s) {
|
||||
return gpuActualCoeffs
|
||||
}
|
||||
}
|
||||
return gpuStabilizedCoeffs
|
||||
}
|
||||
if c, ok := categoryCoeffMap[cat]; ok {
|
||||
return c
|
||||
}
|
||||
return cardsCoeffs
|
||||
}
|
||||
|
||||
type RentalComponentResult struct {
|
||||
LotName string `json:"lot_name"`
|
||||
Category string `json:"category"`
|
||||
Quantity int `json:"quantity"`
|
||||
Condition string `json:"condition"`
|
||||
BuyPrice float64 `json:"buy_price"` // per-unit Estimate price
|
||||
Price float64 `json:"price"` // per-unit "Цена" after uplift
|
||||
Layer1 float64 `json:"layer1"` // total for quantity, ex-VAT, no margin
|
||||
DailyWear float64 `json:"daily_wear"` // total for quantity, ex-VAT, no margin
|
||||
OneTime float64 `json:"one_time"` // Разовый, with margin+VAT
|
||||
Weekly float64 `json:"weekly"` // Еженедельный, with margin+VAT
|
||||
PriceMissing bool `json:"price_missing"`
|
||||
}
|
||||
|
||||
type RentalCalculateResult struct {
|
||||
Items []RentalComponentResult `json:"items"`
|
||||
Layer1Total float64 `json:"layer1_total"`
|
||||
DailyWearTotal float64 `json:"daily_wear_total"`
|
||||
OneTimeTotal float64 `json:"one_time_total"` // Разовый, with margin+VAT
|
||||
WeeklyTotal float64 `json:"weekly_total"` // Еженедельный, with margin+VAT
|
||||
Warnings []string `json:"warnings,omitempty"`
|
||||
}
|
||||
|
||||
// Calculate computes rental pricing for a configuration, always priced per
|
||||
// week (Разовый one-time + Еженедельный recurring).
|
||||
func (s *RentalService) Calculate(configUUID string, req *RentalUpdateRequest) (*RentalCalculateResult, error) {
|
||||
localCfg, err := s.localDB.GetConfigurationByUUID(configUUID)
|
||||
if err != nil {
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
|
||||
conditionByLot := make(map[string]string, len(req.Items))
|
||||
for _, item := range req.Items {
|
||||
conditionByLot[models.NormalizeLotName(item.LotName)] = item.Condition
|
||||
}
|
||||
|
||||
lotNames := make([]string, 0, len(localCfg.Items))
|
||||
for _, item := range localCfg.Items {
|
||||
lotNames = append(lotNames, item.LotName)
|
||||
}
|
||||
var categories map[string]string
|
||||
if localCfg.PricelistID != nil {
|
||||
categories, _ = s.localDB.GetLocalLotCategoriesByServerPricelistID(*localCfg.PricelistID, lotNames)
|
||||
}
|
||||
if categories == nil {
|
||||
categories = map[string]string{}
|
||||
}
|
||||
|
||||
result := &RentalCalculateResult{
|
||||
Items: make([]RentalComponentResult, 0, len(localCfg.Items)),
|
||||
}
|
||||
|
||||
uplift := 1 + req.UpliftPercent/100
|
||||
|
||||
for _, item := range localCfg.Items {
|
||||
condition := conditionByLot[item.LotName]
|
||||
if condition != "used" {
|
||||
condition = "new"
|
||||
}
|
||||
category := categories[item.LotName]
|
||||
coeffs := rentalCoeffsFor(category, item.LotName)
|
||||
|
||||
price := item.UnitPrice * uplift
|
||||
qty := float64(item.Quantity)
|
||||
|
||||
var layer1, residual, term float64
|
||||
if condition == "new" {
|
||||
layer1 = price * coeffs.KNew * qty
|
||||
residual = (price - price*coeffs.KNew) * qty
|
||||
term = coeffs.LifeNewDays
|
||||
} else {
|
||||
layer1 = 0
|
||||
residual = price * qty
|
||||
term = coeffs.LifeUsedDays
|
||||
}
|
||||
dailyWear := 0.0
|
||||
if term > 0 {
|
||||
dailyWear = residual / term
|
||||
}
|
||||
|
||||
result.Layer1Total += layer1
|
||||
result.DailyWearTotal += dailyWear
|
||||
|
||||
oneTime := layer1 * rentalMarginFactor * rentalVATFactor
|
||||
weekly := dailyWear * rentalWeekDays * rentalMarginFactor * rentalVATFactor
|
||||
|
||||
result.Items = append(result.Items, RentalComponentResult{
|
||||
LotName: item.LotName,
|
||||
Category: category,
|
||||
Quantity: item.Quantity,
|
||||
Condition: condition,
|
||||
BuyPrice: item.UnitPrice,
|
||||
Price: price,
|
||||
Layer1: layer1,
|
||||
DailyWear: dailyWear,
|
||||
OneTime: oneTime,
|
||||
Weekly: weekly,
|
||||
PriceMissing: item.UnitPrice <= 0,
|
||||
})
|
||||
}
|
||||
|
||||
result.OneTimeTotal = result.Layer1Total * rentalMarginFactor * rentalVATFactor
|
||||
result.WeeklyTotal = result.DailyWearTotal * rentalWeekDays * rentalMarginFactor * rentalVATFactor
|
||||
|
||||
return result, nil
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -217,6 +217,7 @@ func (s *Service) ImportProjectsToLocal() (*ProjectImportResult, error) {
|
||||
existing.TrackerURL = project.TrackerURL
|
||||
existing.IsActive = project.IsActive
|
||||
existing.IsSystem = project.IsSystem
|
||||
existing.RentalEnabled = project.RentalEnabled
|
||||
existing.CreatedAt = project.CreatedAt
|
||||
existing.UpdatedAt = project.UpdatedAt
|
||||
serverID := project.ID
|
||||
|
||||
@@ -16,7 +16,6 @@ func TestSyncPricelists_BackfillsLotCategoryForUsedPricelistItems(t *testing.T)
|
||||
if err := serverDB.AutoMigrate(
|
||||
&models.Pricelist{},
|
||||
&models.PricelistItem{},
|
||||
&models.Lot{},
|
||||
); err != nil {
|
||||
t.Fatalf("migrate server tables: %v", err)
|
||||
}
|
||||
@@ -33,14 +32,10 @@ func TestSyncPricelists_BackfillsLotCategoryForUsedPricelistItems(t *testing.T)
|
||||
t.Fatalf("create server pricelist: %v", err)
|
||||
}
|
||||
if err := serverDB.Create(&models.PricelistItem{
|
||||
PricelistID: serverPL.ID,
|
||||
LotName: "CPU_A",
|
||||
LotCategory: "CPU",
|
||||
Price: 10,
|
||||
PriceMethod: "",
|
||||
MetaPrices: "",
|
||||
ManualPrice: nil,
|
||||
AvailableQty: nil,
|
||||
PricelistID: serverPL.ID,
|
||||
LotName: "CPU_A",
|
||||
LotCategory: "CPU",
|
||||
Price: 10,
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create server pricelist item: %v", err)
|
||||
}
|
||||
|
||||
@@ -439,7 +439,6 @@ func newServerDBForSyncTest(t *testing.T) *gorm.DB {
|
||||
&models.Configuration{},
|
||||
&models.Pricelist{},
|
||||
&models.PricelistItem{},
|
||||
&models.Lot{},
|
||||
); err != nil {
|
||||
t.Fatalf("migrate server test schema: %v", err)
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
@@ -133,6 +133,8 @@ func (s *LocalConfigurationService) ImportVendorWorkspaceToProject(projectUUID s
|
||||
workspace, err = parseCFXMLWorkspace(data, filepath.Base(sourceFileName))
|
||||
case IsQuoteForgeCSV(data):
|
||||
workspace, err = parseQuoteForgeCSV(data, filepath.Base(sourceFileName))
|
||||
case IsQuoteForgePricingCSV(data):
|
||||
workspace, err = parsePricingCSV(data, filepath.Base(sourceFileName))
|
||||
case IsInspurBOM(data):
|
||||
workspace, err = parseInspurBOM(data, filepath.Base(sourceFileName))
|
||||
case IsNxBOM(data):
|
||||
@@ -984,6 +986,124 @@ func parseQuoteForgeCSV(data []byte, sourceFileName string) (*importedWorkspace,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// IsQuoteForgePricingCSV reports whether data looks like a QuoteForge project
|
||||
// pricing export (the customer-facing FOB/DDP CSV, distinct from the round-trip
|
||||
// "Line;Type;p/n" format). It starts (after optional UTF-8 BOM) with a header
|
||||
// whose first column is "Line Item". The optional columns (LOT, BOM, Estimate,
|
||||
// Stock, Конкуренты) vary by export settings, so parsing resolves columns by name.
|
||||
func IsQuoteForgePricingCSV(data []byte) bool {
|
||||
trimmed := bytes.TrimPrefix(data, []byte{0xEF, 0xBB, 0xBF})
|
||||
firstLine := trimmed
|
||||
if idx := bytes.IndexByte(trimmed, '\n'); idx >= 0 {
|
||||
firstLine = trimmed[:idx]
|
||||
}
|
||||
return bytes.HasPrefix(bytes.TrimSpace(firstLine), []byte("Line Item;"))
|
||||
}
|
||||
|
||||
// parsePricingCSV parses a QuoteForge project pricing export back into importable
|
||||
// configurations. Unlike parseQuoteForgeCSV, component lot names live in the "LOT"
|
||||
// column rather than "p/n" (which is empty/vendor part number in this format), so
|
||||
// the LOT column is required to reconstruct the BOM. Prices come from "Estimate"
|
||||
// (falling back to "BOM") since that column holds the price the export was based on.
|
||||
func parsePricingCSV(data []byte, sourceFileName string) (*importedWorkspace, error) {
|
||||
data = bytes.TrimPrefix(data, []byte{0xEF, 0xBB, 0xBF})
|
||||
|
||||
r := csv.NewReader(bytes.NewReader(data))
|
||||
r.Comma = ';'
|
||||
r.FieldsPerRecord = -1
|
||||
r.LazyQuotes = true
|
||||
|
||||
records, err := r.ReadAll()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse pricing CSV: %w", err)
|
||||
}
|
||||
if len(records) == 0 {
|
||||
return nil, fmt.Errorf("pricing CSV is empty")
|
||||
}
|
||||
|
||||
col := make(map[string]int, len(records[0]))
|
||||
for i, name := range records[0] {
|
||||
col[strings.ToLower(strings.TrimSpace(name))] = i
|
||||
}
|
||||
|
||||
lineIdx, ok := col["line item"]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("pricing CSV has no Line Item column")
|
||||
}
|
||||
lotIdx, hasLot := col["lot"]
|
||||
if !hasLot {
|
||||
return nil, fmt.Errorf("pricing CSV has no LOT column — cannot reconstruct components")
|
||||
}
|
||||
qtyIdx, hasQty := col["кол-во"]
|
||||
if !hasQty {
|
||||
return nil, fmt.Errorf("pricing CSV has no Кол-во column")
|
||||
}
|
||||
descIdx, hasDesc := col["описание"]
|
||||
estimateIdx, hasEstimate := col["estimate"]
|
||||
bomIdx, hasBOM := col["bom"]
|
||||
|
||||
var configs []importedConfiguration
|
||||
var current *importedConfiguration
|
||||
blockIdx := 0
|
||||
|
||||
for _, record := range records[1:] {
|
||||
if csvAllEmpty(record) {
|
||||
continue
|
||||
}
|
||||
lineCol := strings.TrimSpace(csvCol(record, lineIdx))
|
||||
lot := strings.TrimSpace(csvCol(record, lotIdx))
|
||||
|
||||
if lineCol != "" {
|
||||
if current != nil {
|
||||
configs = append(configs, *current)
|
||||
}
|
||||
blockIdx++
|
||||
name := ""
|
||||
if hasDesc {
|
||||
name = strings.TrimSpace(csvCol(record, descIdx))
|
||||
}
|
||||
if name == "" || name == "—" {
|
||||
name = fmt.Sprintf("Config %d", blockIdx)
|
||||
}
|
||||
serverCount := maxInt(parseInt(strings.TrimSpace(csvCol(record, qtyIdx))), 1)
|
||||
current = &importedConfiguration{
|
||||
GroupID: fmt.Sprintf("pricingcsv-%d", blockIdx),
|
||||
Name: name,
|
||||
Line: blockIdx * 10,
|
||||
ServerCount: serverCount,
|
||||
DirectItems: make(localdb.LocalConfigItems, 0),
|
||||
}
|
||||
} else if lot != "" && lot != "—" && current != nil {
|
||||
qty := maxInt(parseInt(strings.TrimSpace(csvCol(record, qtyIdx))), 1)
|
||||
unitPrice := 0.0
|
||||
if hasEstimate {
|
||||
unitPrice = parseCSVPrice(strings.TrimSpace(csvCol(record, estimateIdx)))
|
||||
}
|
||||
if unitPrice == 0 && hasBOM {
|
||||
unitPrice = parseCSVPrice(strings.TrimSpace(csvCol(record, bomIdx)))
|
||||
}
|
||||
current.DirectItems = append(current.DirectItems, localdb.LocalConfigItem{
|
||||
LotName: lot,
|
||||
Quantity: qty,
|
||||
UnitPrice: unitPrice,
|
||||
})
|
||||
}
|
||||
}
|
||||
if current != nil {
|
||||
configs = append(configs, *current)
|
||||
}
|
||||
|
||||
if len(configs) == 0 {
|
||||
return nil, fmt.Errorf("pricing CSV has no importable configurations")
|
||||
}
|
||||
|
||||
return &importedWorkspace{
|
||||
SourceFormat: "PricingCSV",
|
||||
SourceFileName: sourceFileName,
|
||||
Configurations: configs,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// csvCol returns record[idx] or "" when idx is out of range.
|
||||
func csvCol(record []string, idx int) string {
|
||||
if idx < len(record) {
|
||||
|
||||
@@ -542,6 +542,88 @@ func TestIsQuoteForgeCSV(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePricingCSV(t *testing.T) {
|
||||
// Format mirrors pricingCSVHeaders/pricingCSVRow output: the customer-facing
|
||||
// pricing export, distinct from ToCSV's "Line;Type;p/n" round-trip format.
|
||||
const sample = "\xEF\xBB\xBF" + // UTF-8 BOM
|
||||
"Line Item;LOT;PN вендора;Описание;Кол-во;BOM;Estimate;Stock;Конкуренты\n" +
|
||||
"10;;;5_ООО+РН-Бурение_NOL100582279;3;—;18 562,00;3 590,18;17 983,85\n" +
|
||||
";MB_AMD_4.Genoa_2S;—;—;1;—;3 906,00;—;—\n" +
|
||||
";CPU_AMD_9224;—;—;2;—;2 000,00;—;2 266,66\n" +
|
||||
"\n" +
|
||||
"20;;;11_АО+Ангарскнефтехимпроект_NOL100574528;2;—;30 283,00;12 889,60;32 254,39\n" +
|
||||
";MEM_DDR5_64G_5600;—;—;8;—;17 200,00;8 032,56;23 384,32\n"
|
||||
|
||||
workspace, err := parsePricingCSV([]byte(sample), "pricing.csv")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if workspace.SourceFormat != "PricingCSV" {
|
||||
t.Fatalf("expected SourceFormat PricingCSV, got %q", workspace.SourceFormat)
|
||||
}
|
||||
if len(workspace.Configurations) != 2 {
|
||||
t.Fatalf("expected 2 configurations, got %d", len(workspace.Configurations))
|
||||
}
|
||||
|
||||
cfg1 := workspace.Configurations[0]
|
||||
if cfg1.Name != "5_ООО+РН-Бурение_NOL100582279" {
|
||||
t.Fatalf("cfg1 name: got %q", cfg1.Name)
|
||||
}
|
||||
if cfg1.ServerCount != 3 {
|
||||
t.Fatalf("cfg1 server_count: want 3, got %d", cfg1.ServerCount)
|
||||
}
|
||||
if len(cfg1.DirectItems) != 2 {
|
||||
t.Fatalf("cfg1 items: want 2, got %d", len(cfg1.DirectItems))
|
||||
}
|
||||
if cfg1.DirectItems[0].LotName != "MB_AMD_4.Genoa_2S" || cfg1.DirectItems[0].Quantity != 1 || cfg1.DirectItems[0].UnitPrice != 3906 {
|
||||
t.Fatalf("cfg1 item[0]: %+v", cfg1.DirectItems[0])
|
||||
}
|
||||
if cfg1.DirectItems[1].LotName != "CPU_AMD_9224" || cfg1.DirectItems[1].Quantity != 2 || cfg1.DirectItems[1].UnitPrice != 2000 {
|
||||
t.Fatalf("cfg1 item[1]: %+v", cfg1.DirectItems[1])
|
||||
}
|
||||
|
||||
cfg2 := workspace.Configurations[1]
|
||||
if cfg2.Name != "11_АО+Ангарскнефтехимпроект_NOL100574528" {
|
||||
t.Fatalf("cfg2 name: got %q", cfg2.Name)
|
||||
}
|
||||
if cfg2.ServerCount != 2 {
|
||||
t.Fatalf("cfg2 server_count: want 2, got %d", cfg2.ServerCount)
|
||||
}
|
||||
if len(cfg2.DirectItems) != 1 || cfg2.DirectItems[0].LotName != "MEM_DDR5_64G_5600" {
|
||||
t.Fatalf("cfg2 items: %+v", cfg2.DirectItems)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsQuoteForgePricingCSV(t *testing.T) {
|
||||
withBOM := "\xEF\xBB\xBFLine Item;LOT;PN вендора;Описание;Кол-во;BOM;Estimate;Stock;Конкуренты\n10;;;name;1;—;100;—;—\n"
|
||||
noLOT := "Line Item;PN вендора;Описание;Кол-во;BOM;Estimate;Stock;Конкуренты\n10;;name;1;—;100;—;—\n"
|
||||
|
||||
cases := []struct {
|
||||
input string
|
||||
want bool
|
||||
}{
|
||||
{withBOM, true},
|
||||
{noLOT, true},
|
||||
{"Line;Type;p/n;Description\n", false},
|
||||
{"<CFXML>\n</CFXML>", false},
|
||||
{"", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got := IsQuoteForgePricingCSV([]byte(tc.input))
|
||||
if got != tc.want {
|
||||
t.Errorf("IsQuoteForgePricingCSV(%q) = %v, want %v", tc.input[:min(len(tc.input), 40)], got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePricingCSV_NoLOTColumn(t *testing.T) {
|
||||
const sample = "Line Item;PN вендора;Описание;Кол-во;BOM;Estimate;Stock;Конкуренты\n" +
|
||||
"10;;name;1;—;100;—;—\n"
|
||||
if _, err := parsePricingCSV([]byte(sample), "pricing.csv"); err == nil {
|
||||
t.Fatal("expected error when LOT column is missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseCSVPrice(t *testing.T) {
|
||||
cases := []struct {
|
||||
input string
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Tables affected: qt_projects
|
||||
-- recovery.not-started: safe to re-run; ADD COLUMN IF NOT EXISTS
|
||||
-- recovery.partial: ALTER TABLE qt_projects DROP COLUMN rental_enabled;
|
||||
-- recovery.completed: no action needed
|
||||
-- verify: rental_enabled column missing | SELECT 1 FROM information_schema.COLUMNS WHERE table_schema=DATABASE() AND table_name='qt_projects' AND column_name='rental_enabled' HAVING COUNT(*)=0
|
||||
|
||||
ALTER TABLE qt_projects
|
||||
ADD COLUMN IF NOT EXISTS rental_enabled TINYINT(1) NOT NULL DEFAULT 0;
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Tables affected: qt_configurations
|
||||
-- recovery.not-started: safe to re-run; ADD COLUMN IF NOT EXISTS
|
||||
-- recovery.partial: ALTER TABLE qt_configurations DROP COLUMN rental_items, DROP COLUMN rental_uplift_percent;
|
||||
-- recovery.completed: no action needed
|
||||
-- verify: rental_uplift_percent column missing | SELECT 1 FROM information_schema.COLUMNS WHERE table_schema=DATABASE() AND table_name='qt_configurations' AND column_name='rental_uplift_percent' HAVING COUNT(*)=0
|
||||
|
||||
ALTER TABLE qt_configurations
|
||||
ADD COLUMN IF NOT EXISTS rental_items JSON NULL,
|
||||
ADD COLUMN IF NOT EXISTS rental_uplift_percent DECIMAL(8,2) NOT NULL DEFAULT 0;
|
||||
@@ -0,0 +1,17 @@
|
||||
-- Tables affected: qt_pricelist_items
|
||||
-- recovery.not-started: safe to re-run; ADD COLUMN IF NOT EXISTS
|
||||
-- recovery.partial: ALTER TABLE qt_pricelist_items DROP COLUMN lot_description;
|
||||
-- recovery.completed: no action needed
|
||||
-- verify: lot_description column missing | SELECT 1 FROM information_schema.COLUMNS WHERE table_schema=DATABASE() AND table_name='qt_pricelist_items' AND column_name='lot_description' HAVING COUNT(*)=0
|
||||
|
||||
-- QuoteForge previously read a LOT's description via a per-row live join into
|
||||
-- `lot` (internal/repository/pricelist.go GetItems), which never made it into
|
||||
-- the local sync cache. Storing the description directly on the pricelist row
|
||||
-- lets QF sync it like any other pricelist field and removes the join.
|
||||
ALTER TABLE qt_pricelist_items
|
||||
ADD COLUMN IF NOT EXISTS lot_description VARCHAR(10000) NULL;
|
||||
|
||||
UPDATE qt_pricelist_items i
|
||||
JOIN lot l ON l.lot_name = i.lot_name
|
||||
SET i.lot_description = l.lot_description
|
||||
WHERE i.lot_description IS NULL OR i.lot_description = '';
|
||||
@@ -0,0 +1,12 @@
|
||||
-- Tables affected: qt_pricelist_items
|
||||
-- recovery.not-started: safe to re-run; ADD COLUMN IF NOT EXISTS
|
||||
-- recovery.partial: ALTER TABLE qt_pricelist_items DROP COLUMN price_quality;
|
||||
-- recovery.completed: no action needed
|
||||
-- verify: price_quality column missing | SELECT 1 FROM information_schema.COLUMNS WHERE table_schema=DATABASE() AND table_name='qt_pricelist_items' AND column_name='price_quality' HAVING COUNT(*)=0
|
||||
|
||||
-- price_quality is a 0-9 score set by the external pricelist-building tool,
|
||||
-- based on quote recency/count per its own per-lot pricing-period settings.
|
||||
-- QuoteForge only reads and displays it (7-9 good, 4-6 warning, 0-3 poor);
|
||||
-- it never computes or writes this value.
|
||||
ALTER TABLE qt_pricelist_items
|
||||
ADD COLUMN IF NOT EXISTS price_quality TINYINT UNSIGNED NULL;
|
||||
@@ -0,0 +1,18 @@
|
||||
# QuoteForge v2.29
|
||||
|
||||
Дата релиза: 2026-07-10
|
||||
Тег: `v2.29`
|
||||
|
||||
Предыдущий релиз: `v2.28`
|
||||
|
||||
## Ключевые изменения
|
||||
|
||||
- world-прайслист используется как заглушка: где для позиции нет цены в estimate/склад/конкуренты, подставляется цена из world;
|
||||
- подставленные из world цены выделяются цветом (amber) в таблицах «Цена покупки» и «Цена продажи», участвуют в «Итого» и убирают красную звёздочку неполного покрытия;
|
||||
- в CSV-экспорт добавлена колонка «Заглушка (world)» с перечнем столбцов, где сработал фолбэк;
|
||||
- устранён потенциальный дедлок при резолве прайслистов внутри транзакции (single-connection пул) — добавлены транзакционные варианты выборки прайслистов.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Shared LOT price-quality color scale, used everywhere price_quality is
|
||||
// displayed (pricelist detail page, configurator search dropdown, configurator
|
||||
// table, pricing tab). price_quality is a 0-9 score set by the external
|
||||
// pricing tool (see bible-local/03-database.md, qt_pricelist_items.price_quality)
|
||||
// — QF only displays it, never computes it. Single source of the color scale
|
||||
// so every view stays visually consistent.
|
||||
//
|
||||
// Gradient: 0 = red, 5 = yellow, 9 = green.
|
||||
(function () {
|
||||
const RED = [220, 38, 38];
|
||||
const YELLOW = [234, 179, 8];
|
||||
const GREEN = [22, 163, 74];
|
||||
|
||||
function lerp(c1, c2, t) {
|
||||
return c1.map((v, i) => Math.round(v + (c2[i] - v) * t));
|
||||
}
|
||||
|
||||
// Returns "r, g, b" (no rgb() wrapper) so callers can build rgb()/rgba() themselves.
|
||||
function priceQualityRgb(quality) {
|
||||
if (typeof quality !== 'number' || Number.isNaN(quality)) return null;
|
||||
const q = Math.max(0, Math.min(9, quality));
|
||||
const [r, g, b] = q <= 5 ? lerp(RED, YELLOW, q / 5) : lerp(YELLOW, GREEN, (q - 5) / 4);
|
||||
return `${r}, ${g}, ${b}`;
|
||||
}
|
||||
|
||||
function priceQualityColor(quality) {
|
||||
const rgb = priceQualityRgb(quality);
|
||||
return rgb ? `rgb(${rgb})` : null;
|
||||
}
|
||||
|
||||
// Small colored dot for compact contexts (search dropdown, configurator table cell).
|
||||
function qualityDotHtml(quality) {
|
||||
const color = priceQualityColor(quality);
|
||||
if (!color) return '';
|
||||
return `<span class="inline-block w-2 h-2 rounded-full" style="background-color: ${color}" title="Качество цены: ${quality}/9"></span>`;
|
||||
}
|
||||
|
||||
// Colored number badge for a dedicated "quality" column/cell.
|
||||
function qualityBadgeHtml(quality) {
|
||||
if (typeof quality !== 'number') return '<span class="text-gray-400">-</span>';
|
||||
const color = priceQualityColor(quality);
|
||||
return `<span class="font-semibold" style="color: ${color}" title="Качество цены: ${quality}/9">${quality}</span>`;
|
||||
}
|
||||
|
||||
// Light row-tint background for table rows, e.g. the pricing tab.
|
||||
function qualityRowStyle(quality) {
|
||||
const rgb = priceQualityRgb(quality);
|
||||
return rgb ? `background-color: rgba(${rgb}, 0.10)` : '';
|
||||
}
|
||||
|
||||
window.priceQualityColor = priceQualityColor;
|
||||
window.qualityDotHtml = qualityDotHtml;
|
||||
window.qualityBadgeHtml = qualityBadgeHtml;
|
||||
window.qualityRowStyle = qualityRowStyle;
|
||||
})();
|
||||
@@ -8,6 +8,7 @@
|
||||
<link rel="stylesheet" href="/static/app.css">
|
||||
<script src="/static/vendor/tailwindcss.browser.js"></script>
|
||||
<script src="/static/vendor/htmx-1.9.10.min.js"></script>
|
||||
<script src="/static/price-quality.js"></script>
|
||||
<style>
|
||||
.htmx-request { opacity: 0.5; }
|
||||
.line-clamp-2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
|
||||
|
||||
+682
-272
File diff suppressed because it is too large.
Load diff
@@ -58,9 +58,8 @@
|
||||
<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-left text-xs font-medium text-gray-500 uppercase">Описание</th>
|
||||
<th id="th-qty" class="hidden px-6 py-3 text-right 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 id="th-settings" class="px-6 py-3 text-left 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">
|
||||
@@ -91,7 +90,6 @@
|
||||
|
||||
const pl = await resp.json();
|
||||
currentSource = pl.source || '';
|
||||
toggleWarehouseColumns();
|
||||
|
||||
document.getElementById('page-title').textContent = `Прайслист ${pl.version}`;
|
||||
document.getElementById('pl-version').textContent = pl.version;
|
||||
@@ -134,7 +132,6 @@
|
||||
const resp = await fetch(url);
|
||||
const data = await resp.json();
|
||||
currentSource = data.source || currentSource;
|
||||
toggleWarehouseColumns();
|
||||
|
||||
renderItems(data.items || []);
|
||||
renderItemsPagination(data.total_count, data.page, data.per_page);
|
||||
@@ -159,19 +156,7 @@
|
||||
}
|
||||
|
||||
function itemsColspan() {
|
||||
return isStockSource() ? 4 : 5;
|
||||
}
|
||||
|
||||
function toggleWarehouseColumns() {
|
||||
const stock = isStockSource();
|
||||
document.getElementById('th-qty').classList.toggle('hidden', true);
|
||||
document.getElementById('th-settings').classList.toggle('hidden', stock);
|
||||
}
|
||||
|
||||
function formatQty(qty) {
|
||||
if (typeof qty !== 'number') return '—';
|
||||
if (Number.isInteger(qty)) return qty.toString();
|
||||
return qty.toLocaleString('ru-RU', { minimumFractionDigits: 0, maximumFractionDigits: 3 });
|
||||
return 5;
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
@@ -184,48 +169,6 @@
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function formatPriceSettings(item) {
|
||||
// Format price settings to match admin pricing interface style
|
||||
let settings = [];
|
||||
const hasManualPrice = item.manual_price && item.manual_price > 0;
|
||||
const hasMeta = item.meta_prices && item.meta_prices.trim() !== '';
|
||||
const method = (item.price_method || '').toLowerCase();
|
||||
|
||||
// Method indicator
|
||||
if (hasManualPrice) {
|
||||
settings.push('<span class="text-orange-600 font-medium">РУЧН</span>');
|
||||
} else if (method === 'average') {
|
||||
settings.push('Сред');
|
||||
} else if (method === 'weighted_median') {
|
||||
settings.push('Взвеш. мед');
|
||||
} else {
|
||||
settings.push('Мед');
|
||||
}
|
||||
|
||||
// Period (only if not manual price)
|
||||
if (!hasManualPrice) {
|
||||
const period = item.price_period_days !== undefined && item.price_period_days !== null ? item.price_period_days : 90;
|
||||
if (period === 7) settings.push('1н');
|
||||
else if (period === 30) settings.push('1м');
|
||||
else if (period === 90) settings.push('3м');
|
||||
else if (period === 365) settings.push('1г');
|
||||
else if (period === 0) settings.push('все');
|
||||
else settings.push(period + 'д');
|
||||
}
|
||||
|
||||
// Coefficient
|
||||
if (item.price_coefficient && item.price_coefficient !== 0) {
|
||||
settings.push((item.price_coefficient > 0 ? '+' : '') + item.price_coefficient + '%');
|
||||
}
|
||||
|
||||
// Meta article indicator
|
||||
if (hasMeta) {
|
||||
settings.push('<span class="text-purple-600 font-medium">МЕТА</span>');
|
||||
}
|
||||
|
||||
return settings.join(' | ') || '-';
|
||||
}
|
||||
|
||||
function renderItems(items) {
|
||||
if (items.length === 0) {
|
||||
document.getElementById('items-body').innerHTML = `
|
||||
@@ -265,7 +208,7 @@
|
||||
</td>
|
||||
<td class="${p} text-sm text-gray-500" title="${escapeHtml(description)}">${escapeHtml(truncatedDesc)}</td>
|
||||
<td class="${p} whitespace-nowrap text-right font-mono">${priceHtml}</td>
|
||||
${!stock ? `<td class="${p} whitespace-nowrap text-sm"><span class="text-xs bg-gray-100 px-2 py-1 rounded">${formatPriceSettings(item)}</span></td>` : ''}
|
||||
<td class="${p} whitespace-nowrap text-center">${qualityBadgeHtml(item.price_quality)}</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
@@ -22,8 +22,8 @@
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
|
||||
</svg>
|
||||
</button>
|
||||
<div id="project-variant-menu" class="absolute left-0 mt-2 min-w-[10rem] rounded-lg border border-gray-200 bg-white shadow-lg hidden z-10">
|
||||
<div id="project-variant-list" class="py-1"></div>
|
||||
<div id="project-variant-menu" class="absolute left-0 mt-2 w-max max-w-xs min-w-[12rem] rounded-lg border border-gray-200 bg-white shadow-lg hidden z-10 text-sm font-normal">
|
||||
<div id="project-variant-list" class="py-1 max-h-72 overflow-y-auto"></div>
|
||||
</div>
|
||||
</div>
|
||||
<button onclick="openNewVariantModal()" class="inline-flex w-full sm:w-auto justify-center items-center px-3 py-1.5 text-sm font-medium bg-purple-600 text-white rounded-lg hover:bg-purple-700">
|
||||
@@ -314,6 +314,13 @@
|
||||
class="w-full px-3 py-2 border rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
|
||||
<div class="text-xs text-gray-500 mt-1">Оставьте пустым, чтобы скрыть ссылку.</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="flex items-center space-x-2">
|
||||
<input type="checkbox" id="project-settings-rental-enabled" class="rounded border-gray-300">
|
||||
<span class="text-sm font-medium text-gray-700">Аренда</span>
|
||||
</label>
|
||||
<div class="text-xs text-gray-500 mt-1">Добавляет вкладку «Аренда» (расчёт стоимости платного тестирования/аренды) на конфигурациях этого проекта.</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end space-x-3 mt-6">
|
||||
<button onclick="closeProjectSettingsModal()" class="px-4 py-2 text-gray-600 hover:text-gray-800">Отмена</button>
|
||||
@@ -380,8 +387,8 @@ async function loadVariantsForCode(code) {
|
||||
}
|
||||
projectVariants = allProjects
|
||||
.filter(p => (p.code || '').trim() === code && p.is_active !== false)
|
||||
.map(p => ({uuid: p.uuid, variant: (p.variant || '').trim()}));
|
||||
projectVariants.sort((a, b) => normalizeVariantLabel(a.variant).localeCompare(normalizeVariantLabel(b.variant)));
|
||||
.map(p => ({uuid: p.uuid, variant: (p.variant || '').trim(), createdAt: p.created_at || ''}));
|
||||
projectVariants.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
@@ -397,7 +404,7 @@ function renderVariantSelect() {
|
||||
list.innerHTML = '';
|
||||
const variants = projectVariants.length ? projectVariants : [{uuid: projectUUID, variant: (project && project.variant) || ''}];
|
||||
let mainUUID = '';
|
||||
variants.forEach(item => {
|
||||
variants.forEach((item, index) => {
|
||||
const variantLabel = normalizeVariantLabel(item.variant);
|
||||
if (variantLabel === 'main' && !mainUUID) {
|
||||
mainUUID = item.uuid;
|
||||
@@ -410,7 +417,7 @@ function renderVariantSelect() {
|
||||
label.textContent = variantLabel;
|
||||
document.title = (project && project.code ? project.code : '—') + ' / ' + variantLabel + ' — OFS';
|
||||
}
|
||||
option.textContent = variantLabel;
|
||||
option.textContent = (index + 1) + '. ' + variantLabel;
|
||||
option.onclick = function() {
|
||||
menu.classList.add('hidden');
|
||||
if (item.uuid && item.uuid !== projectUUID) {
|
||||
@@ -1253,6 +1260,7 @@ function openProjectSettingsModal() {
|
||||
document.getElementById('project-settings-variant').value = project.variant || '';
|
||||
document.getElementById('project-settings-name').value = project.name || '';
|
||||
document.getElementById('project-settings-tracker-url').value = (project.tracker_url || '').trim();
|
||||
document.getElementById('project-settings-rental-enabled').checked = !!project.rental_enabled;
|
||||
document.getElementById('project-settings-modal').classList.remove('hidden');
|
||||
document.getElementById('project-settings-modal').classList.add('flex');
|
||||
}
|
||||
@@ -1268,6 +1276,7 @@ async function saveProjectSettings() {
|
||||
const variant = document.getElementById('project-settings-variant').value.trim();
|
||||
const name = document.getElementById('project-settings-name').value.trim();
|
||||
const trackerURL = document.getElementById('project-settings-tracker-url').value.trim();
|
||||
const rentalEnabled = document.getElementById('project-settings-rental-enabled').checked;
|
||||
if (!code) {
|
||||
alert('Введите код проекта');
|
||||
return;
|
||||
@@ -1275,7 +1284,7 @@ async function saveProjectSettings() {
|
||||
const resp = await fetch('/api/projects/' + projectUUID, {
|
||||
method: 'PUT',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({code: code, variant: variant, name: name, tracker_url: trackerURL})
|
||||
body: JSON.stringify({code: code, variant: variant, name: name, tracker_url: trackerURL, rental_enabled: rentalEnabled})
|
||||
});
|
||||
if (!resp.ok) {
|
||||
if (resp.status === 409) {
|
||||
|
||||
Reference in new issue
Block a user