| 1 | package fichas |
| 2 | |
| 3 | // The HTTP side of editing in place (level-up §5.1–§5.3): one field at |
| 4 | // a time with script (JSON back), the whole edit form without, and Undo. |
| 5 | |
| 6 | import ( |
| 7 | "bytes" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "net/http" |
| 11 | "net/url" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | |
| 15 | "amadan.net/rastrillo/rastrillo/ui" |
| 16 | "github.com/go-chi/chi/v5" |
| 17 | "gorm.io/gorm" |
| 18 | ) |
| 19 | |
| 20 | // wantsJSON is a script's request: it asked for JSON back. |
| 21 | func wantsJSON(r *http.Request) bool { |
| 22 | return strings.Contains(r.Header.Get("Accept"), "application/json") |
| 23 | } |
| 24 | |
| 25 | func writeJSON(w http.ResponseWriter, status int, v any) { |
| 26 | w.Header().Set("Content-Type", "application/json; charset=utf-8") |
| 27 | w.Header().Set("Cache-Control", "no-store") |
| 28 | w.WriteHeader(status) |
| 29 | _ = json.NewEncoder(w).Encode(v) |
| 30 | } |
| 31 | |
| 32 | // errReenter is a posted locale echo that names no locale Fichas reads |
| 33 | // in: the page that posted it cannot be trusted to say what 1.500 meant. |
| 34 | const errReenter = "Enter the value again." |
| 35 | |
| 36 | // echoedLocale is the locale the posting page was drawn in (§6.8), or |
| 37 | // "" when the echo is missing or names no linked locale as rastrillo |
| 38 | // spells it. |
| 39 | func echoedLocale(r *http.Request, key string) string { |
| 40 | v := r.PostForm.Get(key + ".locale") |
| 41 | if localizerFor(v) != nil { |
| 42 | return v |
| 43 | } |
| 44 | return "" |
| 45 | } |
| 46 | |
| 47 | // postedValue is one field's posted value, read in the page's locale and |
| 48 | // made canonical; or a message saying what to fix. |
| 49 | func postedValue(r *http.Request, def FieldDef, was string) (string, string) { |
| 50 | raw := strings.TrimSpace(r.PostForm.Get(def.Key)) |
| 51 | // A web address is drawn without its scheme; drawn back untouched it |
| 52 | // is the value the editor saw, not a change to https:// (§5.2). |
| 53 | if def.Kind == KindURL && was != "" && raw == displayURL(was) { |
| 54 | return was, "" |
| 55 | } |
| 56 | if def.Kind != KindNumber { |
| 57 | return raw, "" |
| 58 | } |
| 59 | locale := echoedLocale(r, def.Key) |
| 60 | if locale == "" { |
| 61 | return "", errReenter |
| 62 | } |
| 63 | v, err := readNumberInput(locale, raw, was) |
| 64 | if err != nil { |
| 65 | return "", err.Error() |
| 66 | } |
| 67 | return v, "" |
| 68 | } |
| 69 | |
| 70 | // setFieldValue is POST /cards/{id}/fields/{key}: one field, with what |
| 71 | // the editor saw (was.<key>), read in the page's locale (<key>.locale). |
| 72 | func (a *app) setFieldValue(w http.ResponseWriter, r *http.Request) { |
| 73 | id, ok := pathID(w, r) |
| 74 | if !ok { |
| 75 | return |
| 76 | } |
| 77 | actor, err := a.actor(r) |
| 78 | if err != nil { |
| 79 | a.fail(w, r, err) |
| 80 | return |
| 81 | } |
| 82 | _ = r.ParseForm() |
| 83 | card, err := LoadCard(r.Context(), a.db.G, a.sealer, id) |
| 84 | if err != nil { |
| 85 | a.notFoundOrFail(w, r, err) |
| 86 | return |
| 87 | } |
| 88 | key := chi.URLParam(r, "key") |
| 89 | f := card.Field(key) |
| 90 | if f.Def.Key == "" { |
| 91 | notFound(w, r) |
| 92 | return |
| 93 | } |
| 94 | // Line endings are the store's one rule (EditFields compares |
| 95 | // newline-blind; normaliseValue writes LF), not repeated here. |
| 96 | was := r.PostForm.Get("was." + key) |
| 97 | value, problem := postedValue(r, f.Def, was) |
| 98 | if problem != "" { |
| 99 | a.refuseField(w, r, card, key, problem) |
| 100 | return |
| 101 | } |
| 102 | res, err := SetField(r.Context(), a.db.G, a.sealer, id, actor, key, value, was) |
| 103 | a.answerFieldEdit(w, r, card, f, res, err) |
| 104 | } |
| 105 | |
| 106 | // answerFieldEdit says what a one-field edit did: JSON to a script, a |
| 107 | // redirect to everyone else. |
| 108 | func (a *app) answerFieldEdit(w http.ResponseWriter, r *http.Request, card CardView, f FieldView, res EditResult, err error) { |
| 109 | L := a.pageL(r, f.Def.Key) |
| 110 | if fe, ok := IsFormError(err); ok { |
| 111 | a.refuseField(w, r, card, f.Def.Key, fe[f.Def.Key]) |
| 112 | return |
| 113 | } |
| 114 | if c, ok := IsConflict(err); ok { |
| 115 | theirs := c.Fields[f.Def.Key] |
| 116 | me, _ := a.identity(r) |
| 117 | msg := conflictLine(L, f, theirs, me) |
| 118 | if !wantsJSON(r) { |
| 119 | a.backWith(w, r, card.Card.ID, "conflict", "1") |
| 120 | return |
| 121 | } |
| 122 | writeJSON(w, http.StatusConflict, map[string]any{ |
| 123 | "message": msg, "theirs": theirs.Theirs, "seed": editorSeed(L, f.Def, theirs.Theirs), |
| 124 | "cell": a.cellHTML(L, card, f, theirs.Theirs), |
| 125 | }) |
| 126 | return |
| 127 | } |
| 128 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 129 | notFound(w, r) |
| 130 | return |
| 131 | } |
| 132 | if err != nil { |
| 133 | a.fail(w, r, err) |
| 134 | return |
| 135 | } |
| 136 | now := res.Values[f.Def.Key] |
| 137 | msg := changedLine(L, f, now) |
| 138 | if !wantsJSON(r) { |
| 139 | if res.EventID != 0 { |
| 140 | a.backWith(w, r, card.Card.ID, "saved", strconv.FormatInt(res.EventID, 10)) |
| 141 | return |
| 142 | } |
| 143 | a.backWith(w, r, card.Card.ID, "", "") |
| 144 | return |
| 145 | } |
| 146 | writeJSON(w, http.StatusOK, map[string]any{ |
| 147 | "event": res.EventID, "message": msg, "value": now, |
| 148 | "seed": editorSeed(L, f.Def, now), "cell": a.cellHTML(L, card, f, now), |
| 149 | "outOfView": res.EventID != 0 && !a.stillInView(r, card, f.Def.Key, r.PostForm.Get("list")), |
| 150 | }) |
| 151 | } |
| 152 | |
| 153 | // pageL is the localizer the posting page was drawn with, or the |
| 154 | // reader's when the post carried no echo (a field with no number). |
| 155 | func (a *app) pageL(r *http.Request, key string) *ui.Localizer { |
| 156 | if l := localizerFor(echoedLocale(r, key)); l != nil { |
| 157 | return l |
| 158 | } |
| 159 | return a.readerL(r) |
| 160 | } |
| 161 | |
| 162 | // refuseField answers a value a person must fix (422), writing nothing. |
| 163 | func (a *app) refuseField(w http.ResponseWriter, r *http.Request, card CardView, key, problem string) { |
| 164 | if wantsJSON(r) { |
| 165 | writeJSON(w, http.StatusUnprocessableEntity, map[string]any{"error": problem}) |
| 166 | return |
| 167 | } |
| 168 | a.backWith(w, r, card.Card.ID, "refused", "1") |
| 169 | } |
| 170 | |
| 171 | // backWith returns a scriptless post to where it came from (return_to, |
| 172 | // a local path only), or the card, with one notice in the query. |
| 173 | func (a *app) backWith(w http.ResponseWriter, r *http.Request, cardID int64, name, value string) { |
| 174 | to := localReturn(r.PostForm.Get("return_to"), "/cards/"+strconv.FormatInt(cardID, 10)) |
| 175 | if name != "" { |
| 176 | u, _ := url.Parse(to) |
| 177 | q := u.Query() |
| 178 | for _, n := range []string{"saved", "undone", "refused", "conflict"} { |
| 179 | q.Del(n) |
| 180 | } |
| 181 | q.Set(name, value) |
| 182 | u.RawQuery = q.Encode() |
| 183 | to = u.String() |
| 184 | } |
| 185 | http.Redirect(w, r, to, http.StatusSeeOther) |
| 186 | } |
| 187 | |
| 188 | // localReturn is to when it is a path on this app, and fallback |
| 189 | // otherwise: never another origin, never a scheme-relative //host. |
| 190 | func localReturn(to, fallback string) string { |
| 191 | if !strings.HasPrefix(to, "/") || strings.HasPrefix(to, "//") || strings.ContainsAny(to, "\\\r\n\t") { |
| 192 | return fallback |
| 193 | } |
| 194 | u, err := url.Parse(to) |
| 195 | if err != nil || u.Host != "" || u.Scheme != "" { |
| 196 | return fallback |
| 197 | } |
| 198 | return u.RequestURI() |
| 199 | } |
| 200 | |
| 201 | // showValue is a stored value as a reader sees it in a sentence. |
| 202 | func showValue(L *ui.Localizer, kind, v string) string { |
| 203 | switch { |
| 204 | case v == "": |
| 205 | return "" |
| 206 | case kind == KindNumber: |
| 207 | return showNumber(L, v) |
| 208 | case kind == KindDate: |
| 209 | return longDate(L, v) |
| 210 | case kind == KindURL: |
| 211 | return displayURL(v) |
| 212 | } |
| 213 | return v |
| 214 | } |
| 215 | |
| 216 | // editorSeed is what an editor starts from: a number in the reader's |
| 217 | // format without group marks (§6.8), anything else as stored. |
| 218 | func editorSeed(L *ui.Localizer, def FieldDef, v string) string { |
| 219 | if def.Kind == KindNumber { |
| 220 | return seedNumber(L.Format(), v) |
| 221 | } |
| 222 | if def.Kind == KindURL && v != "" { |
| 223 | return displayURL(v) |
| 224 | } |
| 225 | return v |
| 226 | } |
| 227 | |
| 228 | func changedLine(L *ui.Localizer, f FieldView, now string) string { |
| 229 | if now == "" { |
| 230 | return f.Label + " cleared." |
| 231 | } |
| 232 | return f.Label + " changed to " + showValue(L, f.Def.Kind, now) + "." |
| 233 | } |
| 234 | |
| 235 | // conflictLine is §5.2's "Niamh changed this to Contacted." When the |
| 236 | // last change was this person's own, from another tab or window, it says |
| 237 | // so rather than naming them to themselves. |
| 238 | func conflictLine(L *ui.Localizer, f FieldView, c Conflict, me string) string { |
| 239 | who := "Someone" |
| 240 | switch { |
| 241 | case c.By != "" && c.By == me: |
| 242 | who = "You" |
| 243 | case c.By != "": |
| 244 | who = personName(c.By) |
| 245 | } |
| 246 | where := "." |
| 247 | if who == "You" { |
| 248 | where = " in another tab." |
| 249 | } |
| 250 | if c.Theirs == "" { |
| 251 | return who + " cleared this" + where |
| 252 | } |
| 253 | return who + " changed this to " + showValue(L, f.Def.Kind, c.Theirs) + where |
| 254 | } |
| 255 | |
| 256 | // cellHTML draws one table cell's contents as the list draws it. |
| 257 | func (a *app) cellHTML(L *ui.Localizer, card CardView, f FieldView, v string) string { |
| 258 | f.Value = v |
| 259 | var buf bytes.Buffer |
| 260 | if err := pages["index"].ExecuteTemplate(&buf, "fichas-cell-value", map[string]any{"F": f, "L": L, "CardID": card.Card.ID}); err != nil { |
| 261 | a.logger.Error("drawing a cell", "err", err) |
| 262 | return "" |
| 263 | } |
| 264 | return buf.String() |
| 265 | } |
| 266 | |
| 267 | // stillInView reports whether an edited card still belongs where it |
| 268 | // was: it matches the list's search and filters, and the list is not |
| 269 | // sorted by the field just changed (§5.1's "No longer in this view"). |
| 270 | // list is the list's query string, as the page posted it. |
| 271 | func (a *app) stillInView(r *http.Request, card CardView, key, list string) bool { |
| 272 | q, err := url.ParseQuery(list) |
| 273 | if err != nil { |
| 274 | return true |
| 275 | } |
| 276 | if err := a.ix.Sync(r.Context()); err != nil { |
| 277 | return true |
| 278 | } |
| 279 | fields, err := a.ix.Fields(card.TypeKey) |
| 280 | if err != nil { |
| 281 | return true |
| 282 | } |
| 283 | l := parseListValues(q, typeHref(card.TypeKey), fields) |
| 284 | if l.Sort == key { |
| 285 | return false |
| 286 | } |
| 287 | return a.ix.Matches(card.TypeKey, l.query(), card.Card.ID) |
| 288 | } |
| 289 | |
| 290 | // undoEdit is POST /cards/{id}/undo, naming the event to reverse (or an |
| 291 | // Undo's event, to redo it). |
| 292 | func (a *app) undoEdit(w http.ResponseWriter, r *http.Request) { |
| 293 | id, ok := pathID(w, r) |
| 294 | if !ok { |
| 295 | return |
| 296 | } |
| 297 | actor, err := a.actor(r) |
| 298 | if err != nil { |
| 299 | a.fail(w, r, err) |
| 300 | return |
| 301 | } |
| 302 | _ = r.ParseForm() |
| 303 | eventID, _ := strconv.ParseInt(r.PostForm.Get("event"), 10, 64) |
| 304 | res, err := Undo(r.Context(), a.db.G, a.sealer, id, actor, eventID) |
| 305 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 306 | notFound(w, r) |
| 307 | return |
| 308 | } |
| 309 | if err != nil { |
| 310 | a.fail(w, r, err) |
| 311 | return |
| 312 | } |
| 313 | card, err := LoadCard(r.Context(), a.db.G, a.sealer, id) |
| 314 | if err != nil { |
| 315 | a.notFoundOrFail(w, r, err) |
| 316 | return |
| 317 | } |
| 318 | L := localizerFor(r.PostForm.Get("locale")) |
| 319 | if L == nil { |
| 320 | L = a.readerL(r) |
| 321 | } |
| 322 | msg := undoLine(card, res) |
| 323 | if !wantsJSON(r) { |
| 324 | a.backWith(w, r, id, "undone", strconv.FormatInt(res.EventID, 10)+leftMark(res)) |
| 325 | return |
| 326 | } |
| 327 | cells := map[string]map[string]string{} |
| 328 | for _, c := range res.Applied { |
| 329 | f := card.Field(c.Field) |
| 330 | cells[c.Field] = map[string]string{"cell": a.cellHTML(L, card, f, c.After), "value": c.After, "seed": editorSeed(L, f.Def, c.After)} |
| 331 | } |
| 332 | writeJSON(w, http.StatusOK, map[string]any{"event": res.EventID, "redo": res.Redo, "message": msg, "cells": cells}) |
| 333 | } |
| 334 | |
| 335 | // leftMark tells the scriptless notice that an Undo left some fields: |
| 336 | // "-left" after the event id, never their names in a URL. |
| 337 | func leftMark(res UndoResult) string { |
| 338 | if len(res.Left) > 0 { |
| 339 | return "-left" |
| 340 | } |
| 341 | return "" |
| 342 | } |
| 343 | |
| 344 | // undoLine says what an Undo did, naming each field it left (§5.3). |
| 345 | func undoLine(card CardView, res UndoResult) string { |
| 346 | var parts []string |
| 347 | switch { |
| 348 | case len(res.Applied) == 0: |
| 349 | parts = append(parts, "Nothing to undo.") |
| 350 | case res.Redo: |
| 351 | parts = append(parts, "Redone.") |
| 352 | default: |
| 353 | parts = append(parts, "Undone.") |
| 354 | } |
| 355 | for _, l := range res.Left { |
| 356 | label := card.Field(l.Field).Label |
| 357 | inner := label // mid-sentence, so a missing label is lower case |
| 358 | if label == "" { |
| 359 | label, inner = "A field", "a field" |
| 360 | } |
| 361 | switch { |
| 362 | case l.Gone: |
| 363 | parts = append(parts, "The old value for "+inner+" is no longer available, so it was left unchanged.") |
| 364 | case l.By != "": |
| 365 | parts = append(parts, label+" was changed again by "+personName(l.By)+", so it was left as it is.") |
| 366 | default: |
| 367 | parts = append(parts, label+" was changed again, so it was left as it is.") |
| 368 | } |
| 369 | } |
| 370 | return strings.Join(parts, " ") |
| 371 | } |
| 372 | |