9 Commits
Author SHA1 Message Date
Esa Kataja 1ce2d2b9f5 Decode Datastar signals without the SDK
The SDK was used for exactly one call, ReadSignals, which is a JSON decode of
a query parameter. It brought four modules with it, including an HTTP
compression stack, for an SSE generator this app never touches: the search
handlers answer with plain text/html and let Datastar match the fragment by
id.

Five lines replace it. Absent or empty is deliberately not an error — the
first request carries no signals, and rejecting it would 400 the initial
load. Tests cover absent, empty, malformed, and extra signals present.

Nothing changes on the client: Datastar still sends the same
?datastar={"haku":"..."}, and the smoke checks that assert that wire format
are what make the swap safe.
2026-09-05 22:00:40 +03:00
Esa Kataja 0f2cd9f0a9 Page the history and search both lists as you type
Two changes that keep the lists usable after years of entries, and the first
real use of the Datastar client that has been shipping unused.

Paging: history() now walks back from any given day and returns the rows plus
whether older ones exist. The page shows a 30-day window and "Näytä lisää"
grows it by another 30 through ?paivat=, capped at five years so a
hand-edited URL cannot ask for a decade of rows at once. Two tests check that
consecutive windows meet exactly, repeating no day and skipping none, which
is the mistake this shape invites.

Live search: both search boxes bind to a Datastar signal and re-render their
list 250 ms after typing stops. The board search and the catalog search each
return only their own fragment, and the catalog search covers sides as well
as mains.

Three things worth knowing about the Datastar side. Its attribute syntax is
colon-separated in v1.0.3 — data-on:input, not data-on-input; the dashed form
parses as a plugin named "on-input", matches nothing, and fails silently. A
plain text/html response is accepted and matched to the element by id, so
there is no SSE stream to manage and the SDK is used only for ReadSignals.
And both boxes are still ordinary GET forms, so ?haku= filters server-side
with JavaScript off: the live version is an enhancement, not a requirement.

Smoke checks send the real ?datastar={"haku":"..."} wire format and assert
the response is a fragment rather than a whole page.
2026-09-05 21:57:15 +03:00
Esa Kataja aa6541addd Replace the category dots with icons
A coloured dot means nothing until the legend has been learned, which is the
same objection that got the checkboxes made visible. The marks now carry
colour and shape together: a steak, a drumstick, a fish, a leaf, and a
quartered circle for the dishes covering several categories at once.

The steak's bone is a real hole rather than a shape painted in the background
colour, and the leaf lost the midrib it had in the mockup for the same
reason: these sit on cards in the board and on the page background in the
history list, so anything relying on knowing the backdrop breaks in one of
them.

One component, three sizes driven from CSS: 16px normally, 19 in the large
pills, 22 on the logged card. It covers the board, the sides step, the logged
card, the history rows, the catalog rows and the category checkboxes, so no
dot markup or CSS is left.
2026-09-05 21:46:14 +03:00
Esa Kataja 3564d74c39 Give the header a surface
The brand row and theme toggle sit on their own background with a hairline
under it, so the header reads as an object rather than text floating on the
page. The page title and day switcher stay on the page background: they are
content, not chrome.

The colour is its own --header variable rather than a reuse of --card, so the
header can be recoloured without dragging every card along when the palette
gets overhauled. The theme-color meta tags match it, so on a phone the browser
chrome continues the header instead of butting a different shade against it;
those need literal hex, so each file points at the other.
2026-09-05 21:37:03 +03:00
Esa Kataja b67c4edd5a Ask before deleting, and put the row actions on icons
Muokkaa and Poista become a pencil and a bin, which stops the catalog rows
being two words wide. Both carry a Finnish aria-label and title, so nothing
is lost by dropping the text.

An icon is easier to hit by accident than a word, so neither delete happens
immediately now. A tapped bin turns that row's actions into "Poista? Kyllä /
Peruuta", and a logged meal asks "Poistetaanko merkintä?" before it goes.
The meal is the more destructive of the two: a dish is only soft-deleted and
its name still resolves in old entries, while the log row is dropped outright.

Both confirmations are plain links and forms, so they work with the back
button and need no client code.

Also fixes a test that was passing for the wrong reason. The delete check only
asserted a 303 and took the first dish id on the page, which stopped being the
one it had just created when the catalog became grouped and alphabetical — so
it was deleting an unrelated dish. It now finds that dish's own id, and a new
refute helper asserts the dish is actually gone afterwards.
2026-09-05 21:34:18 +03:00
Esa Kataja e64c4aa212 Refuse to log meals in the future
The log is a record of what was eaten, so there is nothing to write down for
a dinner that has not happened, and a stray entry dated next year would sit
at the top of the history forever. A future date is now clamped to today.

The clamp lives in the one function every read and write already goes
through, so ?pvm=, the date picker, saving and deleting are all covered. The
picker also gets max=today, which avoids offering the dead end at all.

Fixes a latent bug found alongside it: today() returned the current instant
with its time of day, while dates parsed from ?pvm= are midnight, so the two
never compared equal. After saving today's dinner the redirect landed on
/?pvm=... and the card then read "la 5.9. kirjattu" instead of "Tänään
kirjattu", and "Tänään" stopped highlighting whenever the date was spelled
out. today() now truncates to midnight in the configured location.
2026-09-05 21:31:23 +03:00
Esa Kataja 4ce189d1e4 Merge the log and history into one page, group dishes by category
Kirjaa and Historia were two views of the same thing: every history row was
already a link back into the logger, and the logger had a day switcher. They
are now one page — the day being logged on top, history underneath, each row
loading its day into the logger above. Two tabs instead of three.

That also closed a gap. On an already-logged day there was no way to swap to
a different dish; "Muokkaa" only reopened the sides for the same one. It now
opens the board, so changing a dish and choosing one for the first time are
the same path.

Dishes are grouped by category on both screens, with Sekalaiset collecting
the ones covering more than one. That group is derived from the stored set
rather than being a fifth category, so a single Tortillat still satisfies
meat, chicken, fish and vegetarian at once when the §8.1 suggester arrives.

The two screens sort differently on purpose. The log board keeps frequency
then name inside each group, so favourites surface without wandering between
categories as counts change. The catalog sorts by name, because there you are
hunting a specific dish to edit rather than picking one to eat. groupDishes
preserves the order it is handed; the caller decides which it wants.

Ruoat is renamed Ruuat throughout, label and route both.
2026-09-05 21:28:14 +03:00
Esa Kataja 705ad5af26 Cut releases from main only, enforced where it can be
main is protected on the remote and takes no direct pushes, so a release
arrives as a pull request from dev. Document that flow.

`make image` refuses to run outside main. That check has to live locally:
the tag and the image are made before anything reaches the remote, so branch
protection cannot catch a release built from the wrong branch.

A pre-commit hook was tried and dropped. It needed installing per clone, so
it enforced nothing that the remote was not already enforcing, while implying
it did.
2026-09-05 20:52:16 +03:00
Esa Kataja 813e82ef5c Say which path and user cannot open the database
sql.Open is lazy, so a permission problem surfaced from whichever query ran
first: "create schema_migrations: unable to open database file (14)", which
names neither the file nor the reason. Ping on open and report the path and
the effective uid and gid instead.

