oficina / fichas Public

Clone
git clone https://amadan.net/oficina/fichas

Plain git — no account needed to clone.

Download

Download this file

1package fichas
2
3import (
4 "context"
5 "crypto/rand"
6 "encoding/hex"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "strconv"
11 "strings"
12 "time"
13 "unicode"
14 "unicode/utf8"
15
16 "amadan.net/oficina/fichas/internal/fichas/seal"
17 "gorm.io/gorm"
18)
19
20// The type designer: adding fields, renaming them, creating card types and
21// arranging a card's face — "in database view I could set up tables and
22// fields" (Paul, 2026-09-29).
23//
24// §4.3 holds throughout. A type or field is ROWS, never DDL: its key is an
25// opaque value generated here and never the user's words, and its label is
26// sealed. A user-added field may be sealed or printed and never plaintext.
27//
28// Every change here writes an Event like a card change does, because "every
29// change to every object" includes the schema, and because the index
30// (index.go) rebuilds from the event log: a field added without an event is
31// a field the Table view would never show.
32
33// Event object kinds for the schema.
34const (
35 ObjectType = "type"
36 ObjectField = "field"
37 // Object kinds later phases write (level-up §9), named now so the
38 // index's feed knows each before anything writes it.
39 ObjectView = "view"
40 ObjectFile = "file"
41 ObjectDraft = "draft"
42 ObjectGroup = "group"
43 ObjectMember = "member"
44)
45
46// Limits, stated so a form can say them.
47const (
48 maxLabel = 80
49 maxOptions = 50
50 maxOption = 60
51 maxText = 2000
52 maxLong = 20000
53)
54
55// FieldSpec is what the add-field form submits.
56type FieldSpec struct {
57 Label string
58 Kind string
59 Tier Tier
60 Options []string // KindEnum only
61}
62
63// FormError is a validation failure a person can fix, keyed by the form
64// field it belongs beside. Handlers render it; nothing is written.
65type FormError map[string]string
66
67func (e FormError) Error() string {
68 parts := make([]string, 0, len(e))
69 for k, v := range e {
70 parts = append(parts, k+": "+v)
71 }
72 return "fichas: " + strings.Join(parts, "; ")
73}
74
75// userKinds are the kinds the designer offers. KindRef ("link to another
76// card") needs a picker and waits; offering it without one would store ids
77// typed by hand.
78var userKinds = map[string]bool{KindText: true, KindLongText: true, KindNumber: true, KindDate: true, KindEnum: true, KindURL: true, KindEmail: true, KindPhone: true}
79
80func (spec FieldSpec) validate() FormError {
81 e := FormError{}
82 label := strings.TrimSpace(spec.Label)
83 switch {
84 case label == "":
85 e["label"] = "Give the field a name."
86 case utf8.RuneCountInString(label) > maxLabel:
87 e["label"] = fmt.Sprintf("Keep the name under %d characters.", maxLabel)
88 }
89 if !userKinds[spec.Kind] {
90 e["kind"] = "Choose what kind of value it holds."
91 }
92 switch spec.Tier {
93 case TierSealed:
94 case TierPrint:
95 // §4.2: a print publishes equality classes. For a short list of
96 // options that IS the values; for paragraphs it is meaningless.
97 switch spec.Kind {
98 case KindEnum:
99 e["tier"] = "A choice can't be findable by exact match: with only a few options, the matches would give the values away."
100 case KindLongText:
101 e["tier"] = "Long text can't be findable by exact match — two notes are almost never identical, so it would find nothing."
102 }
103 default:
104 // TierPlain is not offered, and not accepted: it is reserved for
105 // structural columns the app ships (§4.3).
106 e["tier"] = "Choose whether fichas can check it for duplicates."
107 }
108 if spec.Kind == KindEnum {
109 opts, msg := cleanOptions(spec.Options)
110 if msg != "" {
111 e["options"] = msg
112 } else if len(opts) == 0 {
113 e["options"] = "Add at least one option, one per line."
114 }
115 }
116 if len(e) == 0 {
117 return nil
118 }
119 return e
120}
121
122// cleanOptions trims, drops blanks and duplicates, and enforces the limits.
123func cleanOptions(in []string) ([]string, string) {
124 seen := map[string]bool{}
125 var out []string
126 for _, o := range in {
127 o = strings.TrimSpace(o)
128 if o == "" || seen[o] {
129 continue
130 }
131 if utf8.RuneCountInString(o) > maxOption {
132 return nil, fmt.Sprintf("Keep each option under %d characters.", maxOption)
133 }
134 seen[o] = true
135 out = append(out, o)
136 }
137 if len(out) > maxOptions {
138 return nil, fmt.Sprintf("Keep it to %d options or fewer.", maxOptions)
139 }
140 return out, ""
141}
142
143// newKey is an opaque key: a prefix and 12 random hex digits. Opaque on
144// purpose — a key reaches the durable file in the clear, a label must not.
145func newKey(prefix string) (string, error) {
146 b := make([]byte, 6)
147 if _, err := rand.Read(b); err != nil {
148 return "", fmt.Errorf("fichas: generating a key: %w", err)
149 }
150 return prefix + hex.EncodeToString(b), nil
151}
152
153func sealOptions(s *seal.Sealer, opts []string) ([]byte, error) {
154 if len(opts) == 0 {
155 return nil, nil
156 }
157 raw, err := json.Marshal(opts)
158 if err != nil {
159 return nil, err
160 }
161 return s.Seal(seal.PurposeLabel, raw)
162}
163
164// AddField adds a field to a card type. Existing cards simply have no value
165// for it; nothing is migrated.
166func AddField(ctx context.Context, db *gorm.DB, s *seal.Sealer, typeKey string, actor Actor, spec FieldSpec) (FieldDef, error) {
167 if e := spec.validate(); e != nil {
168 return FieldDef{}, e
169 }
170 var fd FieldDef
171 err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
172 ct, err := typeByKey(tx, typeKey, ScopeCard)
173 if err != nil {
174 return err
175 }
176 key, err := newKey("f_")
177 if err != nil {
178 return err
179 }
180 label, err := s.Seal(seal.PurposeLabel, []byte(strings.TrimSpace(spec.Label)))
181 if err != nil {
182 return err
183 }
184 opts, _ := cleanOptions(spec.Options)
185 sealedOpts, err := sealOptions(s, opts)
186 if err != nil {
187 return err
188 }
189 var ordinal int
190 if err := tx.Model(&FieldDef{}).Where("card_type_id = ?", ct.ID).
191 Select("COALESCE(MAX(ordinal), -1) + 1").Scan(&ordinal).Error; err != nil {
192 return err
193 }
194 fd = FieldDef{CardTypeID: ct.ID, Key: key, SealedLabel: label, SealedOptions: sealedOpts,
195 Kind: spec.Kind, Tier: spec.Tier, Ordinal: ordinal}
196 if err := tx.Create(&fd).Error; err != nil {
197 return fmt.Errorf("fichas: creating the field: %w", err)
198 }
199 return logEvent(tx, s, EventCreated, ObjectField, fd.ID, 0, 0, actor, nil,
200 []change{{Field: "label", After: strings.TrimSpace(spec.Label)}, {Field: "kind", After: spec.Kind}, {Field: "tier", After: string(spec.Tier)}})
201 })
202 if err != nil {
203 return FieldDef{}, err
204 }
205 return fd, nil
206}
207
208// UpdateField renames a field and, for a choice, replaces its options.
209//
210// Kind and tier are NOT editable, and that is the design rather than a gap:
211// both describe how the values already in the database were written, and
212// changing either is a re-encryption of every one of them (Seed refuses the
213// same change for shipped fields). Removing an option does not touch cards
214// that have it: they keep showing their value.
215func UpdateField(ctx context.Context, db *gorm.DB, s *seal.Sealer, key string, actor Actor, label string, options []string) error {
216 label = strings.TrimSpace(label)
217 e := FormError{}
218 if label == "" {
219 e["label"] = "Give the field a name."
220 } else if utf8.RuneCountInString(label) > maxLabel {
221 e["label"] = fmt.Sprintf("Keep the name under %d characters.", maxLabel)
222 }
223 return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
224 var fd FieldDef
225 if err := tx.Where("key = ?", key).First(&fd).Error; err != nil {
226 return err
227 }
228 var opts []string
229 if fd.Kind == KindEnum {
230 var msg string
231 opts, msg = cleanOptions(options)
232 if msg != "" {
233 e["options"] = msg
234 } else if len(opts) == 0 {
235 e["options"] = "Keep at least one option."
236 }
237 }
238 if len(e) > 0 {
239 return e
240 }
241 before, err := openLabel(s, fd.SealedLabel)
242 if err != nil {
243 return err
244 }
245 sealed, err := s.Seal(seal.PurposeLabel, []byte(label))
246 if err != nil {
247 return err
248 }
249 set := map[string]any{"sealed_label": sealed, "updated_at": time.Now()}
250 changes := []change{}
251 if before != label {
252 changes = append(changes, change{Field: "label", Before: before, After: label})
253 }
254 if fd.Kind == KindEnum {
255 var prev []string
256 if len(fd.SealedOptions) > 0 {
257 if prev, err = openOptions(s, fd.SealedOptions); err != nil {
258 return err
259 }
260 }
261 if strings.Join(prev, "\n") != strings.Join(opts, "\n") {
262 so, err := sealOptions(s, opts)
263 if err != nil {
264 return err
265 }
266 set["sealed_options"] = so
267 changes = append(changes, change{Field: "options", Before: strings.Join(prev, "\n"), After: strings.Join(opts, "\n")})
268 }
269 }
270 if len(changes) == 0 {
271 return nil // nothing moved; nothing is logged
272 }
273 if err := tx.Model(&FieldDef{}).Where("id = ?", fd.ID).Updates(set).Error; err != nil {
274 return err
275 }
276 return logEvent(tx, s, EventUpdated, ObjectField, fd.ID, 0, 0, actor, nil, changes)
277 })
278}
279
280// CreateType adds a card type with one field, its title: a type without a
281// name field has cards nobody can tell apart.
282func CreateType(ctx context.Context, db *gorm.DB, s *seal.Sealer, actor Actor, singular, plural string) (CardType, error) {
283 singular, plural = strings.TrimSpace(singular), strings.TrimSpace(plural)
284 e := FormError{}
285 if singular == "" {
286 e["label"] = "Name one of them — Supplier, Candidate, Property."
287 } else if utf8.RuneCountInString(singular) > maxLabel {
288 e["label"] = fmt.Sprintf("Keep the name under %d characters.", maxLabel)
289 }
290 if utf8.RuneCountInString(plural) > maxLabel {
291 e["plural"] = fmt.Sprintf("Keep the name under %d characters.", maxLabel)
292 }
293 if len(e) > 0 {
294 return CardType{}, e
295 }
296 var ct CardType
297 err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
298 key, err := newKey("t_")
299 if err != nil {
300 return err
301 }
302 label, err := s.Seal(seal.PurposeLabel, []byte(singular))
303 if err != nil {
304 return err
305 }
306 var sp []byte
307 if plural != "" {
308 if sp, err = s.Seal(seal.PurposeLabel, []byte(plural)); err != nil {
309 return err
310 }
311 }
312 ct = CardType{Key: key, Scope: ScopeCard, SealedLabel: label, SealedPlural: sp}
313 if err := tx.Create(&ct).Error; err != nil {
314 return fmt.Errorf("fichas: creating the type: %w", err)
315 }
316 fk, err := newKey("f_")
317 if err != nil {
318 return err
319 }
320 nl, err := s.Seal(seal.PurposeLabel, []byte("Name"))
321 if err != nil {
322 return err
323 }
324 // Printed: a name is high-cardinality, and "is this the same one"
325 // is the question worth answering without the key — as Customer's.
326 if err := tx.Create(&FieldDef{CardTypeID: ct.ID, Key: fk, SealedLabel: nl, Kind: KindText, Tier: TierPrint}).Error; err != nil {
327 return err
328 }
329 return logEvent(tx, s, EventCreated, ObjectType, ct.ID, 0, 0, actor, nil,
330 []change{{Field: "label", After: singular}, {Field: "plural", After: plural}})
331 })
332 if err != nil {
333 return CardType{}, err
334 }
335 return ct, nil
336}
337
338// SetFace saves which fields a type's cards show in the Cards view.
339func SetFace(ctx context.Context, db *gorm.DB, s *seal.Sealer, typeKey string, actor Actor, keys []string) error {
340 return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
341 ct, err := typeByKey(tx, typeKey, ScopeCard)
342 if err != nil {
343 return err
344 }
345 var defs []FieldDef
346 if err := tx.Where("card_type_id = ?", ct.ID).Find(&defs).Error; err != nil {
347 return err
348 }
349 known := map[string]bool{FaceLatestCall: true}
350 for _, d := range defs {
351 known[d.Key] = true
352 }
353 clean := []string{}
354 seen := map[string]bool{}
355 for _, k := range keys {
356 if !known[k] {
357 return FormError{"face": "That field isn't on this card type."}
358 }
359 if !seen[k] {
360 seen[k] = true
361 clean = append(clean, k)
362 }
363 }
364 raw, _ := json.Marshal(clean)
365 if string(raw) == ct.FaceKeys {
366 return nil
367 }
368 if err := tx.Model(&CardType{}).Where("id = ?", ct.ID).
369 Updates(map[string]any{"face_keys": string(raw), "updated_at": time.Now()}).Error; err != nil {
370 return err
371 }
372 return logEvent(tx, s, EventUpdated, ObjectType, ct.ID, 0, 0, actor, nil,
373 []change{{Field: "face", Before: ct.FaceKeys, After: string(raw)}})
374 })
375}
376
377// validateValues checks card values against their field kinds before any is
378// written, and says what is wrong in words a person can act on. Before this
379// the store took anything, so a mistyped number or date was a 500.
380func validateValues(defs map[string]FieldDef, values map[string]string) FormError {
381 e := FormError{}
382 for key, v := range values {
383 d, ok := defs[key]
384 if !ok || v == "" {
385 continue
386 }
387 switch d.Kind {
388 case KindNumber:
389 if _, err := strconv.ParseFloat(strings.ReplaceAll(v, ",", ""), 64); err != nil {
390 e[key] = "Enter a number, like 1200 or 3.5."
391 }
392 case KindDate:
393 if _, err := time.Parse("2006-01-02", v); err != nil {
394 e[key] = "Enter a date."
395 }
396 case KindURL:
397 if _, err := normaliseURL(v); err != nil {
398 e[key] = "Enter a web address, like example.com."
399 }
400 case KindEmail:
401 if !looksLikeAnEmail(v) {
402 e[key] = "Enter an email address, like ana@example.com."
403 }
404 case KindPhone:
405 if !looksLikeAPhoneNumber(v) {
406 e[key] = "Enter a phone number, like +353 1 555 0100."
407 }
408 case KindEnum:
409 // The options are sealed and checked by the caller, which has
410 // them open; see optionsError.
411 }
412 limit := maxText
413 if isLong(d) {
414 limit = maxLong
415 }
416 if utf8.RuneCountInString(v) > limit {
417 e[key] = fmt.Sprintf("That's too long — keep it under %d characters.", limit)
418 }
419 }
420 if len(e) == 0 {
421 return nil
422 }
423 return e
424}
425
426// optionsError checks a choice value against the field's options.
427func optionsError(s *seal.Sealer, defs map[string]FieldDef, values map[string]string, e FormError) (FormError, error) {
428 for key, v := range values {
429 d, ok := defs[key]
430 if !ok || d.Kind != KindEnum || v == "" || len(d.SealedOptions) == 0 {
431 continue
432 }
433 opts, err := openOptions(s, d.SealedOptions)
434 if err != nil {
435 return nil, err
436 }
437 found := false
438 for _, o := range opts {
439 if o == v {
440 found = true
441 }
442 }
443 if !found {
444 if e == nil {
445 e = FormError{}
446 }
447 e[key] = "Choose one of the options."
448 }
449 }
450 return e, nil
451}
452
453// IsFormError reports whether err is a validation failure to show beside
454// the fields rather than a failure of the app.
455func IsFormError(err error) (FormError, bool) {
456 var fe FormError
457 if errors.As(err, &fe) {
458 return fe, true
459 }
460 return nil, false
461}
462
463// looksLikeAnEmail is a forgiving check: something@something.something.
464// Whether the address exists is the mail server's question. It refuses
465// what would turn a mailto: link into more than an address (?subject=,
466// &body=, a #), anything percent-encoded, slashes, double quotes,
467// brackets and every kind of whitespace (an apostrophe is fine:
468// o'brien@example.ie): a teammate's value must not pre-fill a draft
469// for whoever clicks it.
470func looksLikeAnEmail(v string) bool {
471 local, domain, ok := strings.Cut(v, "@")
472 if !ok || local == "" || strings.Contains(domain, "@") || !strings.Contains(strings.Trim(domain, "."), ".") {
473 return false
474 }
475 for _, r := range v {
476 if unicode.IsSpace(r) || unicode.IsControl(r) || strings.ContainsRune("?#&/%\\\"<>()[]{},;:", r) {
477 return false
478 }
479 }
480 return true
481}
482
483// DefaultTier is the seal tier a kind gets unless someone chooses
484// otherwise (UX review, 2026-11-12: the designer asked every field an
485// encryption question most people cannot weigh). Values people look for
486// duplicates of, an email, a phone, a web address, are findable by exact
487// match; everything else is private.
488func DefaultTier(kind string) Tier {
489 switch kind {
490 case KindEmail, KindPhone, KindURL:
491 return TierPrint
492 }
493 return TierSealed
494}
495