Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 09:44:04 +03:00
Mikhail ChusavitinandClaude Sonnet 5 702b459fc0 docs: release notes v3.31
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 19:10:50 +03:00
Mikhail ChusavitinandClaude Sonnet 5 ee92c3b392 feat: price_quality в конфигураторе; фикс пустого lot_description в экспорте цен
price_quality теперь синхронизируется не только в прайслист, но и в
LocalComponent/services.ComponentView (/api/components) — виден в
выпадающем списке поиска (цветная точка), в таблице конфигуратора
(левая колонка-пиктограмма) и на вкладке «Ценообразование» (подсветка
строки). Цветовая шкала вынесена в один модуль web/static/price-quality.js
(подключён в base.html), чтобы не дублировать расчёт цвета по шаблонам.
Шкала — градиент 0 (красный) → 5 (жёлтый) → 9 (зелёный).

Экспорт цен (internal/services/export.go): resolveLotDescriptions был
заглушкой, всегда возвращавшей пустую карту — строки BOM/не-BOM в
экспорте всегда оставались без описания LOT. Заменён на реальный
запрос к local_pricelist_items текущего выбранного прайслиста
(LocalDB.GetLocalDescriptionsForLots), по аналогии с уже существующим
GetLocalLotCategoriesByServerPricelistID.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 19:01:47 +03:00
Mikhail ChusavitinandClaude Sonnet 5 3348008198 chore: обновить submodule bible до последнего коммита
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 18:14:04 +03:00
Mikhail ChusavitinandClaude Sonnet 5 bea8d9453e feat: price_quality индикатор для прайслиста; убраны неиспользуемые price_method/period/coefficient/manual_price/meta_prices
Прайслисты: добавлено поле price_quality (0-9, выставляется внешней
утилитой ценообразования на основе количества/свежести котировок за
период — QF только отображает, не считает сам). В карточке прайслиста
рядом с ценой показывается предупреждение (жёлтый/красный «!») при
quality < 7.

price_method/price_period_days/price_coefficient/manual_price/meta_prices
убраны из контракта QF (models.PricelistItem, local_pricelist_items,
API, колонка «Настройки» на странице прайслиста) — эти поля принадлежат
внешнему движку ценообразования и нигде не использовались в клиенте.
Сами колонки в qt_pricelist_items не трогаем — оставлены для обратной
совместимости с внешней системой.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 18:09:01 +03:00
Mikhail ChusavitinandClaude Sonnet 5 39e6fd5642 feat: вкладка Аренда — колонки Estimate/Цена продажи; lot_description для прайслистов
Вкладка «Аренда»: добавлены колонки Estimate и Цена продажи (+ итоги),
чекбокс «БУ» перенесён первым слева, таблица переведена на тот же
разметку/классы, что и таблицы вкладки «Ценообразование».

Прайслисты: local_pricelist_items получает lot_description (синхронизируется
из qt_pricelist_items.lot_description) вместо устаревших available_qty/
partnumbers, которые нигде не заполнялись.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 15:11:06 +03:00
Mikhail ChusavitinandClaude Sonnet 5 7edb80e498 feat: расчёт стоимости платного тестирования/аренды GPU-серверов
Новая вкладка «Аренда» в конфигураторе (доступна для проектов с флагом
rental_enabled): расчёт по методичке "Регламент расчёта стоимости
платного тестирования и аренды GPU-серверов" — Разовый + Еженедельный
платёж по каждому компоненту (New/БУ чекбоксом), с аплифтом к Estimate.

Заодно: поддержка (support_code) в Base-вкладке теперь добавляется как
обычный LOT в спеку (SVC_{срок}y{уровень}_{платформа}) через
autocomplete-пикер вместо выпадающего списка — партномер собирается
тем же lot_name-based механизмом, что и для GPU/CPU/памяти, справочная
цена по регламенту техподдержки хранится в qt_settings.support_pricing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 13:34:07 +03:00
Mikhail ChusavitinandClaude Sonnet 5 b48436de93 feat: поддержка импорта CSV из pricing-экспорта (customer-facing формат)
Позволяет заново импортировать проект из CSV, экспортированного кнопкой
"Экспорт CSV" (Line Item;LOT;PN вендора;...), а не только из
round-trip формата (Line;Type;p/n;...). Колонки резолвятся по имени,
т.к. набор опциональных столбцов зависит от настроек экспорта.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 13:20:01 +03:00
mchus 20e25927f2 feat: нумерация и сортировка вариантов конфигурации по дате создания
Список вариантов в выпадающем меню теперь сортируется по created_at
(старый сверху) и нумеруется; исправлен наследуемый крупный жирный
шрифт в выпадашке.
2026-07-20 20:05:43 +03:00
mchusandClaude Sonnet 5 472333a47e chore: обновить submodule bible до последнего коммита
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 14:13:24 +03:00
mchusandClaude Sonnet 5 dd2213b206 fix: не упоминать world-подстановку для прайслистов, не отмеченных в выгрузке
Комментарий "Заглушка (world)" в CSV раньше писался для любой колонки
(Estimate/Stock/Конкуренты) с фолбэком на world-прайслист, даже если эта
колонка не отмечена галочкой при экспорте.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 14:12:29 +03:00
Mikhail ChusavitinandClaude Opus 4.8 442509f822 docs: release notes v2.29
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 10:28:13 +03:00
Mikhail ChusavitinandClaude Opus 4.8 95556624e5 chore: обновить submodule bible до последнего коммита
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 10:26:51 +03:00
Mikhail ChusavitinandClaude Opus 4.8 70a3ff255f feat: world-прайслист как заглушка для отсутствующих цен
Там, где для LOT нет цены в estimate/warehouse/competitor, подставляется
цена из world-прайслиста. Такие ячейки в таблицах «Цена покупки»/«Цена продажи»
подсвечиваются (amber), участвуют в «Итого» и убирают красную «*».
В CSV-экспорте добавлена колонка «Заглушка (world)» с перечнем столбцов,
где сработал фолбэк.

Добавлены Tx-версии GetLatestLocalPricelistBySource/GetLocalPricesForLots,
чтобы резолв прайслистов внутри транзакции не дедлочил single-connection пул.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 10:25:46 +03:00
mchusandClaude Sonnet 5 498cbf5490 chore: обновить submodule bible до последнего коммита
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-03 07:33:38 +03:00
mchusandClaude Sonnet 5 80eab1db93 fix: UI виснет на секунды при недоступном MySQL-хосте
OfflineDetector дёргал connMgr.IsOnline() на каждый HTTP-запрос, а тот
при офлайне синхронно лез в сеть и держал дайл/пинг с таймаутом 3с под
общей блокировкой состояния — из-за этого /health и другие запросы
блокировались на секунды прямо в обработчике.

IsOnline() теперь чистое чтение кэша. Реальный сетевой опрос вынесен в
фоновый цикл (ConnectionManager.Start/Stop), а сами попытки dial/ping
сериализуются через отдельный connMu и никогда не держат блокировку
состояния во время сетевого I/O — поэтому конкурентные читатели статуса
больше не ждут таймаут MySQL.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-03 07:31:08 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 5067670294 fix: SQLITE_BUSY при клонировании конфигурации вариантов
SetMaxOpenConns(1) сериализует запись через единственное соединение,
busy_timeout=5000 добавляет ожидание до 5с при внешних блокировках.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 12:02:08 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 ea98eef5de docs: release notes v2.27
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-30 00:57:17 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 50f0e4f76f feat: индикатор присутствия в конфигурациях (иконка глаза)
Открытые конфигурации фиксируются в локальном SQLite (app_settings) и
передаются на сервер через qt_client_schema_state.open_config_uuids при
каждом цикле синхронизации. Списки конфигураций обогащаются полем viewers,
в таблицах отображается иконка глаза с подсказкой при наличии других
пользователей, открывших эту конфигурацию.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-30 00:56:06 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 9601619d1b docs: release notes v2.26
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-29 16:22:54 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 f24584f65c fix: лоты без категории в прайслисте не блокируют сборку артикула
ResolveLotCategoriesStrict переименован в ResolveLotCategories и лишён
строгости: лоты, отсутствующие в прайслисте или с пустой lot_category,
просто пропускаются — партномер из них не собирается. Ранее любой
«незнакомый» лот возвращал ошибку и блокировал сохранение конфига.

Удалены ErrMissingCategoryForLot, MissingCategoryForLotError и
fallback через local_components (противоречил cc72052).

resolvePricelistID: если прайслист отсутствует локально после синка —
fallback на последний активный вместо ошибки.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-29 16:21:45 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 f6766ce6b8 refactor: удалить мёртвый код qt_lot_metadata
Таблица qt_lot_metadata не использовалась в рантайме —
ни один репозиторий/сервис/хендлер к ней не обращался.

- удалён models/metadata.go (LotMetadata, Specs, PriceMethod, PriceFreshness)
- удалена LocalToComponent() из localdb/converters.go
- убран &LotMetadata{} из AutoMigrate
- убраны мёртвые поля PriceFreshness/PopularityScore/Specs из ComponentView

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-29 11:56:59 +03:00
Mikhail ChusavitinandClaude Opus 4.8 464d2a48d7 docs: release notes v2.25
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-29 09:12:03 +03:00
Mikhail ChusavitinandClaude Opus 4.8 b23eb1d75a fix: регистронезависимое сопоставление BOM↔корзина (фронт + CSV)
LOT из BOM-маппинга мог быть в смешанном регистре, а корзина — в каноничном
UPPERCASE, из-за чего позиции дублировались (в таблице «Цена покупки» и в
экспорте CSV).

- localdb.NormalizeLotMappings: единая каноничная нормализация LOT-маппингов
  (UPPERCASE + схлопывание дублей с суммированием qty). Убраны две разошедшиеся
  копии normalizeLotMappings (handlers и services — последняя только тримила,
  что и было причиной бага в CSV).
- export.go: BOM-ветка использует общую функцию + канонизирует LOT корзины
  для coverage/lookup. Удалена мёртвая computeMappingTotal.
- index.html (renderPricingTab): сопоставление/дедуп LOT через каноничный ключ
  UPPERCASE; аксессоры _getRowBaseLot/_getRowAllocations возвращают канон.
- Добавлен регресс-тест TestNormalizeLotMappings_*.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-29 08:59:50 +03:00
Mikhail ChusavitinandClaude Opus 4.8 cc72052c8a refactor: единый источник категории LOT — local_pricelist_items.lot_category
Удалён мёртвый серверный слой управления компонентами/категориями,
который дублировал источники категории LOT. В рантайме категория всегда
берётся из local_pricelist_items.lot_category (наполняется синком из
qt_pricelist_items.lot_category).

Удалено:
- repository: UnifiedRepo/DataSource, ComponentRepository, CategoryRepository
- services: старый ConfigurationService (заменён LocalConfigurationService),
  ComponentService, ComponentToLocal, ImportFromLot, ParsePartNumber
- quote.go: недостижимый online-блок (qt_categories) + componentRepo/
  pricingService/priceResolver

Сохранены живые типы: models.Category/DefaultCategories (для /api/categories),
ComponentView/ComponentListResult, CreateConfigRequest/ArticlePreviewRequest/
ConfigurationGetter/ErrConfig*.

bible-local/03-database.md: зафиксирован единственный источник категории LOT;
qt_categories/qt_lot_metadata перенесены в server-side only.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 21:21:34 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 687ab99d85 docs: release notes v2.24
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 12:06:22 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 ce7c8551be fix: ReferenceError sectionCategories → section.categories в renderMultiSelectTabWithSections
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 10:49:35 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 3788492089 docs: release notes v2.23
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 10:32:57 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 f7d26a28f8 chore: обновление субмодуля bible
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 10:30:31 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 bb742d2f38 fix: DKC/CTL/ENC попадали в Other при режиме server
ASSIGNED_CATEGORIES пересобирался из отфильтрованного tab.categories,
поэтому категории скрытые для текущего типа конфигурации переставали
считаться «назначенными» и уходили в Other. Теперь используется
tab._allCategories (полный статический список) — категория принадлежит
вкладке независимо от видимости в текущем режиме.

Также убрал лишний .toUpperCase() в updateTabVisibility.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 10:29:32 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 f70cc680f7 fix: конфигуратор зависал на «Загрузка...», infinite retry при sync, UpsertByUUID
1. JS-конфигуратор: при загрузке сохранённой конфигурации item.category
   всегда undefined (в config.items хранится только lot_name/quantity/unit_price).
   Добавлено обогащение cart из allComponents после загрузки, все сравнения
   категорий переведены на ciStr() вместо .toUpperCase(), исправлены все 4
   точки построения ASSIGNED_CATEGORIES — устраняет TypeError и таб «Other»
   показывал компоненты с известными категориями.

2. RepairPendingChanges: repair-функции теперь возвращают (bool, error);
   attempts/last_error сбрасываются только при modified=true — устраняет
   бесконечный retry когда ошибка на стороне сервера, а не локальных данных.

3. UpsertByUUID: сброс project.ID=0 перед INSERT … ON DUPLICATE KEY UPDATE,
   чтобы конфликт шёл по уникальному uuid, а не по PK чужой строки —
   устраняет «record not found» при разрешении изменений проекта.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 10:27:29 +03:00
mchus 64c9c4e862 docs: bible-local — удаление local_components, правило регистра lot_name, категория из прайслиста 2026-06-26 08:56:32 +03:00
mchus cc91ca10fc docs: release notes v2.22 2026-06-26 08:54:23 +03:00
mchusandClaude Sonnet 4.6 7d190cc7a8 fix: регистронезависимый поиск lot_name и удаление мёртвого кода
- SQLite-запросы по lot_name теперь используют UPPER(lot_name) IN/= для
  совместимости с легаси-данными, синхронизированными до нормализации регистра
- Удалена таблица local_components и весь связанный код синхронизации;
  источник данных для компонентов — local_pricelist_items
- Удалена функция getCategoryFromLotName из JS: категория берётся только
  из прайслиста, без инференса из имени лота
- Регистронезависимые сравнения lot_name в JS (warehouse stock set,
  addedLots, cartLots, allComponents.find, _bomLotValid)
- В support bundle добавлены: latest_pricelist_items.json, local.db,
  autocomplete_lots.json для диагностики

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 08:52:22 +03:00
mchusandClaude Sonnet 4.6 8b2dc6652a docs: release notes v2.21 (полный диф от v2.19)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 10:14:51 +03:00
mchusandClaude Sonnet 4.6 cea979e327 docs: release notes v2.21
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 10:13:57 +03:00
mchusandClaude Sonnet 4.6 4d002671ae chore: обновление субмодуля bible
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 10:10:16 +03:00
mchusandClaude Sonnet 4.6 949479550c fix: устранение race condition и улучшение диагностики синхронизации
- SyncPricelists() теперь захватывает pricelistMu, предотвращая параллельный
  запуск фонового тикера и ручного sync (было причиной UNIQUE constraint ошибки)
- Дедупликация lot_name в fetchServerPricelistItems на случай дублей на сервере
- PushPendingChanges пишет запись в sync_log (тип "changes") при каждом запуске
- syncPricelists вызывает reportClientSchemaState через defer — состояние
  клиента отправляется на сервер независимо от исхода синхронизации

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 10:08:20 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 677b5d898f fix: не зачёркивать старую цену в итоге конфигурации если изменений нет
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-23 11:59:06 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 b3cab3477b feat: /:code/:variant URL для вариантов опти + валидация имени варианта
- Роут GET /:code/:variant → редирект на /projects/:uuid (case-insensitive)
- Валидация имени варианта: только URL-безопасные символы [A-Za-z0-9._-]
  (бэкенд validateProjectVariantName + клиентская проверка в обеих формах)
- Подсказки в UI: «Используется в URL: /КОД/Вариант»

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-23 11:39:50 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 6d4a37df8b feat: ревизия до обновления цен + короткие ссылки /:code для опти
- При нажатии «обновить цены» создаётся ревизия текущего состояния
  («до обновления цен») через новый эндпоинт POST /api/configs/:uuid/snapshot,
  затем saveConfig создаёт ревизию с новыми ценами
- Роут GET /:code → редирект на /projects/:uuid по коду опти (регистронезависимо)
- Валидация кода опти: только URL-безопасные символы [A-Za-z0-9._-]
  (бэкенд + клиентская проверка + подсказка в форме)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-23 11:29:40 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 7cc101d24d docs: release notes v2.19
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-23 09:49:44 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 4900cd073c feat: server-driven configurator settings via qt_settings
Replaces hardcoded JS category filters and config-type buttons with
server-pushed settings synced from qt_settings (MariaDB) → local_qt_settings (SQLite).

- new table local_qt_settings (AutoMigrate) — synced after component sync
- GET /api/configurator-settings returns config_types, tab_config,
  always_visible_tabs, required_categories with hardcoded fallbacks
- new-config modal: type buttons rendered from server data (Сервер/СХД static fallback)
- configurator: TAB_CONFIG and category filter driven by server; required-category badge on tabs
- SyncQtSettings wired into SyncComponents and SyncAll handlers (non-fatal on old server)
- bible-local/server-contract-qt-settings.md — contract for server-side agent
- page titles: OFS → QFS

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-23 09:33:31 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 c0588e9710 chore: release.sh — только darwin-arm64 и windows-amd64
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-18 14:34:12 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 0cd4f99b46 docs: release notes v1.18
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-18 14:26:36 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 4982adbe41 fix: сортировка строк по категории в pricing CSV и вкладке Ценообразование (no-BOM)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-18 14:25:23 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 5359ae6ded fix: pricing-таблица использует qty из корзины (source of truth)
Ценообразование показывало неверное количество для LOT-ов с bundle
(lot_qty_per_pn > 1) или устаревшим quantity_per_pn в vendor_spec.
Итог Estimate расходился с Estimate-табом.

Теперь qty берётся из корзины если LOT там присутствует; BOM-расчёт
(row.quantity × lot_qty_per_pn) остаётся fallback для ещё не применённых строк.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-17 12:20:13 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 76d93c6be8 feat: сохранение и экспорт ручной цены (buy/sale) из вкладки Ценообразование
Сохранение:
- restoreAutosaveDraftIfAny теперь восстанавливает pricing_ui из notes драфта
- saveConfigOnExit привязан к pagehide и visibilitychange — цены сохраняются
  на сервер при уходе со страницы без явного нажатия «Сохранить»

Экспорт CSV:
- exportPricingCSV передаёт manual_price (buy для FOB, sale для DDP)
- ProjectPricingExportOptions.ManualPrice *float64 — новое поле
- distributeManualPrice распределяет ручную цену пропорционально estimate
  с коррекцией остатка на последней строке
- Колонка «Ручная цена» в CSV (заголовок, строки, итог конфига)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-17 09:59:27 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 c6385f6cf1 fix: CSV экспорт — bundle (1 PN → N LOT) разворачивается в отдельные строки
buildPricingExportBlock теперь создаёт одну строку на каждый LOT mapping,
а не одну строку на BOM-строку. BOM-цена ставится только в первую подстроку
(как vendorOrig в фронтенде). Добавлен computeSingleLotTotal, удалён
неиспользуемый formatLotDisplay.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-17 07:53:37 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 1ab5186d0c fix: BOM — cart-LOT priority в дропдауне + корректный qtyMismatch при lot_qty_per_pn > 1
- filterAutocompleteBOM: LOT из текущего конфигуратора выводятся первыми
  с разделителем «── прочие ──», остальные — по popularity_score
- qtyMismatch теперь сравнивает cartQty с pn_qty × lot_qty_per_pn во всех
  трёх местах рендера BOM-таблицы; «8 LOT = 1 PN» больше не даёт ложного
  жёлтого предупреждения

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-17 07:48:40 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 b6fdac1caa feat: Nx BOM import — формат <qty>x <description>
Добавлен новый вариант импорта спеки: quantity-first формат, где каждая
строка начинается с `<qty>x <description>` (например, «2x Intel Xeon 8570»).
Порядок детекции: Inspur → Nx → Text BOM. Заголовок «, в составе:» работает
так же, как в Text BOM — последний токен перед запятой становится server_model.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-17 07:42:46 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 b837ca7866 docs: release notes v1.17
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-16 17:56:58 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 c8092da370 fix: поиск по LOT в книгах партномеров — CAST(lots_json AS TEXT) LIKE
modernc.org/sqlite (glebarez/sqlite) не приводит BLOB к TEXT при LIKE,
в отличие от нативного sqlite3. lots_json хранится как BLOB (json.Marshal
возвращает []byte), поэтому `lots_json LIKE ?` всегда возвращал 0.
Исправлено на CAST(lots_json AS TEXT) LIKE — теперь поиск по LOT имени
работает корректно.

Заодно обновлён плейсхолдер поля поиска: «PN, LOT или описание».

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-16 17:52:58 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 4f105822c6 docs: release notes v1.16
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-16 17:30:05 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 6df262b8ee fix: self-heal застрявших pending changes при broken project reference
- ensureConfigurationProject: если project не найден ни на сервере, ни локально
  (stale UUID после удаления), падаем в fallback «Без проекта» вместо вечной ошибки
- PushPendingChanges: автоматически вызывает RepairPendingChanges() перед циклом,
  чтобы локально-исправимые проблемы чинились до попытки отправки
- maxPendingChangeAttempts=20: после 20 неудачных попыток change считается
  unrecoverable и удаляется из очереди (логируется ERROR)
- pushSingleChange/pushConfigurationChange: unknown entity type / operation
  теперь дропается с warn вместо вечного error в цикле
- latestSyncErrorState: last_sync_error_text в qt_client_schema_state теперь
  содержит JSON-массив с type/uuid/op/attempts/error по всем застрявшим changes
  (до 20 штук) вместо текста только последней ошибки

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-16 17:28:07 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 0fc0366bb1 feat: синхронизировать книги партномеров вместе с прайслистами
PullPartnumberBooks вызывается автоматически после каждой синхронизации
прайслистов — в фоновом воркере, при ручном триггере /api/sync/pricelists
и при полной синхронизации /api/sync/all. Отдельная кнопка «Синхронизировать»
на странице Партномера удалена.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-16 17:09:14 +03:00
Mikhail ChusavitinandClaude Sonnet 4.6 d204e337b5 feat: сохранять ручные PN→LOT маппинги как lot_suggestion в qt_vendor_partnumber_seen
При сохранении vendor-spec строки с заполненным lot_mappings автоматически
отправляются на сервер и пишутся в новый столбец lot_suggestion. Столбец
хранит JSON-массив [{lot_name, qty}] — тот же формат, что qt_partnumber_book_items.lots_json.

Если миграция ещё не прошла (столбец отсутствует), приложение логирует WARN
и записывает строку без столбца; сбоя нет.

Контракт для инструмента создания partnumber-books описан в bible-local/11-lot-suggestions.md.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-16 15:39:53 +03:00
Mikhail ChusavitinandClaude Opus 4.8 d340bf80af docs: release notes v1.14
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 09:19:58 +03:00
99 changed files with 5964 additions and 3343 deletions

No files matched your search

