Compare commits
87
Commits
6d4a37df8b
..
v3.48
No files matched your search
@@ -1,4 +1,4 @@
|
||||
.PHONY: build build-release clean test run version install-hooks
|
||||
.PHONY: build build-release clean test run version install-hooks migrate migrate-status migrate-baseline
|
||||
|
||||
# Get version from git
|
||||
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
|
||||
@@ -55,6 +55,24 @@ clean:
|
||||
rm -rf bin/
|
||||
rm -f $(BINARY)
|
||||
|
||||
# Server (MariaDB) migrations — migrations/*.sql tracked in qt_schema_migrations.
|
||||
# Always built from the current source (go run), never a possibly stale bin/ binary.
|
||||
# Uses the connection saved in the local app settings.
|
||||
|
||||
# List migrations with applied/pending state (read-only)
|
||||
migrate-status:
|
||||
go run ./cmd/qfs -migrate-status
|
||||
|
||||
# Apply pending migrations
|
||||
migrate:
|
||||
go run ./cmd/qfs -migrate
|
||||
|
||||
# Record migrations up to UPTO as applied WITHOUT running them (one-time, for a server
|
||||
# whose schema is already current): make migrate-baseline UPTO=033_add_price_quality_to_pricelist_items.sql
|
||||
migrate-baseline:
|
||||
@test -n "$(UPTO)" || (echo "usage: make migrate-baseline UPTO=<file.sql>"; exit 1)
|
||||
go run ./cmd/qfs -migrate-baseline "$(UPTO)"
|
||||
|
||||
# Run tests
|
||||
test:
|
||||
go test -v ./...
|
||||
|
||||
@@ -24,7 +24,8 @@ go run ./cmd/qfs
|
||||
Useful commands:
|
||||
|
||||
```bash
|
||||
go run ./cmd/qfs -migrate
|
||||
make migrate-status
|
||||
make migrate
|
||||
go test ./...
|
||||
go vet ./...
|
||||
make build-release
|
||||
|
||||
@@ -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/`). Обнови в том же коммите, что и код.
|
||||
@@ -19,3 +19,14 @@ var StaticFiles embed.FS
|
||||
func StaticFS() (fs.FS, error) {
|
||||
return fs.Sub(StaticFiles, "web/static")
|
||||
}
|
||||
|
||||
// MigrationFiles contains the MariaDB server migrations (migrations/*.sql), so
|
||||
// `qfs -migrate` works from any directory. Applied via models.RunSQLMigrations.
|
||||
//
|
||||
//go:embed migrations/*.sql
|
||||
var MigrationFiles embed.FS
|
||||
|
||||
// MigrationsFS returns a filesystem rooted at migrations/.
|
||||
func MigrationsFS() (fs.FS, error) {
|
||||
return fs.Sub(MigrationFiles, "migrations")
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package quoteforge
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMigrationsEmbedded(t *testing.T) {
|
||||
migrations, err := MigrationsFS()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := fs.Stat(migrations, "034_add_feature_flags_to_configurations.sql"); err != nil {
|
||||
t.Fatalf("migration 034 not embedded: %v", err)
|
||||
}
|
||||
}
|
||||
+1
-1
Submodule bible updated: 52444350c1...1977730d93.
@@ -30,6 +30,8 @@ Pull-only:
|
||||
- pricelists and pricelist items;
|
||||
- partnumber books and partnumber book items.
|
||||
|
||||
Configuration feature flags — see [Configuration feature flags](#configuration-feature-flags).
|
||||
|
||||
Readiness guard:
|
||||
- every sync push/pull runs a preflight check;
|
||||
- blocked sync returns `423 Locked` with a machine-readable reason;
|
||||
@@ -40,24 +42,69 @@ 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 (Цена продажи).
|
||||
Their column sets differ (see below); the shared per-LOT row expansion/grouping rules apply to both.
|
||||
|
||||
Column order (both tables):
|
||||
Buy table column order:
|
||||
|
||||
```
|
||||
PN вендора | Описание | LOT | Кол-во | Estimate | Склад | Конкуренты | Ручная цена
|
||||
```
|
||||
|
||||
Sale table column order:
|
||||
|
||||
```
|
||||
PN вендора | Описание | LOT | Кол-во | Накидка, % | Цена
|
||||
```
|
||||
|
||||
Sale per-row pricing (`_saleRowPrice`/`recomputeSalePrices` in `index.html`,
|
||||
`applySaleRowPricing` in `internal/services/export.go`):
|
||||
- each row's base is its raw Estimate unit price × qty, unless the table-wide "Ручная
|
||||
цена" input is set — then the base is that row's proportional share of the manual
|
||||
total (same distribution as before this existed, last row absorbs the rounding
|
||||
remainder), overwriting the row's own base rather than filling a separate column;
|
||||
- `Цена = base × (Аплифт к estimate + row's own Накидка% / 100)` — Накидка is a
|
||||
per-row percentage, additive to the table-wide uplift, entered directly in the
|
||||
row's own input; unset rows default to 0% (no change to older configs' totals);
|
||||
negative values are discounts, and the factor is floored at 0 so no price goes
|
||||
negative (`_saleRowPrice` / `applySaleRowPricing`);
|
||||
Склад/Конкуренты are not shown or exported for the Sale table;
|
||||
- per-row Накидка is keyed by `"<vendorPN>::<lot>"` (uppercased, "NONE" when there's
|
||||
no vendor PN) — plain `lot_name` isn't a safe key since the same LOT can appear
|
||||
under more than one vendor-PN group (see row expansion rules below) — and persisted
|
||||
as an additive key, `Notes.pricing_ui.sale_row_markups`, alongside the existing
|
||||
`sale_uplift`/`sale_custom_price`; unknown `Notes` / `pricing_ui` keys are carried
|
||||
through verbatim on save (`loadedNotesExtra` / `loadedPricingUIExtra`) so a client
|
||||
never erases fields added by a newer version (see
|
||||
[decisions/2026-09-15-sale-row-markup-and-minimal-csv.md](decisions/2026-09-15-sale-row-markup-and-minimal-csv.md));
|
||||
- the Sale table's own "Экспорт CSV" button additionally sends
|
||||
`minimal_sale_columns: true` + `sale_row_markups`, which collapses
|
||||
`POST /api/configs/:uuid/export/pricing` output to exactly `LOT;Описание;Кол-во;Цена`
|
||||
(`ProjectPricingExportOptions.MinimalSaleColumns` in `internal/services/export.go`).
|
||||
This is scoped to that one request: Buy export and the project-level bulk export
|
||||
never set it and are unaffected.
|
||||
|
||||
Per-LOT row expansion rules:
|
||||
- each `lot_mappings` entry in a BOM row becomes its own table row with its own quantity and prices;
|
||||
- `baseLot` (resolved LOT without an explicit mapping) is treated as the first sub-row with `quantity_per_pn` from `_getRowLotQtyPerPN`;
|
||||
@@ -74,6 +121,50 @@ Controls terminology:
|
||||
|
||||
CSV export reads PN вендора, Описание, and LOT from `data-vendor-pn`, `data-desc`, `data-lot` row attributes to bypass the rowspan cell offset problem.
|
||||
|
||||
In the colour-optional indicator mode (`app_settings.indicator_mode = "accessible"`, see
|
||||
[03-database.md](03-database.md) and [decisions/2026-08-31-accessible-indicator-mode.md](decisions/2026-08-31-accessible-indicator-mode.md))
|
||||
both tables gain a narrow leading price-quality meter column (per sub-row), the row background
|
||||
tint is removed, `world`-fallback cells show a `W` text marker instead of amber, and the footer
|
||||
total shows a `⚠` prefix instead of red. CSV output is unaffected.
|
||||
|
||||
## Configuration feature flags
|
||||
|
||||
A configuration records which data features it uses in `feature_flags`, so a client
|
||||
that does not know one of them refuses to write it instead of silently dropping data.
|
||||
Rationale: [decisions/2026-09-24-configuration-feature-flags.md](decisions/2026-09-24-configuration-feature-flags.md).
|
||||
|
||||
Storage:
|
||||
- `qt_configurations.feature_flags` / `local_configurations.feature_flags` — JSON array
|
||||
of strings, sorted, no duplicates; empty list is stored as `NULL`
|
||||
(e.g. `["sale_row_markups"]`);
|
||||
- carried in version snapshots; exposed on reads as `feature_flags`, plus
|
||||
`unsupported_features` when this build doesn't know some of them.
|
||||
|
||||
Flag name format:
|
||||
- `lower_snake_case`, ASCII `[a-z0-9_]`, starts with a letter, at most 64 chars;
|
||||
- names the **data** the configuration holds, not the UI or the release:
|
||||
`<area>_<data>` — e.g. `sale_row_markups`, not `new_pricing_tab` or `v3_42`;
|
||||
- a name is permanent: never renamed, never reused for different data, never removed
|
||||
from `configfeatures.known` while any configuration can still carry it;
|
||||
- a change in the *meaning* of existing data that old clients would mis-handle gets a
|
||||
new flag (e.g. `sale_row_markups_v2`), not a silent reinterpretation of the old one.
|
||||
|
||||
Lifecycle:
|
||||
- flags are derived from content on every local write (`configfeatures.Detect`), never
|
||||
sent by the UI; a flag disappears when its data does;
|
||||
- a client refuses any write (local save or sync push) to a configuration carrying a
|
||||
flag missing from its `configfeatures.known`, returns `409 unsupported_config_features`,
|
||||
and the configurator locks itself with a banner listing the raw flag names;
|
||||
- a new data feature that older clients would drop on save must add its flag — to
|
||||
`known`, to `Detect`, and to the registry below — in the same change. Data that old
|
||||
clients round-trip verbatim needs no flag.
|
||||
|
||||
Registry:
|
||||
|
||||
| Flag | Set when | Data | Since |
|
||||
| --- | --- | --- | --- |
|
||||
| `sale_row_markups` | `Notes.pricing_ui.sale_row_markups` has at least one non-zero value | per-row «Накидка, %» on the Sale table (negative = discount) | flag introduced 2026-09-24; data since v3.41 |
|
||||
|
||||
## Configuration versioning
|
||||
|
||||
Configuration revisions are append-only snapshots stored in `local_configuration_versions`.
|
||||
@@ -112,16 +203,21 @@ Configurations have a `config_type` field: `"server"` (default) or `"storage"`.
|
||||
|
||||
Rules:
|
||||
- `config_type` defaults to `"server"` for all existing and new configurations unless explicitly set;
|
||||
- `config_type` is a free-form code (no enum on client or server); every write path — update, clone,
|
||||
clone-from-version, rollback, sync push/pull — must carry it unchanged, including codes this client
|
||||
does not know;
|
||||
- the configurator page is shared for both types; the SW tab is always visible regardless of type;
|
||||
- storage configurations use the same vendor_spec + PN→LOT + pricing flow as server configurations;
|
||||
- storage component categories map to existing tabs: `ENC`/`DKC`/`CTL` → Base, `HIC` → PCI (HIC-карты СХД; `HBA`/`NIC` — серверные, не смешивать), `SSD`/`HDD` → Storage (используют существующие серверные LOT), `ACC` → Accessories (используют существующие серверные LOT), `SW` → SW.
|
||||
- `DKC` = контроллерная полка (модель СХД + тип дисков + кол-во слотов + кол-во контроллеров); `CTL` = контроллер (кэш + встроенные порты); `ENC` = дисковая полка без контроллера.
|
||||
- the available config types and their localized names flow from `qt_settings.config_types` on the server;
|
||||
QF falls back to hardcoded "server/Сервер" and "storage/СХД" when the setting is absent.
|
||||
QF falls back to hardcoded "server/Сервер" and "storage/СХД" when the setting is absent;
|
||||
- every "new configuration" type picker (`/configs` and the project page) renders its buttons from
|
||||
`config_types` — a new type added on the server appears without a client release.
|
||||
|
||||
## 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 +227,108 @@ 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 in the background sync worker (after the pricelist pull) and in the manual full sync
|
||||
(`POST /api/sync/all`); 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;
|
||||
- absent or unparseable settings: `GET /api/configurator-settings` serves the Go-side default for that
|
||||
key only (`internal/handlers/component.go`); this is the single fallback — the configurator page
|
||||
holds no copy of tabs/categories and builds its tab buttons from the served `tab_config`;
|
||||
- `config_types[].categories` is an allowlist: a category absent from all types is shown everywhere;
|
||||
- `qt_categories.name` and `qt_categories.name_ru` are not used by QF runtime; do not depend on them.
|
||||
|
||||
## Article generation
|
||||
|
||||
`internal/article` builds the `article` string (`{MODEL}-{CPU}-{MEM}-{GPU}-{DISK}-{NET}-{PSU}-{SUPPORT}`)
|
||||
from the configuration's `items` + `server_model`.
|
||||
|
||||
- which segment a cart LOT belongs to is decided by its `lot_category`, resolved through
|
||||
`ResolveLotCategories` → `GetLocalComponentCategoriesByLotNames`, i.e. the **component
|
||||
universe** (latest active `world` ∪ `estimate`), the same source the configurator/BOM/pricing
|
||||
tab use. It must **not** be scoped to the configuration's pinned pricelist: a world-only LOT
|
||||
(e.g. `GPU_NV_RTX_PRO_6000D_...`, priced by the world fallback, never added to the estimate
|
||||
pricelist) is a legitimate cart member and still carries a real `lot_category` in `world`.
|
||||
Scoping to one pricelist silently dropped such LOTs from the article. See
|
||||
[decisions/2026-09-01-article-category-from-component-universe.md](decisions/2026-09-01-article-category-from-component-universe.md);
|
||||
- `BuildOptions` no longer takes a pricelist; `POST /api/configs/preview-article` still accepts
|
||||
`pricelist_id` but ignores it;
|
||||
- category comes only from real synced pricelist columns — never inferred from the `lot_name`
|
||||
prefix (the `SVC_` SUPPORT segment is the sole lot_name-pattern exception, see below);
|
||||
- within a segment the model/capacity/speed **token** is still parsed from the `lot_name` —
|
||||
that is the article text itself, not categorization;
|
||||
- when a token can't be parsed (the `lot_name` doesn't fit `{GROUP}_{VENDOR}_{MODEL}[_{SPEC}…]`)
|
||||
the segment carries the LOT's `lot_category` as the token — **never** a bare `UNK`. Such a
|
||||
segment comes back with `Recognized = false` in `BuildResult.Segments`, plus a `Warnings`
|
||||
entry naming the `lot_name`. The configurator highlights the segment (amber) and lists the
|
||||
warnings; create/update/rollback log `WARN "article generation degraded"`. No catalog of real
|
||||
lot_names / model names lives in the repo (`no-hardcoded-vendors`), so only *structural*
|
||||
parse failure is detected, not a wrong-but-well-formed token. See
|
||||
[decisions/2026-09-01-article-degraded-token-visibility.md](decisions/2026-09-01-article-degraded-token-visibility.md).
|
||||
|
||||
## Support as a BOM LOT
|
||||
|
||||
The Base tab's support-level picker adds/replaces a synthetic LOT in `cart` (e.g.
|
||||
`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 (HGX only for SXM/HGX-named GPUs or H100/H200/B200/B300 non-PCIe; PCIe GPUs like A30 stay x86)
|
||||
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.
|
||||
|
||||
+42
-16
@@ -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 |
|
||||
@@ -18,15 +17,18 @@ Main tables:
|
||||
| `local_partnumber_book_items` | PN -> LOT catalog payload |
|
||||
| `pending_changes` | sync queue |
|
||||
| `connection_settings` | encrypted MariaDB connection settings |
|
||||
| `app_settings` | local app state |
|
||||
| `app_settings` | local app state (key→value); includes `indicator_mode` = `color` \| `accessible`, a per-client display preference set on `/setup` |
|
||||
| `local_schema_migrations` | applied local migration markers |
|
||||
| `local_qt_settings` | server-pushed configurator settings cache (from `qt_settings`) |
|
||||
|
||||
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,9 +53,11 @@ 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`)
|
||||
- `qt_schema_migrations` — server migration history (applied via `make migrate`, see [Migrations](#migrations))
|
||||
- `qt_scheduler_runs` — server background job tracking (no Go code references it in this repo)
|
||||
|
||||
### Competitor subsystem (server-side only, not used by QuoteForge Go code)
|
||||
@@ -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,9 @@ 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 "Цена" |
|
||||
| feature_flags | JSON NULL | added by migration 034. Data features the configuration uses (`["sale_row_markups"]`); derived on save, a client refuses to write a config with a flag it doesn't know. See [decisions/2026-09-24-configuration-feature-flags.md](decisions/2026-09-24-configuration-feature-flags.md) |
|
||||
|
||||
### qt_lot_metadata
|
||||
PK: lot_name
|
||||
@@ -253,12 +258,17 @@ 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 visual scale lives in **one shared JS module**, `web/static/price-quality.js` (loaded by `base.html` for every page) — `priceQualityColor`/`priceQualityLevel`/`qualityMeterHtml`/`qualityDotHtml`/`qualityBadgeHtml`/`qualityRowStyle`. Do not reimplement the scale locally in a template; add a new helper to that module instead. Used in: pricelist detail "Качество" column, configurator search dropdown, configurator table (leftmost quality column), pricing tab.
|
||||
|
||||
The module has **two render modes**, chosen per client by `window.QF_INDICATOR_MODE` (injected by `base.html` from `app_settings.indicator_mode`, default `color`): `color` = hue scale red 0 → yellow 5 → green 9; `accessible` = colour-blind-safe 5-step signal-strength meter (`priceQualityLevel`: `0-1/2-3/4-5/6-7/8-9`), single neutral hue. In `accessible` mode the pricing tab drops the row background tint for a leading meter column, the `world`-fallback amber cell tint becomes a `W` text marker, and the "contaminated total" red becomes a `⚠` prefix — see [decisions/2026-08-31-accessible-indicator-mode.md](decisions/2026-08-31-accessible-indicator-mode.md). Any new colour-only signal must add a branch in this module keyed on `isAccessible()`, not a local one.
|
||||
|
||||
The real table also has `price_method`, `price_period_days`, `price_coefficient`, `manual_price`, `meta_prices` and `lead_time_weeks` columns, owned and written by the external pricing engine that maintains `qt_pricelist_items` — **keep them in the table for backward compatibility with that system; QF must never drop, rename, or write to them.** QF itself does not model, sync, or display any of them (tried once, removed as unused/dead in the client). Do not re-add them to `models.PricelistItem`/`LocalPricelistItem` without a concrete UI need.
|
||||
|
||||
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 +303,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 | |
|
||||
|
||||
@@ -416,5 +427,20 @@ SQLite:
|
||||
- local migration state is tracked in `local_schema_migrations`.
|
||||
|
||||
MariaDB:
|
||||
- SQL files live in `migrations/`;
|
||||
- they are applied by `go run ./cmd/qfs -migrate`.
|
||||
- SQL files live in `migrations/` (embedded into the binary), one file per change,
|
||||
`NNN_short_topic.sql`, with the recovery/verify header used by the existing files;
|
||||
filenames containing `local_` are SQLite-only and skipped;
|
||||
- applied state is tracked per filename in `qt_schema_migrations`;
|
||||
- commands (always from current source — never run a `bin/` binary of unknown age):
|
||||
- `make migrate-status` (`qfs -migrate-status`) — list applied/pending, read-only;
|
||||
- `make migrate` (`qfs -migrate`) — apply pending files in filename order, then exit;
|
||||
refuses when `qt_schema_migrations` has no applied rows at all (every file would re-run);
|
||||
- `make migrate-baseline UPTO=<file.sql>` (`qfs -migrate-baseline`) — record files up to
|
||||
`UPTO` as applied **without running them**, for a server whose schema is already current;
|
||||
- migrations use their own connection without read/write timeouts (`openMigrationDB`),
|
||||
not the app's 3s-timeout sync connection — a long backfill must not be cut mid-file;
|
||||
- a file is recorded only after all its statements succeed, so each file must be safe to
|
||||
re-run (`ADD COLUMN IF NOT EXISTS`, idempotent `UPDATE ... WHERE <not yet done>`);
|
||||
- there is no GORM `AutoMigrate` against MariaDB: it retypes production columns to match the
|
||||
running binary's models. On 2026-09-24 a stale v1.18 binary run with the old AutoMigrate
|
||||
`-migrate` did exactly that, which is why it was removed.
|
||||
+19
-1
@@ -29,6 +29,17 @@
|
||||
|
||||
`POST /api/restart` exists only in `debug` mode.
|
||||
|
||||
## Settings
|
||||
|
||||
| Method | Path | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `GET` | `/api/settings/ui` | read per-client UI display preferences → `{ "indicator_mode": "color" \| "accessible" }` |
|
||||
| `PUT` | `/api/settings/ui` | set `indicator_mode` (body `{ "indicator_mode": ... }`); `422` on an unknown value |
|
||||
|
||||
Stored in `app_settings` (SQLite); no restart. Registered in both the normal and the setup-mode
|
||||
route sets. Consumed by `web/static/price-quality.js` and the pricing tab via a
|
||||
`window.QF_INDICATOR_MODE` global that `base.html` renders from the same setting.
|
||||
|
||||
## Reference data
|
||||
|
||||
| Method | Path | Purpose |
|
||||
@@ -50,7 +61,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 +91,13 @@
|
||||
| `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 |
|
||||
|
||||
Configuration reads include `feature_flags` and, when this build doesn't know some of
|
||||
them, `unsupported_features`. Any write to such a configuration returns `409`
|
||||
`{"code":"unsupported_config_features","unsupported_features":[...],"error":"..."}`
|
||||
(see [decisions/2026-09-24-configuration-feature-flags.md](decisions/2026-09-24-configuration-feature-flags.md)).
|
||||
|
||||
## Projects
|
||||
|
||||
|
||||
@@ -63,7 +63,9 @@ They are stored in SQLite and encrypted with `local_encryption.key` unless `QUOT
|
||||
| `-config <path>` | config file path |
|
||||
| `-localdb <path>` | SQLite path |
|
||||
| `-reset-localdb` | destructive local DB reset |
|
||||
| `-migrate` | apply server migrations and exit |
|
||||
| `-migrate` | apply pending server SQL migrations (`migrations/*.sql`) and exit |
|
||||
| `-migrate-status` | list server SQL migrations with applied/pending state and exit |
|
||||
| `-migrate-baseline <file>` | record server migrations up to `<file>` as applied without running them, and exit |
|
||||
| `-version` | print app version and exit |
|
||||
|
||||
## First run
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
|
||||
```bash
|
||||
go run ./cmd/qfs
|
||||
go run ./cmd/qfs -migrate
|
||||
make migrate-status # server SQL migrations: applied/pending
|
||||
make migrate # apply pending server SQL migrations
|
||||
go run ./cmd/migrate_project_updated_at
|
||||
go test ./...
|
||||
go vet ./...
|
||||
|
||||
@@ -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.
|
||||
@@ -0,0 +1,51 @@
|
||||
# Decision: project-level DDP export uses each configuration's own sale uplift
|
||||
|
||||
**Date:** 2026-08-12
|
||||
**Status:** active
|
||||
|
||||
## Context
|
||||
|
||||
Two code paths produce the same "Ценообразование" (pricing) CSV: exporting a single
|
||||
configuration from `index.html` (`exportPricingCSV`), and exporting an entire project
|
||||
from `project_detail.html` (`exportProject` → `POST /api/projects/:uuid/export` →
|
||||
`ExportProjectPricingCSV`). Both end up in `ExportService.buildPricingExportBlock`.
|
||||
|
||||
Each configuration's "Аплифт к estimate" (`#pricing-uplift-sale` in the pricing tab) is
|
||||
saved per configuration, piggybacked into `Configuration.Notes` as
|
||||
`{"pricing_ui":{"sale_uplift":...}}` (see `serializeConfigNotes`/
|
||||
`restorePricingStateFromNotes` in `index.html`). The single-config export sends this value
|
||||
explicitly as `sale_markup` in the request, so it always applies the right uplift.
|
||||
|
||||
The project-level export modal never had an uplift input and never sent `sale_markup`, so
|
||||
`ProjectPricingExportOptions.SaleMarkup` was always `0`. `buildPricingExportBlock` used to
|
||||
fall back to a single hardcoded `defaultSaleMarkup` (1.3) for every configuration in the
|
||||
project, silently ignoring each configuration's own saved uplift — a bulk DDP export did
|
||||
not match what exporting those same configurations individually would produce.
|
||||
|
||||
## Decision
|
||||
|
||||
`buildPricingExportBlock` resolves the DDP estimate factor per configuration via
|
||||
`ProjectPricingExportOptions.effectiveSaleMarkupFactor(cfg)`:
|
||||
|
||||
- an explicit `opts.SaleMarkup` (only ever sent by the single-config pricing tab, which
|
||||
knows the live-edited value that may not be saved yet) always wins;
|
||||
- otherwise it reads that configuration's own saved uplift from `Notes`
|
||||
(`configSavedSaleUplift`);
|
||||
- otherwise it falls back to `defaultSaleMarkup` (1.3), same as before, for configurations
|
||||
that never had an uplift saved.
|
||||
|
||||
Both `applyDDPMarkup` call sites in `buildPricingExportBlock` (the BOM-driven branch and
|
||||
the plain-items fallback) use this per-configuration factor. Stock/Competitor keep using
|
||||
the fixed `stockCompetitorMarkupFactor` (1.3) — only the Estimate uplift is configurable.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Project-level DDP export now goes through the same "pipeline" as single-config export:
|
||||
each row's Estimate is scaled by that configuration's own saved uplift, not a
|
||||
project-wide constant.
|
||||
- If a future caller needs to force one uplift across an entire project export regardless
|
||||
of individual configs' saved settings, it must do so explicitly via `sale_markup` in the
|
||||
request — do not reintroduce a silent global default that overrides saved per-config
|
||||
values.
|
||||
- `configSavedSaleUplift` only reads `Notes`; it does not fail loudly on malformed/foreign
|
||||
JSON in that field — it just returns 0 and lets the 1.3 fallback apply.
|
||||
@@ -0,0 +1,63 @@
|
||||
# Decision: `indicator_mode` — a colour-optional rendering mode for UI signals
|
||||
|
||||
**Date:** 2026-08-31
|
||||
**Status:** active
|
||||
|
||||
## Context
|
||||
|
||||
Several UI signals were encoded by hue alone and unreadable with a colour-vision deficiency:
|
||||
|
||||
- `price_quality` (0–9) as a red→yellow→green gradient — a dot in the configurator search
|
||||
dropdown and inline before `lot_name`, a coloured number in the pricelist "Качество" column,
|
||||
a full-row background tint on the "Ценообразование" tab;
|
||||
- the amber `world`-fallback price cell tint
|
||||
([2026-07-10-world-pricelist-fallback.md](2026-07-10-world-pricelist-fallback.md));
|
||||
- the red "contaminated total" in the pricing footer
|
||||
([2026-07-24-pricing-total-world-share.md](2026-07-24-pricing-total-world-share.md)).
|
||||
|
||||
The bible has no dedicated accessibility contract, but `table-management` §Icon Semantics,
|
||||
`controls-selection` §Buttons, `go-code-style` §Business Logic Placement and `build-version-display`
|
||||
say the same thing: meaning is never carried by one ambiguous channel — back it with
|
||||
shape / number / explicit `title`+`aria-label`, and keep the indicator visually subordinate.
|
||||
|
||||
## Decision
|
||||
|
||||
One per-client preference, **`app_settings.indicator_mode`** = `color` (default) | `accessible`,
|
||||
set on `/setup` ("Настройки") via `GET`/`PUT /api/settings/ui` (`internal/handlers/settings.go`)
|
||||
— no restart. Deliberately named for the concern (how indicators are rendered), not for the
|
||||
current widget, so future colour-only signals attach to the same switch.
|
||||
|
||||
`internal/handlers/web.go` `render()` and `internal/handlers/setup.go` inject the mode for every
|
||||
page; `base.html` publishes it as `window.QF_INDICATOR_MODE`. `web/static/price-quality.js` is
|
||||
still the single source of the price-quality scale and branches on the mode internally, so its
|
||||
call sites do not change.
|
||||
|
||||
In `accessible` mode:
|
||||
|
||||
- `price_quality` renders as a **5-step signal-strength meter** (`priceQualityLevel` =
|
||||
`min(4, floor(score/2))` → `0-1 / 2-3 / 4-5 / 6-7 / 8-9`), five bars in one neutral hue, each
|
||||
instance carrying `title`/`aria-label` = `Качество цены: N/9`. `qualityDotHtml` and
|
||||
`qualityBadgeHtml` return the meter;
|
||||
- `qualityRowStyle` returns `''` — the pricing tab instead shows the meter in a narrow leading
|
||||
column (conditional `<th>` / `colspan` in `index.html`, per-sub-row `<td>`);
|
||||
- the `world`-fallback amber class is dropped for a `W` superscript text marker on the price
|
||||
(text, not a colour class — `applyCustomPrice`'s colour-stripping regex is a non-issue);
|
||||
- `_setPricingTotal` drops `text-red-600` for a leading `⚠` glyph, on the same trigger as the
|
||||
red (`worldShare > 0`). The hover popup — including the "prices for N of M positions" coverage
|
||||
line — is unchanged in both modes; per 2026-07-24 there is still no colour-coded coverage-only
|
||||
signal, and `accessible` mode does not add one.
|
||||
|
||||
`color` mode is byte-for-byte the previous behaviour.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Default unchanged; nothing moves until a user opts in on `/setup`.
|
||||
- `web/static/price-quality.js` stays the only place that knows the 0–9 scale. Any new
|
||||
colour-coded quality/price signal adds a branch there keyed on `isAccessible()`, never a local
|
||||
reimplementation, and its `accessible` form must be shape/text, not another hue.
|
||||
- The pricing-tab tables have a mode-dependent column count (8 / 9). `index.html` guards the
|
||||
`<th>`, the empty-state `colspan`, the `tfoot` "Итого:" `colspan` and the JS row template on
|
||||
`ACCESSIBLE_MODE` / `{{ eq .IndicatorMode "accessible" }}`. CSV export is untouched — it reads
|
||||
`data-*` row attributes, not cell positions.
|
||||
- New routes `GET`/`PUT /api/settings/ui`, registered in both the normal and setup-mode route
|
||||
sets in `cmd/qfs/main.go`. `render()` nil-guards `localDB` for tests.
|
||||
@@ -0,0 +1,62 @@
|
||||
# Decision: article generation reads lot_category from the component universe, not one pricelist
|
||||
|
||||
**Date:** 2026-09-01
|
||||
**Status:** active
|
||||
|
||||
## Context
|
||||
|
||||
`internal/article/generator.go` classifies each cart LOT into an article segment
|
||||
(CPU / MEM / GPU / DISK / NET / PSU) by its `lot_category`. That category was
|
||||
resolved by `ResolveLotCategories` → `GetLocalLotCategoriesByServerPricelistID`,
|
||||
which queries exactly **one** pricelist — the configuration's pinned
|
||||
`pricelist_id` (an `estimate` pricelist). A segment builder skips any LOT whose
|
||||
category is unknown, so a LOT absent from that one pricelist vanished from the
|
||||
article with no warning.
|
||||
|
||||
`GPU_NV_RTX_PRO_6000D_SERVER_84GB_PCIE` exposed this: it exists only in `world`
|
||||
pricelists (where it correctly carries `lot_category = GPU`) and in no `estimate`
|
||||
pricelist. It was priced (world fallback), exported, and shown in the cart, but
|
||||
dropped from the article.
|
||||
|
||||
This is the same class of bug as
|
||||
[2026-07-24-component-universe-world-union.md](2026-07-24-component-universe-world-union.md):
|
||||
the cart's LOT set is `world` ∪ `estimate`, and no read path may silently drop a
|
||||
LOT that only lives in `world`. Article generation was the one component-reading
|
||||
path still scoped to a single pricelist.
|
||||
|
||||
Deriving the category from the `lot_name` prefix was rejected — it is forbidden by
|
||||
the pricelist-contract rules (`02-architecture.md`, `bible/rules/patterns/`):
|
||||
category comes only from real synced pricelist columns.
|
||||
|
||||
## Decision
|
||||
|
||||
`ResolveLotCategories(local, lotNames)` now calls
|
||||
`LocalDB.GetLocalComponentCategoriesByLotNames`, which reads the component universe
|
||||
(`componentUniverse()` — latest active `world` ∪ `estimate`, estimate wins a
|
||||
collision). The server-pricelist parameter is gone.
|
||||
|
||||
- `article.BuildOptions` no longer has `ServerPricelist`.
|
||||
- `POST /api/configs/preview-article` and the create/update paths still accept
|
||||
`pricelist_id` but ignore it for article purposes.
|
||||
- The `lot_name`-token parsing inside a segment (CPU model, memory size, GPU model,
|
||||
disk capacity, port speed, wattage) still parses the token from the `lot_name` —
|
||||
that produces the article text, it does not categorize. One parser bug was fixed
|
||||
alongside: `parseGPUModel` required the model-number token to be all digits
|
||||
(`isNumeric`), so `RTX_PRO_6000D` lost its `D` and collapsed to `RTX_84GB` —
|
||||
indistinguishable from a real `RTX` card and different from its sibling
|
||||
`RTX_PRO_6000` → `RTX6000_96GB`. It now accepts a digit-first alphanumeric token
|
||||
(`isModelNumber`), giving `RTX6000D_84GB`.
|
||||
|
||||
## Consequences
|
||||
|
||||
- A world-only LOT lands in the article with its real category. Article generation
|
||||
no longer depends on which pricelist a LOT was added to.
|
||||
- The article can shift if the latest active `world`/`estimate` pricelist
|
||||
recategorizes a LOT — acceptable, and consistent with how the configurator's
|
||||
category tabs already behave.
|
||||
- `GetLocalLotCategoriesByServerPricelistID` still exists and is still used by
|
||||
`services/rental.go` and `services/export.go`. Those paths have the same
|
||||
single-pricelist blind spot for world-only LOTs; migrating them is out of scope
|
||||
here but should follow the same direction.
|
||||
- Covered by `TestResolveLotCategories_WorldOnlyLot` in
|
||||
`internal/article/categories_test.go`.
|
||||
@@ -0,0 +1,66 @@
|
||||
# Decision: unparsed article tokens degrade to a visible category placeholder, never "UNK"
|
||||
|
||||
**Date:** 2026-09-01
|
||||
**Status:** active
|
||||
|
||||
## Context
|
||||
|
||||
`internal/article` builds each segment by parsing a spec token out of the `lot_name`
|
||||
(CPU model, memory size, GPU model, disk capacity, port speed, wattage). When a
|
||||
`lot_name` did not match the expected shape the generator failed silently or
|
||||
misleadingly:
|
||||
|
||||
- `parseCPUModel` / `parseGPUModel` fell back to `normalizeModelToken` or a literal
|
||||
`"UNK"` with **no signal** — and a partial parse (`RTX_PRO_6000D` → `RTX_84GB`)
|
||||
produced a plausible but wrong token indistinguishable from a real result;
|
||||
- `NET` / `PSU` emitted `UNKNET` / `UNKPSU`;
|
||||
- `MEM` / `DISK` dropped the segment or the capacity and emitted only a terse
|
||||
`mem_unknown` / `disk_unknown` warning;
|
||||
- `BuildResult.Warnings` existed but **nothing consumed it**: the `preview-article`
|
||||
frontend ignored the field and the create/update paths discarded it.
|
||||
|
||||
So a new naming shape (a vendor renames a card family, moves memory ahead of the
|
||||
model, glues an architecture onto the token) would silently produce a wrong or
|
||||
truncated article and no one would notice.
|
||||
|
||||
A vendor/model catalog in the repo to validate tokens against was rejected — it
|
||||
violates `bible/rules/patterns/no-hardcoded-vendors` and needs constant upkeep.
|
||||
Detection is therefore limited to **structural** failure (the name doesn't fit
|
||||
`{GROUP}_{VENDOR}_{MODEL}[_{SPEC}…]`); semantic drift where a wrong token still
|
||||
parses cleanly cannot be caught automatically and is out of scope.
|
||||
|
||||
## Decision
|
||||
|
||||
1. `"UNK"` / `"UNKNET"` / `"UNKPSU"` are gone. When a spec token can't be parsed the
|
||||
article carries the LOT's `lot_category` as the token (`4xGPU`, `2xCPU`,
|
||||
`768G+MEM`, …) via `placeholderToken`.
|
||||
2. Each `build*Segment` returns a `segmentResult{value, degraded, warnings}`. Every
|
||||
degraded segment produces a warning that **names the offending `lot_name`** and
|
||||
states which category was written instead.
|
||||
3. `BuildResult` gains `Segments []ResultSegment{Group, Text, Recognized}`.
|
||||
`Recognized == false` marks a segment whose token is a placeholder.
|
||||
4. `parseCPUModel` / `parseGPUModel` return `(token, ok)`; `ok == false` on the
|
||||
last-ditch fallback path.
|
||||
5. Consumers surface it:
|
||||
- `POST /api/configs/preview-article` returns `segments` and `warnings`; the
|
||||
configurator's article line renders each not-`recognized` segment highlighted
|
||||
(amber) and lists the warnings beneath it (`renderArticleDisplay` in
|
||||
`web/templates/index.html`);
|
||||
- create / update / rollback log `WARN "article generation degraded"` with the
|
||||
`server_model`, article and warnings.
|
||||
6. No list of real `lot_name`s or model names is committed to the repo — not as a
|
||||
fixture, not as a golden table. Tests use synthetic names only.
|
||||
|
||||
## Consequences
|
||||
|
||||
- An unrecognised LOT is always visible in the UI (highlighted token + warning) and
|
||||
in server logs — never a silent drop or a bare `UNK`.
|
||||
- The stored `article` string still contains only the placeholder token; the
|
||||
`recognized` flags are not persisted (regenerated on next save / preview).
|
||||
- `compressArticle` now returns `[]namedSeg` (the caller re-joins) so the degraded
|
||||
flags survive compression.
|
||||
- Structural detection only: a wrong-but-well-formed token (e.g. a future `GTX`
|
||||
where `RTX` was expected) still passes. Closing that needs a validation source,
|
||||
deferred pending a server-side structured-attribute contract.
|
||||
- Covered by `TestBuild_UnparseableModel_CategoryPlaceholder` and
|
||||
`TestParseGPUModel_VendorLetterSuffix`.
|
||||
@@ -0,0 +1,69 @@
|
||||
# Decision: per-row "Накидка" on the Sale table + minimal Sale CSV columns
|
||||
|
||||
**Date:** 2026-09-15
|
||||
**Status:** active
|
||||
|
||||
## Context
|
||||
|
||||
The Sale (Цена продажи) table only had one table-wide "Аплифт к estimate" multiplier
|
||||
and one table-wide "Ручная цена" override. There was no way to push margin up on
|
||||
individual rows (e.g. scarce GPUs) without changing the uplift for every row, and the
|
||||
table showed Estimate/Склад/Конкуренты/Ручная-цена columns that a sales rep handing a
|
||||
quote to a customer never needed — the actual deliverable is just LOT, Описание, Кол-во,
|
||||
and a final price.
|
||||
|
||||
## Decision
|
||||
|
||||
- The Sale table gains a per-row "Накидка, %" input. Each row's final "Цена" is
|
||||
`base × (Аплифт к estimate + Накидка% / 100)`, where `base` is the row's raw Estimate
|
||||
unit price × qty, or — when the table-wide "Ручная цена" is set — that row's
|
||||
proportional share of the manual total (same last-row-absorbs-remainder distribution
|
||||
the table-wide manual price already used, now overwriting the row's base instead of
|
||||
filling a separate column).
|
||||
- The Sale table's visible/exported columns collapse to
|
||||
`PN вендора | Описание | LOT | Кол-во | Накидка, % | Цена` on screen, and exactly
|
||||
`LOT;Описание;Кол-во;Цена` in its own CSV export. Estimate, Склад, Конкуренты, and
|
||||
the old Ручная-цена column are no longer shown or exported for this table. The Buy
|
||||
table (Цена покупки) is untouched.
|
||||
- Per-row markup is keyed by `"<vendorPN>::<lot>"` (uppercased, `NONE` when there is no
|
||||
vendor PN) — not by `lot_name` alone, since the same LOT can appear under more than
|
||||
one vendor-PN BOM group (see "Per-LOT row expansion rules" in `02-architecture.md`).
|
||||
- Persistence is additive: `Configuration.Notes.pricing_ui` gains a new
|
||||
`sale_row_markups` map alongside the existing `sale_uplift`/`sale_custom_price`, the
|
||||
same JSON-blob-in-`Notes` mechanism established by
|
||||
[2026-08-12-project-export-per-config-sale-uplift.md](2026-08-12-project-export-per-config-sale-uplift.md).
|
||||
Zero/unset rows are omitted from the map entirely.
|
||||
- CSV export: `POST /api/configs/:uuid/export/pricing` gained `minimal_sale_columns`
|
||||
(bool) and `sale_row_markups` (map) request fields, read into
|
||||
`ProjectPricingExportOptions.MinimalSaleColumns`/`SaleRowMarkups`. These are wired
|
||||
**only** in `ExportConfigPricingCSV`, gated on `req.MinimalSaleColumns` being true —
|
||||
the Sale table's own "Экспорт CSV" button is the only caller that sets it. Buy export
|
||||
(basis=fob) and the project-level bulk export (`ExportProjectPricingCSV`) never send
|
||||
it and keep their full existing column sets/output unchanged.
|
||||
- `ProjectPricingExportOptions.ManualPrice`, previously parsed from the request but
|
||||
never actually read into the options struct (a pre-existing dead field), is now wired
|
||||
— but only inside the same `MinimalSaleColumns` gate, so this bug fix does not change
|
||||
Buy-table CSV output for anyone already relying on the old (broken) behavior.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Already-saved configurations are unaffected: `sale_row_markups` absent from `Notes`
|
||||
means every row's markup defaults to 0%, reproducing the exact totals the table
|
||||
produced before this change (uplift-only).
|
||||
- **Correction (2026-09-24):** the original claim that old clients "simply ignore" the
|
||||
new key was wrong. A pre-v3.41 client rebuilds `Notes` from scratch on save
|
||||
(only `buy_custom_price`/`sale_uplift`/`sale_custom_price`), so opening and saving a
|
||||
config in an old client — including the best-effort save on page exit — erases
|
||||
`sale_row_markups` on the server, and the next pull overwrites every other client's
|
||||
local copy. Observed in the field: a markup saved and pushed on 09-22 came back as
|
||||
`null` on the 09-23 pull. From this fix on the client carries unknown `Notes` /
|
||||
`pricing_ui` keys through verbatim, so future additive keys survive a save by the
|
||||
current version; nothing can protect against clients older than this fix — all users
|
||||
must upgrade.
|
||||
- Negative Накидка is allowed (a per-row discount). The factor
|
||||
`uplift + pct/100` is floored at 0 on both client and CSV export, so a large discount
|
||||
gives a zero price instead of a negative one.
|
||||
- If a future caller needs the full-column DDP CSV format with per-row markup applied,
|
||||
it must do so explicitly — `MinimalSaleColumns` intentionally couples "reduced
|
||||
columns" and "per-row markup applied" as one request-level switch rather than two
|
||||
independent options, since the only current caller needs both together.
|
||||
@@ -0,0 +1,58 @@
|
||||
# Decision: per-configuration feature flags — clients refuse to write what they don't understand
|
||||
|
||||
**Date:** 2026-09-24
|
||||
**Status:** active
|
||||
|
||||
## Context
|
||||
|
||||
Configurations are synced last-write-wins, and every client rebuilds a configuration's
|
||||
content from what *it* knows before saving. When a newer client adds data (e.g. the
|
||||
per-row "Накидка" in `Notes.pricing_ui.sale_row_markups`, see
|
||||
[2026-09-15-sale-row-markup-and-minimal-csv.md](2026-09-15-sale-row-markup-and-minimal-csv.md)),
|
||||
an older client that opens and saves the same configuration silently drops it; the drop
|
||||
is pushed to the server and the next pull spreads it to every other client. This
|
||||
happened in the field (a markup pushed on 2026-09-22 came back `null` on the 09-23 pull).
|
||||
A global minimum-app-version gate was considered and rejected: it would block all sync
|
||||
for an outdated client, even for configurations that use no new feature.
|
||||
|
||||
## Decision
|
||||
|
||||
- `qt_configurations.feature_flags` (JSON array of strings, NULL = none; server
|
||||
migration `034`) and `local_configurations.feature_flags` (AutoMigrate) record which
|
||||
data features a configuration uses. Synced like any other column; carried in version
|
||||
snapshots.
|
||||
- `internal/configfeatures` is the single source of truth: `known` (flags this build
|
||||
understands), `Detect(notes)` (derive flags from content), `Unknown`, `Check`,
|
||||
`UnsupportedError`. Current flags: `sale_row_markups` (at least one non-zero row markup).
|
||||
- Flags are **derived** on every local write, never sent by the UI: `saveWithVersionAndPending`,
|
||||
`createWithVersionTx`, `rollbackToVersion`, `UpdateServerCount` first `Check` the flags
|
||||
*as stored* and refuse with `*configfeatures.UnsupportedError` if any is unknown, then set
|
||||
`FeatureFlags = Detect(notes)`. This covers update, rename, move, refresh prices,
|
||||
vendor-spec, rental, server count, deactivate/reactivate, rollback (current and target
|
||||
snapshot) and clone (the clone inherits the original's flags). Project line reorder is
|
||||
exempt: it only touches `line_no` and writes the row back with its flags and notes intact.
|
||||
- Every HTTP handler reports errors via `handlers.RespondError`, which turns an
|
||||
`UnsupportedError` into `409` `{"code":"unsupported_config_features","unsupported_features":[...],"error":"..."}`
|
||||
regardless of the status the caller picked.
|
||||
- Reads expose `unsupported_features` (computed in `LocalToConfiguration`). The
|
||||
configurator shows a red banner listing them, disables "Сохранить", skips the
|
||||
exit-save, and also locks itself when a save comes back with the 409.
|
||||
- Sync push (`pushConfigurationUpdate`) reads the server row first and refuses if its
|
||||
flags are unknown — a newer client may have written it after our last pull. Such a
|
||||
refused change is kept in the queue (it is exempt from the max-attempts abandon) so the
|
||||
local edit is pushed once the app is updated.
|
||||
- Until migration `034` runs, the server write retries without `feature_flags`
|
||||
(`withOptionalColumns` in `internal/repository/configuration.go`, same fallback as
|
||||
`line_no`) and logs a warning — sync keeps working, but flags are not stored on the server.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Rule:** any new data feature that an older client would lose on save must add a
|
||||
flag to `configfeatures.known` and to `Detect` in the same change. Features that old
|
||||
clients round-trip safely (e.g. data they carry verbatim) need no flag.
|
||||
- Flags only protect against clients that already contain this check. Clients older
|
||||
than this change ignore `feature_flags` and can still erase newer data — rollout must
|
||||
get every user onto a version with this check.
|
||||
- Order of rollout: apply server migration `034` before (or together with) releasing
|
||||
the client; otherwise flags silently stay local.
|
||||
- The UI shows raw flag ids (an old client, by definition, has no human names for them).
|
||||
@@ -75,6 +75,8 @@ Update this file in the same commit as any change to the flows below.
|
||||
- `POST /api/sync/push` drains the queue by writing to MariaDB.
|
||||
- If a push fails, `increment_attempts` and `last_error` are updated; row stays in queue.
|
||||
- `RepairPendingChanges` reconciles orphaned changes (configuration/project deleted locally).
|
||||
- Background cycle (`sync.Worker.runSync`) runs independent streams: push (gated by readiness guard), then pricelists, partnumber books, qt_settings. A failure in one stream is logged and never stops the others.
|
||||
- Configurations left `sync_status=pending` with no `pending_changes` row (queue row dropped, e.g. a stale event skipped without marking synced) are re-enqueued as an `update` with the current snapshot at the start of each push (`requeueOrphanedPendingConfigurations`).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ category codes that are allowed for each type. QF uses this for:
|
||||
"MB","CPU","MEM","RAID",
|
||||
"SSD","HDD","M2","EDSFF","HHHL",
|
||||
"GPU","NIC","HCA","DPU","HBA",
|
||||
"PSU","PS","ACC","RISERS","CARD","BB"
|
||||
"PSU","PS","ACC","RISERS","CARD","BB","SFP"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -53,7 +53,7 @@ category codes that are allowed for each type. QF uses this for:
|
||||
"categories": [
|
||||
"DKC","CPU","MEM","PS",
|
||||
"SSD","HDD","M2","EDSFF","HHHL",
|
||||
"NIC","HBA","HCA","ACC","CARD"
|
||||
"NIC","HBA","HCA","ACC","CARD","SFP"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -109,7 +109,16 @@ single-select mode.
|
||||
]
|
||||
},
|
||||
{ "key": "power", "label": "Power", "single_select": false, "categories": ["PS","PSU"] },
|
||||
{ "key": "accessories", "label": "Accessories", "single_select": false, "categories": ["ACC","CARD"] },
|
||||
{
|
||||
"key": "accessories",
|
||||
"label": "Accessories",
|
||||
"single_select": false,
|
||||
"categories": ["ACC","CARD","SFP"],
|
||||
"sections": [
|
||||
{ "title": "Аксессуары", "categories": ["ACC","CARD"] },
|
||||
{ "title": "Трансиверы", "categories": ["SFP"] }
|
||||
]
|
||||
},
|
||||
{ "key": "sw", "label": "SW", "single_select": false, "categories": ["SW"] }
|
||||
]
|
||||
```
|
||||
@@ -126,9 +135,15 @@ contain any items. Other tabs are hidden when empty.
|
||||
**Value format:** JSON string array.
|
||||
|
||||
```json
|
||||
["base", "storage", "pci"]
|
||||
["base"]
|
||||
```
|
||||
|
||||
"Empty" is evaluated after the per-`config_type` category filter, so with only
|
||||
`base` listed a tab such as Storage/PCI shows for a server configuration (its
|
||||
categories have components) and hides for a type whose allowlist excludes all of
|
||||
its categories (e.g. networking). Listing a tab here forces it visible for every
|
||||
config type.
|
||||
|
||||
---
|
||||
|
||||
### `required_categories`
|
||||
@@ -148,13 +163,67 @@ 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": 28000, "3": 77000, "5": 112000},
|
||||
"S": {"1": 39500, "3": 98000, "5": 140000},
|
||||
"P": {"1": 88500, "3": 147000}
|
||||
},
|
||||
"HGX-B200": {
|
||||
"B": {"1": 158500, "3": 230500, "5": 284500},
|
||||
"S": {"1": 176500, "3": 266500, "5": 332500},
|
||||
"P": {"1": 232000, "3": 322000}
|
||||
},
|
||||
"HGX-B300": {
|
||||
"B": {"1": 192000, "3": 270000, "5": 328500},
|
||||
"S": {"1": 211500, "3": 309000, "5": 380500},
|
||||
"P": {"1": 286000, "3": 383500}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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
|
||||
leaves `local_qt_settings` empty. The frontend falls back to hardcoded defaults
|
||||
for all four settings. No crash, no data loss.
|
||||
- If a specific key is absent from `qt_settings`: QF falls back to the hardcoded
|
||||
default for that key only.
|
||||
leaves `local_qt_settings` empty. `GET /api/configurator-settings` then serves
|
||||
the Go-side defaults (`internal/handlers/component.go`, `default*()`) for every
|
||||
setting. No crash, no data loss.
|
||||
- If a specific key is absent from `qt_settings`: the same Go-side default is served
|
||||
for that key only.
|
||||
- The Go-side defaults are the **only** fallback and are not kept in step with the
|
||||
server — change tabs/categories in `qt_settings`, not in code. The configurator page
|
||||
has no JS copy: `TAB_CONFIG` (except "Other") and the tab buttons are built from the
|
||||
served `tab_config`; a config type with no `config_types` allowlist sees all categories.
|
||||
- Old QF clients that do not know about `local_qt_settings` continue to use their
|
||||
hardcoded JS constants unchanged.
|
||||
|
||||
|
||||
+209
-121
@@ -60,7 +60,9 @@ func main() {
|
||||
configPath := flag.String("config", "", "path to config file (default: user state dir or QFS_CONFIG_PATH)")
|
||||
localDBPath := flag.String("localdb", "", "path to local SQLite database (default: user state dir or QFS_DB_PATH)")
|
||||
resetLocalDB := flag.Bool("reset-localdb", false, "reset local SQLite data on startup (keeps connection settings)")
|
||||
migrate := flag.Bool("migrate", false, "run database migrations")
|
||||
migrate := flag.Bool("migrate", false, "apply pending server (MariaDB) SQL migrations and exit")
|
||||
migrateStatus := flag.Bool("migrate-status", false, "list server SQL migrations with applied/pending state and exit")
|
||||
migrateBaseline := flag.String("migrate-baseline", "", "record server SQL migrations up to and including this file as applied, without running them, and exit")
|
||||
version := flag.Bool("version", false, "show version information")
|
||||
flag.Parse()
|
||||
|
||||
@@ -168,6 +170,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",
|
||||
@@ -178,26 +187,25 @@ func main() {
|
||||
"online", false,
|
||||
)
|
||||
|
||||
if *migrate {
|
||||
mariaDB, err := connMgr.GetDB()
|
||||
if *migrate || *migrateStatus || *migrateBaseline != "" {
|
||||
mariaDB, err := openMigrationDB(local)
|
||||
if err != nil {
|
||||
slog.Error("cannot run migrations: database not available", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if mariaDB == nil {
|
||||
slog.Error("cannot run migrations: database not available")
|
||||
switch {
|
||||
case *migrateStatus:
|
||||
err = runMigrateStatus(mariaDB)
|
||||
case *migrateBaseline != "":
|
||||
err = runMigrateBaseline(mariaDB, *migrateBaseline)
|
||||
default:
|
||||
err = runMigrateApply(mariaDB)
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("migration command failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
slog.Info("running database migrations...")
|
||||
if err := models.Migrate(mariaDB); err != nil {
|
||||
slog.Error("migration failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := models.SeedCategories(mariaDB); err != nil {
|
||||
slog.Error("seeding categories failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
slog.Info("migrations completed")
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
gin.SetMode(cfg.Server.Mode)
|
||||
@@ -272,6 +280,8 @@ func main() {
|
||||
syncWorker.Stop()
|
||||
workerCancel()
|
||||
backupCancel()
|
||||
connMgr.Stop()
|
||||
connMgrCancel()
|
||||
|
||||
// Then shutdown HTTP server
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
@@ -572,6 +582,10 @@ func runSetupMode(local *localdb.LocalDB) {
|
||||
router.POST("/setup/test", setupHandler.TestConnection)
|
||||
router.GET("/setup/status", setupHandler.GetStatus)
|
||||
|
||||
settingsHandler := handlers.NewSettingsHandler(local)
|
||||
router.GET("/api/settings/ui", settingsHandler.GetUI)
|
||||
router.PUT("/api/settings/ui", settingsHandler.PutUI)
|
||||
|
||||
// Health check
|
||||
router.GET("/health", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
@@ -677,8 +691,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 +702,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 +789,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)
|
||||
@@ -883,6 +897,11 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
router.POST("/setup/test", setupHandler.TestConnection)
|
||||
router.GET("/setup/status", setupHandler.GetStatus)
|
||||
|
||||
// Per-client UI display preferences
|
||||
settingsHandler := handlers.NewSettingsHandler(local)
|
||||
router.GET("/api/settings/ui", settingsHandler.GetUI)
|
||||
router.PUT("/api/settings/ui", settingsHandler.PutUI)
|
||||
|
||||
// Web pages
|
||||
router.GET("/", webHandler.Index)
|
||||
router.GET("/configs", webHandler.Configs)
|
||||
@@ -894,7 +913,7 @@ 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 URL: /:code → redirect to /projects/:uuid
|
||||
// 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)
|
||||
@@ -904,6 +923,16 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
}
|
||||
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")
|
||||
@@ -987,8 +1016,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,
|
||||
@@ -1039,6 +1087,7 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"article": result.Article,
|
||||
"segments": result.Segments,
|
||||
"warnings": result.Warnings,
|
||||
})
|
||||
})
|
||||
@@ -1063,16 +1112,11 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
|
||||
config, err := configService.UpdateNoAuth(uuid, &req)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, services.ErrConfigNotFound):
|
||||
respondError(c, http.StatusNotFound, "resource not found", err)
|
||||
case errors.Is(err, services.ErrProjectNotFound):
|
||||
respondError(c, http.StatusNotFound, "resource not found", err)
|
||||
case errors.Is(err, services.ErrProjectForbidden):
|
||||
respondError(c, http.StatusForbidden, "access denied", err)
|
||||
default:
|
||||
respondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
}
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
|
||||
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
|
||||
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1179,16 +1223,11 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
}
|
||||
updated, err := configService.SetProjectNoAuth(uuid, req.ProjectUUID)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, services.ErrConfigNotFound):
|
||||
respondError(c, http.StatusNotFound, "resource not found", err)
|
||||
case errors.Is(err, services.ErrProjectNotFound):
|
||||
respondError(c, http.StatusNotFound, "resource not found", err)
|
||||
case errors.Is(err, services.ErrProjectForbidden):
|
||||
respondError(c, http.StatusForbidden, "access denied", err)
|
||||
default:
|
||||
respondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
}
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
|
||||
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
|
||||
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
|
||||
)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, updated)
|
||||
@@ -1307,6 +1346,39 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
configs.POST("/:uuid/vendor-spec/resolve", vendorSpecHandler.ResolveVendorSpec)
|
||||
configs.POST("/:uuid/vendor-spec/apply", vendorSpecHandler.ApplyVendorSpec)
|
||||
|
||||
// Rental / paid-testing pricing endpoints (Аренда tab)
|
||||
configs.PUT("/:uuid/rental", func(c *gin.Context) {
|
||||
var req services.RentalUpdateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
respondError(c, http.StatusBadRequest, "invalid request", err)
|
||||
return
|
||||
}
|
||||
config, err := configService.UpdateRentalNoAuth(c.Param("uuid"), &req)
|
||||
if err != nil {
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
|
||||
)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, config)
|
||||
})
|
||||
|
||||
configs.POST("/:uuid/rental/calculate", func(c *gin.Context) {
|
||||
var req services.RentalUpdateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
respondError(c, http.StatusBadRequest, "invalid request", err)
|
||||
return
|
||||
}
|
||||
result, err := rentalService.Calculate(c.Param("uuid"), &req)
|
||||
if err != nil {
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
|
||||
)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, result)
|
||||
})
|
||||
|
||||
configs.PATCH("/:uuid/server-count", func(c *gin.Context) {
|
||||
uuid := c.Param("uuid")
|
||||
var req struct {
|
||||
@@ -1323,6 +1395,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")
|
||||
@@ -1503,27 +1585,43 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
|
||||
// Return simplified list of all projects (UUID + Name only)
|
||||
type ProjectSimple struct {
|
||||
UUID string `json:"uuid"`
|
||||
Code string `json:"code"`
|
||||
Variant string `json:"variant"`
|
||||
Name string `json:"name"`
|
||||
IsActive bool `json:"is_active"`
|
||||
UUID string `json:"uuid"`
|
||||
Code string `json:"code"`
|
||||
Variant string `json:"variant"`
|
||||
Name string `json:"name"`
|
||||
IsActive bool `json:"is_active"`
|
||||
RentalEnabled bool `json:"rental_enabled"`
|
||||
ShowStockPrices bool `json:"show_stock_prices"`
|
||||
OnlyInStock bool `json:"only_in_stock"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
simplified := make([]ProjectSimple, 0, len(allProjects))
|
||||
for _, p := range allProjects {
|
||||
simplified = append(simplified, ProjectSimple{
|
||||
UUID: p.UUID,
|
||||
Code: p.Code,
|
||||
Variant: p.Variant,
|
||||
Name: derefString(p.Name),
|
||||
IsActive: p.IsActive,
|
||||
UUID: p.UUID,
|
||||
Code: p.Code,
|
||||
Variant: p.Variant,
|
||||
Name: derefString(p.Name),
|
||||
IsActive: p.IsActive,
|
||||
RentalEnabled: p.RentalEnabled,
|
||||
ShowStockPrices: p.ShowStockPrices,
|
||||
OnlyInStock: p.OnlyInStock,
|
||||
CreatedAt: p.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, simplified)
|
||||
})
|
||||
|
||||
// ProjectWithWarning flattens a project's fields (via embedding) alongside an
|
||||
// optional variant_warning, set when an invalid variant name (reserved "main" or
|
||||
// disallowed characters) was auto-converted into a valid one instead of rejected.
|
||||
type ProjectWithWarning struct {
|
||||
*models.Project
|
||||
VariantWarning string `json:"variant_warning,omitempty"`
|
||||
}
|
||||
|
||||
projects.POST("", func(c *gin.Context) {
|
||||
var req services.CreateProjectRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
@@ -1534,33 +1632,24 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "project code is required"})
|
||||
return
|
||||
}
|
||||
project, err := projectService.Create(dbUsername, &req)
|
||||
project, variantWarning, err := projectService.Create(dbUsername, &req)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, services.ErrReservedMainVariant),
|
||||
errors.Is(err, services.ErrProjectCodeInvalidChars):
|
||||
respondError(c, http.StatusBadRequest, "invalid request", err)
|
||||
case errors.Is(err, services.ErrProjectCodeExists):
|
||||
respondError(c, http.StatusConflict, "conflict detected", err)
|
||||
default:
|
||||
respondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
}
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrProjectCodeInvalidChars, http.StatusBadRequest, "invalid request"},
|
||||
errCase{services.ErrProjectCodeExists, http.StatusConflict, "conflict detected"},
|
||||
)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, project)
|
||||
c.JSON(http.StatusCreated, ProjectWithWarning{Project: project, VariantWarning: variantWarning})
|
||||
})
|
||||
|
||||
projects.GET("/:uuid", func(c *gin.Context) {
|
||||
project, err := projectService.GetByUUID(c.Param("uuid"), dbUsername)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, services.ErrProjectNotFound):
|
||||
respondError(c, http.StatusNotFound, "resource not found", err)
|
||||
case errors.Is(err, services.ErrProjectForbidden):
|
||||
respondError(c, http.StatusForbidden, "access denied", err)
|
||||
default:
|
||||
respondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
}
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
|
||||
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
|
||||
)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, project)
|
||||
@@ -1572,37 +1661,26 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
respondError(c, http.StatusBadRequest, "invalid request", err)
|
||||
return
|
||||
}
|
||||
project, err := projectService.Update(c.Param("uuid"), dbUsername, &req)
|
||||
project, variantWarning, err := projectService.Update(c.Param("uuid"), dbUsername, &req)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, services.ErrReservedMainVariant),
|
||||
errors.Is(err, services.ErrCannotRenameMainVariant),
|
||||
errors.Is(err, services.ErrProjectCodeInvalidChars):
|
||||
respondError(c, http.StatusBadRequest, "invalid request", err)
|
||||
case errors.Is(err, services.ErrProjectCodeExists):
|
||||
respondError(c, http.StatusConflict, "conflict detected", err)
|
||||
case errors.Is(err, services.ErrProjectNotFound):
|
||||
respondError(c, http.StatusNotFound, "resource not found", err)
|
||||
case errors.Is(err, services.ErrProjectForbidden):
|
||||
respondError(c, http.StatusForbidden, "access denied", err)
|
||||
default:
|
||||
respondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
}
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrCannotRenameMainVariant, http.StatusBadRequest, "invalid request"},
|
||||
errCase{services.ErrProjectCodeInvalidChars, http.StatusBadRequest, "invalid request"},
|
||||
errCase{services.ErrProjectCodeExists, http.StatusConflict, "conflict detected"},
|
||||
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
|
||||
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
|
||||
)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, project)
|
||||
c.JSON(http.StatusOK, ProjectWithWarning{Project: project, VariantWarning: variantWarning})
|
||||
})
|
||||
|
||||
projects.POST("/:uuid/archive", func(c *gin.Context) {
|
||||
if err := projectService.Archive(c.Param("uuid"), dbUsername); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, services.ErrProjectNotFound):
|
||||
respondError(c, http.StatusNotFound, "resource not found", err)
|
||||
case errors.Is(err, services.ErrProjectForbidden):
|
||||
respondError(c, http.StatusForbidden, "access denied", err)
|
||||
default:
|
||||
respondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
}
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
|
||||
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
|
||||
)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "project archived"})
|
||||
@@ -1610,14 +1688,10 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
|
||||
projects.POST("/:uuid/reactivate", func(c *gin.Context) {
|
||||
if err := projectService.Reactivate(c.Param("uuid"), dbUsername); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, services.ErrProjectNotFound):
|
||||
respondError(c, http.StatusNotFound, "resource not found", err)
|
||||
case errors.Is(err, services.ErrProjectForbidden):
|
||||
respondError(c, http.StatusForbidden, "access denied", err)
|
||||
default:
|
||||
respondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
}
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
|
||||
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
|
||||
)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "project reactivated"})
|
||||
@@ -1625,16 +1699,11 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
|
||||
projects.DELETE("/:uuid", func(c *gin.Context) {
|
||||
if err := projectService.DeleteVariant(c.Param("uuid"), dbUsername); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, services.ErrCannotDeleteMainVariant):
|
||||
respondError(c, http.StatusBadRequest, "invalid request", err)
|
||||
case errors.Is(err, services.ErrProjectNotFound):
|
||||
respondError(c, http.StatusNotFound, "resource not found", err)
|
||||
case errors.Is(err, services.ErrProjectForbidden):
|
||||
respondError(c, http.StatusForbidden, "access denied", err)
|
||||
default:
|
||||
respondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
}
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrCannotDeleteMainVariant, http.StatusBadRequest, "invalid request"},
|
||||
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
|
||||
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
|
||||
)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "variant deleted"})
|
||||
@@ -1651,18 +1720,38 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
|
||||
result, err := projectService.ListConfigurations(c.Param("uuid"), dbUsername, status)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, services.ErrProjectNotFound):
|
||||
respondError(c, http.StatusNotFound, "resource not found", err)
|
||||
case errors.Is(err, services.ErrProjectForbidden):
|
||||
respondError(c, http.StatusForbidden, "access denied", err)
|
||||
default:
|
||||
respondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
}
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
|
||||
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -1799,7 +1888,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)
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"time"
|
||||
|
||||
qfassets "git.mchus.pro/mchus/quoteforge"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
mysqlDriver "github.com/go-sql-driver/mysql"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// Server (MariaDB) migration commands. Each runs only the embedded migrations/*.sql
|
||||
// files tracked in qt_schema_migrations — never GORM AutoMigrate, which can silently
|
||||
// retype production columns to match whatever models the running binary was built with.
|
||||
// See bible-local/03-database.md "Migrations".
|
||||
|
||||
// openMigrationDB opens a dedicated MariaDB connection for migrations. The app's shared
|
||||
// connection (localdb.GetDSN) has 3s read/write timeouts for offline-first sync; a
|
||||
// backfill UPDATE over qt_pricelist_items needs minutes, and a client-side timeout
|
||||
// mid-statement leaves the file half-applied and unrecorded.
|
||||
func openMigrationDB(local *localdb.LocalDB) (*gorm.DB, error) {
|
||||
dsn, err := local.GetDSN()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("server connection settings: %w", err)
|
||||
}
|
||||
cfg, err := mysqlDriver.ParseDSN(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse DSN: %w", err)
|
||||
}
|
||||
cfg.Timeout = 10 * time.Second
|
||||
cfg.ReadTimeout = 0
|
||||
cfg.WriteTimeout = 0
|
||||
db, err := gorm.Open(mysql.Open(cfg.FormatDSN()), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect to server: %w", err)
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// runMigrateStatus prints every server migration and whether it is applied.
|
||||
func runMigrateStatus(db *gorm.DB) error {
|
||||
migrations, err := qfassets.MigrationsFS()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
states, err := models.SQLMigrationStatus(db, migrations)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pending := 0
|
||||
for _, st := range states {
|
||||
if st.AppliedAt != nil {
|
||||
fmt.Printf(" applied %s (%s)\n", st.Filename, st.AppliedAt.Format("2006-01-02 15:04"))
|
||||
} else {
|
||||
fmt.Printf(" PENDING %s\n", st.Filename)
|
||||
pending++
|
||||
}
|
||||
}
|
||||
fmt.Printf("%d migrations, %d pending\n", len(states), pending)
|
||||
return nil
|
||||
}
|
||||
|
||||
// runMigrateApply applies pending server migrations. Refuses on a server with no
|
||||
// migration history at all: its schema was built by other means, so every file would be
|
||||
// re-run — record a baseline with -migrate-baseline first.
|
||||
func runMigrateApply(db *gorm.DB) error {
|
||||
migrations, err := qfassets.MigrationsFS()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := requireMigrationHistory(db, migrations); err != nil {
|
||||
return err
|
||||
}
|
||||
applied, err := models.RunSQLMigrations(db, migrations, func(filename string) {
|
||||
fmt.Printf(" applying %s ...\n", filename)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(applied) == 0 {
|
||||
fmt.Println("server schema is up to date — nothing to apply")
|
||||
return nil
|
||||
}
|
||||
fmt.Printf("applied %d migration(s)\n", len(applied))
|
||||
return nil
|
||||
}
|
||||
|
||||
// runMigrateBaseline records migrations up to and including upto as applied without
|
||||
// running them.
|
||||
func runMigrateBaseline(db *gorm.DB, upto string) error {
|
||||
migrations, err := qfassets.MigrationsFS()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
recorded, err := models.BaselineSQLMigrations(db, migrations, upto)
|
||||
for _, f := range recorded {
|
||||
fmt.Printf(" recorded %s (not executed)\n", f)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("baseline: %d migration(s) recorded as applied, up to %s\n", len(recorded), upto)
|
||||
return nil
|
||||
}
|
||||
|
||||
func requireMigrationHistory(db *gorm.DB, migrations fs.FS) error {
|
||||
states, err := models.SQLMigrationStatus(db, migrations)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, st := range states {
|
||||
if st.AppliedAt != nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("qt_schema_migrations has no applied migrations, so all %d files would run against this server. "+
|
||||
"Record what the server already has first: qfs -migrate-baseline <last-applied-file.sql> (make migrate-baseline UPTO=...)", len(states))
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/handlers"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// errCase maps a sentinel error to the HTTP status/message respondByErrCase
|
||||
// should use when errors.Is matches it.
|
||||
type errCase struct {
|
||||
err error
|
||||
status int
|
||||
message string
|
||||
}
|
||||
|
||||
// respondByErrCase responds with the status/message of the first matching
|
||||
// case (checked in order), or a 500 "internal server error" fallback when
|
||||
// none match. Centralizes the switch-on-sentinel-error pattern repeated
|
||||
// across the config/project HTTP handlers in this file.
|
||||
func respondByErrCase(c *gin.Context, err error, cases ...errCase) {
|
||||
for _, cs := range cases {
|
||||
if errors.Is(err, cs.err) {
|
||||
handlers.RespondError(c, cs.status, cs.message, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
handlers.RespondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
}
|
||||
@@ -21,30 +21,23 @@ const (
|
||||
// ResolveDBPath returns the local SQLite path using priority:
|
||||
// explicit CLI path > QFS_DB_PATH > OS-specific user state directory.
|
||||
func ResolveDBPath(explicitPath string) (string, error) {
|
||||
if explicitPath != "" {
|
||||
return filepath.Clean(explicitPath), nil
|
||||
}
|
||||
|
||||
if fromEnv := os.Getenv(envDBPath); fromEnv != "" {
|
||||
return filepath.Clean(fromEnv), nil
|
||||
}
|
||||
|
||||
dir, err := defaultStateDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return filepath.Join(dir, defaultDB), nil
|
||||
return resolvePath(explicitPath, envDBPath, defaultDB)
|
||||
}
|
||||
|
||||
// ResolveConfigPath returns the config path using priority:
|
||||
// explicit CLI path > QFS_CONFIG_PATH > OS-specific user state directory.
|
||||
func ResolveConfigPath(explicitPath string) (string, error) {
|
||||
return resolvePath(explicitPath, envCfgPath, defaultCfg)
|
||||
}
|
||||
|
||||
// resolvePath returns a path using priority: explicit CLI path > envVar > OS-specific
|
||||
// user state directory joined with defaultFilename.
|
||||
func resolvePath(explicitPath, envVar, defaultFilename string) (string, error) {
|
||||
if explicitPath != "" {
|
||||
return filepath.Clean(explicitPath), nil
|
||||
}
|
||||
|
||||
if fromEnv := os.Getenv(envCfgPath); fromEnv != "" {
|
||||
if fromEnv := os.Getenv(envVar); fromEnv != "" {
|
||||
return filepath.Clean(fromEnv), nil
|
||||
}
|
||||
|
||||
@@ -53,7 +46,7 @@ func ResolveConfigPath(explicitPath string) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return filepath.Join(dir, defaultCfg), nil
|
||||
return filepath.Join(dir, defaultFilename), nil
|
||||
}
|
||||
|
||||
// ResolveConfigPathNearDB returns config path using priority:
|
||||
|
||||
@@ -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,40 +42,22 @@ 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, read from the component
|
||||
// universe (latest active world ∪ estimate pricelists — the same source the configurator,
|
||||
// BOM and pricing tab use, see bible-local/decisions/2026-07-24-component-universe-world-union.md).
|
||||
// It must NOT be scoped to a single pricelist: a world-only LOT is a legitimate cart member
|
||||
// and still carries a real lot_category in the world pricelist. LOTs present in neither
|
||||
// pricelist are omitted — callers treat a missing key as "no category" and skip that lot.
|
||||
func ResolveLotCategories(local *localdb.LocalDB, lotNames []string) (map[string]string, error) {
|
||||
if local == nil {
|
||||
return nil, fmt.Errorf("local db is nil")
|
||||
}
|
||||
cats, err := local.GetLocalLotCategoriesByServerPricelistID(serverPricelistID, lotNames)
|
||||
cats, err := local.GetLocalComponentCategoriesByLotNames(lotNames)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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)
|
||||
@@ -21,6 +20,7 @@ func TestResolveLotCategoriesStrict_MissingCategoryReturnsError(t *testing.T) {
|
||||
Source: "estimate",
|
||||
Version: "S-2026-02-11-001",
|
||||
Name: "test",
|
||||
IsActive: true,
|
||||
CreatedAt: time.Now(),
|
||||
SyncedAt: time.Now(),
|
||||
}); err != nil {
|
||||
@@ -36,16 +36,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, []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 +56,88 @@ 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, []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")
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveLotCategories_WorldOnlyLot covers a LOT that exists only in the world
|
||||
// pricelist (never added to estimate) but is a legitimate cart member. Its real
|
||||
// lot_category must be resolved from the component universe, not dropped.
|
||||
func TestResolveLotCategories_WorldOnlyLot(t *testing.T) {
|
||||
local, err := localdb.New(filepath.Join(t.TempDir(), "local.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("init local db: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = local.Close() })
|
||||
|
||||
saved := func(serverID uint, source string, items []localdb.LocalPricelistItem) {
|
||||
if err := local.SaveLocalPricelist(&localdb.LocalPricelist{
|
||||
ServerID: serverID, Source: source, Version: source + "-v1", Name: source,
|
||||
IsActive: true, CreatedAt: time.Now(), SyncedAt: time.Now(),
|
||||
}); err != nil {
|
||||
t.Fatalf("save %s pricelist: %v", source, err)
|
||||
}
|
||||
pl, err := local.GetLocalPricelistByServerID(serverID)
|
||||
if err != nil {
|
||||
t.Fatalf("get %s pricelist: %v", source, err)
|
||||
}
|
||||
for i := range items {
|
||||
items[i].PricelistID = pl.ID
|
||||
}
|
||||
if err := local.SaveLocalPricelistItems(items); err != nil {
|
||||
t.Fatalf("save %s items: %v", source, err)
|
||||
}
|
||||
}
|
||||
|
||||
saved(1, "estimate", []localdb.LocalPricelistItem{
|
||||
{LotName: "CPU_INTEL_8358", LotCategory: "CPU", Price: 1},
|
||||
})
|
||||
saved(2, "world", []localdb.LocalPricelistItem{
|
||||
{LotName: "CPU_INTEL_8358", LotCategory: "CPU", Price: 1},
|
||||
{LotName: "GPU_NV_RTX_PRO_6000D_SERVER_84GB_PCIE", LotCategory: "GPU", Price: 9900},
|
||||
})
|
||||
|
||||
cats, err := ResolveLotCategories(local, []string{
|
||||
"CPU_INTEL_8358", "GPU_NV_RTX_PRO_6000D_SERVER_84GB_PCIE",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if cats["GPU_NV_RTX_PRO_6000D_SERVER_84GB_PCIE"] != "GPU" {
|
||||
t.Fatalf("world-only LOT category not resolved: %q", cats["GPU_NV_RTX_PRO_6000D_SERVER_84GB_PCIE"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupForLotCategory(t *testing.T) {
|
||||
|
||||
+213
-175
@@ -11,16 +11,25 @@ import (
|
||||
)
|
||||
|
||||
type BuildOptions struct {
|
||||
ServerModel string
|
||||
SupportCode string
|
||||
ServerPricelist *uint
|
||||
ServerModel string
|
||||
}
|
||||
|
||||
type BuildResult struct {
|
||||
Article string
|
||||
Segments []ResultSegment
|
||||
Warnings []string
|
||||
}
|
||||
|
||||
// ResultSegment is one dash-separated piece of the article, tagged so the UI can
|
||||
// highlight pieces the generator could not fully parse. Recognized is false when
|
||||
// the segment contains a category placeholder (e.g. "GPU" instead of a real model
|
||||
// token) because a lot_name did not match the expected naming shape.
|
||||
type ResultSegment struct {
|
||||
Group string `json:"group"`
|
||||
Text string `json:"text"`
|
||||
Recognized bool `json:"recognized"`
|
||||
}
|
||||
|
||||
var (
|
||||
reMemGiB = regexp.MustCompile(`(?i)(\d+)\s*(GB|G)`)
|
||||
reMemTiB = regexp.MustCompile(`(?i)(\d+)\s*(TB|T)`)
|
||||
@@ -34,6 +43,17 @@ var (
|
||||
type namedSeg struct {
|
||||
group string // "MODEL","CPU","MEM","GPU","DISK","NET","PSU","SUPPORT"
|
||||
value string
|
||||
// degraded marks a segment whose value contains a category placeholder instead
|
||||
// of a parsed spec token, because some lot_name did not match the expected shape.
|
||||
degraded bool
|
||||
}
|
||||
|
||||
// segmentResult is what each build*Segment helper returns: the rendered value, a
|
||||
// degraded flag, and human-readable warnings that name the offending lot_names.
|
||||
type segmentResult struct {
|
||||
value string
|
||||
degraded bool
|
||||
warnings []string
|
||||
}
|
||||
|
||||
func Build(local *localdb.LocalDB, items []models.ConfigItem, opts BuildOptions) (BuildResult, error) {
|
||||
@@ -44,75 +64,59 @@ func Build(local *localdb.LocalDB, items []models.ConfigItem, opts BuildOptions)
|
||||
if model == "" {
|
||||
return BuildResult{}, fmt.Errorf("server_model required")
|
||||
}
|
||||
segs = append(segs, namedSeg{"MODEL", model})
|
||||
segs = append(segs, namedSeg{group: "MODEL", value: model})
|
||||
|
||||
lotNames := make([]string, 0, len(items))
|
||||
for _, it := range items {
|
||||
lotNames = append(lotNames, it.LotName)
|
||||
}
|
||||
|
||||
if opts.ServerPricelist == nil || *opts.ServerPricelist == 0 {
|
||||
return BuildResult{}, fmt.Errorf("pricelist_id required for article")
|
||||
}
|
||||
|
||||
cats, err := ResolveLotCategoriesStrict(local, *opts.ServerPricelist, lotNames)
|
||||
cats, err := ResolveLotCategories(local, lotNames)
|
||||
if err != nil {
|
||||
return BuildResult{}, err
|
||||
}
|
||||
|
||||
if cpuSeg := buildCPUSegment(items, cats); cpuSeg != "" {
|
||||
segs = append(segs, namedSeg{"CPU", cpuSeg})
|
||||
}
|
||||
memSeg, memWarn := buildMemSegment(items, cats)
|
||||
if memWarn != "" {
|
||||
warnings = append(warnings, memWarn)
|
||||
}
|
||||
if memSeg != "" {
|
||||
segs = append(segs, namedSeg{"MEM", memSeg})
|
||||
}
|
||||
if gpuSeg := buildGPUSegment(items, cats); gpuSeg != "" {
|
||||
segs = append(segs, namedSeg{"GPU", gpuSeg})
|
||||
}
|
||||
diskSeg, diskWarn := buildDiskSegment(items, cats)
|
||||
if diskWarn != "" {
|
||||
warnings = append(warnings, diskWarn)
|
||||
}
|
||||
if diskSeg != "" {
|
||||
segs = append(segs, namedSeg{"DISK", diskSeg})
|
||||
}
|
||||
netSeg, netWarn := buildNetSegment(items, cats)
|
||||
if netWarn != "" {
|
||||
warnings = append(warnings, netWarn)
|
||||
}
|
||||
if netSeg != "" {
|
||||
segs = append(segs, namedSeg{"NET", netSeg})
|
||||
}
|
||||
psuSeg, psuWarn := buildPSUSegment(items, cats)
|
||||
if psuWarn != "" {
|
||||
warnings = append(warnings, psuWarn)
|
||||
}
|
||||
if psuSeg != "" {
|
||||
segs = append(segs, namedSeg{"PSU", psuSeg})
|
||||
for _, sb := range []struct {
|
||||
group string
|
||||
build func([]models.ConfigItem, map[string]string) segmentResult
|
||||
}{
|
||||
{"CPU", buildCPUSegment},
|
||||
{"MEM", buildMemSegment},
|
||||
{"GPU", buildGPUSegment},
|
||||
{"DISK", buildDiskSegment},
|
||||
{"NET", buildNetSegment},
|
||||
{"PSU", buildPSUSegment},
|
||||
} {
|
||||
res := sb.build(items, cats)
|
||||
warnings = append(warnings, res.warnings...)
|
||||
if res.value != "" {
|
||||
segs = append(segs, namedSeg{group: sb.group, value: res.value, degraded: res.degraded})
|
||||
}
|
||||
}
|
||||
|
||||
if 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{group: "SUPPORT", value: supportSeg})
|
||||
}
|
||||
|
||||
article := strings.Join(namedSegsValues(segs), "-")
|
||||
if len([]rune(article)) > 80 {
|
||||
article = compressArticle(segs)
|
||||
segs = compressArticle(segs)
|
||||
article = strings.Join(namedSegsValues(segs), "-")
|
||||
warnings = append(warnings, "compressed")
|
||||
}
|
||||
if len([]rune(article)) > 80 {
|
||||
return BuildResult{}, fmt.Errorf("article_overflow")
|
||||
}
|
||||
|
||||
return BuildResult{Article: article, Warnings: warnings}, nil
|
||||
result := BuildResult{Article: article, Warnings: warnings}
|
||||
for _, s := range segs {
|
||||
result.Segments = append(result.Segments, ResultSegment{
|
||||
Group: s.group,
|
||||
Text: s.value,
|
||||
Recognized: !s.degraded,
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func namedSegsValues(segs []namedSeg) []string {
|
||||
@@ -132,62 +136,61 @@ 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 {
|
||||
type agg struct {
|
||||
qty int
|
||||
// placeholderToken returns the token used in the article when a lot's spec can't be
|
||||
// parsed: the lot_category itself (never a bare "UNK"), uppercased.
|
||||
func placeholderToken(cat string) string {
|
||||
t := strings.ToUpper(strings.TrimSpace(cat))
|
||||
if t == "" {
|
||||
return "X"
|
||||
}
|
||||
models := map[string]*agg{}
|
||||
return t
|
||||
}
|
||||
|
||||
func buildCPUSegment(items []models.ConfigItem, cats map[string]string) segmentResult {
|
||||
models := map[string]int{}
|
||||
res := segmentResult{}
|
||||
for _, it := range items {
|
||||
group, ok := GroupForLotCategory(cats[it.LotName])
|
||||
if !ok || group != GroupCPU {
|
||||
continue
|
||||
}
|
||||
model := parseCPUModel(it.LotName)
|
||||
if model == "" {
|
||||
model = "UNK"
|
||||
model, parsed := parseCPUModel(it.LotName)
|
||||
if !parsed {
|
||||
model = placeholderToken(cats[it.LotName])
|
||||
res.degraded = true
|
||||
res.warnings = append(res.warnings, fmt.Sprintf("CPU: не распознана модель LOT %q — в артикул записана категория %q", it.LotName, model))
|
||||
}
|
||||
if _, ok := models[model]; !ok {
|
||||
models[model] = &agg{}
|
||||
}
|
||||
models[model].qty += it.Quantity
|
||||
models[model] += it.Quantity
|
||||
}
|
||||
if len(models) == 0 {
|
||||
return ""
|
||||
return res
|
||||
}
|
||||
parts := make([]string, 0, len(models))
|
||||
for model, a := range models {
|
||||
parts = append(parts, fmt.Sprintf("%dx%s", a.qty, model))
|
||||
}
|
||||
sort.Strings(parts)
|
||||
return strings.Join(parts, "+")
|
||||
res.value = joinQtyTokens(models)
|
||||
return res
|
||||
}
|
||||
|
||||
func buildMemSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
|
||||
func buildMemSegment(items []models.ConfigItem, cats map[string]string) segmentResult {
|
||||
totalGiB := 0
|
||||
res := segmentResult{}
|
||||
unparsed := 0
|
||||
for _, it := range items {
|
||||
group, ok := GroupForLotCategory(cats[it.LotName])
|
||||
if !ok || group != GroupMEM {
|
||||
@@ -195,21 +198,31 @@ func buildMemSegment(items []models.ConfigItem, cats map[string]string) (string,
|
||||
}
|
||||
per := parseMemGiB(it.LotName)
|
||||
if per <= 0 {
|
||||
return "", "mem_unknown"
|
||||
unparsed++
|
||||
res.degraded = true
|
||||
res.warnings = append(res.warnings, fmt.Sprintf("MEM: не распознан объём LOT %q", it.LotName))
|
||||
continue
|
||||
}
|
||||
totalGiB += per * it.Quantity
|
||||
}
|
||||
if totalGiB == 0 {
|
||||
return "", ""
|
||||
parts := make([]string, 0, 2)
|
||||
if totalGiB > 0 {
|
||||
if totalGiB%1024 == 0 {
|
||||
parts = append(parts, fmt.Sprintf("%dT", totalGiB/1024))
|
||||
} else {
|
||||
parts = append(parts, fmt.Sprintf("%dG", totalGiB))
|
||||
}
|
||||
}
|
||||
if totalGiB%1024 == 0 {
|
||||
return fmt.Sprintf("%dT", totalGiB/1024), ""
|
||||
if unparsed > 0 {
|
||||
parts = append(parts, placeholderToken("MEM"))
|
||||
}
|
||||
return fmt.Sprintf("%dG", totalGiB), ""
|
||||
res.value = strings.Join(parts, "+")
|
||||
return res
|
||||
}
|
||||
|
||||
func buildGPUSegment(items []models.ConfigItem, cats map[string]string) string {
|
||||
func buildGPUSegment(items []models.ConfigItem, cats map[string]string) segmentResult {
|
||||
models := map[string]int{}
|
||||
res := segmentResult{}
|
||||
for _, it := range items {
|
||||
group, ok := GroupForLotCategory(cats[it.LotName])
|
||||
if !ok || group != GroupGPU {
|
||||
@@ -218,30 +231,28 @@ func buildGPUSegment(items []models.ConfigItem, cats map[string]string) string {
|
||||
if strings.HasPrefix(strings.ToUpper(it.LotName), "MB_") {
|
||||
continue
|
||||
}
|
||||
model := parseGPUModel(it.LotName)
|
||||
if model == "" {
|
||||
model = "UNK"
|
||||
model, parsed := parseGPUModel(it.LotName)
|
||||
if !parsed {
|
||||
model = placeholderToken(cats[it.LotName])
|
||||
res.degraded = true
|
||||
res.warnings = append(res.warnings, fmt.Sprintf("GPU: не распознана модель LOT %q — в артикул записана категория %q", it.LotName, model))
|
||||
}
|
||||
models[model] += it.Quantity
|
||||
}
|
||||
if len(models) == 0 {
|
||||
return ""
|
||||
return res
|
||||
}
|
||||
parts := make([]string, 0, len(models))
|
||||
for model, qty := range models {
|
||||
parts = append(parts, fmt.Sprintf("%dx%s", qty, model))
|
||||
}
|
||||
sort.Strings(parts)
|
||||
return strings.Join(parts, "+")
|
||||
res.value = joinQtyTokens(models)
|
||||
return res
|
||||
}
|
||||
|
||||
func buildDiskSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
|
||||
func buildDiskSegment(items []models.ConfigItem, cats map[string]string) segmentResult {
|
||||
type key struct {
|
||||
t string
|
||||
c string
|
||||
}
|
||||
groupQty := map[key]int{}
|
||||
warn := ""
|
||||
res := segmentResult{}
|
||||
for _, it := range items {
|
||||
group, ok := GroupForLotCategory(cats[it.LotName])
|
||||
if !ok || group != GroupDISK {
|
||||
@@ -249,14 +260,14 @@ func buildDiskSegment(items []models.ConfigItem, cats map[string]string) (string
|
||||
}
|
||||
capToken := parseCapacity(it.LotName)
|
||||
if capToken == "" {
|
||||
warn = "disk_unknown"
|
||||
res.degraded = true
|
||||
res.warnings = append(res.warnings, fmt.Sprintf("DISK: не распознан объём LOT %q", it.LotName))
|
||||
}
|
||||
typeCode := diskTypeCode(cats[it.LotName], it.LotName)
|
||||
k := key{t: typeCode, c: capToken}
|
||||
groupQty[k] += it.Quantity
|
||||
groupQty[key{t: typeCode, c: capToken}] += it.Quantity
|
||||
}
|
||||
if len(groupQty) == 0 {
|
||||
return "", ""
|
||||
return res
|
||||
}
|
||||
parts := make([]string, 0, len(groupQty))
|
||||
for k, qty := range groupQty {
|
||||
@@ -267,59 +278,53 @@ func buildDiskSegment(items []models.ConfigItem, cats map[string]string) (string
|
||||
}
|
||||
}
|
||||
sort.Strings(parts)
|
||||
return strings.Join(parts, "+"), warn
|
||||
res.value = strings.Join(parts, "+")
|
||||
return res
|
||||
}
|
||||
|
||||
func buildNetSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
|
||||
func buildNetSegment(items []models.ConfigItem, cats map[string]string) segmentResult {
|
||||
return buildProfileSegment(items, cats, GroupNET, parsePortSpeed, "NET")
|
||||
}
|
||||
|
||||
func buildPSUSegment(items []models.ConfigItem, cats map[string]string) segmentResult {
|
||||
return buildProfileSegment(items, cats, GroupPSU, parseWatts, "PSU")
|
||||
}
|
||||
|
||||
// buildProfileSegment groups items of the given category group by a profile token
|
||||
// parsed from their lot name (e.g. port speed, wattage rating). When a lot's profile
|
||||
// can't be determined it falls back to the category placeholder and flags the segment
|
||||
// as degraded, naming the lot in a warning.
|
||||
func buildProfileSegment(items []models.ConfigItem, cats map[string]string, group Group, parseProfile func(string) string, groupLabel string) segmentResult {
|
||||
groupQty := map[string]int{}
|
||||
warn := ""
|
||||
res := segmentResult{}
|
||||
for _, it := range items {
|
||||
group, ok := GroupForLotCategory(cats[it.LotName])
|
||||
if !ok || group != GroupNET {
|
||||
g, ok := GroupForLotCategory(cats[it.LotName])
|
||||
if !ok || g != group {
|
||||
continue
|
||||
}
|
||||
profile := parsePortSpeed(it.LotName)
|
||||
profile := parseProfile(it.LotName)
|
||||
if profile == "" {
|
||||
profile = "UNKNET"
|
||||
warn = "net_unknown"
|
||||
profile = placeholderToken(groupLabel)
|
||||
res.degraded = true
|
||||
res.warnings = append(res.warnings, fmt.Sprintf("%s: не распознан профиль LOT %q — в артикул записана категория %q", groupLabel, it.LotName, profile))
|
||||
}
|
||||
groupQty[profile] += it.Quantity
|
||||
}
|
||||
if len(groupQty) == 0 {
|
||||
return "", ""
|
||||
return res
|
||||
}
|
||||
parts := make([]string, 0, len(groupQty))
|
||||
for profile, qty := range groupQty {
|
||||
parts = append(parts, fmt.Sprintf("%dx%s", qty, profile))
|
||||
}
|
||||
sort.Strings(parts)
|
||||
return strings.Join(parts, "+"), warn
|
||||
res.value = joinQtyTokens(groupQty)
|
||||
return res
|
||||
}
|
||||
|
||||
func buildPSUSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
|
||||
groupQty := map[string]int{}
|
||||
warn := ""
|
||||
for _, it := range items {
|
||||
group, ok := GroupForLotCategory(cats[it.LotName])
|
||||
if !ok || group != GroupPSU {
|
||||
continue
|
||||
}
|
||||
rating := parseWatts(it.LotName)
|
||||
if rating == "" {
|
||||
rating = "UNKPSU"
|
||||
warn = "psu_unknown"
|
||||
}
|
||||
groupQty[rating] += it.Quantity
|
||||
}
|
||||
if len(groupQty) == 0 {
|
||||
return "", ""
|
||||
}
|
||||
parts := make([]string, 0, len(groupQty))
|
||||
for rating, qty := range groupQty {
|
||||
parts = append(parts, fmt.Sprintf("%dx%s", qty, rating))
|
||||
// joinQtyTokens renders {token: qty} as a sorted "NxTOKEN+MxTOKEN" string.
|
||||
func joinQtyTokens(qty map[string]int) string {
|
||||
parts := make([]string, 0, len(qty))
|
||||
for token, n := range qty {
|
||||
parts = append(parts, fmt.Sprintf("%dx%s", n, token))
|
||||
}
|
||||
sort.Strings(parts)
|
||||
return strings.Join(parts, "+"), warn
|
||||
return strings.Join(parts, "+")
|
||||
}
|
||||
|
||||
func normalizeModelToken(lotName string) string {
|
||||
@@ -331,18 +336,27 @@ func normalizeModelToken(lotName string) string {
|
||||
return strings.ToUpper(strings.TrimSpace(token))
|
||||
}
|
||||
|
||||
func parseCPUModel(lotName string) string {
|
||||
// parseCPUModel extracts the model token from a CPU lot_name (shape
|
||||
// CPU_{VENDOR}_{MODEL}, e.g. "CPU_INTEL_8592+"). The bool is false when the name
|
||||
// has no parseable {VENDOR}_{MODEL} tail — a structural failure the caller surfaces.
|
||||
// It cannot validate that the token is a real CPU model (no vendor catalog is kept
|
||||
// in the repo by design), only that the name matched the expected shape.
|
||||
func parseCPUModel(lotName string) (string, bool) {
|
||||
parts := strings.Split(lotName, "_")
|
||||
if len(parts) >= 2 {
|
||||
last := strings.ToUpper(strings.TrimSpace(parts[len(parts)-1]))
|
||||
if last != "" {
|
||||
return last
|
||||
return last, true
|
||||
}
|
||||
}
|
||||
return normalizeModelToken(lotName)
|
||||
return normalizeModelToken(lotName), false
|
||||
}
|
||||
|
||||
func parseGPUModel(lotName string) string {
|
||||
// parseGPUModel extracts a "MODEL[_MEM]" token from a GPU lot_name. The bool is
|
||||
// false when no model token could be located and the result is only the last-ditch
|
||||
// last-underscore-segment fallback — a structural failure the caller surfaces.
|
||||
// Like parseCPUModel it does not validate the token against a catalog.
|
||||
func parseGPUModel(lotName string) (string, bool) {
|
||||
upper := strings.ToUpper(lotName)
|
||||
if idx := strings.Index(upper, "GPU_"); idx >= 0 {
|
||||
upper = upper[idx+4:]
|
||||
@@ -373,7 +387,7 @@ func parseGPUModel(lotName string) string {
|
||||
}
|
||||
if model == "" && i > 0 {
|
||||
model = p
|
||||
} else if model != "" && numSuffix == "" && isNumeric(p) {
|
||||
} else if model != "" && numSuffix == "" && isModelNumber(p) {
|
||||
numSuffix = p
|
||||
}
|
||||
}
|
||||
@@ -383,20 +397,24 @@ func parseGPUModel(lotName string) string {
|
||||
full = model + numSuffix
|
||||
}
|
||||
if full != "" && mem != "" {
|
||||
return full + "_" + mem
|
||||
return full + "_" + mem, true
|
||||
}
|
||||
if full != "" {
|
||||
return full
|
||||
return full, true
|
||||
}
|
||||
return normalizeModelToken(lotName)
|
||||
return normalizeModelToken(lotName), false
|
||||
}
|
||||
|
||||
func isNumeric(s string) bool {
|
||||
if s == "" {
|
||||
// isModelNumber reports whether s looks like a GPU/accelerator model number token:
|
||||
// it starts with a digit and contains only digits and uppercase letters. This keeps
|
||||
// vendor-suffixed names like "6000D" (RTX PRO 6000D) intact instead of dropping the
|
||||
// letter and collapsing two distinct models to the same token.
|
||||
func isModelNumber(s string) bool {
|
||||
if s == "" || s[0] < '0' || s[0] > '9' {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if r < '0' || r > '9' {
|
||||
if (r < '0' || r > '9') && (r < 'A' || r > 'Z') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -448,9 +466,28 @@ func parsePortSpeed(lotName string) string {
|
||||
if m := rePortFC.FindStringSubmatch(lotName); len(m) == 3 {
|
||||
return fmt.Sprintf("%spFC%s", m[1], m[2])
|
||||
}
|
||||
if model := parseDPUModel(lotName); model != "" {
|
||||
return model
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// parseDPUModel extracts the "{FAMILY}_{MODEL}" tail from a DPU lot_name (shape
|
||||
// DPU_{FAMILY}_{MODEL}, e.g. "DPU_BF3_B3220-32G" -> "BF3_B3220-32G"). DPU lots have
|
||||
// no port-speed suffix like NIC/HCA, so they fall through parsePortSpeed's regexes;
|
||||
// this keeps the family prefix (e.g. BF2 vs BF3) so distinct DPU generations sharing
|
||||
// a part-number suffix don't collapse into the same article token. Like parseCPUModel
|
||||
// it does not validate against a vendor catalog, only matches the expected shape.
|
||||
func parseDPUModel(lotName string) string {
|
||||
upper := strings.ToUpper(lotName)
|
||||
const prefix = "DPU_"
|
||||
if !strings.HasPrefix(upper, prefix) {
|
||||
return ""
|
||||
}
|
||||
rest := strings.TrimSpace(upper[len(prefix):])
|
||||
return rest
|
||||
}
|
||||
|
||||
func parseWatts(lotName string) string {
|
||||
if m := reWatts.FindStringSubmatch(lotName); len(m) == 2 {
|
||||
w := atoi(m[1])
|
||||
@@ -504,42 +541,43 @@ func atoi(v string) int {
|
||||
return n
|
||||
}
|
||||
|
||||
func compressArticle(segs []namedSeg) string {
|
||||
// compressArticle shortens an over-long article by progressively dropping/abbreviating
|
||||
// segments. It returns the (possibly shortened) segment list; the caller re-joins it.
|
||||
func compressArticle(segs []namedSeg) []namedSeg {
|
||||
if len(segs) == 0 {
|
||||
return ""
|
||||
return segs
|
||||
}
|
||||
fits := func() bool {
|
||||
return len([]rune(strings.Join(namedSegsValues(segs), "-"))) <= 80
|
||||
}
|
||||
for i, s := range segs {
|
||||
segs[i].value = strings.ReplaceAll(s.value, "GbE", "G")
|
||||
}
|
||||
article := strings.Join(namedSegsValues(segs), "-")
|
||||
if len([]rune(article)) <= 80 {
|
||||
return article
|
||||
if fits() {
|
||||
return segs
|
||||
}
|
||||
|
||||
// 1) remove PSU
|
||||
if i := findSegGroup(segs, "PSU"); i >= 0 {
|
||||
segs = append(segs[:i], segs[i+1:]...)
|
||||
article = strings.Join(namedSegsValues(segs), "-")
|
||||
if len([]rune(article)) <= 80 {
|
||||
return article
|
||||
if fits() {
|
||||
return segs
|
||||
}
|
||||
}
|
||||
|
||||
// 2) compress NET/HBA/HCA
|
||||
if i := findSegGroup(segs, "NET"); i >= 0 {
|
||||
segs[i].value = compressNetSegment(segs[i].value)
|
||||
article = strings.Join(namedSegsValues(segs), "-")
|
||||
if len([]rune(article)) <= 80 {
|
||||
return article
|
||||
if fits() {
|
||||
return segs
|
||||
}
|
||||
}
|
||||
|
||||
// 3) compress DISK
|
||||
if i := findSegGroup(segs, "DISK"); i >= 0 {
|
||||
segs[i].value = compressDiskSegment(segs[i].value)
|
||||
article = strings.Join(namedSegsValues(segs), "-")
|
||||
if len([]rune(article)) <= 80 {
|
||||
return article
|
||||
if fits() {
|
||||
return segs
|
||||
}
|
||||
}
|
||||
|
||||
@@ -547,7 +585,7 @@ func compressArticle(segs []namedSeg) string {
|
||||
if i := findSegGroup(segs, "GPU"); i >= 0 {
|
||||
segs[i].value = compressGPUSegment(segs[i].value)
|
||||
}
|
||||
return strings.Join(namedSegsValues(segs), "-")
|
||||
return segs
|
||||
}
|
||||
|
||||
func compressNetSegment(seg string) string {
|
||||
|
||||
@@ -44,11 +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,
|
||||
ServerModel: "DL380GEN11",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("build article: %v", err)
|
||||
@@ -59,6 +58,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
|
||||
@@ -115,8 +117,7 @@ func TestBuild_CompressArticle_NoGPU_PSUNotNIC(t *testing.T) {
|
||||
{LotName: "PS_1500W_Platinum", Quantity: 2},
|
||||
}
|
||||
result, err := Build(local, items, BuildOptions{
|
||||
ServerModel: "NF5280M6",
|
||||
ServerPricelist: &localPL.ServerID,
|
||||
ServerModel: "NF5280M6",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("build article: %v", err)
|
||||
@@ -137,3 +138,122 @@ func TestBuild_CompressArticle_NoGPU_PSUNotNIC(t *testing.T) {
|
||||
func contains(s, sub string) bool {
|
||||
return strings.Contains(s, sub)
|
||||
}
|
||||
|
||||
func TestParsePortSpeed_DPUModel(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"DPU_BF3_B3220-32G": "BF3_B3220-32G",
|
||||
"DPU_BF2_B2220Q": "BF2_B2220Q",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := parsePortSpeed(in); got != want {
|
||||
t.Errorf("parsePortSpeed(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuild_ParsesDPU verifies a DPU lot (e.g. NVIDIA BlueField) resolves to its
|
||||
// family+model token instead of falling back to the "NET" category placeholder —
|
||||
// DPU lots don't carry a NIC/HCA-style port-speed suffix, so parsePortSpeed needs
|
||||
// its own DPU branch (parseDPUModel).
|
||||
func TestBuild_ParsesDPU(t *testing.T) {
|
||||
local, err := localdb.New(filepath.Join(t.TempDir(), "local.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("init local db: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = local.Close() })
|
||||
|
||||
if err := local.SaveLocalPricelist(&localdb.LocalPricelist{
|
||||
ServerID: 10, Source: "estimate", Version: "v1", Name: "t",
|
||||
IsActive: true, CreatedAt: time.Now(), SyncedAt: time.Now(),
|
||||
}); err != nil {
|
||||
t.Fatalf("save pricelist: %v", err)
|
||||
}
|
||||
pl, err := local.GetLocalPricelistByServerID(10)
|
||||
if err != nil {
|
||||
t.Fatalf("get pricelist: %v", err)
|
||||
}
|
||||
if err := local.SaveLocalPricelistItems([]localdb.LocalPricelistItem{
|
||||
{PricelistID: pl.ID, LotName: "DPU_BF3_B3220-32G", LotCategory: "DPU", Price: 1},
|
||||
}); err != nil {
|
||||
t.Fatalf("save items: %v", err)
|
||||
}
|
||||
|
||||
result, err := Build(local, models.ConfigItems{
|
||||
{LotName: "DPU_BF3_B3220-32G", Quantity: 1},
|
||||
}, BuildOptions{ServerModel: "X1"})
|
||||
if err != nil {
|
||||
t.Fatalf("build: %v", err)
|
||||
}
|
||||
if len(result.Warnings) != 0 {
|
||||
t.Fatalf("expected no warnings, got %v", result.Warnings)
|
||||
}
|
||||
if !contains(result.Article, "BF3_B3220-32G") {
|
||||
t.Fatalf("expected DPU model token in article: %s", result.Article)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseGPUModel_VendorLetterSuffix(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"GPU_NV_RTX_PRO_6000D_SERVER_84GB_PCIE": "RTX6000D_84GB",
|
||||
"GPU_NV_RTX_PRO_6000_SERVER_96GB_PCIE": "RTX6000_96GB",
|
||||
}
|
||||
for in, want := range cases {
|
||||
got, ok := parseGPUModel(in)
|
||||
if !ok || got != want {
|
||||
t.Errorf("parseGPUModel(%q) = %q, %v, want %q, true", in, got, ok, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuild_UnparseableModel_CategoryPlaceholder: a GPU LOT whose name does not
|
||||
// match the expected shape must not silently vanish or emit "UNK" — the article
|
||||
// carries the category token and the segment is flagged not-recognized with a
|
||||
// warning naming the lot.
|
||||
func TestBuild_UnparseableModel_CategoryPlaceholder(t *testing.T) {
|
||||
local, err := localdb.New(filepath.Join(t.TempDir(), "local.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("init local db: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = local.Close() })
|
||||
|
||||
if err := local.SaveLocalPricelist(&localdb.LocalPricelist{
|
||||
ServerID: 9, Source: "estimate", Version: "v1", Name: "t",
|
||||
IsActive: true, CreatedAt: time.Now(), SyncedAt: time.Now(),
|
||||
}); err != nil {
|
||||
t.Fatalf("save pricelist: %v", err)
|
||||
}
|
||||
pl, err := local.GetLocalPricelistByServerID(9)
|
||||
if err != nil {
|
||||
t.Fatalf("get pricelist: %v", err)
|
||||
}
|
||||
if err := local.SaveLocalPricelistItems([]localdb.LocalPricelistItem{
|
||||
{PricelistID: pl.ID, LotName: "WEIRDGPUNAME", LotCategory: "GPU", Price: 1},
|
||||
}); err != nil {
|
||||
t.Fatalf("save items: %v", err)
|
||||
}
|
||||
|
||||
result, err := Build(local, models.ConfigItems{
|
||||
{LotName: "WEIRDGPUNAME", Quantity: 4},
|
||||
}, BuildOptions{ServerModel: "X1"})
|
||||
if err != nil {
|
||||
t.Fatalf("build: %v", err)
|
||||
}
|
||||
if contains(result.Article, "UNK") {
|
||||
t.Fatalf("article must not contain UNK: %s", result.Article)
|
||||
}
|
||||
if !contains(result.Article, "4xGPU") {
|
||||
t.Fatalf("expected category placeholder 4xGPU in article: %s", result.Article)
|
||||
}
|
||||
var gpu *ResultSegment
|
||||
for i := range result.Segments {
|
||||
if result.Segments[i].Group == "GPU" {
|
||||
gpu = &result.Segments[i]
|
||||
}
|
||||
}
|
||||
if gpu == nil || gpu.Recognized {
|
||||
t.Fatalf("GPU segment must be present and not recognized: %+v", result.Segments)
|
||||
}
|
||||
if len(result.Warnings) == 0 || !contains(strings.Join(result.Warnings, "|"), "WEIRDGPUNAME") {
|
||||
t.Fatalf("expected a warning naming WEIRDGPUNAME, got %v", result.Warnings)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
// Package configfeatures holds the per-configuration feature flags: markers recording
|
||||
// which data features a configuration uses, so a client that does not know one of them
|
||||
// refuses to rewrite the configuration instead of silently dropping data it cannot see.
|
||||
//
|
||||
// Flags are derived from content on every save (Detect) and synced as
|
||||
// qt_configurations.feature_flags. A client checks a config's stored flags against the
|
||||
// set it knows (Known) before any write. See
|
||||
// bible-local/decisions/2026-09-24-configuration-feature-flags.md.
|
||||
package configfeatures
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SaleRowMarkups: Notes.pricing_ui.sale_row_markups has at least one row markup.
|
||||
const SaleRowMarkups = "sale_row_markups"
|
||||
|
||||
// known lists every flag this build understands. Adding a flag here is the contract for
|
||||
// "this client can round-trip the data behind it"; a new data feature that an older
|
||||
// client would lose on save must add a flag here and to Detect in the same change.
|
||||
var known = map[string]struct{}{
|
||||
SaleRowMarkups: {},
|
||||
}
|
||||
|
||||
// Known reports whether this build understands flag.
|
||||
func Known(flag string) bool {
|
||||
_, ok := known[flag]
|
||||
return ok
|
||||
}
|
||||
|
||||
// Unknown returns the flags this build does not understand, sorted and de-duplicated.
|
||||
func Unknown(flags []string) []string {
|
||||
seen := make(map[string]struct{}, len(flags))
|
||||
var out []string
|
||||
for _, f := range flags {
|
||||
f = strings.TrimSpace(f)
|
||||
if f == "" || Known(f) {
|
||||
continue
|
||||
}
|
||||
if _, dup := seen[f]; dup {
|
||||
continue
|
||||
}
|
||||
seen[f] = struct{}{}
|
||||
out = append(out, f)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// Detect derives the flags a configuration's content requires. Sorted; nil when none.
|
||||
func Detect(notes string) []string {
|
||||
var flags []string
|
||||
if notesHaveSaleRowMarkups(notes) {
|
||||
flags = append(flags, SaleRowMarkups)
|
||||
}
|
||||
sort.Strings(flags)
|
||||
return flags
|
||||
}
|
||||
|
||||
func notesHaveSaleRowMarkups(notes string) bool {
|
||||
if strings.TrimSpace(notes) == "" {
|
||||
return false
|
||||
}
|
||||
var parsed struct {
|
||||
PricingUI struct {
|
||||
SaleRowMarkups map[string]float64 `json:"sale_row_markups"`
|
||||
} `json:"pricing_ui"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(notes), &parsed); err != nil {
|
||||
return false
|
||||
}
|
||||
for _, pct := range parsed.PricingUI.SaleRowMarkups {
|
||||
if pct != 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// UnsupportedError is returned when a write is refused because the configuration
|
||||
// carries flags this build does not know.
|
||||
type UnsupportedError struct {
|
||||
Flags []string
|
||||
}
|
||||
|
||||
func (e *UnsupportedError) Error() string {
|
||||
return fmt.Sprintf(
|
||||
"конфигурация использует функции, неизвестные этой версии QuoteForge (%s) — обновите приложение, чтобы её изменять",
|
||||
strings.Join(e.Flags, ", "))
|
||||
}
|
||||
|
||||
// Check returns an *UnsupportedError when any of flags is unknown to this build.
|
||||
func Check(flags []string) error {
|
||||
if unknown := Unknown(flags); len(unknown) > 0 {
|
||||
return &UnsupportedError{Flags: unknown}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AsUnsupported unwraps err to an *UnsupportedError, if it is one.
|
||||
func AsUnsupported(err error) (*UnsupportedError, bool) {
|
||||
var ue *UnsupportedError
|
||||
if errors.As(err, &ue) {
|
||||
return ue, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package configfeatures
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDetectSaleRowMarkups(t *testing.T) {
|
||||
cases := []struct {
|
||||
notes string
|
||||
want []string
|
||||
}{
|
||||
{"", nil},
|
||||
{"not json", nil},
|
||||
{`{"pricing_ui":{"sale_uplift":1.5,"sale_row_markups":null}}`, nil},
|
||||
{`{"pricing_ui":{"sale_row_markups":{"NONE::A":0}}}`, nil},
|
||||
{`{"pricing_ui":{"sale_row_markups":{"NONE::A":-50}}}`, []string{SaleRowMarkups}},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := Detect(c.notes); !reflect.DeepEqual(got, c.want) {
|
||||
t.Errorf("Detect(%q) = %v, want %v", c.notes, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownAndCheck(t *testing.T) {
|
||||
got := Unknown([]string{"zeta", SaleRowMarkups, "alpha", "zeta", " "})
|
||||
if want := []string{"alpha", "zeta"}; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("Unknown = %v, want %v", got, want)
|
||||
}
|
||||
if err := Check([]string{SaleRowMarkups}); err != nil {
|
||||
t.Fatalf("Check(known) = %v", err)
|
||||
}
|
||||
ue, ok := AsUnsupported(Check([]string{"future_x"}))
|
||||
if !ok || !reflect.DeepEqual(ue.Flags, []string{"future_x"}) {
|
||||
t.Fatalf("Check(unknown) = %v, %v", ue, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// Flag names are permanent and follow bible-local/02-architecture.md
|
||||
// "Configuration feature flags": lower_snake_case, starts with a letter, ≤ 64 chars.
|
||||
func TestKnownFlagNamesFormat(t *testing.T) {
|
||||
valid := regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
|
||||
for flag := range known {
|
||||
if !valid.MatchString(flag) {
|
||||
t.Errorf("flag %q violates the naming format", flag)
|
||||
}
|
||||
}
|
||||
}
|
||||
+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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -126,6 +118,11 @@ func (h *ComponentHandler) GetCategories(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, models.DefaultCategories)
|
||||
}
|
||||
|
||||
// GetConfiguratorSettings serves the synced qt_settings. The default*() values
|
||||
// below are the only client-side fallback, used per key when the local cache has
|
||||
// no such setting (e.g. before the first sync); they are not kept in step with
|
||||
// the server — edit qt_settings in MariaDB, not these. The configurator page has
|
||||
// no fallback of its own.
|
||||
func (h *ComponentHandler) GetConfiguratorSettings(c *gin.Context) {
|
||||
s, _ := h.localDB.GetConfiguratorSettings()
|
||||
if s == nil {
|
||||
@@ -139,15 +136,51 @@ func (h *ComponentHandler) GetConfiguratorSettings(c *gin.Context) {
|
||||
s.TabConfig = defaultTabConfig()
|
||||
}
|
||||
if len(s.AlwaysVisibleTabs) == 0 {
|
||||
s.AlwaysVisibleTabs = []string{"base", "storage", "pci"}
|
||||
s.AlwaysVisibleTabs = []string{"base"}
|
||||
}
|
||||
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": 28000, "3": 77000, "5": 112000},
|
||||
"S": {"1": 39500, "3": 98000, "5": 140000},
|
||||
"P": {"1": 88500, "3": 147000},
|
||||
},
|
||||
"HGX-B200": {
|
||||
"B": {"1": 158500, "3": 230500, "5": 284500},
|
||||
"S": {"1": 176500, "3": 266500, "5": 332500},
|
||||
"P": {"1": 232000, "3": 322000},
|
||||
},
|
||||
"HGX-B300": {
|
||||
"B": {"1": 192000, "3": 270000, "5": 328500},
|
||||
"S": {"1": 211500, "3": 309000, "5": 380500},
|
||||
"P": {"1": 286000, "3": 383500},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func defaultConfigTypes() []localdb.ConfigTypeDef {
|
||||
return []localdb.ConfigTypeDef{
|
||||
{
|
||||
|
||||
@@ -55,6 +55,15 @@ type ProjectExportOptionsRequest struct {
|
||||
IncludeCompetitor bool `json:"include_competitor"`
|
||||
Basis string `json:"basis"` // "fob" or "ddp"
|
||||
SaleMarkup float64 `json:"sale_markup"` // DDP multiplier; 0 defaults to 1.3
|
||||
|
||||
ManualPrice *float64 `json:"manual_price"` // user-defined total price; distributed proportionally across rows
|
||||
|
||||
// MinimalSaleColumns/SaleRowMarkups are sent only by the single-config Sale-table
|
||||
// "Экспорт CSV" button (index.html exportPricingCSV('sale')) — never by the Buy
|
||||
// export or the project-level bulk export, which always leave these zero-valued so
|
||||
// their output stays unchanged. See services.ProjectPricingExportOptions.
|
||||
MinimalSaleColumns bool `json:"minimal_sale_columns"`
|
||||
SaleRowMarkups map[string]float64 `json:"sale_row_markups"` // "<vendorPN>::<lot>" -> markup percent
|
||||
}
|
||||
|
||||
func (h *ExportHandler) ExportCSV(c *gin.Context) {
|
||||
@@ -238,15 +247,31 @@ func (h *ExportHandler) ExportConfigPricingCSV(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var project *models.Project
|
||||
if config.ProjectUUID != nil && *config.ProjectUUID != "" {
|
||||
if p, err := h.projectService.GetByUUID(*config.ProjectUUID, h.dbUsername); err == nil {
|
||||
project = p
|
||||
}
|
||||
}
|
||||
|
||||
opts := services.ProjectPricingExportOptions{
|
||||
IncludeLOT: req.IncludeLOT,
|
||||
IncludeBOM: req.IncludeBOM,
|
||||
IncludeEstimate: req.IncludeEstimate,
|
||||
IncludeStock: req.IncludeStock,
|
||||
IncludeStock: req.IncludeStock && project != nil && project.ShowStockPrices,
|
||||
IncludeCompetitor: req.IncludeCompetitor,
|
||||
Basis: req.Basis,
|
||||
SaleMarkup: req.SaleMarkup,
|
||||
}
|
||||
// MinimalSaleColumns/SaleRowMarkups/ManualPrice are only ever sent by the Sale
|
||||
// table's own "Экспорт CSV" button (index.html exportPricingCSV('sale')) — gating
|
||||
// on the request's own flag keeps every other caller (Buy export, any other basis=
|
||||
// ddp caller) byte-identical to before this field existed.
|
||||
if req.MinimalSaleColumns {
|
||||
opts.MinimalSaleColumns = true
|
||||
opts.SaleRowMarkups = req.SaleRowMarkups
|
||||
opts.ManualPrice = req.ManualPrice
|
||||
}
|
||||
|
||||
data, err := h.exportService.ConfigToPricingExportData(config, opts)
|
||||
if err != nil {
|
||||
@@ -260,10 +285,8 @@ func (h *ExportHandler) ExportConfigPricingCSV(c *gin.Context) {
|
||||
}
|
||||
|
||||
projectCode := config.Name
|
||||
if config.ProjectUUID != nil && *config.ProjectUUID != "" {
|
||||
if project, err := h.projectService.GetByUUID(*config.ProjectUUID, h.dbUsername); err == nil && project != nil {
|
||||
projectCode = project.Code
|
||||
}
|
||||
if project != nil {
|
||||
projectCode = project.Code
|
||||
}
|
||||
|
||||
filename := fmt.Sprintf("%s (%s) %s %s SPEC.csv",
|
||||
@@ -309,7 +332,7 @@ func (h *ExportHandler) ExportProjectPricingCSV(c *gin.Context) {
|
||||
IncludeLOT: req.IncludeLOT,
|
||||
IncludeBOM: req.IncludeBOM,
|
||||
IncludeEstimate: req.IncludeEstimate,
|
||||
IncludeStock: req.IncludeStock,
|
||||
IncludeStock: req.IncludeStock && project.ShowStockPrices,
|
||||
IncludeCompetitor: req.IncludeCompetitor,
|
||||
Basis: req.Basis,
|
||||
SaleMarkup: req.SaleMarkup,
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -16,13 +16,12 @@ func NewQuoteHandler(quoteService *services.QuoteService) *QuoteHandler {
|
||||
}
|
||||
|
||||
func (h *QuoteHandler) Validate(c *gin.Context) {
|
||||
var req services.QuoteRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
|
||||
req, ok := BindJSON[services.QuoteRequest](c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.quoteService.ValidateAndCalculate(&req)
|
||||
result, err := h.quoteService.ValidateAndCalculate(req)
|
||||
if err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
|
||||
return
|
||||
@@ -32,13 +31,12 @@ func (h *QuoteHandler) Validate(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (h *QuoteHandler) Calculate(c *gin.Context) {
|
||||
var req services.QuoteRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
|
||||
req, ok := BindJSON[services.QuoteRequest](c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.quoteService.ValidateAndCalculate(&req)
|
||||
result, err := h.quoteService.ValidateAndCalculate(req)
|
||||
if err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
|
||||
return
|
||||
@@ -51,13 +49,12 @@ func (h *QuoteHandler) Calculate(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (h *QuoteHandler) PriceLevels(c *gin.Context) {
|
||||
var req services.PriceLevelsRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
|
||||
req, ok := BindJSON[services.PriceLevelsRequest](c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.quoteService.CalculatePriceLevels(&req)
|
||||
result, err := h.quoteService.CalculatePriceLevels(req)
|
||||
if err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
|
||||
return
|
||||
|
||||
@@ -4,8 +4,10 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -13,9 +15,30 @@ func RespondError(c *gin.Context, status int, fallback string, err error) {
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
}
|
||||
// A write refused over unknown configuration feature flags is a 409 with the flag list,
|
||||
// whatever status the caller picked — every config write path funnels through here.
|
||||
if ue, ok := configfeatures.AsUnsupported(err); ok {
|
||||
c.JSON(http.StatusConflict, gin.H{
|
||||
"error": ue.Error(),
|
||||
"code": "unsupported_config_features",
|
||||
"unsupported_features": ue.Flags,
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(status, gin.H{"error": clientFacingErrorMessage(status, fallback, err)})
|
||||
}
|
||||
|
||||
// BindJSON decodes the request body into T, responding with a 422 and writing
|
||||
// the error via RespondError on failure. The second return value reports success.
|
||||
func BindJSON[T any](c *gin.Context) (*T, bool) {
|
||||
var req T
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
|
||||
return nil, false
|
||||
}
|
||||
return &req, true
|
||||
}
|
||||
|
||||
func clientFacingErrorMessage(status int, fallback string, err error) string {
|
||||
if err == nil {
|
||||
return fallback
|
||||
|
||||
@@ -2,7 +2,13 @@ package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestClientFacingErrorMessageKeepsDomain4xx(t *testing.T) {
|
||||
@@ -39,3 +45,26 @@ type errString string
|
||||
func (e errString) Error() string {
|
||||
return string(e)
|
||||
}
|
||||
|
||||
func TestRespondErrorUnsupportedFeaturesIs409(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
|
||||
err := fmt.Errorf("wrapped: %w", configfeatures.Check([]string{"future_x"}))
|
||||
RespondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want 409", w.Code)
|
||||
}
|
||||
var body struct {
|
||||
Code string `json:"code"`
|
||||
Features []string `json:"unsupported_features"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode body: %v", err)
|
||||
}
|
||||
if body.Code != "unsupported_config_features" || len(body.Features) != 1 || body.Features[0] != "future_x" {
|
||||
t.Fatalf("unexpected body %s", w.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// SettingsHandler serves per-client UI display preferences stored in app_settings.
|
||||
type SettingsHandler struct {
|
||||
localDB *localdb.LocalDB
|
||||
}
|
||||
|
||||
func NewSettingsHandler(localDB *localdb.LocalDB) *SettingsHandler {
|
||||
return &SettingsHandler{localDB: localDB}
|
||||
}
|
||||
|
||||
type uiSettingsResponse struct {
|
||||
IndicatorMode string `json:"indicator_mode"`
|
||||
}
|
||||
|
||||
// GetUI returns the current UI display preferences.
|
||||
func (h *SettingsHandler) GetUI(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, uiSettingsResponse{
|
||||
IndicatorMode: h.localDB.GetIndicatorMode(),
|
||||
})
|
||||
}
|
||||
|
||||
// PutUI updates UI display preferences. Currently only indicator_mode.
|
||||
func (h *SettingsHandler) PutUI(c *gin.Context) {
|
||||
req, ok := BindJSON[struct {
|
||||
IndicatorMode string `json:"indicator_mode"`
|
||||
}](c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.localDB.SetIndicatorMode(req.IndicatorMode); err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid indicator_mode", err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, uiSettingsResponse{
|
||||
IndicatorMode: h.localDB.GetIndicatorMode(),
|
||||
})
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
qfassets "git.mchus.pro/mchus/quoteforge"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/appmeta"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/db"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -56,7 +57,9 @@ func (h *SetupHandler) ShowSetup(c *gin.Context) {
|
||||
settings, _ := h.localDB.GetSettings()
|
||||
|
||||
data := gin.H{
|
||||
"Settings": settings,
|
||||
"Settings": settings,
|
||||
"IndicatorMode": h.localDB.GetIndicatorMode(),
|
||||
"AppVersion": appmeta.Version(),
|
||||
}
|
||||
|
||||
tmpl := h.templates["setup.html"]
|
||||
@@ -207,4 +210,3 @@ func buildMySQLDSN(host string, port int, database, user, password string, timeo
|
||||
}
|
||||
return cfg.FormatDSN()
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+13
-96
@@ -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"`
|
||||
@@ -293,7 +240,7 @@ type SyncAllResponse struct {
|
||||
|
||||
// SyncAll performs full bidirectional sync:
|
||||
// - push pending local changes (projects/configurations) to server
|
||||
// - pull components, pricelists, projects, and configurations from server
|
||||
// - pull components, pricelists, qt_settings, projects, and configurations from server
|
||||
// POST /api/sync/all
|
||||
func (h *SyncHandler) SyncAll(c *gin.Context) {
|
||||
if !h.ensureSyncReadiness(c) {
|
||||
@@ -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
|
||||
@@ -368,6 +282,12 @@ func (h *SyncHandler) SyncAll(c *gin.Context) {
|
||||
slog.Warn("partnumber books pull failed during full sync", "error", err)
|
||||
}
|
||||
|
||||
// Configurator settings (config_types, tab_config, ...): non-fatal, the
|
||||
// local cache is kept on failure.
|
||||
if err := h.syncService.SyncQtSettings(); err != nil {
|
||||
slog.Warn("qt_settings sync failed during full sync", "error", err)
|
||||
}
|
||||
|
||||
projectsResult, err := h.syncService.ImportProjectsToLocal()
|
||||
if err != nil {
|
||||
slog.Error("project import failed during full sync", "error", err)
|
||||
@@ -375,7 +295,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 +308,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 +321,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 +481,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) {
|
||||
|
||||
@@ -114,6 +114,10 @@ func NewWebHandler(_ string, localDB *localdb.LocalDB) (*WebHandler, error) {
|
||||
|
||||
func (h *WebHandler) render(c *gin.Context, name string, data gin.H) {
|
||||
data["AppVersion"] = appmeta.Version()
|
||||
data["IndicatorMode"] = localdb.IndicatorModeColor
|
||||
if h.localDB != nil {
|
||||
data["IndicatorMode"] = h.localDB.GetIndicatorMode()
|
||||
}
|
||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||
tmpl, ok := h.templates[name]
|
||||
if !ok {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -19,7 +19,6 @@ func TestConfigurationConvertersPreserveBusinessFields(t *testing.T) {
|
||||
WarehousePricelistID: &warehouseID,
|
||||
CompetitorPricelistID: &competitorID,
|
||||
DisablePriceRefresh: true,
|
||||
OnlyInStock: true,
|
||||
}
|
||||
|
||||
local := ConfigurationToLocal(cfg)
|
||||
@@ -57,7 +56,6 @@ func TestConfigurationSnapshotPreservesBusinessFields(t *testing.T) {
|
||||
WarehousePricelistID: &warehouseID,
|
||||
CompetitorPricelistID: &competitorID,
|
||||
DisablePriceRefresh: true,
|
||||
OnlyInStock: true,
|
||||
VendorSpec: VendorSpec{
|
||||
{
|
||||
SortOrder: 10,
|
||||
@@ -110,7 +108,6 @@ func TestConfigurationFingerprintIncludesPricingSelectorsAndVendorSpec(t *testin
|
||||
WarehousePricelistID: &warehouseID,
|
||||
CompetitorPricelistID: &competitorID,
|
||||
DisablePriceRefresh: true,
|
||||
OnlyInStock: true,
|
||||
VendorSpec: VendorSpec{
|
||||
{
|
||||
SortOrder: 10,
|
||||
|
||||
+107
-80
@@ -3,15 +3,52 @@ package localdb
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
|
||||
"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,
|
||||
}
|
||||
@@ -26,6 +63,7 @@ func ConfigurationToLocal(cfg *models.Configuration) *LocalConfiguration {
|
||||
TotalPrice: cfg.TotalPrice,
|
||||
CustomPrice: cfg.CustomPrice,
|
||||
Notes: cfg.Notes,
|
||||
FeatureFlags: cfg.FeatureFlags,
|
||||
IsTemplate: cfg.IsTemplate,
|
||||
ServerCount: cfg.ServerCount,
|
||||
ServerModel: cfg.ServerModel,
|
||||
@@ -37,7 +75,8 @@ func ConfigurationToLocal(cfg *models.Configuration) *LocalConfiguration {
|
||||
ConfigType: cfg.ConfigType,
|
||||
VendorSpec: modelVendorSpecToLocal(cfg.VendorSpec),
|
||||
DisablePriceRefresh: cfg.DisablePriceRefresh,
|
||||
OnlyInStock: cfg.OnlyInStock,
|
||||
RentalItems: modelRentalItemsToLocal(cfg.RentalItems),
|
||||
RentalUpliftPercent: cfg.RentalUpliftPercent,
|
||||
Line: cfg.Line,
|
||||
PriceUpdatedAt: cfg.PriceUpdatedAt,
|
||||
CreatedAt: cfg.CreatedAt,
|
||||
@@ -75,6 +114,8 @@ func LocalToConfiguration(local *LocalConfiguration) *models.Configuration {
|
||||
TotalPrice: local.TotalPrice,
|
||||
CustomPrice: local.CustomPrice,
|
||||
Notes: local.Notes,
|
||||
FeatureFlags: local.FeatureFlags,
|
||||
UnsupportedFeatures: configfeatures.Unknown(local.FeatureFlags),
|
||||
IsTemplate: local.IsTemplate,
|
||||
ServerCount: local.ServerCount,
|
||||
ServerModel: local.ServerModel,
|
||||
@@ -86,7 +127,8 @@ func LocalToConfiguration(local *LocalConfiguration) *models.Configuration {
|
||||
ConfigType: local.ConfigType,
|
||||
VendorSpec: localVendorSpecToModel(local.VendorSpec),
|
||||
DisablePriceRefresh: local.DisablePriceRefresh,
|
||||
OnlyInStock: local.OnlyInStock,
|
||||
RentalItems: localRentalItemsToModel(local.RentalItems),
|
||||
RentalUpliftPercent: local.RentalUpliftPercent,
|
||||
Line: local.Line,
|
||||
PriceUpdatedAt: local.PriceUpdatedAt,
|
||||
CreatedAt: local.CreatedAt,
|
||||
@@ -195,19 +237,44 @@ 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,
|
||||
OwnerUsername: project.OwnerUsername,
|
||||
Code: project.Code,
|
||||
Variant: project.Variant,
|
||||
Name: project.Name,
|
||||
TrackerURL: project.TrackerURL,
|
||||
IsActive: project.IsActive,
|
||||
IsSystem: project.IsSystem,
|
||||
CreatedAt: project.CreatedAt,
|
||||
UpdatedAt: project.UpdatedAt,
|
||||
SyncStatus: "pending",
|
||||
UUID: project.UUID,
|
||||
OwnerUsername: project.OwnerUsername,
|
||||
Code: project.Code,
|
||||
Variant: project.Variant,
|
||||
Name: project.Name,
|
||||
TrackerURL: project.TrackerURL,
|
||||
IsActive: project.IsActive,
|
||||
IsSystem: project.IsSystem,
|
||||
RentalEnabled: project.RentalEnabled,
|
||||
ShowStockPrices: project.ShowStockPrices,
|
||||
OnlyInStock: project.OnlyInStock,
|
||||
CreatedAt: project.CreatedAt,
|
||||
UpdatedAt: project.UpdatedAt,
|
||||
SyncStatus: "pending",
|
||||
}
|
||||
if project.ID > 0 {
|
||||
serverID := project.ID
|
||||
@@ -218,16 +285,19 @@ func ProjectToLocal(project *models.Project) *LocalProject {
|
||||
|
||||
func LocalToProject(local *LocalProject) *models.Project {
|
||||
project := &models.Project{
|
||||
UUID: local.UUID,
|
||||
OwnerUsername: local.OwnerUsername,
|
||||
Code: local.Code,
|
||||
Variant: local.Variant,
|
||||
Name: local.Name,
|
||||
TrackerURL: local.TrackerURL,
|
||||
IsActive: local.IsActive,
|
||||
IsSystem: local.IsSystem,
|
||||
CreatedAt: local.CreatedAt,
|
||||
UpdatedAt: local.UpdatedAt,
|
||||
UUID: local.UUID,
|
||||
OwnerUsername: local.OwnerUsername,
|
||||
Code: local.Code,
|
||||
Variant: local.Variant,
|
||||
Name: local.Name,
|
||||
TrackerURL: local.TrackerURL,
|
||||
IsActive: local.IsActive,
|
||||
IsSystem: local.IsSystem,
|
||||
RentalEnabled: local.RentalEnabled,
|
||||
ShowStockPrices: local.ShowStockPrices,
|
||||
OnlyInStock: local.OnlyInStock,
|
||||
CreatedAt: local.CreatedAt,
|
||||
UpdatedAt: local.UpdatedAt,
|
||||
}
|
||||
if local.ServerID != nil {
|
||||
project.ID = *local.ServerID
|
||||
@@ -267,68 +337,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",
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package localdb
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newModeDB(t *testing.T) *LocalDB {
|
||||
t.Helper()
|
||||
local, err := New(filepath.Join(t.TempDir(), "mode.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open localdb: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = local.Close() })
|
||||
return local
|
||||
}
|
||||
|
||||
func TestIndicatorMode(t *testing.T) {
|
||||
local := newModeDB(t)
|
||||
|
||||
if got := local.GetIndicatorMode(); got != IndicatorModeColor {
|
||||
t.Fatalf("unset: got %q, want %q", got, IndicatorModeColor)
|
||||
}
|
||||
|
||||
if err := local.SetIndicatorMode(IndicatorModeAccessible); err != nil {
|
||||
t.Fatalf("set accessible: %v", err)
|
||||
}
|
||||
if got := local.GetIndicatorMode(); got != IndicatorModeAccessible {
|
||||
t.Fatalf("after set accessible: got %q, want %q", got, IndicatorModeAccessible)
|
||||
}
|
||||
|
||||
if err := local.SetIndicatorMode(IndicatorModeColor); err != nil {
|
||||
t.Fatalf("set color: %v", err)
|
||||
}
|
||||
if got := local.GetIndicatorMode(); got != IndicatorModeColor {
|
||||
t.Fatalf("after set color: got %q, want %q", got, IndicatorModeColor)
|
||||
}
|
||||
|
||||
if err := local.SetIndicatorMode("rainbow"); err == nil {
|
||||
t.Fatal("expected error for invalid mode, got nil")
|
||||
}
|
||||
if got := local.GetIndicatorMode(); got != IndicatorModeColor {
|
||||
t.Fatalf("after rejected set: got %q, want %q", got, IndicatorModeColor)
|
||||
}
|
||||
}
|
||||
+284
-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,9 @@ 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,
|
||||
show_stock_prices INTEGER NOT NULL DEFAULT 0,
|
||||
only_in_stock INTEGER NOT NULL DEFAULT 0,
|
||||
created_at DATETIME,
|
||||
updated_at DATETIME,
|
||||
synced_at DATETIME NULL,
|
||||
@@ -224,7 +236,6 @@ func autoMigrateLocalSchema(db *gorm.DB) error {
|
||||
&LocalConfigurationVersion{},
|
||||
&LocalPricelist{},
|
||||
&LocalPricelistItem{},
|
||||
&LocalComponent{},
|
||||
&AppSetting{},
|
||||
&LocalSyncGuardState{},
|
||||
&PendingChange{},
|
||||
@@ -700,6 +711,14 @@ func (l *LocalDB) GetProjectByCode(code string) (*LocalProject, error) {
|
||||
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 {
|
||||
@@ -1111,6 +1130,43 @@ func (l *LocalDB) upsertAppSetting(tx *gorm.DB, key, value string, updatedAt tim
|
||||
`, key, value, updatedAt.Format(time.RFC3339)).Error
|
||||
}
|
||||
|
||||
// Indicator display mode: how the UI renders signals that are otherwise carried
|
||||
// by colour alone (price-quality scale, world-fallback price cells, incomplete
|
||||
// pricing totals). "color" (default) keeps the hue coding; "accessible" swaps it
|
||||
// for shape/text so it stays readable with a colour-vision deficiency. Per-client
|
||||
// preference stored in app_settings; consumed by web/static/price-quality.js and
|
||||
// the pricing tab via base.html's window.QF_INDICATOR_MODE.
|
||||
const (
|
||||
IndicatorModeColor = "color"
|
||||
IndicatorModeAccessible = "accessible"
|
||||
)
|
||||
|
||||
// GetIndicatorMode returns the stored indicator display mode, falling back to
|
||||
// "color" when unset or invalid.
|
||||
func (l *LocalDB) GetIndicatorMode() string {
|
||||
value, ok := l.getAppSettingValue("indicator_mode")
|
||||
if !ok {
|
||||
return IndicatorModeColor
|
||||
}
|
||||
switch strings.TrimSpace(value) {
|
||||
case IndicatorModeAccessible:
|
||||
return IndicatorModeAccessible
|
||||
default:
|
||||
return IndicatorModeColor
|
||||
}
|
||||
}
|
||||
|
||||
// SetIndicatorMode stores the indicator display mode. Only the two known
|
||||
// literals are accepted.
|
||||
func (l *LocalDB) SetIndicatorMode(mode string) error {
|
||||
mode = strings.TrimSpace(mode)
|
||||
if mode != IndicatorModeColor && mode != IndicatorModeAccessible {
|
||||
return fmt.Errorf("invalid indicator mode %q", mode)
|
||||
}
|
||||
now := time.Now()
|
||||
return l.upsertAppSetting(l.db, "indicator_mode", mode, now)
|
||||
}
|
||||
|
||||
// SetLastSyncTime sets the last sync timestamp
|
||||
func (l *LocalDB) SetLastSyncTime(t time.Time) error {
|
||||
// Using raw SQL for upsert since SQLite doesn't have native UPSERT in all versions
|
||||
@@ -1229,24 +1285,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
|
||||
@@ -1263,11 +1361,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.
|
||||
@@ -1279,11 +1376,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 {
|
||||
@@ -1292,11 +1389,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 {
|
||||
@@ -1305,6 +1411,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
|
||||
@@ -1372,6 +1489,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
|
||||
@@ -1436,10 +1577,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
|
||||
}
|
||||
@@ -1447,26 +1589,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
|
||||
@@ -1489,15 +1644,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
|
||||
}
|
||||
@@ -1650,6 +1862,17 @@ func (l *LocalDB) MarkChangesSynced(ids []int64) error {
|
||||
return l.db.Where("id IN ?", ids).Delete(&PendingChange{}).Error
|
||||
}
|
||||
|
||||
// ListConfigurationsPendingWithoutQueue returns configurations still marked pending
|
||||
// whose pending_changes rows are gone, so nothing will ever push them.
|
||||
func (l *LocalDB) ListConfigurationsPendingWithoutQueue() ([]LocalConfiguration, error) {
|
||||
var configs []LocalConfiguration
|
||||
err := l.db.Where(
|
||||
"sync_status = ? AND uuid NOT IN (SELECT entity_uuid FROM pending_changes WHERE entity_type = ?)",
|
||||
"pending", "configuration",
|
||||
).Find(&configs).Error
|
||||
return configs, err
|
||||
}
|
||||
|
||||
// PurgeOrphanConfigurationPendingChanges removes configuration pending changes
|
||||
// whose entity_uuid no longer exists in local_configurations.
|
||||
func (l *LocalDB) PurgeOrphanConfigurationPendingChanges() (int64, error) {
|
||||
@@ -1681,12 +1904,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)
|
||||
}
|
||||
@@ -1697,7 +1921,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,
|
||||
@@ -1713,12 +1943,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
|
||||
@@ -1744,7 +1975,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
|
||||
}
|
||||
@@ -1765,18 +1996,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
|
||||
@@ -1788,7 +2020,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
|
||||
@@ -1797,11 +2029,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.
|
||||
@@ -1863,28 +2095,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,150 @@ 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,
|
||||
},
|
||||
{
|
||||
id: "2026_08_12_local_project_stock_settings",
|
||||
name: "Add show_stock_prices and only_in_stock to local_projects",
|
||||
run: addLocalProjectStockSettings,
|
||||
},
|
||||
}
|
||||
|
||||
func addLocalPricelistItemPriceQuality(tx *gorm.DB) error {
|
||||
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
|
||||
}
|
||||
|
||||
func addLocalProjectStockSettings(tx *gorm.DB) error {
|
||||
stmts := []string{
|
||||
`ALTER TABLE local_projects ADD COLUMN show_stock_prices INTEGER NOT NULL DEFAULT 0`,
|
||||
`ALTER TABLE local_projects ADD COLUMN only_in_stock INTEGER NOT NULL DEFAULT 0`,
|
||||
}
|
||||
for _, stmt := range stmts {
|
||||
if err := tx.Exec(stmt).Error; err != nil {
|
||||
if !strings.Contains(strings.ToLower(err.Error()), "duplicate") &&
|
||||
!strings.Contains(strings.ToLower(err.Error()), "exists") {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type localPartnumberCatalogRow struct {
|
||||
|
||||
+78
-27
@@ -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 {
|
||||
@@ -94,6 +102,7 @@ type LocalConfiguration struct {
|
||||
TotalPrice *float64 `json:"total_price"`
|
||||
CustomPrice *float64 `json:"custom_price"`
|
||||
Notes string `json:"notes"`
|
||||
FeatureFlags models.FeatureFlags `gorm:"type:text" json:"feature_flags,omitempty"`
|
||||
IsTemplate bool `gorm:"default:false" json:"is_template"`
|
||||
ServerCount int `gorm:"default:1" json:"server_count"`
|
||||
ServerModel string `gorm:"size:100" json:"server_model,omitempty"`
|
||||
@@ -103,14 +112,15 @@ type LocalConfiguration struct {
|
||||
WarehousePricelistID *uint `gorm:"index" json:"warehouse_pricelist_id,omitempty"`
|
||||
CompetitorPricelistID *uint `gorm:"index" json:"competitor_pricelist_id,omitempty"`
|
||||
DisablePriceRefresh bool `gorm:"default:false" json:"disable_price_refresh"`
|
||||
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
|
||||
RentalItems RentalItemConditions `gorm:"type:text" json:"rental_items,omitempty"`
|
||||
RentalUpliftPercent float64 `gorm:"default:0" json:"rental_uplift_percent"`
|
||||
VendorSpec VendorSpec `gorm:"type:text" json:"vendor_spec,omitempty"`
|
||||
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"`
|
||||
@@ -123,20 +133,23 @@ func (LocalConfiguration) TableName() string {
|
||||
}
|
||||
|
||||
type LocalProject struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"uniqueIndex;not null" json:"uuid"`
|
||||
ServerID *uint `json:"server_id,omitempty"`
|
||||
OwnerUsername string `gorm:"not null;index" json:"owner_username"`
|
||||
Code string `gorm:"not null;index:idx_local_projects_code_variant,priority:1" json:"code"`
|
||||
Variant string `gorm:"default:'';index:idx_local_projects_code_variant,priority:2" json:"variant"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
TrackerURL string `json:"tracker_url"`
|
||||
IsActive bool `gorm:"default:true;index" json:"is_active"`
|
||||
IsSystem bool `gorm:"default:false;index" json:"is_system"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
SyncedAt *time.Time `json:"synced_at,omitempty"`
|
||||
SyncStatus string `gorm:"default:'local'" json:"sync_status"` // local/synced/pending
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"uniqueIndex;not null" json:"uuid"`
|
||||
ServerID *uint `json:"server_id,omitempty"`
|
||||
OwnerUsername string `gorm:"not null;index" json:"owner_username"`
|
||||
Code string `gorm:"not null;index:idx_local_projects_code_variant,priority:1" json:"code"`
|
||||
Variant string `gorm:"default:'';index:idx_local_projects_code_variant,priority:2" json:"variant"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
TrackerURL string `json:"tracker_url"`
|
||||
IsActive bool `gorm:"default:true;index" json:"is_active"`
|
||||
IsSystem bool `gorm:"default:false;index" json:"is_system"`
|
||||
RentalEnabled bool `gorm:"default:false" json:"rental_enabled"`
|
||||
ShowStockPrices bool `gorm:"default:false" json:"show_stock_prices"`
|
||||
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
SyncedAt *time.Time `json:"synced_at,omitempty"`
|
||||
SyncStatus string `gorm:"default:'local'" json:"sync_status"` // local/synced/pending
|
||||
}
|
||||
|
||||
func (LocalProject) TableName() string {
|
||||
@@ -169,7 +182,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 +192,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 +215,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 +307,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 +371,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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
)
|
||||
|
||||
// BuildConfigurationSnapshot serializes the full local configuration state.
|
||||
@@ -21,6 +23,7 @@ func BuildConfigurationSnapshot(localCfg *LocalConfiguration) (string, error) {
|
||||
"total_price": localCfg.TotalPrice,
|
||||
"custom_price": localCfg.CustomPrice,
|
||||
"notes": localCfg.Notes,
|
||||
"feature_flags": localCfg.FeatureFlags,
|
||||
"is_template": localCfg.IsTemplate,
|
||||
"server_count": localCfg.ServerCount,
|
||||
"server_model": localCfg.ServerModel,
|
||||
@@ -30,7 +33,8 @@ func BuildConfigurationSnapshot(localCfg *LocalConfiguration) (string, error) {
|
||||
"warehouse_pricelist_id": localCfg.WarehousePricelistID,
|
||||
"competitor_pricelist_id": localCfg.CompetitorPricelistID,
|
||||
"disable_price_refresh": localCfg.DisablePriceRefresh,
|
||||
"only_in_stock": localCfg.OnlyInStock,
|
||||
"rental_items": localCfg.RentalItems,
|
||||
"rental_uplift_percent": localCfg.RentalUpliftPercent,
|
||||
"vendor_spec": localCfg.VendorSpec,
|
||||
"line": localCfg.Line,
|
||||
"price_updated_at": localCfg.PriceUpdatedAt,
|
||||
@@ -52,28 +56,30 @@ func BuildConfigurationSnapshot(localCfg *LocalConfiguration) (string, error) {
|
||||
// DecodeConfigurationSnapshot returns editable fields from one saved snapshot.
|
||||
func DecodeConfigurationSnapshot(data string) (*LocalConfiguration, error) {
|
||||
var snapshot struct {
|
||||
ProjectUUID *string `json:"project_uuid"`
|
||||
IsActive *bool `json:"is_active"`
|
||||
Name string `json:"name"`
|
||||
Items LocalConfigItems `json:"items"`
|
||||
TotalPrice *float64 `json:"total_price"`
|
||||
CustomPrice *float64 `json:"custom_price"`
|
||||
Notes string `json:"notes"`
|
||||
IsTemplate bool `json:"is_template"`
|
||||
ServerCount int `json:"server_count"`
|
||||
ServerModel string `json:"server_model"`
|
||||
SupportCode string `json:"support_code"`
|
||||
Article string `json:"article"`
|
||||
PricelistID *uint `json:"pricelist_id"`
|
||||
WarehousePricelistID *uint `json:"warehouse_pricelist_id"`
|
||||
CompetitorPricelistID *uint `json:"competitor_pricelist_id"`
|
||||
DisablePriceRefresh bool `json:"disable_price_refresh"`
|
||||
OnlyInStock bool `json:"only_in_stock"`
|
||||
VendorSpec VendorSpec `json:"vendor_spec"`
|
||||
Line int `json:"line"`
|
||||
PriceUpdatedAt *time.Time `json:"price_updated_at"`
|
||||
OriginalUserID uint `json:"original_user_id"`
|
||||
OriginalUsername string `json:"original_username"`
|
||||
ProjectUUID *string `json:"project_uuid"`
|
||||
IsActive *bool `json:"is_active"`
|
||||
Name string `json:"name"`
|
||||
Items LocalConfigItems `json:"items"`
|
||||
TotalPrice *float64 `json:"total_price"`
|
||||
CustomPrice *float64 `json:"custom_price"`
|
||||
Notes string `json:"notes"`
|
||||
FeatureFlags models.FeatureFlags `json:"feature_flags"`
|
||||
IsTemplate bool `json:"is_template"`
|
||||
ServerCount int `json:"server_count"`
|
||||
ServerModel string `json:"server_model"`
|
||||
SupportCode string `json:"support_code"`
|
||||
Article string `json:"article"`
|
||||
PricelistID *uint `json:"pricelist_id"`
|
||||
WarehousePricelistID *uint `json:"warehouse_pricelist_id"`
|
||||
CompetitorPricelistID *uint `json:"competitor_pricelist_id"`
|
||||
DisablePriceRefresh bool `json:"disable_price_refresh"`
|
||||
RentalItems RentalItemConditions `json:"rental_items"`
|
||||
RentalUpliftPercent float64 `json:"rental_uplift_percent"`
|
||||
VendorSpec VendorSpec `json:"vendor_spec"`
|
||||
Line int `json:"line"`
|
||||
PriceUpdatedAt *time.Time `json:"price_updated_at"`
|
||||
OriginalUserID uint `json:"original_user_id"`
|
||||
OriginalUsername string `json:"original_username"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal([]byte(data), &snapshot); err != nil {
|
||||
@@ -93,6 +99,7 @@ func DecodeConfigurationSnapshot(data string) (*LocalConfiguration, error) {
|
||||
TotalPrice: snapshot.TotalPrice,
|
||||
CustomPrice: snapshot.CustomPrice,
|
||||
Notes: snapshot.Notes,
|
||||
FeatureFlags: snapshot.FeatureFlags,
|
||||
IsTemplate: snapshot.IsTemplate,
|
||||
ServerCount: snapshot.ServerCount,
|
||||
ServerModel: snapshot.ServerModel,
|
||||
@@ -102,7 +109,8 @@ func DecodeConfigurationSnapshot(data string) (*LocalConfiguration, error) {
|
||||
WarehousePricelistID: snapshot.WarehousePricelistID,
|
||||
CompetitorPricelistID: snapshot.CompetitorPricelistID,
|
||||
DisablePriceRefresh: snapshot.DisablePriceRefresh,
|
||||
OnlyInStock: snapshot.OnlyInStock,
|
||||
RentalItems: snapshot.RentalItems,
|
||||
RentalUpliftPercent: snapshot.RentalUpliftPercent,
|
||||
VendorSpec: snapshot.VendorSpec,
|
||||
Line: snapshot.Line,
|
||||
PriceUpdatedAt: snapshot.PriceUpdatedAt,
|
||||
@@ -120,7 +128,8 @@ type configurationSpecPriceFingerprint struct {
|
||||
WarehousePricelistID *uint `json:"warehouse_pricelist_id,omitempty"`
|
||||
CompetitorPricelistID *uint `json:"competitor_pricelist_id,omitempty"`
|
||||
DisablePriceRefresh bool `json:"disable_price_refresh"`
|
||||
OnlyInStock bool `json:"only_in_stock"`
|
||||
RentalItems RentalItemConditions `json:"rental_items,omitempty"`
|
||||
RentalUpliftPercent float64 `json:"rental_uplift_percent"`
|
||||
VendorSpec VendorSpec `json:"vendor_spec,omitempty"`
|
||||
}
|
||||
|
||||
@@ -151,6 +160,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,
|
||||
@@ -160,7 +175,8 @@ func BuildConfigurationSpecPriceFingerprint(localCfg *LocalConfiguration) (strin
|
||||
WarehousePricelistID: localCfg.WarehousePricelistID,
|
||||
CompetitorPricelistID: localCfg.CompetitorPricelistID,
|
||||
DisablePriceRefresh: localCfg.DisablePriceRefresh,
|
||||
OnlyInStock: localCfg.OnlyInStock,
|
||||
RentalItems: rentalItems,
|
||||
RentalUpliftPercent: localCfg.RentalUpliftPercent,
|
||||
VendorSpec: localCfg.VendorSpec,
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +31,40 @@ func (c *ConfigItems) Scan(value interface{}) error {
|
||||
return json.Unmarshal(bytes, c)
|
||||
}
|
||||
|
||||
// FeatureFlags lists the data features a configuration uses (see internal/configfeatures).
|
||||
// Stored as a JSON array; an empty list is stored as NULL.
|
||||
type FeatureFlags []string
|
||||
|
||||
func (f FeatureFlags) Value() (driver.Value, error) {
|
||||
if len(f) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
data, err := json.Marshal([]string(f))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
func (f *FeatureFlags) Scan(value interface{}) error {
|
||||
*f = nil
|
||||
var data []byte
|
||||
switch v := value.(type) {
|
||||
case nil:
|
||||
return nil
|
||||
case []byte:
|
||||
data = v
|
||||
case string:
|
||||
data = []byte(v)
|
||||
default:
|
||||
return errors.New("type assertion failed for FeatureFlags")
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(data, f)
|
||||
}
|
||||
|
||||
func (c ConfigItems) Total() float64 {
|
||||
var total float64
|
||||
for _, item := range c {
|
||||
@@ -64,6 +98,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) {
|
||||
@@ -91,36 +160,38 @@ func (v *VendorSpec) Scan(value interface{}) error {
|
||||
}
|
||||
|
||||
type Configuration struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"size:36;uniqueIndex;not null" json:"uuid"`
|
||||
UserID *uint `json:"user_id,omitempty"` // Legacy field, no longer required for ownership
|
||||
OwnerUsername string `gorm:"size:100;not null;default:'';index" json:"owner_username"`
|
||||
ProjectUUID *string `gorm:"size:36;index" json:"project_uuid,omitempty"`
|
||||
AppVersion string `gorm:"size:64" json:"app_version,omitempty"`
|
||||
Name string `gorm:"size:200;not null" json:"name"`
|
||||
Items ConfigItems `gorm:"type:json;not null" json:"items"`
|
||||
TotalPrice *float64 `gorm:"type:decimal(12,2)" json:"total_price"`
|
||||
CustomPrice *float64 `gorm:"type:decimal(12,2)" json:"custom_price"`
|
||||
Notes string `gorm:"type:text" json:"notes"`
|
||||
IsTemplate bool `gorm:"default:false" json:"is_template"`
|
||||
ServerCount int `gorm:"default:1" json:"server_count"`
|
||||
ServerModel string `gorm:"size:100" json:"server_model,omitempty"`
|
||||
SupportCode string `gorm:"size:20" json:"support_code,omitempty"`
|
||||
Article string `gorm:"size:80" json:"article,omitempty"`
|
||||
PricelistID *uint `gorm:"index" json:"pricelist_id,omitempty"`
|
||||
WarehousePricelistID *uint `gorm:"index" json:"warehouse_pricelist_id,omitempty"`
|
||||
CompetitorPricelistID *uint `gorm:"index" json:"competitor_pricelist_id,omitempty"`
|
||||
VendorSpec VendorSpec `gorm:"type:json" json:"vendor_spec,omitempty"`
|
||||
ConfigType string `gorm:"size:20;default:server" json:"config_type"` // "server" | "storage"
|
||||
DisablePriceRefresh bool `gorm:"default:false" json:"disable_price_refresh"`
|
||||
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
|
||||
Line int `gorm:"column:line_no;index" json:"line"`
|
||||
PriceUpdatedAt *time.Time `gorm:"type:timestamp" json:"price_updated_at,omitempty"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
CurrentVersionNo int `gorm:"-" json:"current_version_no,omitempty"`
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"size:36;uniqueIndex;not null" json:"uuid"`
|
||||
UserID *uint `json:"user_id,omitempty"` // Legacy field, no longer required for ownership
|
||||
OwnerUsername string `gorm:"size:100;not null;default:'';index" json:"owner_username"`
|
||||
ProjectUUID *string `gorm:"size:36;index" json:"project_uuid,omitempty"`
|
||||
AppVersion string `gorm:"size:64" json:"app_version,omitempty"`
|
||||
Name string `gorm:"size:200;not null" json:"name"`
|
||||
Items ConfigItems `gorm:"type:json;not null" json:"items"`
|
||||
TotalPrice *float64 `gorm:"type:decimal(12,2)" json:"total_price"`
|
||||
CustomPrice *float64 `gorm:"type:decimal(12,2)" json:"custom_price"`
|
||||
Notes string `gorm:"type:text" json:"notes"`
|
||||
FeatureFlags FeatureFlags `gorm:"type:json" json:"feature_flags,omitempty"`
|
||||
UnsupportedFeatures []string `gorm:"-" json:"unsupported_features,omitempty"` // flags this build doesn't know; computed on read
|
||||
IsTemplate bool `gorm:"default:false" json:"is_template"`
|
||||
ServerCount int `gorm:"default:1" json:"server_count"`
|
||||
ServerModel string `gorm:"size:100" json:"server_model,omitempty"`
|
||||
SupportCode string `gorm:"size:20" json:"support_code,omitempty"`
|
||||
Article string `gorm:"size:80" json:"article,omitempty"`
|
||||
PricelistID *uint `gorm:"index" json:"pricelist_id,omitempty"`
|
||||
WarehousePricelistID *uint `gorm:"index" json:"warehouse_pricelist_id,omitempty"`
|
||||
CompetitorPricelistID *uint `gorm:"index" json:"competitor_pricelist_id,omitempty"`
|
||||
VendorSpec VendorSpec `gorm:"type:json" json:"vendor_spec,omitempty"`
|
||||
ConfigType string `gorm:"size:20;default:server" json:"config_type"` // "server" | "storage"
|
||||
DisablePriceRefresh bool `gorm:"default:false" json:"disable_price_refresh"`
|
||||
RentalItems RentalItemConditions `gorm:"type:json" json:"rental_items,omitempty"`
|
||||
RentalUpliftPercent float64 `gorm:"type:decimal(8,2);default:0" json:"rental_uplift_percent"`
|
||||
Line int `gorm:"column:line_no;index" json:"line"`
|
||||
PriceUpdatedAt *time.Time `gorm:"type:timestamp" json:"price_updated_at,omitempty"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
CurrentVersionNo int `gorm:"-" json:"current_version_no,omitempty"`
|
||||
}
|
||||
|
||||
func (Configuration) TableName() string {
|
||||
return "qt_configurations"
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,58 +1,6 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// AllModels returns all models for auto-migration
|
||||
func AllModels() []interface{} {
|
||||
return []interface{}{
|
||||
&Category{},
|
||||
&LotMetadata{},
|
||||
&Project{},
|
||||
&Configuration{},
|
||||
&Pricelist{},
|
||||
&PricelistItem{},
|
||||
}
|
||||
}
|
||||
|
||||
// Migrate runs auto-migration for all QuoteForge tables
|
||||
// Handles MySQL constraint errors gracefully for existing tables
|
||||
func Migrate(db *gorm.DB) error {
|
||||
for _, model := range AllModels() {
|
||||
if err := db.AutoMigrate(model); err != nil {
|
||||
// Skip known MySQL constraint errors for existing tables
|
||||
errStr := err.Error()
|
||||
if strings.Contains(errStr, "Can't DROP") ||
|
||||
strings.Contains(errStr, "Duplicate key name") ||
|
||||
strings.Contains(errStr, "check that it exists") ||
|
||||
strings.Contains(errStr, "Cannot change column") ||
|
||||
strings.Contains(errStr, "used in a foreign key constraint") {
|
||||
slog.Warn("migration warning (skipped)", "model", model, "error", errStr)
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SeedCategories upserts default categories, updating display_order on existing rows.
|
||||
func SeedCategories(db *gorm.DB) error {
|
||||
for _, cat := range DefaultCategories {
|
||||
var existing Category
|
||||
if err := db.Where("code = ?", cat.Code).First(&existing).Error; err != nil {
|
||||
if err := db.Create(&cat).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := db.Model(&existing).Update("display_order", cat.DisplayOrder).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Server schema changes are SQL files in migrations/, applied by `qfs -migrate`
|
||||
// (models.RunSQLMigrations). There is deliberately no GORM AutoMigrate against
|
||||
// MariaDB: it retypes production columns to match whatever models the running binary
|
||||
// was built with — an old binary run with -migrate once did exactly that.
|
||||
@@ -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 {
|
||||
|
||||
+14
-11
@@ -3,17 +3,20 @@ package models
|
||||
import "time"
|
||||
|
||||
type Project struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"size:36;uniqueIndex;not null" json:"uuid"`
|
||||
OwnerUsername string `gorm:"size:100;not null;index" json:"owner_username"`
|
||||
Code string `gorm:"size:100;not null;index:idx_qt_projects_code_variant,priority:1" json:"code"`
|
||||
Variant string `gorm:"size:100;not null;default:'';index:idx_qt_projects_code_variant,priority:2" json:"variant"`
|
||||
Name *string `gorm:"size:200" json:"name,omitempty"`
|
||||
TrackerURL string `gorm:"size:500" json:"tracker_url"`
|
||||
IsActive bool `gorm:"default:true;index" json:"is_active"`
|
||||
IsSystem bool `gorm:"default:false;index" json:"is_system"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"size:36;uniqueIndex;not null" json:"uuid"`
|
||||
OwnerUsername string `gorm:"size:100;not null;index" json:"owner_username"`
|
||||
Code string `gorm:"size:100;not null;index:idx_qt_projects_code_variant,priority:1" json:"code"`
|
||||
Variant string `gorm:"size:100;not null;default:'';index:idx_qt_projects_code_variant,priority:2" json:"variant"`
|
||||
Name *string `gorm:"size:200" json:"name,omitempty"`
|
||||
TrackerURL string `gorm:"size:500" json:"tracker_url"`
|
||||
IsActive bool `gorm:"default:true;index" json:"is_active"`
|
||||
IsSystem bool `gorm:"default:false;index" json:"is_system"`
|
||||
RentalEnabled bool `gorm:"default:false" json:"rental_enabled"`
|
||||
ShowStockPrices bool `gorm:"default:false" json:"show_stock_prices"`
|
||||
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (Project) TableName() string {
|
||||
|
||||
@@ -4,8 +4,7 @@ import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -24,10 +23,87 @@ func (SQLSchemaMigration) TableName() string {
|
||||
return "qt_schema_migrations"
|
||||
}
|
||||
|
||||
// NeedsSQLMigrations reports whether at least one SQL migration from migrationsDir
|
||||
// SQLMigrationState is one server migration file and when it was recorded as applied
|
||||
// (nil = pending).
|
||||
type SQLMigrationState struct {
|
||||
Filename string
|
||||
AppliedAt *time.Time
|
||||
}
|
||||
|
||||
// SQLMigrationStatus lists every server migration in migrations with its applied state.
|
||||
// Read-only: does not create qt_schema_migrations.
|
||||
func SQLMigrationStatus(db *gorm.DB, migrations fs.FS) ([]SQLMigrationState, error) {
|
||||
files, err := listSQLMigrationFiles(migrations)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
applied := map[string]time.Time{}
|
||||
if db.Migrator().HasTable(&SQLSchemaMigration{}) {
|
||||
var rows []SQLSchemaMigration
|
||||
if err := db.Find(&rows).Error; err != nil {
|
||||
return nil, fmt.Errorf("read qt_schema_migrations: %w", err)
|
||||
}
|
||||
for _, r := range rows {
|
||||
applied[r.Filename] = r.AppliedAt
|
||||
}
|
||||
}
|
||||
states := make([]SQLMigrationState, 0, len(files))
|
||||
for _, f := range files {
|
||||
st := SQLMigrationState{Filename: f}
|
||||
if at, ok := applied[f]; ok {
|
||||
at := at
|
||||
st.AppliedAt = &at
|
||||
}
|
||||
states = append(states, st)
|
||||
}
|
||||
return states, nil
|
||||
}
|
||||
|
||||
// BaselineSQLMigrations records every migration up to and including upto as applied
|
||||
// WITHOUT executing it — for a server whose schema was brought up to date by other
|
||||
// means before qt_schema_migrations was used. Returns the filenames newly recorded.
|
||||
func BaselineSQLMigrations(db *gorm.DB, migrations fs.FS, upto string) ([]string, error) {
|
||||
files, err := listSQLMigrationFiles(migrations)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
found := false
|
||||
for _, f := range files {
|
||||
if f == upto {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return nil, fmt.Errorf("baseline migration %q not found", upto)
|
||||
}
|
||||
if err := ensureSQLMigrationsTable(db); err != nil {
|
||||
return nil, fmt.Errorf("migrate qt_schema_migrations table: %w", err)
|
||||
}
|
||||
var recorded []string
|
||||
for _, f := range files {
|
||||
if f > upto {
|
||||
break
|
||||
}
|
||||
var count int64
|
||||
if err := db.Model(&SQLSchemaMigration{}).Where("filename = ?", f).Count(&count).Error; err != nil {
|
||||
return recorded, fmt.Errorf("check migration %s: %w", f, err)
|
||||
}
|
||||
if count > 0 {
|
||||
continue
|
||||
}
|
||||
if err := db.Create(&SQLSchemaMigration{Filename: f}).Error; err != nil {
|
||||
return recorded, fmt.Errorf("record baseline migration %s: %w", f, err)
|
||||
}
|
||||
recorded = append(recorded, f)
|
||||
}
|
||||
return recorded, nil
|
||||
}
|
||||
|
||||
// NeedsSQLMigrations reports whether at least one SQL migration from migrations
|
||||
// is not yet recorded in qt_schema_migrations.
|
||||
func NeedsSQLMigrations(db *gorm.DB, migrationsDir string) (bool, error) {
|
||||
files, err := listSQLMigrationFiles(migrationsDir)
|
||||
func NeedsSQLMigrations(db *gorm.DB, migrations fs.FS) (bool, error) {
|
||||
files, err := listSQLMigrationFiles(migrations)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -48,50 +124,51 @@ func NeedsSQLMigrations(db *gorm.DB, migrationsDir string) (bool, error) {
|
||||
return count < int64(len(files)), nil
|
||||
}
|
||||
|
||||
// RunSQLMigrations applies SQL files from migrationsDir once and records them in qt_schema_migrations.
|
||||
// Local SQLite-only scripts are skipped automatically.
|
||||
func RunSQLMigrations(db *gorm.DB, migrationsDir string) error {
|
||||
// RunSQLMigrations applies pending SQL files from migrations once each, in filename
|
||||
// order, and records them in qt_schema_migrations. onApply (optional) is called with
|
||||
// each filename before it runs. Local SQLite-only scripts are skipped automatically.
|
||||
// Returns the filenames applied.
|
||||
func RunSQLMigrations(db *gorm.DB, migrations fs.FS, onApply func(filename string)) ([]string, error) {
|
||||
if err := ensureSQLMigrationsTable(db); err != nil {
|
||||
return fmt.Errorf("migrate qt_schema_migrations table: %w", err)
|
||||
return nil, fmt.Errorf("migrate qt_schema_migrations table: %w", err)
|
||||
}
|
||||
|
||||
files, err := listSQLMigrationFiles(migrationsDir)
|
||||
files, err := listSQLMigrationFiles(migrations)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var applied []string
|
||||
|
||||
for _, filename := range files {
|
||||
var count int64
|
||||
if err := db.Model(&SQLSchemaMigration{}).Where("filename = ?", filename).Count(&count).Error; err != nil {
|
||||
return fmt.Errorf("check migration %s: %w", filename, err)
|
||||
return applied, fmt.Errorf("check migration %s: %w", filename, err)
|
||||
}
|
||||
if count > 0 {
|
||||
continue
|
||||
}
|
||||
if onApply != nil {
|
||||
onApply(filename)
|
||||
}
|
||||
|
||||
path := filepath.Join(migrationsDir, filename)
|
||||
content, err := os.ReadFile(path)
|
||||
content, err := fs.ReadFile(migrations, filename)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migration %s: %w", filename, err)
|
||||
return applied, fmt.Errorf("read migration %s: %w", filename, err)
|
||||
}
|
||||
|
||||
statements := splitSQLStatements(string(content))
|
||||
if len(statements) == 0 {
|
||||
if err := db.Create(&SQLSchemaMigration{Filename: filename}).Error; err != nil {
|
||||
return fmt.Errorf("record empty migration %s: %w", filename, err)
|
||||
if statements := splitSQLStatements(string(content)); len(statements) > 0 {
|
||||
if err := executeMigrationStatements(db, filename, statements); err != nil {
|
||||
return applied, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if err := executeMigrationStatements(db, filename, statements); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := db.Create(&SQLSchemaMigration{Filename: filename}).Error; err != nil {
|
||||
return fmt.Errorf("record migration %s: %w", filename, err)
|
||||
return applied, fmt.Errorf("record migration %s: %w", filename, err)
|
||||
}
|
||||
applied = append(applied, filename)
|
||||
}
|
||||
|
||||
return nil
|
||||
return applied, nil
|
||||
}
|
||||
|
||||
// IsMigrationPermissionError returns true if err indicates insufficient privileges
|
||||
@@ -199,13 +276,13 @@ func splitSQLStatements(script string) []string {
|
||||
return stmts
|
||||
}
|
||||
|
||||
func listSQLMigrationFiles(migrationsDir string) ([]string, error) {
|
||||
entries, err := os.ReadDir(migrationsDir)
|
||||
func listSQLMigrationFiles(migrations fs.FS) ([]string, error) {
|
||||
entries, err := fs.ReadDir(migrations, ".")
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("read migrations dir %s: %w", migrationsDir, err)
|
||||
return nil, fmt.Errorf("read migrations dir: %w", err)
|
||||
}
|
||||
|
||||
files := make([]string, 0, len(entries))
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestSQLMigrationStatusAndListing(t *testing.T) {
|
||||
migrations := fstest.MapFS{
|
||||
"002_b.sql": {Data: []byte("ALTER TABLE x ADD COLUMN b INT;")},
|
||||
"001_a.sql": {Data: []byte("ALTER TABLE x ADD COLUMN a INT;")},
|
||||
"006_local_only_versions.sql": {Data: []byte("-- sqlite only")},
|
||||
"README.md": {Data: []byte("not a migration")},
|
||||
}
|
||||
db, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "m.db")), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// No history table yet: everything pending, nothing created.
|
||||
states, err := SQLMigrationStatus(db, migrations)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(states) != 2 || states[0].Filename != "001_a.sql" || states[1].Filename != "002_b.sql" {
|
||||
t.Fatalf("unexpected listing %+v", states)
|
||||
}
|
||||
if states[0].AppliedAt != nil || db.Migrator().HasTable(&SQLSchemaMigration{}) {
|
||||
t.Fatal("status must be read-only and report pending")
|
||||
}
|
||||
|
||||
if err := db.AutoMigrate(&SQLSchemaMigration{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&SQLSchemaMigration{Filename: "001_a.sql"}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
states, _ = SQLMigrationStatus(db, migrations)
|
||||
if states[0].AppliedAt == nil || states[1].AppliedAt != nil {
|
||||
t.Fatalf("want 001 applied, 002 pending: %+v", states)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitSQLStatementsSkipsComments(t *testing.T) {
|
||||
got := splitSQLStatements("-- header; with semicolon\nALTER TABLE a ADD COLUMN x INT;\n\nALTER TABLE b\n ADD COLUMN y INT;\n")
|
||||
if len(got) != 2 || got[1] != "ALTER TABLE b\n ADD COLUMN y INT" {
|
||||
t.Fatalf("unexpected statements %q", got)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
@@ -16,13 +18,9 @@ func NewConfigurationRepository(db *gorm.DB) *ConfigurationRepository {
|
||||
}
|
||||
|
||||
func (r *ConfigurationRepository) Create(config *models.Configuration) error {
|
||||
if err := r.db.Create(config).Error; err != nil {
|
||||
if isUnknownLineNoColumnError(err) {
|
||||
return r.db.Omit("line_no").Create(config).Error
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
return withOptionalColumns(func(omit []string) error {
|
||||
return r.db.Omit(omit...).Create(config).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *ConfigurationRepository) GetByID(id uint) (*models.Configuration, error) {
|
||||
@@ -44,21 +42,40 @@ func (r *ConfigurationRepository) GetByUUID(uuid string) (*models.Configuration,
|
||||
}
|
||||
|
||||
func (r *ConfigurationRepository) Update(config *models.Configuration) error {
|
||||
if err := r.db.Save(config).Error; err != nil {
|
||||
if isUnknownLineNoColumnError(err) {
|
||||
return r.db.Omit("line_no").Save(config).Error
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
return withOptionalColumns(func(omit []string) error {
|
||||
return r.db.Omit(omit...).Save(config).Error
|
||||
})
|
||||
}
|
||||
|
||||
func isUnknownLineNoColumnError(err error) bool {
|
||||
// optionalConfigColumns are qt_configurations columns added by server migrations that a
|
||||
// not-yet-migrated server may lack (line_no: 028, feature_flags: 034). A write that fails
|
||||
// on one of them is retried without it, so clients keep syncing until the migration runs.
|
||||
var optionalConfigColumns = []string{"line_no", "feature_flags"}
|
||||
|
||||
func withOptionalColumns(write func(omit []string) error) error {
|
||||
var omit []string
|
||||
for {
|
||||
err := write(omit)
|
||||
col := unknownOptionalColumn(err)
|
||||
if col == "" || slices.Contains(omit, col) {
|
||||
return err
|
||||
}
|
||||
slog.Warn("qt_configurations column missing on server — writing without it; run server migrations", "column", col)
|
||||
omit = append(omit, col)
|
||||
}
|
||||
}
|
||||
|
||||
func unknownOptionalColumn(err error) string {
|
||||
if err == nil {
|
||||
return false
|
||||
return ""
|
||||
}
|
||||
msg := strings.ToLower(err.Error())
|
||||
return strings.Contains(msg, "unknown column 'line_no'") || strings.Contains(msg, "no column named line_no")
|
||||
for _, col := range optionalConfigColumns {
|
||||
if strings.Contains(msg, "unknown column '"+col+"'") || strings.Contains(msg, "no column named "+col) {
|
||||
return col
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (r *ConfigurationRepository) Delete(id uint) error {
|
||||
@@ -104,7 +121,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,9 @@ func (r *ProjectRepository) UpsertByUUID(project *models.Project) error {
|
||||
"tracker_url",
|
||||
"is_active",
|
||||
"is_system",
|
||||
"rental_enabled",
|
||||
"show_stock_prices",
|
||||
"only_in_stock",
|
||||
"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"`
|
||||
@@ -61,592 +34,13 @@ type CreateConfigRequest struct {
|
||||
CompetitorPricelistID *uint `json:"competitor_pricelist_id,omitempty"`
|
||||
ConfigType string `json:"config_type,omitempty"` // "server" | "storage"
|
||||
DisablePriceRefresh bool `json:"disable_price_refresh"`
|
||||
OnlyInStock bool `json:"only_in_stock"`
|
||||
}
|
||||
|
||||
type ArticlePreviewRequest struct {
|
||||
Items models.ConfigItems `json:"items"`
|
||||
ServerModel string `json:"server_model"`
|
||||
SupportCode string `json:"support_code,omitempty"`
|
||||
PricelistID *uint `json:"pricelist_id,omitempty"`
|
||||
// PricelistID is accepted for backward compatibility but ignored: article
|
||||
// categories come from the component universe (world ∪ estimate), not one pricelist.
|
||||
PricelistID *uint `json:"pricelist_id,omitempty"`
|
||||
}
|
||||
|
||||
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)
|
||||
// }
|
||||
+255
-110
@@ -3,6 +3,7 @@ package services
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
@@ -58,16 +59,56 @@ type ProjectPricingExportOptions struct {
|
||||
IncludeEstimate bool `json:"include_estimate"`
|
||||
IncludeStock bool `json:"include_stock"`
|
||||
IncludeCompetitor bool `json:"include_competitor"`
|
||||
Basis string `json:"basis"` // "fob" or "ddp"; empty defaults to "fob"
|
||||
SaleMarkup float64 `json:"sale_markup"` // DDP multiplier; 0 defaults to 1.3
|
||||
ManualPrice *float64 `json:"manual_price"` // user-defined total price; distributed proportionally across rows
|
||||
Basis string `json:"basis"` // "fob" or "ddp"; empty defaults to "fob"
|
||||
SaleMarkup float64 `json:"sale_markup"` // DDP uplift applied to Estimate only; 0 defaults to 1.3
|
||||
ManualPrice *float64 `json:"manual_price"` // user-defined total price; distributed proportionally across rows
|
||||
|
||||
// MinimalSaleColumns/SaleRowMarkups back the Sale table's own per-row "Накидка"
|
||||
// feature (index.html renderPricingTab/_saleRowPrice). Only ever set by
|
||||
// ExportConfigPricingCSV when the request explicitly asks for it — the Buy export
|
||||
// and project-level bulk export never set these, so their output is unaffected.
|
||||
MinimalSaleColumns bool `json:"minimal_sale_columns"`
|
||||
SaleRowMarkups map[string]float64 `json:"sale_row_markups"` // "<vendorPN>::<lot>" -> markup percent
|
||||
}
|
||||
|
||||
func (o ProjectPricingExportOptions) saleMarkupFactor() float64 {
|
||||
// defaultSaleMarkup mirrors PricingMarkup.DEFAULT_SALE_UPLIFT in web/templates/index.html.
|
||||
// Keep both in sync; the frontend always sends an explicit value, this is a fallback for
|
||||
// other API callers that omit sale_markup.
|
||||
const defaultSaleMarkup = 1.3
|
||||
|
||||
// effectiveSaleMarkupFactor resolves the DDP estimate uplift for one configuration.
|
||||
// An explicit opts.SaleMarkup (sent by the single-config pricing tab, which knows the
|
||||
// live-edited value) always wins. Otherwise each configuration's own saved uplift
|
||||
// (persisted in Notes by the "Ценообразование" tab, see index.html buildPricingState/
|
||||
// restorePricingStateFromNotes) is used, so bulk project export matches what exporting
|
||||
// that same configuration individually would produce — one pipeline, not a single
|
||||
// project-wide constant.
|
||||
func (o ProjectPricingExportOptions) effectiveSaleMarkupFactor(cfg *models.Configuration) float64 {
|
||||
if o.SaleMarkup > 0 {
|
||||
return o.SaleMarkup
|
||||
}
|
||||
return 1.3
|
||||
if v := configSavedSaleUplift(cfg); v > 0 {
|
||||
return v
|
||||
}
|
||||
return defaultSaleMarkup
|
||||
}
|
||||
|
||||
// configSavedSaleUplift reads the per-configuration DDP estimate uplift persisted by the
|
||||
// pricing tab. Notes stores {"pricing_ui":{"sale_uplift":...}} as JSON — see
|
||||
// serializeConfigNotes/restorePricingStateFromNotes in index.html.
|
||||
func configSavedSaleUplift(cfg *models.Configuration) float64 {
|
||||
if cfg == nil || strings.TrimSpace(cfg.Notes) == "" {
|
||||
return 0
|
||||
}
|
||||
var parsed struct {
|
||||
PricingUI struct {
|
||||
SaleUplift float64 `json:"sale_uplift"`
|
||||
} `json:"pricing_ui"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(cfg.Notes), &parsed); err != nil {
|
||||
return 0
|
||||
}
|
||||
return parsed.PricingUI.SaleUplift
|
||||
}
|
||||
|
||||
func (o ProjectPricingExportOptions) isDDP() bool {
|
||||
@@ -88,15 +129,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.
|
||||
@@ -257,10 +301,14 @@ func (s *ExportService) ToPricingCSV(w io.Writer, data *ProjectPricingExportData
|
||||
return fmt.Errorf("failed to write pricing header: %w", err)
|
||||
}
|
||||
|
||||
writeRows := opts.IncludeLOT || opts.IncludeBOM
|
||||
writeRows := opts.IncludeLOT || opts.IncludeBOM || opts.MinimalSaleColumns
|
||||
for _, cfg := range data.Configs {
|
||||
if err := csvWriter.Write(pricingConfigSummaryRow(cfg, opts)); err != nil {
|
||||
return fmt.Errorf("failed to write config summary row: %w", err)
|
||||
// Minimal mode (single-config Sale export) skips the per-config summary line —
|
||||
// it's just LOT/Описание/Кол-во/Цена item rows, see pricingCSVHeaders.
|
||||
if !opts.MinimalSaleColumns {
|
||||
if err := csvWriter.Write(pricingConfigSummaryRow(cfg, opts)); err != nil {
|
||||
return fmt.Errorf("failed to write config summary row: %w", err)
|
||||
}
|
||||
}
|
||||
if writeRows {
|
||||
for _, row := range cfg.Rows {
|
||||
@@ -380,7 +428,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,42 +459,44 @@ 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() {
|
||||
applyDDPMarkup(block.Rows, opts.saleMarkupFactor())
|
||||
}
|
||||
if opts.ManualPrice != nil && *opts.ManualPrice > 0 {
|
||||
distributeManualPrice(block.Rows, *opts.ManualPrice)
|
||||
}
|
||||
applySalePricing(block.Rows, cfg, opts)
|
||||
return block, nil
|
||||
}
|
||||
|
||||
@@ -465,26 +515,42 @@ 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,
|
||||
})
|
||||
}
|
||||
|
||||
if opts.isDDP() {
|
||||
applyDDPMarkup(block.Rows, opts.saleMarkupFactor())
|
||||
}
|
||||
if opts.ManualPrice != nil && *opts.ManualPrice > 0 {
|
||||
distributeManualPrice(block.Rows, *opts.ManualPrice)
|
||||
}
|
||||
applySalePricing(block.Rows, cfg, opts)
|
||||
|
||||
return block, nil
|
||||
}
|
||||
|
||||
// applySalePricing applies the DDP estimate uplift/manual-price/markup pipeline to a
|
||||
// pricing export block. MinimalSaleColumns (only ever set by the single-config Sale
|
||||
// export button) switches to applySaleRowPricing, which additionally folds in each
|
||||
// row's own "Накидка" percent; every other caller (Buy export, project bulk export)
|
||||
// keeps the original applyDDPMarkup + distributeManualPrice behavior unchanged.
|
||||
func applySalePricing(rows []ProjectPricingExportRow, cfg *models.Configuration, opts ProjectPricingExportOptions) {
|
||||
if opts.MinimalSaleColumns {
|
||||
applySaleRowPricing(rows, opts.effectiveSaleMarkupFactor(cfg), opts.ManualPrice, opts.SaleRowMarkups)
|
||||
return
|
||||
}
|
||||
if opts.isDDP() {
|
||||
applyDDPMarkup(rows, opts.effectiveSaleMarkupFactor(cfg))
|
||||
}
|
||||
if opts.ManualPrice != nil && *opts.ManualPrice > 0 {
|
||||
distributeManualPrice(rows, *opts.ManualPrice)
|
||||
}
|
||||
}
|
||||
|
||||
// sortConfigItemsByCategoryMap returns a copy of items sorted by category display order.
|
||||
// categories maps lot_name → category code; catOrder maps category code → display order.
|
||||
func sortConfigItemsByCategoryMap(items models.ConfigItems, catOrder map[string]int, categories map[string]string) models.ConfigItems {
|
||||
@@ -501,11 +567,69 @@ func sortConfigItemsByCategoryMap(items models.ConfigItems, catOrder map[string]
|
||||
return sorted
|
||||
}
|
||||
|
||||
func applyDDPMarkup(rows []ProjectPricingExportRow, factor float64) {
|
||||
// stockCompetitorMarkupFactor is the fixed DDP multiplier applied to Stock and
|
||||
// Competitor columns, independent of the user-configurable estimate uplift.
|
||||
// Only used by the non-minimal (full-column) DDP export path — the Sale table itself
|
||||
// no longer displays/exports Stock/Competitor, see applySaleRowPricing.
|
||||
const stockCompetitorMarkupFactor = 1.3
|
||||
|
||||
func applyDDPMarkup(rows []ProjectPricingExportRow, estimateFactor float64) {
|
||||
for i := range rows {
|
||||
rows[i].Estimate = scaleFloatPtr(rows[i].Estimate, factor)
|
||||
rows[i].Stock = scaleFloatPtr(rows[i].Stock, factor)
|
||||
rows[i].Competitor = scaleFloatPtr(rows[i].Competitor, factor)
|
||||
rows[i].Estimate = scaleFloatPtr(rows[i].Estimate, estimateFactor)
|
||||
rows[i].Stock = scaleFloatPtr(rows[i].Stock, stockCompetitorMarkupFactor)
|
||||
rows[i].Competitor = scaleFloatPtr(rows[i].Competitor, stockCompetitorMarkupFactor)
|
||||
}
|
||||
}
|
||||
|
||||
// saleRowKey mirrors _saleRowKey in web/templates/index.html: a LOT can appear more
|
||||
// than once across different vendor-PN BOM groups, so lot_name alone isn't a safe key.
|
||||
// "—" is the row-builder's own placeholder for "no vendor PN" (see the VendorPN: "—"
|
||||
// literals in buildPricingExportBlock), matching the frontend's empty-string case.
|
||||
func saleRowKey(vendorPN, lot string) string {
|
||||
v := strings.ToUpper(strings.TrimSpace(vendorPN))
|
||||
if v == "" || v == "—" {
|
||||
v = "NONE"
|
||||
}
|
||||
return v + "::" + strings.ToUpper(strings.TrimSpace(lot))
|
||||
}
|
||||
|
||||
// applySaleRowPricing implements the per-row "Накидка" pricing pipeline for the
|
||||
// minimal Sale CSV export: each row's base (its raw Estimate, or a proportional share
|
||||
// of manualPrice when set — same last-row-absorbs-remainder distribution as
|
||||
// distributeManualPrice, but overwriting the base instead of a side field) is
|
||||
// multiplied by (saleUplift + that row's own markup percent / 100). Mirrors
|
||||
// _saleRowPrice/recomputeSalePrices in web/templates/index.html exactly.
|
||||
func applySaleRowPricing(rows []ProjectPricingExportRow, saleUplift float64, manualPrice *float64, rowMarkups map[string]float64) {
|
||||
rawTotal := 0.0
|
||||
lastPricedIdx := -1
|
||||
for i, row := range rows {
|
||||
if row.Estimate != nil && *row.Estimate > 0 {
|
||||
rawTotal += *row.Estimate
|
||||
lastPricedIdx = i
|
||||
}
|
||||
}
|
||||
useManual := manualPrice != nil && *manualPrice > 0 && rawTotal > 0
|
||||
|
||||
assigned := 0.0
|
||||
for i := range rows {
|
||||
if rows[i].Estimate == nil || *rows[i].Estimate <= 0 {
|
||||
continue
|
||||
}
|
||||
base := *rows[i].Estimate
|
||||
if useManual {
|
||||
if i == lastPricedIdx {
|
||||
base = math.Round((*manualPrice-assigned)*100) / 100
|
||||
} else {
|
||||
share := (*rows[i].Estimate / rawTotal) * (*manualPrice)
|
||||
base = math.Round(share*100) / 100
|
||||
assigned += base
|
||||
}
|
||||
}
|
||||
key := saleRowKey(rows[i].VendorPN, rows[i].LotDisplay)
|
||||
// Negative markup is a discount; floored at 0 like _saleRowPrice so a price never goes negative.
|
||||
factor := math.Max(0, saleUplift+(rowMarkups[key]/100))
|
||||
price := math.Round(base*factor*100) / 100
|
||||
rows[i].Estimate = floatPtr(price)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -584,9 +708,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 +747,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 +798,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 +834,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 +857,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 +867,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.
|
||||
@@ -815,6 +933,9 @@ func estimateOnlyTotal(estimatePrice *float64, fallbackUnitPrice float64, quanti
|
||||
}
|
||||
|
||||
func pricingCSVHeaders(opts ProjectPricingExportOptions) []string {
|
||||
if opts.MinimalSaleColumns {
|
||||
return []string{"LOT", "Описание", "Кол-во", "Цена"}
|
||||
}
|
||||
headers := make([]string, 0, 9)
|
||||
headers = append(headers, "Line Item")
|
||||
if opts.IncludeLOT {
|
||||
@@ -836,10 +957,19 @@ func pricingCSVHeaders(opts ProjectPricingExportOptions) []string {
|
||||
if opts.ManualPrice != nil && *opts.ManualPrice > 0 {
|
||||
headers = append(headers, "Ручная цена")
|
||||
}
|
||||
headers = append(headers, "Заглушка (world)")
|
||||
return headers
|
||||
}
|
||||
|
||||
func pricingCSVRow(row ProjectPricingExportRow, opts ProjectPricingExportOptions) []string {
|
||||
if opts.MinimalSaleColumns {
|
||||
return []string{
|
||||
emptyDash(row.LotDisplay),
|
||||
emptyDash(row.Description),
|
||||
fmt.Sprintf("%d", exportPositiveInt(row.Quantity, 1)),
|
||||
formatMoneyValue(row.Estimate),
|
||||
}
|
||||
}
|
||||
record := make([]string, 0, 9)
|
||||
record = append(record, "")
|
||||
if opts.IncludeLOT {
|
||||
@@ -865,6 +995,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,10 +1039,10 @@ func pricingConfigSummaryRow(cfg ProjectPricingExportConfig, opts ProjectPricing
|
||||
if opts.ManualPrice != nil && *opts.ManualPrice > 0 {
|
||||
record = append(record, formatMoneyValue(opts.ManualPrice))
|
||||
}
|
||||
record = append(record, "")
|
||||
return record
|
||||
}
|
||||
|
||||
|
||||
func formatMoneyValue(value *float64) string {
|
||||
if value == nil {
|
||||
return "—"
|
||||
|
||||
@@ -561,3 +561,22 @@ type failingWriter struct{}
|
||||
func (fw *failingWriter) Write(p []byte) (int, error) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
func TestApplySaleRowPricingNegativeMarkup(t *testing.T) {
|
||||
rows := []ProjectPricingExportRow{
|
||||
{LotDisplay: "GPU_A", Estimate: floatPtr(1000)},
|
||||
{LotDisplay: "GPU_B", Estimate: floatPtr(1000)},
|
||||
{LotDisplay: "GPU_C", Estimate: floatPtr(1000)},
|
||||
}
|
||||
applySaleRowPricing(rows, 1.5, nil, map[string]float64{
|
||||
"NONE::GPU_A": -50, // discount: 1.5 - 0.5 = 1.0
|
||||
"NONE::GPU_B": 25, // 1.5 + 0.25 = 1.75
|
||||
"NONE::GPU_C": -300, // would be -1.5 — floored at 0
|
||||
})
|
||||
want := []float64{1000, 1750, 0}
|
||||
for i, w := range want {
|
||||
if rows[i].Estimate == nil || *rows[i].Estimate != w {
|
||||
t.Fatalf("row %d: got %v, want %v", i, rows[i].Estimate, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/appmeta"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/article"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/services/sync"
|
||||
@@ -70,14 +71,18 @@ func (s *LocalConfigurationService) Create(ownerUsername string, req *CreateConf
|
||||
|
||||
if strings.TrimSpace(req.ServerModel) != "" {
|
||||
articleResult, articleErr := article.Build(s.localDB, req.Items, article.BuildOptions{
|
||||
ServerModel: req.ServerModel,
|
||||
SupportCode: req.SupportCode,
|
||||
ServerPricelist: pricelistID,
|
||||
ServerModel: req.ServerModel,
|
||||
})
|
||||
if articleErr != nil {
|
||||
return nil, articleErr
|
||||
}
|
||||
req.Article = articleResult.Article
|
||||
if len(articleResult.Warnings) > 0 {
|
||||
slog.Warn("article generation degraded",
|
||||
"server_model", req.ServerModel,
|
||||
"article", articleResult.Article,
|
||||
"warnings", articleResult.Warnings)
|
||||
}
|
||||
}
|
||||
|
||||
total := req.Items.Total()
|
||||
@@ -104,7 +109,6 @@ func (s *LocalConfigurationService) Create(ownerUsername string, req *CreateConf
|
||||
CompetitorPricelistID: req.CompetitorPricelistID,
|
||||
ConfigType: req.ConfigType,
|
||||
DisablePriceRefresh: req.DisablePriceRefresh,
|
||||
OnlyInStock: req.OnlyInStock,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
if cfg.ConfigType == "" {
|
||||
@@ -168,14 +172,18 @@ func (s *LocalConfigurationService) Update(uuid string, ownerUsername string, re
|
||||
|
||||
if strings.TrimSpace(req.ServerModel) != "" {
|
||||
articleResult, articleErr := article.Build(s.localDB, req.Items, article.BuildOptions{
|
||||
ServerModel: req.ServerModel,
|
||||
SupportCode: req.SupportCode,
|
||||
ServerPricelist: pricelistID,
|
||||
ServerModel: req.ServerModel,
|
||||
})
|
||||
if articleErr != nil {
|
||||
return nil, articleErr
|
||||
}
|
||||
req.Article = articleResult.Article
|
||||
if len(articleResult.Warnings) > 0 {
|
||||
slog.Warn("article generation degraded",
|
||||
"server_model", req.ServerModel,
|
||||
"article", articleResult.Article,
|
||||
"warnings", articleResult.Warnings)
|
||||
}
|
||||
}
|
||||
|
||||
total := req.Items.Total()
|
||||
@@ -206,7 +214,6 @@ func (s *LocalConfigurationService) Update(uuid string, ownerUsername string, re
|
||||
localCfg.WarehousePricelistID = req.WarehousePricelistID
|
||||
localCfg.CompetitorPricelistID = req.CompetitorPricelistID
|
||||
localCfg.DisablePriceRefresh = req.DisablePriceRefresh
|
||||
localCfg.OnlyInStock = req.OnlyInStock
|
||||
localCfg.UpdatedAt = time.Now()
|
||||
localCfg.SyncStatus = "pending"
|
||||
|
||||
@@ -220,14 +227,10 @@ func (s *LocalConfigurationService) Update(uuid string, ownerUsername string, re
|
||||
|
||||
// BuildArticlePreview generates server article based on current items and server_model/support_code.
|
||||
func (s *LocalConfigurationService) BuildArticlePreview(req *ArticlePreviewRequest) (article.BuildResult, error) {
|
||||
pricelistID, err := s.resolvePricelistID(req.PricelistID)
|
||||
if err != nil {
|
||||
return article.BuildResult{}, err
|
||||
}
|
||||
// Categories for the article come from the component universe (world ∪ estimate),
|
||||
// not from a specific pricelist, so req.PricelistID is no longer needed here.
|
||||
return article.Build(s.localDB, req.Items, article.BuildOptions{
|
||||
ServerModel: req.ServerModel,
|
||||
SupportCode: req.SupportCode,
|
||||
ServerPricelist: pricelistID,
|
||||
ServerModel: req.ServerModel,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -322,6 +325,7 @@ func (s *LocalConfigurationService) CloneToProject(configUUID string, ownerUsern
|
||||
TotalPrice: &total,
|
||||
CustomPrice: original.CustomPrice,
|
||||
Notes: original.Notes,
|
||||
FeatureFlags: original.FeatureFlags,
|
||||
IsTemplate: false,
|
||||
ServerCount: original.ServerCount,
|
||||
ServerModel: original.ServerModel,
|
||||
@@ -330,8 +334,8 @@ func (s *LocalConfigurationService) CloneToProject(configUUID string, ownerUsern
|
||||
PricelistID: original.PricelistID,
|
||||
WarehousePricelistID: original.WarehousePricelistID,
|
||||
CompetitorPricelistID: original.CompetitorPricelistID,
|
||||
ConfigType: original.ConfigType,
|
||||
DisablePriceRefresh: original.DisablePriceRefresh,
|
||||
OnlyInStock: original.OnlyInStock,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
@@ -533,14 +537,18 @@ func (s *LocalConfigurationService) UpdateNoAuth(uuid string, req *CreateConfigR
|
||||
|
||||
if strings.TrimSpace(req.ServerModel) != "" {
|
||||
articleResult, articleErr := article.Build(s.localDB, req.Items, article.BuildOptions{
|
||||
ServerModel: req.ServerModel,
|
||||
SupportCode: req.SupportCode,
|
||||
ServerPricelist: pricelistID,
|
||||
ServerModel: req.ServerModel,
|
||||
})
|
||||
if articleErr != nil {
|
||||
return nil, articleErr
|
||||
}
|
||||
req.Article = articleResult.Article
|
||||
if len(articleResult.Warnings) > 0 {
|
||||
slog.Warn("article generation degraded",
|
||||
"server_model", req.ServerModel,
|
||||
"article", articleResult.Article,
|
||||
"warnings", articleResult.Warnings)
|
||||
}
|
||||
}
|
||||
|
||||
total := req.Items.Total()
|
||||
@@ -570,7 +578,6 @@ func (s *LocalConfigurationService) UpdateNoAuth(uuid string, req *CreateConfigR
|
||||
localCfg.WarehousePricelistID = req.WarehousePricelistID
|
||||
localCfg.CompetitorPricelistID = req.CompetitorPricelistID
|
||||
localCfg.DisablePriceRefresh = req.DisablePriceRefresh
|
||||
localCfg.OnlyInStock = req.OnlyInStock
|
||||
localCfg.UpdatedAt = time.Now()
|
||||
localCfg.SyncStatus = "pending"
|
||||
|
||||
@@ -654,6 +661,7 @@ func (s *LocalConfigurationService) CloneNoAuthToProjectFromVersion(configUUID s
|
||||
return nil, fmt.Errorf("decode version snapshot for clone: %w", decErr)
|
||||
}
|
||||
snapshotCfg := localdb.LocalToConfiguration(snapshot)
|
||||
snapshotCfg.ConfigType = original.ConfigType // not part of version snapshots
|
||||
original = snapshotCfg
|
||||
original.UUID = configUUID // preserve original UUID for project resolution
|
||||
}
|
||||
@@ -680,6 +688,7 @@ func (s *LocalConfigurationService) CloneNoAuthToProjectFromVersion(configUUID s
|
||||
TotalPrice: &total,
|
||||
CustomPrice: original.CustomPrice,
|
||||
Notes: original.Notes,
|
||||
FeatureFlags: original.FeatureFlags,
|
||||
IsTemplate: false,
|
||||
ServerCount: original.ServerCount,
|
||||
ServerModel: original.ServerModel,
|
||||
@@ -688,8 +697,8 @@ func (s *LocalConfigurationService) CloneNoAuthToProjectFromVersion(configUUID s
|
||||
PricelistID: original.PricelistID,
|
||||
WarehousePricelistID: original.WarehousePricelistID,
|
||||
CompetitorPricelistID: original.CompetitorPricelistID,
|
||||
ConfigType: original.ConfigType,
|
||||
DisablePriceRefresh: original.DisablePriceRefresh,
|
||||
OnlyInStock: original.OnlyInStock,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
@@ -925,6 +934,9 @@ func (s *LocalConfigurationService) UpdateServerCount(configUUID string, serverC
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
|
||||
if err := applyFeatureFlags(localCfg.FeatureFlags, localCfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
localCfg.ServerCount = serverCount
|
||||
total := localCfg.Items.Total()
|
||||
if serverCount > 1 {
|
||||
@@ -1169,6 +1181,9 @@ func (s *LocalConfigurationService) createWithVersion(localCfg *localdb.LocalCon
|
||||
}
|
||||
|
||||
func (s *LocalConfigurationService) createWithVersionTx(tx *gorm.DB, localCfg *localdb.LocalConfiguration, createdBy string) error {
|
||||
if err := applyFeatureFlags(localCfg.FeatureFlags, localCfg); err != nil {
|
||||
return err
|
||||
}
|
||||
if localCfg.IsActive {
|
||||
if err := s.ensureConfigurationLineTx(tx, localCfg); err != nil {
|
||||
return err
|
||||
@@ -1214,6 +1229,9 @@ func (s *LocalConfigurationService) saveWithVersionAndPending(localCfg *localdb.
|
||||
}
|
||||
return fmt.Errorf("lock configuration row: %w", err)
|
||||
}
|
||||
if err := applyFeatureFlags(locked.FeatureFlags, localCfg); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if operation == "update" {
|
||||
currentVersion, err := s.loadCurrentVersionTx(tx, &locked)
|
||||
@@ -1294,6 +1312,7 @@ func hasNonRevisionConfigurationChanges(current *localdb.LocalConfiguration, nex
|
||||
}
|
||||
if current.Name != next.Name ||
|
||||
current.Notes != next.Notes ||
|
||||
strings.Join(current.FeatureFlags, ",") != strings.Join(next.FeatureFlags, ",") ||
|
||||
current.IsTemplate != next.IsTemplate ||
|
||||
current.ServerModel != next.ServerModel ||
|
||||
current.SupportCode != next.SupportCode ||
|
||||
@@ -1325,6 +1344,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 {
|
||||
@@ -1603,12 +1656,17 @@ func (s *LocalConfigurationService) rollbackToVersion(configurationUUID string,
|
||||
return fmt.Errorf("decode target rollback snapshot: %w", err)
|
||||
}
|
||||
|
||||
if err := configfeatures.Check(append(append([]string{}, current.FeatureFlags...), rollbackData.FeatureFlags...)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Keep stable identity/sync linkage; restore editable config content from target snapshot.
|
||||
current.Name = rollbackData.Name
|
||||
current.Items = rollbackData.Items
|
||||
current.TotalPrice = rollbackData.TotalPrice
|
||||
current.CustomPrice = rollbackData.CustomPrice
|
||||
current.Notes = rollbackData.Notes
|
||||
current.FeatureFlags = configfeatures.Detect(rollbackData.Notes)
|
||||
current.IsTemplate = rollbackData.IsTemplate
|
||||
current.ServerCount = rollbackData.ServerCount
|
||||
current.ServerModel = rollbackData.ServerModel
|
||||
@@ -1618,7 +1676,6 @@ func (s *LocalConfigurationService) rollbackToVersion(configurationUUID string,
|
||||
current.WarehousePricelistID = rollbackData.WarehousePricelistID
|
||||
current.CompetitorPricelistID = rollbackData.CompetitorPricelistID
|
||||
current.DisablePriceRefresh = rollbackData.DisablePriceRefresh
|
||||
current.OnlyInStock = rollbackData.OnlyInStock
|
||||
current.VendorSpec = rollbackData.VendorSpec
|
||||
if rollbackData.Line > 0 {
|
||||
current.Line = rollbackData.Line
|
||||
@@ -1813,7 +1870,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()
|
||||
@@ -1822,3 +1880,14 @@ func (s *LocalConfigurationService) resolvePricelistID(pricelistID *uint) (*uint
|
||||
}
|
||||
return &latest.ServerID, nil
|
||||
}
|
||||
|
||||
// applyFeatureFlags refuses a write when the configuration as stored carries feature
|
||||
// flags this build doesn't know (it could not round-trip the data behind them), and
|
||||
// otherwise re-derives next's flags from its content.
|
||||
func applyFeatureFlags(stored models.FeatureFlags, next *localdb.LocalConfiguration) error {
|
||||
if err := configfeatures.Check(stored); err != nil {
|
||||
return err
|
||||
}
|
||||
next.FeatureFlags = configfeatures.Detect(next.Notes)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
)
|
||||
|
||||
// config_type is free-form (codes come from qt_settings.config_types), so an
|
||||
// unknown code like "networking" must survive every write path unchanged.
|
||||
func TestConfigTypeSurvivesUpdateAndClone(t *testing.T) {
|
||||
service, local := newLocalConfigServiceForTest(t)
|
||||
|
||||
created, err := service.Create("tester", &CreateConfigRequest{
|
||||
Name: "net",
|
||||
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 1, UnitPrice: 1000}},
|
||||
ConfigType: "networking",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
|
||||
// The configurator's save payload carries no config_type.
|
||||
if _, err := service.UpdateNoAuth(created.UUID, &CreateConfigRequest{
|
||||
Name: "net",
|
||||
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 2, UnitPrice: 1000}},
|
||||
}); err != nil {
|
||||
t.Fatalf("update: %v", err)
|
||||
}
|
||||
if stored, _ := local.GetConfigurationByUUID(created.UUID); stored.ConfigType != "networking" {
|
||||
t.Fatalf("config_type after update = %q, want networking", stored.ConfigType)
|
||||
}
|
||||
|
||||
for _, fromVersion := range []int{0, 1} {
|
||||
clone, err := service.CloneNoAuthToProjectFromVersion(created.UUID, "copy", "tester", nil, fromVersion)
|
||||
if err != nil {
|
||||
t.Fatalf("clone from version %d: %v", fromVersion, err)
|
||||
}
|
||||
if stored, _ := local.GetConfigurationByUUID(clone.UUID); stored.ConfigType != "networking" {
|
||||
t.Fatalf("clone from version %d: config_type = %q, want networking", fromVersion, stored.ConfigType)
|
||||
}
|
||||
}
|
||||
|
||||
clone, err := service.CloneToProject(created.UUID, "tester", "copy2", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("clone to project: %v", err)
|
||||
}
|
||||
if stored, _ := local.GetConfigurationByUUID(clone.UUID); stored.ConfigType != "networking" {
|
||||
t.Fatalf("CloneToProject: config_type = %q, want networking", stored.ConfigType)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
)
|
||||
|
||||
const notesWithRowMarkup = `{"pricing_ui":{"sale_uplift":1.5,"sale_row_markups":{"NONE::CPU_A":-50}}}`
|
||||
|
||||
func TestSaveDerivesFeatureFlagsFromContent(t *testing.T) {
|
||||
service, local := newLocalConfigServiceForTest(t)
|
||||
|
||||
created, err := service.Create("tester", &CreateConfigRequest{
|
||||
Name: "cfg",
|
||||
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 1, UnitPrice: 1000}},
|
||||
Notes: notesWithRowMarkup,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
stored, _ := local.GetConfigurationByUUID(created.UUID)
|
||||
if want := (models.FeatureFlags{configfeatures.SaleRowMarkups}); !reflect.DeepEqual(stored.FeatureFlags, want) {
|
||||
t.Fatalf("flags after create = %v, want %v", stored.FeatureFlags, want)
|
||||
}
|
||||
|
||||
// Removing the markups clears the flag.
|
||||
if _, err := service.UpdateNoAuth(created.UUID, &CreateConfigRequest{
|
||||
Name: "cfg",
|
||||
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 1, UnitPrice: 1000}},
|
||||
Notes: `{"pricing_ui":{"sale_uplift":1.5}}`,
|
||||
}); err != nil {
|
||||
t.Fatalf("update: %v", err)
|
||||
}
|
||||
stored, _ = local.GetConfigurationByUUID(created.UUID)
|
||||
if len(stored.FeatureFlags) != 0 {
|
||||
t.Fatalf("flags after clearing markups = %v, want none", stored.FeatureFlags)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWritesRefusedForUnknownFeatureFlags(t *testing.T) {
|
||||
service, local := newLocalConfigServiceForTest(t)
|
||||
|
||||
created, err := service.Create("tester", &CreateConfigRequest{
|
||||
Name: "cfg",
|
||||
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 1, UnitPrice: 1000}},
|
||||
Notes: `{"pricing_ui":{},"future":{"x":1}}`,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
// Simulate a pull of a config last written by a newer client.
|
||||
if err := local.DB().Model(&localdb.LocalConfiguration{}).
|
||||
Where("uuid = ?", created.UUID).
|
||||
Update("feature_flags", models.FeatureFlags{"future_x", configfeatures.SaleRowMarkups}).Error; err != nil {
|
||||
t.Fatalf("set flags: %v", err)
|
||||
}
|
||||
|
||||
got, err := service.GetByUUIDNoAuth(created.UUID)
|
||||
if err != nil {
|
||||
t.Fatalf("get: %v", err)
|
||||
}
|
||||
if want := []string{"future_x"}; !reflect.DeepEqual(got.UnsupportedFeatures, want) {
|
||||
t.Fatalf("UnsupportedFeatures = %v, want %v", got.UnsupportedFeatures, want)
|
||||
}
|
||||
|
||||
assertRefused := func(name string, err error) {
|
||||
t.Helper()
|
||||
ue, ok := configfeatures.AsUnsupported(err)
|
||||
if !ok || !reflect.DeepEqual(ue.Flags, []string{"future_x"}) {
|
||||
t.Fatalf("%s: want UnsupportedError{future_x}, got %v", name, err)
|
||||
}
|
||||
}
|
||||
_, err = service.UpdateNoAuth(created.UUID, &CreateConfigRequest{
|
||||
Name: "cfg",
|
||||
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 2, UnitPrice: 1000}},
|
||||
})
|
||||
assertRefused("update", err)
|
||||
_, err = service.RenameNoAuth(created.UUID, "renamed")
|
||||
assertRefused("rename", err)
|
||||
_, err = service.UpdateServerCount(created.UUID, 3)
|
||||
assertRefused("server count", err)
|
||||
_, err = service.CloneNoAuthToProjectFromVersion(created.UUID, "copy", "tester", nil, 0)
|
||||
assertRefused("clone", err)
|
||||
_, err = service.RollbackToVersion(created.UUID, 1, "tester")
|
||||
assertRefused("rollback", err)
|
||||
|
||||
stored, _ := local.GetConfigurationByUUID(created.UUID)
|
||||
if stored.Name != "cfg" || stored.Items[0].Quantity != 1 || stored.ServerCount != 1 {
|
||||
t.Fatalf("refused writes must leave the row untouched, got %+v", stored)
|
||||
}
|
||||
}
|
||||
@@ -154,7 +154,6 @@ func TestUpdateNoAuthCreatesRevisionWhenPricingSettingsChanged(t *testing.T) {
|
||||
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 1, UnitPrice: 1000}},
|
||||
ServerCount: 1,
|
||||
DisablePriceRefresh: true,
|
||||
OnlyInStock: true,
|
||||
}); err != nil {
|
||||
t.Fatalf("update pricing settings: %v", err)
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ var (
|
||||
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("код опти содержит недопустимые символы (разрешены: буквы, цифры, дефис, точка, подчёркивание)")
|
||||
)
|
||||
@@ -29,6 +28,10 @@ var (
|
||||
// projectCodeRe allows only URL-path-safe characters so project codes can appear directly in URLs.
|
||||
var projectCodeRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
|
||||
|
||||
// invalidVariantCharsRe matches runs of characters not allowed in a variant name, so they
|
||||
// can be collapsed to a single separator by sanitizeProjectVariantName.
|
||||
var invalidVariantCharsRe = regexp.MustCompile(`[^A-Za-z0-9._-]+`)
|
||||
|
||||
type ProjectService struct {
|
||||
localDB *localdb.LocalDB
|
||||
}
|
||||
@@ -45,10 +48,13 @@ type CreateProjectRequest struct {
|
||||
}
|
||||
|
||||
type UpdateProjectRequest struct {
|
||||
Code *string `json:"code,omitempty"`
|
||||
Variant *string `json:"variant,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
TrackerURL *string `json:"tracker_url,omitempty"`
|
||||
Code *string `json:"code,omitempty"`
|
||||
Variant *string `json:"variant,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
TrackerURL *string `json:"tracker_url,omitempty"`
|
||||
RentalEnabled *bool `json:"rental_enabled,omitempty"`
|
||||
ShowStockPrices *bool `json:"show_stock_prices,omitempty"`
|
||||
OnlyInStock *bool `json:"only_in_stock,omitempty"`
|
||||
}
|
||||
|
||||
type ProjectConfigurationsResult struct {
|
||||
@@ -57,7 +63,10 @@ type ProjectConfigurationsResult struct {
|
||||
Total float64 `json:"total"`
|
||||
}
|
||||
|
||||
func (s *ProjectService) Create(ownerUsername string, req *CreateProjectRequest) (*models.Project, error) {
|
||||
// Create creates a project. If req.Variant is not a valid variant name (reserved word
|
||||
// "main" or disallowed characters) it is auto-converted into a valid one instead of
|
||||
// rejecting the request; the returned warning is non-empty when that happened.
|
||||
func (s *ProjectService) Create(ownerUsername string, req *CreateProjectRequest) (*models.Project, string, error) {
|
||||
var namePtr *string
|
||||
if req.Name != nil {
|
||||
name := strings.TrimSpace(*req.Name)
|
||||
@@ -67,17 +76,14 @@ func (s *ProjectService) Create(ownerUsername string, req *CreateProjectRequest)
|
||||
}
|
||||
code := strings.TrimSpace(req.Code)
|
||||
if code == "" {
|
||||
return nil, fmt.Errorf("project code is required")
|
||||
return nil, "", fmt.Errorf("project code is required")
|
||||
}
|
||||
if !projectCodeRe.MatchString(code) {
|
||||
return nil, ErrProjectCodeInvalidChars
|
||||
}
|
||||
variant := strings.TrimSpace(req.Variant)
|
||||
if err := validateProjectVariantName(variant); err != nil {
|
||||
return nil, err
|
||||
return nil, "", ErrProjectCodeInvalidChars
|
||||
}
|
||||
variant, variantWarning := sanitizeProjectVariantName(strings.TrimSpace(req.Variant))
|
||||
if err := s.ensureUniqueProjectCodeVariant("", code, variant); err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
@@ -95,43 +101,44 @@ func (s *ProjectService) Create(ownerUsername string, req *CreateProjectRequest)
|
||||
SyncStatus: "pending",
|
||||
}
|
||||
if err := s.localDB.SaveProject(localProject); err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
if err := s.enqueueProjectPendingChange(localProject, "create"); err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
return localdb.LocalToProject(localProject), nil
|
||||
return localdb.LocalToProject(localProject), variantWarning, nil
|
||||
}
|
||||
|
||||
func (s *ProjectService) Update(projectUUID, ownerUsername string, req *UpdateProjectRequest) (*models.Project, error) {
|
||||
// Update updates a project. Like Create, an invalid req.Variant (reserved word "main" or
|
||||
// disallowed characters) is auto-converted into a valid one instead of rejecting the
|
||||
// request; the returned warning is non-empty when that happened.
|
||||
func (s *ProjectService) Update(projectUUID, ownerUsername string, req *UpdateProjectRequest) (*models.Project, string, error) {
|
||||
localProject, err := s.localDB.GetProjectByUUID(projectUUID)
|
||||
if err != nil {
|
||||
return nil, ErrProjectNotFound
|
||||
return nil, "", ErrProjectNotFound
|
||||
}
|
||||
|
||||
if req.Code != nil {
|
||||
code := strings.TrimSpace(*req.Code)
|
||||
if code == "" {
|
||||
return nil, fmt.Errorf("project code is required")
|
||||
return nil, "", fmt.Errorf("project code is required")
|
||||
}
|
||||
if !projectCodeRe.MatchString(code) {
|
||||
return nil, ErrProjectCodeInvalidChars
|
||||
return nil, "", ErrProjectCodeInvalidChars
|
||||
}
|
||||
localProject.Code = code
|
||||
}
|
||||
var variantWarning string
|
||||
if req.Variant != nil {
|
||||
newVariant := strings.TrimSpace(*req.Variant)
|
||||
// Block renaming of the main variant (empty Variant) — there must always be a main.
|
||||
if strings.TrimSpace(localProject.Variant) == "" && newVariant != "" {
|
||||
return nil, ErrCannotRenameMainVariant
|
||||
}
|
||||
localProject.Variant = newVariant
|
||||
if err := validateProjectVariantName(localProject.Variant); err != nil {
|
||||
return nil, err
|
||||
return nil, "", ErrCannotRenameMainVariant
|
||||
}
|
||||
localProject.Variant, variantWarning = sanitizeProjectVariantName(newVariant)
|
||||
}
|
||||
if err := s.ensureUniqueProjectCodeVariant(projectUUID, localProject.Code, localProject.Variant); err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
if req.Name != nil {
|
||||
@@ -147,15 +154,24 @@ 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
|
||||
}
|
||||
if req.ShowStockPrices != nil {
|
||||
localProject.ShowStockPrices = *req.ShowStockPrices
|
||||
}
|
||||
if req.OnlyInStock != nil {
|
||||
localProject.OnlyInStock = *req.OnlyInStock
|
||||
}
|
||||
localProject.UpdatedAt = time.Now()
|
||||
localProject.SyncStatus = "pending"
|
||||
if err := s.localDB.SaveProject(localProject); err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
if err := s.enqueueProjectPendingChange(localProject, "update"); err != nil {
|
||||
return nil, err
|
||||
return nil, "", err
|
||||
}
|
||||
return localdb.LocalToProject(localProject), nil
|
||||
return localdb.LocalToProject(localProject), variantWarning, nil
|
||||
}
|
||||
|
||||
func (s *ProjectService) ensureUniqueProjectCodeVariant(excludeUUID, code, variant string) error {
|
||||
@@ -190,11 +206,31 @@ func normalizeProjectVariant(variant string) string {
|
||||
return strings.ToLower(strings.TrimSpace(variant))
|
||||
}
|
||||
|
||||
func validateProjectVariantName(variant string) error {
|
||||
if normalizeProjectVariant(variant) == "main" {
|
||||
return ErrReservedMainVariant
|
||||
// sanitizeProjectVariantName converts an invalid variant name (the reserved word "main",
|
||||
// or a name containing characters outside [A-Za-z0-9._-]) into a valid one, returning a
|
||||
// warning describing the change. Empty input (the implicit main variant) always passes
|
||||
// through unchanged with no warning. Invalid characters are collapsed to a single "-";
|
||||
// if that empties the name, or the result collides with the reserved "main", a "-variant"
|
||||
// suffix is appended to guarantee a valid, non-reserved result.
|
||||
func sanitizeProjectVariantName(variant string) (sanitized string, warning string) {
|
||||
original := strings.TrimSpace(variant)
|
||||
if original == "" {
|
||||
return "", ""
|
||||
}
|
||||
return nil
|
||||
sanitized = original
|
||||
if !projectCodeRe.MatchString(sanitized) {
|
||||
sanitized = strings.Trim(invalidVariantCharsRe.ReplaceAllString(sanitized, "-"), "-")
|
||||
}
|
||||
if sanitized == "" {
|
||||
sanitized = "variant"
|
||||
}
|
||||
if normalizeProjectVariant(sanitized) == "main" {
|
||||
sanitized += "-variant"
|
||||
}
|
||||
if sanitized == original {
|
||||
return sanitized, ""
|
||||
}
|
||||
return sanitized, fmt.Sprintf("имя варианта %q недопустимо — использовано %q", original, sanitized)
|
||||
}
|
||||
|
||||
func (s *ProjectService) Archive(projectUUID, ownerUsername string) error {
|
||||
@@ -302,6 +338,15 @@ func (s *ProjectService) GetByCode(code string) (*models.Project, error) {
|
||||
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 {
|
||||
|
||||
@@ -1,37 +1,47 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
)
|
||||
|
||||
func TestProjectServiceCreateRejectsReservedMainVariant(t *testing.T) {
|
||||
// TestProjectServiceCreateSanitizesReservedMainVariant verifies that naming a new
|
||||
// variant "main" no longer errors: the name is auto-converted to a valid one and a
|
||||
// warning is returned instead of the request being rejected.
|
||||
func TestProjectServiceCreateSanitizesReservedMainVariant(t *testing.T) {
|
||||
local, err := newProjectTestLocalDB(t)
|
||||
if err != nil {
|
||||
t.Fatalf("open localdb: %v", err)
|
||||
}
|
||||
service := NewProjectService(local)
|
||||
|
||||
_, err = service.Create("tester", &CreateProjectRequest{
|
||||
project, warning, err := service.Create("tester", &CreateProjectRequest{
|
||||
Code: "OPS-1",
|
||||
Variant: "main",
|
||||
})
|
||||
if !errors.Is(err, ErrReservedMainVariant) {
|
||||
t.Fatalf("expected ErrReservedMainVariant, got %v", err)
|
||||
if err != nil {
|
||||
t.Fatalf("create project: %v", err)
|
||||
}
|
||||
if warning == "" {
|
||||
t.Fatalf("expected a warning about the reserved variant name")
|
||||
}
|
||||
if project.Variant == "" || normalizeProjectVariant(project.Variant) == "main" {
|
||||
t.Fatalf("expected variant to be converted away from 'main', got %q", project.Variant)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectServiceUpdateRejectsReservedMainVariant(t *testing.T) {
|
||||
// TestProjectServiceUpdateSanitizesReservedMainVariant mirrors the create case for
|
||||
// renaming an existing (non-main) variant to "main".
|
||||
func TestProjectServiceUpdateSanitizesReservedMainVariant(t *testing.T) {
|
||||
local, err := newProjectTestLocalDB(t)
|
||||
if err != nil {
|
||||
t.Fatalf("open localdb: %v", err)
|
||||
}
|
||||
service := NewProjectService(local)
|
||||
|
||||
created, err := service.Create("tester", &CreateProjectRequest{
|
||||
created, _, err := service.Create("tester", &CreateProjectRequest{
|
||||
Code: "OPS-1",
|
||||
Variant: "Lenovo",
|
||||
})
|
||||
@@ -40,11 +50,41 @@ func TestProjectServiceUpdateRejectsReservedMainVariant(t *testing.T) {
|
||||
}
|
||||
|
||||
mainName := "main"
|
||||
_, err = service.Update(created.UUID, "tester", &UpdateProjectRequest{
|
||||
updated, warning, err := service.Update(created.UUID, "tester", &UpdateProjectRequest{
|
||||
Variant: &mainName,
|
||||
})
|
||||
if !errors.Is(err, ErrReservedMainVariant) {
|
||||
t.Fatalf("expected ErrReservedMainVariant, got %v", err)
|
||||
if err != nil {
|
||||
t.Fatalf("update project: %v", err)
|
||||
}
|
||||
if warning == "" {
|
||||
t.Fatalf("expected a warning about the reserved variant name")
|
||||
}
|
||||
if updated.Variant == "" || normalizeProjectVariant(updated.Variant) == "main" {
|
||||
t.Fatalf("expected variant to be converted away from 'main', got %q", updated.Variant)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSanitizeProjectVariantName_InvalidChars verifies disallowed characters are
|
||||
// stripped/replaced rather than rejected outright.
|
||||
func TestSanitizeProjectVariantName_InvalidChars(t *testing.T) {
|
||||
sanitized, warning := sanitizeProjectVariantName("Лендинг сервер!")
|
||||
if warning == "" {
|
||||
t.Fatalf("expected a warning for invalid characters")
|
||||
}
|
||||
if !projectCodeRe.MatchString(sanitized) {
|
||||
t.Fatalf("sanitized variant %q still fails projectCodeRe", sanitized)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSanitizeProjectVariantName_ValidPassesThrough ensures already-valid names are
|
||||
// left untouched with no warning.
|
||||
func TestSanitizeProjectVariantName_ValidPassesThrough(t *testing.T) {
|
||||
sanitized, warning := sanitizeProjectVariantName("lenovo-2u")
|
||||
if warning != "" {
|
||||
t.Fatalf("expected no warning, got %q", warning)
|
||||
}
|
||||
if sanitized != "lenovo-2u" {
|
||||
t.Fatalf("expected unchanged variant, got %q", sanitized)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+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
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/appmeta"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/db"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
@@ -217,6 +218,9 @@ func (s *Service) ImportProjectsToLocal() (*ProjectImportResult, error) {
|
||||
existing.TrackerURL = project.TrackerURL
|
||||
existing.IsActive = project.IsActive
|
||||
existing.IsSystem = project.IsSystem
|
||||
existing.RentalEnabled = project.RentalEnabled
|
||||
existing.ShowStockPrices = project.ShowStockPrices
|
||||
existing.OnlyInStock = project.OnlyInStock
|
||||
existing.CreatedAt = project.CreatedAt
|
||||
existing.UpdatedAt = project.UpdatedAt
|
||||
serverID := project.ID
|
||||
@@ -322,6 +326,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 +346,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 +408,7 @@ func (s *Service) SyncPricelists() (int, error) {
|
||||
CreatedAt: pl.CreatedAt,
|
||||
SyncedAt: time.Now(),
|
||||
IsUsed: false,
|
||||
IsActive: true,
|
||||
}
|
||||
|
||||
itemCount, err := s.syncNewPricelistSnapshot(localPL)
|
||||
@@ -414,6 +431,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 +634,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 +837,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 +923,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)
|
||||
}
|
||||
@@ -877,6 +957,8 @@ func (s *Service) PushPendingChanges() (int, error) {
|
||||
slog.Info("auto-repaired errored pending changes", "repaired", repaired)
|
||||
}
|
||||
|
||||
s.requeueOrphanedPendingConfigurations()
|
||||
|
||||
changes, err := s.localDB.GetPendingChanges()
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("getting pending changes: %w", err)
|
||||
@@ -888,7 +970,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,7 +984,14 @@ 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 newAttempts >= maxPendingChangeAttempts {
|
||||
if firstErr == "" {
|
||||
firstErr = err.Error()
|
||||
}
|
||||
failed++
|
||||
// Refused over unknown feature flags: not a transient failure, and dropping it would
|
||||
// lose the local edit — keep it queued until the app is updated.
|
||||
_, unsupported := configfeatures.AsUnsupported(err)
|
||||
if newAttempts >= maxPendingChangeAttempts && !unsupported {
|
||||
slog.Error("abandoning pending change after max attempts",
|
||||
"id", change.ID, "type", change.EntityType, "op", change.Operation,
|
||||
"attempts", newAttempts, "last_error", err.Error())
|
||||
@@ -919,10 +1011,73 @@ 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
|
||||
}
|
||||
|
||||
// requeueOrphanedPendingConfigurations re-enqueues an update for configurations that are
|
||||
// still sync_status=pending but have no queue row left (the row was dropped, e.g. a stale
|
||||
// event was skipped without marking the config synced). The update carries the current
|
||||
// local snapshot and version, so the server receives the latest state.
|
||||
func (s *Service) requeueOrphanedPendingConfigurations() int {
|
||||
orphans, err := s.localDB.ListConfigurationsPendingWithoutQueue()
|
||||
if err != nil {
|
||||
slog.Warn("failed to list orphaned pending configurations", "error", err)
|
||||
return 0
|
||||
}
|
||||
|
||||
requeued := 0
|
||||
for _, orphan := range orphans {
|
||||
cfg, versionID, versionNo, err := s.loadCurrentConfigurationState(orphan.UUID)
|
||||
if err != nil {
|
||||
slog.Warn("cannot requeue orphaned pending configuration", "uuid", orphan.UUID, "error", err)
|
||||
continue
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
payload := ConfigurationChangePayload{
|
||||
EventID: uuid.New().String(),
|
||||
IdempotencyKey: fmt.Sprintf("%s:v%d:requeue", orphan.UUID, versionNo),
|
||||
ConfigurationUUID: orphan.UUID,
|
||||
ProjectUUID: cfg.ProjectUUID,
|
||||
PricelistID: cfg.PricelistID,
|
||||
Operation: "update",
|
||||
CurrentVersionID: versionID,
|
||||
CurrentVersionNo: versionNo,
|
||||
ConflictPolicy: "last_write_wins",
|
||||
Snapshot: cfg,
|
||||
CreatedAt: now,
|
||||
}
|
||||
raw, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
slog.Warn("cannot marshal requeued configuration payload", "uuid", orphan.UUID, "error", err)
|
||||
continue
|
||||
}
|
||||
if err := s.localDB.DB().Create(&localdb.PendingChange{
|
||||
EntityType: "configuration",
|
||||
EntityUUID: orphan.UUID,
|
||||
Operation: "update",
|
||||
Payload: string(raw),
|
||||
CreatedAt: now,
|
||||
}).Error; err != nil {
|
||||
slog.Warn("cannot enqueue requeued configuration", "uuid", orphan.UUID, "error", err)
|
||||
continue
|
||||
}
|
||||
requeued++
|
||||
}
|
||||
|
||||
if requeued > 0 {
|
||||
slog.Info("requeued orphaned pending configurations", "requeued", requeued)
|
||||
}
|
||||
return requeued
|
||||
}
|
||||
|
||||
// pushSingleChange pushes a single pending change to the server
|
||||
func (s *Service) pushSingleChange(change *localdb.PendingChange) error {
|
||||
switch change.EntityType {
|
||||
@@ -1209,6 +1364,15 @@ func (s *Service) pushConfigurationUpdate(change *localdb.PendingChange) error {
|
||||
}
|
||||
}
|
||||
|
||||
// A newer client may have written this config since our last pull, adding data this
|
||||
// build can't see (marked by a feature flag we don't know). Pushing our snapshot over
|
||||
// it would erase that data, so refuse; the change stays queued until the app is updated.
|
||||
if serverCfg, getErr := configRepo.GetByUUID(cfg.UUID); getErr == nil {
|
||||
if err := configfeatures.Check(serverCfg.FeatureFlags); err != nil {
|
||||
return fmt.Errorf("push of configuration %s refused: %w", cfg.UUID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Update on server
|
||||
if err := configRepo.Update(&cfg); err != nil {
|
||||
return fmt.Errorf("updating configuration on server: %w", err)
|
||||
@@ -1606,24 +1770,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
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package sync_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/models"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/services"
|
||||
syncsvc "git.mchus.pro/mchus/quoteforge/internal/services/sync"
|
||||
)
|
||||
|
||||
// Reproduces the state seen in the field bundle: configuration stays sync_status=pending
|
||||
// while its pending_changes rows are gone. Push must not leave it pending forever.
|
||||
func TestPushPendingChangesRequeuesOrphanedPendingConfiguration(t *testing.T) {
|
||||
local := newLocalDBForSyncTest(t)
|
||||
serverDB := newServerDBForSyncTest(t)
|
||||
|
||||
localSync := syncsvc.NewService(nil, local)
|
||||
configService := services.NewLocalConfigurationService(local, localSync, &services.QuoteService{}, func() bool { return false })
|
||||
pushService := syncsvc.NewServiceWithDB(serverDB, local)
|
||||
|
||||
created, err := configService.Create("tester", &services.CreateConfigRequest{
|
||||
Name: "Orphan v1",
|
||||
Items: models.ConfigItems{{LotName: "CPU_O", Quantity: 1, UnitPrice: 500}},
|
||||
ServerCount: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create config: %v", err)
|
||||
}
|
||||
if _, err := configService.UpdateNoAuth(created.UUID, &services.CreateConfigRequest{
|
||||
Name: "Orphan v2",
|
||||
Items: models.ConfigItems{{LotName: "CPU_O", Quantity: 2, UnitPrice: 500}},
|
||||
ServerCount: 1,
|
||||
ProjectUUID: created.ProjectUUID,
|
||||
}); err != nil {
|
||||
t.Fatalf("update config: %v", err)
|
||||
}
|
||||
|
||||
// Simulate the dropped queue: rows are gone, local config still marked pending.
|
||||
if err := local.DB().Where("1 = 1").Delete(&localdb.PendingChange{}).Error; err != nil {
|
||||
t.Fatalf("clear pending changes: %v", err)
|
||||
}
|
||||
|
||||
if _, err := pushService.PushPendingChanges(); err != nil {
|
||||
t.Fatalf("push: %v", err)
|
||||
}
|
||||
|
||||
var serverCfg models.Configuration
|
||||
if err := serverDB.Where("uuid = ?", created.UUID).First(&serverCfg).Error; err != nil {
|
||||
t.Fatalf("configuration not on server: %v", err)
|
||||
}
|
||||
if serverCfg.Name != "Orphan v2" {
|
||||
t.Fatalf("expected latest version on server, got %q", serverCfg.Name)
|
||||
}
|
||||
|
||||
localCfg, err := local.GetConfigurationByUUID(created.UUID)
|
||||
if err != nil {
|
||||
t.Fatalf("get local config: %v", err)
|
||||
}
|
||||
if localCfg.SyncStatus != "synced" {
|
||||
t.Fatalf("expected sync_status synced, got %q", localCfg.SyncStatus)
|
||||
}
|
||||
if got := local.CountPendingChanges(); got != 0 {
|
||||
t.Fatalf("expected empty pending queue, got %d", got)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ func TestPushPendingChangesProjectsBeforeConfigurations(t *testing.T) {
|
||||
projectService := services.NewProjectService(local)
|
||||
configService := services.NewLocalConfigurationService(local, localSync, &services.QuoteService{}, func() bool { return false })
|
||||
|
||||
project, err := projectService.Create("tester", &services.CreateProjectRequest{Name: ptrString("Project A"), Code: "PRJ-A"})
|
||||
project, _, err := projectService.Create("tester", &services.CreateProjectRequest{Name: ptrString("Project A"), Code: "PRJ-A"})
|
||||
if err != nil {
|
||||
t.Fatalf("create project: %v", err)
|
||||
}
|
||||
@@ -74,11 +74,11 @@ func TestPushPendingChangesProjectCreateThenUpdateBeforeFirstPush(t *testing.T)
|
||||
configService := services.NewLocalConfigurationService(local, localSync, &services.QuoteService{}, func() bool { return false })
|
||||
pushService := syncsvc.NewServiceWithDB(serverDB, local)
|
||||
|
||||
project, err := projectService.Create("tester", &services.CreateProjectRequest{Name: ptrString("Project v1"), Code: "PRJ-V1"})
|
||||
project, _, err := projectService.Create("tester", &services.CreateProjectRequest{Name: ptrString("Project v1"), Code: "PRJ-V1"})
|
||||
if err != nil {
|
||||
t.Fatalf("create project: %v", err)
|
||||
}
|
||||
if _, err := projectService.Update(project.UUID, "tester", &services.UpdateProjectRequest{Name: ptrString("Project v2")}); err != nil {
|
||||
if _, _, err := projectService.Update(project.UUID, "tester", &services.UpdateProjectRequest{Name: ptrString("Project v2")}); err != nil {
|
||||
t.Fatalf("update project: %v", err)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -71,33 +71,22 @@ func (w *Worker) runSync() {
|
||||
return
|
||||
}
|
||||
|
||||
// Each stream is independent: a failure in one must not stop the others.
|
||||
// Readiness only gates pushing local changes to the server.
|
||||
if readiness, err := w.service.EnsureReadinessForSync(); err != nil {
|
||||
w.logger.Warn("background sync: blocked by readiness guard",
|
||||
w.logger.Warn("background sync: push blocked by readiness guard",
|
||||
"error", err,
|
||||
"reason_code", readiness.ReasonCode,
|
||||
"reason_text", readiness.ReasonText,
|
||||
)
|
||||
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 {
|
||||
} else if pushed, err := w.service.PushPendingChanges(); err != nil {
|
||||
w.logger.Warn("background sync: failed to push pending changes", "error", err)
|
||||
} else if pushed > 0 {
|
||||
w.logger.Info("background sync: pushed pending changes", "count", pushed)
|
||||
}
|
||||
|
||||
// Then check for new pricelists
|
||||
err = w.service.SyncPricelistsIfNeeded()
|
||||
if err != nil {
|
||||
if err := w.service.SyncPricelistsIfNeeded(); err != nil {
|
||||
w.logger.Warn("background sync: failed to sync pricelists", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Pull partnumber books together with pricelists
|
||||
@@ -105,5 +94,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,11 @@
|
||||
-- Tables affected: qt_configurations
|
||||
-- recovery.not-started: safe to re-run; ADD COLUMN IF NOT EXISTS
|
||||
-- recovery.partial: ALTER TABLE qt_configurations DROP COLUMN feature_flags;
|
||||
-- recovery.completed: no action needed
|
||||
-- verify: feature_flags column missing | SELECT 1 FROM information_schema.COLUMNS WHERE table_schema=DATABASE() AND table_name='qt_configurations' AND column_name='feature_flags' HAVING COUNT(*)=0
|
||||
|
||||
-- Per-configuration feature flags (JSON array of strings, NULL = none). A client refuses
|
||||
-- to write a configuration carrying a flag it doesn't know. See
|
||||
-- bible-local/decisions/2026-09-24-configuration-feature-flags.md.
|
||||
ALTER TABLE qt_configurations
|
||||
ADD COLUMN IF NOT EXISTS feature_flags JSON NULL;
|
||||
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user