Compare commits
10
Commits
0.6.0
...
e77c546cb2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e77c546cb2 | ||
|
|
67e8520b08 | ||
|
|
842c4c9b0c | ||
|
|
58200b2bf9 | ||
|
|
35de0e1990 | ||
|
|
975cf38170 | ||
|
|
ab46e63bf0 | ||
|
|
3f7414707a | ||
|
|
cd99cd20df | ||
|
|
8bb0471a71 |
@@ -1,17 +0,0 @@
|
|||||||
when:
|
|
||||||
event: [push, pull_request]
|
|
||||||
|
|
||||||
steps:
|
|
||||||
e2e-build:
|
|
||||||
image: rust:1
|
|
||||||
commands:
|
|
||||||
- cargo build
|
|
||||||
|
|
||||||
e2e-test:
|
|
||||||
image: node:24
|
|
||||||
directory: e2e
|
|
||||||
commands:
|
|
||||||
- apt-get update
|
|
||||||
- apt-get install -y --no-install-recommends ca-certificates fonts-liberation libasound2 libatk-bridge2.0-0 libatk1.0-0 libcups2 libdbus-1-3 libdrm2 libgbm1 libglib2.0-0 libgtk-3-0 libnspr4 libnss3 libpango-1.0-0 libx11-6 libxcb1 libxcomposite1 libxdamage1 libxext6 libxfixes3 libxkbcommon0 libxrandr2 xdg-utils
|
|
||||||
- npm install && npx playwright install chromium
|
|
||||||
- npx playwright test
|
|
||||||
@@ -6,3 +6,13 @@ steps:
|
|||||||
image: rust:1
|
image: rust:1
|
||||||
commands:
|
commands:
|
||||||
- cargo test --all
|
- cargo test --all
|
||||||
|
- cargo build --all
|
||||||
|
|
||||||
|
e2e-test:
|
||||||
|
image: node:24
|
||||||
|
directory: e2e
|
||||||
|
commands:
|
||||||
|
- apt-get update
|
||||||
|
- apt-get install -y --no-install-recommends ca-certificates fonts-liberation libasound2 libatk-bridge2.0-0 libatk1.0-0 libcups2 libdbus-1-3 libdrm2 libgbm1 libglib2.0-0 libgtk-3-0 libnspr4 libnss3 libpango-1.0-0 libx11-6 libxcb1 libxcomposite1 libxdamage1 libxext6 libxfixes3 libxkbcommon0 libxrandr2 xdg-utils
|
||||||
|
- npm install && npx playwright install chromium
|
||||||
|
- npx playwright test
|
||||||
|
|||||||
Generated
+8
-1
@@ -116,6 +116,12 @@ dependencies = [
|
|||||||
"tracing",
|
"tracing",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "barcoders"
|
||||||
|
version = "2.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a3826fb6e98ec72c0c0db8c9a40af4932d16793021027469857e84c1b50a1e8f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "base64"
|
name = "base64"
|
||||||
version = "0.13.1"
|
version = "0.13.1"
|
||||||
@@ -1772,11 +1778,12 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sustenance"
|
name = "sustenance"
|
||||||
version = "0.4.0"
|
version = "0.7.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"argon2",
|
"argon2",
|
||||||
"async-trait",
|
"async-trait",
|
||||||
"axum",
|
"axum",
|
||||||
|
"barcoders",
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"hex",
|
"hex",
|
||||||
|
|||||||
+2
-1
@@ -1,12 +1,13 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "sustenance"
|
name = "sustenance"
|
||||||
version = "0.4.0"
|
version = "0.7.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
argon2 = "0.5"
|
argon2 = "0.5"
|
||||||
async-trait = "0.1"
|
async-trait = "0.1"
|
||||||
axum = { version = "0.8", features = ["ws"] }
|
axum = { version = "0.8", features = ["ws"] }
|
||||||
|
barcoders = { version = "2.0.0", features = ["svg"] }
|
||||||
base64 = "0.22"
|
base64 = "0.22"
|
||||||
futures-util = "0.3"
|
futures-util = "0.3"
|
||||||
hex = "0.4"
|
hex = "0.4"
|
||||||
|
|||||||
@@ -57,6 +57,8 @@ The file is optional — if it is missing or invalid, seeding is silently skippe
|
|||||||
- Global categories with common defaults seeded at startup and custom category creation
|
- Global categories with common defaults seeded at startup and custom category creation
|
||||||
- Items grouped by category and assigned from the add/edit forms
|
- Items grouped by category and assigned from the add/edit forms
|
||||||
- Meals with ingredients, markdown descriptions, and one-click "add meal to list"
|
- Meals with ingredients, markdown descriptions, and one-click "add meal to list"
|
||||||
|
- Rewards cards with store name and number, rendered as scannable Code 128 / Code 39 barcodes
|
||||||
|
- Single-card scan view that shows one barcode at a time and keeps the screen awake for scanning
|
||||||
- Server-authoritative last-write-wins updates
|
- Server-authoritative last-write-wins updates
|
||||||
- Per-list WebSocket updates with server-rendered htmx fragments
|
- Per-list WebSocket updates with server-rendered htmx fragments
|
||||||
- In-memory presence for members currently viewing a list
|
- In-memory presence for members currently viewing a list
|
||||||
|
|||||||
+12
-1
@@ -46,12 +46,23 @@ export async function addItem(page: Page, name: string, quantity = "") {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Adds an ingredient to the current meal page. */
|
/** Adds an ingredient to the current meal page. */
|
||||||
export async function addIngredient(page: Page, name: string, quantity = "") {
|
export async function addIngredient(
|
||||||
|
page: Page,
|
||||||
|
name: string,
|
||||||
|
quantity = "",
|
||||||
|
category?: string,
|
||||||
|
) {
|
||||||
await page.fill("#ingredient-name", name);
|
await page.fill("#ingredient-name", name);
|
||||||
|
if (category) {
|
||||||
|
await page.selectOption("#ingredient-category", { label: category });
|
||||||
|
}
|
||||||
if (quantity) {
|
if (quantity) {
|
||||||
await page.fill("#ingredient-quantity", quantity);
|
await page.fill("#ingredient-quantity", quantity);
|
||||||
}
|
}
|
||||||
await page.click("#add-ingredient-button");
|
await page.click("#add-ingredient-button");
|
||||||
|
// The form submit is hx-boosted (full body swap to the same URL), so wait for
|
||||||
|
// the new row to appear. This also acts as a settle point so the next action
|
||||||
|
// doesn't race the async body replacement and target a stale form.
|
||||||
await expect(page.locator(".ingredient-list").filter({ hasText: name })).toBeVisible();
|
await expect(page.locator(".ingredient-list").filter({ hasText: name })).toBeVisible();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { expect } from "@playwright/test";
|
||||||
|
import { test } from "../fixtures";
|
||||||
|
import { registerAndLogin, createList, createMeal } from "../helpers";
|
||||||
|
|
||||||
|
test("the meals page filters by name as you type", async ({ page }) => {
|
||||||
|
await registerAndLogin(page, "alice@example.com");
|
||||||
|
await createMeal(page, "Spaghetti Bolognese", "");
|
||||||
|
await createMeal(page, "Chicken Curry", "");
|
||||||
|
await createMeal(page, "Pancakes", "");
|
||||||
|
|
||||||
|
await page.goto("/meals");
|
||||||
|
await expect(page.locator(".list-card").filter({ hasText: "Spaghetti Bolognese" })).toBeVisible();
|
||||||
|
await expect(page.locator(".list-card").filter({ hasText: "Chicken Curry" })).toBeVisible();
|
||||||
|
await expect(page.locator(".list-card").filter({ hasText: "Pancakes" })).toBeVisible();
|
||||||
|
|
||||||
|
// Type a query; only matching meals remain.
|
||||||
|
await page.fill("#meal-search", "chicken");
|
||||||
|
await expect(page.locator(".list-card").filter({ hasText: "Chicken Curry" })).toBeVisible();
|
||||||
|
await expect(page.locator(".list-card").filter({ hasText: "Spaghetti Bolognese" })).toHaveCount(0);
|
||||||
|
await expect(page.locator(".list-card").filter({ hasText: "Pancakes" })).toHaveCount(0);
|
||||||
|
|
||||||
|
// Clearing the search restores all meals.
|
||||||
|
await page.fill("#meal-search", "");
|
||||||
|
await expect(page.locator(".list-card").filter({ hasText: "Spaghetti Bolognese" })).toBeVisible();
|
||||||
|
await expect(page.locator(".list-card").filter({ hasText: "Pancakes" })).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the meals page shows an empty state when nothing matches", async ({ page }) => {
|
||||||
|
await registerAndLogin(page, "alice@example.com");
|
||||||
|
await createMeal(page, "Spaghetti Bolognese", "");
|
||||||
|
|
||||||
|
await page.goto("/meals");
|
||||||
|
await page.fill("#meal-search", "zzzz");
|
||||||
|
await expect(page.locator(".meal-filter-empty")).toBeVisible();
|
||||||
|
await expect(page.locator(".list-card")).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the add-meal picker filters meals as you type", async ({ page }) => {
|
||||||
|
await registerAndLogin(page, "alice@example.com");
|
||||||
|
await createMeal(page, "Spaghetti Bolognese", "");
|
||||||
|
await createMeal(page, "Chicken Curry", "");
|
||||||
|
await createList(page, "Weekly shop");
|
||||||
|
|
||||||
|
await page.click(".add-meal-button");
|
||||||
|
const picker = page.locator(".meal-picker-backdrop");
|
||||||
|
await expect(picker).toBeVisible();
|
||||||
|
await expect(picker.locator(".meal-picker-button").filter({ hasText: "Spaghetti Bolognese" })).toBeVisible();
|
||||||
|
await expect(picker.locator(".meal-picker-button").filter({ hasText: "Chicken Curry" })).toBeVisible();
|
||||||
|
|
||||||
|
await picker.locator(".meal-filter").fill("curry");
|
||||||
|
await expect(picker.locator(".meal-picker-button").filter({ hasText: "Chicken Curry" })).toBeVisible();
|
||||||
|
await expect(picker.locator(".meal-picker-button").filter({ hasText: "Spaghetti Bolognese" })).toHaveCount(0);
|
||||||
|
|
||||||
|
// The search box keeps focus and the modal stays open.
|
||||||
|
await expect(picker.locator(".meal-filter")).toBeFocused();
|
||||||
|
await expect(picker).toBeVisible();
|
||||||
|
});
|
||||||
@@ -77,9 +77,7 @@ test("ingredients are grouped under their categories", async ({ page }) => {
|
|||||||
await createMeal(page, "Spaghetti Bolognese", "");
|
await createMeal(page, "Spaghetti Bolognese", "");
|
||||||
|
|
||||||
// Add an ingredient in the default "Produce" category.
|
// Add an ingredient in the default "Produce" category.
|
||||||
await page.fill("#ingredient-name", "Tomato");
|
await addIngredient(page, "Tomato", "", "Produce");
|
||||||
await page.selectOption("#ingredient-category", { label: "Produce" });
|
|
||||||
await page.click("#add-ingredient-button");
|
|
||||||
|
|
||||||
// Add one without a category.
|
// Add one without a category.
|
||||||
await addIngredient(page, "Penne");
|
await addIngredient(page, "Penne");
|
||||||
|
|||||||
@@ -0,0 +1,169 @@
|
|||||||
|
import { expect } from "@playwright/test";
|
||||||
|
import { test } from "../fixtures";
|
||||||
|
import { registerAndLogin } from "../helpers";
|
||||||
|
|
||||||
|
/** Navigates to the rewards cards page. */
|
||||||
|
async function gotoRewards(page: import("@playwright/test").Page) {
|
||||||
|
await page.goto("/rewards");
|
||||||
|
await expect(page.locator("h1")).toContainText("Rewards cards");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds a rewards card and lands back on the /rewards page with it rendered.
|
||||||
|
*/
|
||||||
|
async function addCard(
|
||||||
|
page: import("@playwright/test").Page,
|
||||||
|
storeName: string,
|
||||||
|
number: string,
|
||||||
|
symbology?: string,
|
||||||
|
) {
|
||||||
|
await page.fill("#store-name", storeName);
|
||||||
|
await page.fill("#card-number", number);
|
||||||
|
if (symbology) {
|
||||||
|
await page.selectOption("#symbology", symbology);
|
||||||
|
}
|
||||||
|
await page.click('button:has-text("Add card")');
|
||||||
|
await expect(page).toHaveURL(/\/rewards$/);
|
||||||
|
const card = page.locator(".rewards-card").filter({ hasText: storeName });
|
||||||
|
await expect(card).toBeVisible();
|
||||||
|
return card;
|
||||||
|
}
|
||||||
|
|
||||||
|
test("the rewards page shows an empty state before any cards are added", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await registerAndLogin(page, "alice@example.com");
|
||||||
|
await gotoRewards(page);
|
||||||
|
await expect(page.locator(".empty-state")).toContainText("No rewards cards yet");
|
||||||
|
await expect(page.locator(".rewards-card")).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the Rewards link is available in the site navigation", async ({ page }) => {
|
||||||
|
await registerAndLogin(page, "alice@example.com");
|
||||||
|
const nav = page.locator(".site-nav");
|
||||||
|
await expect(nav.locator('a[href="/rewards"]')).toHaveText("Rewards");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a user can add a rewards card and see its barcode", async ({ page }) => {
|
||||||
|
await registerAndLogin(page, "alice@example.com");
|
||||||
|
await gotoRewards(page);
|
||||||
|
|
||||||
|
const card = await addCard(page, "Kroger", "606171584511340224537");
|
||||||
|
|
||||||
|
// The card renders an inline SVG barcode and the store's card number.
|
||||||
|
await expect(card.locator(".rewards-barcode svg")).toBeVisible();
|
||||||
|
await expect(card.locator(".rewards-number")).toHaveText("606171584511340224537");
|
||||||
|
|
||||||
|
// The barcode should be included via the embedded SVG (Code 128 set B→C mix),
|
||||||
|
// not rendered client-side from scratch by an image.
|
||||||
|
const svg = card.locator(".rewards-barcode svg");
|
||||||
|
await expect(svg).toHaveAttribute("viewBox", /\d+ \d+/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a user can add a card as Code 39 and see its barcode", async ({ page }) => {
|
||||||
|
await registerAndLogin(page, "alice@example.com");
|
||||||
|
await gotoRewards(page);
|
||||||
|
|
||||||
|
const card = await addCard(page, "Safeway", "ABC123", "code39");
|
||||||
|
await expect(card.locator(".rewards-barcode svg")).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("multiple rewards cards are each rendered with their own barcode", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await registerAndLogin(page, "alice@example.com");
|
||||||
|
await gotoRewards(page);
|
||||||
|
|
||||||
|
await addCard(page, "Kroger", "606171584511340224537");
|
||||||
|
await addCard(page, "Safeway", "012345678901");
|
||||||
|
|
||||||
|
await expect(page.locator(".rewards-card")).toHaveCount(2);
|
||||||
|
await expect(page.locator(".rewards-card").filter({ hasText: "Kroger" })).toBeVisible();
|
||||||
|
await expect(page.locator(".rewards-card").filter({ hasText: "Safeway" })).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("removing a rewards card prompts for confirmation and deletes on accept", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await registerAndLogin(page, "alice@example.com");
|
||||||
|
await gotoRewards(page);
|
||||||
|
await addCard(page, "Kroger", "606171584511340224537");
|
||||||
|
|
||||||
|
await expect(page).toHaveURL(/\/rewards$/);
|
||||||
|
await expect(page.locator(".rewards-card")).toHaveCount(1);
|
||||||
|
|
||||||
|
page.on("dialog", (dialog) => dialog.accept());
|
||||||
|
await page.click('button:has-text("Remove")');
|
||||||
|
|
||||||
|
// The card is deleted and the empty state returns.
|
||||||
|
await expect(page.locator(".rewards-card")).toHaveCount(0);
|
||||||
|
await expect(page.locator(".empty-state")).toContainText("No rewards cards yet");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("cancelling the remove confirmation keeps the rewards card", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await registerAndLogin(page, "alice@example.com");
|
||||||
|
await gotoRewards(page);
|
||||||
|
await addCard(page, "Kroger", "606171584511340224537");
|
||||||
|
|
||||||
|
await expect(page.locator(".rewards-card")).toHaveCount(1);
|
||||||
|
|
||||||
|
page.on("dialog", (dialog) => dialog.dismiss());
|
||||||
|
await page.click('button:has-text("Remove")');
|
||||||
|
|
||||||
|
// The card must remain after cancelling.
|
||||||
|
await expect(page.locator(".rewards-card")).toHaveCount(1);
|
||||||
|
await expect(page.locator(".rewards-card").filter({ hasText: "Kroger" })).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a user can open a single-card scan view with only one barcode", async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await registerAndLogin(page, "alice@example.com");
|
||||||
|
await gotoRewards(page);
|
||||||
|
await addCard(page, "Kroger", "606171584511340224537");
|
||||||
|
await addCard(page, "Safeway", "012345678901");
|
||||||
|
|
||||||
|
// Click the Kroger card's barcode to open its focused scan view.
|
||||||
|
await page
|
||||||
|
.locator(".rewards-card")
|
||||||
|
.filter({ hasText: "Kroger" })
|
||||||
|
.locator(".rewards-card-link")
|
||||||
|
.click();
|
||||||
|
|
||||||
|
await expect(page).toHaveURL(/\/rewards\/\d+/);
|
||||||
|
// Only one barcode is rendered on the scan page.
|
||||||
|
await expect(page.locator(".scan-barcode svg")).toHaveCount(1);
|
||||||
|
await expect(page.locator(".scan-store")).toHaveText("Kroger");
|
||||||
|
await expect(page.locator(".scan-card .rewards-number")).toHaveText(
|
||||||
|
"606171584511340224537",
|
||||||
|
);
|
||||||
|
// The wake-lock script is loaded on the scan page.
|
||||||
|
await expect(page.locator('script[src*="rewards.js"]')).toHaveCount(1);
|
||||||
|
|
||||||
|
// Back link returns to the list.
|
||||||
|
await page.click('.scan-back');
|
||||||
|
await expect(page).toHaveURL(/\/rewards$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a scan view for another user's card is not accessible", async ({ page }) => {
|
||||||
|
await registerAndLogin(page, "alice@example.com");
|
||||||
|
await gotoRewards(page);
|
||||||
|
await addCard(page, "Kroger", "606171584511340224537");
|
||||||
|
|
||||||
|
// Grab the card id from the URL of the scan view.
|
||||||
|
await page
|
||||||
|
.locator(".rewards-card-link")
|
||||||
|
.click();
|
||||||
|
const url = page.url();
|
||||||
|
const cardId = url.split("/").pop();
|
||||||
|
|
||||||
|
// Sign out and sign in as a different user.
|
||||||
|
await page.click('button:has-text("Sign out")');
|
||||||
|
await registerAndLogin(page, "bob@example.com");
|
||||||
|
|
||||||
|
// Bob cannot view Alice's card.
|
||||||
|
await page.goto(`/rewards/${cardId}`);
|
||||||
|
await expect(page.locator(".scan-barcode svg")).toHaveCount(0);
|
||||||
|
});
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# Set the Cargo.toml version, commit it, and tag the commit with that version.
|
||||||
|
# Usage: just tag 1.2.3
|
||||||
|
tag ver:
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# Validate the version argument.
|
||||||
|
if [[ ! "{{ver}}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||||
|
echo "error: version must be in the form X.Y.Z (got '{{ver}}')" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Bump the version in Cargo.toml.
|
||||||
|
sed -i -E "s/^version = \".*\"/version = \"{{ver}}\"/" Cargo.toml
|
||||||
|
|
||||||
|
# Regenerate Cargo.lock so it reflects the new version.
|
||||||
|
cargo build
|
||||||
|
|
||||||
|
# Stage, commit, and tag.
|
||||||
|
git add Cargo.toml Cargo.lock
|
||||||
|
git commit -m "version {{ver}} [skip ci]"
|
||||||
|
git tag "{{ver}}"
|
||||||
|
|
||||||
|
# Run the Rust unit tests.
|
||||||
|
# Usage: just test
|
||||||
|
test:
|
||||||
|
cargo test --all
|
||||||
|
|
||||||
|
# Format the Rust code.
|
||||||
|
# Usage: just fmt
|
||||||
|
fmt:
|
||||||
|
cargo fmt --all
|
||||||
|
|
||||||
|
# Run the end-to-end Playwright tests.
|
||||||
|
# Usage: just e2e
|
||||||
|
e2e:
|
||||||
|
cd e2e && npm test
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
CREATE TABLE rewards_cards (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
store_name TEXT NOT NULL,
|
||||||
|
number TEXT NOT NULL,
|
||||||
|
symbology TEXT NOT NULL DEFAULT 'code128',
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX rewards_cards_user_idx ON rewards_cards(user_id);
|
||||||
@@ -65,8 +65,14 @@ pub static STORE: LazyLock<StaticAssetStore> = LazyLock::new(|| {
|
|||||||
"passkey-login.js" => "../static/passkey-login.js",
|
"passkey-login.js" => "../static/passkey-login.js",
|
||||||
"passkey-register.js" => "../static/passkey-register.js",
|
"passkey-register.js" => "../static/passkey-register.js",
|
||||||
"password-toggle.js" => "../static/password-toggle.js",
|
"password-toggle.js" => "../static/password-toggle.js",
|
||||||
|
"rewards.js" => "../static/rewards.js",
|
||||||
"htmx.min.js" => "../static/htmx.min.js",
|
"htmx.min.js" => "../static/htmx.min.js",
|
||||||
|
"idiomorph-ext.min.js" => "../static/idiomorph-ext.min.js",
|
||||||
"htmx-ws.min.js" => "../static/htmx-ws.min.js",
|
"htmx-ws.min.js" => "../static/htmx-ws.min.js",
|
||||||
|
"favicon.ico" => "../static/favicon.ico",
|
||||||
|
"favicon-32x32.png" => "../static/favicon-32x32.png",
|
||||||
|
"apple-touch-icon.png" => "../static/apple-touch-icon.png",
|
||||||
|
"logo.svg" => "../static/logo.svg",
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -113,3 +113,19 @@ pub struct PresenceUser {
|
|||||||
pub user_id: i64,
|
pub user_id: i64,
|
||||||
pub display_name: String,
|
pub display_name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A stored rewards-card number that can be shown as a scannable barcode.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct RewardsCard {
|
||||||
|
pub id: i64,
|
||||||
|
/// The owner of this card.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub user_id: i64,
|
||||||
|
pub store_name: String,
|
||||||
|
pub number: String,
|
||||||
|
/// Symbology used to render the barcode (e.g. "code128", "code39").
|
||||||
|
pub symbology: String,
|
||||||
|
/// When the card was added.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub created_at: i64,
|
||||||
|
}
|
||||||
|
|||||||
+136
-5
@@ -23,7 +23,9 @@ use tracing::{Level, error, warn};
|
|||||||
use crate::assets;
|
use crate::assets;
|
||||||
use crate::domain::{DomainError, SessionUser};
|
use crate::domain::{DomainError, SessionUser};
|
||||||
use crate::ports::{HubEvent, RealtimeNotifier};
|
use crate::ports::{HubEvent, RealtimeNotifier};
|
||||||
use crate::services::{AuthService, InvitationService, ListService, MealService};
|
use crate::services::{
|
||||||
|
AuthService, InvitationService, ListService, MealService, RewardsCardService,
|
||||||
|
};
|
||||||
use crate::views;
|
use crate::views;
|
||||||
use crate::webauthn::WebAuthnService;
|
use crate::webauthn::WebAuthnService;
|
||||||
|
|
||||||
@@ -33,6 +35,7 @@ pub struct AppState {
|
|||||||
pub lists: Arc<ListService>,
|
pub lists: Arc<ListService>,
|
||||||
pub meals: Arc<MealService>,
|
pub meals: Arc<MealService>,
|
||||||
pub invitations: Arc<InvitationService>,
|
pub invitations: Arc<InvitationService>,
|
||||||
|
pub rewards_cards: Arc<RewardsCardService>,
|
||||||
pub webauthn: Arc<WebAuthnService>,
|
pub webauthn: Arc<WebAuthnService>,
|
||||||
pub realtime: Arc<dyn RealtimeNotifier>,
|
pub realtime: Arc<dyn RealtimeNotifier>,
|
||||||
pub cookie_secure: bool,
|
pub cookie_secure: bool,
|
||||||
@@ -130,6 +133,9 @@ pub fn build_router(state: AppState) -> Router {
|
|||||||
"/lists/{list_id}/meals/{list_meal_id}/remove",
|
"/lists/{list_id}/meals/{list_meal_id}/remove",
|
||||||
post(remove_meal_from_list),
|
post(remove_meal_from_list),
|
||||||
)
|
)
|
||||||
|
.route("/rewards", get(rewards_page).post(create_rewards_card))
|
||||||
|
.route("/rewards/{card_id}", get(rewards_scan_page))
|
||||||
|
.route("/rewards/{card_id}/delete", post(delete_rewards_card))
|
||||||
.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))
|
||||||
@@ -261,6 +267,14 @@ struct CategoryForm {
|
|||||||
csrf: String,
|
csrf: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct RewardsCardForm {
|
||||||
|
store_name: String,
|
||||||
|
number: String,
|
||||||
|
symbology: String,
|
||||||
|
csrf: String,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
struct PasskeyRegisterStartForm {
|
struct PasskeyRegisterStartForm {
|
||||||
csrf: String,
|
csrf: String,
|
||||||
@@ -327,6 +341,7 @@ struct AddMealForm {
|
|||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
struct MealPickerQuery {
|
struct MealPickerQuery {
|
||||||
picker: Option<i64>,
|
picker: Option<i64>,
|
||||||
|
q: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn home() -> Redirect {
|
async fn home() -> Redirect {
|
||||||
@@ -342,8 +357,11 @@ async fn static_asset(Path(path): Path<String>) -> Response {
|
|||||||
let Some(asset) = assets::STORE.get(&path) else {
|
let Some(asset) = assets::STORE.get(&path) else {
|
||||||
return StatusCode::NOT_FOUND.into_response();
|
return StatusCode::NOT_FOUND.into_response();
|
||||||
};
|
};
|
||||||
let mime = match path.as_str() {
|
let mime = match path.rsplit('.').next() {
|
||||||
"style.css" => "text/css",
|
Some("css") => "text/css",
|
||||||
|
Some("ico") => "image/x-icon",
|
||||||
|
Some("png") => "image/png",
|
||||||
|
Some("svg") => "image/svg+xml",
|
||||||
_ => "application/javascript",
|
_ => "application/javascript",
|
||||||
};
|
};
|
||||||
let mut response = ([(header::CONTENT_TYPE, mime)], asset.data).into_response();
|
let mut response = ([(header::CONTENT_TYPE, mime)], asset.data).into_response();
|
||||||
@@ -816,19 +834,131 @@ async fn delete_meal_category(
|
|||||||
Ok(Redirect::to("/meals").into_response())
|
Ok(Redirect::to("/meals").into_response())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn rewards_page(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
user: CurrentUser,
|
||||||
|
) -> Result<Response, AppError> {
|
||||||
|
let cards = state.rewards_cards.list_cards(user.session.user.id).await?;
|
||||||
|
Ok(html_response(views::rewards_page(
|
||||||
|
&user.session.user,
|
||||||
|
&cards,
|
||||||
|
&user.session.csrf_token,
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn rewards_scan_page(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
user: CurrentUser,
|
||||||
|
Path(card_id): Path<i64>,
|
||||||
|
) -> Result<Response, AppError> {
|
||||||
|
let card = state
|
||||||
|
.rewards_cards
|
||||||
|
.get_card(user.session.user.id, card_id)
|
||||||
|
.await?
|
||||||
|
.ok_or(AppError::NotFound)?;
|
||||||
|
Ok(html_response(views::rewards_scan_page(
|
||||||
|
&user.session.user,
|
||||||
|
&card,
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create_rewards_card(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
user: CurrentUser,
|
||||||
|
LoggedForm(form): LoggedForm<RewardsCardForm>,
|
||||||
|
) -> Result<Response, AppError> {
|
||||||
|
verify_csrf(&user, &form.csrf)?;
|
||||||
|
let store_name = form.store_name.trim().to_owned();
|
||||||
|
let number = form.number.trim().to_owned();
|
||||||
|
let symbology = normalize_symbology(&form.symbology);
|
||||||
|
if store_name.is_empty() || store_name.chars().count() > 60 {
|
||||||
|
return Err(AppError::BadRequest(
|
||||||
|
"Store names must be between 1 and 60 characters.".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if number.is_empty() || number.chars().count() > 80 {
|
||||||
|
return Err(AppError::BadRequest(
|
||||||
|
"Card numbers must be between 1 and 80 characters.".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
state
|
||||||
|
.rewards_cards
|
||||||
|
.create_card(user.session.user.id, store_name, number, symbology)
|
||||||
|
.await?;
|
||||||
|
Ok(Redirect::to("/rewards").into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_rewards_card(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
user: CurrentUser,
|
||||||
|
Path(card_id): Path<i64>,
|
||||||
|
LoggedForm(form): LoggedForm<CsrfForm>,
|
||||||
|
) -> Result<Response, AppError> {
|
||||||
|
verify_csrf(&user, &form.csrf)?;
|
||||||
|
state
|
||||||
|
.rewards_cards
|
||||||
|
.delete_card(user.session.user.id, card_id)
|
||||||
|
.await?;
|
||||||
|
Ok(Redirect::to("/rewards").into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Normalizes a submitted symbology value to a known barcode type, falling
|
||||||
|
/// back to Code 128 for unknown or empty values.
|
||||||
|
fn normalize_symbology(value: &str) -> String {
|
||||||
|
match value.trim().to_ascii_lowercase().as_str() {
|
||||||
|
"code39" => "code39".to_owned(),
|
||||||
|
_ => "code128".to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
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>,
|
||||||
|
headers: HeaderMap,
|
||||||
) -> Result<Response, AppError> {
|
) -> Result<Response, AppError> {
|
||||||
let meals = state.meals.list_meals().await?;
|
let q = query.q.clone().unwrap_or_default();
|
||||||
|
let meals = state.meals.list_meals(&q).await?;
|
||||||
let meal_categories = state.meals.list_meal_categories().await?;
|
let meal_categories = state.meals.list_meal_categories().await?;
|
||||||
|
let is_htmx = headers
|
||||||
|
.get("hx-request")
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.is_some_and(|value| value == "true");
|
||||||
|
// A boosted navigation (e.g. the category form's POST redirect) also sends
|
||||||
|
// `HX-Request: true`, but must render the full page, not just the results
|
||||||
|
// fragment. Only a live search (an `hx-get` on the filter box) swaps the
|
||||||
|
// fragment. htmx marks boosted requests with `HX-Boosted: true`.
|
||||||
|
let is_boosted = headers
|
||||||
|
.get("hx-boosted")
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.is_some_and(|value| value == "true");
|
||||||
if let Some(list_id) = query.picker {
|
if let Some(list_id) = query.picker {
|
||||||
return Ok(html_response(views::meal_picker(
|
if query.q.is_some() {
|
||||||
|
// Live search inside the picker: swap only the grouped rows, keeping
|
||||||
|
// the modal and search box focused. The initial picker load has no
|
||||||
|
// `q`, so it falls through to the full modal below.
|
||||||
|
return Ok(html_response(views::meal_picker_results(
|
||||||
|
&meals,
|
||||||
|
&meal_categories,
|
||||||
|
list_id,
|
||||||
|
&user.session.csrf_token,
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let picker = views::meal_picker(
|
||||||
&meals,
|
&meals,
|
||||||
&meal_categories,
|
&meal_categories,
|
||||||
list_id,
|
list_id,
|
||||||
&user.session.csrf_token,
|
&user.session.csrf_token,
|
||||||
|
&q,
|
||||||
|
);
|
||||||
|
return Ok(html_response(picker));
|
||||||
|
}
|
||||||
|
if is_htmx && !is_boosted {
|
||||||
|
// Live search on the meals page: swap only the grouped results.
|
||||||
|
return Ok(html_response(views::meal_results(
|
||||||
|
&meals,
|
||||||
|
&meal_categories,
|
||||||
|
&q,
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
Ok(html_response(views::meals_page(
|
Ok(html_response(views::meals_page(
|
||||||
@@ -836,6 +966,7 @@ async fn meals_page(
|
|||||||
&meals,
|
&meals,
|
||||||
&meal_categories,
|
&meal_categories,
|
||||||
&user.session.csrf_token,
|
&user.session.csrf_token,
|
||||||
|
&q,
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+12
-3
@@ -22,15 +22,18 @@ use crate::hub::InMemoryHub;
|
|||||||
use crate::ports::{
|
use crate::ports::{
|
||||||
CategoryRepository, InvitationRepository, ItemRepository, ListMealRepository, ListRepository,
|
CategoryRepository, InvitationRepository, ItemRepository, ListMealRepository, ListRepository,
|
||||||
MealCategoryRepository, MealIngredientRepository, MealRepository, PasskeyRepository,
|
MealCategoryRepository, MealIngredientRepository, MealRepository, PasskeyRepository,
|
||||||
PasswordHasher, RealtimeNotifier, SessionRepository, TokenGenerator, UserRepository,
|
PasswordHasher, RealtimeNotifier, RewardsCardRepository, 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, RewardsCardService,
|
||||||
|
};
|
||||||
use crate::sqlite::{
|
use crate::sqlite::{
|
||||||
SqliteCategoryRepository, SqliteDatabase, SqliteInvitationRepository, SqliteItemRepository,
|
SqliteCategoryRepository, SqliteDatabase, SqliteInvitationRepository, SqliteItemRepository,
|
||||||
SqliteListMealRepository, SqliteListRepository, SqliteMealCategoryRepository,
|
SqliteListMealRepository, SqliteListRepository, SqliteMealCategoryRepository,
|
||||||
SqliteMealIngredientRepository, SqliteMealRepository, SqlitePasskeyRepository,
|
SqliteMealIngredientRepository, SqliteMealRepository, SqlitePasskeyRepository,
|
||||||
SqliteSessionRepository, SqliteUserRepository,
|
SqliteRewardsCardRepository, SqliteSessionRepository, SqliteUserRepository,
|
||||||
};
|
};
|
||||||
use crate::webauthn::{AppWebauthnConfig, WebAuthnService};
|
use crate::webauthn::{AppWebauthnConfig, WebAuthnService};
|
||||||
|
|
||||||
@@ -90,6 +93,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let meal_categories: Arc<dyn MealCategoryRepository> = Arc::new(SqliteMealCategoryRepository);
|
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 rewards_cards: Arc<dyn RewardsCardRepository> = Arc::new(SqliteRewardsCardRepository);
|
||||||
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2PasswordHasher);
|
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2PasswordHasher);
|
||||||
let tokens: Arc<dyn TokenGenerator> = Arc::new(RandomTokenGenerator);
|
let tokens: Arc<dyn TokenGenerator> = Arc::new(RandomTokenGenerator);
|
||||||
let realtime: Arc<dyn RealtimeNotifier> = Arc::new(InMemoryHub::default());
|
let realtime: Arc<dyn RealtimeNotifier> = Arc::new(InMemoryHub::default());
|
||||||
@@ -114,6 +118,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
Arc::clone(&invitations),
|
Arc::clone(&invitations),
|
||||||
Arc::clone(&tokens),
|
Arc::clone(&tokens),
|
||||||
));
|
));
|
||||||
|
let rewards_cards_service = Arc::new(RewardsCardService::new(
|
||||||
|
db.clone(),
|
||||||
|
Arc::clone(&rewards_cards),
|
||||||
|
));
|
||||||
let meals_service = Arc::new(MealService::new(
|
let meals_service = Arc::new(MealService::new(
|
||||||
db.clone(),
|
db.clone(),
|
||||||
Arc::clone(&meals),
|
Arc::clone(&meals),
|
||||||
@@ -157,6 +165,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
lists: lists_service,
|
lists: lists_service,
|
||||||
meals: meals_service,
|
meals: meals_service,
|
||||||
invitations: invitations_service,
|
invitations: invitations_service,
|
||||||
|
rewards_cards: rewards_cards_service,
|
||||||
webauthn: webauthn_service,
|
webauthn: webauthn_service,
|
||||||
realtime,
|
realtime,
|
||||||
cookie_secure,
|
cookie_secure,
|
||||||
|
|||||||
+32
-2
@@ -3,7 +3,7 @@ use sqlx::SqliteConnection;
|
|||||||
|
|
||||||
use crate::domain::{
|
use crate::domain::{
|
||||||
Category, DomainResult, GroceryList, Item, ListMeal, Meal, MealCategory, MealIngredient,
|
Category, DomainResult, GroceryList, Item, ListMeal, Meal, MealCategory, MealIngredient,
|
||||||
Passkey, PresenceUser, SessionUser, User,
|
Passkey, PresenceUser, RewardsCard, SessionUser, User,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Repositories take `&mut SqliteConnection` (which a `Transaction` derefs to),
|
/// Repositories take `&mut SqliteConnection` (which a `Transaction` derefs to),
|
||||||
@@ -238,7 +238,7 @@ pub trait MealRepository: Send + Sync {
|
|||||||
txn: &mut SqliteConnection,
|
txn: &mut SqliteConnection,
|
||||||
meal_id: i64,
|
meal_id: i64,
|
||||||
) -> DomainResult<Option<Meal>>;
|
) -> DomainResult<Option<Meal>>;
|
||||||
async fn list_meals(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<Meal>>;
|
async fn list_meals(&self, txn: &mut SqliteConnection, query: &str) -> DomainResult<Vec<Meal>>;
|
||||||
async fn update_meal(
|
async fn update_meal(
|
||||||
&self,
|
&self,
|
||||||
txn: &mut SqliteConnection,
|
txn: &mut SqliteConnection,
|
||||||
@@ -314,3 +314,33 @@ pub enum HubEvent {
|
|||||||
ListChanged { list_id: i64, revision: i64 },
|
ListChanged { list_id: i64, revision: i64 },
|
||||||
PresenceChanged { list_id: i64 },
|
PresenceChanged { list_id: i64 },
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Stores and retrieves a user's rewards cards.
|
||||||
|
#[async_trait]
|
||||||
|
pub trait RewardsCardRepository: Send + Sync {
|
||||||
|
async fn list_cards(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
user_id: i64,
|
||||||
|
) -> DomainResult<Vec<RewardsCard>>;
|
||||||
|
async fn get_card(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
user_id: i64,
|
||||||
|
card_id: i64,
|
||||||
|
) -> DomainResult<Option<RewardsCard>>;
|
||||||
|
async fn create_card(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
user_id: i64,
|
||||||
|
store_name: String,
|
||||||
|
number: String,
|
||||||
|
symbology: String,
|
||||||
|
) -> DomainResult<RewardsCard>;
|
||||||
|
async fn delete_card(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
user_id: i64,
|
||||||
|
card_id: i64,
|
||||||
|
) -> DomainResult<()>;
|
||||||
|
}
|
||||||
|
|||||||
+57
-4
@@ -1,12 +1,13 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use crate::domain::{
|
use crate::domain::{
|
||||||
DomainError, DomainResult, GroceryList, Item, ListMeal, Meal, MealCategory, SessionUser, User,
|
DomainError, DomainResult, GroceryList, Item, ListMeal, Meal, MealCategory, RewardsCard,
|
||||||
|
SessionUser, User,
|
||||||
};
|
};
|
||||||
use crate::ports::{
|
use crate::ports::{
|
||||||
CategoryRepository, InvitationRepository, ItemRepository, ListMealRepository, ListRepository,
|
CategoryRepository, InvitationRepository, ItemRepository, ListMealRepository, ListRepository,
|
||||||
MealCategoryRepository, MealIngredientRepository, MealRepository, NewItem, PasswordHasher,
|
MealCategoryRepository, MealIngredientRepository, MealRepository, NewItem, PasswordHasher,
|
||||||
RealtimeNotifier, SessionRepository, TokenGenerator, UserRepository,
|
RealtimeNotifier, RewardsCardRepository, SessionRepository, TokenGenerator, UserRepository,
|
||||||
};
|
};
|
||||||
use crate::sqlite::SqliteDatabase;
|
use crate::sqlite::SqliteDatabase;
|
||||||
|
|
||||||
@@ -389,10 +390,11 @@ impl MealService {
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_meals(&self) -> DomainResult<Vec<Meal>> {
|
pub async fn list_meals(&self, query: &str) -> DomainResult<Vec<Meal>> {
|
||||||
let meals = Arc::clone(&self.meals);
|
let meals = Arc::clone(&self.meals);
|
||||||
|
let query = query.to_owned();
|
||||||
self.db
|
self.db
|
||||||
.run(move |txn| Box::pin(async move { meals.list_meals(txn).await }))
|
.run(move |txn| Box::pin(async move { meals.list_meals(txn, &query).await }))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -628,3 +630,54 @@ impl InvitationService {
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct RewardsCardService {
|
||||||
|
db: SqliteDatabase,
|
||||||
|
cards: Arc<dyn RewardsCardRepository>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RewardsCardService {
|
||||||
|
pub fn new(db: SqliteDatabase, cards: Arc<dyn RewardsCardRepository>) -> Self {
|
||||||
|
Self { db, cards }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list_cards(&self, user_id: i64) -> DomainResult<Vec<RewardsCard>> {
|
||||||
|
let cards = Arc::clone(&self.cards);
|
||||||
|
self.db
|
||||||
|
.run(move |txn| Box::pin(async move { cards.list_cards(txn, user_id).await }))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_card(&self, user_id: i64, card_id: i64) -> DomainResult<Option<RewardsCard>> {
|
||||||
|
let cards = Arc::clone(&self.cards);
|
||||||
|
self.db
|
||||||
|
.run(move |txn| Box::pin(async move { cards.get_card(txn, user_id, card_id).await }))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_card(
|
||||||
|
&self,
|
||||||
|
user_id: i64,
|
||||||
|
store_name: String,
|
||||||
|
number: String,
|
||||||
|
symbology: String,
|
||||||
|
) -> DomainResult<RewardsCard> {
|
||||||
|
let cards = Arc::clone(&self.cards);
|
||||||
|
self.db
|
||||||
|
.run(move |txn| {
|
||||||
|
Box::pin(async move {
|
||||||
|
cards
|
||||||
|
.create_card(txn, user_id, store_name, number, symbology)
|
||||||
|
.await
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_card(&self, user_id: i64, card_id: i64) -> DomainResult<()> {
|
||||||
|
let cards = Arc::clone(&self.cards);
|
||||||
|
self.db
|
||||||
|
.run(move |txn| Box::pin(async move { cards.delete_card(txn, user_id, card_id).await }))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+341
-4
@@ -8,12 +8,12 @@ use sqlx::{Connection, Row, SqliteConnection, SqlitePool, sqlite::SqliteConnectO
|
|||||||
|
|
||||||
use crate::domain::{
|
use crate::domain::{
|
||||||
Category, DomainError, DomainResult, GroceryList, Item, ListMeal, Meal, MealCategory,
|
Category, DomainError, DomainResult, GroceryList, Item, ListMeal, Meal, MealCategory,
|
||||||
MealIngredient, Passkey, SessionUser, User,
|
MealIngredient, Passkey, RewardsCard, SessionUser, User,
|
||||||
};
|
};
|
||||||
use crate::ports::{
|
use crate::ports::{
|
||||||
CategoryRepository, InvitationRepository, ItemRepository, ListMealRepository, ListRepository,
|
CategoryRepository, InvitationRepository, ItemRepository, ListMealRepository, ListRepository,
|
||||||
MealCategoryRepository, MealIngredientRepository, MealRepository, NewItem, PasskeyRepository,
|
MealCategoryRepository, MealIngredientRepository, MealRepository, NewItem, PasskeyRepository,
|
||||||
SessionRepository, UserRepository,
|
RewardsCardRepository, SessionRepository, UserRepository,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// The embedded SQL migrations, applied automatically on startup.
|
/// The embedded SQL migrations, applied automatically on startup.
|
||||||
@@ -1097,12 +1097,15 @@ impl MealRepository for SqliteMealRepository {
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn list_meals(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<Meal>> {
|
async fn list_meals(&self, txn: &mut SqliteConnection, query: &str) -> DomainResult<Vec<Meal>> {
|
||||||
let rows = sqlx::query(
|
let rows = sqlx::query(
|
||||||
"SELECT id, name, description, category_id
|
"SELECT id, name, description, category_id
|
||||||
FROM meals
|
FROM meals
|
||||||
|
WHERE (?1 = '' OR name LIKE '%' || ?2 || '%' ESCAPE '\\')
|
||||||
ORDER BY name COLLATE NOCASE ASC",
|
ORDER BY name COLLATE NOCASE ASC",
|
||||||
)
|
)
|
||||||
|
.bind(query)
|
||||||
|
.bind(escape_like(query))
|
||||||
.fetch_all(&mut *txn)
|
.fetch_all(&mut *txn)
|
||||||
.await
|
.await
|
||||||
.map_err(db_error)?;
|
.map_err(db_error)?;
|
||||||
@@ -1292,6 +1295,115 @@ impl MealIngredientRepository for SqliteMealIngredientRepository {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct SqliteRewardsCardRepository;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl RewardsCardRepository for SqliteRewardsCardRepository {
|
||||||
|
async fn list_cards(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
user_id: i64,
|
||||||
|
) -> DomainResult<Vec<RewardsCard>> {
|
||||||
|
let rows = sqlx::query(
|
||||||
|
"SELECT id, user_id, store_name, number, symbology, created_at
|
||||||
|
FROM rewards_cards
|
||||||
|
WHERE user_id = ?1
|
||||||
|
ORDER BY created_at DESC, id DESC",
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_all(&mut *txn)
|
||||||
|
.await
|
||||||
|
.map_err(db_error)?;
|
||||||
|
Ok(rows.into_iter().map(map_rewards_card_row).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_card(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
user_id: i64,
|
||||||
|
card_id: i64,
|
||||||
|
) -> DomainResult<Option<RewardsCard>> {
|
||||||
|
let row = sqlx::query(
|
||||||
|
"SELECT id, user_id, store_name, number, symbology, created_at
|
||||||
|
FROM rewards_cards
|
||||||
|
WHERE id = ?1 AND user_id = ?2",
|
||||||
|
)
|
||||||
|
.bind(card_id)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_optional(&mut *txn)
|
||||||
|
.await
|
||||||
|
.map_err(db_error)?;
|
||||||
|
Ok(row.map(map_rewards_card_row))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create_card(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
user_id: i64,
|
||||||
|
store_name: String,
|
||||||
|
number: String,
|
||||||
|
symbology: String,
|
||||||
|
) -> DomainResult<RewardsCard> {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO rewards_cards (user_id, store_name, number, symbology, created_at)
|
||||||
|
VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.bind(&store_name)
|
||||||
|
.bind(&number)
|
||||||
|
.bind(&symbology)
|
||||||
|
.bind(now())
|
||||||
|
.execute(&mut *txn)
|
||||||
|
.await
|
||||||
|
.map_err(db_error)?;
|
||||||
|
let card_id = sqlx::query("SELECT last_insert_rowid()")
|
||||||
|
.fetch_one(&mut *txn)
|
||||||
|
.await
|
||||||
|
.map_err(db_error)?
|
||||||
|
.get::<i64, _>(0);
|
||||||
|
Ok(RewardsCard {
|
||||||
|
id: card_id,
|
||||||
|
user_id,
|
||||||
|
store_name,
|
||||||
|
number,
|
||||||
|
symbology,
|
||||||
|
created_at: now(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_card(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
user_id: i64,
|
||||||
|
card_id: i64,
|
||||||
|
) -> DomainResult<()> {
|
||||||
|
let changed = sqlx::query("DELETE FROM rewards_cards WHERE id = ?1 AND user_id = ?2")
|
||||||
|
.bind(card_id)
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(&mut *txn)
|
||||||
|
.await
|
||||||
|
.map_err(db_error)?
|
||||||
|
.rows_affected();
|
||||||
|
if changed == 0 {
|
||||||
|
return Err(DomainError::NotFound);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Maps a `rewards_cards` row (in the shared column order) to a `RewardsCard`.
|
||||||
|
fn map_rewards_card_row(row: sqlx::sqlite::SqliteRow) -> RewardsCard {
|
||||||
|
RewardsCard {
|
||||||
|
id: row.get(0),
|
||||||
|
user_id: row.get(1),
|
||||||
|
store_name: row.get(2),
|
||||||
|
number: row.get(3),
|
||||||
|
symbology: row.get(4),
|
||||||
|
created_at: row.get(5),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async fn ensure_category(txn: &mut SqliteConnection, category_id: Option<i64>) -> DomainResult<()> {
|
async fn ensure_category(txn: &mut SqliteConnection, category_id: Option<i64>) -> DomainResult<()> {
|
||||||
let Some(category_id) = category_id else {
|
let Some(category_id) = category_id else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -1368,6 +1480,14 @@ fn db_error(error: sqlx::Error) -> DomainError {
|
|||||||
DomainError::Database(error.to_string())
|
DomainError::Database(error.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Escapes a user-supplied search term so `%`, `_` and `\` are matched
|
||||||
|
/// literally when interpolated into a `LIKE` pattern with `ESCAPE '\'`.
|
||||||
|
fn escape_like(term: &str) -> String {
|
||||||
|
term.replace('\\', "\\\\")
|
||||||
|
.replace('%', "\\%")
|
||||||
|
.replace('_', "\\_")
|
||||||
|
}
|
||||||
|
|
||||||
fn migrate_error(error: sqlx::migrate::MigrateError) -> DomainError {
|
fn migrate_error(error: sqlx::migrate::MigrateError) -> DomainError {
|
||||||
DomainError::Database(error.to_string())
|
DomainError::Database(error.to_string())
|
||||||
}
|
}
|
||||||
@@ -2340,7 +2460,7 @@ mod tests {
|
|||||||
let meals = db
|
let meals = db
|
||||||
.run(move |txn| {
|
.run(move |txn| {
|
||||||
let meals = meals.clone();
|
let meals = meals.clone();
|
||||||
Box::pin(async move { meals.list_meals(txn).await })
|
Box::pin(async move { meals.list_meals(txn, "").await })
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -2349,6 +2469,51 @@ mod tests {
|
|||||||
assert_eq!(names, vec!["Pasta".to_owned(), "Salad".to_owned()]);
|
assert_eq!(names, vec!["Pasta".to_owned(), "Salad".to_owned()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn list_meals_filters_by_name_case_insensitively() {
|
||||||
|
let db = setup().await;
|
||||||
|
create_meal(&db, "Pasta Carbonara").await;
|
||||||
|
create_meal(&db, "Chicken Curry").await;
|
||||||
|
let meals = SqliteMealRepository;
|
||||||
|
let names = |posted_query: &str| {
|
||||||
|
let meals = meals.clone();
|
||||||
|
let posted_query = posted_query.to_owned();
|
||||||
|
db.run(move |txn| {
|
||||||
|
let meals = meals.clone();
|
||||||
|
Box::pin(async move { meals.list_meals(txn, &posted_query).await })
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let matched = names("pasta").await.unwrap();
|
||||||
|
let matched_names = matched.iter().map(|m| m.name.as_str()).collect::<Vec<_>>();
|
||||||
|
assert_eq!(matched_names, vec!["Pasta Carbonara"]);
|
||||||
|
assert!(names("pizza").await.unwrap().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn list_meals_escapes_like_wildcards() {
|
||||||
|
let db = setup().await;
|
||||||
|
create_meal(&db, "100% Wholemeal Bread").await;
|
||||||
|
create_meal(&db, "Salad").await;
|
||||||
|
let meals = SqliteMealRepository;
|
||||||
|
let names = |posted_query: &str| {
|
||||||
|
let meals = meals.clone();
|
||||||
|
let posted_query = posted_query.to_owned();
|
||||||
|
db.run(move |txn| {
|
||||||
|
let meals = meals.clone();
|
||||||
|
Box::pin(async move { meals.list_meals(txn, &posted_query).await })
|
||||||
|
})
|
||||||
|
};
|
||||||
|
// A bare `%` must not act as a wildcard matching every meal: it only
|
||||||
|
// matches meals that contain a literal `%` character.
|
||||||
|
let matched = names("%").await.unwrap();
|
||||||
|
assert_eq!(matched.len(), 1);
|
||||||
|
assert_eq!(matched[0].name, "100% Wholemeal Bread");
|
||||||
|
// `_` and `%` in the query are matched literally.
|
||||||
|
let matched = names("100%").await.unwrap();
|
||||||
|
assert_eq!(matched.len(), 1);
|
||||||
|
assert_eq!(matched[0].name, "100% Wholemeal Bread");
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn get_meal_returns_meal_with_ingredients() {
|
async fn get_meal_returns_meal_with_ingredients() {
|
||||||
let db = setup().await;
|
let db = setup().await;
|
||||||
@@ -2786,4 +2951,176 @@ mod tests {
|
|||||||
.await;
|
.await;
|
||||||
assert!(matches!(result, Err(DomainError::NotFound)));
|
assert!(matches!(result, Err(DomainError::NotFound)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- RewardsCardRepository ----
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rewards_card_crud_roundtrip() {
|
||||||
|
let db = setup().await;
|
||||||
|
let user = create_user(&db, "alice@example.com").await;
|
||||||
|
let cards = SqliteRewardsCardRepository;
|
||||||
|
|
||||||
|
let created = db
|
||||||
|
.run(move |txn| {
|
||||||
|
let cards = cards.clone();
|
||||||
|
Box::pin(async move {
|
||||||
|
cards
|
||||||
|
.create_card(
|
||||||
|
txn,
|
||||||
|
user.id,
|
||||||
|
"Kroger".into(),
|
||||||
|
"6011 2345 6789".into(),
|
||||||
|
"code128".into(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(created.id > 0);
|
||||||
|
assert_eq!(created.user_id, user.id);
|
||||||
|
assert_eq!(created.store_name, "Kroger");
|
||||||
|
assert_eq!(created.number, "6011 2345 6789");
|
||||||
|
assert_eq!(created.symbology, "code128");
|
||||||
|
|
||||||
|
let listed = db
|
||||||
|
.run(move |txn| {
|
||||||
|
let cards = cards.clone();
|
||||||
|
Box::pin(async move { cards.list_cards(txn, user.id).await })
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(listed.len(), 1);
|
||||||
|
assert_eq!(listed[0].id, created.id);
|
||||||
|
|
||||||
|
db.run(move |txn| {
|
||||||
|
let cards = cards.clone();
|
||||||
|
Box::pin(async move { cards.delete_card(txn, user.id, created.id).await })
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let after = db
|
||||||
|
.run(move |txn| {
|
||||||
|
let cards = cards.clone();
|
||||||
|
Box::pin(async move { cards.list_cards(txn, user.id).await })
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(after.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rewards_cards_are_scoped_to_their_user() {
|
||||||
|
let db = setup().await;
|
||||||
|
let alice = create_user(&db, "alice@example.com").await;
|
||||||
|
let bob = create_user(&db, "bob@example.com").await;
|
||||||
|
let cards = SqliteRewardsCardRepository;
|
||||||
|
|
||||||
|
db.run(move |txn| {
|
||||||
|
let cards = cards.clone();
|
||||||
|
Box::pin(async move {
|
||||||
|
cards
|
||||||
|
.create_card(
|
||||||
|
txn,
|
||||||
|
alice.id,
|
||||||
|
"Kroger".into(),
|
||||||
|
"123".into(),
|
||||||
|
"code128".into(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let bobs = db
|
||||||
|
.run(move |txn| {
|
||||||
|
let cards = cards.clone();
|
||||||
|
Box::pin(async move { cards.list_cards(txn, bob.id).await })
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(bobs.is_empty());
|
||||||
|
|
||||||
|
// Bob cannot delete Alice's card.
|
||||||
|
let result = db
|
||||||
|
.run(move |txn| {
|
||||||
|
let cards = cards.clone();
|
||||||
|
Box::pin(async move { cards.delete_card(txn, bob.id, 1).await })
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert!(matches!(result, Err(DomainError::NotFound)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn delete_missing_rewards_card_fails() {
|
||||||
|
let db = setup().await;
|
||||||
|
let user = create_user(&db, "alice@example.com").await;
|
||||||
|
let cards = SqliteRewardsCardRepository;
|
||||||
|
let result = db
|
||||||
|
.run(move |txn| {
|
||||||
|
let cards = cards.clone();
|
||||||
|
Box::pin(async move { cards.delete_card(txn, user.id, 9999).await })
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert!(matches!(result, Err(DomainError::NotFound)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn get_rewards_card_returns_card_or_none() {
|
||||||
|
let db = setup().await;
|
||||||
|
let alice = create_user(&db, "alice@example.com").await;
|
||||||
|
let bob = create_user(&db, "bob@example.com").await;
|
||||||
|
let cards = SqliteRewardsCardRepository;
|
||||||
|
|
||||||
|
let created = db
|
||||||
|
.run(move |txn| {
|
||||||
|
let cards = cards.clone();
|
||||||
|
Box::pin(async move {
|
||||||
|
cards
|
||||||
|
.create_card(
|
||||||
|
txn,
|
||||||
|
alice.id,
|
||||||
|
"Kroger".into(),
|
||||||
|
"601123456789".into(),
|
||||||
|
"code128".into(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// The owner can fetch their card.
|
||||||
|
let found = db
|
||||||
|
.run(move |txn| {
|
||||||
|
let cards = cards.clone();
|
||||||
|
Box::pin(async move { cards.get_card(txn, alice.id, created.id).await })
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(found.as_ref().map(|c| c.id), Some(created.id));
|
||||||
|
assert_eq!(found.unwrap().store_name, "Kroger");
|
||||||
|
|
||||||
|
// Another user cannot fetch it.
|
||||||
|
let not_found = db
|
||||||
|
.run(move |txn| {
|
||||||
|
let cards = cards.clone();
|
||||||
|
Box::pin(async move { cards.get_card(txn, bob.id, created.id).await })
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(not_found.is_none());
|
||||||
|
|
||||||
|
// A missing id returns None.
|
||||||
|
let missing = db
|
||||||
|
.run(move |txn| {
|
||||||
|
let cards = cards.clone();
|
||||||
|
Box::pin(async move { cards.get_card(txn, alice.id, 9999).await })
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(missing.is_none());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+352
-59
@@ -4,7 +4,8 @@ use pulldown_cmark::{Options, Parser, html as cmark_html};
|
|||||||
use crate::{
|
use crate::{
|
||||||
domain::PresenceUser,
|
domain::PresenceUser,
|
||||||
domain::{
|
domain::{
|
||||||
Category, GroceryList, Item, ListMeal, Meal, MealCategory, MealIngredient, Passkey, User,
|
Category, GroceryList, Item, ListMeal, Meal, MealCategory, MealIngredient, Passkey,
|
||||||
|
RewardsCard, User,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -292,6 +293,7 @@ pub fn meals_page(
|
|||||||
meals: &[Meal],
|
meals: &[Meal],
|
||||||
meal_categories: &[MealCategory],
|
meal_categories: &[MealCategory],
|
||||||
csrf_token: &str,
|
csrf_token: &str,
|
||||||
|
q: &str,
|
||||||
) -> Markup {
|
) -> Markup {
|
||||||
page(
|
page(
|
||||||
"Meals",
|
"Meals",
|
||||||
@@ -305,7 +307,7 @@ pub fn meals_page(
|
|||||||
}
|
}
|
||||||
a class="button button-primary" href="/meals/new" { "New meal" }
|
a class="button button-primary" href="/meals/new" { "New meal" }
|
||||||
}
|
}
|
||||||
@if meals.is_empty() {
|
@if meals.is_empty() && q.is_empty() {
|
||||||
div class="empty-state" {
|
div class="empty-state" {
|
||||||
div class="empty-mark" { "🍽" }
|
div class="empty-mark" { "🍽" }
|
||||||
h3 { "No meals yet" }
|
h3 { "No meals yet" }
|
||||||
@@ -318,28 +320,21 @@ pub fn meals_page(
|
|||||||
h2 { "All meals" }
|
h2 { "All meals" }
|
||||||
span class="count-badge" { (meals.len()) }
|
span class="count-badge" { (meals.len()) }
|
||||||
}
|
}
|
||||||
@if meals.is_empty() {
|
div class="meal-filter-bar" {
|
||||||
p class="muted" { "Create a meal to get started." }
|
input
|
||||||
} @else {
|
class="meal-filter"
|
||||||
@for (category_name, category_meals) in meal_groups(meals, meal_categories) {
|
id="meal-search"
|
||||||
div class="category-group" {
|
type="search"
|
||||||
div class="category-heading" {
|
name="q"
|
||||||
h3 { (category_name) " (" (category_meals.len()) ")" }
|
value=(q)
|
||||||
}
|
placeholder="Search meals"
|
||||||
div class="list-cards" {
|
hx-get="/meals"
|
||||||
@for meal in category_meals {
|
hx-trigger="input changed delay:200ms"
|
||||||
a class="list-card" href=(format!("/meals/{}", meal.id)) {
|
hx-target="#meal-results"
|
||||||
span class="list-card-icon" { "🍽" }
|
hx-swap="innerHTML";
|
||||||
span class="list-card-copy" {
|
}
|
||||||
strong { (meal.name) }
|
div id="meal-results" {
|
||||||
small { (meal.ingredients.len()) " ingredients" }
|
(meal_results(meals, meal_categories, q))
|
||||||
}
|
|
||||||
span class="list-card-arrow" { "→" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
aside class="side-column" {
|
aside class="side-column" {
|
||||||
@@ -375,6 +370,42 @@ pub fn meals_page(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Renders the meals page's grouped results, or the appropriate empty state.
|
||||||
|
/// Distinct from the database-empty state: when a search yields no matches the
|
||||||
|
/// list is empty (pre-filtered in SQL) even though meals exist, so we show a
|
||||||
|
/// search-specific message.
|
||||||
|
pub fn meal_results(meals: &[Meal], meal_categories: &[MealCategory], q: &str) -> Markup {
|
||||||
|
html! {
|
||||||
|
@if meals.is_empty() && q.is_empty() {
|
||||||
|
p class="muted" { "Create a meal to get started." }
|
||||||
|
} @else if meals.is_empty() {
|
||||||
|
div class="meal-filter-empty" {
|
||||||
|
p { "No meals match your search." }
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
@for (category_name, category_meals) in meal_groups(meals, meal_categories) {
|
||||||
|
div class="category-group" {
|
||||||
|
div class="category-heading" {
|
||||||
|
h3 { (category_name) " (" (category_meals.len()) ")" }
|
||||||
|
}
|
||||||
|
div class="list-cards" {
|
||||||
|
@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" { "→" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn meal_groups<'a>(
|
fn meal_groups<'a>(
|
||||||
meals: &'a [Meal],
|
meals: &'a [Meal],
|
||||||
meal_categories: &[MealCategory],
|
meal_categories: &[MealCategory],
|
||||||
@@ -415,6 +446,7 @@ pub fn meal_picker(
|
|||||||
meal_categories: &[MealCategory],
|
meal_categories: &[MealCategory],
|
||||||
list_id: i64,
|
list_id: i64,
|
||||||
csrf_token: &str,
|
csrf_token: &str,
|
||||||
|
q: &str,
|
||||||
) -> Markup {
|
) -> 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()" {
|
||||||
@@ -426,7 +458,19 @@ pub fn meal_picker(
|
|||||||
}
|
}
|
||||||
button class="meal-picker-close" type="button" aria-label="Close" onclick="this.closest('.meal-picker-backdrop').remove()" { "✕" }
|
button class="meal-picker-close" type="button" aria-label="Close" onclick="this.closest('.meal-picker-backdrop').remove()" { "✕" }
|
||||||
}
|
}
|
||||||
@if meals.is_empty() {
|
div class="meal-filter-bar meal-filter-bar-picker" {
|
||||||
|
input
|
||||||
|
class="meal-filter"
|
||||||
|
name="q"
|
||||||
|
type="search"
|
||||||
|
value=(q)
|
||||||
|
placeholder="Search meals"
|
||||||
|
hx-get=(format!("/meals?picker={}", list_id))
|
||||||
|
hx-trigger="input changed delay:200ms"
|
||||||
|
hx-target="#meal-picker-results"
|
||||||
|
hx-swap="innerHTML";
|
||||||
|
}
|
||||||
|
@if meals.is_empty() && q.is_empty() {
|
||||||
div class="meal-picker-empty" {
|
div class="meal-picker-empty" {
|
||||||
span class="empty-mark" { "🍽" }
|
span class="empty-mark" { "🍽" }
|
||||||
h3 { "No meals yet" }
|
h3 { "No meals yet" }
|
||||||
@@ -434,32 +478,51 @@ pub fn meal_picker(
|
|||||||
a class="button button-primary" href="/meals/new" { "Create a meal" }
|
a class="button button-primary" href="/meals/new" { "Create a meal" }
|
||||||
}
|
}
|
||||||
} @else {
|
} @else {
|
||||||
div class="meal-picker-list" {
|
div id="meal-picker-results" class="meal-picker-list" {
|
||||||
@for (category_name, category_meals) in meal_groups(meals, meal_categories) {
|
(meal_picker_results(meals, meal_categories, list_id, csrf_token))
|
||||||
div class="category-group" {
|
}
|
||||||
div class="category-heading" {
|
}
|
||||||
h3 { (category_name) }
|
}
|
||||||
}
|
}
|
||||||
@for meal in category_meals {
|
}
|
||||||
form
|
}
|
||||||
hx-post=(format!("/lists/{}/add-meal", list_id))
|
|
||||||
hx-target="#list-items"
|
/// The grouped picker rows, or the search-specific empty state. Kept separate
|
||||||
hx-swap="outerHTML"
|
/// from the database-empty state above.
|
||||||
hx-on::after-request="if (event.detail.successful) this.closest('.meal-picker-backdrop').remove()"
|
pub fn meal_picker_results(
|
||||||
class="meal-picker-row"
|
meals: &[Meal],
|
||||||
{
|
meal_categories: &[MealCategory],
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
list_id: i64,
|
||||||
input type="hidden" name="meal_id" value=(meal.id);
|
csrf_token: &str,
|
||||||
button class="meal-picker-button" type="submit" {
|
) -> Markup {
|
||||||
span class="meal-picker-icon" { "🍽" }
|
html! {
|
||||||
span class="meal-picker-copy" {
|
@if meals.is_empty() {
|
||||||
strong { (meal.name) }
|
div class="meal-picker-empty" {
|
||||||
small { (meal.ingredients.len()) " ingredients" }
|
p { "No meals match your search." }
|
||||||
}
|
}
|
||||||
span class="meal-picker-add" { "Add" }
|
} @else {
|
||||||
}
|
@for (category_name, category_meals) in meal_groups(meals, meal_categories) {
|
||||||
}
|
div class="category-group" {
|
||||||
|
div class="category-heading" {
|
||||||
|
h3 { (category_name) }
|
||||||
|
}
|
||||||
|
@for meal in category_meals {
|
||||||
|
form
|
||||||
|
hx-post=(format!("/lists/{}/add-meal", list_id))
|
||||||
|
hx-target="#list-items"
|
||||||
|
hx-swap="morph:outerHTML"
|
||||||
|
hx-on::after-request="if (event.detail.successful) this.closest('.meal-picker-backdrop').remove()"
|
||||||
|
class="meal-picker-row"
|
||||||
|
{
|
||||||
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
|
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" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -585,7 +648,7 @@ pub fn meal_page(
|
|||||||
}
|
}
|
||||||
div class="list-topbar-actions" {
|
div class="list-topbar-actions" {
|
||||||
button type="button" class="button button-small button-quiet" onclick="document.getElementById('meal-edit-modal').showModal()" { "Edit" }
|
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.')" {
|
form method="post" action=(format!("/meals/{}/delete", meal.id)) hx-confirm="Delete this meal and its ingredients? This cannot be undone." {
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
button class="danger-link bordered-delete" type="submit" { "Delete" }
|
button class="danger-link bordered-delete" type="submit" { "Delete" }
|
||||||
}
|
}
|
||||||
@@ -743,6 +806,19 @@ fn render_markdown(source: &str) -> Markup {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
/// Extracts the rendered SVG width from `viewBox="0 0 <width> <height>"`.
|
||||||
|
fn svg_width(svg: &str) -> u32 {
|
||||||
|
let viewbox = svg
|
||||||
|
.split("viewBox=\"")
|
||||||
|
.nth(1)
|
||||||
|
.expect("expected viewBox")
|
||||||
|
.split('"')
|
||||||
|
.next()
|
||||||
|
.unwrap();
|
||||||
|
let width = viewbox.split_whitespace().nth(2).expect("expected width");
|
||||||
|
width.parse().expect("expected numeric width")
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn render_markdown_turns_bullets_into_list_html() {
|
fn render_markdown_turns_bullets_into_list_html() {
|
||||||
let html = render_markdown("- one\n- two\n").into_string();
|
let html = render_markdown("- one\n- two\n").into_string();
|
||||||
@@ -764,6 +840,76 @@ mod tests {
|
|||||||
let ts = 1_786_060_800;
|
let ts = 1_786_060_800;
|
||||||
assert_eq!(format_date(ts), "7 Aug 2026");
|
assert_eq!(format_date(ts), "7 Aug 2026");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn barcode_svg_renders_code128_svg() {
|
||||||
|
let html = barcode_svg("code128", "601123456789").into_string();
|
||||||
|
assert!(html.contains("<svg"), "expected svg, got: {html}");
|
||||||
|
assert!(html.contains("</svg>"), "expected closing svg, got: {html}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn code128_uses_set_c_for_even_digit_numbers() {
|
||||||
|
// Set C (Ć) packs two digits per symbol, so an even-length digit-only
|
||||||
|
// number should be encoded with set C rather than set B.
|
||||||
|
assert_eq!(code128_input("601123456789"), "Ć601123456789");
|
||||||
|
// Non-numeric data falls back to set B.
|
||||||
|
assert_eq!(code128_input("ABC123"), "ƁABC123");
|
||||||
|
assert_eq!(code128_input(""), "Ɓ");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn code128_odd_digit_numbers_lead_with_set_b_then_switch_to_set_c() {
|
||||||
|
// 21-digit number: first digit in set B, then set C for the rest.
|
||||||
|
assert_eq!(
|
||||||
|
code128_input("606171584511340224537"),
|
||||||
|
"Ɓ6Ć06171584511340224537"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn code128_set_c_renders_shorter_than_set_b() {
|
||||||
|
let number = "601123456789";
|
||||||
|
let set_c = barcode_svg("code128", number).into_string();
|
||||||
|
// Force set B by using a non-numeric character so the digit-only
|
||||||
|
// fast path doesn't kick in.
|
||||||
|
let set_b = barcode_svg("code128", &format!("{number} ")).into_string();
|
||||||
|
let width_c = svg_width(&set_c);
|
||||||
|
let width_b = svg_width(&set_b);
|
||||||
|
assert!(
|
||||||
|
width_c < width_b,
|
||||||
|
"expected set C ({width_c}) narrower than set B ({width_b})"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn code128_odd_digit_number_renders_shorter_than_pure_set_b() {
|
||||||
|
let number = "606171584511340224537";
|
||||||
|
let mixed = barcode_svg("code128", number).into_string();
|
||||||
|
// Force pure set B by appending a non-numeric character.
|
||||||
|
let set_b = barcode_svg("code128", &format!("{number} ")).into_string();
|
||||||
|
let width_mixed = svg_width(&mixed);
|
||||||
|
let width_b = svg_width(&set_b);
|
||||||
|
assert!(
|
||||||
|
width_mixed < width_b,
|
||||||
|
"expected mixed ({width_mixed}) narrower than set B ({width_b})"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn barcode_svg_renders_code39_svg() {
|
||||||
|
let html = barcode_svg("code39", "ABC123").into_string();
|
||||||
|
assert!(html.contains("<svg"), "expected svg, got: {html}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn barcode_svg_falls_back_to_text_for_invalid_number() {
|
||||||
|
// Code 39 only supports uppercase letters and digits, so lowercase
|
||||||
|
// input cannot be encoded and falls back to plain text.
|
||||||
|
let html = barcode_svg("code39", "abc").into_string();
|
||||||
|
assert!(!html.contains("<svg"), "expected no svg, got: {html}");
|
||||||
|
assert!(html.contains("abc"), "expected fallback text, got: {html}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn list_page(
|
pub fn list_page(
|
||||||
@@ -864,7 +1010,7 @@ fn list_content(
|
|||||||
class="add-item-form"
|
class="add-item-form"
|
||||||
hx-post=(format!("/lists/{}/items", list.id))
|
hx-post=(format!("/lists/{}/items", list.id))
|
||||||
hx-target="#list-items"
|
hx-target="#list-items"
|
||||||
hx-swap="outerHTML"
|
hx-swap="morph:outerHTML"
|
||||||
hx-on::after-request="if (event.detail.successful) this.reset()"
|
hx-on::after-request="if (event.detail.successful) this.reset()"
|
||||||
{
|
{
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
@@ -891,7 +1037,7 @@ pub fn list_items_fragment(
|
|||||||
) -> 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="morph" {
|
||||||
(list_items_content(items, categories, csrf_token, editable))
|
(list_items_content(items, categories, csrf_token, editable))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -975,7 +1121,7 @@ fn item_row(item: &Item, categories: &[Category], csrf_token: &str, editable: bo
|
|||||||
class="check-form"
|
class="check-form"
|
||||||
hx-post=(format!("/lists/{}/items/{}/check", item.list_id, item.id))
|
hx-post=(format!("/lists/{}/items/{}/check", item.list_id, item.id))
|
||||||
hx-target="#list-items"
|
hx-target="#list-items"
|
||||||
hx-swap="outerHTML"
|
hx-swap="morph:outerHTML"
|
||||||
{
|
{
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
input type="hidden" name="checked" value=(next_checked);
|
input type="hidden" name="checked" value=(next_checked);
|
||||||
@@ -1006,7 +1152,7 @@ fn item_row(item: &Item, categories: &[Category], csrf_token: &str, editable: bo
|
|||||||
form
|
form
|
||||||
hx-post=(format!("/lists/{}/items/{}/edit", item.list_id, item.id))
|
hx-post=(format!("/lists/{}/items/{}/edit", item.list_id, item.id))
|
||||||
hx-target="#list-items"
|
hx-target="#list-items"
|
||||||
hx-swap="outerHTML"
|
hx-swap="morph:outerHTML"
|
||||||
class="stack"
|
class="stack"
|
||||||
{
|
{
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
@@ -1025,7 +1171,7 @@ fn item_row(item: &Item, categories: &[Category], csrf_token: &str, editable: bo
|
|||||||
form
|
form
|
||||||
hx-post=(format!("/lists/{}/items/{}/delete", item.list_id, item.id))
|
hx-post=(format!("/lists/{}/items/{}/delete", item.list_id, item.id))
|
||||||
hx-target="#list-items"
|
hx-target="#list-items"
|
||||||
hx-swap="outerHTML"
|
hx-swap="morph:outerHTML"
|
||||||
{
|
{
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
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-delete-{}", item.id)) class="button button-danger" type="submit" { "Remove item" }
|
||||||
@@ -1149,7 +1295,7 @@ pub fn list_meals_panel(
|
|||||||
form
|
form
|
||||||
hx-post=(format!("/lists/{}/meals/{}/remove", list_id, meal.id))
|
hx-post=(format!("/lists/{}/meals/{}/remove", list_id, meal.id))
|
||||||
hx-target="#list-items"
|
hx-target="#list-items"
|
||||||
hx-swap="outerHTML"
|
hx-swap="morph:outerHTML"
|
||||||
class="list-meal-remove"
|
class="list-meal-remove"
|
||||||
{
|
{
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
@@ -1260,6 +1406,148 @@ pub fn invite_result(url: &str) -> Markup {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn rewards_page(user: &User, cards: &[RewardsCard], csrf_token: &str) -> Markup {
|
||||||
|
page(
|
||||||
|
"Rewards cards",
|
||||||
|
Some(user),
|
||||||
|
html! {
|
||||||
|
div class="page-heading" {
|
||||||
|
div {
|
||||||
|
p class="eyebrow" { "REWARDS CARDS" }
|
||||||
|
h1 class="page-title" { "Rewards cards" }
|
||||||
|
p class="lede" { "Your store cards, ready to scan." }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
div class="dashboard-grid" {
|
||||||
|
section class="panel" {
|
||||||
|
div class="panel-heading" {
|
||||||
|
h2 { "Your cards" }
|
||||||
|
span class="count-badge" { (cards.len()) }
|
||||||
|
}
|
||||||
|
@if cards.is_empty() {
|
||||||
|
div class="empty-state" {
|
||||||
|
div class="empty-mark" { "🏷" }
|
||||||
|
h3 { "No rewards cards yet" }
|
||||||
|
p { "Add a card to see its barcode here." }
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
div class="rewards-grid" {
|
||||||
|
@for card in cards {
|
||||||
|
div class="rewards-card" {
|
||||||
|
a class="rewards-card-link" href=(format!("/rewards/{}", card.id)) aria-label=(format!("Show {} barcode", card.store_name)) {}
|
||||||
|
div class="rewards-card-heading" {
|
||||||
|
strong { (card.store_name) }
|
||||||
|
form method="post" action=(format!("/rewards/{}/delete", card.id)) hx-confirm="Remove this rewards card? This cannot be undone." {
|
||||||
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
|
button class="danger-link bordered-delete" type="submit" { "Remove" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
div class="rewards-barcode" {
|
||||||
|
(barcode_svg(&card.symbology, &card.number))
|
||||||
|
}
|
||||||
|
p class="rewards-number" { (card.number) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
section class="panel create-panel" {
|
||||||
|
div class="panel-heading" { h2 { "Add a card" } }
|
||||||
|
form method="post" action="/rewards" class="stack" {
|
||||||
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
|
label for="store-name" { "Store name" }
|
||||||
|
input id="store-name" name="store_name" type="text" maxlength="60" placeholder="e.g. Kroger" required;
|
||||||
|
label for="card-number" { "Card number" }
|
||||||
|
input id="card-number" name="number" type="text" maxlength="80" placeholder="e.g. 6011 2345 6789" required;
|
||||||
|
label for="symbology" { "Barcode type" }
|
||||||
|
select id="symbology" name="symbology" {
|
||||||
|
option value="code128" selected { "Code 128 (recommended)" }
|
||||||
|
option value="code39" { "Code 39" }
|
||||||
|
}
|
||||||
|
button class="button button-primary" type="submit" { "Add card" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A focused, single-barcode view for scanning at the register. Only one
|
||||||
|
/// barcode is shown at a time so a scanner can't pick up multiple codes.
|
||||||
|
pub fn rewards_scan_page(user: &User, card: &RewardsCard) -> Markup {
|
||||||
|
page(
|
||||||
|
&card.store_name,
|
||||||
|
Some(user),
|
||||||
|
html! {
|
||||||
|
div class="scan-page" {
|
||||||
|
a class="button button-quiet scan-back" href="/rewards" { "← All cards" }
|
||||||
|
div class="scan-card" {
|
||||||
|
p class="eyebrow" { "REWARDS CARD" }
|
||||||
|
h1 class="scan-store" { (card.store_name) }
|
||||||
|
div class="scan-barcode" {
|
||||||
|
(barcode_svg(&card.symbology, &card.number))
|
||||||
|
}
|
||||||
|
p class="rewards-number" { (card.number) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
script src=(crate::assets::url("rewards.js")) {}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders a rewards-card number as an inline SVG barcode using the given
|
||||||
|
/// symbology. Falls back to a plain text label if the number can't be encoded
|
||||||
|
/// (for example, a Code 128 number that isn't valid for the chosen symbology).
|
||||||
|
fn barcode_svg(symbology: &str, number: &str) -> Markup {
|
||||||
|
let generated = match symbology {
|
||||||
|
"code39" => barcoders::sym::code39::Code39::new(number)
|
||||||
|
.ok()
|
||||||
|
.map(|code| code.encode())
|
||||||
|
.and_then(|encoded| {
|
||||||
|
barcoders::generators::svg::SVG::new(60)
|
||||||
|
.generate(&encoded)
|
||||||
|
.ok()
|
||||||
|
}),
|
||||||
|
_ => barcoders::sym::code128::Code128::new(&code128_input(number))
|
||||||
|
.ok()
|
||||||
|
.map(|code| code.encode())
|
||||||
|
.and_then(|encoded| {
|
||||||
|
barcoders::generators::svg::SVG::new(60)
|
||||||
|
.generate(&encoded)
|
||||||
|
.ok()
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
match generated {
|
||||||
|
Some(svg) => html! { (maud::PreEscaped(svg)) },
|
||||||
|
None => html! { span class="rewards-unencodable" { (number) } },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the Code 128 input string, choosing the most compact character set.
|
||||||
|
///
|
||||||
|
/// Code 128 set C packs two digits per symbol, so numeric data renders roughly
|
||||||
|
/// half as wide as set B (one character per symbol). Google Wallet (via ZXing)
|
||||||
|
/// picks set C automatically for numeric runs, so we do the same to keep the
|
||||||
|
/// rendered barcode compact and consistent with it:
|
||||||
|
///
|
||||||
|
/// - Even-length digit-only numbers: all set C (`Ć` prefix).
|
||||||
|
/// - Odd-length digit-only numbers: first digit in set B, then switch to set C
|
||||||
|
/// for the remaining even count of digits (e.g. `Ɓ6Ć0171...`).
|
||||||
|
/// - Anything else: set B (`Ɓ` prefix).
|
||||||
|
fn code128_input(number: &str) -> String {
|
||||||
|
let is_all_digits = !number.is_empty() && number.chars().all(|c| c.is_ascii_digit());
|
||||||
|
if !is_all_digits {
|
||||||
|
return format!("Ɓ{number}");
|
||||||
|
}
|
||||||
|
let len = number.chars().count();
|
||||||
|
if len % 2 == 0 {
|
||||||
|
format!("Ć{number}")
|
||||||
|
} else {
|
||||||
|
let (first, rest) = number.split_at(1);
|
||||||
|
format!("Ɓ{first}Ć{rest}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Formats a Unix timestamp as a human-readable date (e.g. "7 Aug 2026").
|
/// Formats a Unix timestamp as a human-readable date (e.g. "7 Aug 2026").
|
||||||
fn format_date(timestamp: i64) -> String {
|
fn format_date(timestamp: i64) -> String {
|
||||||
let days = timestamp.div_euclid(86_400);
|
let days = timestamp.div_euclid(86_400);
|
||||||
@@ -1308,17 +1596,22 @@ fn page(title: &str, user: Option<&User>, content: Markup) -> Markup {
|
|||||||
meta charset="utf-8";
|
meta charset="utf-8";
|
||||||
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="icon" href=(crate::assets::url("favicon.ico")) sizes="any";
|
||||||
|
link rel="icon" type="image/png" href=(crate::assets::url("favicon-32x32.png")) sizes="32x32";
|
||||||
|
link rel="apple-touch-icon" href=(crate::assets::url("apple-touch-icon.png"));
|
||||||
link rel="stylesheet" href=(crate::assets::url("style.css"));
|
link rel="stylesheet" href=(crate::assets::url("style.css"));
|
||||||
script src=(crate::assets::url("htmx.min.js")) {}
|
script src=(crate::assets::url("htmx.min.js")) {}
|
||||||
|
script src=(crate::assets::url("idiomorph-ext.min.js")) {}
|
||||||
script src=(crate::assets::url("htmx-ws.min.js")) {}
|
script src=(crate::assets::url("htmx-ws.min.js")) {}
|
||||||
}
|
}
|
||||||
body hx-boost="true" {
|
body hx-boost="true" hx-ext="morph" {
|
||||||
header class="site-header" {
|
header class="site-header" {
|
||||||
a class="brand" href="/lists" { span class="brand-mark" { "S" } "Sustenance" }
|
a class="brand" href="/lists" { img class="brand-mark" src=(crate::assets::url("logo.svg")) alt="Sustenance logo"; "Sustenance" }
|
||||||
@if let Some(user) = user {
|
@if let Some(user) = user {
|
||||||
nav class="site-nav" {
|
nav class="site-nav" {
|
||||||
a href="/lists" { "Lists" }
|
a href="/lists" { "Lists" }
|
||||||
a href="/meals" { "Meals" }
|
a href="/meals" { "Meals" }
|
||||||
|
a href="/rewards" { "Rewards" }
|
||||||
}
|
}
|
||||||
div class="account-nav" {
|
div class="account-nav" {
|
||||||
a class="user-name" href="/account" { (user.display_name) }
|
a class="user-name" href="/account" { (user.display_name) }
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.2 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 832 B |
Vendored
+1
File diff suppressed because one or more lines are too long
+143
@@ -0,0 +1,143 @@
|
|||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
viewBox="0 0 64 64"
|
||||||
|
role="img"
|
||||||
|
aria-labelledby="title"
|
||||||
|
>
|
||||||
|
<title id="title">Sustenance grocery bag with produce</title>
|
||||||
|
|
||||||
|
<!-- Background -->
|
||||||
|
<rect width="64" height="64" rx="12" fill="#286247"/>
|
||||||
|
|
||||||
|
<!-- Back of the paper bag -->
|
||||||
|
<path
|
||||||
|
d="
|
||||||
|
M7 27
|
||||||
|
L16 22
|
||||||
|
L24 26
|
||||||
|
L32 22
|
||||||
|
L40 25
|
||||||
|
L49 21
|
||||||
|
L57 25
|
||||||
|
L47 31
|
||||||
|
L39 28
|
||||||
|
L31 32
|
||||||
|
L23 27
|
||||||
|
L16 31
|
||||||
|
Z
|
||||||
|
"
|
||||||
|
fill="#F2D39B"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- Back rim -->
|
||||||
|
<path
|
||||||
|
d="M7 27 16 22 24 26 32 22 40 25 49 21 57 25"
|
||||||
|
fill="none"
|
||||||
|
stroke="#1F4938"
|
||||||
|
stroke-width="2.75"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- Leafy greens -->
|
||||||
|
<path
|
||||||
|
d="M42 28C39 21 42 12 49 7c2 3 2 6 1 9 3-2 6-2 8 0-1 5-5 9-12 13Z"
|
||||||
|
fill="#8EC866"
|
||||||
|
stroke="#1F4938"
|
||||||
|
stroke-width="2.5"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
d="M45 27 53 15M47 22l7-1M49 18l-1-5"
|
||||||
|
fill="none"
|
||||||
|
stroke="#1F4938"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- Carrot leaves -->
|
||||||
|
<path
|
||||||
|
d="
|
||||||
|
M17 14c-2-4-1-7 0-10 3 3 4 6 3 10
|
||||||
|
m0 0c0-5 2-8 5-10 1 5-1 8-5 11
|
||||||
|
"
|
||||||
|
fill="#8EC866"
|
||||||
|
stroke="#1F4938"
|
||||||
|
stroke-width="2.5"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- Carrot -->
|
||||||
|
<path
|
||||||
|
d="M13 18c3-4 9-5 13-2l-3 20-5 2Z"
|
||||||
|
fill="#F29A3F"
|
||||||
|
stroke="#1F4938"
|
||||||
|
stroke-width="2.5"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
d="m16 24 7-2m-6 7 5-2"
|
||||||
|
fill="none"
|
||||||
|
stroke="#1F4938"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- Tomato -->
|
||||||
|
<path
|
||||||
|
d="M27 25c0-6 4-10 10-10s10 4 10 10c0 7-4 12-10 12S27 32 27 25Z"
|
||||||
|
fill="#E65A46"
|
||||||
|
stroke="#1F4938"
|
||||||
|
stroke-width="2.5"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
d="m37 15-4 5 4-1 4 2-1-5"
|
||||||
|
fill="#78B75B"
|
||||||
|
stroke="#1F4938"
|
||||||
|
stroke-width="2"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- Front and sides of the paper bag -->
|
||||||
|
<path
|
||||||
|
d="
|
||||||
|
M7 27
|
||||||
|
L16 31
|
||||||
|
L23 27
|
||||||
|
L31 32
|
||||||
|
L39 28
|
||||||
|
L47 31
|
||||||
|
L57 25
|
||||||
|
L55 51
|
||||||
|
L45 59
|
||||||
|
L11 51
|
||||||
|
Z
|
||||||
|
"
|
||||||
|
fill="#F2D39B"
|
||||||
|
stroke="#1F4938"
|
||||||
|
stroke-width="2.75"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- Front opening edge -->
|
||||||
|
<path
|
||||||
|
d="M7 27 16 31 23 27 31 32 39 28 47 31 57 25"
|
||||||
|
fill="none"
|
||||||
|
stroke="#1F4938"
|
||||||
|
stroke-width="2.75"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- Side-panel seam and paper creases -->
|
||||||
|
<path
|
||||||
|
d="M47 31 45 59M45 59l10-8M15 36l1 9"
|
||||||
|
fill="none"
|
||||||
|
stroke="#1F4938"
|
||||||
|
stroke-width="2.25"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 2.6 KiB |
@@ -0,0 +1,30 @@
|
|||||||
|
// Keep the screen awake while a rewards barcode is on screen so the cashier
|
||||||
|
// can scan it without the display dimming or locking. This mirrors how wallet
|
||||||
|
// apps behave when showing a barcode. The Screen Wake Lock API is best-effort:
|
||||||
|
// it may be rejected (e.g. low battery) or auto-released when the tab is hidden,
|
||||||
|
// so we re-acquire whenever the page becomes visible again.
|
||||||
|
(function () {
|
||||||
|
var wakeLock = null;
|
||||||
|
|
||||||
|
function requestWakeLock() {
|
||||||
|
if (!("wakeLock" in navigator)) return;
|
||||||
|
navigator.wakeLock
|
||||||
|
.request("screen")
|
||||||
|
.then(function (sentinel) {
|
||||||
|
wakeLock = sentinel;
|
||||||
|
})
|
||||||
|
.catch(function () {
|
||||||
|
// Best-effort only; ignore failures (unsupported, low battery, etc.).
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-acquire if the lock was released (e.g. the tab was hidden) and the user
|
||||||
|
// returns to the page.
|
||||||
|
document.addEventListener("visibilitychange", function () {
|
||||||
|
if (document.visibilityState === "visible" && wakeLock === null) {
|
||||||
|
requestWakeLock();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
requestWakeLock();
|
||||||
|
})();
|
||||||
+103
-1
@@ -38,7 +38,7 @@ a { color: inherit; }
|
|||||||
}
|
}
|
||||||
|
|
||||||
.brand { display: inline-flex; align-items: center; gap: 10px; text-decoration: none; font-weight: 800; letter-spacing: -.03em; }
|
.brand { display: inline-flex; align-items: center; gap: 10px; text-decoration: none; font-weight: 800; letter-spacing: -.03em; }
|
||||||
.brand-mark { display: grid; place-items: center; width: 32px; height: 32px; border-radius: 11px 11px 11px 3px; background: var(--deep-sage); color: white; transform: rotate(-6deg); }
|
.brand-mark { display: block; width: 34px; height: 34px; border-radius: 9px; object-fit: cover; }
|
||||||
.site-nav { display: flex; align-items: center; gap: 6px; }
|
.site-nav { display: flex; align-items: center; gap: 6px; }
|
||||||
.site-nav a {
|
.site-nav a {
|
||||||
padding: 8px 14px;
|
padding: 8px 14px;
|
||||||
@@ -378,6 +378,11 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
|
|||||||
.meal-picker-empty { padding: 34px 22px 30px; text-align: center; color: var(--muted); }
|
.meal-picker-empty { padding: 34px 22px 30px; text-align: center; color: var(--muted); }
|
||||||
.meal-picker-empty h3 { color: var(--ink); }
|
.meal-picker-empty h3 { color: var(--ink); }
|
||||||
.meal-picker-empty p { margin-bottom: 18px; }
|
.meal-picker-empty p { margin-bottom: 18px; }
|
||||||
|
.meal-filter-bar { margin: -6px 0 18px; }
|
||||||
|
.meal-filter-bar input { min-height: 40px; padding: 8px 12px; font-size: .9rem; }
|
||||||
|
.meal-filter-bar-picker { margin: 14px 24px 4px; }
|
||||||
|
.meal-filter-empty { padding: 28px 18px; text-align: center; color: var(--muted); }
|
||||||
|
.meal-filter-empty p { margin: 0; }
|
||||||
|
|
||||||
@media (max-width: 780px) {
|
@media (max-width: 780px) {
|
||||||
.site-header, .site-main, .site-footer { width: min(100% - 28px, 600px); }
|
.site-header, .site-main, .site-footer { width: min(100% - 28px, 600px); }
|
||||||
@@ -403,3 +408,100 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
|
|||||||
.side-column { grid-template-columns: 1fr; }
|
.side-column { grid-template-columns: 1fr; }
|
||||||
.site-footer { margin-bottom: 20px; }
|
.site-footer { margin-bottom: 20px; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Rewards cards */
|
||||||
|
.rewards-grid { display: grid; gap: 16px; }
|
||||||
|
.rewards-card {
|
||||||
|
position: relative;
|
||||||
|
padding: 18px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 18px;
|
||||||
|
background: #fff;
|
||||||
|
transition: border-color .16s ease, transform .16s ease;
|
||||||
|
}
|
||||||
|
.rewards-card:hover { border-color: var(--sage); transform: translateY(-1px); }
|
||||||
|
/* Stretched link: makes the whole card clickable to open the scan view. */
|
||||||
|
.rewards-card-link {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
border-radius: inherit;
|
||||||
|
z-index: 1;
|
||||||
|
}
|
||||||
|
.rewards-card-heading {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
margin-bottom: 14px;
|
||||||
|
}
|
||||||
|
.rewards-card-heading strong { font-size: 1.05rem; }
|
||||||
|
.rewards-barcode {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 14px;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
.rewards-barcode svg { width: 100%; height: auto; max-width: 340px; }
|
||||||
|
.rewards-number {
|
||||||
|
margin: 12px 0 0;
|
||||||
|
text-align: center;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: .85rem;
|
||||||
|
letter-spacing: .08em;
|
||||||
|
}
|
||||||
|
.rewards-unencodable {
|
||||||
|
display: block;
|
||||||
|
color: var(--coral);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
/* Keep the Remove button above the stretched link so it stays clickable. */
|
||||||
|
.rewards-card-heading form { position: relative; z-index: 2; }
|
||||||
|
|
||||||
|
/* Single-card scan view */
|
||||||
|
.scan-page {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 22px;
|
||||||
|
padding: 12px 0 40px;
|
||||||
|
}
|
||||||
|
.scan-back { align-self: flex-start; }
|
||||||
|
.scan-card {
|
||||||
|
width: min(100%, 460px);
|
||||||
|
padding: clamp(24px, 6vw, 42px);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 28px;
|
||||||
|
background: #fff;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.scan-store { margin: 4px 0 26px; font-size: clamp(1.3rem, 4vw, 1.7rem); }
|
||||||
|
.scan-barcode {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 22px;
|
||||||
|
border-radius: 14px;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
.scan-barcode svg {
|
||||||
|
width: 100%;
|
||||||
|
height: auto;
|
||||||
|
max-width: 420px;
|
||||||
|
}
|
||||||
|
.scan-card .rewards-number {
|
||||||
|
margin-top: 18px;
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
width: 100%;
|
||||||
|
min-height: 46px;
|
||||||
|
padding: 10px 13px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 12px;
|
||||||
|
outline: none;
|
||||||
|
color: var(--ink);
|
||||||
|
background: #fff;
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
select:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113, 93, .12); }
|
||||||
|
|||||||
Reference in New Issue
Block a user