+328
View File
@@ -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/`). Обнови в том же коммите, что и код.
+99 -3
View File
@@ -40,14 +40,25 @@ Readiness guard:
## Pricing contract
Prices come only from `local_pricelist_items`.
`local_pricelist_items` is the single source of truth for both prices and component catalog (lot_name + lot_category). There is no separate component catalog table.
Rules:
- `local_components` is metadata-only;
- quote calculation must not read prices from components;
- `local_components` table has been removed; do not recreate it;
- component list for the configurator autocomplete comes from `local_pricelist_items` via `ListComponents`;
- quote calculation reads prices from `local_pricelist_items` only;
- latest pricelist selection ignores snapshots without items;
- auto pricelist mode stays auto and must not be persisted as an explicit resolved ID.
## lot_name case handling
lot_names in `local_pricelist_items` may be stored in mixed case in databases synced before normalization was enforced. `NormalizeLotName` (uppercase + trim) is applied at sync time via `PricelistItemToLocal`, but existing rows are not retroactively updated.
Rules:
- all SQLite queries that filter by `lot_name` must use `UPPER(lot_name) IN ?` or `UPPER(lot_name) = ?` with an uppercased input — never a bare `=` or `IN` on a string that may have been sourced from user input or a legacy row;
- result map keys must preserve the original case passed by the caller (build a `uppercase → original` index before the query);
- `GetLocalPricesForLots` is the canonical pattern: it uppercases the input list, queries with `UPPER(lot_name) IN ?`, and returns keys that match the input lot_names;
- frontend JS must never infer a component category from the lot_name prefix; `lot_category` from `local_pricelist_items` is the only valid source; items without a category fall into the "Other" tab.
## Pricing tab layout
The Pricing tab (Ценообразование) has two tables: Buy (Цена покупки) and Sale (Цена продажи).
@@ -116,6 +127,91 @@ Rules:
- 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.
## Server-driven configurator settings (`qt_settings`)
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.
| Setting key | Effect in QF |
|-------------|-------------|
| `config_types` | New-config modal buttons; category allowlist per config type |
| `tab_config` | Configurator tab structure, sections, singleSelect |
| `always_visible_tabs` | Which tabs are shown even when empty |
| `required_categories` | Per-config-type badge on tabs with unfilled required categories |
| `support_pricing` | Price data for the Base tab's support-level picker (see below) |
Rules:
- sync runs as part of the pricelist pull; failure is non-fatal (Warn log only);
- `local_qt_settings` is a read-only cache — never written by user actions;
- absent or unparseable settings: QF uses hardcoded fallbacks for that key only;
- `config_types[].categories` is an allowlist: a category absent from all types is shown everywhere;
- `qt_categories.name` and `qt_categories.name_ru` are not used by QF runtime; do not depend on them.
## Support as a BOM LOT
The Base tab's support-level picker adds/replaces a synthetic LOT in `cart` (e.g.
`SVC_3yB_HGX-H200`, quantity 1) exactly like adding any other component — not a separate
mechanism. This means support flows through `total_price`, the Pricing tab, exports, and the
rental calc the same way any BOM line does, with no special-casing needed in those paths.
- lot_name shape: `SVC_{years}y{level}_{platform}` (e.g. `SVC_3yB_HGX-H200`); `internal/article
/generator.go`'s `buildSupportSegment` detects it by the `SVC_` lot_name prefix (support LOTs
aren't in the pricelist catalog, so there's no `lot_category` to key off — same lot_name-pattern
approach the generator already uses for GPU/CPU/memory parsing) and emits the `{years}y{level}`
token as the article's SUPPORT segment, replacing the old separate `BuildOptions.SupportCode`
field/`isSupportCodeValid` check;
- `Configuration.SupportCode` (the DB column) is no longer read by article generation; it's
inert legacy metadata now — the LOT in `items` is the source of truth;
- the picker's displayed price is computed client-side per "Регламент расчёта стоимости
технической поддержки серверов": x86 is a percent of the rest of the cart's total (proxy for
"цена продажи"), HGX platforms use a fixed multi-year price by chip generation. The pricing
table itself lives in `qt_settings["support_pricing"]` so it can be edited in MariaDB without
a QuoteForge release — see `bible-local/server-contract-qt-settings.md` for the schema; the
fixed list of offerable level×duration codes stays in the frontend, only the price is
server-driven;
- platform (x86 vs HGX-H100/H200 vs HGX-B200 vs HGX-B300) is auto-detected client-side from the
cart's GPU components, the same chip-generation classification used by the rental
depreciation calc (`internal/services/rental.go`), so the picker only offers combinations
valid for the current configuration;
- the support LOT has no `lot_category` (not in the pricelist), so it renders under the
"Other" category tab like any other uncategorized item — no new tab/category was added for it.
## Rental / paid-testing pricing contract
QuoteForge can quote paid testing / short-to-mid-term rental of a configuration's hardware, per the draft
regulation "Регламент расчёта стоимости платного тестирования и аренды GPU-серверов" (methodology may still
change; buyout/Step 9 of the regulation is intentionally not implemented).
Rules:
- rental is enabled per **project** via `Project.RentalEnabled` (`qt_projects.rental_enabled`); when set, the
configurator shows a 4th top-level tab ("Аренда") for every configuration in that project;
- New/БУ condition per component lives only on the configuration, in `Configuration.RentalItems`
(`RentalItemCondition{LotName, Condition}`) — it is not a property of the lot/pricelist and does not touch
`ConfigItem`/BOM; the same lot_name can be "new" in one configuration and "used" in another;
- the "Цена" the methodology depreciates against is `Estimate buy price × (1 + RentalUpliftPercent/100)` —
QuoteForge has no per-component sale price, so a single project-configuration-wide uplift percentage stands
in for it;
- pricing is always quoted per week — Разовый (one-time layer-1 hit) + Еженедельный (recurring); there is no
term/weeks input, a sales rep multiplies the weekly rate by however many weeks are needed;
- annual BASE support price is **computed automatically**, never entered manually, per "Регламент расчёта
стоимости технической поддержки серверов": any GPU component present classifies the configuration as HGX and
uses the regulation's fixed per-platform price (H100/H200, B200, B300, by lot_name substring); no GPU present
falls back to 5% of the uplifted price sum as an x86 sale-price proxy — `support_code` is pure
article-formatting metadata (see `internal/article/generator.go`) and is never resolved to a price, so there
is no SVC_-catalog lookup to reuse;
- GPU "actual vs stabilized generation" classification for depreciation life (2yr vs 3yr) and the separate
GPU "support platform" classification (H100/H200 vs B200 vs B300) are both hardcoded lot_name substring
lists in `internal/services/rental.go`, not sourced from `lot_category`;
- `RentalItems` and `RentalUpliftPercent` are included in the revision dedup fingerprint
(`BuildConfigurationSpecPriceFingerprint`), so rental edits create new revisions like other spec/price-affecting
changes;
- `internal/services/rental.go` (`RentalService.Calculate`) is stateless: it re-derives categories via
`GetLocalLotCategoriesByServerPricelistID` and computes pricing (including the auto support price) from the
request body, so calculate calls do not require saving first.
## Vendor BOM contract
+41 -15
View File
@@ -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 |
@@ -20,12 +19,16 @@ Main tables:
| `connection_settings` | encrypted MariaDB connection settings |
| `app_settings` | local app state |
| `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
@@ -34,12 +37,11 @@ MariaDB is the central sync database (`RFQ_LOG`). Final schema as of 2026-04-15.
### QuoteForge tables (qt_*)
Runtime read:
- `qt_categories` — pricelist categories
- `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
- `qt_partnumber_book_items` — PN→LOT catalog payload
- `qt_settings` — server-pushed configurator settings; schema managed by server-side agent (see `bible-local/server-contract-qt-settings.md`)
Runtime read/write:
- `qt_projects` — projects
@@ -48,9 +50,11 @@ Runtime read/write:
- `qt_pricelist_sync_status` — pricelist sync timestamps per user
Insert-only tracking:
- `qt_vendor_partnumber_seen` — vendor partnumbers encountered during sync
- `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`)
@@ -77,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.
@@ -91,11 +95,26 @@ Full column reference as of 2026-03-21 (`RFQ_LOG` final schema).
|--------|------|-------|
| id | bigint UNSIGNED PK AUTO_INCREMENT | |
| code | varchar(20) UNIQUE NOT NULL | |
| name | varchar(100) NOT NULL | |
| name_ru | varchar(100) | |
| name | varchar(100) NOT NULL | being removed; QF does not use at runtime |
| name_ru | varchar(100) | being removed; QF does not use at runtime |
| display_order | bigint DEFAULT 0 | |
| is_required | tinyint(1) DEFAULT 0 | |
### qt_settings
Managed by the server-side agent. QF has SELECT-only access.
See `bible-local/server-contract-qt-settings.md` for full schema and value formats.
| Column | Type | Notes |
|--------|------|-------|
| name | varchar(100) PK | setting key |
| value | TEXT NOT NULL | JSON-encoded value |
### local_qt_settings (SQLite)
Read-only cache of `qt_settings`. Synced during component sync.
| Column | Type | Notes |
|--------|------|-------|
| name | text PK | setting key |
| value | text | JSON value as-is from server |
### qt_client_schema_state
PK: (username, hostname)
| Column | Type | Notes |
@@ -174,6 +193,8 @@ PK: lot_name
| line_no | int | position within project |
| price_updated_at | timestamp | |
| vendor_spec | longtext JSON | |
| rental_items | JSON | per-lot New/БУ condition for the Аренда tab; see [02-architecture.md](02-architecture.md#rental--paid-testing-pricing-contract) |
| rental_uplift_percent | decimal(8,2) DEFAULT 0 | uplift applied to Estimate buy price for rental "Цена" |
### qt_lot_metadata
PK: lot_name
@@ -236,12 +257,15 @@ PK: lot_name
| pricelist_id | bigint UNSIGNED NOT NULL | FK → qt_pricelists.id |
| lot_name | varchar(255) NOT NULL | INDEX with pricelist_id |
| lot_category | varchar(50) | |
| lot_description | varchar(10000) | added by migration 032; backfilled once from `lot.lot_description`. QF syncs this column directly — do not join `lot` per-row to get a description |
| price | decimal(12,2) NOT NULL | |
| price_method | varchar(20) | |
| price_period_days | bigint DEFAULT 90 | |
| price_coefficient | decimal(5,2) DEFAULT 0 | |
| manual_price | decimal(12,2) | |
| meta_prices | varchar(1000) | |
| price_quality | tinyint unsigned, nullable | added by migration 033. Set by the external pricelist-building tool, 0-9, based on quote recency/count per its own per-lot pricing-period settings — QF only reads and displays it, never computes it. |
`price_quality` is synced through `LocalPricelistItem` (pricelist detail page) and, separately, through `LocalComponent`/`services.ComponentView` (`/api/components`, used by the configurator's search dropdown and item table) — both read paths go through `pricelistItemRow`/`toLocalComponent()` in `internal/localdb/components.go`. The `/api/components` path reads the component universe (`world` ∪ `estimate`, see [decisions/2026-07-24-component-universe-world-union.md](decisions/2026-07-24-component-universe-world-union.md)), where a world-only LOT is forced to `price_quality = 0` — the only place QF writes this field rather than reading it. The color scale (red 0 → yellow 5 → green 9, gradient) lives in **one shared JS module**, `web/static/price-quality.js` (loaded by `base.html` for every page) — `priceQualityColor`/`qualityDotHtml`/`qualityBadgeHtml`/`qualityRowStyle`. Do not reimplement the color scale locally in a template; add a new helper to that module instead. Used in: pricelist detail "Качество" column, configurator search dropdown (colored dot), configurator table (leftmost quality-dot column), pricing tab (row background tint).
The real table also has `price_method`, `price_period_days`, `price_coefficient`, `manual_price`, `meta_prices` and `lead_time_weeks` columns, owned and written by the external pricing engine that maintains `qt_pricelist_items` — **keep them in the table for backward compatibility with that system; QF must never drop, rename, or write to them.** QF itself does not model, sync, or display any of them (tried once, removed as unused/dead in the client). Do not re-add them to `models.PricelistItem`/`LocalPricelistItem` without a concrete UI need.
Fields QF never populates and does not model: `AvailableQty`/`Partnumbers` (removed from `models.PricelistItem` and `LocalPricelistItem` — no writer ever set them; always empty).
### qt_pricelist_sync_status
PK: username
@@ -276,6 +300,7 @@ PK: username
| tracker_url | varchar(500) | |
| is_active | tinyint(1) DEFAULT 1 | |
| is_system | tinyint(1) DEFAULT 0 | |
| rental_enabled | tinyint(1) DEFAULT 0 | shows the Аренда tab on this project's configurations |
| created_at | timestamp | |
| updated_at | timestamp ON UPDATE | |
@@ -312,6 +337,7 @@ PK: job_name
| ignored_by | varchar(100) | |
| created_at | datetime(3) | |
| updated_at | datetime(3) | |
| lot_suggestion | longtext (JSON) | nullable; set when user manually maps PN → LOT in vendor-spec UI; same format as `qt_partnumber_book_items.lots_json`; see [11-lot-suggestions.md](11-lot-suggestions.md) |
### stock_ignore_rules
| Column | Type | Notes |
+3 -1
View File
@@ -50,7 +50,7 @@
| --- | --- | --- |
| `POST` | `/api/quote/validate` | validate config items |
| `POST` | `/api/quote/calculate` | calculate quote totals |
| `POST` | `/api/quote/price-levels` | resolve estimate/warehouse/competitor prices |
| `POST` | `/api/quote/price-levels` | resolve estimate/warehouse/competitor prices (falls back to `world` source per column, see [decisions/2026-07-10-world-pricelist-fallback.md](decisions/2026-07-10-world-pricelist-fallback.md)) |
| `POST` | `/api/export/csv` | export a single configuration |
| `GET` | `/api/configs/:uuid/export` | export a stored configuration |
| `GET` | `/api/projects/:uuid/export` | legacy project BOM export |
@@ -80,6 +80,8 @@
| `PUT` | `/api/configs/:uuid/vendor-spec` | replace vendor BOM |
| `POST` | `/api/configs/:uuid/vendor-spec/resolve` | resolve PN -> LOT |
| `POST` | `/api/configs/:uuid/vendor-spec/apply` | apply BOM to cart |
| `PUT` | `/api/configs/:uuid/rental` | persist Аренда tab state (per-lot New/БУ, weeks, uplift %, annual support) |
| `POST` | `/api/configs/:uuid/rental/calculate` | compute rental/paid-testing pricing without persisting |
## Projects
+66 -4
View File
@@ -25,6 +25,33 @@ Rules:
- QuoteForge does not use legacy BOM tables;
- apply flow rebuilds cart rows from `lot_mappings[]`.
## Split partnumbers (HPE option codes)
HPE specs carry the partnumber in two columns: base PN plus an option code
(`P52534-B21` + `B19`). The canonical partnumber is the concatenation
`P52534-B21#B19`, and it is what gets compared against the partnumber book.
Rules:
- the import grid has a `PN code` column type in addition to `P/N`; it is optional
and at most one column may carry it;
- an empty code cell keeps the bare PN — no trailing `#`;
- the composed value is stored in `vendor_partnumber`. There is **no separate
`pn_code` field**: no DDL and no new JSON key, and the stored string is exactly
the string the resolver looks up;
- the column layout of the import grid is not persisted. On load the grid is
re-derived from `vendor_spec`, and the `PN code` column reappears only when at
least one stored partnumber contains `#`, split on the first `#`.
## Re-resolving an existing BOM
Opening a configuration does **not** re-resolve its BOM: `loadVendorSpec` renders the
`lot_mappings[]` frozen at save time, so a configuration keeps the mapping it was
saved with even after the partnumber book changes.
Book entries added later are picked up only through the `Пересопоставить` button,
which calls the resolve endpoint for every row. Book matches win over the stored
mapping (resolver step 1 beats step 2); rows the book does not know keep theirs.
## Partnumber books
Partnumber books are pull-only snapshots from PriceForge.
@@ -112,6 +139,41 @@ Rules:
- lines that do not match `<description> - <quantity> шт.` are skipped;
- no price data is present in the format; `unit_price` and `total_price` are left nil.
## Nx BOM import (quantity-first)
The same endpoint `POST /api/projects/:uuid/vendor-import` also accepts a quantity-first BOM
where each item line begins with `<qty>x <description>`.
Format: an optional header line ending with `, в составе:` followed by one component per line as
`<qty>x <description>`. The `x` separator is case-insensitive; parentheses, commas, and hyphens
inside the description are preserved as-is.
Example:
```
Сервер G893-SD1-AAX3, в составе:
1x 8U 2CPU 8GPU Server System (32x DDR5 DIMM Slots,8x 2.5" Hot-Swap Drive Bays, 4+4 3000W, 2x 10Gb/s RJ45, 2x IPMI RJ45)
2x Intel Xeon 8570 (56 cores, 2.1GHz, 300MB, 350W)
32x 64GB DDR5 ECC RDIMM
1x GPU Nvidia HGX H200 141GB 8GPU
3x 1.92TB NVMe PCIe SFF RI
5x 7.68TB NVMe PCIe SFF RI
8x 1-port 400G NDR OSFP CX7
2x 2-port 100GbE QSFP56 CX6
1x 2-port 10GbE RJ45
```
Rules:
- the entire file becomes a single configuration (`server_count = 1`);
- the header (any line ending with `, в составе:`) supplies `server_model` and `name`; the model is the
last whitespace-separated token before the comma;
- without a header, `name` falls back to the uploaded filename (without extension) and `server_model` is empty;
- the format carries no partnumbers — each line's description is stored as both `vendor_partnumber` and
`description`, so rows resolve through the active partnumber book when matched and otherwise stay
unresolved and editable in the UI;
- lines that do not match `<qty>x <description>` are skipped;
- no price data is present in the format; `unit_price` and `total_price` are left nil;
- detection runs before Text BOM in the format switch (Inspur → Nx → Text).
## Pasted BOM text parsing
`POST /api/vendor-spec/parse-text` is a stateless endpoint that parses pasted single-column text BOM
@@ -119,7 +181,7 @@ Rules:
`{"rows": [{vendor_partnumber, quantity, description}], "format": "Inspur"|"Text"|""}`.
This shares the exact detectors and parsers used by the file-import path
(`ParsePastedBOMText` → `IsInspurBOM`/`parseInspurBOM`, `IsTextBOM`/`parseTextBOM`), so paste and upload
behave identically — there is no second parser in the frontend. The configurator's BOM paste box calls
this endpoint; an empty `rows` result (or any payload containing tabs, i.e. a real spreadsheet table)
falls back to the manual column-mapping grid.
(`ParsePastedBOMText` → `IsInspurBOM`/`parseInspurBOM`, `IsNxBOM`/`parseNxBOM`, `IsTextBOM`/`parseTextBOM`),
so paste and upload behave identically — there is no second parser in the frontend. The configurator's BOM
paste box calls this endpoint; an empty `rows` result (or any payload containing tabs, i.e. a real
spreadsheet table) falls back to the manual column-mapping grid.
+161
View File
@@ -0,0 +1,161 @@
# 11 - Lot Suggestions (qt_vendor_partnumber_seen)
## Purpose
`qt_vendor_partnumber_seen` records vendor partnumbers encountered during import
that have no mapping in the active partnumber book. When a user manually maps
such a partnumber to one or more LOT names in the QuoteForge UI, those mappings
are written back to the server as **lot suggestions** — hints for the team that
maintains `qt_partnumber_book_items`.
## Schema Extension
Add one nullable column to `qt_vendor_partnumber_seen`:
```sql
ALTER TABLE `qt_vendor_partnumber_seen`
ADD COLUMN `lot_suggestion` longtext DEFAULT NULL
COMMENT 'JSON array [{lot_name, qty}] — user-entered LOT mappings from the UI';
```
### Updated table contract (relevant columns only)
| Column | Type | Notes |
|--------|------|-------|
| `partnumber` | varchar(255) UNIQUE NOT NULL | natural key |
| `lot_suggestion` | longtext (JSON) | nullable; set when user maps the PN manually |
`lot_suggestion` contains the same JSON shape as `qt_partnumber_book_items.lots_json`:
```json
[
{ "lot_name": "LOT_A", "qty": 1 },
{ "lot_name": "LOT_B", "qty": 2 }
]
```
Rules:
- `null` or absent means no suggestion has been entered yet;
- an empty array `[]` is not a valid value — use `null` instead;
- a single PN may map to multiple lots (`lot_name` entries), each with its own `qty`;
- the array is ordered — the order reflects the order of `lot_mappings[]` in the
vendor spec row at the time of last user save;
- `qty` must be a positive integer (≥ 1).
## Write Contract (QuoteForge → MariaDB)
QuoteForge writes `lot_suggestion` when all of the following are true:
1. The user saves a vendor BOM via `PUT /api/configs/:uuid/vendor-spec`.
2. At least one `vendor_spec` row has a non-empty `lot_mappings[]` array (manually
entered or confirmed by the user — not auto-resolved from a partnumber book).
3. The MariaDB connection is available at the time of save.
For each such row:
```sql
INSERT INTO qt_vendor_partnumber_seen
(source_type, vendor, partnumber, description, is_ignored, last_seen_at, lot_suggestion)
VALUES
('manual', '', ?, ?, 0, NOW(3), ?)
ON DUPLICATE KEY UPDATE
lot_suggestion = VALUES(lot_suggestion),
last_seen_at = IF(lot_suggestion IS NULL, last_seen_at, NOW(3))
```
- `lot_suggestion` value = JSON-marshalled `lot_mappings[]` from the vendor spec item,
reusing the same `{lot_name, qty}` shape.
- If the PN row already exists and `lot_suggestion` is already set, it is **overwritten**
with the latest user input (the user is assumed to have corrected it).
- If the user **clears** all lot_mappings for a PN (sets to empty), no update is sent —
the existing `lot_suggestion` on the server is left untouched.
- Rows where `lot_mappings[]` is empty or nil are skipped entirely (no insert, no update).
- Writes are best-effort: a MariaDB error for one row is logged and skipped; remaining
rows continue. A write failure does not fail the vendor-spec save.
## Read Contract (Partnumber-Book Creation Tool → MariaDB)
The tool that maintains `qt_partnumber_book_items` reads `qt_vendor_partnumber_seen`
to discover new partnumbers and their suggested mappings.
### Discovery query
```sql
SELECT
s.id,
s.partnumber,
s.description,
s.vendor,
s.lot_suggestion,
s.last_seen_at,
b.lots_json AS book_lots_json
FROM qt_vendor_partnumber_seen s
LEFT JOIN qt_partnumber_book_items b ON b.partnumber = s.partnumber
WHERE s.is_ignored = 0
AND s.lot_suggestion IS NOT NULL
ORDER BY s.last_seen_at DESC;
```
### Interpretation rules
| Condition | Meaning | Suggested action |
|-----------|---------|-----------------|
| `book_lots_json IS NULL` AND `lot_suggestion IS NOT NULL` | No book entry yet; user suggested mapping | Create new `qt_partnumber_book_items` row with `lots_json = lot_suggestion` |
| `book_lots_json IS NOT NULL` AND `lot_suggestion IS NOT NULL` AND they differ | User corrected or extended the existing mapping | Review diff and decide whether to update `qt_partnumber_book_items` |
| `book_lots_json IS NOT NULL` AND `lot_suggestion IS NOT NULL` AND they match | Suggestion already applied | No action needed |
### Suggestion format
`lot_suggestion` is valid JSON (or `null`). Parse it as an array of objects:
```json
[
{ "lot_name": "LOT_A", "qty": 1 },
{ "lot_name": "LOT_B", "qty": 2 }
]
```
Map directly to `qt_partnumber_book_items.lots_json` — the formats are identical.
### Multiple lots per PN
One PN may have multiple suggestion entries (e.g., a bundle). The array carries
all of them. The book-creation tool must preserve the full array when writing
`lots_json`, not just the first element.
### Qty semantics
`qty` in a lot suggestion means "how many of this LOT per one occurrence of the
vendor PN". This matches `qt_partnumber_book_items.lots_json` exactly. Example:
a server platform that comes with 4 PSUs would produce
`[{"lot_name": "PS_1300W_Titanium", "qty": 4}]`.
## Permissions
The existing `qfs_user` grant covers this column — no new permission is required:
```sql
GRANT SELECT, INSERT, UPDATE ON RFQ_LOG.qt_vendor_partnumber_seen TO 'qfs_user'@'%';
```
The book-creation tool connects with its own credentials and needs at minimum:
```sql
GRANT SELECT ON RFQ_LOG.qt_vendor_partnumber_seen TO '<book_tool_user>'@'%';
GRANT SELECT, INSERT, UPDATE ON RFQ_LOG.qt_partnumber_book_items TO '<book_tool_user>'@'%';
```
## Migration
Migration is applied outside this repo (server-side DDL):
```sql
ALTER TABLE `qt_vendor_partnumber_seen`
ADD COLUMN IF NOT EXISTS `lot_suggestion` longtext DEFAULT NULL
COMMENT 'JSON [{lot_name, qty}] — user LOT suggestions from QuoteForge UI';
```
QuoteForge handles a missing column gracefully: if the migration has not run yet,
the write with `lot_suggestion` fails with "Unknown column" (MariaDB 1054), a warning
is logged, and the row is re-inserted without the column. The app never crashes on
migration lag.
+2
View File
@@ -15,6 +15,8 @@ Project-specific architecture and operational contracts.
| [07-dev.md](07-dev.md) | Development commands and guardrails |
| [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.
+214
View File
@@ -0,0 +1,214 @@
# Server contract: qt_settings
## Purpose
`qt_settings` is a general-purpose key→JSON-value table that the price management
application uses to push configuration into QuoteForge clients. QF reads it during
component sync and caches the result in `local_qt_settings` (SQLite).
## Required MariaDB changes (implemented by server-side agent)
```sql
CREATE TABLE IF NOT EXISTS qt_settings (
name VARCHAR(100) NOT NULL PRIMARY KEY,
value TEXT NOT NULL -- JSON-encoded value
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
GRANT SELECT ON RFQ_LOG.qt_settings TO 'qfs_user'@'%';
```
## Settings consumed by QuoteForge
All values are JSON. Missing or unparseable entries are silently skipped; QF
falls back to hardcoded defaults for each missing key.
---
### `config_types`
Defines the available device configuration types, their localized names, and the
category codes that are allowed for each type. QF uses this for:
- the new-config modal (button list + labels);
- the configurator's category filter per `config_type`.
**Value format:** JSON array of objects.
```json
[
{
"code": "server",
"name_ru": "Сервер",
"display_order": 10,
"categories": [
"MB","CPU","MEM","RAID",
"SSD","HDD","M2","EDSFF","HHHL",
"GPU","NIC","HCA","DPU","HBA",
"PSU","PS","ACC","RISERS","CARD","BB"
]
},
{
"code": "storage",
"name_ru": "СХД",
"display_order": 20,
"categories": [
"DKC","CPU","MEM","PS",
"SSD","HDD","M2","EDSFF","HHHL",
"NIC","HBA","HCA","ACC","CARD"
]
}
]
```
Fields:
| Field | Type | Description |
|-------|------|-------------|
| `code` | string | Identifier stored on `qt_configurations.config_type`. Must be stable. |
| `name_ru` | string | Display name in Russian for the QF UI. |
| `display_order` | int | Sort order for the modal button list. |
| `categories` | string[] | Allowlist of LOT category codes visible in this config type. A category absent from ALL entries is visible in all types. |
---
### `tab_config`
Defines the configurator tab layout: which tabs exist, which categories each tab
contains, optional sub-sections within a tab, and whether the tab uses
single-select mode.
**Value format:** JSON array of tab objects (ordered — defines tab bar order).
```json
[
{
"key": "base",
"label": "Base",
"single_select": true,
"categories": ["MB","CPU","MEM","ENC","DKC","CTL"],
"sections": null
},
{
"key": "storage",
"label": "Storage",
"single_select": false,
"categories": ["RAID","M2","SSD","HDD","EDSFF","HHHL"],
"sections": [
{ "title": "RAID Контроллеры", "categories": ["RAID"] },
{ "title": "Диски", "categories": ["M2","SSD","HDD","EDSFF","HHHL"] }
]
},
{
"key": "pci",
"label": "PCI",
"single_select": false,
"categories": ["GPU","DPU","NIC","HCA","HBA","HIC"],
"sections": [
{ "title": "GPU / DPU", "categories": ["GPU","DPU"] },
{ "title": "NIC / HCA", "categories": ["NIC","HCA"] },
{ "title": "HBA", "categories": ["HBA"] },
{ "title": "HIC", "categories": ["HIC"] }
]
},
{ "key": "power", "label": "Power", "single_select": false, "categories": ["PS","PSU"] },
{ "key": "accessories", "label": "Accessories", "single_select": false, "categories": ["ACC","CARD"] },
{ "key": "sw", "label": "SW", "single_select": false, "categories": ["SW"] }
]
```
The QF frontend always appends an "other" tab for any categories not listed here.
---
### `always_visible_tabs`
Tab keys that are always shown in the configurator regardless of whether they
contain any items. Other tabs are hidden when empty.
**Value format:** JSON string array.
```json
["base", "storage", "pci"]
```
---
### `required_categories`
Category codes that must have at least one LOT selected for a configuration to
be considered complete. Keyed by `config_type` code. QF uses this to show a
badge on the tab label when required categories are missing.
**Value format:** JSON object mapping config_type code → string array.
```json
{
"server": ["CPU", "MEM", "BB"],
"storage": ["DKC", "CPU", "MEM"]
}
```
---
### `support_pricing`
Price data from "Регламент расчёта стоимости технической поддержки серверов", used by the
Base tab's support-level picker to display a computed price next to the chosen support code.
This is reference/quoting data only — QF never adds it as a cart line or configuration cost;
see [02-architecture.md](02-architecture.md#support-pricing-reference-not-a-cart-item).
x86 is a percent of sale price (QF approximates sale price as the configuration's Estimate
total). HGX platforms (any GPU category component present, classified by chip generation via
lot_name substring) use a fixed multi-year price instead. Both are keyed `level -> duration in
years (as a JSON string key) -> value`; a combination absent from the table is not offered by
the regulation and the picker won't show it.
**Value format:**
```json
{
"x86_percent": {
"W": {"3": 0.06},
"B": {"1": 0.05, "3": 0.10, "5": 0.14},
"S": {"1": 0.07, "3": 0.13, "5": 0.18},
"P": {"1": 0.12, "3": 0.20, "5": 0.45}
},
"hgx_price": {
"HGX-H200": {
"B": {"1": 20000, "3": 55000, "5": 80000},
"S": {"1": 28000, "3": 70000, "5": 100000},
"P": {"1": 63000, "3": 105000}
},
"HGX-B200": {
"B": {"1": 40000, "3": 100000, "5": 145000},
"S": {"1": 55000, "3": 130000, "5": 185000},
"P": {"1": 101000, "3": 176000}
},
"HGX-B300": {
"B": {"1": 40000, "3": 100000, "5": 145000},
"S": {"1": 55000, "3": 130000, "5": 185000},
"P": {"1": 112000, "3": 187000}
}
}
}
```
Editing this setting in MariaDB (no QF release needed) changes the price shown by the picker
immediately on the next component sync — this is the intended way to keep support pricing
current as the regulation evolves.
---
## Backward compatibility
- If `qt_settings` does not exist (old server): QF logs `Warn` during sync and
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.
- Old QF clients that do not know about `local_qt_settings` continue to use their
hardcoded JS constants unchanged.
## Note on `qt_categories`
`qt_categories.name` and `qt_categories.name_ru` are being removed.
QF runtime does not depend on them — `GetCategories` derives `Name` from the
category code string stored in `local_components`.
+192 -100
View File
@@ -168,6 +168,13 @@ func main() {
// Create connection manager. Runtime stays local-first; MariaDB is used on demand by sync/setup only.
connMgr := db.NewConnectionManager(local)
// Keep the online-status cache fresh in the background so request-handling
// goroutines (health checks, middleware, etc.) never block on the MySQL
// dial/read timeout themselves.
connMgrCtx, connMgrCancel := context.WithCancel(context.Background())
defer connMgrCancel()
connMgr.Start(connMgrCtx)
dbUser := local.GetDBUser()
slog.Info("starting QuoteForge server",
@@ -272,6 +279,8 @@ func main() {
syncWorker.Stop()
workerCancel()
backupCancel()
connMgr.Stop()
connMgrCancel()
// Then shutdown HTTP server
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -677,8 +686,7 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
var projectService *services.ProjectService
syncService = sync.NewService(connMgr, local)
componentService := services.NewComponentService(nil, nil)
quoteService := services.NewQuoteService(nil, nil, local, nil)
quoteService := services.NewQuoteService(nil, local)
exportService := services.NewExportService(cfg.Export, local)
// isOnline function for local-first architecture
@@ -689,6 +697,7 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
// Local-first configuration service (replaces old ConfigurationService)
projectService = services.NewProjectService(local)
configService := services.NewLocalConfigurationService(local, syncService, quoteService, isOnline)
rentalService := services.NewRentalService(local)
// Data hygiene: remove empty nameless projects and ensure every configuration is attached to a project.
if removed, err := local.ConsolidateSystemProjects(); err == nil && removed > 0 {
@@ -775,11 +784,11 @@ 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)
vendorSpecHandler := handlers.NewVendorSpecHandler(local)
vendorSpecHandler := handlers.NewVendorSpecHandler(local, syncService)
partnumberBooksHandler := handlers.NewPartnumberBooksHandler(local)
respondError := handlers.RespondError
syncHandler, err := handlers.NewSyncHandler(local, syncService, connMgr, templatesPath, backgroundSyncInterval)
@@ -894,6 +903,27 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
router.GET("/pricelists/:id", webHandler.PricelistDetail)
router.GET("/partnumber-books", webHandler.PartnumberBooks)
// Short project URLs: /:code → main variant, /:code/:variant → named variant
router.GET("/:code", func(c *gin.Context) {
code := c.Param("code")
project, err := projectService.GetByCode(code)
if err != nil {
c.Redirect(http.StatusFound, "/projects")
return
}
c.Redirect(http.StatusFound, "/projects/"+project.UUID)
})
router.GET("/:code/:variant", func(c *gin.Context) {
code := c.Param("code")
variant := c.Param("variant")
project, err := projectService.GetByCodeAndVariant(code, variant)
if err != nil {
c.Redirect(http.StatusFound, "/projects")
return
}
c.Redirect(http.StatusFound, "/projects/"+project.UUID)
})
// htmx partials
partials := router.Group("/partials")
{
@@ -919,6 +949,7 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
// Categories (public)
api.GET("/categories", componentHandler.GetCategories)
api.GET("/configurator-settings", componentHandler.GetConfiguratorSettings)
// Quote (public)
quote := api.Group("/quote")
@@ -975,8 +1006,27 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
return
}
uuids := make([]string, len(cfgs))
for i, cfg := range cfgs {
uuids[i] = cfg.UUID
}
viewers, _ := syncService.ListActiveViewersByConfigUUIDs(uuids)
type cfgRow struct {
models.Configuration
Viewers []string `json:"viewers"`
}
rows := make([]cfgRow, len(cfgs))
for i, cfg := range cfgs {
v := viewers[cfg.UUID]
if v == nil {
v = []string{}
}
rows[i] = cfgRow{Configuration: cfg, Viewers: v}
}
c.JSON(http.StatusOK, gin.H{
"configurations": cfgs,
"configurations": rows,
"total": total,
"page": page,
"per_page": perPage,
@@ -1051,16 +1101,11 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
config, err := configService.UpdateNoAuth(uuid, &req)
if err != nil {
switch {
case errors.Is(err, services.ErrConfigNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
@@ -1147,6 +1192,15 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
c.JSON(http.StatusOK, config)
})
configs.POST("/:uuid/snapshot", func(c *gin.Context) {
uuid := c.Param("uuid")
if err := configService.SnapshotCurrentState(uuid); err != nil {
respondError(c, http.StatusInternalServerError, "internal server error", err)
return
}
c.JSON(http.StatusOK, gin.H{"ok": true})
})
configs.PATCH("/:uuid/project", func(c *gin.Context) {
uuid := c.Param("uuid")
var req struct {
@@ -1158,16 +1212,11 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
}
updated, err := configService.SetProjectNoAuth(uuid, req.ProjectUUID)
if err != nil {
switch {
case errors.Is(err, services.ErrConfigNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, updated)
@@ -1286,6 +1335,39 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
configs.POST("/:uuid/vendor-spec/resolve", vendorSpecHandler.ResolveVendorSpec)
configs.POST("/:uuid/vendor-spec/apply", vendorSpecHandler.ApplyVendorSpec)
// Rental / paid-testing pricing endpoints (Аренда tab)
configs.PUT("/:uuid/rental", func(c *gin.Context) {
var req services.RentalUpdateRequest
if err := c.ShouldBindJSON(&req); err != nil {
respondError(c, http.StatusBadRequest, "invalid request", err)
return
}
config, err := configService.UpdateRentalNoAuth(c.Param("uuid"), &req)
if err != nil {
respondByErrCase(c, err,
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
)
return
}
c.JSON(http.StatusOK, config)
})
configs.POST("/:uuid/rental/calculate", func(c *gin.Context) {
var req services.RentalUpdateRequest
if err := c.ShouldBindJSON(&req); err != nil {
respondError(c, http.StatusBadRequest, "invalid request", err)
return
}
result, err := rentalService.Calculate(c.Param("uuid"), &req)
if err != nil {
respondByErrCase(c, err,
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
)
return
}
c.JSON(http.StatusOK, result)
})
configs.PATCH("/:uuid/server-count", func(c *gin.Context) {
uuid := c.Param("uuid")
var req struct {
@@ -1302,6 +1384,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")
@@ -1482,21 +1574,25 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
// Return simplified list of all projects (UUID + Name only)
type ProjectSimple struct {
UUID string `json:"uuid"`
Code string `json:"code"`
Variant string `json:"variant"`
Name string `json:"name"`
IsActive bool `json:"is_active"`
UUID string `json:"uuid"`
Code string `json:"code"`
Variant string `json:"variant"`
Name string `json:"name"`
IsActive bool `json:"is_active"`
RentalEnabled bool `json:"rental_enabled"`
CreatedAt time.Time `json:"created_at"`
}
simplified := make([]ProjectSimple, 0, len(allProjects))
for _, p := range allProjects {
simplified = append(simplified, ProjectSimple{
UUID: p.UUID,
Code: p.Code,
Variant: p.Variant,
Name: derefString(p.Name),
IsActive: p.IsActive,
UUID: p.UUID,
Code: p.Code,
Variant: p.Variant,
Name: derefString(p.Name),
IsActive: p.IsActive,
RentalEnabled: p.RentalEnabled,
CreatedAt: p.CreatedAt,
})
}
@@ -1515,14 +1611,12 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
}
project, err := projectService.Create(dbUsername, &req)
if err != nil {
switch {
case errors.Is(err, services.ErrReservedMainVariant):
respondError(c, http.StatusBadRequest, "invalid request", err)
case errors.Is(err, services.ErrProjectCodeExists):
respondError(c, http.StatusConflict, "conflict detected", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrReservedMainVariant, http.StatusBadRequest, "invalid request"},
errCase{services.ErrProjectCodeInvalidChars, http.StatusBadRequest, "invalid request"},
errCase{services.ErrProjectVariantInvalidChars, http.StatusBadRequest, "invalid request"},
errCase{services.ErrProjectCodeExists, http.StatusConflict, "conflict detected"},
)
return
}
c.JSON(http.StatusCreated, project)
@@ -1531,14 +1625,10 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
projects.GET("/:uuid", func(c *gin.Context) {
project, err := projectService.GetByUUID(c.Param("uuid"), dbUsername)
if err != nil {
switch {
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, project)
@@ -1552,19 +1642,15 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
}
project, err := projectService.Update(c.Param("uuid"), dbUsername, &req)
if err != nil {
switch {
case errors.Is(err, services.ErrReservedMainVariant),
errors.Is(err, services.ErrCannotRenameMainVariant):
respondError(c, http.StatusBadRequest, "invalid request", err)
case errors.Is(err, services.ErrProjectCodeExists):
respondError(c, http.StatusConflict, "conflict detected", err)
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrReservedMainVariant, http.StatusBadRequest, "invalid request"},
errCase{services.ErrCannotRenameMainVariant, http.StatusBadRequest, "invalid request"},
errCase{services.ErrProjectCodeInvalidChars, http.StatusBadRequest, "invalid request"},
errCase{services.ErrProjectVariantInvalidChars, http.StatusBadRequest, "invalid request"},
errCase{services.ErrProjectCodeExists, http.StatusConflict, "conflict detected"},
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, project)
@@ -1572,14 +1658,10 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
projects.POST("/:uuid/archive", func(c *gin.Context) {
if err := projectService.Archive(c.Param("uuid"), dbUsername); err != nil {
switch {
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, gin.H{"message": "project archived"})
@@ -1587,14 +1669,10 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
projects.POST("/:uuid/reactivate", func(c *gin.Context) {
if err := projectService.Reactivate(c.Param("uuid"), dbUsername); err != nil {
switch {
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, gin.H{"message": "project reactivated"})
@@ -1602,16 +1680,11 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
projects.DELETE("/:uuid", func(c *gin.Context) {
if err := projectService.DeleteVariant(c.Param("uuid"), dbUsername); err != nil {
switch {
case errors.Is(err, services.ErrCannotDeleteMainVariant):
respondError(c, http.StatusBadRequest, "invalid request", err)
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrCannotDeleteMainVariant, http.StatusBadRequest, "invalid request"},
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, gin.H{"message": "variant deleted"})
@@ -1628,18 +1701,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) {
@@ -1776,7 +1869,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)
+31
View File
@@ -0,0 +1,31 @@
package main
import (
"errors"
"net/http"
"git.mchus.pro/mchus/quoteforge/internal/handlers"
"github.com/gin-gonic/gin"
)
// errCase maps a sentinel error to the HTTP status/message respondByErrCase
// should use when errors.Is matches it.
type errCase struct {
err error
status int
message string
}
// respondByErrCase responds with the status/message of the first matching
// case (checked in order), or a 500 "internal server error" fallback when
// none match. Centralizes the switch-on-sentinel-error pattern repeated
// across the config/project HTTP handlers in this file.
func respondByErrCase(c *gin.Context, err error, cases ...errCase) {
for _, cs := range cases {
if errors.Is(err, cs.err) {
handlers.RespondError(c, cs.status, cs.message, err)
return
}
}
handlers.RespondError(c, http.StatusInternalServerError, "internal server error", err)
}
+9 -16
View File
@@ -21,30 +21,23 @@ const (
// ResolveDBPath returns the local SQLite path using priority:
// explicit CLI path > QFS_DB_PATH > OS-specific user state directory.
func ResolveDBPath(explicitPath string) (string, error) {
if explicitPath != "" {
return filepath.Clean(explicitPath), nil
}
if fromEnv := os.Getenv(envDBPath); fromEnv != "" {
return filepath.Clean(fromEnv), nil
}
dir, err := defaultStateDir()
if err != nil {
return "", err
}
return filepath.Join(dir, defaultDB), nil
return resolvePath(explicitPath, envDBPath, defaultDB)
}
// ResolveConfigPath returns the config path using priority:
// explicit CLI path > QFS_CONFIG_PATH > OS-specific user state directory.
func ResolveConfigPath(explicitPath string) (string, error) {
return resolvePath(explicitPath, envCfgPath, defaultCfg)
}
// resolvePath returns a path using priority: explicit CLI path > envVar > OS-specific
// user state directory joined with defaultFilename.
func resolvePath(explicitPath, envVar, defaultFilename string) (string, error) {
if explicitPath != "" {
return filepath.Clean(explicitPath), nil
}
if fromEnv := os.Getenv(envCfgPath); fromEnv != "" {
if fromEnv := os.Getenv(envVar); fromEnv != "" {
return filepath.Clean(fromEnv), nil
}
@@ -53,7 +46,7 @@ func ResolveConfigPath(explicitPath string) (string, error) {
return "", err
}
return filepath.Join(dir, defaultCfg), nil
return filepath.Join(dir, defaultFilename), nil
}
// ResolveConfigPathNearDB returns config path using priority:
+6 -46
View File
@@ -1,31 +1,12 @@
package article
import (
"errors"
"fmt"
"strings"
"git.mchus.pro/mchus/quoteforge/internal/localdb"
)
// ErrMissingCategoryForLot is returned when a lot has no category in local_pricelist_items.lot_category.
var ErrMissingCategoryForLot = errors.New("missing_category_for_lot")
type MissingCategoryForLotError struct {
LotName string
}
func (e *MissingCategoryForLotError) Error() string {
if e == nil || strings.TrimSpace(e.LotName) == "" {
return ErrMissingCategoryForLot.Error()
}
return fmt.Sprintf("%s: %s", ErrMissingCategoryForLot.Error(), e.LotName)
}
func (e *MissingCategoryForLotError) Unwrap() error {
return ErrMissingCategoryForLot
}
type Group string
const (
@@ -61,9 +42,10 @@ func GroupForLotCategory(cat string) (group Group, ok bool) {
}
}
// ResolveLotCategoriesStrict resolves categories for lotNames using local_pricelist_items.lot_category
// for a given server pricelist id. If any lot is missing or has empty category, returns an error.
func ResolveLotCategoriesStrict(local *localdb.LocalDB, serverPricelistID uint, lotNames []string) (map[string]string, error) {
// ResolveLotCategories returns lot_category for each lotName found in local_pricelist_items
// for the given server pricelist. Lots not found in the pricelist are omitted from the result —
// callers must treat a missing key as "no category" and skip that lot.
func ResolveLotCategories(local *localdb.LocalDB, serverPricelistID uint, lotNames []string) (map[string]string, error) {
if local == nil {
return nil, fmt.Errorf("local db is nil")
}
@@ -71,30 +53,8 @@ func ResolveLotCategoriesStrict(local *localdb.LocalDB, serverPricelistID uint,
if err != nil {
return nil, err
}
missing := make([]string, 0)
for _, lot := range lotNames {
cat := strings.TrimSpace(cats[lot])
if cat == "" {
missing = append(missing, lot)
continue
}
cats[lot] = cat
}
if len(missing) > 0 {
fallback, err := local.GetLocalComponentCategoriesByLotNames(missing)
if err != nil {
return nil, err
}
for _, lot := range missing {
if cat := strings.TrimSpace(fallback[lot]); cat != "" {
cats[lot] = cat
}
}
for _, lot := range missing {
if strings.TrimSpace(cats[lot]) == "" {
return nil, &MissingCategoryForLotError{LotName: lot}
}
}
for lot, cat := range cats {
cats[lot] = strings.TrimSpace(cat)
}
return cats, nil
}
+27 -24
View File
@@ -1,7 +1,6 @@
package article
import (
"errors"
"path/filepath"
"testing"
"time"
@@ -9,7 +8,7 @@ import (
"git.mchus.pro/mchus/quoteforge/internal/localdb"
)
func TestResolveLotCategoriesStrict_MissingCategoryReturnsError(t *testing.T) {
func TestResolveLotCategories_MissingLotOmitted(t *testing.T) {
local, err := localdb.New(filepath.Join(t.TempDir(), "local.db"))
if err != nil {
t.Fatalf("init local db: %v", err)
@@ -36,16 +35,19 @@ func TestResolveLotCategoriesStrict_MissingCategoryReturnsError(t *testing.T) {
t.Fatalf("save local items: %v", err)
}
_, err = ResolveLotCategoriesStrict(local, 1, []string{"CPU_A"})
if err == nil {
t.Fatalf("expected error")
cats, err := ResolveLotCategories(local, 1, []string{"CPU_A", "UNKNOWN"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !errors.Is(err, ErrMissingCategoryForLot) {
t.Fatalf("expected ErrMissingCategoryForLot, got %v", err)
if cats["CPU_A"] != "" {
t.Fatalf("expected empty category for lot with blank lot_category, got %q", cats["CPU_A"])
}
if _, ok := cats["UNKNOWN"]; ok {
t.Fatalf("expected UNKNOWN lot to be omitted from result")
}
}
func TestResolveLotCategoriesStrict_FallbackToLocalComponents(t *testing.T) {
func TestResolveLotCategories_ReturnsKnownCategories(t *testing.T) {
local, err := localdb.New(filepath.Join(t.TempDir(), "local.db"))
if err != nil {
t.Fatalf("init local db: %v", err)
@@ -53,39 +55,40 @@ func TestResolveLotCategoriesStrict_FallbackToLocalComponents(t *testing.T) {
t.Cleanup(func() { _ = local.Close() })
if err := local.SaveLocalPricelist(&localdb.LocalPricelist{
ServerID: 2,
ServerID: 1,
Source: "estimate",
Version: "S-2026-02-11-002",
Version: "S-2026-02-11-001",
Name: "test",
IsActive: true,
CreatedAt: time.Now(),
SyncedAt: time.Now(),
}); err != nil {
t.Fatalf("save local pricelist: %v", err)
t.Fatalf("save pricelist: %v", err)
}
localPL, err := local.GetLocalPricelistByServerID(2)
pl, err := local.GetLocalPricelistByServerID(1)
if err != nil {
t.Fatalf("get local pricelist: %v", err)
t.Fatalf("get pricelist: %v", err)
}
if err := local.SaveLocalPricelistItems([]localdb.LocalPricelistItem{
{PricelistID: localPL.ID, LotName: "CPU_B", LotCategory: "", Price: 10},
{PricelistID: pl.ID, LotName: "CPU_B", LotCategory: "CPU", Price: 10},
{PricelistID: pl.ID, LotName: "MB_X", LotCategory: "MB", Price: 5},
}); err != nil {
t.Fatalf("save local items: %v", err)
}
if err := local.DB().Create(&localdb.LocalComponent{
LotName: "CPU_B",
Category: "CPU",
LotDescription: "cpu",
}).Error; err != nil {
t.Fatalf("save local components: %v", err)
t.Fatalf("save items: %v", err)
}
cats, err := ResolveLotCategoriesStrict(local, 2, []string{"CPU_B"})
cats, err := ResolveLotCategories(local, 1, []string{"CPU_B", "MB_X", "NOT_IN_PL"})
if err != nil {
t.Fatalf("expected fallback, got error: %v", err)
t.Fatalf("unexpected error: %v", err)
}
if cats["CPU_B"] != "CPU" {
t.Fatalf("expected CPU, got %q", cats["CPU_B"])
}
if cats["MB_X"] != "MB" {
t.Fatalf("expected MB, got %q", cats["MB_X"])
}
if _, ok := cats["NOT_IN_PL"]; ok {
t.Fatalf("expected NOT_IN_PL to be omitted")
}
}
func TestGroupForLotCategory(t *testing.T) {
+33 -59
View File
@@ -12,7 +12,6 @@ import (
type BuildOptions struct {
ServerModel string
SupportCode string
ServerPricelist *uint
}
@@ -55,7 +54,7 @@ func Build(local *localdb.LocalDB, items []models.ConfigItem, opts BuildOptions)
return BuildResult{}, fmt.Errorf("pricelist_id required for article")
}
cats, err := ResolveLotCategoriesStrict(local, *opts.ServerPricelist, lotNames)
cats, err := ResolveLotCategories(local, *opts.ServerPricelist, lotNames)
if err != nil {
return BuildResult{}, err
}
@@ -95,12 +94,8 @@ func Build(local *localdb.LocalDB, items []models.ConfigItem, opts BuildOptions)
segs = append(segs, namedSeg{"PSU", psuSeg})
}
if strings.TrimSpace(opts.SupportCode) != "" {
code := strings.TrimSpace(opts.SupportCode)
if !isSupportCodeValid(code) {
return BuildResult{}, fmt.Errorf("invalid_support_code")
}
segs = append(segs, namedSeg{"SUPPORT", code})
if supportSeg := buildSupportSegment(items); supportSeg != "" {
segs = append(segs, namedSeg{"SUPPORT", supportSeg})
}
article := strings.Join(namedSegsValues(segs), "-")
@@ -132,28 +127,22 @@ func findSegGroup(segs []namedSeg, group string) int {
return -1
}
func isSupportCodeValid(code string) bool {
if len(code) < 3 {
return false
}
if !strings.Contains(code, "y") {
return false
}
parts := strings.Split(code, "y")
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return false
}
for _, r := range parts[0] {
if r < '0' || r > '9' {
return false
// buildSupportSegment finds a support LOT in items (added to the spec via the
// Base tab's support picker, e.g. "SVC_3yB_HGX-H200") and returns its
// duration+level token ("3yB") for the article. Support is a regular BOM
// LOT, not pricelist-backed, so it's detected by lot_name prefix like the
// other lot_name-pattern parsers in this file, rather than by lot_category.
func buildSupportSegment(items []models.ConfigItem) string {
for _, it := range items {
if !strings.HasPrefix(strings.ToUpper(it.LotName), "SVC_") {
continue
}
parts := strings.SplitN(it.LotName, "_", 3)
if len(parts) >= 2 && parts[1] != "" {
return parts[1]
}
}
switch parts[1] {
case "W", "B", "S", "P":
return true
default:
return false
}
return ""
}
func buildCPUSegment(items []models.ConfigItem, cats map[string]string) string {
@@ -271,17 +260,28 @@ func buildDiskSegment(items []models.ConfigItem, cats map[string]string) (string
}
func buildNetSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
return buildProfileSegment(items, cats, GroupNET, parsePortSpeed, "UNKNET", "net_unknown")
}
func buildPSUSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
return buildProfileSegment(items, cats, GroupPSU, parseWatts, "UNKPSU", "psu_unknown")
}
// buildProfileSegment groups items of the given category group by a profile token
// parsed from their lot name (e.g. port speed, wattage rating), falling back to
// unknownToken and warnCode when a lot's profile can't be determined.
func buildProfileSegment(items []models.ConfigItem, cats map[string]string, group Group, parseProfile func(string) string, unknownToken, warnCode string) (string, string) {
groupQty := map[string]int{}
warn := ""
for _, it := range items {
group, ok := GroupForLotCategory(cats[it.LotName])
if !ok || group != GroupNET {
g, ok := GroupForLotCategory(cats[it.LotName])
if !ok || g != group {
continue
}
profile := parsePortSpeed(it.LotName)
profile := parseProfile(it.LotName)
if profile == "" {
profile = "UNKNET"
warn = "net_unknown"
profile = unknownToken
warn = warnCode
}
groupQty[profile] += it.Quantity
}
@@ -296,32 +296,6 @@ func buildNetSegment(items []models.ConfigItem, cats map[string]string) (string,
return strings.Join(parts, "+"), warn
}
func buildPSUSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
groupQty := map[string]int{}
warn := ""
for _, it := range items {
group, ok := GroupForLotCategory(cats[it.LotName])
if !ok || group != GroupPSU {
continue
}
rating := parseWatts(it.LotName)
if rating == "" {
rating = "UNKPSU"
warn = "psu_unknown"
}
groupQty[rating] += it.Quantity
}
if len(groupQty) == 0 {
return "", ""
}
parts := make([]string, 0, len(groupQty))
for rating, qty := range groupQty {
parts = append(parts, fmt.Sprintf("%dx%s", qty, rating))
}
sort.Strings(parts)
return strings.Join(parts, "+"), warn
}
func normalizeModelToken(lotName string) string {
if idx := strings.Index(lotName, "_"); idx >= 0 && idx+1 < len(lotName) {
lotName = lotName[idx+1:]
+4 -1
View File
@@ -44,10 +44,10 @@ func TestBuild_ParsesNetAndPSU(t *testing.T) {
{LotName: "NIC_2p25G_MCX512A-AC", Quantity: 1},
{LotName: "HBA_2pFC32_Gen6", Quantity: 1},
{LotName: "PS_1000W_Platinum", Quantity: 2},
{LotName: "SVC_1yW_x86", Quantity: 1},
}
result, err := Build(local, items, BuildOptions{
ServerModel: "DL380GEN11",
SupportCode: "1yW",
ServerPricelist: &localPL.ServerID,
})
if err != nil {
@@ -59,6 +59,9 @@ func TestBuild_ParsesNetAndPSU(t *testing.T) {
if contains(result.Article, "UNKNET") || contains(result.Article, "UNKPSU") {
t.Fatalf("unexpected UNK in article: %s", result.Article)
}
if !contains(result.Article, "1yW") {
t.Fatalf("expected support segment 1yW in article: %s", result.Article)
}
}
// TestBuild_CompressArticle_NoGPU_PSUNotNIC reproduces the bug where 2 PSUs produced
+162 -77
View File
@@ -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
}
+143 -16
View File
@@ -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,
})
}
@@ -125,3 +117,138 @@ func (h *ComponentHandler) GetCategories(c *gin.Context) {
c.JSON(http.StatusOK, models.DefaultCategories)
}
func (h *ComponentHandler) GetConfiguratorSettings(c *gin.Context) {
s, _ := h.localDB.GetConfiguratorSettings()
if s == nil {
s = &localdb.ConfiguratorSettings{}
}
if len(s.ConfigTypes) == 0 {
s.ConfigTypes = defaultConfigTypes()
}
if len(s.TabConfig) == 0 {
s.TabConfig = defaultTabConfig()
}
if len(s.AlwaysVisibleTabs) == 0 {
s.AlwaysVisibleTabs = []string{"base", "storage", "pci"}
}
if len(s.RequiredCategories) == 0 {
s.RequiredCategories = map[string][]string{"server": {"CPU", "MEM", "BB"}}
}
if s.SupportPricing == nil {
s.SupportPricing = defaultSupportPricing()
}
c.JSON(http.StatusOK, s)
}
// defaultSupportPricing mirrors "Регламент расчёта стоимости технической
// поддержки серверов" (BASE/STANDARD/PREMIUM tiers, x86 % of sale price /
// HGX fixed multi-year price by chip generation). Used only when the
// qt_settings "support_pricing" key is absent so it can be edited in
// MariaDB without a QuoteForge release.
func defaultSupportPricing() *localdb.SupportPricingTable {
return &localdb.SupportPricingTable{
X86Percent: map[string]map[string]float64{
"W": {"3": 0.06},
"B": {"1": 0.05, "3": 0.10, "5": 0.14},
"S": {"1": 0.07, "3": 0.13, "5": 0.18},
"P": {"1": 0.12, "3": 0.20, "5": 0.45},
},
HGXPrice: map[string]map[string]map[string]float64{
"HGX-H200": {
"B": {"1": 20000, "3": 55000, "5": 80000},
"S": {"1": 28000, "3": 70000, "5": 100000},
"P": {"1": 63000, "3": 105000},
},
"HGX-B200": {
"B": {"1": 40000, "3": 100000, "5": 145000},
"S": {"1": 55000, "3": 130000, "5": 185000},
"P": {"1": 101000, "3": 176000},
},
"HGX-B300": {
"B": {"1": 40000, "3": 100000, "5": 145000},
"S": {"1": 55000, "3": 130000, "5": 185000},
"P": {"1": 112000, "3": 187000},
},
},
}
}
func defaultConfigTypes() []localdb.ConfigTypeDef {
return []localdb.ConfigTypeDef{
{
Code: "server",
NameRu: "Сервер",
DisplayOrder: 10,
Categories: []string{
"MB", "CPU", "MEM", "RAID",
"SSD", "HDD", "M2", "EDSFF", "HHHL",
"GPU", "NIC", "HCA", "DPU", "HBA",
"PSU", "PS", "ACC", "RISERS", "CARD", "BB",
},
},
{
Code: "storage",
NameRu: "СХД",
DisplayOrder: 20,
Categories: []string{
"DKC", "CPU", "MEM", "PS",
"SSD", "HDD", "M2", "EDSFF", "HHHL",
"NIC", "HBA", "HCA", "ACC", "CARD",
},
},
}
}
func defaultTabConfig() []localdb.TabDef {
return []localdb.TabDef{
{
Key: "base",
Label: "Base",
SingleSelect: true,
Categories: []string{"MB", "CPU", "MEM", "ENC", "DKC", "CTL"},
},
{
Key: "storage",
Label: "Storage",
SingleSelect: false,
Categories: []string{"RAID", "M2", "SSD", "HDD", "EDSFF", "HHHL"},
Sections: []localdb.TabSection{
{Title: "RAID Контроллеры", Categories: []string{"RAID"}},
{Title: "Диски", Categories: []string{"M2", "SSD", "HDD", "EDSFF", "HHHL"}},
},
},
{
Key: "pci",
Label: "PCI",
SingleSelect: false,
Categories: []string{"GPU", "DPU", "NIC", "HCA", "HBA", "HIC"},
Sections: []localdb.TabSection{
{Title: "GPU / DPU", Categories: []string{"GPU", "DPU"}},
{Title: "NIC / HCA", Categories: []string{"NIC", "HCA"}},
{Title: "HBA", Categories: []string{"HBA"}},
{Title: "HIC", Categories: []string{"HIC"}},
},
},
{
Key: "power",
Label: "Power",
SingleSelect: false,
Categories: []string{"PS", "PSU"},
},
{
Key: "accessories",
Label: "Accessories",
SingleSelect: false,
Categories: []string{"ACC", "CARD"},
},
{
Key: "sw",
Label: "SW",
SingleSelect: false,
Categories: []string{"SW"},
},
}
}
+6 -20
View File
@@ -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,
})
}
+9 -12
View File
@@ -16,13 +16,12 @@ func NewQuoteHandler(quoteService *services.QuoteService) *QuoteHandler {
}
func (h *QuoteHandler) Validate(c *gin.Context) {
var req services.QuoteRequest
if err := c.ShouldBindJSON(&req); err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
req, ok := BindJSON[services.QuoteRequest](c)
if !ok {
return
}
result, err := h.quoteService.ValidateAndCalculate(&req)
result, err := h.quoteService.ValidateAndCalculate(req)
if err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
return
@@ -32,13 +31,12 @@ func (h *QuoteHandler) Validate(c *gin.Context) {
}
func (h *QuoteHandler) Calculate(c *gin.Context) {
var req services.QuoteRequest
if err := c.ShouldBindJSON(&req); err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
req, ok := BindJSON[services.QuoteRequest](c)
if !ok {
return
}
result, err := h.quoteService.ValidateAndCalculate(&req)
result, err := h.quoteService.ValidateAndCalculate(req)
if err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
return
@@ -51,13 +49,12 @@ func (h *QuoteHandler) Calculate(c *gin.Context) {
}
func (h *QuoteHandler) PriceLevels(c *gin.Context) {
var req services.PriceLevelsRequest
if err := c.ShouldBindJSON(&req); err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
req, ok := BindJSON[services.PriceLevelsRequest](c)
if !ok {
return
}
result, err := h.quoteService.CalculatePriceLevels(&req)
result, err := h.quoteService.CalculatePriceLevels(req)
if err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
return
+12
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"github.com/gin-gonic/gin"
@@ -16,6 +17,17 @@ func RespondError(c *gin.Context, status int, fallback string, err error) {
c.JSON(status, gin.H{"error": clientFacingErrorMessage(status, fallback, err)})
}
// BindJSON decodes the request body into T, responding with a 422 and writing
// the error via RespondError on failure. The second return value reports success.
func BindJSON[T any](c *gin.Context) (*T, bool) {
var req T
if err := c.ShouldBindJSON(&req); err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
return nil, false
}
return &req, true
}
func clientFacingErrorMessage(status int, fallback string, err error) string {
if err == nil {
return fallback
+106 -1
View File
@@ -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 {
+14 -87
View File
@@ -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,48 +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())
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) {
@@ -232,6 +184,10 @@ func (h *SyncHandler) SyncPricelists(c *gin.Context) {
}
h.localDB.AppendSyncLog("pricelists", "ok", "", synced, startTime, time.Since(startTime).Milliseconds())
if _, err := h.syncService.PullPartnumberBooks(); err != nil {
slog.Warn("partnumber books pull failed after pricelist sync", "error", err)
}
c.JSON(http.StatusOK, SyncResultResponse{
Success: true,
Message: "Pricelists synced successfully",
@@ -272,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 +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()
@@ -307,34 +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
// Sync pricelists
plNow := time.Now()
pricelistsSynced, err = h.syncService.SyncPricelists()
@@ -342,16 +269,19 @@ 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
}
h.localDB.AppendSyncLog("pricelists", "ok", "", pricelistsSynced, plNow, time.Since(plNow).Milliseconds())
if _, err := h.syncService.PullPartnumberBooks(); err != nil {
slog.Warn("partnumber books pull failed during full sync", "error", err)
}
projectsResult, err := h.syncService.ImportProjectsToLocal()
if err != nil {
slog.Error("project import failed during full sync", "error", err)
@@ -359,7 +289,6 @@ func (h *SyncHandler) SyncAll(c *gin.Context) {
"success": false,
"error": "project import failed",
"pending_pushed": pendingPushed,
"components_synced": componentsSynced,
"pricelists_synced": pricelistsSynced,
})
_ = c.Error(err)
@@ -373,7 +302,6 @@ func (h *SyncHandler) SyncAll(c *gin.Context) {
"success": false,
"error": "configuration import failed",
"pending_pushed": pendingPushed,
"components_synced": componentsSynced,
"pricelists_synced": pricelistsSynced,
"projects_imported": projectsResult.Imported,
"projects_updated": projectsResult.Updated,
@@ -387,7 +315,6 @@ func (h *SyncHandler) SyncAll(c *gin.Context) {
Success: true,
Message: "Full sync completed successfully",
PendingPushed: pendingPushed,
ComponentsSynced: componentsSynced,
PricelistsSynced: pricelistsSynced,
ProjectsImported: projectsResult.Imported,
ProjectsUpdated: projectsResult.Updated,
@@ -548,7 +475,7 @@ func (h *SyncHandler) GetInfo(c *gin.Context) {
// Get local counts
configCount := h.localDB.CountConfigurations()
projectCount := h.localDB.CountProjects()
componentCount := h.localDB.CountLocalComponents()
componentCount := h.localDB.CountComponents()
pricelistCount := h.localDB.CountLocalPricelists()
// Get error count (only changes with LastError != "")
+43 -26
View File
@@ -4,11 +4,11 @@ import (
"errors"
"log/slog"
"net/http"
"strings"
"git.mchus.pro/mchus/quoteforge/internal/localdb"
"git.mchus.pro/mchus/quoteforge/internal/repository"
"git.mchus.pro/mchus/quoteforge/internal/services"
syncsvc "git.mchus.pro/mchus/quoteforge/internal/services/sync"
"github.com/gin-gonic/gin"
)
@@ -16,12 +16,14 @@ import (
type VendorSpecHandler struct {
localDB *localdb.LocalDB
configService *services.LocalConfigurationService
syncService *syncsvc.Service // optional; nil = no server push
}
func NewVendorSpecHandler(localDB *localdb.LocalDB) *VendorSpecHandler {
func NewVendorSpecHandler(localDB *localdb.LocalDB, syncService *syncsvc.Service) *VendorSpecHandler {
return &VendorSpecHandler{
localDB: localDB,
configService: services.NewLocalConfigurationService(localDB, nil, nil, func() bool { return false }),
syncService: syncService,
}
}
@@ -97,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 = ""
@@ -111,40 +113,55 @@ func (h *VendorSpecHandler) PutVendorSpec(c *gin.Context) {
return
}
// Push manual lot mappings as suggestions to the server (best-effort, non-blocking).
h.pushLotSuggestions(body.VendorSpec)
c.JSON(http.StatusOK, gin.H{"vendor_spec": spec})
}
func normalizeLotMappings(in []localdb.VendorSpecLotMapping) []localdb.VendorSpecLotMapping {
if len(in) == 0 {
return nil
// pushLotSuggestions sends manual PN→LOT mappings to qt_vendor_partnumber_seen.lot_suggestion.
// Errors are logged and silently dropped — they must not affect the HTTP response.
func (h *VendorSpecHandler) pushLotSuggestions(spec []localdb.VendorSpecItem) {
if h.syncService == nil {
return
}
merged := make(map[string]int, len(in))
order := make([]string, 0, len(in))
for _, m := range in {
lot := strings.TrimSpace(m.LotName)
if lot == "" {
var items []syncsvc.SeenPartnumber
for _, row := range spec {
if row.VendorPartnumber == "" || len(row.LotMappings) == 0 {
continue
}
qty := m.QuantityPerPN
if qty < 1 {
qty = 1
suggestion := make([]syncsvc.LotSuggestionEntry, 0, len(row.LotMappings))
for _, m := range row.LotMappings {
if m.LotName == "" {
continue
}
qty := m.QuantityPerPN
if qty < 1 {
qty = 1
}
suggestion = append(suggestion, syncsvc.LotSuggestionEntry{
LotName: m.LotName,
Qty: qty,
})
}
if _, exists := merged[lot]; !exists {
order = append(order, lot)
if len(suggestion) == 0 {
continue
}
merged[lot] += qty
}
out := make([]localdb.VendorSpecLotMapping, 0, len(order))
for _, lot := range order {
out = append(out, localdb.VendorSpecLotMapping{
LotName: lot,
QuantityPerPN: merged[lot],
items = append(items, syncsvc.SeenPartnumber{
Partnumber: row.VendorPartnumber,
Description: row.Description,
LotSuggestion: suggestion,
})
}
if len(out) == 0 {
return nil
if len(items) == 0 {
return
}
if err := h.syncService.PushPartnumberSeen(items); err != nil {
slog.Warn("vendor_spec: failed to push lot suggestions to server", "error", err)
}
return out
}
// ResolveVendorSpec resolves vendor PN → LOT without modifying the cart.
+176
View File
@@ -0,0 +1,176 @@
package localdb
import (
"path/filepath"
"testing"
"time"
)
// seedUniversePricelist stores one active pricelist of the given source with the
// supplied items and returns its local id.
func seedUniversePricelist(t *testing.T, local *LocalDB, serverID uint, source, version string, created time.Time, items []LocalPricelistItem) uint {
t.Helper()
pl := &LocalPricelist{
ServerID: serverID,
Source: source,
Version: version,
Name: version,
CreatedAt: created,
SyncedAt: created,
IsActive: true,
}
if err := local.SaveLocalPricelist(pl); err != nil {
t.Fatalf("save %s pricelist: %v", source, err)
}
stored, err := local.GetLocalPricelistByServerID(serverID)
if err != nil {
t.Fatalf("load %s pricelist: %v", source, err)
}
for i := range items {
items[i].PricelistID = stored.ID
}
if err := local.SaveLocalPricelistItems(items); err != nil {
t.Fatalf("save %s items: %v", source, err)
}
return stored.ID
}
func quality(v int) *int { return &v }
func newUniverseDB(t *testing.T, name string) *LocalDB {
t.Helper()
local, err := New(filepath.Join(t.TempDir(), name))
if err != nil {
t.Fatalf("open localdb: %v", err)
}
t.Cleanup(func() { _ = local.Close() })
return local
}
// The component universe is world ∪ estimate: a LOT the estimate pricelist does not
// carry must still be selectable, otherwise BOM lot_mappings resolved from the
// partnumber book get silently dropped on save.
func TestComponentUniverseUnionsWorldAndEstimate(t *testing.T) {
local := newUniverseDB(t, "universe_union.db")
base := time.Now().Add(-time.Minute)
seedUniversePricelist(t, local, 1, "estimate", "E-1", base, []LocalPricelistItem{
{LotName: "CPU_A", LotCategory: "CPU", LotDescription: "from estimate", Price: 100, PriceQuality: quality(8)},
{LotName: "SHARED_LOT", LotCategory: "MEM", LotDescription: "from estimate", Price: 50, PriceQuality: quality(9)},
})
seedUniversePricelist(t, local, 2, "world", "W-1", base, []LocalPricelistItem{
{LotName: "SHARED_LOT", LotCategory: "WRONG", LotDescription: "from world", Price: 55, PriceQuality: quality(1)},
{LotName: "NIC_WORLD_ONLY", LotCategory: "NIC", LotDescription: "from world", Price: 70, PriceQuality: quality(7)},
})
components, total, err := local.ListComponents(ComponentFilter{}, 0, 100)
if err != nil {
t.Fatalf("ListComponents: %v", err)
}
if total != 3 {
t.Fatalf("expected 3 components (dedup on SHARED_LOT), got %d", total)
}
byLot := make(map[string]LocalComponent, len(components))
for _, c := range components {
if _, dup := byLot[c.LotName]; dup {
t.Fatalf("duplicate lot in universe: %s", c.LotName)
}
byLot[c.LotName] = c
}
worldOnly, ok := byLot["NIC_WORLD_ONLY"]
if !ok {
t.Fatal("world-only LOT missing from the component universe")
}
if worldOnly.PriceQuality == nil || *worldOnly.PriceQuality != 0 {
t.Fatalf("world-only LOT must report price_quality 0, got %v", worldOnly.PriceQuality)
}
// The estimate row wins a collision, so its metadata stays authoritative.
shared := byLot["SHARED_LOT"]
if shared.Category != "MEM" || shared.LotDescription != "from estimate" {
t.Fatalf("estimate row must win a collision, got category=%q description=%q", shared.Category, shared.LotDescription)
}
if shared.PriceQuality == nil || *shared.PriceQuality != 9 {
t.Fatalf("estimate price_quality must survive a collision, got %v", shared.PriceQuality)
}
if got := local.CountComponents(); got != 3 {
t.Fatalf("CountComponents: expected 3, got %d", got)
}
single, err := local.GetLocalComponent("nic_world_only")
if err != nil {
t.Fatalf("GetLocalComponent for a world-only LOT: %v", err)
}
if single.LotName != "NIC_WORLD_ONLY" {
t.Fatalf("GetLocalComponent returned %q", single.LotName)
}
categories, err := local.GetLocalComponentCategories()
if err != nil {
t.Fatalf("GetLocalComponentCategories: %v", err)
}
if len(categories) != 3 {
t.Fatalf("expected CPU/MEM/NIC, got %v", categories)
}
cats, err := local.GetLocalComponentCategoriesByLotNames([]string{"NIC_WORLD_ONLY", "SHARED_LOT"})
if err != nil {
t.Fatalf("GetLocalComponentCategoriesByLotNames: %v", err)
}
if cats["NIC_WORLD_ONLY"] != "NIC" || cats["SHARED_LOT"] != "MEM" {
t.Fatalf("unexpected categories: %v", cats)
}
found, err := local.SearchLocalComponents("world_only", 10)
if err != nil || len(found) != 1 {
t.Fatalf("SearchLocalComponents: got %d rows, err=%v", len(found), err)
}
inCategory, err := local.SearchLocalComponentsByCategory("NIC", "", 10)
if err != nil || len(inCategory) != 1 {
t.Fatalf("SearchLocalComponentsByCategory: got %d rows, err=%v", len(inCategory), err)
}
}
// Only one of the two pricelists existing must not break the universe.
func TestComponentUniverseWithSingleSource(t *testing.T) {
t.Run("estimate only", func(t *testing.T) {
local := newUniverseDB(t, "universe_estimate_only.db")
seedUniversePricelist(t, local, 1, "estimate", "E-1", time.Now(), []LocalPricelistItem{
{LotName: "CPU_A", LotCategory: "CPU", Price: 100, PriceQuality: quality(8)},
})
if got := local.CountComponents(); got != 1 {
t.Fatalf("expected 1 component, got %d", got)
}
})
t.Run("world only", func(t *testing.T) {
local := newUniverseDB(t, "universe_world_only.db")
seedUniversePricelist(t, local, 2, "world", "W-1", time.Now(), []LocalPricelistItem{
{LotName: "CPU_A", LotCategory: "CPU", Price: 100, PriceQuality: quality(8)},
})
components, _, err := local.ListComponents(ComponentFilter{}, 0, 10)
if err != nil {
t.Fatalf("ListComponents: %v", err)
}
if len(components) != 1 {
t.Fatalf("expected 1 component, got %d", len(components))
}
if components[0].PriceQuality == nil || *components[0].PriceQuality != 0 {
t.Fatalf("world-only LOT must report price_quality 0, got %v", components[0].PriceQuality)
}
})
t.Run("neither", func(t *testing.T) {
local := newUniverseDB(t, "universe_empty.db")
if _, _, err := local.ListComponents(ComponentFilter{}, 0, 10); err == nil {
t.Fatal("expected an error when no estimate and no world pricelist exists")
}
if got := local.CountComponents(); got != 0 {
t.Fatalf("expected 0, got %d", got)
}
})
}
+224 -308
View File
@@ -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
}
+78 -57
View File
@@ -6,12 +6,48 @@ import (
"git.mchus.pro/mchus/quoteforge/internal/models"
)
// NormalizeLotMappings is the single canonical normalizer for vendor BOM LOT
// mappings. LOT names are canonicalized to their uppercase form (see
// models.NormalizeLotName) so that all BOM↔cart matching is case-insensitive,
// duplicate LOTs are merged (summing quantity-per-PN), and quantities are at
// least 1. Returns nil for an empty result. Both the persistence path
// (handlers) and the CSV export path must use this — do not reimplement it.
func NormalizeLotMappings(in []VendorSpecLotMapping) []VendorSpecLotMapping {
if len(in) == 0 {
return nil
}
merged := make(map[string]int, len(in))
order := make([]string, 0, len(in))
for _, m := range in {
lot := models.NormalizeLotName(m.LotName)
if lot == "" {
continue
}
qty := m.QuantityPerPN
if qty < 1 {
qty = 1
}
if _, exists := merged[lot]; !exists {
order = append(order, lot)
}
merged[lot] += qty
}
if len(order) == 0 {
return nil
}
out := make([]VendorSpecLotMapping, 0, len(order))
for _, lot := range order {
out = append(out, VendorSpecLotMapping{LotName: lot, QuantityPerPN: merged[lot]})
}
return out
}
// ConfigurationToLocal converts models.Configuration to LocalConfiguration
func ConfigurationToLocal(cfg *models.Configuration) *LocalConfiguration {
items := make(LocalConfigItems, len(cfg.Items))
for i, item := range cfg.Items {
items[i] = LocalConfigItem{
LotName: item.LotName,
LotName: models.NormalizeLotName(item.LotName),
Quantity: item.Quantity,
UnitPrice: item.UnitPrice,
}
@@ -38,6 +74,8 @@ func ConfigurationToLocal(cfg *models.Configuration) *LocalConfiguration {
VendorSpec: modelVendorSpecToLocal(cfg.VendorSpec),
DisablePriceRefresh: cfg.DisablePriceRefresh,
OnlyInStock: cfg.OnlyInStock,
RentalItems: modelRentalItemsToLocal(cfg.RentalItems),
RentalUpliftPercent: cfg.RentalUpliftPercent,
Line: cfg.Line,
PriceUpdatedAt: cfg.PriceUpdatedAt,
CreatedAt: cfg.CreatedAt,
@@ -87,6 +125,8 @@ func LocalToConfiguration(local *LocalConfiguration) *models.Configuration {
VendorSpec: localVendorSpecToModel(local.VendorSpec),
DisablePriceRefresh: local.DisablePriceRefresh,
OnlyInStock: local.OnlyInStock,
RentalItems: localRentalItemsToModel(local.RentalItems),
RentalUpliftPercent: local.RentalUpliftPercent,
Line: local.Line,
PriceUpdatedAt: local.PriceUpdatedAt,
CreatedAt: local.CreatedAt,
@@ -195,6 +235,28 @@ func localVendorSpecToModel(spec VendorSpec) models.VendorSpec {
return out
}
func modelRentalItemsToLocal(items models.RentalItemConditions) RentalItemConditions {
if len(items) == 0 {
return nil
}
out := make(RentalItemConditions, len(items))
for i, item := range items {
out[i] = RentalItemCondition{LotName: item.LotName, Condition: item.Condition}
}
return out
}
func localRentalItemsToModel(items RentalItemConditions) models.RentalItemConditions {
if len(items) == 0 {
return nil
}
out := make(models.RentalItemConditions, len(items))
for i, item := range items {
out[i] = models.RentalItemCondition{LotName: item.LotName, Condition: item.Condition}
}
return out
}
func ProjectToLocal(project *models.Project) *LocalProject {
local := &LocalProject{
UUID: project.UUID,
@@ -205,6 +267,7 @@ func ProjectToLocal(project *models.Project) *LocalProject {
TrackerURL: project.TrackerURL,
IsActive: project.IsActive,
IsSystem: project.IsSystem,
RentalEnabled: project.RentalEnabled,
CreatedAt: project.CreatedAt,
UpdatedAt: project.UpdatedAt,
SyncStatus: "pending",
@@ -226,6 +289,7 @@ func LocalToProject(local *LocalProject) *models.Project {
TrackerURL: local.TrackerURL,
IsActive: local.IsActive,
IsSystem: local.IsSystem,
RentalEnabled: local.RentalEnabled,
CreatedAt: local.CreatedAt,
UpdatedAt: local.UpdatedAt,
}
@@ -267,68 +331,25 @@ func LocalToPricelist(local *LocalPricelist) *models.Pricelist {
// PricelistItemToLocal converts models.PricelistItem to LocalPricelistItem
func PricelistItemToLocal(item *models.PricelistItem, localPricelistID uint) *LocalPricelistItem {
partnumbers := make(LocalStringList, 0, len(item.Partnumbers))
partnumbers = append(partnumbers, item.Partnumbers...)
return &LocalPricelistItem{
PricelistID: localPricelistID,
LotName: item.LotName,
LotCategory: item.LotCategory,
Price: item.Price,
AvailableQty: item.AvailableQty,
Partnumbers: partnumbers,
PricelistID: localPricelistID,
LotName: models.NormalizeLotName(item.LotName),
LotCategory: item.LotCategory,
LotDescription: item.LotDescription,
Price: item.Price,
PriceQuality: item.PriceQuality,
}
}
// LocalToPricelistItem converts LocalPricelistItem to models.PricelistItem
func LocalToPricelistItem(local *LocalPricelistItem, serverPricelistID uint) *models.PricelistItem {
partnumbers := make([]string, 0, len(local.Partnumbers))
partnumbers = append(partnumbers, local.Partnumbers...)
return &models.PricelistItem{
ID: local.ID,
PricelistID: serverPricelistID,
LotName: local.LotName,
LotCategory: local.LotCategory,
Price: local.Price,
AvailableQty: local.AvailableQty,
Partnumbers: partnumbers,
}
}
// ComponentToLocal converts models.LotMetadata to LocalComponent
func ComponentToLocal(meta *models.LotMetadata) *LocalComponent {
var lotDesc string
var category string
if meta.Lot != nil {
lotDesc = meta.Lot.LotDescription
}
// Extract category from lot_name (e.g., "CPU_AMD_9654" -> "CPU")
if len(meta.LotName) > 0 {
for i, ch := range meta.LotName {
if ch == '_' {
category = meta.LotName[:i]
break
}
}
}
return &LocalComponent{
LotName: meta.LotName,
LotDescription: lotDesc,
Category: category,
Model: meta.Model,
}
}
// LocalToComponent converts LocalComponent to models.LotMetadata
func LocalToComponent(local *LocalComponent) *models.LotMetadata {
return &models.LotMetadata{
LotName: local.LotName,
Model: local.Model,
Lot: &models.Lot{
LotName: local.LotName,
LotDescription: local.LotDescription,
},
ID: local.ID,
PricelistID: serverPricelistID,
LotName: local.LotName,
LotCategory: local.LotCategory,
LotDescription: local.LotDescription,
Price: local.Price,
PriceQuality: local.PriceQuality,
}
}
+30
View File
@@ -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",
+243 -74
View File
@@ -46,7 +46,6 @@ type LocalDB struct {
var localReadOnlyCacheTables = []string{
"local_pricelist_items",
"local_pricelists",
"local_components",
"local_partnumber_book_items",
"local_partnumber_books",
}
@@ -78,7 +77,6 @@ func ResetData(dbPath string) error {
"local_configuration_versions",
"local_pricelists",
"local_pricelist_items",
"local_components",
"local_sync_guard_state",
"pending_changes",
"app_settings",
@@ -116,6 +114,13 @@ func New(dbPath string) (*LocalDB, error) {
return nil, fmt.Errorf("opening sqlite database: %w", err)
}
// SQLite requires a single writer connection to avoid SQLITE_BUSY under concurrent requests.
sqlDB, err := db.DB()
if err != nil {
return nil, fmt.Errorf("get sql.DB from gorm: %w", err)
}
sqlDB.SetMaxOpenConns(1)
// Enable WAL mode so background sync writes never block UI reads.
if err := db.Exec("PRAGMA journal_mode=WAL").Error; err != nil {
slog.Warn("failed to enable WAL mode", "error", err)
@@ -123,6 +128,10 @@ func New(dbPath string) (*LocalDB, error) {
if err := db.Exec("PRAGMA synchronous=NORMAL").Error; err != nil {
slog.Warn("failed to set synchronous=NORMAL", "error", err)
}
// Wait up to 5 s before returning SQLITE_BUSY (guards against WAL checkpoints and external locks).
if err := db.Exec("PRAGMA busy_timeout = 5000").Error; err != nil {
slog.Warn("failed to set busy_timeout", "error", err)
}
if err := ensureLocalProjectsTable(db); err != nil {
return nil, fmt.Errorf("ensure local_projects table: %w", err)
@@ -202,6 +211,7 @@ CREATE TABLE local_projects (
tracker_url TEXT NULL,
is_active INTEGER NOT NULL DEFAULT 1,
is_system INTEGER NOT NULL DEFAULT 0,
rental_enabled INTEGER NOT NULL DEFAULT 0,
created_at DATETIME,
updated_at DATETIME,
synced_at DATETIME NULL,
@@ -224,12 +234,12 @@ func autoMigrateLocalSchema(db *gorm.DB) error {
&LocalConfigurationVersion{},
&LocalPricelist{},
&LocalPricelistItem{},
&LocalComponent{},
&AppSetting{},
&LocalSyncGuardState{},
&PendingChange{},
&LocalPartnumberBook{},
&SyncLogEntry{},
&LocalQtSetting{},
)
}
@@ -691,6 +701,22 @@ func (l *LocalDB) GetProjectByUUID(uuid string) (*LocalProject, error) {
return &project, nil
}
func (l *LocalDB) GetProjectByCode(code string) (*LocalProject, error) {
var project LocalProject
if err := l.db.Where("LOWER(code) = LOWER(?) AND variant = ''", code).First(&project).Error; err != nil {
return nil, err
}
return &project, nil
}
func (l *LocalDB) GetProjectByCodeAndVariant(code, variant string) (*LocalProject, error) {
var project LocalProject
if err := l.db.Where("LOWER(code) = LOWER(?) AND LOWER(variant) = LOWER(?)", code, variant).First(&project).Error; err != nil {
return nil, err
}
return &project, nil
}
func (l *LocalDB) GetProjectByName(ownerUsername, name string) (*LocalProject, error) {
var project LocalProject
if err := l.db.Where("owner_username = ? AND name = ?", ownerUsername, name).First(&project).Error; err != nil {
@@ -1220,24 +1246,66 @@ func (l *LocalDB) GetLastComponentSyncError() string {
return strings.TrimSpace(value)
}
func (l *LocalDB) SetComponentSyncResult(status, errorText string, attemptedAt time.Time) error {
status = strings.TrimSpace(status)
errorText = strings.TrimSpace(errorText)
if status == "" {
status = "unknown"
}
return l.db.Transaction(func(tx *gorm.DB) error {
if err := l.upsertAppSetting(tx, "last_component_sync_status", status, attemptedAt); err != nil {
return err
}
if err := l.upsertAppSetting(tx, "last_component_sync_error", errorText, attemptedAt); err != nil {
return err
}
if err := l.upsertAppSetting(tx, "last_component_sync_attempt_at", attemptedAt.Format(time.RFC3339), attemptedAt); err != nil {
return err
}
const openConfigUUIDsKey = "open_config_uuids"
// GetOpenConfigUUIDs returns UUIDs of all configurations currently open in the configurator.
func (l *LocalDB) GetOpenConfigUUIDs() []string {
value, ok := l.getAppSettingValue(openConfigUUIDsKey)
if !ok || value == "" {
return nil
})
}
var uuids []string
if err := json.Unmarshal([]byte(value), &uuids); err != nil {
return nil
}
return uuids
}
// AddOpenConfigUUID records that a configuration is open in the configurator.
func (l *LocalDB) AddOpenConfigUUID(uuid string) error {
uuids := l.GetOpenConfigUUIDs()
for _, u := range uuids {
if u == uuid {
return nil
}
}
uuids = append(uuids, uuid)
raw, err := json.Marshal(uuids)
if err != nil {
return err
}
return l.db.Exec(`
INSERT INTO app_settings (key, value, updated_at)
VALUES (?, ?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
`, openConfigUUIDsKey, string(raw), time.Now().Format(time.RFC3339)).Error
}
// RemoveOpenConfigUUID records that a configuration is no longer open in the configurator.
func (l *LocalDB) RemoveOpenConfigUUID(uuid string) error {
uuids := l.GetOpenConfigUUIDs()
filtered := uuids[:0]
for _, u := range uuids {
if u != uuid {
filtered = append(filtered, u)
}
}
var raw []byte
var err error
if len(filtered) == 0 {
raw = []byte("[]")
} else {
raw, err = json.Marshal(filtered)
if err != nil {
return err
}
}
return l.db.Exec(`
INSERT INTO app_settings (key, value, updated_at)
VALUES (?, ?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
`, openConfigUUIDsKey, string(raw), time.Now().Format(time.RFC3339)).Error
}
// CountLocalPricelists returns the number of local pricelists
@@ -1254,11 +1322,10 @@ func (l *LocalDB) CountAllPricelistItems() int64 {
return count
}
// CountComponents returns the number of rows in local_components.
func (l *LocalDB) CountComponents() int64 {
var count int64
l.db.Model(&LocalComponent{}).Count(&count)
return count
// DBFilePath returns the path to the SQLite database file.
func (l *LocalDB) DBFilePath() string {
return l.path
}
// DBFileSizeBytes returns the size of the SQLite database file in bytes.
@@ -1270,11 +1337,11 @@ func (l *LocalDB) DBFileSizeBytes() int64 {
return info.Size()
}
// GetLatestLocalPricelist returns the most recently synced pricelist
// GetLatestLocalPricelist returns the most recently synced active estimate pricelist.
func (l *LocalDB) GetLatestLocalPricelist() (*LocalPricelist, error) {
var pricelist LocalPricelist
if err := l.db.
Where("source = ?", "estimate").
Where("source = ? AND is_active = ?", "estimate", true).
Where("EXISTS (SELECT 1 FROM local_pricelist_items WHERE local_pricelist_items.pricelist_id = local_pricelists.id)").
Order("created_at DESC, id DESC").
First(&pricelist).Error; err != nil {
@@ -1283,11 +1350,20 @@ func (l *LocalDB) GetLatestLocalPricelist() (*LocalPricelist, error) {
return &pricelist, nil
}
// GetLatestLocalPricelistBySource returns the most recently synced pricelist for a source.
// GetLatestLocalPricelistBySource returns the most recently synced active pricelist for a source.
func (l *LocalDB) GetLatestLocalPricelistBySource(source string) (*LocalPricelist, error) {
return GetLatestLocalPricelistBySourceTx(l.db, source)
}
// GetLatestLocalPricelistBySourceTx is the transaction-scoped variant of
// GetLatestLocalPricelistBySource. Callers already inside an l.db.Transaction(...) callback
// must use this with the given tx instead of the method above — the connection pool has a
// single connection (see New()), so querying via l.db while the transaction holds that
// connection deadlocks forever.
func GetLatestLocalPricelistBySourceTx(tx *gorm.DB, source string) (*LocalPricelist, error) {
var pricelist LocalPricelist
if err := l.db.
Where("source = ?", source).
if err := tx.
Where("source = ? AND is_active = ?", source, true).
Where("EXISTS (SELECT 1 FROM local_pricelist_items WHERE local_pricelist_items.pricelist_id = local_pricelists.id)").
Order("created_at DESC, id DESC").
First(&pricelist).Error; err != nil {
@@ -1296,6 +1372,17 @@ func (l *LocalDB) GetLatestLocalPricelistBySource(source string) (*LocalPricelis
return &pricelist, nil
}
// DeactivateLocalPricelistsNotIn marks all local pricelists with is_active=true whose
// server_id is not in activeServerIDs as inactive. Used after each pricelist sync to
// mirror server-side deactivations locally.
func (l *LocalDB) DeactivateLocalPricelistsNotIn(activeServerIDs []uint) error {
q := l.db.Model(&LocalPricelist{}).Where("is_active = ?", true)
if len(activeServerIDs) > 0 {
q = q.Where("server_id NOT IN ?", activeServerIDs)
}
return q.Update("is_active", false).Error
}
// GetLocalPricelistByServerID returns a local pricelist by its server ID
func (l *LocalDB) GetLocalPricelistByServerID(serverID uint) (*LocalPricelist, error) {
var pricelist LocalPricelist
@@ -1363,6 +1450,30 @@ func (l *LocalDB) CountLocalPricelistItems(pricelistID uint) int64 {
return count
}
// GetLocalPricelistCoverageByCategory returns item count per lot_category and the total
// for the given local pricelist ID. Only items with price > 0 are counted.
func (l *LocalDB) GetLocalPricelistCoverageByCategory(pricelistID uint) (map[string]int64, int64, error) {
type row struct {
Category string `gorm:"column:lot_category"`
Count int64 `gorm:"column:cnt"`
}
var rows []row
if err := l.db.Model(&LocalPricelistItem{}).
Select("COALESCE(NULLIF(TRIM(lot_category),''), '?') AS lot_category, COUNT(*) AS cnt").
Where("pricelist_id = ? AND price > 0", pricelistID).
Group("lot_category").
Scan(&rows).Error; err != nil {
return nil, 0, err
}
result := make(map[string]int64, len(rows))
var total int64
for _, r := range rows {
result[r.Category] = r.Count
total += r.Count
}
return result, total, nil
}
// CountLocalPricelistItemsWithEmptyCategory returns the number of items for a pricelist with missing lot_category.
func (l *LocalDB) CountLocalPricelistItemsWithEmptyCategory(pricelistID uint) (int64, error) {
var count int64
@@ -1427,10 +1538,11 @@ func (l *LocalDB) GetLocalPricelistItems(pricelistID uint) ([]LocalPricelistItem
return items, nil
}
// GetLocalPriceForLot returns the price for a lot from a local pricelist
// GetLocalPriceForLot returns the price for a lot from a local pricelist.
// Matching is case-insensitive via UPPER(lot_name) to handle legacy mixed-case rows.
func (l *LocalDB) GetLocalPriceForLot(pricelistID uint, lotName string) (float64, error) {
var item LocalPricelistItem
if err := l.db.Where("pricelist_id = ? AND lot_name = ?", pricelistID, lotName).
if err := l.db.Where("pricelist_id = ? AND UPPER(lot_name) = ?", pricelistID, strings.ToUpper(lotName)).
First(&item).Error; err != nil {
return 0, err
}
@@ -1438,26 +1550,39 @@ func (l *LocalDB) GetLocalPriceForLot(pricelistID uint, lotName string) (float64
}
// GetLocalPricesForLots returns prices for multiple lots from a local pricelist in a single query.
// Uses the composite index (pricelist_id, lot_name). Missing lots are omitted from the result.
// Missing lots are omitted from the result.
// lotNames must already be normalized (uppercased); matching is done via UPPER(lot_name) to handle
// legacy rows that were stored in mixed case before normalization was enforced at sync time.
// Keys in the returned map are uppercased (matching the input lotNames).
func (l *LocalDB) GetLocalPricesForLots(pricelistID uint, lotNames []string) (map[string]float64, error) {
return GetLocalPricesForLotsTx(l.db, pricelistID, lotNames)
}
// GetLocalPricesForLotsTx is the transaction-scoped variant of GetLocalPricesForLots. See
// GetLatestLocalPricelistBySourceTx for why callers inside an l.db.Transaction(...) callback
// must use this with the given tx instead of the method above.
func GetLocalPricesForLotsTx(tx *gorm.DB, pricelistID uint, lotNames []string) (map[string]float64, error) {
result := make(map[string]float64, len(lotNames))
if len(lotNames) == 0 {
return result, nil
}
type row struct {
LotName string `gorm:"column:lot_name"`
Price float64 `gorm:"column:price"`
}
var rows []row
if err := l.db.Model(&LocalPricelistItem{}).
// Use UPPER(lot_name) so rows synced before normalization (mixed-case) are still matched.
if err := tx.Model(&LocalPricelistItem{}).
Select("lot_name, price").
Where("pricelist_id = ? AND lot_name IN ?", pricelistID, lotNames).
Where("pricelist_id = ? AND UPPER(lot_name) IN ?", pricelistID, lotNames).
Find(&rows).Error; err != nil {
return nil, err
}
for _, r := range rows {
if r.Price > 0 {
result[r.LotName] = r.Price
// Key must be uppercase to match callers that normalise lot names before lookup.
result[strings.ToUpper(r.LotName)] = r.Price
}
}
return result, nil
@@ -1480,15 +1605,72 @@ func (l *LocalDB) GetLocalLotCategoriesByServerPricelistID(serverPricelistID uin
LotName string `gorm:"column:lot_name"`
LotCategory string `gorm:"column:lot_category"`
}
// Build uppercase → original mapping so result keys match what the caller passed.
upperToOrig := make(map[string]string, len(lotNames))
upper := make([]string, len(lotNames))
for i, n := range lotNames {
u := strings.ToUpper(n)
upper[i] = u
upperToOrig[u] = n
}
var rows []row
if err := l.db.Model(&LocalPricelistItem{}).
Select("lot_name, lot_category").
Where("pricelist_id = ? AND lot_name IN ?", localPL.ID, lotNames).
Where("pricelist_id = ? AND UPPER(lot_name) IN ?", localPL.ID, upper).
Find(&rows).Error; err != nil {
return nil, err
}
for _, r := range rows {
result[r.LotName] = r.LotCategory
orig := upperToOrig[strings.ToUpper(r.LotName)]
if orig == "" {
orig = r.LotName
}
result[orig] = r.LotCategory
}
return result, nil
}
// GetLocalDescriptionsForLots returns lot_description for each lot_name from a local
// pricelist resolved by server ID. Missing lots are not included in the map.
func (l *LocalDB) GetLocalDescriptionsForLots(serverPricelistID uint, lotNames []string) (map[string]string, error) {
result := make(map[string]string, len(lotNames))
if serverPricelistID == 0 || len(lotNames) == 0 {
return result, nil
}
localPL, err := l.GetLocalPricelistByServerID(serverPricelistID)
if err != nil {
return nil, err
}
type row struct {
LotName string `gorm:"column:lot_name"`
LotDescription string `gorm:"column:lot_description"`
}
// Build uppercase → original mapping so result keys match what the caller passed.
upperToOrig := make(map[string]string, len(lotNames))
upper := make([]string, len(lotNames))
for i, n := range lotNames {
u := strings.ToUpper(n)
upper[i] = u
upperToOrig[u] = n
}
var rows []row
if err := l.db.Model(&LocalPricelistItem{}).
Select("lot_name, lot_description").
Where("pricelist_id = ? AND UPPER(lot_name) IN ?", localPL.ID, upper).
Find(&rows).Error; err != nil {
return nil, err
}
for _, r := range rows {
if r.LotDescription == "" {
continue
}
orig := upperToOrig[strings.ToUpper(r.LotName)]
if orig == "" {
orig = r.LotName
}
result[orig] = r.LotDescription
}
return result, nil
}
@@ -1672,12 +1854,13 @@ func (l *LocalDB) RepairPendingChanges() (int, []string, error) {
var remainingErrors []string
for _, change := range erroredChanges {
var modified bool
var repairErr error
switch change.EntityType {
case "project":
repairErr = l.repairProjectChange(&change)
modified, repairErr = l.repairProjectChange(&change)
case "configuration":
repairErr = l.repairConfigurationChange(&change)
modified, repairErr = l.repairConfigurationChange(&change)
default:
repairErr = fmt.Errorf("unknown entity type: %s", change.EntityType)
}
@@ -1688,7 +1871,13 @@ func (l *LocalDB) RepairPendingChanges() (int, []string, error) {
continue
}
// Clear error and reset attempts
// Only reset attempts when the repair actually changed local data.
// If nothing was modified, the error is server-side; leaving attempts
// intact lets maxPendingChangeAttempts eventually abandon the change.
if !modified {
continue
}
if err := l.db.Model(&PendingChange{}).Where("id = ?", change.ID).Updates(map[string]interface{}{
"last_error": "",
"attempts": 0,
@@ -1704,12 +1893,13 @@ func (l *LocalDB) RepairPendingChanges() (int, []string, error) {
}
// repairProjectChange validates and fixes project data.
// Returns (modified, err): modified=true only when local data was actually changed.
// Note: This only validates local data. Server-side conflicts (like duplicate code+variant)
// are handled by sync service layer with deduplication logic.
func (l *LocalDB) repairProjectChange(change *PendingChange) error {
func (l *LocalDB) repairProjectChange(change *PendingChange) (bool, error) {
project, err := l.GetProjectByUUID(change.EntityUUID)
if err != nil {
return fmt.Errorf("project not found locally: %w", err)
return false, fmt.Errorf("project not found locally: %w", err)
}
modified := false
@@ -1735,7 +1925,7 @@ func (l *LocalDB) repairProjectChange(change *PendingChange) error {
if strings.TrimSpace(project.OwnerUsername) == "" {
project.OwnerUsername = l.GetDBUser()
if project.OwnerUsername == "" {
return fmt.Errorf("cannot determine owner username")
return false, fmt.Errorf("cannot determine owner username")
}
modified = true
}
@@ -1756,18 +1946,19 @@ func (l *LocalDB) repairProjectChange(change *PendingChange) error {
if modified {
if err := l.SaveProject(project); err != nil {
return fmt.Errorf("saving repaired project: %w", err)
return false, fmt.Errorf("saving repaired project: %w", err)
}
}
return nil
return modified, nil
}
// repairConfigurationChange validates and fixes configuration data
func (l *LocalDB) repairConfigurationChange(change *PendingChange) error {
// repairConfigurationChange validates and fixes configuration data.
// Returns (modified, err): modified=true only when local data was actually changed.
func (l *LocalDB) repairConfigurationChange(change *PendingChange) (bool, error) {
config, err := l.GetConfigurationByUUID(change.EntityUUID)
if err != nil {
return fmt.Errorf("configuration not found locally: %w", err)
return false, fmt.Errorf("configuration not found locally: %w", err)
}
modified := false
@@ -1779,7 +1970,7 @@ func (l *LocalDB) repairConfigurationChange(change *PendingChange) error {
// Project doesn't exist locally - use default system project
systemProject, sysErr := l.EnsureDefaultProject(config.OriginalUsername)
if sysErr != nil {
return fmt.Errorf("getting system project: %w", sysErr)
return false, fmt.Errorf("getting system project: %w", sysErr)
}
config.ProjectUUID = &systemProject.UUID
modified = true
@@ -1788,11 +1979,11 @@ func (l *LocalDB) repairConfigurationChange(change *PendingChange) error {
if modified {
if err := l.SaveConfiguration(config); err != nil {
return fmt.Errorf("saving repaired configuration: %w", err)
return false, fmt.Errorf("saving repaired configuration: %w", err)
}
}
return nil
return modified, nil
}
// GetSyncGuardState returns the latest readiness guard state.
@@ -1854,28 +2045,6 @@ func (l *LocalDB) GetLocalPricelistItemsPage(pricelistID uint, search string, pa
return items, total, nil
}
// GetLocalComponentDescriptionsByLotNames returns a map of lot_name → lot_description for the given lots.
func (l *LocalDB) GetLocalComponentDescriptionsByLotNames(lotNames []string) (map[string]string, error) {
if len(lotNames) == 0 {
return map[string]string{}, nil
}
type row struct {
LotName string
LotDescription string
}
var rows []row
if err := l.db.Table("local_components").
Select("lot_name, lot_description").
Where("lot_name IN ?", lotNames).
Scan(&rows).Error; err != nil {
return nil, fmt.Errorf("fetch component descriptions: %w", err)
}
m := make(map[string]string, len(rows))
for _, r := range rows {
m[r.LotName] = r.LotDescription
}
return m, nil
}
// GetSchemaMigrations returns all applied local schema migrations ordered by applied_at.
func (l *LocalDB) GetSchemaMigrations() ([]LocalSchemaMigration, error) {
+123
View File
@@ -124,6 +124,129 @@ var localMigrations = []localMigration{
name: "Deduplicate local_pricelist_items and add unique index on (pricelist_id, lot_name)",
run: deduplicatePricelistItemsAndAddUniqueIndex,
},
{
id: "2026_07_22_local_project_rental_enabled",
name: "Add rental_enabled to local_projects",
run: addLocalProjectRentalEnabled,
},
{
id: "2026_07_22_pricelist_items_add_description_drop_unused",
name: "Add lot_description to local_pricelist_items, drop unused available_qty/partnumbers",
run: addPricelistItemDescriptionDropUnused,
},
{
id: "2026_07_22_pricelist_items_price_quality",
name: "Add price_quality to local_pricelist_items",
run: addLocalPricelistItemPriceQuality,
},
}
func addLocalPricelistItemPriceQuality(tx *gorm.DB) error {
type columnInfo struct {
Name string `gorm:"column:name"`
}
var columns []columnInfo
if err := tx.Raw(`
SELECT name FROM pragma_table_info('local_pricelist_items')
WHERE name = 'price_quality'
`).Scan(&columns).Error; err != nil {
return fmt.Errorf("check local_pricelist_items(price_quality) existence: %w", err)
}
if len(columns) > 0 {
slog.Info("price_quality already present on local_pricelist_items")
return nil
}
if err := tx.Exec(`ALTER TABLE local_pricelist_items ADD COLUMN price_quality INTEGER`).Error; err != nil {
return fmt.Errorf("add local_pricelist_items.price_quality: %w", err)
}
slog.Info("added price_quality to local_pricelist_items")
return nil
}
func addPricelistItemDescriptionDropUnused(tx *gorm.DB) error {
type columnInfo struct {
Name string `gorm:"column:name"`
}
var columns []columnInfo
if err := tx.Raw(`
SELECT name FROM pragma_table_info('local_pricelist_items')
WHERE name IN ('lot_description', 'available_qty', 'partnumbers')
`).Scan(&columns).Error; err != nil {
return fmt.Errorf("check local_pricelist_items columns: %w", err)
}
have := make(map[string]bool, len(columns))
for _, c := range columns {
have[c.Name] = true
}
if have["lot_description"] && !have["available_qty"] && !have["partnumbers"] {
slog.Info("local_pricelist_items already migrated to description-only schema")
return nil
}
// SQLite: recreate table without the never-populated available_qty/partnumbers
// columns, adding lot_description (synced from qt_pricelist_items.lot_description).
if err := tx.Exec(`
CREATE TABLE local_pricelist_items_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
pricelist_id INTEGER NOT NULL,
lot_name TEXT NOT NULL,
lot_category TEXT,
lot_description TEXT,
price REAL NOT NULL
)
`).Error; err != nil {
return fmt.Errorf("create new local_pricelist_items table: %w", err)
}
if err := tx.Exec(`
INSERT INTO local_pricelist_items_new (id, pricelist_id, lot_name, lot_category, price)
SELECT id, pricelist_id, lot_name, lot_category, price
FROM local_pricelist_items
`).Error; err != nil {
return fmt.Errorf("copy data to new local_pricelist_items table: %w", err)
}
if err := tx.Exec(`DROP TABLE local_pricelist_items`).Error; err != nil {
return fmt.Errorf("drop old local_pricelist_items table: %w", err)
}
if err := tx.Exec(`ALTER TABLE local_pricelist_items_new RENAME TO local_pricelist_items`).Error; err != nil {
return fmt.Errorf("rename new local_pricelist_items table: %w", err)
}
if err := tx.Exec(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_local_pricelist_items_pricelist_lot_unique
ON local_pricelist_items(pricelist_id, lot_name)
`).Error; err != nil {
return fmt.Errorf("recreate unique index on local_pricelist_items: %w", err)
}
if err := tx.Exec(`
CREATE INDEX IF NOT EXISTS idx_local_pricelist_items_lot_category
ON local_pricelist_items(lot_category)
`).Error; err != nil {
return fmt.Errorf("recreate idx_local_pricelist_items_lot_category: %w", err)
}
slog.Info("added lot_description to local_pricelist_items and dropped available_qty/partnumbers")
return nil
}
func addLocalProjectRentalEnabled(tx *gorm.DB) error {
if err := tx.Exec(`ALTER TABLE local_projects ADD COLUMN rental_enabled INTEGER NOT NULL DEFAULT 0`).Error; err != nil {
if !strings.Contains(strings.ToLower(err.Error()), "duplicate") &&
!strings.Contains(strings.ToLower(err.Error()), "exists") {
return err
}
}
return nil
}
type localPartnumberCatalogRow struct {
+70 -12
View File
@@ -5,6 +5,8 @@ import (
"encoding/json"
"errors"
"time"
"git.mchus.pro/mchus/quoteforge/internal/models"
)
// AppSetting stores application settings in local SQLite
@@ -46,7 +48,13 @@ func (c *LocalConfigItems) Scan(value interface{}) error {
default:
return errors.New("type assertion failed for LocalConfigItems")
}
return json.Unmarshal(bytes, c)
if err := json.Unmarshal(bytes, c); err != nil {
return err
}
for i := range *c {
(*c)[i].LotName = models.NormalizeLotName((*c)[i].LotName)
}
return nil
}
func (c LocalConfigItems) Total() float64 {
@@ -104,13 +112,15 @@ type LocalConfiguration struct {
CompetitorPricelistID *uint `gorm:"index" json:"competitor_pricelist_id,omitempty"`
DisablePriceRefresh bool `gorm:"default:false" json:"disable_price_refresh"`
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
RentalItems RentalItemConditions `gorm:"type:text" json:"rental_items,omitempty"`
RentalUpliftPercent float64 `gorm:"default:0" json:"rental_uplift_percent"`
VendorSpec VendorSpec `gorm:"type:text" json:"vendor_spec,omitempty"`
Line int `gorm:"column:line_no;index" json:"line"`
PriceUpdatedAt *time.Time `gorm:"type:timestamp" json:"price_updated_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
SyncedAt *time.Time `json:"synced_at"`
ConfigType string `gorm:"default:server" json:"config_type"` // "server" | "storage"
ConfigType string `gorm:"default:server" json:"config_type"` // "server" | "storage"
SyncStatus string `gorm:"default:'local'" json:"sync_status"` // 'local', 'synced', 'modified'
OriginalUserID uint `json:"original_user_id"` // UserID from MariaDB for reference
OriginalUsername string `gorm:"not null;default:'';index" json:"original_username"`
@@ -133,6 +143,7 @@ type LocalProject struct {
TrackerURL string `json:"tracker_url"`
IsActive bool `gorm:"default:true;index" json:"is_active"`
IsSystem bool `gorm:"default:false;index" json:"is_system"`
RentalEnabled bool `gorm:"default:false" json:"rental_enabled"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
SyncedAt *time.Time `json:"synced_at,omitempty"`
@@ -169,7 +180,8 @@ type LocalPricelist struct {
Name string `json:"name"`
CreatedAt time.Time `gorm:"index:idx_local_pricelists_source_created_at,priority:2,sort:desc" json:"created_at"`
SyncedAt time.Time `json:"synced_at"`
IsUsed bool `gorm:"default:false" json:"is_used"` // Used by any local configuration
IsUsed bool `gorm:"default:false" json:"is_used"` // Used by any local configuration
IsActive bool `gorm:"not null;default:true;index" json:"is_active"` // Mirrors qt_pricelists.is_active
}
func (LocalPricelist) TableName() string {
@@ -178,13 +190,16 @@ func (LocalPricelist) TableName() string {
// LocalPricelistItem stores pricelist items
type LocalPricelistItem struct {
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
PricelistID uint `gorm:"not null;index" json:"pricelist_id"`
LotName string `gorm:"not null" json:"lot_name"`
LotCategory string `gorm:"column:lot_category" json:"lot_category,omitempty"`
Price float64 `gorm:"not null" json:"price"`
AvailableQty *float64 `json:"available_qty,omitempty"`
Partnumbers LocalStringList `gorm:"type:text" json:"partnumbers,omitempty"`
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
PricelistID uint `gorm:"not null;index" json:"pricelist_id"`
LotName string `gorm:"not null" json:"lot_name"`
LotCategory string `gorm:"column:lot_category" json:"lot_category,omitempty"`
LotDescription string `gorm:"column:lot_description" json:"lot_description,omitempty"`
Price float64 `gorm:"not null" json:"price"`
// PriceQuality mirrors qt_pricelist_items.price_quality: a 0-9 score set by
// the external pricing tool. 7-9 good, 4-6 warning, 0-3 poor.
PriceQuality *int `gorm:"column:price_quality" json:"price_quality,omitempty"`
}
func (LocalPricelistItem) TableName() string {
@@ -198,6 +213,7 @@ type LocalComponent struct {
LotDescription string `json:"lot_description"`
Category string `json:"category"`
Model string `json:"model"`
PriceQuality *int `json:"price_quality,omitempty"`
}
func (LocalComponent) TableName() string {
@@ -289,6 +305,39 @@ func (LocalPartnumberBookItem) TableName() string {
return "local_partnumber_book_items"
}
// RentalItemCondition tracks New/БУ condition per component for a single
// configuration's Аренда (rental) tab. Independent of the lot's catalog data.
type RentalItemCondition struct {
LotName string `json:"lot_name"`
Condition string `json:"condition"` // "new" or "used"
}
type RentalItemConditions []RentalItemCondition
func (r RentalItemConditions) Value() (driver.Value, error) {
if r == nil {
return nil, nil
}
return json.Marshal(r)
}
func (r *RentalItemConditions) Scan(value interface{}) error {
if value == nil {
*r = nil
return nil
}
var bytes []byte
switch v := value.(type) {
case []byte:
bytes = v
case string:
bytes = []byte(v)
default:
return errors.New("type assertion failed for RentalItemConditions")
}
return json.Unmarshal(bytes, r)
}
// VendorSpecItem represents a single row in a vendor BOM specification
type VendorSpecItem struct {
SortOrder int `json:"sort_order"`
@@ -320,8 +369,8 @@ type VendorSpecLotMapping struct {
// SyncLogEntry records the outcome of a single sync operation for diagnostics.
type SyncLogEntry struct {
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
SyncType string `gorm:"not null;index;size:32" json:"sync_type"` // components | pricelists | push | full
Status string `gorm:"not null;size:16" json:"status"` // ok | error | skipped
SyncType string `gorm:"not null;index;size:32" json:"sync_type"` // components | pricelists | push | full
Status string `gorm:"not null;size:16" json:"status"` // ok | error | skipped
ErrorText string `gorm:"size:1000" json:"error_text,omitempty"`
SyncedCount int `gorm:"default:0" json:"synced_count"`
StartedAt time.Time `gorm:"not null;index" json:"started_at"`
@@ -356,3 +405,12 @@ func (v *VendorSpec) Scan(value interface{}) error {
}
return json.Unmarshal(bytes, v)
}
// LocalQtSetting caches server-pushed settings from qt_settings (MariaDB) into local SQLite.
// Synced during component sync. Each row is a JSON-valued setting identified by name.
type LocalQtSetting struct {
Name string `gorm:"primaryKey;size:100"`
Value string `gorm:"type:text"`
}
func (LocalQtSetting) TableName() string { return "local_qt_settings" }
+144
View File
@@ -0,0 +1,144 @@
package localdb
import (
"encoding/json"
"fmt"
"log/slog"
"gorm.io/gorm"
)
// ConfigTypeDef describes one device configuration type as synced from qt_settings.
type ConfigTypeDef struct {
Code string `json:"code"`
NameRu string `json:"name_ru"`
DisplayOrder int `json:"display_order"`
Categories []string `json:"categories"`
}
// TabSection is a named sub-group of categories within a configurator tab.
type TabSection struct {
Title string `json:"title"`
Categories []string `json:"categories"`
}
// TabDef describes one tab in the configurator as synced from qt_settings.
type TabDef struct {
Key string `json:"key"`
Label string `json:"label"`
SingleSelect bool `json:"single_select"`
Categories []string `json:"categories"`
Sections []TabSection `json:"sections,omitempty"`
}
// 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"`
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.
// 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 err := tx.Create(&rows).Error; err != nil {
return fmt.Errorf("inserting local_qt_settings: %w", err)
}
slog.Info("qt_settings synced", "count", len(rows))
return nil
})
}
// GetQtSetting returns the raw JSON value for a named setting.
// found is false when the key does not exist.
func (l *LocalDB) GetQtSetting(name string) (value string, found bool, err error) {
var row LocalQtSetting
res := l.db.Where("name = ?", name).First(&row)
if res.Error != nil {
if res.Error == gorm.ErrRecordNotFound {
return "", false, nil
}
return "", false, res.Error
}
return row.Value, true, nil
}
// GetConfiguratorSettings reads all four known settings from local_qt_settings and
// parses them. Any missing or unparseable key is left as nil/zero in the result;
// the caller must apply fallbacks.
func (l *LocalDB) GetConfiguratorSettings() (*ConfiguratorSettings, error) {
out := &ConfiguratorSettings{}
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 {
return out, fmt.Errorf("reading setting %q: %w", key, err)
}
if !found || raw == "" {
continue
}
switch key {
case "config_types":
if err := json.Unmarshal([]byte(raw), &out.ConfigTypes); err != nil {
slog.Warn("failed to parse config_types setting", "error", err)
}
case "tab_config":
if err := json.Unmarshal([]byte(raw), &out.TabConfig); err != nil {
slog.Warn("failed to parse tab_config setting", "error", err)
}
case "always_visible_tabs":
if err := json.Unmarshal([]byte(raw), &out.AlwaysVisibleTabs); err != nil {
slog.Warn("failed to parse always_visible_tabs setting", "error", err)
}
case "required_categories":
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
}
}
}
return out, nil
}
+18 -2
View File
@@ -31,6 +31,8 @@ func BuildConfigurationSnapshot(localCfg *LocalConfiguration) (string, error) {
"competitor_pricelist_id": localCfg.CompetitorPricelistID,
"disable_price_refresh": localCfg.DisablePriceRefresh,
"only_in_stock": localCfg.OnlyInStock,
"rental_items": localCfg.RentalItems,
"rental_uplift_percent": localCfg.RentalUpliftPercent,
"vendor_spec": localCfg.VendorSpec,
"line": localCfg.Line,
"price_updated_at": localCfg.PriceUpdatedAt,
@@ -67,8 +69,10 @@ func DecodeConfigurationSnapshot(data string) (*LocalConfiguration, error) {
PricelistID *uint `json:"pricelist_id"`
WarehousePricelistID *uint `json:"warehouse_pricelist_id"`
CompetitorPricelistID *uint `json:"competitor_pricelist_id"`
DisablePriceRefresh bool `json:"disable_price_refresh"`
OnlyInStock bool `json:"only_in_stock"`
DisablePriceRefresh bool `json:"disable_price_refresh"`
OnlyInStock bool `json:"only_in_stock"`
RentalItems RentalItemConditions `json:"rental_items"`
RentalUpliftPercent float64 `json:"rental_uplift_percent"`
VendorSpec VendorSpec `json:"vendor_spec"`
Line int `json:"line"`
PriceUpdatedAt *time.Time `json:"price_updated_at"`
@@ -103,6 +107,8 @@ func DecodeConfigurationSnapshot(data string) (*LocalConfiguration, error) {
CompetitorPricelistID: snapshot.CompetitorPricelistID,
DisablePriceRefresh: snapshot.DisablePriceRefresh,
OnlyInStock: snapshot.OnlyInStock,
RentalItems: snapshot.RentalItems,
RentalUpliftPercent: snapshot.RentalUpliftPercent,
VendorSpec: snapshot.VendorSpec,
Line: snapshot.Line,
PriceUpdatedAt: snapshot.PriceUpdatedAt,
@@ -121,6 +127,8 @@ type configurationSpecPriceFingerprint struct {
CompetitorPricelistID *uint `json:"competitor_pricelist_id,omitempty"`
DisablePriceRefresh bool `json:"disable_price_refresh"`
OnlyInStock bool `json:"only_in_stock"`
RentalItems RentalItemConditions `json:"rental_items,omitempty"`
RentalUpliftPercent float64 `json:"rental_uplift_percent"`
VendorSpec VendorSpec `json:"vendor_spec,omitempty"`
}
@@ -151,6 +159,12 @@ func BuildConfigurationSpecPriceFingerprint(localCfg *LocalConfiguration) (strin
return items[i].UnitPrice < items[j].UnitPrice
})
rentalItems := make(RentalItemConditions, len(localCfg.RentalItems))
copy(rentalItems, localCfg.RentalItems)
sort.Slice(rentalItems, func(i, j int) bool {
return rentalItems[i].LotName < rentalItems[j].LotName
})
payload := configurationSpecPriceFingerprint{
Items: items,
ServerCount: localCfg.ServerCount,
@@ -161,6 +175,8 @@ func BuildConfigurationSpecPriceFingerprint(localCfg *LocalConfiguration) (strin
CompetitorPricelistID: localCfg.CompetitorPricelistID,
DisablePriceRefresh: localCfg.DisablePriceRefresh,
OnlyInStock: localCfg.OnlyInStock,
RentalItems: rentalItems,
RentalUpliftPercent: localCfg.RentalUpliftPercent,
VendorSpec: localCfg.VendorSpec,
}
+37
View File
@@ -64,6 +64,41 @@ type VendorSpecItem struct {
LotMappings []VendorSpecLotMapping `json:"lot_mappings,omitempty"`
}
// RentalItemCondition tracks whether a component is being rented/tested as
// new or used hardware, for a single configuration's Аренда tab. This is
// independent of the lot's catalog data: the same lot_name can be "new" in
// one configuration and "used" in another.
type RentalItemCondition struct {
LotName string `json:"lot_name"`
Condition string `json:"condition"` // "new" or "used"
}
type RentalItemConditions []RentalItemCondition
func (r RentalItemConditions) Value() (driver.Value, error) {
if r == nil {
return nil, nil
}
return json.Marshal(r)
}
func (r *RentalItemConditions) Scan(value interface{}) error {
if value == nil {
*r = nil
return nil
}
var bytes []byte
switch v := value.(type) {
case []byte:
bytes = v
case string:
bytes = []byte(v)
default:
return errors.New("type assertion failed for RentalItemConditions")
}
return json.Unmarshal(bytes, r)
}
type VendorSpec []VendorSpecItem
func (v VendorSpec) Value() (driver.Value, error) {
@@ -114,6 +149,8 @@ type Configuration struct {
ConfigType string `gorm:"size:20;default:server" json:"config_type"` // "server" | "storage"
DisablePriceRefresh bool `gorm:"default:false" json:"disable_price_refresh"`
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
RentalItems RentalItemConditions `gorm:"type:json" json:"rental_items,omitempty"`
RentalUpliftPercent float64 `gorm:"type:decimal(8,2);default:0" json:"rental_uplift_percent"`
Line int `gorm:"column:line_no;index" json:"line"`
PriceUpdatedAt *time.Time `gorm:"type:timestamp" json:"price_updated_at,omitempty"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
+5 -8
View File
@@ -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))
}
-92
View File
@@ -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
View File
@@ -11,7 +11,6 @@ import (
func AllModels() []interface{} {
return []interface{}{
&Category{},
&LotMetadata{},
&Project{},
&Configuration{},
&Pricelist{},
+14 -18
View File
@@ -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 {
+1
View File
@@ -12,6 +12,7 @@ type Project struct {
TrackerURL string `gorm:"size:500" json:"tracker_url"`
IsActive bool `gorm:"default:true;index" json:"is_active"`
IsSystem bool `gorm:"default:false;index" json:"is_system"`
RentalEnabled bool `gorm:"default:false" json:"rental_enabled"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
}
+10
View File
@@ -0,0 +1,10 @@
package models
// QtSetting is the MariaDB-side model for qt_settings.
// The table is managed by the server-side agent; QF only reads from it.
type QtSetting struct {
Name string `gorm:"primaryKey;size:100" json:"name"`
Value string `gorm:"type:text" json:"value"`
}
func (QtSetting) TableName() string { return "qt_settings" }
-76
View File
@@ -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
}
-140
View File
@@ -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 -1
View File
@@ -104,7 +104,7 @@ func (r *ConfigurationRepository) ListAll(offset, limit int) ([]models.Configura
r.db.Model(&models.Configuration{}).Count(&total)
err := r.db.
Order("created_at DESC").
Order("created_at DESC, id DESC").
Offset(offset).
Limit(limit).
Find(&configs).Error
+1 -1
View File
@@ -157,7 +157,7 @@ func (r *PartnumberBookRepository) listCatalogItems(partnumbers localdb.LocalStr
query := r.db.Model(&localdb.LocalPartnumberBookItem{}).Where("partnumber IN ?", []string(partnumbers))
if search != "" {
trimmedSearch := "%" + search + "%"
query = query.Where("partnumber LIKE ? OR lots_json LIKE ? OR description LIKE ?", trimmedSearch, trimmedSearch, trimmedSearch)
query = query.Where("partnumber LIKE ? OR CAST(lots_json AS TEXT) LIKE ? OR description LIKE ?", trimmedSearch, trimmedSearch, trimmedSearch)
}
var total int64
+14 -10
View File
@@ -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
+1 -1
View File
@@ -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)
+6
View File
@@ -23,6 +23,11 @@ func (r *ProjectRepository) Update(project *models.Project) error {
}
func (r *ProjectRepository) UpsertByUUID(project *models.Project) error {
// Clear the client-side primary key so the upsert is driven purely by the
// uuid unique constraint. Passing a non-zero ID can trigger ON DUPLICATE KEY
// on the primary key of an unrelated row, leaving uuid unchanged and causing
// the follow-up SELECT to return ErrRecordNotFound.
project.ID = 0
if err := r.db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "uuid"}},
DoUpdates: clause.AssignmentColumns([]string{
@@ -33,6 +38,7 @@ func (r *ProjectRepository) UpsertByUUID(project *models.Project) error {
"tracker_url",
"is_active",
"is_system",
"rental_enabled",
"updated_at",
}),
}).Create(project).Error; err != nil {
-393
View File
@@ -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
}
+6 -212
View File
@@ -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 -609
View File
@@ -2,11 +2,8 @@ package services
import (
"errors"
"time"
"git.mchus.pro/mchus/quoteforge/internal/models"
"git.mchus.pro/mchus/quoteforge/internal/repository"
"github.com/google/uuid"
)
var (
@@ -14,37 +11,13 @@ var (
ErrConfigForbidden = errors.New("access to configuration forbidden")
)
// ConfigurationGetter is an interface for services that can retrieve configurations
// Used by handlers to work with both ConfigurationService and LocalConfigurationService
// ConfigurationGetter is an interface for services that can retrieve configurations.
// Used by handlers to work with LocalConfigurationService.
type ConfigurationGetter interface {
GetByUUID(uuid string, ownerUsername string) (*models.Configuration, error)
GetByUUIDNoAuth(uuid string) (*models.Configuration, error)
}
type ConfigurationService struct {
configRepo *repository.ConfigurationRepository
projectRepo *repository.ProjectRepository
componentRepo *repository.ComponentRepository
pricelistRepo *repository.PricelistRepository
quoteService *QuoteService
}
func NewConfigurationService(
configRepo *repository.ConfigurationRepository,
projectRepo *repository.ProjectRepository,
componentRepo *repository.ComponentRepository,
pricelistRepo *repository.PricelistRepository,
quoteService *QuoteService,
) *ConfigurationService {
return &ConfigurationService{
configRepo: configRepo,
projectRepo: projectRepo,
componentRepo: componentRepo,
pricelistRepo: pricelistRepo,
quoteService: quoteService,
}
}
type CreateConfigRequest struct {
Name string `json:"name"`
Items models.ConfigItems `json:"items"`
@@ -70,583 +43,3 @@ type ArticlePreviewRequest struct {
SupportCode string `json:"support_code,omitempty"`
PricelistID *uint `json:"pricelist_id,omitempty"`
}
func (s *ConfigurationService) Create(ownerUsername string, req *CreateConfigRequest) (*models.Configuration, error) {
projectUUID, err := s.resolveProjectUUID(ownerUsername, req.ProjectUUID)
if err != nil {
return nil, err
}
pricelistID, err := s.resolvePricelistID(req.PricelistID)
if err != nil {
return nil, err
}
total := req.Items.Total()
// If server count is greater than 1, multiply the total by server count
if req.ServerCount > 1 {
total *= float64(req.ServerCount)
}
config := &models.Configuration{
UUID: uuid.New().String(),
OwnerUsername: ownerUsername,
ProjectUUID: projectUUID,
Name: req.Name,
Items: req.Items,
TotalPrice: &total,
CustomPrice: req.CustomPrice,
Notes: req.Notes,
IsTemplate: req.IsTemplate,
ServerCount: req.ServerCount,
ServerModel: req.ServerModel,
SupportCode: req.SupportCode,
Article: req.Article,
PricelistID: pricelistID,
WarehousePricelistID: req.WarehousePricelistID,
CompetitorPricelistID: req.CompetitorPricelistID,
ConfigType: req.ConfigType,
DisablePriceRefresh: req.DisablePriceRefresh,
OnlyInStock: req.OnlyInStock,
}
if config.ConfigType == "" {
config.ConfigType = "server"
}
if err := s.configRepo.Create(config); err != nil {
return nil, err
}
return config, nil
}
func (s *ConfigurationService) GetByUUID(uuid string, ownerUsername string) (*models.Configuration, error) {
config, err := s.configRepo.GetByUUID(uuid)
if err != nil {
return nil, ErrConfigNotFound
}
// Allow access if user owns config or it's a template
if !s.isOwner(config, ownerUsername) && !config.IsTemplate {
return nil, ErrConfigForbidden
}
return config, nil
}
func (s *ConfigurationService) Update(uuid string, ownerUsername string, req *CreateConfigRequest) (*models.Configuration, error) {
config, err := s.configRepo.GetByUUID(uuid)
if err != nil {
return nil, ErrConfigNotFound
}
if !s.isOwner(config, ownerUsername) {
return nil, ErrConfigForbidden
}
projectUUID, err := s.resolveProjectUUID(ownerUsername, req.ProjectUUID)
if err != nil {
return nil, err
}
pricelistID, err := s.resolvePricelistID(req.PricelistID)
if err != nil {
return nil, err
}
total := req.Items.Total()
// If server count is greater than 1, multiply the total by server count
if req.ServerCount > 1 {
total *= float64(req.ServerCount)
}
config.Name = req.Name
config.ProjectUUID = projectUUID
config.Items = req.Items
config.TotalPrice = &total
config.CustomPrice = req.CustomPrice
config.Notes = req.Notes
config.IsTemplate = req.IsTemplate
config.ServerCount = req.ServerCount
config.ServerModel = req.ServerModel
config.SupportCode = req.SupportCode
config.Article = req.Article
config.PricelistID = pricelistID
config.WarehousePricelistID = req.WarehousePricelistID
config.CompetitorPricelistID = req.CompetitorPricelistID
config.DisablePriceRefresh = req.DisablePriceRefresh
config.OnlyInStock = req.OnlyInStock
if err := s.configRepo.Update(config); err != nil {
return nil, err
}
return config, nil
}
func (s *ConfigurationService) Delete(uuid string, ownerUsername string) error {
config, err := s.configRepo.GetByUUID(uuid)
if err != nil {
return ErrConfigNotFound
}
if !s.isOwner(config, ownerUsername) {
return ErrConfigForbidden
}
return s.configRepo.Delete(config.ID)
}
func (s *ConfigurationService) Rename(uuid string, ownerUsername string, newName string) (*models.Configuration, error) {
config, err := s.configRepo.GetByUUID(uuid)
if err != nil {
return nil, ErrConfigNotFound
}
if !s.isOwner(config, ownerUsername) {
return nil, ErrConfigForbidden
}
config.Name = newName
if err := s.configRepo.Update(config); err != nil {
return nil, err
}
return config, nil
}
func (s *ConfigurationService) Clone(configUUID string, ownerUsername string, newName string) (*models.Configuration, error) {
return s.CloneToProject(configUUID, ownerUsername, newName, nil)
}
func (s *ConfigurationService) CloneToProject(configUUID string, ownerUsername string, newName string, projectUUID *string) (*models.Configuration, error) {
original, err := s.GetByUUID(configUUID, ownerUsername)
if err != nil {
return nil, err
}
resolvedProjectUUID := original.ProjectUUID
if projectUUID != nil {
resolvedProjectUUID, err = s.resolveProjectUUID(ownerUsername, projectUUID)
if err != nil {
return nil, err
}
}
// Create copy with new UUID and name
total := original.Items.Total()
// If server count is greater than 1, multiply the total by server count
if original.ServerCount > 1 {
total *= float64(original.ServerCount)
}
clone := &models.Configuration{
UUID: uuid.New().String(),
OwnerUsername: ownerUsername,
ProjectUUID: resolvedProjectUUID,
Name: newName,
Items: original.Items,
TotalPrice: &total,
CustomPrice: original.CustomPrice,
Notes: original.Notes,
IsTemplate: false, // Clone is never a template
ServerCount: original.ServerCount,
ServerModel: original.ServerModel,
SupportCode: original.SupportCode,
Article: original.Article,
PricelistID: original.PricelistID,
WarehousePricelistID: original.WarehousePricelistID,
CompetitorPricelistID: original.CompetitorPricelistID,
DisablePriceRefresh: original.DisablePriceRefresh,
OnlyInStock: original.OnlyInStock,
}
if err := s.configRepo.Create(clone); err != nil {
return nil, err
}
return clone, nil
}
func (s *ConfigurationService) ListByUser(ownerUsername string, page, perPage int) ([]models.Configuration, int64, error) {
if page < 1 {
page = 1
}
if perPage < 1 || perPage > 100 {
perPage = 20
}
offset := (page - 1) * perPage
return s.configRepo.ListByUser(ownerUsername, offset, perPage)
}
// ListAll returns all configurations without user filter (for use when auth is disabled)
func (s *ConfigurationService) ListAll(page, perPage int) ([]models.Configuration, int64, error) {
if page < 1 {
page = 1
}
if perPage < 1 || perPage > 100 {
perPage = 20
}
offset := (page - 1) * perPage
return s.configRepo.ListAll(offset, perPage)
}
// GetByUUIDNoAuth returns configuration without ownership check (for use when auth is disabled)
func (s *ConfigurationService) GetByUUIDNoAuth(uuid string) (*models.Configuration, error) {
config, err := s.configRepo.GetByUUID(uuid)
if err != nil {
return nil, ErrConfigNotFound
}
return config, nil
}
// UpdateNoAuth updates configuration without ownership check
func (s *ConfigurationService) UpdateNoAuth(uuid string, req *CreateConfigRequest) (*models.Configuration, error) {
config, err := s.configRepo.GetByUUID(uuid)
if err != nil {
return nil, ErrConfigNotFound
}
projectUUID, err := s.resolveProjectUUID(config.OwnerUsername, req.ProjectUUID)
if err != nil {
return nil, err
}
pricelistID, err := s.resolvePricelistID(req.PricelistID)
if err != nil {
return nil, err
}
total := req.Items.Total()
if req.ServerCount > 1 {
total *= float64(req.ServerCount)
}
config.Name = req.Name
config.ProjectUUID = projectUUID
config.Items = req.Items
config.TotalPrice = &total
config.CustomPrice = req.CustomPrice
config.Notes = req.Notes
config.IsTemplate = req.IsTemplate
config.ServerCount = req.ServerCount
config.ServerModel = req.ServerModel
config.SupportCode = req.SupportCode
config.Article = req.Article
config.PricelistID = pricelistID
config.WarehousePricelistID = req.WarehousePricelistID
config.CompetitorPricelistID = req.CompetitorPricelistID
config.DisablePriceRefresh = req.DisablePriceRefresh
config.OnlyInStock = req.OnlyInStock
if err := s.configRepo.Update(config); err != nil {
return nil, err
}
return config, nil
}
// DeleteNoAuth deletes configuration without ownership check
func (s *ConfigurationService) DeleteNoAuth(uuid string) error {
config, err := s.configRepo.GetByUUID(uuid)
if err != nil {
return ErrConfigNotFound
}
return s.configRepo.Delete(config.ID)
}
// RenameNoAuth renames configuration without ownership check
func (s *ConfigurationService) RenameNoAuth(uuid string, newName string) (*models.Configuration, error) {
config, err := s.configRepo.GetByUUID(uuid)
if err != nil {
return nil, ErrConfigNotFound
}
config.Name = newName
if err := s.configRepo.Update(config); err != nil {
return nil, err
}
return config, nil
}
// CloneNoAuth clones configuration without ownership check
func (s *ConfigurationService) CloneNoAuth(configUUID string, newName string, ownerUsername string) (*models.Configuration, error) {
return s.CloneNoAuthToProject(configUUID, newName, ownerUsername, nil)
}
func (s *ConfigurationService) CloneNoAuthToProject(configUUID string, newName string, ownerUsername string, projectUUID *string) (*models.Configuration, error) {
original, err := s.configRepo.GetByUUID(configUUID)
if err != nil {
return nil, ErrConfigNotFound
}
resolvedProjectUUID := original.ProjectUUID
if projectUUID != nil {
resolvedProjectUUID, err = s.resolveProjectUUID(ownerUsername, projectUUID)
if err != nil {
return nil, err
}
}
total := original.Items.Total()
if original.ServerCount > 1 {
total *= float64(original.ServerCount)
}
clone := &models.Configuration{
UUID: uuid.New().String(),
OwnerUsername: ownerUsername,
ProjectUUID: resolvedProjectUUID,
Name: newName,
Items: original.Items,
TotalPrice: &total,
CustomPrice: original.CustomPrice,
Notes: original.Notes,
IsTemplate: false,
ServerCount: original.ServerCount,
PricelistID: original.PricelistID,
OnlyInStock: original.OnlyInStock,
}
if err := s.configRepo.Create(clone); err != nil {
return nil, err
}
return clone, nil
}
func (s *ConfigurationService) resolveProjectUUID(ownerUsername string, projectUUID *string) (*string, error) {
_ = ownerUsername
if s.projectRepo == nil {
return projectUUID, nil
}
if projectUUID == nil || *projectUUID == "" {
return nil, nil
}
project, err := s.projectRepo.GetByUUID(*projectUUID)
if err != nil {
return nil, ErrProjectNotFound
}
if !project.IsActive {
return nil, errors.New("project is archived")
}
return &project.UUID, nil
}
func (s *ConfigurationService) resolvePricelistID(pricelistID *uint) (*uint, error) {
if s.pricelistRepo == nil {
return pricelistID, nil
}
if pricelistID != nil && *pricelistID > 0 {
if _, err := s.pricelistRepo.GetByID(*pricelistID); err != nil {
return nil, err
}
return pricelistID, nil
}
latest, err := s.pricelistRepo.GetLatestActive()
if err != nil {
return nil, nil
}
return &latest.ID, nil
}
// RefreshPricesNoAuth refreshes prices without ownership check
func (s *ConfigurationService) RefreshPricesNoAuth(uuid string) (*models.Configuration, error) {
config, err := s.configRepo.GetByUUID(uuid)
if err != nil {
return nil, ErrConfigNotFound
}
var latestPricelistID *uint
if s.pricelistRepo != nil {
if pl, err := s.pricelistRepo.GetLatestActive(); err == nil {
latestPricelistID = &pl.ID
}
}
updatedItems := make(models.ConfigItems, len(config.Items))
for i, item := range config.Items {
if latestPricelistID != nil {
if price, err := s.pricelistRepo.GetPriceForLot(*latestPricelistID, item.LotName); err == nil && price > 0 {
updatedItems[i] = models.ConfigItem{
LotName: item.LotName,
Quantity: item.Quantity,
UnitPrice: price,
}
continue
}
}
if s.componentRepo == nil {
updatedItems[i] = item
continue
}
metadata, err := s.componentRepo.GetByLotName(item.LotName)
if err != nil || metadata.CurrentPrice == nil {
updatedItems[i] = item
continue
}
updatedItems[i] = models.ConfigItem{
LotName: item.LotName,
Quantity: item.Quantity,
UnitPrice: *metadata.CurrentPrice,
}
}
config.Items = updatedItems
total := updatedItems.Total()
if config.ServerCount > 1 {
total *= float64(config.ServerCount)
}
config.TotalPrice = &total
if latestPricelistID != nil {
config.PricelistID = latestPricelistID
}
now := time.Now()
config.PriceUpdatedAt = &now
if err := s.configRepo.Update(config); err != nil {
return nil, err
}
return config, nil
}
func (s *ConfigurationService) ListTemplates(page, perPage int) ([]models.Configuration, int64, error) {
if page < 1 {
page = 1
}
if perPage < 1 || perPage > 100 {
perPage = 20
}
offset := (page - 1) * perPage
return s.configRepo.ListTemplates(offset, perPage)
}
// RefreshPrices updates all component prices in the configuration with current prices
func (s *ConfigurationService) RefreshPrices(uuid string, ownerUsername string) (*models.Configuration, error) {
config, err := s.configRepo.GetByUUID(uuid)
if err != nil {
return nil, ErrConfigNotFound
}
if !s.isOwner(config, ownerUsername) {
return nil, ErrConfigForbidden
}
var latestPricelistID *uint
if s.pricelistRepo != nil {
if pl, err := s.pricelistRepo.GetLatestActive(); err == nil {
latestPricelistID = &pl.ID
}
}
// Update prices for all items
updatedItems := make(models.ConfigItems, len(config.Items))
for i, item := range config.Items {
if latestPricelistID != nil {
if price, err := s.pricelistRepo.GetPriceForLot(*latestPricelistID, item.LotName); err == nil && price > 0 {
updatedItems[i] = models.ConfigItem{
LotName: item.LotName,
Quantity: item.Quantity,
UnitPrice: price,
}
continue
}
}
// Get current component price
if s.componentRepo == nil {
updatedItems[i] = item
continue
}
metadata, err := s.componentRepo.GetByLotName(item.LotName)
if err != nil || metadata.CurrentPrice == nil {
// Keep original item if component not found or no price available
updatedItems[i] = item
continue
}
// Update item with current price
updatedItems[i] = models.ConfigItem{
LotName: item.LotName,
Quantity: item.Quantity,
UnitPrice: *metadata.CurrentPrice,
}
}
// Update configuration
config.Items = updatedItems
total := updatedItems.Total()
// If server count is greater than 1, multiply the total by server count
if config.ServerCount > 1 {
total *= float64(config.ServerCount)
}
config.TotalPrice = &total
if latestPricelistID != nil {
config.PricelistID = latestPricelistID
}
// Set price update timestamp
now := time.Now()
config.PriceUpdatedAt = &now
if err := s.configRepo.Update(config); err != nil {
return nil, err
}
return config, nil
}
func (s *ConfigurationService) isOwner(config *models.Configuration, ownerUsername string) bool {
if config == nil || ownerUsername == "" {
return false
}
return config.OwnerUsername == ownerUsername
}
// // Export configuration as JSON
// type ConfigExport struct {
// Name string `json:"name"`
// Notes string `json:"notes"`
// Items models.ConfigItems `json:"items"`
// }
//
// func (s *ConfigurationService) ExportJSON(uuid string, userID uint) ([]byte, error) {
// config, err := s.GetByUUID(uuid, userID)
// if err != nil {
// return nil, err
// }
//
// export := ConfigExport{
// Name: config.Name,
// Notes: config.Notes,
// Items: config.Items,
// }
//
// return json.MarshalIndent(export, "", " ")
// }
//
// func (s *ConfigurationService) ImportJSON(userID uint, data []byte) (*models.Configuration, error) {
// var export ConfigExport
// if err := json.Unmarshal(data, &export); err != nil {
// return nil, err
// }
//
// req := &CreateConfigRequest{
// Name: export.Name,
// Notes: export.Notes,
// Items: export.Items,
// }
//
// return s.Create(userID, req)
// }
+235 -103
View File
@@ -53,20 +53,26 @@ type ProjectExportData struct {
}
type ProjectPricingExportOptions struct {
IncludeLOT bool `json:"include_lot"`
IncludeBOM bool `json:"include_bom"`
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
IncludeLOT bool `json:"include_lot"`
IncludeBOM bool `json:"include_bom"`
IncludeEstimate bool `json:"include_estimate"`
IncludeStock bool `json:"include_stock"`
IncludeCompetitor bool `json:"include_competitor"`
Basis string `json:"basis"` // "fob" or "ddp"; empty defaults to "fob"
SaleMarkup float64 `json:"sale_markup"` // DDP uplift applied to Estimate only; 0 defaults to 1.3
ManualPrice *float64 `json:"manual_price"` // user-defined total price; distributed proportionally across rows
}
// defaultSaleMarkup mirrors PricingMarkup.DEFAULT_SALE_UPLIFT in web/templates/index.html.
// Keep both in sync; the frontend always sends an explicit value, this is a fallback for
// other API callers that omit sale_markup.
const defaultSaleMarkup = 1.3
func (o ProjectPricingExportOptions) saleMarkupFactor() float64 {
if o.SaleMarkup > 0 {
return o.SaleMarkup
}
return 1.3
return defaultSaleMarkup
}
func (o ProjectPricingExportOptions) isDDP() bool {
@@ -87,14 +93,18 @@ type ProjectPricingExportConfig struct {
}
type ProjectPricingExportRow struct {
LotDisplay string
VendorPN string
Description string
Quantity int
BOMTotal *float64
Estimate *float64
Stock *float64
Competitor *float64
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.
@@ -378,7 +388,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{}{}
}
@@ -388,71 +398,137 @@ func (s *ExportService) buildPricingExportBlock(cfg *models.Configuration, opts
description = componentDescriptions[rowMappings[0].LotName]
}
pricingRow := ProjectPricingExportRow{
LotDisplay: formatLotDisplay(rowMappings),
VendorPN: row.VendorPartnumber,
Description: description,
Quantity: exportPositiveInt(row.Quantity, 1),
BOMTotal: vendorRowTotal(row),
Estimate: computeMappingTotal(priceMap, rowMappings, row.Quantity, func(p pricingLevels) *float64 { return p.Estimate }),
Stock: computeMappingTotal(priceMap, rowMappings, row.Quantity, func(p pricingLevels) *float64 { return p.Stock }),
Competitor: computeMappingTotal(priceMap, rowMappings, row.Quantity, func(p pricingLevels) *float64 { return p.Competitor }),
if len(rowMappings) == 0 {
block.Rows = append(block.Rows, ProjectPricingExportRow{
LotDisplay: "н/д",
VendorPN: row.VendorPartnumber,
Description: description,
Quantity: exportPositiveInt(row.Quantity, 1),
BOMTotal: vendorRowTotal(row),
})
continue
}
// One export row per LOT mapping so that bundles (1 PN → N LOTs) appear
// as separate lines, matching the frontend pricing table layout.
pnQty := exportPositiveInt(row.Quantity, 1)
for i, mapping := range rowMappings {
lotQty := pnQty * mapping.QuantityPerPN
var bomTotal *float64
if i == 0 {
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 }),
EstimateWorld: priceMap[mapping.LotName].EstimateWorld,
StockWorld: priceMap[mapping.LotName].StockWorld,
CompetitorWorld: priceMap[mapping.LotName].CompetitorWorld,
})
}
block.Rows = append(block.Rows, pricingRow)
}
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)
}
return block, nil
}
catOrder := defaultCategoryOrder()
lotNames := make([]string, 0, len(cfg.Items))
for _, item := range cfg.Items {
if item.LotName != "" {
lotNames = append(lotNames, item.LotName)
}
}
itemCategories := s.resolveCategories(cfg.PricelistID, lotNames)
sortedItems := sortConfigItemsByCategoryMap(cfg.Items, catOrder, itemCategories)
for _, item := range sortedItems {
if item.LotName == "" {
continue
}
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)
}
return block, nil
}
func applyDDPMarkup(rows []ProjectPricingExportRow, factor float64) {
// 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 {
sorted := make(models.ConfigItems, len(items))
copy(sorted, items)
sort.SliceStable(sorted, func(i, j int) bool {
orderI, hasI := categoryDisplayOrder(catOrder, categories[sorted[i].LotName])
orderJ, hasJ := categoryDisplayOrder(catOrder, categories[sorted[j].LotName])
if hasI && hasJ {
return orderI < orderJ
}
return hasI && !hasJ
})
return sorted
}
// stockCompetitorMarkupFactor is the fixed DDP multiplier applied to Stock and
// Competitor columns, independent of the user-configurable estimate uplift.
// Mirrors PricingMarkup.STOCK_COMPETITOR_FIXED in web/templates/index.html.
const stockCompetitorMarkupFactor = 1.3
func applyDDPMarkup(rows []ProjectPricingExportRow, estimateFactor float64) {
for i := range rows {
rows[i].Estimate = scaleFloatPtr(rows[i].Estimate, factor)
rows[i].Stock = scaleFloatPtr(rows[i].Stock, factor)
rows[i].Competitor = scaleFloatPtr(rows[i].Competitor, factor)
rows[i].Estimate = scaleFloatPtr(rows[i].Estimate, estimateFactor)
rows[i].Stock = scaleFloatPtr(rows[i].Stock, stockCompetitorMarkupFactor)
rows[i].Competitor = scaleFloatPtr(rows[i].Competitor, stockCompetitorMarkupFactor)
}
}
@@ -531,9 +607,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 {
@@ -567,20 +646,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
}
@@ -603,12 +697,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{}
}
@@ -620,7 +733,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
}
@@ -643,28 +756,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)
@@ -675,25 +766,50 @@ 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
// 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.
func distributeManualPrice(rows []ProjectPricingExportRow, manualPrice float64) {
if manualPrice <= 0 || len(rows) == 0 {
return
}
total := 0.0
hasValue := false
qty := exportPositiveInt(pnQty, 1)
for _, mapping := range mappings {
price := selector(priceMap[mapping.LotName])
if price == nil || *price <= 0 {
totalEstimate := 0.0
for _, row := range rows {
if row.Estimate != nil && *row.Estimate > 0 {
totalEstimate += *row.Estimate
}
}
if totalEstimate <= 0 {
return
}
lastIdx := -1
for i, row := range rows {
if row.Estimate != nil && *row.Estimate > 0 {
lastIdx = i
}
}
assigned := 0.0
for i, row := range rows {
if row.Estimate == nil || *row.Estimate <= 0 {
continue
}
total += *price * float64(qty*mapping.QuantityPerPN)
hasValue = true
var share float64
if i == lastIdx {
share = math.Round((manualPrice-assigned)*100) / 100
} else {
share = math.Round((*row.Estimate/totalEstimate)*manualPrice*100) / 100
assigned += share
}
rows[i].ManualPrice = floatPtr(share)
}
if !hasValue {
}
func computeSingleLotTotal(priceMap map[string]pricingLevels, lotName string, qty int, selector func(pricingLevels) *float64) *float64 {
price := selector(priceMap[lotName])
if price == nil || *price <= 0 {
return nil
}
return floatPtr(total)
return floatPtr(*price * float64(qty))
}
func totalForUnitPrice(unitPrice *float64, quantity int) *float64 {
@@ -716,7 +832,7 @@ func estimateOnlyTotal(estimatePrice *float64, fallbackUnitPrice float64, quanti
}
func pricingCSVHeaders(opts ProjectPricingExportOptions) []string {
headers := make([]string, 0, 8)
headers := make([]string, 0, 9)
headers = append(headers, "Line Item")
if opts.IncludeLOT {
headers = append(headers, "LOT")
@@ -734,11 +850,15 @@ func pricingCSVHeaders(opts ProjectPricingExportOptions) []string {
if opts.IncludeCompetitor {
headers = append(headers, "Конкуренты")
}
if opts.ManualPrice != nil && *opts.ManualPrice > 0 {
headers = append(headers, "Ручная цена")
}
headers = append(headers, "Заглушка (world)")
return headers
}
func pricingCSVRow(row ProjectPricingExportRow, opts ProjectPricingExportOptions) []string {
record := make([]string, 0, 8)
record := make([]string, 0, 9)
record = append(record, "")
if opts.IncludeLOT {
record = append(record, emptyDash(row.LotDisplay))
@@ -760,11 +880,29 @@ func pricingCSVRow(row ProjectPricingExportRow, opts ProjectPricingExportOptions
if opts.IncludeCompetitor {
record = append(record, formatMoneyValue(row.Competitor))
}
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
}
func pricingConfigSummaryRow(cfg ProjectPricingExportConfig, opts ProjectPricingExportOptions) []string {
record := make([]string, 0, 8)
record := make([]string, 0, 9)
record = append(record, fmt.Sprintf("%d", cfg.Line))
if opts.IncludeLOT {
record = append(record, "")
@@ -786,19 +924,13 @@ func pricingConfigSummaryRow(cfg ProjectPricingExportConfig, opts ProjectPricing
if opts.IncludeCompetitor {
record = append(record, formatMoneyValue(sumPricingColumn(cfg.Rows, func(row ProjectPricingExportRow) *float64 { return row.Competitor })))
}
if opts.ManualPrice != nil && *opts.ManualPrice > 0 {
record = append(record, formatMoneyValue(opts.ManualPrice))
}
record = append(record, "")
return record
}
func formatLotDisplay(mappings []localdb.VendorSpecLotMapping) string {
switch len(mappings) {
case 0:
return "н/д"
case 1:
return mappings[0].LotName
default:
return fmt.Sprintf("%s +%d", mappings[0].LotName, len(mappings)-1)
}
}
func formatMoneyValue(value *float64) string {
if value == nil {
+126 -5
View File
@@ -71,7 +71,6 @@ func (s *LocalConfigurationService) Create(ownerUsername string, req *CreateConf
if strings.TrimSpace(req.ServerModel) != "" {
articleResult, articleErr := article.Build(s.localDB, req.Items, article.BuildOptions{
ServerModel: req.ServerModel,
SupportCode: req.SupportCode,
ServerPricelist: pricelistID,
})
if articleErr != nil {
@@ -169,7 +168,6 @@ func (s *LocalConfigurationService) Update(uuid string, ownerUsername string, re
if strings.TrimSpace(req.ServerModel) != "" {
articleResult, articleErr := article.Build(s.localDB, req.Items, article.BuildOptions{
ServerModel: req.ServerModel,
SupportCode: req.SupportCode,
ServerPricelist: pricelistID,
})
if articleErr != nil {
@@ -226,7 +224,6 @@ func (s *LocalConfigurationService) BuildArticlePreview(req *ArticlePreviewReque
}
return article.Build(s.localDB, req.Items, article.BuildOptions{
ServerModel: req.ServerModel,
SupportCode: req.SupportCode,
ServerPricelist: pricelistID,
})
}
@@ -423,6 +420,13 @@ func (s *LocalConfigurationService) RefreshPrices(uuid string, ownerUsername str
}
}
// Capture fingerprint of the current state before any mutations.
preRefreshFP, err := localdb.BuildConfigurationSpecPriceFingerprint(localCfg)
if err != nil {
return nil, fmt.Errorf("build pre-refresh fingerprint: %w", err)
}
preRefreshCfg := *localCfg
// Update prices for all items from pricelist
updatedItems := make(localdb.LocalConfigItems, len(localCfg.Items))
for i, item := range localCfg.Items {
@@ -462,6 +466,18 @@ func (s *LocalConfigurationService) RefreshPrices(uuid string, ownerUsername str
localCfg.UpdatedAt = now
localCfg.SyncStatus = "pending"
// Before saving the new prices, snapshot the pre-refresh state so the revision
// history shows a clear before/after for every price update.
postRefreshFP, err := localdb.BuildConfigurationSpecPriceFingerprint(localCfg)
if err != nil {
return nil, fmt.Errorf("build post-refresh fingerprint: %w", err)
}
if preRefreshFP != postRefreshFP {
if err := s.snapshotPreRefreshTx(&preRefreshCfg, ownerUsername); err != nil {
return nil, fmt.Errorf("snapshot pre-refresh state: %w", err)
}
}
cfg, err := s.saveWithVersionAndPending(localCfg, "update", ownerUsername)
if err != nil {
return nil, fmt.Errorf("refresh prices with version: %w", err)
@@ -515,7 +531,6 @@ func (s *LocalConfigurationService) UpdateNoAuth(uuid string, req *CreateConfigR
if strings.TrimSpace(req.ServerModel) != "" {
articleResult, articleErr := article.Build(s.localDB, req.Items, article.BuildOptions{
ServerModel: req.ServerModel,
SupportCode: req.SupportCode,
ServerPricelist: pricelistID,
})
if articleErr != nil {
@@ -820,6 +835,13 @@ func (s *LocalConfigurationService) RefreshPricesNoAuth(uuid string, pricelistSe
}
}
// Capture fingerprint of the current state before any mutations.
preRefreshFP, err := localdb.BuildConfigurationSpecPriceFingerprint(localCfg)
if err != nil {
return nil, fmt.Errorf("build pre-refresh fingerprint: %w", err)
}
preRefreshCfg := *localCfg
// Update prices for all items from pricelist
updatedItems := make(localdb.LocalConfigItems, len(localCfg.Items))
for i, item := range localCfg.Items {
@@ -859,6 +881,18 @@ func (s *LocalConfigurationService) RefreshPricesNoAuth(uuid string, pricelistSe
localCfg.UpdatedAt = now
localCfg.SyncStatus = "pending"
// Before saving the new prices, snapshot the pre-refresh state so the revision
// history shows a clear before/after for every price update.
postRefreshFP, err := localdb.BuildConfigurationSpecPriceFingerprint(localCfg)
if err != nil {
return nil, fmt.Errorf("build post-refresh fingerprint: %w", err)
}
if preRefreshFP != postRefreshFP {
if err := s.snapshotPreRefreshTx(&preRefreshCfg, ""); err != nil {
return nil, fmt.Errorf("snapshot pre-refresh state: %w", err)
}
}
cfg, err := s.saveWithVersionAndPending(localCfg, "update", "")
if err != nil {
return nil, fmt.Errorf("refresh prices without auth with version: %w", err)
@@ -866,6 +900,16 @@ func (s *LocalConfigurationService) RefreshPricesNoAuth(uuid string, pricelistSe
return cfg, nil
}
// SnapshotCurrentState creates a revision of the current configuration state without modifying it.
// Called before a client-side price refresh so the revision history has a clear before/after.
func (s *LocalConfigurationService) SnapshotCurrentState(uuid string) error {
localCfg, err := s.localDB.GetConfigurationByUUID(uuid)
if err != nil {
return ErrConfigNotFound
}
return s.snapshotPreRefreshTx(localCfg, "")
}
// UpdateServerCount updates server count and recalculates total price without creating a new version.
func (s *LocalConfigurationService) UpdateServerCount(configUUID string, serverCount int) (*models.Configuration, error) {
if serverCount < 1 {
@@ -1277,6 +1321,40 @@ func (s *LocalConfigurationService) UpdateVendorSpecNoAuth(uuid string, spec loc
return cfg, nil
}
// RentalUpdateRequest carries the editable fields of a configuration's
// Аренда (rental) tab. Persisted independently of the BOM/pricing tabs.
type RentalUpdateRequest struct {
Items []models.RentalItemCondition `json:"items"`
UpliftPercent float64 `json:"uplift_percent"`
}
// UpdateRentalNoAuth updates only the rental fields of a configuration without ownership check.
func (s *LocalConfigurationService) UpdateRentalNoAuth(uuid string, req *RentalUpdateRequest) (*models.Configuration, error) {
localCfg, err := s.localDB.GetConfigurationByUUID(uuid)
if err != nil {
return nil, ErrConfigNotFound
}
conditions := make(localdb.RentalItemConditions, 0, len(req.Items))
for _, item := range req.Items {
conditions = append(conditions, localdb.RentalItemCondition{
LotName: models.NormalizeLotName(item.LotName),
Condition: item.Condition,
})
}
localCfg.RentalItems = conditions
localCfg.RentalUpliftPercent = req.UpliftPercent
localCfg.UpdatedAt = time.Now()
localCfg.SyncStatus = "pending"
cfg, err := s.saveWithVersionAndPending(localCfg, "update", "")
if err != nil {
return nil, fmt.Errorf("update rental fields without auth with version: %w", err)
}
return cfg, nil
}
func (s *LocalConfigurationService) ApplyVendorSpecItemsNoAuth(uuid string, items localdb.LocalConfigItems) (*models.Configuration, error) {
localCfg, err := s.localDB.GetConfigurationByUUID(uuid)
if err != nil {
@@ -1432,12 +1510,25 @@ func (s *LocalConfigurationService) appendVersionTx(
localCfg *localdb.LocalConfiguration,
operation string,
createdBy string,
) (*localdb.LocalConfigurationVersion, error) {
return s.appendVersionTxNote(tx, localCfg, operation, createdBy, "")
}
func (s *LocalConfigurationService) appendVersionTxNote(
tx *gorm.DB,
localCfg *localdb.LocalConfiguration,
operation string,
createdBy string,
noteOverride string,
) (*localdb.LocalConfigurationVersion, error) {
snapshot, err := s.buildConfigurationSnapshot(localCfg)
if err != nil {
return nil, fmt.Errorf("build snapshot: %w", err)
}
changeNote := fmt.Sprintf("%s via local-first flow", operation)
if noteOverride != "" {
changeNote = noteOverride
}
var createdByPtr *string
if createdBy != "" {
@@ -1478,6 +1569,35 @@ func (s *LocalConfigurationService) appendVersionTx(
return nil, fmt.Errorf("%w: exceeded retries for %s", ErrVersionConflict, localCfg.UUID)
}
// snapshotPreRefreshTx creates a revision of the current configuration state before a price
// refresh so the history clearly shows what existed before prices were updated.
// Called only when prices are about to change (fingerprints differ).
func (s *LocalConfigurationService) snapshotPreRefreshTx(localCfg *localdb.LocalConfiguration, createdBy string) error {
return s.localDB.DB().Transaction(func(tx *gorm.DB) error {
var locked localdb.LocalConfiguration
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Where("uuid = ?", localCfg.UUID).
First(&locked).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrConfigNotFound
}
return fmt.Errorf("lock row for pre-refresh snapshot: %w", err)
}
version, err := s.appendVersionTxNote(tx, localCfg, "update", createdBy, "до обновления цен")
if err != nil {
return fmt.Errorf("append pre-refresh version: %w", err)
}
if err := tx.Model(&localdb.LocalConfiguration{}).
Where("uuid = ?", localCfg.UUID).
Update("current_version_id", version.ID).Error; err != nil {
return fmt.Errorf("set current_version_id for pre-refresh snapshot: %w", err)
}
return nil
})
}
func (s *LocalConfigurationService) buildConfigurationSnapshot(localCfg *localdb.LocalConfiguration) (string, error) {
return localdb.BuildConfigurationSnapshot(localCfg)
}
@@ -1723,7 +1843,8 @@ func (s *LocalConfigurationService) resolvePricelistID(pricelistID *uint) (*uint
}
}
}
return nil, fmt.Errorf("pricelist %d not available locally", *pricelistID)
// Pricelist not found even after sync — fall back to the latest active one.
slog.Warn("pricelist not available locally, falling back to latest active", "server_pricelist_id", *pricelistID)
}
latest, err := s.localDB.GetLatestLocalPricelist()
+47 -10
View File
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"net/url"
"regexp"
"strings"
"time"
@@ -16,14 +17,19 @@ import (
)
var (
ErrProjectNotFound = errors.New("project not found")
ErrProjectForbidden = errors.New("access to project forbidden")
ErrProjectCodeExists = errors.New("project code and variant already exist")
ErrCannotDeleteMainVariant = errors.New("cannot delete main variant")
ErrReservedMainVariant = errors.New("variant name 'main' is reserved")
ErrCannotRenameMainVariant = errors.New("cannot rename main variant")
ErrProjectNotFound = errors.New("project not found")
ErrProjectForbidden = errors.New("access to project forbidden")
ErrProjectCodeExists = errors.New("project code and variant already exist")
ErrCannotDeleteMainVariant = errors.New("cannot delete main variant")
ErrReservedMainVariant = errors.New("variant name 'main' is reserved")
ErrCannotRenameMainVariant = errors.New("cannot rename main variant")
ErrProjectCodeInvalidChars = errors.New("код опти содержит недопустимые символы (разрешены: буквы, цифры, дефис, точка, подчёркивание)")
ErrProjectVariantInvalidChars = errors.New("имя варианта содержит недопустимые символы (разрешены: буквы, цифры, дефис, точка, подчёркивание)")
)
// projectCodeRe allows only URL-path-safe characters so project codes can appear directly in URLs.
var projectCodeRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
type ProjectService struct {
localDB *localdb.LocalDB
}
@@ -40,10 +46,11 @@ type CreateProjectRequest struct {
}
type UpdateProjectRequest struct {
Code *string `json:"code,omitempty"`
Variant *string `json:"variant,omitempty"`
Name *string `json:"name,omitempty"`
TrackerURL *string `json:"tracker_url,omitempty"`
Code *string `json:"code,omitempty"`
Variant *string `json:"variant,omitempty"`
Name *string `json:"name,omitempty"`
TrackerURL *string `json:"tracker_url,omitempty"`
RentalEnabled *bool `json:"rental_enabled,omitempty"`
}
type ProjectConfigurationsResult struct {
@@ -64,6 +71,9 @@ func (s *ProjectService) Create(ownerUsername string, req *CreateProjectRequest)
if code == "" {
return nil, fmt.Errorf("project code is required")
}
if !projectCodeRe.MatchString(code) {
return nil, ErrProjectCodeInvalidChars
}
variant := strings.TrimSpace(req.Variant)
if err := validateProjectVariantName(variant); err != nil {
return nil, err
@@ -106,6 +116,9 @@ func (s *ProjectService) Update(projectUUID, ownerUsername string, req *UpdatePr
if code == "" {
return nil, fmt.Errorf("project code is required")
}
if !projectCodeRe.MatchString(code) {
return nil, ErrProjectCodeInvalidChars
}
localProject.Code = code
}
if req.Variant != nil {
@@ -136,6 +149,9 @@ func (s *ProjectService) Update(projectUUID, ownerUsername string, req *UpdatePr
} else if strings.TrimSpace(localProject.TrackerURL) == "" {
localProject.TrackerURL = normalizeProjectTrackerURL(localProject.Code, "")
}
if req.RentalEnabled != nil {
localProject.RentalEnabled = *req.RentalEnabled
}
localProject.UpdatedAt = time.Now()
localProject.SyncStatus = "pending"
if err := s.localDB.SaveProject(localProject); err != nil {
@@ -183,6 +199,9 @@ func validateProjectVariantName(variant string) error {
if normalizeProjectVariant(variant) == "main" {
return ErrReservedMainVariant
}
if variant != "" && !projectCodeRe.MatchString(variant) {
return ErrProjectVariantInvalidChars
}
return nil
}
@@ -282,6 +301,24 @@ func (s *ProjectService) GetByUUID(projectUUID, ownerUsername string) (*models.P
return localdb.LocalToProject(localProject), nil
}
// GetByCode finds the main variant of a project by its code (case-insensitive).
func (s *ProjectService) GetByCode(code string) (*models.Project, error) {
localProject, err := s.localDB.GetProjectByCode(code)
if err != nil {
return nil, ErrProjectNotFound
}
return localdb.LocalToProject(localProject), nil
}
// GetByCodeAndVariant finds a project by code + variant (both case-insensitive).
func (s *ProjectService) GetByCodeAndVariant(code, variant string) (*models.Project, error) {
localProject, err := s.localDB.GetProjectByCodeAndVariant(code, variant)
if err != nil {
return nil, ErrProjectNotFound
}
return localdb.LocalToProject(localProject), nil
}
func (s *ProjectService) ListConfigurations(projectUUID, ownerUsername, status string) (*ProjectConfigurationsResult, error) {
project, err := s.GetByUUID(projectUUID, ownerUsername)
if err != nil {
+66 -87
View File
@@ -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 {
+47 -2
View File
@@ -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{})
+212
View File
@@ -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
}
+61 -6
View File
@@ -1,20 +1,31 @@
package sync
import (
"encoding/json"
"fmt"
"log/slog"
"strings"
"time"
)
// SeenPartnumber represents an unresolved vendor partnumber to report.
type SeenPartnumber struct {
Partnumber string
Description string
Ignored bool
Partnumber string
Description string
Ignored bool
LotSuggestion []LotSuggestionEntry // optional; set when user manually mapped PN → LOT in UI
}
// LotSuggestionEntry is one suggested LOT mapping for a vendor partnumber.
// JSON shape mirrors qt_partnumber_book_items.lots_json: {"lot_name", "qty"}.
type LotSuggestionEntry struct {
LotName string `json:"lot_name"`
Qty int `json:"qty"`
}
// PushPartnumberSeen inserts unresolved vendor partnumbers into qt_vendor_partnumber_seen on MariaDB.
// Existing rows are left untouched: no updates to last_seen_at, is_ignored, or description.
// When LotSuggestion is provided the column is updated too; if the column does not exist yet
// (migration pending) the write is retried without it and a warning is logged — the app never panics.
func (s *Service) PushPartnumberSeen(items []SeenPartnumber) error {
if len(items) == 0 {
return nil
@@ -30,7 +41,43 @@ func (s *Service) PushPartnumberSeen(items []SeenPartnumber) error {
if item.Partnumber == "" {
continue
}
err := mariaDB.Exec(`
if len(item.LotSuggestion) > 0 {
suggJSON, marshalErr := json.Marshal(item.LotSuggestion)
if marshalErr != nil {
slog.Error("partnumber_seen: failed to marshal lot_suggestion, skipping suggestion",
"partnumber", item.Partnumber, "error", marshalErr)
suggJSON = nil
}
if suggJSON != nil {
err = mariaDB.Exec(`
INSERT INTO qt_vendor_partnumber_seen
(source_type, vendor, partnumber, description, is_ignored, last_seen_at, lot_suggestion)
VALUES
('manual', '', ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
lot_suggestion = VALUES(lot_suggestion),
last_seen_at = NOW(3)
`, item.Partnumber, item.Description, item.Ignored, now, string(suggJSON)).Error
if err == nil {
continue
}
// Column not yet migrated — fall through to insert without lot_suggestion.
if !isUnknownColumnError(err) {
slog.Error("partnumber_seen: failed to upsert with lot_suggestion",
"partnumber", item.Partnumber, "error", err)
continue
}
slog.Warn("partnumber_seen: lot_suggestion column missing (migration pending), inserting without it",
"partnumber", item.Partnumber)
}
}
// Insert without lot_suggestion (baseline behaviour or fallback).
err = mariaDB.Exec(`
INSERT INTO qt_vendor_partnumber_seen
(source_type, vendor, partnumber, description, is_ignored, last_seen_at)
VALUES
@@ -40,10 +87,18 @@ func (s *Service) PushPartnumberSeen(items []SeenPartnumber) error {
`, item.Partnumber, item.Description, item.Ignored, now).Error
if err != nil {
slog.Error("failed to insert partnumber_seen", "partnumber", item.Partnumber, "error", err)
// Continue with remaining items
}
}
slog.Info("partnumber_seen pushed to server", "count", len(items))
return nil
}
// isUnknownColumnError returns true when MariaDB reports that a column does not exist.
func isUnknownColumnError(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "unknown column") || strings.Contains(msg, "1054")
}
+15
View File
@@ -0,0 +1,15 @@
package sync
import "fmt"
// SyncQtSettings pulls qt_settings (tab_config, config_types, etc.) from
// MariaDB into the local cache so the configurator picks up server-driven
// category/tab changes without requiring a client rebuild.
func (s *Service) SyncQtSettings() error {
mariaDB, err := s.getDB()
if err != nil {
return fmt.Errorf("database not available: %w", err)
}
return s.localDB.SyncQtSettings(mariaDB)
}
+39 -5
View File
@@ -1,6 +1,7 @@
package sync
import (
"encoding/json"
"errors"
"fmt"
"log/slog"
@@ -248,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,
@@ -256,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),
@@ -276,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(),
@@ -284,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
}
@@ -320,14 +331,37 @@ func latestSyncErrorState(local *localdb.LocalDB) (*string, *string) {
return optionalString(strings.TrimSpace(guard.ReasonCode)), optionalString(strings.TrimSpace(guard.ReasonText))
}
var pending localdb.PendingChange
var errored []localdb.PendingChange
if err := local.DB().
Where("TRIM(COALESCE(last_error, '')) <> ''").
Order("id DESC").
First(&pending).Error; err == nil {
return optionalString("PENDING_CHANGE_ERROR"), optionalString(strings.TrimSpace(pending.LastError))
Limit(20).
Find(&errored).Error; err != nil || len(errored) == 0 {
return nil, nil
}
return nil, nil
type errorEntry struct {
Type string `json:"type"`
UUID string `json:"uuid"`
Op string `json:"op"`
Attempts int `json:"attempts"`
Error string `json:"error"`
}
entries := make([]errorEntry, 0, len(errored))
for _, ch := range errored {
entries = append(entries, errorEntry{
Type: ch.EntityType,
UUID: ch.EntityUUID,
Op: ch.Operation,
Attempts: ch.Attempts,
Error: strings.TrimSpace(ch.LastError),
})
}
detail, jsonErr := json.Marshal(entries)
if jsonErr != nil {
return optionalString("PENDING_CHANGE_ERROR"), optionalString(strings.TrimSpace(errored[0].LastError))
}
return optionalString("PENDING_CHANGE_ERROR"), optionalString(string(detail))
}
func optionalString(value string) *string {
+147 -46
View File
@@ -217,6 +217,7 @@ func (s *Service) ImportProjectsToLocal() (*ProjectImportResult, error) {
existing.TrackerURL = project.TrackerURL
existing.IsActive = project.IsActive
existing.IsSystem = project.IsSystem
existing.RentalEnabled = project.RentalEnabled
existing.CreatedAt = project.CreatedAt
existing.UpdatedAt = project.UpdatedAt
serverID := project.ID
@@ -322,6 +323,12 @@ func (s *Service) NeedSync() (bool, error) {
// SyncPricelists synchronizes all active pricelists from server to local SQLite
func (s *Service) SyncPricelists() (int, error) {
s.pricelistMu.Lock()
defer s.pricelistMu.Unlock()
return s.syncPricelists()
}
func (s *Service) syncPricelists() (int, error) {
slog.Info("starting pricelist sync")
plSyncStart := time.Now()
if _, err := s.EnsureReadinessForSync(); err != nil {
@@ -336,6 +343,12 @@ func (s *Service) SyncPricelists() (int, error) {
return 0, fmt.Errorf("database not available: %w", err)
}
defer func() {
if reportErr := s.reportClientSchemaState(mariaDB, time.Now().UTC()); reportErr != nil {
slog.Warn("failed to report client state after pricelist sync", "error", reportErr)
}
}()
// Create repository
pricelistRepo := repository.NewPricelistRepository(mariaDB)
@@ -392,6 +405,7 @@ func (s *Service) SyncPricelists() (int, error) {
CreatedAt: pl.CreatedAt,
SyncedAt: time.Now(),
IsUsed: false,
IsActive: true,
}
itemCount, err := s.syncNewPricelistSnapshot(localPL)
@@ -414,6 +428,12 @@ func (s *Service) SyncPricelists() (int, error) {
slog.Info("deleted stale local pricelists", "deleted", removed)
}
// Mirror server-side deactivations: any local pricelist not in the current active set
// is marked is_active=false so offline lookups skip it.
if err := s.localDB.DeactivateLocalPricelistsNotIn(serverPricelistIDs); err != nil {
slog.Warn("failed to deactivate stale local pricelists", "error", err)
}
// Backfill lot_category for used pricelists (older local caches may miss the column values).
s.backfillUsedPricelistItemCategories(pricelistRepo, serverPricelistIDs)
@@ -611,6 +631,56 @@ func (s *Service) backfillUsedPricelistItemCategories(pricelistRepo *repository.
}
}
// ListActiveViewersByConfigUUIDs returns a map of configUUID → []username for users
// who currently have those configs open (based on the last two sync cycles).
func (s *Service) ListActiveViewersByConfigUUIDs(uuids []string) (map[string][]string, error) {
if len(uuids) == 0 {
return map[string][]string{}, nil
}
mariaDB, err := s.getDB()
if err != nil || mariaDB == nil {
return map[string][]string{}, nil
}
selfUsername := strings.ToLower(strings.TrimSpace(s.localDB.GetDBUser()))
type row struct {
Username string `gorm:"column:username"`
OpenConfigJSON string `gorm:"column:open_config_uuids"`
}
var rows []row
if err := mariaDB.Raw(`
SELECT username, open_config_uuids
FROM qt_client_schema_state
WHERE open_config_uuids IS NOT NULL
AND open_config_uuids != '[]'
AND last_checked_at > NOW() - INTERVAL 10 MINUTE
`).Scan(&rows).Error; err != nil {
return map[string][]string{}, nil
}
wantSet := make(map[string]struct{}, len(uuids))
for _, u := range uuids {
wantSet[u] = struct{}{}
}
result := make(map[string][]string)
for _, r := range rows {
if strings.ToLower(strings.TrimSpace(r.Username)) == selfUsername {
continue
}
var openUUIDs []string
if err := json.Unmarshal([]byte(r.OpenConfigJSON), &openUUIDs); err != nil {
continue
}
for _, ou := range openUUIDs {
if _, ok := wantSet[ou]; ok {
result[ou] = append(result[ou], r.Username)
}
}
}
return result, nil
}
// ListUserSyncStatuses returns users who have recorded a client schema state check.
func (s *Service) ListUserSyncStatuses(onlineThreshold time.Duration) ([]UserSyncStatus, error) {
mariaDB, err := s.getDB()
@@ -764,9 +834,16 @@ func (s *Service) fetchServerPricelistItems(serverPricelistID uint) ([]localdb.L
return nil, fmt.Errorf("getting server pricelist items: %w", err)
}
localItems := make([]localdb.LocalPricelistItem, len(serverItems))
for i, item := range serverItems {
localItems[i] = *localdb.PricelistItemToLocal(&item, 0)
seen := make(map[string]struct{}, len(serverItems))
localItems := make([]localdb.LocalPricelistItem, 0, len(serverItems))
for i := range serverItems {
lotName := serverItems[i].LotName
if _, dup := seen[lotName]; dup {
slog.Warn("duplicate lot_name in server pricelist, skipping", "pricelist_id", serverPricelistID, "lot_name", lotName)
continue
}
seen[lotName] = struct{}{}
localItems = append(localItems, *localdb.PricelistItemToLocal(&serverItems[i], 0))
}
return localItems, nil
@@ -843,7 +920,7 @@ func (s *Service) SyncPricelistsIfNeeded() error {
}
slog.Info("new pricelists detected, syncing...")
_, err = s.SyncPricelists()
_, err = s.syncPricelists()
if err != nil {
return fmt.Errorf("syncing pricelists: %w", err)
}
@@ -851,6 +928,11 @@ func (s *Service) SyncPricelistsIfNeeded() error {
return nil
}
// maxPendingChangeAttempts is the number of failed attempts after which a pending change
// is considered unrecoverable and removed from the queue. Applies only to changes that
// fail with a non-transient error (e.g. corrupt payload, unknown operation).
const maxPendingChangeAttempts = 20
// PushPendingChanges pushes all pending changes to the server
func (s *Service) PushPendingChanges() (int, error) {
if _, err := s.EnsureReadinessForSync(); err != nil {
@@ -864,6 +946,14 @@ func (s *Service) PushPendingChanges() (int, error) {
slog.Info("purged orphan configuration pending changes", "removed", removed)
}
// Auto-repair locally-fixable problems (e.g. stale project references)
// before attempting to push, so that repaired changes succeed on this cycle.
if repaired, _, repairErr := s.localDB.RepairPendingChanges(); repairErr != nil {
slog.Warn("auto-repair of errored pending changes failed", "error", repairErr)
} else if repaired > 0 {
slog.Info("auto-repaired errored pending changes", "repaired", repaired)
}
changes, err := s.localDB.GetPendingChanges()
if err != nil {
return 0, fmt.Errorf("getting pending changes: %w", err)
@@ -875,7 +965,10 @@ func (s *Service) PushPendingChanges() (int, error) {
}
slog.Info("pushing pending changes", "count", len(changes))
pushStart := time.Now()
pushed := 0
failed := 0
var firstErr string
var syncedIDs []int64
sortedChanges := prioritizeProjectChanges(changes)
@@ -884,8 +977,18 @@ func (s *Service) PushPendingChanges() (int, error) {
if err != nil {
s.markConnectionBroken(err)
slog.Warn("failed to push change", "id", change.ID, "type", change.EntityType, "operation", change.Operation, "error", err)
// Increment attempts
newAttempts := change.Attempts + 1
s.localDB.IncrementPendingChangeAttempts(change.ID, err.Error())
if firstErr == "" {
firstErr = err.Error()
}
failed++
if newAttempts >= maxPendingChangeAttempts {
slog.Error("abandoning pending change after max attempts",
"id", change.ID, "type", change.EntityType, "op", change.Operation,
"attempts", newAttempts, "last_error", err.Error())
syncedIDs = append(syncedIDs, change.ID)
}
continue
}
@@ -900,7 +1003,13 @@ func (s *Service) PushPendingChanges() (int, error) {
}
}
slog.Info("pending changes pushed", "pushed", pushed, "failed", len(changes)-pushed)
if failed > 0 {
s.localDB.AppendSyncLog("changes", "error", firstErr, pushed, pushStart, time.Since(pushStart).Milliseconds())
} else {
s.localDB.AppendSyncLog("changes", "ok", "", pushed, pushStart, time.Since(pushStart).Milliseconds())
}
slog.Info("pending changes pushed", "pushed", pushed, "failed", failed)
return pushed, nil
}
@@ -912,7 +1021,11 @@ func (s *Service) pushSingleChange(change *localdb.PendingChange) error {
case "configuration":
return s.pushConfigurationChange(change)
default:
return fmt.Errorf("unknown entity type: %s", change.EntityType)
// Unknown entity type: this change was queued by a newer or different build
// and cannot be processed. Remove it from the queue.
slog.Warn("dropping pending change with unknown entity type",
"id", change.ID, "type", change.EntityType, "op", change.Operation)
return nil
}
}
@@ -1045,7 +1158,10 @@ func (s *Service) pushConfigurationChange(change *localdb.PendingChange) error {
case "delete":
return s.pushConfigurationDelete(change)
default:
return fmt.Errorf("unknown operation: %s", change.Operation)
// Unknown operation: queued by a newer or different build. Drop from queue.
slog.Warn("dropping pending change with unknown operation",
"id", change.ID, "type", change.EntityType, "op", change.Operation)
return nil
}
}
@@ -1245,24 +1361,30 @@ func (s *Service) ensureConfigurationProject(mariaDB *gorm.DB, cfg *models.Confi
localProject, localErr := s.localDB.GetProjectByUUID(*cfg.ProjectUUID)
if localErr != nil {
return err
// Project not found locally either: stale reference (project was deleted).
// Fall through to system project so this configuration is not stuck forever.
slog.Warn("configuration references missing project, assigning to system project",
"cfg_uuid", cfg.UUID,
"project_uuid", *cfg.ProjectUUID,
)
} else {
modelProject := localdb.LocalToProject(localProject)
if modelProject.OwnerUsername == "" {
modelProject.OwnerUsername = cfg.OwnerUsername
}
if createErr := projectRepo.UpsertByUUID(modelProject); createErr != nil {
return createErr
}
if modelProject.ID > 0 {
serverID := modelProject.ID
localProject.ServerID = &serverID
localProject.SyncStatus = "synced"
now := time.Now()
localProject.SyncedAt = &now
_ = s.localDB.SaveProjectPreservingUpdatedAt(localProject)
}
return nil
}
modelProject := localdb.LocalToProject(localProject)
if modelProject.OwnerUsername == "" {
modelProject.OwnerUsername = cfg.OwnerUsername
}
if createErr := projectRepo.UpsertByUUID(modelProject); createErr != nil {
return createErr
}
if modelProject.ID > 0 {
serverID := modelProject.ID
localProject.ServerID = &serverID
localProject.SyncStatus = "synced"
now := time.Now()
localProject.SyncedAt = &now
_ = s.localDB.SaveProjectPreservingUpdatedAt(localProject)
}
return nil
}
systemProject := &models.Project{}
@@ -1574,24 +1696,3 @@ func (s *Service) getConnectionStatus() db.ConnectionStatus {
return s.connMgr.GetStatus()
}
// SyncComponentsIfEmpty syncs components from MariaDB when local_components is empty.
// Used by the background worker on first run to populate the catalog for new users.
func (s *Service) SyncComponentsIfEmpty() error {
if s.localDB.CountComponents() > 0 {
return nil
}
mariaDB, err := s.getDB()
if err != nil {
_ = s.localDB.SetComponentSyncResult("error", err.Error(), time.Now())
return err
}
result, err := s.localDB.SyncComponents(mariaDB)
now := time.Now()
if err != nil {
_ = s.localDB.SetComponentSyncResult("error", err.Error(), now)
return err
}
_ = s.localDB.SetComponentSyncResult("ok", "", now)
slog.Info("background sync: initial component sync completed", "synced", result.TotalSynced)
return nil
}
@@ -16,7 +16,6 @@ func TestSyncPricelists_BackfillsLotCategoryForUsedPricelistItems(t *testing.T)
if err := serverDB.AutoMigrate(
&models.Pricelist{},
&models.PricelistItem{},
&models.Lot{},
); err != nil {
t.Fatalf("migrate server tables: %v", err)
}
@@ -33,14 +32,10 @@ func TestSyncPricelists_BackfillsLotCategoryForUsedPricelistItems(t *testing.T)
t.Fatalf("create server pricelist: %v", err)
}
if err := serverDB.Create(&models.PricelistItem{
PricelistID: serverPL.ID,
LotName: "CPU_A",
LotCategory: "CPU",
Price: 10,
PriceMethod: "",
MetaPrices: "",
ManualPrice: nil,
AvailableQty: nil,
PricelistID: serverPL.ID,
LotName: "CPU_A",
LotCategory: "CPU",
Price: 10,
}).Error; err != nil {
t.Fatalf("create server pricelist item: %v", err)
}
@@ -439,7 +439,6 @@ func newServerDBForSyncTest(t *testing.T) *gorm.DB {
&models.Configuration{},
&models.Pricelist{},
&models.PricelistItem{},
&models.Lot{},
); err != nil {
t.Fatalf("migrate server test schema: %v", err)
}
+10 -5
View File
@@ -80,11 +80,6 @@ func (w *Worker) runSync() {
return
}
// Populate component catalog on first run (empty local_components)
if err := w.service.SyncComponentsIfEmpty(); err != nil {
w.logger.Warn("background sync: initial component sync failed", "error", err)
}
// Push pending changes first
pushed, err := w.service.PushPendingChanges()
if err != nil {
@@ -100,5 +95,15 @@ func (w *Worker) runSync() {
return
}
// Pull partnumber books together with pricelists
if _, err := w.service.PullPartnumberBooks(); err != nil {
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")
}
+219 -8
View File
@@ -133,8 +133,12 @@ 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):
workspace, err = parseNxBOM(data, filepath.Base(sourceFileName))
case IsTextBOM(data):
workspace, err = parseTextBOM(data, filepath.Base(sourceFileName))
default:
@@ -163,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
}
@@ -171,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)
}
@@ -217,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 {
@@ -240,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)
@@ -255,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{}
}
@@ -274,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))
@@ -683,6 +687,93 @@ func parseInspurBOM(data []byte, sourceFileName string) (*importedWorkspace, err
}, nil
}
// nxBOMItemLine matches a quantity-first BOM line: "<qty>x <description>"
// where the quantity prefix is digits followed immediately by "x" (case-insensitive).
// Parentheses, commas, and hyphens inside the description are preserved.
var nxBOMItemLine = regexp.MustCompile(`(?i)^(\d+)[xX]\s+(.+\S)\s*$`)
// IsNxBOM reports whether data looks like a quantity-first "Nx" BOM where each
// item line begins with "<qty>x <description>" (e.g. "2x Intel Xeon 8570 ...").
func IsNxBOM(data []byte) bool {
for _, raw := range strings.Split(string(data), "\n") {
if nxBOMItemLine.MatchString(strings.TrimSpace(raw)) {
return true
}
}
return false
}
// parseNxBOM parses a quantity-first "Nx" BOM into a single configuration.
// An optional header line ending with ", в составе:" supplies server_model and name.
// Each "<qty>x <description>" line becomes one vendor spec row; description is stored
// as both vendor_partnumber and description so rows resolve through the active
// partnumber book when matched and otherwise stay unresolved and editable in the UI.
func parseNxBOM(data []byte, sourceFileName string) (*importedWorkspace, error) {
lines := strings.Split(string(data), "\n")
rows := make([]localdb.VendorSpecItem, 0, len(lines))
sortOrder := 10
serverModel := ""
for _, raw := range lines {
line := strings.TrimSpace(raw)
if line == "" {
continue
}
if m := textBOMHeaderLine.FindStringSubmatch(line); m != nil {
if fields := strings.Fields(m[1]); len(fields) > 0 {
serverModel = fields[len(fields)-1]
}
continue
}
m := nxBOMItemLine.FindStringSubmatch(line)
if m == nil {
continue
}
qty, err := strconv.Atoi(m[1])
if err != nil || qty <= 0 {
continue
}
description := strings.TrimSpace(m[2])
if description == "" {
continue
}
rows = append(rows, localdb.VendorSpecItem{
SortOrder: sortOrder,
VendorPartnumber: description,
Quantity: qty,
Description: description,
})
sortOrder += 10
}
if len(rows) == 0 {
return nil, fmt.Errorf("Nx BOM has no importable rows")
}
name := serverModel
if name == "" {
name = strings.TrimSuffix(filepath.Base(sourceFileName), filepath.Ext(sourceFileName))
}
if name == "" {
name = "Nx BOM Import"
}
return &importedWorkspace{
SourceFormat: "Nx",
SourceFileName: sourceFileName,
Configurations: []importedConfiguration{
{
GroupID: "nx-0",
Name: name,
Line: 10,
ServerCount: 1,
ServerModel: serverModel,
Rows: rows,
},
},
}, nil
}
// textBOMItemLine matches a human-readable BOM line of the form
// "<description> - <quantity> шт." where the separator may be a hyphen,
// en-dash or em-dash and the quantity may have an optional space before "шт".
@@ -709,6 +800,8 @@ func ParsePastedBOMText(text string) ([]localdb.VendorSpecItem, string) {
switch {
case IsInspurBOM(data):
ws, err = parseInspurBOM(data, "")
case IsNxBOM(data):
ws, err = parseNxBOM(data, "")
case IsTextBOM(data):
ws, err = parseTextBOM(data, "")
default:
@@ -893,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;
+25
View File
@@ -0,0 +1,25 @@
# QuoteForge v1.14
Дата релиза: 2026-06-16
Тег: `v1.14`
Предыдущий релиз: `v1.13`
## Ключевые изменения
- добавлен импорт человекочитаемого текстового BOM формата `<описание> - <кол-во> шт.`
(с необязательным заголовком, оканчивающимся на `, в составе:`) — как при загрузке файла
через `POST /api/projects/:uuid/vendor-import`, так и при вставке в конфигураторе;
- заголовок конфигурации определяется по маркеру `, в составе:` с любым префиксом
(`Сервер X3` и `Вычислительный GPU сервер X3` → модель `X3`);
- парсинг устойчив к пробелам в начале/конце строки (в P/N не попадает лишний пробел),
а также к запятым и дефисам внутри описания (`RAID0,1,10`, `8-GPU-2304GB`);
- вставка BOM в конфигураторе и импорт файла используют единый серверный парсер
(`POST /api/vendor-spec/parse-text`) — дублирующая логика разбора на фронтенде удалена;
- сабмодуль `bible` обновлён до актуальных контрактов (build-version-display,
local-first-recovery, резервные копии миграций).
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+20
View File
@@ -0,0 +1,20 @@
# QuoteForge v1.16
Дата релиза: 2026-06-16
Тег: `v1.16`
Предыдущий релиз: `v1.15`
## Ключевые изменения
- self-heal застрявших pending changes: конфигурации со ссылкой на удалённый проект теперь автоматически переназначаются на «Без проекта» вместо вечной ошибки;
- авторемонт очереди (`RepairPendingChanges`) запускается автоматически перед каждым push-циклом;
- после 20 неудачных попыток неисправимые записи удаляются из очереди (логируются как ERROR);
- неизвестные `entity_type` и `operation` в очереди дропаются с предупреждением вместо блокировки;
- детальная диагностика в `qt_client_schema_state.last_sync_error_text`: теперь JSON-массив с `uuid`/`op`/`attempts`/`error` по каждому застрявшему изменению;
- книги партномеров синхронизируются автоматически вместе с прайслистами.
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+15
View File
@@ -0,0 +1,15 @@
# QuoteForge v1.17
Дата релиза: 2026-06-16
Тег: `v1.17`
Предыдущий релиз: `v1.16`
## Ключевые изменения
- исправлен поиск в разделе Партномера по LOT-имени и описанию — `lots_json` хранится как BLOB, `modernc.org/sqlite` не коерсит BLOB→TEXT при LIKE, исправлено через `CAST(lots_json AS TEXT) LIKE`;
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+20
View File
@@ -0,0 +1,20 @@
# QuoteForge v1.18
Дата релиза: 2026-06-18
Тег: `v1.18`
Предыдущий релиз: `v1.17`
## Ключевые изменения
- BOM: поддержка формата `<qty>x <description>` при импорте Nx-спецификаций;
- BOM: приоритет cart-LOT в дропдауне, корректный qtyMismatch при lot_qty_per_pn > 1;
- CSV экспорт: bundle (1 PN → N LOT) разворачивается в отдельные строки;
- ценообразование: ручная цена (buy/sale) сохраняется и экспортируется в CSV;
- ценообразование: таблица использует qty из корзины как источник истины;
- ценообразование: правильный порядок строк (MB→CPU→MEM→…) в pricing CSV и вкладке Ценообразование при отсутствии BOM;
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+35
View File
@@ -0,0 +1,35 @@
# QuoteForge v2.19
Дата релиза: 2026-06-23
Тег: `v2.19`
## Что нового
### Серверно-управляемые настройки конфигуратора
Типы устройств, структура вкладок и фильтры категорий теперь приезжают с сервера вместо жёстко заданных JS-констант.
- новая таблица `qt_settings` на стороне сервера (контракт в `bible-local/server-contract-qt-settings.md`);
- QF синхронизирует `qt_settings` → `local_qt_settings` (SQLite) после каждой синхронизации компонентов;
- новый endpoint `GET /api/configurator-settings` отдаёт четыре настройки: `config_types`, `tab_config`, `always_visible_tabs`, `required_categories`;
- при недоступности сервера или отсутствии таблицы QF автоматически использует прежние захардкоженные значения — поведение не меняется.
### Динамический выбор типа оборудования
- модальное окно «Новая конфигурация» загружает типы устройств с сервера: названия и количество кнопок определяются в `qt_settings.config_types`;
- добавление новых типов устройств не требует обновления QF.
### Серверно-управляемая фильтрация категорий
- конфигуратор фильтрует LOT-категории по списку из `qt_settings.config_types[].categories`;
- структура вкладок обновляется из `qt_settings.tab_config` (порядок вкладок, подразделы, single-select режим);
- бейдж на вкладке при незаполненных обязательных категориях (`qt_settings.required_categories`).
### Прочее
- тайтлы страниц переименованы с OFS на QFS.
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+29
View File
@@ -0,0 +1,29 @@
# QuoteForge v2.21
Дата релиза: 2026-06-25
Тег: `v2.21`
## Что нового
### Короткие ссылки на проекты и варианты
- `GET /:code` — редирект на проект по коду опти (регистронезависимо);
- `GET /:code/:variant` — редирект на конкретный вариант проекта;
- валидация кода опти и имени варианта: только URL-безопасные символы `[A-Za-z0-9._-]` — проверка на бэкенде и в форме с подсказкой `«Используется в URL: /КОД/Вариант»`.
### Ревизия «до обновления цен»
При нажатии «Обновить цены» автоматически создаётся ревизия текущего состояния конфигурации до применения новых цен, после чего сохраняется ревизия с обновлёнными ценами. История изменений теперь полная.
### Исправления
- Старая цена в итоге конфигурации больше не зачёркивается, если цены фактически не изменились.
- Устранён race condition: `SyncPricelists()` теперь защищена мьютексом — параллельный запуск фонового тикера и ручной синхронизации больше не приводит к `UNIQUE constraint failed`.
- Дублирующиеся `lot_name` в серверном прайслисте пропускаются при загрузке вместо аварийного завершения синхронизации.
- Ошибки отправки конфигураций и проектов на сервер теперь видны в диалоге «Информация о синхронизации» и в support bundle (`sync_log`, тип `changes`).
- Состояние клиента (`last_sync_error_code` и др.) отправляется на сервер по завершении синхронизации независимо от её результата.
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+23
View File
@@ -0,0 +1,23 @@
# QuoteForge v2.22
Дата релиза: 2026-06-26
Тег: `v2.22`
## Что нового
### Исправления
- **MB-автокомплит в конфигураторе теперь работает в offline-режиме.** Корневая причина: прайслист мог быть синхронизирован до введения нормализации имён лотов, из-за чего SQLite хранил их в исходном регистре (`MB_AMD_2.Rome_...`). Запрос на поиск цены отправлял уже нормализованное имя (`MB_AMD_2.ROME_...`), `IN`-сравнение в SQLite регистрозависимо — совпадений не было, цена возвращалась как null, и автокомплит показывал пустой список. Все запросы к `local_pricelist_items` по `lot_name` переведены на `UPPER(lot_name)`.
- **Удалён мёртвый код инференса категории из имени лота.** Функция `getCategoryFromLotName` на фронтенде выводила категорию из префикса лота (`DKC_AFF_A1K` → `DKC`) как fallback. Категория всегда приходит из прайслиста; функция удалена. Позиции без категории корректно попадают во вкладку «Other».
- **Удалена таблица `local_components` и весь связанный с ней код.** Источник данных для компонентов — только `local_pricelist_items`. Убраны маршрут `POST /api/sync/components`, поля `ComponentsSynced` и `LastComponentSync` в ответах синхронизации.
- **Support bundle расширен диагностическими файлами:** `latest_pricelist_items.json` (все позиции активного estimate-прайслиста), `autocomplete_lots.json` (позиции по категориям с флагом `has_price`), `local.db` (полная копия SQLite-базы).
- **Регистронезависимые сравнения lot_name на фронтенде:** Set-коллекции для склада, добавленных позиций и корзины BOM теперь нормализуют ключи через `.toUpperCase()`.
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+23
View File
@@ -0,0 +1,23 @@
# QuoteForge v2.23
Дата релиза: 2026-06-26
Тег: `v2.23`
## Что нового
### Исправления
- **Конфигуратор больше не зависает на «Загрузка...».** При открытии сохранённой конфигурации поле `category` у позиций корзины было `undefined` (в `config.items` хранятся только `lot_name/quantity/unit_price`), что приводило к `TypeError` в JS. Теперь после загрузки `allComponents` корзина обогащается категориями из справочника компонентов.
- **Регистронезависимые сравнения категорий в конфигураторе.** Все сравнения `category` переведены на хелпер `ciStr()` вместо принудительного `.toUpperCase()` — интерфейс показывает категории как есть, логика сравнения регистронезависима.
- **Вкладка Other показывает только компоненты без назначенной категории.** Исправлена ошибка при которой компоненты DKC/CTL/ENC попадали в Other при режиме «server»: `ASSIGNED_CATEGORIES` пересобирался из отфильтрованного списка, а не из полного статического. Теперь используется `_allCategories`.
- **Исправлена ошибка «record not found» при синхронизации проектов.** `UpsertByUUID` передавал ненулевой `ID` в `INSERT … ON DUPLICATE KEY UPDATE`, из-за чего MariaDB разрешала коллизию по первичному ключу чужой строки, не обновляя `uuid`, — последующий `SELECT` не находил запись. Теперь `project.ID` сбрасывается в `0` до вставки.
- **Устранён бесконечный retry при ошибках синхронизации на стороне сервера.** `RepairPendingChanges` сбрасывал счётчик попыток даже если локальные данные не менялись, что создавало бесконечный цикл при серверных ошибках. Repair-функции теперь возвращают `(bool, error)` и сброс происходит только при `modified=true`.
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+15
View File
@@ -0,0 +1,15 @@
# QuoteForge v2.24
Дата релиза: 2026-06-26
Тег: `v2.24`
## Что нового
### Исправления
- **Исправлен ReferenceError в конфигураторе при выборе компонента в секционированных вкладках (Storage, PCI).** Переменная `sectionCategories` не была определена — опечатка, должно быть `section.categories`. Ошибка возникала при клике на элемент автокомплита во вкладках с секциями.
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+17
View File
@@ -0,0 +1,17 @@
# QuoteForge v2.25
Дата релиза: 2026-06-29
Тег: `v2.25`
Предыдущий релиз: `v2.24`
## Ключевые изменения
- исправлено дублирование позиций в таблице «Цена покупки» и в экспорте CSV: сопоставление LOT между BOM и корзиной теперь регистронезависимое;
- нормализация LOT-маппингов BOM сведена в единую каноничную функцию на бэкенде (UPPERCASE + схлопывание дублей) — устранены разошедшиеся копии, дававшие разный результат на фронте и в CSV;
- единый источник категории LOT — `local_pricelist_items.lot_category`; удалён неиспользуемый серверный слой управления компонентами/категориями.
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+17
View File
@@ -0,0 +1,17 @@
# QuoteForge v2.26
Дата релиза: 2026-06-29
Тег: `v2.26`
Предыдущий релиз: `v2.25`
## Ключевые изменения
- fix: лоты, отсутствующие в текущем прайслисте, больше не блокируют сохранение конфига и генерацию артикула — такие лоты просто пропускаются;
- fix: если прайслист конфига удалён с сервера, автоматически выбирается последний активный;
- refactor: удалён мёртвый код qt_lot_metadata;
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+15
View File
@@ -0,0 +1,15 @@
# QuoteForge v2.27
Дата релиза: 2026-06-30
Тег: `v2.27`
Предыдущий релиз: `v2.26`
## Ключевые изменения
- в таблицах конфигураций появилась иконка глаза — показывает, что конфигурацию сейчас открыл другой пользователь; при наведении виден список имён;
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+18
View File
@@ -0,0 +1,18 @@
# QuoteForge v2.29
Дата релиза: 2026-07-10
Тег: `v2.29`
Предыдущий релиз: `v2.28`
## Ключевые изменения
- world-прайслист используется как заглушка: где для позиции нет цены в estimate/склад/конкуренты, подставляется цена из world;
- подставленные из world цены выделяются цветом (amber) в таблицах «Цена покупки» и «Цена продажи», участвуют в «Итого» и убирают красную звёздочку неполного покрытия;
- в CSV-экспорт добавлена колонка «Заглушка (world)» с перечнем столбцов, где сработал фолбэк;
- устранён потенциальный дедлок при резолве прайслистов внутри транзакции (single-connection пул) — добавлены транзакционные варианты выборки прайслистов.
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+21
View File
@@ -0,0 +1,21 @@
# QuoteForge v3.31
Дата релиза: 2026-07-22
Тег: `v3.31`
Предыдущий релиз: `v2.30`
## Ключевые изменения
- поддержка импорта CSV из customer-facing формата pricing-экспорта (не только из round-trip формата) — колонки резолвятся по имени;
- список вариантов конфигурации в выпадающем меню нумеруется и сортируется по дате создания (старый сверху);
- новая вкладка «Аренда» в конфигураторе (для проектов с флагом rental_enabled): расчёт разового и еженедельного платежа по регламенту платного тестирования/аренды GPU-серверов, с колонками Estimate/Цена продажи и чекбоксом «БУ»;
- техподдержка (support_code) на вкладке Base теперь добавляется как обычный LOT через autocomplete-пикер вместо выпадающего списка;
- прайслисты: local_pricelist_items получает lot_description напрямую из qt_pricelist_items.lot_description (вместо устаревших неиспользуемых available_qty/partnumbers) — описание LOT теперь берётся из одного места везде в проекте, включая экспорт цен (там раньше подстановка описания молча не работала);
- добавлено price_quality — качество цены LOT (0-9), проставляется внешней утилитой ценообразования; показывается цветным индикатором (градиент красный → жёлтый → зелёный) в прайслисте, в поиске компонентов конфигуратора, в таблице конфигуратора и на вкладке «Ценообразование» (подсветка строки);
- из контракта прайслиста убраны неиспользуемые в клиенте поля (price_method, price_period_days, price_coefficient, manual_price, meta_prices) — сами колонки в базе не тронуты, оставлены для обратной совместимости с внешним движком ценообразования.
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+21
View File
@@ -0,0 +1,21 @@
# QuoteForge v3.32
Дата релиза: 2026-07-24
Тег: `v3.32`
Предыдущий релиз: `v3.31`
## Ключевые изменения
- колонка «PN code» в таблице импорта BOM: HPE-спецификации хранят партномер в двух столбцах (базовый P/N и код опции), теперь они склеиваются в канонический вид `P52534-B21#B19` прямо в интерфейсе — раньше это приходилось делать через CONCATENATE в Excel. Склеенное значение сохраняется в `vendor_partnumber` и сравнивается с книгой партномеров как есть, а при повторном открытии конфигурации разбирается обратно на две колонки; схема БД не менялась;
- список допустимых LOT конфигуратора собирается из объединения прайслистов `world` и `estimate`, а не только из `estimate`. Прежняя область видимости молча теряла сопоставления BOM: резолвер находил LOT по книге партномеров, которая про прайслисты ничего не знает, а фронт отбрасывал всё, чего нет в estimate — при этом в корзину такой LOT всё равно попадал, и строка BOM оставалась с «н/д». Дедупликация по имени LOT без учёта регистра, при совпадении выигрывает запись из estimate; позиции, найденные только в world, показываются с качеством цены 0 (самый красный);
- LOT, сопоставленный по книге партномеров, сохраняется в спецификации, даже если его нет ни в одном прайслисте — раньше такое сопоставление пропадало без предупреждения. LOT, введённые руками, по-прежнему проверяются по списку;
- кнопка «Пересопоставить» на вкладке BOM — заново прогоняет строки через актуальную книгу партномеров. При открытии конфигурации сопоставления намеренно остаются такими, какими были сохранены, поэтому записи, добавленные в книгу позже, подхватываются только этой кнопкой;
- вкладка «Ценообразование»: убраны звёздочки у итогов (переносились на отдельную строку и разъезжались). Итог по столбцам Estimate, Склад и Конкуренты подсвечивается красным тогда и только тогда, когда часть суммы посчитана по ценам-заглушкам из прайслиста `world`; при наведении всплывает подсказка с точной долей таких цен и с покрытием по позициям;
- колонка «PN вендора» на вкладке «Ценообразование» больше не переносит партномер на две строки;
- индикатор качества цены показывается во всех таблицах конфигуратора, а не только на вкладке Base; колонка-индикатор везде без текстового заголовка, только с тултипом.
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+17
View File
@@ -0,0 +1,17 @@
# QuoteForge v3.33
Дата релиза: 2026-07-30
Тег: `v3.33`
Предыдущий релиз: `v3.32`
## Ключевые изменения
- новые категории прайслиста (например `SYS`), не входящие ни в одну известную вкладку конфигуратора, больше не пропадают из «Прочее» — устранены три места самоотравления `ASSIGNED_CATEGORIES`, сведены в одну функцию;
- фоновая синхронизация `qt_settings` (tab_config, config_types, required_categories, поддержка) подключена к воркеру — раньше была мёртвым кодом, и правки в центральной таблице не доезжали до клиентов;
- детерминированная сортировка при постраничной выдаче конфигураций (`ListAll`).
## Запуск на macOS
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
После этого бинарник запустится без предупреждения Gatekeeper.
+19 -30
View File
@@ -53,45 +53,34 @@ mkdir -p "${RELEASE_DIR}"
# Create release notes template only when missing.
ensure_release_notes "${RELEASE_DIR}/RELEASE_NOTES.md"
# Build for all platforms
# Build binaries
echo -e "${YELLOW}→ Building binaries...${NC}"
make build-all
LDFLAGS="-s -w -X main.Version=${VERSION}"
echo "Building qfs for macOS (Apple Silicon)..."
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags="${LDFLAGS}" -o bin/qfs-darwin-arm64 ./cmd/qfs
echo "✓ Built: bin/qfs-darwin-arm64"
echo "Building qfs for Windows..."
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="${LDFLAGS}" -o bin/qfs-windows-amd64.exe ./cmd/qfs
echo "✓ Built: bin/qfs-windows-amd64.exe"
# Package binaries with checksums
echo ""
echo -e "${YELLOW}→ Creating release packages...${NC}"
# Linux AMD64
if [ -f "bin/qfs-linux-amd64" ]; then
cd bin
tar -czf "../${RELEASE_DIR}/qfs-${VERSION}-linux-amd64.tar.gz" qfs-linux-amd64
cd ..
echo -e "${GREEN} ✓ qfs-${VERSION}-linux-amd64.tar.gz${NC}"
fi
# macOS Intel
if [ -f "bin/qfs-darwin-amd64" ]; then
cd bin
tar -czf "../${RELEASE_DIR}/qfs-${VERSION}-darwin-amd64.tar.gz" qfs-darwin-amd64
cd ..
echo -e "${GREEN} ✓ qfs-${VERSION}-darwin-amd64.tar.gz${NC}"
fi
# macOS Apple Silicon
if [ -f "bin/qfs-darwin-arm64" ]; then
cd bin
tar -czf "../${RELEASE_DIR}/qfs-${VERSION}-darwin-arm64.tar.gz" qfs-darwin-arm64
cd ..
echo -e "${GREEN} ✓ qfs-${VERSION}-darwin-arm64.tar.gz${NC}"
fi
cd bin
tar -czf "../${RELEASE_DIR}/qfs-${VERSION}-darwin-arm64.tar.gz" qfs-darwin-arm64
cd ..
echo -e "${GREEN} ✓ qfs-${VERSION}-darwin-arm64.tar.gz${NC}"
# Windows AMD64
if [ -f "bin/qfs-windows-amd64.exe" ]; then
cd bin
zip -q "../${RELEASE_DIR}/qfs-${VERSION}-windows-amd64.zip" qfs-windows-amd64.exe
cd ..
echo -e "${GREEN} ✓ qfs-${VERSION}-windows-amd64.zip${NC}"
fi
cd bin
zip -q "../${RELEASE_DIR}/qfs-${VERSION}-windows-amd64.zip" qfs-windows-amd64.exe
cd ..
echo -e "${GREEN} ✓ qfs-${VERSION}-windows-amd64.zip${NC}"
# Generate checksums
echo ""
+37
View File
@@ -7,3 +7,40 @@
-webkit-box-orient: vertical;
overflow: hidden;
}
/* Pricing footer totals: instant hover popup explaining how much of the sum rests on
world-pricelist stand-in prices. A native title= tooltip was too slow and too easy to
miss on a number the user is meant to distrust. */
.pricing-total-tip {
position: relative;
cursor: help;
}
.pricing-total-tip > .pricing-total-tip__body {
visibility: hidden;
opacity: 0;
position: absolute;
right: 0;
bottom: calc(100% + 6px);
z-index: 30;
width: max-content;
max-width: 20rem;
padding: 0.5rem 0.625rem;
border-radius: 0.375rem;
background: #1f2937;
color: #f9fafb;
font-size: 0.75rem;
font-weight: 400;
line-height: 1.35;
text-align: left;
white-space: normal;
box-shadow: 0 4px 12px rgb(0 0 0 / 0.18);
transition: opacity 0.1s ease-in;
pointer-events: none;
}
.pricing-total-tip:hover > .pricing-total-tip__body,
.pricing-total-tip:focus-visible > .pricing-total-tip__body {
visibility: visible;
opacity: 1;
}
+55
View File
@@ -0,0 +1,55 @@
// Shared LOT price-quality color scale, used everywhere price_quality is
// displayed (pricelist detail page, configurator search dropdown, configurator
// table, pricing tab). price_quality is a 0-9 score set by the external
// pricing tool (see bible-local/03-database.md, qt_pricelist_items.price_quality)
// — QF only displays it, never computes it. Single source of the color scale
// so every view stays visually consistent.
//
// Gradient: 0 = red, 5 = yellow, 9 = green.
(function () {
const RED = [220, 38, 38];
const YELLOW = [234, 179, 8];
const GREEN = [22, 163, 74];
function lerp(c1, c2, t) {
return c1.map((v, i) => Math.round(v + (c2[i] - v) * t));
}
// Returns "r, g, b" (no rgb() wrapper) so callers can build rgb()/rgba() themselves.
function priceQualityRgb(quality) {
if (typeof quality !== 'number' || Number.isNaN(quality)) return null;
const q = Math.max(0, Math.min(9, quality));
const [r, g, b] = q <= 5 ? lerp(RED, YELLOW, q / 5) : lerp(YELLOW, GREEN, (q - 5) / 4);
return `${r}, ${g}, ${b}`;
}
function priceQualityColor(quality) {
const rgb = priceQualityRgb(quality);
return rgb ? `rgb(${rgb})` : null;
}
// Small colored dot for compact contexts (search dropdown, configurator table cell).
function qualityDotHtml(quality) {
const color = priceQualityColor(quality);
if (!color) return '';
return `<span class="inline-block w-2 h-2 rounded-full" style="background-color: ${color}" title="Качество цены: ${quality}/9"></span>`;
}
// Colored number badge for a dedicated "quality" column/cell.
function qualityBadgeHtml(quality) {
if (typeof quality !== 'number') return '<span class="text-gray-400">-</span>';
const color = priceQualityColor(quality);
return `<span class="font-semibold" style="color: ${color}" title="Качество цены: ${quality}/9">${quality}</span>`;
}
// Light row-tint background for table rows, e.g. the pricing tab.
function qualityRowStyle(quality) {
const rgb = priceQualityRgb(quality);
return rgb ? `background-color: rgba(${rgb}, 0.10)` : '';
}
window.priceQualityColor = priceQualityColor;
window.qualityDotHtml = qualityDotHtml;
window.qualityBadgeHtml = qualityBadgeHtml;
window.qualityRowStyle = qualityRowStyle;
})();
+5 -2
View File
@@ -8,6 +8,7 @@
<link rel="stylesheet" href="/static/app.css">
<script src="/static/vendor/tailwindcss.browser.js"></script>
<script src="/static/vendor/htmx-1.9.10.min.js"></script>
<script src="/static/price-quality.js"></script>
<style>
.htmx-request { opacity: 0.5; }
.line-clamp-2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
@@ -629,11 +630,13 @@
const totalColor = totalDelta > 0 ? 'text-red-600' : totalDelta < 0 ? 'text-green-600' : 'text-gray-600';
const totalArrow = _fmtArrow(r.prevTotal || 0, r.newTotal || 0);
const totalPrevHtml = totalDelta !== 0
? `<span class="text-gray-400 line-through text-xs mr-1">${_fmtMoneyDiff(r.prevTotal || 0)}</span>`
: '';
html += `<div class="flex justify-between items-center text-sm bg-gray-50 rounded px-3 py-2 mb-1">
<span class="text-gray-600 font-medium">Итог конфигурации</span>
<span>
<span class="text-gray-400 line-through text-xs mr-1">${_fmtMoneyDiff(r.prevTotal || 0)}</span>
<span class="${totalColor} font-semibold">${_fmtMoneyDiff(r.newTotal || 0)}</span>${totalArrow}
${totalPrevHtml}<span class="${totalColor} font-semibold">${_fmtMoneyDiff(r.newTotal || 0)}</span>${totalArrow}
</span>
</div>`;
}
+1 -1
View File
@@ -1,4 +1,4 @@
{{define "title"}}Ревизии - OFS{{end}}
{{define "title"}}QFS Ревизии{{end}}
{{define "content"}}
<div class="space-y-4">
+52 -8
View File
@@ -1,4 +1,4 @@
{{define "title"}}Мои конфигурации - OFS{{end}}
{{define "title"}}QFS Мои конфигурации{{end}}
{{define "content"}}
<div class="space-y-4">
@@ -55,12 +55,12 @@
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Тип оборудования</label>
<div class="inline-flex rounded-lg border border-gray-200 overflow-hidden w-full">
<button type="button" id="type-server-btn" onclick="setCreateType('server')"
<div id="config-type-buttons" class="inline-flex rounded-lg border border-gray-200 overflow-hidden w-full">
<button type="button" data-type="server" onclick="setCreateType('server')"
class="flex-1 py-2 text-sm font-medium bg-blue-600 text-white">
Сервер
</button>
<button type="button" id="type-storage-btn" onclick="setCreateType('storage')"
<button type="button" data-type="storage" onclick="setCreateType('storage')"
class="flex-1 py-2 text-sm font-medium bg-white text-gray-700 hover:bg-gray-50 border-l border-gray-200">
СХД
</button>
@@ -242,6 +242,7 @@ function renderConfigs(configs) {
html += '<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Цена (за 1 шт)</th>';
html += '<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Кол-во</th>';
html += '<th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Сумма</th>';
html += '<th class="px-2 py-3 w-8"></th>';
html += '<th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Действия</th>';
html += '</tr></thead><tbody class="divide-y">';
@@ -298,6 +299,16 @@ function renderConfigs(configs) {
html += '<td class="px-4 py-3 text-sm text-gray-500">' + pricePerUnit + '</td>';
html += '<td class="px-4 py-3 text-sm text-gray-500">' + serverCount + '</td>';
html += '<td class="px-4 py-3 text-sm text-right">' + total + '</td>';
const viewers = c.viewers || [];
if (viewers.length > 0) {
const names = viewers.map(escapeHtml).join(', ');
html += '<td class="px-2 py-3 text-center w-8">';
html += '<span title="Открыта: ' + names + '" class="inline-flex items-center justify-center text-blue-500 cursor-default">';
html += '<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path></svg>';
html += '</span></td>';
} else {
html += '<td class="px-2 py-3 w-8"></td>';
}
html += '<td class="px-4 py-3 text-sm text-right space-x-2">';
if (configStatusMode === 'archived') {
html += '<button onclick="reactivateConfig(\'' + c.uuid + '\')" class="text-emerald-600 hover:text-emerald-800" title="Восстановить">';
@@ -532,18 +543,51 @@ async function cloneConfig() {
}
let createConfigType = 'server';
let _cfgSettings = null;
async function loadCfgSettings() {
if (_cfgSettings) return _cfgSettings;
try {
const r = await fetch('/api/configurator-settings');
if (r.ok) _cfgSettings = await r.json();
} catch(e) { /* use hardcoded fallback */ }
return _cfgSettings;
}
function renderConfigTypeButtons(types) {
if (!types || !types.length) return;
const el = document.getElementById('config-type-buttons');
if (!el) return;
el.innerHTML = types
.sort((a, b) => (a.display_order || 0) - (b.display_order || 0))
.map((t, i) => {
const borderClass = i > 0 ? 'border-l border-gray-200' : '';
return `<button type="button" data-type="${t.code}" onclick="setCreateType('${t.code}')"
class="flex-1 py-2 text-sm font-medium ${borderClass} bg-white text-gray-700 hover:bg-gray-50">
${t.name_ru || t.code}
</button>`;
}).join('');
// activate first type
const firstCode = types[0].code;
createConfigType = firstCode;
setCreateType(firstCode);
}
function setCreateType(type) {
createConfigType = type;
document.getElementById('type-server-btn').className = 'flex-1 py-2 text-sm font-medium ' +
(type === 'server' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700 hover:bg-gray-50 border-l border-gray-200');
document.getElementById('type-storage-btn').className = 'flex-1 py-2 text-sm font-medium border-l border-gray-200 ' +
(type === 'storage' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700 hover:bg-gray-50');
document.querySelectorAll('#config-type-buttons button').forEach(btn => {
const active = btn.dataset.type === type;
btn.className = 'flex-1 py-2 text-sm font-medium ' +
(active
? 'bg-blue-600 text-white border-l border-gray-200'
: 'bg-white text-gray-700 hover:bg-gray-50 border-l border-gray-200');
});
}
function openCreateModal() {
createConfigType = 'server';
setCreateType('server');
loadCfgSettings().then(s => renderConfigTypeButtons(s && s.config_types));
document.getElementById('opportunity-number').value = '';
document.getElementById('create-project-input').value = '';
document.getElementById('create-modal').classList.remove('hidden');
+975 -410
View File
File diff suppressed because it is too large. Load diff
+4 -7
View File
@@ -1,4 +1,4 @@
{{define "title"}}OFS - Партномера{{end}}
{{define "title"}}QFS Партномера{{end}}
{{define "content"}}
<div class="space-y-4">
@@ -22,20 +22,17 @@
</div>
<div id="summary-empty" class="hidden bg-yellow-50 border border-yellow-200 rounded-lg p-4 text-sm text-yellow-800">
Нет активного листа сопоставлений. Нажмите «Синхронизировать» для загрузки с сервера.
Нет активного листа сопоставлений. Книги загружаются автоматически вместе с прайслистами.
</div>
<!-- All books list (collapsed by default) -->
<div class="bg-white rounded-lg shadow overflow-hidden">
<!-- Header row — always visible -->
<div class="px-4 py-3 flex items-center justify-between">
<div class="px-4 py-3">
<button onclick="toggleBooksSection()" class="flex items-center gap-2 text-sm font-semibold text-gray-800 hover:text-gray-600 select-none">
<svg id="books-chevron" class="w-4 h-4 text-gray-400 transition-transform duration-150" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"/></svg>
Снимки сопоставлений (Partnumber Books)
</button>
<button onclick="syncPartnumberBooks()" class="px-4 py-2 bg-orange-500 text-white rounded hover:bg-orange-600 text-sm font-medium">
Синхронизировать
</button>
</div>
<!-- Collapsible body -->
<div id="books-section-body" class="hidden border-t">
@@ -69,7 +66,7 @@
<div id="active-book-section" class="hidden bg-white rounded-lg shadow overflow-hidden">
<div class="px-4 py-3 border-b flex items-center justify-between gap-3">
<span class="font-semibold text-gray-800 whitespace-nowrap">Сопоставления активного листа</span>
<input type="text" id="pn-search" placeholder="Поиск по PN или LOT..."
<input type="text" id="pn-search" placeholder="Поиск по PN, LOT или описанию..."
class="flex-1 max-w-xs px-3 py-1.5 border rounded text-sm focus:ring-2 focus:ring-blue-400 focus:outline-none"
oninput="onItemsSearchInput(this.value)">
<span id="pn-count" class="text-xs text-gray-400 whitespace-nowrap"></span>
+4 -61
View File
@@ -1,4 +1,4 @@
{{define "title"}}Прайслист - OFS{{end}}
{{define "title"}}QFS Прайслист{{end}}
{{define "content"}}
<div class="space-y-6">
@@ -58,9 +58,8 @@
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Артикул</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Категория</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Описание</th>
<th id="th-qty" class="hidden px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">Доступно</th>
<th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">Цена, $</th>
<th id="th-settings" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Настройки</th>
<th class="px-6 py-3 w-6" title="Качество цены"></th>
</tr>
</thead>
<tbody id="items-body" class="bg-white divide-y divide-gray-200">
@@ -91,7 +90,6 @@
const pl = await resp.json();
currentSource = pl.source || '';
toggleWarehouseColumns();
document.getElementById('page-title').textContent = `Прайслист ${pl.version}`;
document.getElementById('pl-version').textContent = pl.version;
@@ -134,7 +132,6 @@
const resp = await fetch(url);
const data = await resp.json();
currentSource = data.source || currentSource;
toggleWarehouseColumns();
renderItems(data.items || []);
renderItemsPagination(data.total_count, data.page, data.per_page);
@@ -159,19 +156,7 @@
}
function itemsColspan() {
return isStockSource() ? 4 : 5;
}
function toggleWarehouseColumns() {
const stock = isStockSource();
document.getElementById('th-qty').classList.toggle('hidden', true);
document.getElementById('th-settings').classList.toggle('hidden', stock);
}
function formatQty(qty) {
if (typeof qty !== 'number') return '—';
if (Number.isInteger(qty)) return qty.toString();
return qty.toLocaleString('ru-RU', { minimumFractionDigits: 0, maximumFractionDigits: 3 });
return 5;
}
function escapeHtml(text) {
@@ -184,48 +169,6 @@
.replace(/'/g, '&#039;');
}
function formatPriceSettings(item) {
// Format price settings to match admin pricing interface style
let settings = [];
const hasManualPrice = item.manual_price && item.manual_price > 0;
const hasMeta = item.meta_prices && item.meta_prices.trim() !== '';
const method = (item.price_method || '').toLowerCase();
// Method indicator
if (hasManualPrice) {
settings.push('<span class="text-orange-600 font-medium">РУЧН</span>');
} else if (method === 'average') {
settings.push('Сред');
} else if (method === 'weighted_median') {
settings.push('Взвеш. мед');
} else {
settings.push('Мед');
}
// Period (only if not manual price)
if (!hasManualPrice) {
const period = item.price_period_days !== undefined && item.price_period_days !== null ? item.price_period_days : 90;
if (period === 7) settings.push('1н');
else if (period === 30) settings.push('1м');
else if (period === 90) settings.push('3м');
else if (period === 365) settings.push('1г');
else if (period === 0) settings.push('все');
else settings.push(period + 'д');
}
// Coefficient
if (item.price_coefficient && item.price_coefficient !== 0) {
settings.push((item.price_coefficient > 0 ? '+' : '') + item.price_coefficient + '%');
}
// Meta article indicator
if (hasMeta) {
settings.push('<span class="text-purple-600 font-medium">МЕТА</span>');
}
return settings.join(' | ') || '-';
}
function renderItems(items) {
if (items.length === 0) {
document.getElementById('items-body').innerHTML = `
@@ -265,7 +208,7 @@
</td>
<td class="${p} text-sm text-gray-500" title="${escapeHtml(description)}">${escapeHtml(truncatedDesc)}</td>
<td class="${p} whitespace-nowrap text-right font-mono">${priceHtml}</td>
${!stock ? `<td class="${p} whitespace-nowrap text-sm"><span class="text-xs bg-gray-100 px-2 py-1 rounded">${formatPriceSettings(item)}</span></td>` : ''}
<td class="${p} whitespace-nowrap text-center">${qualityBadgeHtml(item.price_quality)}</td>
</tr>
`;
}).join('');
+1 -1
View File
@@ -1,4 +1,4 @@
{{define "title"}}Прайслисты - OFS{{end}}
{{define "title"}}QFS Прайслисты{{end}}
{{define "content"}}
<div class="space-y-6">
+35 -11
View File
@@ -1,4 +1,4 @@
{{define "title"}}Проект - OFS{{end}}
{{define "title"}}QFS Проект{{end}}
{{define "content"}}
<div class="space-y-4">
@@ -22,8 +22,8 @@
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
</svg>
</button>
<div id="project-variant-menu" class="absolute left-0 mt-2 min-w-[10rem] rounded-lg border border-gray-200 bg-white shadow-lg hidden z-10">
<div id="project-variant-list" class="py-1"></div>
<div id="project-variant-menu" class="absolute left-0 mt-2 w-max max-w-xs min-w-[12rem] rounded-lg border border-gray-200 bg-white shadow-lg hidden z-10 text-sm font-normal">
<div id="project-variant-list" class="py-1 max-h-72 overflow-y-auto"></div>
</div>
</div>
<button onclick="openNewVariantModal()" class="inline-flex w-full sm:w-auto justify-center items-center px-3 py-1.5 text-sm font-medium bg-purple-600 text-white rounded-lg hover:bg-purple-700">
@@ -207,9 +207,11 @@
</div>
<div>
<label for="new-variant-value" class="block text-sm font-medium text-gray-700 mb-1">Вариант</label>
<input id="new-variant-value" type="text" placeholder="Например: Lenovo"
<input id="new-variant-value" type="text" placeholder="Например: B200"
pattern="[A-Za-z0-9._-]+"
title="Только буквы, цифры, дефис, точка, подчёркивание"
class="w-full px-3 py-2 border rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
<div class="text-xs text-gray-500 mt-1">Оставьте пустым для main нельзя — нужно уникальное значение.</div>
<div class="text-xs text-gray-500 mt-1">Буквы, цифры, дефис, точка, подчёркивание. Используется в URL: /КОД/Вариант.</div>
</div>
</div>
<div class="mt-6 flex justify-end gap-2">
@@ -312,6 +314,13 @@
class="w-full px-3 py-2 border rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
<div class="text-xs text-gray-500 mt-1">Оставьте пустым, чтобы скрыть ссылку.</div>
</div>
<div>
<label class="flex items-center space-x-2">
<input type="checkbox" id="project-settings-rental-enabled" class="rounded border-gray-300">
<span class="text-sm font-medium text-gray-700">Аренда</span>
</label>
<div class="text-xs text-gray-500 mt-1">Добавляет вкладку «Аренда» (расчёт стоимости платного тестирования/аренды) на конфигурациях этого проекта.</div>
</div>
</div>
<div class="flex justify-end space-x-3 mt-6">
<button onclick="closeProjectSettingsModal()" class="px-4 py-2 text-gray-600 hover:text-gray-800">Отмена</button>
@@ -378,8 +387,8 @@ async function loadVariantsForCode(code) {
}
projectVariants = allProjects
.filter(p => (p.code || '').trim() === code && p.is_active !== false)
.map(p => ({uuid: p.uuid, variant: (p.variant || '').trim()}));
projectVariants.sort((a, b) => normalizeVariantLabel(a.variant).localeCompare(normalizeVariantLabel(b.variant)));
.map(p => ({uuid: p.uuid, variant: (p.variant || '').trim(), createdAt: p.created_at || ''}));
projectVariants.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
} catch (e) {
// ignore
}
@@ -395,7 +404,7 @@ function renderVariantSelect() {
list.innerHTML = '';
const variants = projectVariants.length ? projectVariants : [{uuid: projectUUID, variant: (project && project.variant) || ''}];
let mainUUID = '';
variants.forEach(item => {
variants.forEach((item, index) => {
const variantLabel = normalizeVariantLabel(item.variant);
if (variantLabel === 'main' && !mainUUID) {
mainUUID = item.uuid;
@@ -408,7 +417,7 @@ function renderVariantSelect() {
label.textContent = variantLabel;
document.title = (project && project.code ? project.code : '—') + ' / ' + variantLabel + ' — OFS';
}
option.textContent = variantLabel;
option.textContent = (index + 1) + '. ' + variantLabel;
option.onclick = function() {
menu.classList.add('hidden');
if (item.uuid && item.uuid !== projectUUID) {
@@ -516,7 +525,16 @@ function renderConfigs(configs) {
html += '<td class="px-4 py-3 text-sm text-gray-500"><input type="number" min="1" value="' + serverCount + '" class="w-16 px-1 py-0.5 border rounded text-center text-sm" data-uuid="' + c.uuid + '" data-prev="' + serverCount + '" onchange="updateConfigServerCount(this)"></td>';
}
html += '<td class="px-4 py-3 text-sm text-right" data-total-uuid="' + c.uuid + '">' + formatMoneyNoDecimals(total) + '</td>';
html += '<td class="px-2 py-3 text-sm text-center text-gray-500 w-12">main</td>';
const projViewers = c.viewers || [];
if (projViewers.length > 0) {
const projNames = projViewers.map(escapeHtml).join(', ');
html += '<td class="px-2 py-3 text-center w-12">';
html += '<span title="Открыта: ' + projNames + '" class="inline-flex items-center justify-center text-blue-500 cursor-default">';
html += '<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path></svg>';
html += '</span></td>';
} else {
html += '<td class="px-2 py-3 w-12"></td>';
}
html += '<td class="px-4 py-3 text-sm text-right whitespace-nowrap"><div class="inline-flex items-center justify-end gap-2">';
if (configStatusMode === 'archived') {
html += '<button onclick="reactivateConfig(\'' + c.uuid + '\')" class="text-emerald-600 hover:text-emerald-800" title="Восстановить">';
@@ -842,6 +860,10 @@ async function createNewVariant() {
showToast('Укажите вариант', 'error');
return;
}
if (!/^[A-Za-z0-9._-]+$/.test(variant)) {
showToast('Имя варианта содержит недопустимые символы. Разрешены: буквы, цифры, дефис, точка, подчёркивание.', 'error');
return;
}
const payload = {
code: code,
variant: variant,
@@ -1238,6 +1260,7 @@ function openProjectSettingsModal() {
document.getElementById('project-settings-variant').value = project.variant || '';
document.getElementById('project-settings-name').value = project.name || '';
document.getElementById('project-settings-tracker-url').value = (project.tracker_url || '').trim();
document.getElementById('project-settings-rental-enabled').checked = !!project.rental_enabled;
document.getElementById('project-settings-modal').classList.remove('hidden');
document.getElementById('project-settings-modal').classList.add('flex');
}
@@ -1253,6 +1276,7 @@ async function saveProjectSettings() {
const variant = document.getElementById('project-settings-variant').value.trim();
const name = document.getElementById('project-settings-name').value.trim();
const trackerURL = document.getElementById('project-settings-tracker-url').value.trim();
const rentalEnabled = document.getElementById('project-settings-rental-enabled').checked;
if (!code) {
alert('Введите код проекта');
return;
@@ -1260,7 +1284,7 @@ async function saveProjectSettings() {
const resp = await fetch('/api/projects/' + projectUUID, {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({code: code, variant: variant, name: name, tracker_url: trackerURL})
body: JSON.stringify({code: code, variant: variant, name: name, tracker_url: trackerURL, rental_enabled: rentalEnabled})
});
if (!resp.ok) {
if (resp.status === 409) {
+21 -2
View File
@@ -1,4 +1,4 @@
{{define "title"}}Мои проекты - OFS{{end}}
{{define "title"}}QFS Мои проекты{{end}}
{{define "content"}}
<div class="space-y-4">
@@ -39,12 +39,18 @@
<div>
<label for="create-project-code" class="block text-sm font-medium text-gray-700 mb-1">Код проекта</label>
<input id="create-project-code" type="text" placeholder="Например: OPS-123"
pattern="[A-Za-z0-9._-]+"
title="Только буквы, цифры, дефис, точка, подчёркивание"
class="w-full px-3 py-2 border rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
<p class="text-xs text-gray-400 mt-1">Буквы, цифры, дефис, точка, подчёркивание. Код используется в URL.</p>
</div>
<div>
<label for="create-project-variant" class="block text-sm font-medium text-gray-700 mb-1">Вариант (необязательно)</label>
<input id="create-project-variant" type="text" placeholder="Например: Lenovo"
<input id="create-project-variant" type="text" placeholder="Например: B200"
pattern="[A-Za-z0-9._-]*"
title="Только буквы, цифры, дефис, точка, подчёркивание"
class="w-full px-3 py-2 border rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
<p class="text-xs text-gray-400 mt-1">Используется в URL: /КОД/Вариант</p>
</div>
<div>
<label for="create-project-tracker-url" class="block text-sm font-medium text-gray-700 mb-1">Ссылка на трекер</label>
@@ -396,6 +402,14 @@ async function createProject() {
alert('Введите код проекта');
return;
}
if (!/^[A-Za-z0-9._-]+$/.test(code)) {
alert('Код проекта содержит недопустимые символы.\nРазрешены: буквы, цифры, дефис, точка, подчёркивание.');
return;
}
if (variant && !/^[A-Za-z0-9._-]+$/.test(variant)) {
alert('Имя варианта содержит недопустимые символы.\nРазрешены: буквы, цифры, дефис, точка, подчёркивание.');
return;
}
const resp = await fetch('/api/projects', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
@@ -411,6 +425,11 @@ async function createProject() {
alert('Проект с таким кодом и вариантом уже существует');
return;
}
if (resp.status === 400) {
const body = await resp.json().catch(() => ({}));
alert(body.error || 'Некорректный запрос');
return;
}
alert('Не удалось создать проект');
return;
}