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 "amadan.net/rastrillo/rastrillo"
5 "errors"
6 "log/slog"
7 "net/http"
8 "strconv"
9 "strings"
10
11 "amadan.net/oficina/estilo.git/chrome"
12 "amadan.net/oficina/estilo.git/menu"
13 "amadan.net/rastrillo/rastrillo/auth"
14 "amadan.net/rastrillo/rastrillo/db"
15 "amadan.net/rastrillo/rastrillo/sessions"
16 "github.com/go-chi/chi/v5"
17 "gorm.io/gorm"
18
19 "amadan.net/oficina/fichas/internal/fichas/seal"
20)
21
22// app holds what every handler needs.
23type app struct {
24 db *db.DB
25 // sealer is the only way anything in this app reads or writes a
26 // value. A handler that touches a sealed column without it is a bug
27 // the compiler will catch.
28 sealer *seal.Sealer
29 cfg Config
30 // ix is the decrypted in-memory index that search, sort and filter
31 // run over. It follows the event log, so no write path updates it.
32 ix *Index
33 auth *auth.Auth
34 // sess is the sessions core auth's sessions live in (same table, same
35 // cookie), for the one thing auth does not do on a GET: end the
36 // session of somebody the door has just refused (refusedSession).
37 sess *sessions.Sessions
38 owners []string
39 // testIdentity and allowUnauthenticated let a test act as a person
40 // without a magic-link round trip. **Only AppForTest sets them**, and
41 // TestProductionRefusesAnUnauthenticatedRequest is what stops that
42 // seam becoming a hole — memoria shipped this exact bypass with its
43 // safety argument resting on a test that did not exist.
44 testIdentity string
45 allowUnauthenticated bool
46 logger *slog.Logger
47 // negotiation matches a reader's Accept-Language to the formats
48 // Fichas offers (formats.go).
49 negotiation *rastrillo.Locales
50}
51
52// UseAuth attaches the sign-in flow. Called by main after the mailer
53// exists; without it requireSession refuses every request.
54func (a *app) UseAuth(au *auth.Auth) { a.auth = au }
55
56// actor names who is making a change.
57//
58// Slice 1 has no sign-in, so there are exactly two answers and neither is
59// a guess: a configured local-development member, or a refusal. It never
60// falls back to the app acting as itself — AppBecause exists for honest
61// machine writes and borrowing it here would put "fichas did this" on
62// every row a person typed, which is the attribution failure suite ruling
63// 9 is about.
64func (a *app) actor(r *http.Request) (Actor, error) {
65 address, ok := a.identity(r)
66 if !ok || !a.Admit(address) {
67 // requireSession already refused this request, so reaching here
68 // means a write path was mounted outside the guard. Refuse
69 // loudly rather than inventing an actor.
70 return Actor{}, errors.New("fichas: no admitted identity on a write path")
71 }
72 m, err := memberByAddress(r.Context(), a.db.G, a.sealer, address)
73 if err != nil {
74 return Actor{}, err
75 }
76 return Person(m.ID), nil
77}
78
79// The sign-in handlers are thin because rastrillo's auth owns the flow;
80// they exist so the router names methods on the app and a nil auth is
81// refused in one place rather than panicking in several. The door itself
82// is signin.go.
83func (a *app) authBegin(w http.ResponseWriter, r *http.Request) { a.authOr500(w, r, authBegin) }
84func (a *app) authCallback(w http.ResponseWriter, r *http.Request) { a.authOr500(w, r, authCallback) }
85func (a *app) authVerify(w http.ResponseWriter, r *http.Request) { a.authOr500(w, r, authVerify) }
86
87type authRoute int
88
89const (
90 authBegin authRoute = iota
91 authCallback
92 authVerify
93)
94
95func (a *app) authOr500(w http.ResponseWriter, r *http.Request, which authRoute) {
96 if a.auth == nil {
97 a.logger.Error("no sign-in configured")
98 http.Error(w, "sign-in is not configured", http.StatusInternalServerError)
99 return
100 }
101 switch which {
102 case authBegin:
103 a.auth.Begin(w, r)
104 case authCallback:
105 a.auth.Callback(w, r)
106 case authVerify:
107 a.auth.Verify(w, r)
108 }
109}
110
111// NavItem is one entry in the sidebar.
112type NavItem struct {
113 Label, Href string
114 Current bool
115 Singular string
116 Count int
117}
118
119// page renders a shell page with what every shell page needs: the card
120// types in the sidebar, and who is signed in.
121func (a *app) page(w http.ResponseWriter, r *http.Request, name string, data map[string]any) {
122 a.pageStatus(w, r, http.StatusOK, name, data)
123}
124
125// pageStatus is page with a status — 422 for a form sent back with errors.
126func (a *app) pageStatus(w http.ResponseWriter, r *http.Request, status int, name string, data map[string]any) {
127 current, _ := data["TypeKey"].(string)
128 nav, err := a.nav(r, current)
129 if err != nil {
130 a.fail(w, r, err)
131 return
132 }
133 data["Nav"] = nav
134 me, _ := a.identity(r)
135 data["Account"] = a.account(r, me)
136 data["Theme"] = themeAttr(r)
137 data["L"] = a.readerL(r)
138 if err := a.buildFrame(r, name, data, nav); err != nil {
139 a.fail(w, r, err)
140 return
141 }
142 if status != http.StatusOK {
143 w.WriteHeader(status)
144 }
145 render(w, name, data)
146}
147
148// account is the suite's account menu (estilo chrome, spec §8.2), drawn at
149// the rail's foot and opening upward (Paul, 2026-10-01: "put any shared
150// stuff in the bottom left and maybe roll it into a dropup"): who is
151// signed in, "All apps" when there is a hub directory, Appearance, and the
152// one Sign out. Fichas has no Home connect, so no "Connect your Oficina
153// account", and no credits page yet, so no Help → Open source.
154func (a *app) account(r *http.Request, address string) *chrome.Account {
155 acc := &chrome.Account{
156 TriggerLabel: "Account",
157 Initials: chrome.Initials("", address),
158 Address: address,
159 Labels: chrome.AccountLabels{SignedInAs: "Signed in as", Appearance: "Appearance", Help: "Help"},
160 Appearance: &chrome.AppearanceMenu{
161 Action: "/appearance",
162 Return: returnTarget(r),
163 Options: chrome.AppearanceOptions(chrome.Appearance(r), "Light", "Dark", "System"),
164 },
165 SignOut: chrome.SignOut{Action: "/signout", Label: "Sign out"},
166 Rail: true,
167 }
168 if address != "" {
169 acc.TriggerLabel = "Account: " + address
170 }
171 if a.cfg.Directory != "" {
172 acc.Items = []menu.Item{{Href: a.cfg.Directory + "/", Label: "All apps"}}
173 }
174 return acc
175}
176
177// returnTarget is where Appearance brings a person back to: this page if
178// it is one (a GET), otherwise the list — a form re-rendered with errors
179// is a POST's answer, and its URL is not a page.
180func returnTarget(r *http.Request) string {
181 if r.Method != http.MethodGet && r.Method != http.MethodHead {
182 return "/"
183 }
184 return r.URL.RequestURI()
185}
186
187// nav lists the card types, from the index rather than the database: the
188// labels are sealed and the index has them open already. Scoped to cards —
189// an entry type (Call log) is something you add to a card, not somewhere
190// you go.
191func (a *app) nav(r *http.Request, current string) ([]NavItem, error) {
192 if err := a.ix.Sync(r.Context()); err != nil {
193 return nil, err
194 }
195 var out []NavItem
196 for _, t := range a.ix.Types() {
197 out = append(out, NavItem{Label: t.Plural, Href: typeHref(t.Key), Current: t.Key == current, Singular: t.Label, Count: t.Count})
198 }
199 return out, nil
200}
201
202// typeHref is a card type's list page. Keys are opaque, so a URL never
203// carries a type's name.
204func typeHref(key string) string { return "/t/" + key }
205
206// currentType is the type a request is about: the {type} in the path, a
207// ?type= on a form, or the first type.
208func (a *app) currentType(r *http.Request) (TypeInfo, error) {
209 if err := a.ix.Sync(r.Context()); err != nil {
210 return TypeInfo{}, err
211 }
212 want := chi.URLParam(r, "type")
213 if want == "" {
214 want = r.FormValue("type")
215 }
216 types := a.ix.Types()
217 for _, t := range types {
218 if t.Key == want || (want == "" && t.Key == TypeCustomer) {
219 return t, nil
220 }
221 }
222 if want == "" && len(types) > 0 {
223 return types[0], nil
224 }
225 return TypeInfo{}, gorm.ErrRecordNotFound
226}
227
228// pluralLabel names a collection: a type is "Customer", its list is
229// "Customers". Deliberately naive; a type designer gets its own field for
230// this rather than growing English rules here.
231func pluralLabel(s string) string {
232 if s == "" || strings.HasSuffix(s, "s") {
233 return s
234 }
235 return s + "s"
236}
237
238func (a *app) newCard(w http.ResponseWriter, r *http.Request) {
239 ti, err := a.currentType(r)
240 if err != nil {
241 a.notFoundOrFail(w, r, err)
242 return
243 }
244 fields, err := CardFields(r.Context(), a.db.G, a.sealer, ti.Key)
245 if err != nil {
246 a.fail(w, r, err)
247 return
248 }
249 a.page(w, r, "card_new", map[string]any{"TypeKey": ti.Key, "Type": ti, "Fields": fields})
250}
251
252func (a *app) createCard(w http.ResponseWriter, r *http.Request) {
253 actor, err := a.actor(r)
254 if err != nil {
255 a.fail(w, r, err)
256 return
257 }
258 ti, err := a.currentType(r)
259 if err != nil {
260 a.notFoundOrFail(w, r, err)
261 return
262 }
263 fields, err := CardFields(r.Context(), a.db.G, a.sealer, ti.Key)
264 if err != nil {
265 a.fail(w, r, err)
266 return
267 }
268 values := formValues(r, fields)
269 // Numbers are read in the locale the form was drawn in (§6.8).
270 problems := FormError{}
271 for _, f := range fields {
272 if _, posted := values[f.Def.Key]; posted && f.Def.Kind == KindNumber {
273 v, problem := postedValue(r, f.Def, "")
274 if problem != "" {
275 problems[f.Def.Key] = problem
276 continue // what was typed is drawn again as typed
277 }
278 values[f.Def.Key] = v
279 }
280 }
281 var card Card
282 if len(problems) > 0 {
283 err = problems
284 } else {
285 card, err = CreateCard(r.Context(), a.db.G, a.sealer, ti.Key, actor, values)
286 }
287 if fe, ok := IsFormError(err); ok {
288 // Sent back with what was typed and a message beside each field
289 // that needs it, never a 500 and never an empty form.
290 a.pageStatus(w, r, http.StatusUnprocessableEntity, "card_new", map[string]any{
291 "TypeKey": ti.Key, "Type": ti, "Fields": withValues(fields, values), "Errors": fe})
292 return
293 }
294 if err != nil {
295 a.fail(w, r, err)
296 return
297 }
298 http.Redirect(w, r, "/cards/"+strconv.FormatInt(card.ID, 10), http.StatusSeeOther)
299}
300
301// withValues fills blank field views with what a form submitted, so a form
302// sent back with errors keeps everything the person typed.
303func withValues(fields []FieldView, values map[string]string) []FieldView {
304 out := make([]FieldView, len(fields))
305 copy(out, fields)
306 for i := range out {
307 if v, ok := values[out[i].Def.Key]; ok {
308 out[i].Value = v
309 }
310 }
311 return out
312}
313
314func (a *app) addEntry(w http.ResponseWriter, r *http.Request) {
315 id, ok := pathID(w, r)
316 if !ok {
317 return
318 }
319 actor, err := a.actor(r)
320 if err != nil {
321 a.fail(w, r, err)
322 return
323 }
324 fields, err := EntryFields(r.Context(), a.db.G, a.sealer, TypeCallLog)
325 if err != nil {
326 a.fail(w, r, err)
327 return
328 }
329 values := formValues(r, fields)
330 _, err = AddEntry(r.Context(), a.db.G, a.sealer, id, actor, TypeCallLog, "manual", values)
331 if fe, ok := IsFormError(err); ok {
332 card, lerr := LoadCard(r.Context(), a.db.G, a.sealer, id)
333 if lerr != nil {
334 a.notFoundOrFail(w, r, lerr)
335 return
336 }
337 pane := cardPane{Card: card, CloseHref: typeHref(card.TypeKey)}
338 a.pageStatus(w, r, http.StatusUnprocessableEntity, "card_show", map[string]any{
339 "TypeKey": card.TypeKey, "Card": card, "Pane": pane, "EntryFields": withValues(fields, values), "Errors": fe})
340 return
341 }
342 if err != nil {
343 a.notFoundOrFail(w, r, err)
344 return
345 }
346 // Back where the call was logged: the card beside the list, or its page.
347 http.Redirect(w, r, localReturn(r.PostForm.Get("return_to"), "/cards/"+strconv.FormatInt(id, 10)), http.StatusSeeOther)
348}
349
350// confirmDelete is a PAGE, not a modal: AGENTS.md requires a destructive
351// action to have its own URL, so that it is reachable, linkable and works
352// with scripts off.
353func (a *app) confirmDelete(w http.ResponseWriter, r *http.Request) {
354 id, ok := pathID(w, r)
355 if !ok {
356 return
357 }
358 card, err := LoadCard(r.Context(), a.db.G, a.sealer, id)
359 if err != nil {
360 a.notFoundOrFail(w, r, err)
361 return
362 }
363 a.page(w, r, "card_delete", map[string]any{"TypeKey": card.TypeKey, "Card": card})
364}
365
366func (a *app) deleteCard(w http.ResponseWriter, r *http.Request) {
367 id, ok := pathID(w, r)
368 if !ok {
369 return
370 }
371 actor, err := a.actor(r)
372 if err != nil {
373 a.fail(w, r, err)
374 return
375 }
376 if err := DeleteCard(r.Context(), a.db.G, a.sealer, id, actor); err != nil {
377 a.notFoundOrFail(w, r, err)
378 return
379 }
380 http.Redirect(w, r, "/", http.StatusSeeOther)
381}
382
383// formValues pulls exactly the fields the type defines out of the form.
384//
385// **Never binds the request body onto a model** (AGENTS.md): the field
386// list comes from the card type, and anything else a form posts is
387// ignored because it was never asked for.
388func formValues(r *http.Request, fields []FieldView) map[string]string {
389 _ = r.ParseForm()
390 out := map[string]string{}
391 for _, f := range fields {
392 v, present := r.Form[f.Def.Key]
393 if !present {
394 continue
395 }
396 out[f.Def.Key] = strings.TrimSpace(strings.Join(v, ""))
397 }
398 return out
399}
400
401func pathID(w http.ResponseWriter, r *http.Request) (int64, bool) {
402 id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
403 if err != nil || id <= 0 {
404 notFound(w, r)
405 return 0, false
406 }
407 return id, true
408}
409
410// notFoundOrFail 404s a missing row rather than 403ing or 500ing it — the
411// suite's rule that a row you cannot have is a row that is not there.
412func (a *app) notFoundOrFail(w http.ResponseWriter, r *http.Request, err error) {
413 if errors.Is(err, gorm.ErrRecordNotFound) {
414 notFound(w, r)
415 return
416 }
417 a.fail(w, r, err)
418}
419
420func (a *app) fail(w http.ResponseWriter, r *http.Request, err error) {
421 a.logger.Error("request failed", "path", r.URL.Path, "err", err)
422 ErrorPage(w, r, http.StatusInternalServerError, "")
423}
424
425// errNotFound is a 404 for things that are not gorm rows.
426var errNotFound = gorm.ErrRecordNotFound
427