| 1 | package fichas |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/fichas/internal/fichas/locale" |
| 5 | "bytes" |
| 6 | "embed" |
| 7 | "html/template" |
| 8 | "log/slog" |
| 9 | "net/http" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/estilo.git/chrome" |
| 13 | "amadan.net/oficina/estilo.git/menu" |
| 14 | "amadan.net/oficina/estilo.git/savestatus" |
| 15 | "amadan.net/rastrillo/rastrillo" |
| 16 | "amadan.net/rastrillo/rastrillo/ui" |
| 17 | |
| 18 | "amadan.net/oficina/fichas/internal/fichas/icons" |
| 19 | ) |
| 20 | |
| 21 | //go:embed templates static |
| 22 | var appFS embed.FS |
| 23 | |
| 24 | // assets fingerprints static/: {{asset "static/tokens.css"}} in a |
| 25 | // template returns a content-hashed URL, served immutable-cacheable by |
| 26 | // the handler App mounts. |
| 27 | var assets = rastrillo.NewAssets(appFS) |
| 28 | |
| 29 | // pages is one *template.Template per page, each combining layout.html |
| 30 | // with that page's own file — kept separate so every page can define a |
| 31 | // template named "content" without colliding with the others. |
| 32 | var pages = map[string]*template.Template{} |
| 33 | |
| 34 | func init() { |
| 35 | // Two shells. The app's own pages use rastrillo's sidebar shell |
| 36 | // (templates/shell.html); sign-in and errors keep the plain column |
| 37 | // (templates/layout.html), because Calma keeps app chrome out of the |
| 38 | // place the suite meets you. Both define "layout". |
| 39 | shells := map[string]string{ |
| 40 | "contract_prepare": "shell", "index": "shell", "card_new": "shell", "card_show": "shell", |
| 41 | "card_edit": "shell", "card_delete": "shell", |
| 42 | "fields": "shell", "field_new": "shell", "field_edit": "shell", |
| 43 | "type_new": "shell", "card_layout": "shell", "history": "shell", |
| 44 | "signin": "layout", "errors": "layout", |
| 45 | } |
| 46 | for name, shell := range shells { |
| 47 | t := template.Must(template.New("layout"). |
| 48 | Funcs(ui.Funcs(ui.WithIcons(icons.Icon, icons.Assets))). |
| 49 | Funcs(template.FuncMap{ |
| 50 | "asset": assets.Path, |
| 51 | "options": selectOptions, |
| 52 | "ago": ago, |
| 53 | "dateAgo": dateAgo, |
| 54 | "stamp": stamp, |
| 55 | "longDate": longDate, |
| 56 | "dateLang": dateLang, |
| 57 | "agoLang": agoLang, |
| 58 | "sameText": sameText, |
| 59 | "stageTone": stageTone, |
| 60 | "isLong": isLong, |
| 61 | "lower": lower, |
| 62 | "count": count, |
| 63 | "showNumber": showNumber, |
| 64 | "showValue": showValue, |
| 65 | "seed": editorSeed, |
| 66 | "personName": personName, |
| 67 | "editField": editField, |
| 68 | "telHref": telHref, |
| 69 | "mailHref": mailHref, |
| 70 | "errFor": errFor, |
| 71 | "yesNo": yesNo, |
| 72 | "displayURL": displayURL, |
| 73 | "safeHref": safeHref, |
| 74 | }). |
| 75 | ParseFS(ui.Templates(), "*.html")) |
| 76 | // estilo chrome: the sign-in door (estilo-signin and friends, |
| 77 | // which call ui's field and callout) and the account menu at the |
| 78 | // rail's foot (estilo-account, whose rows are menu's). Same tree, |
| 79 | // and before the app's own files so the app's templates are the |
| 80 | // last word on any name. |
| 81 | t = template.Must(t.ParseFS(menu.Templates(), "templates/*.html")) |
| 82 | t = template.Must(t.ParseFS(chrome.Templates(), "templates/*.html")) |
| 83 | t = template.Must(t.Parse(savestatus.Template())) |
| 84 | pages[name] = template.Must(t.ParseFS(appFS, "templates/"+shell+".html", "templates/partials.html", "templates/"+name+".html")) |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | // render executes name's layout into a buffer before anything touches |
| 89 | // the wire: a template error becomes a clean 500 instead of garbage |
| 90 | // appended to a half-written page, and headers (flash cookies, say) |
| 91 | // stay settable until the status line is written. |
| 92 | func render(w http.ResponseWriter, name string, data any) { |
| 93 | var buf bytes.Buffer |
| 94 | if err := pages[name].ExecuteTemplate(&buf, "layout", data); err != nil { |
| 95 | slog.Error("render", "page", name, "err", err) |
| 96 | http.Error(w, "something went wrong", http.StatusInternalServerError) |
| 97 | return |
| 98 | } |
| 99 | buf.WriteTo(w) |
| 100 | } |
| 101 | |
| 102 | // renderStatus is render with a status other than 200 (the door's 403 |
| 103 | // refusal): the page is rendered first, so a template error is still a |
| 104 | // clean 500 rather than a 403 with half a page. |
| 105 | func renderStatus(w http.ResponseWriter, name string, data any, status int) { |
| 106 | var buf bytes.Buffer |
| 107 | if err := pages[name].ExecuteTemplate(&buf, "layout", data); err != nil { |
| 108 | slog.Error("render", "page", name, "err", err) |
| 109 | http.Error(w, "something went wrong", http.StatusInternalServerError) |
| 110 | return |
| 111 | } |
| 112 | w.WriteHeader(status) |
| 113 | buf.WriteTo(w) |
| 114 | } |
| 115 | |
| 116 | // ErrorPage renders the "errors" page — templates/errors.html, which |
| 117 | // wraps ui's error-page partial in the layout — for status inside ref |
| 118 | // (rastrillo.NewRef, or empty when there is none to show). It is the |
| 119 | // rastrillo.ErrorPageFunc cmd/fichas/main.go points Options.ErrorPage at, |
| 120 | // so a panic gets the same page a handled failure would; wire it to |
| 121 | // Ctx.ErrorPage too as the app grows handlers of its own. |
| 122 | func ErrorPage(w http.ResponseWriter, r *http.Request, status int, ref string) { |
| 123 | w.WriteHeader(status) |
| 124 | render(w, "errors", map[string]any{"Status": status, "Ref": ref, "Theme": themeAttr(r)}) |
| 125 | } |
| 126 | |
| 127 | // notFound is the app's 404: the error page, never the router's bare |
| 128 | // "404 page not found" in plain text (UX review, 2026-11-12). Every |
| 129 | // "this is not here" in Fichas goes through it, including a row you may |
| 130 | // not see and a route you may not use. |
| 131 | func notFound(w http.ResponseWriter, r *http.Request) { |
| 132 | ErrorPage(w, r, http.StatusNotFound, "") |
| 133 | } |
| 134 | |
| 135 | // themeAttr is <html data-theme>: the person's Appearance choice, "light" or |
| 136 | // "dark", and empty for System, when the page follows the operating |
| 137 | // system. Every page draws it, so the scheme is right in the first paint. |
| 138 | func themeAttr(r *http.Request) string { return chrome.ThemeAttr(chrome.Appearance(r)) } |
| 139 | |
| 140 | // mailHref is an email value's mailto: link, or nothing when it is not |
| 141 | // an address: a value cannot carry mailto: parameters into the link. |
| 142 | func mailHref(v string) string { |
| 143 | if looksLikeAnEmail(v) { |
| 144 | return "mailto:" + v |
| 145 | } |
| 146 | return "" |
| 147 | } |
| 148 | |
| 149 | // telHref is a phone number's tel: link, or nothing when it is not one. |
| 150 | func telHref(v string) template.URL { |
| 151 | if d := telDigits(v); d != "" && looksLikeAPhoneNumber(v) { |
| 152 | return template.URL("tel:" + d) |
| 153 | } |
| 154 | return "" |
| 155 | } |
| 156 | |
| 157 | // editField is a field as the edit form first draws it: a number as its |
| 158 | // seed in the reader's format (§6.8). Once the form has been posted, |
| 159 | // what was typed is drawn again as typed. |
| 160 | func editField(f FieldView, typed bool, L *ui.Localizer) FieldView { |
| 161 | if !typed && f.Def.Kind == KindNumber { |
| 162 | f.Value = seedNumber(L.Format(), f.Value) |
| 163 | } |
| 164 | return f |
| 165 | } |
| 166 | |
| 167 | // selectOptions turns a field's unsealed enum values into what |
| 168 | // ui's field-select wants, marking the current one selected. |
| 169 | // |
| 170 | // A blank first option is always offered: a required-looking select with |
| 171 | // no empty choice silently submits its first value for a card nobody has |
| 172 | // set a stage on yet, which writes a value a person never chose. |
| 173 | func selectOptions(values []string, current string) []map[string]any { |
| 174 | out := make([]map[string]any, 0, len(values)+2) |
| 175 | out = append(out, map[string]any{"Value": "", "Label": "—", "Selected": current == ""}) |
| 176 | known := current == "" |
| 177 | for _, v := range values { |
| 178 | out = append(out, map[string]any{"Value": v, "Label": v, "Selected": v == current}) |
| 179 | known = known || v == current |
| 180 | } |
| 181 | // A stored value the field no longer offers is still the card's: it |
| 182 | // is shown and kept, so saving another field never clears it (§5.2). |
| 183 | if !known { |
| 184 | out = append(out, map[string]any{"Value": current, "Label": current + " (no longer offered)", "Selected": true}) |
| 185 | } |
| 186 | return out |
| 187 | } |
| 188 | |
| 189 | // ago is a past moment in words, for a <time> whose title carries the |
| 190 | // absolute date (AGENTS.md: dates relative, absolute in a title). The |
| 191 | // words are English; past two weeks it is the date, as the reader's |
| 192 | // locale writes it (§6.8, Mapa's relative). |
| 193 | func ago(L *ui.Localizer, when time.Time) string { return relative(datesOf(L), time.Now(), when) } |
| 194 | |
| 195 | // stamp is a moment in full, for a title: "12 November 2026 at 21:09" |
| 196 | // in the reader's locale. |
| 197 | func stamp(L *ui.Localizer, when time.Time) string { return datesOf(L).Stamp(when) } |
| 198 | |
| 199 | // longDate is a stored date in full, year and all, as the reader's |
| 200 | // locale writes it; anything that is no date is shown as it is. |
| 201 | func longDate(L *ui.Localizer, v string) string { |
| 202 | d, err := time.Parse(time.DateOnly, v) |
| 203 | if err != nil || len(v) != len(time.DateOnly) { |
| 204 | return v |
| 205 | } |
| 206 | return datesOf(L).Format("dateYear", d) |
| 207 | } |
| 208 | |
| 209 | // dateAgo is ago for a stored date value ("2026-10-02"), which can be in |
| 210 | // the future — a next action usually is. Anything that does not parse is |
| 211 | // returned unchanged rather than hidden. |
| 212 | func dateAgo(L *ui.Localizer, v string) string { |
| 213 | d, days, ok := daysFromToday(v) |
| 214 | if !ok { |
| 215 | return v |
| 216 | } |
| 217 | dates := datesOf(L) |
| 218 | switch { |
| 219 | case days == 0: |
| 220 | return "today" |
| 221 | case days == 1: |
| 222 | return "tomorrow" |
| 223 | case days == -1: |
| 224 | return "yesterday" |
| 225 | case days > 1 && days < 14: |
| 226 | return "in " + dates.Number(days) + " days" |
| 227 | case days < -1 && days > -14: |
| 228 | return dates.Number(-days) + " days ago" |
| 229 | case d.Year() == time.Now().Year(): |
| 230 | return dates.Format("date", d) |
| 231 | default: |
| 232 | return dates.Format("dateYear", d) |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | // daysFromToday reads a stored date and counts the days from today to |
| 237 | // it, or reports it is no date. |
| 238 | func daysFromToday(v string) (time.Time, int, bool) { |
| 239 | d, err := time.ParseInLocation("2006-01-02", v, time.Local) |
| 240 | if err != nil { |
| 241 | return time.Time{}, 0, false |
| 242 | } |
| 243 | now := time.Now() |
| 244 | today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local) |
| 245 | return d, int(d.Sub(today).Hours() / 24), true |
| 246 | } |
| 247 | |
| 248 | // dateLang is the lang of what dateAgo writes: the reader's locale when |
| 249 | // it writes a date in that locale's words ("4. März"), nothing when it |
| 250 | // writes the interface's English ("in 3 days"). WCAG 3.1.2. |
| 251 | func dateLang(L *ui.Localizer, v string) string { |
| 252 | if _, days, ok := daysFromToday(v); ok && (days >= 14 || days <= -14) && L != nil { |
| 253 | return L.Identity() |
| 254 | } |
| 255 | return "" |
| 256 | } |
| 257 | |
| 258 | // agoLang is ago's: the reader's locale once ago writes a date. |
| 259 | func agoLang(L *ui.Localizer, when time.Time) string { |
| 260 | if time.Since(when) >= 14*24*time.Hour && L != nil { |
| 261 | return L.Identity() |
| 262 | } |
| 263 | return "" |
| 264 | } |
| 265 | |
| 266 | func relative(dates *locale.Locale, now, when time.Time) string { |
| 267 | d := now.Sub(when) |
| 268 | switch { |
| 269 | case d < time.Minute: |
| 270 | return "just now" |
| 271 | case d < time.Hour: |
| 272 | return plural(dates, int(d.Minutes()), "minute") + " ago" |
| 273 | case d < 24*time.Hour: |
| 274 | return plural(dates, int(d.Hours()), "hour") + " ago" |
| 275 | case d < 14*24*time.Hour: |
| 276 | return plural(dates, int(d.Hours()/24), "day") + " ago" |
| 277 | } |
| 278 | return dates.Format("dateYear", when) |
| 279 | } |
| 280 | |
| 281 | func plural(dates *locale.Locale, n int, unit string) string { |
| 282 | if n == 1 { |
| 283 | return "1 " + unit |
| 284 | } |
| 285 | return dates.Number(n) + " " + unit + "s" |
| 286 | } |
| 287 | |
| 288 | // stageTone maps the seeded Stage values to status-pill tones. The |
| 289 | // partial's own docs put this in the app: resolving a raw value to a tone |
| 290 | // is product logic. A value it does not know is neutral, never hidden. |
| 291 | func stageTone(stage string) string { |
| 292 | switch stage { |
| 293 | case "Proposal": |
| 294 | return "warning" |
| 295 | case "Won": |
| 296 | return "positive" |
| 297 | case "Lost": |
| 298 | return "negative" |
| 299 | default: |
| 300 | return "neutral" |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | // errFor is the error for one form field, or "" — nil-safe, because most |
| 305 | // pages have no errors and pass none. |
| 306 | func errFor(errs any, key string) string { |
| 307 | if fe, ok := errs.(FormError); ok { |
| 308 | return fe[key] |
| 309 | } |
| 310 | return "" |
| 311 | } |
| 312 | |
| 313 | func yesNo(b bool) string { |
| 314 | if b { |
| 315 | return "Yes" |
| 316 | } |
| 317 | return "No — private" |
| 318 | } |
| 319 | |