Compare commits
14
Commits
34cee5f874
..
v3.39
No files matched your search
+1
-1
Submodule bible updated: 52444350c1...1977730d93.
@@ -85,6 +85,12 @@ Controls terminology:
|
||||
|
||||
CSV export reads PN вендора, Описание, and LOT from `data-vendor-pn`, `data-desc`, `data-lot` row attributes to bypass the rowspan cell offset problem.
|
||||
|
||||
In the colour-optional indicator mode (`app_settings.indicator_mode = "accessible"`, see
|
||||
[03-database.md](03-database.md) and [decisions/2026-08-31-accessible-indicator-mode.md](decisions/2026-08-31-accessible-indicator-mode.md))
|
||||
both tables gain a narrow leading price-quality meter column (per sub-row), the row background
|
||||
tint is removed, `world`-fallback cells show a `W` text marker instead of amber, and the footer
|
||||
total shows a `⚠` prefix instead of red. CSV output is unaffected.
|
||||
|
||||
## Configuration versioning
|
||||
|
||||
Configuration revisions are append-only snapshots stored in `local_configuration_versions`.
|
||||
|
||||
@@ -17,7 +17,7 @@ Main tables:
|
||||
| `local_partnumber_book_items` | PN -> LOT catalog payload |
|
||||
| `pending_changes` | sync queue |
|
||||
| `connection_settings` | encrypted MariaDB connection settings |
|
||||
| `app_settings` | local app state |
|
||||
| `app_settings` | local app state (key→value); includes `indicator_mode` = `color` \| `accessible`, a per-client display preference set on `/setup` |
|
||||
| `local_schema_migrations` | applied local migration markers |
|
||||
| `local_qt_settings` | server-pushed configurator settings cache (from `qt_settings`) |
|
||||
|
||||
@@ -261,7 +261,9 @@ PK: lot_name
|
||||
| price | decimal(12,2) NOT NULL | |
|
||||
| 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).
|
||||
`price_quality` is synced through `LocalPricelistItem` (pricelist detail page) and, separately, through `LocalComponent`/`services.ComponentView` (`/api/components`, used by the configurator's search dropdown and item table) — both read paths go through `pricelistItemRow`/`toLocalComponent()` in `internal/localdb/components.go`. The `/api/components` path reads the component universe (`world` ∪ `estimate`, see [decisions/2026-07-24-component-universe-world-union.md](decisions/2026-07-24-component-universe-world-union.md)), where a world-only LOT is forced to `price_quality = 0` — the only place QF writes this field rather than reading it. The visual scale lives in **one shared JS module**, `web/static/price-quality.js` (loaded by `base.html` for every page) — `priceQualityColor`/`priceQualityLevel`/`qualityMeterHtml`/`qualityDotHtml`/`qualityBadgeHtml`/`qualityRowStyle`. Do not reimplement the scale locally in a template; add a new helper to that module instead. Used in: pricelist detail "Качество" column, configurator search dropdown, configurator table (leftmost quality column), pricing tab.
|
||||
|
||||
The module has **two render modes**, chosen per client by `window.QF_INDICATOR_MODE` (injected by `base.html` from `app_settings.indicator_mode`, default `color`): `color` = hue scale red 0 → yellow 5 → green 9; `accessible` = colour-blind-safe 5-step signal-strength meter (`priceQualityLevel`: `0-1/2-3/4-5/6-7/8-9`), single neutral hue. In `accessible` mode the pricing tab drops the row background tint for a leading meter column, the `world`-fallback amber cell tint becomes a `W` text marker, and the "contaminated total" red becomes a `⚠` prefix — see [decisions/2026-08-31-accessible-indicator-mode.md](decisions/2026-08-31-accessible-indicator-mode.md). Any new colour-only signal must add a branch in this module keyed on `isAccessible()`, not a local one.
|
||||
|
||||
The real table also has `price_method`, `price_period_days`, `price_coefficient`, `manual_price`, `meta_prices` and `lead_time_weeks` columns, owned and written by the external pricing engine that maintains `qt_pricelist_items` — **keep them in the table for backward compatibility with that system; QF must never drop, rename, or write to them.** QF itself does not model, sync, or display any of them (tried once, removed as unused/dead in the client). Do not re-add them to `models.PricelistItem`/`LocalPricelistItem` without a concrete UI need.
|
||||
|
||||
|
||||
@@ -29,6 +29,17 @@
|
||||
|
||||
`POST /api/restart` exists only in `debug` mode.
|
||||
|
||||
## Settings
|
||||
|
||||
| Method | Path | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `GET` | `/api/settings/ui` | read per-client UI display preferences → `{ "indicator_mode": "color" \| "accessible" }` |
|
||||
| `PUT` | `/api/settings/ui` | set `indicator_mode` (body `{ "indicator_mode": ... }`); `422` on an unknown value |
|
||||
|
||||
Stored in `app_settings` (SQLite); no restart. Registered in both the normal and the setup-mode
|
||||
route sets. Consumed by `web/static/price-quality.js` and the pricing tab via a
|
||||
`window.QF_INDICATOR_MODE` global that `base.html` renders from the same setting.
|
||||
|
||||
## Reference data
|
||||
|
||||
| Method | Path | Purpose |
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
# Decision: project-level DDP export uses each configuration's own sale uplift
|
||||
|
||||
**Date:** 2026-08-12
|
||||
**Status:** active
|
||||
|
||||
## Context
|
||||
|
||||
Two code paths produce the same "Ценообразование" (pricing) CSV: exporting a single
|
||||
configuration from `index.html` (`exportPricingCSV`), and exporting an entire project
|
||||
from `project_detail.html` (`exportProject` → `POST /api/projects/:uuid/export` →
|
||||
`ExportProjectPricingCSV`). Both end up in `ExportService.buildPricingExportBlock`.
|
||||
|
||||
Each configuration's "Аплифт к estimate" (`#pricing-uplift-sale` in the pricing tab) is
|
||||
saved per configuration, piggybacked into `Configuration.Notes` as
|
||||
`{"pricing_ui":{"sale_uplift":...}}` (see `serializeConfigNotes`/
|
||||
`restorePricingStateFromNotes` in `index.html`). The single-config export sends this value
|
||||
explicitly as `sale_markup` in the request, so it always applies the right uplift.
|
||||
|
||||
The project-level export modal never had an uplift input and never sent `sale_markup`, so
|
||||
`ProjectPricingExportOptions.SaleMarkup` was always `0`. `buildPricingExportBlock` used to
|
||||
fall back to a single hardcoded `defaultSaleMarkup` (1.3) for every configuration in the
|
||||
project, silently ignoring each configuration's own saved uplift — a bulk DDP export did
|
||||
not match what exporting those same configurations individually would produce.
|
||||
|
||||
## Decision
|
||||
|
||||
`buildPricingExportBlock` resolves the DDP estimate factor per configuration via
|
||||
`ProjectPricingExportOptions.effectiveSaleMarkupFactor(cfg)`:
|
||||
|
||||
- an explicit `opts.SaleMarkup` (only ever sent by the single-config pricing tab, which
|
||||
knows the live-edited value that may not be saved yet) always wins;
|
||||
- otherwise it reads that configuration's own saved uplift from `Notes`
|
||||
(`configSavedSaleUplift`);
|
||||
- otherwise it falls back to `defaultSaleMarkup` (1.3), same as before, for configurations
|
||||
that never had an uplift saved.
|
||||
|
||||
Both `applyDDPMarkup` call sites in `buildPricingExportBlock` (the BOM-driven branch and
|
||||
the plain-items fallback) use this per-configuration factor. Stock/Competitor keep using
|
||||
the fixed `stockCompetitorMarkupFactor` (1.3) — only the Estimate uplift is configurable.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Project-level DDP export now goes through the same "pipeline" as single-config export:
|
||||
each row's Estimate is scaled by that configuration's own saved uplift, not a
|
||||
project-wide constant.
|
||||
- If a future caller needs to force one uplift across an entire project export regardless
|
||||
of individual configs' saved settings, it must do so explicitly via `sale_markup` in the
|
||||
request — do not reintroduce a silent global default that overrides saved per-config
|
||||
values.
|
||||
- `configSavedSaleUplift` only reads `Notes`; it does not fail loudly on malformed/foreign
|
||||
JSON in that field — it just returns 0 and lets the 1.3 fallback apply.
|
||||
@@ -0,0 +1,63 @@
|
||||
# Decision: `indicator_mode` — a colour-optional rendering mode for UI signals
|
||||
|
||||
**Date:** 2026-08-31
|
||||
**Status:** active
|
||||
|
||||
## Context
|
||||
|
||||
Several UI signals were encoded by hue alone and unreadable with a colour-vision deficiency:
|
||||
|
||||
- `price_quality` (0–9) as a red→yellow→green gradient — a dot in the configurator search
|
||||
dropdown and inline before `lot_name`, a coloured number in the pricelist "Качество" column,
|
||||
a full-row background tint on the "Ценообразование" tab;
|
||||
- the amber `world`-fallback price cell tint
|
||||
([2026-07-10-world-pricelist-fallback.md](2026-07-10-world-pricelist-fallback.md));
|
||||
- the red "contaminated total" in the pricing footer
|
||||
([2026-07-24-pricing-total-world-share.md](2026-07-24-pricing-total-world-share.md)).
|
||||
|
||||
The bible has no dedicated accessibility contract, but `table-management` §Icon Semantics,
|
||||
`controls-selection` §Buttons, `go-code-style` §Business Logic Placement and `build-version-display`
|
||||
say the same thing: meaning is never carried by one ambiguous channel — back it with
|
||||
shape / number / explicit `title`+`aria-label`, and keep the indicator visually subordinate.
|
||||
|
||||
## Decision
|
||||
|
||||
One per-client preference, **`app_settings.indicator_mode`** = `color` (default) | `accessible`,
|
||||
set on `/setup` ("Настройки") via `GET`/`PUT /api/settings/ui` (`internal/handlers/settings.go`)
|
||||
— no restart. Deliberately named for the concern (how indicators are rendered), not for the
|
||||
current widget, so future colour-only signals attach to the same switch.
|
||||
|
||||
`internal/handlers/web.go` `render()` and `internal/handlers/setup.go` inject the mode for every
|
||||
page; `base.html` publishes it as `window.QF_INDICATOR_MODE`. `web/static/price-quality.js` is
|
||||
still the single source of the price-quality scale and branches on the mode internally, so its
|
||||
call sites do not change.
|
||||
|
||||
In `accessible` mode:
|
||||
|
||||
- `price_quality` renders as a **5-step signal-strength meter** (`priceQualityLevel` =
|
||||
`min(4, floor(score/2))` → `0-1 / 2-3 / 4-5 / 6-7 / 8-9`), five bars in one neutral hue, each
|
||||
instance carrying `title`/`aria-label` = `Качество цены: N/9`. `qualityDotHtml` and
|
||||
`qualityBadgeHtml` return the meter;
|
||||
- `qualityRowStyle` returns `''` — the pricing tab instead shows the meter in a narrow leading
|
||||
column (conditional `<th>` / `colspan` in `index.html`, per-sub-row `<td>`);
|
||||
- the `world`-fallback amber class is dropped for a `W` superscript text marker on the price
|
||||
(text, not a colour class — `applyCustomPrice`'s colour-stripping regex is a non-issue);
|
||||
- `_setPricingTotal` drops `text-red-600` for a leading `⚠` glyph, on the same trigger as the
|
||||
red (`worldShare > 0`). The hover popup — including the "prices for N of M positions" coverage
|
||||
line — is unchanged in both modes; per 2026-07-24 there is still no colour-coded coverage-only
|
||||
signal, and `accessible` mode does not add one.
|
||||
|
||||
`color` mode is byte-for-byte the previous behaviour.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Default unchanged; nothing moves until a user opts in on `/setup`.
|
||||
- `web/static/price-quality.js` stays the only place that knows the 0–9 scale. Any new
|
||||
colour-coded quality/price signal adds a branch there keyed on `isAccessible()`, never a local
|
||||
reimplementation, and its `accessible` form must be shape/text, not another hue.
|
||||
- The pricing-tab tables have a mode-dependent column count (8 / 9). `index.html` guards the
|
||||
`<th>`, the empty-state `colspan`, the `tfoot` "Итого:" `colspan` and the JS row template on
|
||||
`ACCESSIBLE_MODE` / `{{ eq .IndicatorMode "accessible" }}`. CSV export is untouched — it reads
|
||||
`data-*` row attributes, not cell positions.
|
||||
- New routes `GET`/`PUT /api/settings/ui`, registered in both the normal and setup-mode route
|
||||
sets in `cmd/qfs/main.go`. `render()` nil-guards `localDB` for tests.
|
||||
+79
-113
@@ -581,6 +581,10 @@ func runSetupMode(local *localdb.LocalDB) {
|
||||
router.POST("/setup/test", setupHandler.TestConnection)
|
||||
router.GET("/setup/status", setupHandler.GetStatus)
|
||||
|
||||
settingsHandler := handlers.NewSettingsHandler(local)
|
||||
router.GET("/api/settings/ui", settingsHandler.GetUI)
|
||||
router.PUT("/api/settings/ui", settingsHandler.PutUI)
|
||||
|
||||
// Health check
|
||||
router.GET("/health", func(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
@@ -892,6 +896,11 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
router.POST("/setup/test", setupHandler.TestConnection)
|
||||
router.GET("/setup/status", setupHandler.GetStatus)
|
||||
|
||||
// Per-client UI display preferences
|
||||
settingsHandler := handlers.NewSettingsHandler(local)
|
||||
router.GET("/api/settings/ui", settingsHandler.GetUI)
|
||||
router.PUT("/api/settings/ui", settingsHandler.PutUI)
|
||||
|
||||
// Web pages
|
||||
router.GET("/", webHandler.Index)
|
||||
router.GET("/configs", webHandler.Configs)
|
||||
@@ -1101,16 +1110,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 +1221,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 +1353,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 +1369,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)
|
||||
@@ -1590,25 +1583,29 @@ 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"`
|
||||
RentalEnabled bool `json:"rental_enabled"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UUID string `json:"uuid"`
|
||||
Code string `json:"code"`
|
||||
Variant string `json:"variant"`
|
||||
Name string `json:"name"`
|
||||
IsActive bool `json:"is_active"`
|
||||
RentalEnabled bool `json:"rental_enabled"`
|
||||
ShowStockPrices bool `json:"show_stock_prices"`
|
||||
OnlyInStock bool `json:"only_in_stock"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
simplified := make([]ProjectSimple, 0, len(allProjects))
|
||||
for _, p := range allProjects {
|
||||
simplified = append(simplified, ProjectSimple{
|
||||
UUID: p.UUID,
|
||||
Code: p.Code,
|
||||
Variant: p.Variant,
|
||||
Name: derefString(p.Name),
|
||||
IsActive: p.IsActive,
|
||||
RentalEnabled: p.RentalEnabled,
|
||||
CreatedAt: p.CreatedAt,
|
||||
UUID: p.UUID,
|
||||
Code: p.Code,
|
||||
Variant: p.Variant,
|
||||
Name: derefString(p.Name),
|
||||
IsActive: p.IsActive,
|
||||
RentalEnabled: p.RentalEnabled,
|
||||
ShowStockPrices: p.ShowStockPrices,
|
||||
OnlyInStock: p.OnlyInStock,
|
||||
CreatedAt: p.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1627,16 +1624,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 +1638,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 +1655,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 +1671,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 +1682,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 +1693,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 +1714,10 @@ func setupRouter(cfg *config.Config, local *localdb.LocalDB, connMgr *db.Connect
|
||||
|
||||
result, err := projectService.ListConfigurations(c.Param("uuid"), dbUsername, status)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, services.ErrProjectNotFound):
|
||||
respondError(c, http.StatusNotFound, "resource not found", err)
|
||||
case errors.Is(err, services.ErrProjectForbidden):
|
||||
respondError(c, http.StatusForbidden, "access denied", err)
|
||||
default:
|
||||
respondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
}
|
||||
respondByErrCase(c, err,
|
||||
errCase{services.ErrProjectNotFound, http.StatusNotFound, "resource not found"},
|
||||
errCase{services.ErrProjectForbidden, http.StatusForbidden, "access denied"},
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/handlers"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// errCase maps a sentinel error to the HTTP status/message respondByErrCase
|
||||
// should use when errors.Is matches it.
|
||||
type errCase struct {
|
||||
err error
|
||||
status int
|
||||
message string
|
||||
}
|
||||
|
||||
// respondByErrCase responds with the status/message of the first matching
|
||||
// case (checked in order), or a 500 "internal server error" fallback when
|
||||
// none match. Centralizes the switch-on-sentinel-error pattern repeated
|
||||
// across the config/project HTTP handlers in this file.
|
||||
func respondByErrCase(c *gin.Context, err error, cases ...errCase) {
|
||||
for _, cs := range cases {
|
||||
if errors.Is(err, cs.err) {
|
||||
handlers.RespondError(c, cs.status, cs.message, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
handlers.RespondError(c, http.StatusInternalServerError, "internal server error", err)
|
||||
}
|
||||
@@ -21,30 +21,23 @@ const (
|
||||
// ResolveDBPath returns the local SQLite path using priority:
|
||||
// explicit CLI path > QFS_DB_PATH > OS-specific user state directory.
|
||||
func ResolveDBPath(explicitPath string) (string, error) {
|
||||
if explicitPath != "" {
|
||||
return filepath.Clean(explicitPath), nil
|
||||
}
|
||||
|
||||
if fromEnv := os.Getenv(envDBPath); fromEnv != "" {
|
||||
return filepath.Clean(fromEnv), nil
|
||||
}
|
||||
|
||||
dir, err := defaultStateDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return filepath.Join(dir, defaultDB), nil
|
||||
return resolvePath(explicitPath, envDBPath, defaultDB)
|
||||
}
|
||||
|
||||
// ResolveConfigPath returns the config path using priority:
|
||||
// explicit CLI path > QFS_CONFIG_PATH > OS-specific user state directory.
|
||||
func ResolveConfigPath(explicitPath string) (string, error) {
|
||||
return resolvePath(explicitPath, envCfgPath, defaultCfg)
|
||||
}
|
||||
|
||||
// resolvePath returns a path using priority: explicit CLI path > envVar > OS-specific
|
||||
// user state directory joined with defaultFilename.
|
||||
func resolvePath(explicitPath, envVar, defaultFilename string) (string, error) {
|
||||
if explicitPath != "" {
|
||||
return filepath.Clean(explicitPath), nil
|
||||
}
|
||||
|
||||
if fromEnv := os.Getenv(envCfgPath); fromEnv != "" {
|
||||
if fromEnv := os.Getenv(envVar); fromEnv != "" {
|
||||
return filepath.Clean(fromEnv), nil
|
||||
}
|
||||
|
||||
@@ -53,7 +46,7 @@ func ResolveConfigPath(explicitPath string) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return filepath.Join(dir, defaultCfg), nil
|
||||
return filepath.Join(dir, defaultFilename), nil
|
||||
}
|
||||
|
||||
// ResolveConfigPathNearDB returns config path using priority:
|
||||
|
||||
@@ -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:]
|
||||
|
||||
@@ -238,11 +238,18 @@ func (h *ExportHandler) ExportConfigPricingCSV(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var project *models.Project
|
||||
if config.ProjectUUID != nil && *config.ProjectUUID != "" {
|
||||
if p, err := h.projectService.GetByUUID(*config.ProjectUUID, h.dbUsername); err == nil {
|
||||
project = p
|
||||
}
|
||||
}
|
||||
|
||||
opts := services.ProjectPricingExportOptions{
|
||||
IncludeLOT: req.IncludeLOT,
|
||||
IncludeBOM: req.IncludeBOM,
|
||||
IncludeEstimate: req.IncludeEstimate,
|
||||
IncludeStock: req.IncludeStock,
|
||||
IncludeStock: req.IncludeStock && project != nil && project.ShowStockPrices,
|
||||
IncludeCompetitor: req.IncludeCompetitor,
|
||||
Basis: req.Basis,
|
||||
SaleMarkup: req.SaleMarkup,
|
||||
@@ -260,10 +267,8 @@ func (h *ExportHandler) ExportConfigPricingCSV(c *gin.Context) {
|
||||
}
|
||||
|
||||
projectCode := config.Name
|
||||
if config.ProjectUUID != nil && *config.ProjectUUID != "" {
|
||||
if project, err := h.projectService.GetByUUID(*config.ProjectUUID, h.dbUsername); err == nil && project != nil {
|
||||
projectCode = project.Code
|
||||
}
|
||||
if project != nil {
|
||||
projectCode = project.Code
|
||||
}
|
||||
|
||||
filename := fmt.Sprintf("%s (%s) %s %s SPEC.csv",
|
||||
@@ -309,7 +314,7 @@ func (h *ExportHandler) ExportProjectPricingCSV(c *gin.Context) {
|
||||
IncludeLOT: req.IncludeLOT,
|
||||
IncludeBOM: req.IncludeBOM,
|
||||
IncludeEstimate: req.IncludeEstimate,
|
||||
IncludeStock: req.IncludeStock,
|
||||
IncludeStock: req.IncludeStock && project.ShowStockPrices,
|
||||
IncludeCompetitor: req.IncludeCompetitor,
|
||||
Basis: req.Basis,
|
||||
SaleMarkup: req.SaleMarkup,
|
||||
|
||||
@@ -16,13 +16,12 @@ func NewQuoteHandler(quoteService *services.QuoteService) *QuoteHandler {
|
||||
}
|
||||
|
||||
func (h *QuoteHandler) Validate(c *gin.Context) {
|
||||
var req services.QuoteRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
|
||||
req, ok := BindJSON[services.QuoteRequest](c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.quoteService.ValidateAndCalculate(&req)
|
||||
result, err := h.quoteService.ValidateAndCalculate(req)
|
||||
if err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
|
||||
return
|
||||
@@ -32,13 +31,12 @@ func (h *QuoteHandler) Validate(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (h *QuoteHandler) Calculate(c *gin.Context) {
|
||||
var req services.QuoteRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
|
||||
req, ok := BindJSON[services.QuoteRequest](c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.quoteService.ValidateAndCalculate(&req)
|
||||
result, err := h.quoteService.ValidateAndCalculate(req)
|
||||
if err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
|
||||
return
|
||||
@@ -51,13 +49,12 @@ func (h *QuoteHandler) Calculate(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (h *QuoteHandler) PriceLevels(c *gin.Context) {
|
||||
var req services.PriceLevelsRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
|
||||
req, ok := BindJSON[services.PriceLevelsRequest](c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.quoteService.CalculatePriceLevels(&req)
|
||||
result, err := h.quoteService.CalculatePriceLevels(req)
|
||||
if err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
|
||||
return
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -16,6 +17,17 @@ func RespondError(c *gin.Context, status int, fallback string, err error) {
|
||||
c.JSON(status, gin.H{"error": clientFacingErrorMessage(status, fallback, err)})
|
||||
}
|
||||
|
||||
// BindJSON decodes the request body into T, responding with a 422 and writing
|
||||
// the error via RespondError on failure. The second return value reports success.
|
||||
func BindJSON[T any](c *gin.Context) (*T, bool) {
|
||||
var req T
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid request", err)
|
||||
return nil, false
|
||||
}
|
||||
return &req, true
|
||||
}
|
||||
|
||||
func clientFacingErrorMessage(status int, fallback string, err error) string {
|
||||
if err == nil {
|
||||
return fallback
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// SettingsHandler serves per-client UI display preferences stored in app_settings.
|
||||
type SettingsHandler struct {
|
||||
localDB *localdb.LocalDB
|
||||
}
|
||||
|
||||
func NewSettingsHandler(localDB *localdb.LocalDB) *SettingsHandler {
|
||||
return &SettingsHandler{localDB: localDB}
|
||||
}
|
||||
|
||||
type uiSettingsResponse struct {
|
||||
IndicatorMode string `json:"indicator_mode"`
|
||||
}
|
||||
|
||||
// GetUI returns the current UI display preferences.
|
||||
func (h *SettingsHandler) GetUI(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, uiSettingsResponse{
|
||||
IndicatorMode: h.localDB.GetIndicatorMode(),
|
||||
})
|
||||
}
|
||||
|
||||
// PutUI updates UI display preferences. Currently only indicator_mode.
|
||||
func (h *SettingsHandler) PutUI(c *gin.Context) {
|
||||
req, ok := BindJSON[struct {
|
||||
IndicatorMode string `json:"indicator_mode"`
|
||||
}](c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.localDB.SetIndicatorMode(req.IndicatorMode); err != nil {
|
||||
RespondError(c, http.StatusUnprocessableEntity, "invalid indicator_mode", err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, uiSettingsResponse{
|
||||
IndicatorMode: h.localDB.GetIndicatorMode(),
|
||||
})
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
qfassets "git.mchus.pro/mchus/quoteforge"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/appmeta"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/db"
|
||||
"git.mchus.pro/mchus/quoteforge/internal/localdb"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -56,7 +57,9 @@ func (h *SetupHandler) ShowSetup(c *gin.Context) {
|
||||
settings, _ := h.localDB.GetSettings()
|
||||
|
||||
data := gin.H{
|
||||
"Settings": settings,
|
||||
"Settings": settings,
|
||||
"IndicatorMode": h.localDB.GetIndicatorMode(),
|
||||
"AppVersion": appmeta.Version(),
|
||||
}
|
||||
|
||||
tmpl := h.templates["setup.html"]
|
||||
@@ -207,4 +210,3 @@ func buildMySQLDSN(host string, port int, database, user, password string, timeo
|
||||
}
|
||||
return cfg.FormatDSN()
|
||||
}
|
||||
|
||||
@@ -114,6 +114,10 @@ func NewWebHandler(_ string, localDB *localdb.LocalDB) (*WebHandler, error) {
|
||||
|
||||
func (h *WebHandler) render(c *gin.Context, name string, data gin.H) {
|
||||
data["AppVersion"] = appmeta.Version()
|
||||
data["IndicatorMode"] = localdb.IndicatorModeColor
|
||||
if h.localDB != nil {
|
||||
data["IndicatorMode"] = h.localDB.GetIndicatorMode()
|
||||
}
|
||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||
tmpl, ok := h.templates[name]
|
||||
if !ok {
|
||||
|
||||
@@ -19,7 +19,6 @@ func TestConfigurationConvertersPreserveBusinessFields(t *testing.T) {
|
||||
WarehousePricelistID: &warehouseID,
|
||||
CompetitorPricelistID: &competitorID,
|
||||
DisablePriceRefresh: true,
|
||||
OnlyInStock: true,
|
||||
}
|
||||
|
||||
local := ConfigurationToLocal(cfg)
|
||||
@@ -57,7 +56,6 @@ func TestConfigurationSnapshotPreservesBusinessFields(t *testing.T) {
|
||||
WarehousePricelistID: &warehouseID,
|
||||
CompetitorPricelistID: &competitorID,
|
||||
DisablePriceRefresh: true,
|
||||
OnlyInStock: true,
|
||||
VendorSpec: VendorSpec{
|
||||
{
|
||||
SortOrder: 10,
|
||||
@@ -110,7 +108,6 @@ func TestConfigurationFingerprintIncludesPricingSelectorsAndVendorSpec(t *testin
|
||||
WarehousePricelistID: &warehouseID,
|
||||
CompetitorPricelistID: &competitorID,
|
||||
DisablePriceRefresh: true,
|
||||
OnlyInStock: true,
|
||||
VendorSpec: VendorSpec{
|
||||
{
|
||||
SortOrder: 10,
|
||||
|
||||
@@ -73,7 +73,6 @@ func ConfigurationToLocal(cfg *models.Configuration) *LocalConfiguration {
|
||||
ConfigType: cfg.ConfigType,
|
||||
VendorSpec: modelVendorSpecToLocal(cfg.VendorSpec),
|
||||
DisablePriceRefresh: cfg.DisablePriceRefresh,
|
||||
OnlyInStock: cfg.OnlyInStock,
|
||||
RentalItems: modelRentalItemsToLocal(cfg.RentalItems),
|
||||
RentalUpliftPercent: cfg.RentalUpliftPercent,
|
||||
Line: cfg.Line,
|
||||
@@ -124,7 +123,6 @@ func LocalToConfiguration(local *LocalConfiguration) *models.Configuration {
|
||||
ConfigType: local.ConfigType,
|
||||
VendorSpec: localVendorSpecToModel(local.VendorSpec),
|
||||
DisablePriceRefresh: local.DisablePriceRefresh,
|
||||
OnlyInStock: local.OnlyInStock,
|
||||
RentalItems: localRentalItemsToModel(local.RentalItems),
|
||||
RentalUpliftPercent: local.RentalUpliftPercent,
|
||||
Line: local.Line,
|
||||
@@ -259,18 +257,20 @@ func localRentalItemsToModel(items RentalItemConditions) models.RentalItemCondit
|
||||
|
||||
func ProjectToLocal(project *models.Project) *LocalProject {
|
||||
local := &LocalProject{
|
||||
UUID: project.UUID,
|
||||
OwnerUsername: project.OwnerUsername,
|
||||
Code: project.Code,
|
||||
Variant: project.Variant,
|
||||
Name: project.Name,
|
||||
TrackerURL: project.TrackerURL,
|
||||
IsActive: project.IsActive,
|
||||
IsSystem: project.IsSystem,
|
||||
RentalEnabled: project.RentalEnabled,
|
||||
CreatedAt: project.CreatedAt,
|
||||
UpdatedAt: project.UpdatedAt,
|
||||
SyncStatus: "pending",
|
||||
UUID: project.UUID,
|
||||
OwnerUsername: project.OwnerUsername,
|
||||
Code: project.Code,
|
||||
Variant: project.Variant,
|
||||
Name: project.Name,
|
||||
TrackerURL: project.TrackerURL,
|
||||
IsActive: project.IsActive,
|
||||
IsSystem: project.IsSystem,
|
||||
RentalEnabled: project.RentalEnabled,
|
||||
ShowStockPrices: project.ShowStockPrices,
|
||||
OnlyInStock: project.OnlyInStock,
|
||||
CreatedAt: project.CreatedAt,
|
||||
UpdatedAt: project.UpdatedAt,
|
||||
SyncStatus: "pending",
|
||||
}
|
||||
if project.ID > 0 {
|
||||
serverID := project.ID
|
||||
@@ -281,17 +281,19 @@ func ProjectToLocal(project *models.Project) *LocalProject {
|
||||
|
||||
func LocalToProject(local *LocalProject) *models.Project {
|
||||
project := &models.Project{
|
||||
UUID: local.UUID,
|
||||
OwnerUsername: local.OwnerUsername,
|
||||
Code: local.Code,
|
||||
Variant: local.Variant,
|
||||
Name: local.Name,
|
||||
TrackerURL: local.TrackerURL,
|
||||
IsActive: local.IsActive,
|
||||
IsSystem: local.IsSystem,
|
||||
RentalEnabled: local.RentalEnabled,
|
||||
CreatedAt: local.CreatedAt,
|
||||
UpdatedAt: local.UpdatedAt,
|
||||
UUID: local.UUID,
|
||||
OwnerUsername: local.OwnerUsername,
|
||||
Code: local.Code,
|
||||
Variant: local.Variant,
|
||||
Name: local.Name,
|
||||
TrackerURL: local.TrackerURL,
|
||||
IsActive: local.IsActive,
|
||||
IsSystem: local.IsSystem,
|
||||
RentalEnabled: local.RentalEnabled,
|
||||
ShowStockPrices: local.ShowStockPrices,
|
||||
OnlyInStock: local.OnlyInStock,
|
||||
CreatedAt: local.CreatedAt,
|
||||
UpdatedAt: local.UpdatedAt,
|
||||
}
|
||||
if local.ServerID != nil {
|
||||
project.ID = *local.ServerID
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package localdb
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newModeDB(t *testing.T) *LocalDB {
|
||||
t.Helper()
|
||||
local, err := New(filepath.Join(t.TempDir(), "mode.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("open localdb: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = local.Close() })
|
||||
return local
|
||||
}
|
||||
|
||||
func TestIndicatorMode(t *testing.T) {
|
||||
local := newModeDB(t)
|
||||
|
||||
if got := local.GetIndicatorMode(); got != IndicatorModeColor {
|
||||
t.Fatalf("unset: got %q, want %q", got, IndicatorModeColor)
|
||||
}
|
||||
|
||||
if err := local.SetIndicatorMode(IndicatorModeAccessible); err != nil {
|
||||
t.Fatalf("set accessible: %v", err)
|
||||
}
|
||||
if got := local.GetIndicatorMode(); got != IndicatorModeAccessible {
|
||||
t.Fatalf("after set accessible: got %q, want %q", got, IndicatorModeAccessible)
|
||||
}
|
||||
|
||||
if err := local.SetIndicatorMode(IndicatorModeColor); err != nil {
|
||||
t.Fatalf("set color: %v", err)
|
||||
}
|
||||
if got := local.GetIndicatorMode(); got != IndicatorModeColor {
|
||||
t.Fatalf("after set color: got %q, want %q", got, IndicatorModeColor)
|
||||
}
|
||||
|
||||
if err := local.SetIndicatorMode("rainbow"); err == nil {
|
||||
t.Fatal("expected error for invalid mode, got nil")
|
||||
}
|
||||
if got := local.GetIndicatorMode(); got != IndicatorModeColor {
|
||||
t.Fatalf("after rejected set: got %q, want %q", got, IndicatorModeColor)
|
||||
}
|
||||
}
|
||||
@@ -212,6 +212,8 @@ CREATE TABLE local_projects (
|
||||
is_active INTEGER NOT NULL DEFAULT 1,
|
||||
is_system INTEGER NOT NULL DEFAULT 0,
|
||||
rental_enabled INTEGER NOT NULL DEFAULT 0,
|
||||
show_stock_prices INTEGER NOT NULL DEFAULT 0,
|
||||
only_in_stock INTEGER NOT NULL DEFAULT 0,
|
||||
created_at DATETIME,
|
||||
updated_at DATETIME,
|
||||
synced_at DATETIME NULL,
|
||||
@@ -1128,6 +1130,43 @@ func (l *LocalDB) upsertAppSetting(tx *gorm.DB, key, value string, updatedAt tim
|
||||
`, key, value, updatedAt.Format(time.RFC3339)).Error
|
||||
}
|
||||
|
||||
// Indicator display mode: how the UI renders signals that are otherwise carried
|
||||
// by colour alone (price-quality scale, world-fallback price cells, incomplete
|
||||
// pricing totals). "color" (default) keeps the hue coding; "accessible" swaps it
|
||||
// for shape/text so it stays readable with a colour-vision deficiency. Per-client
|
||||
// preference stored in app_settings; consumed by web/static/price-quality.js and
|
||||
// the pricing tab via base.html's window.QF_INDICATOR_MODE.
|
||||
const (
|
||||
IndicatorModeColor = "color"
|
||||
IndicatorModeAccessible = "accessible"
|
||||
)
|
||||
|
||||
// GetIndicatorMode returns the stored indicator display mode, falling back to
|
||||
// "color" when unset or invalid.
|
||||
func (l *LocalDB) GetIndicatorMode() string {
|
||||
value, ok := l.getAppSettingValue("indicator_mode")
|
||||
if !ok {
|
||||
return IndicatorModeColor
|
||||
}
|
||||
switch strings.TrimSpace(value) {
|
||||
case IndicatorModeAccessible:
|
||||
return IndicatorModeAccessible
|
||||
default:
|
||||
return IndicatorModeColor
|
||||
}
|
||||
}
|
||||
|
||||
// SetIndicatorMode stores the indicator display mode. Only the two known
|
||||
// literals are accepted.
|
||||
func (l *LocalDB) SetIndicatorMode(mode string) error {
|
||||
mode = strings.TrimSpace(mode)
|
||||
if mode != IndicatorModeColor && mode != IndicatorModeAccessible {
|
||||
return fmt.Errorf("invalid indicator mode %q", mode)
|
||||
}
|
||||
now := time.Now()
|
||||
return l.upsertAppSetting(l.db, "indicator_mode", mode, now)
|
||||
}
|
||||
|
||||
// SetLastSyncTime sets the last sync timestamp
|
||||
func (l *LocalDB) SetLastSyncTime(t time.Time) error {
|
||||
// Using raw SQL for upsert since SQLite doesn't have native UPSERT in all versions
|
||||
|
||||
@@ -139,6 +139,11 @@ var localMigrations = []localMigration{
|
||||
name: "Add price_quality to local_pricelist_items",
|
||||
run: addLocalPricelistItemPriceQuality,
|
||||
},
|
||||
{
|
||||
id: "2026_08_12_local_project_stock_settings",
|
||||
name: "Add show_stock_prices and only_in_stock to local_projects",
|
||||
run: addLocalProjectStockSettings,
|
||||
},
|
||||
}
|
||||
|
||||
func addLocalPricelistItemPriceQuality(tx *gorm.DB) error {
|
||||
@@ -249,6 +254,22 @@ func addLocalProjectRentalEnabled(tx *gorm.DB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func addLocalProjectStockSettings(tx *gorm.DB) error {
|
||||
stmts := []string{
|
||||
`ALTER TABLE local_projects ADD COLUMN show_stock_prices INTEGER NOT NULL DEFAULT 0`,
|
||||
`ALTER TABLE local_projects ADD COLUMN only_in_stock INTEGER NOT NULL DEFAULT 0`,
|
||||
}
|
||||
for _, stmt := range stmts {
|
||||
if err := tx.Exec(stmt).Error; err != nil {
|
||||
if !strings.Contains(strings.ToLower(err.Error()), "duplicate") &&
|
||||
!strings.Contains(strings.ToLower(err.Error()), "exists") {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type localPartnumberCatalogRow struct {
|
||||
Partnumber string
|
||||
LotsJSON LocalPartnumberBookLots
|
||||
|
||||
+17
-16
@@ -111,7 +111,6 @@ type LocalConfiguration struct {
|
||||
WarehousePricelistID *uint `gorm:"index" json:"warehouse_pricelist_id,omitempty"`
|
||||
CompetitorPricelistID *uint `gorm:"index" json:"competitor_pricelist_id,omitempty"`
|
||||
DisablePriceRefresh bool `gorm:"default:false" json:"disable_price_refresh"`
|
||||
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
|
||||
RentalItems RentalItemConditions `gorm:"type:text" json:"rental_items,omitempty"`
|
||||
RentalUpliftPercent float64 `gorm:"default:0" json:"rental_uplift_percent"`
|
||||
VendorSpec VendorSpec `gorm:"type:text" json:"vendor_spec,omitempty"`
|
||||
@@ -133,21 +132,23 @@ func (LocalConfiguration) TableName() string {
|
||||
}
|
||||
|
||||
type LocalProject struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"uniqueIndex;not null" json:"uuid"`
|
||||
ServerID *uint `json:"server_id,omitempty"`
|
||||
OwnerUsername string `gorm:"not null;index" json:"owner_username"`
|
||||
Code string `gorm:"not null;index:idx_local_projects_code_variant,priority:1" json:"code"`
|
||||
Variant string `gorm:"default:'';index:idx_local_projects_code_variant,priority:2" json:"variant"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
TrackerURL string `json:"tracker_url"`
|
||||
IsActive bool `gorm:"default:true;index" json:"is_active"`
|
||||
IsSystem bool `gorm:"default:false;index" json:"is_system"`
|
||||
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"`
|
||||
SyncStatus string `gorm:"default:'local'" json:"sync_status"` // local/synced/pending
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"uniqueIndex;not null" json:"uuid"`
|
||||
ServerID *uint `json:"server_id,omitempty"`
|
||||
OwnerUsername string `gorm:"not null;index" json:"owner_username"`
|
||||
Code string `gorm:"not null;index:idx_local_projects_code_variant,priority:1" json:"code"`
|
||||
Variant string `gorm:"default:'';index:idx_local_projects_code_variant,priority:2" json:"variant"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
TrackerURL string `json:"tracker_url"`
|
||||
IsActive bool `gorm:"default:true;index" json:"is_active"`
|
||||
IsSystem bool `gorm:"default:false;index" json:"is_system"`
|
||||
RentalEnabled bool `gorm:"default:false" json:"rental_enabled"`
|
||||
ShowStockPrices bool `gorm:"default:false" json:"show_stock_prices"`
|
||||
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
SyncedAt *time.Time `json:"synced_at,omitempty"`
|
||||
SyncStatus string `gorm:"default:'local'" json:"sync_status"` // local/synced/pending
|
||||
}
|
||||
|
||||
func (LocalProject) TableName() string {
|
||||
|
||||
@@ -30,7 +30,6 @@ func BuildConfigurationSnapshot(localCfg *LocalConfiguration) (string, error) {
|
||||
"warehouse_pricelist_id": localCfg.WarehousePricelistID,
|
||||
"competitor_pricelist_id": localCfg.CompetitorPricelistID,
|
||||
"disable_price_refresh": localCfg.DisablePriceRefresh,
|
||||
"only_in_stock": localCfg.OnlyInStock,
|
||||
"rental_items": localCfg.RentalItems,
|
||||
"rental_uplift_percent": localCfg.RentalUpliftPercent,
|
||||
"vendor_spec": localCfg.VendorSpec,
|
||||
@@ -54,30 +53,29 @@ func BuildConfigurationSnapshot(localCfg *LocalConfiguration) (string, error) {
|
||||
// DecodeConfigurationSnapshot returns editable fields from one saved snapshot.
|
||||
func DecodeConfigurationSnapshot(data string) (*LocalConfiguration, error) {
|
||||
var snapshot struct {
|
||||
ProjectUUID *string `json:"project_uuid"`
|
||||
IsActive *bool `json:"is_active"`
|
||||
Name string `json:"name"`
|
||||
Items LocalConfigItems `json:"items"`
|
||||
TotalPrice *float64 `json:"total_price"`
|
||||
CustomPrice *float64 `json:"custom_price"`
|
||||
Notes string `json:"notes"`
|
||||
IsTemplate bool `json:"is_template"`
|
||||
ServerCount int `json:"server_count"`
|
||||
ServerModel string `json:"server_model"`
|
||||
SupportCode string `json:"support_code"`
|
||||
Article string `json:"article"`
|
||||
PricelistID *uint `json:"pricelist_id"`
|
||||
WarehousePricelistID *uint `json:"warehouse_pricelist_id"`
|
||||
CompetitorPricelistID *uint `json:"competitor_pricelist_id"`
|
||||
ProjectUUID *string `json:"project_uuid"`
|
||||
IsActive *bool `json:"is_active"`
|
||||
Name string `json:"name"`
|
||||
Items LocalConfigItems `json:"items"`
|
||||
TotalPrice *float64 `json:"total_price"`
|
||||
CustomPrice *float64 `json:"custom_price"`
|
||||
Notes string `json:"notes"`
|
||||
IsTemplate bool `json:"is_template"`
|
||||
ServerCount int `json:"server_count"`
|
||||
ServerModel string `json:"server_model"`
|
||||
SupportCode string `json:"support_code"`
|
||||
Article string `json:"article"`
|
||||
PricelistID *uint `json:"pricelist_id"`
|
||||
WarehousePricelistID *uint `json:"warehouse_pricelist_id"`
|
||||
CompetitorPricelistID *uint `json:"competitor_pricelist_id"`
|
||||
DisablePriceRefresh bool `json:"disable_price_refresh"`
|
||||
OnlyInStock bool `json:"only_in_stock"`
|
||||
RentalItems RentalItemConditions `json:"rental_items"`
|
||||
RentalUpliftPercent float64 `json:"rental_uplift_percent"`
|
||||
VendorSpec VendorSpec `json:"vendor_spec"`
|
||||
Line int `json:"line"`
|
||||
PriceUpdatedAt *time.Time `json:"price_updated_at"`
|
||||
OriginalUserID uint `json:"original_user_id"`
|
||||
OriginalUsername string `json:"original_username"`
|
||||
VendorSpec VendorSpec `json:"vendor_spec"`
|
||||
Line int `json:"line"`
|
||||
PriceUpdatedAt *time.Time `json:"price_updated_at"`
|
||||
OriginalUserID uint `json:"original_user_id"`
|
||||
OriginalUsername string `json:"original_username"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal([]byte(data), &snapshot); err != nil {
|
||||
@@ -106,7 +104,6 @@ func DecodeConfigurationSnapshot(data string) (*LocalConfiguration, error) {
|
||||
WarehousePricelistID: snapshot.WarehousePricelistID,
|
||||
CompetitorPricelistID: snapshot.CompetitorPricelistID,
|
||||
DisablePriceRefresh: snapshot.DisablePriceRefresh,
|
||||
OnlyInStock: snapshot.OnlyInStock,
|
||||
RentalItems: snapshot.RentalItems,
|
||||
RentalUpliftPercent: snapshot.RentalUpliftPercent,
|
||||
VendorSpec: snapshot.VendorSpec,
|
||||
@@ -126,7 +123,6 @@ type configurationSpecPriceFingerprint struct {
|
||||
WarehousePricelistID *uint `json:"warehouse_pricelist_id,omitempty"`
|
||||
CompetitorPricelistID *uint `json:"competitor_pricelist_id,omitempty"`
|
||||
DisablePriceRefresh bool `json:"disable_price_refresh"`
|
||||
OnlyInStock bool `json:"only_in_stock"`
|
||||
RentalItems RentalItemConditions `json:"rental_items,omitempty"`
|
||||
RentalUpliftPercent float64 `json:"rental_uplift_percent"`
|
||||
VendorSpec VendorSpec `json:"vendor_spec,omitempty"`
|
||||
@@ -174,7 +170,6 @@ func BuildConfigurationSpecPriceFingerprint(localCfg *LocalConfiguration) (strin
|
||||
WarehousePricelistID: localCfg.WarehousePricelistID,
|
||||
CompetitorPricelistID: localCfg.CompetitorPricelistID,
|
||||
DisablePriceRefresh: localCfg.DisablePriceRefresh,
|
||||
OnlyInStock: localCfg.OnlyInStock,
|
||||
RentalItems: rentalItems,
|
||||
RentalUpliftPercent: localCfg.RentalUpliftPercent,
|
||||
VendorSpec: localCfg.VendorSpec,
|
||||
|
||||
@@ -126,38 +126,36 @@ func (v *VendorSpec) Scan(value interface{}) error {
|
||||
}
|
||||
|
||||
type Configuration struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"size:36;uniqueIndex;not null" json:"uuid"`
|
||||
UserID *uint `json:"user_id,omitempty"` // Legacy field, no longer required for ownership
|
||||
OwnerUsername string `gorm:"size:100;not null;default:'';index" json:"owner_username"`
|
||||
ProjectUUID *string `gorm:"size:36;index" json:"project_uuid,omitempty"`
|
||||
AppVersion string `gorm:"size:64" json:"app_version,omitempty"`
|
||||
Name string `gorm:"size:200;not null" json:"name"`
|
||||
Items ConfigItems `gorm:"type:json;not null" json:"items"`
|
||||
TotalPrice *float64 `gorm:"type:decimal(12,2)" json:"total_price"`
|
||||
CustomPrice *float64 `gorm:"type:decimal(12,2)" json:"custom_price"`
|
||||
Notes string `gorm:"type:text" json:"notes"`
|
||||
IsTemplate bool `gorm:"default:false" json:"is_template"`
|
||||
ServerCount int `gorm:"default:1" json:"server_count"`
|
||||
ServerModel string `gorm:"size:100" json:"server_model,omitempty"`
|
||||
SupportCode string `gorm:"size:20" json:"support_code,omitempty"`
|
||||
Article string `gorm:"size:80" json:"article,omitempty"`
|
||||
PricelistID *uint `gorm:"index" json:"pricelist_id,omitempty"`
|
||||
WarehousePricelistID *uint `gorm:"index" json:"warehouse_pricelist_id,omitempty"`
|
||||
CompetitorPricelistID *uint `gorm:"index" json:"competitor_pricelist_id,omitempty"`
|
||||
VendorSpec VendorSpec `gorm:"type:json" json:"vendor_spec,omitempty"`
|
||||
ConfigType string `gorm:"size:20;default:server" json:"config_type"` // "server" | "storage"
|
||||
DisablePriceRefresh bool `gorm:"default:false" json:"disable_price_refresh"`
|
||||
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"size:36;uniqueIndex;not null" json:"uuid"`
|
||||
UserID *uint `json:"user_id,omitempty"` // Legacy field, no longer required for ownership
|
||||
OwnerUsername string `gorm:"size:100;not null;default:'';index" json:"owner_username"`
|
||||
ProjectUUID *string `gorm:"size:36;index" json:"project_uuid,omitempty"`
|
||||
AppVersion string `gorm:"size:64" json:"app_version,omitempty"`
|
||||
Name string `gorm:"size:200;not null" json:"name"`
|
||||
Items ConfigItems `gorm:"type:json;not null" json:"items"`
|
||||
TotalPrice *float64 `gorm:"type:decimal(12,2)" json:"total_price"`
|
||||
CustomPrice *float64 `gorm:"type:decimal(12,2)" json:"custom_price"`
|
||||
Notes string `gorm:"type:text" json:"notes"`
|
||||
IsTemplate bool `gorm:"default:false" json:"is_template"`
|
||||
ServerCount int `gorm:"default:1" json:"server_count"`
|
||||
ServerModel string `gorm:"size:100" json:"server_model,omitempty"`
|
||||
SupportCode string `gorm:"size:20" json:"support_code,omitempty"`
|
||||
Article string `gorm:"size:80" json:"article,omitempty"`
|
||||
PricelistID *uint `gorm:"index" json:"pricelist_id,omitempty"`
|
||||
WarehousePricelistID *uint `gorm:"index" json:"warehouse_pricelist_id,omitempty"`
|
||||
CompetitorPricelistID *uint `gorm:"index" json:"competitor_pricelist_id,omitempty"`
|
||||
VendorSpec VendorSpec `gorm:"type:json" json:"vendor_spec,omitempty"`
|
||||
ConfigType string `gorm:"size:20;default:server" json:"config_type"` // "server" | "storage"
|
||||
DisablePriceRefresh bool `gorm:"default:false" json:"disable_price_refresh"`
|
||||
RentalItems RentalItemConditions `gorm:"type:json" json:"rental_items,omitempty"`
|
||||
RentalUpliftPercent float64 `gorm:"type:decimal(8,2);default:0" json:"rental_uplift_percent"`
|
||||
Line int `gorm:"column:line_no;index" json:"line"`
|
||||
PriceUpdatedAt *time.Time `gorm:"type:timestamp" json:"price_updated_at,omitempty"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
CurrentVersionNo int `gorm:"-" json:"current_version_no,omitempty"`
|
||||
RentalUpliftPercent float64 `gorm:"type:decimal(8,2);default:0" json:"rental_uplift_percent"`
|
||||
Line int `gorm:"column:line_no;index" json:"line"`
|
||||
PriceUpdatedAt *time.Time `gorm:"type:timestamp" json:"price_updated_at,omitempty"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
CurrentVersionNo int `gorm:"-" json:"current_version_no,omitempty"`
|
||||
}
|
||||
|
||||
func (Configuration) TableName() string {
|
||||
return "qt_configurations"
|
||||
}
|
||||
|
||||
+14
-12
@@ -3,18 +3,20 @@ package models
|
||||
import "time"
|
||||
|
||||
type Project struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"size:36;uniqueIndex;not null" json:"uuid"`
|
||||
OwnerUsername string `gorm:"size:100;not null;index" json:"owner_username"`
|
||||
Code string `gorm:"size:100;not null;index:idx_qt_projects_code_variant,priority:1" json:"code"`
|
||||
Variant string `gorm:"size:100;not null;default:'';index:idx_qt_projects_code_variant,priority:2" json:"variant"`
|
||||
Name *string `gorm:"size:200" json:"name,omitempty"`
|
||||
TrackerURL string `gorm:"size:500" json:"tracker_url"`
|
||||
IsActive bool `gorm:"default:true;index" json:"is_active"`
|
||||
IsSystem bool `gorm:"default:false;index" json:"is_system"`
|
||||
RentalEnabled bool `gorm:"default:false" json:"rental_enabled"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||
UUID string `gorm:"size:36;uniqueIndex;not null" json:"uuid"`
|
||||
OwnerUsername string `gorm:"size:100;not null;index" json:"owner_username"`
|
||||
Code string `gorm:"size:100;not null;index:idx_qt_projects_code_variant,priority:1" json:"code"`
|
||||
Variant string `gorm:"size:100;not null;default:'';index:idx_qt_projects_code_variant,priority:2" json:"variant"`
|
||||
Name *string `gorm:"size:200" json:"name,omitempty"`
|
||||
TrackerURL string `gorm:"size:500" json:"tracker_url"`
|
||||
IsActive bool `gorm:"default:true;index" json:"is_active"`
|
||||
IsSystem bool `gorm:"default:false;index" json:"is_system"`
|
||||
RentalEnabled bool `gorm:"default:false" json:"rental_enabled"`
|
||||
ShowStockPrices bool `gorm:"default:false" json:"show_stock_prices"`
|
||||
OnlyInStock bool `gorm:"default:false" json:"only_in_stock"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (Project) TableName() string {
|
||||
|
||||
@@ -39,6 +39,8 @@ func (r *ProjectRepository) UpsertByUUID(project *models.Project) error {
|
||||
"is_active",
|
||||
"is_system",
|
||||
"rental_enabled",
|
||||
"show_stock_prices",
|
||||
"only_in_stock",
|
||||
"updated_at",
|
||||
}),
|
||||
}).Create(project).Error; err != nil {
|
||||
|
||||
@@ -34,7 +34,6 @@ type CreateConfigRequest struct {
|
||||
CompetitorPricelistID *uint `json:"competitor_pricelist_id,omitempty"`
|
||||
ConfigType string `json:"config_type,omitempty"` // "server" | "storage"
|
||||
DisablePriceRefresh bool `json:"disable_price_refresh"`
|
||||
OnlyInStock bool `json:"only_in_stock"`
|
||||
}
|
||||
|
||||
type ArticlePreviewRequest struct {
|
||||
|
||||
@@ -3,6 +3,7 @@ package services
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
@@ -59,15 +60,48 @@ 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
|
||||
}
|
||||
|
||||
func (o ProjectPricingExportOptions) saleMarkupFactor() float64 {
|
||||
// defaultSaleMarkup mirrors PricingMarkup.DEFAULT_SALE_UPLIFT in web/templates/index.html.
|
||||
// Keep both in sync; the frontend always sends an explicit value, this is a fallback for
|
||||
// other API callers that omit sale_markup.
|
||||
const defaultSaleMarkup = 1.3
|
||||
|
||||
// effectiveSaleMarkupFactor resolves the DDP estimate uplift for one configuration.
|
||||
// An explicit opts.SaleMarkup (sent by the single-config pricing tab, which knows the
|
||||
// live-edited value) always wins. Otherwise each configuration's own saved uplift
|
||||
// (persisted in Notes by the "Ценообразование" tab, see index.html buildPricingState/
|
||||
// restorePricingStateFromNotes) is used, so bulk project export matches what exporting
|
||||
// that same configuration individually would produce — one pipeline, not a single
|
||||
// project-wide constant.
|
||||
func (o ProjectPricingExportOptions) effectiveSaleMarkupFactor(cfg *models.Configuration) float64 {
|
||||
if o.SaleMarkup > 0 {
|
||||
return o.SaleMarkup
|
||||
}
|
||||
return 1.3
|
||||
if v := configSavedSaleUplift(cfg); v > 0 {
|
||||
return v
|
||||
}
|
||||
return defaultSaleMarkup
|
||||
}
|
||||
|
||||
// configSavedSaleUplift reads the per-configuration DDP estimate uplift persisted by the
|
||||
// pricing tab. Notes stores {"pricing_ui":{"sale_uplift":...}} as JSON — see
|
||||
// serializeConfigNotes/restorePricingStateFromNotes in index.html.
|
||||
func configSavedSaleUplift(cfg *models.Configuration) float64 {
|
||||
if cfg == nil || strings.TrimSpace(cfg.Notes) == "" {
|
||||
return 0
|
||||
}
|
||||
var parsed struct {
|
||||
PricingUI struct {
|
||||
SaleUplift float64 `json:"sale_uplift"`
|
||||
} `json:"pricing_ui"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(cfg.Notes), &parsed); err != nil {
|
||||
return 0
|
||||
}
|
||||
return parsed.PricingUI.SaleUplift
|
||||
}
|
||||
|
||||
func (o ProjectPricingExportOptions) isDDP() bool {
|
||||
@@ -452,7 +486,7 @@ func (s *ExportService) buildPricingExportBlock(cfg *models.Configuration, opts
|
||||
})
|
||||
}
|
||||
if opts.isDDP() {
|
||||
applyDDPMarkup(block.Rows, opts.saleMarkupFactor())
|
||||
applyDDPMarkup(block.Rows, opts.effectiveSaleMarkupFactor(cfg))
|
||||
}
|
||||
if opts.ManualPrice != nil && *opts.ManualPrice > 0 {
|
||||
distributeManualPrice(block.Rows, *opts.ManualPrice)
|
||||
@@ -489,7 +523,7 @@ func (s *ExportService) buildPricingExportBlock(cfg *models.Configuration, opts
|
||||
}
|
||||
|
||||
if opts.isDDP() {
|
||||
applyDDPMarkup(block.Rows, opts.saleMarkupFactor())
|
||||
applyDDPMarkup(block.Rows, opts.effectiveSaleMarkupFactor(cfg))
|
||||
}
|
||||
if opts.ManualPrice != nil && *opts.ManualPrice > 0 {
|
||||
distributeManualPrice(block.Rows, *opts.ManualPrice)
|
||||
@@ -514,11 +548,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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -103,7 +103,6 @@ func (s *LocalConfigurationService) Create(ownerUsername string, req *CreateConf
|
||||
CompetitorPricelistID: req.CompetitorPricelistID,
|
||||
ConfigType: req.ConfigType,
|
||||
DisablePriceRefresh: req.DisablePriceRefresh,
|
||||
OnlyInStock: req.OnlyInStock,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
if cfg.ConfigType == "" {
|
||||
@@ -204,7 +203,6 @@ func (s *LocalConfigurationService) Update(uuid string, ownerUsername string, re
|
||||
localCfg.WarehousePricelistID = req.WarehousePricelistID
|
||||
localCfg.CompetitorPricelistID = req.CompetitorPricelistID
|
||||
localCfg.DisablePriceRefresh = req.DisablePriceRefresh
|
||||
localCfg.OnlyInStock = req.OnlyInStock
|
||||
localCfg.UpdatedAt = time.Now()
|
||||
localCfg.SyncStatus = "pending"
|
||||
|
||||
@@ -328,7 +326,6 @@ func (s *LocalConfigurationService) CloneToProject(configUUID string, ownerUsern
|
||||
WarehousePricelistID: original.WarehousePricelistID,
|
||||
CompetitorPricelistID: original.CompetitorPricelistID,
|
||||
DisablePriceRefresh: original.DisablePriceRefresh,
|
||||
OnlyInStock: original.OnlyInStock,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
@@ -566,7 +563,6 @@ func (s *LocalConfigurationService) UpdateNoAuth(uuid string, req *CreateConfigR
|
||||
localCfg.WarehousePricelistID = req.WarehousePricelistID
|
||||
localCfg.CompetitorPricelistID = req.CompetitorPricelistID
|
||||
localCfg.DisablePriceRefresh = req.DisablePriceRefresh
|
||||
localCfg.OnlyInStock = req.OnlyInStock
|
||||
localCfg.UpdatedAt = time.Now()
|
||||
localCfg.SyncStatus = "pending"
|
||||
|
||||
@@ -685,7 +681,6 @@ func (s *LocalConfigurationService) CloneNoAuthToProjectFromVersion(configUUID s
|
||||
WarehousePricelistID: original.WarehousePricelistID,
|
||||
CompetitorPricelistID: original.CompetitorPricelistID,
|
||||
DisablePriceRefresh: original.DisablePriceRefresh,
|
||||
OnlyInStock: original.OnlyInStock,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
@@ -1648,7 +1643,6 @@ func (s *LocalConfigurationService) rollbackToVersion(configurationUUID string,
|
||||
current.WarehousePricelistID = rollbackData.WarehousePricelistID
|
||||
current.CompetitorPricelistID = rollbackData.CompetitorPricelistID
|
||||
current.DisablePriceRefresh = rollbackData.DisablePriceRefresh
|
||||
current.OnlyInStock = rollbackData.OnlyInStock
|
||||
current.VendorSpec = rollbackData.VendorSpec
|
||||
if rollbackData.Line > 0 {
|
||||
current.Line = rollbackData.Line
|
||||
|
||||
@@ -154,7 +154,6 @@ func TestUpdateNoAuthCreatesRevisionWhenPricingSettingsChanged(t *testing.T) {
|
||||
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 1, UnitPrice: 1000}},
|
||||
ServerCount: 1,
|
||||
DisablePriceRefresh: true,
|
||||
OnlyInStock: true,
|
||||
}); err != nil {
|
||||
t.Fatalf("update pricing settings: %v", err)
|
||||
}
|
||||
|
||||
@@ -46,11 +46,13 @@ type CreateProjectRequest struct {
|
||||
}
|
||||
|
||||
type UpdateProjectRequest struct {
|
||||
Code *string `json:"code,omitempty"`
|
||||
Variant *string `json:"variant,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
TrackerURL *string `json:"tracker_url,omitempty"`
|
||||
RentalEnabled *bool `json:"rental_enabled,omitempty"`
|
||||
Code *string `json:"code,omitempty"`
|
||||
Variant *string `json:"variant,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
TrackerURL *string `json:"tracker_url,omitempty"`
|
||||
RentalEnabled *bool `json:"rental_enabled,omitempty"`
|
||||
ShowStockPrices *bool `json:"show_stock_prices,omitempty"`
|
||||
OnlyInStock *bool `json:"only_in_stock,omitempty"`
|
||||
}
|
||||
|
||||
type ProjectConfigurationsResult struct {
|
||||
@@ -152,6 +154,12 @@ func (s *ProjectService) Update(projectUUID, ownerUsername string, req *UpdatePr
|
||||
if req.RentalEnabled != nil {
|
||||
localProject.RentalEnabled = *req.RentalEnabled
|
||||
}
|
||||
if req.ShowStockPrices != nil {
|
||||
localProject.ShowStockPrices = *req.ShowStockPrices
|
||||
}
|
||||
if req.OnlyInStock != nil {
|
||||
localProject.OnlyInStock = *req.OnlyInStock
|
||||
}
|
||||
localProject.UpdatedAt = time.Now()
|
||||
localProject.SyncStatus = "pending"
|
||||
if err := s.localDB.SaveProject(localProject); err != nil {
|
||||
|
||||
@@ -218,6 +218,8 @@ func (s *Service) ImportProjectsToLocal() (*ProjectImportResult, error) {
|
||||
existing.IsActive = project.IsActive
|
||||
existing.IsSystem = project.IsSystem
|
||||
existing.RentalEnabled = project.RentalEnabled
|
||||
existing.ShowStockPrices = project.ShowStockPrices
|
||||
existing.OnlyInStock = project.OnlyInStock
|
||||
existing.CreatedAt = project.CreatedAt
|
||||
existing.UpdatedAt = project.UpdatedAt
|
||||
serverID := project.ID
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# QuoteForge v3.34
|
||||
|
||||
Дата релиза: 2026-08-10
|
||||
Тег: `v3.34`
|
||||
|
||||
Предыдущий релиз: `v3.33`
|
||||
|
||||
## Ключевые изменения
|
||||
|
||||
- CSV-экспорт цены продажи (DDP): колонка Estimate игнорировала пользовательский коэффициент «Аплифт к estimate» и всегда экспортировалась с x1,3 — фронтенд не передавал значение поля в бэкенд, а `applyDDPMarkup` применял один и тот же множитель ко всем трём колонкам сразу; теперь Estimate масштабируется по аплифту, Склад/Конкуренты — фиксированным x1,3;
|
||||
- рефакторинг дублирующегося кода без изменения поведения: в Go-хендлерах устранены повторяющиеся switch-конструкции обработки ошибок и bind-логика (`cmd/qfs/main.go`, `internal/handlers`, `internal/appstate`, `internal/article`); во фронтенде сведены в общие функции пять идентичных обработчиков клавиатурной навигации автокомплита и четыре функции сборки нового элемента корзины.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,16 @@
|
||||
# QuoteForge v3.35
|
||||
|
||||
Дата релиза: 2026-08-12
|
||||
Тег: `v3.35`
|
||||
|
||||
Предыдущий релиз: `v3.34`
|
||||
|
||||
## Ключевые изменения
|
||||
|
||||
- новый чекбокс «Складские цены» на уровне проекта (по аналогии с «Аренда») — включает/выключает показ складских цен во всех ценовых интерфейсах конфигураций проекта, включая CSV-экспорт; по умолчанию выключен;
|
||||
- чекбокс «Только наличие» перенесён из настроек цен конфигурации в настройки проекта и теперь активен только при включённых «Складские цены»; фильтрация компонентов по наличию работает как раньше.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,16 @@
|
||||
# QuoteForge v3.36
|
||||
|
||||
Дата релиза: 2026-08-12
|
||||
Тег: `v3.36`
|
||||
|
||||
Предыдущий релиз: `v3.35`
|
||||
|
||||
## Ключевые изменения
|
||||
|
||||
- исправлен DDP-экспорт CSV со страницы проекта: раньше всегда применялся коэффициент 1,3 ко всем конфигурациям, теперь используется собственный аплифт каждой конфигурации из раздела «Ценообразование» — экспорт с проекта идёт по тому же конвейеру, что и экспорт с конкретной конфигурации;
|
||||
- упрощена подпись DDP в модалке экспорта проекта.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -0,0 +1,16 @@
|
||||
# QuoteForge v3.37
|
||||
|
||||
Дата релиза: 2026-08-24
|
||||
Тег: `v3.37`
|
||||
|
||||
Предыдущий релиз: `v3.36`
|
||||
|
||||
## Ключевые изменения
|
||||
|
||||
- исправлен баг конфигуратора: при изменении количества в таблицах с несколькими компонентами (диски, RAID-контроллеры и т.п.) поле «Кол-во» затиралось суммой в долларах, а «Стоимость» переставала пересчитываться корректно;
|
||||
- заодно ужесточён поиск строки в таблице при обновлении количества — теперь строго по LOT-коду, без риска задеть соседнюю строку с похожим названием.
|
||||
|
||||
## Запуск на macOS
|
||||
|
||||
Снимите карантинный атрибут через терминал: `xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64`
|
||||
После этого бинарник запустится без предупреждения Gatekeeper.
|
||||
@@ -44,3 +44,42 @@
|
||||
visibility: visible;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Colour-blind-safe price-quality indicator (mono mode). 5-step signal meter,
|
||||
single neutral hue — magnitude reads from the number of lit bars, not colour. */
|
||||
.qf-quality-meter {
|
||||
display: inline-flex;
|
||||
align-items: flex-end;
|
||||
gap: 1px;
|
||||
height: 12px;
|
||||
vertical-align: middle;
|
||||
line-height: 0;
|
||||
}
|
||||
.qf-quality-meter > i {
|
||||
display: inline-block;
|
||||
width: 3px;
|
||||
background-color: #d1d5db;
|
||||
border-radius: 1px;
|
||||
}
|
||||
.qf-quality-meter > i.on {
|
||||
background-color: #374151;
|
||||
}
|
||||
.qf-quality-meter > i:nth-child(1) { height: 30%; }
|
||||
.qf-quality-meter > i:nth-child(2) { height: 45%; }
|
||||
.qf-quality-meter > i:nth-child(3) { height: 62%; }
|
||||
.qf-quality-meter > i:nth-child(4) { height: 80%; }
|
||||
.qf-quality-meter > i:nth-child(5) { height: 100%; }
|
||||
.qf-quality-meter[data-size="sm"] {
|
||||
height: 10px;
|
||||
gap: 1px;
|
||||
}
|
||||
.qf-quality-meter[data-size="sm"] > i {
|
||||
width: 2px;
|
||||
}
|
||||
|
||||
/* Leading meter column on the pricing tab tables (mono mode). */
|
||||
.pricing-quality-meter {
|
||||
width: 1%;
|
||||
white-space: nowrap;
|
||||
text-align: center;
|
||||
}
|
||||
@@ -1,16 +1,25 @@
|
||||
// Shared LOT price-quality color scale, used everywhere price_quality is
|
||||
// Shared LOT price-quality indicator, 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.
|
||||
// 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 visual scale so
|
||||
// every view stays consistent.
|
||||
//
|
||||
// Gradient: 0 = red, 5 = yellow, 9 = green.
|
||||
// Two render modes, chosen per client via window.QF_INDICATOR_MODE (injected by
|
||||
// base.html from app_settings, key indicator_mode):
|
||||
// "color" (default) — hue scale, 0 = red, 5 = yellow, 9 = green.
|
||||
// "accessible" — colour-blind-safe 5-step signal-strength meter,
|
||||
// single neutral hue, magnitude encoded by bar count.
|
||||
// See bible-local/decisions/2026-08-31-accessible-indicator-mode.md.
|
||||
(function () {
|
||||
const RED = [220, 38, 38];
|
||||
const YELLOW = [234, 179, 8];
|
||||
const GREEN = [22, 163, 74];
|
||||
|
||||
function isAccessible() {
|
||||
return window.QF_INDICATOR_MODE === 'accessible';
|
||||
}
|
||||
|
||||
function lerp(c1, c2, t) {
|
||||
return c1.map((v, i) => Math.round(v + (c2[i] - v) * t));
|
||||
}
|
||||
@@ -28,27 +37,53 @@
|
||||
return rgb ? `rgb(${rgb})` : null;
|
||||
}
|
||||
|
||||
// Small colored dot for compact contexts (search dropdown, configurator table cell).
|
||||
// 0-9 score -> 0-4 meter level. 0-1 / 2-3 / 4-5 / 6-7 / 8-9.
|
||||
function priceQualityLevel(quality) {
|
||||
if (typeof quality !== 'number' || Number.isNaN(quality)) return null;
|
||||
const q = Math.max(0, Math.min(9, quality));
|
||||
return Math.min(4, Math.floor(q / 2));
|
||||
}
|
||||
|
||||
// Monochrome 5-step signal-strength meter. size: undefined | 'sm'.
|
||||
function qualityMeterHtml(quality, opts) {
|
||||
const level = priceQualityLevel(quality);
|
||||
if (level === null) return '';
|
||||
const size = opts && opts.size === 'sm' ? ' data-size="sm"' : '';
|
||||
const title = `Качество цены: ${quality}/9`;
|
||||
let bars = '';
|
||||
for (let i = 0; i < 5; i++) {
|
||||
bars += `<i class="${i <= level ? 'on' : ''}"></i>`;
|
||||
}
|
||||
return `<span class="qf-quality-meter"${size} role="img" aria-label="${title}" title="${title}">${bars}</span>`;
|
||||
}
|
||||
|
||||
// Small indicator for compact contexts (search dropdown, configurator table cell).
|
||||
function qualityDotHtml(quality) {
|
||||
if (isAccessible()) return qualityMeterHtml(quality, { size: 'sm' });
|
||||
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.
|
||||
// Indicator for a dedicated "quality" column/cell.
|
||||
function qualityBadgeHtml(quality) {
|
||||
if (typeof quality !== 'number') return '<span class="text-gray-400">-</span>';
|
||||
if (isAccessible()) return qualityMeterHtml(quality, { size: 'sm' });
|
||||
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.
|
||||
// Light row-tint background for table rows, e.g. the pricing tab. Suppressed
|
||||
// in accessible mode — the pricing tab carries its own leading meter column there.
|
||||
function qualityRowStyle(quality) {
|
||||
if (isAccessible()) return '';
|
||||
const rgb = priceQualityRgb(quality);
|
||||
return rgb ? `background-color: rgba(${rgb}, 0.10)` : '';
|
||||
}
|
||||
|
||||
window.priceQualityColor = priceQualityColor;
|
||||
window.priceQualityLevel = priceQualityLevel;
|
||||
window.qualityMeterHtml = qualityMeterHtml;
|
||||
window.qualityDotHtml = qualityDotHtml;
|
||||
window.qualityBadgeHtml = qualityBadgeHtml;
|
||||
window.qualityRowStyle = qualityRowStyle;
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
<link rel="stylesheet" href="/static/app.css">
|
||||
<script src="/static/vendor/tailwindcss.browser.js"></script>
|
||||
<script src="/static/vendor/htmx-1.9.10.min.js"></script>
|
||||
<script>window.QF_INDICATOR_MODE = "{{ .IndicatorMode }}";</script>
|
||||
<script src="/static/price-quality.js"></script>
|
||||
<style>
|
||||
.htmx-request { opacity: 0.5; }
|
||||
@@ -19,7 +20,7 @@
|
||||
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||
<div class="flex justify-between h-14">
|
||||
<div class="flex items-center space-x-8">
|
||||
<a href="/" class="text-xl font-bold text-blue-600">QuoteForge</a>
|
||||
<a href="/" class="text-xl font-bold text-blue-600">QuoteForge<span class="text-xs font-normal text-gray-400 align-middle ml-1">{{.AppVersion}}</span></a>
|
||||
<div class="hidden md:flex space-x-4">
|
||||
<a href="/projects" class="text-gray-600 hover:text-gray-900 px-3 py-2 text-sm">Мои проекты</a>
|
||||
<a href="/pricelists" class="text-gray-600 hover:text-gray-900 px-3 py-2 text-sm">Прайслисты</a>
|
||||
@@ -55,10 +56,6 @@
|
||||
{{template "content" .}}
|
||||
</main>
|
||||
|
||||
<footer class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3 text-right">
|
||||
<span class="text-xs text-gray-400">v{{.AppVersion}}</span>
|
||||
</footer>
|
||||
|
||||
<div id="toast" class="fixed bottom-4 right-4 z-50"></div>
|
||||
|
||||
<!-- Dead-man's switch overlay: shown when backend process stops responding -->
|
||||
|
||||
+134
-200
@@ -222,24 +222,25 @@
|
||||
<table class="w-full text-sm border-collapse">
|
||||
<thead class="bg-gray-50 text-gray-700">
|
||||
<tr>
|
||||
{{if eq .IndicatorMode "accessible"}}<th class="px-2 py-2 border-b" title="Качество цены"><span class="sr-only">Качество цены</span></th>{{end}}
|
||||
<th class="px-2 py-2 text-left border-b whitespace-nowrap">PN вендора</th>
|
||||
<th class="px-2 py-2 text-left border-b">Описание</th>
|
||||
<th class="px-2 py-2 text-left border-b">LOT</th>
|
||||
<th class="px-2 py-2 text-right border-b">Кол-во</th>
|
||||
<th class="px-2 py-2 text-right border-b">Estimate</th>
|
||||
<th class="px-2 py-2 text-right border-b">Склад</th>
|
||||
<th class="px-2 py-2 text-right border-b stock-price-col">Склад</th>
|
||||
<th class="px-2 py-2 text-right border-b">Конкуренты</th>
|
||||
<th class="px-2 py-2 text-right border-b">Ручная цена</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="pricing-body-buy">
|
||||
<tr><td colspan="8" class="px-2 py-8 text-center text-gray-400">Загрузите BOM во вкладке «BOM»</td></tr>
|
||||
<tr><td colspan="{{if eq .IndicatorMode "accessible"}}9{{else}}8{{end}}" class="px-2 py-8 text-center text-gray-400">Загрузите BOM во вкладке «BOM»</td></tr>
|
||||
</tbody>
|
||||
<tfoot id="pricing-foot-buy" class="hidden bg-gray-50 font-semibold">
|
||||
<tr>
|
||||
<td colspan="4" class="px-2 py-2 text-right">Итого:</td>
|
||||
<td colspan="{{if eq .IndicatorMode "accessible"}}5{{else}}4{{end}}" class="px-2 py-2 text-right">Итого:</td>
|
||||
<td class="px-2 py-2 text-right" id="pricing-total-buy-estimate">—</td>
|
||||
<td class="px-2 py-2 text-right" id="pricing-total-buy-warehouse">—</td>
|
||||
<td class="px-2 py-2 text-right stock-price-col" id="pricing-total-buy-warehouse">—</td>
|
||||
<td class="px-2 py-2 text-right" id="pricing-total-buy-competitor">—</td>
|
||||
<td class="px-2 py-2 text-right font-bold" id="pricing-total-buy-vendor">—</td>
|
||||
</tr>
|
||||
@@ -271,24 +272,25 @@
|
||||
<table class="w-full text-sm border-collapse">
|
||||
<thead class="bg-gray-50 text-gray-700">
|
||||
<tr>
|
||||
{{if eq .IndicatorMode "accessible"}}<th class="px-2 py-2 border-b" title="Качество цены"><span class="sr-only">Качество цены</span></th>{{end}}
|
||||
<th class="px-2 py-2 text-left border-b whitespace-nowrap">PN вендора</th>
|
||||
<th class="px-2 py-2 text-left border-b">Описание</th>
|
||||
<th class="px-2 py-2 text-left border-b">LOT</th>
|
||||
<th class="px-2 py-2 text-right border-b">Кол-во</th>
|
||||
<th class="px-2 py-2 text-right border-b">Estimate</th>
|
||||
<th class="px-2 py-2 text-right border-b">Склад</th>
|
||||
<th class="px-2 py-2 text-right border-b stock-price-col">Склад</th>
|
||||
<th class="px-2 py-2 text-right border-b">Конкуренты</th>
|
||||
<th class="px-2 py-2 text-right border-b">Ручная цена</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="pricing-body-sale">
|
||||
<tr><td colspan="8" class="px-2 py-8 text-center text-gray-400">Загрузите BOM во вкладке «BOM»</td></tr>
|
||||
<tr><td colspan="{{if eq .IndicatorMode "accessible"}}9{{else}}8{{end}}" class="px-2 py-8 text-center text-gray-400">Загрузите BOM во вкладке «BOM»</td></tr>
|
||||
</tbody>
|
||||
<tfoot id="pricing-foot-sale" class="hidden bg-gray-50 font-semibold">
|
||||
<tr>
|
||||
<td colspan="4" class="px-2 py-2 text-right">Итого:</td>
|
||||
<td colspan="{{if eq .IndicatorMode "accessible"}}5{{else}}4{{end}}" class="px-2 py-2 text-right">Итого:</td>
|
||||
<td class="px-2 py-2 text-right" id="pricing-total-sale-estimate">—</td>
|
||||
<td class="px-2 py-2 text-right" id="pricing-total-sale-warehouse">—</td>
|
||||
<td class="px-2 py-2 text-right stock-price-col" id="pricing-total-sale-warehouse">—</td>
|
||||
<td class="px-2 py-2 text-right" id="pricing-total-sale-competitor">—</td>
|
||||
<td class="px-2 py-2 text-right font-bold" id="pricing-total-sale-vendor">—</td>
|
||||
</tr>
|
||||
@@ -395,10 +397,6 @@
|
||||
<input id="settings-disable-price-refresh" type="checkbox" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
|
||||
<span>Не обновлять цены</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-2 text-sm text-gray-700">
|
||||
<input id="settings-only-in-stock" type="checkbox" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
|
||||
<span>Только наличие</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="px-5 py-4 border-t flex justify-end gap-2">
|
||||
<button type="button" onclick="closePriceSettingsModal()" class="px-4 py-2 bg-gray-100 text-gray-700 rounded hover:bg-gray-200">Отмена</button>
|
||||
@@ -411,6 +409,9 @@
|
||||
<div id="autocomplete-dropdown" class="hidden absolute z-50 bg-white border rounded-lg shadow-lg max-h-96 overflow-y-auto w-96"></div>
|
||||
|
||||
<style>
|
||||
#top-section-pricing.hide-stock-prices .stock-price-col {
|
||||
display: none;
|
||||
}
|
||||
.autocomplete-item {
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
@@ -594,6 +595,7 @@ let resolvedAutoPricelistIds = {
|
||||
};
|
||||
let disablePriceRefresh = false;
|
||||
let onlyInStock = false;
|
||||
let showStockPrices = false;
|
||||
let activePricelistsBySource = {
|
||||
estimate: [],
|
||||
warehouse: [],
|
||||
@@ -609,6 +611,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;
|
||||
@@ -979,6 +994,7 @@ document.addEventListener('DOMContentLoaded', async function() {
|
||||
await loadProjectIndex();
|
||||
updateConfigBreadcrumbs();
|
||||
applyRentalTabVisibility();
|
||||
applyStockPriceSettings();
|
||||
|
||||
rentalConditions = {};
|
||||
(config.rental_items || []).forEach(item => {
|
||||
@@ -996,7 +1012,6 @@ document.addEventListener('DOMContentLoaded', async function() {
|
||||
selectedPricelistIds.warehouse = config.warehouse_pricelist_id || null;
|
||||
selectedPricelistIds.competitor = config.competitor_pricelist_id || null;
|
||||
disablePriceRefresh = Boolean(config.disable_price_refresh);
|
||||
onlyInStock = Boolean(config.only_in_stock);
|
||||
|
||||
if (config.items && config.items.length > 0) {
|
||||
cart = config.items.map(item => ({
|
||||
@@ -1190,10 +1205,6 @@ function syncPriceSettingsControls() {
|
||||
if (disableCheckbox) {
|
||||
disableCheckbox.checked = disablePriceRefresh;
|
||||
}
|
||||
const inStockCheckbox = document.getElementById('settings-only-in-stock');
|
||||
if (inStockCheckbox) {
|
||||
inStockCheckbox.checked = onlyInStock;
|
||||
}
|
||||
}
|
||||
|
||||
function getPricelistVersionById(source, id) {
|
||||
@@ -1210,7 +1221,8 @@ function renderPricelistSettingsSummary() {
|
||||
const competitor = selectedPricelistIds.competitor ? getPricelistVersionById('competitor', selectedPricelistIds.competitor) || `ID ${selectedPricelistIds.competitor}` : '—';
|
||||
const refreshState = disablePriceRefresh ? ' | Обновление цен: выкл' : '';
|
||||
const stockFilterState = onlyInStock ? ' | Только наличие: вкл' : '';
|
||||
summary.textContent = `Estimate: ${estimate}, Склад: ${warehouse}, Конкуренты: ${competitor}${refreshState}${stockFilterState}`;
|
||||
const stockPricesState = showStockPrices ? ' | Складские цены: вкл' : '';
|
||||
summary.textContent = `Estimate: ${estimate}, Склад: ${warehouse}, Конкуренты: ${competitor}${refreshState}${stockFilterState}${stockPricesState}`;
|
||||
}
|
||||
|
||||
function updateRefreshPricesButtonState() {
|
||||
@@ -1280,7 +1292,6 @@ function applyPriceSettings() {
|
||||
const warehouseVal = parseInt(document.getElementById('settings-pricelist-warehouse')?.value || '');
|
||||
const competitorVal = parseInt(document.getElementById('settings-pricelist-competitor')?.value || '');
|
||||
const disableVal = Boolean(document.getElementById('settings-disable-price-refresh')?.checked);
|
||||
const inStockVal = Boolean(document.getElementById('settings-only-in-stock')?.checked);
|
||||
|
||||
const prevWarehouseID = currentWarehousePricelistID();
|
||||
if (Number.isFinite(estimateVal) && estimateVal > 0) {
|
||||
@@ -1296,7 +1307,6 @@ function applyPriceSettings() {
|
||||
resolvedAutoPricelistIds.competitor = null;
|
||||
}
|
||||
disablePriceRefresh = disableVal;
|
||||
onlyInStock = inStockVal;
|
||||
|
||||
const nextWarehouseID = currentWarehousePricelistID();
|
||||
if (Number.isFinite(prevWarehouseID) && prevWarehouseID > 0 && prevWarehouseID !== nextWarehouseID) {
|
||||
@@ -1589,7 +1599,7 @@ function renderMultiSelectTab(components) {
|
||||
const total = getDisplayPrice(item) * item.quantity;
|
||||
|
||||
html += `
|
||||
<tr class="hover:bg-gray-50">
|
||||
<tr class="hover:bg-gray-50" data-lot-name="${escapeHtml(item.lot_name)}">
|
||||
<td class="px-2 py-2 text-center">${qualityDotHtml(comp?.price_quality)}</td>
|
||||
<td class="px-3 py-2 min-w-48">
|
||||
<div class="autocomplete-wrapper relative">
|
||||
@@ -1700,7 +1710,7 @@ function renderMultiSelectTabWithSections(sections) {
|
||||
const total = getDisplayPrice(item) * item.quantity;
|
||||
|
||||
html += `
|
||||
<tr class="hover:bg-gray-50">
|
||||
<tr class="hover:bg-gray-50" data-lot-name="${escapeHtml(item.lot_name)}">
|
||||
<td class="px-2 py-2 text-center">${qualityDotHtml(comp?.price_quality)}</td>
|
||||
<td class="px-3 py-2 min-w-48">
|
||||
<div class="autocomplete-wrapper relative">
|
||||
@@ -1885,7 +1895,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);
|
||||
@@ -1897,27 +1910,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,
|
||||
@@ -1933,15 +1942,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;
|
||||
@@ -1986,22 +2015,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) {
|
||||
@@ -2010,31 +2024,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)
|
||||
@@ -2091,22 +2084,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) {
|
||||
@@ -2115,25 +2093,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();
|
||||
|
||||
@@ -2143,10 +2103,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)
|
||||
@@ -2180,22 +2137,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) {
|
||||
@@ -2205,29 +2147,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
|
||||
@@ -2263,22 +2186,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) {
|
||||
@@ -2323,9 +2231,9 @@ function updateMultiQuantity(lotName, value) {
|
||||
updateCartUI();
|
||||
triggerAutoSave();
|
||||
// Update total in the row
|
||||
const row = document.querySelector(`input[onchange*="${lotName}"]`)?.closest('tr');
|
||||
const row = document.querySelector(`tr[data-lot-name="${CSS.escape(lotName)}"]`);
|
||||
if (row) {
|
||||
const totalCell = row.querySelector('td:nth-child(5)');
|
||||
const totalCell = row.querySelector('td:nth-child(6)');
|
||||
if (totalCell) {
|
||||
totalCell.textContent = formatMoney(getDisplayPrice(item) * item.quantity);
|
||||
}
|
||||
@@ -2422,13 +2330,6 @@ function updateCartUI() {
|
||||
document.getElementById('cart-items').innerHTML = html;
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
if (!text) return '';
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function updateServerModelForQuote(value) {
|
||||
serverModelForQuote = value || '';
|
||||
scheduleArticlePreview();
|
||||
@@ -2720,8 +2621,7 @@ function buildSavePayload() {
|
||||
pricelist_id: selectedPricelistIds.estimate,
|
||||
warehouse_pricelist_id: selectedPricelistIds.warehouse,
|
||||
competitor_pricelist_id: selectedPricelistIds.competitor,
|
||||
disable_price_refresh: disablePriceRefresh,
|
||||
only_in_stock: onlyInStock
|
||||
disable_price_refresh: disablePriceRefresh
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2782,7 +2682,6 @@ function restoreAutosaveDraftIfAny() {
|
||||
supportCode = payload.support_code || supportCode;
|
||||
currentArticle = payload.article || currentArticle;
|
||||
selectedPricelistIds.estimate = payload.pricelist_id || selectedPricelistIds.estimate;
|
||||
onlyInStock = Boolean(payload.only_in_stock);
|
||||
|
||||
const customPriceInput = document.getElementById('custom-price-input');
|
||||
if (customPriceInput) {
|
||||
@@ -3351,6 +3250,24 @@ function applyRentalTabVisibility() {
|
||||
}
|
||||
}
|
||||
|
||||
function applyStockPriceSettings() {
|
||||
const proj = projectUUID ? projectByUUID[projectUUID] : null;
|
||||
showStockPrices = !!(proj && proj.show_stock_prices);
|
||||
onlyInStock = !!(proj && proj.show_stock_prices && proj.only_in_stock);
|
||||
|
||||
const pricingSection = document.getElementById('top-section-pricing');
|
||||
if (pricingSection) {
|
||||
pricingSection.classList.toggle('hide-stock-prices', !showStockPrices);
|
||||
}
|
||||
|
||||
if (onlyInStock) {
|
||||
ensureWarehouseStockFilterLoaded().then(() => {
|
||||
renderTab();
|
||||
updateCartUI();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleRentalRecalc() {
|
||||
clearTimeout(rentalRecalcTimer);
|
||||
rentalRecalcTimer = setTimeout(renderRentalTab, 300);
|
||||
@@ -4573,12 +4490,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) => ({
|
||||
@@ -4594,6 +4508,17 @@ async function renderPricingTab() {
|
||||
// families since applyCustomPrice() strips those on vendor-price cells via regex.
|
||||
const WORLD_CLS = 'bg-amber-50 text-amber-700';
|
||||
|
||||
// Colour-blind-safe mode: leading signal-meter column, no row tint, and the
|
||||
// amber world-fallback cell tint is replaced by a text marker.
|
||||
const ACCESSIBLE_MODE = window.QF_INDICATOR_MODE === 'accessible';
|
||||
const worldCls = (w) => (!ACCESSIBLE_MODE && w) ? WORLD_CLS : '';
|
||||
const worldMark = (w) => (ACCESSIBLE_MODE && w)
|
||||
? '<sup class="text-gray-500 font-semibold" title="Цена-заглушка из прайслиста WORLD">W</sup>'
|
||||
: '';
|
||||
const meterCell = (q, bt) => ACCESSIBLE_MODE
|
||||
? `<td class="pricing-quality-meter px-2 py-1.5 align-middle ${bt || ''}">${qualityMeterHtml(q)}</td>`
|
||||
: '';
|
||||
|
||||
// ─── Build shared row data (unit prices for display, totals for math) ────
|
||||
// Each BOM row is exploded into per-LOT sub-rows; grouped by vendor PN via groupStart/groupSize.
|
||||
const cartQtyMap = {};
|
||||
@@ -4724,7 +4649,7 @@ async function renderPricingTab() {
|
||||
// ─── Populate Buy table ──────────────────────────────────────────────────
|
||||
tbodyBuy.innerHTML = '';
|
||||
if (!rowData.length) {
|
||||
tbodyBuy.innerHTML = '<tr><td colspan="8" class="px-2 py-8 text-center text-gray-400">Нет данных для отображения</td></tr>';
|
||||
tbodyBuy.innerHTML = `<tr><td colspan="${ACCESSIBLE_MODE ? 9 : 8}" class="px-2 py-8 text-center text-gray-400">Нет данных для отображения</td></tr>`;
|
||||
tfootBuy.classList.add('hidden');
|
||||
} else {
|
||||
let totEst = 0, totWh = 0, totComp = 0, totVendor = 0;
|
||||
@@ -4758,12 +4683,13 @@ async function renderPricingTab() {
|
||||
<td${rs} class="px-2 py-1.5 text-xs text-gray-500 truncate max-w-xs border-t border-gray-200 align-top">${escapeHtml(r.desc)}</td>`;
|
||||
})() : '';
|
||||
tr.innerHTML = `
|
||||
${meterCell(r.priceQuality, borderTop)}
|
||||
${pnDescHtml}
|
||||
<td class="px-2 py-1.5 text-xs ${borderTop}">${r.lotCell}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop}">${r.qty}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${r.estWorld ? WORLD_CLS : ''}">${r.estUnit > 0 ? formatCurrency(r.estUnit) : '—'}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${r.whWorld ? WORLD_CLS : ''}">${r.warehouseUnit != null ? formatCurrency(r.warehouseUnit) : '—'}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${r.compWorld ? WORLD_CLS : ''}">${r.competitorUnit != null ? formatCurrency(r.competitorUnit) : '—'}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${worldCls(r.estWorld)}">${r.estUnit > 0 ? formatCurrency(r.estUnit) : '—'}${worldMark(r.estWorld)}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs stock-price-col ${borderTop} ${worldCls(r.whWorld)}">${r.warehouseUnit != null ? formatCurrency(r.warehouseUnit) : '—'}${worldMark(r.whWorld)}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${worldCls(r.compWorld)}">${r.competitorUnit != null ? formatCurrency(r.competitorUnit) : '—'}${worldMark(r.compWorld)}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs pricing-vendor-price-buy ${borderTop} ${r.vendorOrigUnit == null ? 'text-gray-400' : ''}">${r.vendorOrigUnit != null ? formatCurrency(r.vendorOrigUnit) : '—'}</td>
|
||||
`;
|
||||
tbodyBuy.appendChild(tr);
|
||||
@@ -4778,7 +4704,7 @@ async function renderPricingTab() {
|
||||
// ─── Populate Sale table ─────────────────────────────────────────────────
|
||||
tbodySale.innerHTML = '';
|
||||
if (!rowData.length) {
|
||||
tbodySale.innerHTML = '<tr><td colspan="8" class="px-2 py-8 text-center text-gray-400">Нет данных для отображения</td></tr>';
|
||||
tbodySale.innerHTML = `<tr><td colspan="${ACCESSIBLE_MODE ? 9 : 8}" class="px-2 py-8 text-center text-gray-400">Нет данных для отображения</td></tr>`;
|
||||
tfootSale.classList.add('hidden');
|
||||
} else {
|
||||
let totEst = 0, totWh = 0, totComp = 0;
|
||||
@@ -4815,12 +4741,13 @@ async function renderPricingTab() {
|
||||
<td${rs} class="px-2 py-1.5 text-xs text-gray-500 truncate max-w-xs border-t border-gray-200 align-top">${escapeHtml(r.desc)}</td>`;
|
||||
})() : '';
|
||||
tr.innerHTML = `
|
||||
${meterCell(r.priceQuality, borderTop)}
|
||||
${pnDescHtml}
|
||||
<td class="px-2 py-1.5 text-xs ${borderTop}">${r.lotCell}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop}">${r.qty}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${r.estWorld ? WORLD_CLS : ''}">${saleEstUnit > 0 ? formatCurrency(saleEstUnit) : '—'}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${r.whWorld ? WORLD_CLS : ''}">${saleWhUnit != null ? formatCurrency(saleWhUnit) : '—'}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${r.compWorld ? WORLD_CLS : ''}">${saleCompUnit != null ? formatCurrency(saleCompUnit) : '—'}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${worldCls(r.estWorld)}">${saleEstUnit > 0 ? formatCurrency(saleEstUnit) : '—'}${worldMark(r.estWorld)}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs stock-price-col ${borderTop} ${worldCls(r.whWorld)}">${saleWhUnit != null ? formatCurrency(saleWhUnit) : '—'}${worldMark(r.whWorld)}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs ${borderTop} ${worldCls(r.compWorld)}">${saleCompUnit != null ? formatCurrency(saleCompUnit) : '—'}${worldMark(r.compWorld)}</td>
|
||||
<td class="px-2 py-1.5 text-right text-xs pricing-vendor-price-sale ${borderTop} text-gray-400">—</td>
|
||||
`;
|
||||
tbodySale.appendChild(tr);
|
||||
@@ -4867,10 +4794,15 @@ function _setPricingTotal(elId, has, total, worldTotal, count, totalRows) {
|
||||
parts.push(`Цены есть не для всех позиций: ${count} из ${totalRows}`);
|
||||
}
|
||||
|
||||
// Red is reserved for a sum that actually leans on world stand-in prices.
|
||||
el.className = `${el.className} ${share > 0 ? 'text-red-600' : ''} pricing-total-tip`
|
||||
// A sum that leans on world stand-in prices is flagged: by red in color
|
||||
// mode, by a leading ⚠ glyph in accessible mode. The hover popup carries the
|
||||
// exact share (and the coverage line, when some positions have no price) in
|
||||
// both modes.
|
||||
const accessible = window.QF_INDICATOR_MODE === 'accessible';
|
||||
el.className = `${el.className} ${share > 0 && !accessible ? 'text-red-600' : ''} pricing-total-tip`
|
||||
.replace(/\s+/g, ' ').trim();
|
||||
el.innerHTML = `${formatCurrency(total)}<span class="pricing-total-tip__body">${parts.join('<br>')}</span>`;
|
||||
const mark = share > 0 && accessible ? '<span title="Часть суммы — цена-заглушка WORLD">⚠</span> ' : '';
|
||||
el.innerHTML = `${mark}${formatCurrency(total)}<span class="pricing-total-tip__body">${parts.join('<br>')}</span>`;
|
||||
}
|
||||
|
||||
// One decimal, comma separator, no trailing ",0".
|
||||
@@ -5028,6 +4960,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',
|
||||
@@ -5036,9 +4969,10 @@ async function exportPricingCSV(table) {
|
||||
include_lot: true,
|
||||
include_bom: true,
|
||||
include_estimate: true,
|
||||
include_stock: true,
|
||||
include_stock: !!showStockPrices,
|
||||
include_competitor: true,
|
||||
basis: basis,
|
||||
sale_markup: saleUplift > 0 ? saleUplift : null,
|
||||
manual_price: manualPrice > 0 ? manualPrice : null,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -178,7 +178,7 @@
|
||||
<label class="flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||
<input type="radio" name="export-basis" value="ddp" class="border-gray-300">
|
||||
<span class="font-medium">DDP</span>
|
||||
<span class="text-gray-400">— Цена продажи ×1,3</span>
|
||||
<span class="text-gray-400">— Цена продажи</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
@@ -321,6 +321,20 @@
|
||||
</label>
|
||||
<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-show-stock-prices" class="rounded border-gray-300" onchange="applyStockSettingsGating()">
|
||||
<span class="text-sm font-medium text-gray-700">Складские цены</span>
|
||||
</label>
|
||||
<div class="text-xs text-gray-500 mt-1">Показывает складские (Stock) цены во всех ценовых интерфейсах конфигураций этого проекта, включая экспорты CSV.</div>
|
||||
</div>
|
||||
<div id="project-settings-only-in-stock-wrap">
|
||||
<label class="flex items-center space-x-2">
|
||||
<input type="checkbox" id="project-settings-only-in-stock" 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>
|
||||
@@ -1261,10 +1275,24 @@ function openProjectSettingsModal() {
|
||||
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-show-stock-prices').checked = !!project.show_stock_prices;
|
||||
document.getElementById('project-settings-only-in-stock').checked = !!project.only_in_stock;
|
||||
applyStockSettingsGating();
|
||||
document.getElementById('project-settings-modal').classList.remove('hidden');
|
||||
document.getElementById('project-settings-modal').classList.add('flex');
|
||||
}
|
||||
|
||||
function applyStockSettingsGating() {
|
||||
const showStockPrices = document.getElementById('project-settings-show-stock-prices').checked;
|
||||
const onlyInStock = document.getElementById('project-settings-only-in-stock');
|
||||
const wrap = document.getElementById('project-settings-only-in-stock-wrap');
|
||||
onlyInStock.disabled = !showStockPrices;
|
||||
if (!showStockPrices) {
|
||||
onlyInStock.checked = false;
|
||||
}
|
||||
wrap.classList.toggle('opacity-50', !showStockPrices);
|
||||
}
|
||||
|
||||
function closeProjectSettingsModal() {
|
||||
document.getElementById('project-settings-modal').classList.add('hidden');
|
||||
document.getElementById('project-settings-modal').classList.remove('flex');
|
||||
@@ -1277,6 +1305,8 @@ async function saveProjectSettings() {
|
||||
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;
|
||||
const showStockPrices = document.getElementById('project-settings-show-stock-prices').checked;
|
||||
const onlyInStock = document.getElementById('project-settings-only-in-stock').checked;
|
||||
if (!code) {
|
||||
alert('Введите код проекта');
|
||||
return;
|
||||
@@ -1284,7 +1314,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, rental_enabled: rentalEnabled})
|
||||
body: JSON.stringify({code: code, variant: variant, name: name, tracker_url: trackerURL, rental_enabled: rentalEnabled, show_stock_prices: showStockPrices, only_in_stock: onlyInStock})
|
||||
});
|
||||
if (!resp.ok) {
|
||||
if (resp.status === 409) {
|
||||
@@ -1521,6 +1551,12 @@ function openExportModal() {
|
||||
const modal = document.getElementById('project-export-modal');
|
||||
if (!modal) return;
|
||||
setProjectExportStatus('', '');
|
||||
const stockCheckbox = document.getElementById('export-col-stock');
|
||||
const showStockPrices = !!(project && project.show_stock_prices);
|
||||
stockCheckbox.disabled = !showStockPrices;
|
||||
if (!showStockPrices) {
|
||||
stockCheckbox.checked = false;
|
||||
}
|
||||
modal.classList.remove('hidden');
|
||||
modal.classList.add('flex');
|
||||
}
|
||||
|
||||
+104
-24
@@ -4,26 +4,39 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>OFS - Настройка подключения</title>
|
||||
<title>QuoteForge — Настройки</title>
|
||||
<link rel="stylesheet" href="/static/app.css">
|
||||
<script src="/static/vendor/tailwindcss.browser.js"></script>
|
||||
</head>
|
||||
<body class="bg-gray-100 min-h-screen flex items-center justify-center">
|
||||
<div class="max-w-md w-full mx-4">
|
||||
<div class="bg-white rounded-lg shadow-lg p-8">
|
||||
<div class="text-center mb-8">
|
||||
<h1 class="text-2xl font-bold text-blue-600">QuoteForge</h1>
|
||||
<p class="text-gray-600 mt-2">Настройка подключения к базе данных</p>
|
||||
</div>
|
||||
|
||||
<div class="bg-amber-50 border border-amber-300 rounded-md p-3 mb-4 flex items-start gap-2">
|
||||
<svg class="w-5 h-5 text-amber-500 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
|
||||
<body class="bg-gray-100 min-h-screen">
|
||||
<div class="max-w-4xl w-full mx-auto px-4 py-10">
|
||||
{{if .Settings}}
|
||||
<div class="mb-4">
|
||||
<a href="/" class="inline-flex items-center gap-1.5 text-sm text-blue-600 hover:text-blue-800">
|
||||
<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="M10 19l-7-7m0 0l7-7m-7 7h18"/>
|
||||
</svg>
|
||||
<p class="text-sm text-amber-800"><span class="font-semibold">Важно:</span> не закрывайте консольное окно приложения — без него программа не работает.</p>
|
||||
</div>
|
||||
Вернуться в приложение
|
||||
</a>
|
||||
</div>
|
||||
{{end}}
|
||||
<div class="text-center mb-6">
|
||||
<h1 class="text-2xl font-bold text-blue-600">QuoteForge</h1>
|
||||
<p class="text-gray-600 mt-1">Настройки</p>
|
||||
</div>
|
||||
|
||||
<form id="setup-form" class="space-y-4">
|
||||
<div class="bg-amber-50 border border-amber-300 rounded-md p-3 mb-6 flex items-start gap-2">
|
||||
<svg class="w-5 h-5 text-amber-500 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
|
||||
</svg>
|
||||
<p class="text-sm text-amber-800"><span class="font-semibold">Важно:</span> не закрывайте консольное окно приложения — без него программа не работает.</p>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-6 md:grid-cols-2">
|
||||
<div class="bg-white rounded-lg shadow-lg p-6 flex flex-col">
|
||||
<h2 class="text-lg font-semibold text-gray-800 mb-4">Подключение к базе данных</h2>
|
||||
|
||||
<form id="setup-form" class="space-y-4 flex flex-col flex-1">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Хост сервера</label>
|
||||
<input type="text" name="host" id="host"
|
||||
@@ -68,13 +81,7 @@
|
||||
|
||||
<div id="status" class="hidden p-3 rounded-md text-sm"></div>
|
||||
|
||||
<div class="flex space-x-3 pt-4">
|
||||
{{if .Settings}}
|
||||
<a href="/"
|
||||
class="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition text-center">
|
||||
Назад
|
||||
</a>
|
||||
{{end}}
|
||||
<div class="flex space-x-3 pt-4 mt-auto">
|
||||
<button type="button" onclick="testConnection()"
|
||||
class="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 transition">
|
||||
Проверить
|
||||
@@ -87,8 +94,56 @@
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<p class="text-center text-gray-500 text-sm mt-4">
|
||||
QuoteForge v1.0 - Конфигуратор серверов
|
||||
<div class="bg-white rounded-lg shadow-lg p-6 flex flex-col">
|
||||
<h2 class="text-lg font-semibold text-gray-800">Индикаторы</h2>
|
||||
<p class="text-sm text-gray-600 mt-1 mb-4">
|
||||
Часть подсказок в интерфейсе передаётся только цветом: качество цены в спецификации
|
||||
и на вкладке «Ценообразование», цены-заглушки, неполные итоги. Выберите режим без
|
||||
цветовой кодировки, если цвета трудно различать.
|
||||
</p>
|
||||
|
||||
<div class="space-y-3">
|
||||
<label class="flex items-start gap-3 p-3 border border-gray-200 rounded-md cursor-pointer hover:bg-gray-50">
|
||||
<input type="radio" name="indicator-mode" value="color" class="mt-1"
|
||||
{{if ne .IndicatorMode "accessible"}}checked{{end}}>
|
||||
<span class="flex-1">
|
||||
<span class="block text-sm font-medium text-gray-800">Цветовая индикация</span>
|
||||
<span class="block text-xs text-gray-500 mt-0.5">Шкала «красный → жёлтый → зелёный», подсветка ячеек.</span>
|
||||
<span class="inline-flex items-center gap-1.5 mt-2">
|
||||
<span class="inline-block w-2 h-2 rounded-full" style="background-color:rgb(220,38,38)"></span>
|
||||
<span class="inline-block w-2 h-2 rounded-full" style="background-color:rgb(234,179,8)"></span>
|
||||
<span class="inline-block w-2 h-2 rounded-full" style="background-color:rgb(22,163,74)"></span>
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label class="flex items-start gap-3 p-3 border border-gray-200 rounded-md cursor-pointer hover:bg-gray-50">
|
||||
<input type="radio" name="indicator-mode" value="accessible" class="mt-1"
|
||||
{{if eq .IndicatorMode "accessible"}}checked{{end}}>
|
||||
<span class="flex-1">
|
||||
<span class="block text-sm font-medium text-gray-800">Без цветовой кодировки</span>
|
||||
<span class="block text-xs text-gray-500 mt-0.5">Значок-«сигнал» из 5 столбиков и текстовые пометки вместо цвета.</span>
|
||||
<span class="inline-flex items-end gap-2 mt-2">
|
||||
<span class="qf-quality-meter"><i></i><i></i><i></i><i></i><i></i></span>
|
||||
<span class="qf-quality-meter"><i class="on"></i><i class="on"></i><i></i><i></i><i></i></span>
|
||||
<span class="qf-quality-meter"><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i><i class="on"></i></span>
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="mt-auto pt-4">
|
||||
<div id="indicator-status" class="hidden mb-3 p-2 rounded-md text-sm"></div>
|
||||
<button type="button" onclick="saveIndicatorMode()"
|
||||
class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition">
|
||||
Сохранить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="text-center text-gray-500 text-sm mt-8">
|
||||
QuoteForge {{.AppVersion}} — Конфигуратор серверов
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -159,6 +214,31 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function saveIndicatorMode() {
|
||||
const mode = document.querySelector('input[name="indicator-mode"]:checked')?.value || 'color';
|
||||
const box = document.getElementById('indicator-status');
|
||||
box.className = 'mb-3 p-2 rounded-md text-sm bg-blue-100 text-blue-800';
|
||||
box.textContent = 'Сохранение...';
|
||||
try {
|
||||
const resp = await fetch('/api/settings/ui', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ indicator_mode: mode }),
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (resp.ok) {
|
||||
box.className = 'mb-3 p-2 rounded-md text-sm bg-green-100 text-green-800';
|
||||
box.textContent = '✓ Сохранено. Изменения появятся при следующем открытии страниц.';
|
||||
} else {
|
||||
box.className = 'mb-3 p-2 rounded-md text-sm bg-red-100 text-red-800';
|
||||
box.textContent = data.error || 'Не удалось сохранить';
|
||||
}
|
||||
} catch (e) {
|
||||
box.className = 'mb-3 p-2 rounded-md text-sm bg-red-100 text-red-800';
|
||||
box.textContent = 'Ошибка сети: ' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
async function checkServerReady() {
|
||||
let attempts = 0;
|
||||
const maxAttempts = 30; // 30 seconds max
|
||||
|
||||
Reference in new issue
Block a user