Merge branch 'feature/commercial-redesign'
Commercial redesign: landing page, session-cookie auth (signup/login/ forgot/reset), side-nav app shell, full account and admin pages, and a teaching-layer UI overhaul. Adds green-bean inventory management and SCA-style cupping scoring ported from hope_roaster.
This commit is contained in:
@@ -3,3 +3,4 @@ appdata//
|
||||
data/
|
||||
*.log
|
||||
.DS_Store
|
||||
dev-harness.mjs
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Additive only: existing users/sessions/roast_plans rows and columns are untouched.
|
||||
CREATE TABLE password_reset_tokens (token_hash text PRIMARY KEY, user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, expires_at timestamptz NOT NULL, created_at timestamptz NOT NULL DEFAULT now());
|
||||
ALTER TABLE users ADD COLUMN disabled_at timestamptz;
|
||||
ALTER TABLE sessions ADD COLUMN user_agent text, ADD COLUMN ip text, ADD COLUMN last_seen_at timestamptz;
|
||||
CREATE TABLE audit_events (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), actor_user_id uuid REFERENCES users(id) ON DELETE SET NULL, action text NOT NULL, target text, created_at timestamptz NOT NULL DEFAULT now());
|
||||
CREATE INDEX audit_events_created ON audit_events(created_at DESC);
|
||||
CREATE INDEX sessions_user_id ON sessions(user_id);
|
||||
CREATE INDEX password_reset_tokens_user_id ON password_reset_tokens(user_id);
|
||||
@@ -0,0 +1,45 @@
|
||||
-- Additive only: existing tables, rows, and columns are untouched.
|
||||
CREATE TABLE green_bean_lots (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
origin text NOT NULL,
|
||||
variety text NOT NULL DEFAULT '',
|
||||
process text NOT NULL DEFAULT '',
|
||||
producer text NOT NULL DEFAULT '',
|
||||
purchase_date date,
|
||||
initial_weight_g numeric NOT NULL,
|
||||
remaining_weight_g numeric NOT NULL,
|
||||
cost_total numeric,
|
||||
moisture_pct numeric,
|
||||
density_g_l numeric,
|
||||
notes text NOT NULL DEFAULT '',
|
||||
archived boolean NOT NULL DEFAULT false,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE bean_consumption (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
lot_id uuid NOT NULL REFERENCES green_bean_lots(id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
roast_plan_id uuid REFERENCES roast_plans(id) ON DELETE SET NULL,
|
||||
weight_g numeric NOT NULL CHECK (weight_g > 0),
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
-- One draw-down per roast plan, ever (NULLs are distinct in Postgres, so plan-less manual
|
||||
-- entries remain unlimited). This is the server-side backstop that makes the client's
|
||||
-- "Draw from lot" button idempotent even if clicked twice or from two devices.
|
||||
CREATE UNIQUE INDEX bean_consumption_one_per_plan ON bean_consumption(roast_plan_id);
|
||||
CREATE TABLE cupping_sessions (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
roast_plan_id uuid REFERENCES roast_plans(id) ON DELETE SET NULL,
|
||||
data jsonb NOT NULL,
|
||||
total_score numeric NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX green_bean_lots_user ON green_bean_lots(user_id, archived, purchase_date DESC);
|
||||
CREATE INDEX bean_consumption_lot ON bean_consumption(lot_id, created_at DESC);
|
||||
CREATE INDEX bean_consumption_user ON bean_consumption(user_id);
|
||||
CREATE INDEX cupping_sessions_user ON cupping_sessions(user_id, updated_at DESC);
|
||||
CREATE INDEX cupping_sessions_plan ON cupping_sessions(roast_plan_id);
|
||||
Generated
+10
@@ -11,6 +11,7 @@
|
||||
"@earendil-works/pi-coding-agent": "^0.83.0",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"express": "^5.0.1",
|
||||
"nodemailer": "^9.0.3",
|
||||
"pg": "^8.22.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -2745,6 +2746,15 @@
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/nodemailer": {
|
||||
"version": "9.0.3",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-9.0.3.tgz",
|
||||
"integrity": "sha512-n+YP+NKwR5zRWa60k3GiQ6Q3B4KXCoAw40dAKeCtYn020iNN74aWK2liXIC3ZEATeGql7we3tE3t8QwhY0eskw==",
|
||||
"license": "MIT-0",
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/object-hash": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz",
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
"@earendil-works/pi-coding-agent": "^0.83.0",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"express": "^5.0.1",
|
||||
"nodemailer": "^9.0.3",
|
||||
"pg": "^8.22.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Account — Roast Planner</title>
|
||||
<link rel="stylesheet" href="/app.css" />
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
|
||||
<meta name="theme-color" content="#A8481A" />
|
||||
</head>
|
||||
<body>
|
||||
<div class="app-shell">
|
||||
<nav class="side-nav" id="side-nav" aria-label="Main navigation">
|
||||
<div class="side-nav-brand">
|
||||
<span class="brand-mark" aria-hidden="true">◐</span>
|
||||
<span class="brand-name">Roast Planner</span>
|
||||
</div>
|
||||
<div class="nav-group">
|
||||
<a class="nav-item" href="/app"
|
||||
><span class="nav-icon" aria-hidden="true">◐</span
|
||||
><span class="nav-label">Planner</span></a
|
||||
>
|
||||
<a class="nav-item" href="#your-plans"
|
||||
><span class="nav-icon" aria-hidden="true">▤</span
|
||||
><span class="nav-label">Plans</span></a
|
||||
>
|
||||
<a class="nav-item" href="/inventory"
|
||||
><span class="nav-icon" aria-hidden="true">▥</span
|
||||
><span class="nav-label">Inventory</span></a
|
||||
>
|
||||
<a class="nav-item" href="/cupping"
|
||||
><span class="nav-icon" aria-hidden="true">◒</span
|
||||
><span class="nav-label">Cupping</span></a
|
||||
>
|
||||
<a class="nav-item" href="/account" aria-current="page"
|
||||
><span class="nav-icon" aria-hidden="true">◔</span
|
||||
><span class="nav-label">Account</span></a
|
||||
>
|
||||
<a class="nav-item hidden" id="nav-admin" href="/admin"
|
||||
><span class="nav-icon" aria-hidden="true">⚙</span
|
||||
><span class="nav-label">Admin</span></a
|
||||
>
|
||||
</div>
|
||||
<div class="nav-spacer"></div>
|
||||
<button
|
||||
class="icon-btn nav-collapse-toggle"
|
||||
type="button"
|
||||
id="nav-collapse"
|
||||
aria-label="Collapse navigation"
|
||||
title="Collapse navigation"
|
||||
>
|
||||
«
|
||||
</button>
|
||||
<div class="nav-user">
|
||||
<div class="nav-user-avatar" id="nav-user-avatar" aria-hidden="true"></div>
|
||||
<div class="nav-user-detail">
|
||||
<span class="nav-user-email" id="account-email"></span>
|
||||
<button class="nav-user-logout" type="button" id="btn-logout">
|
||||
Log out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="app-workspace" id="app-workspace">
|
||||
<header class="app-header">
|
||||
<div class="header-row-top">
|
||||
<button
|
||||
class="icon-btn nav-hamburger"
|
||||
type="button"
|
||||
id="nav-hamburger"
|
||||
aria-label="Open navigation"
|
||||
aria-expanded="false"
|
||||
>
|
||||
☰
|
||||
</button>
|
||||
<div class="brand">
|
||||
<div class="brand-text">
|
||||
<h1>Account</h1>
|
||||
<p class="brand-sub">Profile, security, plans, and devices</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div class="drawer-overlay hidden" id="drawer-overlay"></div>
|
||||
|
||||
<main class="page-content">
|
||||
<section class="panel-card" id="profile">
|
||||
<div class="panel-head">
|
||||
<h2>Profile</h2>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<p>
|
||||
<strong id="profile-email"></strong>
|
||||
<span class="badge badge-admin hidden" id="profile-role-admin"
|
||||
>Admin</span
|
||||
>
|
||||
</p>
|
||||
<p class="muted" id="profile-since"></p>
|
||||
<p class="subhead">Change email</p>
|
||||
<form id="email-form" class="inline-form">
|
||||
<label class="field"
|
||||
><span class="field-label">New email</span
|
||||
><input
|
||||
class="field-input"
|
||||
type="email"
|
||||
name="email"
|
||||
required
|
||||
autocomplete="email"
|
||||
/></label>
|
||||
<label class="field"
|
||||
><span class="field-label">Current password</span
|
||||
><input
|
||||
class="field-input"
|
||||
type="password"
|
||||
name="password"
|
||||
required
|
||||
autocomplete="current-password"
|
||||
/></label>
|
||||
<button class="primary-btn" type="submit">Update email</button>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-card" id="security">
|
||||
<div class="panel-head">
|
||||
<h2>Security</h2>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<p class="subhead">Change password</p>
|
||||
<form id="password-form" class="inline-form">
|
||||
<label class="field"
|
||||
><span class="field-label">Current password</span
|
||||
><input
|
||||
class="field-input"
|
||||
type="password"
|
||||
name="currentPassword"
|
||||
required
|
||||
autocomplete="current-password"
|
||||
/></label>
|
||||
<label class="field"
|
||||
><span class="field-label">New password</span
|
||||
><input
|
||||
class="field-input"
|
||||
type="password"
|
||||
name="newPassword"
|
||||
required
|
||||
minlength="12"
|
||||
autocomplete="new-password"
|
||||
/></label>
|
||||
<label class="field"
|
||||
><span class="field-label">Confirm new password</span
|
||||
><input
|
||||
class="field-input"
|
||||
type="password"
|
||||
name="confirmPassword"
|
||||
required
|
||||
minlength="12"
|
||||
autocomplete="new-password"
|
||||
/></label>
|
||||
<button class="primary-btn" type="submit">
|
||||
Update password
|
||||
</button>
|
||||
</form>
|
||||
<p class="subhead">Active sessions</p>
|
||||
<div class="table-wrap">
|
||||
<table class="data-table" id="sessions-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Device</th>
|
||||
<th>Last seen</th>
|
||||
<th>Expires</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="sessions-body"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<button class="ghost-btn" type="button" id="btn-revoke-others">
|
||||
Sign out everywhere else
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-card" id="your-plans">
|
||||
<div class="panel-head">
|
||||
<h2>Your plans</h2>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<div class="table-wrap">
|
||||
<table class="data-table" id="plans-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Title</th>
|
||||
<th>Updated</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="plans-body"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-card" id="app">
|
||||
<div class="panel-head">
|
||||
<h2>App</h2>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<p class="muted">
|
||||
Install Roast Planner for a focused, offline-capable
|
||||
workspace. Updates wait for your confirmation so an
|
||||
in-progress plan is never discarded.
|
||||
</p>
|
||||
<button id="btn-install" type="button" class="primary-btn hidden">
|
||||
Install Roast Planner
|
||||
</button>
|
||||
<button id="btn-refresh" type="button" class="ghost-btn hidden">
|
||||
Update ready — refresh safely
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-card danger-zone" id="danger">
|
||||
<div class="panel-head">
|
||||
<h2>Danger zone</h2>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<p class="muted">
|
||||
Deleting your account permanently removes your plans and
|
||||
cannot be undone.
|
||||
</p>
|
||||
<form id="delete-form" class="inline-form">
|
||||
<label class="field"
|
||||
><span class="field-label"
|
||||
>Type your email to confirm</span
|
||||
><input class="field-input" type="email" name="confirmEmail" required
|
||||
/></label>
|
||||
<label class="field"
|
||||
><span class="field-label">Password</span
|
||||
><input
|
||||
class="field-input"
|
||||
type="password"
|
||||
name="password"
|
||||
required
|
||||
autocomplete="current-password"
|
||||
/></label>
|
||||
<button class="ghost-btn" type="submit" style="border-color:var(--fail);color:var(--fail)">
|
||||
Delete my account
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<script type="module" src="/js/account.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+191
-13
@@ -3,22 +3,200 @@
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Roast Planner Admin</title>
|
||||
<title>Admin — Roast Planner</title>
|
||||
<link rel="stylesheet" href="/app.css" />
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
|
||||
<meta name="theme-color" content="#A8481A" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="auth-page">
|
||||
<section class="panel-card auth-card">
|
||||
<a href="/app">← Plans</a>
|
||||
<h1>Administration</h1>
|
||||
<label><input id="signup" type="checkbox" /> Allow new signups</label
|
||||
><button id="save" class="primary-btn">Save setting</button>
|
||||
<h2>Users</h2>
|
||||
<ul id="users"></ul>
|
||||
<h2>Recent roast plans</h2>
|
||||
<ul id="plans"></ul>
|
||||
</section>
|
||||
</main>
|
||||
<div class="app-shell">
|
||||
<nav class="side-nav" id="side-nav" aria-label="Main navigation">
|
||||
<div class="side-nav-brand">
|
||||
<span class="brand-mark" aria-hidden="true">◐</span>
|
||||
<span class="brand-name">Roast Planner</span>
|
||||
</div>
|
||||
<div class="nav-group">
|
||||
<a class="nav-item" href="/app"
|
||||
><span class="nav-icon" aria-hidden="true">◐</span
|
||||
><span class="nav-label">Planner</span></a
|
||||
>
|
||||
<a class="nav-item" href="#plans"
|
||||
><span class="nav-icon" aria-hidden="true">▤</span
|
||||
><span class="nav-label">Plans</span></a
|
||||
>
|
||||
<a class="nav-item" href="/inventory"
|
||||
><span class="nav-icon" aria-hidden="true">▥</span
|
||||
><span class="nav-label">Inventory</span></a
|
||||
>
|
||||
<a class="nav-item" href="/cupping"
|
||||
><span class="nav-icon" aria-hidden="true">◒</span
|
||||
><span class="nav-label">Cupping</span></a
|
||||
>
|
||||
<a class="nav-item" href="/account"
|
||||
><span class="nav-icon" aria-hidden="true">◔</span
|
||||
><span class="nav-label">Account</span></a
|
||||
>
|
||||
<a class="nav-item" href="/admin" aria-current="page"
|
||||
><span class="nav-icon" aria-hidden="true">⚙</span
|
||||
><span class="nav-label">Admin</span></a
|
||||
>
|
||||
</div>
|
||||
<div class="nav-spacer"></div>
|
||||
<button
|
||||
class="icon-btn nav-collapse-toggle"
|
||||
type="button"
|
||||
id="nav-collapse"
|
||||
aria-label="Collapse navigation"
|
||||
title="Collapse navigation"
|
||||
>
|
||||
«
|
||||
</button>
|
||||
<div class="nav-user">
|
||||
<div class="nav-user-avatar" id="nav-user-avatar" aria-hidden="true"></div>
|
||||
<div class="nav-user-detail">
|
||||
<span class="nav-user-email" id="account-email"></span>
|
||||
<button class="nav-user-logout" type="button" id="btn-logout">
|
||||
Log out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="app-workspace" id="app-workspace">
|
||||
<header class="app-header">
|
||||
<div class="header-row-top">
|
||||
<button
|
||||
class="icon-btn nav-hamburger"
|
||||
type="button"
|
||||
id="nav-hamburger"
|
||||
aria-label="Open navigation"
|
||||
aria-expanded="false"
|
||||
>
|
||||
☰
|
||||
</button>
|
||||
<div class="brand">
|
||||
<div class="brand-text">
|
||||
<h1>Administration</h1>
|
||||
<p class="brand-sub">Users, plans, and app settings</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div class="drawer-overlay hidden" id="drawer-overlay"></div>
|
||||
|
||||
<main class="page-content wide">
|
||||
<section class="stat-grid" id="metrics" aria-label="Metrics"></section>
|
||||
|
||||
<section class="panel-card" id="reset-links-card" hidden>
|
||||
<div class="panel-head"><h2>Pending password resets</h2></div>
|
||||
<div class="panel-body">
|
||||
<p class="muted">
|
||||
No outgoing email is configured for this deployment
|
||||
(<code>SMTP_URL</code>). Hand these links to the user
|
||||
directly.
|
||||
</p>
|
||||
<div class="table-wrap">
|
||||
<table class="data-table" id="resets-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Email</th>
|
||||
<th>Link</th>
|
||||
<th>Expires</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="resets-body"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-card">
|
||||
<div class="panel-head"><h2>Signups</h2></div>
|
||||
<div class="panel-body">
|
||||
<label
|
||||
style="display:flex;align-items:center;gap:10px;font-size:13px;color:var(--ink-2)"
|
||||
><span class="switch"
|
||||
><input type="checkbox" id="signup-toggle" /><span
|
||||
class="switch-track"
|
||||
></span></span
|
||||
>Allow new signups</label
|
||||
>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-card" id="users">
|
||||
<div class="panel-head">
|
||||
<h2>Users</h2>
|
||||
<input
|
||||
class="text-input"
|
||||
id="user-search"
|
||||
placeholder="Search by email…"
|
||||
style="max-width:220px"
|
||||
/>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<div class="table-wrap">
|
||||
<table class="data-table" id="users-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Email</th>
|
||||
<th>Role</th>
|
||||
<th>Status</th>
|
||||
<th class="num">Plans</th>
|
||||
<th>Joined</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="users-body"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-card" id="plans">
|
||||
<div class="panel-head">
|
||||
<h2>Roast plans</h2>
|
||||
<button class="ghost-btn small hidden" id="clear-plan-filter">
|
||||
Clear filter
|
||||
</button>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<div class="table-wrap">
|
||||
<table class="data-table" id="plans-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Owner</th>
|
||||
<th>Title</th>
|
||||
<th>Updated</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="plans-body"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-card" id="activity">
|
||||
<div class="panel-head"><h2>Recent activity</h2></div>
|
||||
<div class="panel-body">
|
||||
<div class="table-wrap">
|
||||
<table class="data-table" id="audit-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>When</th>
|
||||
<th>Actor</th>
|
||||
<th>Action</th>
|
||||
<th>Target</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="audit-body"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<script type="module" src="/js/admin.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1087
-71
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,265 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Cupping — Roast Planner</title>
|
||||
<link rel="stylesheet" href="/app.css" />
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
|
||||
<meta name="theme-color" content="#A8481A" />
|
||||
</head>
|
||||
<body>
|
||||
<div class="app-shell">
|
||||
<nav class="side-nav" id="side-nav" aria-label="Main navigation">
|
||||
<div class="side-nav-brand">
|
||||
<span class="brand-mark" aria-hidden="true">◐</span>
|
||||
<span class="brand-name">Roast Planner</span>
|
||||
</div>
|
||||
<div class="nav-group">
|
||||
<a class="nav-item" href="/app"
|
||||
><span class="nav-icon" aria-hidden="true">◐</span
|
||||
><span class="nav-label">Planner</span></a
|
||||
>
|
||||
<a class="nav-item" href="/account#your-plans"
|
||||
><span class="nav-icon" aria-hidden="true">▤</span
|
||||
><span class="nav-label">Plans</span></a
|
||||
>
|
||||
<a class="nav-item" href="/inventory"
|
||||
><span class="nav-icon" aria-hidden="true">▥</span
|
||||
><span class="nav-label">Inventory</span></a
|
||||
>
|
||||
<a class="nav-item" href="/cupping" aria-current="page"
|
||||
><span class="nav-icon" aria-hidden="true">◒</span
|
||||
><span class="nav-label">Cupping</span></a
|
||||
>
|
||||
<a class="nav-item" href="/account"
|
||||
><span class="nav-icon" aria-hidden="true">◔</span
|
||||
><span class="nav-label">Account</span></a
|
||||
>
|
||||
<a class="nav-item hidden" id="nav-admin" href="/admin"
|
||||
><span class="nav-icon" aria-hidden="true">⚙</span
|
||||
><span class="nav-label">Admin</span></a
|
||||
>
|
||||
</div>
|
||||
<div class="nav-spacer"></div>
|
||||
<button
|
||||
class="icon-btn nav-collapse-toggle"
|
||||
type="button"
|
||||
id="nav-collapse"
|
||||
aria-label="Collapse navigation"
|
||||
title="Collapse navigation"
|
||||
>
|
||||
«
|
||||
</button>
|
||||
<div class="nav-user">
|
||||
<div class="nav-user-avatar" id="nav-user-avatar" aria-hidden="true"></div>
|
||||
<div class="nav-user-detail">
|
||||
<span class="nav-user-email" id="account-email"></span>
|
||||
<button class="nav-user-logout" type="button" id="btn-logout">
|
||||
Log out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="app-workspace" id="app-workspace">
|
||||
<header class="app-header">
|
||||
<div class="header-row-top">
|
||||
<button
|
||||
class="icon-btn nav-hamburger"
|
||||
type="button"
|
||||
id="nav-hamburger"
|
||||
aria-label="Open navigation"
|
||||
aria-expanded="false"
|
||||
>
|
||||
☰
|
||||
</button>
|
||||
<div class="brand">
|
||||
<div class="brand-text">
|
||||
<h1 id="cupping-title">Cupping</h1>
|
||||
<p class="brand-sub" id="cupping-subtitle">
|
||||
Tasting and scoring sessions
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-actions hidden" id="session-autosave-wrap">
|
||||
<span class="autosave-chip" id="cupping-autosave-status"
|
||||
><span class="dot"></span
|
||||
><span class="autosave-text">Not saved yet</span></span
|
||||
>
|
||||
</div>
|
||||
</header>
|
||||
<div class="drawer-overlay hidden" id="drawer-overlay"></div>
|
||||
|
||||
<main class="page-content wide" id="cupping-list-view">
|
||||
<section class="panel-card" id="cupping-sessions-list">
|
||||
<div class="panel-head"><h2>Cupping sessions</h2></div>
|
||||
<div class="panel-body">
|
||||
<div class="table-wrap">
|
||||
<table class="data-table" id="sessions-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Coffee</th>
|
||||
<th class="num">Score</th>
|
||||
<th class="num">Cups</th>
|
||||
<th>Flavors</th>
|
||||
<th>Updated</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="sessions-body"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-card" id="new-session-card">
|
||||
<div class="panel-head"><h2>New session</h2></div>
|
||||
<div class="panel-body">
|
||||
<form id="new-session-form" class="inline-form">
|
||||
<label class="field"
|
||||
><span class="field-label">Roast (optional)</span>
|
||||
<select class="field-input" id="new-session-plan">
|
||||
<option value="">— no linked roast —</option>
|
||||
</select></label
|
||||
>
|
||||
<label class="field"
|
||||
><span class="field-label">Cups</span
|
||||
><input
|
||||
class="field-input"
|
||||
type="number"
|
||||
id="new-session-cups"
|
||||
min="1"
|
||||
max="12"
|
||||
value="5"
|
||||
/></label>
|
||||
<button class="primary-btn" type="submit">
|
||||
Start cupping
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<main class="page-content wide hidden" id="cupping-session-view">
|
||||
<div class="workspace-grid">
|
||||
<div class="form-col">
|
||||
<section class="panel-card" id="cup-scores">
|
||||
<div class="panel-head">
|
||||
<h2>Scores</h2>
|
||||
<label class="field" style="margin:0">
|
||||
<span class="field-label">Cups</span>
|
||||
<input
|
||||
class="field-input sm"
|
||||
type="number"
|
||||
id="cup-count"
|
||||
min="1"
|
||||
max="12"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<details class="why-panel" data-why="cup-scores" open>
|
||||
<summary>Why the scale starts at 6</summary>
|
||||
<p>
|
||||
The 6–10 range is a specialty-grading convention:
|
||||
anything below specialty grade simply isn't scored, so
|
||||
6 is the floor of the scale, not "zero". Score in
|
||||
quarter-point steps and leave an attribute unscored
|
||||
(—) rather than guessing — an unscored attribute
|
||||
contributes nothing, which is honest; a guessed 7.5
|
||||
pollutes every comparison you make later. The tick
|
||||
rows count cups, not quality: five clean cups out of
|
||||
five is full marks even if the coffee is merely good.
|
||||
</p>
|
||||
</details>
|
||||
<div id="cup-score-rows"></div>
|
||||
<div id="cup-tick-rows"></div>
|
||||
<details class="cupping-defects">
|
||||
<summary>Defects</summary>
|
||||
<div id="cup-defect-rows"></div>
|
||||
</details>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-card" id="cup-flavors">
|
||||
<div class="panel-head"><h2>Flavors</h2></div>
|
||||
<div class="panel-body">
|
||||
<details class="why-panel" data-why="cup-flavors" open>
|
||||
<summary>Tag what you can point at</summary>
|
||||
<p>
|
||||
A tag is only useful if you could defend it to
|
||||
another taster with the cup in front of you. Two or
|
||||
three confident descriptors beat a dozen hopeful ones
|
||||
— the list is capped at 32, but a session that needs
|
||||
10 is already suspect.
|
||||
</p>
|
||||
</details>
|
||||
<p class="field-note hidden" id="flavor-limit-note">
|
||||
32-tag limit reached.
|
||||
</p>
|
||||
<div id="flavor-families"></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-card" id="cup-notes">
|
||||
<div class="panel-head"><h2>Notes</h2></div>
|
||||
<div class="panel-body">
|
||||
<details class="why-panel" data-why="cup-notes" open>
|
||||
<summary>Notes outlive scores</summary>
|
||||
<p>
|
||||
Numbers compare roasts; sentences explain them. Write
|
||||
what you'd want to read before roasting this coffee
|
||||
again — texture, where it fell apart as it cooled,
|
||||
what you'd change.
|
||||
</p>
|
||||
</details>
|
||||
<textarea
|
||||
class="field-input"
|
||||
id="cup-notes-text"
|
||||
maxlength="4000"
|
||||
rows="5"
|
||||
aria-label="Cupping notes"
|
||||
></textarea>
|
||||
<p class="field-note"><span id="cup-notes-count">0</span>/4000</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<aside class="dock">
|
||||
<div class="dock-card">
|
||||
<div class="dock-card-head"><h2>Score</h2></div>
|
||||
<div class="stat-tile" style="box-shadow:none;border:none;padding:0">
|
||||
<div class="stat-tile-label">Total score</div>
|
||||
<div class="stat-tile-value" id="cup-total">0.00</div>
|
||||
</div>
|
||||
<p class="dock-note">Recomputed by the server on every save.</p>
|
||||
<div class="chip-group" id="flavor-chips"></div>
|
||||
</div>
|
||||
<div class="dock-card">
|
||||
<div class="dock-card-head"><h2>Radar</h2></div>
|
||||
<svg
|
||||
id="cup-radar"
|
||||
viewBox="0 0 240 240"
|
||||
role="img"
|
||||
aria-label="Cupping score radar chart"
|
||||
></svg>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
// Runs synchronously at parse time (before the deferred module script below) so opening
|
||||
// /cupping?session=… never flashes the empty sessions list first while cupping.js's own
|
||||
// async init (which awaits the auth check) is still getting underway.
|
||||
if (new URLSearchParams(location.search).get("session")) {
|
||||
document.getElementById("cupping-list-view").classList.add("hidden");
|
||||
document.getElementById("cupping-session-view").classList.remove("hidden");
|
||||
}
|
||||
</script>
|
||||
<script type="module" src="/js/cupping.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,43 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Reset your password — Roast Planner</title>
|
||||
<link rel="stylesheet" href="/app.css" />
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
|
||||
<meta name="theme-color" content="#A8481A" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="auth-page">
|
||||
<section class="panel-card auth-card">
|
||||
<div class="auth-brand">
|
||||
<span class="brand-mark" aria-hidden="true">◐</span>
|
||||
<strong>Roast Planner</strong>
|
||||
</div>
|
||||
<h1>Forgot your password?</h1>
|
||||
<p class="lede">
|
||||
Enter your account email and we'll send a link to reset your
|
||||
password.
|
||||
</p>
|
||||
<div id="message" class="auth-message" role="alert"></div>
|
||||
<form id="forgot-form">
|
||||
<label
|
||||
>Email
|
||||
<input
|
||||
class="field-input"
|
||||
required
|
||||
type="email"
|
||||
name="email"
|
||||
autocomplete="email"
|
||||
/></label>
|
||||
<button class="primary-btn" type="submit">Send reset link</button>
|
||||
</form>
|
||||
<div class="auth-links">
|
||||
<a href="/login">Back to log in</a>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<script type="module" src="/js/forgot.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+478
-126
@@ -14,71 +14,138 @@
|
||||
<link rel="stylesheet" href="/app.css" />
|
||||
</head>
|
||||
<body>
|
||||
<header class="app-header">
|
||||
<div class="brand">
|
||||
<span class="brand-mark" aria-hidden="true">◐</span>
|
||||
<div class="brand-text">
|
||||
<h1>Roast Planner</h1>
|
||||
<p class="brand-sub" id="header-coffee-name">New plan</p>
|
||||
<div class="app-shell">
|
||||
<nav class="side-nav" id="side-nav" aria-label="Main navigation">
|
||||
<div class="side-nav-brand">
|
||||
<span class="brand-mark" aria-hidden="true">◐</span>
|
||||
<span class="brand-name">Roast Planner</span>
|
||||
</div>
|
||||
<div class="nav-group">
|
||||
<a class="nav-item" href="/app" aria-current="page"
|
||||
><span class="nav-icon" aria-hidden="true">◐</span
|
||||
><span class="nav-label">Planner</span></a
|
||||
>
|
||||
<button class="nav-item" type="button" id="nav-plans">
|
||||
<span class="nav-icon" aria-hidden="true">▤</span
|
||||
><span class="nav-label">Plans</span>
|
||||
</button>
|
||||
<a class="nav-item" href="/inventory"
|
||||
><span class="nav-icon" aria-hidden="true">▥</span
|
||||
><span class="nav-label">Inventory</span></a
|
||||
>
|
||||
<a class="nav-item" href="/cupping"
|
||||
><span class="nav-icon" aria-hidden="true">◒</span
|
||||
><span class="nav-label">Cupping</span></a
|
||||
>
|
||||
<a class="nav-item" href="/account"
|
||||
><span class="nav-icon" aria-hidden="true">◔</span
|
||||
><span class="nav-label">Account</span></a
|
||||
>
|
||||
<a class="nav-item hidden" id="nav-admin" href="/admin"
|
||||
><span class="nav-icon" aria-hidden="true">⚙</span
|
||||
><span class="nav-label">Admin</span></a
|
||||
>
|
||||
</div>
|
||||
<div class="nav-group">
|
||||
<div class="nav-group-title">Tools</div>
|
||||
<button class="nav-item" type="button" id="nav-prefill">
|
||||
<span class="nav-icon" aria-hidden="true">↗</span
|
||||
><span class="nav-label">Prefill from URL</span>
|
||||
</button>
|
||||
<button class="nav-item" type="button" id="nav-alog">
|
||||
<span class="nav-icon" aria-hidden="true">∿</span
|
||||
><span class="nav-label">Reference curve</span>
|
||||
</button>
|
||||
<button class="nav-item" type="button" id="nav-import-export">
|
||||
<span class="nav-icon" aria-hidden="true">⇅</span
|
||||
><span class="nav-label">Import / export</span>
|
||||
</button>
|
||||
<button
|
||||
class="nav-item"
|
||||
type="button"
|
||||
id="btn-toggle-fids"
|
||||
aria-pressed="false"
|
||||
title="Show the worksheet reference codes (e.g. 1.4) on every field"
|
||||
>
|
||||
<span class="nav-icon" aria-hidden="true">#</span
|
||||
><span class="nav-label">Field IDs</span>
|
||||
</button>
|
||||
<button class="nav-item" type="button" id="nav-settings">
|
||||
<span class="nav-icon" aria-hidden="true">◎</span
|
||||
><span class="nav-label">Settings & sync</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="nav-spacer"></div>
|
||||
<button
|
||||
class="icon-btn nav-collapse-toggle"
|
||||
type="button"
|
||||
id="nav-collapse"
|
||||
aria-label="Collapse navigation"
|
||||
title="Collapse navigation"
|
||||
>
|
||||
«
|
||||
</button>
|
||||
<div class="nav-user">
|
||||
<div class="nav-user-avatar" id="nav-user-avatar" aria-hidden="true"></div>
|
||||
<div class="nav-user-detail">
|
||||
<span class="nav-user-email" id="account-email"></span>
|
||||
<button class="nav-user-logout" type="button" id="btn-logout">
|
||||
Log out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav class="section-nav" id="section-nav" aria-label="Plan sections">
|
||||
<a href="#sec-coffee">Plan</a>
|
||||
<a href="#sec-bean">Bean condition</a>
|
||||
<a href="#sec-machine">Roast</a>
|
||||
<a href="#sec-after">Learn</a>
|
||||
</nav>
|
||||
|
||||
<div class="header-actions">
|
||||
<button id="btn-plans" type="button" class="ghost-btn">Plans</button>
|
||||
<button
|
||||
id="btn-toggle-fids"
|
||||
type="button"
|
||||
class="ghost-btn"
|
||||
aria-pressed="false"
|
||||
title="Show the worksheet reference codes (e.g. 1.4) on every field"
|
||||
>
|
||||
Field IDs
|
||||
</button>
|
||||
<button id="btn-toggle-prefill" type="button" class="ghost-btn">
|
||||
Prefill from URL
|
||||
</button>
|
||||
<button id="btn-toggle-alog" type="button" class="ghost-btn">
|
||||
Reference curve
|
||||
</button>
|
||||
<span class="header-divider" aria-hidden="true"></span>
|
||||
<button id="btn-load" type="button" class="ghost-btn">Load</button>
|
||||
<input id="file-load" type="file" accept="application/json" />
|
||||
<button id="btn-save" type="button" class="ghost-btn">Download</button>
|
||||
<details class="account-menu">
|
||||
<summary class="ghost-btn" id="account-summary">Account</summary>
|
||||
<div class="account-menu-popover">
|
||||
<p class="account-email" id="account-email"></p>
|
||||
<button id="btn-settings" type="button">Settings & sync</button>
|
||||
<a id="menu-admin" class="hidden" href="/admin">Admin</a>
|
||||
<button id="btn-logout" type="button">Log out</button>
|
||||
<div class="app-workspace" id="app-workspace">
|
||||
<header class="app-header">
|
||||
<div class="header-row-top">
|
||||
<button
|
||||
class="icon-btn nav-hamburger"
|
||||
type="button"
|
||||
id="nav-hamburger"
|
||||
aria-label="Open navigation"
|
||||
aria-expanded="false"
|
||||
>
|
||||
☰
|
||||
</button>
|
||||
<div class="brand">
|
||||
<div class="brand-text">
|
||||
<h1>Roast Planner</h1>
|
||||
<p class="brand-sub" id="header-coffee-name">New plan</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
<button id="btn-print" type="button" class="primary-btn">Print</button>
|
||||
<span class="autosave-chip" id="autosave-status"
|
||||
><span class="dot"></span
|
||||
><span class="autosave-text">Not saved yet</span></span
|
||||
>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div
|
||||
class="connection-status hidden"
|
||||
id="connection-status"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
></div>
|
||||
<div class="drawer-overlay hidden" id="drawer-overlay"></div>
|
||||
<nav class="section-nav" id="section-nav" aria-label="Plan sections">
|
||||
<a href="#sec-coffee">Plan</a>
|
||||
<a href="#sec-bean">Bean</a>
|
||||
<a href="#sec-machine">Machine plan</a>
|
||||
<a href="#sec-roastlog">Roast log</a>
|
||||
<a href="#sec-after">After</a>
|
||||
</nav>
|
||||
|
||||
<aside
|
||||
class="drawer hidden"
|
||||
id="panel-prefill"
|
||||
<div class="header-actions">
|
||||
<span class="autosave-chip" id="autosave-status"
|
||||
><span class="dot"></span
|
||||
><span class="autosave-text">Not saved yet</span></span
|
||||
>
|
||||
<button id="btn-print" type="button" class="primary-btn">
|
||||
Print
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div
|
||||
class="connection-status hidden"
|
||||
id="connection-status"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
></div>
|
||||
<div class="drawer-overlay hidden" id="drawer-overlay"></div>
|
||||
|
||||
<aside
|
||||
class="drawer hidden"
|
||||
id="panel-prefill"
|
||||
aria-hidden="true"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
@@ -184,6 +251,39 @@
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<aside
|
||||
class="drawer hidden"
|
||||
id="panel-import-export"
|
||||
aria-hidden="true"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="import-export-title"
|
||||
tabindex="-1"
|
||||
>
|
||||
<div class="drawer-head">
|
||||
<h3 id="import-export-title">Import / export</h3>
|
||||
<button
|
||||
class="icon-btn"
|
||||
type="button"
|
||||
data-close-drawer
|
||||
aria-label="Close"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<div class="drawer-body">
|
||||
<p class="stack-label">Load a plan from a JSON file</p>
|
||||
<button id="btn-load" type="button" class="primary-btn">
|
||||
Choose file…
|
||||
</button>
|
||||
<input id="file-load" type="file" accept="application/json" />
|
||||
<p class="stack-label">Save the current plan</p>
|
||||
<button id="btn-save" type="button" class="ghost-btn">
|
||||
Download as JSON
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<aside
|
||||
class="drawer hidden"
|
||||
id="panel-settings"
|
||||
@@ -230,6 +330,28 @@
|
||||
<section class="panel-card" id="sec-coffee">
|
||||
<div class="panel-head"><h2>The Coffee</h2></div>
|
||||
<div class="panel-body">
|
||||
<details class="why-panel" data-why="sec-coffee" open>
|
||||
<summary>Why cultivar sets the clock</summary>
|
||||
<p>
|
||||
A roast plan is three durations laid end to end: drying +
|
||||
Maillard + development = the total roast. Cultivar is the
|
||||
one input that sets a time you cannot negotiate — when
|
||||
first crack lands. The seed's genetics fix how much sugar
|
||||
and acid it carries and how heat gets into it, so each
|
||||
cultivar browns and builds its aromatics on its own
|
||||
schedule. A Bourbon rushed to a 7:30 first crack tastes
|
||||
thin and papery no matter how well you handle the rest; a
|
||||
Gesha dragged to 9:00 goes savory and loses the florals you
|
||||
paid for.
|
||||
</p>
|
||||
<p>
|
||||
That is why the FC anchor below feeds Time Ledger line 1
|
||||
and everything else in the plan is a correction of seconds
|
||||
around it. Treat the cultivar on the bag as your best
|
||||
hypothesis, not a fact — labels are wrong often enough that
|
||||
the "After the Roast" section exists to correct them.
|
||||
</p>
|
||||
</details>
|
||||
<div class="field-grid">
|
||||
<label class="field" data-fid="0.1"
|
||||
><span class="field-label">Coffee / lot</span
|
||||
@@ -254,6 +376,16 @@
|
||||
>
|
||||
</div></label
|
||||
>
|
||||
<label class="field" id="lot-picker-field">
|
||||
<span class="field-label">From inventory lot</span>
|
||||
<select class="field-input" name="inventory.lotId" id="lot-select">
|
||||
<option value="">— none —</option>
|
||||
</select>
|
||||
<span class="field-note" id="lot-picker-note"
|
||||
>Optional — link a lot and the Roast Log can draw the
|
||||
green weight down when you charge.</span
|
||||
>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="subhead">Cultivar</div>
|
||||
@@ -267,14 +399,14 @@
|
||||
placeholder="e.g. Caturra"
|
||||
autocomplete="off"
|
||||
/></label>
|
||||
<div class="field" data-fid="1.3">
|
||||
<label class="field" data-fid="1.3">
|
||||
<span class="field-label">Origin</span
|
||||
><input
|
||||
class="field-input"
|
||||
name="1.3"
|
||||
placeholder="e.g. Huila, Colombia"
|
||||
/>
|
||||
</div>
|
||||
</label>
|
||||
<div class="field wide" data-fid="1.2">
|
||||
<span class="field-label">Group</span>
|
||||
<div class="segmented" data-radio-group="1.2">
|
||||
@@ -303,13 +435,14 @@
|
||||
</div>
|
||||
<div class="field-grid">
|
||||
<label class="field" data-fid="1.4"
|
||||
><span class="field-label"
|
||||
>FC anchor
|
||||
<span class="hint" title="Feeds Time Ledger line 1"
|
||||
>ⓘ</span
|
||||
></span
|
||||
><input class="field-input" name="1.4" placeholder="8:45"
|
||||
/></label>
|
||||
><span class="field-label">FC anchor</span
|
||||
><input class="field-input" name="1.4" placeholder="8:45" />
|
||||
<span class="field-note"
|
||||
>Ledger line 1 — the whole plan hangs from this. Use
|
||||
your cultivar's own row (autofills from the list),
|
||||
never a group average.</span
|
||||
></label
|
||||
>
|
||||
<label class="field" data-fid="1.5"
|
||||
><span class="field-label">Profile mm:ss|mm:ss|mm:ss</span
|
||||
><input
|
||||
@@ -318,25 +451,23 @@
|
||||
placeholder="4:15|3:15|1:30"
|
||||
/></label>
|
||||
<label class="field" data-fid="1.6"
|
||||
><span class="field-label"
|
||||
>± Refine
|
||||
<span
|
||||
class="hint"
|
||||
title="0 on the first cook of this cultivar, otherwise carried from Step 12"
|
||||
>ⓘ</span
|
||||
></span
|
||||
><input class="field-input" name="1.6" placeholder="0"
|
||||
/></label>
|
||||
><span class="field-label">± Refine</span
|
||||
><input class="field-input" name="1.6" placeholder="0" />
|
||||
<span class="field-note"
|
||||
>0 the first time you roast this coffee. Afterwards,
|
||||
carry "One change next batch" here — this is how the
|
||||
plan learns.</span
|
||||
></label
|
||||
>
|
||||
<label class="field" data-fid="1.7"
|
||||
><span class="field-label"
|
||||
>± Dev modifier
|
||||
<span
|
||||
class="hint"
|
||||
title="Step 1's profile 3rd number, minus 1:30"
|
||||
>ⓘ</span
|
||||
></span
|
||||
><input class="field-input" name="1.7"
|
||||
/></label>
|
||||
><span class="field-label">± Dev modifier</span
|
||||
><input class="field-input" name="1.7" />
|
||||
<span class="field-note"
|
||||
>Your cultivar profile's third number minus 1:30 —
|
||||
autofilled; 0 for most cultivars. Feeds ledger line
|
||||
9.</span
|
||||
></label
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -344,20 +475,41 @@
|
||||
<section class="panel-card" id="sec-blend">
|
||||
<div class="panel-head">
|
||||
<h2>Blend</h2>
|
||||
<div class="segmented small" data-radio-group="2.1">
|
||||
<label class="seg-opt"
|
||||
><input type="radio" name="2.1" value="single" checked /><span
|
||||
>Single-origin</span
|
||||
></label
|
||||
>
|
||||
<label class="seg-opt"
|
||||
><input type="radio" name="2.1" value="blend" /><span
|
||||
>Blend</span
|
||||
></label
|
||||
>
|
||||
<div class="field" data-fid="2.1">
|
||||
<div class="segmented small" data-radio-group="2.1">
|
||||
<label class="seg-opt"
|
||||
><input type="radio" name="2.1" value="single" checked /><span
|
||||
>Single-origin</span
|
||||
></label
|
||||
>
|
||||
<label class="seg-opt"
|
||||
><input type="radio" name="2.1" value="blend" /><span
|
||||
>Blend</span
|
||||
></label
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-body" id="blend-body">
|
||||
<details class="why-panel" data-why="sec-blend" open>
|
||||
<summary>Why blends combine times, never temperatures</summary>
|
||||
<p>
|
||||
The drum has one heat setting and one clock — you cannot
|
||||
give 55% of the mass a different schedule than the other
|
||||
45%. Times are additive, so a weighted average of two
|
||||
first-crack anchors is another valid time on the same
|
||||
clock. An average of two temperatures means nothing: first
|
||||
crack is a property of the chemistry, not a dial you set.
|
||||
</p>
|
||||
<p>
|
||||
If one component is 60% or more of the batch, roast the
|
||||
whole batch as that coffee and let the rest ride along. If
|
||||
no component dominates, weight each anchor by its share.
|
||||
And if components disagree by more than about a minute at
|
||||
first crack, split-roast and blend after — one compromise
|
||||
profile serves neither half.
|
||||
</p>
|
||||
</details>
|
||||
<div class="blend-cards" id="blend-cards"></div>
|
||||
<div class="blend-total" id="blend-total">
|
||||
<div class="blend-total-bar">
|
||||
@@ -394,8 +546,12 @@
|
||||
<div class="field-grid">
|
||||
<label class="field" data-fid="2.4"
|
||||
><span class="field-label">Resulting FC anchor</span
|
||||
><input class="field-input" name="2.4"
|
||||
/></label>
|
||||
><input class="field-input" name="2.4" />
|
||||
<span class="field-note"
|
||||
>Replaces 1.4 as ledger line 1 while "Blend" is
|
||||
selected.</span
|
||||
></label
|
||||
>
|
||||
<label class="field" data-fid="2.5"
|
||||
><span class="field-label">Resulting processing modifier</span
|
||||
><input class="field-input" name="2.5"
|
||||
@@ -407,6 +563,30 @@
|
||||
<section class="panel-card" id="sec-process">
|
||||
<div class="panel-head"><h2>Roast Target</h2></div>
|
||||
<div class="panel-body">
|
||||
<details class="why-panel" data-why="sec-process" open>
|
||||
<summary>Why processing moves development, not first crack</summary>
|
||||
<p>
|
||||
Processing changed the chemistry that browning starts
|
||||
from. Naturals and dark honeys keep far more free
|
||||
fructose, and fructose browns faster than sucrose — the
|
||||
same profile lands visibly darker. That is why natural and
|
||||
honey lots take 15–30 seconds <em>less</em> development
|
||||
and want a slightly earlier drop, and why processing never
|
||||
touches the first-crack anchor. Change development and
|
||||
drop, hold everything else, and the experiment stays
|
||||
readable.
|
||||
</p>
|
||||
<p>
|
||||
Roast level is the one input that is purely your decision
|
||||
— and development is a bell curve, not a slider. Shorter
|
||||
development pushes acidity up, longer pulls it down; but
|
||||
too short reads sharp and astringent with no fruit behind
|
||||
it, and too long goes flat and dull. The pleasant region is
|
||||
in the middle and narrower than the acidity curve
|
||||
suggests, which is why the fix is always a 15-second step
|
||||
with a cupping in between, never a big swing.
|
||||
</p>
|
||||
</details>
|
||||
<div class="field wide" data-fid="3.1">
|
||||
<span class="field-label">Process</span>
|
||||
<div class="chip-group" data-radio-group="3.1">
|
||||
@@ -442,8 +622,13 @@
|
||||
<div class="field-grid">
|
||||
<label class="field" data-fid="3.2"
|
||||
><span class="field-label">Dev modifier</span
|
||||
><input class="field-input" name="3.2"
|
||||
/></label>
|
||||
><input class="field-input" name="3.2" />
|
||||
<span class="field-note"
|
||||
>Washed 0 · natural / dark honey −0:15 to −0:30 ·
|
||||
anaerobic a further −0:10 to −0:15. Feeds ledger line
|
||||
8.</span
|
||||
></label
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="subhead">Roast level</div>
|
||||
@@ -483,26 +668,49 @@
|
||||
<input class="field-input" name="4.2" /><span class="unit"
|
||||
>%</span
|
||||
>
|
||||
</div></label
|
||||
</div>
|
||||
<span class="field-note"
|
||||
>Light 11–13% · medium 14–16% · dark 17–18%. Your
|
||||
after-roast scale check against this is the honest
|
||||
measure of roast degree.</span
|
||||
></label
|
||||
>
|
||||
<label class="field" data-fid="4.3"
|
||||
><span class="field-label">Dev base</span
|
||||
><input class="field-input" name="4.3"
|
||||
/></label>
|
||||
><input class="field-input" name="4.3" />
|
||||
<span class="field-note"
|
||||
>Ledger line 7. Light 1:15–2:00 · medium 2:00–3:00 ·
|
||||
dark 3:00–4:00. Development past 4:30 mutes any
|
||||
roast.</span
|
||||
></label
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-card" id="sec-bean">
|
||||
<div class="panel-head"><h2>Bean Condition</h2></div>
|
||||
<div class="unknown-condition" role="note">
|
||||
<strong>Don't have lab measurements?</strong> Moisture and density
|
||||
are optional. Leave them blank and record only evidence you have
|
||||
(supplier COA, lot notes, or your next roast). They never change
|
||||
the ledger automatically. Use Net correction only when you can
|
||||
explain the observation behind it.
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<details class="why-panel" data-why="sec-bean" open>
|
||||
<summary>Why bean condition is worth seconds, not a new plan</summary>
|
||||
<p>
|
||||
Moisture, density and screen size change how much energy the
|
||||
plan costs, not its shape. Wet greens (over 11.5%) stall as
|
||||
they near 100 °C while water boils off — expect the flat
|
||||
spot and don't panic-add heat. Dense, high-grown seed
|
||||
tolerates a hard early push; soft, low-grown seed gives you
|
||||
defects instead of speed. Very large beans scorch outside
|
||||
while the core lags — the safe way to go faster is more
|
||||
airflow at a lower inlet temperature, never more burner.
|
||||
</p>
|
||||
<p>
|
||||
None of these auto-adjust the ledger, and that is
|
||||
deliberate: they inform the ±0:15 judgment in Net correction
|
||||
and your heat/fan choices, nothing more. Don't have lab
|
||||
numbers? Leave moisture and density blank — record only
|
||||
evidence you actually have.
|
||||
</p>
|
||||
</details>
|
||||
<div class="field-grid">
|
||||
<label class="field" data-fid="5.1"
|
||||
><span class="field-label">Moisture</span>
|
||||
@@ -551,15 +759,14 @@
|
||||
</div>
|
||||
</div>
|
||||
<label class="field" data-fid="5.6"
|
||||
><span class="field-label"
|
||||
>± Net correction
|
||||
<span
|
||||
class="hint"
|
||||
title="Judgment call — rarely more than ±0:15"
|
||||
>ⓘ</span
|
||||
></span
|
||||
><input class="field-input" name="5.6"
|
||||
/></label>
|
||||
><span class="field-label">± Net correction</span
|
||||
><input class="field-input" name="5.6" />
|
||||
<span class="field-note"
|
||||
>Rarely more than ±0:15, and only for an observation
|
||||
you can name — moisture and density never create this
|
||||
number automatically. Feeds ledger line 3.</span
|
||||
></label
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -567,6 +774,31 @@
|
||||
<section class="panel-card" id="sec-machine">
|
||||
<div class="panel-head"><h2>Machine Plan</h2></div>
|
||||
<div class="panel-body">
|
||||
<details class="why-panel" data-why="sec-machine" open>
|
||||
<summary>
|
||||
Why the rate of rise must fall, and never touch zero
|
||||
</summary>
|
||||
<p>
|
||||
A bean that is still gaining heat, but gaining it more
|
||||
slowly, is moving through its reactions in order. Two
|
||||
shapes break that. The crash: RoR falls off a cliff just
|
||||
after first crack, when the exotherm ends and an oversized
|
||||
heat cut lands at the same moment. The bake: RoR flattens
|
||||
toward zero, the bean sits at temperature without
|
||||
progressing, and the cup goes flat, papery and
|
||||
sweetness-free — nothing after the drop rescues a bake.
|
||||
</p>
|
||||
<p>
|
||||
So the rule is: decline steadily from the
|
||||
post-turning-point peak, through small frequent heat cuts
|
||||
rather than a few big ones, and stay ahead of the
|
||||
machine's roughly 60-second lag — what you change now
|
||||
shows up a minute from now, so cut <em>before</em> the
|
||||
exotherm, gently. If a phase would need a rate outside the
|
||||
proven bands to hit its milestone, the plan is not
|
||||
reachable — fix the ledger, not the roaster.
|
||||
</p>
|
||||
</details>
|
||||
<div class="subhead">Temperatures & rate-of-rise</div>
|
||||
<div class="milestone-list">
|
||||
<div
|
||||
@@ -587,6 +819,7 @@
|
||||
class="field-input sm"
|
||||
name="temps.charge.tempC"
|
||||
placeholder="°C"
|
||||
aria-label="Charge planned temperature"
|
||||
/><span class="unit">°C</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -600,6 +833,7 @@
|
||||
class="field-input sm milestone-time"
|
||||
name="temps.tp.time"
|
||||
placeholder="m:ss"
|
||||
aria-label="Turning point planned time"
|
||||
/>
|
||||
<div class="band-track">
|
||||
<div class="band-range"></div>
|
||||
@@ -610,6 +844,7 @@
|
||||
class="field-input sm"
|
||||
name="temps.tp.tempC"
|
||||
placeholder="°C"
|
||||
aria-label="Turning point planned temperature"
|
||||
/><span class="unit">°C</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -629,6 +864,7 @@
|
||||
class="field-input sm"
|
||||
name="temps.yellow.tempC"
|
||||
placeholder="°C"
|
||||
aria-label="Yellow planned temperature"
|
||||
/><span class="unit">°C</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -648,6 +884,7 @@
|
||||
class="field-input sm"
|
||||
name="temps.fc.tempC"
|
||||
placeholder="°C"
|
||||
aria-label="First crack planned temperature"
|
||||
/><span class="unit">°C</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -667,12 +904,18 @@
|
||||
class="field-input sm"
|
||||
name="temps.drop.tempC"
|
||||
placeholder="°C"
|
||||
aria-label="Drop planned temperature"
|
||||
/><span class="unit">°C</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="subhead">Actuator schedule (planned)</div>
|
||||
<p class="field-note">
|
||||
The timing of your first heat cut is the main first-crack
|
||||
lever — later cut, earlier crack. Say why you make each
|
||||
change; that's what makes this log readable next week.
|
||||
</p>
|
||||
<div class="actuator-timeline" id="actuator-timeline"></div>
|
||||
<button
|
||||
type="button"
|
||||
@@ -684,9 +927,34 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-card" id="sec-roastlog">
|
||||
<div class="panel-head"><h2>Roast Log — Plan vs. Actual</h2></div>
|
||||
<div class="phase-divider" role="separator" aria-label="Roast day begins">
|
||||
<span class="phase-divider-label">Roast day</span>
|
||||
<span class="phase-divider-text"
|
||||
>Everything above is decided before you charge. Fill in from
|
||||
here down at the machine, then after cupping. Print takes the
|
||||
plan with you.</span
|
||||
>
|
||||
</div>
|
||||
|
||||
<section class="panel-card phase-later" id="sec-roastlog">
|
||||
<div class="panel-head">
|
||||
<h2>Roast Log — Plan vs. Actual</h2>
|
||||
<span class="phase-chip">during the roast</span>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<details class="why-panel" data-why="sec-roastlog" open>
|
||||
<summary>Record what you observed, never what you planned</summary>
|
||||
<p>
|
||||
A planned milestone written into the log as though it
|
||||
happened destroys the only evidence you have. If you never
|
||||
actually heard first crack, write that down — "not heard,
|
||||
called at 8:10 by smell" is a useful record. "8:00"
|
||||
because that was the plan is worse than nothing, because
|
||||
next batch you will trust it. The plan column stays fixed
|
||||
beside your entries precisely so the gap is visible. The
|
||||
gap is the data.
|
||||
</p>
|
||||
</details>
|
||||
<div class="milestone-list">
|
||||
<div class="milestone-row log-row">
|
||||
<div class="milestone-label">Charge</div>
|
||||
@@ -697,16 +965,19 @@
|
||||
class="field-input sm"
|
||||
name="planActual.charge.actualTime"
|
||||
placeholder="0:00"
|
||||
aria-label="Charge actual time"
|
||||
/>
|
||||
<input
|
||||
class="field-input sm"
|
||||
name="planActual.charge.actualBt"
|
||||
placeholder="°C"
|
||||
aria-label="Charge actual temperature"
|
||||
/>
|
||||
<input
|
||||
class="field-input note"
|
||||
name="planActual.charge.note"
|
||||
placeholder="Note"
|
||||
aria-label="Charge note"
|
||||
/>
|
||||
</div>
|
||||
<div class="milestone-row log-row">
|
||||
@@ -716,16 +987,19 @@
|
||||
class="field-input sm"
|
||||
name="planActual.tp.actualTime"
|
||||
placeholder="0:00"
|
||||
aria-label="Turning point actual time"
|
||||
/>
|
||||
<input
|
||||
class="field-input sm"
|
||||
name="planActual.tp.actualBt"
|
||||
placeholder="°C"
|
||||
aria-label="Turning point actual temperature"
|
||||
/>
|
||||
<input
|
||||
class="field-input note"
|
||||
name="planActual.tp.note"
|
||||
placeholder="Note"
|
||||
aria-label="Turning point note"
|
||||
/>
|
||||
</div>
|
||||
<div class="milestone-row log-row">
|
||||
@@ -735,16 +1009,19 @@
|
||||
class="field-input sm"
|
||||
name="planActual.yellow.actualTime"
|
||||
placeholder="0:00"
|
||||
aria-label="Yellow actual time"
|
||||
/>
|
||||
<input
|
||||
class="field-input sm"
|
||||
name="planActual.yellow.actualBt"
|
||||
placeholder="°C"
|
||||
aria-label="Yellow actual temperature"
|
||||
/>
|
||||
<input
|
||||
class="field-input note"
|
||||
name="planActual.yellow.note"
|
||||
placeholder="Note"
|
||||
aria-label="Yellow note"
|
||||
/>
|
||||
</div>
|
||||
<div class="milestone-row log-row">
|
||||
@@ -754,16 +1031,19 @@
|
||||
class="field-input sm"
|
||||
name="planActual.fc.actualTime"
|
||||
placeholder="0:00"
|
||||
aria-label="First crack actual time"
|
||||
/>
|
||||
<input
|
||||
class="field-input sm"
|
||||
name="planActual.fc.actualBt"
|
||||
placeholder="°C"
|
||||
aria-label="First crack actual temperature"
|
||||
/>
|
||||
<input
|
||||
class="field-input note"
|
||||
name="planActual.fc.note"
|
||||
placeholder="Note"
|
||||
aria-label="First crack note"
|
||||
/>
|
||||
</div>
|
||||
<div class="milestone-row log-row">
|
||||
@@ -773,25 +1053,61 @@
|
||||
class="field-input sm"
|
||||
name="planActual.drop.actualTime"
|
||||
placeholder="0:00"
|
||||
aria-label="Drop actual time"
|
||||
/>
|
||||
<input
|
||||
class="field-input sm"
|
||||
name="planActual.drop.actualBt"
|
||||
placeholder="°C"
|
||||
aria-label="Drop actual temperature"
|
||||
/>
|
||||
<input
|
||||
class="field-input note"
|
||||
name="planActual.drop.note"
|
||||
placeholder="Note"
|
||||
aria-label="Drop note"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="inventory-consume hidden" id="inventory-consume">
|
||||
<span class="inventory-consume-label" id="inventory-consume-label"></span>
|
||||
<button type="button" class="ghost-btn small" id="btn-consume">
|
||||
Draw from lot
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-card" id="sec-after">
|
||||
<div class="panel-head"><h2>After the Roast</h2></div>
|
||||
<section class="panel-card phase-later" id="sec-after">
|
||||
<div class="panel-head">
|
||||
<h2>After the Roast</h2>
|
||||
<span class="phase-chip">after cupping</span>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<details class="why-panel" data-why="sec-after" open>
|
||||
<summary>One change per batch — arithmetic, not patience</summary>
|
||||
<p>
|
||||
Move two variables and there are four possible
|
||||
explanations for what the cup does; move three and there
|
||||
are eight, and you can't separate them without more
|
||||
batches than you have coffee for. This worksheet makes
|
||||
single-variable experiments cheap: every number has one
|
||||
owner.
|
||||
</p>
|
||||
<p>
|
||||
Weight loss is the honest instrument — (green − roasted) ÷
|
||||
green × 100 rolls total time, development, and drop
|
||||
temperature into one number your scale can measure. Then
|
||||
match the cup to a symptom: papery or thin → first crack
|
||||
+0:30. Savory, florals gone → first crack −0:30. Sharp
|
||||
acidity with no fruit → development +0:15 (a DTR under 12%
|
||||
confirms it). Flat and dull → development −0:15. Flat with
|
||||
no clear defect → fix the RoR shape, not the times. Write
|
||||
the winner into "One change next batch" — and next time
|
||||
you roast this coffee, carry it into ± Refine (1.6). That
|
||||
handoff is how the plan learns.
|
||||
</p>
|
||||
</details>
|
||||
<div class="field-grid">
|
||||
<label class="field"
|
||||
><span class="field-label">Green in</span>
|
||||
@@ -867,6 +1183,12 @@
|
||||
><input class="field-input" name="afterRoast.disproof"
|
||||
/></label>
|
||||
</div>
|
||||
<div class="cupping-link">
|
||||
<button type="button" class="ghost-btn" id="btn-open-cupping">
|
||||
Open cupping session
|
||||
</button>
|
||||
<span class="field-note" id="cupping-link-note"></span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
@@ -874,6 +1196,10 @@
|
||||
<aside class="dock" aria-label="Live plan feedback">
|
||||
<div class="dock-card ledger-card" id="plan-now">
|
||||
<div class="dock-card-head"><h2>Time Ledger</h2></div>
|
||||
<p class="dock-note">
|
||||
Drying + Maillard + Development = the whole roast. Cultivar
|
||||
sets first crack; process and level set development.
|
||||
</p>
|
||||
|
||||
<div class="ledger-group">
|
||||
<div class="ledger-row">
|
||||
@@ -894,7 +1220,13 @@
|
||||
<div class="ledger-row">
|
||||
<span class="l-fid">6.4</span
|
||||
><span class="l-label">± Batch size</span
|
||||
><input class="ledger-input" name="6.4" placeholder="0" />
|
||||
><input
|
||||
class="ledger-input"
|
||||
name="6.4"
|
||||
placeholder="0"
|
||||
aria-label="Batch-size correction"
|
||||
title="225 g lands first crack ~1:30–2:00 later than 200 g"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ledger-total hero">
|
||||
@@ -952,21 +1284,37 @@
|
||||
<span class="check-name">Drying share</span>
|
||||
<output class="check-value" data-out="check-drying">—</output>
|
||||
<span class="check-band">target 43–51%</span>
|
||||
<span class="check-why"
|
||||
>high = late yellow, browning starved · low = rushed
|
||||
before internal pressure built</span
|
||||
>
|
||||
</div>
|
||||
<div class="check-tile unknown" data-pass="maillard">
|
||||
<span class="check-name">Maillard share</span>
|
||||
<output class="check-value" data-out="check-maillard">—</output>
|
||||
<span class="check-band">target 33–39%</span>
|
||||
<span class="check-why"
|
||||
>low = too small a browning window for sweetness and
|
||||
complexity</span
|
||||
>
|
||||
</div>
|
||||
<div class="check-tile unknown" data-pass="dtr">
|
||||
<span class="check-name">Development ratio</span>
|
||||
<output class="check-value" data-out="check-dtr">—</output>
|
||||
<span class="check-band">target 12–20%</span>
|
||||
<span class="check-why"
|
||||
>under 12% = under-developed — sharp, astringent acidity
|
||||
with no fruit behind it</span
|
||||
>
|
||||
</div>
|
||||
<div class="check-tile unknown" data-pass="ceiling">
|
||||
<span class="check-name">Development ceiling</span>
|
||||
<output class="check-value" data-out="check-ceiling">—</output>
|
||||
<span class="check-band">under 4:30</span>
|
||||
<span class="check-why"
|
||||
>over 4:30 mutes any roast — nothing good is past this
|
||||
line</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1116,8 +1464,12 @@
|
||||
</aside>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<!-- /app-workspace -->
|
||||
</div>
|
||||
<!-- /app-shell -->
|
||||
|
||||
<!-- Kept OUTSIDE #plan-form on purpose: identically-named radios here must not fight for
|
||||
<!-- Kept OUTSIDE #plan-form and OUTSIDE .app-shell on purpose: identically-named radios here must not fight for
|
||||
mutual exclusivity with the screen form's radios (same name + same form owner would
|
||||
silently uncheck one another). This whole block is display:none except when printing;
|
||||
main.js re-syncs it from state.plan on beforeprint. -->
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Inventory — Roast Planner</title>
|
||||
<link rel="stylesheet" href="/app.css" />
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
|
||||
<meta name="theme-color" content="#A8481A" />
|
||||
</head>
|
||||
<body>
|
||||
<div class="app-shell">
|
||||
<nav class="side-nav" id="side-nav" aria-label="Main navigation">
|
||||
<div class="side-nav-brand">
|
||||
<span class="brand-mark" aria-hidden="true">◐</span>
|
||||
<span class="brand-name">Roast Planner</span>
|
||||
</div>
|
||||
<div class="nav-group">
|
||||
<a class="nav-item" href="/app"
|
||||
><span class="nav-icon" aria-hidden="true">◐</span
|
||||
><span class="nav-label">Planner</span></a
|
||||
>
|
||||
<a class="nav-item" href="/account#your-plans"
|
||||
><span class="nav-icon" aria-hidden="true">▤</span
|
||||
><span class="nav-label">Plans</span></a
|
||||
>
|
||||
<a class="nav-item" href="/inventory" aria-current="page"
|
||||
><span class="nav-icon" aria-hidden="true">▥</span
|
||||
><span class="nav-label">Inventory</span></a
|
||||
>
|
||||
<a class="nav-item" href="/cupping"
|
||||
><span class="nav-icon" aria-hidden="true">◒</span
|
||||
><span class="nav-label">Cupping</span></a
|
||||
>
|
||||
<a class="nav-item" href="/account"
|
||||
><span class="nav-icon" aria-hidden="true">◔</span
|
||||
><span class="nav-label">Account</span></a
|
||||
>
|
||||
<a class="nav-item hidden" id="nav-admin" href="/admin"
|
||||
><span class="nav-icon" aria-hidden="true">⚙</span
|
||||
><span class="nav-label">Admin</span></a
|
||||
>
|
||||
</div>
|
||||
<div class="nav-spacer"></div>
|
||||
<button
|
||||
class="icon-btn nav-collapse-toggle"
|
||||
type="button"
|
||||
id="nav-collapse"
|
||||
aria-label="Collapse navigation"
|
||||
title="Collapse navigation"
|
||||
>
|
||||
«
|
||||
</button>
|
||||
<div class="nav-user">
|
||||
<div class="nav-user-avatar" id="nav-user-avatar" aria-hidden="true"></div>
|
||||
<div class="nav-user-detail">
|
||||
<span class="nav-user-email" id="account-email"></span>
|
||||
<button class="nav-user-logout" type="button" id="btn-logout">
|
||||
Log out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="app-workspace" id="app-workspace">
|
||||
<header class="app-header">
|
||||
<div class="header-row-top">
|
||||
<button
|
||||
class="icon-btn nav-hamburger"
|
||||
type="button"
|
||||
id="nav-hamburger"
|
||||
aria-label="Open navigation"
|
||||
aria-expanded="false"
|
||||
>
|
||||
☰
|
||||
</button>
|
||||
<div class="brand">
|
||||
<div class="brand-text">
|
||||
<h1>Inventory</h1>
|
||||
<p class="brand-sub">Green bean lots and remaining stock</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div class="drawer-overlay hidden" id="drawer-overlay"></div>
|
||||
|
||||
<main class="page-content">
|
||||
<section class="panel-card" id="lots">
|
||||
<div class="panel-head">
|
||||
<h2>Green bean lots</h2>
|
||||
<label
|
||||
style="display:flex;align-items:center;gap:10px;font-size:13px;color:var(--ink-2)"
|
||||
><span class="switch"
|
||||
><input type="checkbox" id="show-archived" /><span
|
||||
class="switch-track"
|
||||
></span></span
|
||||
>Show archived</label
|
||||
>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<div class="table-wrap">
|
||||
<table class="data-table" id="lots-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Lot</th>
|
||||
<th>Process</th>
|
||||
<th>Remaining</th>
|
||||
<th>Purchased</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="lots-body"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel-card" id="lot-form-card">
|
||||
<div class="panel-head"><h2 id="lot-form-title">Add a lot</h2></div>
|
||||
<div class="panel-body">
|
||||
<form id="lot-form">
|
||||
<input type="hidden" name="id" />
|
||||
<div class="field-grid">
|
||||
<label class="field"
|
||||
><span class="field-label">Origin *</span
|
||||
><input
|
||||
class="field-input"
|
||||
name="origin"
|
||||
required
|
||||
placeholder="e.g. Huila, Colombia"
|
||||
/></label>
|
||||
<label class="field"
|
||||
><span class="field-label">Variety</span
|
||||
><input class="field-input" name="variety"
|
||||
/></label>
|
||||
<label class="field"
|
||||
><span class="field-label">Process</span
|
||||
><input class="field-input" name="process"
|
||||
/></label>
|
||||
<label class="field"
|
||||
><span class="field-label">Producer</span
|
||||
><input class="field-input" name="producer"
|
||||
/></label>
|
||||
<label class="field"
|
||||
><span class="field-label">Purchase date</span
|
||||
><input class="field-input" type="date" name="purchaseDate"
|
||||
/></label>
|
||||
<label class="field"
|
||||
><span class="field-label">Initial weight *</span>
|
||||
<div class="unit-input">
|
||||
<input
|
||||
class="field-input"
|
||||
type="number"
|
||||
name="initialWeightG"
|
||||
inputmode="decimal"
|
||||
min="0"
|
||||
step="any"
|
||||
required
|
||||
/><span class="unit">g</span>
|
||||
</div></label
|
||||
>
|
||||
<label class="field"
|
||||
><span class="field-label">Cost</span
|
||||
><input
|
||||
class="field-input"
|
||||
type="number"
|
||||
name="costTotal"
|
||||
inputmode="decimal"
|
||||
min="0"
|
||||
step="any"
|
||||
/></label>
|
||||
<label class="field"
|
||||
><span class="field-label">Moisture</span>
|
||||
<div class="unit-input">
|
||||
<input
|
||||
class="field-input"
|
||||
type="number"
|
||||
name="moisturePct"
|
||||
inputmode="decimal"
|
||||
min="0"
|
||||
step="any"
|
||||
/><span class="unit">%</span>
|
||||
</div></label
|
||||
>
|
||||
<label class="field"
|
||||
><span class="field-label">Density</span>
|
||||
<div class="unit-input">
|
||||
<input
|
||||
class="field-input"
|
||||
type="number"
|
||||
name="densityGL"
|
||||
inputmode="decimal"
|
||||
min="0"
|
||||
step="any"
|
||||
/><span class="unit">g/L</span>
|
||||
</div></label
|
||||
>
|
||||
</div>
|
||||
<label class="field"
|
||||
><span class="field-label">Notes</span
|
||||
><input class="field-input" name="notes"
|
||||
/></label>
|
||||
<p class="field-note hidden" id="lot-remaining-note"></p>
|
||||
<button class="primary-btn" type="submit" id="lot-form-submit">
|
||||
Add lot
|
||||
</button>
|
||||
<button
|
||||
class="ghost-btn hidden"
|
||||
type="button"
|
||||
id="lot-form-cancel"
|
||||
>
|
||||
Cancel edit
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<script type="module" src="/js/inventory.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,351 @@
|
||||
import { api, protectedFetch } from "./api.js";
|
||||
import { initSideNav, loadNavUser } from "./nav.js";
|
||||
import { showToast } from "./toast.js";
|
||||
|
||||
function fmtDate(value) {
|
||||
return value ? new Date(value).toLocaleString() : "—";
|
||||
}
|
||||
|
||||
function friendlyDevice(userAgent) {
|
||||
if (!userAgent) return "Unknown device";
|
||||
const browser = /Edg\//.test(userAgent)
|
||||
? "Edge"
|
||||
: /OPR\//.test(userAgent)
|
||||
? "Opera"
|
||||
: /Chrome\//.test(userAgent)
|
||||
? "Chrome"
|
||||
: /CriOS\//.test(userAgent)
|
||||
? "Chrome"
|
||||
: /Firefox\//.test(userAgent)
|
||||
? "Firefox"
|
||||
: /Safari\//.test(userAgent)
|
||||
? "Safari"
|
||||
: "Browser";
|
||||
const os = /Windows/.test(userAgent)
|
||||
? "Windows"
|
||||
: /iPhone|iPad/.test(userAgent)
|
||||
? "iOS"
|
||||
: /Mac OS X/.test(userAgent)
|
||||
? "macOS"
|
||||
: /Android/.test(userAgent)
|
||||
? "Android"
|
||||
: /Linux/.test(userAgent)
|
||||
? "Linux"
|
||||
: "";
|
||||
return os ? `${browser} on ${os}` : browser;
|
||||
}
|
||||
|
||||
async function loadProfile(user) {
|
||||
document.getElementById("profile-email").textContent = user.email;
|
||||
document
|
||||
.getElementById("profile-role-admin")
|
||||
.classList.toggle("hidden", user.role !== "admin");
|
||||
document.getElementById("email-form").email.value = user.email;
|
||||
}
|
||||
|
||||
async function loadSessions() {
|
||||
const body = document.getElementById("sessions-body");
|
||||
try {
|
||||
const { sessions } = await api("/api/account/sessions");
|
||||
if (!sessions.length) {
|
||||
body.innerHTML = `<tr><td colspan="4" class="empty-state">No active sessions.</td></tr>`;
|
||||
return;
|
||||
}
|
||||
body.replaceChildren(
|
||||
...sessions.map((session) => {
|
||||
const tr = document.createElement("tr");
|
||||
const device = document.createElement("td");
|
||||
const label = document.createElement("span");
|
||||
label.className = "session-device-label";
|
||||
label.textContent = friendlyDevice(session.userAgent);
|
||||
if (session.userAgent) label.title = session.userAgent;
|
||||
device.append(label);
|
||||
if (session.current) {
|
||||
const badge = document.createElement("span");
|
||||
badge.className = "badge badge-current";
|
||||
badge.textContent = "This device";
|
||||
badge.style.marginLeft = "8px";
|
||||
device.append(badge);
|
||||
}
|
||||
const lastSeen = document.createElement("td");
|
||||
lastSeen.textContent = fmtDate(session.lastSeenAt || session.createdAt);
|
||||
const expires = document.createElement("td");
|
||||
expires.textContent = fmtDate(session.expiresAt);
|
||||
const actions = document.createElement("td");
|
||||
const revoke = document.createElement("button");
|
||||
revoke.className = "ghost-btn small";
|
||||
revoke.type = "button";
|
||||
revoke.textContent = session.current ? "Sign out" : "Revoke";
|
||||
revoke.addEventListener("click", async () => {
|
||||
try {
|
||||
await api(`/api/account/sessions/${session.id}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
if (session.current) return location.assign("/login");
|
||||
showToast("Session revoked.");
|
||||
loadSessions();
|
||||
} catch (error) {
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
});
|
||||
actions.append(revoke);
|
||||
tr.append(device, lastSeen, expires, actions);
|
||||
return tr;
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
body.innerHTML = `<tr><td colspan="4" class="empty-state">Could not load sessions.</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPlans() {
|
||||
const body = document.getElementById("plans-body");
|
||||
try {
|
||||
const response = await fetch("/api/plans");
|
||||
if (!response.ok) throw new Error("could not load plans");
|
||||
const { plans } = await response.json();
|
||||
if (!plans.length) {
|
||||
body.innerHTML = `<tr><td colspan="3" class="empty-state">No saved plans yet.</td></tr>`;
|
||||
return;
|
||||
}
|
||||
body.replaceChildren(
|
||||
...plans.map((plan) => {
|
||||
const tr = document.createElement("tr");
|
||||
const title = document.createElement("td");
|
||||
title.textContent = plan.plan?.fields?.["0.1"] || "Untitled plan";
|
||||
const updated = document.createElement("td");
|
||||
updated.textContent = fmtDate(plan.updated_at);
|
||||
const actions = document.createElement("td");
|
||||
actions.className = "data-table-actions";
|
||||
|
||||
const open = document.createElement("a");
|
||||
open.className = "ghost-btn small";
|
||||
open.href = `/app?plan=${encodeURIComponent(plan.id)}`;
|
||||
open.textContent = "Open";
|
||||
|
||||
const duplicate = document.createElement("button");
|
||||
duplicate.className = "ghost-btn small";
|
||||
duplicate.type = "button";
|
||||
duplicate.textContent = "Duplicate";
|
||||
duplicate.addEventListener("click", async () => {
|
||||
try {
|
||||
await api("/api/plans", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ plan: plan.plan }),
|
||||
});
|
||||
showToast("Plan duplicated.");
|
||||
loadPlans();
|
||||
} catch (error) {
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
});
|
||||
|
||||
const download = document.createElement("button");
|
||||
download.className = "ghost-btn small";
|
||||
download.type = "button";
|
||||
download.textContent = "Download";
|
||||
download.addEventListener("click", () => {
|
||||
const blob = new Blob([JSON.stringify(plan.plan, null, 2)], {
|
||||
type: "application/json",
|
||||
});
|
||||
const a = document.createElement("a");
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = `${(plan.plan?.fields?.["0.1"] || "roast-plan").replace(/[^\w-]+/g, "_")}.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(a.href);
|
||||
});
|
||||
|
||||
const cup = document.createElement("button");
|
||||
cup.className = "ghost-btn small";
|
||||
cup.type = "button";
|
||||
cup.textContent = "Cup";
|
||||
cup.addEventListener("click", async () => {
|
||||
cup.disabled = true;
|
||||
try {
|
||||
const existing = await api(`/api/cupping?plan=${encodeURIComponent(plan.id)}`);
|
||||
if (existing.sessions?.length) {
|
||||
location.assign(`/cupping?session=${existing.sessions[0].id}`);
|
||||
return;
|
||||
}
|
||||
const created = await api("/api/cupping", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ roastPlanId: plan.id }),
|
||||
});
|
||||
location.assign(`/cupping?session=${created.session.id}`);
|
||||
} catch (error) {
|
||||
showToast(error.message, "fail");
|
||||
cup.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
const del = document.createElement("button");
|
||||
del.className = "ghost-btn small";
|
||||
del.type = "button";
|
||||
del.textContent = "Delete";
|
||||
del.addEventListener("click", async () => {
|
||||
if (!confirm("Delete this plan? This cannot be undone.")) return;
|
||||
try {
|
||||
await api(`/api/plans/${plan.id}`, { method: "DELETE" });
|
||||
showToast("Plan deleted.");
|
||||
loadPlans();
|
||||
} catch (error) {
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
});
|
||||
|
||||
actions.append(open, duplicate, download, cup, del);
|
||||
tr.append(title, updated, actions);
|
||||
return tr;
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
body.innerHTML = `<tr><td colspan="3" class="empty-state">Could not load plans.</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Disables `button` for the duration of `run()` so a slow request can't be double-submitted. */
|
||||
async function guarded(button, run) {
|
||||
if (button.disabled) return;
|
||||
button.disabled = true;
|
||||
try {
|
||||
await run();
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function wireForms(user) {
|
||||
document.getElementById("email-form").addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(event.target));
|
||||
guarded(event.submitter || event.target.querySelector("button[type=submit]"), async () => {
|
||||
try {
|
||||
await api("/api/account/email", { method: "PUT", body: JSON.stringify(data) });
|
||||
showToast("Email updated.");
|
||||
document.getElementById("profile-email").textContent = data.email;
|
||||
event.target.password.value = "";
|
||||
} catch (error) {
|
||||
showToast(
|
||||
error.code === "email_exists"
|
||||
? "That email is already in use."
|
||||
: error.message,
|
||||
"fail",
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
document
|
||||
.getElementById("password-form")
|
||||
.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(event.target));
|
||||
if (data.newPassword !== data.confirmPassword) {
|
||||
showToast("New passwords do not match.", "fail");
|
||||
return;
|
||||
}
|
||||
guarded(event.submitter || event.target.querySelector("button[type=submit]"), async () => {
|
||||
try {
|
||||
await api("/api/account/password", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
showToast("Password updated. Other sessions were signed out.");
|
||||
event.target.reset();
|
||||
loadSessions();
|
||||
} catch (error) {
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
document
|
||||
.getElementById("btn-revoke-others")
|
||||
.addEventListener("click", (event) => {
|
||||
guarded(event.currentTarget, async () => {
|
||||
try {
|
||||
await api("/api/account/sessions/revoke-others", { method: "POST" });
|
||||
showToast("Other sessions signed out.");
|
||||
loadSessions();
|
||||
} catch (error) {
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById("delete-form").addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(event.target));
|
||||
if (data.confirmEmail.trim().toLowerCase() !== user.email.toLowerCase()) {
|
||||
showToast("Type your email exactly to confirm.", "fail");
|
||||
return;
|
||||
}
|
||||
if (!confirm("This permanently deletes your account and plans. Continue?"))
|
||||
return;
|
||||
guarded(event.submitter || event.target.querySelector("button[type=submit]"), async () => {
|
||||
try {
|
||||
await api("/api/account", {
|
||||
method: "DELETE",
|
||||
body: JSON.stringify({ password: data.password }),
|
||||
});
|
||||
location.assign("/");
|
||||
} catch (error) {
|
||||
showToast(
|
||||
error.code === "last_admin"
|
||||
? "You are the only administrator — promote another admin first."
|
||||
: error.message,
|
||||
"fail",
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function wirePwaButtons() {
|
||||
let deferredInstallPrompt = null;
|
||||
window.addEventListener("beforeinstallprompt", (event) => {
|
||||
event.preventDefault();
|
||||
deferredInstallPrompt = event;
|
||||
document.getElementById("btn-install").classList.remove("hidden");
|
||||
});
|
||||
document.getElementById("btn-install").addEventListener("click", async () => {
|
||||
if (!deferredInstallPrompt) return;
|
||||
deferredInstallPrompt.prompt();
|
||||
await deferredInstallPrompt.userChoice;
|
||||
deferredInstallPrompt = null;
|
||||
document.getElementById("btn-install").classList.add("hidden");
|
||||
});
|
||||
if ("serviceWorker" in navigator) {
|
||||
const hadController = !!navigator.serviceWorker.controller;
|
||||
navigator.serviceWorker.getRegistration().then((registration) => {
|
||||
if (registration?.waiting)
|
||||
document.getElementById("btn-refresh").classList.remove("hidden");
|
||||
});
|
||||
navigator.serviceWorker.addEventListener("controllerchange", () => {
|
||||
if (hadController) location.reload();
|
||||
});
|
||||
}
|
||||
document.getElementById("btn-refresh").addEventListener("click", async () => {
|
||||
const registration = await navigator.serviceWorker.getRegistration();
|
||||
registration?.waiting?.postMessage("SKIP_WAITING");
|
||||
});
|
||||
}
|
||||
|
||||
document.getElementById("btn-logout").addEventListener("click", async () => {
|
||||
await protectedFetch("/api/auth/logout", { method: "POST" });
|
||||
location.assign("/");
|
||||
});
|
||||
|
||||
async function init() {
|
||||
initSideNav();
|
||||
const user = await loadNavUser();
|
||||
if (!user) return;
|
||||
document.getElementById("profile-since").textContent =
|
||||
`Member since ${fmtDate(user.createdAt)}`;
|
||||
await loadProfile(user);
|
||||
wireForms(user);
|
||||
wirePwaButtons();
|
||||
await Promise.all([loadSessions(), loadPlans()]);
|
||||
}
|
||||
|
||||
init();
|
||||
+321
-39
@@ -1,47 +1,329 @@
|
||||
const csrf = () =>
|
||||
document.cookie
|
||||
.split("; ")
|
||||
.find((value) => value.startsWith("rp_csrf="))
|
||||
?.split("=")[1] || "";
|
||||
const users = document.querySelector("#users");
|
||||
const plans = document.querySelector("#plans");
|
||||
import { api, protectedFetch } from "./api.js";
|
||||
import { initSideNav, loadNavUser } from "./nav.js";
|
||||
import { showToast } from "./toast.js";
|
||||
|
||||
async function load() {
|
||||
const usersResponse = await fetch("/api/admin/users");
|
||||
if (!usersResponse.ok) return;
|
||||
const body = await usersResponse.json();
|
||||
document.querySelector("#signup").checked = body.signupEnabled;
|
||||
users.replaceChildren(
|
||||
...body.users.map((user) =>
|
||||
Object.assign(document.createElement("li"), {
|
||||
textContent: `${user.email} (${user.role}) — ${user.plan_count} plans`,
|
||||
let currentUsers = [];
|
||||
let planFilterUserId = null;
|
||||
let currentUserId = null;
|
||||
|
||||
function fmtDate(value) {
|
||||
return value ? new Date(value).toLocaleString() : "—";
|
||||
}
|
||||
|
||||
async function loadMetrics() {
|
||||
const grid = document.getElementById("metrics");
|
||||
try {
|
||||
const { metrics } = await api("/api/admin/metrics");
|
||||
const tiles = [
|
||||
["Users", metrics.totalUsers],
|
||||
["Plans", metrics.totalPlans],
|
||||
["Plans updated (7d)", metrics.plansUpdatedLast7Days],
|
||||
["Active sessions", metrics.activeSessions],
|
||||
];
|
||||
grid.replaceChildren(
|
||||
...tiles.map(([label, value]) => {
|
||||
const tile = document.createElement("div");
|
||||
tile.className = "stat-tile";
|
||||
tile.innerHTML = `<div class="stat-tile-label"></div><div class="stat-tile-value"></div>`;
|
||||
tile.querySelector(".stat-tile-label").textContent = label;
|
||||
tile.querySelector(".stat-tile-value").textContent = value;
|
||||
return tile;
|
||||
}),
|
||||
),
|
||||
);
|
||||
const plansResponse = await fetch("/api/admin/plans");
|
||||
if (!plansResponse.ok) return;
|
||||
const plansBody = await plansResponse.json();
|
||||
plans.replaceChildren(
|
||||
...plansBody.plans.map((plan) =>
|
||||
Object.assign(document.createElement("li"), {
|
||||
textContent: `${plan.email}: ${plan.plan?.fields?.["0.1"] || "Untitled plan"}`,
|
||||
);
|
||||
} catch {
|
||||
grid.textContent = "";
|
||||
}
|
||||
}
|
||||
|
||||
async function loadResetLinks() {
|
||||
try {
|
||||
const { links } = await api("/api/admin/password-resets");
|
||||
const card = document.getElementById("reset-links-card");
|
||||
if (!links.length) {
|
||||
card.hidden = true;
|
||||
return;
|
||||
}
|
||||
card.hidden = false;
|
||||
document.getElementById("resets-body").replaceChildren(
|
||||
...links.map((link) => {
|
||||
const tr = document.createElement("tr");
|
||||
const email = document.createElement("td");
|
||||
email.textContent = link.email;
|
||||
const url = document.createElement("td");
|
||||
// Not a clickable <a>: an admin's own session immediately 302s /reset to /app,
|
||||
// so the link is only useful copied out and handed to the actual user.
|
||||
const copyBtn = document.createElement("button");
|
||||
copyBtn.className = "ghost-btn small";
|
||||
copyBtn.type = "button";
|
||||
copyBtn.textContent = "Copy link";
|
||||
copyBtn.addEventListener("click", async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(link.url);
|
||||
copyBtn.textContent = "Copied!";
|
||||
} catch {
|
||||
copyBtn.textContent = link.url;
|
||||
}
|
||||
setTimeout(() => (copyBtn.textContent = "Copy link"), 2000);
|
||||
});
|
||||
url.append(copyBtn);
|
||||
const expires = document.createElement("td");
|
||||
expires.textContent = fmtDate(link.expiresAt);
|
||||
tr.append(email, url, expires);
|
||||
return tr;
|
||||
}),
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
/* optional feature; ignore failures */
|
||||
}
|
||||
}
|
||||
|
||||
function wireSignupToggle() {
|
||||
const toggle = document.getElementById("signup-toggle");
|
||||
toggle.addEventListener("change", async () => {
|
||||
try {
|
||||
await api("/api/admin/signup-enabled", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ enabled: toggle.checked }),
|
||||
});
|
||||
showToast(toggle.checked ? "Signups enabled." : "Signups disabled.");
|
||||
} catch (error) {
|
||||
toggle.checked = !toggle.checked;
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function roleBadge(user) {
|
||||
return user.role === "admin"
|
||||
? `<span class="badge badge-admin">Admin</span>`
|
||||
: `<span class="badge badge-user">User</span>`;
|
||||
}
|
||||
function statusBadge(user) {
|
||||
return user.disabled_at
|
||||
? `<span class="badge badge-disabled">Disabled</span>`
|
||||
: `<span class="badge badge-current">Active</span>`;
|
||||
}
|
||||
|
||||
async function loadUsers() {
|
||||
const body = document.getElementById("users-body");
|
||||
try {
|
||||
const { users, signupEnabled } = await api("/api/admin/users");
|
||||
currentUsers = users;
|
||||
document.getElementById("signup-toggle").checked = signupEnabled;
|
||||
renderUsers();
|
||||
} catch {
|
||||
body.innerHTML = `<tr><td colspan="6" class="empty-state">Could not load users.</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderUsers() {
|
||||
const body = document.getElementById("users-body");
|
||||
const query = document
|
||||
.getElementById("user-search")
|
||||
.value.trim()
|
||||
.toLowerCase();
|
||||
const filtered = query
|
||||
? currentUsers.filter((u) => u.email.toLowerCase().includes(query))
|
||||
: currentUsers;
|
||||
if (!filtered.length) {
|
||||
body.innerHTML = `<tr><td colspan="6" class="empty-state">No matching users.</td></tr>`;
|
||||
return;
|
||||
}
|
||||
body.replaceChildren(
|
||||
...filtered.map((user) => {
|
||||
const tr = document.createElement("tr");
|
||||
const email = document.createElement("td");
|
||||
email.textContent = user.email;
|
||||
const role = document.createElement("td");
|
||||
role.innerHTML = roleBadge(user);
|
||||
const status = document.createElement("td");
|
||||
status.innerHTML = statusBadge(user);
|
||||
const count = document.createElement("td");
|
||||
count.className = "num";
|
||||
count.textContent = user.plan_count;
|
||||
const joined = document.createElement("td");
|
||||
joined.textContent = fmtDate(user.created_at);
|
||||
const actions = document.createElement("td");
|
||||
actions.className = "data-table-actions";
|
||||
|
||||
const isBootstrapAdmin = user.email === "[email protected]";
|
||||
const isSelf = user.id === currentUserId;
|
||||
const viewPlans = document.createElement("button");
|
||||
viewPlans.className = "ghost-btn small";
|
||||
viewPlans.type = "button";
|
||||
viewPlans.textContent = "View plans";
|
||||
viewPlans.addEventListener("click", () => filterPlansByUser(user));
|
||||
actions.append(viewPlans);
|
||||
|
||||
// The server refuses role/disable/delete on the bootstrap admin and on your own
|
||||
// account (so an admin can never lock themselves out) — don't offer buttons the
|
||||
// server will always reject.
|
||||
if (!isBootstrapAdmin && !isSelf) {
|
||||
const roleBtn = document.createElement("button");
|
||||
roleBtn.className = "ghost-btn small";
|
||||
roleBtn.type = "button";
|
||||
const promoting = user.role !== "admin";
|
||||
roleBtn.textContent = promoting ? "Promote" : "Demote";
|
||||
roleBtn.addEventListener("click", async () => {
|
||||
if (
|
||||
promoting &&
|
||||
!confirm(
|
||||
`Grant ${user.email} full admin access, including user management and password-reset links?`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
try {
|
||||
await api(`/api/admin/users/${user.id}/role`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({
|
||||
role: promoting ? "admin" : "user",
|
||||
}),
|
||||
});
|
||||
showToast("Role updated.");
|
||||
loadUsers();
|
||||
} catch (error) {
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
});
|
||||
const disableBtn = document.createElement("button");
|
||||
disableBtn.className = "ghost-btn small";
|
||||
disableBtn.type = "button";
|
||||
const disabling = !user.disabled_at;
|
||||
disableBtn.textContent = disabling ? "Disable" : "Enable";
|
||||
disableBtn.addEventListener("click", async () => {
|
||||
if (
|
||||
disabling &&
|
||||
!confirm(`Disable ${user.email}? This signs them out everywhere immediately.`)
|
||||
)
|
||||
return;
|
||||
try {
|
||||
await api(`/api/admin/users/${user.id}/disabled`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ disabled: disabling }),
|
||||
});
|
||||
showToast(disabling ? "User disabled." : "User enabled.");
|
||||
loadUsers();
|
||||
} catch (error) {
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
});
|
||||
const deleteBtn = document.createElement("button");
|
||||
deleteBtn.className = "ghost-btn small";
|
||||
deleteBtn.type = "button";
|
||||
deleteBtn.textContent = "Delete";
|
||||
deleteBtn.addEventListener("click", async () => {
|
||||
if (
|
||||
!confirm(
|
||||
`Permanently delete ${user.email} and all of their plans?`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
try {
|
||||
await api(`/api/admin/users/${user.id}`, { method: "DELETE" });
|
||||
showToast("User deleted.");
|
||||
loadUsers();
|
||||
loadMetrics();
|
||||
} catch (error) {
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
});
|
||||
actions.append(roleBtn, disableBtn, deleteBtn);
|
||||
}
|
||||
|
||||
tr.append(email, role, status, count, joined, actions);
|
||||
return tr;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
document.querySelector("#save").addEventListener("click", async () => {
|
||||
await fetch("/api/admin/signup-enabled", {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
"x-csrf-token": csrf(),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
enabled: document.querySelector("#signup").checked,
|
||||
}),
|
||||
});
|
||||
await load();
|
||||
async function loadPlans() {
|
||||
const body = document.getElementById("plans-body");
|
||||
try {
|
||||
const url = planFilterUserId
|
||||
? `/api/admin/plans?user=${encodeURIComponent(planFilterUserId)}`
|
||||
: "/api/admin/plans";
|
||||
const { plans } = await api(url);
|
||||
if (!plans.length) {
|
||||
body.innerHTML = `<tr><td colspan="3" class="empty-state">No plans.</td></tr>`;
|
||||
return;
|
||||
}
|
||||
body.replaceChildren(
|
||||
...plans.map((plan) => {
|
||||
const tr = document.createElement("tr");
|
||||
const owner = document.createElement("td");
|
||||
owner.textContent = plan.email;
|
||||
const title = document.createElement("td");
|
||||
title.textContent = plan.title || "Untitled plan";
|
||||
const updated = document.createElement("td");
|
||||
updated.textContent = fmtDate(plan.updated_at);
|
||||
tr.append(owner, title, updated);
|
||||
return tr;
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
body.innerHTML = `<tr><td colspan="3" class="empty-state">Could not load plans.</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function filterPlansByUser(user) {
|
||||
planFilterUserId = user.id;
|
||||
document.getElementById("clear-plan-filter").classList.remove("hidden");
|
||||
document.getElementById("plans").scrollIntoView({ behavior: "smooth" });
|
||||
loadPlans();
|
||||
}
|
||||
|
||||
async function loadAudit() {
|
||||
const body = document.getElementById("audit-body");
|
||||
try {
|
||||
const { events } = await api("/api/admin/audit");
|
||||
if (!events.length) {
|
||||
body.innerHTML = `<tr><td colspan="4" class="empty-state">No activity yet.</td></tr>`;
|
||||
return;
|
||||
}
|
||||
body.replaceChildren(
|
||||
...events.map((event) => {
|
||||
const tr = document.createElement("tr");
|
||||
const when = document.createElement("td");
|
||||
when.textContent = fmtDate(event.created_at);
|
||||
const actor = document.createElement("td");
|
||||
actor.textContent = event.actor_email || "—";
|
||||
const action = document.createElement("td");
|
||||
action.textContent = event.action.replaceAll("_", " ");
|
||||
const target = document.createElement("td");
|
||||
target.textContent = event.target || "—";
|
||||
tr.append(when, actor, action, target);
|
||||
return tr;
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
body.innerHTML = `<tr><td colspan="4" class="empty-state">Could not load activity.</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById("btn-logout").addEventListener("click", async () => {
|
||||
await protectedFetch("/api/auth/logout", { method: "POST" });
|
||||
location.assign("/");
|
||||
});
|
||||
document.getElementById("user-search").addEventListener("input", renderUsers);
|
||||
document.getElementById("clear-plan-filter").addEventListener("click", () => {
|
||||
planFilterUserId = null;
|
||||
document.getElementById("clear-plan-filter").classList.add("hidden");
|
||||
loadPlans();
|
||||
});
|
||||
|
||||
load();
|
||||
async function init() {
|
||||
initSideNav();
|
||||
const user = await loadNavUser();
|
||||
if (!user) return;
|
||||
currentUserId = user.id;
|
||||
wireSignupToggle();
|
||||
await Promise.all([
|
||||
loadMetrics(),
|
||||
loadResetLinks(),
|
||||
loadUsers(),
|
||||
loadPlans(),
|
||||
loadAudit(),
|
||||
]);
|
||||
}
|
||||
|
||||
init();
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
export const csrfToken = () =>
|
||||
document.cookie
|
||||
.split("; ")
|
||||
.find((v) => v.startsWith("rp_csrf="))
|
||||
?.split("=")[1] || "";
|
||||
|
||||
export const protectedFetch = (url, options = {}) =>
|
||||
fetch(url, {
|
||||
...options,
|
||||
headers: { ...options.headers, "x-csrf-token": csrfToken() },
|
||||
});
|
||||
|
||||
export async function api(url, options = {}) {
|
||||
const response = await protectedFetch(url, {
|
||||
...options,
|
||||
headers: { "content-type": "application/json", ...options.headers },
|
||||
});
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (response.status === 401 && body.code === "unauthorized") {
|
||||
// This is specifically requireAuth's code for "no valid session" — the session expired
|
||||
// or was revoked mid-page (account/admin pages otherwise show a permanent "could not
|
||||
// load" error with no indication the user was signed out). A 401 with any other code
|
||||
// (e.g. a wrong current password on an account form) is a normal request failure, not a
|
||||
// sign-out, and must not redirect the user away mid-form.
|
||||
location.assign("/login");
|
||||
return new Promise(() => {}); // navigation is already underway; never resolve
|
||||
}
|
||||
if (!response.ok) {
|
||||
const error = new Error(body.error || body.code || "request_failed");
|
||||
error.code = body.code;
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
@@ -0,0 +1,586 @@
|
||||
import { api, protectedFetch } from "./api.js";
|
||||
import { initSideNav, loadNavUser } from "./nav.js";
|
||||
import { showToast } from "./toast.js";
|
||||
import { wireWhyPanels } from "./why-panels.js";
|
||||
import {
|
||||
SCORE_ATTRS,
|
||||
SCORE_LABELS,
|
||||
TICK_ATTRS,
|
||||
TICK_LABELS,
|
||||
FLAVOR_TAXONOMY,
|
||||
MAX_FLAVOR_TAGS,
|
||||
MAX_CUP_COUNT,
|
||||
computeTotalScore,
|
||||
} from "/shared/cupping.js";
|
||||
|
||||
const sessionId = new URLSearchParams(location.search).get("session");
|
||||
|
||||
function fmtDate(value) {
|
||||
return value ? new Date(value).toLocaleString() : "—";
|
||||
}
|
||||
|
||||
/** Disables `el` for the duration of `run()` so a slow request can't be double-submitted. */
|
||||
async function guarded(el, run) {
|
||||
if (!el || el.disabled) return;
|
||||
el.disabled = true;
|
||||
try {
|
||||
await run();
|
||||
} finally {
|
||||
el.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── List view ───────────────────────────────────────────────────────────
|
||||
|
||||
async function loadSessions() {
|
||||
const body = document.getElementById("sessions-body");
|
||||
try {
|
||||
const { sessions } = await api("/api/cupping");
|
||||
if (!sessions.length) {
|
||||
body.innerHTML = `<tr><td colspan="6" class="empty-state">No cupping sessions yet.</td></tr>`;
|
||||
return;
|
||||
}
|
||||
body.replaceChildren(
|
||||
...sessions.map((s) => {
|
||||
const tr = document.createElement("tr");
|
||||
const coffee = document.createElement("td");
|
||||
coffee.textContent = s.planTitle || "Untitled";
|
||||
const score = document.createElement("td");
|
||||
score.className = "num";
|
||||
const badge = document.createElement("span");
|
||||
badge.className = "badge badge-current";
|
||||
badge.textContent = s.totalScore.toFixed(2);
|
||||
score.append(badge);
|
||||
const cups = document.createElement("td");
|
||||
cups.className = "num";
|
||||
cups.textContent = s.cupCount;
|
||||
const flavors = document.createElement("td");
|
||||
const shown = s.flavorTags.slice(0, 3).map((t) => t.split(".").pop());
|
||||
flavors.textContent =
|
||||
shown.join(", ") + (s.flavorTags.length > 3 ? ` +${s.flavorTags.length - 3}` : "");
|
||||
const updated = document.createElement("td");
|
||||
updated.textContent = fmtDate(s.updatedAt);
|
||||
const actions = document.createElement("td");
|
||||
actions.className = "data-table-actions";
|
||||
const open = document.createElement("a");
|
||||
open.className = "ghost-btn small";
|
||||
open.href = `/cupping?session=${s.id}`;
|
||||
open.textContent = "Open";
|
||||
const del = document.createElement("button");
|
||||
del.className = "ghost-btn small";
|
||||
del.type = "button";
|
||||
del.textContent = "Delete";
|
||||
del.addEventListener("click", (event) => {
|
||||
if (!confirm("Delete this cupping session?")) return;
|
||||
guarded(event.currentTarget, async () => {
|
||||
try {
|
||||
await api(`/api/cupping/${s.id}`, { method: "DELETE" });
|
||||
showToast("Session deleted.");
|
||||
loadSessions();
|
||||
} catch (error) {
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
});
|
||||
});
|
||||
actions.append(open, del);
|
||||
tr.append(coffee, score, cups, flavors, updated, actions);
|
||||
return tr;
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
body.innerHTML = `<tr><td colspan="6" class="empty-state">Could not load sessions.</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPlanOptions() {
|
||||
const select = document.getElementById("new-session-plan");
|
||||
try {
|
||||
const { plans } = await api("/api/plans");
|
||||
select.append(
|
||||
...plans.map((p) => {
|
||||
const option = document.createElement("option");
|
||||
option.value = p.id;
|
||||
option.textContent = p.plan?.fields?.["0.1"] || "Untitled plan";
|
||||
return option;
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
/* the plan-less option still works */
|
||||
}
|
||||
}
|
||||
|
||||
function wireNewSessionForm() {
|
||||
const form = document.getElementById("new-session-form");
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const roastPlanId = document.getElementById("new-session-plan").value || undefined;
|
||||
const cupCount = Number(document.getElementById("new-session-cups").value) || 5;
|
||||
guarded(form.querySelector("button[type=submit]"), async () => {
|
||||
try {
|
||||
const { session } = await api("/api/cupping", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ roastPlanId, cupCount }),
|
||||
});
|
||||
location.assign(`/cupping?session=${session.id}`);
|
||||
} catch (error) {
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Session view ────────────────────────────────────────────────────────
|
||||
|
||||
let data = null; // the coerced session document (snake_case, matches shared/cupping.js)
|
||||
let saveTimer = null;
|
||||
|
||||
function setAutosaveStatus(status) {
|
||||
const chip = document.getElementById("cupping-autosave-status");
|
||||
const text = chip.querySelector(".autosave-text");
|
||||
chip.classList.remove("saving", "saved", "failed");
|
||||
chip.classList.add(status);
|
||||
text.textContent =
|
||||
{ saving: "Saving…", saved: "Synced", failed: "Sync failed" }[status] || "Not saved yet";
|
||||
}
|
||||
|
||||
function scheduleSave() {
|
||||
setAutosaveStatus("saving");
|
||||
clearTimeout(saveTimer);
|
||||
saveTimer = setTimeout(save, 500);
|
||||
}
|
||||
|
||||
async function save() {
|
||||
try {
|
||||
const body = await api(`/api/cupping/${sessionId}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ data }),
|
||||
});
|
||||
document.getElementById("cup-total").textContent = body.session.totalScore.toFixed(2);
|
||||
setAutosaveStatus("saved");
|
||||
} catch (error) {
|
||||
setAutosaveStatus("failed");
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
}
|
||||
|
||||
function liveTotal() {
|
||||
return computeTotalScore(
|
||||
data.scores,
|
||||
data.ticks,
|
||||
data.taint_cups,
|
||||
data.fault_cups,
|
||||
data.cup_count,
|
||||
);
|
||||
}
|
||||
|
||||
function renderTotal() {
|
||||
document.getElementById("cup-total").textContent = liveTotal().toFixed(2);
|
||||
}
|
||||
|
||||
// ── Score sliders ──
|
||||
function renderScoreRows() {
|
||||
const wrap = document.getElementById("cup-score-rows");
|
||||
wrap.replaceChildren(
|
||||
...SCORE_ATTRS.map((attr) => {
|
||||
const row = document.createElement("div");
|
||||
row.className = "cup-score-row";
|
||||
row.dataset.attr = attr;
|
||||
const unscored = !(data.scores[attr] > 0);
|
||||
row.classList.toggle("unscored", unscored);
|
||||
|
||||
const label = document.createElement("span");
|
||||
label.className = "cup-score-label";
|
||||
label.textContent = SCORE_LABELS[attr];
|
||||
|
||||
const slider = document.createElement("input");
|
||||
slider.type = "range";
|
||||
slider.min = "6";
|
||||
slider.max = "10";
|
||||
slider.step = "0.25";
|
||||
slider.value = unscored ? "6" : data.scores[attr];
|
||||
slider.setAttribute("aria-label", `${SCORE_LABELS[attr]} score`);
|
||||
|
||||
const output = document.createElement("output");
|
||||
output.className = "cup-score-value";
|
||||
output.textContent = unscored ? "—" : data.scores[attr].toFixed(2);
|
||||
|
||||
const clearBtn = document.createElement("button");
|
||||
clearBtn.type = "button";
|
||||
clearBtn.className = "ghost-btn small cup-score-clear";
|
||||
clearBtn.hidden = unscored;
|
||||
clearBtn.textContent = "✕";
|
||||
clearBtn.setAttribute("aria-label", `Clear ${SCORE_LABELS[attr]} score`);
|
||||
|
||||
slider.addEventListener("input", () => {
|
||||
data.scores[attr] = Number(slider.value);
|
||||
row.classList.remove("unscored");
|
||||
output.textContent = data.scores[attr].toFixed(2);
|
||||
clearBtn.hidden = false;
|
||||
renderTotal();
|
||||
renderRadar();
|
||||
scheduleSave();
|
||||
});
|
||||
clearBtn.addEventListener("click", () => {
|
||||
data.scores[attr] = 0;
|
||||
row.classList.add("unscored");
|
||||
slider.value = "6";
|
||||
output.textContent = "—";
|
||||
clearBtn.hidden = true;
|
||||
renderTotal();
|
||||
renderRadar();
|
||||
scheduleSave();
|
||||
});
|
||||
|
||||
row.append(label, slider, output, clearBtn);
|
||||
return row;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Tick attributes (fill-up-to cup cells) ──
|
||||
function renderTickRows() {
|
||||
const wrap = document.getElementById("cup-tick-rows");
|
||||
wrap.replaceChildren(
|
||||
...TICK_ATTRS.map((attr) => {
|
||||
const row = document.createElement("div");
|
||||
row.className = "cup-tick-row";
|
||||
row.dataset.tick = attr;
|
||||
|
||||
const label = document.createElement("span");
|
||||
label.className = "cup-score-label";
|
||||
label.textContent = TICK_LABELS[attr];
|
||||
|
||||
const cells = document.createElement("div");
|
||||
cells.className = "cup-tick-cells";
|
||||
cells.setAttribute("role", "group");
|
||||
cells.setAttribute("aria-label", `${TICK_LABELS[attr]} — cups passed`);
|
||||
|
||||
const output = document.createElement("output");
|
||||
|
||||
function renderCells() {
|
||||
const count = data.ticks[attr] || 0;
|
||||
cells.replaceChildren(
|
||||
...Array.from({ length: data.cup_count }, (_, i) => {
|
||||
const btn = document.createElement("button");
|
||||
btn.type = "button";
|
||||
btn.className = "cup-tick";
|
||||
btn.setAttribute("aria-label", `Cup ${i + 1}`);
|
||||
const pressed = i < count;
|
||||
btn.setAttribute("aria-pressed", String(pressed));
|
||||
btn.addEventListener("click", () => {
|
||||
data.ticks[attr] = i >= (data.ticks[attr] || 0) ? i + 1 : i;
|
||||
renderCells();
|
||||
renderTotal();
|
||||
scheduleSave();
|
||||
});
|
||||
return btn;
|
||||
}),
|
||||
);
|
||||
output.textContent = `${count}/${data.cup_count}`;
|
||||
}
|
||||
renderCells();
|
||||
row._renderCells = renderCells;
|
||||
|
||||
row.append(label, cells, output);
|
||||
return row;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Defects (taint/fault steppers) ──
|
||||
function renderDefectRows() {
|
||||
const wrap = document.getElementById("cup-defect-rows");
|
||||
const specs = [
|
||||
{ key: "taint_cups", label: "Taint cups", note: "−2 pts each" },
|
||||
{ key: "fault_cups", label: "Fault cups", note: "−4 pts each" },
|
||||
];
|
||||
wrap.replaceChildren(
|
||||
...specs.map(({ key, label, note }) => {
|
||||
const row = document.createElement("div");
|
||||
row.className = "cup-stepper-row";
|
||||
const labelEl = document.createElement("span");
|
||||
labelEl.className = "cup-score-label";
|
||||
labelEl.textContent = `${label} (${note})`;
|
||||
const minus = document.createElement("button");
|
||||
minus.type = "button";
|
||||
minus.className = "ghost-btn small";
|
||||
minus.textContent = "−";
|
||||
minus.setAttribute("aria-label", `Decrease ${label}`);
|
||||
const count = document.createElement("output");
|
||||
const plus = document.createElement("button");
|
||||
plus.type = "button";
|
||||
plus.className = "ghost-btn small";
|
||||
plus.textContent = "+";
|
||||
plus.setAttribute("aria-label", `Increase ${label}`);
|
||||
|
||||
function update() {
|
||||
count.textContent = data[key];
|
||||
}
|
||||
minus.addEventListener("click", () => {
|
||||
data[key] = Math.max(0, data[key] - 1);
|
||||
update();
|
||||
renderTotal();
|
||||
scheduleSave();
|
||||
});
|
||||
plus.addEventListener("click", () => {
|
||||
data[key] = Math.min(data.cup_count, data[key] + 1);
|
||||
update();
|
||||
renderTotal();
|
||||
scheduleSave();
|
||||
});
|
||||
update();
|
||||
row.append(labelEl, minus, count, plus);
|
||||
return row;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function reclampForCupCount() {
|
||||
for (const attr of TICK_ATTRS) data.ticks[attr] = Math.min(data.ticks[attr] || 0, data.cup_count);
|
||||
data.taint_cups = Math.min(data.taint_cups, data.cup_count);
|
||||
data.fault_cups = Math.min(data.fault_cups, data.cup_count);
|
||||
}
|
||||
|
||||
function wireCupCount() {
|
||||
const input = document.getElementById("cup-count");
|
||||
input.min = "1";
|
||||
input.max = String(MAX_CUP_COUNT);
|
||||
input.value = data.cup_count;
|
||||
input.addEventListener("change", () => {
|
||||
const next = Math.max(1, Math.min(MAX_CUP_COUNT, Number(input.value) || 1));
|
||||
data.cup_count = next;
|
||||
input.value = next;
|
||||
reclampForCupCount();
|
||||
renderTickRows();
|
||||
renderDefectRows();
|
||||
renderTotal();
|
||||
scheduleSave();
|
||||
});
|
||||
}
|
||||
|
||||
// ── Flavor checklist ──
|
||||
function renderFlavorChips() {
|
||||
const chips = document.getElementById("flavor-chips");
|
||||
chips.replaceChildren(
|
||||
...data.flavor_tags.map((tag) => {
|
||||
// A dedicated class, not .chip-opt (a checkbox-option style whose CSS uses a
|
||||
// descendant `span` selector — reusing it here with a nested span for the remove
|
||||
// button doubled-up borders/padding onto that inner span too).
|
||||
const chip = document.createElement("span");
|
||||
chip.className = "flavor-chip";
|
||||
const text = document.createElement("span");
|
||||
text.textContent = tag.split(".").pop().replaceAll("_", " ");
|
||||
const remove = document.createElement("button");
|
||||
remove.type = "button";
|
||||
remove.className = "flavor-chip-remove";
|
||||
remove.setAttribute("aria-label", `Remove ${text.textContent}`);
|
||||
remove.textContent = "✕";
|
||||
remove.addEventListener("click", () => toggleFlavorTag(tag, false));
|
||||
chip.append(text, remove);
|
||||
return chip;
|
||||
}),
|
||||
);
|
||||
document
|
||||
.getElementById("flavor-limit-note")
|
||||
.classList.toggle("hidden", data.flavor_tags.length < MAX_FLAVOR_TAGS);
|
||||
}
|
||||
|
||||
function toggleFlavorTag(tag, checked) {
|
||||
if (checked) {
|
||||
if (data.flavor_tags.length >= MAX_FLAVOR_TAGS || data.flavor_tags.includes(tag)) return;
|
||||
data.flavor_tags.push(tag);
|
||||
} else {
|
||||
data.flavor_tags = data.flavor_tags.filter((t) => t !== tag);
|
||||
}
|
||||
renderFlavorFamilies();
|
||||
renderFlavorChips();
|
||||
scheduleSave();
|
||||
}
|
||||
|
||||
function renderFlavorFamilies() {
|
||||
const wrap = document.getElementById("flavor-families");
|
||||
const atLimit = data.flavor_tags.length >= MAX_FLAVOR_TAGS;
|
||||
wrap.replaceChildren(
|
||||
...Object.entries(FLAVOR_TAXONOMY).map(([familyId, family]) => {
|
||||
const selectedCount = data.flavor_tags.filter((t) => t.startsWith(`${familyId}.`)).length;
|
||||
const details = document.createElement("details");
|
||||
details.className = "flavor-family";
|
||||
const summary = document.createElement("summary");
|
||||
summary.textContent = family.label + (selectedCount ? ` (${selectedCount})` : "");
|
||||
details.append(summary);
|
||||
for (const [subId, descriptors] of Object.entries(family.subgroups)) {
|
||||
const subhead = document.createElement("p");
|
||||
subhead.className = "subhead";
|
||||
subhead.textContent = subId.replaceAll("_", " ");
|
||||
const group = document.createElement("div");
|
||||
group.className = "chip-group";
|
||||
for (const descriptor of descriptors) {
|
||||
const tag = `${familyId}.${subId}.${descriptor}`;
|
||||
const label = document.createElement("label");
|
||||
label.className = "chip-opt";
|
||||
const input = document.createElement("input");
|
||||
input.type = "checkbox";
|
||||
input.checked = data.flavor_tags.includes(tag);
|
||||
input.disabled = atLimit && !input.checked;
|
||||
input.addEventListener("change", () => toggleFlavorTag(tag, input.checked));
|
||||
const span = document.createElement("span");
|
||||
span.textContent = descriptor.replaceAll("_", " ");
|
||||
label.append(input, span);
|
||||
group.append(label);
|
||||
}
|
||||
details.append(subhead, group);
|
||||
}
|
||||
return details;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Radar chart (pure SVG, no dependency) ──
|
||||
const RADAR_CENTER = 120;
|
||||
const RADAR_RADIUS = 90;
|
||||
|
||||
function radarPoints() {
|
||||
const n = SCORE_ATTRS.length;
|
||||
return SCORE_ATTRS.map((attr, i) => {
|
||||
const raw = data.scores[attr] || 0;
|
||||
const frac = raw > 0 ? Math.max(0, Math.min(1, (raw - 6) / 4)) : 0;
|
||||
const angle = -Math.PI / 2 + (2 * Math.PI * i) / n;
|
||||
return {
|
||||
x: RADAR_CENTER + frac * RADAR_RADIUS * Math.cos(angle),
|
||||
y: RADAR_CENTER + frac * RADAR_RADIUS * Math.sin(angle),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function svgEl(tag, attrs) {
|
||||
const el = document.createElementNS("http://www.w3.org/2000/svg", tag);
|
||||
for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v);
|
||||
return el;
|
||||
}
|
||||
|
||||
function initRadarStatic() {
|
||||
const svg = document.getElementById("cup-radar");
|
||||
svg.replaceChildren();
|
||||
// Rings at scores 7/8/9/10 (6 is the center — an unscored/floor axis point).
|
||||
for (const score of [7, 8, 9, 10]) {
|
||||
const r = ((score - 6) / 4) * RADAR_RADIUS;
|
||||
svg.append(
|
||||
svgEl("circle", {
|
||||
cx: RADAR_CENTER,
|
||||
cy: RADAR_CENTER,
|
||||
r,
|
||||
fill: "none",
|
||||
stroke: "var(--line)",
|
||||
"stroke-width": "1",
|
||||
}),
|
||||
);
|
||||
}
|
||||
const n = SCORE_ATTRS.length;
|
||||
SCORE_ATTRS.forEach((attr, i) => {
|
||||
const angle = -Math.PI / 2 + (2 * Math.PI * i) / n;
|
||||
const x2 = RADAR_CENTER + RADAR_RADIUS * Math.cos(angle);
|
||||
const y2 = RADAR_CENTER + RADAR_RADIUS * Math.sin(angle);
|
||||
svg.append(
|
||||
svgEl("line", {
|
||||
x1: RADAR_CENTER,
|
||||
y1: RADAR_CENTER,
|
||||
x2,
|
||||
y2,
|
||||
stroke: "var(--line)",
|
||||
"stroke-width": "1",
|
||||
}),
|
||||
);
|
||||
const lx = RADAR_CENTER + (RADAR_RADIUS + 14) * Math.cos(angle);
|
||||
const ly = RADAR_CENTER + (RADAR_RADIUS + 14) * Math.sin(angle);
|
||||
const label = svgEl("text", {
|
||||
x: lx,
|
||||
y: ly,
|
||||
"text-anchor": "middle",
|
||||
"dominant-baseline": "middle",
|
||||
"font-size": "9",
|
||||
fill: "var(--ink-2)",
|
||||
});
|
||||
label.textContent = SCORE_LABELS[attr].split("/")[0];
|
||||
svg.append(label);
|
||||
});
|
||||
const shape = svgEl("polygon", {
|
||||
id: "radar-shape",
|
||||
fill: "var(--ember)",
|
||||
"fill-opacity": "0.25",
|
||||
stroke: "var(--ember)",
|
||||
"stroke-width": "1.5",
|
||||
});
|
||||
svg.append(shape);
|
||||
}
|
||||
|
||||
function renderRadar() {
|
||||
const shape = document.getElementById("radar-shape");
|
||||
if (!shape) return;
|
||||
shape.setAttribute("points", radarPoints().map((p) => `${p.x},${p.y}`).join(" "));
|
||||
}
|
||||
|
||||
function wireNotes() {
|
||||
const textarea = document.getElementById("cup-notes-text");
|
||||
textarea.value = data.notes;
|
||||
document.getElementById("cup-notes-count").textContent = data.notes.length;
|
||||
textarea.addEventListener("input", () => {
|
||||
data.notes = textarea.value;
|
||||
document.getElementById("cup-notes-count").textContent = data.notes.length;
|
||||
scheduleSave();
|
||||
});
|
||||
}
|
||||
|
||||
async function initSessionView(user) {
|
||||
document.getElementById("cupping-list-view").classList.add("hidden");
|
||||
document.getElementById("cupping-session-view").classList.remove("hidden");
|
||||
document.getElementById("session-autosave-wrap").classList.remove("hidden");
|
||||
setAutosaveStatus("saved");
|
||||
|
||||
let body;
|
||||
try {
|
||||
body = await api(`/api/cupping/${sessionId}`);
|
||||
} catch (error) {
|
||||
showToast(error.message || "Could not load this session.", "fail");
|
||||
location.assign("/cupping");
|
||||
return;
|
||||
}
|
||||
data = body.session.data;
|
||||
document.getElementById("cupping-title").textContent =
|
||||
body.session.planTitle || "Cupping session";
|
||||
document.getElementById("cupping-subtitle").textContent = `${data.cup_count} cups`;
|
||||
|
||||
wireCupCount();
|
||||
renderScoreRows();
|
||||
renderTickRows();
|
||||
renderDefectRows();
|
||||
renderFlavorFamilies();
|
||||
renderFlavorChips();
|
||||
wireNotes();
|
||||
initRadarStatic();
|
||||
renderRadar();
|
||||
renderTotal();
|
||||
wireWhyPanels();
|
||||
void user;
|
||||
}
|
||||
|
||||
async function initListView() {
|
||||
document.getElementById("cupping-list-view").classList.remove("hidden");
|
||||
document.getElementById("cupping-session-view").classList.add("hidden");
|
||||
wireNewSessionForm();
|
||||
await Promise.all([loadSessions(), loadPlanOptions()]);
|
||||
}
|
||||
|
||||
document.getElementById("btn-logout").addEventListener("click", async () => {
|
||||
await protectedFetch("/api/auth/logout", { method: "POST" });
|
||||
location.assign("/");
|
||||
});
|
||||
|
||||
async function init() {
|
||||
initSideNav();
|
||||
const user = await loadNavUser();
|
||||
if (!user) return;
|
||||
if (sessionId) await initSessionView(user);
|
||||
else await initListView();
|
||||
}
|
||||
|
||||
init();
|
||||
@@ -0,0 +1,30 @@
|
||||
const form = document.querySelector("#forgot-form");
|
||||
const message = document.querySelector("#message");
|
||||
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const submitButton = form.querySelector("button[type=submit]");
|
||||
submitButton.disabled = true;
|
||||
try {
|
||||
const response = await fetch("/api/auth/forgot", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(Object.fromEntries(new FormData(form))),
|
||||
});
|
||||
if (response.status === 429) {
|
||||
message.textContent = "Too many requests. Try again in a few minutes.";
|
||||
message.className = "auth-message error";
|
||||
return;
|
||||
}
|
||||
// Always show the same message, whether or not the account exists.
|
||||
message.textContent =
|
||||
"If that email has an account, a reset link is on its way.";
|
||||
message.className = "auth-message info";
|
||||
form.reset();
|
||||
} catch {
|
||||
message.textContent = "Could not reach the server. Try again shortly.";
|
||||
message.className = "auth-message error";
|
||||
} finally {
|
||||
submitButton.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,265 @@
|
||||
import { api, protectedFetch } from "./api.js";
|
||||
import { initSideNav, loadNavUser } from "./nav.js";
|
||||
import { showToast } from "./toast.js";
|
||||
|
||||
let lots = [];
|
||||
let showArchived = false;
|
||||
let editingId = null;
|
||||
|
||||
function fmtDate(value) {
|
||||
return value ? new Date(value).toLocaleDateString() : "—";
|
||||
}
|
||||
|
||||
/** Disables `button` for the duration of `run()` so a slow request can't be double-submitted. */
|
||||
async function guarded(button, run) {
|
||||
if (!button || button.disabled) return;
|
||||
button.disabled = true;
|
||||
try {
|
||||
await run();
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function renderLots() {
|
||||
const body = document.getElementById("lots-body");
|
||||
const visible = showArchived ? lots : lots.filter((l) => !l.archived);
|
||||
if (!visible.length) {
|
||||
body.innerHTML = `<tr><td colspan="5" class="empty-state">No lots yet.</td></tr>`;
|
||||
return;
|
||||
}
|
||||
body.replaceChildren(
|
||||
...visible.map((lot) => {
|
||||
const tr = document.createElement("tr");
|
||||
if (lot.archived) tr.className = "archived";
|
||||
|
||||
const lotCell = document.createElement("td");
|
||||
const strong = document.createElement("strong");
|
||||
strong.textContent = lot.origin;
|
||||
const sub = document.createElement("div");
|
||||
sub.className = "muted";
|
||||
sub.style.fontSize = "11.5px";
|
||||
sub.textContent = [lot.variety, lot.producer].filter(Boolean).join(" · ") || "—";
|
||||
lotCell.append(strong, sub);
|
||||
|
||||
const processCell = document.createElement("td");
|
||||
processCell.textContent = lot.process || "—";
|
||||
|
||||
const remainingCell = document.createElement("td");
|
||||
const pct = lot.initialWeightG > 0
|
||||
? Math.max(0, Math.min(100, (lot.remainingWeightG / lot.initialWeightG) * 100))
|
||||
: 0;
|
||||
const wrap = document.createElement("div");
|
||||
wrap.className = "lot-remaining";
|
||||
const bar = document.createElement("div");
|
||||
bar.className = "blend-total-bar";
|
||||
const fill = document.createElement("div");
|
||||
fill.className = "blend-total-fill";
|
||||
if (lot.remainingWeightG < 0) fill.classList.add("over");
|
||||
fill.style.width = `${lot.remainingWeightG < 0 ? 0 : pct}%`;
|
||||
bar.append(fill);
|
||||
const label = document.createElement("span");
|
||||
label.className = "blend-total-label";
|
||||
label.textContent = `${Math.round(lot.remainingWeightG)} g of ${Math.round(lot.initialWeightG)} g`;
|
||||
wrap.append(bar, label);
|
||||
remainingCell.append(wrap);
|
||||
|
||||
const purchasedCell = document.createElement("td");
|
||||
purchasedCell.textContent = fmtDate(lot.purchaseDate);
|
||||
|
||||
const actions = document.createElement("td");
|
||||
actions.className = "data-table-actions";
|
||||
|
||||
const editBtn = document.createElement("button");
|
||||
editBtn.className = "ghost-btn small";
|
||||
editBtn.type = "button";
|
||||
editBtn.textContent = "Edit";
|
||||
editBtn.addEventListener("click", () => startEdit(lot));
|
||||
|
||||
const archiveBtn = document.createElement("button");
|
||||
archiveBtn.className = "ghost-btn small";
|
||||
archiveBtn.type = "button";
|
||||
archiveBtn.textContent = lot.archived ? "Unarchive" : "Archive";
|
||||
archiveBtn.addEventListener("click", (event) =>
|
||||
guarded(event.currentTarget, async () => {
|
||||
try {
|
||||
await api(`/api/inventory/${lot.id}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ archived: !lot.archived }),
|
||||
});
|
||||
showToast(lot.archived ? "Lot unarchived." : "Lot archived.");
|
||||
await loadLots();
|
||||
} catch (error) {
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const logBtn = document.createElement("button");
|
||||
logBtn.className = "ghost-btn small";
|
||||
logBtn.type = "button";
|
||||
logBtn.textContent = "Log";
|
||||
logBtn.addEventListener("click", () => toggleLog(lot, tr, logBtn));
|
||||
|
||||
const deleteBtn = document.createElement("button");
|
||||
deleteBtn.className = "ghost-btn small";
|
||||
deleteBtn.type = "button";
|
||||
deleteBtn.textContent = "Delete";
|
||||
deleteBtn.addEventListener("click", (event) =>
|
||||
guarded(event.currentTarget, async () => {
|
||||
if (!confirm(`Delete the ${lot.origin} lot? This cannot be undone.`))
|
||||
return;
|
||||
try {
|
||||
await api(`/api/inventory/${lot.id}`, { method: "DELETE" });
|
||||
showToast("Lot deleted.");
|
||||
if (editingId === lot.id) cancelEdit();
|
||||
await loadLots();
|
||||
} catch (error) {
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
actions.append(editBtn, archiveBtn, logBtn, deleteBtn);
|
||||
tr.append(lotCell, processCell, remainingCell, purchasedCell, actions);
|
||||
return tr;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function toggleLog(lot, row, button) {
|
||||
const existing = row.nextElementSibling;
|
||||
if (existing?.classList.contains("lot-log-row")) {
|
||||
existing.remove();
|
||||
return;
|
||||
}
|
||||
guarded(button, async () => {
|
||||
try {
|
||||
const { log } = await api(`/api/inventory/${lot.id}`);
|
||||
const tr = document.createElement("tr");
|
||||
tr.className = "lot-log-row";
|
||||
const td = document.createElement("td");
|
||||
td.colSpan = 5;
|
||||
if (!log.length) {
|
||||
td.className = "empty-state";
|
||||
td.textContent = "No consumption recorded yet.";
|
||||
} else {
|
||||
const ul = document.createElement("ul");
|
||||
ul.style.margin = "0";
|
||||
ul.style.paddingLeft = "18px";
|
||||
for (const entry of log) {
|
||||
const li = document.createElement("li");
|
||||
li.style.fontSize = "12.5px";
|
||||
li.textContent = `${Math.round(entry.weightG)} g — ${entry.planTitle || "manual"} — ${fmtDate(entry.createdAt)}`;
|
||||
ul.append(li);
|
||||
}
|
||||
td.append(ul);
|
||||
}
|
||||
tr.append(td);
|
||||
row.after(tr);
|
||||
} catch (error) {
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function loadLots() {
|
||||
try {
|
||||
const body = await api("/api/inventory");
|
||||
lots = body.lots;
|
||||
renderLots();
|
||||
} catch (error) {
|
||||
document.getElementById("lots-body").innerHTML =
|
||||
`<tr><td colspan="5" class="empty-state">Could not load lots.</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function startEdit(lot) {
|
||||
editingId = lot.id;
|
||||
const form = document.getElementById("lot-form");
|
||||
form.id.value = lot.id;
|
||||
form.origin.value = lot.origin;
|
||||
form.variety.value = lot.variety;
|
||||
form.process.value = lot.process;
|
||||
form.producer.value = lot.producer;
|
||||
form.purchaseDate.value = lot.purchaseDate ? lot.purchaseDate.slice(0, 10) : "";
|
||||
form.initialWeightG.value = lot.initialWeightG;
|
||||
form.costTotal.value = lot.costTotal ?? "";
|
||||
form.moisturePct.value = lot.moisturePct ?? "";
|
||||
form.densityGL.value = lot.densityGL ?? "";
|
||||
form.notes.value = lot.notes;
|
||||
document.getElementById("lot-form-title").textContent = "Edit lot";
|
||||
document.getElementById("lot-form-submit").textContent = "Save changes";
|
||||
document.getElementById("lot-form-cancel").classList.remove("hidden");
|
||||
const note = document.getElementById("lot-remaining-note");
|
||||
note.classList.remove("hidden");
|
||||
note.textContent = `Remaining: ${Math.round(lot.remainingWeightG)} g — remaining weight is only changed by roasts drawing from the lot. Correct the initial weight and the remaining shifts with it.`;
|
||||
document.getElementById("lot-form-card").scrollIntoView({ behavior: "smooth" });
|
||||
}
|
||||
|
||||
function cancelEdit() {
|
||||
editingId = null;
|
||||
const form = document.getElementById("lot-form");
|
||||
form.reset();
|
||||
form.id.value = "";
|
||||
document.getElementById("lot-form-title").textContent = "Add a lot";
|
||||
document.getElementById("lot-form-submit").textContent = "Add lot";
|
||||
document.getElementById("lot-form-cancel").classList.add("hidden");
|
||||
document.getElementById("lot-remaining-note").classList.add("hidden");
|
||||
}
|
||||
|
||||
document.getElementById("lot-form-cancel").addEventListener("click", cancelEdit);
|
||||
document.getElementById("show-archived").addEventListener("change", (event) => {
|
||||
showArchived = event.target.checked;
|
||||
renderLots();
|
||||
});
|
||||
document.getElementById("lot-form").addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const form = event.target;
|
||||
const data = Object.fromEntries(new FormData(form));
|
||||
const submitBtn = document.getElementById("lot-form-submit");
|
||||
guarded(submitBtn, async () => {
|
||||
try {
|
||||
const payload = {
|
||||
origin: data.origin,
|
||||
variety: data.variety,
|
||||
process: data.process,
|
||||
producer: data.producer,
|
||||
purchaseDate: data.purchaseDate || null,
|
||||
initialWeightG: Number(data.initialWeightG),
|
||||
costTotal: data.costTotal === "" ? null : Number(data.costTotal),
|
||||
moisturePct: data.moisturePct === "" ? null : Number(data.moisturePct),
|
||||
densityGL: data.densityGL === "" ? null : Number(data.densityGL),
|
||||
notes: data.notes,
|
||||
};
|
||||
if (editingId) {
|
||||
await api(`/api/inventory/${editingId}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
showToast("Lot updated.");
|
||||
} else {
|
||||
await api("/api/inventory", { method: "POST", body: JSON.stringify(payload) });
|
||||
showToast("Lot added.");
|
||||
}
|
||||
cancelEdit();
|
||||
await loadLots();
|
||||
} catch (error) {
|
||||
showToast(error.message, "fail");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById("btn-logout").addEventListener("click", async () => {
|
||||
await protectedFetch("/api/auth/logout", { method: "POST" });
|
||||
location.assign("/");
|
||||
});
|
||||
|
||||
async function init() {
|
||||
initSideNav();
|
||||
const user = await loadNavUser();
|
||||
if (!user) return;
|
||||
await loadLots();
|
||||
}
|
||||
|
||||
init();
|
||||
@@ -1,25 +0,0 @@
|
||||
const form = document.querySelector("#auth-form");
|
||||
const message = document.querySelector("#message");
|
||||
|
||||
async function submit(url) {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(Object.fromEntries(new FormData(form))),
|
||||
});
|
||||
const body = await response.json();
|
||||
if (!response.ok) {
|
||||
message.textContent = body.error || body.code;
|
||||
return;
|
||||
}
|
||||
location.assign("/app");
|
||||
}
|
||||
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
submit("/api/auth/login");
|
||||
});
|
||||
document.querySelector("#signup").addEventListener("click", () => {
|
||||
const setupToken = form.elements.setupToken.value;
|
||||
submit(setupToken ? "/api/auth/bootstrap" : "/api/auth/signup");
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
const form = document.querySelector("#login-form");
|
||||
const message = document.querySelector("#message");
|
||||
const submitButton = form.querySelector("button[type=submit]");
|
||||
|
||||
function showError(text) {
|
||||
message.textContent = text;
|
||||
message.className = "auth-message error";
|
||||
}
|
||||
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
submitButton.disabled = true;
|
||||
message.textContent = "";
|
||||
try {
|
||||
const response = await fetch("/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(Object.fromEntries(new FormData(form))),
|
||||
});
|
||||
const body = await response.json();
|
||||
if (!response.ok) {
|
||||
showError(
|
||||
body.code === "too_many_attempts"
|
||||
? "Too many attempts. Try again in a few minutes."
|
||||
: body.error || "Could not log in. Check your email and password.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
location.assign("/app");
|
||||
} catch {
|
||||
showError("Could not reach the server. Check your connection and try again.");
|
||||
} finally {
|
||||
submitButton.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import { api, protectedFetch } from "./api.js";
|
||||
import { showToast } from "./toast.js";
|
||||
|
||||
let lots = [];
|
||||
|
||||
function findLot(id) {
|
||||
return lots.find((l) => l.id === id);
|
||||
}
|
||||
|
||||
/** Wires the "From inventory lot" picker (in The Coffee) and the "Draw from lot" action
|
||||
* (in Roast Log — Plan vs. Actual). `getRemotePlanId` is a function since the planner's
|
||||
* remotePlanId is module-local and can change after a sync. */
|
||||
export function initLotPicker({ state, recompute, flushCurrentPlan, getRemotePlanId }) {
|
||||
const select = document.getElementById("lot-select");
|
||||
const note = document.getElementById("lot-picker-note");
|
||||
const consumeRow = document.getElementById("inventory-consume");
|
||||
const consumeLabel = document.getElementById("inventory-consume-label");
|
||||
const consumeBtn = document.getElementById("btn-consume");
|
||||
|
||||
function renderOptions() {
|
||||
const current = state.plan.inventory.lotId;
|
||||
select.replaceChildren(
|
||||
Object.assign(document.createElement("option"), { value: "", textContent: "— none —" }),
|
||||
...lots
|
||||
.filter((l) => !l.archived)
|
||||
.map((l) =>
|
||||
Object.assign(document.createElement("option"), {
|
||||
value: l.id,
|
||||
textContent: `${l.origin}${l.variety ? ` — ${l.variety}` : ""} (${Math.round(l.remainingWeightG)} g remaining)`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (current && !findLot(current)) {
|
||||
// The plan references a lot that's now archived/deleted — keep it selectable so the
|
||||
// stored value still displays instead of silently reverting to "— none —".
|
||||
select.append(
|
||||
Object.assign(document.createElement("option"), {
|
||||
value: current,
|
||||
textContent: state.plan.inventory.lotLabel || "Unavailable lot",
|
||||
disabled: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
select.value = current || "";
|
||||
}
|
||||
|
||||
async function loadLots() {
|
||||
try {
|
||||
const body = await api("/api/inventory");
|
||||
lots = body.lots;
|
||||
} catch {
|
||||
lots = [];
|
||||
}
|
||||
renderOptions();
|
||||
updateConsumeRow();
|
||||
}
|
||||
|
||||
function updateConsumeRow() {
|
||||
const lotId = state.plan.inventory.lotId;
|
||||
if (!lotId) {
|
||||
consumeRow.classList.add("hidden");
|
||||
return;
|
||||
}
|
||||
consumeRow.classList.remove("hidden");
|
||||
const consumed = state.plan.inventory.consumed;
|
||||
if (consumed) {
|
||||
consumeLabel.textContent = `✓ ${Math.round(consumed.weightG)} g drawn from ${consumed.lotLabel} · ${new Date(consumed.atIso).toLocaleDateString()}`;
|
||||
consumeBtn.classList.add("hidden");
|
||||
return;
|
||||
}
|
||||
consumeBtn.classList.remove("hidden");
|
||||
const weightG = Number(state.plan.fields["0.4"]);
|
||||
const lot = findLot(lotId);
|
||||
const lotLabel = lot ? lot.origin : state.plan.inventory.lotLabel || "this lot";
|
||||
if (Number.isFinite(weightG) && weightG > 0) {
|
||||
consumeLabel.textContent = `Charging will draw ${weightG} g from ${lotLabel}.`;
|
||||
consumeBtn.disabled = false;
|
||||
consumeBtn.removeAttribute("title");
|
||||
} else {
|
||||
consumeLabel.textContent = `Set "Green in" (field 0.4) to draw weight from ${lotLabel}.`;
|
||||
consumeBtn.disabled = true;
|
||||
consumeBtn.title = "Enter a Green in weight on The Coffee first";
|
||||
}
|
||||
}
|
||||
|
||||
select.addEventListener("change", () => {
|
||||
const lotId = select.value;
|
||||
state.plan.inventory.lotId = lotId;
|
||||
const lot = findLot(lotId);
|
||||
state.plan.inventory.lotLabel = lot
|
||||
? `${lot.origin}${lot.variety ? ` — ${lot.variety}` : ""}`
|
||||
: "";
|
||||
if (lot) {
|
||||
note.textContent = `${Math.round(lot.remainingWeightG)} g remaining in this lot.`;
|
||||
const nameInput = document.querySelector('[name="0.1"]');
|
||||
if (nameInput && !nameInput.value) {
|
||||
nameInput.value = lot.origin;
|
||||
state.plan.fields["0.1"] = lot.origin;
|
||||
}
|
||||
} else {
|
||||
note.textContent =
|
||||
"Optional — link a lot and the Roast Log can draw the green weight down when you charge.";
|
||||
}
|
||||
updateConsumeRow();
|
||||
recompute();
|
||||
});
|
||||
|
||||
consumeBtn.addEventListener("click", async () => {
|
||||
consumeBtn.disabled = true;
|
||||
try {
|
||||
if (!(await flushCurrentPlan())) {
|
||||
showToast("Could not sync the plan. Try again.", "fail");
|
||||
return;
|
||||
}
|
||||
const roastPlanId = getRemotePlanId();
|
||||
if (!roastPlanId) {
|
||||
showToast("Sync the plan first, then draw from the lot.", "fail");
|
||||
return;
|
||||
}
|
||||
const weightG = Number(state.plan.fields["0.4"]);
|
||||
const response = await protectedFetch(
|
||||
`/api/inventory/${state.plan.inventory.lotId}/consume`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ weightG, roastPlanId }),
|
||||
},
|
||||
);
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (!response.ok && body.code !== "already_consumed") {
|
||||
showToast(body.error || "Could not draw from the lot.", "fail");
|
||||
return;
|
||||
}
|
||||
state.plan.inventory.consumed = {
|
||||
lotId: state.plan.inventory.lotId,
|
||||
lotLabel: state.plan.inventory.lotLabel,
|
||||
weightG,
|
||||
atIso: new Date().toISOString(),
|
||||
};
|
||||
updateConsumeRow();
|
||||
recompute();
|
||||
showToast(`${weightG} g drawn from lot.`);
|
||||
await loadLots();
|
||||
} finally {
|
||||
consumeBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
loadLots();
|
||||
return { updateConsumeRow, renderOptions };
|
||||
}
|
||||
+157
-121
@@ -10,117 +10,26 @@ import { buildPlanCurve, pointsToPathD, tToX, tempToY } from "/shared/curve.js";
|
||||
import { initPrefillPanel } from "./prefill-ui.js";
|
||||
import { initAlogPanel } from "./alog-ui.js";
|
||||
import { initPrint } from "./print.js";
|
||||
import { initLotPicker } from "./lot-picker.js";
|
||||
import { protectedFetch, csrfToken } from "./api.js";
|
||||
import { initSideNav } from "./nav.js";
|
||||
import { wireWhyPanels } from "./why-panels.js";
|
||||
|
||||
const FIELD_ID_SET = new Set(FIELD_IDS);
|
||||
const STORAGE_PREFIX = "roastPlannerPlan.v2";
|
||||
let storageKey = null;
|
||||
let remotePlanId = null;
|
||||
let draftSyncedAt = null;
|
||||
let plans = [];
|
||||
let lastDrawerOpener = null;
|
||||
let deferredInstallPrompt = null;
|
||||
const csrfToken = () =>
|
||||
document.cookie
|
||||
.split("; ")
|
||||
.find((v) => v.startsWith("rp_csrf="))
|
||||
?.split("=")[1] || "";
|
||||
export const protectedFetch = (url, options = {}) =>
|
||||
fetch(url, {
|
||||
...options,
|
||||
headers: { ...options.headers, "x-csrf-token": csrfToken() },
|
||||
});
|
||||
let lotPicker = null;
|
||||
const BAND_DOMAIN = [60, 220]; // shared °C domain for every band-track in the Machine Plan section
|
||||
|
||||
export const state = { plan: blankPlan() };
|
||||
|
||||
const form = document.getElementById("plan-form");
|
||||
|
||||
const FIELD_HELP = {
|
||||
5.1: "Optional moisture percentage. Find it on a supplier certificate of analysis (COA) or measure it with a calibrated meter. Leave it blank when unknown: it does not automatically change your roast timing.",
|
||||
5.2: "Optional green-bean density in g/L. Get it from a supplier COA or measure a known volume. Leave it blank when unknown: it does not automatically change your roast timing.",
|
||||
5.6: "A documented timing adjustment in m:ss, normally no more than ±0:15. Use only after an observation or comparison roast; moisture and density never create this value automatically.",
|
||||
1.4: "Your first-crack anchor in m:ss. It is the starting point for the Time Ledger; use a cultivar reference or a previous comparable roast.",
|
||||
4.3: "Development base in m:ss. Together with the processing and cultivar modifiers it determines development and drop time.",
|
||||
};
|
||||
function helpText(input) {
|
||||
if (FIELD_HELP[input.name]) return FIELD_HELP[input.name];
|
||||
const unit = input
|
||||
.closest(".unit-input")
|
||||
?.querySelector(".unit")?.textContent;
|
||||
const label =
|
||||
input
|
||||
.closest(".field")
|
||||
?.querySelector(".field-label")
|
||||
?.textContent?.trim() ||
|
||||
input.getAttribute("aria-label") ||
|
||||
input.placeholder ||
|
||||
"This value";
|
||||
return `${label} records your plan or roast observation${unit ? ` in ${unit}` : ""}. Use the format shown; leave it blank when you do not know it, then refine it from a supplier record or your next roast.`;
|
||||
}
|
||||
function wireFieldHelp(root = document) {
|
||||
for (const input of root.querySelectorAll(
|
||||
"input[name], select[name], textarea[name], #prefill-url",
|
||||
)) {
|
||||
if (!input.closest("#plan-form") && input.id !== "prefill-url") continue;
|
||||
const field = input.closest(".field");
|
||||
if (
|
||||
input.dataset.helpWired ||
|
||||
(input.type === "radio" && field?.dataset.radioHelp === input.name)
|
||||
)
|
||||
continue;
|
||||
input.dataset.helpWired = "true";
|
||||
if (input.type === "radio" && field) field.dataset.radioHelp = input.name;
|
||||
const id = `field-help-${Math.random().toString(36).slice(2)}`;
|
||||
const help = document.createElement("span");
|
||||
help.id = id;
|
||||
help.className = "field-help-text";
|
||||
help.hidden = true;
|
||||
help.textContent = helpText(input);
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "field-help";
|
||||
button.setAttribute("aria-expanded", "false");
|
||||
button.setAttribute("aria-controls", id);
|
||||
button.setAttribute("aria-label", `Learn about ${input.name}`);
|
||||
button.textContent = "?";
|
||||
button.addEventListener("click", () => {
|
||||
const open = help.hidden;
|
||||
help.hidden = !open;
|
||||
button.setAttribute("aria-expanded", String(open));
|
||||
});
|
||||
const milestone = input
|
||||
.closest(".milestone-row")
|
||||
?.querySelector(".milestone-label")
|
||||
?.textContent?.trim();
|
||||
const fieldLabel = field
|
||||
?.querySelector(".field-label")
|
||||
?.textContent?.trim();
|
||||
input.setAttribute(
|
||||
"aria-label",
|
||||
input.getAttribute("aria-label") ||
|
||||
milestone ||
|
||||
fieldLabel ||
|
||||
input.placeholder ||
|
||||
"Plan value",
|
||||
);
|
||||
input.setAttribute(
|
||||
"aria-describedby",
|
||||
[input.getAttribute("aria-describedby"), id].filter(Boolean).join(" "),
|
||||
);
|
||||
const host = field || input.closest(".unit-input") || input;
|
||||
let wrapper = host?.parentElement?.classList.contains("field-help-host")
|
||||
? host.parentElement
|
||||
: null;
|
||||
if (!wrapper && host) {
|
||||
wrapper = document.createElement("div");
|
||||
wrapper.className = "field-help-host";
|
||||
host.replaceWith(wrapper);
|
||||
wrapper.append(host);
|
||||
}
|
||||
// Labels cannot contain another interactive control, so the help button is a sibling.
|
||||
wrapper?.append(button, help);
|
||||
}
|
||||
}
|
||||
|
||||
// The print worksheet (#print-sheet) sits outside #plan-form on purpose — see index.html —
|
||||
// so its radios don't fight the screen form's identically-named radios for exclusivity.
|
||||
// Every sync pass therefore has to reach both containers explicitly.
|
||||
@@ -235,7 +144,6 @@ function updateBlendVisibility(mode) {
|
||||
function renderBlend() {
|
||||
renderBlendPrintRows();
|
||||
renderBlendCards();
|
||||
wireFieldHelp(document.getElementById("blend-cards"));
|
||||
updateBlendTotal();
|
||||
}
|
||||
|
||||
@@ -293,7 +201,6 @@ function renderActuatorTimeline() {
|
||||
function renderActuators() {
|
||||
renderActuatorPrintRows();
|
||||
renderActuatorTimeline();
|
||||
wireFieldHelp(document.getElementById("actuator-timeline"));
|
||||
}
|
||||
|
||||
// ---- populate every control in the form from state.plan
|
||||
@@ -493,10 +400,41 @@ function renderCurve(ledger) {
|
||||
);
|
||||
}
|
||||
|
||||
// The blank shape has some non-empty defaults of its own (e.g. planActual.charge.actualTime
|
||||
// is "0:00", since charge is always t=0) — compare against those defaults, not against "",
|
||||
// so a fresh plan doesn't read as already having roast-day data.
|
||||
const BLANK_PLAN = blankPlan();
|
||||
|
||||
// True once any value in `obj` differs from the same path in `blank` — used to lift the
|
||||
// "phase-later" muting off Roast Log / After the Roast the moment the user has actually started
|
||||
// using them, without ever hiding the plan column they exist to compare against.
|
||||
function hasVal(obj, blank) {
|
||||
if (obj == null) return false;
|
||||
return Object.keys(obj).some((key) => {
|
||||
const v = obj[key];
|
||||
return typeof v === "object" && v !== null
|
||||
? hasVal(v, blank?.[key])
|
||||
: v !== "" && v != null && v !== blank?.[key];
|
||||
});
|
||||
}
|
||||
|
||||
export function recompute() {
|
||||
const ledger = renderLedger();
|
||||
renderCurve(ledger);
|
||||
renderBandMarkers();
|
||||
document
|
||||
.getElementById("sec-roastlog")
|
||||
?.classList.toggle(
|
||||
"has-data",
|
||||
hasVal(state.plan.planActual, BLANK_PLAN.planActual),
|
||||
);
|
||||
document
|
||||
.getElementById("sec-after")
|
||||
?.classList.toggle(
|
||||
"has-data",
|
||||
hasVal(state.plan.afterRoast, BLANK_PLAN.afterRoast),
|
||||
);
|
||||
lotPicker?.updateConsumeRow();
|
||||
autosave();
|
||||
}
|
||||
|
||||
@@ -514,10 +452,16 @@ function setSaveStatus(status) {
|
||||
}[status] || "Not saved yet";
|
||||
}
|
||||
let syncQueue = Promise.resolve();
|
||||
// Resolves true once the server sync attempt has settled (succeeded, failed, or was correctly
|
||||
// deferred because we're offline/unauthenticated) — offline is not a failure here, the local
|
||||
// write it's paired with in flushCurrentPlan already guarantees the draft isn't lost, and
|
||||
// newPlan()/selectPlan() rely on that to let plan-switching keep working offline. Callers that
|
||||
// specifically need a confirmed server-side plan id (attaching a lot draw or a cupping session)
|
||||
// must check remotePlanId themselves afterward, which they already do.
|
||||
function syncPlan(snapshot = structuredClone(state.plan)) {
|
||||
if (!navigator.onLine || !csrfToken()) {
|
||||
setSaveStatus("local");
|
||||
return Promise.resolve();
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
syncQueue = syncQueue.then(async () => {
|
||||
try {
|
||||
@@ -532,10 +476,11 @@ function syncPlan(snapshot = structuredClone(state.plan)) {
|
||||
if (!response.ok) throw new Error("sync_failed");
|
||||
const body = await response.json();
|
||||
remotePlanId = body.plan.id;
|
||||
draftSyncedAt = body.plan.updated_at;
|
||||
if (storageKey)
|
||||
localStorage.setItem(
|
||||
storageKey,
|
||||
JSON.stringify({ plan: snapshot, remotePlanId }),
|
||||
JSON.stringify({ plan: snapshot, remotePlanId, syncedAt: draftSyncedAt }),
|
||||
);
|
||||
history.replaceState(
|
||||
null,
|
||||
@@ -544,8 +489,10 @@ function syncPlan(snapshot = structuredClone(state.plan)) {
|
||||
);
|
||||
setSaveStatus("saved");
|
||||
await loadPlans();
|
||||
return true;
|
||||
} catch {
|
||||
setSaveStatus("failed");
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return syncQueue;
|
||||
@@ -557,14 +504,13 @@ async function flushCurrentPlan() {
|
||||
if (storageKey)
|
||||
localStorage.setItem(
|
||||
storageKey,
|
||||
JSON.stringify({ plan: snapshot, remotePlanId }),
|
||||
JSON.stringify({ plan: snapshot, remotePlanId, syncedAt: draftSyncedAt }),
|
||||
);
|
||||
} catch {
|
||||
setSaveStatus("failed");
|
||||
return false;
|
||||
}
|
||||
await syncPlan(snapshot);
|
||||
return true;
|
||||
return await syncPlan(snapshot);
|
||||
}
|
||||
function autosave() {
|
||||
setSaveStatus("saving");
|
||||
@@ -594,6 +540,7 @@ function loadFromStorage(userId) {
|
||||
const draft = JSON.parse(raw);
|
||||
if (draft?.plan) {
|
||||
remotePlanId = draft.remotePlanId || null;
|
||||
draftSyncedAt = draft.syncedAt || null;
|
||||
return draft.plan;
|
||||
}
|
||||
return draft; // legacy v2 draft: retain it once, then upgrade on next save
|
||||
@@ -611,6 +558,7 @@ function clearDraft() {
|
||||
}
|
||||
storageKey = null;
|
||||
remotePlanId = null;
|
||||
draftSyncedAt = null;
|
||||
}
|
||||
|
||||
function cultivarAutofill(name) {
|
||||
@@ -670,16 +618,18 @@ function wireDrawers() {
|
||||
panel.querySelector("button, input, [href]")?.focus();
|
||||
}
|
||||
for (const [buttonId, panelId] of [
|
||||
["btn-toggle-prefill", "panel-prefill"],
|
||||
["btn-toggle-alog", "panel-alog"],
|
||||
["btn-plans", "panel-plans"],
|
||||
["btn-settings", "panel-settings"],
|
||||
["nav-prefill", "panel-prefill"],
|
||||
["nav-alog", "panel-alog"],
|
||||
["nav-plans", "panel-plans"],
|
||||
["nav-settings", "panel-settings"],
|
||||
["nav-import-export", "panel-import-export"],
|
||||
])
|
||||
document
|
||||
.getElementById(buttonId)
|
||||
.addEventListener("click", (event) =>
|
||||
open(document.getElementById(panelId), event.currentTarget),
|
||||
);
|
||||
.addEventListener("click", (event) => {
|
||||
document.getElementById("side-nav")?.classList.remove("mobile-open");
|
||||
open(document.getElementById(panelId), event.currentTarget);
|
||||
});
|
||||
overlay.addEventListener("click", closeAll);
|
||||
for (const btn of document.querySelectorAll("[data-close-drawer]"))
|
||||
btn.addEventListener("click", closeAll);
|
||||
@@ -738,6 +688,7 @@ async function loadPlans() {
|
||||
async function selectPlan(plan) {
|
||||
if (!(await flushCurrentPlan())) return;
|
||||
remotePlanId = plan.id;
|
||||
draftSyncedAt = plan.updated_at;
|
||||
state.plan = { ...blankPlan(), ...plan.plan };
|
||||
history.replaceState(
|
||||
null,
|
||||
@@ -748,6 +699,11 @@ async function selectPlan(plan) {
|
||||
renderActuators();
|
||||
renderFormFromPlan();
|
||||
recompute();
|
||||
// renderFormFromPlan() sets the lot <select>'s value, but that only sticks if the option is
|
||||
// already in the DOM — re-render the picker's own option list against the newly-loaded
|
||||
// plan's inventory.lotId so switching to a plan referencing a different (or no) lot doesn't
|
||||
// leave the dropdown showing the previous plan's selection or a blank state.
|
||||
lotPicker?.renderOptions();
|
||||
document.querySelector("[data-close-drawer]")?.click();
|
||||
}
|
||||
async function newPlan() {
|
||||
@@ -755,12 +711,14 @@ async function newPlan() {
|
||||
return;
|
||||
if (!(await flushCurrentPlan())) return;
|
||||
remotePlanId = null;
|
||||
draftSyncedAt = null;
|
||||
state.plan = blankPlan();
|
||||
history.replaceState(null, "", "/app");
|
||||
renderBlend();
|
||||
renderActuators();
|
||||
renderFormFromPlan();
|
||||
recompute();
|
||||
lotPicker?.renderOptions();
|
||||
}
|
||||
|
||||
function wireToolbar() {
|
||||
@@ -864,6 +822,10 @@ function wirePwa() {
|
||||
renderConnection();
|
||||
|
||||
if ("serviceWorker" in navigator) {
|
||||
// A brand-new visitor has no controller yet, so the *first* activation firing
|
||||
// "controllerchange" is not an update — only a page that was already controlled by a
|
||||
// previous service worker should reload when a new one takes over.
|
||||
const hadController = !!navigator.serviceWorker.controller;
|
||||
window.addEventListener("load", () => {
|
||||
navigator.serviceWorker
|
||||
.register("/sw.js")
|
||||
@@ -882,9 +844,9 @@ function wirePwa() {
|
||||
console.warn("Service worker registration failed:", error),
|
||||
);
|
||||
});
|
||||
navigator.serviceWorker.addEventListener("controllerchange", () =>
|
||||
location.reload(),
|
||||
);
|
||||
navigator.serviceWorker.addEventListener("controllerchange", () => {
|
||||
if (hadController) location.reload();
|
||||
});
|
||||
}
|
||||
document.getElementById("btn-refresh").addEventListener("click", async () => {
|
||||
if (!(await flushCurrentPlan())) return;
|
||||
@@ -927,21 +889,36 @@ async function init() {
|
||||
const { user } = await meResponse.json();
|
||||
document.getElementById("account-email").textContent = user.email;
|
||||
document.getElementById("settings-email").textContent = user.email;
|
||||
document.getElementById("account-summary").textContent =
|
||||
user.email.split("@")[0];
|
||||
document.getElementById("nav-user-avatar").textContent = user.email
|
||||
.charAt(0)
|
||||
.toUpperCase();
|
||||
if (user.role === "admin")
|
||||
document.getElementById("menu-admin").classList.remove("hidden");
|
||||
document.getElementById("nav-admin").classList.remove("hidden");
|
||||
const localDraft = loadFromStorage(user.id);
|
||||
state.plan = localDraft ?? blankPlan();
|
||||
const draftRemoteId = remotePlanId;
|
||||
const draftSyncedAtAtLoad = draftSyncedAt;
|
||||
await loadPlans();
|
||||
const requestedId = new URLSearchParams(location.search).get("plan");
|
||||
const selected = plans.find((plan) => plan.id === requestedId);
|
||||
if (selected) {
|
||||
state.plan = selected.plan;
|
||||
// Prefer the local draft only when it targets this exact plan AND was last confirmed
|
||||
// synced at or after the server's own updated_at — otherwise another device's newer
|
||||
// edit (or a draft from before sync tracking existed) would be silently discarded.
|
||||
const draftIsCurrent =
|
||||
selected &&
|
||||
draftRemoteId === selected.id &&
|
||||
draftSyncedAtAtLoad &&
|
||||
new Date(selected.updated_at) <= new Date(draftSyncedAtAtLoad);
|
||||
if (selected && !draftIsCurrent) {
|
||||
state.plan = { ...blankPlan(), ...selected.plan };
|
||||
remotePlanId = selected.id;
|
||||
draftSyncedAt = selected.updated_at;
|
||||
} else if (selected) {
|
||||
remotePlanId = selected.id;
|
||||
} else if (!localDraft && !requestedId && plans[0]) {
|
||||
state.plan = plans[0].plan;
|
||||
state.plan = { ...blankPlan(), ...plans[0].plan };
|
||||
remotePlanId = plans[0].id;
|
||||
draftSyncedAt = plans[0].updated_at;
|
||||
}
|
||||
} catch {
|
||||
// The cached app shell contains no user data. A successful online sign-in records the
|
||||
@@ -957,10 +934,11 @@ async function init() {
|
||||
renderBlend();
|
||||
renderActuators();
|
||||
wireCultivarDatalist();
|
||||
wireFieldHelp();
|
||||
wireWhyPanels();
|
||||
renderBandRanges();
|
||||
renderFormFromPlan();
|
||||
wireForm();
|
||||
initSideNav();
|
||||
wireDrawers();
|
||||
wireToolbar();
|
||||
wirePwa();
|
||||
@@ -974,7 +952,65 @@ async function init() {
|
||||
});
|
||||
initAlogPanel({ state, recompute });
|
||||
initPrint({ beforePrint: renderFormFromPlan });
|
||||
lotPicker = initLotPicker({
|
||||
state,
|
||||
recompute,
|
||||
flushCurrentPlan,
|
||||
getRemotePlanId: () => remotePlanId,
|
||||
});
|
||||
wireCuppingLink();
|
||||
recompute();
|
||||
}
|
||||
|
||||
function wireCuppingLink() {
|
||||
const button = document.getElementById("btn-open-cupping");
|
||||
const note = document.getElementById("cupping-link-note");
|
||||
button.addEventListener("click", async () => {
|
||||
button.disabled = true;
|
||||
try {
|
||||
if (!(await flushCurrentPlan())) {
|
||||
note.textContent = "Could not sync the plan. Try again.";
|
||||
return;
|
||||
}
|
||||
if (!remotePlanId) {
|
||||
note.textContent = "Sync the plan first, then open a cupping session.";
|
||||
return;
|
||||
}
|
||||
const existing = await protectedFetch(
|
||||
`/api/cupping?plan=${encodeURIComponent(remotePlanId)}`,
|
||||
)
|
||||
.then((r) => (r.ok ? r.json() : { sessions: [] }))
|
||||
.catch(() => ({ sessions: [] }));
|
||||
if (existing.sessions?.length) {
|
||||
location.assign(`/cupping?session=${existing.sessions[0].id}`);
|
||||
return;
|
||||
}
|
||||
let created;
|
||||
try {
|
||||
created = await protectedFetch("/api/cupping", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ roastPlanId: remotePlanId }),
|
||||
}).then((r) => r.json());
|
||||
} catch {
|
||||
note.textContent = "Could not reach the server. Try again.";
|
||||
return;
|
||||
}
|
||||
if (created.session) location.assign(`/cupping?session=${created.session.id}`);
|
||||
else note.textContent = "Could not start a cupping session.";
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
// Non-blocking: show whether a session already exists without forcing a sync first.
|
||||
if (remotePlanId)
|
||||
protectedFetch(`/api/cupping?plan=${encodeURIComponent(remotePlanId)}`)
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((body) => {
|
||||
if (body?.sessions?.length)
|
||||
note.textContent = `Session exists — ${body.sessions[0].totalScore.toFixed(2)}`;
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
init();
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
// Shared side-nav behavior (collapse/expand, mobile drawer) for every authenticated page
|
||||
// (planner, account, admin) so each page's own script doesn't reimplement it.
|
||||
export function initSideNav() {
|
||||
const nav = document.getElementById("side-nav");
|
||||
const hamburger = document.getElementById("nav-hamburger");
|
||||
const collapseBtn = document.getElementById("nav-collapse");
|
||||
const workspace = document.getElementById("app-workspace");
|
||||
const overlay = document.getElementById("drawer-overlay");
|
||||
const COLLAPSE_KEY = "roastPlannerNavCollapsed";
|
||||
|
||||
function closeMobileNav() {
|
||||
nav.classList.remove("mobile-open");
|
||||
hamburger?.setAttribute("aria-expanded", "false");
|
||||
if (!document.querySelector(".drawer:not(.hidden)"))
|
||||
overlay?.classList.add("hidden");
|
||||
}
|
||||
hamburger?.addEventListener("click", () => {
|
||||
const open = nav.classList.toggle("mobile-open");
|
||||
hamburger.setAttribute("aria-expanded", String(open));
|
||||
overlay?.classList.toggle("hidden", !open);
|
||||
});
|
||||
overlay?.addEventListener("click", closeMobileNav);
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Escape") closeMobileNav();
|
||||
});
|
||||
|
||||
function applyCollapsed(collapsed) {
|
||||
nav.classList.toggle("collapsed", collapsed);
|
||||
workspace?.classList.toggle("nav-collapsed", collapsed);
|
||||
if (collapseBtn) {
|
||||
collapseBtn.textContent = collapsed ? "»" : "«";
|
||||
collapseBtn.setAttribute(
|
||||
"aria-label",
|
||||
collapsed ? "Expand navigation" : "Collapse navigation",
|
||||
);
|
||||
}
|
||||
}
|
||||
applyCollapsed(localStorage.getItem(COLLAPSE_KEY) === "true");
|
||||
collapseBtn?.addEventListener("click", () => {
|
||||
const next = !nav.classList.contains("collapsed");
|
||||
applyCollapsed(next);
|
||||
localStorage.setItem(COLLAPSE_KEY, String(next));
|
||||
});
|
||||
return { closeMobileNav };
|
||||
}
|
||||
|
||||
/** Populates the nav's user chip and admin link; redirects to /login when signed out. */
|
||||
export async function loadNavUser() {
|
||||
const response = await fetch("/api/auth/me");
|
||||
if (!response.ok) {
|
||||
location.replace("/login");
|
||||
return null;
|
||||
}
|
||||
const { user } = await response.json();
|
||||
const emailEl = document.getElementById("account-email");
|
||||
if (emailEl) emailEl.textContent = user.email;
|
||||
const avatarEl = document.getElementById("nav-user-avatar");
|
||||
if (avatarEl) avatarEl.textContent = user.email.charAt(0).toUpperCase();
|
||||
if (user.role === "admin")
|
||||
document.getElementById("nav-admin")?.classList.remove("hidden");
|
||||
return user;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
const form = document.querySelector("#reset-form");
|
||||
const message = document.querySelector("#message");
|
||||
const resetToken = new URLSearchParams(location.search).get("token") || "";
|
||||
|
||||
function showError(text) {
|
||||
message.textContent = text;
|
||||
message.className = "auth-message error";
|
||||
}
|
||||
|
||||
if (!resetToken) {
|
||||
form.classList.add("hidden");
|
||||
showError(
|
||||
"This reset link is missing its token. Request a new one from the forgot-password page.",
|
||||
);
|
||||
}
|
||||
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(form));
|
||||
if (data.password !== data.confirmPassword) {
|
||||
showError("Passwords do not match.");
|
||||
return;
|
||||
}
|
||||
const submitButton = form.querySelector("button[type=submit]");
|
||||
submitButton.disabled = true;
|
||||
message.textContent = "";
|
||||
try {
|
||||
const response = await fetch("/api/auth/reset", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ token: resetToken, password: data.password }),
|
||||
});
|
||||
const body = await response.json();
|
||||
if (!response.ok) {
|
||||
showError(
|
||||
{
|
||||
invalid_token:
|
||||
"This reset link is invalid or has expired. Request a new one.",
|
||||
account_disabled:
|
||||
"Your password was updated, but this account is disabled. Contact an administrator.",
|
||||
}[body.code] || body.error || "Could not reset the password.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
location.assign("/app");
|
||||
} catch {
|
||||
showError("Could not reach the server. Check your connection and try again.");
|
||||
} finally {
|
||||
submitButton.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
const form = document.querySelector("#setup-form");
|
||||
const message = document.querySelector("#message");
|
||||
|
||||
function showError(text) {
|
||||
message.textContent = text;
|
||||
message.className = "auth-message error";
|
||||
}
|
||||
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const submitButton = form.querySelector("button[type=submit]");
|
||||
submitButton.disabled = true;
|
||||
message.textContent = "";
|
||||
try {
|
||||
const response = await fetch("/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(Object.fromEntries(new FormData(form))),
|
||||
});
|
||||
const body = await response.json();
|
||||
if (!response.ok) {
|
||||
showError(
|
||||
{
|
||||
bootstrap_used: "The administrator account already exists.",
|
||||
invalid_setup_token: "That setup token is incorrect.",
|
||||
bootstrap_unavailable: "Setup is not available in this deployment.",
|
||||
}[body.code] || body.error || "Could not create the administrator.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
location.assign("/app");
|
||||
} catch {
|
||||
showError("Could not reach the server. Check your connection and try again.");
|
||||
} finally {
|
||||
submitButton.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
const form = document.querySelector("#signup-form");
|
||||
const message = document.querySelector("#message");
|
||||
const title = document.querySelector("#signup-title");
|
||||
|
||||
function showError(text) {
|
||||
message.textContent = text;
|
||||
message.className = "auth-message error";
|
||||
}
|
||||
function showInfo(text) {
|
||||
message.textContent = text;
|
||||
message.className = "auth-message info";
|
||||
}
|
||||
|
||||
(async function checkSignupEnabled() {
|
||||
try {
|
||||
const response = await fetch("/api/auth/signup-enabled");
|
||||
const body = await response.json();
|
||||
if (body.enabled) {
|
||||
form.classList.remove("hidden");
|
||||
} else {
|
||||
title.textContent = "Invite only";
|
||||
showInfo(
|
||||
"New signups are currently disabled. Ask an administrator for an invitation.",
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// Don't strand a new customer on a dead page over one failed probe — show the form and
|
||||
// let the real submit enforce the signup-enabled rule if it turns out to matter.
|
||||
form.classList.remove("hidden");
|
||||
showError(
|
||||
"Could not confirm signups are open. You can still try creating an account below.",
|
||||
);
|
||||
}
|
||||
})();
|
||||
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(form));
|
||||
if (data.password !== data.confirmPassword) {
|
||||
showError("Passwords do not match.");
|
||||
return;
|
||||
}
|
||||
const submitButton = form.querySelector("button[type=submit]");
|
||||
submitButton.disabled = true;
|
||||
message.textContent = "";
|
||||
try {
|
||||
const response = await fetch("/api/auth/signup", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ email: data.email, password: data.password }),
|
||||
});
|
||||
const body = await response.json();
|
||||
if (!response.ok) {
|
||||
showError(
|
||||
{
|
||||
email_exists: "An account with that email already exists.",
|
||||
signup_disabled:
|
||||
"New signups are currently disabled. Ask an administrator for an invitation.",
|
||||
}[body.code] || body.error || "Could not create the account.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
location.assign("/app");
|
||||
} catch {
|
||||
showError("Could not reach the server. Check your connection and try again.");
|
||||
} finally {
|
||||
submitButton.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
function stack() {
|
||||
let el = document.querySelector(".toast-stack");
|
||||
if (!el) {
|
||||
el = document.createElement("div");
|
||||
el.className = "toast-stack";
|
||||
el.setAttribute("aria-live", "polite");
|
||||
document.body.append(el);
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
export function showToast(text, type = "") {
|
||||
const toast = document.createElement("div");
|
||||
toast.className = `toast ${type}`.trim();
|
||||
toast.textContent = text;
|
||||
stack().append(toast);
|
||||
setTimeout(() => toast.remove(), 4500);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Shared teaching-layer collapse memory for every page that uses `.why-panel` (`<details>`
|
||||
// with a `data-why` id): the planner and the cupping session view. One localStorage key across
|
||||
// both so a user's dismissals carry over between pages.
|
||||
const WHY_COLLAPSED_KEY = "roastPlannerWhyCollapsed.v1";
|
||||
|
||||
export function wireWhyPanels() {
|
||||
let collapsed;
|
||||
try {
|
||||
collapsed = new Set(JSON.parse(localStorage.getItem(WHY_COLLAPSED_KEY)) || []);
|
||||
} catch {
|
||||
collapsed = new Set();
|
||||
}
|
||||
for (const panel of document.querySelectorAll(".why-panel")) {
|
||||
if (collapsed.has(panel.dataset.why)) panel.open = false;
|
||||
panel.addEventListener("toggle", () => {
|
||||
if (panel.open) collapsed.delete(panel.dataset.why);
|
||||
else collapsed.add(panel.dataset.why);
|
||||
try {
|
||||
localStorage.setItem(WHY_COLLAPSED_KEY, JSON.stringify([...collapsed]));
|
||||
} catch {
|
||||
/* unavailable storage */
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+148
-43
@@ -3,51 +3,156 @@
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Roast Planner</title>
|
||||
<title>Roast Planner — Plan the roast before you light the burner</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="A structured worksheet that computes first crack, development, and drop from your bean — then keeps the plan next to what actually happened."
|
||||
/>
|
||||
<link rel="stylesheet" href="/app.css" />
|
||||
<meta name="theme-color" content="#A8481A" />
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
|
||||
<meta name="theme-color" content="#2A1D16" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="auth-page">
|
||||
<section class="panel-card auth-card">
|
||||
<h1>Roast Planner</h1>
|
||||
<p>Build, save, and revisit your coffee roast plans.</p>
|
||||
<div id="message" role="status"></div>
|
||||
<form id="auth-form">
|
||||
<label
|
||||
>Email
|
||||
<input
|
||||
class="field-input"
|
||||
required
|
||||
type="email"
|
||||
name="email"
|
||||
autocomplete="email" /></label
|
||||
><label
|
||||
>Password
|
||||
<input
|
||||
class="field-input"
|
||||
required
|
||||
type="password"
|
||||
minlength="12"
|
||||
name="password"
|
||||
autocomplete="current-password" /></label
|
||||
><label
|
||||
>Initial admin setup token (first account only)
|
||||
<input
|
||||
class="field-input"
|
||||
type="password"
|
||||
name="setupToken"
|
||||
autocomplete="off" /></label
|
||||
><button class="primary-btn" type="submit">Log in</button
|
||||
><button class="ghost-btn" type="button" id="signup">
|
||||
Create account
|
||||
</button>
|
||||
</form>
|
||||
<p class="muted">
|
||||
Accounts require a password of at least 12 characters.
|
||||
</p>
|
||||
</section>
|
||||
</main>
|
||||
<script type="module" src="/js/landing.js"></script>
|
||||
<header class="marketing-header">
|
||||
<div class="brand">
|
||||
<span class="brand-mark" aria-hidden="true">◐</span>
|
||||
<span>Roast Planner</span>
|
||||
</div>
|
||||
<nav>
|
||||
<a class="ghost-btn" href="/login">Log in</a>
|
||||
<a class="primary-btn" href="/signup">Get started</a>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<section class="hero">
|
||||
<div class="hero-inner">
|
||||
<div>
|
||||
<h1>Plan the roast before you light the burner.</h1>
|
||||
<p class="lede">
|
||||
A structured worksheet that computes first crack, development, and
|
||||
drop from your bean — then keeps the plan next to what actually
|
||||
happened.
|
||||
</p>
|
||||
<div class="hero-ctas">
|
||||
<a class="primary-btn" href="/signup">Start planning — free</a>
|
||||
<a class="ghost-btn" href="#how-it-works">See how it works</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="hero-visual" aria-hidden="true">
|
||||
<div class="dock-card-head">
|
||||
<h2>Time Ledger</h2>
|
||||
</div>
|
||||
<div class="ledger-row">
|
||||
<span class="l-fid">1.4</span
|
||||
><span class="l-label">First crack anchor</span
|
||||
><span class="l-val">9:30</span>
|
||||
</div>
|
||||
<div class="ledger-row">
|
||||
<span class="l-fid">5.6</span
|
||||
><span class="l-label">Bean-condition refinement</span
|
||||
><span class="l-val">+0:10</span>
|
||||
</div>
|
||||
<div class="ledger-row">
|
||||
<span class="l-fid">4.3</span
|
||||
><span class="l-label">Development base</span
|
||||
><span class="l-val">2:15</span>
|
||||
</div>
|
||||
<div class="ledger-total drop">
|
||||
<span>Drop time</span><output>11:55</output>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="marketing-section" id="how-it-works">
|
||||
<h2>Built around the worksheet, not a generic form</h2>
|
||||
<p class="section-lede">
|
||||
Every field ties back to the same time-ledger math professional
|
||||
roasters already use on paper — now it computes itself.
|
||||
</p>
|
||||
<div class="feature-grid">
|
||||
<div class="feature-card">
|
||||
<div class="feature-icon" aria-hidden="true">◐</div>
|
||||
<h3>The Time Ledger</h3>
|
||||
<p>
|
||||
Anchor first crack by cultivar, then let refinements, bean
|
||||
condition, and batch size sum into a plan you can defend.
|
||||
</p>
|
||||
</div>
|
||||
<div class="feature-card">
|
||||
<div class="feature-icon" aria-hidden="true">✓</div>
|
||||
<h3>Sanity checks</h3>
|
||||
<p>
|
||||
Drying, Maillard, and development ratios validated against known
|
||||
bands before you roast.
|
||||
</p>
|
||||
</div>
|
||||
<div class="feature-card">
|
||||
<div class="feature-icon" aria-hidden="true">∿</div>
|
||||
<h3>Plan vs. actual</h3>
|
||||
<p>
|
||||
Log milestones at the machine, attach an Artisan .alog reference
|
||||
curve, and see plan against reality.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="feature-row">
|
||||
<div class="feature-row-item">
|
||||
<span class="feature-icon" aria-hidden="true">↗</span
|
||||
><span>Prefill straight from a bean product page URL</span>
|
||||
</div>
|
||||
<div class="feature-row-item">
|
||||
<span class="feature-icon" aria-hidden="true">🖶</span
|
||||
><span>Printable two-page worksheet, faithful to the original</span>
|
||||
</div>
|
||||
<div class="feature-row-item">
|
||||
<span class="feature-icon" aria-hidden="true">⇩</span
|
||||
><span>Installable PWA that keeps working offline</span>
|
||||
</div>
|
||||
<div class="feature-row-item">
|
||||
<span class="feature-icon" aria-hidden="true">⟳</span
|
||||
><span>Autosave with sync the moment you're back online</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="marketing-section">
|
||||
<h2>Three steps, every roast</h2>
|
||||
<div class="steps-row">
|
||||
<div class="step-item">
|
||||
<h3>Describe the coffee</h3>
|
||||
<p>
|
||||
Cultivar, process, bean condition — the worksheet pulls in the
|
||||
right reference numbers automatically.
|
||||
</p>
|
||||
</div>
|
||||
<div class="step-item">
|
||||
<h3>Review ledger & checks</h3>
|
||||
<p>
|
||||
Watch first crack, development, and drop compute live, with every
|
||||
ratio checked against known-good bands.
|
||||
</p>
|
||||
</div>
|
||||
<div class="step-item">
|
||||
<h3>Roast and record</h3>
|
||||
<p>
|
||||
Log milestones as you go, then compare against an Artisan
|
||||
reference curve after the roast.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="cta-band">
|
||||
<h2>Plan your next roast properly.</h2>
|
||||
<a class="primary-btn" href="/signup">Get started — it's free</a>
|
||||
</section>
|
||||
|
||||
<footer class="marketing-footer">
|
||||
<span>© Roast Planner</span>
|
||||
<span
|
||||
><a href="/login">Log in</a><a href="/signup">Sign up</a></span
|
||||
>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Log in — Roast Planner</title>
|
||||
<link rel="stylesheet" href="/app.css" />
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
|
||||
<meta name="theme-color" content="#A8481A" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="auth-page">
|
||||
<section class="panel-card auth-card">
|
||||
<div class="auth-brand">
|
||||
<span class="brand-mark" aria-hidden="true">◐</span>
|
||||
<strong>Roast Planner</strong>
|
||||
</div>
|
||||
<h1>Log in</h1>
|
||||
<div id="message" class="auth-message" role="alert"></div>
|
||||
<form id="login-form">
|
||||
<label
|
||||
>Email
|
||||
<input
|
||||
class="field-input"
|
||||
required
|
||||
type="email"
|
||||
name="email"
|
||||
autocomplete="email"
|
||||
/></label>
|
||||
<label
|
||||
>Password
|
||||
<input
|
||||
class="field-input"
|
||||
required
|
||||
type="password"
|
||||
name="password"
|
||||
autocomplete="current-password"
|
||||
/></label>
|
||||
<button class="primary-btn" type="submit">Log in</button>
|
||||
</form>
|
||||
<div class="auth-links">
|
||||
<a href="/forgot">Forgot password?</a>
|
||||
<a href="/signup">Create an account</a>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<script type="module" src="/js/login.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,51 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Set a new password — Roast Planner</title>
|
||||
<link rel="stylesheet" href="/app.css" />
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
|
||||
<meta name="theme-color" content="#A8481A" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="auth-page">
|
||||
<section class="panel-card auth-card">
|
||||
<div class="auth-brand">
|
||||
<span class="brand-mark" aria-hidden="true">◐</span>
|
||||
<strong>Roast Planner</strong>
|
||||
</div>
|
||||
<h1>Set a new password</h1>
|
||||
<div id="message" class="auth-message" role="alert"></div>
|
||||
<form id="reset-form">
|
||||
<label
|
||||
>New password
|
||||
<input
|
||||
class="field-input"
|
||||
required
|
||||
type="password"
|
||||
minlength="12"
|
||||
name="password"
|
||||
autocomplete="new-password"
|
||||
/></label>
|
||||
<label
|
||||
>Confirm password
|
||||
<input
|
||||
class="field-input"
|
||||
required
|
||||
type="password"
|
||||
minlength="12"
|
||||
name="confirmPassword"
|
||||
autocomplete="new-password"
|
||||
/></label>
|
||||
<p class="muted">Use at least 12 characters.</p>
|
||||
<button class="primary-btn" type="submit">Set password</button>
|
||||
</form>
|
||||
<div class="auth-links">
|
||||
<a href="/login">Back to log in</a>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<script type="module" src="/js/reset.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,63 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Administrator setup — Roast Planner</title>
|
||||
<link rel="stylesheet" href="/app.css" />
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
|
||||
<meta name="theme-color" content="#A8481A" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="auth-page">
|
||||
<section class="panel-card auth-card">
|
||||
<div class="auth-brand">
|
||||
<span class="brand-mark" aria-hidden="true">◐</span>
|
||||
<strong>Roast Planner</strong>
|
||||
</div>
|
||||
<h1>Create the administrator account</h1>
|
||||
<p class="lede">
|
||||
This runs once, before anyone else can sign up. You'll need the
|
||||
setup token from the deployment environment.
|
||||
</p>
|
||||
<div id="message" class="auth-message" role="alert"></div>
|
||||
<form id="setup-form">
|
||||
<label
|
||||
>Administrator email
|
||||
<input
|
||||
class="field-input"
|
||||
required
|
||||
type="email"
|
||||
name="email"
|
||||
value="[email protected]"
|
||||
readonly
|
||||
/></label>
|
||||
<label
|
||||
>Password
|
||||
<input
|
||||
class="field-input"
|
||||
required
|
||||
type="password"
|
||||
minlength="12"
|
||||
name="password"
|
||||
autocomplete="new-password"
|
||||
/></label>
|
||||
<label
|
||||
>Setup token
|
||||
<input
|
||||
class="field-input"
|
||||
required
|
||||
type="password"
|
||||
name="setupToken"
|
||||
autocomplete="off"
|
||||
/></label>
|
||||
<button class="primary-btn" type="submit">Create administrator</button>
|
||||
</form>
|
||||
<div class="auth-links">
|
||||
<a href="/login">Back to log in</a>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<script type="module" src="/js/setup.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,60 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>Create an account — Roast Planner</title>
|
||||
<link rel="stylesheet" href="/app.css" />
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
|
||||
<meta name="theme-color" content="#A8481A" />
|
||||
</head>
|
||||
<body>
|
||||
<main class="auth-page">
|
||||
<section class="panel-card auth-card">
|
||||
<div class="auth-brand">
|
||||
<span class="brand-mark" aria-hidden="true">◐</span>
|
||||
<strong>Roast Planner</strong>
|
||||
</div>
|
||||
<h1 id="signup-title">Create an account</h1>
|
||||
<div id="message" class="auth-message" role="alert"></div>
|
||||
<form id="signup-form" class="hidden">
|
||||
<label
|
||||
>Email
|
||||
<input
|
||||
class="field-input"
|
||||
required
|
||||
type="email"
|
||||
name="email"
|
||||
autocomplete="email"
|
||||
/></label>
|
||||
<label
|
||||
>Password
|
||||
<input
|
||||
class="field-input"
|
||||
required
|
||||
type="password"
|
||||
minlength="12"
|
||||
name="password"
|
||||
autocomplete="new-password"
|
||||
/></label>
|
||||
<label
|
||||
>Confirm password
|
||||
<input
|
||||
class="field-input"
|
||||
required
|
||||
type="password"
|
||||
minlength="12"
|
||||
name="confirmPassword"
|
||||
autocomplete="new-password"
|
||||
/></label>
|
||||
<p class="muted">Use at least 12 characters.</p>
|
||||
<button class="primary-btn" type="submit">Create account</button>
|
||||
</form>
|
||||
<div class="auth-links">
|
||||
<a href="/login">Already have an account?</a>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<script type="module" src="/js/signup.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+19
-12
@@ -1,15 +1,22 @@
|
||||
const CACHE_NAME = "roast-planner-static-v4";
|
||||
const CACHE_NAME = "roast-planner-static-v6";
|
||||
// Only /app is precached as a navigable page: it is a data-free authenticated shell (draft
|
||||
// data lives only in account-scoped local storage, and logout clears that namespace), so it is
|
||||
// the one page that is both safe and useful to relaunch offline. The marketing page, auth
|
||||
// pages, account, admin, inventory, and cupping all depend on the network (auth checks, live
|
||||
// data) and are deliberately left off this list rather than cached in a way that could show
|
||||
// stale content.
|
||||
const APP_SHELL = [
|
||||
"/",
|
||||
"/landing.html",
|
||||
"/app",
|
||||
"/app.css",
|
||||
"/worksheet.css",
|
||||
"/manifest.webmanifest",
|
||||
"/icon.svg",
|
||||
"/js/main.js",
|
||||
"/js/landing.js",
|
||||
"/js/admin.js",
|
||||
"/js/api.js",
|
||||
"/js/nav.js",
|
||||
"/js/toast.js",
|
||||
"/js/why-panels.js",
|
||||
"/js/lot-picker.js",
|
||||
"/js/prefill-ui.js",
|
||||
"/js/alog-ui.js",
|
||||
"/js/print.js",
|
||||
@@ -18,6 +25,7 @@ const APP_SHELL = [
|
||||
"/shared/time.js",
|
||||
"/shared/reference-data.js",
|
||||
"/shared/curve.js",
|
||||
"/shared/cupping.js",
|
||||
];
|
||||
|
||||
self.addEventListener("install", (event) => {
|
||||
@@ -57,14 +65,13 @@ self.addEventListener("fetch", (event) => {
|
||||
return;
|
||||
|
||||
if (request.mode === "navigate") {
|
||||
// /app is a data-free authenticated shell: draft data lives only in account-scoped
|
||||
// local storage and logout clears that namespace. This makes offline relaunch useful
|
||||
// without ever caching account data or API responses.
|
||||
// Only /app has a meaningful offline shell (see APP_SHELL comment above); every other
|
||||
// page requires the network anyway, so let those navigations fail normally when offline
|
||||
// rather than risk serving stale auth/account/admin content.
|
||||
if (url.pathname !== "/app") return;
|
||||
event.respondWith(
|
||||
fetch(request).catch(() =>
|
||||
url.pathname === "/app"
|
||||
? caches.match("/app")
|
||||
: caches.match("/landing.html"),
|
||||
fetch(request).catch(
|
||||
async () => (await caches.match("/app")) || Response.error(),
|
||||
),
|
||||
);
|
||||
return;
|
||||
|
||||
+1219
-51
File diff suppressed because it is too large
Load Diff
+5
-1
@@ -13,7 +13,11 @@ export function createDb(connectionString = process.env.DATABASE_URL) {
|
||||
? { rejectUnauthorized: true }
|
||||
: undefined,
|
||||
});
|
||||
return { query: (...args) => pool.query(...args), close: () => pool.end() };
|
||||
return {
|
||||
query: (...args) => pool.query(...args),
|
||||
connect: () => pool.connect(),
|
||||
close: () => pool.end(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Apply each versioned SQL file once; failed migrations are not recorded. */
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
/** Sends transactional email via SMTP when configured; the caller decides what to do when this
|
||||
* returns false (e.g. log the link so an admin can hand it to the user manually). */
|
||||
export async function sendMail({ smtpUrl, from, to, subject, text }) {
|
||||
if (!smtpUrl) return false;
|
||||
const { default: nodemailer } = await import("nodemailer");
|
||||
const transporter = nodemailer.createTransport(smtpUrl);
|
||||
await transporter.sendMail({ from, to, subject, text });
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
// Browser-safe ESM (served at /shared/, imported by both server and client — no Node-only
|
||||
// APIs) — the single implementation of cupping scoring/validation. The server always
|
||||
// recomputes the total from coerceSession's output; a client-submitted total is never trusted.
|
||||
//
|
||||
// FLAVOR_TAXONOMY is an ORIGINAL taxonomy for this project: the family/subgroup/descriptor
|
||||
// list and id strings are our own, deliberately not a transcription of the copyrighted
|
||||
// SCA/WCR Coffee Taster's Flavor Wheel graphic or its exact category boundaries/wording.
|
||||
|
||||
export const SCORE_ATTRS = [
|
||||
"fragrance_aroma",
|
||||
"flavor",
|
||||
"aftertaste",
|
||||
"acidity",
|
||||
"body",
|
||||
"balance",
|
||||
"overall",
|
||||
];
|
||||
|
||||
export const SCORE_LABELS = {
|
||||
fragrance_aroma: "Fragrance/Aroma",
|
||||
flavor: "Flavor",
|
||||
aftertaste: "Aftertaste",
|
||||
acidity: "Acidity",
|
||||
body: "Body",
|
||||
balance: "Balance",
|
||||
overall: "Overall",
|
||||
};
|
||||
|
||||
export const TICK_ATTRS = ["uniformity", "clean_cup", "sweetness"];
|
||||
|
||||
export const TICK_LABELS = {
|
||||
uniformity: "Uniformity",
|
||||
clean_cup: "Clean cup",
|
||||
sweetness: "Sweetness",
|
||||
};
|
||||
|
||||
export const STAGE_IDS = [
|
||||
"dry_fragrance",
|
||||
"pour",
|
||||
"crust_aroma",
|
||||
"break",
|
||||
"skim",
|
||||
"taste_1",
|
||||
"taste_2",
|
||||
"taste_3",
|
||||
];
|
||||
|
||||
const STAGE_ORDER = Object.fromEntries(STAGE_IDS.map((s, i) => [s, i]));
|
||||
|
||||
export const DEFAULT_CUP_COUNT = 5;
|
||||
export const MAX_CUP_COUNT = 12;
|
||||
export const MAX_FLAVOR_TAGS = 32;
|
||||
export const MAX_NOTES_CHARS = 4000;
|
||||
const MAX_STAGE_ELAPSED_SEC = 24 * 60 * 60;
|
||||
|
||||
// 1-3 dot-separated segments, lowercase alnum(+underscore) in EVERY segment — three family
|
||||
// ids (nutty_cocoa, green_vegetal, fermented_sour) have an underscore in the first segment.
|
||||
const FLAVOR_ID_RE = /^[a-z0-9_]+(\.[a-z0-9_]+){0,2}$/;
|
||||
|
||||
export const FLAVOR_TAXONOMY = {
|
||||
fruity: {
|
||||
label: "Fruity",
|
||||
subgroups: {
|
||||
berry: ["blueberry", "blackberry", "strawberry"],
|
||||
citrus: ["orange", "lemon", "grapefruit"],
|
||||
stone_fruit: ["peach", "apricot", "cherry"],
|
||||
dried_fruit: ["raisin", "fig", "prune"],
|
||||
},
|
||||
},
|
||||
floral: {
|
||||
label: "Floral",
|
||||
subgroups: {
|
||||
blossom: ["jasmine", "orange_blossom", "chamomile"],
|
||||
herbal_floral: ["lavender", "rose"],
|
||||
},
|
||||
},
|
||||
sweet: {
|
||||
label: "Sweet",
|
||||
subgroups: {
|
||||
sugars: ["brown_sugar", "honey", "caramel"],
|
||||
vanilla: ["vanilla", "malt"],
|
||||
},
|
||||
},
|
||||
nutty_cocoa: {
|
||||
label: "Nutty / Cocoa",
|
||||
subgroups: {
|
||||
nutty: ["almond", "hazelnut", "peanut"],
|
||||
cocoa: ["dark_chocolate", "cocoa_powder"],
|
||||
},
|
||||
},
|
||||
spice: {
|
||||
label: "Spice",
|
||||
subgroups: {
|
||||
warm_spice: ["cinnamon", "clove", "nutmeg"],
|
||||
pungent: ["pepper", "anise"],
|
||||
},
|
||||
},
|
||||
roasted: {
|
||||
label: "Roasted",
|
||||
subgroups: {
|
||||
grain: ["toast", "cereal"],
|
||||
char: ["smoky", "tobacco", "pipe_tobacco"],
|
||||
},
|
||||
},
|
||||
green_vegetal: {
|
||||
label: "Green / Vegetal",
|
||||
subgroups: {
|
||||
fresh: ["cut_grass", "leafy", "herbaceous"],
|
||||
raw: ["beany", "peapod"],
|
||||
},
|
||||
},
|
||||
fermented_sour: {
|
||||
label: "Fermented / Sour",
|
||||
subgroups: {
|
||||
sour: ["citric", "acetic", "tart"],
|
||||
fermented: ["winey", "boozy", "overripe"],
|
||||
},
|
||||
},
|
||||
other: {
|
||||
label: "Other",
|
||||
subgroups: {
|
||||
chemical: ["rubber", "medicinal"],
|
||||
papery: ["papery", "musty", "woody"],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const snapQuarter = (v) => Math.round(v * 4) / 4;
|
||||
|
||||
export function blankSession(cupCount = DEFAULT_CUP_COUNT) {
|
||||
return {
|
||||
cup_count: cupCount,
|
||||
scores: Object.fromEntries(SCORE_ATTRS.map((a) => [a, 0])),
|
||||
ticks: Object.fromEntries(TICK_ATTRS.map((a) => [a, 0])),
|
||||
taint_cups: 0,
|
||||
fault_cups: 0,
|
||||
flavor_tags: [],
|
||||
stage_marks: [],
|
||||
ritual_started_at_iso: "",
|
||||
notes: "",
|
||||
};
|
||||
}
|
||||
|
||||
/** total = sum(scored attrs) + 10*ticks/cupCount per tick attr - 2*taint - 4*fault, floored
|
||||
* at 0, rounded to 2dp. Pure arithmetic over whatever it's handed — call coerceSession first. */
|
||||
export function computeTotalScore(scores, ticks, taintCups, faultCups, cupCount) {
|
||||
let total = SCORE_ATTRS.reduce((sum, a) => sum + Number(scores?.[a] ?? 0), 0);
|
||||
const cc = Number(cupCount);
|
||||
if (cc > 0)
|
||||
total += TICK_ATTRS.reduce((sum, a) => sum + (10 * Number(ticks?.[a] ?? 0)) / cc, 0);
|
||||
total -= 2 * Number(taintCups ?? 0);
|
||||
total -= 4 * Number(faultCups ?? 0);
|
||||
total = Math.max(0, total);
|
||||
return Math.round(total * 100) / 100;
|
||||
}
|
||||
|
||||
/** Validates and clamps a session document. Throws Error with a human message on genuinely
|
||||
* bad input (malformed flavor id, unknown stage, too many tags); everything else is clamped. */
|
||||
export function coerceSession(session) {
|
||||
const raw = session && typeof session === "object" ? session : {};
|
||||
|
||||
// Tolerant of a missing cup_count (defaults it), same stance as every other field below —
|
||||
// but a *present and garbage* value (NaN, a string, etc.) is a genuine client bug, not an
|
||||
// absent field, so that still throws rather than silently defaulting.
|
||||
const cupCountRaw = raw.cup_count == null ? DEFAULT_CUP_COUNT : Number(raw.cup_count);
|
||||
if (!Number.isFinite(cupCountRaw)) throw new Error("cup_count must be a finite number");
|
||||
const cup_count = Math.max(1, Math.min(MAX_CUP_COUNT, Math.round(cupCountRaw)));
|
||||
|
||||
const scores = {};
|
||||
for (const attr of SCORE_ATTRS) {
|
||||
const f = Number(raw.scores?.[attr] ?? 0);
|
||||
if (!Number.isFinite(f)) throw new Error(`${attr} must be a finite number`);
|
||||
scores[attr] = f <= 0 ? 0 : Math.round(snapQuarter(Math.max(6, Math.min(10, f))) * 100) / 100;
|
||||
}
|
||||
|
||||
const ticks = {};
|
||||
for (const attr of TICK_ATTRS) {
|
||||
const f = Number(raw.ticks?.[attr] ?? 0);
|
||||
if (!Number.isFinite(f)) throw new Error(`${attr} must be a finite number`);
|
||||
ticks[attr] = Math.max(0, Math.min(cup_count, Math.round(f)));
|
||||
}
|
||||
|
||||
const taintRaw = Number(raw.taint_cups ?? 0);
|
||||
if (!Number.isFinite(taintRaw)) throw new Error("taint_cups must be a finite number");
|
||||
const taint_cups = Math.max(0, Math.min(cup_count, Math.round(taintRaw)));
|
||||
|
||||
const faultRaw = Number(raw.fault_cups ?? 0);
|
||||
if (!Number.isFinite(faultRaw)) throw new Error("fault_cups must be a finite number");
|
||||
const fault_cups = Math.max(0, Math.min(cup_count, Math.round(faultRaw)));
|
||||
|
||||
const notes = String(raw.notes ?? "").slice(0, MAX_NOTES_CHARS);
|
||||
|
||||
const flavor_tags = [];
|
||||
const seen = new Set();
|
||||
for (const tag of Array.isArray(raw.flavor_tags) ? raw.flavor_tags : []) {
|
||||
if (typeof tag !== "string" || !FLAVOR_ID_RE.test(tag))
|
||||
throw new Error(`invalid flavor tag id: ${JSON.stringify(tag)}`);
|
||||
if (seen.has(tag)) continue;
|
||||
seen.add(tag);
|
||||
flavor_tags.push(tag);
|
||||
}
|
||||
if (flavor_tags.length > MAX_FLAVOR_TAGS)
|
||||
throw new Error(
|
||||
`at most ${MAX_FLAVOR_TAGS} flavor tags allowed, got ${flavor_tags.length} (after de-duplication)`,
|
||||
);
|
||||
|
||||
const markByStage = {};
|
||||
for (const mark of Array.isArray(raw.stage_marks) ? raw.stage_marks : []) {
|
||||
const stage = mark?.stage;
|
||||
// Object.hasOwn, not `in` — `in` walks the prototype chain, so a stage value of
|
||||
// "toString"/"constructor"/etc. would pass validation and later corrupt the sort below
|
||||
// (STAGE_ORDER["toString"] is a function, not a number).
|
||||
if (!Object.hasOwn(STAGE_ORDER, stage))
|
||||
throw new Error(`unknown cupping stage: ${JSON.stringify(stage)}`);
|
||||
const elapsedRaw = Number(mark.elapsed_sec);
|
||||
if (!Number.isFinite(elapsedRaw)) throw new Error("elapsed_sec must be a finite number");
|
||||
const elapsed_sec = Math.max(0, Math.min(MAX_STAGE_ELAPSED_SEC, elapsedRaw));
|
||||
markByStage[stage] = {
|
||||
stage,
|
||||
elapsed_sec,
|
||||
marked_at_iso: String(mark.marked_at_iso ?? ""),
|
||||
};
|
||||
}
|
||||
const stage_marks = Object.values(markByStage).sort(
|
||||
(a, b) => STAGE_ORDER[a.stage] - STAGE_ORDER[b.stage],
|
||||
);
|
||||
|
||||
return {
|
||||
cup_count,
|
||||
scores,
|
||||
ticks,
|
||||
taint_cups,
|
||||
fault_cups,
|
||||
notes,
|
||||
flavor_tags,
|
||||
stage_marks,
|
||||
ritual_started_at_iso: String(raw.ritual_started_at_iso ?? ""),
|
||||
};
|
||||
}
|
||||
@@ -55,6 +55,7 @@ export function blankPlan() {
|
||||
sanityOverride: { drying: null, maillard: null, dtr: null, ceiling: null },
|
||||
reference: null,
|
||||
prefill: null,
|
||||
inventory: { lotId: "", lotLabel: "", consumed: null },
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+454
-64
@@ -1,77 +1,66 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import crypto from "node:crypto";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import request from "supertest";
|
||||
import { newDb } from "pg-mem";
|
||||
import { createApp } from "../server/app.js";
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const password = "this is a long password";
|
||||
|
||||
async function setup() {
|
||||
const mem = newDb();
|
||||
mem.public.registerFunction({
|
||||
name: "gen_random_uuid",
|
||||
returns: "uuid",
|
||||
implementation: () => crypto.randomUUID(),
|
||||
impure: true,
|
||||
});
|
||||
const pg = mem.adapters.createPg();
|
||||
const db = new pg.Pool();
|
||||
await db.query(
|
||||
`CREATE TABLE users(id uuid PRIMARY KEY DEFAULT gen_random_uuid(),email text UNIQUE NOT NULL,password_hash text NOT NULL,role text NOT NULL DEFAULT 'user',created_at timestamptz DEFAULT now()); CREATE TABLE sessions(token_hash text PRIMARY KEY,user_id uuid NOT NULL REFERENCES users(id),csrf_hash text NOT NULL,expires_at timestamptz NOT NULL,created_at timestamptz DEFAULT now()); CREATE TABLE roast_plans(id uuid PRIMARY KEY DEFAULT gen_random_uuid(),user_id uuid NOT NULL REFERENCES users(id),plan jsonb NOT NULL,created_at timestamptz DEFAULT now(),updated_at timestamptz DEFAULT now()); CREATE TABLE app_settings(key text PRIMARY KEY,value text NOT NULL); INSERT INTO app_settings VALUES('signup_enabled','true')`,
|
||||
);
|
||||
const app = createApp({
|
||||
db,
|
||||
root,
|
||||
env: {
|
||||
NODE_ENV: "test",
|
||||
BOOTSTRAP_SETUP_TOKEN: "a-secure-bootstrap-token",
|
||||
},
|
||||
});
|
||||
return { db, app, agent: request.agent(app) };
|
||||
}
|
||||
|
||||
async function signup(agent, email) {
|
||||
const response = await agent
|
||||
.post("/api/auth/signup")
|
||||
.send({ email, password });
|
||||
return { response, csrf: response.body.csrfToken };
|
||||
}
|
||||
import { root, password, setup, signup } from "./helpers.js";
|
||||
|
||||
test("strict CSP/static modules, no-store data, auth lifecycle, and ownership share one database", async () => {
|
||||
const { db, app, agent: first } = await setup();
|
||||
const second = request.agent(app);
|
||||
const anonymous = request.agent(app);
|
||||
|
||||
const landing = await anonymous.get("/");
|
||||
assert.equal(landing.status, 200);
|
||||
const marketing = await anonymous.get("/");
|
||||
assert.equal(marketing.status, 200);
|
||||
assert.match(
|
||||
landing.headers["content-security-policy"],
|
||||
marketing.headers["content-security-policy"],
|
||||
/default-src 'self'/,
|
||||
);
|
||||
assert.doesNotMatch(
|
||||
landing.headers["content-security-policy"],
|
||||
marketing.headers["content-security-policy"],
|
||||
/(?:default-src|script-src)[^;]*unsafe-inline/,
|
||||
);
|
||||
assert.match(marketing.text, /Get started/);
|
||||
|
||||
const login = await anonymous.get("/login");
|
||||
assert.equal(login.status, 200);
|
||||
assert.match(
|
||||
landing.text,
|
||||
/<script type="module" src="\/js\/landing\.js"><\/script>/,
|
||||
login.text,
|
||||
/<script type="module" src="\/js\/login\.js"><\/script>/,
|
||||
);
|
||||
assert.doesNotMatch(landing.text, /<script type="module">/);
|
||||
assert.equal((await anonymous.get("/signup")).status, 200);
|
||||
assert.equal((await anonymous.get("/forgot")).status, 200);
|
||||
assert.equal((await anonymous.get("/reset")).status, 200);
|
||||
assert.equal((await anonymous.get("/api/auth/signup-enabled")).body.enabled, true);
|
||||
|
||||
// Page routes redirect a signed-out browser navigation to /login (never a bare JSON 401 —
|
||||
// that's only for /api/* callers) but the API underneath stays strictly 401/no-store.
|
||||
const adminHtml = await anonymous.get("/admin");
|
||||
assert.equal(adminHtml.status, 401);
|
||||
assert.equal(adminHtml.status, 302);
|
||||
assert.equal(adminHtml.headers.location, "/login");
|
||||
assert.equal(adminHtml.headers["cache-control"], "no-store, private");
|
||||
const accountHtml = await anonymous.get("/account");
|
||||
assert.equal(accountHtml.status, 302);
|
||||
assert.equal(accountHtml.headers.location, "/login");
|
||||
const appHtml = await anonymous.get("/app");
|
||||
assert.equal(appHtml.status, 302);
|
||||
assert.equal(appHtml.headers.location, "/login");
|
||||
assert.equal((await anonymous.get("/api/plans")).status, 401);
|
||||
assert.equal(
|
||||
(await anonymous.get("/api/plans")).headers["cache-control"],
|
||||
"no-store, private",
|
||||
);
|
||||
// Protected HTML shells are never reachable by static filename, only through their routes —
|
||||
// including percent-encoded and repeated-slash variants that bypass an undecoded string
|
||||
// comparison but still resolve to the same file once express.static decodes them.
|
||||
assert.equal((await anonymous.get("/index.html")).status, 302);
|
||||
assert.equal((await anonymous.get("/admin.html")).status, 302);
|
||||
assert.equal((await anonymous.get("/account.html")).status, 302);
|
||||
assert.equal((await anonymous.get("/%69ndex.html")).status, 302);
|
||||
assert.equal((await anonymous.get("//index.html")).status, 302);
|
||||
|
||||
assert.match(
|
||||
(await anonymous.get("/js/admin.js")).text,
|
||||
/async function load/,
|
||||
/loadNavUser/,
|
||||
);
|
||||
const mainScript = await anonymous.get("/js/main.js");
|
||||
assert.match(mainScript.text, /roastPlannerPlan\.v2/);
|
||||
@@ -80,7 +69,7 @@ test("strict CSP/static modules, no-store data, auth lifecycle, and ownership sh
|
||||
assert.match(serviceWorker, /data-free authenticated shell/);
|
||||
assert.match(
|
||||
serviceWorker,
|
||||
/url\.pathname === "\/app"[\s\S]*caches\.match\("\/app"\)/,
|
||||
/if \(url\.pathname !== "\/app"\) return;[\s\S]*caches\.match\("\/app"\)/,
|
||||
);
|
||||
assert.match(serviceWorker, /logout clears that namespace/);
|
||||
|
||||
@@ -88,6 +77,11 @@ test("strict CSP/static modules, no-store data, auth lifecycle, and ownership sh
|
||||
const two = await signup(second, "[email protected]");
|
||||
assert.equal(one.response.status, 201);
|
||||
assert.equal(two.response.status, 201);
|
||||
|
||||
// A signed-in visitor is bounced off the public auth pages straight to /app.
|
||||
assert.equal((await first.get("/login")).status, 302);
|
||||
assert.equal((await first.get("/")).status, 302);
|
||||
|
||||
const plan = await first
|
||||
.post("/api/plans")
|
||||
.set("x-csrf-token", one.csrf)
|
||||
@@ -106,29 +100,62 @@ test("strict CSP/static modules, no-store data, auth lifecycle, and ownership sh
|
||||
).status,
|
||||
404,
|
||||
);
|
||||
assert.equal((await second.get("/api/plans")).body.plans.length, 0);
|
||||
|
||||
const login = request.agent(app);
|
||||
// A non-UUID id is a clean 404, not a 500 from the database driver.
|
||||
assert.equal(
|
||||
(
|
||||
await login
|
||||
await first
|
||||
.put("/api/plans/not-a-uuid")
|
||||
.set("x-csrf-token", one.csrf)
|
||||
.send({ plan: {} })
|
||||
).status,
|
||||
404,
|
||||
);
|
||||
// PUT validates the plan body just like POST does.
|
||||
assert.equal(
|
||||
(
|
||||
await first
|
||||
.put(`/api/plans/${plan.body.plan.id}`)
|
||||
.set("x-csrf-token", one.csrf)
|
||||
.send({ plan: null })
|
||||
).status,
|
||||
400,
|
||||
);
|
||||
assert.equal((await second.get("/api/plans")).body.plans.length, 0);
|
||||
// A signed-in non-admin visiting /admin lands back in the app, not a bare 403 JSON page.
|
||||
const nonAdminVisitsAdmin = await second.get("/admin");
|
||||
assert.equal(nonAdminVisitsAdmin.status, 302);
|
||||
assert.equal(nonAdminVisitsAdmin.headers.location, "/app");
|
||||
assert.equal(
|
||||
(
|
||||
await second
|
||||
.delete(`/api/plans/${plan.body.plan.id}`)
|
||||
.set("x-csrf-token", two.csrf)
|
||||
).status,
|
||||
404,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await first
|
||||
.delete(`/api/plans/${plan.body.plan.id}`)
|
||||
.set("x-csrf-token", one.csrf)
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
assert.equal((await first.get("/api/plans")).body.plans.length, 0);
|
||||
|
||||
const loginAgent = request.agent(app);
|
||||
assert.equal(
|
||||
(
|
||||
await loginAgent
|
||||
.post("/api/auth/login")
|
||||
.send({ email: "[email protected]", password })
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
assert.equal((await login.get("/api/auth/me")).status, 200);
|
||||
const loginCsrf = (
|
||||
await login
|
||||
.post("/api/auth/login")
|
||||
.send({ email: "[email protected]", password })
|
||||
).body.csrfToken;
|
||||
assert.equal(
|
||||
(await login.post("/api/auth/logout").set("x-csrf-token", loginCsrf))
|
||||
.status,
|
||||
200,
|
||||
);
|
||||
assert.equal((await login.get("/api/auth/me")).status, 401);
|
||||
assert.equal((await loginAgent.get("/api/auth/me")).status, 200);
|
||||
// Logout succeeds even without a valid CSRF token (it can only end the caller's own session).
|
||||
assert.equal((await loginAgent.post("/api/auth/logout")).status, 200);
|
||||
assert.equal((await loginAgent.get("/api/auth/me")).status, 401);
|
||||
|
||||
const admin = await first.post("/api/auth/bootstrap").send({
|
||||
email: "[email protected]",
|
||||
@@ -198,3 +225,366 @@ test("bootstrap token is optional after first setup and unavailable before setup
|
||||
409,
|
||||
);
|
||||
});
|
||||
|
||||
test("/setup redirects to /login once the administrator exists", async () => {
|
||||
const { app } = await setup();
|
||||
const agent = request.agent(app);
|
||||
assert.equal((await agent.get("/setup")).status, 200);
|
||||
await agent.post("/api/auth/bootstrap").send({
|
||||
email: "[email protected]",
|
||||
password,
|
||||
setupToken: "a-secure-bootstrap-token",
|
||||
});
|
||||
const fresh = request.agent(app);
|
||||
const setupResponse = await fresh.get("/setup");
|
||||
assert.equal(setupResponse.status, 302);
|
||||
assert.equal(setupResponse.headers.location, "/login");
|
||||
});
|
||||
|
||||
test("forgot/reset password issues a working link without leaking account existence", async () => {
|
||||
const { app } = await setup();
|
||||
const memberAgent = request.agent(app);
|
||||
await signup(memberAgent, "[email protected]");
|
||||
const admin = request.agent(app);
|
||||
await admin.post("/api/auth/bootstrap").send({
|
||||
email: "[email protected]",
|
||||
password,
|
||||
setupToken: "a-secure-bootstrap-token",
|
||||
});
|
||||
|
||||
const unknown = await request(app)
|
||||
.post("/api/auth/forgot")
|
||||
.send({ email: "[email protected]" });
|
||||
assert.equal(unknown.status, 200);
|
||||
const known = await request(app)
|
||||
.post("/api/auth/forgot")
|
||||
.send({ email: "[email protected]" });
|
||||
assert.equal(known.status, 200);
|
||||
assert.deepEqual(known.body, unknown.body);
|
||||
|
||||
const pending = await admin.get("/api/admin/password-resets");
|
||||
assert.equal(pending.status, 200);
|
||||
const entry = pending.body.links.find((l) => l.email === "[email protected]");
|
||||
assert.ok(entry, "expected a pending reset link for [email protected]");
|
||||
const token = new URL(entry.url, "http://x").searchParams.get("token");
|
||||
|
||||
assert.equal(
|
||||
(
|
||||
await request(app)
|
||||
.post("/api/auth/reset")
|
||||
.send({ token: "wrong-token", password: "another long password" })
|
||||
).status,
|
||||
400,
|
||||
);
|
||||
const resetResponse = await request(app)
|
||||
.post("/api/auth/reset")
|
||||
.send({ token, password: "another long password" });
|
||||
assert.equal(resetResponse.status, 200);
|
||||
// The old password no longer works; the new one does.
|
||||
assert.equal(
|
||||
(
|
||||
await request(app)
|
||||
.post("/api/auth/login")
|
||||
.send({ email: "[email protected]", password })
|
||||
).status,
|
||||
401,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await request(app)
|
||||
.post("/api/auth/login")
|
||||
.send({ email: "[email protected]", password: "another long password" })
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
});
|
||||
|
||||
test("account: email change, password change, sessions, and self-delete", async () => {
|
||||
const { app } = await setup();
|
||||
const agent = request.agent(app);
|
||||
const { csrf } = await signup(agent, "[email protected]");
|
||||
|
||||
assert.equal(
|
||||
(
|
||||
await agent
|
||||
.put("/api/account/email")
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ email: "[email protected]", password: "wrong password wrong" })
|
||||
).status,
|
||||
401,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await agent
|
||||
.put("/api/account/email")
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ email: "[email protected]", password })
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
|
||||
const sessionsBefore = await agent.get("/api/account/sessions");
|
||||
assert.equal(sessionsBefore.body.sessions.length, 1);
|
||||
assert.equal(sessionsBefore.body.sessions[0].current, true);
|
||||
|
||||
assert.equal(
|
||||
(
|
||||
await agent
|
||||
.put("/api/account/password")
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ currentPassword: password, newPassword: "yet another long one" })
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
// Logging in with the old password now fails; the new one works.
|
||||
assert.equal(
|
||||
(
|
||||
await request(app)
|
||||
.post("/api/auth/login")
|
||||
.send({ email: "[email protected]", password })
|
||||
).status,
|
||||
401,
|
||||
);
|
||||
const relogin = request.agent(app);
|
||||
assert.equal(
|
||||
(
|
||||
await relogin
|
||||
.post("/api/auth/login")
|
||||
.send({ email: "[email protected]", password: "yet another long one" })
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
(
|
||||
await agent
|
||||
.delete("/api/account")
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ password: "yet another long one" })
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await request(app)
|
||||
.post("/api/auth/login")
|
||||
.send({ email: "[email protected]", password: "yet another long one" })
|
||||
).status,
|
||||
401,
|
||||
);
|
||||
});
|
||||
|
||||
test("the bootstrap admin's email is reserved and fixed, and the bootstrap admin cannot delete themself even as a second admin exists", async () => {
|
||||
const { app } = await setup();
|
||||
|
||||
// Nobody can claim the reserved email via plain signup before bootstrap ever runs.
|
||||
assert.equal(
|
||||
(
|
||||
await request(app)
|
||||
.post("/api/auth/signup")
|
||||
.send({ email: "[email protected]", password })
|
||||
).status,
|
||||
409,
|
||||
);
|
||||
|
||||
const bootstrapAgent = request.agent(app);
|
||||
const admin = await bootstrapAgent.post("/api/auth/bootstrap").send({
|
||||
email: "[email protected]",
|
||||
password,
|
||||
setupToken: "a-secure-bootstrap-token",
|
||||
});
|
||||
assert.equal(admin.status, 201);
|
||||
|
||||
// Someone else still can't claim it after bootstrap (this would also just 409 on the
|
||||
// column's UNIQUE constraint, but the reserved-email check must fire first regardless).
|
||||
const otherAgent = request.agent(app);
|
||||
const { csrf: otherCsrf } = await signup(otherAgent, "[email protected]");
|
||||
assert.equal(
|
||||
(
|
||||
await otherAgent
|
||||
.put("/api/account/email")
|
||||
.set("x-csrf-token", otherCsrf)
|
||||
.send({ email: "[email protected]", password })
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
|
||||
// The bootstrap admin can't change away from the reserved email either — that would strip
|
||||
// every other guard's protection for this account.
|
||||
assert.equal(
|
||||
(
|
||||
await bootstrapAgent
|
||||
.put("/api/account/email")
|
||||
.set("x-csrf-token", admin.body.csrfToken)
|
||||
.send({ email: "[email protected]", password })
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
|
||||
// Promote a second admin, then confirm the bootstrap admin still can't delete themself even
|
||||
// though the "last admin" count check alone would otherwise allow it.
|
||||
const secondAgent = request.agent(app);
|
||||
await signup(secondAgent, "[email protected]");
|
||||
const secondId = (
|
||||
await bootstrapAgent.get("/api/admin/users")
|
||||
).body.users.find((u) => u.email === "[email protected]").id;
|
||||
await bootstrapAgent
|
||||
.put(`/api/admin/users/${secondId}/role`)
|
||||
.set("x-csrf-token", admin.body.csrfToken)
|
||||
.send({ role: "admin" });
|
||||
assert.equal(
|
||||
(
|
||||
await bootstrapAgent
|
||||
.delete("/api/account")
|
||||
.set("x-csrf-token", admin.body.csrfToken)
|
||||
.send({ password })
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
assert.equal((await bootstrapAgent.get("/api/auth/me")).status, 200);
|
||||
});
|
||||
|
||||
test("password-reset links for admin accounts never appear in the shared admin panel", async () => {
|
||||
const { app } = await setup();
|
||||
const bootstrapAgent = request.agent(app);
|
||||
const admin = await bootstrapAgent.post("/api/auth/bootstrap").send({
|
||||
email: "[email protected]",
|
||||
password,
|
||||
setupToken: "a-secure-bootstrap-token",
|
||||
});
|
||||
const secondAgent = request.agent(app);
|
||||
await signup(secondAgent, "[email protected]");
|
||||
const secondId = (
|
||||
await bootstrapAgent.get("/api/admin/users")
|
||||
).body.users.find((u) => u.email === "[email protected]").id;
|
||||
await bootstrapAgent
|
||||
.put(`/api/admin/users/${secondId}/role`)
|
||||
.set("x-csrf-token", admin.body.csrfToken)
|
||||
.send({ role: "admin" });
|
||||
|
||||
// The second admin requests a reset for the bootstrap admin's own account...
|
||||
await request(app)
|
||||
.post("/api/auth/forgot")
|
||||
.send({ email: "[email protected]" });
|
||||
// ...but that link must never surface in the panel any admin (including this one) can read —
|
||||
// otherwise a second admin could take over the account every other guard protects.
|
||||
const pending = await secondAgent.get("/api/admin/password-resets");
|
||||
assert.equal(pending.status, 200);
|
||||
assert.equal(
|
||||
pending.body.links.some((l) => l.email === "[email protected]"),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("admin: metrics, role changes, disable, delete, and audit trail", async () => {
|
||||
const { app } = await setup();
|
||||
const adminAgent = request.agent(app);
|
||||
const admin = await adminAgent.post("/api/auth/bootstrap").send({
|
||||
email: "[email protected]",
|
||||
password,
|
||||
setupToken: "a-secure-bootstrap-token",
|
||||
});
|
||||
const userAgent = request.agent(app);
|
||||
await signup(userAgent, "[email protected]");
|
||||
const userId = (
|
||||
await adminAgent.get("/api/admin/users")
|
||||
).body.users.find((u) => u.email === "[email protected]").id;
|
||||
|
||||
const metrics = await adminAgent.get("/api/admin/metrics");
|
||||
assert.equal(metrics.status, 200);
|
||||
assert.equal(metrics.body.metrics.totalUsers, 2);
|
||||
|
||||
// The bootstrap admin cannot be demoted, disabled, or deleted by another admin, or by itself.
|
||||
const bootstrapId = (
|
||||
await adminAgent.get("/api/admin/users")
|
||||
).body.users.find((u) => u.email === "[email protected]").id;
|
||||
assert.equal(
|
||||
(
|
||||
await adminAgent
|
||||
.put(`/api/admin/users/${bootstrapId}/role`)
|
||||
.set("x-csrf-token", admin.body.csrfToken)
|
||||
.send({ role: "user" })
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
|
||||
assert.equal(
|
||||
(
|
||||
await adminAgent
|
||||
.put(`/api/admin/users/${userId}/role`)
|
||||
.set("x-csrf-token", admin.body.csrfToken)
|
||||
.send({ role: "admin" })
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await adminAgent
|
||||
.put(`/api/admin/users/${userId}/disabled`)
|
||||
.set("x-csrf-token", admin.body.csrfToken)
|
||||
.send({ disabled: true })
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
// A disabled user's existing session stops working and cannot log back in.
|
||||
assert.equal((await userAgent.get("/api/auth/me")).status, 401);
|
||||
assert.equal(
|
||||
(
|
||||
await request(app)
|
||||
.post("/api/auth/login")
|
||||
.send({ email: "[email protected]", password })
|
||||
).status,
|
||||
401,
|
||||
);
|
||||
|
||||
const audit = await adminAgent.get("/api/admin/audit");
|
||||
assert.equal(audit.status, 200);
|
||||
assert.ok(audit.body.events.some((e) => e.action === "role_changed"));
|
||||
assert.ok(audit.body.events.some((e) => e.action === "user_disabled"));
|
||||
|
||||
assert.equal(
|
||||
(
|
||||
await adminAgent
|
||||
.delete(`/api/admin/users/${userId}`)
|
||||
.set("x-csrf-token", admin.body.csrfToken)
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
assert.equal((await adminAgent.get("/api/admin/metrics")).body.metrics.totalUsers, 1);
|
||||
});
|
||||
|
||||
test("login is locked out per-email after repeated failures, independent of source IP", async () => {
|
||||
// Uses distinct simulated client IPs (via a trust-proxy app instance) so the assertion
|
||||
// isolates the per-email lockout from the separate per-IP rate limiter.
|
||||
const { db } = await setup();
|
||||
const app = createApp({
|
||||
db,
|
||||
root,
|
||||
env: {
|
||||
NODE_ENV: "test",
|
||||
BOOTSTRAP_SETUP_TOKEN: "a-secure-bootstrap-token",
|
||||
TRUST_PROXY: true,
|
||||
},
|
||||
});
|
||||
await signup(request.agent(app), "[email protected]");
|
||||
for (let i = 0; i < 10; i++) {
|
||||
await request(app)
|
||||
.post("/api/auth/login")
|
||||
.set("X-Forwarded-For", `10.0.0.${i}`)
|
||||
.send({ email: "[email protected]", password: "wrong password wrong" });
|
||||
}
|
||||
// Further wrong guesses are locked out...
|
||||
const stillWrong = await request(app)
|
||||
.post("/api/auth/login")
|
||||
.set("X-Forwarded-For", "10.0.0.99")
|
||||
.send({ email: "[email protected]", password: "still not it either" });
|
||||
assert.equal(stillWrong.status, 429);
|
||||
assert.equal(stillWrong.body.code, "too_many_attempts");
|
||||
// ...but the lock never blocks the real owner: the correct password always gets them in,
|
||||
// so the lockout can only ever throttle guessing, never be weaponized to deny the owner.
|
||||
const legitimateLogin = await request(app)
|
||||
.post("/api/auth/login")
|
||||
.set("X-Forwarded-For", "10.0.0.100")
|
||||
.send({ email: "[email protected]", password });
|
||||
assert.equal(legitimateLogin.status, 200);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import request from "supertest";
|
||||
import { setup, signup } from "./helpers.js";
|
||||
import { computeTotalScore, SCORE_ATTRS, TICK_ATTRS } from "../shared/cupping.js";
|
||||
|
||||
async function bootstrapPlan(agent, csrf) {
|
||||
const r = await agent
|
||||
.post("/api/plans")
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ plan: { fields: { 0.1: "Test coffee" } } });
|
||||
return r.body.plan.id;
|
||||
}
|
||||
|
||||
test("cupping: auth and CSRF are required on every route", async () => {
|
||||
const { app } = await setup();
|
||||
const anon = request.agent(app);
|
||||
assert.equal((await anon.get("/api/cupping")).status, 401);
|
||||
assert.equal((await anon.post("/api/cupping").send({})).status, 401);
|
||||
|
||||
const agent = request.agent(app);
|
||||
const { csrf } = await signup(agent, "[email protected]");
|
||||
assert.equal((await agent.post("/api/cupping").send({})).status, 403);
|
||||
const created = await agent.post("/api/cupping").set("x-csrf-token", csrf).send({});
|
||||
assert.equal(created.status, 201);
|
||||
assert.equal(
|
||||
(await agent.put(`/api/cupping/${created.body.session.id}`).send({ data: {} })).status,
|
||||
403,
|
||||
);
|
||||
assert.equal((await agent.delete(`/api/cupping/${created.body.session.id}`)).status, 403);
|
||||
});
|
||||
|
||||
test("cupping: create (with and without a linked plan), list, and ownership isolation", async () => {
|
||||
const { app } = await setup();
|
||||
const first = request.agent(app);
|
||||
const second = request.agent(app);
|
||||
const { csrf: firstCsrf } = await signup(first, "[email protected]");
|
||||
await signup(second, "[email protected]");
|
||||
const planId = await bootstrapPlan(first, firstCsrf);
|
||||
|
||||
const linked = await first
|
||||
.post("/api/cupping")
|
||||
.set("x-csrf-token", firstCsrf)
|
||||
.send({ roastPlanId: planId, cupCount: 4 });
|
||||
assert.equal(linked.status, 201);
|
||||
assert.equal(linked.body.session.roastPlanId, planId);
|
||||
assert.equal(linked.body.session.data.cup_count, 4);
|
||||
assert.equal(linked.body.session.totalScore, 0);
|
||||
|
||||
const unlinked = await first.post("/api/cupping").set("x-csrf-token", firstCsrf).send({});
|
||||
assert.equal(unlinked.status, 201);
|
||||
assert.equal(unlinked.body.session.roastPlanId, null);
|
||||
|
||||
assert.equal((await first.get("/api/cupping")).body.sessions.length, 2);
|
||||
assert.equal((await second.get("/api/cupping")).body.sessions.length, 0);
|
||||
assert.equal((await second.get(`/api/cupping/${linked.body.session.id}`)).status, 404);
|
||||
|
||||
const filtered = await first.get(`/api/cupping?plan=${planId}`);
|
||||
assert.equal(filtered.body.sessions.length, 1);
|
||||
assert.equal(filtered.body.sessions[0].id, linked.body.session.id);
|
||||
});
|
||||
|
||||
test("cupping: creating against another user's plan is refused", async () => {
|
||||
const { app } = await setup();
|
||||
const owner = request.agent(app);
|
||||
const attacker = request.agent(app);
|
||||
const { csrf: ownerCsrf } = await signup(owner, "[email protected]");
|
||||
const { csrf: attackerCsrf } = await signup(attacker, "[email protected]");
|
||||
const planId = await bootstrapPlan(owner, ownerCsrf);
|
||||
const attempt = await attacker
|
||||
.post("/api/cupping")
|
||||
.set("x-csrf-token", attackerCsrf)
|
||||
.send({ roastPlanId: planId });
|
||||
assert.equal(attempt.status, 404);
|
||||
});
|
||||
|
||||
test("cupping: server always recomputes the total score and ignores a client-supplied value", async () => {
|
||||
const { app } = await setup();
|
||||
const agent = request.agent(app);
|
||||
const { csrf } = await signup(agent, "[email protected]");
|
||||
const session = (
|
||||
await agent.post("/api/cupping").set("x-csrf-token", csrf).send({ cupCount: 5 })
|
||||
).body.session;
|
||||
|
||||
const scores = Object.fromEntries(SCORE_ATTRS.map((a) => [a, 8]));
|
||||
const ticks = Object.fromEntries(TICK_ATTRS.map((a) => [a, 5]));
|
||||
const expected = computeTotalScore(scores, ticks, 1, 1, 5);
|
||||
|
||||
const saved = await agent
|
||||
.put(`/api/cupping/${session.id}`)
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({
|
||||
data: {
|
||||
cup_count: 5,
|
||||
scores,
|
||||
ticks,
|
||||
taint_cups: 1,
|
||||
fault_cups: 1,
|
||||
flavor_tags: ["fruity.berry.blueberry"],
|
||||
notes: "Bright and clean.",
|
||||
total_score: 999999, // must be discarded — the server recomputes it
|
||||
},
|
||||
});
|
||||
assert.equal(saved.status, 200);
|
||||
assert.equal(saved.body.session.totalScore, expected);
|
||||
assert.notEqual(expected, 999999);
|
||||
|
||||
const reloaded = await agent.get(`/api/cupping/${session.id}`);
|
||||
assert.equal(reloaded.body.session.totalScore, expected);
|
||||
assert.deepEqual(reloaded.body.session.data.flavor_tags, ["fruity.berry.blueberry"]);
|
||||
});
|
||||
|
||||
test("cupping: coerceSession validation errors surface as 400s", async () => {
|
||||
const { app } = await setup();
|
||||
const agent = request.agent(app);
|
||||
const { csrf } = await signup(agent, "[email protected]");
|
||||
const session = (await agent.post("/api/cupping").set("x-csrf-token", csrf).send({})).body
|
||||
.session;
|
||||
|
||||
const badFlavor = await agent
|
||||
.put(`/api/cupping/${session.id}`)
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ data: { flavor_tags: ["Not A Valid Id!"] } });
|
||||
assert.equal(badFlavor.status, 400);
|
||||
assert.equal(badFlavor.body.code, "bad_session");
|
||||
|
||||
const dedupedTags = await agent
|
||||
.put(`/api/cupping/${session.id}`)
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ data: { flavor_tags: Array.from({ length: 33 }, () => "other.chemical.rubber") } });
|
||||
// 33 identical tags dedupe to 1, so this specific input should NOT throw — verifies dedup
|
||||
// happens before the >32 check.
|
||||
assert.equal(dedupedTags.status, 200);
|
||||
assert.deepEqual(dedupedTags.body.session.data.flavor_tags, ["other.chemical.rubber"]);
|
||||
|
||||
// Build 33 genuinely distinct valid-shaped ids by walking the real taxonomy, to trip the
|
||||
// actual >32-after-dedup limit.
|
||||
const { FLAVOR_TAXONOMY } = await import("../shared/cupping.js");
|
||||
const manyValid = [];
|
||||
for (const [famId, fam] of Object.entries(FLAVOR_TAXONOMY)) {
|
||||
for (const [subId, descriptors] of Object.entries(fam.subgroups)) {
|
||||
for (const d of descriptors) manyValid.push(`${famId}.${subId}.${d}`);
|
||||
}
|
||||
}
|
||||
assert.ok(manyValid.length > 32);
|
||||
const overLimit = await agent
|
||||
.put(`/api/cupping/${session.id}`)
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ data: { flavor_tags: manyValid } });
|
||||
assert.equal(overLimit.status, 400);
|
||||
|
||||
const badStage = await agent
|
||||
.put(`/api/cupping/${session.id}`)
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ data: { stage_marks: [{ stage: "not_a_real_stage", elapsed_sec: 1 }] } });
|
||||
assert.equal(badStage.status, 400);
|
||||
|
||||
const notObject = await agent
|
||||
.put(`/api/cupping/${session.id}`)
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ data: "nope" });
|
||||
assert.equal(notObject.status, 400);
|
||||
});
|
||||
|
||||
test("cupping: scores clamp/snap and ticks clamp to cup count", async () => {
|
||||
const { app } = await setup();
|
||||
const agent = request.agent(app);
|
||||
const { csrf } = await signup(agent, "[email protected]");
|
||||
const session = (
|
||||
await agent.post("/api/cupping").set("x-csrf-token", csrf).send({ cupCount: 3 })
|
||||
).body.session;
|
||||
|
||||
const saved = await agent
|
||||
.put(`/api/cupping/${session.id}`)
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({
|
||||
data: {
|
||||
cup_count: 3,
|
||||
scores: { flavor: 11, acidity: 7.13, body: -1 },
|
||||
ticks: { uniformity: 99 },
|
||||
},
|
||||
});
|
||||
assert.equal(saved.status, 200);
|
||||
assert.equal(saved.body.session.data.scores.flavor, 10);
|
||||
assert.equal(saved.body.session.data.scores.acidity, 7.25);
|
||||
assert.equal(saved.body.session.data.scores.body, 0);
|
||||
assert.equal(saved.body.session.data.ticks.uniformity, 3);
|
||||
});
|
||||
|
||||
test("cupping: delete removes the session, and deleting the linked plan nulls roastPlanId instead of deleting the session", async () => {
|
||||
const { app } = await setup();
|
||||
const agent = request.agent(app);
|
||||
const { csrf } = await signup(agent, "[email protected]");
|
||||
const planId = await bootstrapPlan(agent, csrf);
|
||||
const session = (
|
||||
await agent
|
||||
.post("/api/cupping")
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ roastPlanId: planId })
|
||||
).body.session;
|
||||
|
||||
await agent.delete(`/api/plans/${planId}`).set("x-csrf-token", csrf);
|
||||
const afterPlanDelete = await agent.get(`/api/cupping/${session.id}`);
|
||||
assert.equal(afterPlanDelete.status, 200);
|
||||
assert.equal(afterPlanDelete.body.session.roastPlanId, null);
|
||||
|
||||
assert.equal(
|
||||
(await agent.delete(`/api/cupping/${session.id}`).set("x-csrf-token", csrf)).status,
|
||||
200,
|
||||
);
|
||||
assert.equal((await agent.get(`/api/cupping/${session.id}`)).status, 404);
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import crypto from "node:crypto";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import request from "supertest";
|
||||
import { newDb } from "pg-mem";
|
||||
import { createApp } from "../server/app.js";
|
||||
|
||||
export const root = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
"..",
|
||||
);
|
||||
export const password = "this is a long password";
|
||||
|
||||
export async function setup(env = {}) {
|
||||
const mem = newDb();
|
||||
mem.public.registerFunction({
|
||||
name: "gen_random_uuid",
|
||||
returns: "uuid",
|
||||
implementation: () => crypto.randomUUID(),
|
||||
impure: true,
|
||||
});
|
||||
const pg = mem.adapters.createPg();
|
||||
const db = new pg.Pool();
|
||||
await db.query(
|
||||
`CREATE TABLE users(id uuid PRIMARY KEY DEFAULT gen_random_uuid(),email text UNIQUE NOT NULL,password_hash text NOT NULL,role text NOT NULL DEFAULT 'user',created_at timestamptz DEFAULT now(),disabled_at timestamptz);
|
||||
CREATE TABLE sessions(token_hash text PRIMARY KEY,user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,csrf_hash text NOT NULL,expires_at timestamptz NOT NULL,created_at timestamptz DEFAULT now(),user_agent text,ip text,last_seen_at timestamptz);
|
||||
CREATE TABLE roast_plans(id uuid PRIMARY KEY DEFAULT gen_random_uuid(),user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,plan jsonb NOT NULL,created_at timestamptz DEFAULT now(),updated_at timestamptz DEFAULT now());
|
||||
CREATE TABLE app_settings(key text PRIMARY KEY,value text NOT NULL);
|
||||
INSERT INTO app_settings VALUES('signup_enabled','true');
|
||||
CREATE TABLE password_reset_tokens(token_hash text PRIMARY KEY,user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,expires_at timestamptz NOT NULL,created_at timestamptz DEFAULT now());
|
||||
CREATE TABLE audit_events(id uuid PRIMARY KEY DEFAULT gen_random_uuid(),actor_user_id uuid REFERENCES users(id) ON DELETE SET NULL,action text NOT NULL,target text,created_at timestamptz DEFAULT now());
|
||||
CREATE TABLE green_bean_lots(id uuid PRIMARY KEY DEFAULT gen_random_uuid(),user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,origin text NOT NULL,variety text NOT NULL DEFAULT '',process text NOT NULL DEFAULT '',producer text NOT NULL DEFAULT '',purchase_date date,initial_weight_g numeric NOT NULL,remaining_weight_g numeric NOT NULL,cost_total numeric,moisture_pct numeric,density_g_l numeric,notes text NOT NULL DEFAULT '',archived boolean NOT NULL DEFAULT false,created_at timestamptz DEFAULT now(),updated_at timestamptz DEFAULT now());
|
||||
CREATE TABLE bean_consumption(id uuid PRIMARY KEY DEFAULT gen_random_uuid(),lot_id uuid NOT NULL REFERENCES green_bean_lots(id) ON DELETE CASCADE,user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,roast_plan_id uuid REFERENCES roast_plans(id) ON DELETE SET NULL,weight_g numeric NOT NULL CHECK (weight_g > 0),created_at timestamptz DEFAULT now());
|
||||
CREATE UNIQUE INDEX bean_consumption_one_per_plan ON bean_consumption(roast_plan_id);
|
||||
CREATE TABLE cupping_sessions(id uuid PRIMARY KEY DEFAULT gen_random_uuid(),user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,roast_plan_id uuid REFERENCES roast_plans(id) ON DELETE SET NULL,data jsonb NOT NULL,total_score numeric NOT NULL DEFAULT 0,created_at timestamptz DEFAULT now(),updated_at timestamptz DEFAULT now())`,
|
||||
);
|
||||
const app = createApp({
|
||||
db,
|
||||
root,
|
||||
env: {
|
||||
NODE_ENV: "test",
|
||||
BOOTSTRAP_SETUP_TOKEN: "a-secure-bootstrap-token",
|
||||
...env,
|
||||
},
|
||||
});
|
||||
return { db, app, agent: request.agent(app) };
|
||||
}
|
||||
|
||||
export async function signup(agent, email) {
|
||||
const response = await agent.post("/api/auth/signup").send({ email, password });
|
||||
return { response, csrf: response.body.csrfToken };
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import request from "supertest";
|
||||
import { setup, signup } from "./helpers.js";
|
||||
|
||||
async function bootstrapPlan(agent, csrf) {
|
||||
const r = await agent
|
||||
.post("/api/plans")
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ plan: { fields: { 0.1: "Test coffee" } } });
|
||||
return r.body.plan.id;
|
||||
}
|
||||
|
||||
test("inventory: auth and CSRF are required on every route", async () => {
|
||||
const { app } = await setup();
|
||||
const anon = request.agent(app);
|
||||
assert.equal((await anon.get("/api/inventory")).status, 401);
|
||||
assert.equal((await anon.post("/api/inventory").send({})).status, 401);
|
||||
const { agent, csrf } = await (async () => {
|
||||
const a = request.agent(app);
|
||||
const { csrf: c } = await signup(a, "[email protected]");
|
||||
return { agent: a, csrf: c };
|
||||
})();
|
||||
assert.equal(
|
||||
(await agent.post("/api/inventory").send({ origin: "X", initialWeightG: 100 })).status,
|
||||
403,
|
||||
);
|
||||
const created = await agent
|
||||
.post("/api/inventory")
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ origin: "Huila", initialWeightG: 1000 });
|
||||
assert.equal(created.status, 201);
|
||||
assert.equal(
|
||||
(await agent.put(`/api/inventory/${created.body.lot.id}`).send({ origin: "Y" })).status,
|
||||
403,
|
||||
);
|
||||
assert.equal(
|
||||
(await agent.delete(`/api/inventory/${created.body.lot.id}`)).status,
|
||||
403,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await agent
|
||||
.post(`/api/inventory/${created.body.lot.id}/consume`)
|
||||
.send({ weightG: 10 })
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
});
|
||||
|
||||
test("inventory: create, list, and ownership isolation", async () => {
|
||||
const { app } = await setup();
|
||||
const first = request.agent(app);
|
||||
const second = request.agent(app);
|
||||
const { csrf: firstCsrf } = await signup(first, "[email protected]");
|
||||
await signup(second, "[email protected]");
|
||||
|
||||
const bad = await first
|
||||
.post("/api/inventory")
|
||||
.set("x-csrf-token", firstCsrf)
|
||||
.send({ origin: "", initialWeightG: 100 });
|
||||
assert.equal(bad.status, 400);
|
||||
const badWeight = await first
|
||||
.post("/api/inventory")
|
||||
.set("x-csrf-token", firstCsrf)
|
||||
.send({ origin: "Huila", initialWeightG: -5 });
|
||||
assert.equal(badWeight.status, 400);
|
||||
|
||||
const created = await first
|
||||
.post("/api/inventory")
|
||||
.set("x-csrf-token", firstCsrf)
|
||||
.send({ origin: "Huila, Colombia", variety: "Caturra", initialWeightG: 2000 });
|
||||
assert.equal(created.status, 201);
|
||||
assert.equal(created.body.lot.remainingWeightG, 2000);
|
||||
|
||||
assert.equal((await first.get("/api/inventory")).body.lots.length, 1);
|
||||
assert.equal((await second.get("/api/inventory")).body.lots.length, 0);
|
||||
assert.equal((await second.get(`/api/inventory/${created.body.lot.id}`)).status, 404);
|
||||
});
|
||||
|
||||
test("inventory: consume decrements remaining, allows negative, is idempotent per plan, and logs", async () => {
|
||||
const { app } = await setup();
|
||||
const agent = request.agent(app);
|
||||
const { csrf } = await signup(agent, "[email protected]");
|
||||
const planId = await bootstrapPlan(agent, csrf);
|
||||
const lot = (
|
||||
await agent
|
||||
.post("/api/inventory")
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ origin: "Huila", initialWeightG: 300 })
|
||||
).body.lot;
|
||||
|
||||
const first = await agent
|
||||
.post(`/api/inventory/${lot.id}/consume`)
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ weightG: 250, roastPlanId: planId });
|
||||
assert.equal(first.status, 201);
|
||||
assert.equal(first.body.lot.remainingWeightG, 50);
|
||||
|
||||
// A second draw against the SAME plan is rejected — one draw-down per roast plan, ever.
|
||||
const dupe = await agent
|
||||
.post(`/api/inventory/${lot.id}/consume`)
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ weightG: 10, roastPlanId: planId });
|
||||
assert.equal(dupe.status, 409);
|
||||
assert.equal(dupe.body.code, "already_consumed");
|
||||
assert.equal(
|
||||
(await agent.get(`/api/inventory/${lot.id}`)).body.lot.remainingWeightG,
|
||||
50,
|
||||
"remaining must be unchanged after the rejected duplicate",
|
||||
);
|
||||
|
||||
// A manual (plan-less) draw is unlimited and can push remaining negative — an honest
|
||||
// signal of paperwork/shelf drift, not clamped.
|
||||
const manual = await agent
|
||||
.post(`/api/inventory/${lot.id}/consume`)
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ weightG: 100 });
|
||||
assert.equal(manual.status, 201);
|
||||
assert.equal(manual.body.lot.remainingWeightG, -50);
|
||||
|
||||
const zero = await agent
|
||||
.post(`/api/inventory/${lot.id}/consume`)
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ weightG: 0 });
|
||||
assert.equal(zero.status, 400);
|
||||
|
||||
const withLog = await agent.get(`/api/inventory/${lot.id}`);
|
||||
assert.equal(withLog.body.log.length, 2);
|
||||
// Newest first: the manual (plan-less) draw has no plan title; the earlier draw does.
|
||||
assert.equal(withLog.body.log[0].roastPlanId, null);
|
||||
assert.equal(withLog.body.log[0].planTitle, null);
|
||||
assert.equal(withLog.body.log[1].roastPlanId, planId);
|
||||
assert.equal(withLog.body.log[1].planTitle, "Test coffee");
|
||||
});
|
||||
|
||||
test("inventory: consuming against another user's plan is refused", async () => {
|
||||
const { app } = await setup();
|
||||
const owner = request.agent(app);
|
||||
const attacker = request.agent(app);
|
||||
const { csrf: ownerCsrf } = await signup(owner, "[email protected]");
|
||||
const { csrf: attackerCsrf } = await signup(attacker, "[email protected]");
|
||||
const planId = await bootstrapPlan(owner, ownerCsrf);
|
||||
const lot = (
|
||||
await attacker
|
||||
.post("/api/inventory")
|
||||
.set("x-csrf-token", attackerCsrf)
|
||||
.send({ origin: "Huila", initialWeightG: 500 })
|
||||
).body.lot;
|
||||
const consume = await attacker
|
||||
.post(`/api/inventory/${lot.id}/consume`)
|
||||
.set("x-csrf-token", attackerCsrf)
|
||||
.send({ weightG: 50, roastPlanId: planId });
|
||||
assert.equal(consume.status, 404);
|
||||
});
|
||||
|
||||
test("inventory: edit never accepts remainingWeightG directly, but shifting initialWeightG shifts remaining by the delta", async () => {
|
||||
const { app } = await setup();
|
||||
const agent = request.agent(app);
|
||||
const { csrf } = await signup(agent, "[email protected]");
|
||||
const lot = (
|
||||
await agent
|
||||
.post("/api/inventory")
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ origin: "Huila", initialWeightG: 1000 })
|
||||
).body.lot;
|
||||
await agent
|
||||
.post(`/api/inventory/${lot.id}/consume`)
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ weightG: 400 });
|
||||
|
||||
// Attempting to set remainingWeightG directly is silently ignored.
|
||||
const sneaky = await agent
|
||||
.put(`/api/inventory/${lot.id}`)
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ remainingWeightG: 999999 });
|
||||
assert.equal(sneaky.body.lot.remainingWeightG, 600);
|
||||
|
||||
// Correcting the recorded initial weight (e.g. a scale error) shifts remaining by the delta.
|
||||
const corrected = await agent
|
||||
.put(`/api/inventory/${lot.id}`)
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ initialWeightG: 1100 });
|
||||
assert.equal(corrected.body.lot.initialWeightG, 1100);
|
||||
assert.equal(corrected.body.lot.remainingWeightG, 700);
|
||||
|
||||
const archived = await agent
|
||||
.put(`/api/inventory/${lot.id}`)
|
||||
.set("x-csrf-token", csrf)
|
||||
.send({ archived: true });
|
||||
assert.equal(archived.body.lot.archived, true);
|
||||
|
||||
assert.equal(
|
||||
(await agent.delete(`/api/inventory/${lot.id}`).set("x-csrf-token", csrf)).status,
|
||||
200,
|
||||
);
|
||||
assert.equal((await agent.get(`/api/inventory/${lot.id}`)).status, 404);
|
||||
});
|
||||
Reference in New Issue
Block a user