14 Commits
Author SHA1 Message Date
sbstp f480407927 update htmx to latest in 2.x branch
ci/woodpecker/push/e2e Pipeline was successful
ci/woodpecker/push/fmt Pipeline was successful
ci/woodpecker/push/test Pipeline was successful
ci/woodpecker/tag/release Pipeline was successful
2026-08-07 22:53:42 -04:00
sbstp 9267786371 cargo fmt
ci/woodpecker/push/fmt Pipeline is pending
ci/woodpecker/push/test Pipeline is pending
ci/woodpecker/push/e2e Pipeline was canceled
2026-08-07 22:49:50 -04:00
sbstp e24f4ff7e2 archived list count 2026-08-07 22:49:31 -04:00
sbstp 56cd6e32e9 hx boost + bug fix 2026-08-07 22:46:53 -04:00
sbstp 689bd95ff0 list archive
ci/woodpecker/push/e2e Pipeline was successful
ci/woodpecker/push/fmt Pipeline failed
ci/woodpecker/push/test Pipeline was successful
2026-08-07 22:16:29 -04:00
sbstp 240d993d57 improve ux 2026-08-07 21:42:38 -04:00
sbstp c2f6b07742 version 0.4.0 [skip ci]
ci/woodpecker/tag/release Pipeline was successful
2026-08-04 00:06:03 -04:00
sbstp 863d43ef8c record meals that were added to list, allow delete with ingredients
ci/woodpecker/push/e2e Pipeline was successful
ci/woodpecker/push/fmt Pipeline was successful
ci/woodpecker/push/test Pipeline was successful
2026-08-04 00:01:23 -04:00
sbstp dcd1203d31 fix width of passkey button
ci/woodpecker/push/e2e Pipeline was successful
ci/woodpecker/push/fmt Pipeline was successful
ci/woodpecker/push/test Pipeline was successful
2026-08-03 22:36:40 -04:00
sbstp 5638fc4979 fmt & version 0.3.0 [skip ci]
ci/woodpecker/tag/release Pipeline was successful
2026-08-03 21:35:40 -04:00
sbstp 3695fc68d6 meal categories
ci/woodpecker/push/e2e Pipeline was successful
ci/woodpecker/push/fmt Pipeline failed
ci/woodpecker/push/test Pipeline was successful
2026-08-03 21:29:33 -04:00
sbstp cf6853d71e show/hide password button 2026-08-03 21:02:03 -04:00
sbstp fdbf40adac style updates 2026-08-03 14:58:10 -04:00
sbstp a6482ddb0e reset/update password
ci/woodpecker/push/e2e Pipeline was successful
ci/woodpecker/push/fmt Pipeline failed
ci/woodpecker/push/test Pipeline was successful
2026-08-03 11:33:24 -04:00
21 changed files with 1884 additions and 193 deletions
Generated
+1 -1
View File
@@ -1772,7 +1772,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]] [[package]]
name = "sustenance" name = "sustenance"
version = "0.2.0" version = "0.4.0"
dependencies = [ dependencies = [
"argon2", "argon2",
"async-trait", "async-trait",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "sustenance" name = "sustenance"
version = "0.2.0" version = "0.4.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
+9 -1
View File
@@ -11,9 +11,17 @@ export async function registerAndLogin(page: Page, email: string) {
} }
/** Creates a meal with the given name and markdown description. */ /** Creates a meal with the given name and markdown description. */
export async function createMeal(page: Page, name: string, description: string) { export async function createMeal(
page: Page,
name: string,
description: string,
category?: string,
) {
await page.goto("/meals/new"); await page.goto("/meals/new");
await page.fill("#meal-name", name); await page.fill("#meal-name", name);
if (category) {
await page.selectOption("#meal-category", { label: category });
}
await page.fill("#meal-description", description); await page.fill("#meal-description", description);
await page.click('button:has-text("Save meal")'); await page.click('button:has-text("Save meal")');
await expect(page).toHaveURL(/\/meals\/\d+/); await expect(page).toHaveURL(/\/meals\/\d+/);
+44
View File
@@ -52,3 +52,47 @@ test("the add-meal picker closes when clicking outside", async ({ page }) => {
await page.mouse.click(10, 10); await page.mouse.click(10, 10);
await expect(picker).toHaveCount(0); await expect(picker).toHaveCount(0);
}); });
test("a meal added to a list is shown in the meals panel", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createMealWithIngredients(page, "Spaghetti Bolognese", [
{ name: "Penne", quantity: "500g" },
{ name: "Tomato", quantity: "2" },
]);
await createList(page, "Weekly shop");
await page.click(".add-meal-button");
const picker = page.locator(".meal-picker-backdrop");
await picker.locator(".meal-picker-button").filter({ hasText: "Spaghetti Bolognese" }).click();
// The meal appears in the "Meals on this list" panel.
const panel = page.locator("#list-meals-panel");
await expect(panel).toBeVisible();
await expect(panel.locator(".list-meal-row").filter({ hasText: "Spaghetti Bolognese" })).toBeVisible();
});
test("removing a meal from a list removes its ingredients", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createMealWithIngredients(page, "Spaghetti Bolognese", [
{ name: "Penne", quantity: "500g" },
{ name: "Tomato", quantity: "2" },
]);
await createList(page, "Weekly shop");
await page.click(".add-meal-button");
const picker = page.locator(".meal-picker-backdrop");
await picker.locator(".meal-picker-button").filter({ hasText: "Spaghetti Bolognese" }).click();
await expect(page.locator(".item-row").filter({ hasText: "Penne" })).toBeVisible();
await expect(page.locator(".item-row").filter({ hasText: "Tomato" })).toBeVisible();
// Remove the meal from the list.
const panel = page.locator("#list-meals-panel");
const row = panel.locator(".list-meal-row").filter({ hasText: "Spaghetti Bolognese" });
await row.locator(".list-meal-remove-button").click();
// The meal's ingredients are removed from the list.
await expect(page.locator(".item-row").filter({ hasText: "Penne" })).toHaveCount(0);
await expect(page.locator(".item-row").filter({ hasText: "Tomato" })).toHaveCount(0);
await expect(row).toHaveCount(0);
});
+83
View File
@@ -0,0 +1,83 @@
import { expect } from "@playwright/test";
import { test } from "../fixtures";
import { registerAndLogin, createList, addItem } from "../helpers";
test("a user can archive a list and it moves to the archive page", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createList(page, "Weekly shop");
// Archive from the list page.
await page.click('button:has-text("Archive")');
// Lands back on the lists page; the list is no longer shown.
await expect(page).toHaveURL(/\/lists/);
await expect(page.locator(".list-card").filter({ hasText: "Weekly shop" })).toHaveCount(0);
// The archived list is reachable from the archive page.
await page.goto("/archive");
await expect(page.locator(".list-card").filter({ hasText: "Weekly shop" })).toBeVisible();
});
test("the lists frame links to the archive page", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createList(page, "Weekly shop");
await page.goto("/lists");
await page.click('a.archive-link');
await expect(page).toHaveURL(/\/archive/);
});
test("an archived list is read-only", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createList(page, "Weekly shop");
await addItem(page, "Apple");
await page.click('button:has-text("Archive")');
// Open the archived list directly.
await page.goto("/archive");
await page.locator(".list-card").filter({ hasText: "Weekly shop" }).click();
await expect(page).toHaveURL(/\/lists\/\d+/);
// The item is still visible.
await expect(page.locator(".item-row").filter({ hasText: "Apple" })).toBeVisible();
// No mutation UI is present.
await expect(page.locator("#add-item-form")).toHaveCount(0);
await expect(page.locator(".item-actions-button")).toHaveCount(0);
await expect(page.locator(".check-form")).toHaveCount(0);
await expect(page.locator('button:has-text("+ Add meal")')).toHaveCount(0);
});
test("a user can restore an archived list and edit it again", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createList(page, "Weekly shop");
await addItem(page, "Apple");
await page.click('button:has-text("Archive")');
// Open the archived list and restore it.
await page.goto("/archive");
await page.locator(".list-card").filter({ hasText: "Weekly shop" }).click();
await page.click('button:has-text("Restore")');
// Back on the lists page, the list is active again.
await expect(page).toHaveURL(/\/lists/);
await expect(page.locator(".list-card").filter({ hasText: "Weekly shop" })).toBeVisible();
// The list is editable again.
await page.locator(".list-card").filter({ hasText: "Weekly shop" }).click();
await expect(page.locator("#add-item-form")).toBeVisible();
await addItem(page, "Banana");
await expect(page.locator(".item-row").filter({ hasText: "Banana" })).toBeVisible();
});
test("the archive page shows the list name and created date", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createList(page, "Weekly shop");
await page.click('button:has-text("Archive")');
await page.goto("/archive");
const card = page.locator(".list-card").filter({ hasText: "Weekly shop" });
await expect(card).toBeVisible();
// The card shows a created date (e.g. "Created 7 Aug 2026").
await expect(card.locator("small")).toContainText("Created");
});
+30
View File
@@ -13,3 +13,33 @@ test("a user can log out", async ({ page }) => {
await expect(page).toHaveURL(/\/login/); await expect(page).toHaveURL(/\/login/);
await expect(page.locator("h1")).toContainText("Welcome back"); await expect(page.locator("h1")).toContainText("Welcome back");
}); });
test("a user can change their password", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await page.goto("/account");
await page.fill("#new-password", "a-new-strong-password");
await page.fill("#confirm-password", "a-new-strong-password");
await page.click('button:has-text("Update password")');
await expect(page.locator(".alert-success")).toContainText("updated");
// The old password no longer works; the new one does.
await page.click('button:has-text("Sign out")');
await page.fill("#email", "alice@example.com");
await page.fill("#password", "a-strong-password");
await page.click('button[type="submit"]');
await expect(page.locator(".alert-error")).toContainText("incorrect");
await page.fill("#email", "alice@example.com");
await page.fill("#password", "a-new-strong-password");
await page.click('button[type="submit"]');
await expect(page).toHaveURL(/\/lists/);
});
test("changing password rejects a mismatched confirmation", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await page.goto("/account");
await page.fill("#new-password", "a-new-strong-password");
await page.fill("#confirm-password", "a-different-password");
await page.click('button:has-text("Update password")');
await expect(page.locator(".alert-error")).toContainText("do not match");
});
+2
View File
@@ -84,6 +84,8 @@ test("a user can add a category", async ({ page }) => {
await registerAndLogin(page, "alice@example.com"); await registerAndLogin(page, "alice@example.com");
await createList(page, "Weekly shop"); await createList(page, "Weekly shop");
// Categories are managed from the main lists page.
await page.goto("/lists");
await page.fill("#category-name", "Bakery"); await page.fill("#category-name", "Bakery");
await page.click("#add-category-button"); await page.click("#add-category-button");
+111
View File
@@ -0,0 +1,111 @@
import { expect } from "@playwright/test";
import { test } from "../fixtures";
import { registerAndLogin, createMeal } from "../helpers";
test("meals are grouped under their category on the meals page", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createMeal(page, "Beef Stew", "", "Beef");
await createMeal(page, "Chicken Curry", "", "Chicken");
await createMeal(page, "Plain Rice", "");
await page.goto("/meals");
// Each category appears as a heading with its meals beneath it.
const beef = page.locator(".category-group").filter({ hasText: "Beef" });
await expect(beef.locator(".category-heading")).toContainText("Beef");
await expect(beef.locator(".list-card").filter({ hasText: "Beef Stew" })).toBeVisible();
const chicken = page.locator(".category-group").filter({ hasText: "Chicken" });
await expect(chicken.locator(".list-card").filter({ hasText: "Chicken Curry" })).toBeVisible();
// Uncategorized meals land in their own group.
const uncategorized = page.locator(".category-group").filter({ hasText: "Uncategorized" });
await expect(uncategorized.locator(".list-card").filter({ hasText: "Plain Rice" })).toBeVisible();
});
test("a user can create a meal category", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await page.goto("/meals");
await page.fill('form[action="/meals/categories"] input[name="name"]', "Breakfast");
await page.click('form[action="/meals/categories"] button[type="submit"]');
await expect(page).toHaveURL(/\/meals$/);
await expect(page.locator(".meal-category-name").filter({ hasText: "Breakfast" })).toBeVisible();
});
test("a user can delete a meal category and its meals become uncategorized", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
// Create a custom category and a meal in it.
await page.goto("/meals");
await page.fill('form[action="/meals/categories"] input[name="name"]', "Breakfast");
await page.click('form[action="/meals/categories"] button[type="submit"]');
await expect(page).toHaveURL(/\/meals$/);
await createMeal(page, "Pancakes", "", "Breakfast");
// Delete the category.
await page.goto("/meals");
const row = page.locator(".meal-category-row").filter({ hasText: "Breakfast" });
await row.locator(".meal-category-delete").click();
await expect(page).toHaveURL(/\/meals$/);
// The category is gone and the meal is now uncategorized.
await expect(page.locator(".meal-category-name").filter({ hasText: "Breakfast" })).toHaveCount(0);
const uncategorized = page.locator(".category-group").filter({ hasText: "Uncategorized" });
await expect(uncategorized.locator(".list-card").filter({ hasText: "Pancakes" })).toBeVisible();
});
test("a user can change a meal's category via the edit modal", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createMeal(page, "Beef Stew", "", "Beef");
await page.click('button:has-text("Edit")');
const dialog = page.locator("dialog#meal-edit-modal");
await expect(dialog).toBeVisible();
await dialog.locator("#meal-edit-category").selectOption({ label: "Chicken" });
await dialog.locator("#meal-edit-save").click();
await expect(page).toHaveURL(/\/meals\/\d+/);
await page.goto("/meals");
const chicken = page.locator(".category-group").filter({
has: page.locator(".category-heading", { hasText: "Chicken" }),
});
await expect(chicken.locator(".list-card").filter({ hasText: "Beef Stew" })).toBeVisible();
const beef = page.locator(".category-group").filter({
has: page.locator(".category-heading", { hasText: "Beef" }),
});
await expect(beef.locator(".list-card").filter({ hasText: "Beef Stew" })).toHaveCount(0);
});
test("a meal's category is shown on its page", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createMeal(page, "Beef Stew", "", "Beef");
await expect(page.locator(".meal-category-label")).toHaveText("(Beef)");
});
test("the add-meal picker groups meals by category", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createMeal(page, "Beef Stew", "", "Beef");
await createMeal(page, "Chicken Curry", "", "Chicken");
// Go to a list to open the picker.
await page.goto("/lists");
await page.fill("#list-name", "Weekly shop");
await page.click('button:has-text("Create list")');
await expect(page).toHaveURL(/\/lists\/\d+/);
await page.click(".add-meal-button");
const picker = page.locator(".meal-picker-backdrop");
await expect(picker).toBeVisible();
const beef = picker.locator(".category-group").filter({ hasText: "Beef" });
await expect(beef.locator(".meal-picker-button").filter({ hasText: "Beef Stew" })).toBeVisible();
const chicken = picker.locator(".category-group").filter({ hasText: "Chicken" });
await expect(chicken.locator(".meal-picker-button").filter({ hasText: "Chicken Curry" })).toBeVisible();
});
+1
View File
@@ -32,6 +32,7 @@ test("a user can delete a meal", async ({ page }) => {
await registerAndLogin(page, "alice@example.com"); await registerAndLogin(page, "alice@example.com");
await createMeal(page, "Spaghetti Bolognese", ""); await createMeal(page, "Spaghetti Bolognese", "");
page.on("dialog", (dialog) => dialog.accept());
await page.click('button:has-text("Delete")'); await page.click('button:has-text("Delete")');
await expect(page).toHaveURL(/\/meals$/); await expect(page).toHaveURL(/\/meals$/);
await expect(page.locator(".list-card").filter({ hasText: "Spaghetti Bolognese" })).toHaveCount(0); await expect(page.locator(".list-card").filter({ hasText: "Spaghetti Bolognese" })).toHaveCount(0);
@@ -0,0 +1,10 @@
CREATE TABLE meal_categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
position INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
ALTER TABLE meals ADD COLUMN category_id INTEGER REFERENCES meal_categories(id) ON DELETE SET NULL;
CREATE INDEX meals_category_idx ON meals(category_id);
+12
View File
@@ -0,0 +1,12 @@
CREATE TABLE list_meals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
list_id INTEGER NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
meal_id INTEGER REFERENCES meals(id) ON DELETE SET NULL,
name TEXT NOT NULL,
created_at INTEGER NOT NULL
);
ALTER TABLE items ADD COLUMN list_meal_id INTEGER REFERENCES list_meals(id) ON DELETE CASCADE;
CREATE INDEX list_meals_list_idx ON list_meals(list_id);
CREATE INDEX items_list_meal_idx ON items(list_meal_id);
@@ -0,0 +1 @@
ALTER TABLE lists ADD COLUMN archived_at INTEGER;
+26
View File
@@ -31,6 +31,9 @@ pub struct Passkey {
pub user_id: i64, pub user_id: i64,
pub credential_id: String, pub credential_id: String,
pub credential: String, pub credential: String,
/// WebAuthn sign counter, persisted for future cloned-authenticator
/// detection. Not currently read by application logic.
#[allow(dead_code)]
pub counter: i64, pub counter: i64,
} }
@@ -45,6 +48,10 @@ pub struct GroceryList {
pub id: i64, pub id: i64,
pub name: String, pub name: String,
pub revision: i64, pub revision: i64,
/// Unix timestamp of when the list was created.
pub created_at: i64,
/// Unix timestamp of when the list was archived; `None` when active.
pub archived_at: Option<i64>,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@@ -65,11 +72,18 @@ pub struct Category {
pub name: String, pub name: String,
} }
#[derive(Clone, Debug)]
pub struct MealCategory {
pub id: i64,
pub name: String,
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Meal { pub struct Meal {
pub id: i64, pub id: i64,
pub name: String, pub name: String,
pub description: String, pub description: String,
pub category_id: Option<i64>,
pub ingredients: Vec<MealIngredient>, pub ingredients: Vec<MealIngredient>,
} }
@@ -82,6 +96,18 @@ pub struct MealIngredient {
pub category_id: Option<i64>, pub category_id: Option<i64>,
} }
#[derive(Clone, Debug)]
pub struct ListMeal {
pub id: i64,
/// The catalog meal this instance came from; `None` once the meal is deleted.
#[allow(dead_code)]
pub meal_id: Option<i64>,
pub name: String,
/// When the meal was added to the list.
#[allow(dead_code)]
pub created_at: i64,
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct PresenceUser { pub struct PresenceUser {
pub user_id: i64, pub user_id: i64,
+229 -22
View File
@@ -14,6 +14,7 @@ use axum::{
routing::{get, post}, routing::{get, post},
}; };
use futures_util::{SinkExt, StreamExt}; use futures_util::{SinkExt, StreamExt};
use maud::PreEscaped;
use serde::{Deserialize, de::DeserializeOwned}; use serde::{Deserialize, de::DeserializeOwned};
use thiserror::Error; use thiserror::Error;
use tower_http::trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer}; use tower_http::trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer};
@@ -30,6 +31,7 @@ use crate::webauthn::WebAuthnService;
const STYLE_CSS: &[u8] = include_bytes!("../static/style.css"); const STYLE_CSS: &[u8] = include_bytes!("../static/style.css");
const PASSKEY_LOGIN_JS: &[u8] = include_bytes!("../static/passkey-login.js"); const PASSKEY_LOGIN_JS: &[u8] = include_bytes!("../static/passkey-login.js");
const PASSKEY_REGISTER_JS: &[u8] = include_bytes!("../static/passkey-register.js"); const PASSKEY_REGISTER_JS: &[u8] = include_bytes!("../static/passkey-register.js");
const PASSWORD_TOGGLE_JS: &[u8] = include_bytes!("../static/password-toggle.js");
#[derive(Clone)] #[derive(Clone)]
pub struct AppState { pub struct AppState {
@@ -51,6 +53,8 @@ pub enum AppError {
BadRequest(String), BadRequest(String),
#[error("not found")] #[error("not found")]
NotFound, NotFound,
#[error("list is archived")]
Archived,
} }
impl IntoResponse for AppError { impl IntoResponse for AppError {
@@ -70,6 +74,10 @@ impl IntoResponse for AppError {
StatusCode::NOT_FOUND, StatusCode::NOT_FOUND,
views::error_page("404", "That page could not be found."), views::error_page("404", "That page could not be found."),
), ),
AppError::Archived => status_html_response(
StatusCode::CONFLICT,
views::error_page("409", "This list is archived and cannot be modified."),
),
} }
} }
} }
@@ -92,8 +100,12 @@ pub fn build_router(state: AppState) -> Router {
"/account/passkeys/{passkey_id}/delete", "/account/passkeys/{passkey_id}/delete",
post(delete_passkey), post(delete_passkey),
) )
.route("/account/password", post(change_password))
.route("/lists", get(lists_page).post(create_list)) .route("/lists", get(lists_page).post(create_list))
.route("/archive", get(archive_page))
.route("/lists/{list_id}", get(list_page)) .route("/lists/{list_id}", get(list_page))
.route("/lists/{list_id}/archive", post(archive_list))
.route("/lists/{list_id}/unarchive", post(unarchive_list))
.route("/lists/{list_id}/items", post(add_item)) .route("/lists/{list_id}/items", post(add_item))
.route("/lists/{list_id}/items/{item_id}/check", post(check_item)) .route("/lists/{list_id}/items/{item_id}/check", post(check_item))
.route("/lists/{list_id}/items/{item_id}/edit", post(edit_item)) .route("/lists/{list_id}/items/{item_id}/edit", post(edit_item))
@@ -102,6 +114,11 @@ pub fn build_router(state: AppState) -> Router {
.route("/invitations", post(create_invitation)) .route("/invitations", post(create_invitation))
.route("/meals", get(meals_page).post(create_meal)) .route("/meals", get(meals_page).post(create_meal))
.route("/meals/new", get(new_meal_page)) .route("/meals/new", get(new_meal_page))
.route("/meals/categories", post(create_meal_category))
.route(
"/meals/categories/{category_id}/delete",
post(delete_meal_category),
)
.route("/meals/{meal_id}", get(meal_page)) .route("/meals/{meal_id}", get(meal_page))
.route("/meals/{meal_id}/edit", post(edit_meal)) .route("/meals/{meal_id}/edit", post(edit_meal))
.route("/meals/{meal_id}/delete", post(delete_meal)) .route("/meals/{meal_id}/delete", post(delete_meal))
@@ -115,6 +132,10 @@ pub fn build_router(state: AppState) -> Router {
post(delete_ingredient), post(delete_ingredient),
) )
.route("/lists/{list_id}/add-meal", post(add_meal_to_list)) .route("/lists/{list_id}/add-meal", post(add_meal_to_list))
.route(
"/lists/{list_id}/meals/{list_meal_id}/remove",
post(remove_meal_from_list),
)
.route("/lists/{list_id}/stream", get(list_stream)) .route("/lists/{list_id}/stream", get(list_stream))
.route("/invite/{token}", get(invitation_page)) .route("/invite/{token}", get(invitation_page))
.route("/invite/{token}/accept", post(accept_invitation)) .route("/invite/{token}/accept", post(accept_invitation))
@@ -274,11 +295,20 @@ struct DeletePasskeyForm {
csrf: String, csrf: String,
} }
#[derive(Debug, Deserialize)]
struct ChangePasswordForm {
csrf: String,
new_password: String,
confirm_password: String,
}
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct MealForm { struct MealForm {
name: String, name: String,
#[serde(default)] #[serde(default)]
description: String, description: String,
#[serde(default)]
category_id: Option<String>,
csrf: String, csrf: String,
} }
@@ -315,6 +345,7 @@ async fn static_asset(Path(path): Path<String>) -> Response {
"style.css" => ("text/css", STYLE_CSS), "style.css" => ("text/css", STYLE_CSS),
"passkey-login.js" => ("application/javascript", PASSKEY_LOGIN_JS), "passkey-login.js" => ("application/javascript", PASSKEY_LOGIN_JS),
"passkey-register.js" => ("application/javascript", PASSKEY_REGISTER_JS), "passkey-register.js" => ("application/javascript", PASSKEY_REGISTER_JS),
"password-toggle.js" => ("application/javascript", PASSWORD_TOGGLE_JS),
_ => return StatusCode::NOT_FOUND.into_response(), _ => return StatusCode::NOT_FOUND.into_response(),
}; };
([(header::CONTENT_TYPE, mime)], data).into_response() ([(header::CONTENT_TYPE, mime)], data).into_response()
@@ -448,9 +479,42 @@ async fn account_page(
&user.session.user, &user.session.user,
&passkeys, &passkeys,
&user.session.csrf_token, &user.session.csrf_token,
None,
false,
))) )))
} }
async fn change_password(
State(state): State<AppState>,
user: CurrentUser,
LoggedForm(form): LoggedForm<ChangePasswordForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
let passkeys = state.webauthn.list_passkeys(user.session.user.id).await?;
let render = |error: Option<&str>, success: bool| {
html_response(views::account_page(
&user.session.user,
&passkeys,
&user.session.csrf_token,
error,
success,
))
};
if form.new_password != form.confirm_password {
return Ok(render(
Some("New password and confirmation do not match."),
false,
));
}
state
.auth
.change_password(user.session.user.id, form.new_password)
.await?;
Ok(render(None, true))
}
async fn passkey_register_start( async fn passkey_register_start(
State(state): State<AppState>, State(state): State<AppState>,
user: CurrentUser, user: CurrentUser,
@@ -539,13 +603,28 @@ async fn lists_page(
user: CurrentUser, user: CurrentUser,
) -> Result<Response, AppError> { ) -> Result<Response, AppError> {
let lists = state.lists.list_summaries().await?; let lists = state.lists.list_summaries().await?;
let archived = state.lists.list_archived_summaries().await?;
let categories = state.lists.categories().await?;
Ok(html_response(views::lists_page( Ok(html_response(views::lists_page(
&user.session.user, &user.session.user,
&lists, &lists,
archived.len(),
&categories,
&user.session.csrf_token, &user.session.csrf_token,
))) )))
} }
async fn archive_page(
State(state): State<AppState>,
user: CurrentUser,
) -> Result<Response, AppError> {
let archived_lists = state.lists.list_archived_summaries().await?;
Ok(html_response(views::archive_page(
&user.session.user,
&archived_lists,
)))
}
async fn create_list( async fn create_list(
State(state): State<AppState>, State(state): State<AppState>,
user: CurrentUser, user: CurrentUser,
@@ -570,17 +649,43 @@ async fn list_page(
let access = require_list(&state, list_id).await?; let access = require_list(&state, list_id).await?;
let items = state.lists.items(list_id).await?; let items = state.lists.items(list_id).await?;
let categories = state.lists.categories().await?; let categories = state.lists.categories().await?;
let list_meals = state.meals.list_meals_on_list(list_id).await?;
let presence = state.realtime.presence(list_id).await; let presence = state.realtime.presence(list_id).await;
Ok(html_response(views::list_page( Ok(html_response(views::list_page(
&user.session.user, &user.session.user,
&access, &access,
&items, &items,
&categories, &categories,
&list_meals,
&presence, &presence,
&user.session.csrf_token, &user.session.csrf_token,
))) )))
} }
async fn archive_list(
State(state): State<AppState>,
user: CurrentUser,
Path(list_id): Path<i64>,
LoggedForm(form): LoggedForm<CsrfForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
require_list(&state, list_id).await?;
state.lists.archive_list(list_id).await?;
Ok(Redirect::to("/lists").into_response())
}
async fn unarchive_list(
State(state): State<AppState>,
user: CurrentUser,
Path(list_id): Path<i64>,
LoggedForm(form): LoggedForm<CsrfForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
require_list(&state, list_id).await?;
state.lists.unarchive_list(list_id).await?;
Ok(Redirect::to("/lists").into_response())
}
async fn add_item( async fn add_item(
State(state): State<AppState>, State(state): State<AppState>,
user: CurrentUser, user: CurrentUser,
@@ -588,7 +693,7 @@ async fn add_item(
LoggedForm(form): LoggedForm<ItemForm>, LoggedForm(form): LoggedForm<ItemForm>,
) -> Result<Response, AppError> { ) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?; verify_csrf(&user, &form.csrf)?;
require_list(&state, list_id).await?; require_mutable_list(&state, list_id).await?;
let name = form.name.trim().to_owned(); let name = form.name.trim().to_owned();
let quantity = form.quantity.trim().to_owned(); let quantity = form.quantity.trim().to_owned();
let note = form.note.trim().to_owned(); let note = form.note.trim().to_owned();
@@ -612,7 +717,7 @@ async fn check_item(
LoggedForm(form): LoggedForm<CheckForm>, LoggedForm(form): LoggedForm<CheckForm>,
) -> Result<Response, AppError> { ) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?; verify_csrf(&user, &form.csrf)?;
require_list(&state, list_id).await?; require_mutable_list(&state, list_id).await?;
let checked = match form.checked.as_str() { let checked = match form.checked.as_str() {
"1" | "true" => true, "1" | "true" => true,
"0" | "false" => false, "0" | "false" => false,
@@ -632,7 +737,7 @@ async fn edit_item(
LoggedForm(form): LoggedForm<ItemForm>, LoggedForm(form): LoggedForm<ItemForm>,
) -> Result<Response, AppError> { ) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?; verify_csrf(&user, &form.csrf)?;
require_list(&state, list_id).await?; require_mutable_list(&state, list_id).await?;
let name = form.name.trim().to_owned(); let name = form.name.trim().to_owned();
if name.is_empty() || name.chars().count() > 120 { if name.is_empty() || name.chars().count() > 120 {
return Err(AppError::BadRequest( return Err(AppError::BadRequest(
@@ -660,7 +765,7 @@ async fn delete_item(
LoggedForm(form): LoggedForm<CsrfForm>, LoggedForm(form): LoggedForm<CsrfForm>,
) -> Result<Response, AppError> { ) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?; verify_csrf(&user, &form.csrf)?;
require_list(&state, list_id).await?; require_mutable_list(&state, list_id).await?;
state.lists.delete_item(list_id, item_id).await?; state.lists.delete_item(list_id, item_id).await?;
list_fragment_response(&state, &user, list_id).await list_fragment_response(&state, &user, list_id).await
} }
@@ -681,26 +786,65 @@ async fn create_category(
Ok(Redirect::to("/lists").into_response()) Ok(Redirect::to("/lists").into_response())
} }
async fn create_meal_category(
State(state): State<AppState>,
user: CurrentUser,
LoggedForm(form): LoggedForm<CategoryForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
let name = form.name.trim().to_owned();
if name.is_empty() || name.chars().count() > 60 {
return Err(AppError::BadRequest(
"Category names must be between 1 and 60 characters.".into(),
));
}
state.meals.create_meal_category(name).await?;
Ok(Redirect::to("/meals").into_response())
}
async fn delete_meal_category(
State(state): State<AppState>,
user: CurrentUser,
Path(category_id): Path<i64>,
LoggedForm(form): LoggedForm<CsrfForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
state.meals.delete_meal_category(category_id).await?;
Ok(Redirect::to("/meals").into_response())
}
async fn meals_page( async fn meals_page(
State(state): State<AppState>, State(state): State<AppState>,
user: CurrentUser, user: CurrentUser,
Query(query): Query<MealPickerQuery>, Query(query): Query<MealPickerQuery>,
) -> Result<Response, AppError> { ) -> Result<Response, AppError> {
let meals = state.meals.list_meals().await?; let meals = state.meals.list_meals().await?;
let meal_categories = state.meals.list_meal_categories().await?;
if let Some(list_id) = query.picker { if let Some(list_id) = query.picker {
return Ok(html_response(views::meal_picker( return Ok(html_response(views::meal_picker(
&meals, &meals,
&meal_categories,
list_id, list_id,
&user.session.csrf_token, &user.session.csrf_token,
))); )));
} }
Ok(html_response(views::meals_page(&user.session.user, &meals))) Ok(html_response(views::meals_page(
&user.session.user,
&meals,
&meal_categories,
&user.session.csrf_token,
)))
} }
async fn new_meal_page(user: CurrentUser) -> Result<Response, AppError> { async fn new_meal_page(
State(state): State<AppState>,
user: CurrentUser,
) -> Result<Response, AppError> {
let meal_categories = state.meals.list_meal_categories().await?;
Ok(html_response(views::meal_form_page( Ok(html_response(views::meal_form_page(
&user.session.user, &user.session.user,
None, None,
&meal_categories,
&user.session.csrf_token, &user.session.csrf_token,
))) )))
} }
@@ -719,7 +863,11 @@ async fn create_meal(
} }
let meal = state let meal = state
.meals .meals
.create_meal(name, form.description.trim().to_owned()) .create_meal(
name,
form.description.trim().to_owned(),
parse_category_id(form.category_id),
)
.await?; .await?;
Ok(Redirect::to(&format!("/meals/{}", meal.id)).into_response()) Ok(Redirect::to(&format!("/meals/{}", meal.id)).into_response())
} }
@@ -735,10 +883,12 @@ async fn meal_page(
.await? .await?
.ok_or(AppError::NotFound)?; .ok_or(AppError::NotFound)?;
let categories = state.lists.categories().await?; let categories = state.lists.categories().await?;
let meal_categories = state.meals.list_meal_categories().await?;
Ok(html_response(views::meal_page( Ok(html_response(views::meal_page(
&user.session.user, &user.session.user,
&meal, &meal,
&categories, &categories,
&meal_categories,
&user.session.csrf_token, &user.session.csrf_token,
))) )))
} }
@@ -758,7 +908,12 @@ async fn edit_meal(
} }
state state
.meals .meals
.update_meal(meal_id, name, form.description.trim().to_owned()) .update_meal(
meal_id,
name,
form.description.trim().to_owned(),
parse_category_id(form.category_id),
)
.await?; .await?;
Ok(Redirect::to(&format!("/meals/{meal_id}")).into_response()) Ok(Redirect::to(&format!("/meals/{meal_id}")).into_response())
} }
@@ -848,11 +1003,26 @@ async fn add_meal_to_list(
LoggedForm(form): LoggedForm<AddMealForm>, LoggedForm(form): LoggedForm<AddMealForm>,
) -> Result<Response, AppError> { ) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?; verify_csrf(&user, &form.csrf)?;
require_list(&state, list_id).await?; require_mutable_list(&state, list_id).await?;
state.meals.add_meal_to_list(form.meal_id, list_id).await?; state.meals.add_meal_to_list(form.meal_id, list_id).await?;
list_fragment_response(&state, &user, list_id).await list_fragment_response(&state, &user, list_id).await
} }
async fn remove_meal_from_list(
State(state): State<AppState>,
user: CurrentUser,
Path((list_id, list_meal_id)): Path<(i64, i64)>,
LoggedForm(form): LoggedForm<CsrfForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
require_mutable_list(&state, list_id).await?;
state
.meals
.remove_meal_from_list(list_id, list_meal_id)
.await?;
list_fragment_response(&state, &user, list_id).await
}
async fn create_invitation( async fn create_invitation(
State(state): State<AppState>, State(state): State<AppState>,
user: CurrentUser, user: CurrentUser,
@@ -1017,11 +1187,16 @@ async fn websocket_snapshot(
let access = require_list(state, list_id).await?; let access = require_list(state, list_id).await?;
let items = state.lists.items(list_id).await?; let items = state.lists.items(list_id).await?;
let categories = state.lists.categories().await?; let categories = state.lists.categories().await?;
Ok( let list_meals = state.meals.list_meals_on_list(list_id).await?;
views::live_list_fragments(&access, &items, &categories, &user.session.csrf_token) Ok(views::live_list_fragments(
.into_string() &access,
+ &views::presence_panel(presence, true).into_string(), &items,
&categories,
&list_meals,
&user.session.csrf_token,
) )
.into_string()
+ &views::presence_panel(presence, true).into_string())
} }
async fn websocket_list_update( async fn websocket_list_update(
@@ -1032,10 +1207,15 @@ async fn websocket_list_update(
let access = require_list(state, list_id).await?; let access = require_list(state, list_id).await?;
let items = state.lists.items(list_id).await?; let items = state.lists.items(list_id).await?;
let categories = state.lists.categories().await?; let categories = state.lists.categories().await?;
Ok( let list_meals = state.meals.list_meals_on_list(list_id).await?;
views::live_list_fragments(&access, &items, &categories, &user.session.csrf_token) Ok(views::live_list_fragments(
.into_string(), &access,
&items,
&categories,
&list_meals,
&user.session.csrf_token,
) )
.into_string())
} }
async fn list_fragment_response( async fn list_fragment_response(
@@ -1046,12 +1226,26 @@ async fn list_fragment_response(
let access = require_list(state, list_id).await?; let access = require_list(state, list_id).await?;
let items = state.lists.items(list_id).await?; let items = state.lists.items(list_id).await?;
let categories = state.lists.categories().await?; let categories = state.lists.categories().await?;
Ok(html_response(views::list_items_fragment( let list_meals = state.meals.list_meals_on_list(list_id).await?;
&access, let editable = access.archived_at.is_none();
&items, Ok(html_response(PreEscaped(
&categories, views::list_items_fragment(
&user.session.csrf_token, &access,
false, &items,
&categories,
&user.session.csrf_token,
false,
editable,
)
.into_string()
+ &views::list_meals_panel(
&list_meals,
list_id,
&user.session.csrf_token,
true,
editable,
)
.into_string(),
))) )))
} }
@@ -1066,6 +1260,19 @@ async fn require_list(
.ok_or(AppError::NotFound) .ok_or(AppError::NotFound)
} }
/// Like [`require_list`], but also rejects archived lists so they stay
/// immutable until restored.
async fn require_mutable_list(
state: &AppState,
list_id: i64,
) -> Result<crate::domain::GroceryList, AppError> {
let list = require_list(state, list_id).await?;
if list.archived_at.is_some() {
return Err(AppError::Archived);
}
Ok(list)
}
async fn optional_user( async fn optional_user(
state: &AppState, state: &AppState,
headers: &HeaderMap, headers: &HeaderMap,
+10 -5
View File
@@ -19,16 +19,17 @@ use tracing::{info, warn};
use crate::http::{AppState, build_router}; use crate::http::{AppState, build_router};
use crate::hub::InMemoryHub; use crate::hub::InMemoryHub;
use crate::ports::{ use crate::ports::{
CategoryRepository, InvitationRepository, ItemRepository, ListRepository, CategoryRepository, InvitationRepository, ItemRepository, ListMealRepository, ListRepository,
MealIngredientRepository, MealRepository, PasskeyRepository, PasswordHasher, RealtimeNotifier, MealCategoryRepository, MealIngredientRepository, MealRepository, PasskeyRepository,
SessionRepository, TokenGenerator, UserRepository, PasswordHasher, RealtimeNotifier, SessionRepository, TokenGenerator, UserRepository,
}; };
use crate::security::{Argon2PasswordHasher, RandomTokenGenerator}; use crate::security::{Argon2PasswordHasher, RandomTokenGenerator};
use crate::services::{AuthService, InvitationService, ListService, MealService, RegistrationMode}; use crate::services::{AuthService, InvitationService, ListService, MealService, RegistrationMode};
use crate::sqlite::{ use crate::sqlite::{
SqliteCategoryRepository, SqliteDatabase, SqliteInvitationRepository, SqliteItemRepository, SqliteCategoryRepository, SqliteDatabase, SqliteInvitationRepository, SqliteItemRepository,
SqliteListRepository, SqliteMealIngredientRepository, SqliteMealRepository, SqliteListMealRepository, SqliteListRepository, SqliteMealCategoryRepository,
SqlitePasskeyRepository, SqliteSessionRepository, SqliteUserRepository, SqliteMealIngredientRepository, SqliteMealRepository, SqlitePasskeyRepository,
SqliteSessionRepository, SqliteUserRepository,
}; };
use crate::webauthn::{AppWebauthnConfig, WebAuthnService}; use crate::webauthn::{AppWebauthnConfig, WebAuthnService};
@@ -74,9 +75,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let lists: Arc<dyn ListRepository> = Arc::new(SqliteListRepository); let lists: Arc<dyn ListRepository> = Arc::new(SqliteListRepository);
let categories: Arc<dyn CategoryRepository> = Arc::new(SqliteCategoryRepository); let categories: Arc<dyn CategoryRepository> = Arc::new(SqliteCategoryRepository);
let items: Arc<dyn ItemRepository> = Arc::new(SqliteItemRepository); let items: Arc<dyn ItemRepository> = Arc::new(SqliteItemRepository);
let list_meals: Arc<dyn ListMealRepository> = Arc::new(SqliteListMealRepository);
let meals: Arc<dyn MealRepository> = Arc::new(SqliteMealRepository); let meals: Arc<dyn MealRepository> = Arc::new(SqliteMealRepository);
let meal_ingredients: Arc<dyn MealIngredientRepository> = let meal_ingredients: Arc<dyn MealIngredientRepository> =
Arc::new(SqliteMealIngredientRepository); Arc::new(SqliteMealIngredientRepository);
let meal_categories: Arc<dyn MealCategoryRepository> = Arc::new(SqliteMealCategoryRepository);
let invitations: Arc<dyn InvitationRepository> = Arc::new(SqliteInvitationRepository); let invitations: Arc<dyn InvitationRepository> = Arc::new(SqliteInvitationRepository);
let passkeys: Arc<dyn PasskeyRepository> = Arc::new(SqlitePasskeyRepository); let passkeys: Arc<dyn PasskeyRepository> = Arc::new(SqlitePasskeyRepository);
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2PasswordHasher); let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2PasswordHasher);
@@ -107,8 +110,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
db.clone(), db.clone(),
Arc::clone(&meals), Arc::clone(&meals),
Arc::clone(&meal_ingredients), Arc::clone(&meal_ingredients),
Arc::clone(&meal_categories),
Arc::clone(&lists), Arc::clone(&lists),
Arc::clone(&items), Arc::clone(&items),
Arc::clone(&list_meals),
Arc::clone(&realtime), Arc::clone(&realtime),
)); ));
+60 -2
View File
@@ -2,8 +2,8 @@ use async_trait::async_trait;
use sqlx::SqliteConnection; use sqlx::SqliteConnection;
use crate::domain::{ use crate::domain::{
Category, DomainResult, GroceryList, Item, Meal, MealIngredient, Passkey, PresenceUser, Category, DomainResult, GroceryList, Item, ListMeal, Meal, MealCategory, MealIngredient,
SessionUser, User, Passkey, PresenceUser, SessionUser, User,
}; };
/// Repositories take `&mut SqliteConnection` (which a `Transaction` derefs to), /// Repositories take `&mut SqliteConnection` (which a `Transaction` derefs to),
@@ -29,6 +29,12 @@ pub trait UserRepository: Send + Sync {
txn: &mut SqliteConnection, txn: &mut SqliteConnection,
user_handle: Vec<u8>, user_handle: Vec<u8>,
) -> DomainResult<Option<User>>; ) -> DomainResult<Option<User>>;
async fn update_password_hash(
&self,
txn: &mut SqliteConnection,
user_id: i64,
password_hash: String,
) -> DomainResult<()>;
async fn has_users(&self, txn: &mut SqliteConnection) -> DomainResult<bool>; async fn has_users(&self, txn: &mut SqliteConnection) -> DomainResult<bool>;
} }
@@ -82,6 +88,10 @@ pub trait SessionRepository: Send + Sync {
#[async_trait] #[async_trait]
pub trait ListRepository: Send + Sync { pub trait ListRepository: Send + Sync {
async fn list_summaries(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<GroceryList>>; async fn list_summaries(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<GroceryList>>;
async fn list_archived_summaries(
&self,
txn: &mut SqliteConnection,
) -> DomainResult<Vec<GroceryList>>;
async fn create_list( async fn create_list(
&self, &self,
txn: &mut SqliteConnection, txn: &mut SqliteConnection,
@@ -92,6 +102,12 @@ pub trait ListRepository: Send + Sync {
txn: &mut SqliteConnection, txn: &mut SqliteConnection,
list_id: i64, list_id: i64,
) -> DomainResult<Option<GroceryList>>; ) -> DomainResult<Option<GroceryList>>;
async fn set_archived(
&self,
txn: &mut SqliteConnection,
list_id: i64,
archived: bool,
) -> DomainResult<()>;
} }
#[async_trait] #[async_trait]
@@ -107,6 +123,9 @@ pub struct NewItem {
pub quantity: String, pub quantity: String,
pub note: String, pub note: String,
pub category_id: Option<i64>, pub category_id: Option<i64>,
/// When set, links this item to the `list_meals` row it came from, so the
/// item is removed together with that meal instance.
pub list_meal_id: Option<i64>,
} }
#[async_trait] #[async_trait]
@@ -152,6 +171,28 @@ pub trait ItemRepository: Send + Sync {
) -> DomainResult<i64>; ) -> DomainResult<i64>;
} }
#[async_trait]
pub trait ListMealRepository: Send + Sync {
async fn list_meals(
&self,
txn: &mut SqliteConnection,
list_id: i64,
) -> DomainResult<Vec<ListMeal>>;
async fn add_meal(
&self,
txn: &mut SqliteConnection,
list_id: i64,
meal_id: i64,
name: String,
) -> DomainResult<i64>;
async fn remove_meal(
&self,
txn: &mut SqliteConnection,
list_id: i64,
list_meal_id: i64,
) -> DomainResult<i64>;
}
#[async_trait] #[async_trait]
pub trait InvitationRepository: Send + Sync { pub trait InvitationRepository: Send + Sync {
async fn create_invitation( async fn create_invitation(
@@ -168,6 +209,21 @@ pub trait InvitationRepository: Send + Sync {
) -> DomainResult<()>; ) -> DomainResult<()>;
} }
#[async_trait]
pub trait MealCategoryRepository: Send + Sync {
async fn meal_categories(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<MealCategory>>;
async fn create_meal_category(
&self,
txn: &mut SqliteConnection,
name: String,
) -> DomainResult<i64>;
async fn delete_meal_category(
&self,
txn: &mut SqliteConnection,
category_id: i64,
) -> DomainResult<()>;
}
#[async_trait] #[async_trait]
pub trait MealRepository: Send + Sync { pub trait MealRepository: Send + Sync {
async fn create_meal( async fn create_meal(
@@ -175,6 +231,7 @@ pub trait MealRepository: Send + Sync {
txn: &mut SqliteConnection, txn: &mut SqliteConnection,
name: String, name: String,
description: String, description: String,
category_id: Option<i64>,
) -> DomainResult<Meal>; ) -> DomainResult<Meal>;
async fn get_meal( async fn get_meal(
&self, &self,
@@ -188,6 +245,7 @@ pub trait MealRepository: Send + Sync {
meal_id: i64, meal_id: i64,
name: String, name: String,
description: String, description: String,
category_id: Option<i64>,
) -> DomainResult<()>; ) -> DomainResult<()>;
async fn delete_meal(&self, txn: &mut SqliteConnection, meal_id: i64) -> DomainResult<()>; async fn delete_meal(&self, txn: &mut SqliteConnection, meal_id: i64) -> DomainResult<()>;
} }
+123 -8
View File
@@ -1,10 +1,12 @@
use std::sync::Arc; use std::sync::Arc;
use crate::domain::{DomainError, DomainResult, GroceryList, Item, Meal, SessionUser, User}; use crate::domain::{
DomainError, DomainResult, GroceryList, Item, ListMeal, Meal, MealCategory, SessionUser, User,
};
use crate::ports::{ use crate::ports::{
CategoryRepository, InvitationRepository, ItemRepository, ListRepository, CategoryRepository, InvitationRepository, ItemRepository, ListMealRepository, ListRepository,
MealIngredientRepository, MealRepository, NewItem, PasswordHasher, RealtimeNotifier, MealCategoryRepository, MealIngredientRepository, MealRepository, NewItem, PasswordHasher,
SessionRepository, TokenGenerator, UserRepository, RealtimeNotifier, SessionRepository, TokenGenerator, UserRepository,
}; };
use crate::sqlite::SqliteDatabase; use crate::sqlite::SqliteDatabase;
@@ -147,6 +149,22 @@ impl AuthService {
}) })
.await .await
} }
/// Replaces the user's password hash with a freshly hashed new password.
/// No current-password check is performed because the account page is
/// already authenticated and this app has no email capabilities.
pub async fn change_password(&self, user_id: i64, new_password: String) -> DomainResult<()> {
let users = Arc::clone(&self.users);
let hasher = Arc::clone(&self.hasher);
self.db
.run(move |txn| {
Box::pin(async move {
let new_hash = hasher.hash(&new_password)?;
users.update_password_hash(txn, user_id, new_hash).await
})
})
.await
}
} }
pub struct ListService { pub struct ListService {
@@ -181,6 +199,13 @@ impl ListService {
.await .await
} }
pub async fn list_archived_summaries(&self) -> DomainResult<Vec<GroceryList>> {
let lists = Arc::clone(&self.lists);
self.db
.run(move |txn| Box::pin(async move { lists.list_archived_summaries(txn).await }))
.await
}
pub async fn create_list(&self, name: String) -> DomainResult<GroceryList> { pub async fn create_list(&self, name: String) -> DomainResult<GroceryList> {
let lists = Arc::clone(&self.lists); let lists = Arc::clone(&self.lists);
self.db self.db
@@ -195,6 +220,20 @@ impl ListService {
.await .await
} }
pub async fn archive_list(&self, list_id: i64) -> DomainResult<()> {
let lists = Arc::clone(&self.lists);
self.db
.run(move |txn| Box::pin(async move { lists.set_archived(txn, list_id, true).await }))
.await
}
pub async fn unarchive_list(&self, list_id: i64) -> DomainResult<()> {
let lists = Arc::clone(&self.lists);
self.db
.run(move |txn| Box::pin(async move { lists.set_archived(txn, list_id, false).await }))
.await
}
pub async fn items(&self, list_id: i64) -> DomainResult<Vec<Item>> { pub async fn items(&self, list_id: i64) -> DomainResult<Vec<Item>> {
let items = Arc::clone(&self.items); let items = Arc::clone(&self.items);
self.db self.db
@@ -297,8 +336,10 @@ pub struct MealService {
db: SqliteDatabase, db: SqliteDatabase,
meals: Arc<dyn MealRepository>, meals: Arc<dyn MealRepository>,
ingredients: Arc<dyn MealIngredientRepository>, ingredients: Arc<dyn MealIngredientRepository>,
meal_categories: Arc<dyn MealCategoryRepository>,
lists: Arc<dyn ListRepository>, lists: Arc<dyn ListRepository>,
items: Arc<dyn ItemRepository>, items: Arc<dyn ItemRepository>,
list_meals: Arc<dyn ListMealRepository>,
realtime: Arc<dyn RealtimeNotifier>, realtime: Arc<dyn RealtimeNotifier>,
} }
@@ -307,25 +348,36 @@ impl MealService {
db: SqliteDatabase, db: SqliteDatabase,
meals: Arc<dyn MealRepository>, meals: Arc<dyn MealRepository>,
ingredients: Arc<dyn MealIngredientRepository>, ingredients: Arc<dyn MealIngredientRepository>,
meal_categories: Arc<dyn MealCategoryRepository>,
lists: Arc<dyn ListRepository>, lists: Arc<dyn ListRepository>,
items: Arc<dyn ItemRepository>, items: Arc<dyn ItemRepository>,
list_meals: Arc<dyn ListMealRepository>,
realtime: Arc<dyn RealtimeNotifier>, realtime: Arc<dyn RealtimeNotifier>,
) -> Self { ) -> Self {
Self { Self {
db, db,
meals, meals,
ingredients, ingredients,
meal_categories,
lists, lists,
items, items,
list_meals,
realtime, realtime,
} }
} }
pub async fn create_meal(&self, name: String, description: String) -> DomainResult<Meal> { pub async fn create_meal(
&self,
name: String,
description: String,
category_id: Option<i64>,
) -> DomainResult<Meal> {
let meals = Arc::clone(&self.meals); let meals = Arc::clone(&self.meals);
self.db self.db
.run(move |txn| { .run(move |txn| {
Box::pin(async move { meals.create_meal(txn, name, description).await }) Box::pin(
async move { meals.create_meal(txn, name, description, category_id).await },
)
}) })
.await .await
} }
@@ -349,11 +401,43 @@ impl MealService {
meal_id: i64, meal_id: i64,
name: String, name: String,
description: String, description: String,
category_id: Option<i64>,
) -> DomainResult<()> { ) -> DomainResult<()> {
let meals = Arc::clone(&self.meals); let meals = Arc::clone(&self.meals);
self.db self.db
.run(move |txn| { .run(move |txn| {
Box::pin(async move { meals.update_meal(txn, meal_id, name, description).await }) Box::pin(async move {
meals
.update_meal(txn, meal_id, name, description, category_id)
.await
})
})
.await
}
pub async fn list_meal_categories(&self) -> DomainResult<Vec<MealCategory>> {
let meal_categories = Arc::clone(&self.meal_categories);
self.db
.run(move |txn| Box::pin(async move { meal_categories.meal_categories(txn).await }))
.await
}
pub async fn create_meal_category(&self, name: String) -> DomainResult<i64> {
let meal_categories = Arc::clone(&self.meal_categories);
self.db
.run(move |txn| {
Box::pin(async move { meal_categories.create_meal_category(txn, name).await })
})
.await
}
pub async fn delete_meal_category(&self, category_id: i64) -> DomainResult<()> {
let meal_categories = Arc::clone(&self.meal_categories);
self.db
.run(move |txn| {
Box::pin(
async move { meal_categories.delete_meal_category(txn, category_id).await },
)
}) })
.await .await
} }
@@ -428,11 +512,12 @@ impl MealService {
} }
/// Expands a meal's ingredients into items on a list in one unit of work, /// Expands a meal's ingredients into items on a list in one unit of work,
/// bumping the list revision exactly once. /// recording the meal on the list and bumping the list revision exactly once.
pub async fn add_meal_to_list(&self, meal_id: i64, list_id: i64) -> DomainResult<i64> { pub async fn add_meal_to_list(&self, meal_id: i64, list_id: i64) -> DomainResult<i64> {
let meals = Arc::clone(&self.meals); let meals = Arc::clone(&self.meals);
let lists = Arc::clone(&self.lists); let lists = Arc::clone(&self.lists);
let items = Arc::clone(&self.items); let items = Arc::clone(&self.items);
let list_meals = Arc::clone(&self.list_meals);
let revision = self let revision = self
.db .db
.run(move |txn| { .run(move |txn| {
@@ -444,6 +529,9 @@ impl MealService {
if lists.get_list(txn, list_id).await?.is_none() { if lists.get_list(txn, list_id).await?.is_none() {
return Err(DomainError::NotFound); return Err(DomainError::NotFound);
} }
let list_meal_id = list_meals
.add_meal(txn, list_id, meal.id, meal.name.clone())
.await?;
let new_items = meal let new_items = meal
.ingredients .ingredients
.into_iter() .into_iter()
@@ -452,6 +540,7 @@ impl MealService {
quantity: ingredient.quantity, quantity: ingredient.quantity,
note: ingredient.note, note: ingredient.note,
category_id: ingredient.category_id, category_id: ingredient.category_id,
list_meal_id: Some(list_meal_id),
}) })
.collect(); .collect();
items.add_items_bulk(txn, list_id, new_items).await items.add_items_bulk(txn, list_id, new_items).await
@@ -461,6 +550,32 @@ impl MealService {
self.realtime.publish_list_changed(list_id, revision).await; self.realtime.publish_list_changed(list_id, revision).await;
Ok(revision) Ok(revision)
} }
/// Lists the meals that have been added to a list, most recent first.
pub async fn list_meals_on_list(&self, list_id: i64) -> DomainResult<Vec<ListMeal>> {
let list_meals = Arc::clone(&self.list_meals);
self.db
.run(move |txn| Box::pin(async move { list_meals.list_meals(txn, list_id).await }))
.await
}
/// Removes a meal instance from a list, deleting the items that came from it
/// and bumping the list revision exactly once.
pub async fn remove_meal_from_list(
&self,
list_id: i64,
list_meal_id: i64,
) -> DomainResult<i64> {
let list_meals = Arc::clone(&self.list_meals);
let revision = self
.db
.run(move |txn| {
Box::pin(async move { list_meals.remove_meal(txn, list_id, list_meal_id).await })
})
.await?;
self.realtime.publish_list_changed(list_id, revision).await;
Ok(revision)
}
} }
pub struct InvitationService { pub struct InvitationService {
+588 -18
View File
@@ -7,13 +7,13 @@ use sha2::{Digest, Sha256};
use sqlx::{Connection, Row, SqliteConnection, SqlitePool, sqlite::SqliteConnectOptions}; use sqlx::{Connection, Row, SqliteConnection, SqlitePool, sqlite::SqliteConnectOptions};
use crate::domain::{ use crate::domain::{
Category, DomainError, DomainResult, GroceryList, Item, Meal, MealIngredient, Passkey, Category, DomainError, DomainResult, GroceryList, Item, ListMeal, Meal, MealCategory,
SessionUser, User, MealIngredient, Passkey, SessionUser, User,
}; };
use crate::ports::{ use crate::ports::{
CategoryRepository, InvitationRepository, ItemRepository, ListRepository, CategoryRepository, InvitationRepository, ItemRepository, ListMealRepository, ListRepository,
MealIngredientRepository, MealRepository, NewItem, PasskeyRepository, SessionRepository, MealCategoryRepository, MealIngredientRepository, MealRepository, NewItem, PasskeyRepository,
UserRepository, SessionRepository, UserRepository,
}; };
/// The embedded SQL migrations, applied automatically on startup. /// The embedded SQL migrations, applied automatically on startup.
@@ -35,6 +35,7 @@ impl SqliteDatabase {
let pool = SqlitePool::connect_with(options).await.map_err(db_error)?; let pool = SqlitePool::connect_with(options).await.map_err(db_error)?;
MIGRATOR.run(&pool).await.map_err(migrate_error)?; MIGRATOR.run(&pool).await.map_err(migrate_error)?;
seed_default_categories(&pool).await?; seed_default_categories(&pool).await?;
seed_default_meal_categories(&pool).await?;
Ok(Self { pool }) Ok(Self { pool })
} }
@@ -61,6 +62,7 @@ impl SqliteDatabase {
let pool = SqlitePool::connect_with(options).await.map_err(db_error)?; let pool = SqlitePool::connect_with(options).await.map_err(db_error)?;
MIGRATOR.run(&pool).await.map_err(migrate_error)?; MIGRATOR.run(&pool).await.map_err(migrate_error)?;
seed_default_categories(&pool).await?; seed_default_categories(&pool).await?;
seed_default_meal_categories(&pool).await?;
Ok(Self { pool }) Ok(Self { pool })
} }
} }
@@ -117,6 +119,28 @@ async fn seed_default_categories(pool: &SqlitePool) -> DomainResult<()> {
Ok(()) Ok(())
} }
/// Inserts the default meal categories once, if the meal_categories table is empty.
async fn seed_default_meal_categories(pool: &SqlitePool) -> DomainResult<()> {
let count: i64 = sqlx::query("SELECT COUNT(*) FROM meal_categories")
.fetch_one(pool)
.await
.map_err(db_error)?
.get(0);
if count > 0 {
return Ok(());
}
for (position, category_name) in DEFAULT_MEAL_CATEGORIES.iter().enumerate() {
sqlx::query("INSERT INTO meal_categories (name, position, created_at) VALUES (?1, ?2, ?3)")
.bind(category_name)
.bind(position as i64)
.bind(now())
.execute(pool)
.await
.map_err(db_error)?;
}
Ok(())
}
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct SqliteUserRepository; pub struct SqliteUserRepository;
@@ -209,6 +233,21 @@ impl UserRepository for SqliteUserRepository {
})) }))
} }
async fn update_password_hash(
&self,
txn: &mut SqliteConnection,
user_id: i64,
password_hash: String,
) -> DomainResult<()> {
sqlx::query("UPDATE users SET password_hash = ?1 WHERE id = ?2")
.bind(&password_hash)
.bind(user_id)
.execute(&mut *txn)
.await
.map_err(db_error)?;
Ok(())
}
async fn has_users(&self, txn: &mut SqliteConnection) -> DomainResult<bool> { async fn has_users(&self, txn: &mut SqliteConnection) -> DomainResult<bool> {
let row = sqlx::query("SELECT EXISTS(SELECT 1 FROM users)") let row = sqlx::query("SELECT EXISTS(SELECT 1 FROM users)")
.fetch_one(&mut *txn) .fetch_one(&mut *txn)
@@ -403,8 +442,9 @@ pub struct SqliteListRepository;
impl ListRepository for SqliteListRepository { impl ListRepository for SqliteListRepository {
async fn list_summaries(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<GroceryList>> { async fn list_summaries(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<GroceryList>> {
let rows = sqlx::query( let rows = sqlx::query(
"SELECT l.id, l.name, l.revision "SELECT l.id, l.name, l.revision, l.created_at, l.archived_at
FROM lists l FROM lists l
WHERE l.archived_at IS NULL
ORDER BY l.created_at DESC", ORDER BY l.created_at DESC",
) )
.fetch_all(&mut *txn) .fetch_all(&mut *txn)
@@ -416,6 +456,33 @@ impl ListRepository for SqliteListRepository {
id: row.get(0), id: row.get(0),
name: row.get(1), name: row.get(1),
revision: row.get(2), revision: row.get(2),
created_at: row.get(3),
archived_at: row.get(4),
})
.collect())
}
async fn list_archived_summaries(
&self,
txn: &mut SqliteConnection,
) -> DomainResult<Vec<GroceryList>> {
let rows = sqlx::query(
"SELECT l.id, l.name, l.revision, l.created_at, l.archived_at
FROM lists l
WHERE l.archived_at IS NOT NULL
ORDER BY l.archived_at DESC, l.created_at DESC",
)
.fetch_all(&mut *txn)
.await
.map_err(db_error)?;
Ok(rows
.into_iter()
.map(|row| GroceryList {
id: row.get(0),
name: row.get(1),
revision: row.get(2),
created_at: row.get(3),
archived_at: row.get(4),
}) })
.collect()) .collect())
} }
@@ -440,6 +507,8 @@ impl ListRepository for SqliteListRepository {
id: list_id, id: list_id,
name, name,
revision: 0, revision: 0,
created_at: now(),
archived_at: None,
}) })
} }
@@ -449,7 +518,7 @@ impl ListRepository for SqliteListRepository {
list_id: i64, list_id: i64,
) -> DomainResult<Option<GroceryList>> { ) -> DomainResult<Option<GroceryList>> {
let row = sqlx::query( let row = sqlx::query(
"SELECT l.id, l.name, l.revision "SELECT l.id, l.name, l.revision, l.created_at, l.archived_at
FROM lists l FROM lists l
WHERE l.id = ?1", WHERE l.id = ?1",
) )
@@ -461,8 +530,36 @@ impl ListRepository for SqliteListRepository {
id: row.get(0), id: row.get(0),
name: row.get(1), name: row.get(1),
revision: row.get(2), revision: row.get(2),
created_at: row.get(3),
archived_at: row.get(4),
})) }))
} }
async fn set_archived(
&self,
txn: &mut SqliteConnection,
list_id: i64,
archived: bool,
) -> DomainResult<()> {
let result = if archived {
sqlx::query("UPDATE lists SET archived_at = ?1 WHERE id = ?2")
.bind(now())
.bind(list_id)
.execute(&mut *txn)
.await
.map_err(db_error)?
} else {
sqlx::query("UPDATE lists SET archived_at = NULL WHERE id = ?1")
.bind(list_id)
.execute(&mut *txn)
.await
.map_err(db_error)?
};
if result.rows_affected() == 0 {
return Err(DomainError::NotFound);
}
Ok(())
}
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
@@ -601,8 +698,8 @@ impl ItemRepository for SqliteItemRepository {
ensure_category(txn, item.category_id).await?; ensure_category(txn, item.category_id).await?;
sqlx::query( sqlx::query(
"INSERT INTO items "INSERT INTO items
(list_id, name, quantity, note, category_id, checked, version, position, created_at, updated_at) (list_id, name, quantity, note, category_id, checked, version, position, list_meal_id, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, 0, 1, ?6, ?7, ?7)", VALUES (?1, ?2, ?3, ?4, ?5, 0, 1, ?6, ?7, ?8, ?8)",
) )
.bind(list_id) .bind(list_id)
.bind(&item.name) .bind(&item.name)
@@ -610,6 +707,7 @@ impl ItemRepository for SqliteItemRepository {
.bind(&item.note) .bind(&item.note)
.bind(item.category_id) .bind(item.category_id)
.bind(position) .bind(position)
.bind(item.list_meal_id)
.bind(now) .bind(now)
.execute(&mut *txn) .execute(&mut *txn)
.await .await
@@ -699,6 +797,83 @@ impl ItemRepository for SqliteItemRepository {
} }
} }
#[derive(Clone, Copy)]
pub struct SqliteListMealRepository;
#[async_trait]
impl ListMealRepository for SqliteListMealRepository {
async fn list_meals(
&self,
txn: &mut SqliteConnection,
list_id: i64,
) -> DomainResult<Vec<ListMeal>> {
let rows = sqlx::query(
"SELECT id, meal_id, name, created_at
FROM list_meals
WHERE list_id = ?1
ORDER BY created_at ASC, id ASC",
)
.bind(list_id)
.fetch_all(&mut *txn)
.await
.map_err(db_error)?;
Ok(rows
.into_iter()
.map(|row| ListMeal {
id: row.get(0),
meal_id: row.get(1),
name: row.get(2),
created_at: row.get(3),
})
.collect())
}
async fn add_meal(
&self,
txn: &mut SqliteConnection,
list_id: i64,
meal_id: i64,
name: String,
) -> DomainResult<i64> {
sqlx::query(
"INSERT INTO list_meals (list_id, meal_id, name, created_at)
VALUES (?1, ?2, ?3, ?4)",
)
.bind(list_id)
.bind(meal_id)
.bind(&name)
.bind(now())
.execute(&mut *txn)
.await
.map_err(db_error)?;
let id = sqlx::query("SELECT last_insert_rowid()")
.fetch_one(&mut *txn)
.await
.map_err(db_error)?
.get::<i64, _>(0);
Ok(id)
}
async fn remove_meal(
&self,
txn: &mut SqliteConnection,
list_id: i64,
list_meal_id: i64,
) -> DomainResult<i64> {
let changed = sqlx::query("DELETE FROM list_meals WHERE id = ?1 AND list_id = ?2")
.bind(list_meal_id)
.bind(list_id)
.execute(&mut *txn)
.await
.map_err(db_error)?
.rows_affected();
if changed == 0 {
return Err(DomainError::NotFound);
}
bump_revision(txn, list_id).await
}
}
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct SqliteInvitationRepository; pub struct SqliteInvitationRepository;
@@ -764,6 +939,79 @@ impl InvitationRepository for SqliteInvitationRepository {
} }
} }
#[derive(Clone, Copy)]
pub struct SqliteMealCategoryRepository;
#[async_trait]
impl MealCategoryRepository for SqliteMealCategoryRepository {
async fn meal_categories(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<MealCategory>> {
let rows = sqlx::query(
"SELECT id, name
FROM meal_categories
ORDER BY position ASC, name COLLATE NOCASE ASC",
)
.fetch_all(&mut *txn)
.await
.map_err(db_error)?;
Ok(rows
.into_iter()
.map(|row| MealCategory {
id: row.get(0),
name: row.get(1),
})
.collect())
}
async fn create_meal_category(
&self,
txn: &mut SqliteConnection,
name: String,
) -> DomainResult<i64> {
let position: i64 =
sqlx::query("SELECT COALESCE(MAX(position), -1) + 1 FROM meal_categories")
.fetch_one(&mut *txn)
.await
.map_err(db_error)?
.get(0);
let result = sqlx::query(
"INSERT INTO meal_categories (name, position, created_at)
VALUES (?1, ?2, ?3)",
)
.bind(&name)
.bind(position)
.bind(now())
.execute(&mut *txn)
.await;
match result {
Ok(_) => {}
Err(error) if is_unique_violation(&error) => return Err(DomainError::Conflict),
Err(error) => return Err(db_error(error)),
}
Ok(sqlx::query("SELECT last_insert_rowid()")
.fetch_one(&mut *txn)
.await
.map_err(db_error)?
.get::<i64, _>(0))
}
async fn delete_meal_category(
&self,
txn: &mut SqliteConnection,
category_id: i64,
) -> DomainResult<()> {
let changed = sqlx::query("DELETE FROM meal_categories WHERE id = ?1")
.bind(category_id)
.execute(&mut *txn)
.await
.map_err(db_error)?
.rows_affected();
if changed == 0 {
return Err(DomainError::NotFound);
}
Ok(())
}
}
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct SqliteMealRepository; pub struct SqliteMealRepository;
@@ -774,14 +1022,16 @@ impl MealRepository for SqliteMealRepository {
txn: &mut SqliteConnection, txn: &mut SqliteConnection,
name: String, name: String,
description: String, description: String,
category_id: Option<i64>,
) -> DomainResult<Meal> { ) -> DomainResult<Meal> {
let now = now(); let now = now();
sqlx::query( sqlx::query(
"INSERT INTO meals (name, description, created_at, updated_at) "INSERT INTO meals (name, description, category_id, created_at, updated_at)
VALUES (?1, ?2, ?3, ?3)", VALUES (?1, ?2, ?3, ?4, ?4)",
) )
.bind(&name) .bind(&name)
.bind(&description) .bind(&description)
.bind(category_id)
.bind(now) .bind(now)
.execute(&mut *txn) .execute(&mut *txn)
.await .await
@@ -795,6 +1045,7 @@ impl MealRepository for SqliteMealRepository {
id, id,
name, name,
description, description,
category_id,
ingredients: Vec::new(), ingredients: Vec::new(),
}) })
} }
@@ -805,7 +1056,7 @@ impl MealRepository for SqliteMealRepository {
meal_id: i64, meal_id: i64,
) -> DomainResult<Option<Meal>> { ) -> DomainResult<Option<Meal>> {
let row = sqlx::query( let row = sqlx::query(
"SELECT id, name, description "SELECT id, name, description, category_id
FROM meals FROM meals
WHERE id = ?1", WHERE id = ?1",
) )
@@ -820,6 +1071,7 @@ impl MealRepository for SqliteMealRepository {
id: row.get(0), id: row.get(0),
name: row.get(1), name: row.get(1),
description: row.get(2), description: row.get(2),
category_id: row.get(3),
ingredients: Vec::new(), ingredients: Vec::new(),
}; };
let ingredients = SqliteMealIngredientRepository let ingredients = SqliteMealIngredientRepository
@@ -833,7 +1085,7 @@ impl MealRepository for SqliteMealRepository {
async fn list_meals(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<Meal>> { async fn list_meals(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<Meal>> {
let rows = sqlx::query( let rows = sqlx::query(
"SELECT id, name, description "SELECT id, name, description, category_id
FROM meals FROM meals
ORDER BY name COLLATE NOCASE ASC", ORDER BY name COLLATE NOCASE ASC",
) )
@@ -846,6 +1098,7 @@ impl MealRepository for SqliteMealRepository {
id: row.get(0), id: row.get(0),
name: row.get(1), name: row.get(1),
description: row.get(2), description: row.get(2),
category_id: row.get(3),
ingredients: Vec::new(), ingredients: Vec::new(),
}; };
let ingredients = SqliteMealIngredientRepository let ingredients = SqliteMealIngredientRepository
@@ -865,14 +1118,16 @@ impl MealRepository for SqliteMealRepository {
meal_id: i64, meal_id: i64,
name: String, name: String,
description: String, description: String,
category_id: Option<i64>,
) -> DomainResult<()> { ) -> DomainResult<()> {
let changed = sqlx::query( let changed = sqlx::query(
"UPDATE meals "UPDATE meals
SET name = ?1, description = ?2, updated_at = ?3 SET name = ?1, description = ?2, category_id = ?3, updated_at = ?4
WHERE id = ?4", WHERE id = ?5",
) )
.bind(&name) .bind(&name)
.bind(&description) .bind(&description)
.bind(category_id)
.bind(now()) .bind(now())
.bind(meal_id) .bind(meal_id)
.execute(&mut *txn) .execute(&mut *txn)
@@ -1061,6 +1316,9 @@ const DEFAULT_CATEGORIES: &[&str] = &[
"Household", "Household",
]; ];
const DEFAULT_MEAL_CATEGORIES: &[&str] =
&["Beef", "Chicken", "Pasta", "Sandwiches", "Salads", "Soups"];
fn hash_secret(secret: &str) -> Vec<u8> { fn hash_secret(secret: &str) -> Vec<u8> {
let mut hasher = Sha256::new(); let mut hasher = Sha256::new();
hasher.update(secret.as_bytes()); hasher.update(secret.as_bytes());
@@ -1408,6 +1666,85 @@ mod tests {
assert_eq!(ids, vec![first.id, second.id]); assert_eq!(ids, vec![first.id, second.id]);
} }
#[tokio::test]
async fn archiving_a_list_hides_it_from_summaries() {
let db = setup().await;
let list = create_list(&db, "Weekly shop").await;
let lists = SqliteListRepository;
let list_id = list.id;
db.run(move |txn| {
let lists = lists.clone();
Box::pin(async move { lists.set_archived(txn, list_id, true).await })
})
.await
.unwrap();
let summaries = db
.run(move |txn| {
let lists = lists.clone();
Box::pin(async move { lists.list_summaries(txn).await })
})
.await
.unwrap();
assert!(summaries.is_empty());
let archived = db
.run(move |txn| {
let lists = lists.clone();
Box::pin(async move { lists.list_archived_summaries(txn).await })
})
.await
.unwrap();
assert_eq!(archived.len(), 1);
assert_eq!(archived[0].id, list.id);
assert!(archived[0].archived_at.is_some());
}
#[tokio::test]
async fn unarchiving_a_list_restores_it_to_summaries() {
let db = setup().await;
let list = create_list(&db, "Weekly shop").await;
let lists = SqliteListRepository;
let list_id = list.id;
db.run(move |txn| {
let lists = lists.clone();
Box::pin(async move { lists.set_archived(txn, list_id, true).await })
})
.await
.unwrap();
db.run(move |txn| {
let lists = lists.clone();
Box::pin(async move { lists.set_archived(txn, list_id, false).await })
})
.await
.unwrap();
let summaries = db
.run(move |txn| {
let lists = lists.clone();
Box::pin(async move { lists.list_summaries(txn).await })
})
.await
.unwrap();
assert_eq!(summaries.len(), 1);
assert!(summaries[0].archived_at.is_none());
}
#[tokio::test]
async fn archiving_a_missing_list_fails() {
let db = setup().await;
let lists = SqliteListRepository;
let result = db
.run(move |txn| {
let lists = lists.clone();
Box::pin(async move { lists.set_archived(txn, 9999, true).await })
})
.await;
assert!(result.is_err());
}
#[tokio::test] #[tokio::test]
async fn get_list_returns_list_or_none() { async fn get_list_returns_list_or_none() {
let db = setup().await; let db = setup().await;
@@ -1464,6 +1801,119 @@ mod tests {
assert!(matches!(result, Err(DomainError::Conflict))); assert!(matches!(result, Err(DomainError::Conflict)));
} }
// ---- MealCategoryRepository ----
async fn get_meal_categories(db: &SqliteDatabase) -> Vec<MealCategory> {
let categories = SqliteMealCategoryRepository;
db.run(move |txn| {
let categories = categories.clone();
Box::pin(async move { categories.meal_categories(txn).await })
})
.await
.unwrap()
}
#[tokio::test]
async fn meal_categories_are_seeded_with_defaults() {
let db = setup().await;
let categories = get_meal_categories(&db).await;
let names = categories
.iter()
.map(|c| c.name.as_str())
.collect::<Vec<_>>();
assert!(names.contains(&"Beef"));
assert!(names.contains(&"Chicken"));
assert!(names.contains(&"Pasta"));
assert!(names.contains(&"Sandwiches"));
assert!(names.contains(&"Salads"));
assert!(names.contains(&"Soups"));
}
#[tokio::test]
async fn create_meal_category_returns_id_and_lists() {
let db = setup().await;
let categories = SqliteMealCategoryRepository;
let id = db
.run(move |txn| {
let categories = categories.clone();
Box::pin(async move {
categories
.create_meal_category(txn, "Breakfast".into())
.await
})
})
.await
.unwrap();
assert!(id > 0);
let cats = get_meal_categories(&db).await;
assert!(cats.iter().any(|c| c.id == id && c.name == "Breakfast"));
}
#[tokio::test]
async fn create_duplicate_meal_category_conflicts() {
let db = setup().await;
let categories = SqliteMealCategoryRepository;
let result = db
.run(move |txn| {
let categories = categories.clone();
Box::pin(async move { categories.create_meal_category(txn, "Beef".into()).await })
})
.await;
assert!(matches!(result, Err(DomainError::Conflict)));
}
#[tokio::test]
async fn delete_meal_category_cascades_to_null_on_meals() {
let db = setup().await;
let categories = SqliteMealCategoryRepository;
let category_id = db
.run(move |txn| {
let categories = categories.clone();
Box::pin(async move {
categories
.create_meal_category(txn, "Breakfast".into())
.await
})
})
.await
.unwrap();
let meal = create_meal(&db, "Pancakes").await;
let meals = SqliteMealRepository;
db.run(move |txn| {
let meals = meals.clone();
Box::pin(async move {
meals
.update_meal(
txn,
meal.id,
"Pancakes".into(),
String::new(),
Some(category_id),
)
.await
})
})
.await
.unwrap();
db.run(move |txn| {
let categories = categories.clone();
Box::pin(async move { categories.delete_meal_category(txn, category_id).await })
})
.await
.unwrap();
let fetched = db
.run(move |txn| {
let meals = meals.clone();
Box::pin(async move { meals.get_meal(txn, meal.id).await })
})
.await
.unwrap()
.unwrap();
assert_eq!(fetched.category_id, None);
}
// ---- ItemRepository ---- // ---- ItemRepository ----
#[tokio::test] #[tokio::test]
@@ -1536,12 +1986,14 @@ mod tests {
quantity: "500g".into(), quantity: "500g".into(),
note: String::new(), note: String::new(),
category_id: None, category_id: None,
list_meal_id: None,
}, },
NewItem { NewItem {
name: "Tomato".into(), name: "Tomato".into(),
quantity: "2".into(), quantity: "2".into(),
note: String::new(), note: String::new(),
category_id: None, category_id: None,
list_meal_id: None,
}, },
]; ];
let revision = db let revision = db
@@ -1813,7 +2265,7 @@ mod tests {
let name = name.to_owned(); let name = name.to_owned();
db.run(move |txn| { db.run(move |txn| {
let meals = meals.clone(); let meals = meals.clone();
Box::pin(async move { meals.create_meal(txn, name, String::new()).await }) Box::pin(async move { meals.create_meal(txn, name, String::new(), None).await })
}) })
.await .await
.unwrap() .unwrap()
@@ -1931,7 +2383,13 @@ mod tests {
let meals = meals.clone(); let meals = meals.clone();
Box::pin(async move { Box::pin(async move {
meals meals
.update_meal(txn, meal.id, "Pasta al pomodoro".into(), "desc".into()) .update_meal(
txn,
meal.id,
"Pasta al pomodoro".into(),
"desc".into(),
None,
)
.await .await
}) })
}) })
@@ -1958,7 +2416,7 @@ mod tests {
let meals = meals.clone(); let meals = meals.clone();
Box::pin(async move { Box::pin(async move {
meals meals
.update_meal(txn, 9999, "X".into(), String::new()) .update_meal(txn, 9999, "X".into(), String::new(), None)
.await .await
}) })
}) })
@@ -2101,6 +2559,118 @@ mod tests {
assert!(matches!(result, Err(DomainError::NotFound))); assert!(matches!(result, Err(DomainError::NotFound)));
} }
// ---- ListMealRepository ----
async fn add_meal_to_list(db: &SqliteDatabase, list_id: i64, meal: &Meal) -> ListMeal {
let list_meals = SqliteListMealRepository;
let name = meal.name.clone();
let meal_id = meal.id;
let id = db
.run(move |txn| {
let list_meals = list_meals.clone();
Box::pin(async move { list_meals.add_meal(txn, list_id, meal_id, name).await })
})
.await
.unwrap();
ListMeal {
id,
meal_id: Some(meal.id),
name: meal.name.clone(),
created_at: 0,
}
}
#[tokio::test]
async fn list_meals_returns_meals_added_to_a_list() {
let db = setup().await;
let list = create_list(&db, "Weekly shop").await;
let meal = create_meal(&db, "Pasta").await;
add_meal_to_list(&db, list.id, &meal).await;
let list_meals = SqliteListMealRepository;
let meals = db
.run(move |txn| {
let list_meals = list_meals.clone();
Box::pin(async move { list_meals.list_meals(txn, list.id).await })
})
.await
.unwrap();
assert_eq!(meals.len(), 1);
assert_eq!(meals[0].name, "Pasta");
assert_eq!(meals[0].meal_id, Some(meal.id));
}
#[tokio::test]
async fn removing_a_meal_deletes_its_items_and_bumps_revision() {
let db = setup().await;
let list = create_list(&db, "Weekly shop").await;
let meal = create_meal(&db, "Pasta").await;
add_ingredient(&db, meal.id, "Penne", None).await;
add_ingredient(&db, meal.id, "Tomato", None).await;
let list_meal = add_meal_to_list(&db, list.id, &meal).await;
let items = SqliteItemRepository;
let ingredients = SqliteMealIngredientRepository;
let ingredient_rows = db
.run(move |txn| {
let ingredients = ingredients.clone();
Box::pin(async move { ingredients.ingredients_for_meal(txn, meal.id).await })
})
.await
.unwrap();
let new_items = ingredient_rows
.into_iter()
.map(|ingredient| NewItem {
name: ingredient.name,
quantity: ingredient.quantity,
note: ingredient.note,
category_id: ingredient.category_id,
list_meal_id: Some(list_meal.id),
})
.collect();
db.run(move |txn| {
let items = items.clone();
Box::pin(async move { items.add_items_bulk(txn, list.id, new_items).await })
})
.await
.unwrap();
assert_eq!(get_items(&db, list.id).await.len(), 2);
let list_meals = SqliteListMealRepository;
let revision = db
.run(move |txn| {
let list_meals = list_meals.clone();
Box::pin(async move { list_meals.remove_meal(txn, list.id, list_meal.id).await })
})
.await
.unwrap();
assert_eq!(revision, 2);
let meals = db
.run(move |txn| {
let list_meals = list_meals.clone();
Box::pin(async move { list_meals.list_meals(txn, list.id).await })
})
.await
.unwrap();
assert!(meals.is_empty());
assert!(get_items(&db, list.id).await.is_empty());
}
#[tokio::test]
async fn removing_an_unknown_meal_from_a_list_fails() {
let db = setup().await;
let list = create_list(&db, "Weekly shop").await;
let list_meals = SqliteListMealRepository;
let result = db
.run(move |txn| {
let list_meals = list_meals.clone();
Box::pin(async move { list_meals.remove_meal(txn, list.id, 9999).await })
})
.await;
assert!(matches!(result, Err(DomainError::NotFound)));
}
// ---- PasskeyRepository ---- // ---- PasskeyRepository ----
#[tokio::test] #[tokio::test]
+484 -134
View File
@@ -3,7 +3,9 @@ use pulldown_cmark::{Options, Parser, html as cmark_html};
use crate::{ use crate::{
domain::PresenceUser, domain::PresenceUser,
domain::{Category, GroceryList, Item, Meal, MealIngredient, Passkey, User}, domain::{
Category, GroceryList, Item, ListMeal, Meal, MealCategory, MealIngredient, Passkey, User,
},
}; };
pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup { pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup {
@@ -25,13 +27,17 @@ pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup {
label for="email" { "Email" } label for="email" { "Email" }
input id="email" name="email" type="email" autocomplete="email" autofocus; input id="email" name="email" type="email" autocomplete="email" autofocus;
label for="password" { "Password" } label for="password" { "Password" }
input id="password" name="password" type="password" autocomplete="current-password" required; div class="password-field" {
input id="password" name="password" type="password" autocomplete="current-password" required;
button class="password-toggle" type="button" data-toggle-for="password" aria-label="Show password" { "Show" }
}
button class="button button-primary" type="submit" { "Sign in" } button class="button button-primary" type="submit" { "Sign in" }
} }
div class="auth-divider" { span { "or" } } div class="auth-divider" { span { "or" } }
button id="passkey-login" class="button button-secondary" type="button" { "Sign in with a passkey" } button id="passkey-login" class="button button-secondary" type="button" { "Sign in with a passkey" }
p class="auth-switch" { "Need an account? " a href="/register" { "Create one" } } p class="auth-switch" { "Need an account? " a href="/register" { "Create one" } }
} }
script src="/static/password-toggle.js" {}
script src="/static/passkey-login.js" {} script src="/static/passkey-login.js" {}
}, },
) )
@@ -58,11 +64,15 @@ pub fn register_page(error: Option<&str>, invite: Option<&str>) -> Markup {
label for="email" { "Email" } label for="email" { "Email" }
input id="email" name="email" type="email" autocomplete="email" required; input id="email" name="email" type="email" autocomplete="email" required;
label for="password" { "Password" } label for="password" { "Password" }
input id="password" name="password" type="password" autocomplete="new-password" required; div class="password-field" {
input id="password" name="password" type="password" autocomplete="new-password" required;
button class="password-toggle" type="button" data-toggle-for="password" aria-label="Show password" { "Show" }
}
button class="button button-primary" type="submit" { "Create account" } button class="button button-primary" type="submit" { "Create account" }
} }
p class="auth-switch" { "Already have an account? " a href="/login" { "Sign in" } } p class="auth-switch" { "Already have an account? " a href="/login" { "Sign in" } }
} }
script src="/static/password-toggle.js" {}
}, },
) )
} }
@@ -82,7 +92,13 @@ pub fn registration_closed_page() -> Markup {
) )
} }
pub fn account_page(user: &User, passkeys: &[Passkey], csrf_token: &str) -> Markup { pub fn account_page(
user: &User,
passkeys: &[Passkey],
csrf_token: &str,
password_error: Option<&str>,
password_success: bool,
) -> Markup {
page( page(
"Account", "Account",
Some(user), Some(user),
@@ -121,13 +137,46 @@ pub fn account_page(user: &User, passkeys: &[Passkey], csrf_token: &str) -> Mark
} }
button id="add-passkey" class="button button-primary" type="button" data-csrf=(csrf_token) { "Add a passkey" } button id="add-passkey" class="button button-primary" type="button" data-csrf=(csrf_token) { "Add a passkey" }
} }
section class="panel" {
div class="panel-heading" {
h2 { "Password" }
}
p { "Set a new password for your account." }
@if let Some(error) = password_error {
div class="alert alert-error" role="alert" { (error) }
}
@if password_success {
div class="alert alert-success" role="alert" { "Your password has been updated." }
}
form method="post" action="/account/password" class="stack" {
input type="hidden" name="csrf" value=(csrf_token);
label for="new-password" { "New password" }
div class="password-field" {
input id="new-password" name="new_password" type="password" autocomplete="new-password" required;
button class="password-toggle" type="button" data-toggle-for="new-password" aria-label="Show password" { "Show" }
}
label for="confirm-password" { "Confirm new password" }
div class="password-field" {
input id="confirm-password" name="confirm_password" type="password" autocomplete="new-password" required;
button class="password-toggle" type="button" data-toggle-for="confirm-password" aria-label="Show password" { "Show" }
}
button class="button button-primary" type="submit" { "Update password" }
}
}
} }
script src="/static/password-toggle.js" {}
script src="/static/passkey-register.js" {} script src="/static/passkey-register.js" {}
}, },
) )
} }
pub fn lists_page(user: &User, lists: &[GroceryList], csrf_token: &str) -> Markup { pub fn lists_page(
user: &User,
lists: &[GroceryList],
archived_count: usize,
categories: &[Category],
csrf_token: &str,
) -> Markup {
page( page(
"Your lists", "Your lists",
Some(user), Some(user),
@@ -135,7 +184,7 @@ pub fn lists_page(user: &User, lists: &[GroceryList], csrf_token: &str) -> Marku
div class="page-heading" { div class="page-heading" {
div { div {
p class="eyebrow" { "SHARED LISTS" } p class="eyebrow" { "SHARED LISTS" }
h1 { "Grocery lists" } h1 class="page-title" { "Grocery lists" }
p class="lede" { "Everything you need, in one place." } p class="lede" { "Everything you need, in one place." }
} }
} }
@@ -144,6 +193,7 @@ pub fn lists_page(user: &User, lists: &[GroceryList], csrf_token: &str) -> Marku
div class="panel-heading" { div class="panel-heading" {
h2 { "Lists" } h2 { "Lists" }
span class="count-badge" { (lists.len()) } span class="count-badge" { (lists.len()) }
a class="archive-link" href="/archive" { "Archived " span class="count-badge" { (archived_count) } "" }
} }
@if lists.is_empty() { @if lists.is_empty() {
div class="empty-state" { div class="empty-state" {
@@ -174,6 +224,7 @@ pub fn lists_page(user: &User, lists: &[GroceryList], csrf_token: &str) -> Marku
button class="button button-primary" type="submit" { "Create list" } button class="button button-primary" type="submit" { "Create list" }
} }
} }
(categories_panel(categories, csrf_token, false))
section id="sharing" class="panel sharing-panel" { section id="sharing" class="panel sharing-panel" {
div class="panel-heading" { h2 { "Invite someone" } } div class="panel-heading" { h2 { "Invite someone" } }
p { "Create a one-time invite link so a new person can join." } p { "Create a one-time invite link so a new person can join." }
@@ -193,7 +244,55 @@ pub fn lists_page(user: &User, lists: &[GroceryList], csrf_token: &str) -> Marku
) )
} }
pub fn meals_page(user: &User, meals: &[Meal]) -> Markup { pub fn archive_page(user: &User, archived_lists: &[GroceryList]) -> Markup {
page(
"Archive",
Some(user),
html! {
div class="page-heading" {
div {
p class="eyebrow" { "ARCHIVE" }
h1 class="page-title" { "Archived lists" }
p class="lede" { "Past lists, kept for reference." }
}
a class="button button-quiet" href="/lists" { "← Back to lists" }
}
section class="panel" {
div class="panel-heading" {
h2 { "Archive" }
span class="count-badge" { (archived_lists.len()) }
}
@if archived_lists.is_empty() {
div class="empty-state" {
div class="empty-mark" { "🗄" }
h3 { "Nothing archived yet" }
p { "Archive a list and it will show up here." }
}
} @else {
div class="list-cards" {
@for list in archived_lists {
a class="list-card archived-list-card" href=(format!("/lists/{}", list.id)) {
span class="list-card-icon" { "🗄" }
span class="list-card-copy" {
strong { (list.name) }
small { "Created " (format_date(list.created_at)) }
}
span class="list-card-arrow" { "" }
}
}
}
}
}
},
)
}
pub fn meals_page(
user: &User,
meals: &[Meal],
meal_categories: &[MealCategory],
csrf_token: &str,
) -> Markup {
page( page(
"Meals", "Meals",
Some(user), Some(user),
@@ -201,11 +300,18 @@ pub fn meals_page(user: &User, meals: &[Meal]) -> Markup {
div class="page-heading" { div class="page-heading" {
div { div {
p class="eyebrow" { "MEAL LIBRARY" } p class="eyebrow" { "MEAL LIBRARY" }
h1 { "Meals" } h1 class="page-title" { "Meals" }
p class="lede" { "Save a meal and add its ingredients to any list." } p class="lede" { "Save a meal and add its ingredients to any list." }
} }
a class="button button-primary" href="/meals/new" { "New meal" } a class="button button-primary" href="/meals/new" { "New meal" }
} }
@if meals.is_empty() {
div class="empty-state" {
div class="empty-mark" { "🍽" }
h3 { "No meals yet" }
p { "Create a meal to reuse its ingredients across your lists." }
}
}
div class="dashboard-grid" { div class="dashboard-grid" {
section class="panel" { section class="panel" {
div class="panel-heading" { div class="panel-heading" {
@@ -213,21 +319,52 @@ pub fn meals_page(user: &User, meals: &[Meal]) -> Markup {
span class="count-badge" { (meals.len()) } span class="count-badge" { (meals.len()) }
} }
@if meals.is_empty() { @if meals.is_empty() {
div class="empty-state" { p class="muted" { "Create a meal to get started." }
div class="empty-mark" { "🍽" }
h3 { "No meals yet" }
p { "Create a meal to reuse its ingredients across your lists." }
}
} @else { } @else {
div class="list-cards" { @for (category_name, category_meals) in meal_groups(meals, meal_categories) {
@for meal in meals { div class="category-group" {
a class="list-card" href=(format!("/meals/{}", meal.id)) { div class="category-heading" {
span class="list-card-icon" { "🍽" } h3 { (category_name) " (" (category_meals.len()) ")" }
span class="list-card-copy" { }
strong { (meal.name) } div class="list-cards" {
small { (meal.ingredients.len()) " ingredients" } @for meal in category_meals {
a class="list-card" href=(format!("/meals/{}", meal.id)) {
span class="list-card-icon" { "🍽" }
span class="list-card-copy" {
strong { (meal.name) }
small { (meal.ingredients.len()) " ingredients" }
}
span class="list-card-arrow" { "" }
}
}
}
}
}
}
}
aside class="side-column" {
section class="panel categories-panel" {
div class="panel-heading" {
h2 { "Meal categories" }
}
p { "Organize meals by type." }
form method="post" action="/meals/categories" class="category-form" {
input type="hidden" name="csrf" value=(csrf_token);
input name="name" type="text" maxlength="60" placeholder="New category" required;
button class="button button-small button-secondary" type="submit" { "Add" }
}
@if meal_categories.is_empty() {
p class="muted category-empty" { "No categories yet." }
} @else {
div class="meal-category-list" {
@for category in meal_categories {
div class="meal-category-row" {
span class="meal-category-name" { (category.name) }
form method="post" action=(format!("/meals/categories/{}/delete", category.id)) {
input type="hidden" name="csrf" value=(csrf_token);
button class="meal-category-delete" type="submit" aria-label=(format!("Delete {}", category.name)) { "" }
}
} }
span class="list-card-arrow" { "" }
} }
} }
} }
@@ -238,7 +375,47 @@ pub fn meals_page(user: &User, meals: &[Meal]) -> Markup {
) )
} }
pub fn meal_picker(meals: &[Meal], list_id: i64, csrf_token: &str) -> Markup { fn meal_groups<'a>(
meals: &'a [Meal],
meal_categories: &[MealCategory],
) -> Vec<(String, Vec<&'a Meal>)> {
let mut groups = Vec::new();
for category in meal_categories {
let in_category = meals
.iter()
.filter(|meal| meal.category_id == Some(category.id))
.collect::<Vec<_>>();
if !in_category.is_empty() {
groups.push((category.name.clone(), in_category));
}
}
let uncategorized = meals
.iter()
.filter(|meal| meal.category_id.is_none())
.collect::<Vec<_>>();
if !uncategorized.is_empty() {
groups.push(("Uncategorized".into(), uncategorized));
}
groups
}
/// Returns the display name of a meal's category, if it has one.
fn meal_category_name(meal: &Meal, meal_categories: &[MealCategory]) -> Option<String> {
meal.category_id.and_then(|id| {
meal_categories
.iter()
.find(|category| category.id == id)
.map(|category| category.name.clone())
})
}
pub fn meal_picker(
meals: &[Meal],
meal_categories: &[MealCategory],
list_id: i64,
csrf_token: &str,
) -> Markup {
html! { html! {
div class="meal-picker-backdrop" onclick="if (event.target === this) this.remove()" { div class="meal-picker-backdrop" onclick="if (event.target === this) this.remove()" {
div class="meal-picker-modal" role="dialog" aria-modal="true" aria-label="Add a meal" { div class="meal-picker-modal" role="dialog" aria-modal="true" aria-label="Add a meal" {
@@ -258,23 +435,30 @@ pub fn meal_picker(meals: &[Meal], list_id: i64, csrf_token: &str) -> Markup {
} }
} @else { } @else {
div class="meal-picker-list" { div class="meal-picker-list" {
@for meal in meals { @for (category_name, category_meals) in meal_groups(meals, meal_categories) {
form div class="category-group" {
hx-post=(format!("/lists/{}/add-meal", list_id)) div class="category-heading" {
hx-target="#list-items" h3 { (category_name) }
hx-swap="outerHTML" }
hx-on::after-request="if (event.detail.successful) this.closest('.meal-picker-backdrop').remove()" @for meal in category_meals {
class="meal-picker-row" form
{ hx-post=(format!("/lists/{}/add-meal", list_id))
input type="hidden" name="csrf" value=(csrf_token); hx-target="#list-items"
input type="hidden" name="meal_id" value=(meal.id); hx-swap="outerHTML"
button class="meal-picker-button" type="submit" { hx-on::after-request="if (event.detail.successful) this.closest('.meal-picker-backdrop').remove()"
span class="meal-picker-icon" { "🍽" } class="meal-picker-row"
span class="meal-picker-copy" { {
strong { (meal.name) } input type="hidden" name="csrf" value=(csrf_token);
small { (meal.ingredients.len()) " ingredients" } input type="hidden" name="meal_id" value=(meal.id);
button class="meal-picker-button" type="submit" {
span class="meal-picker-icon" { "🍽" }
span class="meal-picker-copy" {
strong { (meal.name) }
small { (meal.ingredients.len()) " ingredients" }
}
span class="meal-picker-add" { "Add" }
}
} }
span class="meal-picker-add" { "Add" }
} }
} }
} }
@@ -285,15 +469,27 @@ pub fn meal_picker(meals: &[Meal], list_id: i64, csrf_token: &str) -> Markup {
} }
} }
pub fn meal_form_page(user: &User, meal: Option<&Meal>, csrf_token: &str) -> Markup { pub fn meal_form_page(
let (title, action, name, description) = match meal { user: &User,
meal: Option<&Meal>,
meal_categories: &[MealCategory],
csrf_token: &str,
) -> Markup {
let (title, action, name, description, category_id) = match meal {
Some(meal) => ( Some(meal) => (
"Edit meal", "Edit meal",
format!("/meals/{}/edit", meal.id), format!("/meals/{}/edit", meal.id),
meal.name.clone(), meal.name.clone(),
meal.description.clone(), meal.description.clone(),
meal.category_id,
),
None => (
"New meal",
"/meals".into(),
String::new(),
String::new(),
None,
), ),
None => ("New meal", "/meals".into(), String::new(), String::new()),
}; };
page( page(
title, title,
@@ -308,6 +504,21 @@ pub fn meal_form_page(user: &User, meal: Option<&Meal>, csrf_token: &str) -> Mar
input type="hidden" name="csrf" value=(csrf_token); input type="hidden" name="csrf" value=(csrf_token);
label for="meal-name" { "Name" } label for="meal-name" { "Name" }
input id="meal-name" name="name" type="text" maxlength="120" value=(name) required; input id="meal-name" name="name" type="text" maxlength="120" value=(name) required;
label for="meal-category" { "Category" }
select id="meal-category" name="category_id" {
@if category_id.is_none() {
option value="" selected { "Uncategorized" }
} @else {
option value="" { "Uncategorized" }
}
@for category in meal_categories {
@if category_id == Some(category.id) {
option value=(category.id) selected { (category.name) }
} @else {
option value=(category.id) { (category.name) }
}
}
}
label for="meal-description" { "Description (markdown)" } label for="meal-description" { "Description (markdown)" }
textarea id="meal-description" name="description" rows="8" { (description) } textarea id="meal-description" name="description" rows="8" { (description) }
button class="button button-primary" type="submit" { "Save meal" } button class="button button-primary" type="submit" { "Save meal" }
@@ -320,20 +531,19 @@ pub fn meal_form_page(user: &User, meal: Option<&Meal>, csrf_token: &str) -> Mar
) )
} }
pub fn meal_page(user: &User, meal: &Meal, categories: &[Category], csrf_token: &str) -> Markup { pub fn meal_page(
user: &User,
meal: &Meal,
categories: &[Category],
meal_categories: &[MealCategory],
csrf_token: &str,
) -> Markup {
page( page(
&meal.name, &meal.name,
Some(user), Some(user),
html! { html! {
div class="page-heading" { div class="page-heading" {
a class="back-link" href="/meals" { "← All meals" } a class="back-link" href="/meals" { "← All meals" }
div class="list-topbar-actions" {
button type="button" class="button button-small button-quiet" onclick="document.getElementById('meal-edit-modal').showModal()" { "Edit" }
form method="post" action=(format!("/meals/{}/delete", meal.id)) {
input type="hidden" name="csrf" value=(csrf_token);
button class="danger-link" type="submit" { "Delete" }
}
}
} }
dialog id="meal-edit-modal" class="item-modal" { dialog id="meal-edit-modal" class="item-modal" {
div class="item-modal-card" { div class="item-modal-card" {
@@ -345,6 +555,21 @@ pub fn meal_page(user: &User, meal: &Meal, categories: &[Category], csrf_token:
input type="hidden" name="csrf" value=(csrf_token); input type="hidden" name="csrf" value=(csrf_token);
label { "Name" } label { "Name" }
input id="meal-edit-name" name="name" value=(meal.name) maxlength="120" required; input id="meal-edit-name" name="name" value=(meal.name) maxlength="120" required;
label { "Category" }
select id="meal-edit-category" name="category_id" {
@if meal.category_id.is_none() {
option value="" selected { "Uncategorized" }
} @else {
option value="" { "Uncategorized" }
}
@for category in meal_categories {
@if meal.category_id == Some(category.id) {
option value=(category.id) selected { (category.name) }
} @else {
option value=(category.id) { (category.name) }
}
}
}
label { "Description (markdown)" } label { "Description (markdown)" }
textarea id="meal-edit-description" name="description" rows="8" { (meal.description) } textarea id="meal-edit-description" name="description" rows="8" { (meal.description) }
button id="meal-edit-save" class="button button-primary" type="submit" { "Save meal" } button id="meal-edit-save" class="button button-primary" type="submit" { "Save meal" }
@@ -356,7 +581,14 @@ pub fn meal_page(user: &User, meal: &Meal, categories: &[Category], csrf_token:
div class="list-heading" { div class="list-heading" {
div { div {
p class="eyebrow" { "MEAL" } p class="eyebrow" { "MEAL" }
h1 { (meal.name) } h1 { (meal.name) @if let Some(category_name) = meal_category_name(meal, meal_categories) { span class="meal-category-label" { "(" (category_name) ")" } } }
}
div class="list-topbar-actions" {
button type="button" class="button button-small button-quiet" onclick="document.getElementById('meal-edit-modal').showModal()" { "Edit" }
form method="post" action=(format!("/meals/{}/delete", meal.id)) onsubmit="return confirm('Delete this meal and its ingredients? This cannot be undone.')" {
input type="hidden" name="csrf" value=(csrf_token);
button class="danger-link bordered-delete" type="submit" { "Delete" }
}
} }
} }
@if meal.description.is_empty() { @if meal.description.is_empty() {
@@ -364,7 +596,7 @@ pub fn meal_page(user: &User, meal: &Meal, categories: &[Category], csrf_token:
} @else { } @else {
div class="markdown" { (render_markdown(&meal.description)) } div class="markdown" { (render_markdown(&meal.description)) }
} }
h2 class="category-heading" { "Ingredients" } hr class="ingredients-divider" {}
@if meal.ingredients.is_empty() { @if meal.ingredients.is_empty() {
p class="muted" { "No ingredients yet." } p class="muted" { "No ingredients yet." }
} @else { } @else {
@@ -382,14 +614,14 @@ pub fn meal_page(user: &User, meal: &Meal, categories: &[Category], csrf_token:
input type="hidden" name="csrf" value=(csrf_token); input type="hidden" name="csrf" value=(csrf_token);
label { "Name" } label { "Name" }
input id="ingredient-name" name="name" type="text" maxlength="120" required; input id="ingredient-name" name="name" type="text" maxlength="120" required;
label { "Quantity" }
input id="ingredient-quantity" name="quantity" type="text" maxlength="40";
label { "Note" }
input id="ingredient-note" name="note" type="text" maxlength="120";
label { "Category" } label { "Category" }
select id="ingredient-category" name="category_id" { select id="ingredient-category" name="category_id" {
(category_options(categories, None)) (category_options(categories, None))
} }
label { "Quantity" }
input id="ingredient-quantity" name="quantity" type="text" maxlength="40";
label { "Note" }
input id="ingredient-note" name="note" type="text" maxlength="120";
button id="add-ingredient-button" class="button button-primary" type="submit" { "Add ingredient" } button id="add-ingredient-button" class="button button-primary" type="submit" { "Add ingredient" }
} }
} }
@@ -431,19 +663,19 @@ fn ingredient_row(
input type="hidden" name="csrf" value=(csrf_token); input type="hidden" name="csrf" value=(csrf_token);
label { "Name" } label { "Name" }
input id=(format!("ingredient-edit-name-{}", ingredient.id)) name="name" value=(ingredient.name) maxlength="120" required; input id=(format!("ingredient-edit-name-{}", ingredient.id)) name="name" value=(ingredient.name) maxlength="120" required;
label { "Quantity" }
input id=(format!("ingredient-edit-quantity-{}", ingredient.id)) name="quantity" value=(ingredient.quantity) maxlength="40";
label { "Note" }
input id=(format!("ingredient-edit-note-{}", ingredient.id)) name="note" value=(ingredient.note) maxlength="120";
label { "Category" } label { "Category" }
select id=(format!("ingredient-edit-category-{}", ingredient.id)) name="category_id" { select id=(format!("ingredient-edit-category-{}", ingredient.id)) name="category_id" {
(category_options(categories, ingredient.category_id)) (category_options(categories, ingredient.category_id))
} }
label { "Quantity" }
input id=(format!("ingredient-edit-quantity-{}", ingredient.id)) name="quantity" value=(ingredient.quantity) maxlength="40";
label { "Note" }
input id=(format!("ingredient-edit-note-{}", ingredient.id)) name="note" value=(ingredient.note) maxlength="120";
button id=(format!("ingredient-edit-save-{}", ingredient.id)) class="button button-primary" type="submit" { "Save" } button id=(format!("ingredient-edit-save-{}", ingredient.id)) class="button button-primary" type="submit" { "Save" }
} }
form method="post" action=(format!("/meals/{}/ingredients/{}/delete", meal_id, ingredient.id)) { form method="post" action=(format!("/meals/{}/ingredients/{}/delete", meal_id, ingredient.id)) {
input type="hidden" name="csrf" value=(csrf_token); input type="hidden" name="csrf" value=(csrf_token);
button id=(format!("ingredient-edit-delete-{}", ingredient.id)) class="danger-link" type="submit" { "Remove" } button id=(format!("ingredient-edit-delete-{}", ingredient.id)) class="button button-danger" type="submit" { "Remove" }
} }
} }
} }
@@ -525,6 +757,13 @@ mod tests {
assert!(html.contains("<strong>"), "expected <strong>, got: {html}"); assert!(html.contains("<strong>"), "expected <strong>, got: {html}");
assert!(html.contains("<em>"), "expected <em>, got: {html}"); assert!(html.contains("<em>"), "expected <em>, got: {html}");
} }
#[test]
fn format_date_renders_human_readable_date() {
// 2026-08-07T00:00:00Z in Unix seconds.
let ts = 1_786_060_800;
assert_eq!(format_date(ts), "7 Aug 2026");
}
} }
pub fn list_page( pub fn list_page(
@@ -532,6 +771,7 @@ pub fn list_page(
list: &GroceryList, list: &GroceryList,
items: &[Item], items: &[Item],
categories: &[Category], categories: &[Category],
list_meals: &[ListMeal],
presence: &[PresenceUser], presence: &[PresenceUser],
csrf_token: &str, csrf_token: &str,
) -> Markup { ) -> Markup {
@@ -543,9 +783,11 @@ pub fn list_page(
a class="back-link" href="/lists" { "← All lists" } a class="back-link" href="/lists" { "← All lists" }
div class="list-topbar-actions" { div class="list-topbar-actions" {
span class="live-pill" { span class="live-dot" {} "Live" } span class="live-pill" { span class="live-dot" {} "Live" }
button class="button button-small add-meal-button" hx-get=(format!("/meals?picker={}", list.id)) hx-target="#meal-picker" hx-swap="innerHTML" { "+ Add meal" }
} }
} }
@if let Some(ts) = list.archived_at {
div class="archived-banner" { "This list was archived on " (format_date(ts)) "." }
}
div id="meal-picker" class="meal-picker" {} div id="meal-picker" class="meal-picker" {}
div class="list-layout" { div class="list-layout" {
section class="panel list-panel" { section class="panel list-panel" {
@@ -555,12 +797,25 @@ pub fn list_page(
h1 { (list.name) } h1 { (list.name) }
p class="list-meta" { (items.iter().filter(|item| !item.checked).count()) " items to get" } p class="list-meta" { (items.iter().filter(|item| !item.checked).count()) " items to get" }
} }
div class="list-topbar-actions" {
@if list.archived_at.is_some() {
form method="post" action=(format!("/lists/{}/unarchive", list.id)) {
input type="hidden" name="csrf" value=(csrf_token);
button class="button button-small button-quiet" type="submit" { "Restore" }
}
} @else {
form method="post" action=(format!("/lists/{}/archive", list.id)) {
input type="hidden" name="csrf" value=(csrf_token);
button class="button button-small button-quiet" type="submit" { "Archive" }
}
}
}
} }
(list_content_fragment(list, items, categories, csrf_token, false)) (list_content_fragment(list, items, categories, csrf_token, false, list.archived_at.is_none()))
} }
aside class="side-column" { aside class="side-column" {
(list_meals_panel(list_meals, list.id, csrf_token, false, list.archived_at.is_none()))
(presence_panel(presence, false)) (presence_panel(presence, false))
(categories_panel(categories, csrf_token, false))
section class="panel tip-panel" { section class="panel tip-panel" {
span class="tip-label" { "TIP" } span class="tip-label" { "TIP" }
p { "Check items off as you go. Everyone viewing this list will see it instantly." } p { "Check items off as you go. Everyone viewing this list will see it instantly." }
@@ -578,17 +833,18 @@ pub fn list_content_fragment(
categories: &[Category], categories: &[Category],
csrf_token: &str, csrf_token: &str,
out_of_band: bool, out_of_band: bool,
editable: bool,
) -> Markup { ) -> Markup {
if out_of_band { if out_of_band {
html! { html! {
div id="list-content" hx-swap-oob="outerHTML" { div id="list-content" hx-swap-oob="outerHTML" {
(list_content(list, items, categories, csrf_token)) (list_content(list, items, categories, csrf_token, editable))
} }
} }
} else { } else {
html! { html! {
div id="list-content" { div id="list-content" {
(list_content(list, items, categories, csrf_token)) (list_content(list, items, categories, csrf_token, editable))
} }
} }
} }
@@ -599,26 +855,29 @@ fn list_content(
items: &[Item], items: &[Item],
categories: &[Category], categories: &[Category],
csrf_token: &str, csrf_token: &str,
editable: bool,
) -> Markup { ) -> Markup {
html! { html! {
form @if editable {
id="add-item-form" form
class="add-item-form" id="add-item-form"
hx-post=(format!("/lists/{}/items", list.id)) class="add-item-form"
hx-target="#list-items" hx-post=(format!("/lists/{}/items", list.id))
hx-swap="outerHTML" hx-target="#list-items"
hx-on::after-request="if (event.detail.successful) this.reset()" hx-swap="outerHTML"
{ hx-on::after-request="if (event.detail.successful) this.reset()"
input type="hidden" name="csrf" value=(csrf_token); {
label class="sr-only" for="item-name" { "Item name" } input type="hidden" name="csrf" value=(csrf_token);
input id="item-name" name="name" type="text" maxlength="120" placeholder="Add an item..." autocomplete="off" required; label class="sr-only" for="item-name" { "Item name" }
input id="item-quantity" name="quantity" type="text" maxlength="40" placeholder="Qty" aria-label="Quantity"; input id="item-name" name="name" type="text" maxlength="120" placeholder="Add an item..." autocomplete="off" required;
select id="item-category" name="category_id" aria-label="Category" { select id="item-category" name="category_id" aria-label="Category" {
(category_options(categories, None)) (category_options(categories, None))
}
input id="item-quantity" name="quantity" type="text" maxlength="40" placeholder="Qty" aria-label="Quantity";
button id="add-item-button" class="button button-primary add-button" type="submit" { "+ Add" }
} }
button id="add-item-button" class="button button-primary add-button" type="submit" { "+ Add" }
} }
(list_items_fragment(list, items, categories, csrf_token, false)) (list_items_fragment(list, items, categories, csrf_token, false, editable))
} }
} }
@@ -628,23 +887,29 @@ pub fn list_items_fragment(
categories: &[Category], categories: &[Category],
csrf_token: &str, csrf_token: &str,
out_of_band: bool, out_of_band: bool,
editable: bool,
) -> Markup { ) -> Markup {
if out_of_band { if out_of_band {
html! { html! {
div id="list-items" class="items" data-revision=(list.revision) hx-swap-oob="outerHTML" { div id="list-items" class="items" data-revision=(list.revision) hx-swap-oob="outerHTML" {
(list_items_content(items, categories, csrf_token)) (list_items_content(items, categories, csrf_token, editable))
} }
} }
} else { } else {
html! { html! {
div id="list-items" class="items" data-revision=(list.revision) { div id="list-items" class="items" data-revision=(list.revision) {
(list_items_content(items, categories, csrf_token)) (list_items_content(items, categories, csrf_token, editable))
} }
} }
} }
} }
fn list_items_content(items: &[Item], categories: &[Category], csrf_token: &str) -> Markup { fn list_items_content(
items: &[Item],
categories: &[Category],
csrf_token: &str,
editable: bool,
) -> Markup {
html! { html! {
@if items.is_empty() { @if items.is_empty() {
div class="empty-items" { div class="empty-items" {
@@ -655,7 +920,7 @@ fn list_items_content(items: &[Item], categories: &[Category], csrf_token: &str)
} @else { } @else {
div class="item-list" { div class="item-list" {
@for group in item_groups(items, categories) { @for group in item_groups(items, categories) {
(category_group(&group.0, &group.1, categories, csrf_token)) (category_group(&group.0, &group.1, categories, csrf_token, editable))
} }
} }
} }
@@ -689,32 +954,37 @@ fn category_group(
items: &[&Item], items: &[&Item],
categories: &[Category], categories: &[Category],
csrf_token: &str, csrf_token: &str,
editable: bool,
) -> Markup { ) -> Markup {
html! { html! {
section class="category-group" { section class="category-group" {
h2 class="category-heading" { (name) } h2 class="category-heading" { (name) }
@for item in items { @for item in items {
(item_row(item, categories, csrf_token)) (item_row(item, categories, csrf_token, editable))
} }
} }
} }
} }
fn item_row(item: &Item, categories: &[Category], csrf_token: &str) -> Markup { fn item_row(item: &Item, categories: &[Category], csrf_token: &str, editable: bool) -> Markup {
let next_checked = if item.checked { "0" } else { "1" }; let next_checked = if item.checked { "0" } else { "1" };
html! { html! {
article class=(if item.checked { "item-row is-checked" } else { "item-row" }) id=(format!("item-{}", item.id)) data-version=(item.version) { article class=(if item.checked { "item-row is-checked" } else { "item-row" }) id=(format!("item-{}", item.id)) data-version=(item.version) {
form @if editable {
class="check-form" form
hx-post=(format!("/lists/{}/items/{}/check", item.list_id, item.id)) class="check-form"
hx-target="#list-items" hx-post=(format!("/lists/{}/items/{}/check", item.list_id, item.id))
hx-swap="outerHTML" hx-target="#list-items"
{ hx-swap="outerHTML"
input type="hidden" name="csrf" value=(csrf_token); {
input type="hidden" name="checked" value=(next_checked); input type="hidden" name="csrf" value=(csrf_token);
button id=(format!("item-check-{}", item.id)) class="check-button" type="submit" aria-label=(if item.checked { "Mark unchecked" } else { "Mark complete" }) { input type="hidden" name="checked" value=(next_checked);
@if item.checked { "" } @else { "" } button id=(format!("item-check-{}", item.id)) class="check-button" type="submit" aria-label=(if item.checked { "Mark unchecked" } else { "Mark complete" }) {
@if item.checked { "" } @else { "" }
}
} }
} @else if item.checked {
span class="check-button check-button-static" { "" }
} }
label class="item-copy" for=(format!("item-check-{}", item.id)) { label class="item-copy" for=(format!("item-check-{}", item.id)) {
@if !item.quantity.is_empty() { @if !item.quantity.is_empty() {
@@ -725,39 +995,41 @@ fn item_row(item: &Item, categories: &[Category], csrf_token: &str) -> Markup {
small { (item.note) } small { (item.note) }
} }
} }
button type="button" class="item-actions-button" aria-label="Item actions" onclick=(format!("document.getElementById('item-edit-{}').showModal()", item.id)) { "•••" } @if editable {
dialog id=(format!("item-edit-{}", item.id)) class="item-modal" { button type="button" class="item-actions-button" aria-label="Item actions" onclick=(format!("document.getElementById('item-edit-{}').showModal()", item.id)) { "•••" }
div class="item-modal-card" { dialog id=(format!("item-edit-{}", item.id)) class="item-modal" {
div class="item-modal-header" { div class="item-modal-card" {
h3 { (item.name) } div class="item-modal-header" {
button type="button" class="meal-picker-close" aria-label="Close" onclick="this.closest('dialog').close()" { "" } h3 { (item.name) }
} button type="button" class="meal-picker-close" aria-label="Close" onclick="this.closest('dialog').close()" { "" }
form }
hx-post=(format!("/lists/{}/items/{}/edit", item.list_id, item.id)) form
hx-target="#list-items" hx-post=(format!("/lists/{}/items/{}/edit", item.list_id, item.id))
hx-swap="outerHTML" hx-target="#list-items"
class="stack" hx-swap="outerHTML"
{ class="stack"
input type="hidden" name="csrf" value=(csrf_token); {
label { "Name" } input type="hidden" name="csrf" value=(csrf_token);
input id=(format!("item-edit-name-{}", item.id)) name="name" value=(item.name) maxlength="120" required; label { "Name" }
label { "Quantity" } input id=(format!("item-edit-name-{}", item.id)) name="name" value=(item.name) maxlength="120" required;
input id=(format!("item-edit-quantity-{}", item.id)) name="quantity" value=(item.quantity) maxlength="40"; label { "Category" }
label { "Note" } select id=(format!("item-edit-category-{}", item.id)) name="category_id" {
input id=(format!("item-edit-note-{}", item.id)) name="note" value=(item.note) maxlength="120"; (category_options(categories, item.category_id))
label { "Category" } }
select id=(format!("item-edit-category-{}", item.id)) name="category_id" { label { "Quantity" }
(category_options(categories, item.category_id)) input id=(format!("item-edit-quantity-{}", item.id)) name="quantity" value=(item.quantity) maxlength="40";
label { "Note" }
input id=(format!("item-edit-note-{}", item.id)) name="note" value=(item.note) maxlength="120";
button id=(format!("item-edit-save-{}", item.id)) class="button button-primary" type="submit" { "Save" }
}
form
hx-post=(format!("/lists/{}/items/{}/delete", item.list_id, item.id))
hx-target="#list-items"
hx-swap="outerHTML"
{
input type="hidden" name="csrf" value=(csrf_token);
button id=(format!("item-edit-delete-{}", item.id)) class="button button-danger" type="submit" { "Remove item" }
} }
button id=(format!("item-edit-save-{}", item.id)) class="button button-primary" type="submit" { "Save" }
}
form
hx-post=(format!("/lists/{}/items/{}/delete", item.list_id, item.id))
hx-target="#list-items"
hx-swap="outerHTML"
{
input type="hidden" name="csrf" value=(csrf_token);
button id=(format!("item-edit-delete-{}", item.id)) class="danger-link" type="submit" { "Remove item" }
} }
} }
} }
@@ -827,11 +1099,64 @@ pub fn live_list_fragments(
list: &GroceryList, list: &GroceryList,
items: &[Item], items: &[Item],
categories: &[Category], categories: &[Category],
list_meals: &[ListMeal],
csrf_token: &str, csrf_token: &str,
) -> Markup { ) -> Markup {
let editable = list.archived_at.is_none();
html! { html! {
(list_content_fragment(list, items, categories, csrf_token, true)) (list_items_fragment(list, items, categories, csrf_token, true, editable))
(categories_panel(categories, csrf_token, true)) (list_meals_panel(list_meals, list.id, csrf_token, true, editable))
}
}
pub fn list_meals_panel(
list_meals: &[ListMeal],
list_id: i64,
csrf_token: &str,
out_of_band: bool,
editable: bool,
) -> Markup {
let panel = html! {
div class="panel-heading" {
h2 { "Meals on this list" }
span class="count-badge" { (list_meals.len()) }
}
@if list_meals.is_empty() {
p class="muted" { "No meals added yet." }
} @else {
div class="list-meals" {
@for meal in list_meals {
div class="list-meal-row" {
span class="list-meal-icon" { "🍽" }
span class="list-meal-name" { (meal.name) }
@if editable {
form
hx-post=(format!("/lists/{}/meals/{}/remove", list_id, meal.id))
hx-target="#list-items"
hx-swap="outerHTML"
class="list-meal-remove"
{
input type="hidden" name="csrf" value=(csrf_token);
button type="submit" class="list-meal-remove-button" aria-label=(format!("Remove {} from list", meal.name)) { "" }
}
}
}
}
}
}
@if editable {
button class="button button-small add-meal-button" hx-get=(format!("/meals?picker={}", list_id)) hx-target="#meal-picker" hx-swap="innerHTML" { "+ Add meal" }
}
};
if out_of_band {
html! {
section id="list-meals-panel" class="panel list-meals-panel" hx-swap-oob="outerHTML" { (panel) }
}
} else {
html! {
section id="list-meals-panel" class="panel list-meals-panel" { (panel) }
}
} }
} }
@@ -919,6 +1244,31 @@ pub fn invite_result(url: &str) -> Markup {
} }
} }
/// Formats a Unix timestamp as a human-readable date (e.g. "7 Aug 2026").
fn format_date(timestamp: i64) -> String {
let days = timestamp.div_euclid(86_400);
let (y, m, d) = civil_from_days(days);
const MONTHS: [&str; 12] = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
format!("{} {} {}", d, MONTHS[(m - 1) as usize], y)
}
/// Converts a count of days since the Unix epoch into a (year, month, day)
/// civil date using Howard Hinnant's `civil_from_days` algorithm.
fn civil_from_days(z: i64) -> (i64, i64, i64) {
let z = z + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
(if m <= 2 { y + 1 } else { y }, m, d)
}
pub fn error_page(status: &str, message: &str) -> Markup { pub fn error_page(status: &str, message: &str) -> Markup {
page( page(
status, status,
@@ -943,10 +1293,10 @@ fn page(title: &str, user: Option<&User>, content: Markup) -> Markup {
meta name="viewport" content="width=device-width, initial-scale=1"; meta name="viewport" content="width=device-width, initial-scale=1";
title { (title) " · Sustenance" } title { (title) " · Sustenance" }
link rel="stylesheet" href="/static/style.css"; link rel="stylesheet" href="/static/style.css";
script src="https://unpkg.com/htmx.org@2.0.4" {} script src="https://unpkg.com/htmx.org@2.0.10" {}
script src="https://unpkg.com/htmx-ext-ws@2.0.2/ws.js" {} script src="https://unpkg.com/htmx-ext-ws@2.0.4/ws.js" {}
} }
body { body hx-boost="true" {
header class="site-header" { header class="site-header" {
a class="brand" href="/lists" { span class="brand-mark" { "S" } "Sustenance" } a class="brand" href="/lists" { span class="brand-mark" { "S" } "Sustenance" }
@if let Some(user) = user { @if let Some(user) = user {
+16
View File
@@ -0,0 +1,16 @@
// Toggle password visibility so users can check for typos, especially on mobile.
document.querySelectorAll(".password-toggle").forEach(function (button) {
button.addEventListener("pointerdown", function (event) {
// Toggle on press (not click) for an instant response. preventScroll avoids
// a scroll-to-input animation that makes rapid toggling feel laggy, and
// keeping focus on the input keeps the mobile keyboard open.
event.preventDefault();
var input = document.getElementById(button.getAttribute("data-toggle-for"));
if (!input) return;
var showing = input.type === "text";
input.type = showing ? "password" : "text";
button.textContent = showing ? "Show" : "Hide";
button.setAttribute("aria-label", showing ? "Show password" : "Hide password");
input.focus({ preventScroll: true });
});
});
+43 -1
View File
@@ -67,14 +67,25 @@ h3 { margin-bottom: 6px; font-size: 1rem; }
.muted { color: var(--muted); } .muted { color: var(--muted); }
.page-heading { display: flex; justify-content: space-between; align-items: end; margin-bottom: 34px; } .page-heading { display: flex; justify-content: space-between; align-items: end; margin-bottom: 34px; }
.page-heading h1.page-title { font-size: clamp(1.6rem, 3.2vw, 2.3rem); }
.dashboard-grid { display: grid; grid-template-columns: minmax(0, 1.5fr) minmax(260px, .8fr); gap: 22px; align-items: start; } .dashboard-grid { display: grid; grid-template-columns: minmax(0, 1.5fr) minmax(260px, .8fr); gap: 22px; align-items: start; }
.panel { padding: 26px; border: 1px solid rgba(221, 225, 210, .9); border-radius: 24px; background: rgba(255, 253, 248, .88); box-shadow: var(--shadow); } .panel { padding: 26px; border: 1px solid rgba(221, 225, 210, .9); border-radius: 24px; background: rgba(255, 253, 248, .88); box-shadow: var(--shadow); }
.panel-heading { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-bottom: 22px; } .panel-heading { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-bottom: 22px; }
.archive-link { margin-left: auto; color: var(--muted); font-size: .78rem; font-weight: 700; text-decoration: none; }
.archive-link:hover { color: var(--deep-sage); }
.count-badge { display: inline-grid; place-items: center; min-width: 27px; height: 27px; padding: 0 8px; border-radius: 99px; color: var(--deep-sage); background: #e8f0e1; font-size: .78rem; font-weight: 800; } .count-badge { display: inline-grid; place-items: center; min-width: 27px; height: 27px; padding: 0 8px; border-radius: 99px; color: var(--deep-sage); background: #e8f0e1; font-size: .78rem; font-weight: 800; }
.stack { display: grid; gap: 9px; } .stack { display: grid; gap: 9px; }
.stack label { color: var(--muted); font-size: .82rem; font-weight: 700; } .stack label { color: var(--muted); font-size: .82rem; font-weight: 700; }
input { width: 100%; min-height: 46px; padding: 10px 13px; border: 1px solid var(--line); border-radius: 12px; outline: none; color: var(--ink); background: #fff; } input { width: 100%; min-height: 46px; padding: 10px 13px; border: 1px solid var(--line); border-radius: 12px; outline: none; color: var(--ink); background: #fff; }
input:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113, 93, .12); } input:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113, 93, .12); }
.password-field { position: relative; }
.password-field input { padding-right: 64px; }
.password-toggle { position: absolute; top: 50%; right: 8px; transform: translateY(-50%); min-height: 32px; padding: 5px 10px; border: 0; border-radius: 9px; cursor: pointer; color: var(--deep-sage); background: #e7f0e1; font-weight: 800; font-size: .78rem; }
.password-toggle:hover { background: #dbe9d2; }
select { width: 100%; min-height: 46px; padding: 10px 34px 10px 13px; border: 1px solid var(--line); border-radius: 12px; outline: none; color: var(--ink); background: #fff; font: inherit; appearance: none; -webkit-appearance: none; background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path d='M4 6l4 4 4-4' fill='none' stroke='%2355715d' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/></svg>"); background-repeat: no-repeat; background-position: right 12px center; }
select:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113, 93, .12); }
select option { color: var(--ink); background: #fff; }
select option:checked { color: var(--deep-sage); font-weight: 700; }
textarea { width: 100%; padding: 10px 13px; border: 1px solid var(--line); border-radius: 12px; outline: none; color: var(--ink); background: #fff; font: inherit; resize: vertical; } textarea { width: 100%; padding: 10px 13px; border: 1px solid var(--line); border-radius: 12px; outline: none; color: var(--ink); background: #fff; font: inherit; resize: vertical; }
textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113, 93, .12); } textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113, 93, .12); }
.button { display: inline-flex; align-items: center; justify-content: center; min-height: 44px; padding: 10px 17px; border: 0; border-radius: 12px; cursor: pointer; text-decoration: none; font-weight: 800; transition: transform .16s ease, box-shadow .16s ease, background .16s ease; } .button { display: inline-flex; align-items: center; justify-content: center; min-height: 44px; padding: 10px 17px; border: 0; border-radius: 12px; cursor: pointer; text-decoration: none; font-weight: 800; transition: transform .16s ease, box-shadow .16s ease, background .16s ease; }
@@ -91,12 +102,18 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
.list-card-copy { display: grid; flex: 1; gap: 2px; } .list-card-copy { display: grid; flex: 1; gap: 2px; }
.list-card-copy small { color: var(--muted); font-size: .75rem; } .list-card-copy small { color: var(--muted); font-size: .75rem; }
.list-card-arrow { color: var(--muted); font-size: 1.25rem; } .list-card-arrow { color: var(--muted); font-size: 1.25rem; }
.archived-list-card { opacity: .72; }
.archived-list-card .list-card-icon { color: var(--muted); background: #eef0ea; }
.archived-list-card .list-card-copy { align-items: flex-start; }
.archived-list-card form { margin-left: auto; }
.archived-banner { margin-bottom: 18px; padding: 11px 14px; border: 1px solid var(--line); border-radius: 12px; color: var(--muted); background: #f1f3ec; font-size: .82rem; font-weight: 700; }
.empty-state { padding: 35px 18px 24px; text-align: center; color: var(--muted); } .empty-state { padding: 35px 18px 24px; text-align: center; color: var(--muted); }
.empty-mark { display: grid; place-items: center; width: 50px; height: 50px; margin: 0 auto 15px; border-radius: 18px; color: var(--deep-sage); background: #edf3e8; font-size: 1.8rem; } .empty-mark { display: grid; place-items: center; width: 50px; height: 50px; margin: 0 auto 15px; border-radius: 18px; color: var(--deep-sage); background: #edf3e8; font-size: 1.8rem; }
.empty-state h3 { color: var(--ink); } .empty-state h3 { color: var(--ink); }
.auth-card { width: min(100%, 480px); margin: 7vh auto 0; padding: clamp(27px, 6vw, 54px); border: 1px solid var(--line); border-radius: 28px; background: rgba(255, 253, 248, .9); box-shadow: var(--shadow); } .auth-card { width: min(100%, 480px); margin: 7vh auto 0; padding: clamp(27px, 6vw, 54px); border: 1px solid var(--line); border-radius: 28px; background: rgba(255, 253, 248, .9); box-shadow: var(--shadow); }
.auth-card .button { margin-top: 11px; } .auth-card .button { margin-top: 11px; }
#passkey-login { width: 100%; }
.auth-divider { display: flex; align-items: center; gap: 12px; margin: 20px 0 4px; color: var(--muted); font-size: .8rem; } .auth-divider { display: flex; align-items: center; gap: 12px; margin: 20px 0 4px; color: var(--muted); font-size: .8rem; }
.auth-divider::before, .auth-divider::after { content: ""; flex: 1; height: 1px; background: var(--line); } .auth-divider::before, .auth-divider::after { content: ""; flex: 1; height: 1px; background: var(--line); }
.passkey-list { display: grid; gap: 8px; margin-bottom: 16px; } .passkey-list { display: grid; gap: 8px; margin-bottom: 16px; }
@@ -107,6 +124,7 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
.auth-switch a { color: var(--deep-sage); font-weight: 800; } .auth-switch a { color: var(--deep-sage); font-weight: 800; }
.alert { margin-bottom: 18px; padding: 12px 14px; border-radius: 12px; font-size: .9rem; } .alert { margin-bottom: 18px; padding: 12px 14px; border-radius: 12px; font-size: .9rem; }
.alert-error { color: #874d40; background: #fbe7e0; } .alert-error { color: #874d40; background: #fbe7e0; }
.alert-success { color: #3d6b4f; background: #e4f2e6; }
.list-topbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 27px; } .list-topbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 27px; }
.back-link { color: var(--muted); font-size: .85rem; font-weight: 700; text-decoration: none; } .back-link { color: var(--muted); font-size: .85rem; font-weight: 700; text-decoration: none; }
@@ -126,7 +144,8 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
.list-heading { display: flex; justify-content: space-between; margin-bottom: 25px; } .list-heading { display: flex; justify-content: space-between; margin-bottom: 25px; }
.list-heading h1 { max-width: 100%; margin-bottom: 5px; overflow-wrap: anywhere; font-size: clamp(1.45rem, 2.8vw, 2.05rem); } .list-heading h1 { max-width: 100%; margin-bottom: 5px; overflow-wrap: anywhere; font-size: clamp(1.45rem, 2.8vw, 2.05rem); }
.list-meta { margin: 0; color: var(--muted); font-size: .85rem; } .list-meta { margin: 0; color: var(--muted); font-size: .85rem; }
.add-item-form { display: grid; grid-template-columns: minmax(0, 1fr) 90px 145px auto; gap: 8px; margin-bottom: 19px; } .meal-category-label { margin-left: 10px; color: var(--muted); font-size: .8em; font-weight: 500; white-space: nowrap; }
.add-item-form { display: grid; grid-template-columns: minmax(0, 1fr) 145px 90px auto; gap: 8px; margin-bottom: 19px; }
.add-item-form input { min-height: 50px; } .add-item-form input { min-height: 50px; }
.add-item-form select { min-height: 50px; } .add-item-form select { min-height: 50px; }
.add-button { min-height: 50px; } .add-button { min-height: 50px; }
@@ -134,11 +153,14 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
.item-list { display: grid; gap: 6px; } .item-list { display: grid; gap: 6px; }
.category-group + .category-group { margin-top: 18px; } .category-group + .category-group { margin-top: 18px; }
.category-heading { margin: 0 7px 4px; color: var(--deep-sage); font-size: .72rem; letter-spacing: .12em; text-transform: uppercase; } .category-heading { margin: 0 7px 4px; color: var(--deep-sage); font-size: .72rem; letter-spacing: .12em; text-transform: uppercase; }
.ingredients-divider { margin: 26px 0 18px; border: 0; border-top: 1px solid var(--line); }
.item-row { display: flex; align-items: center; gap: 12px; min-height: 66px; padding: 9px 7px 9px 10px; border-bottom: 1px solid #edf0e6; } .item-row { display: flex; align-items: center; gap: 12px; min-height: 66px; padding: 9px 7px 9px 10px; border-bottom: 1px solid #edf0e6; }
.item-row:last-child { border-bottom: 0; } .item-row:last-child { border-bottom: 0; }
.check-form { flex: 0 0 auto; } .check-form { flex: 0 0 auto; }
.check-button { display: grid; place-items: center; width: 28px; height: 28px; padding: 0; border: 2px solid #c8d6c1; border-radius: 9px; color: #fff; background: transparent; cursor: pointer; font-size: .88rem; font-weight: 900; } .check-button { display: grid; place-items: center; width: 28px; height: 28px; padding: 0; border: 2px solid #c8d6c1; border-radius: 9px; color: #fff; background: transparent; cursor: pointer; font-size: .88rem; font-weight: 900; }
.is-checked .check-button { border-color: var(--deep-sage); background: var(--deep-sage); } .is-checked .check-button { border-color: var(--deep-sage); background: var(--deep-sage); }
.check-button-static { cursor: default; }
.is-checked .check-button-static { border-color: var(--deep-sage); background: var(--deep-sage); }
.item-copy { display: grid; grid-template-columns: auto 1fr; flex: 1; min-width: 0; gap: 2px 7px; align-items: baseline; } .item-copy { display: grid; grid-template-columns: auto 1fr; flex: 1; min-width: 0; gap: 2px 7px; align-items: baseline; }
.item-copy strong { grid-column: 2; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .item-copy strong { grid-column: 2; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.item-qty { grid-column: 1; grid-row: 1; color: var(--muted); font-weight: 700; white-space: nowrap; } .item-qty { grid-column: 1; grid-row: 1; color: var(--muted); font-weight: 700; white-space: nowrap; }
@@ -207,6 +229,10 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
.edit-form { margin-bottom: 12px; } .edit-form { margin-bottom: 12px; }
.edit-form input { min-height: 38px; padding: 7px 10px; font-size: .85rem; } .edit-form input { min-height: 38px; padding: 7px 10px; font-size: .85rem; }
.danger-link { padding: 0; border: 0; color: var(--coral); background: none; cursor: pointer; font-size: .8rem; font-weight: 800; } .danger-link { padding: 0; border: 0; color: var(--coral); background: none; cursor: pointer; font-size: .8rem; font-weight: 800; }
.bordered-delete { padding: 7px 14px; border: 1px solid var(--coral); border-radius: 10px; background: none; }
.bordered-delete:hover { background: #fbeae4; }
.button-danger { width: 100%; color: var(--coral); background: #fbeae4; }
.button-danger:hover { background: #f7ddd4; }
.empty-items { padding: 34px 10px 18px; color: var(--muted); text-align: center; } .empty-items { padding: 34px 10px 18px; color: var(--muted); text-align: center; }
.empty-items-icon { display: block; margin-bottom: 7px; color: var(--yellow); font-size: 1.7rem; } .empty-items-icon { display: block; margin-bottom: 7px; color: var(--yellow); font-size: 1.7rem; }
.empty-items p { margin-bottom: 2px; color: var(--ink); font-weight: 800; } .empty-items p { margin-bottom: 2px; color: var(--ink); font-weight: 800; }
@@ -217,12 +243,28 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
.category-form input { min-height: 38px; padding: 7px 10px; font-size: .84rem; } .category-form input { min-height: 38px; padding: 7px 10px; font-size: .84rem; }
.category-list { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 14px; } .category-list { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 14px; }
.category-chip { padding: 5px 9px; border-radius: 99px; color: var(--deep-sage); background: #edf3e8; font-size: .72rem; font-weight: 800; } .category-chip { padding: 5px 9px; border-radius: 99px; color: var(--deep-sage); background: #edf3e8; font-size: .72rem; font-weight: 800; }
/* Meal categories side panel */
.meal-category-list { display: grid; gap: 2px; margin-top: 14px; }
.meal-category-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 7px 4px; border-bottom: 1px solid #edf0e6; }
.meal-category-row:last-child { border-bottom: 0; }
.meal-category-name { font-size: .9rem; font-weight: 700; }
.meal-category-delete { padding: 2px 6px; border: 0; border-radius: 7px; color: var(--muted); background: transparent; cursor: pointer; font-size: .8rem; line-height: 1; }
.meal-category-delete:hover { color: var(--coral); background: #fbeae4; }
.category-empty { margin: 13px 0 0; font-size: .8rem; } .category-empty { margin: 13px 0 0; font-size: .8rem; }
.category-result { margin-top: 10px; } .category-result { margin-top: 10px; }
.category-success { margin: 0; color: var(--deep-sage); font-size: .76rem; font-weight: 800; } .category-success { margin: 0; color: var(--deep-sage); font-size: .76rem; font-weight: 800; }
.presence-list { display: grid; gap: 12px; } .presence-list { display: grid; gap: 12px; }
.presence-person { display: flex; align-items: center; gap: 10px; font-size: .9rem; font-weight: 700; } .presence-person { display: flex; align-items: center; gap: 10px; font-size: .9rem; font-weight: 700; }
.avatar { display: grid; place-items: center; width: 32px; height: 32px; border-radius: 11px; color: var(--deep-sage); background: #e6f0df; font-size: .7rem; font-weight: 900; } .avatar { display: grid; place-items: center; width: 32px; height: 32px; border-radius: 11px; color: var(--deep-sage); background: #e6f0df; font-size: .7rem; font-weight: 900; }
.list-meals { display: grid; gap: 8px; }
.list-meal-row { display: flex; align-items: center; gap: 10px; padding: 6px 4px; border-bottom: 1px solid #edf0e6; }
.list-meal-row:last-child { border-bottom: 0; }
.list-meal-icon { display: grid; place-items: center; flex: 0 0 auto; width: 30px; height: 30px; border-radius: 10px; color: var(--deep-sage); background: #eef4e9; font-size: .95rem; }
.list-meal-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: .9rem; font-weight: 700; }
.list-meal-remove { margin: 0; flex: 0 0 auto; }
.list-meal-remove-button { padding: 2px 7px; border: 0; border-radius: 7px; color: var(--muted); background: transparent; cursor: pointer; font-size: .8rem; line-height: 1; }
.list-meal-remove-button:hover { color: var(--coral); background: #fbeae4; }
.list-meals-panel .add-meal-button { margin-top: 12px; width: 100%; }
.sharing-panel p, .tip-panel p { color: var(--muted); font-size: .86rem; } .sharing-panel p, .tip-panel p { color: var(--muted); font-size: .86rem; }
.invite-result { margin-top: 15px; } .invite-result { margin-top: 15px; }
.invite-link-result { padding: 11px; border-radius: 12px; background: #f1f5ec; } .invite-link-result { padding: 11px; border-radius: 12px; background: #f1f5ec; }