The cause in practice is a bind-mounted ./data that Docker created as root
while the container runs as FOODSTER_UID. Documented in the README.
2026-09-05 20:23:44 +03:00
20 changed files with 357 additions and 1334 deletions
+7 -14
View File
@@ -1,29 +1,22 @@
# Copy to .env and fill in. .env is gitignored — the real registry hostname # Copy to .env and fill in. .env is gitignored — the real registry hostname
# must not end up in the repository. # must not end up in the repository.
# Image coordinates. REPO carries no tag. # Image coordinates. FOODSTER_REPO carries no tag.
REPO=registry.example.com/you/foodster FOODSTER_REPO=registry.example.com/you/foodster
TAG=latest FOODSTER_TAG=latest
# Shared household password. The app will not start without it. # Shared household password. The app will not start without it.
PASSWORD=changeme FOODSTER_PASSWORD=changeme
# Hostname Traefik routes to. Kept here rather than in compose.yaml so no # Hostname Traefik routes to. Kept here rather than in compose.yaml so no
# infrastructure detail is committed. # infrastructure detail is committed.
HOST=foodster.example.com FOODSTER_HOST=foodster.example.com
# Anything other than prod is written into the browser tab title, so a dev
# instance open beside the real one can be told apart.
ENV=prod
# The database lives in ./data, bind-mounted into the container. These must # The database lives in ./data, bind-mounted into the container. These must
# match whoever owns that directory on the host, or the container cannot # match whoever owns that directory on the host, or the container cannot
# write to it. `id -u` and `id -g` will tell you. # write to it. `id -u` and `id -g` will tell you.
# FOODSTER_UID=1000
# Named PUID/PGID because UID is read-only in bash and a plain UID here would FOODSTER_GID=1000
# be quietly replaced by the invoking shell's own.
PUID=1000
PGID=1000
# Used for every calendar-day calculation. Set it in development too: under # Used for every calendar-day calculation. Set it in development too: under
# UTC the date rolls over three hours late, which is exactly when dinner # UTC the date rolls over three hours late, which is exactly when dinner
-22
View File
@@ -1,22 +0,0 @@
name: check
on:
push:
branches: [dev]
# ponytail: only because Traefik still serves its default self-signed cert for
# git.kessinen.com. Remove once the LE-DNS01-cloudflare runbook has been run.
env:
GIT_SSL_NO_VERIFY: "true"
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache: true
- run: make check
-58
View File
@@ -1,58 +0,0 @@
name: release
on:
push:
branches: [main]
# ponytail: only because Traefik still serves its default self-signed cert for
# git.kessinen.com. Remove once the LE-DNS01-cloudflare runbook has been run.
env:
GIT_SSL_NO_VERIFY: "true"
REGISTRY: git.kessinen.com
IMAGE: git.kessinen.com/kessinen/foodster
jobs:
image:
runs-on: ubuntu-latest
steps:
# Full history and tags: the release number is derived by counting the
# tags already cut today.
- uses: actions/checkout@v4
with:
fetch-depth: 0
# The job container is node:22-bookworm and has no docker client. The
# static binary is one file; installing docker.io would pull a daemon
# that is never used, since the build runs against the host's.
- name: Install the docker client
run: |
curl -fsSL https://download.docker.com/linux/static/stable/x86_64/docker-27.3.1.tgz \
| tar xz --strip-components=1 -C /usr/local/bin docker/docker
docker version --format '{{.Client.Version}}'
- name: Work out the release tag
id: rel
run: |
day=$(date +%Y%m%d)
tag="v$day-$(( $(git tag -l "v$day-*" | wc -l) + 1 ))"
echo "tag=$tag" >> "$GITHUB_OUTPUT"
echo "==> $tag"
- name: Tag the commit
run: |
git tag "${{ steps.rel.outputs.tag }}"
git push origin "${{ steps.rel.outputs.tag }}"
- name: Log in to the registry
run: |
echo "${{ secrets.GITEA_TOKEN }}" \
| docker login "$REGISTRY" -u "${{ gitea.actor }}" --password-stdin
- name: Build and push
run: |
tag="${{ steps.rel.outputs.tag }}"
docker build --platform linux/amd64 --build-arg VERSION="$tag" \
-f Containerfile \
-t "$IMAGE:$tag" -t "$IMAGE:latest" .
docker push "$IMAGE:$tag"
docker push "$IMAGE:latest"
echo "pushed $IMAGE:$tag and :latest - pull it in dockge when ready"
-104
View File
@@ -1,104 +0,0 @@
# Contributing
A household project, so this is less a set of rules than a note to whoever
picks it up next — including me in six months.
## Getting set up
```sh
cp .env.example .env # then edit it
make run # http://localhost:8080, tab titled "dev · Foodster"
make # every target, with a one-line description
```
`make check` is the gate: `go vet`, gofmt, unit tests, and `scripts/smoke.sh`,
which drives a real server over HTTP. Run it before every commit.
## Branches
`dev` is where work happens. `main` holds released versions only — it is
protected on the remote and takes no direct pushes, so a release arrives as a
pull request from `dev`, squash-merged.
After a squash merge, reset `dev` onto it or the next pull request will offer
the same commits again:
```sh
git switch main && git pull --ff-only
git switch dev && git reset --hard main
git push --force-with-lease origin dev
```
The release workflow only triggers on `main`, and `main` only moves through a
pull request, so a release can never be built from the wrong branch. Nothing
needs to check for it.
## Commit messages
Conventional Commits — a type, an optional scope, then a short subject in the
imperative.
```
feat(kirjaa): expand the selected day in place
fix: redirect the catalog to /ruuat, not /ruoat
chore(deps): bump the vendored Datastar client
```
| Type | For |
|---|---|
| `feat` | new behaviour someone will notice |
| `fix` | a bug, ideally naming what broke |
| `refactor` | same behaviour, different shape |
| `test` | tests only |
| `docs` | documentation only |
| `build` | Makefile, Containerfile, compose, CI |
| `chore` | anything else: dependencies, seeds, tidying |
**The body matters more than the type.** Explain *why*, and what the
alternative was — the diff already says what changed. If a fix was subtle,
say what made it subtle; if a test caught something, say what. Commits here
are the only design record this project has.
### Release pull requests
Because `main` is squash-merged, a pull request title becomes a commit message
on `main`. A release spans a fix, a feature and some chores at once, so none
of the types above fits it honestly. Use `release:` instead:
```
release: repair the catalog 404 and stop the page jumping
```
`main`'s log is then one line per deployment, which is what that branch is
for, and the pull request body serves as the release notes. No version in the
title — CI creates the CalVer tag after the merge, so it is not known yet.
The types above are for `dev`, where a commit really does do one thing.
## Deploying
The server keeps its own `compose.yaml` and `.env`. Neither is pulled from
here, so a release that renames a variable, adds one, or changes a mount
needs both copied across **in the same deploy** — otherwise the container
comes up against the old names and the app refuses to start.
Anything in this repository that reaches the server by hand belongs in the
release notes, flagged as breaking.
## Things that are easy to get wrong
- **The interface is Finnish.** Code, comments, this file and the PRD are
English. There is no i18n layer and no language switcher.
- **No infrastructure detail is committed** — no hostnames, registry paths or
ports. They live in `.env`, which is gitignored, because the PRD leaves the
door open to publishing this repository.
- **Migrations are immutable once shipped.** A released migration has run on a
live database and will not run again. Add a new numbered file instead.
- **Interactions patch, they do not navigate.** Anything that reloads the page
loses the scroll position, which on a long list is maddening. Links stay
links and forms stay forms so it works without JavaScript; Datastar layers
over them with `data-on:click__prevent` and `data-on:submit__prevent`.
- **A `ponytail:` comment marks a deliberate shortcut** and names its ceiling,
so the next reader can tell a decision from an oversight.
- **Assert what a response does, not just that it responded.** A redirect to a
dead URL is still a 303; that one shipped.
+52 -3
View File
@@ -3,8 +3,13 @@
COMPOSE ?= podman compose COMPOSE ?= podman compose
BIN := foodster BIN := foodster
PKG := ./cmd/foodster PKG := ./cmd/foodster
STATIC := cmd/foodster/static
# Shared password and TZ live here. Gitignored. # Vendored Datastar client. Bump, run `make vendor`, commit the result.
DATASTAR_VERSION ?= v1.0.3
SEED ?= seeds/testi.json
# Registry coordinates, shared password and TZ live here. Gitignored.
ifneq (,$(wildcard .env)) ifneq (,$(wildcard .env))
include .env include .env
export export
@@ -14,7 +19,7 @@ endif
GOFILES = $(shell find . -name '*.go' -not -name '*_templ.go' 2>/dev/null) GOFILES = $(shell find . -name '*.go' -not -name '*_templ.go' 2>/dev/null)
.DEFAULT_GOAL := help .DEFAULT_GOAL := help
.PHONY: help generate build run test smoke check lint fix up down logs clean .PHONY: help generate build run seed test smoke check lint fix icons vendor image push release up down logs clean
help: ## Show this help help: ## Show this help
@grep -hE '^[a-zA-Z_-]+:.*## ' $(MAKEFILE_LIST) \ @grep -hE '^[a-zA-Z_-]+:.*## ' $(MAKEFILE_LIST) \
@@ -28,7 +33,10 @@ build: generate ## Build ./foodster
-ldflags="-s -w -X main.version=dev" -o $(BIN) $(PKG) -ldflags="-s -w -X main.version=dev" -o $(BIN) $(PKG)
run: generate ## Run locally on :8080 (database in ./data) run: generate ## Run locally on :8080 (database in ./data)
PASSWORD=$${PASSWORD:-dev} ENV=dev go run $(PKG) FOODSTER_PASSWORD=$${FOODSTER_PASSWORD:-dev} go run $(PKG)
seed: ## Import a dish bundle (SEED=seeds/testi.json)
go run $(PKG) -import $(SEED)
test: generate ## Run unit tests test: generate ## Run unit tests
go test ./... go test ./...
@@ -44,6 +52,21 @@ check: ## Everything that must pass before a commit
@$(MAKE) --no-print-directory smoke @$(MAKE) --no-print-directory smoke
@echo "check: all passed" @echo "check: all passed"
icons: ## Rasterise home-screen PNGs from assets/icon.svg and optimise them
rsvg-convert -w 180 -h 180 assets/icon.svg -o $(STATIC)/apple-touch-icon.png
rsvg-convert -w 192 -h 192 assets/icon.svg -o $(STATIC)/icon-192.png
rsvg-convert -w 512 -h 512 assets/icon.svg -o $(STATIC)/icon-512.png
# oxipng -o max alone loses to optipng on the 512; --zopfli wins at every
# size. Slow, but these are three tiny files built by hand.
oxipng -o max --zopfli --quiet \
$(STATIC)/apple-touch-icon.png $(STATIC)/icon-192.png $(STATIC)/icon-512.png
@ls -l $(STATIC)/*.png
vendor: ## Re-download the Datastar client (DATASTAR_VERSION=v1.0.3)
curl -sSfL -o $(STATIC)/datastar.js \
"https://cdn.jsdelivr.net/gh/starfederation/datastar@$(DATASTAR_VERSION)/bundles/datastar.js"
@head -1 $(STATIC)/datastar.js
lint: generate ## go vet, gofmt check, golangci-lint when installed lint: generate ## go vet, gofmt check, golangci-lint when installed
go vet ./... go vet ./...
@bad=$$(gofmt -l $(GOFILES) 2>/dev/null); \ @bad=$$(gofmt -l $(GOFILES) 2>/dev/null); \
@@ -56,6 +79,32 @@ fix: ## Format Go and templ sources, tidy go.mod
go tool templ fmt . go tool templ fmt .
go mod tidy go mod tidy
image: ## Build and tag an image as vYYYYMMDD-N. Creates a git tag.
@test -n "$(FOODSTER_REPO)" || { echo "set FOODSTER_REPO in .env"; exit 1; }
@# A release tag must point into main, or the tag records a commit that
@# was never released.
@branch=$$(git symbolic-ref --short HEAD); \
if [ "$$branch" != "main" ]; then \
echo "releases are cut from main, not $$branch:"; \
echo " git switch main && git merge --ff-only dev"; \
exit 1; \
fi
@day=$$(date +%Y%m%d); \
tag="v$$day-$$(( $$(git tag -l "v$$day-*" | wc -l) + 1 ))"; \
echo "==> $$tag"; \
git tag "$$tag"; \
podman build --platform linux/amd64 --build-arg VERSION="$$tag" \
-t "$(FOODSTER_REPO):$$tag" -t "$(FOODSTER_REPO):latest" .
push: ## Push the newest tag and :latest
@test -n "$(FOODSTER_REPO)" || { echo "set FOODSTER_REPO in .env"; exit 1; }
@tag=$$(git tag -l 'v*' --sort=-creatordate | head -n1); \
test -n "$$tag" || { echo "no tags yet - run make image"; exit 1; }; \
podman push "$(FOODSTER_REPO):$$tag"; \
podman push "$(FOODSTER_REPO):latest"
release: image push ## Build, tag and push in one go
up: ## Start the stack up: ## Start the stack
@mkdir -p data # or the engine creates it root-owned and the app cannot write @mkdir -p data # or the engine creates it root-owned and the app cannot write
$(COMPOSE) up -d $(COMPOSE) up -d
+21 -47
View File
@@ -113,23 +113,6 @@ in English.
Side dishes live in their own table and have no category. The pool is Side dishes live in their own table and have no category. The pool is
expected to stay small. expected to stay small.
### Tähteet — leftovers (stage 1)
A single built-in entry, flagged `special` on the main dish table. It is
**not food**: it exists so a day can be recorded as "we ate what was already
there" without inventing a meal that was never cooked.
- No category, which is why it cannot be an ordinary main: those must have
at least one.
- Created by a migration. The household does not add, edit or delete it, and
it never appears in the Ruuat catalog.
- Loggable exactly like any other entry, and shown on the log board apart
from the categories.
- **The stage 2 suggester must never propose it.** It is excluded from the
eligible pool outright, so cooldown, category coverage (§8.1) and
frequency weighting (§8.2) all skip it — despite it being among the
most-logged entries.
### Meal log entry ("what was actually eaten") (stage 1) ### Meal log entry ("what was actually eaten") (stage 1)
- `id` - `id`
- `date` — SQL `DATE`, day granularity only. There is no time-of-day field - `date` — SQL `DATE`, day granularity only. There is no time-of-day field
@@ -351,7 +334,7 @@ build and no asset bundler.
is imported because the runtime image carries no zoneinfo. All date logic is imported because the runtime image carries no zoneinfo. All date logic
uses that location explicitly and never `time.Local`. uses that location explicitly and never `time.Local`.
- **Auth**: HTTP Basic with one shared household password read from - **Auth**: HTTP Basic with one shared household password read from
`PASSWORD`; the username is ignored. Compared using `FOODSTER_PASSWORD`; the username is ignored. Compared using
`subtle.ConstantTimeCompare` over SHA-256 digests so neither the value nor `subtle.ConstantTimeCompare` over SHA-256 digests so neither the value nor
its length leaks through timing. `/healthz` is the only route outside auth. its length leaks through timing. `/healthz` is the only route outside auth.
- **Exposure**: the app is served on a public hostname behind Traefik, which - **Exposure**: the app is served on a public hostname behind Traefik, which
@@ -372,27 +355,22 @@ Explicitly *not* React.
## 10. Deployment ## 10. Deployment
Images are built by CI, pushed to a private container registry, then pulled on Images are built locally, pushed to a private container registry, then pulled
the server and run with Docker Compose. on the server and run with Docker Compose.
- **Branches**: `main` carries released versions only, so its history is the - **Branches**: `main` carries released versions only, so its history is the
deployment history and every release tag points into it. Development happens deployment history and every release tag points into it. Development happens
on `dev`, and `main` is protected on the remote: it accepts no direct on `dev`, and `main` is protected on the remote: it accepts no direct
pushes, so a release arrives as a pull request from `dev`. The release pushes, so a release arrives as a pull request from `dev`. `make image`
workflow runs only on `main`, so a release cannot be built from anywhere additionally refuses to run outside `main` — that one has to be local,
else and nothing needs to check for it. because the tag and the image are made before anything reaches the remote.
- **Versioning**: CalVer `vYYYYMMDD-N`, where `N` is the Nth build of that - **Versioning**: CalVer `vYYYYMMDD-N`, where `N` is the Nth build of that
day. The release workflow derives `N` by counting the day's existing git day. `make image` derives `N` by counting the day's existing git tags,
tags, creates the new tag, and bakes the version into the binary through creates the new tag, and bakes the version into the binary through
`-ldflags -X main.version`. `-ldflags -X main.version`. `make release` builds, tags and pushes.
- **CI**: Gitea Actions, workflows in `.gitea/workflows/`. `check.yaml` runs - **Tooling**: a `Makefile` is the single entry point — `make` on its own
`make check` on every push to `dev`; `release.yaml` builds and pushes the lists every target. Build, test, lint, format, image and compose commands
image when a pull request merges into `main`. Merging is the release — all live there rather than in loose scripts.
there is no local build step.
- **Tooling**: a `Makefile` covers development — `make` on its own lists every
target. Build, test, lint, format and compose commands live there rather
than in loose scripts. Commands run a handful of times a year are written
out in the README instead of earning a target.
- **Image**: a two-stage `Containerfile`. `golang:1.27-alpine` compiles a - **Image**: a two-stage `Containerfile`. `golang:1.27-alpine` compiles a
static binary; the runtime stage is `FROM scratch` holding only that static binary; the runtime stage is `FROM scratch` holding only that
binary, running as UID 65534. binary, running as UID 65534.
@@ -400,25 +378,21 @@ the server and run with Docker Compose.
`/data/foodster.db`, bind-mounted from `./data` on the host rather than `/data/foodster.db`, bind-mounted from `./data` on the host rather than
kept in a named volume, so the file can be listed and copied without going kept in a named volume, so the file can be listed and copied without going
through the container engine. Backup is `cp -r data`. Because the image through the container engine. Backup is `cp -r data`. Because the image
runs as UID 65534, compose sets `user:` from `PUID`/`PGID` runs as UID 65534, compose sets `user:` from `FOODSTER_UID`/`FOODSTER_GID`
to match whoever owns that directory. `restart: unless-stopped`. to match whoever owns that directory. `restart: unless-stopped`.
- **Configuration**, entirely through environment variables (see - **Configuration**, entirely through environment variables (see
`.env.example`): `.env.example`):
Names carry no application prefix: the container namespaces them already. - `FOODSTER_REPO` and `FOODSTER_TAG` — image coordinates.
- `REPO` and `TAG` — image coordinates. - `FOODSTER_PASSWORD` — the shared password. Required; the app refuses to
- `PASSWORD` — the shared password. Required; the app refuses to start start without it.
without it. - `FOODSTER_DB` — database file path, default `./data/foodster.db`. The
- `DB` — database file path, default `./data/foodster.db`. The directory is directory is created on startup if missing.
created on startup if missing. - `FOODSTER_UID` / `FOODSTER_GID` — host owner of `./data`.
- `ENV` — anything but `prod` is prefixed to the browser tab title, so a
dev instance open beside the real one can be told apart.
- `PUID` / `PGID` — host owner of `./data`. Not `UID`, which is read-only
in bash and would be replaced by the invoking shell's own value.
- `TZ` — default `Europe/Helsinki`. - `TZ` — default `Europe/Helsinki`.
- The registry hostname exists only in `.env`, which is gitignored, because - The registry hostname exists only in `.env`, which is gitignored, because
§11 leaves open the possibility of publishing this repository. §11 leaves open the possibility of publishing this repository.
- **Routing**: Traefik on an external `traefik` network, matching on - **Routing**: Traefik on an external `traefik` network, matching on
`HOST` and terminating TLS. The container publishes no ports — `FOODSTER_HOST` and terminating TLS. The container publishes no ports —
doing so would put an unencrypted copy of the app on the host, bypassing doing so would put an unencrypted copy of the app on the host, bypassing
the proxy. The hostname lives in `.env` rather than `compose.yaml`, so no the proxy. The hostname lives in `.env` rather than `compose.yaml`, so no
infrastructure detail is committed. infrastructure detail is committed.
@@ -430,7 +404,7 @@ the server and run with Docker Compose.
- Pending migrations are applied on app start. - Pending migrations are applied on app start.
- The Datastar client is vendored at `cmd/foodster/static/datastar.js` and - The Datastar client is vendored at `cmd/foodster/static/datastar.js` and
served from the app's own origin — the SDK ships no browser asset, and a served from the app's own origin — the SDK ships no browser asset, and a
CDN link would break an offline LAN. The README says how to refresh it; the pinned CDN link would break an offline LAN. `make vendor` refreshes it; the pinned
version lives in the `Makefile` and in the file's first line. version lives in the `Makefile` and in the file's first line.
- No internet exposure; the server binds to the LAN. - No internet exposure; the server binds to the LAN.
+55 -90
View File
@@ -11,35 +11,35 @@ See [PRD.md](PRD.md) for the full specification.
## Status ## Status
**Stage 1 — eating history: in use.** The meal catalog and the daily log came **Stage 1 — eating history: in development.** The meal catalog and the daily
first, because the suggester is worthless until there are a few weeks of real log come first, because the suggester is worthless until there are a few
history to weight against. weeks of real history to weight against.
Working: Working:
- **Kirjaa** — log a dinner: pick a dish, tick sides, save. Dishes are grouped - **Kirjaa** — log a dinner: pick a dish, tick sides, save. Dishes are ordered
by category, then ordered and sized by how often they are eaten, so the and sized by how often they are eaten, so the likely answer is the biggest
likely answer is the biggest target. The history sits on the same page target. The history sits on the same page underneath: every day back to the
underneath: every day back to the first entry, unlogged days shown as first entry, unlogged days shown as explicit gaps, and every row a link that
explicit gaps, and every row opening that day's logger in place. Older days loads that day into the logger above it.
arrive a window at a time.
- **Ruuat** — add, edit and delete mains and sides, or import a whole bundle - **Ruuat** — add, edit and delete mains and sides, or import a whole bundle
by paste or file upload. Grouped by category and alphabetical inside, since by paste or file upload. Grouped by category and alphabetical inside, since
this is a list you manage rather than one you pick from. Edit and delete are this is a list you manage rather than one you pick from. Deletes are soft,
row icons, and a delete asks first. Deletes are soft, so old log entries so old log entries keep showing the dish they used.
keep showing the dish they used.
- **Search as you type** on both tabs, debounced, patching just the list.
- **Category icons**, not colour dots: shape and colour together, so two marks
are told apart by more than hue.
- **Light / dark**, remembered per device, dark by default. The button shows - **Light / dark**, remembered per device, dark by default. The button shows
the theme that is on — moon while dark, sun while light — not the one a the theme that is on — moon while dark, sun while light — not the one a
click would bring. click would bring.
Nothing navigates. Every interaction patches the page through Datastar, so
the scroll position survives; links and forms still work with JavaScript off.
Still to build: Still to build:
- Live search as you type, and paging for the history and catalog lists once
years of entries make them long. Both via Datastar.
- Category icons instead of plain colour dots — colour and shape together, so
a red blob and a yellow blob are told apart by more than hue.
- Edit and delete as icons in the catalog rows, and a confirmation step before
a delete actually happens.
- A background for the header. Something subtle; the palette gets overhauled
later.
- Stage 2: the seven-meal suggester, which starts once there is history to - Stage 2: the seven-meal suggester, which starts once there is history to
weight against. weight against.
@@ -58,9 +58,6 @@ One static Go binary. No Node.js, no bundler, no separate database server.
| Auth | HTTP Basic, one shared household password | | Auth | HTTP Basic, one shared household password |
| Runtime image | `FROM scratch` | | Runtime image | `FROM scratch` |
Working on it: [CONTRIBUTING.md](CONTRIBUTING.md) — branches, commit messages,
and the conventions that are easy to miss.
## Branches ## Branches
`main` holds released versions only. Every release tag points at a commit on `main` holds released versions only. Every release tag points at a commit on
@@ -74,20 +71,20 @@ no direct pushes, so a release arrives through a pull request.
git switch dev # where the work happens git switch dev # where the work happens
# ... commits ... # ... commits ...
make check # lint, unit tests, smoke make check # lint, unit tests, smoke
git push origin dev # CI runs make check too git push origin dev
tea pr create --base main --head dev # or open it in the forge tea pr create --base main --head dev # or open it in the forge
# squash-merge the pull request — that is the whole release # merge the pull request, then:
git switch main && git pull --ff-only
make release # builds, tags vYYYYMMDD-N, pushes the image
git push origin --tags
``` ```
Merging is the release. CI builds the image, tags it `vYYYYMMDD-N` and `make image` additionally refuses to run from any branch but `main`, so a
`latest`, pushes both to the registry, and creates the matching git tag. There release tag can never point at a commit that was not released. That check
is nothing to run locally afterwards; pull the new image on the server when lives locally because it has to: tags and images are built before anything
you are ready. reaches the remote, so protection there cannot catch it.
A release tag can therefore never point at a commit that was not released:
the workflow only runs on `main`, and `main` only moves through a pull
request.
## Quick start ## Quick start
@@ -102,39 +99,15 @@ make run # http://localhost:8080
make fix gofmt, templ fmt, go mod tidy make fix gofmt, templ fmt, go mod tidy
make lint go vet, gofmt check, golangci-lint when installed make lint go vet, gofmt check, golangci-lint when installed
make test go test ./... make test go test ./...
make smoke end-to-end check against a scratch server
make check lint + test + smoke — run before every commit
make build ./foodster make build ./foodster
make seed import a dish bundle (SEED=seeds/testi.json)
make vendor re-download the Datastar client
make image build and tag vYYYYMMDD-N (creates a git tag)
make push push the newest tag and :latest
make release image + push
make up/down/logs compose make up/down/logs compose
``` ```
Images are built by CI, not here — see [Deployment](#deployment).
### Occasional commands
Rare enough not to earn a `make` target. Both write into
`cmd/foodster/static/`, and the results are committed.
Re-download the vendored Datastar client after bumping the version:
```sh
curl -sSfL -o cmd/foodster/static/datastar.js \
"https://cdn.jsdelivr.net/gh/starfederation/[email protected]/bundles/datastar.js"
```
Re-rasterise the home-screen icons after editing `assets/icon.svg`:
```sh
cd cmd/foodster/static
rsvg-convert -w 180 -h 180 ../../../assets/icon.svg -o apple-touch-icon.png
rsvg-convert -w 192 -h 192 ../../../assets/icon.svg -o icon-192.png
rsvg-convert -w 512 -h 512 ../../../assets/icon.svg -o icon-512.png
oxipng -o max --zopfli --quiet apple-touch-icon.png icon-192.png icon-512.png
```
`oxipng -o max` on its own loses to optipng on the 512; `--zopfli` wins at
every size. Slow, but these are three tiny files built by hand.
## Importing dishes ## Importing dishes
The **Ruuat** tab takes a bundle of mains and sides: paste the JSON or upload The **Ruuat** tab takes a bundle of mains and sides: paste the JSON or upload
@@ -165,7 +138,7 @@ The same importer runs from the command line when you just want to repopulate
a scratch database: a scratch database:
```sh ```sh
go run ./cmd/foodster -import seeds/testi.json make seed # or: SEED=seeds/other.json make seed
``` ```
## Icons ## Icons
@@ -176,8 +149,12 @@ cannot be transparent and must not change with the theme; they are rasterised
from `assets/icon.svg`, which is opaque and keeps the artwork inside the from `assets/icon.svg`, which is opaque and keeps the artwork inside the
central 80% so Android can mask it to any shape. central 80% so Android can mask it to any shape.
The PNGs are committed so the build needs no rasterizer. The commands to ```sh
regenerate them are under [Occasional commands](#occasional-commands). make icons # rsvg-convert, then optipng -o7
```
The PNGs are committed so the build needs no rasterizer. Re-run `make icons`
after editing `assets/icon.svg`.
## Migrations ## Migrations
@@ -196,30 +173,25 @@ Everything is environment variables. `.env` is gitignored; start from
| Variable | Default | Purpose | | Variable | Default | Purpose |
|---|---|---| |---|---|---|
| `PASSWORD` | *required* | Shared password. The app will not start without it. | | `FOODSTER_PASSWORD` | *required* | Shared password. The app will not start without it. |
| `DB` | `./data/foodster.db` | SQLite file path; the directory is created if missing. | | `FOODSTER_DB` | `./data/foodster.db` | SQLite file path; the directory is created if missing. |
| `ENV` | `prod` | Anything else is prefixed to the tab title (`dev · Foodster`). | | `FOODSTER_UID` / `FOODSTER_GID` | `1000` | Host owner of `./data`, for the bind mount. |
| `ADDR` | `:8080` | Listen address. Only useful for a second local instance. |
| `PUID` / `PGID` | `1000` | Host owner of `./data`, for the bind mount. |
| `TZ` | `Europe/Helsinki` | Used for every calendar-day calculation. | | `TZ` | `Europe/Helsinki` | Used for every calendar-day calculation. |
| `REPO` | *required to run* | Image repository, no tag. Used by `compose.yaml`. | | `FOODSTER_REPO` | *required to build* | Image repository, no tag. |
| `TAG` | `latest` | Tag to run under compose. | | `FOODSTER_TAG` | `latest` | Tag to run under compose. |
| `HOST` | *required to run* | Hostname Traefik routes to. | | `FOODSTER_PORT` | `8080` | Host port to publish. |
Names carry no prefix: the container gives them their own namespace already.
`PUID`/`PGID` are the exception — `UID` is read-only in bash, so a value set
in `.env` would be silently replaced by the invoking shell's own.
Set `TZ` in development too. Under UTC the date rolls over three hours late, Set `TZ` in development too. Under UTC the date rolls over three hours late,
which is exactly when dinner gets logged. which is exactly when dinner gets logged.
## Deployment ## Deployment
Images are built by CI when a pull request merges into `main`, and run under Images are built with Podman and run under Docker Compose on a LAN server.
Docker Compose on a LAN server. They are OCI images, so either engine works. They are OCI images, so either engine works.
```sh ```sh
# on the server, once CI reports the build finished: make release # build, tag, push
# on the server:
docker compose pull && docker compose up -d docker compose pull && docker compose up -d
``` ```
@@ -228,18 +200,11 @@ running version is served at `GET /healthz`, which is the one route outside
authentication. authentication.
There is no database container. SQLite lives in `./data`, bind-mounted into There is no database container. SQLite lives in `./data`, bind-mounted into
the container, so you can inspect the file with any sqlite client without the container, so a backup is `cp -r data` and you can inspect the file with
going through the engine. Back it up with any sqlite client without going through the engine.
```sh
sqlite3 data/foodster.db ".backup data/foodster-$(date +%F).db"
```
rather than copying the directory: the database runs in WAL mode, and a plain
copy of a live database can catch the `.db` and its `-wal` mid-write.
That directory must exist and be owned by the user compose runs as — `make up` That directory must exist and be owned by the user compose runs as — `make up`
creates it, and `PUID`/`PGID` in `.env` tell the container who creates it, and `FOODSTER_UID`/`FOODSTER_GID` in `.env` tell the container who
that is. Get them from `id -u` and `id -g`. that is. Get them from `id -u` and `id -g`.
If the app exits with `cannot open /data/foodster.db ... unable to open If the app exits with `cannot open /data/foodster.db ... unable to open
@@ -248,7 +213,7 @@ bind-mount directory as root, and the container is not root:
```sh ```sh
ls -ldn data # whose is it? ls -ldn data # whose is it?
sudo chown -R 1000:1000 data # match PUID / PGID sudo chown -R 1000:1000 data # match FOODSTER_UID / FOODSTER_GID
docker compose restart docker compose restart
``` ```
@@ -270,7 +235,7 @@ counting it would lock the household out for simply opening the app.
address, meaning it arrived through the proxy. A client connecting directly address, meaning it arrived through the proxy. A client connecting directly
could otherwise forge a new address per attempt and skip the limiter. could otherwise forge a new address per attempt and skip the limiter.
**None of this replaces a strong `PASSWORD`.** Rate limiting removes **None of this replaces a strong `FOODSTER_PASSWORD`.** Rate limiting removes
brute force as a practical route; it does not make a guessable password safe. brute force as a practical route; it does not make a guessable password safe.
## Mockups ## Mockups
+1 -1
View File
@@ -1,6 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512" <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512"
role="img" aria-label="Foodster"> role="img" aria-label="Foodster">
<!-- Source for the home-screen PNGs; the README says how to rasterise it. <!-- Source for the home-screen PNGs; `make icons` rasterises it.
Unlike favicon.svg this one is opaque and fixed-colour: a home screen Unlike favicon.svg this one is opaque and fixed-colour: a home screen
icon cannot be transparent and must not change with the system theme. icon cannot be transparent and must not change with the system theme.
The bowl sits inside the central 80% so Android can mask it to any The bowl sits inside the central 80% so Android can mask it to any

Before

Width:  |  Height:  |  Size: 927 B

After

Width:  |  Height:  |  Size: 918 B

-49
View File
@@ -131,55 +131,6 @@ func TestSoftDeleteHidesDishButKeepsHistory(t *testing.T) {
} }
} }
func TestTahteetIsLoggableButNotFood(t *testing.T) {
h := seeded(t)
// The migration creates it; nobody adds it.
special, err := listSpecial(h.db, "")
if err != nil {
t.Fatalf("listSpecial: %v", err)
}
if len(special) != 1 || special[0].Name != "Tähteet" {
t.Fatalf("special = %+v, want exactly Tähteet", special)
}
// It must not turn up among the dishes: not on the board's categories,
// not in the catalog, and not in whatever the suggester later draws from.
dishes, err := listDishes(h.db, "")
if err != nil {
t.Fatalf("listDishes: %v", err)
}
for _, d := range dishes {
if d.Name == "Tähteet" {
t.Fatal("Tähteet appears among the dishes")
}
}
// It carries no category at all, which is why it cannot be an ordinary
// dish: those are required to have one.
if len(special[0].Categories) != 0 {
t.Errorf("categories = %v, want none", special[0].Categories)
}
// And it gets its own mark: no categories is not the same as several, so
// it must not fall through to the mixed Sekalaiset one.
if got := special[0].CategoryKey(); got != "tahteet" {
t.Errorf("CategoryKey = %q, want tahteet", got)
}
// Logging it has to work exactly like logging a real meal.
date := day(t, "2026-09-05")
if err := saveEntry(h.db, date, special[0].ID, nil); err != nil {
t.Fatalf("saveEntry: %v", err)
}
entry, err := entryFor(h.db, date)
if err != nil || entry == nil {
t.Fatalf("entryFor: %v, %v", entry, err)
}
if entry.Main.Name != "Tähteet" {
t.Errorf("logged %q, want Tähteet", entry.Main.Name)
}
}
func TestSoftDeleteSideHidesItFromPickers(t *testing.T) { func TestSoftDeleteSideHidesItFromPickers(t *testing.T) {
h := seeded(t) h := seeded(t)
id := h.sideNamed(t, "Riisi") id := h.sideNamed(t, "Riisi")
+45 -194
View File
@@ -60,19 +60,12 @@ func render(w http.ResponseWriter, r *http.Request, c templ.Component) {
// there is nothing to write down for a dinner that has not happened, and a // there is nothing to write down for a dinner that has not happened, and a
// stray entry dated next year would sit at the top of the history forever. // stray entry dated next year would sit at the top of the history forever.
// Every read and write goes through here, so the clamp covers them all. // Every read and write goes through here, so the clamp covers them all.
//
// The past is clamped too, at maxHistoryDays. The day list runs unbroken from
// today down to the selected day, so a picker set to 1994 would ask for eleven
// thousand rows. Same ceiling ?paivat= already has.
func (a *app) date(r *http.Request) time.Time { func (a *app) date(r *http.Request) time.Time {
now := today(a.loc) now := today(a.loc)
if raw := r.FormValue("pvm"); raw != "" { if raw := r.FormValue("pvm"); raw != "" {
if d, err := time.ParseInLocation(dateLayout, raw, a.loc); err == nil { if d, err := time.ParseInLocation(dateLayout, raw, a.loc); err == nil {
switch floor := now.AddDate(0, 0, -maxHistoryDays+1); { if d.After(now) {
case d.After(now):
return now return now
case d.Before(floor):
return floor
} }
return d return d
} }
@@ -93,7 +86,6 @@ type logView struct {
ShowBoard bool ShowBoard bool
Dishes []Dish // flat, only to know whether anything matched Dishes []Dish // flat, only to know whether anything matched
Groups []DishGroup // what the board actually renders Groups []DishGroup // what the board actually renders
Special []Dish // Tähteet and the like: loggable, but not food
Sides []Side Sides []Side
New mainForm // inline "add the dish you were looking for" New mainForm // inline "add the dish you were looking for"
History HistoryPage History HistoryPage
@@ -105,57 +97,17 @@ type logView struct {
Confirming bool Confirming bool
} }
// logOptions is what the Kirjaa screen is being asked to show. Pulled out of
// the request for a page load or a patch, and set directly after a write,
// where the answer is simply "that day, nothing else open".
type logOptions struct {
Date time.Time
Dish string // ?ruoka=, opening the sides step
Changing bool // ?muuta=, swapping the dish on a logged day
Confirming bool // ?poista=, asking before deleting the entry
Search string
}
func (a *app) logOptionsFrom(r *http.Request) logOptions {
q := r.URL.Query()
return logOptions{
Date: a.date(r),
Dish: q.Get("ruoka"),
Changing: q.Get("muuta") != "",
Confirming: q.Get("poista") != "",
Search: strings.TrimSpace(q.Get("haku")),
}
}
func (a *app) index(w http.ResponseWriter, r *http.Request) { func (a *app) index(w http.ResponseWriter, r *http.Request) {
render(w, r, logPage(a.buildLog(r, a.logOptionsFrom(r)))) date := a.date(r)
}
// day patches the list in place. Every link in it calls here rather than
// loading a page, so opening a day leaves the scroll position alone.
func (a *app) day(w http.ResponseWriter, r *http.Request) {
fragment(w, r, dayList(a.buildLog(r, a.logOptionsFrom(r))))
}
// finishDay answers a write: a patch for Datastar, a redirect otherwise.
func (a *app) finishDay(w http.ResponseWriter, r *http.Request, date time.Time) {
if isDatastar(r) {
fragment(w, r, dayList(a.buildLog(r, logOptions{Date: date})))
return
}
a.redirectToDay(w, r, date)
}
func (a *app) buildLog(r *http.Request, o logOptions) logView {
date := o.Date
v := logView{ v := logView{
Date: date, Date: date,
Today: today(a.loc), Today: today(a.loc),
Search: o.Search, Search: strings.TrimSpace(r.URL.Query().Get("haku")),
Checked: map[int64]bool{}, Checked: map[int64]bool{},
Confirming: o.Confirming,
} }
v.Confirming = r.URL.Query().Get("poista") != ""
entry, err := entryFor(a.db, date) entry, err := entryFor(a.db, date)
if err != nil { if err != nil {
log.Printf("entry for %s: %v", date.Format(dateLayout), err) log.Printf("entry for %s: %v", date.Format(dateLayout), err)
@@ -165,8 +117,8 @@ func (a *app) buildLog(r *http.Request, o logOptions) logView {
// ?ruoka= opens the sides step for that dish. When it is the dish already // ?ruoka= opens the sides step for that dish. When it is the dish already
// logged, the existing sides come back ticked, which makes editing an // logged, the existing sides come back ticked, which makes editing an
// entry the same screen as creating one. // entry the same screen as creating one.
if o.Dish != "" { if raw := r.URL.Query().Get("ruoka"); raw != "" {
if id, err := strconv.ParseInt(o.Dish, 10, 64); err == nil { if id, err := strconv.ParseInt(raw, 10, 64); err == nil {
if dish, err := dishByID(a.db, id); err == nil { if dish, err := dishByID(a.db, id); err == nil {
v.Chosen = dish v.Chosen = dish
if entry != nil && entry.Main.ID == id { if entry != nil && entry.Main.ID == id {
@@ -181,7 +133,7 @@ func (a *app) buildLog(r *http.Request, o logOptions) logView {
// The board shows when there is nothing logged yet, or when the entry is // The board shows when there is nothing logged yet, or when the entry is
// being changed. "Muokkaa" on a logged day sets ?muuta=1 and lands here, // being changed. "Muokkaa" on a logged day sets ?muuta=1 and lands here,
// so swapping the dish and picking one for the first time are one path. // so swapping the dish and picking one for the first time are one path.
changing := o.Changing || v.Search != "" changing := r.URL.Query().Get("muuta") != "" || v.Search != ""
if v.Chosen == nil && (v.Entry == nil || changing) { if v.Chosen == nil && (v.Entry == nil || changing) {
v.ShowBoard = true v.ShowBoard = true
if v.Dishes, err = listDishes(a.db, v.Search); err != nil { if v.Dishes, err = listDishes(a.db, v.Search); err != nil {
@@ -190,9 +142,6 @@ func (a *app) buildLog(r *http.Request, o logOptions) logView {
// listDishes already orders by frequency then name, so grouping keeps // listDishes already orders by frequency then name, so grouping keeps
// the favourites at the top of each category. // the favourites at the top of each category.
v.Groups = groupDishes(v.Dishes) v.Groups = groupDishes(v.Dishes)
if v.Special, err = listSpecial(a.db, v.Search); err != nil {
log.Printf("list special: %v", err)
}
// Seed the inline add form with whatever was searched for, so a miss // Seed the inline add form with whatever was searched for, so a miss
// turns straight into "add it" without retyping. // turns straight into "add it" without retyping.
v.New = mainForm{Name: v.Search, Categories: map[string]bool{}, HasSides: true} v.New = mainForm{Name: v.Search, Categories: map[string]bool{}, HasSides: true}
@@ -203,31 +152,13 @@ func (a *app) buildLog(r *http.Request, o logOptions) logView {
} }
} }
a.loadDays(r, &v)
return v
}
// loadDays fills the day list. The selected day expands inside it rather than
// in a panel above it, so choosing a day from the list does not reorder the
// list underneath the tap.
func (a *app) loadDays(r *http.Request, v *logView) {
v.HistoryDays = historyWindow(r) v.HistoryDays = historyWindow(r)
v.HistoryMore = v.HistoryDays + historyDays v.HistoryMore = v.HistoryDays + historyDays
if v.History, err = history(a.db, a.loc, today(a.loc), v.HistoryDays); err != nil {
// The window has to reach the selected day, or it would have nowhere to
// expand. history() takes it as a floor rather than the caller inflating
// the day count, because the window also truncates at the first entry ever
// logged — and a day older than that still has to be loggable.
page, err := history(a.db, a.loc, v.Today, v.HistoryDays, v.Date)
if err != nil {
log.Printf("history: %v", err) log.Printf("history: %v", err)
} }
// Nothing logged ever: the selected day is still the one being worked on,
// so it needs a row of its own to open in. render(w, r, logPage(v))
if len(page.Rows) == 0 {
page.Rows = []HistoryRow{{Date: v.Date, Entry: v.Entry}}
}
v.History = page
} }
// searchSignals is what Datastar sends back: for a GET it JSON-encodes the // searchSignals is what Datastar sends back: for a GET it JSON-encodes the
@@ -260,50 +191,6 @@ func fragment(w http.ResponseWriter, r *http.Request, c templ.Component) {
} }
} }
// isDatastar reports whether the request came from the client library, which
// tags its own. Everything below keeps working without JavaScript: the same
// handlers redirect instead of patching when the header is absent.
func isDatastar(r *http.Request) bool {
return r.Header.Get("Datastar-Request") != ""
}
// patchElements sends one Datastar event carrying several elements, each
// matched to the page by its id. A text/html response can only replace one
// element, and the catalog has to move its list and its forms together —
// opening an edit form also has to un-highlight whatever was open before.
//
// ponytail: about twenty lines instead of the SDK, which brought four modules
// for an SSE generator we would otherwise never call.
func patchElements(w http.ResponseWriter, r *http.Request, components ...templ.Component) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
var out strings.Builder
out.WriteString("event: datastar-patch-elements\n")
for _, c := range components {
var html strings.Builder
if err := c.Render(r.Context(), &html); err != nil {
log.Printf("patch %s: %v", r.URL.Path, err)
return
}
// One `data: elements` line per line of HTML, as the protocol wants.
for _, line := range strings.Split(html.String(), "\n") {
if strings.TrimSpace(line) == "" {
continue
}
out.WriteString("data: elements ")
out.WriteString(line)
out.WriteString("\n")
}
}
out.WriteString("\n")
io.WriteString(w, out.String())
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
// searchBoard re-renders the dish board as the search box is typed into. // searchBoard re-renders the dish board as the search box is typed into.
func (a *app) searchBoard(w http.ResponseWriter, r *http.Request) { func (a *app) searchBoard(w http.ResponseWriter, r *http.Request) {
var signals searchSignals var signals searchSignals
@@ -323,9 +210,6 @@ func (a *app) searchBoard(w http.ResponseWriter, r *http.Request) {
} }
v.Dishes = dishes v.Dishes = dishes
v.Groups = groupDishes(dishes) v.Groups = groupDishes(dishes)
if v.Special, err = listSpecial(a.db, v.Search); err != nil {
log.Printf("search special: %v", err)
}
v.New = mainForm{Name: v.Search, Categories: map[string]bool{}, HasSides: true} v.New = mainForm{Name: v.Search, Categories: map[string]bool{}, HasSides: true}
fragment(w, r, boardList(v)) fragment(w, r, boardList(v))
@@ -389,12 +273,6 @@ func (a *app) quickAdd(w http.ResponseWriter, r *http.Request) {
log.Printf("quick add: %v", err) log.Printf("quick add: %v", err)
form.Err = "Tallennus epäonnistui." form.Err = "Tallennus epäonnistui."
default: default:
// Created: straight on to its sides step.
opts := logOptions{Date: date, Dish: strconv.FormatInt(id, 10)}
if isDatastar(r) {
fragment(w, r, dayList(a.buildLog(r, opts)))
return
}
a.redirectToPick(w, r, date, id) a.redirectToPick(w, r, date, id)
return return
} }
@@ -402,11 +280,23 @@ func (a *app) quickAdd(w http.ResponseWriter, r *http.Request) {
// Rejected: back to the board with the form filled in and the search // Rejected: back to the board with the form filled in and the search
// still narrowed, so the add card stays on screen. // still narrowed, so the add card stays on screen.
v := a.buildLog(r, logOptions{Date: date, Search: form.Name}) v := logView{
v.New = form Date: date,
if isDatastar(r) { Today: today(a.loc),
fragment(w, r, dayList(v)) Search: form.Name,
return Checked: map[int64]bool{},
New: form,
ShowBoard: true,
}
var err error
if v.Dishes, err = listDishes(a.db, v.Search); err != nil {
log.Printf("list dishes: %v", err)
}
v.Groups = groupDishes(v.Dishes)
v.HistoryDays = historyWindow(r)
v.HistoryMore = v.HistoryDays + historyDays
if v.History, err = history(a.db, a.loc, today(a.loc), v.HistoryDays); err != nil {
log.Printf("history: %v", err)
} }
render(w, r, logPage(v)) render(w, r, logPage(v))
} }
@@ -442,7 +332,7 @@ func (a *app) save(w http.ResponseWriter, r *http.Request) {
http.Error(w, "tallennus epäonnistui", http.StatusInternalServerError) http.Error(w, "tallennus epäonnistui", http.StatusInternalServerError)
return return
} }
a.finishDay(w, r, date) a.redirectToDay(w, r, date)
} }
func (a *app) delete(w http.ResponseWriter, r *http.Request) { func (a *app) delete(w http.ResponseWriter, r *http.Request) {
@@ -452,12 +342,15 @@ func (a *app) delete(w http.ResponseWriter, r *http.Request) {
http.Error(w, "poisto epäonnistui", http.StatusInternalServerError) http.Error(w, "poisto epäonnistui", http.StatusInternalServerError)
return return
} }
a.finishDay(w, r, date) a.redirectToDay(w, r, date)
} }
// redirectToDay is the no-JavaScript path back after a write.
func (a *app) redirectToDay(w http.ResponseWriter, r *http.Request, date time.Time) { func (a *app) redirectToDay(w http.ResponseWriter, r *http.Request, date time.Time) {
http.Redirect(w, r, dayURL("/", date, today(a.loc)), http.StatusSeeOther) target := "/"
if !date.Equal(today(a.loc)) {
target += "?pvm=" + date.Format(dateLayout)
}
http.Redirect(w, r, target, http.StatusSeeOther)
} }
// mainForm and sideForm carry what the user typed, so a rejected submission // mainForm and sideForm carry what the user typed, so a rejected submission
@@ -491,20 +384,7 @@ type catalogView struct {
DeleteKind string DeleteKind string
} }
// catalog renders the whole page. show patches the same state in place, so
// nothing navigates: both build the view the same way.
func (a *app) catalog(w http.ResponseWriter, r *http.Request) { func (a *app) catalog(w http.ResponseWriter, r *http.Request) {
a.renderCatalog(w, r, a.catalogState(r))
}
// show is what every catalog link actually calls. It patches the list and both
// forms rather than loading a page, so opening an edit form or asking to
// delete a row leaves the scroll position exactly where it was.
func (a *app) show(w http.ResponseWriter, r *http.Request) {
a.patchCatalog(w, r, a.catalogState(r))
}
func (a *app) catalogState(r *http.Request) catalogView {
v := catalogView{ v := catalogView{
Main: mainForm{Categories: map[string]bool{}, HasSides: true}, Main: mainForm{Categories: map[string]bool{}, HasSides: true},
Search: strings.TrimSpace(r.URL.Query().Get("haku")), Search: strings.TrimSpace(r.URL.Query().Get("haku")),
@@ -540,11 +420,10 @@ func (a *app) catalogState(r *http.Request) catalogView {
} }
} }
return v a.renderCatalog(w, r, v)
} }
// fillCatalog loads the lists into a view built from the request. func (a *app) renderCatalog(w http.ResponseWriter, r *http.Request, v catalogView) {
func (a *app) fillCatalog(v *catalogView) {
if v.Main.Categories == nil { if v.Main.Categories == nil {
v.Main.Categories = map[string]bool{} v.Main.Categories = map[string]bool{}
} }
@@ -560,20 +439,9 @@ func (a *app) fillCatalog(v *catalogView) {
if v.Sides, err = listSides(a.db, v.Search); err != nil { if v.Sides, err = listSides(a.db, v.Search); err != nil {
log.Printf("list sides: %v", err) log.Printf("list sides: %v", err)
} }
}
func (a *app) renderCatalog(w http.ResponseWriter, r *http.Request, v catalogView) {
a.fillCatalog(&v)
render(w, r, catalogPage(v)) render(w, r, catalogPage(v))
} }
// patchCatalog swaps the list and both forms in one event. They move together:
// opening an edit form also has to clear whatever delete was being confirmed.
func (a *app) patchCatalog(w http.ResponseWriter, r *http.Request, v catalogView) {
a.fillCatalog(&v)
patchElements(w, r, catalogList(v), mainForm_(v.Main), sideForm_(v.Side))
}
// saveMain adds or updates a main dish. A rejected form is re-rendered with // saveMain adds or updates a main dish. A rejected form is re-rendered with
// the values still in it; a good one redirects, so refresh cannot re-submit. // the values still in it; a good one redirects, so refresh cannot re-submit.
func (a *app) saveMain(w http.ResponseWriter, r *http.Request) { func (a *app) saveMain(w http.ResponseWriter, r *http.Request) {
@@ -614,28 +482,11 @@ func (a *app) saveMain(w http.ResponseWriter, r *http.Request) {
log.Printf("save main: %v", err) log.Printf("save main: %v", err)
form.Err = "Tallennus epäonnistui." form.Err = "Tallennus epäonnistui."
default: default:
// Saved: hand back a blank form so it collapses, and a list with http.Redirect(w, r, "/ruoat", http.StatusSeeOther)
// the dish in it.
a.finishCatalog(w, r, catalogView{})
return return
} }
} }
a.finishCatalog(w, r, catalogView{Main: form}) a.renderCatalog(w, r, catalogView{Main: form})
}
// finishCatalog answers a catalog write: a patch for Datastar, a redirect for
// a plain form post. Without the redirect, submitting with JavaScript off
// would leave the browser sitting on a POST it could not reload.
func (a *app) finishCatalog(w http.ResponseWriter, r *http.Request, v catalogView) {
if isDatastar(r) {
a.patchCatalog(w, r, v)
return
}
if v.Main.Err != "" || v.Side.Err != "" {
a.renderCatalog(w, r, v)
return
}
http.Redirect(w, r, "/ruuat", http.StatusSeeOther)
} }
func (a *app) saveSide(w http.ResponseWriter, r *http.Request) { func (a *app) saveSide(w http.ResponseWriter, r *http.Request) {
@@ -660,11 +511,11 @@ func (a *app) saveSide(w http.ResponseWriter, r *http.Request) {
log.Printf("save side: %v", err) log.Printf("save side: %v", err)
form.Err = "Tallennus epäonnistui." form.Err = "Tallennus epäonnistui."
default: default:
a.finishCatalog(w, r, catalogView{}) http.Redirect(w, r, "/ruoat", http.StatusSeeOther)
return return
} }
} }
a.finishCatalog(w, r, catalogView{Side: form}) a.renderCatalog(w, r, catalogView{Side: form})
} }
// deleteDish soft-deletes, so log entries keep resolving the name (PRD §6). // deleteDish soft-deletes, so log entries keep resolving the name (PRD §6).
@@ -688,7 +539,7 @@ func (a *app) deleteDish(w http.ResponseWriter, r *http.Request) {
http.Error(w, "poisto epäonnistui", http.StatusInternalServerError) http.Error(w, "poisto epäonnistui", http.StatusInternalServerError)
return return
} }
a.finishCatalog(w, r, catalogView{}) http.Redirect(w, r, "/ruoat", http.StatusSeeOther)
} }
// importDishes takes a bundle either pasted into the textarea or uploaded as a // importDishes takes a bundle either pasted into the textarea or uploaded as a
+7 -31
View File
@@ -32,24 +32,9 @@ import (
//go:embed static //go:embed static
var staticFS embed.FS var staticFS embed.FS
// version is replaced at build time with the CalVer tag by the release workflow. // version is replaced at build time with the CalVer tag (see `make image`).
var version = "dev" var version = "dev"
// envTag marks the browser tab of anything that is not production, so a dev
// instance and the real one open side by side are told apart at a glance.
// Empty in production, which is the default.
var envTag string
func setEnvTag(value string) {
value = strings.TrimSpace(value)
if value == "" || strings.EqualFold(value, "prod") || strings.EqualFold(value, "production") {
envTag = ""
return
}
// Whatever it says, so ENV=staging labels itself too.
envTag = strings.ToLower(value)
}
const ( const (
listenAddr = ":8080" listenAddr = ":8080"
defaultTZ = "Europe/Helsinki" defaultTZ = "Europe/Helsinki"
@@ -70,7 +55,7 @@ func run() error {
"import a JSON dish bundle (PRD §7.3 shape) and exit") "import a JSON dish bundle (PRD §7.3 shape) and exit")
flag.Parse() flag.Parse()
db, err := openDB(cmp.Or(os.Getenv("DB"), defaultDB)) db, err := openDB(cmp.Or(os.Getenv("FOODSTER_DB"), defaultDB))
if err != nil { if err != nil {
return err return err
} }
@@ -81,9 +66,9 @@ func run() error {
return runImport(db, *importPath) return runImport(db, *importPath)
} }
password := os.Getenv("PASSWORD") password := os.Getenv("FOODSTER_PASSWORD")
if password == "" { if password == "" {
return errors.New("PASSWORD is not set") return errors.New("FOODSTER_PASSWORD is not set")
} }
// Fail rather than fall back to UTC: a silently wrong zone shifts logged // Fail rather than fall back to UTC: a silently wrong zone shifts logged
@@ -94,21 +79,14 @@ func run() error {
return fmt.Errorf("TZ: %w", err) return fmt.Errorf("TZ: %w", err)
} }
setEnvTag(os.Getenv("ENV")) // The container always publishes :8080; FOODSTER_ADDR exists so tests and
// a second local instance can pick another port.
addr := cmp.Or(os.Getenv("FOODSTER_ADDR"), listenAddr)
// The container always publishes :8080; ADDR exists so tests and a second
// local instance can pick another port.
addr := cmp.Or(os.Getenv("ADDR"), listenAddr)
// WriteTimeout and IdleTimeout matter more than they look: the pool holds
// exactly one database connection, so a reader stalling on a long history
// response blocks every other request behind it.
srv := &http.Server{ srv := &http.Server{
Addr: addr, Addr: addr,
Handler: routes(db, loc, password), Handler: routes(db, loc, password),
ReadHeaderTimeout: 10 * time.Second, ReadHeaderTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 120 * time.Second,
} }
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
@@ -181,11 +159,9 @@ func routes(db *sql.DB, loc *time.Location, password string) http.Handler {
mux.HandleFunc("POST /kirjaa", a.save) mux.HandleFunc("POST /kirjaa", a.save)
mux.HandleFunc("POST /lisaa", a.quickAdd) mux.HandleFunc("POST /lisaa", a.quickAdd)
mux.HandleFunc("GET /etsi", a.searchBoard) mux.HandleFunc("GET /etsi", a.searchBoard)
mux.HandleFunc("GET /paiva", a.day)
mux.HandleFunc("POST /poista", a.delete) mux.HandleFunc("POST /poista", a.delete)
mux.HandleFunc("GET /ruuat", a.catalog) mux.HandleFunc("GET /ruuat", a.catalog)
mux.HandleFunc("GET /ruuat/etsi", a.searchCatalog) mux.HandleFunc("GET /ruuat/etsi", a.searchCatalog)
mux.HandleFunc("GET /ruuat/nayta", a.show)
mux.HandleFunc("POST /ruuat/paaruoka", a.saveMain) mux.HandleFunc("POST /ruuat/paaruoka", a.saveMain)
mux.HandleFunc("POST /ruuat/lisuke", a.saveSide) mux.HandleFunc("POST /ruuat/lisuke", a.saveSide)
mux.HandleFunc("POST /ruuat/poista", a.deleteDish) mux.HandleFunc("POST /ruuat/poista", a.deleteDish)
+7 -32
View File
@@ -105,29 +105,6 @@ func TestReadSignals(t *testing.T) {
} }
} }
func TestEnvTagMarksNonProduction(t *testing.T) {
t.Cleanup(func() { envTag = "" })
cases := []struct{ env, want string }{
// Production is the default and must stay unmarked: the tag exists to
// pick the dev tab out of two identical ones.
{"", "Foodster"},
{"prod", "Foodster"},
{"PRODUCTION", "Foodster"},
{" ", "Foodster"},
{"dev", "dev · Foodster"},
{"DEV", "dev · Foodster"},
{"staging", "staging · Foodster"},
}
for _, c := range cases {
setEnvTag(c.env)
if got := pageTitle("Foodster"); got != c.want {
t.Errorf("ENV=%q: title = %q, want %q", c.env, got, c.want)
}
}
}
func TestMigrateCreatesSchema(t *testing.T) { func TestMigrateCreatesSchema(t *testing.T) {
db, err := openDB(t.TempDir() + "/test.db") db, err := openDB(t.TempDir() + "/test.db")
if err != nil { if err != nil {
@@ -269,16 +246,14 @@ func TestMealLogOneEntryPerDate(t *testing.T) {
} }
defer db.Close() defer db.Close()
// Ids well clear of anything the migrations create. if _, err := db.Exec(`INSERT INTO main_dishes (id, name) VALUES (1, 'Lohikeitto'), (2, 'Lihapullat')`); err != nil {
if _, err := db.Exec(
`INSERT INTO main_dishes (id, name) VALUES (101, 'Lohikeitto'), (102, 'Lihapullat')`); err != nil {
t.Fatalf("seed: %v", err) t.Fatalf("seed: %v", err)
} }
if _, err := db.Exec(`INSERT INTO meal_log (date, main_dish_id) VALUES ('2026-09-05', 101)`); err != nil { if _, err := db.Exec(`INSERT INTO meal_log (date, main_dish_id) VALUES ('2026-09-05', 1)`); err != nil {
t.Fatalf("first entry: %v", err) t.Fatalf("first entry: %v", err)
} }
// PRD §6: a second dinner for the same day must be refused. // PRD §6: a second dinner for the same day must be refused.
if _, err := db.Exec(`INSERT INTO meal_log (date, main_dish_id) VALUES ('2026-09-05', 102)`); err == nil { if _, err := db.Exec(`INSERT INTO meal_log (date, main_dish_id) VALUES ('2026-09-05', 2)`); err == nil {
t.Error("second entry for the same date was accepted, want a unique violation") t.Error("second entry for the same date was accepted, want a unique violation")
} }
} }
@@ -290,18 +265,18 @@ func TestDuplicateNamesAreCaseInsensitive(t *testing.T) {
} }
defer db.Close() defer db.Close()
if _, err := db.Exec(`INSERT INTO main_dishes (id, name) VALUES (101, 'Kanacurry')`); err != nil { if _, err := db.Exec(`INSERT INTO main_dishes (id, name) VALUES (1, 'Kanacurry')`); err != nil {
t.Fatalf("first insert: %v", err) t.Fatalf("first insert: %v", err)
} }
if _, err := db.Exec(`INSERT INTO main_dishes (id, name) VALUES (102, 'kanacurry')`); err == nil { if _, err := db.Exec(`INSERT INTO main_dishes (id, name) VALUES (2, 'kanacurry')`); err == nil {
t.Error("case-variant duplicate was accepted, want a unique violation") t.Error("case-variant duplicate was accepted, want a unique violation")
} }
// Soft-deleting the original frees the name again (PRD §7.3). // Soft-deleting the original frees the name again (PRD §7.3).
if _, err := db.Exec(`UPDATE main_dishes SET deleted_at = datetime('now') WHERE id = 101`); err != nil { if _, err := db.Exec(`UPDATE main_dishes SET deleted_at = datetime('now') WHERE id = 1`); err != nil {
t.Fatalf("soft delete: %v", err) t.Fatalf("soft delete: %v", err)
} }
if _, err := db.Exec(`INSERT INTO main_dishes (id, name) VALUES (102, 'kanacurry')`); err != nil { if _, err := db.Exec(`INSERT INTO main_dishes (id, name) VALUES (2, 'kanacurry')`); err != nil {
t.Errorf("name still blocked after soft delete: %v", err) t.Errorf("name still blocked after soft delete: %v", err)
} }
} }
-19
View File
@@ -1,19 +0,0 @@
-- Tähteet: leftovers.
--
-- Not a dish. It exists so a day can be recorded as "we ate what was already
-- there" without inventing a meal that was never cooked. It has no category,
-- it is not something the household adds or edits, and the stage 2 suggester
-- must never propose it (PRD §8).
--
-- Modelled as a flagged row in main_dishes rather than a nullable
-- main_dish_id on meal_log: the log keeps one shape, and every foreign key
-- and join carries on working untouched.
ALTER TABLE main_dishes
ADD COLUMN special INTEGER NOT NULL DEFAULT 0 CHECK (special IN (0, 1));
-- OR IGNORE in case a household already typed a dish by this name: the unique
-- index on lower(name) would otherwise fail the migration. Their row stays as
-- an ordinary dish, which is wrong but harmless and fixable by hand.
INSERT OR IGNORE INTO main_dishes (name, has_sides, special)
VALUES ('Tähteet', 0, 1);
+4 -75
View File
@@ -134,8 +134,6 @@ html[data-theme="light"] .themetoggle .i-moon { display: none; }
.c-kana { color: var(--kana); } .c-kana { color: var(--kana); }
.c-kala { color: var(--kala); } .c-kala { color: var(--kala); }
.c-kasvis { color: var(--kasvis); } .c-kasvis { color: var(--kasvis); }
/* Not a category, so not a category colour. */
.c-tahteet { color: var(--muted); }
/* Day switcher */ /* Day switcher */
.dayseg { display: flex; gap: 6px; margin-top: 11px; flex-wrap: wrap; } .dayseg { display: flex; gap: 6px; margin-top: 11px; flex-wrap: wrap; }
@@ -210,20 +208,6 @@ html[data-theme="light"] .themetoggle .i-moon { display: none; }
font-size: 10px; font-size: 10px;
color: var(--muted); color: var(--muted);
} }
/* Not food: set apart from the categories, and deliberately quiet. */
.special {
margin-top: 22px;
padding-top: 16px;
border-top: 1px dashed var(--line);
}
.pill.plain {
font-size: 16px;
padding: 12px 16px;
background: var(--sunk);
color: var(--muted);
font-weight: 600;
}
.pill.xl { font-size: 22px; padding: 14px 18px; flex: 1 1 100%; } .pill.xl { font-size: 22px; padding: 14px 18px; flex: 1 1 100%; }
.pill.lg { font-size: 18px; padding: 12px 16px; } .pill.lg { font-size: 18px; padding: 12px 16px; }
.pill.md { font-size: 15.5px; padding: 11px 14px; } .pill.md { font-size: 15.5px; padding: 11px 14px; }
@@ -326,26 +310,8 @@ html[data-theme="light"] .themetoggle .i-moon { display: none; }
text-transform: uppercase; text-transform: uppercase;
color: var(--muted); color: var(--muted);
} }
/* The day list is the page; rows are links and the selected one expands. */ /* History sits under the logger on the same page, so whole rows are links. */
.history { margin-top: 4px; } .history { margin-top: 8px; }
/* Marked with a bar down the side, not rules above and below: the rows either
side already draw a bottom border, so a horizontal rule here doubled up.
scroll-margin keeps the anchor off the viewport edge. */
.open {
scroll-margin-top: 12px;
margin: 8px 0 18px;
padding: 10px 0 4px 13px;
border-left: 3px solid var(--accent);
}
.openday {
margin: 0 0 12px;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--accent);
}
.entry, .gapline { .entry, .gapline {
display: flex; display: flex;
gap: 12px; gap: 12px;
@@ -457,52 +423,15 @@ html[data-theme="light"] .themetoggle .i-moon { display: none; }
cursor: pointer; cursor: pointer;
} }
/* Catalog structure: Pääruuat and Lisukkeet are the two halves of the /* Catalog rows */
catalog, the categories are subdivisions of the first. Two levels, so they
must not look alike. */
.section + .section { margin-top: 34px; }
.sectiontitle {
display: flex;
align-items: center;
gap: 9px;
margin: 0 0 4px;
padding-bottom: 8px;
border-bottom: 2px solid var(--ink);
font-size: 18px;
font-weight: 700;
letter-spacing: -0.03em;
}
.sectiontitle .count {
padding: 2px 8px;
border-radius: 999px;
background: var(--sunk);
color: var(--muted);
font-size: 12px;
font-weight: 600;
letter-spacing: 0;
}
.sechead { .sechead {
margin: 20px 0 2px; margin: 26px 0 6px;
font-size: 11px; font-size: 11px;
font-weight: 600; font-weight: 600;
letter-spacing: 0.09em; letter-spacing: 0.09em;
text-transform: uppercase; text-transform: uppercase;
color: var(--muted); color: var(--muted);
} }
/* Collapsed add/edit forms, so the page opens on the catalog. */
.addform > summary {
cursor: pointer;
font-weight: 600;
font-size: 15px;
min-height: 24px;
}
.addform[open] > summary {
margin-bottom: 14px;
padding-bottom: 10px;
border-bottom: 1px solid var(--line);
}
.row { .row {
display: flex; display: flex;
align-items: center; align-items: center;
+12 -124
View File
@@ -28,24 +28,13 @@ type Dish struct {
TimesEaten int TimesEaten int
} }
// Rows flagged `special` in the database — Tähteet — are loggable but are not // CategoryKey is the class suffix for the colour dot. A dish covering several
// food. They carry no category, never appear in the catalog, and PRD §8 // categories (tortillas, build-your-own pizza) gets the mixed marker.
// excludes them from the suggester: cooldown, coverage and weighting all skip
// them. dishByID deliberately does not filter on the flag, because logging one
// has to work like logging anything else.
// CategoryKey picks the mark for a dish. One covering several categories
// (tortillas, build-your-own pizza) gets the mixed one; carrying none at all
// means it is not food, and Tähteet is not a mixture of anything.
func (d Dish) CategoryKey() string { func (d Dish) CategoryKey() string {
switch len(d.Categories) { if len(d.Categories) == 1 {
case 0:
return "tahteet"
case 1:
return categoryFI[d.Categories[0]] return categoryFI[d.Categories[0]]
default:
return "sek"
} }
return "sek"
} }
// Size buckets the dish by how often it has been eaten. The board draws // Size buckets the dish by how often it has been eaten. The board draws
@@ -88,17 +77,6 @@ func (e Entry) SidesLabel() string {
// listDishes returns live mains ordered by how often they have been eaten. // listDishes returns live mains ordered by how often they have been eaten.
// An empty search matches everything. // An empty search matches everything.
func listDishes(db *sql.DB, search string) ([]Dish, error) { func listDishes(db *sql.DB, search string) ([]Dish, error) {
return queryDishes(db, search, false)
}
// listSpecial returns the entries that are not food — Tähteet and anything
// like it. They are loggable but never suggested, and never appear in the
// catalog, so they are fetched deliberately rather than by accident.
func listSpecial(db *sql.DB, search string) ([]Dish, error) {
return queryDishes(db, search, true)
}
func queryDishes(db *sql.DB, search string, special bool) ([]Dish, error) {
rows, err := db.Query(` rows, err := db.Query(`
SELECT m.id, m.name, m.has_sides, SELECT m.id, m.name, m.has_sides,
coalesce((SELECT group_concat(c.category) coalesce((SELECT group_concat(c.category)
@@ -107,9 +85,8 @@ func queryDishes(db *sql.DB, search string, special bool) ([]Dish, error) {
(SELECT count(*) FROM meal_log l WHERE l.main_dish_id = m.id) (SELECT count(*) FROM meal_log l WHERE l.main_dish_id = m.id)
FROM main_dishes m FROM main_dishes m
WHERE m.deleted_at IS NULL WHERE m.deleted_at IS NULL
AND m.special = ?
AND (? = '' OR lower(m.name) LIKE '%' || lower(?) || '%') AND (? = '' OR lower(m.name) LIKE '%' || lower(?) || '%')
ORDER BY 5 DESC, m.name`, special, search, search) ORDER BY 5 DESC, m.name`, search, search)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -305,8 +282,7 @@ func updateMain(db *sql.DB, id int64, name string, categories []string, hasSides
defer tx.Rollback() defer tx.Rollback()
if _, err := tx.Exec( if _, err := tx.Exec(
`UPDATE main_dishes SET name = ?, has_sides = ? `UPDATE main_dishes SET name = ?, has_sides = ? WHERE id = ? AND deleted_at IS NULL`,
WHERE id = ? AND deleted_at IS NULL AND special = 0`,
name, hasSides, id, name, hasSides, id,
); err != nil { ); err != nil {
return taken(err) return taken(err)
@@ -346,14 +322,9 @@ func updateSide(db *sql.DB, id int64, name string) error {
// Soft delete: the row stays so historical log entries keep resolving their // Soft delete: the row stays so historical log entries keep resolving their
// names, but it disappears from the catalog and every picker (PRD §6). // names, but it disappears from the catalog and every picker (PRD §6).
//
// `special = 0` here and in updateMain: the catalog never lists Tähteet, so
// the UI cannot reach it, but a stale tab or a hand-made POST could — and
// removing it would take away the row migration 0002 guarantees.
func softDeleteMain(db *sql.DB, id int64) error { func softDeleteMain(db *sql.DB, id int64) error {
_, err := db.Exec( _, err := db.Exec(
`UPDATE main_dishes SET deleted_at = datetime('now') `UPDATE main_dishes SET deleted_at = datetime('now') WHERE id = ?`, id)
WHERE id = ? AND special = 0`, id)
return err return err
} }
@@ -438,12 +409,7 @@ type HistoryPage struct {
// history walks back day by day from a given day, so a day nobody wrote down // history walks back day by day from a given day, so a day nobody wrote down
// shows up as an explicit gap rather than silently missing. It stops at the // shows up as an explicit gap rather than silently missing. It stops at the
// first entry ever recorded — before that there is no history to be missing. // first entry ever recorded — before that there is no history to be missing.
// func history(db *sql.DB, loc *time.Location, from time.Time, days int) (HistoryPage, error) {
// reach names a day that must appear whatever the window says. The log board
// opens inside the selected day's row, so a date picked from before the first
// entry ever logged used to render nothing at all: no row, no board, no way to
// log it. Pass the zero time to ask for the plain window.
func history(db *sql.DB, loc *time.Location, from time.Time, days int, reach time.Time) (HistoryPage, error) {
var first sql.NullString var first sql.NullString
if err := db.QueryRow(`SELECT min(date) FROM meal_log`).Scan(&first); err != nil { if err := db.QueryRow(`SELECT min(date) FROM meal_log`).Scan(&first); err != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
@@ -468,92 +434,14 @@ func history(db *sql.DB, loc *time.Location, from time.Time, days int, reach tim
oldest = firstDate oldest = firstDate
page.More = false page.More = false
} }
if !reach.IsZero() && reach.Before(oldest) {
oldest = reach
page.More = firstDate.Before(oldest)
}
page.Next = oldest.AddDate(0, 0, -1) page.Next = oldest.AddDate(0, 0, -1)
entries, err := entriesBetween(db, oldest, from)
if err != nil {
return HistoryPage{}, err
}
for d := from; !d.Before(oldest); d = d.AddDate(0, 0, -1) { for d := from; !d.Before(oldest); d = d.AddDate(0, 0, -1) {
row := HistoryRow{Date: d} entry, err := entryFor(db, d)
if e := entries[d.Format(dateLayout)]; e != nil { if err != nil {
e.Date = d return HistoryPage{}, err
row.Entry = e
} }
page.Rows = append(page.Rows, row) page.Rows = append(page.Rows, HistoryRow{Date: d, Entry: entry})
} }
return page, nil return page, nil
} }
// entriesBetween loads every logged day in the inclusive range, keyed by
// stored date string, in two queries rather than two per day. The widest
// window a URL can ask for is five years, which day-at-a-time made 3,600 round
// trips through a pool of exactly one connection.
func entriesBetween(db *sql.DB, from, to time.Time) (map[string]*Entry, error) {
lo, hi := from.Format(dateLayout), to.Format(dateLayout)
rows, err := db.Query(`
SELECT l.id, l.date, m.id, m.name, m.has_sides,
coalesce((SELECT group_concat(c.category)
FROM main_dish_categories c
WHERE c.main_dish_id = m.id), '')
FROM meal_log l
JOIN main_dishes m ON m.id = l.main_dish_id
WHERE l.date BETWEEN ? AND ?`, lo, hi)
if err != nil {
return nil, err
}
defer rows.Close()
byDate := map[string]*Entry{}
byLog := map[int64]*Entry{}
for rows.Next() {
var logID int64
var date, cats string
var e Entry
if err := rows.Scan(
&logID, &date, &e.Main.ID, &e.Main.Name, &e.Main.HasSides, &cats,
); err != nil {
return nil, err
}
if cats != "" {
e.Main.Categories = strings.Split(cats, ",")
}
byDate[date] = &e
byLog[logID] = &e
}
if err := rows.Err(); err != nil {
return nil, err
}
if len(byLog) == 0 {
return byDate, nil
}
sides, err := db.Query(`
SELECT ls.meal_log_id, s.id, s.name
FROM meal_log_sides ls
JOIN side_dishes s ON s.id = ls.side_dish_id
JOIN meal_log l ON l.id = ls.meal_log_id
WHERE l.date BETWEEN ? AND ?
ORDER BY s.name`, lo, hi)
if err != nil {
return nil, err
}
defer sides.Close()
for sides.Next() {
var logID int64
var s Side
if err := sides.Scan(&logID, &s.ID, &s.Name); err != nil {
return nil, err
}
if e := byLog[logID]; e != nil {
e.Sides = append(e.Sides, s)
}
}
return byDate, sides.Err()
}
+4 -65
View File
@@ -235,7 +235,7 @@ func TestHistoryMarksUnloggedDaysAsGaps(t *testing.T) {
t.Fatalf("save -3: %v", err) t.Fatalf("save -3: %v", err)
} }
page, err := history(h.db, loc, now, 60, time.Time{}) page, err := history(h.db, loc, now, 60)
if err != nil { if err != nil {
t.Fatalf("history: %v", err) t.Fatalf("history: %v", err)
} }
@@ -271,7 +271,7 @@ func TestHistoryPagesInWindows(t *testing.T) {
t.Fatalf("save -9: %v", err) t.Fatalf("save -9: %v", err)
} }
first, err := history(h.db, loc, now, 5, time.Time{}) first, err := history(h.db, loc, now, 5)
if err != nil { if err != nil {
t.Fatalf("first window: %v", err) t.Fatalf("first window: %v", err)
} }
@@ -286,7 +286,7 @@ func TestHistoryPagesInWindows(t *testing.T) {
} }
// The windows must meet exactly: no day repeated, none skipped. // The windows must meet exactly: no day repeated, none skipped.
second, err := history(h.db, loc, first.Next, 5, time.Time{}) second, err := history(h.db, loc, first.Next, 5)
if err != nil { if err != nil {
t.Fatalf("second window: %v", err) t.Fatalf("second window: %v", err)
} }
@@ -305,7 +305,7 @@ func TestHistoryPagesInWindows(t *testing.T) {
func TestHistoryEmptyWithoutEntries(t *testing.T) { func TestHistoryEmptyWithoutEntries(t *testing.T) {
h := seeded(t) h := seeded(t)
page, err := history(h.db, time.UTC, today(time.UTC), 60, time.Time{}) page, err := history(h.db, time.UTC, today(time.UTC), 60)
if err != nil { if err != nil {
t.Fatalf("history: %v", err) t.Fatalf("history: %v", err)
} }
@@ -316,64 +316,3 @@ func TestHistoryEmptyWithoutEntries(t *testing.T) {
t.Error("More is set although there is no history at all") t.Error("More is set although there is no history at all")
} }
} }
// A date picked from before the first entry ever logged used to fall outside
// the window entirely: no row, so the log board had nothing to open in and the
// day could not be filled in at all.
func TestHistoryReachesDaysOlderThanTheFirstEntry(t *testing.T) {
h := seeded(t)
loc := time.UTC
now := today(loc)
if err := saveEntry(h.db, now, h.mainNamed(t, "Lohikeitto"), nil); err != nil {
t.Fatalf("save today: %v", err)
}
want := now.AddDate(0, 0, -100)
page, err := history(h.db, loc, now, 30, want)
if err != nil {
t.Fatalf("history: %v", err)
}
if len(page.Rows) != 101 {
t.Fatalf("%d rows, want 101 (today back to the selected day)", len(page.Rows))
}
last := page.Rows[len(page.Rows)-1]
if !last.Date.Equal(want) {
t.Errorf("last row is %s, want the selected %s",
last.Date.Format(dateLayout), want.Format(dateLayout))
}
if page.More {
t.Error("More is set although the window reached past the oldest entry")
}
}
// The sides of every day come back in one query now; each still has to land on
// its own day.
func TestHistoryKeepsSidesWithTheirOwnDay(t *testing.T) {
h := seeded(t)
loc := time.UTC
now := today(loc)
muusi := h.sideNamed(t, "Perunamuusi")
riisi := h.sideNamed(t, "Riisi")
if err := saveEntry(h.db, now, h.mainNamed(t, "Lohikeitto"), []int64{muusi}); err != nil {
t.Fatalf("save today: %v", err)
}
if err := saveEntry(h.db, now.AddDate(0, 0, -1), h.mainNamed(t, "Lihapullat"), []int64{riisi}); err != nil {
t.Fatalf("save -1: %v", err)
}
page, err := history(h.db, loc, now, 30, time.Time{})
if err != nil {
t.Fatalf("history: %v", err)
}
if len(page.Rows) != 2 {
t.Fatalf("%d rows, want 2", len(page.Rows))
}
for i, want := range []string{"Perunamuusi", "Riisi"} {
got := page.Rows[i].Entry
if got == nil || len(got.Sides) != 1 || got.Sides[0].Name != want {
t.Errorf("row %d sides = %+v, want just %s", i, got.Sides, want)
}
}
}
+105 -257
View File
@@ -43,23 +43,6 @@ func dayURL(base string, d, now time.Time) string {
return base + "?pvm=" + isoDate(d) return base + "?pvm=" + isoDate(d)
} }
// showURL turns a catalog page link into the patch endpoint behind it, so the
// href and the Datastar call never drift apart.
func showURL(pageURL string) string {
return strings.Replace(pageURL, "/ruuat?", "/ruuat/nayta?", 1)
}
// dayPatch is the endpoint behind every link in the day list. The href beside
// it stays a real page URL for anyone without JavaScript; Datastar calls this
// instead and swaps the list where it stands.
func dayPatch(d time.Time, param string) string {
url := "/paiva?pvm=" + isoDate(d)
if param != "" {
url += "&" + param
}
return url
}
// pickSeparator joins a dish onto a day URL, which already carries ?pvm= for // pickSeparator joins a dish onto a day URL, which already carries ?pvm= for
// any day but today. // any day but today.
func pickSeparator(v logView) string { func pickSeparator(v logView) string {
@@ -69,16 +52,6 @@ func pickSeparator(v logView) string {
return "&" return "&"
} }
// stepURL is the page URL for a link inside the open day: the fallback when
// there is no JavaScript to intercept it.
func stepURL(v logView, param string) string {
url := dayURL("/", v.Date, v.Today)
if param != "" {
url += pickSeparator(v) + param
}
return url
}
// jsString renders a Go string as a JavaScript literal, for the data-signals // jsString renders a Go string as a JavaScript literal, for the data-signals
// attribute that seeds the search box. // attribute that seeds the search box.
func jsString(s string) string { func jsString(s string) string {
@@ -108,16 +81,6 @@ func categoryLabels(d Dish) string {
return strings.Join(names, ", ") return strings.Join(names, ", ")
} }
// pageTitle prefixes the tab title on any instance that is not production.
// The tab is the only place a browser shows which of two identical apps you
// are looking at.
func pageTitle(title string) string {
if envTag == "" {
return title
}
return envTag + " · " + title
}
// countFI renders "1 pääruoka" but "16 pääruokaa": Finnish takes the partitive // countFI renders "1 pääruoka" but "16 pääruokaa": Finnish takes the partitive
// after every number except one. // after every number except one.
func countFI(n int, one, many string) string { func countFI(n int, one, many string) string {
@@ -140,7 +103,7 @@ templ page(title, current string) {
// header rather than butting against it. // header rather than butting against it.
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#FFFFFF"/> <meta name="theme-color" media="(prefers-color-scheme: light)" content="#FFFFFF"/>
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#1C1E22"/> <meta name="theme-color" media="(prefers-color-scheme: dark)" content="#1C1E22"/>
<title>{ pageTitle(title) }</title> <title>{ title }</title>
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml"/> <link rel="icon" href="/static/favicon.svg" type="image/svg+xml"/>
<link rel="apple-touch-icon" href="/static/apple-touch-icon.png"/> <link rel="apple-touch-icon" href="/static/apple-touch-icon.png"/>
<!-- use-credentials: the manifest is fetched behind Basic auth and <!-- use-credentials: the manifest is fetched behind Basic auth and
@@ -220,10 +183,6 @@ templ categoryIcon(key string) {
<span class="cat c-kasvis"> <span class="cat c-kasvis">
@glyphKasvis() @glyphKasvis()
</span> </span>
case "tahteet":
<span class="cat c-tahteet">
@glyphTahteet()
</span>
default: default:
<span class="cat"> <span class="cat">
@glyphSekalaiset() @glyphSekalaiset()
@@ -231,15 +190,6 @@ templ categoryIcon(key string) {
} }
} }
// A lidded tub. Tähteet is not food and not a mixture of categories, so it
// gets neither a category colour nor the quartered mark.
templ glyphTahteet() {
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false" fill="currentColor">
<rect x="1.4" y="2.6" width="13.2" height="3" rx="1.3"></rect>
<path d="M2.8 6.8h10.4l-.9 6.6a1.6 1.6 0 0 1-1.6 1.4H5.3a1.6 1.6 0 0 1-1.6-1.4z"></path>
</svg>
}
// A steak, its bone knocked out with fill-rule so the hole is transparent on // A steak, its bone knocked out with fill-rule so the hole is transparent on
// whatever background the icon lands on. // whatever background the icon lands on.
templ glyphLiha() { templ glyphLiha() {
@@ -318,72 +268,57 @@ templ logPage(v logView) {
@daySwitch(v) @daySwitch(v)
</header> </header>
<main class="pad"> <main class="pad">
@dayList(v) switch {
case v.Chosen != nil:
@sidesStep(v)
case v.ShowBoard:
@board(v)
default:
@loggedCard(v)
}
@historyList(v)
</main> </main>
} }
} }
// dayList is the whole page: every day back through the window, with the // historyList sits under the day being logged: the two were always one thing,
// selected one expanded where it sits. Opening a day used to swap in a panel // since every row here is a link back into the logger above it.
// above the list and drop that day out of it, so the rows below jumped up templ historyList(v logView) {
// under the tap. Now nothing moves — the row grows. <section class="history">
templ dayList(v logView) { <h3 class="sechead">Aiemmin</h3>
<section class="history" id="paivat"> if len(v.History.Rows) == 0 {
<p class="muted small">Ei vielä merkintöjä.</p>
}
for i, row := range v.History.Rows { for i, row := range v.History.Rows {
if i == 0 || v.History.Rows[i-1].Date.Month() != row.Date.Month() { if !row.Date.Equal(v.Date) {
<p class="monthrule">{ monthFI(row.Date) }</p> if i == 0 || v.History.Rows[i-1].Date.Month() != row.Date.Month() {
} <p class="monthrule">{ monthFI(row.Date) }</p>
if row.Date.Equal(v.Date) { }
<div class="open"> if row.Entry != nil {
<p class="openday"> <a class="entry" href={ templ.SafeURL(dayURL("/", row.Date, v.Today)) }>
if row.Date.Equal(v.Today) { <time>{ dayLabelFI(row.Date) }</time>
Tänään <div>
} else { <div class="nm">
{ longDateFI(row.Date) } @categoryIcon(row.Entry.Main.CategoryKey())
} { row.Entry.Main.Name }
</p> </div>
switch { <div class="sd">{ row.Entry.SidesLabel() }</div>
case v.Chosen != nil:
@sidesStep(v)
case v.ShowBoard:
@board(v)
default:
@loggedCard(v)
}
</div>
} else if row.Entry != nil {
<a
class="entry"
href={ templ.SafeURL(dayURL("/", row.Date, v.Today)) }
data-on:click__prevent={ "@get('" + dayPatch(row.Date, "") + "')" }
>
<time>{ dayLabelFI(row.Date) }</time>
<div>
<div class="nm">
@categoryIcon(row.Entry.Main.CategoryKey())
{ row.Entry.Main.Name }
</div> </div>
<div class="sd">{ row.Entry.SidesLabel() }</div> <span class="chev"></span>
</div> </a>
<span class="chev"></span> } else {
</a> <a class="gapline" href={ templ.SafeURL(dayURL("/", row.Date, v.Today)) }>
} else { <time>{ dayLabelFI(row.Date) }</time>
<a <span>Ei merkintää</span>
class="gapline" <span class="act">Merkitse</span>
href={ templ.SafeURL(dayURL("/", row.Date, v.Today)) } </a>
data-on:click__prevent={ "@get('" + dayPatch(row.Date, "") + "')" } }
>
<time>{ dayLabelFI(row.Date) }</time>
<span>Ei merkintää</span>
<span class="act">Merkitse</span>
</a>
} }
} }
if v.History.More { if v.History.More {
<a <a
class="more" class="more"
href={ templ.SafeURL(dayURL("/", v.Date, v.Today) + pickSeparator(v) + "paivat=" + strconv.Itoa(v.HistoryMore)) } href={ templ.SafeURL(dayURL("/", v.Date, v.Today) + pickSeparator(v) + "paivat=" + strconv.Itoa(v.HistoryMore)) }
data-on:click__prevent={ "@get('" + dayPatch(v.Date, "paivat="+strconv.Itoa(v.HistoryMore)) + "')" }
>Näytä lisää</a> >Näytä lisää</a>
} }
</section> </section>
@@ -450,29 +385,6 @@ templ boardList(v logView) {
} }
</div> </div>
} }
// Tähteet is not food, so it sits apart from the categories rather
// than inside one. Fixed size: it will be among the most-logged
// entries, and it should not tower over the actual cooking.
if len(v.Special) > 0 {
<div class="special">
for _, d := range v.Special {
<a
class="pill plain"
href={ templ.SafeURL(stepURL(v, "ruoka="+strconv.FormatInt(d.ID, 10))) }
data-on:click__prevent={ "@get('" + dayPatch(v.Date, "ruoka="+strconv.FormatInt(d.ID, 10)) + "')" }
>
@categoryIcon(d.CategoryKey())
{ d.Name }
if d.TimesEaten > 0 {
<span class="n">{ strconv.Itoa(d.TimesEaten) }</span>
}
</a>
}
</div>
}
// Tähteet always matches an empty search, so the add card keys off the
// real dishes only: otherwise a fresh install would show leftovers and
// no way to add anything.
if len(v.Dishes) == 0 { if len(v.Dishes) == 0 {
@quickAddCard(v) @quickAddCard(v)
} }
@@ -495,11 +407,7 @@ templ quickAddCard(v logView) {
if v.New.Err != "" { if v.New.Err != "" {
<p class="formerr">{ v.New.Err }</p> <p class="formerr">{ v.New.Err }</p>
} }
<form <form method="post" action="/lisaa">
method="post"
action="/lisaa"
data-on:submit__prevent="@post('/lisaa', {contentType: 'form'})"
>
<input type="hidden" name="pvm" value={ isoDate(v.Date) }/> <input type="hidden" name="pvm" value={ isoDate(v.Date) }/>
<label class="field"> <label class="field">
<span>Nimi</span> <span>Nimi</span>
@@ -530,8 +438,7 @@ templ quickAddCard(v logView) {
templ dishPill(d Dish, v logView) { templ dishPill(d Dish, v logView) {
<a <a
class={ "pill", d.Size() } class={ "pill", d.Size() }
href={ templ.SafeURL(stepURL(v, "ruoka="+strconv.FormatInt(d.ID, 10))) } href={ templ.SafeURL(dayURL("/", v.Date, v.Today) + pickSeparator(v) + "ruoka=" + strconv.FormatInt(d.ID, 10)) }
data-on:click__prevent={ "@get('" + dayPatch(v.Date, "ruoka="+strconv.FormatInt(d.ID, 10)) + "')" }
> >
@categoryIcon(d.CategoryKey()) @categoryIcon(d.CategoryKey())
{ d.Name } { d.Name }
@@ -547,11 +454,7 @@ templ sidesStep(v logView) {
@categoryIcon(v.Chosen.CategoryKey()) @categoryIcon(v.Chosen.CategoryKey())
{ v.Chosen.Name } { v.Chosen.Name }
</h3> </h3>
<form <form method="post" action="/kirjaa">
method="post"
action="/kirjaa"
data-on:submit__prevent="@post('/kirjaa', {contentType: 'form'})"
>
<input type="hidden" name="pvm" value={ isoDate(v.Date) }/> <input type="hidden" name="pvm" value={ isoDate(v.Date) }/>
<input type="hidden" name="ruoka" value={ strconv.FormatInt(v.Chosen.ID, 10) }/> <input type="hidden" name="ruoka" value={ strconv.FormatInt(v.Chosen.ID, 10) }/>
if v.Chosen.HasSides && len(v.Sides) > 0 { if v.Chosen.HasSides && len(v.Sides) > 0 {
@@ -573,11 +476,7 @@ templ sidesStep(v logView) {
} }
<button class="primary" type="submit">Tallenna</button> <button class="primary" type="submit">Tallenna</button>
</form> </form>
<a <a class="ghost" href={ templ.SafeURL(dayURL("/", v.Date, v.Today)) }>Peruuta</a>
class="ghost"
href={ templ.SafeURL(stepURL(v, "")) }
data-on:click__prevent={ "@get('" + dayPatch(v.Date, "") + "')" }
>Peruuta</a>
</section> </section>
} }
@@ -598,31 +497,21 @@ templ loggedCard(v logView) {
if v.Confirming { if v.Confirming {
<p class="q">Poistetaanko merkintä?</p> <p class="q">Poistetaanko merkintä?</p>
<div class="pair"> <div class="pair">
<form <form method="post" action="/poista">
method="post"
action="/poista"
data-on:submit__prevent="@post('/poista', {contentType: 'form'})"
>
<input type="hidden" name="pvm" value={ isoDate(v.Date) }/> <input type="hidden" name="pvm" value={ isoDate(v.Date) }/>
<button class="btn del" type="submit">Kyllä, poista</button> <button class="btn del" type="submit">Kyllä, poista</button>
</form> </form>
<a <a class="btn" href={ templ.SafeURL(dayURL("/", v.Date, v.Today)) }>Peruuta</a>
class="btn"
href={ templ.SafeURL(stepURL(v, "")) }
data-on:click__prevent={ "@get('" + dayPatch(v.Date, "") + "')" }
>Peruuta</a>
</div> </div>
} else { } else {
<div class="pair"> <div class="pair">
<a <a
class="btn" class="btn"
href={ templ.SafeURL(stepURL(v, "muuta=1")) } href={ templ.SafeURL(dayURL("/", v.Date, v.Today) + pickSeparator(v) + "muuta=1") }
data-on:click__prevent={ "@get('" + dayPatch(v.Date, "muuta=1") + "')" }
>Muokkaa</a> >Muokkaa</a>
<a <a
class="btn del" class="btn del"
href={ templ.SafeURL(stepURL(v, "poista=1")) } href={ templ.SafeURL(dayURL("/", v.Date, v.Today) + pickSeparator(v) + "poista=1") }
data-on:click__prevent={ "@get('" + dayPatch(v.Date, "poista=1") + "')" }
>Poista</a> >Poista</a>
</div> </div>
} }
@@ -642,6 +531,8 @@ templ catalogPage(v catalogView) {
if v.Report != nil { if v.Report != nil {
@importReport(v.Report) @importReport(v.Report)
} }
@mainForm_(v.Main)
@sideForm_(v.Side)
<div data-signals:haku={ jsString(v.Search) }> <div data-signals:haku={ jsString(v.Search) }>
<form method="get" action="/ruuat" class="searchrow"> <form method="get" action="/ruuat" class="searchrow">
<input <input
@@ -655,10 +546,6 @@ templ catalogPage(v catalogView) {
data-on:input__debounce.250ms="@get('/ruuat/etsi')" data-on:input__debounce.250ms="@get('/ruuat/etsi')"
/> />
</form> </form>
// The add and edit forms stay outside the patched fragment, or
// typing in the search box would collapse a form mid-edit.
@mainForm_(v.Main)
@sideForm_(v.Side)
@catalogList(v) @catalogList(v)
</div> </div>
<details class="card"> <details class="card">
@@ -670,105 +557,77 @@ templ catalogPage(v catalogView) {
} }
// catalogList carries the id Datastar patches, so typing in the search box // catalogList carries the id Datastar patches, so typing in the search box
// swaps the lists without touching the forms above them. // swaps the lists without reloading the forms above them.
//
// Two levels of heading, because there are two: Pääruuat and Lisukkeet are
// the halves of the catalog, and the categories are subdivisions of the
// first. They were previously styled the same, which made a category look
// like a peer of the entire side-dish list.
templ catalogList(v catalogView) { templ catalogList(v catalogView) {
<div id="ruokalista"> <div id="ruokalista">
<section class="section"> if v.Mains == 0 {
@sectionTitle("Pääruuat", v.Mains) <h3 class="sechead">Pääruuat</h3>
if v.Mains == 0 { <p class="muted small">
@emptyNote(v.Search) if v.Search == "" {
} Ei vielä pääruokia.
// Grouped by category, alphabetical inside. The catalog is a list } else {
// you manage, so a predictable position beats a useful one. Ei osumia.
for _, g := range v.Groups {
<h3 class="sechead">{ g.Label }</h3>
for _, d := range g.Dishes {
<div class="row">
@categoryIcon(d.CategoryKey())
<div class="rowtext">
<div class="nm">{ d.Name }</div>
if !d.HasSides {
<div class="sd">Ei lisukkeita</div>
}
</div>
@rowActions(v, "/ruuat?muokkaa="+strconv.FormatInt(d.ID, 10), d.ID, "paa")
</div>
} }
} </p>
</section> }
<section class="section"> // Grouped by category, alphabetical inside. The catalog is a list you
@sectionTitle("Lisukkeet", len(v.Sides)) // manage, so a predictable position beats a useful one.
if len(v.Sides) == 0 { for _, g := range v.Groups {
@emptyNote(v.Search) <h3 class="sechead">{ g.Label }</h3>
} for _, d := range g.Dishes {
for _, s := range v.Sides {
<div class="row"> <div class="row">
<div class="rowtext"><div class="nm">{ s.Name }</div></div> @categoryIcon(d.CategoryKey())
@rowActions(v, "/ruuat?muokkaa-lisuke="+strconv.FormatInt(s.ID, 10), s.ID, "lisuke") <div class="rowtext">
<div class="nm">{ d.Name }</div>
if !d.HasSides {
<div class="sd">Ei lisukkeita</div>
}
</div>
@rowActions(v, "/ruuat?muokkaa="+strconv.FormatInt(d.ID, 10), d.ID, "paa")
</div> </div>
} }
</section>
</div>
}
templ sectionTitle(label string, n int) {
<h2 class="sectiontitle">
{ label }
<span class="count">{ strconv.Itoa(n) }</span>
</h2>
}
templ emptyNote(search string) {
<p class="muted small">
if search == "" {
Ei vielä mitään.
} else {
Ei osumia haulle { search }.
} }
</p> <h3 class="sechead">Lisukkeet</h3>
if len(v.Sides) == 0 {
<p class="muted small">
if v.Search == "" {
Ei vielä lisukkeita.
} else {
Ei osumia.
}
</p>
}
for _, s := range v.Sides {
<div class="row">
<div class="rowtext"><div class="nm">{ s.Name }</div></div>
@rowActions(v, "/ruuat?muokkaa-lisuke="+strconv.FormatInt(s.ID, 10), s.ID, "lisuke")
</div>
}
</div>
} }
// rowActions is a pencil and a bin, until the bin is tapped: then the row // rowActions is a pencil and a bin, until the bin is tapped: then the row
// asks. An icon is a smaller target to hit by accident than a word, and the // asks. An icon is a smaller target to hit by accident than a word, and the
// dish disappears from every picker the moment it goes. // dish disappears from every picker the moment it goes.
// Every control here is a real link or form, so the page still works without
// JavaScript. Datastar intercepts them and patches the list in place instead,
// which is the whole point: a delete confirmation halfway down a long list
// must not send the browser back to the top.
templ rowActions(v catalogView, editURL string, id int64, kind string) { templ rowActions(v catalogView, editURL string, id int64, kind string) {
if v.DeleteID == id && v.DeleteKind == kind { if v.DeleteID == id && v.DeleteKind == kind {
<div class="rowactions confirming"> <div class="rowactions confirming">
<span>Poista?</span> <span>Poista?</span>
<form <form method="post" action="/ruuat/poista">
method="post"
action="/ruuat/poista"
data-on:submit__prevent="@post('/ruuat/poista', {contentType: 'form'})"
>
<input type="hidden" name="id" value={ strconv.FormatInt(id, 10) }/> <input type="hidden" name="id" value={ strconv.FormatInt(id, 10) }/>
<input type="hidden" name="tyyppi" value={ kind }/> <input type="hidden" name="tyyppi" value={ kind }/>
<button type="submit" class="del">Kyllä</button> <button type="submit" class="del">Kyllä</button>
</form> </form>
<a href="/ruuat" data-on:click__prevent="@get('/ruuat/nayta')">Peruuta</a> <a href="/ruuat">Peruuta</a>
</div> </div>
} else { } else {
<div class="rowactions"> <div class="rowactions">
<a <a href={ templ.SafeURL(editURL) } aria-label="Muokkaa" title="Muokkaa">
href={ templ.SafeURL(editURL) }
data-on:click__prevent={ "@get('" + showURL(editURL) + "')" }
aria-label="Muokkaa"
title="Muokkaa"
>
@iconPencil() @iconPencil()
</a> </a>
<a <a
class="del" class="del"
href={ templ.SafeURL("/ruuat?poista=" + strconv.FormatInt(id, 10) + "&tyyppi=" + kind) } href={ templ.SafeURL("/ruuat?poista=" + strconv.FormatInt(id, 10) + "&tyyppi=" + kind) }
data-on:click__prevent={ "@get('/ruuat/nayta?poista=" + strconv.FormatInt(id, 10) + "&tyyppi=" + kind + "')" }
aria-label="Poista" aria-label="Poista"
title="Poista" title="Poista"
> >
@@ -792,26 +651,19 @@ templ iconTrash() {
</svg> </svg>
} }
// Collapsed by default so the page opens on the catalog rather than on two
// screens of empty form. Forced open when editing or after a rejected
// submission, since the form is then the thing that needs attention.
templ mainForm_(f mainForm) { templ mainForm_(f mainForm) {
<details class="card addform" id="paaruoka" open?={ f.ID != 0 || f.Err != "" }> <section class="card" id="paaruoka">
<summary> <h3>
if f.ID == 0 { if f.ID == 0 {
Lisää pääruoka Lisää pääruoka
} else { } else {
Muokkaa pääruokaa Muokkaa pääruokaa
} }
</summary> </h3>
if f.Err != "" { if f.Err != "" {
<p class="formerr">{ f.Err }</p> <p class="formerr">{ f.Err }</p>
} }
<form <form method="post" action="/ruuat/paaruoka">
method="post"
action="/ruuat/paaruoka"
data-on:submit__prevent="@post('/ruuat/paaruoka', {contentType: 'form'})"
>
if f.ID != 0 { if f.ID != 0 {
<input type="hidden" name="id" value={ strconv.FormatInt(f.ID, 10) }/> <input type="hidden" name="id" value={ strconv.FormatInt(f.ID, 10) }/>
} }
@@ -839,9 +691,9 @@ templ mainForm_(f mainForm) {
<button class="primary" type="submit">Tallenna</button> <button class="primary" type="submit">Tallenna</button>
</form> </form>
if f.ID != 0 { if f.ID != 0 {
<a class="ghost" href="/ruuat" data-on:click__prevent="@get('/ruuat/nayta')">Peruuta</a> <a class="ghost" href="/ruuat">Peruuta</a>
} }
</details> </section>
} }
templ categoryChip(value, label string, f mainForm) { templ categoryChip(value, label string, f mainForm) {
@@ -857,22 +709,18 @@ templ categoryChip(value, label string, f mainForm) {
} }
templ sideForm_(f sideForm) { templ sideForm_(f sideForm) {
<details class="card addform" id="lisuke" open?={ f.ID != 0 || f.Err != "" }> <section class="card" id="lisuke">
<summary> <h3>
if f.ID == 0 { if f.ID == 0 {
Lisää lisuke Lisää lisuke
} else { } else {
Muokkaa lisuketta Muokkaa lisuketta
} }
</summary> </h3>
if f.Err != "" { if f.Err != "" {
<p class="formerr">{ f.Err }</p> <p class="formerr">{ f.Err }</p>
} }
<form <form method="post" action="/ruuat/lisuke">
method="post"
action="/ruuat/lisuke"
data-on:submit__prevent="@post('/ruuat/lisuke', {contentType: 'form'})"
>
if f.ID != 0 { if f.ID != 0 {
<input type="hidden" name="id" value={ strconv.FormatInt(f.ID, 10) }/> <input type="hidden" name="id" value={ strconv.FormatInt(f.ID, 10) }/>
} }
@@ -883,9 +731,9 @@ templ sideForm_(f sideForm) {
<button class="primary" type="submit">Tallenna</button> <button class="primary" type="submit">Tallenna</button>
</form> </form>
if f.ID != 0 { if f.ID != 0 {
<a class="ghost" href="/ruuat" data-on:click__prevent="@get('/ruuat/nayta')">Peruuta</a> <a class="ghost" href="/ruuat">Peruuta</a>
} }
</details> </section>
} }
templ importForm() { templ importForm() {
+9 -13
View File
@@ -1,23 +1,19 @@
services: services:
app: app:
image: ${REPO:?set REPO in .env}:${TAG:-latest} image: ${FOODSTER_REPO:?set FOODSTER_REPO in .env}:${FOODSTER_TAG:-latest}
restart: unless-stopped restart: unless-stopped
# A bind mount rather than a named volume: the database sits in ./data on # The database is a bind mount, not a named volume: it sits in ./data on
# the host, where it can be listed, copied and backed up without going # the host where it can be listed, copied and opened with any sqlite
# through the container engine. The image runs as UID 65534, so the # client. The image runs as UID 65534, so the container has to be told
# container has to be told which host user owns that directory. # which host user owns that directory.
# user: "${FOODSTER_UID:-1000}:${FOODSTER_GID:-1000}"
# PUID/PGID rather than UID/GID: UID is a read-only variable in bash, so a
# value set here would be silently replaced by the invoking shell's own.
user: "${PUID:-1000}:${PGID:-1000}"
volumes: volumes:
- ./data:/data - ./data:/data
environment: environment:
PASSWORD: ${PASSWORD:?set PASSWORD in .env} FOODSTER_PASSWORD: ${FOODSTER_PASSWORD:?set FOODSTER_PASSWORD in .env}
DB: /data/foodster.db FOODSTER_DB: /data/foodster.db
ENV: ${ENV:-prod}
TZ: ${TZ:-Europe/Helsinki} TZ: ${TZ:-Europe/Helsinki}
# No published ports: Traefik reaches the container over the shared # No published ports: Traefik reaches the container over the shared
@@ -26,7 +22,7 @@ services:
labels: labels:
- traefik.enable=true - traefik.enable=true
- traefik.http.routers.foodster.entrypoints=websecure - traefik.http.routers.foodster.entrypoints=websecure
- traefik.http.routers.foodster.rule=Host(`${HOST:?set HOST in .env}`) - traefik.http.routers.foodster.rule=Host(`${FOODSTER_HOST:?set FOODSTER_HOST in .env}`)
- traefik.http.routers.foodster.tls=true - traefik.http.routers.foodster.tls=true
- traefik.http.services.foodster.loadbalancer.server.port=8080 - traefik.http.services.foodster.loadbalancer.server.port=8080
- traefik.docker.network=traefik - traefik.docker.network=traefik
+18 -89
View File
@@ -11,18 +11,12 @@ cd "$(dirname "$0")/.."
addr=127.0.0.1:8099 addr=127.0.0.1:8099
pass=smoke pass=smoke
# Dates are relative, never literal. A hardcoded one turns into "some day in
# the past" at the next midnight, and the assertions quietly start meaning
# something else.
d0=$(date +%F)
d1=$(date -d yesterday +%F)
tmp=$(mktemp -d) tmp=$(mktemp -d)
trap 'kill ${srv:-0} 2>/dev/null || true; rm -rf "$tmp"' EXIT trap 'kill ${srv:-0} 2>/dev/null || true; rm -rf "$tmp"' EXIT
go build -o "$tmp/foodster" ./cmd/foodster go build -o "$tmp/foodster" ./cmd/foodster
PASSWORD="$pass" DB="$tmp/smoke.db" ADDR="$addr" \ FOODSTER_PASSWORD="$pass" FOODSTER_DB="$tmp/smoke.db" FOODSTER_ADDR="$addr" \
"$tmp/foodster" >"$tmp/server.log" 2>&1 & "$tmp/foodster" >"$tmp/server.log" 2>&1 &
srv=$! srv=$!
@@ -78,8 +72,6 @@ check "theme script is served" \
home=$(curl -s -u ":$pass" "http://$addr/") home=$(curl -s -u ":$pass" "http://$addr/")
check "the header carries the brand" "$home" "Foodster" check "the header carries the brand" "$home" "Foodster"
# ENV is unset here, so this instance is production and unmarked.
check "production tabs are not tagged" "$home" "<title>Foodster</title>"
check "dark is the default without JavaScript" "$home" '<html lang="fi" data-theme="dark">' check "dark is the default without JavaScript" "$home" '<html lang="fi" data-theme="dark">'
check "the theme toggle is present" "$home" "data-theme-toggle" check "the theme toggle is present" "$home" "data-theme-toggle"
check "both theme icons ship so CSS can pick one" "$home" 'class="i-moon"' check "both theme icons ship so CSS can pick one" "$home" 'class="i-moon"'
@@ -122,11 +114,6 @@ check "malformed JSON is explained" \
board=$(curl -s -u ":$pass" "http://$addr/") board=$(curl -s -u ":$pass" "http://$addr/")
check "board lists imported dishes" "$board" "Lihapullat" check "board lists imported dishes" "$board" "Lihapullat"
# Tähteet is loggable but is not food: on the board, never in the catalog.
check "leftovers are on the board" "$board" "Tähteet"
refute "leftovers are not in the catalog" \
"$(curl -s -u ":$pass" "http://$addr/ruuat")" "Tähteet"
# Pull a real dish id out of the board rather than assuming one. # Pull a real dish id out of the board rather than assuming one.
ruoka=$(printf '%s' "$board" | grep -o 'ruoka=[0-9]*' | head -n1 | cut -d= -f2) ruoka=$(printf '%s' "$board" | grep -o 'ruoka=[0-9]*' | head -n1 | cut -d= -f2)
if [ -z "$ruoka" ]; then if [ -z "$ruoka" ]; then
@@ -140,53 +127,25 @@ check "picking a dish opens the sides step" \
check "saving redirects back to the day" \ check "saving redirects back to the day" \
"$(curl -s -o /dev/null -w '%{http_code}' -u ":$pass" \ "$(curl -s -o /dev/null -w '%{http_code}' -u ":$pass" \
-d "pvm=$d0&ruoka=$ruoka" "http://$addr/kirjaa")" "303" -d "pvm=2026-09-05&ruoka=$ruoka" "http://$addr/kirjaa")" "303"
check "the saved day shows what was eaten" \ check "the saved day shows what was eaten" \
"$(curl -s -u ":$pass" "http://$addr/?pvm=$d0")" "kirjattu" "$(curl -s -u ":$pass" "http://$addr/?pvm=2026-09-05")" "kirjattu"
# The selected day expands inside the list rather than in a panel above it, check "history is on the same page as the logger" \
# so the rows below do not shift when one is tapped. "$(curl -s -u ":$pass" "http://$addr/")" "Aiemmin"
day=$(curl -s -u ":$pass" "http://$addr/?pvm=$d0")
check "the selected day expands in place" "$day" 'class="open"'
check "and stays in the list rather than being lifted out" "$day" "kirjattu"
# ---- the day list patches in place instead of navigating ----------------
dayp=$(curl -s -u ":$pass" -H 'Datastar-Request: true' "http://$addr/paiva?pvm=$d0")
check "opening a day patches the list" "$dayp" 'id="paivat"'
refute "and returns a fragment, not a page" "$dayp" "<html"
check "picking a dish patches to the sides step" \
"$(curl -s -u ":$pass" -H 'Datastar-Request: true' \
"http://$addr/paiva?pvm=$d0&ruoka=$ruoka")" "Tallenna"
check "saving from Datastar patches back" \
"$(curl -s -u ":$pass" -H 'Datastar-Request: true' \
-d "pvm=$d1&ruoka=$ruoka" "http://$addr/kirjaa")" 'id="paivat"'
check "deleting from Datastar patches back" \
"$(curl -s -u ":$pass" -H 'Datastar-Request: true' \
-d "pvm=$d1" "http://$addr/poista")" 'id="paivat"'
# Without the header it must still redirect, for no JavaScript.
check "a plain save still redirects to the day" \
"$(curl -s -o /dev/null -w '%{redirect_url}' -u ":$pass" \
-d "pvm=$d1&ruoka=$ruoka" "http://$addr/kirjaa")" "pvm=$d1"
# Deleting a logged meal drops the row outright, so it asks first. # Deleting a logged meal drops the row outright, so it asks first.
saved=$(curl -s -u ":$pass" "http://$addr/?pvm=$d0&poista=1") saved=$(curl -s -u ":$pass" "http://$addr/?pvm=2026-09-05&poista=1")
check "deleting a meal asks first" "$saved" "Poistetaanko merkintä?" check "deleting a meal asks first" "$saved" "Poistetaanko merkintä?"
# Assert the entry is still shown, rather than that no gap row exists anywhere refute "and does not delete while asking" "$saved" "Ei merkintää"
# on the page: other days are legitimately unlogged and render their own.
check "and the entry is still there while asking" "$saved" "kirjattu"
check "deleting redirects back" \ check "deleting redirects back" \
"$(curl -s -o /dev/null -w '%{http_code}' -u ":$pass" \ "$(curl -s -o /dev/null -w '%{http_code}' -u ":$pass" \
-d "pvm=$d0" "http://$addr/poista")" "303" -d "pvm=2026-09-05" "http://$addr/poista")" "303"
check "the day is empty again" \ check "the day is empty again" \
"$(curl -s -u ":$pass" "http://$addr/?pvm=$d0")" "Etsi" "$(curl -s -u ":$pass" "http://$addr/?pvm=2026-09-05")" "Etsi"
check "search filters the board" \ check "search filters the board" \
"$(curl -s -u ":$pass" "http://$addr/?haku=keitto")" "keitto" "$(curl -s -u ":$pass" "http://$addr/?haku=keitto")" "keitto"
@@ -248,12 +207,9 @@ check "the quick-added dish is on the board" \
# ---- catalog CRUD from the UI ------------------------------------------- # ---- catalog CRUD from the UI -------------------------------------------
# Assert where it redirects, not just that it does: these pointed at the old check "adding a main redirects" \
# /ruoat spelling for a while and every 303-only check was happy. "$(curl -s -o /dev/null -w '%{http_code}' -u ":$pass" \
check "adding a main redirects back to the catalog" \ -d 'nimi=uunikala&kategoria=fish&lisukkeita=1' "http://$addr/ruuat/paaruoka")" "303"
"$(curl -s -o /dev/null -w '%{redirect_url}' -u ":$pass" \
-d 'nimi=uunikala&kategoria=fish&lisukkeita=1' "http://$addr/ruuat/paaruoka")" \
"/ruuat"
catalog=$(curl -s -u ":$pass" "http://$addr/ruuat") catalog=$(curl -s -u ":$pass" "http://$addr/ruuat")
check "the new main is listed, sentence-cased" "$catalog" "Uunikala" check "the new main is listed, sentence-cased" "$catalog" "Uunikala"
@@ -270,10 +226,9 @@ check "a nameless dish is refused" \
"$(curl -s -u ":$pass" -d 'nimi=+++&kategoria=fish' "http://$addr/ruuat/paaruoka")" \ "$(curl -s -u ":$pass" -d 'nimi=+++&kategoria=fish' "http://$addr/ruuat/paaruoka")" \
"Anna nimi." "Anna nimi."
check "adding a side redirects back to the catalog" \ check "adding a side redirects" \
"$(curl -s -o /dev/null -w '%{redirect_url}' -u ":$pass" \ "$(curl -s -o /dev/null -w '%{http_code}' -u ":$pass" \
-d 'nimi=lohkoperunat' "http://$addr/ruuat/lisuke")" \ -d 'nimi=lohkoperunat' "http://$addr/ruuat/lisuke")" "303"
"/ruuat"
check "the new side is listed" \ check "the new side is listed" \
"$(curl -s -u ":$pass" "http://$addr/ruuat")" "Lohkoperunat" "$(curl -s -u ":$pass" "http://$addr/ruuat")" "Lohkoperunat"
@@ -296,35 +251,9 @@ check "the bin asks before deleting" \
check "the dish is still there while it asks" \ check "the dish is still there while it asks" \
"$(curl -s -u ":$pass" "http://$addr/ruuat?poista=$uusi&tyyppi=paa")" "Uunikala" "$(curl -s -u ":$pass" "http://$addr/ruuat?poista=$uusi&tyyppi=paa")" "Uunikala"
# ---- the catalog patches in place instead of navigating ----------------- check "confirming the delete redirects" \
"$(curl -s -o /dev/null -w '%{http_code}' -u ":$pass" \
# A delete confirmation halfway down a long list must not send the browser -d "id=$uusi&tyyppi=paa" "http://$addr/ruuat/poista")" "303"
# back to the top, so these answer with a Datastar patch rather than a page.
patch=$(curl -s -u ":$pass" -H 'Datastar-Request: true' \
"http://$addr/ruuat/nayta?poista=$uusi&tyyppi=paa")
check "asking to delete patches rather than navigates" "$patch" "event: datastar-patch-elements"
check "the patch carries the list" "$patch" 'id="ruokalista"'
check "and both forms, so an open one closes" "$patch" 'id="paaruoka"'
check "the row it patches in is asking" "$patch" "Poista?"
check "patches are served as an event stream" \
"$(curl -s -o /dev/null -w '%{content_type}' -u ":$pass" -H 'Datastar-Request: true' \
"http://$addr/ruuat/nayta")" "text/event-stream"
check "deleting from Datastar patches too" \
"$(curl -s -u ":$pass" -H 'Datastar-Request: true' \
-d "id=$uusi&tyyppi=paa" "http://$addr/ruuat/poista")" \
"event: datastar-patch-elements"
refute "and the dish is gone from the patched list" \
"$(curl -s -u ":$pass" -H 'Datastar-Request: true' "http://$addr/ruuat/nayta")" \
"Uunikala"
# Without the header it must still be an ordinary redirect, for no JavaScript.
check "a plain form post still redirects" \
"$(curl -s -o /dev/null -w '%{redirect_url}' -u ":$pass" \
-d 'nimi=Testiruoka&kategoria=fish' "http://$addr/ruuat/paaruoka")" \
"/ruuat"
refute "the dish is gone once confirmed" \ refute "the dish is gone once confirmed" \
"$(curl -s -u ":$pass" "http://$addr/ruuat")" "Uunikala" "$(curl -s -u ":$pass" "http://$addr/ruuat")" "Uunikala"
+10 -47
View File
@@ -1,56 +1,19 @@
{ {
"mains": [ "mains": [
{"name": "Jauheliha-perunasiivu pelti", "categories": ["meat"], "has_sides": false}, {"name": "Uunilohi", "categories": ["fish"], "has_sides": true},
{"name": "Jauhelihakastike", "categories": ["meat"], "has_sides": true}, {"name": "Lasagnette", "categories": ["meat"], "has_sides": false},
{"name": "Jauhelihakeitto", "categories": ["meat"], "has_sides": false}, {"name": "Jauhelihakastike", "categories": ["meat"], "has_sides": true},
{"name": "Jauhelihapihvit", "categories": ["meat"], "has_sides": true}, {"name": "Risotto", "categories": ["vegetarian"], "has_sides": false},
{"name": "Kebab", "categories": ["meat"], "has_sides": true}, {"name": "Pakastepizza", "categories": ["meat"], "has_sides": false},
{"name": "Kinkkukiusaus", "categories": ["meat"], "has_sides": false}, {"name": "Kanakeitto", "categories": ["chicken"], "has_sides": false},
{"name": "Lasagnette", "categories": ["meat"], "has_sides": false}, {"name": "Kasvissosekeitto", "categories": ["vegetarian"], "has_sides": false}
{"name": "Lihapullat/pihvit", "categories": ["meat"], "has_sides": true},
{"name": "Makaronilaatikko", "categories": ["meat"], "has_sides": false},
{"name": "Makaronimössö", "categories": ["meat"], "has_sides": false},
{"name": "Maksalaatikko", "categories": ["meat"], "has_sides": false},
{"name": "Nachopelti", "categories": ["meat"], "has_sides": false},
{"name": "Nakkikeitto", "categories": ["meat"], "has_sides": false},
{"name": "Pakastepizza", "categories": ["meat"], "has_sides": false},
{"name": "Possunsuikalekastike", "categories": ["meat"], "has_sides": true},
{"name": "Possurisotto", "categories": ["meat"], "has_sides": false},
{"name": "Pyttipannu", "categories": ["meat"], "has_sides": false},
{"name": "Uuniliha", "categories": ["meat"], "has_sides": true},
{"name": "Uunimakkara", "categories": ["meat"], "has_sides": true},
{"name": "Broilerin koipireidet", "categories": ["chicken"], "has_sides": true},
{"name": "Kanakastike", "categories": ["chicken"], "has_sides": true},
{"name": "Kanakeitto", "categories": ["chicken"], "has_sides": false},
{"name": "Kanamakaronilaatikko", "categories": ["chicken"], "has_sides": false},
{"name": "Kanapasta", "categories": ["chicken"], "has_sides": false},
{"name": "Kanarisotto", "categories": ["chicken"], "has_sides": false},
{"name": "Kalakeitto", "categories": ["fish"], "has_sides": false},
{"name": "Lohicuscus-salaatti", "categories": ["fish"], "has_sides": false},
{"name": "Lohipyörykät", "categories": ["fish"], "has_sides": true},
{"name": "Uunilohi", "categories": ["fish"], "has_sides": true},
{"name": "Uuniperunat (lohitäytteellä)", "categories": ["fish"], "has_sides": false},
{"name": "Hernekeitto", "categories": ["vegetarian"], "has_sides": false},
{"name": "Italianpata (lihaton)", "categories": ["vegetarian"], "has_sides": true},
{"name": "Kasvispihvit", "categories": ["vegetarian"], "has_sides": true},
{"name": "Kasvissosekeitto", "categories": ["vegetarian"], "has_sides": false},
{"name": "Pinaattiletut", "categories": ["vegetarian"], "has_sides": false},
{"name": "Risotto", "categories": ["vegetarian"], "has_sides": false},
{"name": "Tortillat", "categories": ["meat", "chicken", "fish", "vegetarian"], "has_sides": false}
], ],
"sides": [ "sides": [
{"name": "Keitetyt perunat"}, {"name": "Keitetyt perunat"},
{"name": "Lohkoperunat"},
{"name": "Muusi"},
{"name": "Pasta"},
{"name": "Ranskalaiset"}, {"name": "Ranskalaiset"},
{"name": "Lohkoperunat"},
{"name": "Muussi"},
{"name": "Riisi"}, {"name": "Riisi"},
{"name": "Spagetti"}, {"name": "Pasta"}
{"name": "Tillikastike"},
{"name": "Wokkivihannekset"}
] ]
} }