Files
QuoteForge/internal/configfeatures/configfeatures.go
T
Mikhail ChusavitinandClaude Opus 5.5 4e3b43dbd0 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>
2026-09-24 12:10:58 +03:00

112 lines
3.1 KiB
Go

// 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
}