feat: фича-флаги конфигурации — клиент не сохраняет то, чего не понимает

Конфигурация хранит feature_flags (JSON-массив, NULL = нет) — какие данные
она использует. Флаги выводятся из содержимого при каждом сохранении
(internal/configfeatures). Если у конфигурации есть флаг, неизвестный этой
версии, клиент отказывается её изменять: все write-пути отдают 409
unsupported_config_features со списком флагов, конфигуратор показывает
баннер «обновите приложение» и блокирует сохранение. Push на сервер тоже
отказывается, если серверная версия несёт неизвестный флаг; такое изменение
остаётся в очереди до обновления.

Первый флаг: sale_row_markups. Серверная миграция 034 добавляет колонку;
до её применения запись идёт без колонки (с warning). Формат имён и реестр
флагов — bible-local/02-architecture.md, ADL 2026-09-24.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Mikhail ChusavitinandClaude Opus 5.5 committed 2026-09-24 12:10:58 +03:00
1 parent 6b9652e3ac
commit ef34505418
18 files changed
+579 -20

No files matched your search

+40
View File
@@ -30,6 +30,8 @@ Pull-only:
- pricelists and pricelist items;
- partnumber books and partnumber book items.
Configuration feature flags — see [Configuration feature flags](#configuration-feature-flags).
Readiness guard:
- every sync push/pull runs a preflight check;
- blocked sync returns `423 Locked` with a machine-readable reason;
@@ -125,6 +127,44 @@ both tables gain a narrow leading price-quality meter column (per sub-row), the
tint is removed, `world`-fallback cells show a `W` text marker instead of amber, and the footer
total shows a `⚠` prefix instead of red. CSV output is unaffected.
## Configuration feature flags
A configuration records which data features it uses in `feature_flags`, so a client
that does not know one of them refuses to write it instead of silently dropping data.
Rationale: [decisions/2026-09-24-configuration-feature-flags.md](decisions/2026-09-24-configuration-feature-flags.md).
Storage:
- `qt_configurations.feature_flags` / `local_configurations.feature_flags` — JSON array
of strings, sorted, no duplicates; empty list is stored as `NULL`
(e.g. `["sale_row_markups"]`);
- carried in version snapshots; exposed on reads as `feature_flags`, plus
`unsupported_features` when this build doesn't know some of them.
Flag name format:
- `lower_snake_case`, ASCII `[a-z0-9_]`, starts with a letter, at most 64 chars;
- names the **data** the configuration holds, not the UI or the release:
`<area>_<data>` — e.g. `sale_row_markups`, not `new_pricing_tab` or `v3_42`;
- a name is permanent: never renamed, never reused for different data, never removed
from `configfeatures.known` while any configuration can still carry it;
- a change in the *meaning* of existing data that old clients would mis-handle gets a
new flag (e.g. `sale_row_markups_v2`), not a silent reinterpretation of the old one.
Lifecycle:
- flags are derived from content on every local write (`configfeatures.Detect`), never
sent by the UI; a flag disappears when its data does;
- a client refuses any write (local save or sync push) to a configuration carrying a
flag missing from its `configfeatures.known`, returns `409 unsupported_config_features`,
and the configurator locks itself with a banner listing the raw flag names;
- a new data feature that older clients would drop on save must add its flag — to
`known`, to `Detect`, and to the registry below — in the same change. Data that old
clients round-trip verbatim needs no flag.
Registry:
| Flag | Set when | Data | Since |
| --- | --- | --- | --- |
| `sale_row_markups` | `Notes.pricing_ui.sale_row_markups` has at least one non-zero value | per-row «Накидка, %» on the Sale table (negative = discount) | flag introduced 2026-09-24; data since v3.41 |
## Configuration versioning
Configuration revisions are append-only snapshots stored in `local_configuration_versions`.
+1
View File
@@ -195,6 +195,7 @@ PK: lot_name
| vendor_spec | longtext JSON | |
| rental_items | JSON | per-lot New/БУ condition for the Аренда tab; see [02-architecture.md](02-architecture.md#rental--paid-testing-pricing-contract) |
| rental_uplift_percent | decimal(8,2) DEFAULT 0 | uplift applied to Estimate buy price for rental "Цена" |
| feature_flags | JSON NULL | added by migration 034. Data features the configuration uses (`["sale_row_markups"]`); derived on save, a client refuses to write a config with a flag it doesn't know. See [decisions/2026-09-24-configuration-feature-flags.md](decisions/2026-09-24-configuration-feature-flags.md) |
### qt_lot_metadata
PK: lot_name
+5
View File
@@ -94,6 +94,11 @@ route sets. Consumed by `web/static/price-quality.js` and the pricing tab via a
| `PUT` | `/api/configs/:uuid/rental` | persist Аренда tab state (per-lot New/БУ, weeks, uplift %, annual support) |
| `POST` | `/api/configs/:uuid/rental/calculate` | compute rental/paid-testing pricing without persisting |
Configuration reads include `feature_flags` and, when this build doesn't know some of
them, `unsupported_features`. Any write to such a configuration returns `409`
`{"code":"unsupported_config_features","unsupported_features":[...],"error":"..."}`
(see [decisions/2026-09-24-configuration-feature-flags.md](decisions/2026-09-24-configuration-feature-flags.md)).
## Projects
| Method | Path | Purpose |
@@ -0,0 +1,58 @@
# Decision: per-configuration feature flags — clients refuse to write what they don't understand
**Date:** 2026-09-24
**Status:** active
## Context
Configurations are synced last-write-wins, and every client rebuilds a configuration's
content from what *it* knows before saving. When a newer client adds data (e.g. the
per-row "Накидка" in `Notes.pricing_ui.sale_row_markups`, see
[2026-09-15-sale-row-markup-and-minimal-csv.md](2026-09-15-sale-row-markup-and-minimal-csv.md)),
an older client that opens and saves the same configuration silently drops it; the drop
is pushed to the server and the next pull spreads it to every other client. This
happened in the field (a markup pushed on 2026-09-22 came back `null` on the 09-23 pull).
A global minimum-app-version gate was considered and rejected: it would block all sync
for an outdated client, even for configurations that use no new feature.
## Decision
- `qt_configurations.feature_flags` (JSON array of strings, NULL = none; server
migration `034`) and `local_configurations.feature_flags` (AutoMigrate) record which
data features a configuration uses. Synced like any other column; carried in version
snapshots.
- `internal/configfeatures` is the single source of truth: `known` (flags this build
understands), `Detect(notes)` (derive flags from content), `Unknown`, `Check`,
`UnsupportedError`. Current flags: `sale_row_markups` (at least one non-zero row markup).
- Flags are **derived** on every local write, never sent by the UI: `saveWithVersionAndPending`,
`createWithVersionTx`, `rollbackToVersion`, `UpdateServerCount` first `Check` the flags
*as stored* and refuse with `*configfeatures.UnsupportedError` if any is unknown, then set
`FeatureFlags = Detect(notes)`. This covers update, rename, move, refresh prices,
vendor-spec, rental, server count, deactivate/reactivate, rollback (current and target
snapshot) and clone (the clone inherits the original's flags). Project line reorder is
exempt: it only touches `line_no` and writes the row back with its flags and notes intact.
- Every HTTP handler reports errors via `handlers.RespondError`, which turns an
`UnsupportedError` into `409` `{"code":"unsupported_config_features","unsupported_features":[...],"error":"..."}`
regardless of the status the caller picked.
- Reads expose `unsupported_features` (computed in `LocalToConfiguration`). The
configurator shows a red banner listing them, disables "Сохранить", skips the
exit-save, and also locks itself when a save comes back with the 409.
- Sync push (`pushConfigurationUpdate`) reads the server row first and refuses if its
flags are unknown — a newer client may have written it after our last pull. Such a
refused change is kept in the queue (it is exempt from the max-attempts abandon) so the
local edit is pushed once the app is updated.
- Until migration `034` runs, the server write retries without `feature_flags`
(`withOptionalColumns` in `internal/repository/configuration.go`, same fallback as
`line_no`) and logs a warning — sync keeps working, but flags are not stored on the server.
## Consequences
- **Rule:** any new data feature that an older client would lose on save must add a
flag to `configfeatures.known` and to `Detect` in the same change. Features that old
clients round-trip safely (e.g. data they carry verbatim) need no flag.
- Flags only protect against clients that already contain this check. Clients older
than this change ignore `feature_flags` and can still erase newer data — rollout must
get every user onto a version with this check.
- Order of rollout: apply server migration `034` before (or together with) releasing
the client; otherwise flags silently stay local.
- The UI shows raw flag ids (an old client, by definition, has no human names for them).
+111
View File
@@ -0,0 +1,111 @@
// Package configfeatures holds the per-configuration feature flags: markers recording
// which data features a configuration uses, so a client that does not know one of them
// refuses to rewrite the configuration instead of silently dropping data it cannot see.
//
// Flags are derived from content on every save (Detect) and synced as
// qt_configurations.feature_flags. A client checks a config's stored flags against the
// set it knows (Known) before any write. See
// bible-local/decisions/2026-09-24-configuration-feature-flags.md.
package configfeatures
import (
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
)
// SaleRowMarkups: Notes.pricing_ui.sale_row_markups has at least one row markup.
const SaleRowMarkups = "sale_row_markups"
// known lists every flag this build understands. Adding a flag here is the contract for
// "this client can round-trip the data behind it"; a new data feature that an older
// client would lose on save must add a flag here and to Detect in the same change.
var known = map[string]struct{}{
SaleRowMarkups: {},
}
// Known reports whether this build understands flag.
func Known(flag string) bool {
_, ok := known[flag]
return ok
}
// Unknown returns the flags this build does not understand, sorted and de-duplicated.
func Unknown(flags []string) []string {
seen := make(map[string]struct{}, len(flags))
var out []string
for _, f := range flags {
f = strings.TrimSpace(f)
if f == "" || Known(f) {
continue
}
if _, dup := seen[f]; dup {
continue
}
seen[f] = struct{}{}
out = append(out, f)
}
sort.Strings(out)
return out
}
// Detect derives the flags a configuration's content requires. Sorted; nil when none.
func Detect(notes string) []string {
var flags []string
if notesHaveSaleRowMarkups(notes) {
flags = append(flags, SaleRowMarkups)
}
sort.Strings(flags)
return flags
}
func notesHaveSaleRowMarkups(notes string) bool {
if strings.TrimSpace(notes) == "" {
return false
}
var parsed struct {
PricingUI struct {
SaleRowMarkups map[string]float64 `json:"sale_row_markups"`
} `json:"pricing_ui"`
}
if err := json.Unmarshal([]byte(notes), &parsed); err != nil {
return false
}
for _, pct := range parsed.PricingUI.SaleRowMarkups {
if pct != 0 {
return true
}
}
return false
}
// UnsupportedError is returned when a write is refused because the configuration
// carries flags this build does not know.
type UnsupportedError struct {
Flags []string
}
func (e *UnsupportedError) Error() string {
return fmt.Sprintf(
"конфигурация использует функции, неизвестные этой версии QuoteForge (%s) — обновите приложение, чтобы её изменять",
strings.Join(e.Flags, ", "))
}
// Check returns an *UnsupportedError when any of flags is unknown to this build.
func Check(flags []string) error {
if unknown := Unknown(flags); len(unknown) > 0 {
return &UnsupportedError{Flags: unknown}
}
return nil
}
// AsUnsupported unwraps err to an *UnsupportedError, if it is one.
func AsUnsupported(err error) (*UnsupportedError, bool) {
var ue *UnsupportedError
if errors.As(err, &ue) {
return ue, true
}
return nil, false
}
@@ -0,0 +1,50 @@
package configfeatures
import (
"reflect"
"regexp"
"testing"
)
func TestDetectSaleRowMarkups(t *testing.T) {
cases := []struct {
notes string
want []string
}{
{"", nil},
{"not json", nil},
{`{"pricing_ui":{"sale_uplift":1.5,"sale_row_markups":null}}`, nil},
{`{"pricing_ui":{"sale_row_markups":{"NONE::A":0}}}`, nil},
{`{"pricing_ui":{"sale_row_markups":{"NONE::A":-50}}}`, []string{SaleRowMarkups}},
}
for _, c := range cases {
if got := Detect(c.notes); !reflect.DeepEqual(got, c.want) {
t.Errorf("Detect(%q) = %v, want %v", c.notes, got, c.want)
}
}
}
func TestUnknownAndCheck(t *testing.T) {
got := Unknown([]string{"zeta", SaleRowMarkups, "alpha", "zeta", " "})
if want := []string{"alpha", "zeta"}; !reflect.DeepEqual(got, want) {
t.Fatalf("Unknown = %v, want %v", got, want)
}
if err := Check([]string{SaleRowMarkups}); err != nil {
t.Fatalf("Check(known) = %v", err)
}
ue, ok := AsUnsupported(Check([]string{"future_x"}))
if !ok || !reflect.DeepEqual(ue.Flags, []string{"future_x"}) {
t.Fatalf("Check(unknown) = %v, %v", ue, ok)
}
}
// Flag names are permanent and follow bible-local/02-architecture.md
// "Configuration feature flags": lower_snake_case, starts with a letter, ≤ 64 chars.
func TestKnownFlagNamesFormat(t *testing.T) {
valid := regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
for flag := range known {
if !valid.MatchString(flag) {
t.Errorf("flag %q violates the naming format", flag)
}
}
}
+11
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"strings"
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
"github.com/gin-gonic/gin"
)
@@ -14,6 +15,16 @@ func RespondError(c *gin.Context, status int, fallback string, err error) {
if err != nil {
_ = c.Error(err)
}
// A write refused over unknown configuration feature flags is a 409 with the flag list,
// whatever status the caller picked — every config write path funnels through here.
if ue, ok := configfeatures.AsUnsupported(err); ok {
c.JSON(http.StatusConflict, gin.H{
"error": ue.Error(),
"code": "unsupported_config_features",
"unsupported_features": ue.Flags,
})
return
}
c.JSON(status, gin.H{"error": clientFacingErrorMessage(status, fallback, err)})
}
+29
View File
@@ -2,7 +2,13 @@ package handlers
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
"github.com/gin-gonic/gin"
)
func TestClientFacingErrorMessageKeepsDomain4xx(t *testing.T) {
@@ -39,3 +45,26 @@ type errString string
func (e errString) Error() string {
return string(e)
}
func TestRespondErrorUnsupportedFeaturesIs409(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
err := fmt.Errorf("wrapped: %w", configfeatures.Check([]string{"future_x"}))
RespondError(c, http.StatusInternalServerError, "internal server error", err)
if w.Code != http.StatusConflict {
t.Fatalf("status = %d, want 409", w.Code)
}
var body struct {
Code string `json:"code"`
Features []string `json:"unsupported_features"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatalf("decode body: %v", err)
}
if body.Code != "unsupported_config_features" || len(body.Features) != 1 || body.Features[0] != "future_x" {
t.Fatalf("unexpected body %s", w.Body.String())
}
}
+4
View File
@@ -3,6 +3,7 @@ package localdb
import (
"time"
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
"git.mchus.pro/mchus/quoteforge/internal/models"
)
@@ -62,6 +63,7 @@ func ConfigurationToLocal(cfg *models.Configuration) *LocalConfiguration {
TotalPrice: cfg.TotalPrice,
CustomPrice: cfg.CustomPrice,
Notes: cfg.Notes,
FeatureFlags: cfg.FeatureFlags,
IsTemplate: cfg.IsTemplate,
ServerCount: cfg.ServerCount,
ServerModel: cfg.ServerModel,
@@ -112,6 +114,8 @@ func LocalToConfiguration(local *LocalConfiguration) *models.Configuration {
TotalPrice: local.TotalPrice,
CustomPrice: local.CustomPrice,
Notes: local.Notes,
FeatureFlags: local.FeatureFlags,
UnsupportedFeatures: configfeatures.Unknown(local.FeatureFlags),
IsTemplate: local.IsTemplate,
ServerCount: local.ServerCount,
ServerModel: local.ServerModel,
+1
View File
@@ -102,6 +102,7 @@ type LocalConfiguration struct {
TotalPrice *float64 `json:"total_price"`
CustomPrice *float64 `json:"custom_price"`
Notes string `json:"notes"`
FeatureFlags models.FeatureFlags `gorm:"type:text" json:"feature_flags,omitempty"`
IsTemplate bool `gorm:"default:false" json:"is_template"`
ServerCount int `gorm:"default:1" json:"server_count"`
ServerModel string `gorm:"size:100" json:"server_model,omitempty"`
+5
View File
@@ -5,6 +5,8 @@ import (
"fmt"
"sort"
"time"
"git.mchus.pro/mchus/quoteforge/internal/models"
)
// BuildConfigurationSnapshot serializes the full local configuration state.
@@ -21,6 +23,7 @@ func BuildConfigurationSnapshot(localCfg *LocalConfiguration) (string, error) {
"total_price": localCfg.TotalPrice,
"custom_price": localCfg.CustomPrice,
"notes": localCfg.Notes,
"feature_flags": localCfg.FeatureFlags,
"is_template": localCfg.IsTemplate,
"server_count": localCfg.ServerCount,
"server_model": localCfg.ServerModel,
@@ -60,6 +63,7 @@ func DecodeConfigurationSnapshot(data string) (*LocalConfiguration, error) {
TotalPrice *float64 `json:"total_price"`
CustomPrice *float64 `json:"custom_price"`
Notes string `json:"notes"`
FeatureFlags models.FeatureFlags `json:"feature_flags"`
IsTemplate bool `json:"is_template"`
ServerCount int `json:"server_count"`
ServerModel string `json:"server_model"`
@@ -95,6 +99,7 @@ func DecodeConfigurationSnapshot(data string) (*LocalConfiguration, error) {
TotalPrice: snapshot.TotalPrice,
CustomPrice: snapshot.CustomPrice,
Notes: snapshot.Notes,
FeatureFlags: snapshot.FeatureFlags,
IsTemplate: snapshot.IsTemplate,
ServerCount: snapshot.ServerCount,
ServerModel: snapshot.ServerModel,
+36
View File
@@ -31,6 +31,40 @@ func (c *ConfigItems) Scan(value interface{}) error {
return json.Unmarshal(bytes, c)
}
// FeatureFlags lists the data features a configuration uses (see internal/configfeatures).
// Stored as a JSON array; an empty list is stored as NULL.
type FeatureFlags []string
func (f FeatureFlags) Value() (driver.Value, error) {
if len(f) == 0 {
return nil, nil
}
data, err := json.Marshal([]string(f))
if err != nil {
return nil, err
}
return string(data), nil
}
func (f *FeatureFlags) Scan(value interface{}) error {
*f = nil
var data []byte
switch v := value.(type) {
case nil:
return nil
case []byte:
data = v
case string:
data = []byte(v)
default:
return errors.New("type assertion failed for FeatureFlags")
}
if len(data) == 0 {
return nil
}
return json.Unmarshal(data, f)
}
func (c ConfigItems) Total() float64 {
var total float64
for _, item := range c {
@@ -137,6 +171,8 @@ type Configuration struct {
TotalPrice *float64 `gorm:"type:decimal(12,2)" json:"total_price"`
CustomPrice *float64 `gorm:"type:decimal(12,2)" json:"custom_price"`
Notes string `gorm:"type:text" json:"notes"`
FeatureFlags FeatureFlags `gorm:"type:json" json:"feature_flags,omitempty"`
UnsupportedFeatures []string `gorm:"-" json:"unsupported_features,omitempty"` // flags this build doesn't know; computed on read
IsTemplate bool `gorm:"default:false" json:"is_template"`
ServerCount int `gorm:"default:1" json:"server_count"`
ServerModel string `gorm:"size:100" json:"server_model,omitempty"`
+34 -17
View File
@@ -1,6 +1,8 @@
package repository
import (
"log/slog"
"slices"
"strings"
"git.mchus.pro/mchus/quoteforge/internal/models"
@@ -16,13 +18,9 @@ func NewConfigurationRepository(db *gorm.DB) *ConfigurationRepository {
}
func (r *ConfigurationRepository) Create(config *models.Configuration) error {
if err := r.db.Create(config).Error; err != nil {
if isUnknownLineNoColumnError(err) {
return r.db.Omit("line_no").Create(config).Error
}
return err
}
return nil
return withOptionalColumns(func(omit []string) error {
return r.db.Omit(omit...).Create(config).Error
})
}
func (r *ConfigurationRepository) GetByID(id uint) (*models.Configuration, error) {
@@ -44,21 +42,40 @@ func (r *ConfigurationRepository) GetByUUID(uuid string) (*models.Configuration,
}
func (r *ConfigurationRepository) Update(config *models.Configuration) error {
if err := r.db.Save(config).Error; err != nil {
if isUnknownLineNoColumnError(err) {
return r.db.Omit("line_no").Save(config).Error
}
return err
}
return nil
return withOptionalColumns(func(omit []string) error {
return r.db.Omit(omit...).Save(config).Error
})
}
func isUnknownLineNoColumnError(err error) bool {
// optionalConfigColumns are qt_configurations columns added by server migrations that a
// not-yet-migrated server may lack (line_no: 028, feature_flags: 034). A write that fails
// on one of them is retried without it, so clients keep syncing until the migration runs.
var optionalConfigColumns = []string{"line_no", "feature_flags"}
func withOptionalColumns(write func(omit []string) error) error {
var omit []string
for {
err := write(omit)
col := unknownOptionalColumn(err)
if col == "" || slices.Contains(omit, col) {
return err
}
slog.Warn("qt_configurations column missing on server — writing without it; run server migrations", "column", col)
omit = append(omit, col)
}
}
func unknownOptionalColumn(err error) string {
if err == nil {
return false
return ""
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "unknown column 'line_no'") || strings.Contains(msg, "no column named line_no")
for _, col := range optionalConfigColumns {
if strings.Contains(msg, "unknown column '"+col+"'") || strings.Contains(msg, "no column named "+col) {
return col
}
}
return ""
}
func (r *ConfigurationRepository) Delete(id uint) error {
+29
View File
@@ -10,6 +10,7 @@ import (
"git.mchus.pro/mchus/quoteforge/internal/appmeta"
"git.mchus.pro/mchus/quoteforge/internal/article"
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
"git.mchus.pro/mchus/quoteforge/internal/localdb"
"git.mchus.pro/mchus/quoteforge/internal/models"
"git.mchus.pro/mchus/quoteforge/internal/services/sync"
@@ -324,6 +325,7 @@ func (s *LocalConfigurationService) CloneToProject(configUUID string, ownerUsern
TotalPrice: &total,
CustomPrice: original.CustomPrice,
Notes: original.Notes,
FeatureFlags: original.FeatureFlags,
IsTemplate: false,
ServerCount: original.ServerCount,
ServerModel: original.ServerModel,
@@ -684,6 +686,7 @@ func (s *LocalConfigurationService) CloneNoAuthToProjectFromVersion(configUUID s
TotalPrice: &total,
CustomPrice: original.CustomPrice,
Notes: original.Notes,
FeatureFlags: original.FeatureFlags,
IsTemplate: false,
ServerCount: original.ServerCount,
ServerModel: original.ServerModel,
@@ -928,6 +931,9 @@ func (s *LocalConfigurationService) UpdateServerCount(configUUID string, serverC
return nil, ErrConfigNotFound
}
if err := applyFeatureFlags(localCfg.FeatureFlags, localCfg); err != nil {
return nil, err
}
localCfg.ServerCount = serverCount
total := localCfg.Items.Total()
if serverCount > 1 {
@@ -1172,6 +1178,9 @@ func (s *LocalConfigurationService) createWithVersion(localCfg *localdb.LocalCon
}
func (s *LocalConfigurationService) createWithVersionTx(tx *gorm.DB, localCfg *localdb.LocalConfiguration, createdBy string) error {
if err := applyFeatureFlags(localCfg.FeatureFlags, localCfg); err != nil {
return err
}
if localCfg.IsActive {
if err := s.ensureConfigurationLineTx(tx, localCfg); err != nil {
return err
@@ -1217,6 +1226,9 @@ func (s *LocalConfigurationService) saveWithVersionAndPending(localCfg *localdb.
}
return fmt.Errorf("lock configuration row: %w", err)
}
if err := applyFeatureFlags(locked.FeatureFlags, localCfg); err != nil {
return err
}
if operation == "update" {
currentVersion, err := s.loadCurrentVersionTx(tx, &locked)
@@ -1297,6 +1309,7 @@ func hasNonRevisionConfigurationChanges(current *localdb.LocalConfiguration, nex
}
if current.Name != next.Name ||
current.Notes != next.Notes ||
strings.Join(current.FeatureFlags, ",") != strings.Join(next.FeatureFlags, ",") ||
current.IsTemplate != next.IsTemplate ||
current.ServerModel != next.ServerModel ||
current.SupportCode != next.SupportCode ||
@@ -1640,12 +1653,17 @@ func (s *LocalConfigurationService) rollbackToVersion(configurationUUID string,
return fmt.Errorf("decode target rollback snapshot: %w", err)
}
if err := configfeatures.Check(append(append([]string{}, current.FeatureFlags...), rollbackData.FeatureFlags...)); err != nil {
return err
}
// Keep stable identity/sync linkage; restore editable config content from target snapshot.
current.Name = rollbackData.Name
current.Items = rollbackData.Items
current.TotalPrice = rollbackData.TotalPrice
current.CustomPrice = rollbackData.CustomPrice
current.Notes = rollbackData.Notes
current.FeatureFlags = configfeatures.Detect(rollbackData.Notes)
current.IsTemplate = rollbackData.IsTemplate
current.ServerCount = rollbackData.ServerCount
current.ServerModel = rollbackData.ServerModel
@@ -1859,3 +1877,14 @@ func (s *LocalConfigurationService) resolvePricelistID(pricelistID *uint) (*uint
}
return &latest.ServerID, nil
}
// applyFeatureFlags refuses a write when the configuration as stored carries feature
// flags this build doesn't know (it could not round-trip the data behind them), and
// otherwise re-derives next's flags from its content.
func applyFeatureFlags(stored models.FeatureFlags, next *localdb.LocalConfiguration) error {
if err := configfeatures.Check(stored); err != nil {
return err
}
next.FeatureFlags = configfeatures.Detect(next.Notes)
return nil
}
@@ -0,0 +1,95 @@
package services
import (
"reflect"
"testing"
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
"git.mchus.pro/mchus/quoteforge/internal/localdb"
"git.mchus.pro/mchus/quoteforge/internal/models"
)
const notesWithRowMarkup = `{"pricing_ui":{"sale_uplift":1.5,"sale_row_markups":{"NONE::CPU_A":-50}}}`
func TestSaveDerivesFeatureFlagsFromContent(t *testing.T) {
service, local := newLocalConfigServiceForTest(t)
created, err := service.Create("tester", &CreateConfigRequest{
Name: "cfg",
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 1, UnitPrice: 1000}},
Notes: notesWithRowMarkup,
})
if err != nil {
t.Fatalf("create: %v", err)
}
stored, _ := local.GetConfigurationByUUID(created.UUID)
if want := (models.FeatureFlags{configfeatures.SaleRowMarkups}); !reflect.DeepEqual(stored.FeatureFlags, want) {
t.Fatalf("flags after create = %v, want %v", stored.FeatureFlags, want)
}
// Removing the markups clears the flag.
if _, err := service.UpdateNoAuth(created.UUID, &CreateConfigRequest{
Name: "cfg",
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 1, UnitPrice: 1000}},
Notes: `{"pricing_ui":{"sale_uplift":1.5}}`,
}); err != nil {
t.Fatalf("update: %v", err)
}
stored, _ = local.GetConfigurationByUUID(created.UUID)
if len(stored.FeatureFlags) != 0 {
t.Fatalf("flags after clearing markups = %v, want none", stored.FeatureFlags)
}
}
func TestWritesRefusedForUnknownFeatureFlags(t *testing.T) {
service, local := newLocalConfigServiceForTest(t)
created, err := service.Create("tester", &CreateConfigRequest{
Name: "cfg",
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 1, UnitPrice: 1000}},
Notes: `{"pricing_ui":{},"future":{"x":1}}`,
})
if err != nil {
t.Fatalf("create: %v", err)
}
// Simulate a pull of a config last written by a newer client.
if err := local.DB().Model(&localdb.LocalConfiguration{}).
Where("uuid = ?", created.UUID).
Update("feature_flags", models.FeatureFlags{"future_x", configfeatures.SaleRowMarkups}).Error; err != nil {
t.Fatalf("set flags: %v", err)
}
got, err := service.GetByUUIDNoAuth(created.UUID)
if err != nil {
t.Fatalf("get: %v", err)
}
if want := []string{"future_x"}; !reflect.DeepEqual(got.UnsupportedFeatures, want) {
t.Fatalf("UnsupportedFeatures = %v, want %v", got.UnsupportedFeatures, want)
}
assertRefused := func(name string, err error) {
t.Helper()
ue, ok := configfeatures.AsUnsupported(err)
if !ok || !reflect.DeepEqual(ue.Flags, []string{"future_x"}) {
t.Fatalf("%s: want UnsupportedError{future_x}, got %v", name, err)
}
}
_, err = service.UpdateNoAuth(created.UUID, &CreateConfigRequest{
Name: "cfg",
Items: models.ConfigItems{{LotName: "CPU_A", Quantity: 2, UnitPrice: 1000}},
})
assertRefused("update", err)
_, err = service.RenameNoAuth(created.UUID, "renamed")
assertRefused("rename", err)
_, err = service.UpdateServerCount(created.UUID, 3)
assertRefused("server count", err)
_, err = service.CloneNoAuthToProjectFromVersion(created.UUID, "copy", "tester", nil, 0)
assertRefused("clone", err)
_, err = service.RollbackToVersion(created.UUID, 1, "tester")
assertRefused("rollback", err)
stored, _ := local.GetConfigurationByUUID(created.UUID)
if stored.Name != "cfg" || stored.Items[0].Quantity != 1 || stored.ServerCount != 1 {
t.Fatalf("refused writes must leave the row untouched, got %+v", stored)
}
}
+14 -1
View File
@@ -10,6 +10,7 @@ import (
"sync"
"time"
"git.mchus.pro/mchus/quoteforge/internal/configfeatures"
"git.mchus.pro/mchus/quoteforge/internal/appmeta"
"git.mchus.pro/mchus/quoteforge/internal/db"
"git.mchus.pro/mchus/quoteforge/internal/localdb"
@@ -985,7 +986,10 @@ func (s *Service) PushPendingChanges() (int, error) {
firstErr = err.Error()
}
failed++
if newAttempts >= maxPendingChangeAttempts {
// Refused over unknown feature flags: not a transient failure, and dropping it would
// lose the local edit — keep it queued until the app is updated.
_, unsupported := configfeatures.AsUnsupported(err)
if newAttempts >= maxPendingChangeAttempts && !unsupported {
slog.Error("abandoning pending change after max attempts",
"id", change.ID, "type", change.EntityType, "op", change.Operation,
"attempts", newAttempts, "last_error", err.Error())
@@ -1301,6 +1305,15 @@ func (s *Service) pushConfigurationUpdate(change *localdb.PendingChange) error {
}
}
// A newer client may have written this config since our last pull, adding data this
// build can't see (marked by a feature flag we don't know). Pushing our snapshot over
// it would erase that data, so refuse; the change stays queued until the app is updated.
if serverCfg, getErr := configRepo.GetByUUID(cfg.UUID); getErr == nil {
if err := configfeatures.Check(serverCfg.FeatureFlags); err != nil {
return fmt.Errorf("push of configuration %s refused: %w", cfg.UUID, err)
}
}
// Update on server
if err := configRepo.Update(&cfg); err != nil {
return fmt.Errorf("updating configuration on server: %w", err)
@@ -0,0 +1,11 @@
-- Tables affected: qt_configurations
-- recovery.not-started: safe to re-run; ADD COLUMN IF NOT EXISTS
-- recovery.partial: ALTER TABLE qt_configurations DROP COLUMN feature_flags;
-- recovery.completed: no action needed
-- verify: feature_flags column missing | SELECT 1 FROM information_schema.COLUMNS WHERE table_schema=DATABASE() AND table_name='qt_configurations' AND column_name='feature_flags' HAVING COUNT(*)=0
-- Per-configuration feature flags (JSON array of strings, NULL = none). A client refuses
-- to write a configuration carrying a flag it doesn't know. See
-- bible-local/decisions/2026-09-24-configuration-feature-flags.md.
ALTER TABLE qt_configurations
ADD COLUMN IF NOT EXISTS feature_flags JSON NULL;
+45 -2
View File
@@ -37,13 +37,24 @@
title="Настройки цен">
Цены
</button>
<button onclick="saveConfig()" class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700">
<button id="save-config-btn" onclick="saveConfig()" class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed">
Сохранить
</button>
<span id="price-update-date" class="text-sm text-gray-500"></span>
</div>
</div>
<!-- Shown when the config carries feature flags this build doesn't know: saving is refused
(see setConfigUnsupportedFeatures / internal/configfeatures). -->
<div id="config-unsupported-banner" class="hidden bg-red-50 border border-red-200 text-red-800 rounded-lg px-4 py-3 text-sm" role="alert">
<div class="font-semibold">Эта конфигурация создана в более новой версии QuoteForge</div>
<div class="mt-1">
Она использует функции, которых нет в вашей версии:
<span id="config-unsupported-list" class="font-mono"></span>.
Сохранение отключено, чтобы не потерять эти данные. Обновите приложение, чтобы редактировать конфигурацию.
</div>
</div>
<!-- Server count input -->
<div class="bg-white rounded-lg shadow p-4 mb-4">
<div class="flex items-center space-x-4">
@@ -623,6 +634,25 @@ const PricingMarkup = {
// reads it live rather than relying on per-render input state.
let saleRowMarkups = {};
// Feature flags of this configuration unknown to this build (server-computed
// unsupported_features). Non-empty → saving is refused both here and by the backend.
let configUnsupportedFeatures = [];
function setConfigUnsupportedFeatures(flags) {
configUnsupportedFeatures = Array.isArray(flags) ? flags.filter(Boolean) : [];
const blocked = configUnsupportedFeatures.length > 0;
document.getElementById('config-unsupported-banner')?.classList.toggle('hidden', !blocked);
const list = document.getElementById('config-unsupported-list');
if (list) list.textContent = configUnsupportedFeatures.join(', ');
const btn = document.getElementById('save-config-btn');
if (btn) btn.disabled = blocked;
}
function unsupportedFeaturesMessage() {
return 'Сохранение невозможно: конфигурация использует функции, неизвестные этой версии ('
+ configUnsupportedFeatures.join(', ') + '). Обновите приложение.';
}
// Notes keys this client doesn't understand (top-level and inside pricing_ui), kept from
// the last restorePricingStateFromNotes() and written back verbatim on save — otherwise
// an older client re-saving a config silently drops fields added by a newer one.
@@ -1043,6 +1073,7 @@ document.addEventListener('DOMContentLoaded', async function() {
supportCode = parseSupportCodeFromLotName((cart.find(i => (i.lot_name || '').toUpperCase().startsWith('SVC_')) || {}).lot_name);
currentArticle = config.article || '';
restorePricingStateFromNotes(config.notes || '');
setConfigUnsupportedFeatures(config.unsupported_features);
// Restore custom price if saved
if (config.custom_price) {
@@ -2770,7 +2801,7 @@ function restoreAutosaveDraftIfAny() {
}
function saveConfigOnExit() {
if (!configUUID || !hasUnsavedChanges || exitSaveStarted) return;
if (!configUUID || !hasUnsavedChanges || exitSaveStarted || configUnsupportedFeatures.length) return;
exitSaveStarted = true;
try {
fetch('/api/configs/' + configUUID, {
@@ -2800,6 +2831,10 @@ function triggerAutoSave() {
async function saveConfig(showNotification = true) {
// RBAC disabled - no token check required
if (!configUUID) return;
if (configUnsupportedFeatures.length) {
if (showNotification) showToast(unsupportedFeaturesMessage(), 'error');
return;
}
if (priceLevelsRefreshTimer) {
clearTimeout(priceLevelsRefreshTimer);
priceLevelsRefreshTimer = null;
@@ -2817,6 +2852,14 @@ async function saveConfig(showNotification = true) {
});
if (!resp.ok) {
// 409 unsupported_config_features: a newer client added data this build can't
// round-trip (possibly since this page was opened) — lock the page.
const errBody = await resp.json().catch(() => null);
if (errBody && errBody.code === 'unsupported_config_features') {
setConfigUnsupportedFeatures(errBody.unsupported_features);
if (showNotification) showToast(unsupportedFeaturesMessage(), 'error');
return;
}
if (showNotification) {
showToast('Ошибка сохранения', 'error');
}