Compare commits
51
Commits
v2.19
...
34cee5f874
No files matched your search
@@ -0,0 +1,328 @@
|
||||
# Task: World-прайслист как заглушка для отсутствующих цен
|
||||
|
||||
> Это задание для агента-исполнителя. Оно самодостаточно: содержит все файлы, точки
|
||||
> входа, edge-cases и способ проверки. Не отступай от контрактов ниже без причины.
|
||||
|
||||
## Context (зачем)
|
||||
|
||||
В приложение синхронизируется 4 типа прайслистов (`source`): `estimate`, `warehouse`,
|
||||
`competitor` и `world`. Первые три отображаются в таблицах «Цена покупки» / «Цена продажи»
|
||||
на вкладке «Ценообразование». **`world` сейчас не читается нигде** — он уже приезжает и
|
||||
лежит в `local_pricelists` (sync копирует любой `source`, что прислал сервер), но код его
|
||||
игнорирует.
|
||||
|
||||
Задача: сделать `world` **фолбэком-заглушкой**. Там, где для LOT нет цены в
|
||||
estimate/warehouse/competitor, подставить цену из `world` и **выделить такую ячейку цветом**,
|
||||
чтобы было видно, что цена не из «родного» прайслиста.
|
||||
|
||||
На скриншоте видно проблему: у ряда позиций пусто («—») в колонках «Склад» и «Конкуренты»,
|
||||
из-за чего «Итого» неполный и помечен красной звёздочкой «*».
|
||||
|
||||
## Решения по продукту (согласованы с заказчиком)
|
||||
|
||||
1. **Колонки:** world подставляется во **все три** — Estimate, Склад (warehouse), Конкуренты
|
||||
(competitor), в любую, где нет цены.
|
||||
2. **Итого:** подставленная world-цена **участвует в «Итого»**. За счёт этого покрытие
|
||||
становится полным и красная «*» пропадает (если все пробелы закрыты world).
|
||||
3. **Подсветка:** красим **только конкретную ячейку**, где сработала подстановка (не всю строку).
|
||||
Используем янтарный/amber (см. ниже), т.к. семейства gray/green/red/blue стираются регэкспом
|
||||
в `applyCustomPrice`.
|
||||
4. **Охват:** та же логика применяется в таблице **«Цена продажи»** и в **CSV-экспорте**
|
||||
(в CSV цвета нет → добавляем отдельную колонку-комментарий «Заглушка (world)», где перечислены
|
||||
столбцы с фолбэком, напр. `world: Stock, Конкуренты`; см. раздел CSV).
|
||||
|
||||
## Ключевой факт: source-константы
|
||||
|
||||
Файл `internal/models/pricelist.go` определяет `PricelistSource`. Сейчас нет `world`.
|
||||
Добавь константу и включи её в валидацию:
|
||||
|
||||
```go
|
||||
const (
|
||||
PricelistSourceEstimate PricelistSource = "estimate"
|
||||
PricelistSourceWarehouse PricelistSource = "warehouse"
|
||||
PricelistSourceCompetitor PricelistSource = "competitor"
|
||||
PricelistSourceWorld PricelistSource = "world" // NEW
|
||||
)
|
||||
```
|
||||
- Добавь `PricelistSourceWorld` в `IsValid()`.
|
||||
- **НЕ трогай** `NormalizePricelistSource` так, чтобы `world` схлопывался в `estimate` — наоборот,
|
||||
добавь ветку `case PricelistSourceWorld: return PricelistSourceWorld`, иначе где-то world
|
||||
превратится в estimate. Проверь всех вызывающих `NormalizePricelistSource`.
|
||||
- `world`-строки уже синкаются, схема БД менять не нужно (`source` — свободная строка).
|
||||
Отдельный столбец `world_pricelist_id` в конфигурациях **не добавляем** — world резолвим
|
||||
всегда через «последний активный», как ниже.
|
||||
|
||||
---
|
||||
|
||||
## ЧАСТЬ 1 — Backend: `internal/services/quote.go` → `CalculatePriceLevels`
|
||||
|
||||
Это основной источник данных для экранной таблицы (endpoint `POST /api/quote/price-levels`,
|
||||
handler `internal/handlers/quote.go:53`).
|
||||
|
||||
### 1.1 Расширить ответную структуру `PriceLevelsItem` (строки ~80-93)
|
||||
|
||||
Добавь три флага, показывающих, что соответствующая цена подставлена из world:
|
||||
|
||||
```go
|
||||
type PriceLevelsItem struct {
|
||||
// ... существующие поля ...
|
||||
EstimateFromWorld bool `json:"estimate_from_world"`
|
||||
WarehouseFromWorld bool `json:"warehouse_from_world"`
|
||||
CompetitorFromWorld bool `json:"competitor_from_world"`
|
||||
PriceMissing []string `json:"price_missing"`
|
||||
}
|
||||
```
|
||||
|
||||
### 1.2 Резолв world-прайслиста и его цен
|
||||
|
||||
В `CalculatePriceLevels` карта `levelBySource` (строки ~205-209) содержит только 3 источника.
|
||||
Добавь резолв world **отдельно** (не обязательно добавлять его в `levelBySource`, чтобы не
|
||||
попасть в `ResolvedPricelistIDs` как «обычный» уровень — хотя можно и добавить, тогда
|
||||
он просто не отрисуется на фронте). Проще всего — отдельный блок после цикла резолва:
|
||||
|
||||
- Определи `worldID uint`:
|
||||
- если `req.PricelistIDs["world"] > 0` — взять его;
|
||||
- иначе `s.pricelistRepo.GetLatestActiveBySource("world")`;
|
||||
- иначе `s.localDB.GetLatestLocalPricelistBySource("world")`.
|
||||
- Если `worldID != 0` — `worldPrices, _ := s.lookupPricesByPricelistID(worldID, lotNames, req.NoCache)`.
|
||||
- Если world-прайслиста нет — `worldPrices` пустой, фолбэк просто не срабатывает (штатно).
|
||||
|
||||
Переиспользуй существующий `lookupPricesByPricelistID` (строка ~286) — он уже умеет
|
||||
server→local fallback и кэш. Ничего нового писать не надо.
|
||||
|
||||
### 1.3 Применить фолбэк в цикле по позициям (строки ~253-274)
|
||||
|
||||
Сейчас логика: `EstimatePrice`/`WarehousePrice`/`CompetitorPrice` ставятся только если
|
||||
`p > 0`, иначе `nil` и `source` дописывается в `PriceMissing`.
|
||||
|
||||
Новая логика для КАЖДОЙ из трёх колонок (пример для warehouse):
|
||||
|
||||
```go
|
||||
if p, ok := levelBySource[...Warehouse].prices[reqItem.LotName]; ok && p > 0 {
|
||||
price := p
|
||||
item.WarehousePrice = &price
|
||||
} else if wp, ok := worldPrices[reqItem.LotName]; ok && wp > 0 {
|
||||
price := wp
|
||||
item.WarehousePrice = &price
|
||||
item.WarehouseFromWorld = true
|
||||
}
|
||||
```
|
||||
|
||||
- Аналогично для Estimate (`EstimateFromWorld`) и Competitor (`CompetitorFromWorld`).
|
||||
- **`PriceMissing`**: позиция считается missing **только если и родной, и world цены нет**.
|
||||
Т.е. дописывай source в `PriceMissing`, только когда `item.XxxPrice == nil` ПОСЛЕ попытки
|
||||
world-фолбэка. Существующие проверки `if item.WarehousePrice == nil { append PriceMissing }`
|
||||
сработают корректно сами, т.к. при успешном world-фолбэке указатель уже не nil. ✅
|
||||
- Дельты (`calculateDelta`, строки ~276-278) остаются как есть — они работают по указателям и
|
||||
автоматически учтут world-цены.
|
||||
|
||||
**Gotcha:** порядок важен — сначала пытаемся родную цену, только при её отсутствии/≤0 берём world.
|
||||
|
||||
---
|
||||
|
||||
## ЧАСТЬ 2 — Frontend: `web/templates/index.html` → `renderPricingTab`
|
||||
|
||||
Данные приходят в `priceMap[U(lot)]` = объект `PriceLevelsItem` с новыми полями
|
||||
`*_from_world`. Нужно протянуть флаги до ячеек и покрасить.
|
||||
|
||||
### 2.1 `_getUnitPrices(pl)` (строки ~4125-4129)
|
||||
|
||||
Верни ещё и флаги источника:
|
||||
|
||||
```js
|
||||
const _getUnitPrices = (pl) => ({
|
||||
estUnit: (pl && pl.estimate_price > 0) ? pl.estimate_price : 0,
|
||||
warehouseUnit: (pl && pl.warehouse_price > 0) ? pl.warehouse_price : null,
|
||||
competitorUnit: (pl && pl.competitor_price > 0) ? pl.competitor_price : null,
|
||||
estWorld: !!(pl && pl.estimate_from_world),
|
||||
whWorld: !!(pl && pl.warehouse_from_world),
|
||||
compWorld: !!(pl && pl.competitor_from_world),
|
||||
});
|
||||
```
|
||||
|
||||
### 2.2 Протянуть флаги через `_buildRows` (строки ~4135-4244)
|
||||
|
||||
В каждом месте, где формируется sub-row/row объект (`_pushCartRow` ~4143, baseLot ~4185,
|
||||
allocs ~4197, финальный push ~4221), добавь поля `estWorld/whWorld/compWorld` из `u`.
|
||||
- Для «н/д»-строки без subRows (строки ~4208-4215) — все три `false`.
|
||||
- В финальном push (строки ~4221-4232) прокинь `estWorld: sub.estWorld` и т.д.
|
||||
|
||||
### 2.3 Покрасить ячейки в Buy-таблице (строки ~4283-4285)
|
||||
|
||||
Определи хелпер класса подсветки один раз в начале `renderPricingTab`:
|
||||
|
||||
```js
|
||||
const WORLD_CLS = 'bg-amber-50 text-amber-700'; // фон ячейки + цвет текста
|
||||
```
|
||||
|
||||
Применяй к соответствующей `<td>`:
|
||||
|
||||
```js
|
||||
<td class="px-3 py-1.5 text-right text-xs ${borderTop} ${r.estWorld ? WORLD_CLS : ''}">${r.estUnit > 0 ? formatCurrency(r.estUnit) : '—'}</td>
|
||||
<td class="px-3 py-1.5 text-right text-xs ${borderTop} ${r.whWorld ? WORLD_CLS : ''}">${r.warehouseUnit != null ? formatCurrency(r.warehouseUnit) : '—'}</td>
|
||||
<td class="px-3 py-1.5 text-right text-xs ${borderTop} ${r.compWorld ? WORLD_CLS : ''}">${r.competitorUnit != null ? formatCurrency(r.competitorUnit) : '—'}</td>
|
||||
```
|
||||
|
||||
> **Важно про цвет:** НЕ используй `text-gray/green/red/blue-*` для маркера — `applyCustomPrice`
|
||||
> (строки ~4393-4461) вырезает эти семейства регэкспом на vendor-ячейках. `amber` безопасен.
|
||||
> `amber-50/amber-700` уже в духе палитры проекта (там есть `bg-orange-*`, `text-red-*`).
|
||||
|
||||
### 2.4 Итого и красная «*» (строки ~4269-4293, `_setPartialTotal` ~4357-4367)
|
||||
|
||||
Здесь **менять почти ничего не нужно**: т.к. backend теперь отдаёт world-цену в
|
||||
`warehouse_price`/`competitor_price` (не nil), значения `r.warehouse`/`r.competitor` перестают
|
||||
быть null там, где сработал world → `cntWh`/`cntComp` увеличиваются → покрытие полное →
|
||||
`_setPartialTotal` сам уберёт «*». ✅ Просто проверь это поведение при тесте.
|
||||
|
||||
### 2.5 Таблица «Цена продажи» (строки ~4303-4345)
|
||||
|
||||
Sale-таблица считает цены как `unit * множитель` из тех же `r.warehouseUnit`/`r.competitorUnit`
|
||||
(строки ~4310-4312), поэтому world-цены попадут туда автоматически. Нужно только **покрасить**
|
||||
ячейки Estimate/Склад/Конкуренты по тем же флагам (строки ~4335-4337) — добавь
|
||||
`${r.estWorld ? WORLD_CLS : ''}` и аналоги, как в 2.3.
|
||||
|
||||
---
|
||||
|
||||
## ЧАСТЬ 3 — CSV-экспорт: `internal/services/export.go`
|
||||
|
||||
Путь экспорта полностью отдельный от `CalculatePriceLevels`. Точка входа:
|
||||
`ExportConfigPricingCSV` (`internal/handlers/export.go:226`) →
|
||||
`ConfigToPricingExportData` → `buildPricingExportBlock` → `resolvePricingTotals` (строка ~593).
|
||||
|
||||
### 3.1 World-фолбэк в `resolvePricingTotals` (строки ~593-641)
|
||||
|
||||
- После резолва `estimateID/warehouseID/competitorID` добавь `worldID`:
|
||||
`s.localDB.GetLatestLocalPricelistBySource("world")` → `worldID = &latest.ServerID`.
|
||||
- `worldPrices := s.batchLookupPrices(worldID, lots)` (переиспользуй существующий batch, строка ~645).
|
||||
- В цикле по `lots` (строки ~628-639): если родной цены нет — подставь `worldPrices[lot]` и
|
||||
запомни, что она из world.
|
||||
|
||||
### 3.2 Пометка world-цен в CSV
|
||||
|
||||
Расширь `pricingLevels` (строка ~587) флагами источника:
|
||||
|
||||
```go
|
||||
type pricingLevels struct {
|
||||
Estimate *float64
|
||||
Stock *float64
|
||||
Competitor *float64
|
||||
EstimateWorld bool
|
||||
StockWorld bool
|
||||
CompetitorWorld bool
|
||||
}
|
||||
```
|
||||
|
||||
Прокинь их до `ProjectPricingExportRow` (строка ~90) — добавь такие же bool-поля
|
||||
(смотри, где строится row: `buildPricingExportBlock` ~строка 353).
|
||||
|
||||
**Способ пометки: отдельная колонка-комментарий** (согласовано с заказчиком). Значения цен НЕ
|
||||
меняем (никаких суффиксов) — добавляем в конец строки новую текстовую колонку, где перечислены
|
||||
столбцы, в которых цена взята из world-прайслиста.
|
||||
|
||||
#### Заголовок — `pricingCSVHeaders` (строки ~767-790)
|
||||
|
||||
Добавь колонку **последней** (после «Ручная цена»), чтобы не сдвигать существующие столбцы:
|
||||
|
||||
```go
|
||||
headers = append(headers, "Заглушка (world)")
|
||||
```
|
||||
|
||||
#### Строка — `pricingCSVRow` (строки ~792-819)
|
||||
|
||||
Собери человекочитаемый список названий колонок, где сработал world-фолбэк, и добавь его
|
||||
последним полем. Названия бери те же, что в заголовках таблицы: `Estimate`, `Stock`, `Конкуренты`.
|
||||
|
||||
```go
|
||||
var worldCols []string
|
||||
if row.EstimateWorld { worldCols = append(worldCols, "Estimate") }
|
||||
if row.StockWorld { worldCols = append(worldCols, "Stock") }
|
||||
if row.CompetitorWorld { worldCols = append(worldCols, "Конкуренты") }
|
||||
comment := ""
|
||||
if len(worldCols) > 0 {
|
||||
comment = "world: " + strings.Join(worldCols, ", ")
|
||||
}
|
||||
record = append(record, comment) // напр. "world: Stock, Конкуренты"; пусто, если фолбэка не было
|
||||
```
|
||||
|
||||
- Если world-фолбэк ни в одной колонке не сработал — ячейка пустая (`""`).
|
||||
- Порядок и число колонок в заголовке и в строке должны совпадать — колонку-комментарий
|
||||
добавляй **и туда, и туда** последней, безусловно (не под флагом `opts.*`), чтобы CSV не
|
||||
«съехал».
|
||||
|
||||
#### Итоговая строка — `pricingConfigSummaryRow` (строки ~821-848)
|
||||
|
||||
Добавь пустую ячейку в конец (комментарий на суммарной строке не нужен), чтобы число колонок
|
||||
совпадало с шапкой:
|
||||
|
||||
```go
|
||||
record = append(record, "")
|
||||
```
|
||||
|
||||
- Суммы (`sumPricingColumn`, строки ~877+) считают по указателям — world-цены уже включены в
|
||||
Estimate/Stock/Competitor, ничего не меняем.
|
||||
- Не забудь `import "strings"` — он в файле уже есть (используется в `collectPricingLots`).
|
||||
|
||||
---
|
||||
|
||||
## Files to modify
|
||||
|
||||
| Файл | Что |
|
||||
|------|-----|
|
||||
| `internal/models/pricelist.go` | Константа `PricelistSourceWorld`, `IsValid`, `NormalizePricelistSource` |
|
||||
| `internal/services/quote.go` | `PriceLevelsItem` + 3 флага; резолв world; фолбэк в `CalculatePriceLevels` |
|
||||
| `web/templates/index.html` | `_getUnitPrices`, `_buildRows`, покраска ячеек Buy+Sale (`WORLD_CLS`) |
|
||||
| `internal/services/export.go` | `pricingLevels`+флаги, `resolvePricingTotals` world-фолбэк, `ProjectPricingExportRow`, `pricingCSVRow` маркер |
|
||||
|
||||
## Edge cases (чтобы не споткнуться)
|
||||
|
||||
1. **World-прайслиста нет вовсе** → `worldID == 0`, `worldPrices` пуст → поведение как сейчас
|
||||
(пустые «—» и «*»). Не должно падать.
|
||||
2. **World-цена = 0 или ≤ 0** → считается отсутствующей, фолбэк не срабатывает (проверка `wp > 0`).
|
||||
3. **Родная цена есть** → world НЕ используется, флаг `false`, ячейка не красится.
|
||||
4. **LOT есть только в world** → все три колонки берутся из world и красятся; `PriceMissing`
|
||||
пустой; строка полностью «заглушечная».
|
||||
5. **Кэш цен** (`priceCache` в quote.go) — world идёт через тот же `lookupPricesByPricelistID`,
|
||||
ключ кэша включает `pricelistID`, коллизий нет.
|
||||
6. **`applyCustomPrice` regex** — маркер-класс должен быть `amber` (или иное семейство, кроме
|
||||
gray/green/red/blue), иначе будет затёрт на vendor-ячейках. Vendor-колонку world не трогает.
|
||||
7. **Sale-таблица** множит на коэффициент — world-цена корректно умножается, красим по флагу.
|
||||
8. **Нормализация LOT** — все lookup'ы идут по `NormalizeLotName` (uppercase); world-цены
|
||||
тоже резолвятся через `lookupPricesByPricelistID`, который матчит `UPPER(lot_name)`. Согласовано.
|
||||
|
||||
## Verification (как проверить end-to-end)
|
||||
|
||||
1. Сборка: `go build ./cmd/qfs && go vet ./...`
|
||||
2. Убедись, что в локальной БД есть world-прайслист с ценами:
|
||||
```bash
|
||||
sqlite3 ~/.local/state/quoteforge/qfs.db \
|
||||
"SELECT id,source,version FROM local_pricelists WHERE source='world';"
|
||||
sqlite3 ~/.local/state/quoteforge/qfs.db \
|
||||
"SELECT COUNT(*) FROM local_pricelist_items WHERE pricelist_id=(SELECT id FROM local_pricelists WHERE source='world' ORDER BY id DESC LIMIT 1);"
|
||||
```
|
||||
Если world-прайслиста нет — синхронизировать/залить тестовый (иначе фолбэк нечем проверять).
|
||||
3. Backend-проверка API напрямую (подставь LOT, у которого нет warehouse/competitor цены, но
|
||||
есть world):
|
||||
```bash
|
||||
curl -s -X POST http://localhost:8080/api/quote/price-levels \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"items":[{"lot_name":"MB_INTEL_4.SAPHIRE(EMERALD)RAPIDS_2S_32XDDR5_HGX8","quantity":1}]}' | jq
|
||||
```
|
||||
Ожидаем: у позиции без родной competitor-цены `competitor_price != null` и
|
||||
`competitor_from_world: true`, а `price_missing` не содержит `competitor`.
|
||||
4. UI (`go run ./cmd/qfs`, вкладка «Ценообразование», раздел «Цена покупки»):
|
||||
- ячейки, ранее «—» в «Склад»/«Конкуренты», теперь показывают цену на **amber-фоне**;
|
||||
- «Итого» по этим колонкам стало полным и **без красной «*»** (если все пробелы закрыты world);
|
||||
- то же самое в «Цена продажи».
|
||||
Прогони этот шаг через `/verify` или браузерную автоматизацию для скриншота до/после.
|
||||
5. CSV: нажми «Экспорт CSV», убедись, что world-цены присутствуют в Estimate/Stock/Конкуренты,
|
||||
а в последней колонке «Заглушка (world)» указано, где именно сработал фолбэк
|
||||
(напр. `world: Stock, Конкуренты`). Число колонок в шапке, строках и итоговой строке совпадает.
|
||||
6. Существующие тесты: `go test ./internal/services/...`
|
||||
(см. `internal/services/quote_price_levels_test.go` — добавь кейс на world-фолбэк:
|
||||
позиция без warehouse/competitor цены, но с world → флаги `*_from_world=true`, `price_missing` пуст).
|
||||
|
||||
## Docs
|
||||
|
||||
Согласно `CLAUDE.md`/`bible-local`: архитектурное решение о world-фолбэке записать в
|
||||
`bible-local/` (например, в `04-api.md` — новые поля `*_from_world` в `/api/quote/price-levels`,
|
||||
и/или короткая заметка в `bible-local/decisions/`). Обнови в том же коммите, что и код.
|
||||
@@ -40,14 +40,25 @@ Readiness guard:
|
||||
|
||||
## Pricing contract
|
||||
|
||||
Prices come only from `local_pricelist_items`.
|
||||
`local_pricelist_items` is the single source of truth for both prices and component catalog (lot_name + lot_category). There is no separate component catalog table.
|
||||
|
||||
Rules:
|
||||
- `local_components` is metadata-only;
|
||||
- quote calculation must not read prices from components;
|
||||
- `local_components` table has been removed; do not recreate it;
|
||||
- component list for the configurator autocomplete comes from `local_pricelist_items` via `ListComponents`;
|
||||
- quote calculation reads prices from `local_pricelist_items` only;
|
||||
- latest pricelist selection ignores snapshots without items;
|
||||
- auto pricelist mode stays auto and must not be persisted as an explicit resolved ID.
|
||||
|
||||
## lot_name case handling
|
||||
|
||||
lot_names in `local_pricelist_items` may be stored in mixed case in databases synced before normalization was enforced. `NormalizeLotName` (uppercase + trim) is applied at sync time via `PricelistItemToLocal`, but existing rows are not retroactively updated.
|
||||
|
||||
Rules:
|
||||
- all SQLite queries that filter by `lot_name` must use `UPPER(lot_name) IN ?` or `UPPER(lot_name) = ?` with an uppercased input — never a bare `=` or `IN` on a string that may have been sourced from user input or a legacy row;
|
||||
- result map keys must preserve the original case passed by the caller (build a `uppercase → original` index before the query);
|
||||
- `GetLocalPricesForLots` is the canonical pattern: it uppercases the input list, queries with `UPPER(lot_name) IN ?`, and returns keys that match the input lot_names;
|
||||
- frontend JS must never infer a component category from the lot_name prefix; `lot_category` from `local_pricelist_items` is the only valid source; items without a category fall into the "Other" tab.
|
||||
|
||||
## Pricing tab layout
|
||||
|
||||
The Pricing tab (Ценообразование) has two tables: Buy (Цена покупки) and Sale (Цена продажи).
|
||||
@@ -121,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.
|
||||
|
||||
@@ -131,14 +142,77 @@ 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 after `SyncComponents`; failure is non-fatal (Warn log only);
|
||||
- sync runs as part of the pricelist pull; failure is non-fatal (Warn log only);
|
||||
- `local_qt_settings` is a read-only cache — never written by user actions;
|
||||
- absent or unparseable settings: QF uses hardcoded fallbacks for that key only;
|
||||
- `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.
|
||||
|
||||
+20
-12
@@ -8,9 +8,8 @@ Main tables:
|
||||
|
||||
| Table | Purpose |
|
||||
| --- | --- |
|
||||
| `local_components` | synced component metadata |
|
||||
| `local_pricelists` | local pricelist headers |
|
||||
| `local_pricelist_items` | local pricelist rows, the only runtime price source |
|
||||
| `local_pricelist_items` | pricelist rows; the only runtime source of prices and component catalog |
|
||||
| `local_projects` | user projects |
|
||||
| `local_configurations` | user configurations |
|
||||
| `local_configuration_versions` | immutable revision snapshots |
|
||||
@@ -25,8 +24,11 @@ Main tables:
|
||||
Rules:
|
||||
- cache tables may be rebuilt if local migration recovery requires it;
|
||||
- user-authored tables must not be dropped as a recovery shortcut;
|
||||
- `local_pricelist_items` is the only valid runtime source of prices;
|
||||
- configuration `items` and `vendor_spec` are stored as JSON payloads inside configuration rows.
|
||||
- `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.
|
||||
|
||||
## MariaDB
|
||||
|
||||
@@ -35,8 +37,6 @@ MariaDB is the central sync database (`RFQ_LOG`). Final schema as of 2026-04-15.
|
||||
### QuoteForge tables (qt_*)
|
||||
|
||||
Runtime read:
|
||||
- `qt_categories` — pricelist categories (note: `name`/`name_ru` columns being removed; QF does not use them)
|
||||
- `qt_lot_metadata` — component metadata, price settings
|
||||
- `qt_pricelists` — pricelist headers (source: estimate / warehouse / competitor)
|
||||
- `qt_pricelist_items` — pricelist rows
|
||||
- `qt_partnumber_books` — partnumber book headers
|
||||
@@ -53,6 +53,8 @@ Insert-only tracking:
|
||||
- `qt_vendor_partnumber_seen` — vendor partnumbers encountered during sync; `lot_suggestion` column updated when user manually maps PN → LOT in vendor-spec UI
|
||||
|
||||
Server-side only (not queried by client runtime):
|
||||
- `qt_categories` — pricelist category registry; QF runtime serves category lists for the UI from `models.DefaultCategories` (Go) overlaid with categories present in `local_pricelist_items`, not from this table. `name`/`name_ru` columns being removed.
|
||||
- `qt_lot_metadata` — component metadata / price settings; the Go server-side component/category management layer (`ComponentRepository`, `CategoryRepository`, `ComponentService`) was removed — no client code reads this table
|
||||
- `qt_component_usage_stats` — aggregated component popularity stats (written by server jobs)
|
||||
- `qt_pricing_alerts` — price anomaly alerts (models exist in Go; feature disabled in runtime)
|
||||
- `qt_schema_migrations` — server migration history (applied via `go run ./cmd/qfs -migrate`)
|
||||
@@ -79,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.
|
||||
@@ -191,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
|
||||
@@ -253,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
|
||||
@@ -293,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 | |
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
| --- | --- | --- |
|
||||
| `POST` | `/api/quote/validate` | validate config items |
|
||||
| `POST` | `/api/quote/calculate` | calculate quote totals |
|
||||
| `POST` | `/api/quote/price-levels` | resolve estimate/warehouse/competitor prices |
|
||||
| `POST` | `/api/quote/price-levels` | resolve estimate/warehouse/competitor prices (falls back to `world` source per column, see [decisions/2026-07-10-world-pricelist-fallback.md](decisions/2026-07-10-world-pricelist-fallback.md)) |
|
||||
| `POST` | `/api/export/csv` | export a single configuration |
|
||||
| `GET` | `/api/configs/:uuid/export` | export a stored configuration |
|
||||
| `GET` | `/api/projects/:uuid/export` | legacy project BOM export |
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Decision: `world` pricelist as a fallback stub for missing prices
|
||||
|
||||
**Date:** 2026-07-10
|
||||
**Status:** active
|
||||
|
||||
## Context
|
||||
|
||||
Four pricelist `source` values sync from the server: `estimate`, `warehouse`, `competitor`,
|
||||
`world`. Only the first three were ever read — `world` synced into `local_pricelists` /
|
||||
`local_pricelist_items` but nothing consumed it, so LOTs with no warehouse/competitor price
|
||||
showed as "—" in the "Ценообразование" tab, which also broke the "Итого" coverage (red "*").
|
||||
|
||||
## Decision
|
||||
|
||||
`world` is a fallback stub, applied per-column, only when the native price for that column
|
||||
is missing or ≤ 0:
|
||||
|
||||
- Resolution order per column: native source price → `world` price → still missing.
|
||||
- Applies to all three Buy columns (Estimate, Склад, Конкуренты), the Sale table (same
|
||||
unit prices, multiplied by the existing sale coefficients), and CSV export.
|
||||
- A world-fallback price counts toward "Итого" like a native price (closes the red "*" gap).
|
||||
- UI marks only the specific cell that used a fallback, with `bg-amber-50 text-amber-700`
|
||||
(amber was chosen because `applyCustomPrice()` strips `gray/green/red/blue` text-color
|
||||
classes via regex on vendor-price cells — amber survives that).
|
||||
- CSV keeps price values untouched (no suffixes) and adds one trailing comment column,
|
||||
"Заглушка (world)", listing which columns used the fallback per row (e.g.
|
||||
`world: Stock, Конкуренты`), always present regardless of export options so column counts
|
||||
stay aligned across header/rows/summary.
|
||||
- `world` is resolved independently in each call site (`quote.go` `CalculatePriceLevels`,
|
||||
`export.go` `resolvePricingTotals`) via "explicit ID → latest active → latest local", same
|
||||
pattern as the other three sources. It is intentionally NOT added to `levelBySource` /
|
||||
`ResolvedPricelistIDs` as a fourth on-screen level.
|
||||
- `NormalizePricelistSource("world")` returns `PricelistSourceWorld`, not `estimate` — it must
|
||||
not collapse into the estimate source.
|
||||
|
||||
## Consequences
|
||||
|
||||
- `PriceLevelsItem` (API `POST /api/quote/price-levels`) carries three new bools:
|
||||
`estimate_from_world`, `warehouse_from_world`, `competitor_from_world`.
|
||||
- `price_missing` on that endpoint only lists a source when BOTH the native and the
|
||||
`world` price are unavailable.
|
||||
- No new config-level column (e.g. `world_pricelist_id`) — world always resolves to
|
||||
"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
|
||||
|
||||
+156
-18
@@ -168,6 +168,13 @@ func main() {
|
||||
// Create connection manager. Runtime stays local-first; MariaDB is used on demand by sync/setup only.
|
||||
connMgr := db.NewConnectionManager(local)
|
||||
|
||||
// Keep the online-status cache fresh in the background so request-handling
|
||||
// goroutines (health checks, middleware, etc.) never block on the MySQL
|
||||
// dial/read timeout themselves.
|
||||
connMgrCtx, connMgrCancel := context.WithCancel(context.Background())
|
||||
defer connMgrCancel()
|
||||
connMgr.Start(connMgrCtx)
|
||||
|
||||
dbUser := local.GetDBUser()
|
||||
|
||||
slog.Info("starting QuoteForge server",
|
||||
@@ -272,6 +279,8 @@ func main() {
|
||||
syncWorker.Stop()
|
||||
workerCancel()
|
||||
backupCancel()
|
||||
connMgr.Stop()
|
||||
connMgrCancel()
|
||||
|
||||
// Then shutdown HTTP server
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
@@ -677,8 +686,7 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
var projectService *services.ProjectService
|
||||
|
||||
syncService = sync.NewService(connMgr, local)
|
||||
componentService := services.NewComponentService(nil, nil)
|
||||
quoteService := services.NewQuoteService(nil, nil, local, nil)
|
||||
quoteService := services.NewQuoteService(nil, local)
|
||||
exportService := services.NewExportService(cfg.Export, local)
|
||||
|
||||
// isOnline function for local-first architecture
|
||||
@@ -689,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 {
|
||||
@@ -775,7 +784,7 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
templatesPath := filepath.Join("web", "templates")
|
||||
|
||||
// Handlers
|
||||
componentHandler := handlers.NewComponentHandler(componentService, local)
|
||||
componentHandler := handlers.NewComponentHandler(local)
|
||||
quoteHandler := handlers.NewQuoteHandler(quoteService)
|
||||
exportHandler := handlers.NewExportHandler(exportService, configService, projectService, dbUsername)
|
||||
pricelistHandler := handlers.NewPricelistHandler(local)
|
||||
@@ -894,6 +903,27 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
router.GET("/pricelists/:id", webHandler.PricelistDetail)
|
||||
router.GET("/partnumber-books", webHandler.PartnumberBooks)
|
||||
|
||||
// Short project URLs: /:code → main variant, /:code/:variant → named variant
|
||||
router.GET("/:code", func(c *gin.Context) {
|
||||
code := c.Param("code")
|
||||
project, err := projectService.GetByCode(code)
|
||||
if err != nil {
|
||||
c.Redirect(http.StatusFound, "/projects")
|
||||
return
|
||||
}
|
||||
c.Redirect(http.StatusFound, "/projects/"+project.UUID)
|
||||
})
|
||||
router.GET("/:code/:variant", func(c *gin.Context) {
|
||||
code := c.Param("code")
|
||||
variant := c.Param("variant")
|
||||
project, err := projectService.GetByCodeAndVariant(code, variant)
|
||||
if err != nil {
|
||||
c.Redirect(http.StatusFound, "/projects")
|
||||
return
|
||||
}
|
||||
c.Redirect(http.StatusFound, "/projects/"+project.UUID)
|
||||
})
|
||||
|
||||
// htmx partials
|
||||
partials := router.Group("/partials")
|
||||
{
|
||||
@@ -976,8 +1006,27 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
return
|
||||
}
|
||||
|
||||
uuids := make([]string, len(cfgs))
|
||||
for i, cfg := range cfgs {
|
||||
uuids[i] = cfg.UUID
|
||||
}
|
||||
viewers, _ := syncService.ListActiveViewersByConfigUUIDs(uuids)
|
||||
|
||||
type cfgRow struct {
|
||||
models.Configuration
|
||||
Viewers []string `json:"viewers"`
|
||||
}
|
||||
rows := make([]cfgRow, len(cfgs))
|
||||
for i, cfg := range cfgs {
|
||||
v := viewers[cfg.UUID]
|
||||
if v == nil {
|
||||
v = []string{}
|
||||
}
|
||||
rows[i] = cfgRow{Configuration: cfg, Viewers: v}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"configurations": cfgs,
|
||||
"configurations": rows,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"per_page": perPage,
|
||||
@@ -1148,6 +1197,15 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
c.JSON(http.StatusOK, config)
|
||||
})
|
||||
|
||||
configs.POST("/:uuid/snapshot", func(c *gin.Context) {
|
||||
uuid := c.Param("uuid")
|
||||
if err := configService.SnapshotCurrentState(uuid); err != nil {
|
||||
respondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
})
|
||||
|
||||
configs.PATCH("/:uuid/project", func(c *gin.Context) {
|
||||
uuid := c.Param("uuid")
|
||||
var req struct {
|
||||
@@ -1287,6 +1345,45 @@ 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 {
|
||||
switch {
|
||||
case errors.Is(err, services.ErrConfigNotFound):
|
||||
respondError(c, http.StatusNotFound, "resource not found", err)
|
||||
default:
|
||||
respondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
}
|
||||
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 {
|
||||
switch {
|
||||
case errors.Is(err, services.ErrConfigNotFound):
|
||||
respondError(c, http.StatusNotFound, "resource not found", err)
|
||||
default:
|
||||
respondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, result)
|
||||
})
|
||||
|
||||
configs.PATCH("/:uuid/server-count", func(c *gin.Context) {
|
||||
uuid := c.Param("uuid")
|
||||
var req struct {
|
||||
@@ -1303,6 +1400,16 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
}
|
||||
c.JSON(http.StatusOK, config)
|
||||
})
|
||||
|
||||
configs.POST("/:uuid/presence", func(c *gin.Context) {
|
||||
_ = local.AddOpenConfigUUID(c.Param("uuid"))
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
})
|
||||
|
||||
configs.DELETE("/:uuid/presence", func(c *gin.Context) {
|
||||
_ = local.RemoveOpenConfigUUID(c.Param("uuid"))
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
})
|
||||
}
|
||||
|
||||
projects := api.Group("/projects")
|
||||
@@ -1483,21 +1590,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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1517,7 +1628,9 @@ 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):
|
||||
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)
|
||||
@@ -1555,7 +1668,9 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, services.ErrReservedMainVariant),
|
||||
errors.Is(err, services.ErrCannotRenameMainVariant):
|
||||
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)
|
||||
@@ -1639,8 +1754,32 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
projUUIDs := make([]string, len(result.Configs))
|
||||
for i, cfg := range result.Configs {
|
||||
projUUIDs[i] = cfg.UUID
|
||||
}
|
||||
projViewers, _ := syncService.ListActiveViewersByConfigUUIDs(projUUIDs)
|
||||
|
||||
type projCfgRow struct {
|
||||
models.Configuration
|
||||
Viewers []string `json:"viewers"`
|
||||
}
|
||||
projRows := make([]projCfgRow, len(result.Configs))
|
||||
for i, cfg := range result.Configs {
|
||||
v := projViewers[cfg.UUID]
|
||||
if v == nil {
|
||||
v = []string{}
|
||||
}
|
||||
projRows[i] = projCfgRow{Configuration: cfg, Viewers: v}
|
||||
}
|
||||
|
||||
c.Header("X-Config-Status", status)
|
||||
c.JSON(http.StatusOK, result)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"project_uuid": result.ProjectUUID,
|
||||
"configurations": projRows,
|
||||
"total": result.Total,
|
||||
})
|
||||
})
|
||||
|
||||
projects.PATCH("/:uuid/configs/reorder", func(c *gin.Context) {
|
||||
@@ -1777,7 +1916,6 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
syncAPI.GET("/readiness", syncHandler.GetReadiness)
|
||||
syncAPI.GET("/info", syncHandler.GetInfo)
|
||||
syncAPI.GET("/users-status", syncHandler.GetUsersStatus)
|
||||
syncAPI.POST("/components", syncHandler.SyncComponents)
|
||||
syncAPI.POST("/pricelists", syncHandler.SyncPricelists)
|
||||
syncAPI.POST("/partnumber-books", syncHandler.SyncPartnumberBooks)
|
||||
syncAPI.POST("/partnumber-seen", syncHandler.ReportPartnumberSeen)
|
||||
|
||||
@@ -1,31 +1,12 @@
|
||||
package article
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
)
|
||||
|
||||
// ErrMissingCategoryForLot is returned when a lot has no category in local_pricelist_items.lot_category.
|
||||
var ErrMissingCategoryForLot = errors.New("missing_category_for_lot")
|
||||
|
||||
type MissingCategoryForLotError struct {
|
||||
LotName string
|
||||
}
|
||||
|
||||
func (e *MissingCategoryForLotError) Error() string {
|
||||
if e == nil || strings.TrimSpace(e.LotName) == "" {
|
||||
return ErrMissingCategoryForLot.Error()
|
||||
}
|
||||
return fmt.Sprintf("%s: %s", ErrMissingCategoryForLot.Error(), e.LotName)
|
||||
}
|
||||
|
||||
func (e *MissingCategoryForLotError) Unwrap() error {
|
||||
return ErrMissingCategoryForLot
|
||||
}
|
||||
|
||||
type Group string
|
||||
|
||||
const (
|
||||
@@ -61,9 +42,10 @@ func GroupForLotCategory(cat string) (group Group, ok bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// ResolveLotCategoriesStrict resolves categories for lotNames using local_pricelist_items.lot_category
|
||||
// for a given server pricelist id. If any lot is missing or has empty category, returns an error.
|
||||
func ResolveLotCategoriesStrict(local *localdb.LocalDB, serverPricelistID uint, lotNames []string) (map[string]string, error) {
|
||||
// ResolveLotCategories returns lot_category for each lotName found in local_pricelist_items
|
||||
// for the given server pricelist. Lots not found in the pricelist are omitted from the result —
|
||||
// callers must treat a missing key as "no category" and skip that lot.
|
||||
func ResolveLotCategories(local *localdb.LocalDB, serverPricelistID uint, lotNames []string) (map[string]string, error) {
|
||||
if local == nil {
|
||||
return nil, fmt.Errorf("local db is nil")
|
||||
}
|
||||
@@ -71,30 +53,8 @@ func ResolveLotCategoriesStrict(local *localdb.LocalDB, serverPricelistID uint,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
missing := make([]string, 0)
|
||||
for _, lot := range lotNames {
|
||||
cat := strings.TrimSpace(cats[lot])
|
||||
if cat == "" {
|
||||
missing = append(missing, lot)
|
||||
continue
|
||||
}
|
||||
cats[lot] = cat
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
fallback, err := local.GetLocalComponentCategoriesByLotNames(missing)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, lot := range missing {
|
||||
if cat := strings.TrimSpace(fallback[lot]); cat != "" {
|
||||
cats[lot] = cat
|
||||
}
|
||||
}
|
||||
for _, lot := range missing {
|
||||
if strings.TrimSpace(cats[lot]) == "" {
|
||||
return nil, &MissingCategoryForLotError{LotName: lot}
|
||||
}
|
||||
}
|
||||
for lot, cat := range cats {
|
||||
cats[lot] = strings.TrimSpace(cat)
|
||||
}
|
||||
return cats, nil
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package article
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -9,7 +8,7 @@ import (
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
)
|
||||
|
||||
func TestResolveLotCategoriesStrict_MissingCategoryReturnsError(t *testing.T) {
|
||||
func TestResolveLotCategories_MissingLotOmitted(t *testing.T) {
|
||||
local, err := localdb.New(filepath.Join(t.TempDir(), "local.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("init local db: %v", err)
|
||||
@@ -36,16 +35,19 @@ func TestResolveLotCategoriesStrict_MissingCategoryReturnsError(t *testing.T) {
|
||||
t.Fatalf("save local items: %v", err)
|
||||
}
|
||||
|
||||
_, err = ResolveLotCategoriesStrict(local, 1, []string{"CPU_A"})
|
||||
if err == nil {
|
||||
t.Fatalf("expected error")
|
||||
cats, err := ResolveLotCategories(local, 1, []string{"CPU_A", "UNKNOWN"})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !errors.Is(err, ErrMissingCategoryForLot) {
|
||||
t.Fatalf("expected ErrMissingCategoryForLot, got %v", err)
|
||||
if cats["CPU_A"] != "" {
|
||||
t.Fatalf("expected empty category for lot with blank lot_category, got %q", cats["CPU_A"])
|
||||
}
|
||||
if _, ok := cats["UNKNOWN"]; ok {
|
||||
t.Fatalf("expected UNKNOWN lot to be omitted from result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveLotCategoriesStrict_FallbackToLocalComponents(t *testing.T) {
|
||||
func TestResolveLotCategories_ReturnsKnownCategories(t *testing.T) {
|
||||
local, err := localdb.New(filepath.Join(t.TempDir(), "local.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("init local db: %v", err)
|
||||
@@ -53,39 +55,40 @@ func TestResolveLotCategoriesStrict_FallbackToLocalComponents(t *testing.T) {
|
||||
t.Cleanup(func() { _ = local.Close() })
|
||||
|
||||
if err := local.SaveLocalPricelist(&localdb.LocalPricelist{
|
||||
ServerID: 2,
|
||||
ServerID: 1,
|
||||
Source: "estimate",
|
||||
Version: "S-2026-02-11-002",
|
||||
Version: "S-2026-02-11-001",
|
||||
Name: "test",
|
||||
IsActive: true,
|
||||
CreatedAt: time.Now(),
|
||||
SyncedAt: time.Now(),
|
||||
}); err != nil {
|
||||
t.Fatalf("save local pricelist: %v", err)
|
||||
t.Fatalf("save pricelist: %v", err)
|
||||
}
|
||||
localPL, err := local.GetLocalPricelistByServerID(2)
|
||||
pl, err := local.GetLocalPricelistByServerID(1)
|
||||
if err != nil {
|
||||
t.Fatalf("get local pricelist: %v", err)
|
||||
t.Fatalf("get pricelist: %v", err)
|
||||
}
|
||||
if err := local.SaveLocalPricelistItems([]localdb.LocalPricelistItem{
|
||||
{PricelistID: localPL.ID, LotName: "CPU_B", LotCategory: "", Price: 10},
|
||||
{PricelistID: pl.ID, LotName: "CPU_B", LotCategory: "CPU", Price: 10},
|
||||
{PricelistID: pl.ID, LotName: "MB_X", LotCategory: "MB", Price: 5},
|
||||
}); err != nil {
|
||||
t.Fatalf("save local items: %v", err)
|
||||
}
|
||||
if err := local.DB().Create(&localdb.LocalComponent{
|
||||
LotName: "CPU_B",
|
||||
Category: "CPU",
|
||||
LotDescription: "cpu",
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("save local components: %v", err)
|
||||
t.Fatalf("save items: %v", err)
|
||||
}
|
||||
|
||||
cats, err := ResolveLotCategoriesStrict(local, 2, []string{"CPU_B"})
|
||||
cats, err := ResolveLotCategories(local, 1, []string{"CPU_B", "MB_X", "NOT_IN_PL"})
|
||||
if err != nil {
|
||||
t.Fatalf("expected fallback, got error: %v", err)
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if cats["CPU_B"] != "CPU" {
|
||||
t.Fatalf("expected CPU, got %q", cats["CPU_B"])
|
||||
}
|
||||
if cats["MB_X"] != "MB" {
|
||||
t.Fatalf("expected MB, got %q", cats["MB_X"])
|
||||
}
|
||||
if _, ok := cats["NOT_IN_PL"]; ok {
|
||||
t.Fatalf("expected NOT_IN_PL to be omitted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupForLotCategory(t *testing.T) {
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
|
||||
type BuildOptions struct {
|
||||
ServerModel string
|
||||
SupportCode string
|
||||
ServerPricelist *uint
|
||||
}
|
||||
|
||||
@@ -55,7 +54,7 @@ func Build(local *localdb.LocalDB, items []models.ConfigItem, opts BuildOptions)
|
||||
return BuildResult{}, fmt.Errorf("pricelist_id required for article")
|
||||
}
|
||||
|
||||
cats, err := ResolveLotCategoriesStrict(local, *opts.ServerPricelist, lotNames)
|
||||
cats, err := ResolveLotCategories(local, *opts.ServerPricelist, lotNames)
|
||||
if err != nil {
|
||||
return BuildResult{}, err
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
+162
-77
@@ -17,6 +17,11 @@ const (
|
||||
defaultPingInterval = 30 * time.Second
|
||||
defaultReconnectCooldown = 10 * time.Second
|
||||
|
||||
// defaultStatusCheckInterval controls how often the background prober
|
||||
// re-checks connectivity to keep IsOnline() cheap. Request-handling
|
||||
// goroutines must never pay the MySQL dial/read timeout themselves.
|
||||
defaultStatusCheckInterval = 15 * time.Second
|
||||
|
||||
maxOpenConns = 10
|
||||
maxIdleConns = 2
|
||||
connMaxLifetime = 5 * time.Minute
|
||||
@@ -33,86 +38,148 @@ type ConnectionStatus struct {
|
||||
// ConnectionManager manages database connections with thread-safety and connection pooling
|
||||
type ConnectionManager struct {
|
||||
localDB *localdb.LocalDB // for getting DSN from settings
|
||||
mu sync.RWMutex // protects db and state
|
||||
mu sync.RWMutex // protects db/lastError/lastCheck only — never held during network I/O
|
||||
connMu sync.Mutex // serializes actual dial/ping attempts; held *instead of* mu during network I/O
|
||||
db *gorm.DB // current connection (nil if not connected)
|
||||
lastError error // last connection error
|
||||
lastCheck time.Time // time of last check/attempt
|
||||
connectTimeout time.Duration // timeout for connection (default: 5s)
|
||||
pingInterval time.Duration // minimum interval between pings (default: 30s)
|
||||
reconnectCooldown time.Duration // pause after failed attempt (default: 10s)
|
||||
|
||||
statusCheckInterval time.Duration // background prober cadence (default: 15s)
|
||||
stopStatusLoop chan struct{} // closed by Stop() to end the background loop
|
||||
}
|
||||
|
||||
// NewConnectionManager creates a new ConnectionManager instance
|
||||
func NewConnectionManager(localDB *localdb.LocalDB) *ConnectionManager {
|
||||
return &ConnectionManager{
|
||||
localDB: localDB,
|
||||
connectTimeout: defaultConnectTimeout,
|
||||
pingInterval: defaultPingInterval,
|
||||
reconnectCooldown: defaultReconnectCooldown,
|
||||
db: nil,
|
||||
lastError: nil,
|
||||
lastCheck: time.Time{},
|
||||
localDB: localDB,
|
||||
connectTimeout: defaultConnectTimeout,
|
||||
pingInterval: defaultPingInterval,
|
||||
reconnectCooldown: defaultReconnectCooldown,
|
||||
statusCheckInterval: defaultStatusCheckInterval,
|
||||
db: nil,
|
||||
lastError: nil,
|
||||
lastCheck: time.Time{},
|
||||
}
|
||||
}
|
||||
|
||||
// GetDB returns the current database connection, establishing it if needed
|
||||
// Thread-safe and respects connection cooldowns
|
||||
// Start launches a background goroutine that keeps the online-status cache
|
||||
// fresh, so that IsOnline() (called from request-handling middleware) never
|
||||
// blocks on network I/O itself. Returns immediately — the app must be able
|
||||
// to serve the local-first UI right away, before connectivity is even known.
|
||||
// Until the first background check completes, IsOnline() reports offline
|
||||
// (the safe default). Stop via ctx cancellation or Stop().
|
||||
func (cm *ConnectionManager) Start(ctx context.Context) {
|
||||
cm.mu.Lock()
|
||||
if cm.stopStatusLoop == nil {
|
||||
cm.stopStatusLoop = make(chan struct{})
|
||||
}
|
||||
stopCh := cm.stopStatusLoop
|
||||
cm.mu.Unlock()
|
||||
|
||||
go func() {
|
||||
// Prime the cache in the background; the dial/read timeout must not
|
||||
// delay server startup.
|
||||
cm.checkOnlineNow()
|
||||
|
||||
ticker := time.NewTicker(cm.statusCheckInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-stopCh:
|
||||
return
|
||||
case <-ticker.C:
|
||||
cm.checkOnlineNow()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Stop ends the background status-refresh loop started by Start.
|
||||
func (cm *ConnectionManager) Stop() {
|
||||
cm.mu.Lock()
|
||||
defer cm.mu.Unlock()
|
||||
if cm.stopStatusLoop != nil {
|
||||
close(cm.stopStatusLoop)
|
||||
cm.stopStatusLoop = nil
|
||||
}
|
||||
}
|
||||
|
||||
// GetDB returns the current database connection, establishing it if needed.
|
||||
// Thread-safe and respects connection cooldowns. The actual network I/O
|
||||
// (dial/ping) never runs while holding cm.mu, so concurrent readers of the
|
||||
// cached status (IsOnline, GetStatus) are never blocked by an in-flight
|
||||
// connection attempt — only concurrent GetDB/checkOnlineNow callers are
|
||||
// serialized against each other, via connMu.
|
||||
func (cm *ConnectionManager) GetDB() (*gorm.DB, error) {
|
||||
// Handle case where localDB is nil
|
||||
if cm.localDB == nil {
|
||||
return nil, fmt.Errorf("local database not initialized")
|
||||
}
|
||||
|
||||
// First check if we already have a valid connection
|
||||
cm.mu.RLock()
|
||||
if cm.db != nil {
|
||||
// Check if connection is still valid and within ping interval
|
||||
if time.Since(cm.lastCheck) < cm.pingInterval {
|
||||
cm.mu.RUnlock()
|
||||
return cm.db, nil
|
||||
}
|
||||
if db, err, ok := cm.cachedResult(); ok {
|
||||
return db, err
|
||||
}
|
||||
cm.mu.RUnlock()
|
||||
|
||||
// Upgrade to write lock
|
||||
// Serialize actual connection attempts so concurrent callers don't dial
|
||||
// in parallel. This may block the calling goroutine on network I/O, but
|
||||
// never blocks other goroutines that only read the cached status.
|
||||
cm.connMu.Lock()
|
||||
defer cm.connMu.Unlock()
|
||||
|
||||
// Re-check: another goroutine may have just finished connecting while we
|
||||
// were waiting for connMu.
|
||||
if db, err, ok := cm.cachedResult(); ok {
|
||||
return db, err
|
||||
}
|
||||
|
||||
newDB, err := cm.dial()
|
||||
|
||||
cm.mu.Lock()
|
||||
defer cm.mu.Unlock()
|
||||
|
||||
// Double-check: someone else might have connected while we were waiting for the write lock
|
||||
if cm.db != nil {
|
||||
// Check if connection is still valid and within ping interval
|
||||
if time.Since(cm.lastCheck) < cm.pingInterval {
|
||||
return cm.db, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Check if we're in cooldown period after a failed attempt
|
||||
if cm.lastError != nil && time.Since(cm.lastCheck) < cm.reconnectCooldown {
|
||||
return nil, cm.lastError
|
||||
}
|
||||
|
||||
// Attempt to connect
|
||||
err := cm.connect()
|
||||
if err != nil {
|
||||
// Drop stale handle so callers don't treat it as an active connection.
|
||||
cm.db = nil
|
||||
cm.lastError = err
|
||||
cm.lastCheck = time.Now()
|
||||
cm.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Update last check time and return success
|
||||
cm.lastCheck = time.Now()
|
||||
cm.db = newDB
|
||||
cm.lastError = nil
|
||||
return cm.db, nil
|
||||
cm.lastCheck = time.Now()
|
||||
cm.mu.Unlock()
|
||||
|
||||
return newDB, nil
|
||||
}
|
||||
|
||||
// connect establishes a new database connection
|
||||
func (cm *ConnectionManager) connect() error {
|
||||
// cachedResult returns (db, err, true) if the cached state is still fresh
|
||||
// enough to answer without a new network round-trip: either a live
|
||||
// connection within pingInterval, or a recent failure still within
|
||||
// reconnectCooldown. Returns ok=false if a fresh connection attempt is needed.
|
||||
func (cm *ConnectionManager) cachedResult() (*gorm.DB, error, bool) {
|
||||
cm.mu.RLock()
|
||||
defer cm.mu.RUnlock()
|
||||
|
||||
if cm.db != nil && time.Since(cm.lastCheck) < cm.pingInterval {
|
||||
return cm.db, nil, true
|
||||
}
|
||||
if cm.db == nil && cm.lastError != nil && time.Since(cm.lastCheck) < cm.reconnectCooldown {
|
||||
return nil, cm.lastError, true
|
||||
}
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
// dial establishes a new database connection. Pure network I/O — must not be
|
||||
// called while holding cm.mu.
|
||||
func (cm *ConnectionManager) dial() (*gorm.DB, error) {
|
||||
// Get DSN from local settings
|
||||
dsn, err := cm.localDB.GetDSN()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting DSN: %w", err)
|
||||
return nil, fmt.Errorf("getting DSN: %w", err)
|
||||
}
|
||||
|
||||
// Create context with timeout
|
||||
@@ -124,18 +191,18 @@ func (cm *ConnectionManager) connect() error {
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("opening database connection: %w", err)
|
||||
return nil, fmt.Errorf("opening database connection: %w", err)
|
||||
}
|
||||
|
||||
// Test the connection
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return fmt.Errorf("getting sql.DB: %w", err)
|
||||
return nil, fmt.Errorf("getting sql.DB: %w", err)
|
||||
}
|
||||
|
||||
// Ping with timeout
|
||||
if err = sqlDB.PingContext(ctx); err != nil {
|
||||
return fmt.Errorf("pinging database: %w", err)
|
||||
return nil, fmt.Errorf("pinging database: %w", err)
|
||||
}
|
||||
|
||||
// Set connection pool settings
|
||||
@@ -143,15 +210,25 @@ func (cm *ConnectionManager) connect() error {
|
||||
sqlDB.SetMaxIdleConns(maxIdleConns)
|
||||
sqlDB.SetConnMaxLifetime(connMaxLifetime)
|
||||
|
||||
// Store the connection
|
||||
cm.db = db
|
||||
|
||||
return nil
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// IsOnline checks if the database is currently connected and responsive.
|
||||
// If disconnected, it tries to reconnect (respecting cooldowns in GetDB).
|
||||
// IsOnline returns the cached connectivity status. It never performs network
|
||||
// I/O itself so it is safe to call from request-handling middleware; the
|
||||
// background loop started by Start() (or an explicit TryConnect) is
|
||||
// responsible for keeping the cache fresh.
|
||||
func (cm *ConnectionManager) IsOnline() bool {
|
||||
cm.mu.RLock()
|
||||
defer cm.mu.RUnlock()
|
||||
return cm.db != nil && cm.lastError == nil
|
||||
}
|
||||
|
||||
// checkOnlineNow checks if the database is currently connected and
|
||||
// responsive, performing real network I/O (dial/ping) as needed. If
|
||||
// disconnected, it tries to reconnect (respecting cooldowns in GetDB). This
|
||||
// must only be called from the background status loop or explicit
|
||||
// user-triggered reconnects, never from request-handling goroutines.
|
||||
func (cm *ConnectionManager) checkOnlineNow() bool {
|
||||
cm.mu.RLock()
|
||||
isDisconnected := cm.db == nil
|
||||
lastErr := cm.lastError
|
||||
@@ -169,57 +246,65 @@ func (cm *ConnectionManager) IsOnline() bool {
|
||||
return lastErr == nil
|
||||
}
|
||||
|
||||
// Need to perform actual ping.
|
||||
cm.mu.Lock()
|
||||
defer cm.mu.Unlock()
|
||||
// Serialize actual ping attempts (network I/O) against other
|
||||
// connect/ping attempts, without ever holding cm.mu during the I/O.
|
||||
cm.connMu.Lock()
|
||||
defer cm.connMu.Unlock()
|
||||
|
||||
// Double-check after acquiring write lock
|
||||
if cm.db == nil {
|
||||
cm.mu.RLock()
|
||||
db := cm.db
|
||||
checkedRecently = time.Since(cm.lastCheck) < cm.pingInterval
|
||||
cm.mu.RUnlock()
|
||||
|
||||
if db == nil {
|
||||
return false
|
||||
}
|
||||
if checkedRecently {
|
||||
return true
|
||||
}
|
||||
|
||||
// Perform ping with timeout
|
||||
// Perform ping with timeout — no locks held here.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), cm.connectTimeout)
|
||||
defer cancel()
|
||||
|
||||
sqlDB, err := cm.db.DB()
|
||||
sqlDB, err := db.DB()
|
||||
if err == nil {
|
||||
err = sqlDB.PingContext(ctx)
|
||||
}
|
||||
|
||||
cm.mu.Lock()
|
||||
defer cm.mu.Unlock()
|
||||
if err != nil {
|
||||
cm.lastError = err
|
||||
cm.lastCheck = time.Now()
|
||||
cm.db = nil
|
||||
return false
|
||||
}
|
||||
|
||||
if err = sqlDB.PingContext(ctx); err != nil {
|
||||
cm.lastError = err
|
||||
cm.lastCheck = time.Now()
|
||||
cm.db = nil
|
||||
return false
|
||||
}
|
||||
|
||||
// Update last check time and return success
|
||||
cm.lastCheck = time.Now()
|
||||
cm.lastError = nil
|
||||
return true
|
||||
}
|
||||
|
||||
// TryConnect forces a new connection attempt (for UI "Reconnect" button)
|
||||
// Ignores cooldown period
|
||||
// TryConnect forces a new connection attempt (for UI "Reconnect" button).
|
||||
// Ignores the reconnect cooldown, but still serializes against other
|
||||
// dial attempts via connMu and never holds cm.mu during network I/O.
|
||||
func (cm *ConnectionManager) TryConnect() error {
|
||||
cm.connMu.Lock()
|
||||
defer cm.connMu.Unlock()
|
||||
|
||||
newDB, err := cm.dial()
|
||||
|
||||
cm.mu.Lock()
|
||||
defer cm.mu.Unlock()
|
||||
|
||||
// Attempt to connect
|
||||
err := cm.connect()
|
||||
if err != nil {
|
||||
cm.db = nil
|
||||
cm.lastError = err
|
||||
cm.lastCheck = time.Now()
|
||||
return err
|
||||
}
|
||||
|
||||
// Update last check time and clear error
|
||||
cm.lastCheck = time.Now()
|
||||
cm.db = newDB
|
||||
cm.lastError = nil
|
||||
cm.lastCheck = time.Now()
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -7,20 +7,17 @@ import (
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/repository"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type ComponentHandler struct {
|
||||
componentService *services.ComponentService
|
||||
localDB *localdb.LocalDB
|
||||
localDB *localdb.LocalDB
|
||||
}
|
||||
|
||||
func NewComponentHandler(componentService *services.ComponentService, localDB *localdb.LocalDB) *ComponentHandler {
|
||||
func NewComponentHandler(localDB *localdb.LocalDB) *ComponentHandler {
|
||||
return &ComponentHandler{
|
||||
componentService: componentService,
|
||||
localDB: localDB,
|
||||
localDB: localDB,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,17 +31,10 @@ func (h *ComponentHandler) List(c *gin.Context) {
|
||||
perPage = 20
|
||||
}
|
||||
|
||||
filter := repository.ComponentFilter{
|
||||
Category: c.Query("category"),
|
||||
Search: c.Query("search"),
|
||||
HasPrice: c.Query("has_price") == "true",
|
||||
ExcludeHidden: c.Query("include_hidden") != "true", // По умолчанию скрытые не показываются
|
||||
}
|
||||
|
||||
localFilter := localdb.ComponentFilter{
|
||||
Category: filter.Category,
|
||||
Search: filter.Search,
|
||||
HasPrice: filter.HasPrice,
|
||||
Category: c.Query("category"),
|
||||
Search: c.Query("search"),
|
||||
HasPrice: c.Query("has_price") == "true",
|
||||
}
|
||||
offset := (page - 1) * perPage
|
||||
localComps, total, err := h.localDB.ListComponents(localFilter, offset, perPage)
|
||||
@@ -61,6 +51,7 @@ func (h *ComponentHandler) List(c *gin.Context) {
|
||||
Category: lc.Category,
|
||||
CategoryName: lc.Category,
|
||||
Model: lc.Model,
|
||||
PriceQuality: lc.PriceQuality,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,6 +82,7 @@ func (h *ComponentHandler) Get(c *gin.Context) {
|
||||
Category: component.Category,
|
||||
CategoryName: component.Category,
|
||||
Model: component.Model,
|
||||
PriceQuality: component.PriceQuality,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -144,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{
|
||||
{
|
||||
|
||||
@@ -177,29 +177,15 @@ func (h *PricelistHandler) GetItems(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
lotNames := make([]string, len(items))
|
||||
for i, item := range items {
|
||||
lotNames[i] = item.LotName
|
||||
}
|
||||
descMap, err := h.localDB.GetLocalComponentDescriptionsByLotNames(lotNames)
|
||||
if err != nil {
|
||||
RespondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
return
|
||||
}
|
||||
|
||||
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": descMap[item.LotName],
|
||||
"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,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ func (h *SupportBundleHandler) DownloadBundle(c *gin.Context) {
|
||||
|
||||
// local_db_stats.json
|
||||
writeJSON("local_db_stats.json", map[string]any{
|
||||
"components": h.localDB.CountLocalComponents(),
|
||||
"components": h.localDB.CountComponents(),
|
||||
"configurations": h.localDB.CountConfigurations(),
|
||||
"projects": h.localDB.CountProjects(),
|
||||
"pricelists": h.localDB.CountLocalPricelists(),
|
||||
@@ -139,6 +139,7 @@ func (h *SupportBundleHandler) DownloadBundle(c *gin.Context) {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
SyncedAt time.Time `json:"synced_at"`
|
||||
IsUsed bool `json:"is_used"`
|
||||
IsActive bool `json:"is_active"`
|
||||
}
|
||||
bySource := map[string][]plEntry{}
|
||||
for _, pl := range pricelists {
|
||||
@@ -150,12 +151,78 @@ func (h *SupportBundleHandler) DownloadBundle(c *gin.Context) {
|
||||
CreatedAt: pl.CreatedAt,
|
||||
SyncedAt: pl.SyncedAt,
|
||||
IsUsed: pl.IsUsed,
|
||||
IsActive: pl.IsActive,
|
||||
}
|
||||
bySource[pl.Source] = append(bySource[pl.Source], e)
|
||||
}
|
||||
writeJSON("pricelists.json", bySource)
|
||||
}
|
||||
|
||||
// pricelist_coverage.json — for each local estimate pricelist: item count by lot_category
|
||||
if pl, err := h.localDB.GetLatestLocalPricelist(); err == nil {
|
||||
type catRow struct {
|
||||
Category string `json:"category"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
type plCoverage struct {
|
||||
Version string `json:"version"`
|
||||
ServerID uint `json:"server_id"`
|
||||
TotalItems int64 `json:"total_items"`
|
||||
Categories []catRow `json:"categories"`
|
||||
}
|
||||
rows, total, catErr := h.localDB.GetLocalPricelistCoverageByCategory(pl.ID)
|
||||
if catErr == nil {
|
||||
cats := make([]catRow, 0, len(rows))
|
||||
for cat, cnt := range rows {
|
||||
cats = append(cats, catRow{Category: cat, Count: cnt})
|
||||
}
|
||||
writeJSON("pricelist_coverage.json", plCoverage{
|
||||
Version: pl.Version,
|
||||
ServerID: pl.ServerID,
|
||||
TotalItems: total,
|
||||
Categories: cats,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// configurator_settings.json — what /api/configurator-settings actually returns
|
||||
if cfgSettings, err := h.localDB.GetConfiguratorSettings(); err == nil {
|
||||
writeJSON("configurator_settings.json", cfgSettings)
|
||||
} else {
|
||||
writeJSON("configurator_settings.json", map[string]any{"error": err.Error()})
|
||||
}
|
||||
|
||||
// component_categories.json — distinct categories in active estimate pricelist
|
||||
if cats, err := h.localDB.GetLocalComponentCategories(); err == nil {
|
||||
writeJSON("component_categories.json", cats)
|
||||
}
|
||||
|
||||
// autocomplete_lots.json — per-category breakdown of lots with their prices
|
||||
// Mirrors what filterAutocomplete() works with: lot_name + estimate_price per category.
|
||||
if pl, err := h.localDB.GetLatestLocalPricelist(); err == nil {
|
||||
if items, err := h.localDB.GetLocalPricelistItems(pl.ID); err == nil {
|
||||
type lotEntry struct {
|
||||
LotName string `json:"lot_name"`
|
||||
Price float64 `json:"price"`
|
||||
HasPrice bool `json:"has_price"`
|
||||
}
|
||||
byCategory := map[string][]lotEntry{}
|
||||
for _, it := range items {
|
||||
entry := lotEntry{
|
||||
LotName: it.LotName,
|
||||
Price: it.Price,
|
||||
HasPrice: it.Price > 0,
|
||||
}
|
||||
byCategory[it.LotCategory] = append(byCategory[it.LotCategory], entry)
|
||||
}
|
||||
writeJSON("autocomplete_lots.json", map[string]any{
|
||||
"pricelist_version": pl.Version,
|
||||
"pricelist_id": pl.ServerID,
|
||||
"by_category": byCategory,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// schema_migrations.json
|
||||
migrations, err := h.localDB.GetSchemaMigrations()
|
||||
if err != nil {
|
||||
@@ -163,6 +230,44 @@ func (h *SupportBundleHandler) DownloadBundle(c *gin.Context) {
|
||||
}
|
||||
writeJSON("schema_migrations.json", migrations)
|
||||
|
||||
// latest_pricelist_items.json — all items from the most recent active estimate pricelist
|
||||
if pl, err := h.localDB.GetLatestLocalPricelist(); err == nil {
|
||||
if items, err := h.localDB.GetLocalPricelistItems(pl.ID); err == nil {
|
||||
type plItem struct {
|
||||
LotName string `json:"lot_name"`
|
||||
LotCategory string `json:"lot_category"`
|
||||
Price float64 `json:"price"`
|
||||
}
|
||||
out := make([]plItem, len(items))
|
||||
for i, it := range items {
|
||||
out[i] = plItem{
|
||||
LotName: it.LotName,
|
||||
LotCategory: it.LotCategory,
|
||||
Price: it.Price,
|
||||
}
|
||||
}
|
||||
writeJSON("latest_pricelist_items.json", map[string]any{
|
||||
"pricelist_version": pl.Version,
|
||||
"pricelist_id": pl.ServerID,
|
||||
"source": pl.Source,
|
||||
"item_count": len(out),
|
||||
"items": out,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// local.db — full SQLite database file (for deep diagnostics)
|
||||
if dbPath := h.localDB.DBFilePath(); dbPath != "" {
|
||||
if f, err := os.Open(dbPath); err == nil {
|
||||
defer f.Close()
|
||||
if w, err := zw.Create("local.db"); err == nil {
|
||||
if _, err := io.Copy(w, f); err != nil {
|
||||
slog.Warn("support bundle: error copying local.db", "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// app.log (tail 5 MiB)
|
||||
if h.logFilePath != "" {
|
||||
if f, err := os.Open(h.logFilePath); err == nil {
|
||||
|
||||
@@ -50,7 +50,6 @@ func NewSyncHandler(localDB *localdb.LocalDB, syncService *sync.Service, connMgr
|
||||
|
||||
// SyncStatusResponse represents the sync status
|
||||
type SyncStatusResponse struct {
|
||||
LastComponentSync *time.Time `json:"last_component_sync"`
|
||||
LastPricelistSync *time.Time `json:"last_pricelist_sync"`
|
||||
LastPricelistAttemptAt *time.Time `json:"last_pricelist_attempt_at,omitempty"`
|
||||
LastPricelistSyncStatus string `json:"last_pricelist_sync_status,omitempty"`
|
||||
@@ -61,7 +60,6 @@ type SyncStatusResponse struct {
|
||||
ComponentsCount int64 `json:"components_count"`
|
||||
PricelistsCount int64 `json:"pricelists_count"`
|
||||
ServerPricelists int `json:"server_pricelists"`
|
||||
NeedComponentSync bool `json:"need_component_sync"`
|
||||
NeedPricelistSync bool `json:"need_pricelist_sync"`
|
||||
Readiness *sync.SyncReadiness `json:"readiness,omitempty"`
|
||||
}
|
||||
@@ -80,19 +78,16 @@ type SyncReadinessResponse struct {
|
||||
func (h *SyncHandler) GetStatus(c *gin.Context) {
|
||||
connStatus := h.connMgr.GetStatus()
|
||||
isOnline := connStatus.IsConnected && strings.TrimSpace(connStatus.LastError) == ""
|
||||
lastComponentSync := h.localDB.GetComponentSyncTime()
|
||||
lastPricelistSync := h.localDB.GetLastSyncTime()
|
||||
componentsCount := h.localDB.CountLocalComponents()
|
||||
componentsCount := h.localDB.CountComponents()
|
||||
pricelistsCount := h.localDB.CountLocalPricelists()
|
||||
lastPricelistAttemptAt := h.localDB.GetLastPricelistSyncAttemptAt()
|
||||
lastPricelistSyncStatus := h.localDB.GetLastPricelistSyncStatus()
|
||||
lastPricelistSyncError := h.localDB.GetLastPricelistSyncError()
|
||||
hasFailedSync := strings.EqualFold(lastPricelistSyncStatus, "failed")
|
||||
needComponentSync := h.localDB.NeedComponentSync(24)
|
||||
readiness := h.getReadinessLocal()
|
||||
|
||||
c.JSON(http.StatusOK, SyncStatusResponse{
|
||||
LastComponentSync: lastComponentSync,
|
||||
LastPricelistSync: lastPricelistSync,
|
||||
LastPricelistAttemptAt: lastPricelistAttemptAt,
|
||||
LastPricelistSyncStatus: lastPricelistSyncStatus,
|
||||
@@ -103,7 +98,6 @@ func (h *SyncHandler) GetStatus(c *gin.Context) {
|
||||
ComponentsCount: componentsCount,
|
||||
PricelistsCount: pricelistsCount,
|
||||
ServerPricelists: 0,
|
||||
NeedComponentSync: needComponentSync,
|
||||
NeedPricelistSync: lastPricelistSync == nil || hasFailedSync,
|
||||
Readiness: readiness,
|
||||
})
|
||||
@@ -169,52 +163,6 @@ type SyncResultResponse struct {
|
||||
Duration string `json:"duration"`
|
||||
}
|
||||
|
||||
// SyncComponents syncs components from MariaDB to local SQLite
|
||||
// POST /api/sync/components
|
||||
func (h *SyncHandler) SyncComponents(c *gin.Context) {
|
||||
if !h.ensureSyncReadiness(c) {
|
||||
return
|
||||
}
|
||||
|
||||
// Get database connection from ConnectionManager
|
||||
mariaDB, err := h.connMgr.GetDB()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{
|
||||
"success": false,
|
||||
"error": "database connection failed",
|
||||
})
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
result, err := h.localDB.SyncComponents(mariaDB)
|
||||
if err != nil {
|
||||
_ = h.localDB.SetComponentSyncResult("error", err.Error(), now)
|
||||
h.localDB.AppendSyncLog("components", "error", err.Error(), 0, now, time.Since(now).Milliseconds())
|
||||
slog.Error("component sync failed", "error", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"success": false,
|
||||
"error": "component sync failed",
|
||||
})
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
_ = h.localDB.SetComponentSyncResult("ok", "", now)
|
||||
h.localDB.AppendSyncLog("components", "ok", "", result.TotalSynced, now, result.Duration.Milliseconds())
|
||||
|
||||
if err := h.localDB.SyncQtSettings(mariaDB); err != nil {
|
||||
slog.Warn("qt_settings sync failed", "error", err)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, SyncResultResponse{
|
||||
Success: true,
|
||||
Message: "Components synced successfully",
|
||||
Synced: result.TotalSynced,
|
||||
Duration: result.Duration.String(),
|
||||
})
|
||||
}
|
||||
|
||||
// SyncPricelists syncs pricelists from MariaDB to local SQLite
|
||||
// POST /api/sync/pricelists
|
||||
func (h *SyncHandler) SyncPricelists(c *gin.Context) {
|
||||
@@ -280,7 +228,6 @@ type SyncAllResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message"`
|
||||
PendingPushed int `json:"pending_pushed"`
|
||||
ComponentsSynced int `json:"components_synced"`
|
||||
PricelistsSynced int `json:"pricelists_synced"`
|
||||
ProjectsImported int `json:"projects_imported"`
|
||||
ProjectsUpdated int `json:"projects_updated"`
|
||||
@@ -301,7 +248,7 @@ func (h *SyncHandler) SyncAll(c *gin.Context) {
|
||||
}
|
||||
|
||||
startTime := time.Now()
|
||||
var pendingPushed, componentsSynced, pricelistsSynced int
|
||||
var pricelistsSynced int
|
||||
|
||||
// Push local pending changes first (projects/configurations)
|
||||
pendingPushed, err := h.syncService.PushPendingChanges()
|
||||
@@ -315,38 +262,6 @@ func (h *SyncHandler) SyncAll(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Sync components
|
||||
mariaDB, err := h.connMgr.GetDB()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{
|
||||
"success": false,
|
||||
"error": "database connection failed",
|
||||
})
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
compNow := time.Now()
|
||||
compResult, err := h.localDB.SyncComponents(mariaDB)
|
||||
if err != nil {
|
||||
_ = h.localDB.SetComponentSyncResult("error", err.Error(), compNow)
|
||||
h.localDB.AppendSyncLog("components", "error", err.Error(), 0, compNow, time.Since(compNow).Milliseconds())
|
||||
slog.Error("component sync failed during full sync", "error", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"success": false,
|
||||
"error": "component sync failed",
|
||||
})
|
||||
_ = c.Error(err)
|
||||
return
|
||||
}
|
||||
_ = h.localDB.SetComponentSyncResult("ok", "", compNow)
|
||||
h.localDB.AppendSyncLog("components", "ok", "", compResult.TotalSynced, compNow, compResult.Duration.Milliseconds())
|
||||
componentsSynced = compResult.TotalSynced
|
||||
|
||||
if err := h.localDB.SyncQtSettings(mariaDB); err != nil {
|
||||
slog.Warn("qt_settings sync failed", "error", err)
|
||||
}
|
||||
|
||||
// Sync pricelists
|
||||
plNow := time.Now()
|
||||
pricelistsSynced, err = h.syncService.SyncPricelists()
|
||||
@@ -354,10 +269,9 @@ func (h *SyncHandler) SyncAll(c *gin.Context) {
|
||||
h.localDB.AppendSyncLog("pricelists", "error", err.Error(), 0, plNow, time.Since(plNow).Milliseconds())
|
||||
slog.Error("pricelist sync failed during full sync", "error", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"success": false,
|
||||
"error": "pricelist sync failed",
|
||||
"pending_pushed": pendingPushed,
|
||||
"components_synced": componentsSynced,
|
||||
"success": false,
|
||||
"error": "pricelist sync failed",
|
||||
"pending_pushed": pendingPushed,
|
||||
})
|
||||
_ = c.Error(err)
|
||||
return
|
||||
@@ -375,7 +289,6 @@ func (h *SyncHandler) SyncAll(c *gin.Context) {
|
||||
"success": false,
|
||||
"error": "project import failed",
|
||||
"pending_pushed": pendingPushed,
|
||||
"components_synced": componentsSynced,
|
||||
"pricelists_synced": pricelistsSynced,
|
||||
})
|
||||
_ = c.Error(err)
|
||||
@@ -389,7 +302,6 @@ func (h *SyncHandler) SyncAll(c *gin.Context) {
|
||||
"success": false,
|
||||
"error": "configuration import failed",
|
||||
"pending_pushed": pendingPushed,
|
||||
"components_synced": componentsSynced,
|
||||
"pricelists_synced": pricelistsSynced,
|
||||
"projects_imported": projectsResult.Imported,
|
||||
"projects_updated": projectsResult.Updated,
|
||||
@@ -403,7 +315,6 @@ func (h *SyncHandler) SyncAll(c *gin.Context) {
|
||||
Success: true,
|
||||
Message: "Full sync completed successfully",
|
||||
PendingPushed: pendingPushed,
|
||||
ComponentsSynced: componentsSynced,
|
||||
PricelistsSynced: pricelistsSynced,
|
||||
ProjectsImported: projectsResult.Imported,
|
||||
ProjectsUpdated: projectsResult.Updated,
|
||||
@@ -564,7 +475,7 @@ func (h *SyncHandler) GetInfo(c *gin.Context) {
|
||||
// Get local counts
|
||||
configCount := h.localDB.CountConfigurations()
|
||||
projectCount := h.localDB.CountProjects()
|
||||
componentCount := h.localDB.CountLocalComponents()
|
||||
componentCount := h.localDB.CountComponents()
|
||||
pricelistCount := h.localDB.CountLocalPricelists()
|
||||
|
||||
// Get error count (only changes with LastError != "")
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/repository"
|
||||
@@ -100,7 +99,7 @@ func (h *VendorSpecHandler) PutVendorSpec(c *gin.Context) {
|
||||
body.VendorSpec[i].SortOrder = (i + 1) * 10
|
||||
}
|
||||
// Persist canonical LOT mapping only.
|
||||
body.VendorSpec[i].LotMappings = normalizeLotMappings(body.VendorSpec[i].LotMappings)
|
||||
body.VendorSpec[i].LotMappings = localdb.NormalizeLotMappings(body.VendorSpec[i].LotMappings)
|
||||
body.VendorSpec[i].ResolvedLotName = ""
|
||||
body.VendorSpec[i].ResolutionSource = ""
|
||||
body.VendorSpec[i].ManualLotSuggestion = ""
|
||||
@@ -165,39 +164,6 @@ func (h *VendorSpecHandler) pushLotSuggestions(spec []localdb.VendorSpecItem) {
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeLotMappings(in []localdb.VendorSpecLotMapping) []localdb.VendorSpecLotMapping {
|
||||
if len(in) == 0 {
|
||||
return nil
|
||||
}
|
||||
merged := make(map[string]int, len(in))
|
||||
order := make([]string, 0, len(in))
|
||||
for _, m := range in {
|
||||
lot := strings.TrimSpace(m.LotName)
|
||||
if lot == "" {
|
||||
continue
|
||||
}
|
||||
qty := m.QuantityPerPN
|
||||
if qty < 1 {
|
||||
qty = 1
|
||||
}
|
||||
if _, exists := merged[lot]; !exists {
|
||||
order = append(order, lot)
|
||||
}
|
||||
merged[lot] += qty
|
||||
}
|
||||
out := make([]localdb.VendorSpecLotMapping, 0, len(order))
|
||||
for _, lot := range order {
|
||||
out = append(out, localdb.VendorSpecLotMapping{
|
||||
LotName: lot,
|
||||
QuantityPerPN: merged[lot],
|
||||
})
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ResolveVendorSpec resolves vendor PN → LOT without modifying the cart.
|
||||
// POST /api/configs/:uuid/vendor-spec/resolve
|
||||
func (h *VendorSpecHandler) ResolveVendorSpec(c *gin.Context) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
+224
-308
@@ -2,7 +2,6 @@ package localdb
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -24,344 +23,261 @@ type ComponentSyncResult struct {
|
||||
Duration time.Duration
|
||||
}
|
||||
|
||||
// SyncComponents loads components from MariaDB (lot + qt_lot_metadata) into local_components
|
||||
func (l *LocalDB) SyncComponents(mariaDB *gorm.DB) (*ComponentSyncResult, error) {
|
||||
startTime := time.Now()
|
||||
|
||||
// Build the component catalog from every runtime source of LOT names.
|
||||
// Storage lots may exist in qt_lot_metadata / qt_pricelist_items before they appear in lot,
|
||||
// so the sync cannot start from lot alone.
|
||||
type componentRow struct {
|
||||
LotName string
|
||||
LotDescription string
|
||||
Category *string
|
||||
Model *string
|
||||
}
|
||||
|
||||
var rows []componentRow
|
||||
err := mariaDB.Raw(`
|
||||
SELECT
|
||||
src.lot_name,
|
||||
COALESCE(MAX(NULLIF(TRIM(l.lot_description), '')), '') AS lot_description,
|
||||
COALESCE(
|
||||
MAX(NULLIF(TRIM(c.code), '')),
|
||||
MAX(NULLIF(TRIM(l.lot_category), '')),
|
||||
SUBSTRING_INDEX(src.lot_name, '_', 1)
|
||||
) AS category,
|
||||
MAX(NULLIF(TRIM(m.model), '')) AS model
|
||||
FROM (
|
||||
SELECT lot_name FROM lot
|
||||
UNION
|
||||
SELECT lot_name FROM qt_lot_metadata
|
||||
WHERE is_hidden = FALSE OR is_hidden IS NULL
|
||||
UNION
|
||||
SELECT lot_name FROM qt_pricelist_items
|
||||
) src
|
||||
LEFT JOIN lot l ON l.lot_name = src.lot_name
|
||||
LEFT JOIN qt_lot_metadata m
|
||||
ON m.lot_name = src.lot_name
|
||||
AND (m.is_hidden = FALSE OR m.is_hidden IS NULL)
|
||||
LEFT JOIN qt_categories c ON m.category_id = c.id
|
||||
GROUP BY src.lot_name
|
||||
ORDER BY src.lot_name
|
||||
`).Scan(&rows).Error
|
||||
// latestActivePricelistID returns the local DB id of the most recently created
|
||||
// active pricelist for the given source ("estimate", "warehouse", etc.).
|
||||
func (l *LocalDB) latestActivePricelistID(source string) (uint, error) {
|
||||
var id uint
|
||||
err := l.db.Table("local_pricelists").
|
||||
Select("id").
|
||||
Where("is_active = ? AND source = ?", true, source).
|
||||
Order("created_at DESC, id DESC").
|
||||
Limit(1).
|
||||
Scan(&id).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("querying components from MariaDB: %w", err)
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if len(rows) == 0 {
|
||||
slog.Warn("no components found in MariaDB")
|
||||
return &ComponentSyncResult{
|
||||
Duration: time.Since(startTime),
|
||||
}, nil
|
||||
if id == 0 {
|
||||
return 0, fmt.Errorf("no active %s pricelist", source)
|
||||
}
|
||||
|
||||
// Get existing local components for comparison
|
||||
existingMap := make(map[string]bool)
|
||||
var existing []LocalComponent
|
||||
if err := l.db.Find(&existing).Error; err != nil {
|
||||
return nil, fmt.Errorf("reading existing local components: %w", err)
|
||||
}
|
||||
for _, c := range existing {
|
||||
existingMap[c.LotName] = true
|
||||
}
|
||||
|
||||
// Prepare components for batch insert/update.
|
||||
// Source joins may duplicate the same lot_name, so collapse them before insert.
|
||||
syncTime := time.Now()
|
||||
components := make([]LocalComponent, 0, len(rows))
|
||||
componentIndex := make(map[string]int, len(rows))
|
||||
newCount := 0
|
||||
|
||||
for _, row := range rows {
|
||||
lotName := strings.TrimSpace(row.LotName)
|
||||
if lotName == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
category := ""
|
||||
if row.Category != nil {
|
||||
category = strings.TrimSpace(*row.Category)
|
||||
} else {
|
||||
// Parse category from lot_name (e.g., "CPU_AMD_9654" -> "CPU")
|
||||
parts := strings.SplitN(lotName, "_", 2)
|
||||
if len(parts) >= 1 {
|
||||
category = parts[0]
|
||||
}
|
||||
}
|
||||
|
||||
model := ""
|
||||
if row.Model != nil {
|
||||
model = strings.TrimSpace(*row.Model)
|
||||
}
|
||||
|
||||
comp := LocalComponent{
|
||||
LotName: lotName,
|
||||
LotDescription: strings.TrimSpace(row.LotDescription),
|
||||
Category: category,
|
||||
Model: model,
|
||||
}
|
||||
|
||||
if idx, exists := componentIndex[lotName]; exists {
|
||||
// Keep the first row, but fill any missing metadata from duplicates.
|
||||
if components[idx].LotDescription == "" && comp.LotDescription != "" {
|
||||
components[idx].LotDescription = comp.LotDescription
|
||||
}
|
||||
if components[idx].Category == "" && comp.Category != "" {
|
||||
components[idx].Category = comp.Category
|
||||
}
|
||||
if components[idx].Model == "" && comp.Model != "" {
|
||||
components[idx].Model = comp.Model
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
componentIndex[lotName] = len(components)
|
||||
components = append(components, comp)
|
||||
|
||||
if !existingMap[lotName] {
|
||||
newCount++
|
||||
}
|
||||
}
|
||||
|
||||
// Use transaction for bulk upsert
|
||||
err = l.db.Transaction(func(tx *gorm.DB) error {
|
||||
// Delete all existing and insert new (simpler than upsert for SQLite)
|
||||
if err := tx.Where("1=1").Delete(&LocalComponent{}).Error; err != nil {
|
||||
return fmt.Errorf("clearing local components: %w", err)
|
||||
}
|
||||
|
||||
// Batch insert
|
||||
batchSize := 500
|
||||
for i := 0; i < len(components); i += batchSize {
|
||||
end := i + batchSize
|
||||
if end > len(components) {
|
||||
end = len(components)
|
||||
}
|
||||
if err := tx.CreateInBatches(components[i:end], batchSize).Error; err != nil {
|
||||
return fmt.Errorf("inserting components batch: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Update last sync time
|
||||
if err := l.SetComponentSyncTime(syncTime); err != nil {
|
||||
slog.Warn("failed to update component sync time", "error", err)
|
||||
}
|
||||
|
||||
result := &ComponentSyncResult{
|
||||
TotalSynced: len(components),
|
||||
NewCount: newCount,
|
||||
UpdateCount: len(components) - newCount,
|
||||
Duration: time.Since(startTime),
|
||||
}
|
||||
|
||||
slog.Info("components synced",
|
||||
"total", result.TotalSynced,
|
||||
"new", result.NewCount,
|
||||
"updated", result.UpdateCount,
|
||||
"duration", result.Duration)
|
||||
|
||||
return result, nil
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// SearchLocalComponents searches components in local cache by query string
|
||||
// Searches in lot_name, lot_description, category, and model fields
|
||||
// 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"`
|
||||
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,
|
||||
LotDescription: r.Description,
|
||||
PriceQuality: r.PriceQuality,
|
||||
}
|
||||
}
|
||||
|
||||
// SearchLocalComponents searches the component universe by lot_name.
|
||||
func (l *LocalDB) SearchLocalComponents(query string, limit int) ([]LocalComponent, error) {
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
|
||||
var components []LocalComponent
|
||||
|
||||
if query == "" {
|
||||
// Return all components with limit
|
||||
err := l.db.Order("lot_name").Limit(limit).Find(&components).Error
|
||||
return components, err
|
||||
}
|
||||
|
||||
// Search with LIKE on multiple fields
|
||||
searchPattern := "%" + strings.ToLower(query) + "%"
|
||||
|
||||
err := l.db.Where(
|
||||
"LOWER(lot_name) LIKE ? OR LOWER(lot_description) LIKE ? OR LOWER(category) LIKE ? OR LOWER(model) LIKE ?",
|
||||
searchPattern, searchPattern, searchPattern, searchPattern,
|
||||
).Order("lot_name").Limit(limit).Find(&components).Error
|
||||
|
||||
return components, err
|
||||
}
|
||||
|
||||
// SearchLocalComponentsByCategory searches components by category and optional query
|
||||
func (l *LocalDB) SearchLocalComponentsByCategory(category string, query string, limit int) ([]LocalComponent, error) {
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
|
||||
var components []LocalComponent
|
||||
db := l.db.Where("LOWER(category) = ?", strings.ToLower(category))
|
||||
|
||||
if query != "" {
|
||||
searchPattern := "%" + strings.ToLower(query) + "%"
|
||||
db = db.Where(
|
||||
"LOWER(lot_name) LIKE ? OR LOWER(lot_description) LIKE ? OR LOWER(model) LIKE ?",
|
||||
searchPattern, searchPattern, searchPattern,
|
||||
)
|
||||
}
|
||||
|
||||
err := db.Order("lot_name").Limit(limit).Find(&components).Error
|
||||
return components, err
|
||||
}
|
||||
|
||||
// ListComponents returns components with filtering and pagination
|
||||
func (l *LocalDB) ListComponents(filter ComponentFilter, offset, limit int) ([]LocalComponent, int64, error) {
|
||||
db := l.db
|
||||
|
||||
// Apply category filter
|
||||
if filter.Category != "" {
|
||||
db = db.Where("LOWER(category) = ?", strings.ToLower(filter.Category))
|
||||
}
|
||||
|
||||
// Apply search filter
|
||||
if filter.Search != "" {
|
||||
searchPattern := "%" + strings.ToLower(filter.Search) + "%"
|
||||
db = db.Where(
|
||||
"LOWER(lot_name) LIKE ? OR LOWER(lot_description) LIKE ? OR LOWER(category) LIKE ? OR LOWER(model) LIKE ?",
|
||||
searchPattern, searchPattern, searchPattern, searchPattern,
|
||||
)
|
||||
}
|
||||
|
||||
// Get total count
|
||||
var total int64
|
||||
if err := db.Model(&LocalComponent{}).Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Apply pagination and get results
|
||||
var components []LocalComponent
|
||||
if err := db.Order("lot_name").Offset(offset).Limit(limit).Find(&components).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return components, total, nil
|
||||
}
|
||||
|
||||
// GetLocalComponent returns a single component by lot_name
|
||||
func (l *LocalDB) GetLocalComponent(lotName string) (*LocalComponent, error) {
|
||||
var component LocalComponent
|
||||
err := l.db.Where("lot_name = ?", lotName).First(&component).Error
|
||||
db, err := l.componentUniverse()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &component, nil
|
||||
|
||||
if query != "" {
|
||||
db = db.Where("LOWER(lot_name) LIKE ?", "%"+strings.ToLower(query)+"%")
|
||||
}
|
||||
|
||||
var rows []pricelistItemRow
|
||||
if err := db.Select("lot_name, lot_category, lot_description, price_quality").
|
||||
Order("lot_name").Limit(limit).Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
components := make([]LocalComponent, len(rows))
|
||||
for i, r := range rows {
|
||||
components[i] = r.toLocalComponent()
|
||||
}
|
||||
return components, nil
|
||||
}
|
||||
|
||||
// GetLocalComponentCategoriesByLotNames returns category for each lot_name in the local component cache.
|
||||
// Missing lots are not included in the map; caller is responsible for strict validation.
|
||||
// SearchLocalComponentsByCategory searches the component universe filtered by category.
|
||||
func (l *LocalDB) SearchLocalComponentsByCategory(category, query string, limit int) ([]LocalComponent, error) {
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
db, err := l.componentUniverse()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
db = db.Where("UPPER(lot_category) = ?", strings.ToUpper(category))
|
||||
if query != "" {
|
||||
db = db.Where("LOWER(lot_name) LIKE ?", "%"+strings.ToLower(query)+"%")
|
||||
}
|
||||
|
||||
var rows []pricelistItemRow
|
||||
if err := db.Select("lot_name, lot_category, lot_description, price_quality").
|
||||
Order("lot_name").Limit(limit).Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
components := make([]LocalComponent, len(rows))
|
||||
for i, r := range rows {
|
||||
components[i] = r.toLocalComponent()
|
||||
}
|
||||
return components, nil
|
||||
}
|
||||
|
||||
// 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) {
|
||||
db, err := l.componentUniverse()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if filter.Category != "" {
|
||||
db = db.Where("UPPER(lot_category) = ?", strings.ToUpper(filter.Category))
|
||||
}
|
||||
if filter.Search != "" {
|
||||
db = db.Where("LOWER(lot_name) LIKE ?", "%"+strings.ToLower(filter.Search)+"%")
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
var rows []pricelistItemRow
|
||||
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))
|
||||
for i, r := range rows {
|
||||
components[i] = r.toLocalComponent()
|
||||
}
|
||||
return components, total, nil
|
||||
}
|
||||
|
||||
// GetLocalComponent returns a single component by lot_name from the component universe.
|
||||
func (l *LocalDB) GetLocalComponent(lotName string) (*LocalComponent, error) {
|
||||
db, err := l.componentUniverse()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var row pricelistItemRow
|
||||
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
|
||||
}
|
||||
c := row.toLocalComponent()
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
// GetLocalComponentCategoriesByLotNames returns category for each lot_name
|
||||
// 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
|
||||
}
|
||||
|
||||
type row struct {
|
||||
LotName string `gorm:"column:lot_name"`
|
||||
Category string `gorm:"column:category"`
|
||||
db, err := l.componentUniverse()
|
||||
if err != nil {
|
||||
return result, nil
|
||||
}
|
||||
var rows []row
|
||||
if err := l.db.Model(&LocalComponent{}).
|
||||
Select("lot_name, category").
|
||||
Where("lot_name IN ?", lotNames).
|
||||
Find(&rows).Error; err != nil {
|
||||
|
||||
// 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 []pricelistItemRow
|
||||
if err := db.
|
||||
Select("lot_name, lot_category").
|
||||
Where("UPPER(lot_name) IN ?", upper).
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, r := range rows {
|
||||
result[r.LotName] = r.Category
|
||||
orig := upperToOrig[strings.ToUpper(r.LotName)]
|
||||
if orig == "" {
|
||||
orig = r.LotName
|
||||
}
|
||||
result[orig] = r.Category
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetLocalComponentCategories returns distinct categories from local components
|
||||
// GetLocalComponentCategories returns distinct categories from the component universe.
|
||||
func (l *LocalDB) GetLocalComponentCategories() ([]string, error) {
|
||||
var categories []string
|
||||
err := l.db.Model(&LocalComponent{}).
|
||||
Distinct("category").
|
||||
Where("category != ''").
|
||||
Order("category").
|
||||
Pluck("category", &categories).Error
|
||||
return categories, err
|
||||
}
|
||||
|
||||
// CountLocalComponents returns the total number of local components
|
||||
func (l *LocalDB) CountLocalComponents() int64 {
|
||||
var count int64
|
||||
l.db.Model(&LocalComponent{}).Count(&count)
|
||||
return count
|
||||
}
|
||||
|
||||
// CountLocalComponentsByCategory returns component count by category
|
||||
func (l *LocalDB) CountLocalComponentsByCategory(category string) int64 {
|
||||
var count int64
|
||||
l.db.Model(&LocalComponent{}).Where("LOWER(category) = ?", strings.ToLower(category)).Count(&count)
|
||||
return count
|
||||
}
|
||||
|
||||
// GetComponentSyncTime returns the last component sync timestamp
|
||||
func (l *LocalDB) GetComponentSyncTime() *time.Time {
|
||||
var setting struct {
|
||||
Value string
|
||||
}
|
||||
if err := l.db.Table("app_settings").
|
||||
Where("key = ?", "last_component_sync").
|
||||
First(&setting).Error; err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
t, err := time.Parse(time.RFC3339, setting.Value)
|
||||
db, err := l.componentUniverse()
|
||||
if err != nil {
|
||||
return nil
|
||||
return nil, err
|
||||
}
|
||||
return &t
|
||||
|
||||
var categories []string
|
||||
if err := db.
|
||||
Where("lot_category != ''").
|
||||
Distinct("lot_category").
|
||||
Order("lot_category").
|
||||
Pluck("lot_category", &categories).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return categories, nil
|
||||
}
|
||||
|
||||
// SetComponentSyncTime sets the last component sync timestamp
|
||||
func (l *LocalDB) SetComponentSyncTime(t time.Time) error {
|
||||
return l.db.Exec(`
|
||||
INSERT INTO app_settings (key, value, updated_at)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
|
||||
`, "last_component_sync", t.Format(time.RFC3339), time.Now().Format(time.RFC3339)).Error
|
||||
}
|
||||
|
||||
// NeedComponentSync checks if component sync is needed (older than specified hours)
|
||||
func (l *LocalDB) NeedComponentSync(maxAgeHours int) bool {
|
||||
syncTime := l.GetComponentSyncTime()
|
||||
if syncTime == nil {
|
||||
return true
|
||||
// CountComponents returns the number of lot names in the component universe
|
||||
// (used to check if data is available).
|
||||
func (l *LocalDB) CountComponents() int64 {
|
||||
db, err := l.componentUniverse()
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return time.Since(*syncTime).Hours() > float64(maxAgeHours)
|
||||
var count int64
|
||||
db.Count(&count)
|
||||
return count
|
||||
}
|
||||
@@ -6,12 +6,48 @@ import (
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
)
|
||||
|
||||
// NormalizeLotMappings is the single canonical normalizer for vendor BOM LOT
|
||||
// mappings. LOT names are canonicalized to their uppercase form (see
|
||||
// models.NormalizeLotName) so that all BOM↔cart matching is case-insensitive,
|
||||
// duplicate LOTs are merged (summing quantity-per-PN), and quantities are at
|
||||
// least 1. Returns nil for an empty result. Both the persistence path
|
||||
// (handlers) and the CSV export path must use this — do not reimplement it.
|
||||
func NormalizeLotMappings(in []VendorSpecLotMapping) []VendorSpecLotMapping {
|
||||
if len(in) == 0 {
|
||||
return nil
|
||||
}
|
||||
merged := make(map[string]int, len(in))
|
||||
order := make([]string, 0, len(in))
|
||||
for _, m := range in {
|
||||
lot := models.NormalizeLotName(m.LotName)
|
||||
if lot == "" {
|
||||
continue
|
||||
}
|
||||
qty := m.QuantityPerPN
|
||||
if qty < 1 {
|
||||
qty = 1
|
||||
}
|
||||
if _, exists := merged[lot]; !exists {
|
||||
order = append(order, lot)
|
||||
}
|
||||
merged[lot] += qty
|
||||
}
|
||||
if len(order) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]VendorSpecLotMapping, 0, len(order))
|
||||
for _, lot := range order {
|
||||
out = append(out, VendorSpecLotMapping{LotName: lot, QuantityPerPN: merged[lot]})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ConfigurationToLocal converts models.Configuration to LocalConfiguration
|
||||
func ConfigurationToLocal(cfg *models.Configuration) *LocalConfiguration {
|
||||
items := make(LocalConfigItems, len(cfg.Items))
|
||||
for i, item := range cfg.Items {
|
||||
items[i] = LocalConfigItem{
|
||||
LotName: item.LotName,
|
||||
LotName: models.NormalizeLotName(item.LotName),
|
||||
Quantity: item.Quantity,
|
||||
UnitPrice: item.UnitPrice,
|
||||
}
|
||||
@@ -38,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,
|
||||
@@ -87,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,
|
||||
@@ -195,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,
|
||||
@@ -205,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",
|
||||
@@ -226,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,
|
||||
}
|
||||
@@ -267,68 +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: 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,
|
||||
}
|
||||
}
|
||||
|
||||
// ComponentToLocal converts models.LotMetadata to LocalComponent
|
||||
func ComponentToLocal(meta *models.LotMetadata) *LocalComponent {
|
||||
var lotDesc string
|
||||
var category string
|
||||
|
||||
if meta.Lot != nil {
|
||||
lotDesc = meta.Lot.LotDescription
|
||||
}
|
||||
|
||||
// Extract category from lot_name (e.g., "CPU_AMD_9654" -> "CPU")
|
||||
if len(meta.LotName) > 0 {
|
||||
for i, ch := range meta.LotName {
|
||||
if ch == '_' {
|
||||
category = meta.LotName[:i]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &LocalComponent{
|
||||
LotName: meta.LotName,
|
||||
LotDescription: lotDesc,
|
||||
Category: category,
|
||||
Model: meta.Model,
|
||||
}
|
||||
}
|
||||
|
||||
// LocalToComponent converts LocalComponent to models.LotMetadata
|
||||
func LocalToComponent(local *LocalComponent) *models.LotMetadata {
|
||||
return &models.LotMetadata{
|
||||
LotName: local.LotName,
|
||||
Model: local.Model,
|
||||
Lot: &models.Lot{
|
||||
LotName: local.LotName,
|
||||
LotDescription: local.LotDescription,
|
||||
},
|
||||
ID: local.ID,
|
||||
PricelistID: serverPricelistID,
|
||||
LotName: local.LotName,
|
||||
LotCategory: local.LotCategory,
|
||||
LotDescription: local.LotDescription,
|
||||
Price: local.Price,
|
||||
PriceQuality: local.PriceQuality,
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,36 @@ import (
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
)
|
||||
|
||||
func TestNormalizeLotMappings_CaseInsensitiveMerge(t *testing.T) {
|
||||
in := []VendorSpecLotMapping{
|
||||
{LotName: "cpu_intel_6960p", QuantityPerPN: 1},
|
||||
{LotName: "CPU_INTEL_6960P", QuantityPerPN: 2},
|
||||
{LotName: " ps_5200w_Titanium ", QuantityPerPN: 0},
|
||||
{LotName: "", QuantityPerPN: 5},
|
||||
}
|
||||
|
||||
out := NormalizeLotMappings(in)
|
||||
|
||||
if len(out) != 2 {
|
||||
t.Fatalf("expected 2 merged mappings, got %d: %+v", len(out), out)
|
||||
}
|
||||
if out[0].LotName != "CPU_INTEL_6960P" || out[0].QuantityPerPN != 3 {
|
||||
t.Fatalf("expected CPU_INTEL_6960P qty 3, got %+v", out[0])
|
||||
}
|
||||
if out[1].LotName != "PS_5200W_TITANIUM" || out[1].QuantityPerPN != 1 {
|
||||
t.Fatalf("expected PS_5200W_TITANIUM qty 1 (clamped), got %+v", out[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeLotMappings_Empty(t *testing.T) {
|
||||
if NormalizeLotMappings(nil) != nil {
|
||||
t.Fatal("expected nil for empty input")
|
||||
}
|
||||
if NormalizeLotMappings([]VendorSpecLotMapping{{LotName: " "}}) != nil {
|
||||
t.Fatal("expected nil when all entries blank")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPricelistItemToLocal_PreservesLotCategory(t *testing.T) {
|
||||
item := &models.PricelistItem{
|
||||
LotName: "CPU_A",
|
||||
|
||||
+242
-74
@@ -46,7 +46,6 @@ type LocalDB struct {
|
||||
var localReadOnlyCacheTables = []string{
|
||||
"local_pricelist_items",
|
||||
"local_pricelists",
|
||||
"local_components",
|
||||
"local_partnumber_book_items",
|
||||
"local_partnumber_books",
|
||||
}
|
||||
@@ -78,7 +77,6 @@ func ResetData(dbPath string) error {
|
||||
"local_configuration_versions",
|
||||
"local_pricelists",
|
||||
"local_pricelist_items",
|
||||
"local_components",
|
||||
"local_sync_guard_state",
|
||||
"pending_changes",
|
||||
"app_settings",
|
||||
@@ -116,6 +114,13 @@ func New(dbPath string) (*LocalDB, error) {
|
||||
return nil, fmt.Errorf("opening sqlite database: %w", err)
|
||||
}
|
||||
|
||||
// SQLite requires a single writer connection to avoid SQLITE_BUSY under concurrent requests.
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get sql.DB from gorm: %w", err)
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
|
||||
// Enable WAL mode so background sync writes never block UI reads.
|
||||
if err := db.Exec("PRAGMA journal_mode=WAL").Error; err != nil {
|
||||
slog.Warn("failed to enable WAL mode", "error", err)
|
||||
@@ -123,6 +128,10 @@ func New(dbPath string) (*LocalDB, error) {
|
||||
if err := db.Exec("PRAGMA synchronous=NORMAL").Error; err != nil {
|
||||
slog.Warn("failed to set synchronous=NORMAL", "error", err)
|
||||
}
|
||||
// Wait up to 5 s before returning SQLITE_BUSY (guards against WAL checkpoints and external locks).
|
||||
if err := db.Exec("PRAGMA busy_timeout = 5000").Error; err != nil {
|
||||
slog.Warn("failed to set busy_timeout", "error", err)
|
||||
}
|
||||
|
||||
if err := ensureLocalProjectsTable(db); err != nil {
|
||||
return nil, fmt.Errorf("ensure local_projects table: %w", err)
|
||||
@@ -202,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,
|
||||
@@ -224,7 +234,6 @@ func autoMigrateLocalSchema(db *gorm.DB) error {
|
||||
&LocalConfigurationVersion{},
|
||||
&LocalPricelist{},
|
||||
&LocalPricelistItem{},
|
||||
&LocalComponent{},
|
||||
&AppSetting{},
|
||||
&LocalSyncGuardState{},
|
||||
&PendingChange{},
|
||||
@@ -692,6 +701,22 @@ func (l *LocalDB) GetProjectByUUID(uuid string) (*LocalProject, error) {
|
||||
return &project, nil
|
||||
}
|
||||
|
||||
func (l *LocalDB) GetProjectByCode(code string) (*LocalProject, error) {
|
||||
var project LocalProject
|
||||
if err := l.db.Where("LOWER(code) = LOWER(?) AND variant = ''", code).First(&project).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &project, nil
|
||||
}
|
||||
|
||||
func (l *LocalDB) GetProjectByCodeAndVariant(code, variant string) (*LocalProject, error) {
|
||||
var project LocalProject
|
||||
if err := l.db.Where("LOWER(code) = LOWER(?) AND LOWER(variant) = LOWER(?)", code, variant).First(&project).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &project, nil
|
||||
}
|
||||
|
||||
func (l *LocalDB) GetProjectByName(ownerUsername, name string) (*LocalProject, error) {
|
||||
var project LocalProject
|
||||
if err := l.db.Where("owner_username = ? AND name = ?", ownerUsername, name).First(&project).Error; err != nil {
|
||||
@@ -1221,24 +1246,66 @@ func (l *LocalDB) GetLastComponentSyncError() string {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
|
||||
func (l *LocalDB) SetComponentSyncResult(status, errorText string, attemptedAt time.Time) error {
|
||||
status = strings.TrimSpace(status)
|
||||
errorText = strings.TrimSpace(errorText)
|
||||
if status == "" {
|
||||
status = "unknown"
|
||||
}
|
||||
return l.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := l.upsertAppSetting(tx, "last_component_sync_status", status, attemptedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := l.upsertAppSetting(tx, "last_component_sync_error", errorText, attemptedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := l.upsertAppSetting(tx, "last_component_sync_attempt_at", attemptedAt.Format(time.RFC3339), attemptedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
const openConfigUUIDsKey = "open_config_uuids"
|
||||
|
||||
// GetOpenConfigUUIDs returns UUIDs of all configurations currently open in the configurator.
|
||||
func (l *LocalDB) GetOpenConfigUUIDs() []string {
|
||||
value, ok := l.getAppSettingValue(openConfigUUIDsKey)
|
||||
if !ok || value == "" {
|
||||
return nil
|
||||
})
|
||||
}
|
||||
var uuids []string
|
||||
if err := json.Unmarshal([]byte(value), &uuids); err != nil {
|
||||
return nil
|
||||
}
|
||||
return uuids
|
||||
}
|
||||
|
||||
// AddOpenConfigUUID records that a configuration is open in the configurator.
|
||||
func (l *LocalDB) AddOpenConfigUUID(uuid string) error {
|
||||
uuids := l.GetOpenConfigUUIDs()
|
||||
for _, u := range uuids {
|
||||
if u == uuid {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
uuids = append(uuids, uuid)
|
||||
raw, err := json.Marshal(uuids)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return l.db.Exec(`
|
||||
INSERT INTO app_settings (key, value, updated_at)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
|
||||
`, openConfigUUIDsKey, string(raw), time.Now().Format(time.RFC3339)).Error
|
||||
}
|
||||
|
||||
// RemoveOpenConfigUUID records that a configuration is no longer open in the configurator.
|
||||
func (l *LocalDB) RemoveOpenConfigUUID(uuid string) error {
|
||||
uuids := l.GetOpenConfigUUIDs()
|
||||
filtered := uuids[:0]
|
||||
for _, u := range uuids {
|
||||
if u != uuid {
|
||||
filtered = append(filtered, u)
|
||||
}
|
||||
}
|
||||
var raw []byte
|
||||
var err error
|
||||
if len(filtered) == 0 {
|
||||
raw = []byte("[]")
|
||||
} else {
|
||||
raw, err = json.Marshal(filtered)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return l.db.Exec(`
|
||||
INSERT INTO app_settings (key, value, updated_at)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
|
||||
`, openConfigUUIDsKey, string(raw), time.Now().Format(time.RFC3339)).Error
|
||||
}
|
||||
|
||||
// CountLocalPricelists returns the number of local pricelists
|
||||
@@ -1255,11 +1322,10 @@ func (l *LocalDB) CountAllPricelistItems() int64 {
|
||||
return count
|
||||
}
|
||||
|
||||
// CountComponents returns the number of rows in local_components.
|
||||
func (l *LocalDB) CountComponents() int64 {
|
||||
var count int64
|
||||
l.db.Model(&LocalComponent{}).Count(&count)
|
||||
return count
|
||||
|
||||
// DBFilePath returns the path to the SQLite database file.
|
||||
func (l *LocalDB) DBFilePath() string {
|
||||
return l.path
|
||||
}
|
||||
|
||||
// DBFileSizeBytes returns the size of the SQLite database file in bytes.
|
||||
@@ -1271,11 +1337,11 @@ func (l *LocalDB) DBFileSizeBytes() int64 {
|
||||
return info.Size()
|
||||
}
|
||||
|
||||
// GetLatestLocalPricelist returns the most recently synced pricelist
|
||||
// GetLatestLocalPricelist returns the most recently synced active estimate pricelist.
|
||||
func (l *LocalDB) GetLatestLocalPricelist() (*LocalPricelist, error) {
|
||||
var pricelist LocalPricelist
|
||||
if err := l.db.
|
||||
Where("source = ?", "estimate").
|
||||
Where("source = ? AND is_active = ?", "estimate", true).
|
||||
Where("EXISTS (SELECT 1 FROM local_pricelist_items WHERE local_pricelist_items.pricelist_id = local_pricelists.id)").
|
||||
Order("created_at DESC, id DESC").
|
||||
First(&pricelist).Error; err != nil {
|
||||
@@ -1284,11 +1350,20 @@ func (l *LocalDB) GetLatestLocalPricelist() (*LocalPricelist, error) {
|
||||
return &pricelist, nil
|
||||
}
|
||||
|
||||
// GetLatestLocalPricelistBySource returns the most recently synced pricelist for a source.
|
||||
// GetLatestLocalPricelistBySource returns the most recently synced active pricelist for a source.
|
||||
func (l *LocalDB) GetLatestLocalPricelistBySource(source string) (*LocalPricelist, error) {
|
||||
return GetLatestLocalPricelistBySourceTx(l.db, source)
|
||||
}
|
||||
|
||||
// GetLatestLocalPricelistBySourceTx is the transaction-scoped variant of
|
||||
// GetLatestLocalPricelistBySource. Callers already inside an l.db.Transaction(...) callback
|
||||
// must use this with the given tx instead of the method above — the connection pool has a
|
||||
// single connection (see New()), so querying via l.db while the transaction holds that
|
||||
// connection deadlocks forever.
|
||||
func GetLatestLocalPricelistBySourceTx(tx *gorm.DB, source string) (*LocalPricelist, error) {
|
||||
var pricelist LocalPricelist
|
||||
if err := l.db.
|
||||
Where("source = ?", source).
|
||||
if err := tx.
|
||||
Where("source = ? AND is_active = ?", source, true).
|
||||
Where("EXISTS (SELECT 1 FROM local_pricelist_items WHERE local_pricelist_items.pricelist_id = local_pricelists.id)").
|
||||
Order("created_at DESC, id DESC").
|
||||
First(&pricelist).Error; err != nil {
|
||||
@@ -1297,6 +1372,17 @@ func (l *LocalDB) GetLatestLocalPricelistBySource(source string) (*LocalPricelis
|
||||
return &pricelist, nil
|
||||
}
|
||||
|
||||
// DeactivateLocalPricelistsNotIn marks all local pricelists with is_active=true whose
|
||||
// server_id is not in activeServerIDs as inactive. Used after each pricelist sync to
|
||||
// mirror server-side deactivations locally.
|
||||
func (l *LocalDB) DeactivateLocalPricelistsNotIn(activeServerIDs []uint) error {
|
||||
q := l.db.Model(&LocalPricelist{}).Where("is_active = ?", true)
|
||||
if len(activeServerIDs) > 0 {
|
||||
q = q.Where("server_id NOT IN ?", activeServerIDs)
|
||||
}
|
||||
return q.Update("is_active", false).Error
|
||||
}
|
||||
|
||||
// GetLocalPricelistByServerID returns a local pricelist by its server ID
|
||||
func (l *LocalDB) GetLocalPricelistByServerID(serverID uint) (*LocalPricelist, error) {
|
||||
var pricelist LocalPricelist
|
||||
@@ -1364,6 +1450,30 @@ func (l *LocalDB) CountLocalPricelistItems(pricelistID uint) int64 {
|
||||
return count
|
||||
}
|
||||
|
||||
// GetLocalPricelistCoverageByCategory returns item count per lot_category and the total
|
||||
// for the given local pricelist ID. Only items with price > 0 are counted.
|
||||
func (l *LocalDB) GetLocalPricelistCoverageByCategory(pricelistID uint) (map[string]int64, int64, error) {
|
||||
type row struct {
|
||||
Category string `gorm:"column:lot_category"`
|
||||
Count int64 `gorm:"column:cnt"`
|
||||
}
|
||||
var rows []row
|
||||
if err := l.db.Model(&LocalPricelistItem{}).
|
||||
Select("COALESCE(NULLIF(TRIM(lot_category),''), '?') AS lot_category, COUNT(*) AS cnt").
|
||||
Where("pricelist_id = ? AND price > 0", pricelistID).
|
||||
Group("lot_category").
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
result := make(map[string]int64, len(rows))
|
||||
var total int64
|
||||
for _, r := range rows {
|
||||
result[r.Category] = r.Count
|
||||
total += r.Count
|
||||
}
|
||||
return result, total, nil
|
||||
}
|
||||
|
||||
// CountLocalPricelistItemsWithEmptyCategory returns the number of items for a pricelist with missing lot_category.
|
||||
func (l *LocalDB) CountLocalPricelistItemsWithEmptyCategory(pricelistID uint) (int64, error) {
|
||||
var count int64
|
||||
@@ -1428,10 +1538,11 @@ func (l *LocalDB) GetLocalPricelistItems(pricelistID uint) ([]LocalPricelistItem
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// GetLocalPriceForLot returns the price for a lot from a local pricelist
|
||||
// GetLocalPriceForLot returns the price for a lot from a local pricelist.
|
||||
// Matching is case-insensitive via UPPER(lot_name) to handle legacy mixed-case rows.
|
||||
func (l *LocalDB) GetLocalPriceForLot(pricelistID uint, lotName string) (float64, error) {
|
||||
var item LocalPricelistItem
|
||||
if err := l.db.Where("pricelist_id = ? AND lot_name = ?", pricelistID, lotName).
|
||||
if err := l.db.Where("pricelist_id = ? AND UPPER(lot_name) = ?", pricelistID, strings.ToUpper(lotName)).
|
||||
First(&item).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -1439,26 +1550,39 @@ func (l *LocalDB) GetLocalPriceForLot(pricelistID uint, lotName string) (float64
|
||||
}
|
||||
|
||||
// GetLocalPricesForLots returns prices for multiple lots from a local pricelist in a single query.
|
||||
// Uses the composite index (pricelist_id, lot_name). Missing lots are omitted from the result.
|
||||
// Missing lots are omitted from the result.
|
||||
// lotNames must already be normalized (uppercased); matching is done via UPPER(lot_name) to handle
|
||||
// legacy rows that were stored in mixed case before normalization was enforced at sync time.
|
||||
// Keys in the returned map are uppercased (matching the input lotNames).
|
||||
func (l *LocalDB) GetLocalPricesForLots(pricelistID uint, lotNames []string) (map[string]float64, error) {
|
||||
return GetLocalPricesForLotsTx(l.db, pricelistID, lotNames)
|
||||
}
|
||||
|
||||
// GetLocalPricesForLotsTx is the transaction-scoped variant of GetLocalPricesForLots. See
|
||||
// GetLatestLocalPricelistBySourceTx for why callers inside an l.db.Transaction(...) callback
|
||||
// must use this with the given tx instead of the method above.
|
||||
func GetLocalPricesForLotsTx(tx *gorm.DB, pricelistID uint, lotNames []string) (map[string]float64, error) {
|
||||
result := make(map[string]float64, len(lotNames))
|
||||
if len(lotNames) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type row struct {
|
||||
LotName string `gorm:"column:lot_name"`
|
||||
Price float64 `gorm:"column:price"`
|
||||
}
|
||||
var rows []row
|
||||
if err := l.db.Model(&LocalPricelistItem{}).
|
||||
// Use UPPER(lot_name) so rows synced before normalization (mixed-case) are still matched.
|
||||
if err := tx.Model(&LocalPricelistItem{}).
|
||||
Select("lot_name, price").
|
||||
Where("pricelist_id = ? AND lot_name IN ?", pricelistID, lotNames).
|
||||
Where("pricelist_id = ? AND UPPER(lot_name) IN ?", pricelistID, lotNames).
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, r := range rows {
|
||||
if r.Price > 0 {
|
||||
result[r.LotName] = r.Price
|
||||
// Key must be uppercase to match callers that normalise lot names before lookup.
|
||||
result[strings.ToUpper(r.LotName)] = r.Price
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
@@ -1481,15 +1605,72 @@ func (l *LocalDB) GetLocalLotCategoriesByServerPricelistID(serverPricelistID uin
|
||||
LotName string `gorm:"column:lot_name"`
|
||||
LotCategory string `gorm:"column:lot_category"`
|
||||
}
|
||||
// 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_category").
|
||||
Where("pricelist_id = ? AND lot_name IN ?", localPL.ID, lotNames).
|
||||
Where("pricelist_id = ? AND UPPER(lot_name) IN ?", localPL.ID, upper).
|
||||
Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, r := range rows {
|
||||
result[r.LotName] = r.LotCategory
|
||||
orig := upperToOrig[strings.ToUpper(r.LotName)]
|
||||
if orig == "" {
|
||||
orig = r.LotName
|
||||
}
|
||||
result[orig] = r.LotCategory
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -1673,12 +1854,13 @@ func (l *LocalDB) RepairPendingChanges() (int, []string, error) {
|
||||
var remainingErrors []string
|
||||
|
||||
for _, change := range erroredChanges {
|
||||
var modified bool
|
||||
var repairErr error
|
||||
switch change.EntityType {
|
||||
case "project":
|
||||
repairErr = l.repairProjectChange(&change)
|
||||
modified, repairErr = l.repairProjectChange(&change)
|
||||
case "configuration":
|
||||
repairErr = l.repairConfigurationChange(&change)
|
||||
modified, repairErr = l.repairConfigurationChange(&change)
|
||||
default:
|
||||
repairErr = fmt.Errorf("unknown entity type: %s", change.EntityType)
|
||||
}
|
||||
@@ -1689,7 +1871,13 @@ func (l *LocalDB) RepairPendingChanges() (int, []string, error) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Clear error and reset attempts
|
||||
// Only reset attempts when the repair actually changed local data.
|
||||
// If nothing was modified, the error is server-side; leaving attempts
|
||||
// intact lets maxPendingChangeAttempts eventually abandon the change.
|
||||
if !modified {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := l.db.Model(&PendingChange{}).Where("id = ?", change.ID).Updates(map[string]interface{}{
|
||||
"last_error": "",
|
||||
"attempts": 0,
|
||||
@@ -1705,12 +1893,13 @@ func (l *LocalDB) RepairPendingChanges() (int, []string, error) {
|
||||
}
|
||||
|
||||
// repairProjectChange validates and fixes project data.
|
||||
// Returns (modified, err): modified=true only when local data was actually changed.
|
||||
// Note: This only validates local data. Server-side conflicts (like duplicate code+variant)
|
||||
// are handled by sync service layer with deduplication logic.
|
||||
func (l *LocalDB) repairProjectChange(change *PendingChange) error {
|
||||
func (l *LocalDB) repairProjectChange(change *PendingChange) (bool, error) {
|
||||
project, err := l.GetProjectByUUID(change.EntityUUID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("project not found locally: %w", err)
|
||||
return false, fmt.Errorf("project not found locally: %w", err)
|
||||
}
|
||||
|
||||
modified := false
|
||||
@@ -1736,7 +1925,7 @@ func (l *LocalDB) repairProjectChange(change *PendingChange) error {
|
||||
if strings.TrimSpace(project.OwnerUsername) == "" {
|
||||
project.OwnerUsername = l.GetDBUser()
|
||||
if project.OwnerUsername == "" {
|
||||
return fmt.Errorf("cannot determine owner username")
|
||||
return false, fmt.Errorf("cannot determine owner username")
|
||||
}
|
||||
modified = true
|
||||
}
|
||||
@@ -1757,18 +1946,19 @@ func (l *LocalDB) repairProjectChange(change *PendingChange) error {
|
||||
|
||||
if modified {
|
||||
if err := l.SaveProject(project); err != nil {
|
||||
return fmt.Errorf("saving repaired project: %w", err)
|
||||
return false, fmt.Errorf("saving repaired project: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
return modified, nil
|
||||
}
|
||||
|
||||
// repairConfigurationChange validates and fixes configuration data
|
||||
func (l *LocalDB) repairConfigurationChange(change *PendingChange) error {
|
||||
// repairConfigurationChange validates and fixes configuration data.
|
||||
// Returns (modified, err): modified=true only when local data was actually changed.
|
||||
func (l *LocalDB) repairConfigurationChange(change *PendingChange) (bool, error) {
|
||||
config, err := l.GetConfigurationByUUID(change.EntityUUID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("configuration not found locally: %w", err)
|
||||
return false, fmt.Errorf("configuration not found locally: %w", err)
|
||||
}
|
||||
|
||||
modified := false
|
||||
@@ -1780,7 +1970,7 @@ func (l *LocalDB) repairConfigurationChange(change *PendingChange) error {
|
||||
// Project doesn't exist locally - use default system project
|
||||
systemProject, sysErr := l.EnsureDefaultProject(config.OriginalUsername)
|
||||
if sysErr != nil {
|
||||
return fmt.Errorf("getting system project: %w", sysErr)
|
||||
return false, fmt.Errorf("getting system project: %w", sysErr)
|
||||
}
|
||||
config.ProjectUUID = &systemProject.UUID
|
||||
modified = true
|
||||
@@ -1789,11 +1979,11 @@ func (l *LocalDB) repairConfigurationChange(change *PendingChange) error {
|
||||
|
||||
if modified {
|
||||
if err := l.SaveConfiguration(config); err != nil {
|
||||
return fmt.Errorf("saving repaired configuration: %w", err)
|
||||
return false, fmt.Errorf("saving repaired configuration: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
return modified, nil
|
||||
}
|
||||
|
||||
// GetSyncGuardState returns the latest readiness guard state.
|
||||
@@ -1855,28 +2045,6 @@ func (l *LocalDB) GetLocalPricelistItemsPage(pricelistID uint, search string, pa
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
// GetLocalComponentDescriptionsByLotNames returns a map of lot_name → lot_description for the given lots.
|
||||
func (l *LocalDB) GetLocalComponentDescriptionsByLotNames(lotNames []string) (map[string]string, error) {
|
||||
if len(lotNames) == 0 {
|
||||
return map[string]string{}, nil
|
||||
}
|
||||
type row struct {
|
||||
LotName string
|
||||
LotDescription string
|
||||
}
|
||||
var rows []row
|
||||
if err := l.db.Table("local_components").
|
||||
Select("lot_name, lot_description").
|
||||
Where("lot_name IN ?", lotNames).
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, fmt.Errorf("fetch component descriptions: %w", err)
|
||||
}
|
||||
m := make(map[string]string, len(rows))
|
||||
for _, r := range rows {
|
||||
m[r.LotName] = r.LotDescription
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// GetSchemaMigrations returns all applied local schema migrations ordered by applied_at.
|
||||
func (l *LocalDB) GetSchemaMigrations() ([]LocalSchemaMigration, error) {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+61
-12
@@ -5,6 +5,8 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
)
|
||||
|
||||
// AppSetting stores application settings in local SQLite
|
||||
@@ -46,7 +48,13 @@ func (c *LocalConfigItems) Scan(value interface{}) error {
|
||||
default:
|
||||
return errors.New("type assertion failed for LocalConfigItems")
|
||||
}
|
||||
return json.Unmarshal(bytes, c)
|
||||
if err := json.Unmarshal(bytes, c); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range *c {
|
||||
(*c)[i].LotName = models.NormalizeLotName((*c)[i].LotName)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c LocalConfigItems) Total() float64 {
|
||||
@@ -104,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"`
|
||||
@@ -133,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"`
|
||||
@@ -169,7 +180,8 @@ 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
|
||||
}
|
||||
|
||||
func (LocalPricelist) TableName() string {
|
||||
@@ -178,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 {
|
||||
@@ -198,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 {
|
||||
@@ -289,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"`
|
||||
@@ -320,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,36 +31,51 @@ 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
|
||||
// local_qt_settings cache in a single SQLite transaction. Returns an error if
|
||||
// the qt_settings table doesn't exist on the server (old server without the
|
||||
// table) or on any query/write failure.
|
||||
// local_qt_settings cache in a single SQLite transaction.
|
||||
// If the read fails (no connection, table missing on old server) or the server
|
||||
// returns an empty table, the existing local_qt_settings are preserved so the
|
||||
// configurator keeps working offline or against old server versions.
|
||||
func (l *LocalDB) SyncQtSettings(mariaDB *gorm.DB) error {
|
||||
var rows []LocalQtSetting
|
||||
if err := mariaDB.
|
||||
Table("qt_settings").
|
||||
Select("name, value").
|
||||
Find(&rows).Error; err != nil {
|
||||
slog.Warn("qt_settings: read from MariaDB failed, keeping existing local cache", "error", err)
|
||||
return fmt.Errorf("reading qt_settings from MariaDB: %w", err)
|
||||
}
|
||||
|
||||
if len(rows) == 0 {
|
||||
slog.Warn("qt_settings: server returned empty table, keeping existing local cache")
|
||||
return nil
|
||||
}
|
||||
|
||||
return l.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Exec("DELETE FROM local_qt_settings").Error; err != nil {
|
||||
return fmt.Errorf("clearing local_qt_settings: %w", err)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := tx.Create(&rows).Error; err != nil {
|
||||
return fmt.Errorf("inserting local_qt_settings: %w", err)
|
||||
}
|
||||
@@ -89,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 {
|
||||
@@ -115,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"`
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
package models
|
||||
|
||||
// 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"`
|
||||
}
|
||||
import "strings"
|
||||
|
||||
func (Lot) TableName() string {
|
||||
return "lot"
|
||||
// NormalizeLotName returns the canonical form of a lot name: trimmed and uppercased.
|
||||
// Apply at every point where a lot name enters the system (sync, API input, config load).
|
||||
func NormalizeLotName(s string) string {
|
||||
return strings.ToUpper(strings.TrimSpace(s))
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
type PriceMethod string
|
||||
|
||||
const (
|
||||
PriceMethodManual PriceMethod = "manual"
|
||||
PriceMethodMedian PriceMethod = "median"
|
||||
PriceMethodAverage PriceMethod = "average"
|
||||
PriceMethodWeightedMedian PriceMethod = "weighted_median"
|
||||
)
|
||||
|
||||
type Specs map[string]interface{}
|
||||
|
||||
func (s Specs) Value() (driver.Value, error) {
|
||||
return json.Marshal(s)
|
||||
}
|
||||
|
||||
func (s *Specs) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
*s = make(Specs)
|
||||
return nil
|
||||
}
|
||||
bytes, ok := value.([]byte)
|
||||
if !ok {
|
||||
return errors.New("type assertion to []byte failed")
|
||||
}
|
||||
return json.Unmarshal(bytes, s)
|
||||
}
|
||||
|
||||
type LotMetadata struct {
|
||||
LotName string `gorm:"column:lot_name;primaryKey;size:255" json:"lot_name"`
|
||||
CategoryID *uint `gorm:"column:category_id" json:"category_id"`
|
||||
Model string `gorm:"size:100" json:"model"`
|
||||
Specs Specs `gorm:"type:json" json:"specs"`
|
||||
CurrentPrice *float64 `gorm:"type:decimal(12,2)" json:"current_price"`
|
||||
PriceMethod PriceMethod `gorm:"type:enum('manual','median','average','weighted_median');default:'median'" json:"price_method"`
|
||||
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"`
|
||||
PriceUpdatedAt *time.Time `json:"price_updated_at"`
|
||||
RequestCount int `gorm:"default:0" json:"request_count"`
|
||||
LastRequestDate *time.Time `gorm:"type:date" json:"last_request_date"`
|
||||
PopularityScore float64 `gorm:"type:decimal(10,4);default:0" json:"popularity_score"`
|
||||
MetaPrices string `gorm:"size:1000" json:"meta_prices"`
|
||||
MetaMethod string `gorm:"size:20" json:"meta_method"`
|
||||
MetaPeriodDays int `gorm:"default:90" json:"meta_period_days"`
|
||||
IsHidden bool `gorm:"default:false" json:"is_hidden"`
|
||||
|
||||
// Relations
|
||||
Lot *Lot `gorm:"foreignKey:LotName;references:LotName" json:"lot,omitempty"`
|
||||
Category *Category `gorm:"foreignKey:CategoryID" json:"category,omitempty"`
|
||||
}
|
||||
|
||||
func (LotMetadata) TableName() string {
|
||||
return "qt_lot_metadata"
|
||||
}
|
||||
|
||||
type PriceFreshness string
|
||||
|
||||
const (
|
||||
FreshnessFresh PriceFreshness = "fresh"
|
||||
FreshnessNormal PriceFreshness = "normal"
|
||||
FreshnessStale PriceFreshness = "stale"
|
||||
FreshnessCritical PriceFreshness = "critical"
|
||||
)
|
||||
|
||||
func (m *LotMetadata) GetPriceFreshness(greenDays, yellowDays, redDays, minQuotes int) PriceFreshness {
|
||||
if m.CurrentPrice == nil || *m.CurrentPrice == 0 {
|
||||
return FreshnessCritical
|
||||
}
|
||||
if m.PriceUpdatedAt == nil {
|
||||
return FreshnessCritical
|
||||
}
|
||||
|
||||
daysSince := int(time.Since(*m.PriceUpdatedAt).Hours() / 24)
|
||||
|
||||
if daysSince < greenDays && m.RequestCount >= minQuotes {
|
||||
return FreshnessFresh
|
||||
} else if daysSince < yellowDays {
|
||||
return FreshnessNormal
|
||||
} else if daysSince < redDays {
|
||||
return FreshnessStale
|
||||
}
|
||||
return FreshnessCritical
|
||||
}
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
func AllModels() []interface{} {
|
||||
return []interface{}{
|
||||
&Category{},
|
||||
&LotMetadata{},
|
||||
&Project{},
|
||||
&Configuration{},
|
||||
&Pricelist{},
|
||||
|
||||
@@ -10,11 +10,12 @@ const (
|
||||
PricelistSourceEstimate PricelistSource = "estimate"
|
||||
PricelistSourceWarehouse PricelistSource = "warehouse"
|
||||
PricelistSourceCompetitor PricelistSource = "competitor"
|
||||
PricelistSourceWorld PricelistSource = "world"
|
||||
)
|
||||
|
||||
func (s PricelistSource) IsValid() bool {
|
||||
switch s {
|
||||
case PricelistSourceEstimate, PricelistSourceWarehouse, PricelistSourceCompetitor:
|
||||
case PricelistSourceEstimate, PricelistSourceWarehouse, PricelistSourceCompetitor, PricelistSourceWorld:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
@@ -27,6 +28,8 @@ func NormalizePricelistSource(source string) PricelistSource {
|
||||
return PricelistSourceWarehouse
|
||||
case PricelistSourceCompetitor:
|
||||
return PricelistSourceCompetitor
|
||||
case PricelistSourceWorld:
|
||||
return PricelistSourceWorld
|
||||
default:
|
||||
return PricelistSourceEstimate
|
||||
}
|
||||
@@ -52,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"`
|
||||
}
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type CategoryRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewCategoryRepository(db *gorm.DB) *CategoryRepository {
|
||||
return &CategoryRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *CategoryRepository) GetAll() ([]models.Category, error) {
|
||||
var categories []models.Category
|
||||
err := r.db.Order("display_order ASC").Find(&categories).Error
|
||||
return categories, err
|
||||
}
|
||||
|
||||
func (r *CategoryRepository) GetByCode(code string) (*models.Category, error) {
|
||||
var category models.Category
|
||||
err := r.db.Where("code = ?", code).First(&category).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &category, nil
|
||||
}
|
||||
|
||||
func (r *CategoryRepository) GetByID(id uint) (*models.Category, error) {
|
||||
var category models.Category
|
||||
err := r.db.First(&category, id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &category, nil
|
||||
}
|
||||
|
||||
// CreateIfNotExists creates a new category if it doesn't exist, returns existing one if it does
|
||||
func (r *CategoryRepository) CreateIfNotExists(code string) (*models.Category, error) {
|
||||
// Try to find existing
|
||||
existing, err := r.GetByCode(code)
|
||||
if err == nil {
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
// Get max display order to put new category at the end
|
||||
var maxOrder int
|
||||
r.db.Model(&models.Category{}).Select("COALESCE(MAX(display_order), 0)").Scan(&maxOrder)
|
||||
|
||||
// Create new category
|
||||
newCat := &models.Category{
|
||||
Code: code,
|
||||
Name: code, // Use code as name initially
|
||||
NameRu: code,
|
||||
DisplayOrder: maxOrder + 1,
|
||||
IsRequired: false,
|
||||
}
|
||||
|
||||
if err := r.db.Create(newCat).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return newCat, nil
|
||||
}
|
||||
|
||||
// Create creates a new category
|
||||
func (r *CategoryRepository) Create(category *models.Category) error {
|
||||
return r.db.Create(category).Error
|
||||
}
|
||||
|
||||
// Update updates an existing category
|
||||
func (r *CategoryRepository) Update(category *models.Category) error {
|
||||
return r.db.Save(category).Error
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ComponentRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewComponentRepository(db *gorm.DB) *ComponentRepository {
|
||||
return &ComponentRepository{db: db}
|
||||
}
|
||||
|
||||
type ComponentFilter struct {
|
||||
Category string
|
||||
Search string
|
||||
HasPrice bool
|
||||
ExcludeHidden bool
|
||||
SortField string
|
||||
SortDir string
|
||||
}
|
||||
|
||||
func (r *ComponentRepository) List(filter ComponentFilter, offset, limit int) ([]models.LotMetadata, int64, error) {
|
||||
var components []models.LotMetadata
|
||||
var total int64
|
||||
|
||||
query := r.db.Model(&models.LotMetadata{}).
|
||||
Preload("Lot").
|
||||
Preload("Category")
|
||||
|
||||
if filter.Category != "" {
|
||||
query = query.Joins("JOIN qt_categories ON qt_lot_metadata.category_id = qt_categories.id").
|
||||
Where("qt_categories.code = ?", filter.Category)
|
||||
}
|
||||
if filter.Search != "" {
|
||||
search := "%" + filter.Search + "%"
|
||||
query = query.Where("lot_name LIKE ? OR model LIKE ?", search, search)
|
||||
}
|
||||
if filter.HasPrice {
|
||||
query = query.Where("current_price IS NOT NULL AND current_price > 0")
|
||||
}
|
||||
if filter.ExcludeHidden {
|
||||
query = query.Where("is_hidden = ? OR is_hidden IS NULL", false)
|
||||
}
|
||||
|
||||
query.Count(&total)
|
||||
|
||||
// Apply sorting
|
||||
sortDir := "ASC"
|
||||
if filter.SortDir == "desc" {
|
||||
sortDir = "DESC"
|
||||
}
|
||||
|
||||
switch filter.SortField {
|
||||
case "popularity_score":
|
||||
query = query.Order("popularity_score " + sortDir)
|
||||
case "current_price":
|
||||
query = query.Order("CASE WHEN current_price IS NULL OR current_price = 0 THEN 1 ELSE 0 END").
|
||||
Order("current_price " + sortDir)
|
||||
case "lot_name":
|
||||
query = query.Order("lot_name " + sortDir)
|
||||
default:
|
||||
// Default: sort by popularity, no price goes last
|
||||
query = query.
|
||||
Order("CASE WHEN current_price IS NULL OR current_price = 0 THEN 1 ELSE 0 END").
|
||||
Order("popularity_score DESC")
|
||||
}
|
||||
|
||||
err := query.
|
||||
Offset(offset).
|
||||
Limit(limit).
|
||||
Find(&components).Error
|
||||
|
||||
return components, total, err
|
||||
}
|
||||
|
||||
func (r *ComponentRepository) GetByLotName(lotName string) (*models.LotMetadata, error) {
|
||||
var component models.LotMetadata
|
||||
err := r.db.
|
||||
Preload("Lot").
|
||||
Preload("Category").
|
||||
Where("lot_name = ?", lotName).
|
||||
First(&component).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &component, nil
|
||||
}
|
||||
|
||||
func (r *ComponentRepository) GetMultiple(lotNames []string) ([]models.LotMetadata, error) {
|
||||
var components []models.LotMetadata
|
||||
err := r.db.
|
||||
Preload("Lot").
|
||||
Preload("Category").
|
||||
Where("lot_name IN ?", lotNames).
|
||||
Find(&components).Error
|
||||
return components, err
|
||||
}
|
||||
|
||||
func (r *ComponentRepository) Update(component *models.LotMetadata) error {
|
||||
return r.db.Save(component).Error
|
||||
}
|
||||
|
||||
func (r *ComponentRepository) DB() *gorm.DB {
|
||||
return r.db
|
||||
}
|
||||
|
||||
func (r *ComponentRepository) Create(component *models.LotMetadata) error {
|
||||
return r.db.Create(component).Error
|
||||
}
|
||||
|
||||
func (r *ComponentRepository) IncrementRequestCount(lotName string) error {
|
||||
now := time.Now()
|
||||
return r.db.Model(&models.LotMetadata{}).
|
||||
Where("lot_name = ?", lotName).
|
||||
Updates(map[string]interface{}{
|
||||
"request_count": gorm.Expr("request_count + 1"),
|
||||
"last_request_date": now,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// GetAllLots returns all lots from the existing lot table
|
||||
func (r *ComponentRepository) GetAllLots() ([]models.Lot, error) {
|
||||
var lots []models.Lot
|
||||
err := r.db.Find(&lots).Error
|
||||
return lots, err
|
||||
}
|
||||
|
||||
// GetLotsWithoutMetadata returns lots that don't have qt_lot_metadata entries
|
||||
func (r *ComponentRepository) GetLotsWithoutMetadata() ([]models.Lot, error) {
|
||||
var lots []models.Lot
|
||||
err := r.db.
|
||||
Where("lot_name NOT IN (SELECT lot_name FROM qt_lot_metadata)").
|
||||
Find(&lots).Error
|
||||
return lots, err
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -269,12 +260,21 @@ func (r *PricelistRepository) GetPriceForLot(pricelistID uint, lotName string) (
|
||||
}
|
||||
|
||||
// GetPricesForLots returns price map for given lots within a pricelist.
|
||||
// Keys in the returned map match the requested lot names (case-preserving) so that
|
||||
// callers using Go map lookups are not confused by case differences between the
|
||||
// requested name and the stored value (e.g. pricelist renamed lots to UPPERCASE).
|
||||
func (r *PricelistRepository) GetPricesForLots(pricelistID uint, lotNames []string) (map[string]float64, error) {
|
||||
result := make(map[string]float64, len(lotNames))
|
||||
if pricelistID == 0 || len(lotNames) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Build case-insensitive index: lowercase → original requested name.
|
||||
lotIndex := make(map[string]string, len(lotNames))
|
||||
for _, n := range lotNames {
|
||||
lotIndex[strings.ToLower(n)] = n
|
||||
}
|
||||
|
||||
var rows []models.PricelistItem
|
||||
if err := r.db.Select("lot_name, price").
|
||||
Where("pricelist_id = ? AND lot_name IN ?", pricelistID, lotNames).
|
||||
@@ -284,7 +284,11 @@ func (r *PricelistRepository) GetPricesForLots(pricelistID uint, lotNames []stri
|
||||
|
||||
for _, row := range rows {
|
||||
if row.Price > 0 {
|
||||
result[row.LotName] = row.Price
|
||||
key := row.LotName
|
||||
if requested, ok := lotIndex[strings.ToLower(row.LotName)]; ok {
|
||||
key = requested
|
||||
}
|
||||
result[key] = row.Price
|
||||
}
|
||||
}
|
||||
return result, 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)
|
||||
|
||||
@@ -23,6 +23,11 @@ func (r *ProjectRepository) Update(project *models.Project) error {
|
||||
}
|
||||
|
||||
func (r *ProjectRepository) UpsertByUUID(project *models.Project) error {
|
||||
// Clear the client-side primary key so the upsert is driven purely by the
|
||||
// uuid unique constraint. Passing a non-zero ID can trigger ON DUPLICATE KEY
|
||||
// on the primary key of an unrelated row, leaving uuid unchanged and causing
|
||||
// the follow-up SELECT to return ErrRecordNotFound.
|
||||
project.ID = 0
|
||||
if err := r.db.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "uuid"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{
|
||||
@@ -33,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 {
|
||||
|
||||
@@ -1,393 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// DataSource defines the unified interface for data access
|
||||
// It abstracts whether data comes from MariaDB (online) or SQLite (offline)
|
||||
type DataSource interface {
|
||||
// Components
|
||||
GetComponents(filter ComponentFilter, offset, limit int) ([]models.LotMetadata, int64, error)
|
||||
GetComponent(lotName string) (*models.LotMetadata, error)
|
||||
|
||||
// Configurations
|
||||
SaveConfiguration(cfg *models.Configuration) error
|
||||
GetConfigurations(ownerUsername string) ([]models.Configuration, error)
|
||||
GetConfigurationByUUID(uuid string) (*models.Configuration, error)
|
||||
DeleteConfiguration(uuid string) error
|
||||
|
||||
// Pricelists (read-only in offline mode)
|
||||
GetPricelists() ([]models.PricelistSummary, error)
|
||||
GetPricelistByID(id uint) (*models.Pricelist, error)
|
||||
GetPricelistItems(pricelistID uint) ([]models.PricelistItem, error)
|
||||
GetLatestPricelist() (*models.Pricelist, error)
|
||||
}
|
||||
|
||||
// UnifiedRepo implements DataSource with automatic online/offline switching
|
||||
type UnifiedRepo struct {
|
||||
mariaDB *gorm.DB
|
||||
localDB *localdb.LocalDB
|
||||
isOnline bool
|
||||
}
|
||||
|
||||
// NewUnifiedRepo creates a new unified repository
|
||||
func NewUnifiedRepo(mariaDB *gorm.DB, localDB *localdb.LocalDB, isOnline bool) *UnifiedRepo {
|
||||
return &UnifiedRepo{
|
||||
mariaDB: mariaDB,
|
||||
localDB: localDB,
|
||||
isOnline: isOnline,
|
||||
}
|
||||
}
|
||||
|
||||
// SetOnlineStatus updates the online/offline status
|
||||
func (r *UnifiedRepo) SetOnlineStatus(online bool) {
|
||||
r.isOnline = online
|
||||
}
|
||||
|
||||
// IsOnline returns the current online/offline status
|
||||
func (r *UnifiedRepo) IsOnline() bool {
|
||||
return r.isOnline
|
||||
}
|
||||
|
||||
// Component methods
|
||||
|
||||
// GetComponents returns components from MariaDB (online) or local cache (offline)
|
||||
func (r *UnifiedRepo) GetComponents(filter ComponentFilter, offset, limit int) ([]models.LotMetadata, int64, error) {
|
||||
if r.isOnline {
|
||||
return r.getComponentsOnline(filter, offset, limit)
|
||||
}
|
||||
return r.getComponentsOffline(filter, offset, limit)
|
||||
}
|
||||
|
||||
func (r *UnifiedRepo) getComponentsOnline(filter ComponentFilter, offset, limit int) ([]models.LotMetadata, int64, error) {
|
||||
repo := NewComponentRepository(r.mariaDB)
|
||||
return repo.List(filter, offset, limit)
|
||||
}
|
||||
|
||||
func (r *UnifiedRepo) getComponentsOffline(filter ComponentFilter, offset, limit int) ([]models.LotMetadata, int64, error) {
|
||||
var components []localdb.LocalComponent
|
||||
query := r.localDB.DB().Model(&localdb.LocalComponent{})
|
||||
|
||||
// Apply filters
|
||||
if filter.Category != "" {
|
||||
query = query.Where("category = ?", filter.Category)
|
||||
}
|
||||
if filter.Search != "" {
|
||||
search := "%" + filter.Search + "%"
|
||||
query = query.Where("lot_name LIKE ? OR lot_description LIKE ? OR model LIKE ?", search, search, search)
|
||||
}
|
||||
var total int64
|
||||
query.Count(&total)
|
||||
|
||||
// Apply sorting
|
||||
sortDir := "ASC"
|
||||
if filter.SortDir == "desc" {
|
||||
sortDir = "DESC"
|
||||
}
|
||||
switch filter.SortField {
|
||||
case "lot_name":
|
||||
query = query.Order("lot_name " + sortDir)
|
||||
default:
|
||||
query = query.Order("lot_name ASC")
|
||||
}
|
||||
|
||||
if err := query.Offset(offset).Limit(limit).Find(&components).Error; err != nil {
|
||||
return nil, 0, fmt.Errorf("fetching offline components: %w", err)
|
||||
}
|
||||
|
||||
// Convert to models.LotMetadata
|
||||
result := make([]models.LotMetadata, len(components))
|
||||
for i, comp := range components {
|
||||
result[i] = models.LotMetadata{
|
||||
LotName: comp.LotName,
|
||||
Model: comp.Model,
|
||||
Lot: &models.Lot{
|
||||
LotName: comp.LotName,
|
||||
LotDescription: comp.LotDescription,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return result, total, nil
|
||||
}
|
||||
|
||||
// GetComponent returns a single component by lot name
|
||||
func (r *UnifiedRepo) GetComponent(lotName string) (*models.LotMetadata, error) {
|
||||
if r.isOnline {
|
||||
repo := NewComponentRepository(r.mariaDB)
|
||||
return repo.GetByLotName(lotName)
|
||||
}
|
||||
|
||||
var comp localdb.LocalComponent
|
||||
if err := r.localDB.DB().Where("lot_name = ?", lotName).First(&comp).Error; err != nil {
|
||||
return nil, fmt.Errorf("fetching offline component: %w", err)
|
||||
}
|
||||
|
||||
return &models.LotMetadata{
|
||||
LotName: comp.LotName,
|
||||
Model: comp.Model,
|
||||
Lot: &models.Lot{
|
||||
LotName: comp.LotName,
|
||||
LotDescription: comp.LotDescription,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Configuration methods
|
||||
|
||||
// SaveConfiguration saves a configuration (online: MariaDB, offline: SQLite + pending_changes)
|
||||
func (r *UnifiedRepo) SaveConfiguration(cfg *models.Configuration) error {
|
||||
if r.isOnline {
|
||||
repo := NewConfigurationRepository(r.mariaDB)
|
||||
return repo.Create(cfg)
|
||||
}
|
||||
|
||||
// Offline: save to local SQLite and queue for sync
|
||||
localCfg := &localdb.LocalConfiguration{
|
||||
UUID: cfg.UUID,
|
||||
Name: cfg.Name,
|
||||
TotalPrice: cfg.TotalPrice,
|
||||
CustomPrice: cfg.CustomPrice,
|
||||
Notes: cfg.Notes,
|
||||
IsTemplate: cfg.IsTemplate,
|
||||
ServerCount: cfg.ServerCount,
|
||||
CreatedAt: cfg.CreatedAt,
|
||||
UpdatedAt: time.Now(),
|
||||
SyncStatus: "pending",
|
||||
OriginalUsername: cfg.OwnerUsername,
|
||||
}
|
||||
|
||||
// Convert items
|
||||
localItems := make(localdb.LocalConfigItems, len(cfg.Items))
|
||||
for i, item := range cfg.Items {
|
||||
localItems[i] = localdb.LocalConfigItem{
|
||||
LotName: item.LotName,
|
||||
Quantity: item.Quantity,
|
||||
UnitPrice: item.UnitPrice,
|
||||
}
|
||||
}
|
||||
localCfg.Items = localItems
|
||||
|
||||
if err := r.localDB.SaveConfiguration(localCfg); err != nil {
|
||||
return fmt.Errorf("saving local configuration: %w", err)
|
||||
}
|
||||
|
||||
// Add to pending changes queue
|
||||
payload, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshaling configuration for sync: %w", err)
|
||||
}
|
||||
|
||||
return r.localDB.AddPendingChange("configuration", cfg.UUID, "create", string(payload))
|
||||
}
|
||||
|
||||
// GetConfigurations returns all configurations for a user
|
||||
func (r *UnifiedRepo) GetConfigurations(ownerUsername string) ([]models.Configuration, error) {
|
||||
if r.isOnline {
|
||||
repo := NewConfigurationRepository(r.mariaDB)
|
||||
configs, _, err := repo.ListByUser(ownerUsername, 0, 1000)
|
||||
return configs, err
|
||||
}
|
||||
|
||||
// Offline: get from local SQLite
|
||||
localConfigs, err := r.localDB.GetConfigurations()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching local configurations: %w", err)
|
||||
}
|
||||
|
||||
// Convert to models.Configuration
|
||||
result := make([]models.Configuration, len(localConfigs))
|
||||
for i, lc := range localConfigs {
|
||||
items := make(models.ConfigItems, len(lc.Items))
|
||||
for j, item := range lc.Items {
|
||||
items[j] = models.ConfigItem{
|
||||
LotName: item.LotName,
|
||||
Quantity: item.Quantity,
|
||||
UnitPrice: item.UnitPrice,
|
||||
}
|
||||
}
|
||||
|
||||
result[i] = models.Configuration{
|
||||
UUID: lc.UUID,
|
||||
OwnerUsername: lc.OriginalUsername,
|
||||
Name: lc.Name,
|
||||
Items: items,
|
||||
TotalPrice: lc.TotalPrice,
|
||||
CustomPrice: lc.CustomPrice,
|
||||
Notes: lc.Notes,
|
||||
IsTemplate: lc.IsTemplate,
|
||||
ServerCount: lc.ServerCount,
|
||||
CreatedAt: lc.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetConfigurationByUUID returns a configuration by UUID
|
||||
func (r *UnifiedRepo) GetConfigurationByUUID(uuid string) (*models.Configuration, error) {
|
||||
if r.isOnline {
|
||||
repo := NewConfigurationRepository(r.mariaDB)
|
||||
return repo.GetByUUID(uuid)
|
||||
}
|
||||
|
||||
localCfg, err := r.localDB.GetConfigurationByUUID(uuid)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching local configuration: %w", err)
|
||||
}
|
||||
|
||||
items := make(models.ConfigItems, len(localCfg.Items))
|
||||
for i, item := range localCfg.Items {
|
||||
items[i] = models.ConfigItem{
|
||||
LotName: item.LotName,
|
||||
Quantity: item.Quantity,
|
||||
UnitPrice: item.UnitPrice,
|
||||
}
|
||||
}
|
||||
|
||||
return &models.Configuration{
|
||||
UUID: localCfg.UUID,
|
||||
Name: localCfg.Name,
|
||||
Items: items,
|
||||
TotalPrice: localCfg.TotalPrice,
|
||||
CustomPrice: localCfg.CustomPrice,
|
||||
Notes: localCfg.Notes,
|
||||
IsTemplate: localCfg.IsTemplate,
|
||||
ServerCount: localCfg.ServerCount,
|
||||
CreatedAt: localCfg.CreatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// DeleteConfiguration deletes a configuration
|
||||
func (r *UnifiedRepo) DeleteConfiguration(uuid string) error {
|
||||
if r.isOnline {
|
||||
// Get ID first
|
||||
cfg, err := r.GetConfigurationByUUID(uuid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
repo := NewConfigurationRepository(r.mariaDB)
|
||||
return repo.Delete(cfg.ID)
|
||||
}
|
||||
|
||||
// Offline: delete from local and queue sync
|
||||
if err := r.localDB.DeleteConfiguration(uuid); err != nil {
|
||||
return fmt.Errorf("deleting local configuration: %w", err)
|
||||
}
|
||||
|
||||
return r.localDB.AddPendingChange("configuration", uuid, "delete", "")
|
||||
}
|
||||
|
||||
// Pricelist methods
|
||||
|
||||
// GetPricelists returns all pricelists
|
||||
func (r *UnifiedRepo) GetPricelists() ([]models.PricelistSummary, error) {
|
||||
if r.isOnline {
|
||||
repo := NewPricelistRepository(r.mariaDB)
|
||||
summaries, _, err := repo.List(0, 1000)
|
||||
return summaries, err
|
||||
}
|
||||
|
||||
// Offline: get from local cache
|
||||
localPLs, err := r.localDB.GetLocalPricelists()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching local pricelists: %w", err)
|
||||
}
|
||||
|
||||
summaries := make([]models.PricelistSummary, len(localPLs))
|
||||
for i, pl := range localPLs {
|
||||
itemCount := r.localDB.CountLocalPricelistItems(pl.ID)
|
||||
summaries[i] = models.PricelistSummary{
|
||||
ID: pl.ServerID,
|
||||
Version: pl.Version,
|
||||
CreatedAt: pl.CreatedAt,
|
||||
ItemCount: itemCount,
|
||||
}
|
||||
}
|
||||
|
||||
return summaries, nil
|
||||
}
|
||||
|
||||
// GetPricelistByID returns a pricelist by ID
|
||||
func (r *UnifiedRepo) GetPricelistByID(id uint) (*models.Pricelist, error) {
|
||||
if r.isOnline {
|
||||
repo := NewPricelistRepository(r.mariaDB)
|
||||
return repo.GetByID(id)
|
||||
}
|
||||
|
||||
// Offline: get from local cache
|
||||
localPL, err := r.localDB.GetLocalPricelistByServerID(id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching local pricelist: %w", err)
|
||||
}
|
||||
|
||||
itemCount := r.localDB.CountLocalPricelistItems(localPL.ID)
|
||||
return &models.Pricelist{
|
||||
ID: localPL.ServerID,
|
||||
Version: localPL.Version,
|
||||
CreatedAt: localPL.CreatedAt,
|
||||
ItemCount: int(itemCount),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetPricelistItems returns items for a pricelist
|
||||
func (r *UnifiedRepo) GetPricelistItems(pricelistID uint) ([]models.PricelistItem, error) {
|
||||
if r.isOnline {
|
||||
repo := NewPricelistRepository(r.mariaDB)
|
||||
items, _, err := repo.GetItems(pricelistID, 0, 100000, "")
|
||||
return items, err
|
||||
}
|
||||
|
||||
// Offline: get from local cache
|
||||
// First find the local pricelist by server ID
|
||||
localPL, err := r.localDB.GetLocalPricelistByServerID(pricelistID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching local pricelist: %w", err)
|
||||
}
|
||||
|
||||
localItems, err := r.localDB.GetLocalPricelistItems(localPL.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching local pricelist items: %w", err)
|
||||
}
|
||||
|
||||
items := make([]models.PricelistItem, len(localItems))
|
||||
for i, item := range localItems {
|
||||
items[i] = models.PricelistItem{
|
||||
ID: item.ID,
|
||||
PricelistID: pricelistID,
|
||||
LotName: item.LotName,
|
||||
Price: item.Price,
|
||||
}
|
||||
}
|
||||
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// GetLatestPricelist returns the latest pricelist
|
||||
func (r *UnifiedRepo) GetLatestPricelist() (*models.Pricelist, error) {
|
||||
if r.isOnline {
|
||||
repo := NewPricelistRepository(r.mariaDB)
|
||||
return repo.GetLatestActive()
|
||||
}
|
||||
|
||||
// Offline: get from local cache
|
||||
localPL, err := r.localDB.GetLatestLocalPricelist()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching latest local pricelist: %w", err)
|
||||
}
|
||||
|
||||
itemCount := r.localDB.CountLocalPricelistItems(localPL.ID)
|
||||
return &models.Pricelist{
|
||||
ID: localPL.ServerID,
|
||||
Version: localPL.Version,
|
||||
CreatedAt: localPL.CreatedAt,
|
||||
ItemCount: int(itemCount),
|
||||
}, nil
|
||||
}
|
||||
@@ -1,43 +1,5 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/repository"
|
||||
)
|
||||
|
||||
type ComponentService struct {
|
||||
componentRepo *repository.ComponentRepository
|
||||
categoryRepo *repository.CategoryRepository
|
||||
}
|
||||
|
||||
func NewComponentService(
|
||||
componentRepo *repository.ComponentRepository,
|
||||
categoryRepo *repository.CategoryRepository,
|
||||
) *ComponentService {
|
||||
return &ComponentService{
|
||||
componentRepo: componentRepo,
|
||||
categoryRepo: categoryRepo,
|
||||
}
|
||||
}
|
||||
|
||||
// ParsePartNumber extracts category and model from lot_name
|
||||
// "CPU_AMD_9654" → category="CPU", model="AMD_9654"
|
||||
// "MB_INTEL_4.Sapphire_2S_32xDDR5" → category="MB", model="INTEL_4.Sapphire_2S_32xDDR5"
|
||||
func ParsePartNumber(lotName string) (category, model string) {
|
||||
parts := strings.SplitN(lotName, "_", 2)
|
||||
if len(parts) >= 1 {
|
||||
category = parts[0]
|
||||
}
|
||||
if len(parts) >= 2 {
|
||||
model = parts[1]
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type ComponentListResult struct {
|
||||
Items []ComponentView `json:"items"`
|
||||
TotalCount int64 `json:"total_count"`
|
||||
@@ -47,178 +9,10 @@ type ComponentListResult struct {
|
||||
}
|
||||
|
||||
type ComponentView struct {
|
||||
LotName string `json:"lot_name"`
|
||||
Description string `json:"description"`
|
||||
Category string `json:"category"`
|
||||
CategoryName string `json:"category_name"`
|
||||
Model string `json:"model"`
|
||||
PriceFreshness models.PriceFreshness `json:"price_freshness"`
|
||||
PopularityScore float64 `json:"popularity_score"`
|
||||
Specs models.Specs `json:"specs,omitempty"`
|
||||
}
|
||||
|
||||
func (s *ComponentService) List(filter repository.ComponentFilter, page, perPage int) (*ComponentListResult, error) {
|
||||
// If no database connection (offline mode), return empty list
|
||||
// Components should be loaded via /api/sync/components first
|
||||
if s.componentRepo == nil {
|
||||
return &ComponentListResult{
|
||||
Items: []ComponentView{},
|
||||
TotalCount: 0,
|
||||
Page: page,
|
||||
PerPage: perPage,
|
||||
TotalPages: 1,
|
||||
}, nil
|
||||
}
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if perPage < 1 {
|
||||
perPage = 20
|
||||
}
|
||||
if perPage > 5000 {
|
||||
perPage = 5000
|
||||
}
|
||||
offset := (page - 1) * perPage
|
||||
|
||||
components, total, err := s.componentRepo.List(filter, offset, perPage)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
views := make([]ComponentView, len(components))
|
||||
for i, c := range components {
|
||||
view := ComponentView{
|
||||
LotName: c.LotName,
|
||||
Model: c.Model,
|
||||
PriceFreshness: c.GetPriceFreshness(30, 60, 90, 3),
|
||||
PopularityScore: c.PopularityScore,
|
||||
Specs: c.Specs,
|
||||
}
|
||||
|
||||
if c.Lot != nil {
|
||||
view.Description = c.Lot.LotDescription
|
||||
}
|
||||
if c.Category != nil {
|
||||
view.Category = c.Category.Code
|
||||
view.CategoryName = c.Category.Name
|
||||
}
|
||||
|
||||
views[i] = view
|
||||
}
|
||||
|
||||
totalPages := int((total + int64(perPage) - 1) / int64(perPage))
|
||||
if totalPages < 1 {
|
||||
totalPages = 1
|
||||
}
|
||||
return &ComponentListResult{
|
||||
Items: views,
|
||||
TotalCount: total,
|
||||
Page: page,
|
||||
PerPage: perPage,
|
||||
TotalPages: totalPages,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *ComponentService) GetByLotName(lotName string) (*ComponentView, error) {
|
||||
// If no database connection (offline mode), return error
|
||||
if s.componentRepo == nil {
|
||||
return nil, fmt.Errorf("offline mode: component data not available")
|
||||
}
|
||||
|
||||
c, err := s.componentRepo.GetByLotName(lotName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Track usage (best-effort)
|
||||
if err := s.componentRepo.IncrementRequestCount(lotName); err != nil {
|
||||
slog.Warn("component: could not increment request count", "lot", lotName, "err", err)
|
||||
}
|
||||
|
||||
view := &ComponentView{
|
||||
LotName: c.LotName,
|
||||
Model: c.Model,
|
||||
PriceFreshness: c.GetPriceFreshness(30, 60, 90, 3),
|
||||
PopularityScore: c.PopularityScore,
|
||||
Specs: c.Specs,
|
||||
}
|
||||
|
||||
if c.Lot != nil {
|
||||
view.Description = c.Lot.LotDescription
|
||||
}
|
||||
if c.Category != nil {
|
||||
view.Category = c.Category.Code
|
||||
view.CategoryName = c.Category.Name
|
||||
}
|
||||
|
||||
return view, nil
|
||||
}
|
||||
|
||||
func (s *ComponentService) GetCategories() ([]models.Category, error) {
|
||||
// If no database connection (offline mode), return default categories
|
||||
if s.categoryRepo == nil {
|
||||
return models.DefaultCategories, nil
|
||||
}
|
||||
return s.categoryRepo.GetAll()
|
||||
}
|
||||
|
||||
// ImportFromLot creates metadata entries for lots that don't have them
|
||||
func (s *ComponentService) ImportFromLot() (int, error) {
|
||||
// If no database connection (offline mode), return error
|
||||
if s.componentRepo == nil || s.categoryRepo == nil {
|
||||
return 0, fmt.Errorf("offline mode: import not available")
|
||||
}
|
||||
|
||||
lots, err := s.componentRepo.GetLotsWithoutMetadata()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
categories, err := s.categoryRepo.GetAll()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
categoryMap := make(map[string]uint)
|
||||
for _, cat := range categories {
|
||||
categoryMap[strings.ToUpper(cat.Code)] = cat.ID
|
||||
}
|
||||
|
||||
imported := 0
|
||||
for _, lot := range lots {
|
||||
// Use lot_category from database if available, otherwise parse from lot_name
|
||||
var category string
|
||||
if lot.LotCategory != nil && *lot.LotCategory != "" {
|
||||
category = strings.ToUpper(*lot.LotCategory)
|
||||
} else {
|
||||
category, _ = ParsePartNumber(lot.LotName)
|
||||
category = strings.ToUpper(category)
|
||||
}
|
||||
|
||||
_, model := ParsePartNumber(lot.LotName)
|
||||
|
||||
metadata := &models.LotMetadata{
|
||||
LotName: lot.LotName,
|
||||
Model: model,
|
||||
Specs: make(models.Specs),
|
||||
}
|
||||
|
||||
if catID, ok := categoryMap[category]; ok {
|
||||
metadata.CategoryID = &catID
|
||||
} else {
|
||||
// Create new category if it doesn't exist
|
||||
newCat, err := s.categoryRepo.CreateIfNotExists(category)
|
||||
if err == nil && newCat != nil {
|
||||
metadata.CategoryID = &newCat.ID
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.componentRepo.Create(metadata); err != nil {
|
||||
continue
|
||||
}
|
||||
imported++
|
||||
}
|
||||
|
||||
return imported, nil
|
||||
LotName string `json:"lot_name"`
|
||||
Description string `json:"description"`
|
||||
Category string `json:"category"`
|
||||
CategoryName string `json:"category_name"`
|
||||
Model string `json:"model"`
|
||||
PriceQuality *int `json:"price_quality,omitempty"`
|
||||
}
|
||||
@@ -2,11 +2,8 @@ package services
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/repository"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -14,37 +11,13 @@ var (
|
||||
ErrConfigForbidden = errors.New("access to configuration forbidden")
|
||||
)
|
||||
|
||||
// ConfigurationGetter is an interface for services that can retrieve configurations
|
||||
// Used by handlers to work with both ConfigurationService and LocalConfigurationService
|
||||
// ConfigurationGetter is an interface for services that can retrieve configurations.
|
||||
// Used by handlers to work with LocalConfigurationService.
|
||||
type ConfigurationGetter interface {
|
||||
GetByUUID(uuid string, ownerUsername string) (*models.Configuration, error)
|
||||
GetByUUIDNoAuth(uuid string) (*models.Configuration, error)
|
||||
}
|
||||
|
||||
type ConfigurationService struct {
|
||||
configRepo *repository.ConfigurationRepository
|
||||
projectRepo *repository.ProjectRepository
|
||||
componentRepo *repository.ComponentRepository
|
||||
pricelistRepo *repository.PricelistRepository
|
||||
quoteService *QuoteService
|
||||
}
|
||||
|
||||
func NewConfigurationService(
|
||||
configRepo *repository.ConfigurationRepository,
|
||||
projectRepo *repository.ProjectRepository,
|
||||
componentRepo *repository.ComponentRepository,
|
||||
pricelistRepo *repository.PricelistRepository,
|
||||
quoteService *QuoteService,
|
||||
) *ConfigurationService {
|
||||
return &ConfigurationService{
|
||||
configRepo: configRepo,
|
||||
projectRepo: projectRepo,
|
||||
componentRepo: componentRepo,
|
||||
pricelistRepo: pricelistRepo,
|
||||
quoteService: quoteService,
|
||||
}
|
||||
}
|
||||
|
||||
type CreateConfigRequest struct {
|
||||
Name string `json:"name"`
|
||||
Items models.ConfigItems `json:"items"`
|
||||
@@ -70,583 +43,3 @@ type ArticlePreviewRequest struct {
|
||||
SupportCode string `json:"support_code,omitempty"`
|
||||
PricelistID *uint `json:"pricelist_id,omitempty"`
|
||||
}
|
||||
|
||||
func (s *ConfigurationService) Create(ownerUsername string, req *CreateConfigRequest) (*models.Configuration, error) {
|
||||
projectUUID, err := s.resolveProjectUUID(ownerUsername, req.ProjectUUID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pricelistID, err := s.resolvePricelistID(req.PricelistID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
total := req.Items.Total()
|
||||
|
||||
// If server count is greater than 1, multiply the total by server count
|
||||
if req.ServerCount > 1 {
|
||||
total *= float64(req.ServerCount)
|
||||
}
|
||||
|
||||
config := &models.Configuration{
|
||||
UUID: uuid.New().String(),
|
||||
OwnerUsername: ownerUsername,
|
||||
ProjectUUID: projectUUID,
|
||||
Name: req.Name,
|
||||
Items: req.Items,
|
||||
TotalPrice: &total,
|
||||
CustomPrice: req.CustomPrice,
|
||||
Notes: req.Notes,
|
||||
IsTemplate: req.IsTemplate,
|
||||
ServerCount: req.ServerCount,
|
||||
ServerModel: req.ServerModel,
|
||||
SupportCode: req.SupportCode,
|
||||
Article: req.Article,
|
||||
PricelistID: pricelistID,
|
||||
WarehousePricelistID: req.WarehousePricelistID,
|
||||
CompetitorPricelistID: req.CompetitorPricelistID,
|
||||
ConfigType: req.ConfigType,
|
||||
DisablePriceRefresh: req.DisablePriceRefresh,
|
||||
OnlyInStock: req.OnlyInStock,
|
||||
}
|
||||
if config.ConfigType == "" {
|
||||
config.ConfigType = "server"
|
||||
}
|
||||
|
||||
if err := s.configRepo.Create(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func (s *ConfigurationService) GetByUUID(uuid string, ownerUsername string) (*models.Configuration, error) {
|
||||
config, err := s.configRepo.GetByUUID(uuid)
|
||||
if err != nil {
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
|
||||
// Allow access if user owns config or it's a template
|
||||
if !s.isOwner(config, ownerUsername) && !config.IsTemplate {
|
||||
return nil, ErrConfigForbidden
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func (s *ConfigurationService) Update(uuid string, ownerUsername string, req *CreateConfigRequest) (*models.Configuration, error) {
|
||||
config, err := s.configRepo.GetByUUID(uuid)
|
||||
if err != nil {
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
|
||||
if !s.isOwner(config, ownerUsername) {
|
||||
return nil, ErrConfigForbidden
|
||||
}
|
||||
|
||||
projectUUID, err := s.resolveProjectUUID(ownerUsername, req.ProjectUUID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pricelistID, err := s.resolvePricelistID(req.PricelistID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
total := req.Items.Total()
|
||||
|
||||
// If server count is greater than 1, multiply the total by server count
|
||||
if req.ServerCount > 1 {
|
||||
total *= float64(req.ServerCount)
|
||||
}
|
||||
|
||||
config.Name = req.Name
|
||||
config.ProjectUUID = projectUUID
|
||||
config.Items = req.Items
|
||||
config.TotalPrice = &total
|
||||
config.CustomPrice = req.CustomPrice
|
||||
config.Notes = req.Notes
|
||||
config.IsTemplate = req.IsTemplate
|
||||
config.ServerCount = req.ServerCount
|
||||
config.ServerModel = req.ServerModel
|
||||
config.SupportCode = req.SupportCode
|
||||
config.Article = req.Article
|
||||
config.PricelistID = pricelistID
|
||||
config.WarehousePricelistID = req.WarehousePricelistID
|
||||
config.CompetitorPricelistID = req.CompetitorPricelistID
|
||||
config.DisablePriceRefresh = req.DisablePriceRefresh
|
||||
config.OnlyInStock = req.OnlyInStock
|
||||
|
||||
if err := s.configRepo.Update(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func (s *ConfigurationService) Delete(uuid string, ownerUsername string) error {
|
||||
config, err := s.configRepo.GetByUUID(uuid)
|
||||
if err != nil {
|
||||
return ErrConfigNotFound
|
||||
}
|
||||
|
||||
if !s.isOwner(config, ownerUsername) {
|
||||
return ErrConfigForbidden
|
||||
}
|
||||
|
||||
return s.configRepo.Delete(config.ID)
|
||||
}
|
||||
|
||||
func (s *ConfigurationService) Rename(uuid string, ownerUsername string, newName string) (*models.Configuration, error) {
|
||||
config, err := s.configRepo.GetByUUID(uuid)
|
||||
if err != nil {
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
|
||||
if !s.isOwner(config, ownerUsername) {
|
||||
return nil, ErrConfigForbidden
|
||||
}
|
||||
|
||||
config.Name = newName
|
||||
|
||||
if err := s.configRepo.Update(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func (s *ConfigurationService) Clone(configUUID string, ownerUsername string, newName string) (*models.Configuration, error) {
|
||||
return s.CloneToProject(configUUID, ownerUsername, newName, nil)
|
||||
}
|
||||
|
||||
func (s *ConfigurationService) CloneToProject(configUUID string, ownerUsername string, newName string, projectUUID *string) (*models.Configuration, error) {
|
||||
original, err := s.GetByUUID(configUUID, ownerUsername)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resolvedProjectUUID := original.ProjectUUID
|
||||
if projectUUID != nil {
|
||||
resolvedProjectUUID, err = s.resolveProjectUUID(ownerUsername, projectUUID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Create copy with new UUID and name
|
||||
total := original.Items.Total()
|
||||
|
||||
// If server count is greater than 1, multiply the total by server count
|
||||
if original.ServerCount > 1 {
|
||||
total *= float64(original.ServerCount)
|
||||
}
|
||||
|
||||
clone := &models.Configuration{
|
||||
UUID: uuid.New().String(),
|
||||
OwnerUsername: ownerUsername,
|
||||
ProjectUUID: resolvedProjectUUID,
|
||||
Name: newName,
|
||||
Items: original.Items,
|
||||
TotalPrice: &total,
|
||||
CustomPrice: original.CustomPrice,
|
||||
Notes: original.Notes,
|
||||
IsTemplate: false, // Clone is never a template
|
||||
ServerCount: original.ServerCount,
|
||||
ServerModel: original.ServerModel,
|
||||
SupportCode: original.SupportCode,
|
||||
Article: original.Article,
|
||||
PricelistID: original.PricelistID,
|
||||
WarehousePricelistID: original.WarehousePricelistID,
|
||||
CompetitorPricelistID: original.CompetitorPricelistID,
|
||||
DisablePriceRefresh: original.DisablePriceRefresh,
|
||||
OnlyInStock: original.OnlyInStock,
|
||||
}
|
||||
|
||||
if err := s.configRepo.Create(clone); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return clone, nil
|
||||
}
|
||||
|
||||
func (s *ConfigurationService) ListByUser(ownerUsername string, page, perPage int) ([]models.Configuration, int64, error) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if perPage < 1 || perPage > 100 {
|
||||
perPage = 20
|
||||
}
|
||||
offset := (page - 1) * perPage
|
||||
|
||||
return s.configRepo.ListByUser(ownerUsername, offset, perPage)
|
||||
}
|
||||
|
||||
// ListAll returns all configurations without user filter (for use when auth is disabled)
|
||||
func (s *ConfigurationService) ListAll(page, perPage int) ([]models.Configuration, int64, error) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if perPage < 1 || perPage > 100 {
|
||||
perPage = 20
|
||||
}
|
||||
offset := (page - 1) * perPage
|
||||
|
||||
return s.configRepo.ListAll(offset, perPage)
|
||||
}
|
||||
|
||||
// GetByUUIDNoAuth returns configuration without ownership check (for use when auth is disabled)
|
||||
func (s *ConfigurationService) GetByUUIDNoAuth(uuid string) (*models.Configuration, error) {
|
||||
config, err := s.configRepo.GetByUUID(uuid)
|
||||
if err != nil {
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// UpdateNoAuth updates configuration without ownership check
|
||||
func (s *ConfigurationService) UpdateNoAuth(uuid string, req *CreateConfigRequest) (*models.Configuration, error) {
|
||||
config, err := s.configRepo.GetByUUID(uuid)
|
||||
if err != nil {
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
|
||||
projectUUID, err := s.resolveProjectUUID(config.OwnerUsername, req.ProjectUUID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pricelistID, err := s.resolvePricelistID(req.PricelistID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
total := req.Items.Total()
|
||||
if req.ServerCount > 1 {
|
||||
total *= float64(req.ServerCount)
|
||||
}
|
||||
|
||||
config.Name = req.Name
|
||||
config.ProjectUUID = projectUUID
|
||||
config.Items = req.Items
|
||||
config.TotalPrice = &total
|
||||
config.CustomPrice = req.CustomPrice
|
||||
config.Notes = req.Notes
|
||||
config.IsTemplate = req.IsTemplate
|
||||
config.ServerCount = req.ServerCount
|
||||
config.ServerModel = req.ServerModel
|
||||
config.SupportCode = req.SupportCode
|
||||
config.Article = req.Article
|
||||
config.PricelistID = pricelistID
|
||||
config.WarehousePricelistID = req.WarehousePricelistID
|
||||
config.CompetitorPricelistID = req.CompetitorPricelistID
|
||||
config.DisablePriceRefresh = req.DisablePriceRefresh
|
||||
config.OnlyInStock = req.OnlyInStock
|
||||
|
||||
if err := s.configRepo.Update(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// DeleteNoAuth deletes configuration without ownership check
|
||||
func (s *ConfigurationService) DeleteNoAuth(uuid string) error {
|
||||
config, err := s.configRepo.GetByUUID(uuid)
|
||||
if err != nil {
|
||||
return ErrConfigNotFound
|
||||
}
|
||||
return s.configRepo.Delete(config.ID)
|
||||
}
|
||||
|
||||
// RenameNoAuth renames configuration without ownership check
|
||||
func (s *ConfigurationService) RenameNoAuth(uuid string, newName string) (*models.Configuration, error) {
|
||||
config, err := s.configRepo.GetByUUID(uuid)
|
||||
if err != nil {
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
|
||||
config.Name = newName
|
||||
if err := s.configRepo.Update(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// CloneNoAuth clones configuration without ownership check
|
||||
func (s *ConfigurationService) CloneNoAuth(configUUID string, newName string, ownerUsername string) (*models.Configuration, error) {
|
||||
return s.CloneNoAuthToProject(configUUID, newName, ownerUsername, nil)
|
||||
}
|
||||
|
||||
func (s *ConfigurationService) CloneNoAuthToProject(configUUID string, newName string, ownerUsername string, projectUUID *string) (*models.Configuration, error) {
|
||||
original, err := s.configRepo.GetByUUID(configUUID)
|
||||
if err != nil {
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
resolvedProjectUUID := original.ProjectUUID
|
||||
if projectUUID != nil {
|
||||
resolvedProjectUUID, err = s.resolveProjectUUID(ownerUsername, projectUUID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
total := original.Items.Total()
|
||||
if original.ServerCount > 1 {
|
||||
total *= float64(original.ServerCount)
|
||||
}
|
||||
|
||||
clone := &models.Configuration{
|
||||
UUID: uuid.New().String(),
|
||||
OwnerUsername: ownerUsername,
|
||||
ProjectUUID: resolvedProjectUUID,
|
||||
Name: newName,
|
||||
Items: original.Items,
|
||||
TotalPrice: &total,
|
||||
CustomPrice: original.CustomPrice,
|
||||
Notes: original.Notes,
|
||||
IsTemplate: false,
|
||||
ServerCount: original.ServerCount,
|
||||
PricelistID: original.PricelistID,
|
||||
OnlyInStock: original.OnlyInStock,
|
||||
}
|
||||
|
||||
if err := s.configRepo.Create(clone); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return clone, nil
|
||||
}
|
||||
|
||||
func (s *ConfigurationService) resolveProjectUUID(ownerUsername string, projectUUID *string) (*string, error) {
|
||||
_ = ownerUsername
|
||||
if s.projectRepo == nil {
|
||||
return projectUUID, nil
|
||||
}
|
||||
if projectUUID == nil || *projectUUID == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
project, err := s.projectRepo.GetByUUID(*projectUUID)
|
||||
if err != nil {
|
||||
return nil, ErrProjectNotFound
|
||||
}
|
||||
if !project.IsActive {
|
||||
return nil, errors.New("project is archived")
|
||||
}
|
||||
|
||||
return &project.UUID, nil
|
||||
}
|
||||
|
||||
func (s *ConfigurationService) resolvePricelistID(pricelistID *uint) (*uint, error) {
|
||||
if s.pricelistRepo == nil {
|
||||
return pricelistID, nil
|
||||
}
|
||||
if pricelistID != nil && *pricelistID > 0 {
|
||||
if _, err := s.pricelistRepo.GetByID(*pricelistID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pricelistID, nil
|
||||
}
|
||||
latest, err := s.pricelistRepo.GetLatestActive()
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
return &latest.ID, nil
|
||||
}
|
||||
|
||||
// RefreshPricesNoAuth refreshes prices without ownership check
|
||||
func (s *ConfigurationService) RefreshPricesNoAuth(uuid string) (*models.Configuration, error) {
|
||||
config, err := s.configRepo.GetByUUID(uuid)
|
||||
if err != nil {
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
|
||||
var latestPricelistID *uint
|
||||
if s.pricelistRepo != nil {
|
||||
if pl, err := s.pricelistRepo.GetLatestActive(); err == nil {
|
||||
latestPricelistID = &pl.ID
|
||||
}
|
||||
}
|
||||
|
||||
updatedItems := make(models.ConfigItems, len(config.Items))
|
||||
for i, item := range config.Items {
|
||||
if latestPricelistID != nil {
|
||||
if price, err := s.pricelistRepo.GetPriceForLot(*latestPricelistID, item.LotName); err == nil && price > 0 {
|
||||
updatedItems[i] = models.ConfigItem{
|
||||
LotName: item.LotName,
|
||||
Quantity: item.Quantity,
|
||||
UnitPrice: price,
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if s.componentRepo == nil {
|
||||
updatedItems[i] = item
|
||||
continue
|
||||
}
|
||||
metadata, err := s.componentRepo.GetByLotName(item.LotName)
|
||||
if err != nil || metadata.CurrentPrice == nil {
|
||||
updatedItems[i] = item
|
||||
continue
|
||||
}
|
||||
|
||||
updatedItems[i] = models.ConfigItem{
|
||||
LotName: item.LotName,
|
||||
Quantity: item.Quantity,
|
||||
UnitPrice: *metadata.CurrentPrice,
|
||||
}
|
||||
}
|
||||
|
||||
config.Items = updatedItems
|
||||
total := updatedItems.Total()
|
||||
if config.ServerCount > 1 {
|
||||
total *= float64(config.ServerCount)
|
||||
}
|
||||
|
||||
config.TotalPrice = &total
|
||||
if latestPricelistID != nil {
|
||||
config.PricelistID = latestPricelistID
|
||||
}
|
||||
now := time.Now()
|
||||
config.PriceUpdatedAt = &now
|
||||
|
||||
if err := s.configRepo.Update(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func (s *ConfigurationService) ListTemplates(page, perPage int) ([]models.Configuration, int64, error) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if perPage < 1 || perPage > 100 {
|
||||
perPage = 20
|
||||
}
|
||||
offset := (page - 1) * perPage
|
||||
|
||||
return s.configRepo.ListTemplates(offset, perPage)
|
||||
}
|
||||
|
||||
// RefreshPrices updates all component prices in the configuration with current prices
|
||||
func (s *ConfigurationService) RefreshPrices(uuid string, ownerUsername string) (*models.Configuration, error) {
|
||||
config, err := s.configRepo.GetByUUID(uuid)
|
||||
if err != nil {
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
|
||||
if !s.isOwner(config, ownerUsername) {
|
||||
return nil, ErrConfigForbidden
|
||||
}
|
||||
|
||||
var latestPricelistID *uint
|
||||
if s.pricelistRepo != nil {
|
||||
if pl, err := s.pricelistRepo.GetLatestActive(); err == nil {
|
||||
latestPricelistID = &pl.ID
|
||||
}
|
||||
}
|
||||
|
||||
// Update prices for all items
|
||||
updatedItems := make(models.ConfigItems, len(config.Items))
|
||||
for i, item := range config.Items {
|
||||
if latestPricelistID != nil {
|
||||
if price, err := s.pricelistRepo.GetPriceForLot(*latestPricelistID, item.LotName); err == nil && price > 0 {
|
||||
updatedItems[i] = models.ConfigItem{
|
||||
LotName: item.LotName,
|
||||
Quantity: item.Quantity,
|
||||
UnitPrice: price,
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Get current component price
|
||||
if s.componentRepo == nil {
|
||||
updatedItems[i] = item
|
||||
continue
|
||||
}
|
||||
metadata, err := s.componentRepo.GetByLotName(item.LotName)
|
||||
if err != nil || metadata.CurrentPrice == nil {
|
||||
// Keep original item if component not found or no price available
|
||||
updatedItems[i] = item
|
||||
continue
|
||||
}
|
||||
|
||||
// Update item with current price
|
||||
updatedItems[i] = models.ConfigItem{
|
||||
LotName: item.LotName,
|
||||
Quantity: item.Quantity,
|
||||
UnitPrice: *metadata.CurrentPrice,
|
||||
}
|
||||
}
|
||||
|
||||
// Update configuration
|
||||
config.Items = updatedItems
|
||||
total := updatedItems.Total()
|
||||
|
||||
// If server count is greater than 1, multiply the total by server count
|
||||
if config.ServerCount > 1 {
|
||||
total *= float64(config.ServerCount)
|
||||
}
|
||||
|
||||
config.TotalPrice = &total
|
||||
if latestPricelistID != nil {
|
||||
config.PricelistID = latestPricelistID
|
||||
}
|
||||
|
||||
// Set price update timestamp
|
||||
now := time.Now()
|
||||
config.PriceUpdatedAt = &now
|
||||
|
||||
if err := s.configRepo.Update(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func (s *ConfigurationService) isOwner(config *models.Configuration, ownerUsername string) bool {
|
||||
if config == nil || ownerUsername == "" {
|
||||
return false
|
||||
}
|
||||
return config.OwnerUsername == ownerUsername
|
||||
}
|
||||
|
||||
// // Export configuration as JSON
|
||||
// type ConfigExport struct {
|
||||
// Name string `json:"name"`
|
||||
// Notes string `json:"notes"`
|
||||
// Items models.ConfigItems `json:"items"`
|
||||
// }
|
||||
//
|
||||
// func (s *ConfigurationService) ExportJSON(uuid string, userID uint) ([]byte, error) {
|
||||
// config, err := s.GetByUUID(uuid, userID)
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
//
|
||||
// export := ConfigExport{
|
||||
// Name: config.Name,
|
||||
// Notes: config.Notes,
|
||||
// Items: config.Items,
|
||||
// }
|
||||
//
|
||||
// return json.MarshalIndent(export, "", " ")
|
||||
// }
|
||||
//
|
||||
// func (s *ConfigurationService) ImportJSON(userID uint, data []byte) (*models.Configuration, error) {
|
||||
// var export ConfigExport
|
||||
// if err := json.Unmarshal(data, &export); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
//
|
||||
// req := &CreateConfigRequest{
|
||||
// Name: export.Name,
|
||||
// Notes: export.Notes,
|
||||
// Items: export.Items,
|
||||
// }
|
||||
//
|
||||
// return s.Create(userID, req)
|
||||
// }
|
||||
+109
-85
@@ -88,15 +88,18 @@ type ProjectPricingExportConfig struct {
|
||||
}
|
||||
|
||||
type ProjectPricingExportRow struct {
|
||||
LotDisplay string
|
||||
VendorPN string
|
||||
Description string
|
||||
Quantity int
|
||||
BOMTotal *float64
|
||||
Estimate *float64
|
||||
Stock *float64
|
||||
Competitor *float64
|
||||
ManualPrice *float64 // proportional share of the user-defined total price
|
||||
LotDisplay string
|
||||
VendorPN string
|
||||
Description string
|
||||
Quantity int
|
||||
BOMTotal *float64
|
||||
Estimate *float64
|
||||
Stock *float64
|
||||
Competitor *float64
|
||||
ManualPrice *float64 // proportional share of the user-defined total price
|
||||
EstimateWorld bool
|
||||
StockWorld bool
|
||||
CompetitorWorld bool
|
||||
}
|
||||
|
||||
// ToCSV writes project export data in the new structured CSV format.
|
||||
@@ -380,7 +383,7 @@ func (s *ExportService) buildPricingExportBlock(cfg *models.Configuration, opts
|
||||
if opts.IncludeBOM && localCfg != nil && len(localCfg.VendorSpec) > 0 {
|
||||
coveredLots := make(map[string]struct{})
|
||||
for _, row := range localCfg.VendorSpec {
|
||||
rowMappings := normalizeLotMappings(row.LotMappings)
|
||||
rowMappings := localdb.NormalizeLotMappings(row.LotMappings)
|
||||
for _, mapping := range rowMappings {
|
||||
coveredLots[mapping.LotName] = struct{}{}
|
||||
}
|
||||
@@ -411,34 +414,41 @@ func (s *ExportService) buildPricingExportBlock(cfg *models.Configuration, opts
|
||||
bomTotal = vendorRowTotal(row)
|
||||
}
|
||||
block.Rows = append(block.Rows, ProjectPricingExportRow{
|
||||
LotDisplay: mapping.LotName,
|
||||
VendorPN: row.VendorPartnumber,
|
||||
Description: description,
|
||||
Quantity: lotQty,
|
||||
BOMTotal: bomTotal,
|
||||
Estimate: computeSingleLotTotal(priceMap, mapping.LotName, lotQty, func(p pricingLevels) *float64 { return p.Estimate }),
|
||||
Stock: computeSingleLotTotal(priceMap, mapping.LotName, lotQty, func(p pricingLevels) *float64 { return p.Stock }),
|
||||
Competitor: computeSingleLotTotal(priceMap, mapping.LotName, lotQty, func(p pricingLevels) *float64 { return p.Competitor }),
|
||||
LotDisplay: mapping.LotName,
|
||||
VendorPN: row.VendorPartnumber,
|
||||
Description: description,
|
||||
Quantity: lotQty,
|
||||
BOMTotal: bomTotal,
|
||||
Estimate: computeSingleLotTotal(priceMap, mapping.LotName, lotQty, func(p pricingLevels) *float64 { return p.Estimate }),
|
||||
Stock: computeSingleLotTotal(priceMap, mapping.LotName, lotQty, func(p pricingLevels) *float64 { return p.Stock }),
|
||||
Competitor: computeSingleLotTotal(priceMap, mapping.LotName, lotQty, func(p pricingLevels) *float64 { return p.Competitor }),
|
||||
EstimateWorld: priceMap[mapping.LotName].EstimateWorld,
|
||||
StockWorld: priceMap[mapping.LotName].StockWorld,
|
||||
CompetitorWorld: priceMap[mapping.LotName].CompetitorWorld,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
for _, item := range cfg.Items {
|
||||
if item.LotName == "" {
|
||||
lot := models.NormalizeLotName(item.LotName)
|
||||
if lot == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := coveredLots[item.LotName]; ok {
|
||||
if _, ok := coveredLots[lot]; ok {
|
||||
continue
|
||||
}
|
||||
estimate := estimateOnlyTotal(priceMap[item.LotName].Estimate, item.UnitPrice, item.Quantity)
|
||||
estimate := estimateOnlyTotal(priceMap[lot].Estimate, item.UnitPrice, item.Quantity)
|
||||
block.Rows = append(block.Rows, ProjectPricingExportRow{
|
||||
LotDisplay: item.LotName,
|
||||
VendorPN: "—",
|
||||
Description: componentDescriptions[item.LotName],
|
||||
Quantity: exportPositiveInt(item.Quantity, 1),
|
||||
Estimate: estimate,
|
||||
Stock: totalForUnitPrice(priceMap[item.LotName].Stock, item.Quantity),
|
||||
Competitor: totalForUnitPrice(priceMap[item.LotName].Competitor, item.Quantity),
|
||||
LotDisplay: lot,
|
||||
VendorPN: "—",
|
||||
Description: componentDescriptions[lot],
|
||||
Quantity: exportPositiveInt(item.Quantity, 1),
|
||||
Estimate: estimate,
|
||||
Stock: totalForUnitPrice(priceMap[lot].Stock, item.Quantity),
|
||||
Competitor: totalForUnitPrice(priceMap[lot].Competitor, item.Quantity),
|
||||
EstimateWorld: priceMap[lot].EstimateWorld && priceMap[lot].Estimate != nil && *priceMap[lot].Estimate > 0,
|
||||
StockWorld: priceMap[lot].StockWorld,
|
||||
CompetitorWorld: priceMap[lot].CompetitorWorld,
|
||||
})
|
||||
}
|
||||
if opts.isDDP() {
|
||||
@@ -465,13 +475,16 @@ func (s *ExportService) buildPricingExportBlock(cfg *models.Configuration, opts
|
||||
}
|
||||
estimate := estimateOnlyTotal(priceMap[item.LotName].Estimate, item.UnitPrice, item.Quantity)
|
||||
block.Rows = append(block.Rows, ProjectPricingExportRow{
|
||||
LotDisplay: item.LotName,
|
||||
VendorPN: "—",
|
||||
Description: componentDescriptions[item.LotName],
|
||||
Quantity: exportPositiveInt(item.Quantity, 1),
|
||||
Estimate: estimate,
|
||||
Stock: totalForUnitPrice(priceMap[item.LotName].Stock, item.Quantity),
|
||||
Competitor: totalForUnitPrice(priceMap[item.LotName].Competitor, item.Quantity),
|
||||
LotDisplay: item.LotName,
|
||||
VendorPN: "—",
|
||||
Description: componentDescriptions[item.LotName],
|
||||
Quantity: exportPositiveInt(item.Quantity, 1),
|
||||
Estimate: estimate,
|
||||
Stock: totalForUnitPrice(priceMap[item.LotName].Stock, item.Quantity),
|
||||
Competitor: totalForUnitPrice(priceMap[item.LotName].Competitor, item.Quantity),
|
||||
EstimateWorld: priceMap[item.LotName].EstimateWorld && priceMap[item.LotName].Estimate != nil && *priceMap[item.LotName].Estimate > 0,
|
||||
StockWorld: priceMap[item.LotName].StockWorld,
|
||||
CompetitorWorld: priceMap[item.LotName].CompetitorWorld,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -584,9 +597,12 @@ func sortItemsByCategory(items []ExportItem, categoryOrder map[string]int) {
|
||||
}
|
||||
|
||||
type pricingLevels struct {
|
||||
Estimate *float64
|
||||
Stock *float64
|
||||
Competitor *float64
|
||||
Estimate *float64
|
||||
Stock *float64
|
||||
Competitor *float64
|
||||
EstimateWorld bool
|
||||
StockWorld bool
|
||||
CompetitorWorld bool
|
||||
}
|
||||
|
||||
func (s *ExportService) resolvePricingTotals(cfg *models.Configuration, localCfg *localdb.LocalConfiguration, opts ProjectPricingExportOptions) map[string]pricingLevels {
|
||||
@@ -620,20 +636,35 @@ func (s *ExportService) resolvePricingTotals(cfg *models.Configuration, localCfg
|
||||
}
|
||||
}
|
||||
|
||||
var worldID *uint
|
||||
if latest, err := s.localDB.GetLatestLocalPricelistBySource("world"); err == nil && latest != nil {
|
||||
worldID = &latest.ServerID
|
||||
}
|
||||
|
||||
estimatePrices := s.batchLookupPrices(estimateID, lots)
|
||||
stockPrices := s.batchLookupPrices(warehouseID, lots)
|
||||
competitorPrices := s.batchLookupPrices(competitorID, lots)
|
||||
worldPrices := s.batchLookupPrices(worldID, lots)
|
||||
|
||||
for _, lot := range lots {
|
||||
level := pricingLevels{}
|
||||
if p, ok := estimatePrices[lot]; ok {
|
||||
level.Estimate = floatPtr(p)
|
||||
} else if p, ok := worldPrices[lot]; ok && p > 0 {
|
||||
level.Estimate = floatPtr(p)
|
||||
level.EstimateWorld = true
|
||||
}
|
||||
if p, ok := stockPrices[lot]; ok {
|
||||
level.Stock = floatPtr(p)
|
||||
} else if p, ok := worldPrices[lot]; ok && p > 0 {
|
||||
level.Stock = floatPtr(p)
|
||||
level.StockWorld = true
|
||||
}
|
||||
if p, ok := competitorPrices[lot]; ok {
|
||||
level.Competitor = floatPtr(p)
|
||||
} else if p, ok := worldPrices[lot]; ok && p > 0 {
|
||||
level.Competitor = floatPtr(p)
|
||||
level.CompetitorWorld = true
|
||||
}
|
||||
result[lot] = level
|
||||
}
|
||||
@@ -656,12 +687,31 @@ func (s *ExportService) batchLookupPrices(serverPricelistID *uint, lots []string
|
||||
return prices
|
||||
}
|
||||
|
||||
// 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 {
|
||||
lots := collectPricingLots(cfg, localCfg, true)
|
||||
if s.localDB == nil || len(lots) == 0 {
|
||||
if s.localDB == nil {
|
||||
return map[string]string{}
|
||||
}
|
||||
descriptions, err := s.localDB.GetLocalComponentDescriptionsByLotNames(lots)
|
||||
|
||||
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{}
|
||||
}
|
||||
@@ -673,7 +723,7 @@ func collectPricingLots(cfg *models.Configuration, localCfg *localdb.LocalConfig
|
||||
out := make([]string, 0)
|
||||
if includeBOM && localCfg != nil {
|
||||
for _, row := range localCfg.VendorSpec {
|
||||
for _, mapping := range normalizeLotMappings(row.LotMappings) {
|
||||
for _, mapping := range localdb.NormalizeLotMappings(row.LotMappings) {
|
||||
if _, ok := seen[mapping.LotName]; ok {
|
||||
continue
|
||||
}
|
||||
@@ -696,28 +746,6 @@ func collectPricingLots(cfg *models.Configuration, localCfg *localdb.LocalConfig
|
||||
return out
|
||||
}
|
||||
|
||||
func normalizeLotMappings(mappings []localdb.VendorSpecLotMapping) []localdb.VendorSpecLotMapping {
|
||||
if len(mappings) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]localdb.VendorSpecLotMapping, 0, len(mappings))
|
||||
for _, mapping := range mappings {
|
||||
lot := strings.TrimSpace(mapping.LotName)
|
||||
if lot == "" {
|
||||
continue
|
||||
}
|
||||
qty := mapping.QuantityPerPN
|
||||
if qty < 1 {
|
||||
qty = 1
|
||||
}
|
||||
out = append(out, localdb.VendorSpecLotMapping{
|
||||
LotName: lot,
|
||||
QuantityPerPN: qty,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func vendorRowTotal(row localdb.VendorSpecItem) *float64 {
|
||||
if row.TotalPrice != nil {
|
||||
return floatPtr(*row.TotalPrice)
|
||||
@@ -728,27 +756,6 @@ func vendorRowTotal(row localdb.VendorSpecItem) *float64 {
|
||||
return floatPtr(*row.UnitPrice * float64(exportPositiveInt(row.Quantity, 1)))
|
||||
}
|
||||
|
||||
func computeMappingTotal(priceMap map[string]pricingLevels, mappings []localdb.VendorSpecLotMapping, pnQty int, selector func(pricingLevels) *float64) *float64 {
|
||||
if len(mappings) == 0 {
|
||||
return nil
|
||||
}
|
||||
total := 0.0
|
||||
hasValue := false
|
||||
qty := exportPositiveInt(pnQty, 1)
|
||||
for _, mapping := range mappings {
|
||||
price := selector(priceMap[mapping.LotName])
|
||||
if price == nil || *price <= 0 {
|
||||
continue
|
||||
}
|
||||
total += *price * float64(qty*mapping.QuantityPerPN)
|
||||
hasValue = true
|
||||
}
|
||||
if !hasValue {
|
||||
return nil
|
||||
}
|
||||
return floatPtr(total)
|
||||
}
|
||||
|
||||
// distributeManualPrice sets ManualPrice on each row proportionally based on the
|
||||
// row's Estimate share. The last row with a price absorbs rounding remainder so
|
||||
// the sum of ManualPrice values always equals manualPrice exactly.
|
||||
@@ -836,6 +843,7 @@ func pricingCSVHeaders(opts ProjectPricingExportOptions) []string {
|
||||
if opts.ManualPrice != nil && *opts.ManualPrice > 0 {
|
||||
headers = append(headers, "Ручная цена")
|
||||
}
|
||||
headers = append(headers, "Заглушка (world)")
|
||||
return headers
|
||||
}
|
||||
|
||||
@@ -865,6 +873,21 @@ func pricingCSVRow(row ProjectPricingExportRow, opts ProjectPricingExportOptions
|
||||
if opts.ManualPrice != nil && *opts.ManualPrice > 0 {
|
||||
record = append(record, formatMoneyValue(row.ManualPrice))
|
||||
}
|
||||
var worldCols []string
|
||||
if opts.IncludeEstimate && row.EstimateWorld {
|
||||
worldCols = append(worldCols, "Estimate")
|
||||
}
|
||||
if opts.IncludeStock && row.StockWorld {
|
||||
worldCols = append(worldCols, "Stock")
|
||||
}
|
||||
if opts.IncludeCompetitor && row.CompetitorWorld {
|
||||
worldCols = append(worldCols, "Конкуренты")
|
||||
}
|
||||
comment := ""
|
||||
if len(worldCols) > 0 {
|
||||
comment = "world: " + strings.Join(worldCols, ", ")
|
||||
}
|
||||
record = append(record, comment)
|
||||
return record
|
||||
}
|
||||
|
||||
@@ -894,6 +917,7 @@ func pricingConfigSummaryRow(cfg ProjectPricingExportConfig, opts ProjectPricing
|
||||
if opts.ManualPrice != nil && *opts.ManualPrice > 0 {
|
||||
record = append(record, formatMoneyValue(opts.ManualPrice))
|
||||
}
|
||||
record = append(record, "")
|
||||
return record
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -423,6 +420,13 @@ func (s *LocalConfigurationService) RefreshPrices(uuid string, ownerUsername str
|
||||
}
|
||||
}
|
||||
|
||||
// Capture fingerprint of the current state before any mutations.
|
||||
preRefreshFP, err := localdb.BuildConfigurationSpecPriceFingerprint(localCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build pre-refresh fingerprint: %w", err)
|
||||
}
|
||||
preRefreshCfg := *localCfg
|
||||
|
||||
// Update prices for all items from pricelist
|
||||
updatedItems := make(localdb.LocalConfigItems, len(localCfg.Items))
|
||||
for i, item := range localCfg.Items {
|
||||
@@ -462,6 +466,18 @@ func (s *LocalConfigurationService) RefreshPrices(uuid string, ownerUsername str
|
||||
localCfg.UpdatedAt = now
|
||||
localCfg.SyncStatus = "pending"
|
||||
|
||||
// Before saving the new prices, snapshot the pre-refresh state so the revision
|
||||
// history shows a clear before/after for every price update.
|
||||
postRefreshFP, err := localdb.BuildConfigurationSpecPriceFingerprint(localCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build post-refresh fingerprint: %w", err)
|
||||
}
|
||||
if preRefreshFP != postRefreshFP {
|
||||
if err := s.snapshotPreRefreshTx(&preRefreshCfg, ownerUsername); err != nil {
|
||||
return nil, fmt.Errorf("snapshot pre-refresh state: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
cfg, err := s.saveWithVersionAndPending(localCfg, "update", ownerUsername)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("refresh prices with version: %w", err)
|
||||
@@ -515,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 {
|
||||
@@ -820,6 +835,13 @@ func (s *LocalConfigurationService) RefreshPricesNoAuth(uuid string, pricelistSe
|
||||
}
|
||||
}
|
||||
|
||||
// Capture fingerprint of the current state before any mutations.
|
||||
preRefreshFP, err := localdb.BuildConfigurationSpecPriceFingerprint(localCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build pre-refresh fingerprint: %w", err)
|
||||
}
|
||||
preRefreshCfg := *localCfg
|
||||
|
||||
// Update prices for all items from pricelist
|
||||
updatedItems := make(localdb.LocalConfigItems, len(localCfg.Items))
|
||||
for i, item := range localCfg.Items {
|
||||
@@ -859,6 +881,18 @@ func (s *LocalConfigurationService) RefreshPricesNoAuth(uuid string, pricelistSe
|
||||
localCfg.UpdatedAt = now
|
||||
localCfg.SyncStatus = "pending"
|
||||
|
||||
// Before saving the new prices, snapshot the pre-refresh state so the revision
|
||||
// history shows a clear before/after for every price update.
|
||||
postRefreshFP, err := localdb.BuildConfigurationSpecPriceFingerprint(localCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build post-refresh fingerprint: %w", err)
|
||||
}
|
||||
if preRefreshFP != postRefreshFP {
|
||||
if err := s.snapshotPreRefreshTx(&preRefreshCfg, ""); err != nil {
|
||||
return nil, fmt.Errorf("snapshot pre-refresh state: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
cfg, err := s.saveWithVersionAndPending(localCfg, "update", "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("refresh prices without auth with version: %w", err)
|
||||
@@ -866,6 +900,16 @@ func (s *LocalConfigurationService) RefreshPricesNoAuth(uuid string, pricelistSe
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// SnapshotCurrentState creates a revision of the current configuration state without modifying it.
|
||||
// Called before a client-side price refresh so the revision history has a clear before/after.
|
||||
func (s *LocalConfigurationService) SnapshotCurrentState(uuid string) error {
|
||||
localCfg, err := s.localDB.GetConfigurationByUUID(uuid)
|
||||
if err != nil {
|
||||
return ErrConfigNotFound
|
||||
}
|
||||
return s.snapshotPreRefreshTx(localCfg, "")
|
||||
}
|
||||
|
||||
// UpdateServerCount updates server count and recalculates total price without creating a new version.
|
||||
func (s *LocalConfigurationService) UpdateServerCount(configUUID string, serverCount int) (*models.Configuration, error) {
|
||||
if serverCount < 1 {
|
||||
@@ -1277,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 {
|
||||
@@ -1432,12 +1510,25 @@ func (s *LocalConfigurationService) appendVersionTx(
|
||||
localCfg *localdb.LocalConfiguration,
|
||||
operation string,
|
||||
createdBy string,
|
||||
) (*localdb.LocalConfigurationVersion, error) {
|
||||
return s.appendVersionTxNote(tx, localCfg, operation, createdBy, "")
|
||||
}
|
||||
|
||||
func (s *LocalConfigurationService) appendVersionTxNote(
|
||||
tx *gorm.DB,
|
||||
localCfg *localdb.LocalConfiguration,
|
||||
operation string,
|
||||
createdBy string,
|
||||
noteOverride string,
|
||||
) (*localdb.LocalConfigurationVersion, error) {
|
||||
snapshot, err := s.buildConfigurationSnapshot(localCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build snapshot: %w", err)
|
||||
}
|
||||
changeNote := fmt.Sprintf("%s via local-first flow", operation)
|
||||
if noteOverride != "" {
|
||||
changeNote = noteOverride
|
||||
}
|
||||
|
||||
var createdByPtr *string
|
||||
if createdBy != "" {
|
||||
@@ -1478,6 +1569,35 @@ func (s *LocalConfigurationService) appendVersionTx(
|
||||
return nil, fmt.Errorf("%w: exceeded retries for %s", ErrVersionConflict, localCfg.UUID)
|
||||
}
|
||||
|
||||
// snapshotPreRefreshTx creates a revision of the current configuration state before a price
|
||||
// refresh so the history clearly shows what existed before prices were updated.
|
||||
// Called only when prices are about to change (fingerprints differ).
|
||||
func (s *LocalConfigurationService) snapshotPreRefreshTx(localCfg *localdb.LocalConfiguration, createdBy string) error {
|
||||
return s.localDB.DB().Transaction(func(tx *gorm.DB) error {
|
||||
var locked localdb.LocalConfiguration
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("uuid = ?", localCfg.UUID).
|
||||
First(&locked).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrConfigNotFound
|
||||
}
|
||||
return fmt.Errorf("lock row for pre-refresh snapshot: %w", err)
|
||||
}
|
||||
|
||||
version, err := s.appendVersionTxNote(tx, localCfg, "update", createdBy, "до обновления цен")
|
||||
if err != nil {
|
||||
return fmt.Errorf("append pre-refresh version: %w", err)
|
||||
}
|
||||
|
||||
if err := tx.Model(&localdb.LocalConfiguration{}).
|
||||
Where("uuid = ?", localCfg.UUID).
|
||||
Update("current_version_id", version.ID).Error; err != nil {
|
||||
return fmt.Errorf("set current_version_id for pre-refresh snapshot: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *LocalConfigurationService) buildConfigurationSnapshot(localCfg *localdb.LocalConfiguration) (string, error) {
|
||||
return localdb.BuildConfigurationSnapshot(localCfg)
|
||||
}
|
||||
@@ -1723,7 +1843,8 @@ func (s *LocalConfigurationService) resolvePricelistID(pricelistID *uint) (*uint
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("pricelist %d not available locally", *pricelistID)
|
||||
// Pricelist not found even after sync — fall back to the latest active one.
|
||||
slog.Warn("pricelist not available locally, falling back to latest active", "server_pricelist_id", *pricelistID)
|
||||
}
|
||||
|
||||
latest, err := s.localDB.GetLatestLocalPricelist()
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -16,14 +17,19 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrProjectNotFound = errors.New("project not found")
|
||||
ErrProjectForbidden = errors.New("access to project forbidden")
|
||||
ErrProjectCodeExists = errors.New("project code and variant already exist")
|
||||
ErrCannotDeleteMainVariant = errors.New("cannot delete main variant")
|
||||
ErrReservedMainVariant = errors.New("variant name 'main' is reserved")
|
||||
ErrCannotRenameMainVariant = errors.New("cannot rename main variant")
|
||||
ErrProjectNotFound = errors.New("project not found")
|
||||
ErrProjectForbidden = errors.New("access to project forbidden")
|
||||
ErrProjectCodeExists = errors.New("project code and variant already exist")
|
||||
ErrCannotDeleteMainVariant = errors.New("cannot delete main variant")
|
||||
ErrReservedMainVariant = errors.New("variant name 'main' is reserved")
|
||||
ErrCannotRenameMainVariant = errors.New("cannot rename main variant")
|
||||
ErrProjectCodeInvalidChars = errors.New("код опти содержит недопустимые символы (разрешены: буквы, цифры, дефис, точка, подчёркивание)")
|
||||
ErrProjectVariantInvalidChars = errors.New("имя варианта содержит недопустимые символы (разрешены: буквы, цифры, дефис, точка, подчёркивание)")
|
||||
)
|
||||
|
||||
// projectCodeRe allows only URL-path-safe characters so project codes can appear directly in URLs.
|
||||
var projectCodeRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
|
||||
|
||||
type ProjectService struct {
|
||||
localDB *localdb.LocalDB
|
||||
}
|
||||
@@ -40,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 {
|
||||
@@ -64,6 +71,9 @@ func (s *ProjectService) Create(ownerUsername string, req *CreateProjectRequest)
|
||||
if code == "" {
|
||||
return nil, fmt.Errorf("project code is required")
|
||||
}
|
||||
if !projectCodeRe.MatchString(code) {
|
||||
return nil, ErrProjectCodeInvalidChars
|
||||
}
|
||||
variant := strings.TrimSpace(req.Variant)
|
||||
if err := validateProjectVariantName(variant); err != nil {
|
||||
return nil, err
|
||||
@@ -106,6 +116,9 @@ func (s *ProjectService) Update(projectUUID, ownerUsername string, req *UpdatePr
|
||||
if code == "" {
|
||||
return nil, fmt.Errorf("project code is required")
|
||||
}
|
||||
if !projectCodeRe.MatchString(code) {
|
||||
return nil, ErrProjectCodeInvalidChars
|
||||
}
|
||||
localProject.Code = code
|
||||
}
|
||||
if req.Variant != nil {
|
||||
@@ -136,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 {
|
||||
@@ -183,6 +199,9 @@ func validateProjectVariantName(variant string) error {
|
||||
if normalizeProjectVariant(variant) == "main" {
|
||||
return ErrReservedMainVariant
|
||||
}
|
||||
if variant != "" && !projectCodeRe.MatchString(variant) {
|
||||
return ErrProjectVariantInvalidChars
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -282,6 +301,24 @@ func (s *ProjectService) GetByUUID(projectUUID, ownerUsername string) (*models.P
|
||||
return localdb.LocalToProject(localProject), nil
|
||||
}
|
||||
|
||||
// GetByCode finds the main variant of a project by its code (case-insensitive).
|
||||
func (s *ProjectService) GetByCode(code string) (*models.Project, error) {
|
||||
localProject, err := s.localDB.GetProjectByCode(code)
|
||||
if err != nil {
|
||||
return nil, ErrProjectNotFound
|
||||
}
|
||||
return localdb.LocalToProject(localProject), nil
|
||||
}
|
||||
|
||||
// GetByCodeAndVariant finds a project by code + variant (both case-insensitive).
|
||||
func (s *ProjectService) GetByCodeAndVariant(code, variant string) (*models.Project, error) {
|
||||
localProject, err := s.localDB.GetProjectByCodeAndVariant(code, variant)
|
||||
if err != nil {
|
||||
return nil, ErrProjectNotFound
|
||||
}
|
||||
return localdb.LocalToProject(localProject), nil
|
||||
}
|
||||
|
||||
func (s *ProjectService) ListConfigurations(projectUUID, ownerUsername, status string) (*ProjectConfigurationsResult, error) {
|
||||
project, err := s.GetByUUID(projectUUID, ownerUsername)
|
||||
if err != nil {
|
||||
|
||||
+66
-87
@@ -18,32 +18,22 @@ var (
|
||||
)
|
||||
|
||||
type QuoteService struct {
|
||||
componentRepo *repository.ComponentRepository
|
||||
pricelistRepo *repository.PricelistRepository
|
||||
localDB *localdb.LocalDB
|
||||
pricingService priceResolver
|
||||
cacheMu sync.RWMutex
|
||||
priceCache map[string]cachedLotPrice
|
||||
cacheTTL time.Duration
|
||||
}
|
||||
|
||||
type priceResolver interface {
|
||||
GetEffectivePrice(lotName string) (*float64, error)
|
||||
pricelistRepo *repository.PricelistRepository
|
||||
localDB *localdb.LocalDB
|
||||
cacheMu sync.RWMutex
|
||||
priceCache map[string]cachedLotPrice
|
||||
cacheTTL time.Duration
|
||||
}
|
||||
|
||||
func NewQuoteService(
|
||||
componentRepo *repository.ComponentRepository,
|
||||
pricelistRepo *repository.PricelistRepository,
|
||||
localDB *localdb.LocalDB,
|
||||
pricingService priceResolver,
|
||||
) *QuoteService {
|
||||
return &QuoteService{
|
||||
componentRepo: componentRepo,
|
||||
pricelistRepo: pricelistRepo,
|
||||
localDB: localDB,
|
||||
pricingService: pricingService,
|
||||
priceCache: make(map[string]cachedLotPrice, 4096),
|
||||
cacheTTL: 10 * time.Second,
|
||||
pricelistRepo: pricelistRepo,
|
||||
localDB: localDB,
|
||||
priceCache: make(map[string]cachedLotPrice, 4096),
|
||||
cacheTTL: 10 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,6 +89,9 @@ type PriceLevelsItem struct {
|
||||
DeltaCompEstimatePct *float64 `json:"delta_comp_estimate_pct"`
|
||||
DeltaCompWhAbs *float64 `json:"delta_comp_wh_abs"`
|
||||
DeltaCompWhPct *float64 `json:"delta_comp_wh_pct"`
|
||||
EstimateFromWorld bool `json:"estimate_from_world"`
|
||||
WarehouseFromWorld bool `json:"warehouse_from_world"`
|
||||
CompetitorFromWorld bool `json:"competitor_from_world"`
|
||||
PriceMissing []string `json:"price_missing"`
|
||||
}
|
||||
|
||||
@@ -111,6 +104,9 @@ func (s *QuoteService) ValidateAndCalculate(req *QuoteRequest) (*QuoteValidation
|
||||
if len(req.Items) == 0 {
|
||||
return nil, ErrEmptyQuote
|
||||
}
|
||||
for i := range req.Items {
|
||||
req.Items[i].LotName = models.NormalizeLotName(req.Items[i].LotName)
|
||||
}
|
||||
|
||||
// Strict local-first path: calculations use local SQLite snapshot regardless of online status.
|
||||
if s.localDB != nil {
|
||||
@@ -172,79 +168,23 @@ func (s *QuoteService) ValidateAndCalculate(req *QuoteRequest) (*QuoteValidation
|
||||
return result, nil
|
||||
}
|
||||
|
||||
if s.componentRepo == nil || s.pricingService == nil {
|
||||
return nil, errors.New("quote calculation not available")
|
||||
}
|
||||
|
||||
result := &QuoteValidationResult{
|
||||
Valid: true,
|
||||
Items: make([]QuoteItem, 0, len(req.Items)),
|
||||
Errors: make([]string, 0),
|
||||
Warnings: make([]string, 0),
|
||||
}
|
||||
|
||||
lotNames := make([]string, len(req.Items))
|
||||
quantities := make(map[string]int)
|
||||
for i, item := range req.Items {
|
||||
lotNames[i] = item.LotName
|
||||
quantities[item.LotName] = item.Quantity
|
||||
}
|
||||
|
||||
components, err := s.componentRepo.GetMultiple(lotNames)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
componentMap := make(map[string]*models.LotMetadata)
|
||||
for i := range components {
|
||||
componentMap[components[i].LotName] = &components[i]
|
||||
}
|
||||
|
||||
var total float64
|
||||
|
||||
for _, reqItem := range req.Items {
|
||||
comp, exists := componentMap[reqItem.LotName]
|
||||
if !exists {
|
||||
result.Valid = false
|
||||
result.Errors = append(result.Errors, "Component not found: "+reqItem.LotName)
|
||||
continue
|
||||
}
|
||||
|
||||
item := QuoteItem{
|
||||
LotName: reqItem.LotName,
|
||||
Quantity: reqItem.Quantity,
|
||||
HasPrice: false,
|
||||
}
|
||||
|
||||
if comp.Lot != nil {
|
||||
item.Description = comp.Lot.LotDescription
|
||||
}
|
||||
if comp.Category != nil {
|
||||
item.Category = comp.Category.Code
|
||||
}
|
||||
|
||||
// Get effective price (override or calculated)
|
||||
price, err := s.pricingService.GetEffectivePrice(reqItem.LotName)
|
||||
if err == nil && price != nil && *price > 0 {
|
||||
item.UnitPrice = *price
|
||||
item.TotalPrice = *price * float64(reqItem.Quantity)
|
||||
item.HasPrice = true
|
||||
total += item.TotalPrice
|
||||
} else {
|
||||
result.Warnings = append(result.Warnings, "No price available for: "+reqItem.LotName)
|
||||
}
|
||||
|
||||
result.Items = append(result.Items, item)
|
||||
}
|
||||
|
||||
result.Total = total
|
||||
return result, nil
|
||||
return nil, errors.New("quote calculation requires local database")
|
||||
}
|
||||
|
||||
func (s *QuoteService) CalculatePriceLevels(req *PriceLevelsRequest) (*PriceLevelsResult, error) {
|
||||
if len(req.Items) == 0 {
|
||||
return nil, ErrEmptyQuote
|
||||
}
|
||||
// Keep original lot names so the response mirrors what the caller sent.
|
||||
// Normalization is applied only for internal DB lookups.
|
||||
originalLotNames := make(map[string]string, len(req.Items))
|
||||
for i := range req.Items {
|
||||
upper := models.NormalizeLotName(req.Items[i].LotName)
|
||||
if _, exists := originalLotNames[upper]; !exists {
|
||||
originalLotNames[upper] = req.Items[i].LotName
|
||||
}
|
||||
req.Items[i].LotName = upper
|
||||
}
|
||||
|
||||
lotNames := make([]string, 0, len(req.Items))
|
||||
seenLots := make(map[string]struct{}, len(req.Items))
|
||||
@@ -302,9 +242,36 @@ func (s *QuoteService) CalculatePriceLevels(req *PriceLevelsRequest) (*PriceLeve
|
||||
}
|
||||
}
|
||||
|
||||
var worldID uint
|
||||
if req.PricelistIDs != nil {
|
||||
if explicitID, ok := req.PricelistIDs[string(models.PricelistSourceWorld)]; ok && explicitID > 0 {
|
||||
worldID = explicitID
|
||||
}
|
||||
}
|
||||
if worldID == 0 && s.pricelistRepo != nil {
|
||||
if latest, err := s.pricelistRepo.GetLatestActiveBySource(string(models.PricelistSourceWorld)); err == nil {
|
||||
worldID = latest.ID
|
||||
}
|
||||
}
|
||||
if worldID == 0 && s.localDB != nil {
|
||||
if localPL, err := s.localDB.GetLatestLocalPricelistBySource(string(models.PricelistSourceWorld)); err == nil && localPL != nil {
|
||||
worldID = localPL.ServerID
|
||||
}
|
||||
}
|
||||
worldPrices := map[string]float64{}
|
||||
if worldID != 0 {
|
||||
if prices, err := s.lookupPricesByPricelistID(worldID, lotNames, req.NoCache); err == nil {
|
||||
worldPrices = prices
|
||||
}
|
||||
}
|
||||
|
||||
for _, reqItem := range req.Items {
|
||||
responseLotName := originalLotNames[reqItem.LotName]
|
||||
if responseLotName == "" {
|
||||
responseLotName = reqItem.LotName
|
||||
}
|
||||
item := PriceLevelsItem{
|
||||
LotName: reqItem.LotName,
|
||||
LotName: responseLotName,
|
||||
Quantity: reqItem.Quantity,
|
||||
PriceMissing: make([]string, 0, 3),
|
||||
}
|
||||
@@ -312,14 +279,26 @@ func (s *QuoteService) CalculatePriceLevels(req *PriceLevelsRequest) (*PriceLeve
|
||||
if p, ok := levelBySource[models.PricelistSourceEstimate].prices[reqItem.LotName]; ok && p > 0 {
|
||||
price := p
|
||||
item.EstimatePrice = &price
|
||||
} else if wp, ok := worldPrices[reqItem.LotName]; ok && wp > 0 {
|
||||
price := wp
|
||||
item.EstimatePrice = &price
|
||||
item.EstimateFromWorld = true
|
||||
}
|
||||
if p, ok := levelBySource[models.PricelistSourceWarehouse].prices[reqItem.LotName]; ok && p > 0 {
|
||||
price := p
|
||||
item.WarehousePrice = &price
|
||||
} else if wp, ok := worldPrices[reqItem.LotName]; ok && wp > 0 {
|
||||
price := wp
|
||||
item.WarehousePrice = &price
|
||||
item.WarehouseFromWorld = true
|
||||
}
|
||||
if p, ok := levelBySource[models.PricelistSourceCompetitor].prices[reqItem.LotName]; ok && p > 0 {
|
||||
price := p
|
||||
item.CompetitorPrice = &price
|
||||
} else if wp, ok := worldPrices[reqItem.LotName]; ok && wp > 0 {
|
||||
price := wp
|
||||
item.CompetitorPrice = &price
|
||||
item.CompetitorFromWorld = true
|
||||
}
|
||||
|
||||
if item.EstimatePrice == nil {
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
func TestCalculatePriceLevels_WithMissingLevel(t *testing.T) {
|
||||
db := newPriceLevelsTestDB(t)
|
||||
repo := repository.NewPricelistRepository(db)
|
||||
service := NewQuoteService(nil, repo, nil, nil)
|
||||
service := NewQuoteService(repo, nil)
|
||||
|
||||
estimate := seedPricelistWithItem(t, repo, "estimate", "CPU_X", 100)
|
||||
_ = estimate
|
||||
@@ -57,7 +57,7 @@ func TestCalculatePriceLevels_WithMissingLevel(t *testing.T) {
|
||||
func TestCalculatePriceLevels_UsesExplicitPricelistIDs(t *testing.T) {
|
||||
db := newPriceLevelsTestDB(t)
|
||||
repo := repository.NewPricelistRepository(db)
|
||||
service := NewQuoteService(nil, repo, nil, nil)
|
||||
service := NewQuoteService(repo, nil)
|
||||
|
||||
olderEstimate := seedPricelistWithItem(t, repo, "estimate", "CPU_Y", 80)
|
||||
seedPricelistWithItem(t, repo, "estimate", "CPU_Y", 90)
|
||||
@@ -82,6 +82,51 @@ func TestCalculatePriceLevels_UsesExplicitPricelistIDs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalculatePriceLevels_WorldFallback(t *testing.T) {
|
||||
db := newPriceLevelsTestDB(t)
|
||||
repo := repository.NewPricelistRepository(db)
|
||||
service := NewQuoteService(repo, nil)
|
||||
|
||||
seedPricelistWithItem(t, repo, "estimate", "CPU_Z", 100)
|
||||
seedPricelistWithItem(t, repo, "world", "CPU_Z", 150)
|
||||
|
||||
result, err := service.CalculatePriceLevels(&PriceLevelsRequest{
|
||||
Items: []struct {
|
||||
LotName string `json:"lot_name"`
|
||||
Quantity int `json:"quantity"`
|
||||
}{
|
||||
{LotName: "CPU_Z", Quantity: 1},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CalculatePriceLevels returned error: %v", err)
|
||||
}
|
||||
item := result.Items[0]
|
||||
|
||||
if item.EstimatePrice == nil || *item.EstimatePrice != 100 {
|
||||
t.Fatalf("expected native estimate 100, got %#v", item.EstimatePrice)
|
||||
}
|
||||
if item.EstimateFromWorld {
|
||||
t.Fatalf("expected estimate_from_world false when native price exists")
|
||||
}
|
||||
|
||||
if item.WarehousePrice == nil || *item.WarehousePrice != 150 {
|
||||
t.Fatalf("expected world-fallback warehouse 150, got %#v", item.WarehousePrice)
|
||||
}
|
||||
if !item.WarehouseFromWorld {
|
||||
t.Fatalf("expected warehouse_from_world true")
|
||||
}
|
||||
if item.CompetitorPrice == nil || *item.CompetitorPrice != 150 {
|
||||
t.Fatalf("expected world-fallback competitor 150, got %#v", item.CompetitorPrice)
|
||||
}
|
||||
if !item.CompetitorFromWorld {
|
||||
t.Fatalf("expected competitor_from_world true")
|
||||
}
|
||||
if len(item.PriceMissing) != 0 {
|
||||
t.Fatalf("expected no price_missing after world fallback, got %#v", item.PriceMissing)
|
||||
}
|
||||
}
|
||||
|
||||
func newPriceLevelsTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -249,6 +249,13 @@ func (s *Service) reportClientSchemaState(mariaDB *gorm.DB, checkedAt time.Time)
|
||||
pricelistItemsCount := s.localDB.CountAllPricelistItems()
|
||||
componentsCount := s.localDB.CountComponents()
|
||||
dbSizeBytes := s.localDB.DBFileSizeBytes()
|
||||
openConfigUUIDs := s.localDB.GetOpenConfigUUIDs()
|
||||
var openConfigUUIDsJSON *string
|
||||
if len(openConfigUUIDs) > 0 {
|
||||
raw, _ := json.Marshal(openConfigUUIDs)
|
||||
s := string(raw)
|
||||
openConfigUUIDsJSON = &s
|
||||
}
|
||||
return mariaDB.Exec(`
|
||||
INSERT INTO qt_client_schema_state (
|
||||
username, hostname, app_version,
|
||||
@@ -257,9 +264,10 @@ func (s *Service) reportClientSchemaState(mariaDB *gorm.DB, checkedAt time.Time)
|
||||
estimate_pricelist_version, warehouse_pricelist_version, competitor_pricelist_version,
|
||||
last_sync_error_code, last_sync_error_text,
|
||||
local_pricelist_count, pricelist_items_count, components_count, db_size_bytes,
|
||||
open_config_uuids,
|
||||
last_checked_at, updated_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
app_version = VALUES(app_version),
|
||||
last_sync_at = VALUES(last_sync_at),
|
||||
@@ -277,6 +285,7 @@ func (s *Service) reportClientSchemaState(mariaDB *gorm.DB, checkedAt time.Time)
|
||||
pricelist_items_count = VALUES(pricelist_items_count),
|
||||
components_count = VALUES(components_count),
|
||||
db_size_bytes = VALUES(db_size_bytes),
|
||||
open_config_uuids = VALUES(open_config_uuids),
|
||||
last_checked_at = VALUES(last_checked_at),
|
||||
updated_at = VALUES(updated_at)
|
||||
`, username, hostname, appmeta.Version(),
|
||||
@@ -285,6 +294,7 @@ func (s *Service) reportClientSchemaState(mariaDB *gorm.DB, checkedAt time.Time)
|
||||
estimateVersion, warehouseVersion, competitorVersion,
|
||||
lastSyncErrorCode, lastSyncErrorText,
|
||||
localPricelistCount, pricelistItemsCount, componentsCount, dbSizeBytes,
|
||||
openConfigUUIDsJSON,
|
||||
checkedAt, checkedAt).Error
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -322,6 +323,12 @@ func (s *Service) NeedSync() (bool, error) {
|
||||
|
||||
// SyncPricelists synchronizes all active pricelists from server to local SQLite
|
||||
func (s *Service) SyncPricelists() (int, error) {
|
||||
s.pricelistMu.Lock()
|
||||
defer s.pricelistMu.Unlock()
|
||||
return s.syncPricelists()
|
||||
}
|
||||
|
||||
func (s *Service) syncPricelists() (int, error) {
|
||||
slog.Info("starting pricelist sync")
|
||||
plSyncStart := time.Now()
|
||||
if _, err := s.EnsureReadinessForSync(); err != nil {
|
||||
@@ -336,6 +343,12 @@ func (s *Service) SyncPricelists() (int, error) {
|
||||
return 0, fmt.Errorf("database not available: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if reportErr := s.reportClientSchemaState(mariaDB, time.Now().UTC()); reportErr != nil {
|
||||
slog.Warn("failed to report client state after pricelist sync", "error", reportErr)
|
||||
}
|
||||
}()
|
||||
|
||||
// Create repository
|
||||
pricelistRepo := repository.NewPricelistRepository(mariaDB)
|
||||
|
||||
@@ -392,6 +405,7 @@ func (s *Service) SyncPricelists() (int, error) {
|
||||
CreatedAt: pl.CreatedAt,
|
||||
SyncedAt: time.Now(),
|
||||
IsUsed: false,
|
||||
IsActive: true,
|
||||
}
|
||||
|
||||
itemCount, err := s.syncNewPricelistSnapshot(localPL)
|
||||
@@ -414,6 +428,12 @@ func (s *Service) SyncPricelists() (int, error) {
|
||||
slog.Info("deleted stale local pricelists", "deleted", removed)
|
||||
}
|
||||
|
||||
// Mirror server-side deactivations: any local pricelist not in the current active set
|
||||
// is marked is_active=false so offline lookups skip it.
|
||||
if err := s.localDB.DeactivateLocalPricelistsNotIn(serverPricelistIDs); err != nil {
|
||||
slog.Warn("failed to deactivate stale local pricelists", "error", err)
|
||||
}
|
||||
|
||||
// Backfill lot_category for used pricelists (older local caches may miss the column values).
|
||||
s.backfillUsedPricelistItemCategories(pricelistRepo, serverPricelistIDs)
|
||||
|
||||
@@ -611,6 +631,56 @@ func (s *Service) backfillUsedPricelistItemCategories(pricelistRepo *repository.
|
||||
}
|
||||
}
|
||||
|
||||
// ListActiveViewersByConfigUUIDs returns a map of configUUID → []username for users
|
||||
// who currently have those configs open (based on the last two sync cycles).
|
||||
func (s *Service) ListActiveViewersByConfigUUIDs(uuids []string) (map[string][]string, error) {
|
||||
if len(uuids) == 0 {
|
||||
return map[string][]string{}, nil
|
||||
}
|
||||
mariaDB, err := s.getDB()
|
||||
if err != nil || mariaDB == nil {
|
||||
return map[string][]string{}, nil
|
||||
}
|
||||
selfUsername := strings.ToLower(strings.TrimSpace(s.localDB.GetDBUser()))
|
||||
|
||||
type row struct {
|
||||
Username string `gorm:"column:username"`
|
||||
OpenConfigJSON string `gorm:"column:open_config_uuids"`
|
||||
}
|
||||
var rows []row
|
||||
if err := mariaDB.Raw(`
|
||||
SELECT username, open_config_uuids
|
||||
FROM qt_client_schema_state
|
||||
WHERE open_config_uuids IS NOT NULL
|
||||
AND open_config_uuids != '[]'
|
||||
AND last_checked_at > NOW() - INTERVAL 10 MINUTE
|
||||
`).Scan(&rows).Error; err != nil {
|
||||
return map[string][]string{}, nil
|
||||
}
|
||||
|
||||
wantSet := make(map[string]struct{}, len(uuids))
|
||||
for _, u := range uuids {
|
||||
wantSet[u] = struct{}{}
|
||||
}
|
||||
|
||||
result := make(map[string][]string)
|
||||
for _, r := range rows {
|
||||
if strings.ToLower(strings.TrimSpace(r.Username)) == selfUsername {
|
||||
continue
|
||||
}
|
||||
var openUUIDs []string
|
||||
if err := json.Unmarshal([]byte(r.OpenConfigJSON), &openUUIDs); err != nil {
|
||||
continue
|
||||
}
|
||||
for _, ou := range openUUIDs {
|
||||
if _, ok := wantSet[ou]; ok {
|
||||
result[ou] = append(result[ou], r.Username)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ListUserSyncStatuses returns users who have recorded a client schema state check.
|
||||
func (s *Service) ListUserSyncStatuses(onlineThreshold time.Duration) ([]UserSyncStatus, error) {
|
||||
mariaDB, err := s.getDB()
|
||||
@@ -764,9 +834,16 @@ func (s *Service) fetchServerPricelistItems(serverPricelistID uint) ([]localdb.L
|
||||
return nil, fmt.Errorf("getting server pricelist items: %w", err)
|
||||
}
|
||||
|
||||
localItems := make([]localdb.LocalPricelistItem, len(serverItems))
|
||||
for i, item := range serverItems {
|
||||
localItems[i] = *localdb.PricelistItemToLocal(&item, 0)
|
||||
seen := make(map[string]struct{}, len(serverItems))
|
||||
localItems := make([]localdb.LocalPricelistItem, 0, len(serverItems))
|
||||
for i := range serverItems {
|
||||
lotName := serverItems[i].LotName
|
||||
if _, dup := seen[lotName]; dup {
|
||||
slog.Warn("duplicate lot_name in server pricelist, skipping", "pricelist_id", serverPricelistID, "lot_name", lotName)
|
||||
continue
|
||||
}
|
||||
seen[lotName] = struct{}{}
|
||||
localItems = append(localItems, *localdb.PricelistItemToLocal(&serverItems[i], 0))
|
||||
}
|
||||
|
||||
return localItems, nil
|
||||
@@ -843,7 +920,7 @@ func (s *Service) SyncPricelistsIfNeeded() error {
|
||||
}
|
||||
|
||||
slog.Info("new pricelists detected, syncing...")
|
||||
_, err = s.SyncPricelists()
|
||||
_, err = s.syncPricelists()
|
||||
if err != nil {
|
||||
return fmt.Errorf("syncing pricelists: %w", err)
|
||||
}
|
||||
@@ -888,7 +965,10 @@ func (s *Service) PushPendingChanges() (int, error) {
|
||||
}
|
||||
|
||||
slog.Info("pushing pending changes", "count", len(changes))
|
||||
pushStart := time.Now()
|
||||
pushed := 0
|
||||
failed := 0
|
||||
var firstErr string
|
||||
var syncedIDs []int64
|
||||
sortedChanges := prioritizeProjectChanges(changes)
|
||||
|
||||
@@ -899,6 +979,10 @@ func (s *Service) PushPendingChanges() (int, error) {
|
||||
slog.Warn("failed to push change", "id", change.ID, "type", change.EntityType, "operation", change.Operation, "error", err)
|
||||
newAttempts := change.Attempts + 1
|
||||
s.localDB.IncrementPendingChangeAttempts(change.ID, err.Error())
|
||||
if firstErr == "" {
|
||||
firstErr = err.Error()
|
||||
}
|
||||
failed++
|
||||
if newAttempts >= maxPendingChangeAttempts {
|
||||
slog.Error("abandoning pending change after max attempts",
|
||||
"id", change.ID, "type", change.EntityType, "op", change.Operation,
|
||||
@@ -919,7 +1003,13 @@ func (s *Service) PushPendingChanges() (int, error) {
|
||||
}
|
||||
}
|
||||
|
||||
slog.Info("pending changes pushed", "pushed", pushed, "failed", len(changes)-pushed)
|
||||
if failed > 0 {
|
||||
s.localDB.AppendSyncLog("changes", "error", firstErr, pushed, pushStart, time.Since(pushStart).Milliseconds())
|
||||
} else {
|
||||
s.localDB.AppendSyncLog("changes", "ok", "", pushed, pushStart, time.Since(pushStart).Milliseconds())
|
||||
}
|
||||
|
||||
slog.Info("pending changes pushed", "pushed", pushed, "failed", failed)
|
||||
return pushed, nil
|
||||
}
|
||||
|
||||
@@ -1606,24 +1696,3 @@ func (s *Service) getConnectionStatus() db.ConnectionStatus {
|
||||
return s.connMgr.GetStatus()
|
||||
}
|
||||
|
||||
// SyncComponentsIfEmpty syncs components from MariaDB when local_components is empty.
|
||||
// Used by the background worker on first run to populate the catalog for new users.
|
||||
func (s *Service) SyncComponentsIfEmpty() error {
|
||||
if s.localDB.CountComponents() > 0 {
|
||||
return nil
|
||||
}
|
||||
mariaDB, err := s.getDB()
|
||||
if err != nil {
|
||||
_ = s.localDB.SetComponentSyncResult("error", err.Error(), time.Now())
|
||||
return err
|
||||
}
|
||||
result, err := s.localDB.SyncComponents(mariaDB)
|
||||
now := time.Now()
|
||||
if err != nil {
|
||||
_ = s.localDB.SetComponentSyncResult("error", err.Error(), now)
|
||||
return err
|
||||
}
|
||||
_ = s.localDB.SetComponentSyncResult("ok", "", now)
|
||||
slog.Info("background sync: initial component sync completed", "synced", result.TotalSynced)
|
||||
return nil
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -80,11 +80,6 @@ func (w *Worker) runSync() {
|
||||
return
|
||||
}
|
||||
|
||||
// Populate component catalog on first run (empty local_components)
|
||||
if err := w.service.SyncComponentsIfEmpty(); err != nil {
|
||||
w.logger.Warn("background sync: initial component sync failed", "error", err)
|
||||
}
|
||||
|
||||
// Push pending changes first
|
||||
pushed, err := w.service.PushPendingChanges()
|
||||
if err != nil {
|
||||
@@ -105,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):
|
||||
@@ -165,7 +167,7 @@ func (s *LocalConfigurationService) ImportVendorWorkspaceToProject(projectUUID s
|
||||
|
||||
if len(imported.DirectItems) > 0 {
|
||||
items = imported.DirectItems
|
||||
estimatePricelist, _ := s.localDB.GetLatestLocalPricelistBySource("estimate")
|
||||
estimatePricelist, _ := localdb.GetLatestLocalPricelistBySourceTx(tx, "estimate")
|
||||
if estimatePricelist != nil {
|
||||
estimatePricelistID = &estimatePricelist.ServerID
|
||||
}
|
||||
@@ -173,7 +175,7 @@ func (s *LocalConfigurationService) ImportVendorWorkspaceToProject(projectUUID s
|
||||
totalPrice = &val
|
||||
} else {
|
||||
var prepErr error
|
||||
groupRows, items, totalPrice, estimatePricelistID, prepErr = s.prepareImportedConfiguration(imported.Rows, imported.ServerCount, bookRepo)
|
||||
groupRows, items, totalPrice, estimatePricelistID, prepErr = s.prepareImportedConfiguration(tx, imported.Rows, imported.ServerCount, bookRepo)
|
||||
if prepErr != nil {
|
||||
return fmt.Errorf("prepare imported configuration group %s: %w", imported.GroupID, prepErr)
|
||||
}
|
||||
@@ -219,7 +221,7 @@ func (s *LocalConfigurationService) ImportVendorWorkspaceToProject(projectUUID s
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *LocalConfigurationService) prepareImportedConfiguration(rows []localdb.VendorSpecItem, serverCount int, bookRepo *repository.PartnumberBookRepository) (localdb.VendorSpec, localdb.LocalConfigItems, *float64, *uint, error) {
|
||||
func (s *LocalConfigurationService) prepareImportedConfiguration(tx *gorm.DB, rows []localdb.VendorSpecItem, serverCount int, bookRepo *repository.PartnumberBookRepository) (localdb.VendorSpec, localdb.LocalConfigItems, *float64, *uint, error) {
|
||||
resolver := NewVendorSpecResolver(bookRepo)
|
||||
resolved, err := resolver.Resolve(append([]localdb.VendorSpecItem(nil), rows...))
|
||||
if err != nil {
|
||||
@@ -242,13 +244,13 @@ func (s *LocalConfigurationService) prepareImportedConfiguration(rows []localdb.
|
||||
canonical = append(canonical, row)
|
||||
}
|
||||
|
||||
estimatePricelist, _ := s.localDB.GetLatestLocalPricelistBySource("estimate")
|
||||
estimatePricelist, _ := localdb.GetLatestLocalPricelistBySourceTx(tx, "estimate")
|
||||
var serverPricelistID *uint
|
||||
if estimatePricelist != nil {
|
||||
serverPricelistID = &estimatePricelist.ServerID
|
||||
}
|
||||
|
||||
items := aggregateVendorSpecToItems(canonical, estimatePricelist, s.localDB)
|
||||
items := aggregateVendorSpecToItemsTx(tx, canonical, estimatePricelist)
|
||||
totalValue := items.Total()
|
||||
if serverCount > 1 {
|
||||
totalValue *= float64(serverCount)
|
||||
@@ -257,7 +259,7 @@ func (s *LocalConfigurationService) prepareImportedConfiguration(rows []localdb.
|
||||
return canonical, items, totalPrice, serverPricelistID, nil
|
||||
}
|
||||
|
||||
func aggregateVendorSpecToItems(spec localdb.VendorSpec, estimatePricelist *localdb.LocalPricelist, local *localdb.LocalDB) localdb.LocalConfigItems {
|
||||
func aggregateVendorSpecToItemsTx(tx *gorm.DB, spec localdb.VendorSpec, estimatePricelist *localdb.LocalPricelist) localdb.LocalConfigItems {
|
||||
if len(spec) == 0 {
|
||||
return localdb.LocalConfigItems{}
|
||||
}
|
||||
@@ -276,8 +278,8 @@ func aggregateVendorSpecToItems(spec localdb.VendorSpec, estimatePricelist *loca
|
||||
sort.Strings(order)
|
||||
|
||||
var priceMap map[string]float64
|
||||
if estimatePricelist != nil && local != nil && len(order) > 0 {
|
||||
priceMap, _ = local.GetLocalPricesForLots(estimatePricelist.ID, order)
|
||||
if estimatePricelist != nil && len(order) > 0 {
|
||||
priceMap, _ = localdb.GetLocalPricesForLotsTx(tx, estimatePricelist.ID, order)
|
||||
}
|
||||
|
||||
items := make(localdb.LocalConfigItems, 0, len(order))
|
||||
@@ -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,35 @@
|
||||
# QuoteForge v2.19
|
||||
|
||||
Дата релиза: 2026-06-23
|
||||
Тег: `v2.19`
|
||||
|
||||
## Что нового
|
||||
|
||||
### Серверно-управляемые настройки конфигуратора
|
||||
|
||||
Типы устройств, структура вкладок и фильтры категорий теперь приезжают с сервера вместо жёстко заданных JS-констант.
|
||||
|
||||
- новая таблица `qt_settings` на стороне сервера (контракт в `bible-local/server-contract-qt-settings.md`);
|
||||
- QF синхронизирует `qt_settings` → `local_qt_settings` (SQLite) после каждой синхронизации компонентов;
|
||||
- новый endpoint `GET /api/configurator-settings` отдаёт четыре настройки: `config_types`, `tab_config`, `always_visible_tabs`, `required_categories`;
|
||||
- при недоступности сервера или отсутствии таблицы QF автоматически использует прежние захардкоженные значения — поведение не меняется.
|
||||
|
||||
### Динамический выбор типа оборудования
|
||||
|
||||
- модальное окно «Новая конфигурация» загружает типы устройств с сервера: названия и количество кнопок определяются в `qt_settings.config_types`;
|
||||
- добавление новых типов устройств не требует обновления QF.
|
||||
|
||||
### Серверно-управляемая фильтрация категорий
|
||||
|
||||
- конфигуратор фильтрует LOT-категории по списку из `qt_settings.config_types[].categories`;
|
||||
- структура вкладок обновляется из `qt_settings.tab_config` (порядок вкладок, подразделы, single-select режим);
|
||||
- бейдж на вкладке при незаполненных обязательных категориях (`qt_settings.required_categories`).
|
||||
|
||||
### Прочее
|
||||
|
||||
- тайтлы страниц переименованы с OFS на QFS.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,29 @@
|
||||
# QuoteForge v2.21
|
||||
|
||||
Дата релиза: 2026-06-25
|
||||
Тег: `v2.21`
|
||||
|
||||
## Что нового
|
||||
|
||||
### Короткие ссылки на проекты и варианты
|
||||
|
||||
- `GET /:code` — редирект на проект по коду опти (регистронезависимо);
|
||||
- `GET /:code/:variant` — редирект на конкретный вариант проекта;
|
||||
- валидация кода опти и имени варианта: только URL-безопасные символы `[A-Za-z0-9._-]` — проверка на бэкенде и в форме с подсказкой `«Используется в URL: /КОД/Вариант»`.
|
||||
|
||||
### Ревизия «до обновления цен»
|
||||
|
||||
При нажатии «Обновить цены» автоматически создаётся ревизия текущего состояния конфигурации до применения новых цен, после чего сохраняется ревизия с обновлёнными ценами. История изменений теперь полная.
|
||||
|
||||
### Исправления
|
||||
|
||||
- Старая цена в итоге конфигурации больше не зачёркивается, если цены фактически не изменились.
|
||||
- Устранён race condition: `SyncPricelists()` теперь защищена мьютексом — параллельный запуск фонового тикера и ручной синхронизации больше не приводит к `UNIQUE constraint failed`.
|
||||
- Дублирующиеся `lot_name` в серверном прайслисте пропускаются при загрузке вместо аварийного завершения синхронизации.
|
||||
- Ошибки отправки конфигураций и проектов на сервер теперь видны в диалоге «Информация о синхронизации» и в support bundle (`sync_log`, тип `changes`).
|
||||
- Состояние клиента (`last_sync_error_code` и др.) отправляется на сервер по завершении синхронизации независимо от её результата.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,23 @@
|
||||
# QuoteForge v2.22
|
||||
|
||||
Дата релиза: 2026-06-26
|
||||
Тег: `v2.22`
|
||||
|
||||
## Что нового
|
||||
|
||||
### Исправления
|
||||
|
||||
- **MB-автокомплит в конфигураторе теперь работает в offline-режиме.** Корневая причина: прайслист мог быть синхронизирован до введения нормализации имён лотов, из-за чего SQLite хранил их в исходном регистре (`MB_AMD_2.Rome_...`). Запрос на поиск цены отправлял уже нормализованное имя (`MB_AMD_2.ROME_...`), `IN`-сравнение в SQLite регистрозависимо — совпадений не было, цена возвращалась как null, и автокомплит показывал пустой список. Все запросы к `local_pricelist_items` по `lot_name` переведены на `UPPER(lot_name)`.
|
||||
|
||||
- **Удалён мёртвый код инференса категории из имени лота.** Функция `getCategoryFromLotName` на фронтенде выводила категорию из префикса лота (`DKC_AFF_A1K` → `DKC`) как fallback. Категория всегда приходит из прайслиста; функция удалена. Позиции без категории корректно попадают во вкладку «Other».
|
||||
|
||||
- **Удалена таблица `local_components` и весь связанный с ней код.** Источник данных для компонентов — только `local_pricelist_items`. Убраны маршрут `POST /api/sync/components`, поля `ComponentsSynced` и `LastComponentSync` в ответах синхронизации.
|
||||
|
||||
- **Support bundle расширен диагностическими файлами:** `latest_pricelist_items.json` (все позиции активного estimate-прайслиста), `autocomplete_lots.json` (позиции по категориям с флагом `has_price`), `local.db` (полная копия SQLite-базы).
|
||||
|
||||
- **Регистронезависимые сравнения lot_name на фронтенде:** Set-коллекции для склада, добавленных позиций и корзины BOM теперь нормализуют ключи через `.toUpperCase()`.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,23 @@
|
||||
# QuoteForge v2.23
|
||||
|
||||
Дата релиза: 2026-06-26
|
||||
Тег: `v2.23`
|
||||
|
||||
## Что нового
|
||||
|
||||
### Исправления
|
||||
|
||||
- **Конфигуратор больше не зависает на «Загрузка...».** При открытии сохранённой конфигурации поле `category` у позиций корзины было `undefined` (в `config.items` хранятся только `lot_name/quantity/unit_price`), что приводило к `TypeError` в JS. Теперь после загрузки `allComponents` корзина обогащается категориями из справочника компонентов.
|
||||
|
||||
- **Регистронезависимые сравнения категорий в конфигураторе.** Все сравнения `category` переведены на хелпер `ciStr()` вместо принудительного `.toUpperCase()` — интерфейс показывает категории как есть, логика сравнения регистронезависима.
|
||||
|
||||
- **Вкладка Other показывает только компоненты без назначенной категории.** Исправлена ошибка при которой компоненты DKC/CTL/ENC попадали в Other при режиме «server»: `ASSIGNED_CATEGORIES` пересобирался из отфильтрованного списка, а не из полного статического. Теперь используется `_allCategories`.
|
||||
|
||||
- **Исправлена ошибка «record not found» при синхронизации проектов.** `UpsertByUUID` передавал ненулевой `ID` в `INSERT … ON DUPLICATE KEY UPDATE`, из-за чего MariaDB разрешала коллизию по первичному ключу чужой строки, не обновляя `uuid`, — последующий `SELECT` не находил запись. Теперь `project.ID` сбрасывается в `0` до вставки.
|
||||
|
||||
- **Устранён бесконечный retry при ошибках синхронизации на стороне сервера.** `RepairPendingChanges` сбрасывал счётчик попыток даже если локальные данные не менялись, что создавало бесконечный цикл при серверных ошибках. Repair-функции теперь возвращают `(bool, error)` и сброс происходит только при `modified=true`.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,15 @@
|
||||
# QuoteForge v2.24
|
||||
|
||||
Дата релиза: 2026-06-26
|
||||
Тег: `v2.24`
|
||||
|
||||
## Что нового
|
||||
|
||||
### Исправления
|
||||
|
||||
- **Исправлен ReferenceError в конфигураторе при выборе компонента в секционированных вкладках (Storage, PCI).** Переменная `sectionCategories` не была определена — опечатка, должно быть `section.categories`. Ошибка возникала при клике на элемент автокомплита во вкладках с секциями.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,17 @@
|
||||
# QuoteForge v2.25
|
||||
|
||||
Дата релиза: 2026-06-29
|
||||
Тег: `v2.25`
|
||||
|
||||
Предыдущий релиз: `v2.24`
|
||||
|
||||
## Ключевые изменения
|
||||
|
||||
- исправлено дублирование позиций в таблице «Цена покупки» и в экспорте CSV: сопоставление LOT между BOM и корзиной теперь регистронезависимое;
|
||||
- нормализация LOT-маппингов BOM сведена в единую каноничную функцию на бэкенде (UPPERCASE + схлопывание дублей) — устранены разошедшиеся копии, дававшие разный результат на фронте и в CSV;
|
||||
- единый источник категории LOT — `local_pricelist_items.lot_category`; удалён неиспользуемый серверный слой управления компонентами/категориями.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,17 @@
|
||||
# QuoteForge v2.26
|
||||
|
||||
Дата релиза: 2026-06-29
|
||||
Тег: `v2.26`
|
||||
|
||||
Предыдущий релиз: `v2.25`
|
||||
|
||||
## Ключевые изменения
|
||||
|
||||
- fix: лоты, отсутствующие в текущем прайслисте, больше не блокируют сохранение конфига и генерацию артикула — такие лоты просто пропускаются;
|
||||
- fix: если прайслист конфига удалён с сервера, автоматически выбирается последний активный;
|
||||
- refactor: удалён мёртвый код qt_lot_metadata;
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,15 @@
|
||||
# QuoteForge v2.27
|
||||
|
||||
Дата релиза: 2026-06-30
|
||||
Тег: `v2.27`
|
||||
|
||||
Предыдущий релиз: `v2.26`
|
||||
|
||||
## Ключевые изменения
|
||||
|
||||
- в таблицах конфигураций появилась иконка глаза — показывает, что конфигурацию сейчас открыл другой пользователь; при наведении виден список имён;
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -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; }
|
||||
@@ -629,11 +630,13 @@
|
||||
|
||||
const totalColor = totalDelta > 0 ? 'text-red-600' : totalDelta < 0 ? 'text-green-600' : 'text-gray-600';
|
||||
const totalArrow = _fmtArrow(r.prevTotal || 0, r.newTotal || 0);
|
||||
const totalPrevHtml = totalDelta !== 0
|
||||
? `<span class="text-gray-400 line-through text-xs mr-1">${_fmtMoneyDiff(r.prevTotal || 0)}</span>`
|
||||
: '';
|
||||
html += `<div class="flex justify-between items-center text-sm bg-gray-50 rounded px-3 py-2 mb-1">
|
||||
<span class="text-gray-600 font-medium">Итог конфигурации</span>
|
||||
<span>
|
||||
<span class="text-gray-400 line-through text-xs mr-1">${_fmtMoneyDiff(r.prevTotal || 0)}</span>
|
||||
<span class="${totalColor} font-semibold">${_fmtMoneyDiff(r.newTotal || 0)}</span>${totalArrow}
|
||||
${totalPrevHtml}<span class="${totalColor} font-semibold">${_fmtMoneyDiff(r.newTotal || 0)}</span>${totalArrow}
|
||||
</span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
@@ -242,6 +242,7 @@ function renderConfigs(configs) {
|
||||
html += '<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Цена (за 1 шт)</th>';
|
||||
html += '<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Кол-во</th>';
|
||||
html += '<th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Сумма</th>';
|
||||
html += '<th class="px-2 py-3 w-8"></th>';
|
||||
html += '<th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Действия</th>';
|
||||
html += '</tr></thead><tbody class="divide-y">';
|
||||
|
||||
@@ -298,6 +299,16 @@ function renderConfigs(configs) {
|
||||
html += '<td class="px-4 py-3 text-sm text-gray-500">' + pricePerUnit + '</td>';
|
||||
html += '<td class="px-4 py-3 text-sm text-gray-500">' + serverCount + '</td>';
|
||||
html += '<td class="px-4 py-3 text-sm text-right">' + total + '</td>';
|
||||
const viewers = c.viewers || [];
|
||||
if (viewers.length > 0) {
|
||||
const names = viewers.map(escapeHtml).join(', ');
|
||||
html += '<td class="px-2 py-3 text-center w-8">';
|
||||
html += '<span title="Открыта: ' + names + '" class="inline-flex items-center justify-center text-blue-500 cursor-default">';
|
||||
html += '<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path></svg>';
|
||||
html += '</span></td>';
|
||||
} else {
|
||||
html += '<td class="px-2 py-3 w-8"></td>';
|
||||
}
|
||||
html += '<td class="px-4 py-3 text-sm text-right space-x-2">';
|
||||
if (configStatusMode === 'archived') {
|
||||
html += '<button onclick="reactivateConfig(\'' + c.uuid + '\')" class="text-emerald-600 hover:text-emerald-800" title="Восстановить">';
|
||||
|
||||
+732
-208
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">
|
||||
@@ -207,9 +207,11 @@
|
||||
</div>
|
||||
<div>
|
||||
<label for="new-variant-value" class="block text-sm font-medium text-gray-700 mb-1">Вариант</label>
|
||||
<input id="new-variant-value" type="text" placeholder="Например: Lenovo"
|
||||
<input id="new-variant-value" type="text" placeholder="Например: B200"
|
||||
pattern="[A-Za-z0-9._-]+"
|
||||
title="Только буквы, цифры, дефис, точка, подчёркивание"
|
||||
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">Оставьте пустым для main нельзя — нужно уникальное значение.</div>
|
||||
<div class="text-xs text-gray-500 mt-1">Буквы, цифры, дефис, точка, подчёркивание. Используется в URL: /КОД/Вариант.</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-6 flex justify-end gap-2">
|
||||
@@ -312,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>
|
||||
@@ -378,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
|
||||
}
|
||||
@@ -395,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;
|
||||
@@ -408,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) {
|
||||
@@ -516,7 +525,16 @@ function renderConfigs(configs) {
|
||||
html += '<td class="px-4 py-3 text-sm text-gray-500"><input type="number" min="1" value="' + serverCount + '" class="w-16 px-1 py-0.5 border rounded text-center text-sm" data-uuid="' + c.uuid + '" data-prev="' + serverCount + '" onchange="updateConfigServerCount(this)"></td>';
|
||||
}
|
||||
html += '<td class="px-4 py-3 text-sm text-right" data-total-uuid="' + c.uuid + '">' + formatMoneyNoDecimals(total) + '</td>';
|
||||
html += '<td class="px-2 py-3 text-sm text-center text-gray-500 w-12">main</td>';
|
||||
const projViewers = c.viewers || [];
|
||||
if (projViewers.length > 0) {
|
||||
const projNames = projViewers.map(escapeHtml).join(', ');
|
||||
html += '<td class="px-2 py-3 text-center w-12">';
|
||||
html += '<span title="Открыта: ' + projNames + '" class="inline-flex items-center justify-center text-blue-500 cursor-default">';
|
||||
html += '<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path></svg>';
|
||||
html += '</span></td>';
|
||||
} else {
|
||||
html += '<td class="px-2 py-3 w-12"></td>';
|
||||
}
|
||||
html += '<td class="px-4 py-3 text-sm text-right whitespace-nowrap"><div class="inline-flex items-center justify-end gap-2">';
|
||||
if (configStatusMode === 'archived') {
|
||||
html += '<button onclick="reactivateConfig(\'' + c.uuid + '\')" class="text-emerald-600 hover:text-emerald-800" title="Восстановить">';
|
||||
@@ -842,6 +860,10 @@ async function createNewVariant() {
|
||||
showToast('Укажите вариант', 'error');
|
||||
return;
|
||||
}
|
||||
if (!/^[A-Za-z0-9._-]+$/.test(variant)) {
|
||||
showToast('Имя варианта содержит недопустимые символы. Разрешены: буквы, цифры, дефис, точка, подчёркивание.', 'error');
|
||||
return;
|
||||
}
|
||||
const payload = {
|
||||
code: code,
|
||||
variant: variant,
|
||||
@@ -1238,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');
|
||||
}
|
||||
@@ -1253,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;
|
||||
@@ -1260,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) {
|
||||
|
||||
@@ -39,12 +39,18 @@
|
||||
<div>
|
||||
<label for="create-project-code" class="block text-sm font-medium text-gray-700 mb-1">Код проекта</label>
|
||||
<input id="create-project-code" type="text" placeholder="Например: OPS-123"
|
||||
pattern="[A-Za-z0-9._-]+"
|
||||
title="Только буквы, цифры, дефис, точка, подчёркивание"
|
||||
class="w-full px-3 py-2 border rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
|
||||
<p class="text-xs text-gray-400 mt-1">Буквы, цифры, дефис, точка, подчёркивание. Код используется в URL.</p>
|
||||
</div>
|
||||
<div>
|
||||
<label for="create-project-variant" class="block text-sm font-medium text-gray-700 mb-1">Вариант (необязательно)</label>
|
||||
<input id="create-project-variant" type="text" placeholder="Например: Lenovo"
|
||||
<input id="create-project-variant" type="text" placeholder="Например: B200"
|
||||
pattern="[A-Za-z0-9._-]*"
|
||||
title="Только буквы, цифры, дефис, точка, подчёркивание"
|
||||
class="w-full px-3 py-2 border rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
|
||||
<p class="text-xs text-gray-400 mt-1">Используется в URL: /КОД/Вариант</p>
|
||||
</div>
|
||||
<div>
|
||||
<label for="create-project-tracker-url" class="block text-sm font-medium text-gray-700 mb-1">Ссылка на трекер</label>
|
||||
@@ -396,6 +402,14 @@ async function createProject() {
|
||||
alert('Введите код проекта');
|
||||
return;
|
||||
}
|
||||
if (!/^[A-Za-z0-9._-]+$/.test(code)) {
|
||||
alert('Код проекта содержит недопустимые символы.\nРазрешены: буквы, цифры, дефис, точка, подчёркивание.');
|
||||
return;
|
||||
}
|
||||
if (variant && !/^[A-Za-z0-9._-]+$/.test(variant)) {
|
||||
alert('Имя варианта содержит недопустимые символы.\nРазрешены: буквы, цифры, дефис, точка, подчёркивание.');
|
||||
return;
|
||||
}
|
||||
const resp = await fetch('/api/projects', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
@@ -411,6 +425,11 @@ async function createProject() {
|
||||
alert('Проект с таким кодом и вариантом уже существует');
|
||||
return;
|
||||
}
|
||||
if (resp.status === 400) {
|
||||
const body = await resp.json().catch(() => ({}));
|
||||
alert(body.error || 'Некорректный запрос');
|
||||
return;
|
||||
}
|
||||
alert('Не удалось создать проект');
|
||||
return;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user