Compare commits

..
8 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
16 changed files with 326 additions and 338 deletions

No files matched your search

+1
View File
@@ -16,6 +16,7 @@ Project-specific architecture and operational contracts.
| [09-vendor-spec.md](09-vendor-spec.md) | Vendor BOM and CFXML import contract |
| [10-agent-api-guide.md](10-agent-api-guide.md) | End-to-end API guide for agents pricing servers from a TZ |
| [11-lot-suggestions.md](11-lot-suggestions.md) | lot_suggestion column in qt_vendor_partnumber_seen — write/read contract for manual UI mappings |
| [decisions/](decisions/README.md) | Architectural decision log, one file per decision |
## Rules
@@ -43,3 +43,7 @@ is missing or ≤ 0:
"latest active `world` pricelist," not a per-configuration pin.
- If no `world` pricelist exists locally, behavior is unchanged (missing prices stay "—",
no error).
- How the footer totals surface this fallback is decided separately in
[2026-07-24-pricing-total-world-share.md](2026-07-24-pricing-total-world-share.md);
membership of world LOTs in the configurator's LOT set is decided in
[2026-07-24-component-universe-world-union.md](2026-07-24-component-universe-world-union.md).
@@ -0,0 +1,47 @@
# Decision: pricing totals signal the world-fallback share, not row coverage
**Date:** 2026-07-24
**Status:** active
## Context
The footer totals of both "Ценообразование" tables used to mean one thing: a red number
with a trailing `*` said "prices are missing for some positions (N of M)". Two problems:
- the asterisk was a separate `<span>` after the number and wrapped onto its own line,
pushing the footer layout around;
- coverage was the wrong thing to warn about. Since
[2026-07-10-world-pricelist-fallback.md](2026-07-10-world-pricelist-fallback.md) a
missing price is silently filled from the `world` pricelist, so the total is rarely
incomplete — it is *contaminated*. A sum resting on world stand-in prices looked exactly
like a sum of real ones.
## Decision
`_setPricingTotal` in `web/templates/index.html` renders every footer total for Estimate,
Склад and Конкуренты in both tables (buy and sale):
- No asterisk, ever. The number stands alone.
- The total is red **if and only if** part of it was computed from `world` prices — that
is, `worldTotal > 0`. A clean sum is not coloured. Red is a contamination signal, not a
coverage signal.
- The world share per column is accumulated from the same per-row flags that tint the
cells amber (`estWorld` / `whWorld` / `compWorld`), summed over line totals, not unit
prices.
- Hovering the total opens a styled popup (`.pricing-total-tip` in `web/static/app.css`),
not a `title=` tooltip — the native one appears too late to notice on a number the user
is meant to distrust. It states the exact percentage and, when prices are genuinely
missing for some rows, adds the coverage line that the asterisk used to carry.
- "Ручная цена" is not part of this: it is user input, never world-derived.
## Consequences
- Red in the pricing footer means "part of this sum is a stand-in price", nothing else.
Do not reuse it for coverage, staleness or any other condition.
- The colour and popup classes are re-applied on every render and stripped first, so they
never accumulate across re-renders.
- The totals are written with `innerHTML` (number plus popup element). Nothing may read
`textContent` off `#pricing-total-*-estimate|warehouse|competitor`; the vendor-price
column and row `data-` attributes remain the read path for `applyCustomPrice` and
`_getPricingEstimateTotal`.
- The old `_setPartialTotal` helper is gone; do not reintroduce a coverage-only signal.
+52 -99
View File
@@ -1101,16 +1101,11 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
config, err := configService.UpdateNoAuth(uuid, &req)
if err != nil {
switch {
case errors.Is(err, services.ErrConfigNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
@@ -1217,16 +1212,11 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
}
updated, err := configService.SetProjectNoAuth(uuid, req.ProjectUUID)
if err != nil {
switch {
case errors.Is(err, services.ErrConfigNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, updated)
@@ -1354,12 +1344,9 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
}
config, err := configService.UpdateRentalNoAuth(c.Param("uuid"), &req)
if err != nil {
switch {
case errors.Is(err, services.ErrConfigNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
)
return
}
c.JSON(http.StatusOK, config)
@@ -1373,12 +1360,9 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
}
result, err := rentalService.Calculate(c.Param("uuid"), &req)
if err != nil {
switch {
case errors.Is(err, services.ErrConfigNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrConfigNotFound, http.StatusNotFound, "resource not found"},
)
return
}
c.JSON(http.StatusOK, result)
@@ -1627,16 +1611,12 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
}
project, err := projectService.Create(dbUsername, &req)
if err != nil {
switch {
case errors.Is(err, services.ErrReservedMainVariant),
errors.Is(err, services.ErrProjectCodeInvalidChars),
errors.Is(err, services.ErrProjectVariantInvalidChars):
respondError(c, http.StatusBadRequest, "invalid request", err)
case errors.Is(err, services.ErrProjectCodeExists):
respondError(c, http.StatusConflict, "conflict detected", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrReservedMainVariant, http.StatusBadRequest, "invalid request"},
errCase{services.ErrProjectCodeInvalidChars, http.StatusBadRequest, "invalid request"},
errCase{services.ErrProjectVariantInvalidChars, http.StatusBadRequest, "invalid request"},
errCase{services.ErrProjectCodeExists, http.StatusConflict, "conflict detected"},
)
return
}
c.JSON(http.StatusCreated, project)
@@ -1645,14 +1625,10 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
projects.GET("/:uuid", func(c *gin.Context) {
project, err := projectService.GetByUUID(c.Param("uuid"), dbUsername)
if err != nil {
switch {
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, project)
@@ -1666,21 +1642,15 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
}
project, err := projectService.Update(c.Param("uuid"), dbUsername, &req)
if err != nil {
switch {
case errors.Is(err, services.ErrReservedMainVariant),
errors.Is(err, services.ErrCannotRenameMainVariant),
errors.Is(err, services.ErrProjectCodeInvalidChars),
errors.Is(err, services.ErrProjectVariantInvalidChars):
respondError(c, http.StatusBadRequest, "invalid request", err)
case errors.Is(err, services.ErrProjectCodeExists):
respondError(c, http.StatusConflict, "conflict detected", err)
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrReservedMainVariant, http.StatusBadRequest, "invalid request"},
errCase{services.ErrCannotRenameMainVariant, http.StatusBadRequest, "invalid request"},
errCase{services.ErrProjectCodeInvalidChars, http.StatusBadRequest, "invalid request"},
errCase{services.ErrProjectVariantInvalidChars, http.StatusBadRequest, "invalid request"},
errCase{services.ErrProjectCodeExists, http.StatusConflict, "conflict detected"},
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, project)
@@ -1688,14 +1658,10 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
projects.POST("/:uuid/archive", func(c *gin.Context) {
if err := projectService.Archive(c.Param("uuid"), dbUsername); err != nil {
switch {
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, gin.H{"message": "project archived"})
@@ -1703,14 +1669,10 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
projects.POST("/:uuid/reactivate", func(c *gin.Context) {
if err := projectService.Reactivate(c.Param("uuid"), dbUsername); err != nil {
switch {
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, gin.H{"message": "project reactivated"})
@@ -1718,16 +1680,11 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
projects.DELETE("/:uuid", func(c *gin.Context) {
if err := projectService.DeleteVariant(c.Param("uuid"), dbUsername); err != nil {
switch {
case errors.Is(err, services.ErrCannotDeleteMainVariant):
respondError(c, http.StatusBadRequest, "invalid request", err)
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrCannotDeleteMainVariant, http.StatusBadRequest, "invalid request"},
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
c.JSON(http.StatusOK, gin.H{"message": "variant deleted"})
@@ -1744,14 +1701,10 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
result, err := projectService.ListConfigurations(c.Param("uuid"), dbUsername, status)
if err != nil {
switch {
case errors.Is(err, services.ErrProjectNotFound):
respondError(c, http.StatusNotFound, "resource not found", err)
case errors.Is(err, services.ErrProjectForbidden):
respondError(c, http.StatusForbidden, "access denied", err)
default:
respondError(c, http.StatusInternalServerError, "internal server error", err)
}
respondByErrCase(c, err,
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
)
return
}
+31
View File
@@ -0,0 +1,31 @@
package main
import (
"errors"
"net/http"
"git.mchus.pro/mchus/quoteforge/internal/handlers"
"github.com/gin-gonic/gin"
)
// errCase maps a sentinel error to the HTTP status/message respondByErrCase
// should use when errors.Is matches it.
type errCase struct {
err error
status int
message string
}
// respondByErrCase responds with the status/message of the first matching
// case (checked in order), or a 500 "internal server error" fallback when
// none match. Centralizes the switch-on-sentinel-error pattern repeated
// across the config/project HTTP handlers in this file.
func respondByErrCase(c *gin.Context, err error, cases ...errCase) {
for _, cs := range cases {
if errors.Is(err, cs.err) {
handlers.RespondError(c, cs.status, cs.message, err)
return
}
}
handlers.RespondError(c, http.StatusInternalServerError, "internal server error", err)
}
+9 -16
View File
@@ -21,30 +21,23 @@ const (
// ResolveDBPath returns the local SQLite path using priority:
// explicit CLI path > QFS_DB_PATH > OS-specific user state directory.
func ResolveDBPath(explicitPath string) (string, error) {
if explicitPath != "" {
return filepath.Clean(explicitPath), nil
}
if fromEnv := os.Getenv(envDBPath); fromEnv != "" {
return filepath.Clean(fromEnv), nil
}
dir, err := defaultStateDir()
if err != nil {
return "", err
}
return filepath.Join(dir, defaultDB), nil
return resolvePath(explicitPath, envDBPath, defaultDB)
}
// ResolveConfigPath returns the config path using priority:
// explicit CLI path > QFS_CONFIG_PATH > OS-specific user state directory.
func ResolveConfigPath(explicitPath string) (string, error) {
return resolvePath(explicitPath, envCfgPath, defaultCfg)
}
// resolvePath returns a path using priority: explicit CLI path > envVar > OS-specific
// user state directory joined with defaultFilename.
func resolvePath(explicitPath, envVar, defaultFilename string) (string, error) {
if explicitPath != "" {
return filepath.Clean(explicitPath), nil
}
if fromEnv := os.Getenv(envCfgPath); fromEnv != "" {
if fromEnv := os.Getenv(envVar); fromEnv != "" {
return filepath.Clean(fromEnv), nil
}
@@ -53,7 +46,7 @@ func ResolveConfigPath(explicitPath string) (string, error) {
return "", err
}
return filepath.Join(dir, defaultCfg), nil
return filepath.Join(dir, defaultFilename), nil
}
// ResolveConfigPathNearDB returns config path using priority:
+16 -31
View File
@@ -260,17 +260,28 @@ func buildDiskSegment(items []models.ConfigItem, cats map[string]string) (string
}
func buildNetSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
return buildProfileSegment(items, cats, GroupNET, parsePortSpeed, "UNKNET", "net_unknown")
}
func buildPSUSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
return buildProfileSegment(items, cats, GroupPSU, parseWatts, "UNKPSU", "psu_unknown")
}
// buildProfileSegment groups items of the given category group by a profile token
// parsed from their lot name (e.g. port speed, wattage rating), falling back to
// unknownToken and warnCode when a lot's profile can't be determined.
func buildProfileSegment(items []models.ConfigItem, cats map[string]string, group Group, parseProfile func(string) string, unknownToken, warnCode string) (string, string) {
groupQty := map[string]int{}
warn := ""
for _, it := range items {
group, ok := GroupForLotCategory(cats[it.LotName])
if !ok || group != GroupNET {
g, ok := GroupForLotCategory(cats[it.LotName])
if !ok || g != group {
continue
}
profile := parsePortSpeed(it.LotName)
profile := parseProfile(it.LotName)
if profile == "" {
profile = "UNKNET"
warn = "net_unknown"
profile = unknownToken
warn = warnCode
}
groupQty[profile] += it.Quantity
}
@@ -285,32 +296,6 @@ func buildNetSegment(items []models.ConfigItem, cats map[string]string) (string,
return strings.Join(parts, "+"), warn
}
func buildPSUSegment(items []models.ConfigItem, cats map[string]string) (string, string) {
groupQty := map[string]int{}
warn := ""
for _, it := range items {
group, ok := GroupForLotCategory(cats[it.LotName])
if !ok || group != GroupPSU {
continue
}
rating := parseWatts(it.LotName)
if rating == "" {
rating = "UNKPSU"
warn = "psu_unknown"
}
groupQty[rating] += it.Quantity
}
if len(groupQty) == 0 {
return "", ""
}
parts := make([]string, 0, len(groupQty))
for rating, qty := range groupQty {
parts = append(parts, fmt.Sprintf("%dx%s", qty, rating))
}
sort.Strings(parts)
return strings.Join(parts, "+"), warn
}
func normalizeModelToken(lotName string) string {
if idx := strings.Index(lotName, "_"); idx >= 0 && idx+1 < len(lotName) {
lotName = lotName[idx+1:]
+9 -12
View File
@@ -16,13 +16,12 @@ func NewQuoteHandler(quoteService *services.QuoteService) *QuoteHandler {
}
func (h *QuoteHandler) Validate(c *gin.Context) {
var req services.QuoteRequest
if err := c.ShouldBindJSON(&req); err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
req, ok := BindJSON[services.QuoteRequest](c)
if !ok {
return
}
result, err := h.quoteService.ValidateAndCalculate(&req)
result, err := h.quoteService.ValidateAndCalculate(req)
if err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
return
@@ -32,13 +31,12 @@ func (h *QuoteHandler) Validate(c *gin.Context) {
}
func (h *QuoteHandler) Calculate(c *gin.Context) {
var req services.QuoteRequest
if err := c.ShouldBindJSON(&req); err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
req, ok := BindJSON[services.QuoteRequest](c)
if !ok {
return
}
result, err := h.quoteService.ValidateAndCalculate(&req)
result, err := h.quoteService.ValidateAndCalculate(req)
if err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
return
@@ -51,13 +49,12 @@ func (h *QuoteHandler) Calculate(c *gin.Context) {
}
func (h *QuoteHandler) PriceLevels(c *gin.Context) {
var req services.PriceLevelsRequest
if err := c.ShouldBindJSON(&req); err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
req, ok := BindJSON[services.PriceLevelsRequest](c)
if !ok {
return
}
result, err := h.quoteService.CalculatePriceLevels(&req)
result, err := h.quoteService.CalculatePriceLevels(req)
if err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
return
+12
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"github.com/gin-gonic/gin"
@@ -16,6 +17,17 @@ func RespondError(c *gin.Context, status int, fallback string, err error) {
c.JSON(status, gin.H{"error": clientFacingErrorMessage(status, fallback, err)})
}
// BindJSON decodes the request body into T, responding with a 422 and writing
// the error via RespondError on failure. The second return value reports success.
func BindJSON[T any](c *gin.Context) (*T, bool) {
var req T
if err := c.ShouldBindJSON(&req); err != nil {
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
return nil, false
}
return &req, true
}
func clientFacingErrorMessage(status int, fallback string, err error) string {
if err == nil {
return fallback
+1 -1
View File
@@ -104,7 +104,7 @@ func (r *ConfigurationRepository) ListAll(offset, limit int) ([]models.Configura
r.db.Model(&models.Configuration{}).Count(&total)
err := r.db.
Order("created_at DESC").
Order("created_at DESC, id DESC").
Offset(offset).
Limit(limit).
Find(&configs).Error
+16 -6
View File
@@ -59,15 +59,20 @@ type ProjectPricingExportOptions struct {
IncludeStock bool `json:"include_stock"`
IncludeCompetitor bool `json:"include_competitor"`
Basis string `json:"basis"` // "fob" or "ddp"; empty defaults to "fob"
SaleMarkup float64 `json:"sale_markup"` // DDP multiplier; 0 defaults to 1.3
SaleMarkup float64 `json:"sale_markup"` // DDP uplift applied to Estimate only; 0 defaults to 1.3
ManualPrice *float64 `json:"manual_price"` // user-defined total price; distributed proportionally across rows
}
// defaultSaleMarkup mirrors PricingMarkup.DEFAULT_SALE_UPLIFT in web/templates/index.html.
// Keep both in sync; the frontend always sends an explicit value, this is a fallback for
// other API callers that omit sale_markup.
const defaultSaleMarkup = 1.3
func (o ProjectPricingExportOptions) saleMarkupFactor() float64 {
if o.SaleMarkup > 0 {
return o.SaleMarkup
}
return 1.3
return defaultSaleMarkup
}
func (o ProjectPricingExportOptions) isDDP() bool {
@@ -514,11 +519,16 @@ func sortConfigItemsByCategoryMap(items models.ConfigItems, catOrder map[string]
return sorted
}
func applyDDPMarkup(rows []ProjectPricingExportRow, factor float64) {
// stockCompetitorMarkupFactor is the fixed DDP multiplier applied to Stock and
// Competitor columns, independent of the user-configurable estimate uplift.
// Mirrors PricingMarkup.STOCK_COMPETITOR_FIXED in web/templates/index.html.
const stockCompetitorMarkupFactor = 1.3
func applyDDPMarkup(rows []ProjectPricingExportRow, estimateFactor float64) {
for i := range rows {
rows[i].Estimate = scaleFloatPtr(rows[i].Estimate, factor)
rows[i].Stock = scaleFloatPtr(rows[i].Stock, factor)
rows[i].Competitor = scaleFloatPtr(rows[i].Competitor, factor)
rows[i].Estimate = scaleFloatPtr(rows[i].Estimate, estimateFactor)
rows[i].Stock = scaleFloatPtr(rows[i].Stock, stockCompetitorMarkupFactor)
rows[i].Competitor = scaleFloatPtr(rows[i].Competitor, stockCompetitorMarkupFactor)
}
}
+15
View File
@@ -0,0 +1,15 @@
package sync
import "fmt"
// SyncQtSettings pulls qt_settings (tab_config, config_types, etc.) from
// MariaDB into the local cache so the configurator picks up server-driven
// category/tab changes without requiring a client rebuild.
func (s *Service) SyncQtSettings() error {
mariaDB, err := s.getDB()
if err != nil {
return fmt.Errorf("database not available: %w", err)
}
return s.localDB.SyncQtSettings(mariaDB)
}
+5
View File
@@ -100,5 +100,10 @@ func (w *Worker) runSync() {
w.logger.Warn("background sync: failed to pull partnumber books", "error", err)
}
// Pull configurator settings (tab_config, categories, etc.)
if err := w.service.SyncQtSettings(); err != nil {
w.logger.Warn("background sync: failed to sync qt_settings", "error", err)
}
w.logger.Info("background sync cycle completed")
}
+1 -1
View File
@@ -11,7 +11,7 @@
- список допустимых LOT конфигуратора собирается из объединения прайслистов `world` и `estimate`, а не только из `estimate`. Прежняя область видимости молча теряла сопоставления BOM: резолвер находил LOT по книге партномеров, которая про прайслисты ничего не знает, а фронт отбрасывал всё, чего нет в estimate — при этом в корзину такой LOT всё равно попадал, и строка BOM оставалась с «н/д». Дедупликация по имени LOT без учёта регистра, при совпадении выигрывает запись из estimate; позиции, найденные только в world, показываются с качеством цены 0 (самый красный);
- LOT, сопоставленный по книге партномеров, сохраняется в спецификации, даже если его нет ни в одном прайслисте — раньше такое сопоставление пропадало без предупреждения. LOT, введённые руками, по-прежнему проверяются по списку;
- кнопка «Пересопоставить» на вкладке BOM — заново прогоняет строки через актуальную книгу партномеров. При открытии конфигурации сопоставления намеренно остаются такими, какими были сохранены, поэтому записи, добавленные в книгу позже, подхватываются только этой кнопкой;
- вкладка «Ценообразование»: убраны звёздочки у итогов (переносились на отдельную строку и разъезжались), все три суммы — Estimate, Склад, Конкуренты — показываются красным, а при наведении всплывает подсказка с долей суммы, посчитанной по ценам-заглушкам из прайслиста `world`, и с покрытием по позициям;
- вкладка «Ценообразование»: убраны звёздочки у итогов (переносились на отдельную строку и разъезжались). Итог по столбцам Estimate, Склад и Конкуренты подсвечивается красным тогда и только тогда, когда часть суммы посчитана по ценам-заглушкам из прайслиста `world`; при наведении всплывает подсказка с точной долей таких цен и с покрытием по позициям;
- колонка «PN вендора» на вкладке «Ценообразование» больше не переносит партномер на две строки;
- индикатор качества цены показывается во всех таблицах конфигуратора, а не только на вкладке Base; колонка-индикатор везде без текстового заголовка, только с тултипом.
+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.
+90 -172
View File
@@ -474,9 +474,17 @@ let TAB_CONFIG = {
}
};
let ASSIGNED_CATEGORIES = Object.values(TAB_CONFIG)
.flatMap(t => t.categories)
.map(c => ciStr(c));
// Categories belonging to any real tab (everything except "other").
// "other" is defined as "whatever isn't in this set" — it must never
// contribute to it, or its own contents would exclude themselves.
function computeAssignedCategories() {
return Object.entries(TAB_CONFIG)
.filter(([key]) => key !== 'other')
.flatMap(([, t]) => t._allCategories || t.categories)
.map(c => ciStr(c));
}
let ASSIGNED_CATEGORIES = computeAssignedCategories();
// State
let configUUID = '{{.ConfigUUID}}';
@@ -601,6 +609,19 @@ let warehouseStockLoadsByPricelist = new Map();
let componentPricesCache = {}; // { lot_name: price } - caches prices loaded via API
let componentPricesCacheLoading = new Map(); // { category: Promise } - tracks ongoing price loads
// ─── Sale (DDP) pricing markup — single source of truth for this file ───
// Mirrors internal/services/export.go (saleMarkupFactor / stockCompetitorMarkupFactor).
// Keep both sides in sync: Estimate scales by the user's uplift, Stock/Competitor by a fixed factor.
const PricingMarkup = {
DEFAULT_SALE_UPLIFT: 1.3,
STOCK_COMPETITOR_FIXED: 1.3,
// Reads the "Аплифт к estimate" input; falls back to DEFAULT_SALE_UPLIFT when empty/invalid.
getSaleUplift() {
const v = parseDecimalInput(document.getElementById('pricing-uplift-sale')?.value || '');
return v > 0 ? v : this.DEFAULT_SALE_UPLIFT;
},
};
// Autocomplete state
let autocompleteInput = null;
let autocompleteCategory = null;
@@ -822,23 +843,20 @@ async function loadCategoriesFromAPI() {
categoryOrderMap[ciStr(cat.code)] = cat.display_order;
});
// Build list of unassigned categories
const knownCodes = Object.values(TAB_CONFIG)
.flatMap(t => t.categories)
.map(c => ciStr(c));
// Build list of unassigned categories (excludes "other" itself, so
// this stays correct even if it's re-run after "other" was already
// populated by a previous call).
const knownCodes = computeAssignedCategories();
const unassignedCategories = cats
.filter(cat => !knownCodes.includes(ciStr(cat.code)))
.sort((a, b) => a.display_order - b.display_order)
.map(cat => cat.code);
ASSIGNED_CATEGORIES = knownCodes;
// Update "other" tab with unassigned categories
TAB_CONFIG.other.categories = unassignedCategories;
// Rebuild ASSIGNED_CATEGORIES
ASSIGNED_CATEGORIES = Object.values(TAB_CONFIG)
.flatMap(t => t.categories)
.map(c => ciStr(c));
} catch(e) {
console.error('Failed to load categories, using defaults', e);
// Will use default configuration if API fails
@@ -882,8 +900,12 @@ function applyServerSettings(settings) {
sections: tab.sections || undefined
};
});
// Rebuild ASSIGNED_CATEGORIES from the known (non-"other") tabs only,
// before restoring .other — otherwise categories already parked in
// .other (e.g. by loadCategoriesFromAPI) get counted as "assigned"
// and immediately excluded from the "other" tab again.
ASSIGNED_CATEGORIES = computeAssignedCategories();
TAB_CONFIG.other = otherTab || { categories: [], singleSelect: false, label: 'Other' };
ASSIGNED_CATEGORIES = Object.values(TAB_CONFIG).flatMap(t => t.categories).map(c => ciStr(c));
}
// always_visible_tabs
@@ -1394,11 +1416,10 @@ function applyConfigTypeToTabs() {
}
});
// Rebuild assigned categories index using the full static list (_allCategories),
// not the filtered one — hidden categories still belong to their tab, not to Other.
ASSIGNED_CATEGORIES = Object.values(TAB_CONFIG)
.flatMap(t => t._allCategories || t.categories)
.map(c => ciStr(c));
// Rebuild assigned categories index using the full static list
// (_allCategories), not the filtered one — hidden categories still
// belong to their tab, not to Other.
ASSIGNED_CATEGORIES = computeAssignedCategories();
}
function updateTabVisibility() {
@@ -1877,7 +1898,10 @@ function renderAutocomplete() {
dropdown.classList.remove('hidden');
}
function handleAutocompleteKey(event, category) {
// Shared ArrowUp/ArrowDown/Enter/Escape navigation for all autocomplete dropdown
// variants (single-select, multi-select, section, edit-item, BOM row); onSelect
// receives the chosen autocompleteFiltered index and applies it to that context.
function handleAutocompleteKeyGeneric(event, onSelect) {
if (event.key === 'ArrowDown') {
event.preventDefault();
autocompleteIndex = Math.min(autocompleteIndex + 1, autocompleteFiltered.length - 1);
@@ -1889,27 +1913,23 @@ function handleAutocompleteKey(event, category) {
} else if (event.key === 'Enter') {
event.preventDefault();
if (autocompleteIndex >= 0 && autocompleteIndex < autocompleteFiltered.length) {
selectAutocompleteItem(autocompleteIndex);
onSelect(autocompleteIndex);
}
} else if (event.key === 'Escape') {
hideAutocomplete();
}
}
function selectAutocompleteItem(index) {
const comp = autocompleteFiltered[index];
if (!comp || !autocompleteCategory) return;
function handleAutocompleteKey(event, category) {
handleAutocompleteKeyGeneric(event, (index) => selectAutocompleteItem(index));
}
// Remove existing item of this category
cart = cart.filter(item =>
ciStr(item.category) !== ciStr(autocompleteCategory)
);
const qtyInput = document.getElementById('qty-' + autocompleteCategory);
const qty = parseInt(qtyInput?.value) || 1;
// Builds a fresh cart entry for a component picked from an autocomplete dropdown.
// Warehouse/competitor prices and their deltas start unknown (null) until the
// next price-levels refresh fills them in.
function buildNewCartItem(comp, qty) {
const price = componentPricesCache[comp.lot_name] || 0;
cart.push({
return {
lot_name: comp.lot_name,
quantity: qty,
unit_price: price,
@@ -1925,15 +1945,35 @@ function selectAutocompleteItem(index) {
price_missing: ['warehouse', 'competitor'],
description: comp.description || '',
category: getComponentCategory(comp)
});
};
}
hideAutocomplete();
// Re-renders the tab/cart and kicks off autosave + a price-levels refresh
// after a cart mutation from an autocomplete selection.
function commitCartChange() {
renderTab();
updateCartUI();
triggerAutoSave();
schedulePriceLevelsRefresh({ delay: 80, rerender: true, autosave: false });
}
function selectAutocompleteItem(index) {
const comp = autocompleteFiltered[index];
if (!comp || !autocompleteCategory) return;
// Remove existing item of this category
cart = cart.filter(item =>
ciStr(item.category) !== ciStr(autocompleteCategory)
);
const qtyInput = document.getElementById('qty-' + autocompleteCategory);
const qty = parseInt(qtyInput?.value) || 1;
cart.push(buildNewCartItem(comp, qty));
hideAutocomplete();
commitCartChange();
}
function hideAutocomplete() {
document.getElementById('autocomplete-dropdown').classList.add('hidden');
autocompleteInput = null;
@@ -1978,22 +2018,7 @@ function filterAutocompleteMulti(search) {
}
function handleAutocompleteKeyMulti(event) {
if (event.key === 'ArrowDown') {
event.preventDefault();
autocompleteIndex = Math.min(autocompleteIndex + 1, autocompleteFiltered.length - 1);
renderAutocomplete();
} else if (event.key === 'ArrowUp') {
event.preventDefault();
autocompleteIndex = Math.max(autocompleteIndex - 1, -1);
renderAutocomplete();
} else if (event.key === 'Enter') {
event.preventDefault();
if (autocompleteIndex >= 0 && autocompleteIndex < autocompleteFiltered.length) {
selectAutocompleteItemMulti(autocompleteIndex);
}
} else if (event.key === 'Escape') {
hideAutocomplete();
}
handleAutocompleteKeyGeneric(event, (index) => selectAutocompleteItemMulti(index));
}
function selectAutocompleteItemMulti(index) {
@@ -2002,31 +2027,10 @@ function selectAutocompleteItemMulti(index) {
const qtyInput = document.getElementById('new-qty');
const qty = parseInt(qtyInput?.value) || 1;
const price = componentPricesCache[comp.lot_name] || 0;
cart.push({
lot_name: comp.lot_name,
quantity: qty,
unit_price: price,
estimate_price: price,
warehouse_price: null,
competitor_price: null,
delta_wh_estimate_abs: null,
delta_wh_estimate_pct: null,
delta_comp_estimate_abs: null,
delta_comp_estimate_pct: null,
delta_comp_wh_abs: null,
delta_comp_wh_pct: null,
price_missing: ['warehouse', 'competitor'],
description: comp.description || '',
category: getComponentCategory(comp)
});
cart.push(buildNewCartItem(comp, qty));
hideAutocomplete();
renderTab();
updateCartUI();
triggerAutoSave();
schedulePriceLevelsRefresh({ delay: 80, rerender: true, autosave: false });
commitCartChange();
}
// Autocomplete for sectioned tabs (like storage with RAID and Disks sections)
@@ -2083,22 +2087,7 @@ function filterAutocompleteSection(sectionId, search, inputElement) {
}
function handleAutocompleteKeySection(event, sectionId) {
if (event.key === 'ArrowDown') {
event.preventDefault();
autocompleteIndex = Math.min(autocompleteIndex + 1, autocompleteFiltered.length - 1);
renderAutocomplete();
} else if (event.key === 'ArrowUp') {
event.preventDefault();
autocompleteIndex = Math.max(autocompleteIndex - 1, -1);
renderAutocomplete();
} else if (event.key === 'Enter') {
event.preventDefault();
if (autocompleteIndex >= 0 && autocompleteIndex < autocompleteFiltered.length) {
selectAutocompleteItemSection(autocompleteIndex, sectionId);
}
} else if (event.key === 'Escape') {
hideAutocomplete();
}
handleAutocompleteKeyGeneric(event, (index) => selectAutocompleteItemSection(index, sectionId));
}
function selectAutocompleteItemSection(index, sectionId) {
@@ -2107,25 +2096,7 @@ function selectAutocompleteItemSection(index, sectionId) {
const qtyInput = document.getElementById('new-qty-' + sectionId);
const qty = parseInt(qtyInput?.value) || 1;
const price = componentPricesCache[comp.lot_name] || 0;
cart.push({
lot_name: comp.lot_name,
quantity: qty,
unit_price: price,
estimate_price: price,
warehouse_price: null,
competitor_price: null,
delta_wh_estimate_abs: null,
delta_wh_estimate_pct: null,
delta_comp_estimate_abs: null,
delta_comp_estimate_pct: null,
delta_comp_wh_abs: null,
delta_comp_wh_pct: null,
price_missing: ['warehouse', 'competitor'],
description: comp.description || '',
category: getComponentCategory(comp)
});
cart.push(buildNewCartItem(comp, qty));
hideAutocomplete();
@@ -2135,10 +2106,7 @@ function selectAutocompleteItemSection(index, sectionId) {
// Reset quantity to 1
if (qtyInput) qtyInput.value = '1';
renderTab();
updateCartUI();
triggerAutoSave();
schedulePriceLevelsRefresh({ delay: 80, rerender: true, autosave: false });
commitCartChange();
}
// Autocomplete for editing an existing cart item's LOT (multi/section tabs)
@@ -2172,22 +2140,7 @@ function filterAutocompleteEditItem(search) {
}
function handleAutocompleteKeyEditItem(event) {
if (event.key === 'ArrowDown') {
event.preventDefault();
autocompleteIndex = Math.min(autocompleteIndex + 1, autocompleteFiltered.length - 1);
renderAutocomplete();
} else if (event.key === 'ArrowUp') {
event.preventDefault();
autocompleteIndex = Math.max(autocompleteIndex - 1, -1);
renderAutocomplete();
} else if (event.key === 'Enter') {
event.preventDefault();
if (autocompleteIndex >= 0 && autocompleteIndex < autocompleteFiltered.length) {
selectAutocompleteEditItem(autocompleteIndex);
}
} else if (event.key === 'Escape') {
hideAutocomplete();
}
handleAutocompleteKeyGeneric(event, (index) => selectAutocompleteEditItem(index));
}
function selectAutocompleteEditItem(index) {
@@ -2197,29 +2150,10 @@ function selectAutocompleteEditItem(index) {
const oldItem = cart.find(i => i.lot_name === lotName);
const qty = oldItem?.quantity || 1;
cart = cart.filter(i => i.lot_name !== lotName);
const price = componentPricesCache[comp.lot_name] || 0;
cart.push({
lot_name: comp.lot_name,
quantity: qty,
unit_price: price,
estimate_price: price,
warehouse_price: null,
competitor_price: null,
delta_wh_estimate_abs: null,
delta_wh_estimate_pct: null,
delta_comp_estimate_abs: null,
delta_comp_estimate_pct: null,
delta_comp_wh_abs: null,
delta_comp_wh_pct: null,
price_missing: ['warehouse', 'competitor'],
description: comp.description || '',
category: getComponentCategory(comp)
});
cart.push(buildNewCartItem(comp, qty));
hideAutocomplete();
renderTab();
updateCartUI();
triggerAutoSave();
schedulePriceLevelsRefresh({ delay: 80, rerender: true, autosave: false });
commitCartChange();
}
// Autocomplete for BOM LOT mapping
@@ -2255,22 +2189,7 @@ function filterAutocompleteBOM(rowIdx, search) {
}
function handleAutocompleteKeyBOM(event, rowIdx) {
if (event.key === 'ArrowDown') {
event.preventDefault();
autocompleteIndex = Math.min(autocompleteIndex + 1, autocompleteFiltered.length - 1);
renderAutocomplete();
} else if (event.key === 'ArrowUp') {
event.preventDefault();
autocompleteIndex = Math.max(autocompleteIndex - 1, -1);
renderAutocomplete();
} else if (event.key === 'Enter') {
event.preventDefault();
if (autocompleteIndex >= 0 && autocompleteIndex < autocompleteFiltered.length) {
selectAutocompleteItemBOM(autocompleteIndex, rowIdx);
}
} else if (event.key === 'Escape') {
hideAutocomplete();
}
handleAutocompleteKeyGeneric(event, (index) => selectAutocompleteItemBOM(index, rowIdx));
}
function selectAutocompleteItemBOM(index, rowIdx) {
@@ -4565,12 +4484,9 @@ async function renderPricingTab() {
} catch(e) { /* silent */ }
}
// Sale uplift applied to estimate (default 1.3)
const saleUplift = (() => {
const v = parseDecimalInput(document.getElementById('pricing-uplift-sale')?.value || '');
return v > 0 ? v : 1.3;
})();
const SALE_FIXED_MULT = 1.3;
// Sale uplift applied to estimate; Stock/Competitor use the fixed factor. See PricingMarkup.
const saleUplift = PricingMarkup.getSaleUplift();
const SALE_FIXED_MULT = PricingMarkup.STOCK_COMPETITOR_FIXED;
// Helper: returns unit prices from pricelist for a single LOT
const _getUnitPrices = (pl) => ({
@@ -5020,6 +4936,7 @@ async function exportPricingCSV(table) {
const basis = table === 'sale' ? 'ddp' : 'fob';
const manualInputId = table === 'sale' ? 'pricing-custom-price-sale' : 'pricing-custom-price-buy';
const manualPrice = parseDecimalInput(document.getElementById(manualInputId)?.value || '');
const saleUplift = table === 'sale' ? PricingMarkup.getSaleUplift() : 0;
try {
const resp = await fetch(`/api/configs/${configUUID}/export/pricing`, {
method: 'POST',
@@ -5031,6 +4948,7 @@ async function exportPricingCSV(table) {
include_stock: true,
include_competitor: true,
basis: basis,
sale_markup: saleUplift > 0 ? saleUplift : null,
manual_price: manualPrice > 0 ? manualPrice : null,
}),
});