Initial commit: Apothecary v0.4.0

This commit is contained in:
2026-05-03 20:19:26 -04:00
commit 027cf032be
55 changed files with 14678 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
node_modules
dist
*.log
.DS_Store
.env
.env.local
# SQLite
server/data.db
server/data.db-journal
server/data.db-shm
server/data.db-wal
# Build output
server/dist
web/dist
*.tsbuildinfo
# Claude Code local settings
.claude/settings.local.json
+329
View File
@@ -0,0 +1,329 @@
{
"name": "apothecary",
"version": "0.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "apothecary",
"version": "0.4.0",
"devDependencies": {
"concurrently": "^9.1.0"
}
},
"node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"dev": true,
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/chalk/node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/cliui": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
"integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",
"dev": true,
"license": "ISC",
"dependencies": {
"string-width": "^4.2.0",
"strip-ansi": "^6.0.1",
"wrap-ansi": "^7.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
},
"engines": {
"node": ">=7.0.0"
}
},
"node_modules/color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"dev": true,
"license": "MIT"
},
"node_modules/concurrently": {
"version": "9.2.1",
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.1.tgz",
"integrity": "sha512-fsfrO0MxV64Znoy8/l1vVIjjHa29SZyyqPgQBwhiDcaW8wJc2W3XWVOGx4M3oJBnv/zdUZIIp1gDeS98GzP8Ng==",
"dev": true,
"license": "MIT",
"dependencies": {
"chalk": "4.1.2",
"rxjs": "7.8.2",
"shell-quote": "1.8.3",
"supports-color": "8.1.1",
"tree-kill": "1.2.2",
"yargs": "17.7.2"
},
"bin": {
"conc": "dist/bin/concurrently.js",
"concurrently": "dist/bin/concurrently.js"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/open-cli-tools/concurrently?sponsor=1"
}
},
"node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"dev": true,
"license": "MIT"
},
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
"integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/get-caller-file": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
"dev": true,
"license": "ISC",
"engines": {
"node": "6.* || 8.* || >= 10.*"
}
},
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/rxjs": {
"version": "7.8.2",
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.1.0"
}
},
"node_modules/shell-quote": {
"version": "1.8.3",
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
"integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/supports-color": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
"integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/supports-color?sponsor=1"
}
},
"node_modules/tree-kill": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
"integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==",
"dev": true,
"license": "MIT",
"bin": {
"tree-kill": "cli.js"
}
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true,
"license": "0BSD"
},
"node_modules/wrap-ansi": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.0.0",
"string-width": "^4.1.0",
"strip-ansi": "^6.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
"integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=10"
}
},
"node_modules/yargs": {
"version": "17.7.2",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",
"integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==",
"dev": true,
"license": "MIT",
"dependencies": {
"cliui": "^8.0.1",
"escalade": "^3.1.1",
"get-caller-file": "^2.0.5",
"require-directory": "^2.1.1",
"string-width": "^4.2.3",
"y18n": "^5.0.5",
"yargs-parser": "^21.1.1"
},
"engines": {
"node": ">=12"
}
},
"node_modules/yargs-parser": {
"version": "21.1.1",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
"integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=12"
}
}
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"name": "apothecary",
"private": true,
"version": "0.4.0",
"description": "Personal cannabis inventory tracker",
"scripts": {
"dev": "concurrently -n server,web -c cyan,magenta \"npm:dev:server\" \"npm:dev:web\"",
"dev:server": "npm --prefix server run dev",
"dev:web": "npm --prefix web run dev",
"build": "npm --prefix server run build && npm --prefix web run build",
"install:all": "npm install && npm --prefix server install && npm --prefix web install"
},
"devDependencies": {
"concurrently": "^9.1.0"
}
}
+1982
View File
File diff suppressed because it is too large Load Diff
+25
View File
@@ -0,0 +1,25 @@
{
"name": "apothecary-server",
"private": true,
"version": "0.4.0",
"type": "module",
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc -p tsconfig.json && node -e \"require('node:fs').copyFileSync('src/schema.sql','dist/schema.sql')\"",
"start": "node dist/index.js",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"better-sqlite3": "^11.5.0",
"cors": "^2.8.5",
"express": "^4.21.2"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.12",
"@types/cors": "^2.8.17",
"@types/express": "^5.0.0",
"@types/node": "^22.10.2",
"tsx": "^4.19.2",
"typescript": "^5.7.2"
}
}
+40
View File
@@ -0,0 +1,40 @@
import Database from "better-sqlite3";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const DB_PATH = process.env.APOTHECARY_DB ?? join(__dirname, "..", "data.db");
export const db = new Database(DB_PATH);
db.pragma("journal_mode = WAL");
db.pragma("foreign_keys = ON");
const schema = readFileSync(join(__dirname, "schema.sql"), "utf8");
db.exec(schema);
// Add strain_id to products table if missing — older DBs predate the column.
const productCols = db
.prepare(`PRAGMA table_info(products)`)
.all() as { name: string }[];
if (!productCols.some((c) => c.name === "strain_id")) {
db.exec(`ALTER TABLE products ADD COLUMN strain_id TEXT REFERENCES strains(id);`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_products_strain ON products(strain_id);`);
}
export function nextId(prefix: string, table: string): string {
const row = db
.prepare<[string], { id: string }>(
`SELECT id FROM ${table} WHERE id LIKE ? ORDER BY id DESC LIMIT 1`,
)
.get(`${prefix}-%`);
const last = row ? Number(row.id.slice(prefix.length + 1)) : 0;
const pad = prefix === "prd" || prefix === "str" ? 4 : 2;
const n = String(last + 1).padStart(pad, "0");
return `${prefix}-${n}`;
}
export function randomSku(): string {
return "SKU-" + Math.random().toString(36).slice(2, 8).toUpperCase();
}
+21
View File
@@ -0,0 +1,21 @@
import cors from "cors";
import express from "express";
import { seedIfEmpty } from "./seed.js";
import { bootstrapRouter } from "./routes/bootstrap.js";
import { productsRouter } from "./routes/products.js";
import { catalogRouter } from "./routes/catalog.js";
seedIfEmpty();
const app = express();
app.use(cors());
app.use(express.json({ limit: "1mb" }));
app.use("/api", bootstrapRouter);
app.use("/api", productsRouter);
app.use("/api", catalogRouter);
const PORT = Number(process.env.PORT ?? 4000);
app.listen(PORT, () => {
console.log(`[apothecary] api listening on http://localhost:${PORT}`);
});
+128
View File
@@ -0,0 +1,128 @@
import { Router } from "express";
import { db } from "../db.js";
export const bootstrapRouter: Router = Router();
type ProductRow = {
id: string;
sku: string;
asset_tag: string | null;
name: string;
brand_id: string | null;
shop_id: string | null;
bin_id: string | null;
type: string;
kind: string;
weight: number;
last_audit_weight: number | null;
count_original: number;
count_last_audit: number | null;
unit_weight: number;
price: number;
thc: number;
cbd: number;
total_cannabinoids: number;
purchase_date: string;
status: string;
consumed_date: string | null;
gone_date: string | null;
rating: number | null;
notes: string | null;
strain_id: string | null;
};
type StrainRow = {
id: string;
name: string;
brand_id: string | null;
type: string;
default_thc: number | null;
default_cbd: number | null;
default_total_cannabinoids: number | null;
notes: string | null;
};
type AuditRow = {
id: number;
product_id: string;
date: string;
mode: string;
value: number;
prev_value: number | null;
confirmed_by: string | null;
};
bootstrapRouter.get("/bootstrap", (_req, res) => {
const products = db.prepare<[], ProductRow>("SELECT * FROM products ORDER BY id").all();
const audits = db
.prepare<[], AuditRow>("SELECT * FROM audits ORDER BY product_id, date")
.all();
const shops = db.prepare("SELECT * FROM shops ORDER BY id").all();
const brands = db.prepare("SELECT * FROM brands ORDER BY id").all();
const bins = db.prepare("SELECT * FROM bins ORDER BY id").all();
const strains = db
.prepare<[], StrainRow>("SELECT * FROM strains ORDER BY name COLLATE NOCASE")
.all();
const auditsByProduct = new Map<string, AuditRow[]>();
for (const a of audits) {
const arr = auditsByProduct.get(a.product_id) ?? [];
arr.push(a);
auditsByProduct.set(a.product_id, arr);
}
const productsOut = products.map((p) => ({
id: p.id,
sku: p.sku,
assetTag: p.asset_tag,
name: p.name,
brandId: p.brand_id,
shopId: p.shop_id,
binId: p.bin_id,
type: p.type,
kind: p.kind,
weight: p.weight,
lastAuditWeight: p.last_audit_weight,
countOriginal: p.count_original,
countLastAudit: p.count_last_audit,
unitWeight: p.unit_weight,
price: p.price,
thc: p.thc,
cbd: p.cbd,
totalCannabinoids: p.total_cannabinoids,
purchaseDate: p.purchase_date,
status: p.status,
consumedDate: p.consumed_date,
goneDate: p.gone_date,
rating: p.rating,
notes: p.notes,
strainId: p.strain_id,
audits: (auditsByProduct.get(p.id) ?? []).map((a) => ({
date: a.date,
mode: a.mode,
value: a.value,
prev: a.prev_value,
confirmedBy: a.confirmed_by,
})),
}));
const strainsOut = strains.map((s) => ({
id: s.id,
name: s.name,
brandId: s.brand_id,
type: s.type,
defaultThc: s.default_thc,
defaultCbd: s.default_cbd,
defaultTotalCannabinoids: s.default_total_cannabinoids,
notes: s.notes,
}));
res.json({
products: productsOut,
shops,
brands,
bins,
strains: strainsOut,
today: "2026-04-25",
});
});
+94
View File
@@ -0,0 +1,94 @@
import { Router } from "express";
import { db, nextId } from "../db.js";
export const catalogRouter: Router = Router();
catalogRouter.post("/brands", (req, res) => {
const { name } = req.body as { name: string };
if (!name?.trim()) return res.status(400).json({ error: "name required" });
const existing = db
.prepare<[string], { id: string }>("SELECT id FROM brands WHERE name = ?")
.get(name.trim());
if (existing) return res.json({ id: existing.id, name: name.trim() });
const id = nextId("brd", "brands");
db.prepare("INSERT INTO brands (id, name) VALUES (?, ?)").run(id, name.trim());
res.json({ id, name: name.trim() });
});
catalogRouter.post("/shops", (req, res) => {
const { name, location } = req.body as { name: string; location?: string };
if (!name?.trim()) return res.status(400).json({ error: "name required" });
const id = nextId("shp", "shops");
db.prepare("INSERT INTO shops (id, name, location) VALUES (?, ?, ?)").run(
id,
name.trim(),
location?.trim() ?? null,
);
res.json({ id, name: name.trim(), location: location?.trim() ?? null });
});
catalogRouter.post("/bins", (req, res) => {
const { name, location, capacity } = req.body as {
name: string;
location?: string;
capacity?: number;
};
if (!name?.trim()) return res.status(400).json({ error: "name required" });
const id = nextId("bin", "bins");
const cap = Number.isFinite(capacity) && (capacity as number) > 0 ? Math.floor(capacity as number) : 10;
db.prepare("INSERT INTO bins (id, name, location, capacity) VALUES (?, ?, ?, ?)").run(
id,
name.trim(),
location?.trim() ?? null,
cap,
);
res.json({ id, name: name.trim(), location: location?.trim() ?? null, capacity: cap });
});
catalogRouter.patch("/bins/:id", (req, res) => {
const { id } = req.params;
const { name, location, capacity } = req.body as {
name?: string;
location?: string | null;
capacity?: number;
};
const existing = db
.prepare<[string], { id: string; name: string; location: string | null; capacity: number }>(
"SELECT id, name, location, capacity FROM bins WHERE id = ?",
)
.get(id);
if (!existing) return res.status(404).json({ error: "bin not found" });
const nextName = name?.trim() ? name.trim() : existing.name;
const nextLocation =
location === undefined ? existing.location : location?.toString().trim() || null;
const nextCapacity =
Number.isFinite(capacity) && (capacity as number) > 0
? Math.floor(capacity as number)
: existing.capacity;
db.prepare("UPDATE bins SET name = ?, location = ?, capacity = ? WHERE id = ?").run(
nextName,
nextLocation,
nextCapacity,
id,
);
res.json({ id, name: nextName, location: nextLocation, capacity: nextCapacity });
});
// Deleting a bin unassigns any products that reference it (bin_id → NULL),
// so users never lose products when reorganizing storage.
catalogRouter.delete("/bins/:id", (req, res) => {
const { id } = req.params;
const tx = db.transaction(() => {
db.prepare("UPDATE products SET bin_id = NULL WHERE bin_id = ?").run(id);
const result = db.prepare("DELETE FROM bins WHERE id = ?").run(id);
if (result.changes === 0) throw new Error("not found");
});
try {
tx();
res.json({ ok: true });
} catch {
res.status(404).json({ error: "bin not found" });
}
});
+182
View File
@@ -0,0 +1,182 @@
import { Router } from "express";
import { db, nextId, randomSku } from "../db.js";
export const productsRouter: Router = Router();
type CreateBody = {
name: string;
brandId: string;
shopId: string;
binId: string;
type: string;
kind: "bulk" | "discrete";
weight?: number;
countOriginal?: number;
unitWeight?: number;
price: number;
thc: number;
cbd: number;
totalCannabinoids: number;
purchaseDate: string;
sku?: string;
assetTag?: string;
};
productsRouter.post("/products", (req, res) => {
const body = req.body as CreateBody;
if (!body.name) return res.status(400).json({ error: "name required" });
const id = nextId("prd", "products");
const sku = body.sku && body.sku.trim() ? body.sku.trim() : randomSku();
const isDiscrete = body.kind === "discrete";
const trimmedName = body.name.trim();
const brandId = body.brandId ?? null;
const todayIso = new Date().toISOString().slice(0, 10);
const tx = db.transaction(() => {
// Find-or-create the strain (case-insensitive name match scoped to brand+type).
const found = db
.prepare<
[string, string | null, string | null, string],
{ id: string }
>(
`SELECT id FROM strains
WHERE name = ? COLLATE NOCASE
AND (brand_id IS ? OR brand_id = ?)
AND type = ?`,
)
.get(trimmedName, brandId, brandId, body.type);
let strainId: string;
if (found) {
strainId = found.id;
} else {
strainId = nextId("str", "strains");
db.prepare(`
INSERT INTO strains (
id, name, brand_id, type,
default_thc, default_cbd, default_total_cannabinoids, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`).run(
strainId,
trimmedName,
brandId,
body.type,
body.thc,
body.cbd,
body.totalCannabinoids,
todayIso,
);
}
db.prepare(`
INSERT INTO products (
id, sku, asset_tag, name, brand_id, shop_id, bin_id,
type, kind, weight, last_audit_weight,
count_original, count_last_audit, unit_weight,
price, thc, cbd, total_cannabinoids,
purchase_date, status, strain_id
) VALUES (
@id, @sku, @assetTag, @name, @brandId, @shopId, @binId,
@type, @kind, @weight, @lastAuditWeight,
@countOriginal, @countLastAudit, @unitWeight,
@price, @thc, @cbd, @totalCannabinoids,
@purchaseDate, 'active', @strainId
)
`).run({
id,
sku,
assetTag: body.assetTag?.trim() ? body.assetTag.trim() : null,
name: trimmedName,
brandId,
shopId: body.shopId,
binId: body.binId,
type: body.type,
kind: body.kind,
weight: isDiscrete ? 0 : body.weight ?? 0,
lastAuditWeight: isDiscrete ? null : body.weight ?? 0,
countOriginal: isDiscrete ? body.countOriginal ?? 0 : 0,
countLastAudit: isDiscrete ? body.countOriginal ?? 0 : null,
unitWeight: isDiscrete ? body.unitWeight ?? 0 : 0,
price: body.price,
thc: body.thc,
cbd: body.cbd,
totalCannabinoids: body.totalCannabinoids,
purchaseDate: body.purchaseDate,
strainId,
});
});
tx();
res.json({ id });
});
productsRouter.post("/products/:id/finish", (req, res) => {
const { id } = req.params;
const { date, rating, notes } = req.body as { date: string; rating?: number; notes?: string };
const result = db
.prepare(
"UPDATE products SET status = 'consumed', consumed_date = ?, rating = ?, notes = ?, bin_id = NULL WHERE id = ? AND status = 'active'",
)
.run(date, rating ?? null, notes ?? null, id);
if (result.changes === 0) return res.status(404).json({ error: "not found or not active" });
res.json({ ok: true });
});
productsRouter.post("/products/:id/gone", (req, res) => {
const { id } = req.params;
const { date, reason, notes } = req.body as { date: string; reason: string; notes?: string };
const combinedNotes = notes ? `${reason}: ${notes}` : reason;
const tx = db.transaction(() => {
const result = db
.prepare(
"UPDATE products SET status = 'gone', gone_date = ?, notes = ?, bin_id = NULL WHERE id = ? AND status = 'active'",
)
.run(date, combinedNotes, id);
if (result.changes === 0) throw new Error("not found");
db.prepare(
"INSERT INTO audits (product_id, date, mode, value, prev_value, confirmed_by) VALUES (?, ?, 'presence', 0, NULL, 'lost')",
).run(id, date);
});
try {
tx();
res.json({ ok: true });
} catch {
res.status(404).json({ error: "not found or not active" });
}
});
productsRouter.post("/products/:id/audit", (req, res) => {
const { id } = req.params;
const { date, mode, value, confirmedBy } = req.body as {
date: string;
mode: "weigh" | "estimate" | "presence";
value: number;
confirmedBy?: string;
};
const product = db
.prepare<[string], { kind: string; weight: number; last_audit_weight: number | null; count_original: number; count_last_audit: number | null }>(
"SELECT kind, weight, last_audit_weight, count_original, count_last_audit FROM products WHERE id = ?",
)
.get(id);
if (!product) return res.status(404).json({ error: "not found" });
const prev =
product.kind === "discrete"
? product.count_last_audit ?? product.count_original
: product.last_audit_weight ?? product.weight;
const tx = db.transaction(() => {
db.prepare(
"INSERT INTO audits (product_id, date, mode, value, prev_value, confirmed_by) VALUES (?, ?, ?, ?, ?, ?)",
).run(id, date, mode, value, prev, confirmedBy ?? null);
if (product.kind === "discrete") {
db.prepare("UPDATE products SET count_last_audit = ? WHERE id = ?").run(value, id);
} else {
db.prepare("UPDATE products SET last_audit_weight = ? WHERE id = ?").run(value, id);
}
});
tx();
res.json({ ok: true });
});
+72
View File
@@ -0,0 +1,72 @@
CREATE TABLE IF NOT EXISTS shops (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
location TEXT
);
CREATE TABLE IF NOT EXISTS brands (
id TEXT PRIMARY KEY,
name TEXT NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS bins (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
location TEXT,
capacity INTEGER NOT NULL DEFAULT 10
);
CREATE TABLE IF NOT EXISTS strains (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
brand_id TEXT REFERENCES brands(id),
type TEXT NOT NULL,
default_thc REAL,
default_cbd REAL,
default_total_cannabinoids REAL,
notes TEXT,
created_at TEXT NOT NULL,
UNIQUE(name, brand_id, type)
);
CREATE INDEX IF NOT EXISTS idx_strains_brand_type ON strains(brand_id, type);
CREATE TABLE IF NOT EXISTS products (
id TEXT PRIMARY KEY,
sku TEXT NOT NULL,
asset_tag TEXT,
name TEXT NOT NULL,
brand_id TEXT REFERENCES brands(id),
shop_id TEXT REFERENCES shops(id),
bin_id TEXT REFERENCES bins(id),
type TEXT NOT NULL,
kind TEXT NOT NULL,
weight REAL DEFAULT 0,
last_audit_weight REAL,
count_original INTEGER DEFAULT 0,
count_last_audit INTEGER,
unit_weight REAL DEFAULT 0,
price REAL NOT NULL,
thc REAL DEFAULT 0,
cbd REAL DEFAULT 0,
total_cannabinoids REAL DEFAULT 0,
purchase_date TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
consumed_date TEXT,
gone_date TEXT,
rating INTEGER,
notes TEXT
);
CREATE TABLE IF NOT EXISTS audits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_id TEXT NOT NULL REFERENCES products(id) ON DELETE CASCADE,
date TEXT NOT NULL,
mode TEXT NOT NULL,
value REAL NOT NULL,
prev_value REAL,
confirmed_by TEXT
);
CREATE INDEX IF NOT EXISTS idx_products_status ON products(status);
CREATE INDEX IF NOT EXISTS idx_audits_product ON audits(product_id, date);
+5
View File
@@ -0,0 +1,5 @@
// No seed data — the app starts completely empty. Users build their own
// catalog of bins, brands, shops, and products.
export function seedIfEmpty(): void {
// Nothing to do.
}
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022"],
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true,
"verbatimModuleSyntax": false,
"noUncheckedIndexedAccess": false
},
"include": ["src/**/*"]
}
+18
View File
@@ -0,0 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Apothecary — Personal Inventory</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;500;600&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap"
rel="stylesheet"
/>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1795
View File
File diff suppressed because it is too large Load Diff
+24
View File
@@ -0,0 +1,24 @@
{
"name": "apothecary-web",
"private": true,
"version": "0.4.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@tanstack/react-query": "^5.62.7",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@types/react": "^18.3.17",
"@types/react-dom": "^18.3.5",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "^5.7.2",
"vite": "^5.4.11"
}
}
+185
View File
@@ -0,0 +1,185 @@
import { useEffect, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { api } from "./api.js";
import type { Bin, Bootstrap, Product } from "./types.js";
import { computeStats } from "./stats.js";
import { Sidebar } from "./components/Sidebar.js";
import type { ViewKey } from "./components/Sidebar.js";
import { Dashboard } from "./views/Dashboard.js";
import { Inventory } from "./views/Inventory.js";
import { BinsView } from "./views/BinsView.js";
import { BrandsView } from "./views/BrandsView.js";
import { ShopsView } from "./views/ShopsView.js";
import { ChartsView } from "./views/ChartsView.js";
import { SettingsView } from "./views/SettingsView.js";
import type { ThemeKey } from "./views/SettingsView.js";
import { ProductDetail } from "./components/ProductDetail.js";
import { AddProductFlow } from "./components/modals/AddProductFlow.js";
import { ConsumeFlow } from "./components/modals/ConsumeFlow.js";
import { MarkGoneFlow } from "./components/modals/MarkGoneFlow.js";
import { AuditFlow } from "./components/modals/AuditFlow.js";
import {
AddBinModal,
AddBrandModal,
AddShopModal,
EditBinModal,
} from "./components/modals/CatalogModals.js";
type ModalKey =
| "add"
| "consume"
| "gone"
| "audit"
| "addBrand"
| "addShop"
| "addBin"
| "editBin"
| null;
export function App() {
const [view, setView] = useState<ViewKey>("dashboard");
const [selected, setSelected] = useState<Product | null>(null);
const [modal, setModal] = useState<ModalKey>(null);
const [modalProduct, setModalProduct] = useState<Product | null>(null);
const [modalBin, setModalBin] = useState<Bin | null>(null);
const [theme, setTheme] = useState<ThemeKey>(
() => (localStorage.getItem("apothecary.theme") as ThemeKey | null) ?? "light",
);
useEffect(() => {
document.documentElement.dataset.theme = theme;
localStorage.setItem("apothecary.theme", theme);
}, [theme]);
const { data, isLoading, error } = useQuery<Bootstrap>({
queryKey: ["bootstrap"],
queryFn: api.bootstrap,
});
const stats = useMemo(() => (data ? computeStats(data) : null), [data]);
// Re-sync the selected product reference whenever bootstrap refetches
// — otherwise the drawer keeps showing stale audit history after a
// mutation invalidates the cache.
useEffect(() => {
if (selected && data) {
const fresh = data.products.find((p) => p.id === selected.id);
if (fresh && fresh !== selected) setSelected(fresh);
}
}, [data]); // eslint-disable-line react-hooks/exhaustive-deps
const openAdd = () => {
setModalProduct(null);
setModal("add");
};
const openConsume = (p?: Product) => {
setModalProduct(p ?? null);
setSelected(null);
setModal("consume");
};
const openMarkGone = (p?: Product) => {
setModalProduct(p ?? null);
setSelected(null);
setModal("gone");
};
const openAudit = (p?: Product) => {
setModalProduct(p ?? null);
setModal("audit");
};
if (isLoading) {
return (
<div className="parchment" style={{ padding: 60, color: "var(--ink-3)" }}>
Loading
</div>
);
}
if (error || !data || !stats) {
return (
<div className="parchment" style={{ padding: 60, color: "var(--terracotta)" }}>
Failed to load: {String(error ?? "no data")}
</div>
);
}
return (
<div className="app-shell" data-screen-label="App">
<Sidebar
view={view}
onNav={setView}
onAddProduct={openAdd}
onMarkFinished={() => openConsume()}
onAudit={() => openAudit()}
/>
<main className="main parchment" style={{ minWidth: 0 }}>
{view === "dashboard" && (
<Dashboard
data={data}
stats={stats}
onAuditProduct={openAudit}
onSelectProduct={setSelected}
/>
)}
{view === "inventory" && (
<Inventory
data={data}
onSelectProduct={setSelected}
onAddProduct={openAdd}
onAuditNew={() => openAudit()}
/>
)}
{view === "bins" && (
<BinsView
data={data}
onSelectProduct={setSelected}
onAddBin={() => setModal("addBin")}
onEditBin={(bin) => {
setModalBin(bin);
setModal("editBin");
}}
/>
)}
{view === "shops" && (
<ShopsView data={data} onAddShop={() => setModal("addShop")} />
)}
{view === "brands" && (
<BrandsView data={data} onAddBrand={() => setModal("addBrand")} />
)}
{view === "charts" && <ChartsView data={data} stats={stats} />}
{view === "settings" && (
<SettingsView data={data} theme={theme} onThemeChange={setTheme} />
)}
</main>
{selected && (
<ProductDetail
product={selected}
data={data}
onClose={() => setSelected(null)}
onConsume={openConsume}
onMarkGone={openMarkGone}
onAudit={openAudit}
/>
)}
{modal === "add" && <AddProductFlow data={data} onClose={() => setModal(null)} />}
{modal === "consume" && (
<ConsumeFlow data={data} onClose={() => setModal(null)} product={modalProduct} />
)}
{modal === "gone" && (
<MarkGoneFlow data={data} onClose={() => setModal(null)} product={modalProduct} />
)}
{modal === "audit" && (
<AuditFlow data={data} onClose={() => setModal(null)} product={modalProduct} />
)}
{modal === "addBrand" && <AddBrandModal onClose={() => setModal(null)} />}
{modal === "addShop" && <AddShopModal onClose={() => setModal(null)} />}
{modal === "addBin" && <AddBinModal onClose={() => setModal(null)} />}
{modal === "editBin" && modalBin && (
<EditBinModal bin={modalBin} onClose={() => setModal(null)} />
)}
</div>
);
}
+87
View File
@@ -0,0 +1,87 @@
import type { Bootstrap, AuditMode } from "./types.js";
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`/api${path}`, {
...init,
headers: { "Content-Type": "application/json", ...(init?.headers ?? {}) },
});
if (!res.ok) {
const text = await res.text();
throw new Error(`${res.status} ${res.statusText}: ${text}`);
}
return res.json() as Promise<T>;
}
export const api = {
bootstrap: () => request<Bootstrap>("/bootstrap"),
createProduct: (body: {
name: string;
brandId: string;
shopId: string;
binId: string;
type: string;
kind: "bulk" | "discrete";
weight?: number;
countOriginal?: number;
unitWeight?: number;
price: number;
thc: number;
cbd: number;
totalCannabinoids: number;
purchaseDate: string;
sku?: string;
assetTag?: string;
}) => request<{ id: string }>("/products", { method: "POST", body: JSON.stringify(body) }),
finishProduct: (id: string, body: { date: string; rating?: number; notes?: string }) =>
request<{ ok: true }>(`/products/${id}/finish`, {
method: "POST",
body: JSON.stringify(body),
}),
markGone: (id: string, body: { date: string; reason: string; notes?: string }) =>
request<{ ok: true }>(`/products/${id}/gone`, {
method: "POST",
body: JSON.stringify(body),
}),
auditProduct: (
id: string,
body: { date: string; mode: AuditMode; value: number; confirmedBy?: string },
) =>
request<{ ok: true }>(`/products/${id}/audit`, {
method: "POST",
body: JSON.stringify(body),
}),
createBrand: (name: string) =>
request<{ id: string; name: string }>("/brands", {
method: "POST",
body: JSON.stringify({ name }),
}),
createShop: (body: { name: string; location?: string }) =>
request<{ id: string; name: string; location: string | null }>("/shops", {
method: "POST",
body: JSON.stringify(body),
}),
createBin: (body: { name: string; location?: string; capacity?: number }) =>
request<{ id: string; name: string; location: string | null; capacity: number }>("/bins", {
method: "POST",
body: JSON.stringify(body),
}),
updateBin: (
id: string,
body: { name?: string; location?: string | null; capacity?: number },
) =>
request<{ id: string; name: string; location: string | null; capacity: number }>(
`/bins/${id}`,
{ method: "PATCH", body: JSON.stringify(body) },
),
deleteBin: (id: string) =>
request<{ ok: true }>(`/bins/${id}`, { method: "DELETE" }),
};
+404
View File
@@ -0,0 +1,404 @@
import type { Bootstrap, Product } from "../types.js";
import { TYPES, helpers, TODAY_STR } from "../types.js";
import { fmt, TYPE_GLYPHS } from "../format.js";
import { Btn, Pill, Icon } from "./primitives/index.js";
export function ProductDetail({
product,
data,
onClose,
onConsume,
onMarkGone,
onAudit,
}: {
product: Product;
data: Bootstrap;
onClose: () => void;
onConsume: (p: Product) => void;
onMarkGone: (p: Product) => void;
onAudit: (p: Product) => void;
}) {
const bin = data.bins.find((b) => b.id === product.binId);
const cfg = TYPES.find((t) => t.id === product.type);
const pctRemaining = helpers.pctRemaining(product, TODAY_STR);
const est = helpers.estimatedRemaining(product, TODAY_STR);
const last = helpers.lastAudit(product);
const overdue = helpers.auditOverdue(product, TODAY_STR);
const sinceCheck = helpers.daysSinceCheck(product, TODAY_STR);
const isActive = product.status === "active";
const detailRows: [string, React.ReactNode][] = [
["SKU", <span className="mono">{product.sku}</span>],
[
"Asset tag",
product.assetTag ? (
<span className="mono">{product.assetTag}</span>
) : (
<span style={{ color: "var(--ink-3)" }}>None</span>
),
],
["Type", `${product.type} · ${product.kind}`],
["Brand", helpers.brandName(data, product.brandId)],
["Shop", helpers.shopName(data, product.shopId)],
["Total cannabinoids", `${product.totalCannabinoids.toFixed(1)}%`],
["Purchase date", fmt.date(product.purchaseDate)],
["Bin", bin ? `${bin.name}${bin.location}` : <span style={{ color: "var(--ink-3)" }}></span>],
["Audit cadence", `Every ${cfg?.cadenceDays ?? "—"} days · ${cfg?.auditMode ?? "—"}`],
[
"Cost per gram",
product.kind === "bulk" && product.weight > 0
? fmt.money(product.price / product.weight)
: product.kind === "discrete" && product.unitWeight > 0
? `${fmt.money(product.price / (product.countOriginal * product.unitWeight))} (effective)`
: "—",
],
];
if (product.status === "consumed") {
detailRows.push(
["Date finished", fmt.date(product.consumedDate)],
[
"Lasted",
`${Math.round((+new Date(product.consumedDate!) - +new Date(product.purchaseDate)) / 86_400_000)} days`,
],
);
}
if (product.status === "gone") {
detailRows.push(
["Date gone", fmt.date(product.goneDate)],
[
"After",
`${Math.round((+new Date(product.goneDate!) - +new Date(product.purchaseDate)) / 86_400_000)} days`,
],
);
}
return (
<div
style={{
position: "fixed",
inset: 0,
background: "oklch(20% 0.02 60 / 0.4)",
zIndex: 50,
display: "flex",
justifyContent: "flex-end",
}}
onClick={onClose}
>
<div
onClick={(e) => e.stopPropagation()}
style={{
width: "min(720px, 100vw)",
height: "100%",
background: "var(--bg)",
borderLeft: "1px solid var(--line)",
overflow: "auto",
boxShadow: "var(--shadow-lg)",
}}
>
<div
style={{
padding: "20px 32px",
borderBottom: "1px solid var(--line)",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
position: "sticky",
top: 0,
background: "var(--bg)",
zIndex: 1,
}}
>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>
Product · {product.sku}
</div>
<div style={{ display: "flex", gap: 6 }}>
{isActive && (
<Btn variant="ghost" icon="check" onClick={() => onAudit(product)}>
Audit
</Btn>
)}
{isActive && (
<Btn variant="secondary" icon="check" onClick={() => onConsume(product)}>
Mark consumed
</Btn>
)}
{isActive && (
<Btn variant="ghost" icon="bin" onClick={() => onMarkGone(product)}>
Mark gone
</Btn>
)}
<Btn variant="ghost" icon="close" onClick={onClose} />
</div>
</div>
<div style={{ padding: "32px 32px 60px" }}>
<div style={{ display: "flex", alignItems: "baseline", gap: 16, marginBottom: 8 }}>
<div className="serif" style={{ fontSize: 18, color: "var(--ink-3)" }}>
{TYPE_GLYPHS[product.type]} {product.type}
</div>
{product.status === "consumed" && (
<Pill tone="terra">Consumed · {fmt.daysAgo(product.consumedDate)}</Pill>
)}
{product.status === "gone" && (
<Pill tone="amber">Gone · {fmt.daysAgo(product.goneDate)}</Pill>
)}
{isActive && overdue && <Pill tone="amber">Audit overdue · {sinceCheck}d</Pill>}
</div>
<h1
className="serif"
style={{
fontSize: 48,
margin: "0 0 4px",
fontWeight: 500,
letterSpacing: "-0.02em",
lineHeight: 1.1,
}}
>
{product.name}
</h1>
<div style={{ fontSize: 16, color: "var(--ink-2)" }}>
{helpers.brandName(data, product.brandId)} · from {helpers.shopName(data, product.shopId)}
</div>
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(4, 1fr)",
gap: 1,
marginTop: 32,
background: "var(--line)",
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
overflow: "hidden",
}}
>
{(
[
["Price", fmt.money(product.price)],
[
product.kind === "discrete" ? "Quantity" : "Size",
product.kind === "discrete"
? `${product.countOriginal} ${cfg?.unit ?? "ct"}`
: `${product.weight} ${cfg?.unit ?? "g"}`,
],
["THC", `${product.thc.toFixed(1)}%`],
["CBD", `${product.cbd.toFixed(1)}%`],
] as [string, string][]
).map(([l, v]) => (
<div key={l} style={{ padding: "18px 16px", background: "var(--surface)" }}>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>{l}</div>
<div className="serif" style={{ fontSize: 26, marginTop: 4, fontWeight: 500 }}>{v}</div>
</div>
))}
</div>
{isActive && (
<div style={{ marginTop: 20 }}>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "baseline",
marginBottom: 8,
}}
>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>
{product.kind === "discrete" ? "Units remaining" : "Estimated remaining"}
</div>
<div style={{ fontFamily: "var(--mono)", fontSize: 13 }}>
{product.kind === "discrete"
? `${product.countLastAudit ?? product.countOriginal} of ${product.countOriginal}`
: `${est.toFixed(2)} of ${product.weight} ${cfg?.unit ?? "g"}`}
<span style={{ color: "var(--ink-3)", marginLeft: 8 }}>
{Math.round(pctRemaining * 100)}%
</span>
</div>
</div>
<div style={{ height: 8, background: "var(--bg-3)", borderRadius: 4, overflow: "hidden" }}>
<div
style={{
width: `${pctRemaining * 100}%`,
height: "100%",
background:
pctRemaining < 0.25
? "var(--terracotta)"
: pctRemaining < 0.5
? "var(--amber)"
: "var(--sage)",
}}
/>
</div>
{product.kind === "bulk" && last && (
<div
style={{
fontSize: 11,
color: "var(--ink-3)",
marginTop: 6,
fontStyle: "italic",
}}
>
Estimated by linear decay since last {last.mode} on {fmt.dateShort(last.date)} ({last.value}
{cfg?.unit}). Re-audit to update.
</div>
)}
</div>
)}
<div style={{ marginTop: 36 }}>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "baseline",
marginBottom: 12,
}}
>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>Audit history</div>
{isActive && (
<button
onClick={() => onAudit(product)}
style={{
background: "none",
border: "none",
fontSize: 12,
color: "var(--ink-2)",
cursor: "pointer",
textDecoration: "underline",
}}
>
+ New audit
</button>
)}
</div>
{product.audits.length === 0 ? (
<div style={{ fontSize: 13, color: "var(--ink-3)", fontStyle: "italic", padding: "12px 0" }}>
No audits recorded. Cadence for {product.type}: every {cfg?.cadenceDays ?? "—"} days.
</div>
) : (
<div
style={{
display: "flex",
flexDirection: "column",
gap: 0,
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
overflow: "hidden",
}}
>
{[...product.audits].reverse().map((a, i, arr) => (
<div
key={i}
style={{
padding: "12px 16px",
borderBottom: i < arr.length - 1 ? "1px solid var(--line)" : "none",
display: "flex",
alignItems: "center",
gap: 12,
background: "var(--surface)",
}}
>
<div
style={{
width: 8,
height: 8,
borderRadius: "50%",
background:
a.mode === "weigh"
? "var(--sage)"
: a.mode === "estimate"
? "var(--amber)"
: "var(--plum)",
}}
/>
<div style={{ flex: 1 }}>
<div style={{ fontSize: 13, fontWeight: 500 }}>
{a.mode === "weigh" && "Weighed"}
{a.mode === "estimate" && "Estimated"}
{a.mode === "presence" && (a.confirmedBy === "lost" ? "Marked lost" : "Confirmed presence")}
</div>
<div style={{ fontSize: 11, color: "var(--ink-3)" }}>
{fmt.date(a.date)} · {fmt.daysAgo(a.date)}
</div>
</div>
<div className="mono" style={{ fontSize: 13, textAlign: "right" }}>
<div>
{a.value} {cfg?.unit}
</div>
<div style={{ fontSize: 10, color: "var(--ink-3)" }}>
was {a.prev} {cfg?.unit}
</div>
</div>
</div>
))}
</div>
)}
</div>
<div style={{ marginTop: 36 }}>
<div className="smallcaps" style={{ color: "var(--ink-3)", marginBottom: 12 }}>Details</div>
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "14px 32px" }}>
{detailRows.map(([l, v], i) => (
<div
key={i}
style={{
display: "flex",
justifyContent: "space-between",
paddingBottom: 12,
borderBottom: "1px solid var(--line)",
}}
>
<span style={{ color: "var(--ink-3)", fontSize: 12 }}>{l}</span>
<span style={{ fontSize: 13, fontWeight: 500, textAlign: "right" }}>{v}</span>
</div>
))}
</div>
</div>
{(product.status === "consumed" || product.status === "gone") && (
<div
style={{
marginTop: 36,
padding: 24,
background: "var(--bg-2)",
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
}}
>
<div
style={{
display: "flex",
alignItems: "baseline",
justifyContent: "space-between",
marginBottom: 12,
}}
>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>
{product.status === "gone" ? "Why it's gone" : "Final notes"}
</div>
{product.status === "consumed" && (
<div style={{ display: "flex", gap: 2 }}>
{[1, 2, 3, 4, 5].map((n) => (
<Icon
key={n}
name="star"
size={14}
color={n <= (product.rating ?? 0) ? "var(--amber)" : "var(--ink-4)"}
/>
))}
</div>
)}
</div>
<div
className="serif"
style={{ fontSize: 18, lineHeight: 1.5, color: "var(--ink-2)", fontStyle: "italic" }}
>
"{product.notes ?? "No notes recorded."}"
</div>
</div>
)}
</div>
</div>
</div>
);
}
+110
View File
@@ -0,0 +1,110 @@
import { useEffect, useState } from "react";
import type { Product } from "../types.js";
import { Icon, Field, inputStyle } from "./primitives/index.js";
// Scan-friendly product picker. Auto-focuses on mount so a barcode scanner
// can fire immediately. Exact (case-insensitive) match against sku or
// assetTag → calls onMatch and clears itself for the next scan. Falls back
// to a "no match" hint when the value doesn't resolve.
export function ScanField({
products,
onMatch,
matchedProduct,
}: {
products: Product[];
onMatch: (productId: string) => void;
matchedProduct: Product | null;
}) {
const [scan, setScan] = useState("");
const [feedback, setFeedback] = useState<{ type: "matched" | "miss"; text: string } | null>(null);
useEffect(() => {
const trimmed = scan.trim().toLowerCase();
if (!trimmed) {
setFeedback(null);
return;
}
const match = products.find(
(p) =>
p.sku.toLowerCase() === trimmed ||
(p.assetTag != null && p.assetTag.toLowerCase() === trimmed),
);
if (match) {
onMatch(match.id);
setScan("");
setFeedback({ type: "matched", text: `Matched ${match.name}` });
}
}, [scan]); // eslint-disable-line react-hooks/exhaustive-deps
// Show "no match" only after the user has stopped typing for a beat —
// avoids flashing "no match" mid-type while a multi-char SKU is entered.
useEffect(() => {
if (!scan.trim() || feedback?.type === "matched") return;
const timer = setTimeout(() => {
const trimmed = scan.trim().toLowerCase();
const match = products.find(
(p) =>
p.sku.toLowerCase() === trimmed ||
(p.assetTag != null && p.assetTag.toLowerCase() === trimmed),
);
if (!match) setFeedback({ type: "miss", text: "No SKU or asset tag matches that." });
}, 400);
return () => clearTimeout(timer);
}, [scan, products]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<Field label="Scan SKU or asset tag" hint="Or pick from the list below.">
<div
style={{
display: "flex",
alignItems: "center",
gap: 8,
...inputStyle,
padding: "0 12px",
}}
>
<Icon name="search" size={14} color="var(--ink-3)" />
<input
autoFocus
value={scan}
onChange={(e) => setScan(e.target.value)}
onFocus={(e) => e.currentTarget.select()}
placeholder="SKU-XXXXXX or AT-0000"
style={{
border: "none",
outline: "none",
background: "transparent",
padding: "10px 0",
fontSize: 13,
flex: 1,
color: "var(--ink)",
fontFamily: "var(--mono)",
}}
/>
{matchedProduct && !scan && (
<span
className="mono"
style={{
fontSize: 11,
color: "var(--sage)",
whiteSpace: "nowrap",
}}
>
{matchedProduct.name}
</span>
)}
</div>
{feedback && (
<span
style={{
fontSize: 11,
color: feedback.type === "matched" ? "var(--sage)" : "var(--terracotta)",
marginTop: 2,
}}
>
{feedback.text}
</span>
)}
</Field>
);
}
+97
View File
@@ -0,0 +1,97 @@
import { Icon } from "./primitives/index.js";
export type ViewKey =
| "dashboard"
| "inventory"
| "bins"
| "shops"
| "brands"
| "charts"
| "settings";
const NAV: { key: ViewKey; label: string; icon: string }[] = [
{ key: "dashboard", label: "Dashboard", icon: "home" },
{ key: "inventory", label: "Inventory", icon: "box" },
{ key: "bins", label: "Bins", icon: "bin" },
{ key: "shops", label: "Shops", icon: "shop" },
{ key: "brands", label: "Brands", icon: "tag" },
{ key: "charts", label: "Patterns", icon: "chart" },
{ key: "settings", label: "Settings", icon: "settings" },
];
const BRAND = "Apothecary";
const TAGLINES = [
"Strictly medicinal",
"A discreet inventory",
"A herbalist's ledger",
"A modest dispensary",
"Materia medica",
"A green pharmacopeia",
"Tinctures & ephemera",
"Tended with care",
"By the gram",
];
// Picked once at module load — rerolls on a full page refresh, but stays
// stable across React re-renders within the same session.
const TAGLINE = TAGLINES[Math.floor(Math.random() * TAGLINES.length)]!;
export function Sidebar({
view,
onNav,
onAddProduct,
onMarkFinished,
onAudit,
}: {
view: ViewKey;
onNav: (k: ViewKey) => void;
onAddProduct: () => void;
onMarkFinished: () => void;
onAudit: () => void;
}) {
return (
<aside className="sidebar">
<div className="brand">
<div className="brand-mark">A</div>
<div>
<div className="serif" style={{ fontSize: 22, fontWeight: 500, lineHeight: 1 }}>
{BRAND}
</div>
<div
style={{
fontSize: 11,
color: "var(--ink-3)",
textTransform: "uppercase",
letterSpacing: "0.1em",
marginTop: 3,
}}
>
{TAGLINE}
</div>
</div>
</div>
<div className="nav-section">Workspace</div>
{NAV.map((n) => (
<button
key={n.key}
className={"nav-link " + (view === n.key ? "active" : "")}
onClick={() => onNav(n.key)}
>
<Icon name={n.icon} size={16} />
{n.label}
</button>
))}
<div className="nav-section">Quick</div>
<button className="nav-link" onClick={onAddProduct}>
<Icon name="plus" size={16} /> Add product
</button>
<button className="nav-link" onClick={onAudit}>
<Icon name="search" size={16} /> Audit
</button>
<button className="nav-link" onClick={onMarkFinished}>
<Icon name="check" size={16} /> Mark consumed
</button>
</aside>
);
}
@@ -0,0 +1,449 @@
import { useEffect, useMemo, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Bootstrap, Strain } from "../../types.js";
import { TYPES, TODAY_STR } from "../../types.js";
import { fmt } from "../../format.js";
import { api } from "../../api.js";
import { Btn, Field, Input, Select } from "../primitives/index.js";
const NEW_BRAND = "__new_brand__";
const NEW_SHOP = "__new_shop__";
const NEW_BIN = "__new_bin__";
export function AddProductFlow({ data, onClose }: { data: Bootstrap; onClose: () => void }) {
const qc = useQueryClient();
const [form, setForm] = useState({
name: "",
brandId: data.brands[0]?.id ?? NEW_BRAND,
shopId: data.shops[0]?.id ?? NEW_SHOP,
type: "Flower",
weight: 3.5,
countOriginal: 1,
unitWeight: 0.7,
price: 45,
thc: 22,
cbd: 0.4,
totalCannabinoids: 26,
purchaseDate: TODAY_STR,
binId: data.bins[0]?.id ?? NEW_BIN,
sku: "",
assetTag: "",
});
const [newBrand, setNewBrand] = useState("");
const [newShopName, setNewShopName] = useState("");
const [newShopLocation, setNewShopLocation] = useState("");
const [newBinName, setNewBinName] = useState("");
const [newBinLocation, setNewBinLocation] = useState("");
const [newBinCapacity, setNewBinCapacity] = useState(10);
const [error, setError] = useState<string | null>(null);
// Track which cannabinoid fields the user has touched. Pre-fill from a
// matched strain only writes into untouched fields, so we never overwrite
// numbers the user just typed.
const [edited, setEdited] = useState({ thc: false, cbd: false, total: false });
const update = <K extends keyof typeof form>(k: K, v: (typeof form)[K]) =>
setForm((f) => ({ ...f, [k]: v }));
const cfg = TYPES.find((t) => t.id === form.type);
const isDiscrete = cfg?.kind === "discrete";
const cpg = !isDiscrete && form.weight > 0 ? form.price / form.weight : 0;
// Find an existing strain matching the current name + brand + type.
// Case-insensitive + trimmed, brand can be NEW_BRAND (no match) or null.
const matchedStrain: Strain | null = useMemo(() => {
const name = form.name.trim().toLowerCase();
if (!name) return null;
if (form.brandId === NEW_BRAND) return null;
return (
data.strains.find(
(s) =>
s.name.trim().toLowerCase() === name &&
(s.brandId ?? null) === (form.brandId ?? null) &&
s.type === form.type,
) ?? null
);
}, [data.strains, form.name, form.brandId, form.type]);
// Pre-fill cannabinoids from the matched strain into untouched fields.
useEffect(() => {
if (!matchedStrain) return;
setForm((f) => ({
...f,
thc: edited.thc ? f.thc : matchedStrain.defaultThc ?? f.thc,
cbd: edited.cbd ? f.cbd : matchedStrain.defaultCbd ?? f.cbd,
totalCannabinoids: edited.total
? f.totalCannabinoids
: matchedStrain.defaultTotalCannabinoids ?? f.totalCannabinoids,
}));
}, [matchedStrain]); // eslint-disable-line react-hooks/exhaustive-deps
const save = useMutation({
mutationFn: async () => {
let { brandId, shopId, binId } = form;
if (brandId === NEW_BRAND) {
if (!newBrand.trim()) throw new Error("New brand name required");
const b = await api.createBrand(newBrand.trim());
brandId = b.id;
}
if (shopId === NEW_SHOP) {
if (!newShopName.trim()) throw new Error("New shop name required");
const s = await api.createShop({ name: newShopName.trim(), location: newShopLocation.trim() });
shopId = s.id;
}
if (binId === NEW_BIN) {
if (!newBinName.trim()) throw new Error("New bin name required");
const b = await api.createBin({
name: newBinName.trim(),
location: newBinLocation.trim(),
capacity: newBinCapacity,
});
binId = b.id;
}
return api.createProduct({
...form,
brandId,
shopId,
binId,
kind: isDiscrete ? "discrete" : "bulk",
});
},
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["bootstrap"] });
onClose();
},
onError: (e: Error) => setError(e.message),
});
const isNewBrand = form.brandId === NEW_BRAND;
const isNewShop = form.shopId === NEW_SHOP;
const isNewBin = form.binId === NEW_BIN;
return (
<ModalBackdrop onClose={onClose}>
<div
style={{
width: "min(840px, 96vw)",
margin: "40px 20px",
background: "var(--bg)",
border: "1px solid var(--line)",
borderRadius: "var(--r-lg)",
boxShadow: "var(--shadow-lg)",
}}
>
<ModalHeader title="Add a product" eyebrow="New entry" onClose={onClose} />
<div style={{ padding: 32 }}>
<div className="smallcaps" style={{ color: "var(--ink-3)", marginBottom: 16 }}>Identity</div>
<div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16, marginBottom: 28 }}>
<Field
label="Strain"
span={2}
hint={
matchedStrain
? "Matched existing strain — cannabinoid defaults pre-filled."
: undefined
}
>
<Input
value={form.name}
placeholder="e.g. Garden Ghost"
onChange={(e) => update("name", e.target.value)}
/>
</Field>
<Field label="Brand">
<Select value={form.brandId} onChange={(e) => update("brandId", e.target.value)}>
{data.brands.map((b) => (
<option key={b.id} value={b.id}>{b.name}</option>
))}
<option value={NEW_BRAND}>+ Add new brand</option>
</Select>
</Field>
<Field label="Shop">
<Select value={form.shopId} onChange={(e) => update("shopId", e.target.value)}>
{data.shops.map((s) => (
<option key={s.id} value={s.id}>{s.name}</option>
))}
<option value={NEW_SHOP}>+ Add new shop</option>
</Select>
</Field>
{isNewBrand && (
<Field label="New brand name" span={2}>
<Input value={newBrand} onChange={(e) => setNewBrand(e.target.value)} placeholder="e.g. Foxglove Farms" />
</Field>
)}
{isNewShop && (
<>
<Field label="New shop name">
<Input value={newShopName} onChange={(e) => setNewShopName(e.target.value)} placeholder="e.g. Greenleaf Co-op" />
</Field>
<Field label="Location (optional)">
<Input
value={newShopLocation}
onChange={(e) => setNewShopLocation(e.target.value)}
placeholder="e.g. Capitol Hill"
/>
</Field>
</>
)}
<Field label="Type">
<Select value={form.type} onChange={(e) => update("type", e.target.value)}>
{TYPES.map((t) => (
<option key={t.id} value={t.id}>{t.id} ({t.kind})</option>
))}
</Select>
</Field>
<Field label="Bin">
<Select value={form.binId} onChange={(e) => update("binId", e.target.value)}>
{data.bins.map((b) => (
<option key={b.id} value={b.id}>{b.name} {b.location}</option>
))}
<option value={NEW_BIN}>+ Add new bin</option>
</Select>
</Field>
{isNewBin && (
<>
<Field label="New bin name">
<Input
value={newBinName}
onChange={(e) => setNewBinName(e.target.value)}
placeholder="e.g. Top Drawer"
/>
</Field>
<Field label="Location (optional)">
<Input
value={newBinLocation}
onChange={(e) => setNewBinLocation(e.target.value)}
placeholder="e.g. Bedroom"
/>
</Field>
<Field label="Capacity">
<Input
type="number"
min={1}
step={1}
value={newBinCapacity}
onChange={(e) =>
setNewBinCapacity(Math.max(1, Math.floor(+e.target.value || 1)))
}
/>
</Field>
</>
)}
<Field label="SKU" hint="Leave blank — we'll generate one">
<Input value={form.sku} placeholder="SKU-…" onChange={(e) => update("sku", e.target.value)} />
</Field>
<Field label="Asset tag (optional)" hint="If you've physically tagged the item">
<Input
value={form.assetTag}
placeholder="AT-0000"
onChange={(e) => update("assetTag", e.target.value)}
/>
</Field>
</div>
<div className="smallcaps" style={{ color: "var(--ink-3)", marginBottom: 16 }}>Acquisition</div>
<div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginBottom: 8 }}>
{isDiscrete ? (
<>
<Field label={`Quantity (${cfg!.unit})`}>
<Input
type="number"
step="1"
value={form.countOriginal}
onChange={(e) => update("countOriginal", +e.target.value)}
/>
</Field>
<Field label="Per-unit weight (g)" hint="For grams stats">
<Input
type="number"
step="0.1"
value={form.unitWeight}
onChange={(e) => update("unitWeight", +e.target.value)}
/>
</Field>
</>
) : (
<Field label={`Size (${cfg?.unit ?? "g"})`} span={2}>
<Input
type="number"
step="0.1"
value={form.weight}
onChange={(e) => update("weight", +e.target.value)}
/>
</Field>
)}
<Field label="Price ($)">
<Input
type="number"
step="0.01"
value={form.price}
onChange={(e) => update("price", +e.target.value)}
/>
</Field>
<Field label="Purchase date">
<Input
type="date"
value={form.purchaseDate}
onChange={(e) => update("purchaseDate", e.target.value)}
/>
</Field>
</div>
{!isDiscrete && cpg > 0 && (
<div style={{ marginTop: 12, fontSize: 12, color: "var(--ink-3)" }}>
Cost per {cfg?.unit ?? "g"}:{" "}
<span className="mono" style={{ color: "var(--ink-2)" }}>{fmt.money(cpg)}</span>
</div>
)}
<div className="smallcaps" style={{ color: "var(--ink-3)", margin: "28px 0 16px" }}>Cannabinoid profile</div>
<div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
<Field label="THC %">
<Input
type="number"
step="0.1"
value={form.thc}
onChange={(e) => {
setEdited((p) => ({ ...p, thc: true }));
update("thc", +e.target.value);
}}
/>
</Field>
<Field label="CBD %">
<Input
type="number"
step="0.1"
value={form.cbd}
onChange={(e) => {
setEdited((p) => ({ ...p, cbd: true }));
update("cbd", +e.target.value);
}}
/>
</Field>
<Field label="Total cannabinoids %">
<Input
type="number"
step="0.1"
value={form.totalCannabinoids}
onChange={(e) => {
setEdited((p) => ({ ...p, total: true }));
update("totalCannabinoids", +e.target.value);
}}
/>
</Field>
</div>
{error && (
<div style={{ marginTop: 14, fontSize: 12, color: "var(--terracotta)" }}>{error}</div>
)}
</div>
<ModalFooter>
<div style={{ fontSize: 12, color: "var(--ink-3)" }}>
{form.name
? `"${form.name}" → ${
isNewBin
? newBinName.trim() || "new bin"
: data.bins.find((b) => b.id === form.binId)?.name ?? "—"
}.`
: "Fill in the name to continue."}
</div>
<div style={{ display: "flex", gap: 8 }}>
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
<Btn
variant="primary"
icon="check"
disabled={!form.name || save.isPending}
onClick={() => save.mutate()}
>
{save.isPending ? "Saving…" : "Save product"}
</Btn>
</div>
</ModalFooter>
</div>
</ModalBackdrop>
);
}
// ─── Shared modal chrome ──────────────────────────────────────────
export function ModalBackdrop({
children,
onClose,
}: {
children: React.ReactNode;
onClose: () => void;
}) {
return (
<div
style={{
position: "fixed",
inset: 0,
background: "oklch(20% 0.02 60 / 0.4)",
zIndex: 50,
display: "flex",
justifyContent: "center",
alignItems: "flex-start",
overflow: "auto",
}}
onClick={onClose}
>
<div onClick={(e) => e.stopPropagation()} style={{ width: "100%", display: "flex", justifyContent: "center" }}>
{children}
</div>
</div>
);
}
export function ModalHeader({
title,
eyebrow,
eyebrowColor,
onClose,
}: {
title: string;
eyebrow: string;
eyebrowColor?: string;
onClose: () => void;
}) {
return (
<div
style={{
padding: "20px 32px",
borderBottom: "1px solid var(--line)",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<div>
<div className="smallcaps" style={{ color: eyebrowColor ?? "var(--ink-3)" }}>
{eyebrow}
</div>
<h2 className="serif" style={{ fontSize: 28, margin: "4px 0 0", fontWeight: 500 }}>
{title}
</h2>
</div>
<Btn variant="ghost" icon="close" onClick={onClose} />
</div>
);
}
export function ModalFooter({ children }: { children: React.ReactNode }) {
return (
<div
style={{
padding: "16px 32px",
borderTop: "1px solid var(--line)",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
background: "var(--bg-2)",
borderRadius: "0 0 var(--r-lg) var(--r-lg)",
}}
>
{children}
</div>
);
}
+254
View File
@@ -0,0 +1,254 @@
import { useEffect, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Bootstrap, Product } from "../../types.js";
import { TYPES, helpers, TODAY_STR } from "../../types.js";
import { api } from "../../api.js";
import { Btn, Field, Input, Select } from "../primitives/index.js";
import { ScanField } from "../ScanField.js";
import { ModalBackdrop, ModalHeader, ModalFooter } from "./AddProductFlow.js";
const AUDIT_MODE_LABELS: Record<string, { title: string; desc: string }> = {
weigh: {
title: "Reweigh on a scale",
desc: "Place the jar (minus tare) and record the new weight.",
},
estimate: {
title: "Visual estimate",
desc: "Eyeball the remaining amount — quick and approximate.",
},
presence: {
title: "Confirm presence",
desc: "Verify the item is still where you left it. Count units if applicable.",
},
};
export function AuditFlow({
data,
onClose,
product: initialProduct,
}: {
data: Bootstrap;
onClose: () => void;
product: Product | null;
}) {
const qc = useQueryClient();
const overdueFirst = [...data.products]
.filter((p) => p.status === "active")
.sort((a, b) => helpers.daysSinceCheck(b) - helpers.daysSinceCheck(a));
const [productId, setProductId] = useState(initialProduct?.id ?? overdueFirst[0]?.id ?? "");
const [date, setDate] = useState(TODAY_STR);
const [confirmedBy, setConfirmedBy] = useState<"SKU" | "asset" | "visual">("SKU");
const product = data.products.find((p) => p.id === productId);
const cfg = product ? TYPES.find((t) => t.id === product.type) : undefined;
const initialValueFor = (p: Product | undefined): string => {
if (!p) return "0";
if (p.kind === "discrete") {
return String(p.countLastAudit ?? p.countOriginal);
}
return helpers.estimatedRemaining(p, TODAY_STR).toFixed(2);
};
const [value, setValue] = useState<string>(initialValueFor(product));
useEffect(() => {
setValue(initialValueFor(product));
}, [productId]); // eslint-disable-line react-hooks/exhaustive-deps
const audit = useMutation({
mutationFn: () =>
api.auditProduct(productId, {
date,
mode: cfg?.auditMode ?? "weigh",
value: Number(value),
confirmedBy: cfg?.auditMode === "presence" ? confirmedBy : undefined,
}),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["bootstrap"] });
onClose();
},
});
if (!product) return null;
const auditMode = cfg?.auditMode ?? "weigh";
const ml = AUDIT_MODE_LABELS[auditMode] ?? AUDIT_MODE_LABELS.weigh!;
const last = helpers.lastAudit(product);
const prevValue =
product.kind === "discrete"
? product.countLastAudit ?? product.countOriginal
: last
? last.value
: product.weight;
const delta = Number(value) - prevValue;
return (
<ModalBackdrop onClose={onClose}>
<div
style={{
width: "min(720px, 96vw)",
margin: "40px 20px",
background: "var(--bg)",
border: "1px solid var(--line)",
borderRadius: "var(--r-lg)",
boxShadow: "var(--shadow-lg)",
}}
>
<ModalHeader title={ml.title} eyebrow="Audit" onClose={onClose} />
<div style={{ padding: 32 }}>
<ScanField
products={overdueFirst}
matchedProduct={product ?? null}
onMatch={setProductId}
/>
<div style={{ marginTop: 16 }}>
<Field label="Or pick from list">
<Select value={productId} onChange={(e) => setProductId(e.target.value)}>
{overdueFirst.map((p) => {
const od = helpers.auditOverdue(p);
const sc = helpers.daysSinceCheck(p);
return (
<option key={p.id} value={p.id}>
{od ? "⚠ " : ""}
{p.name} {helpers.brandName(data, p.brandId)} · {sc}d since check
</option>
);
})}
</Select>
</Field>
</div>
<div
style={{
marginTop: 16,
padding: 16,
background: "var(--bg-2)",
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
}}
>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<div>
<div className="serif" style={{ fontSize: 20, fontWeight: 500 }}>
{product.name}
</div>
<div style={{ fontSize: 12, color: "var(--ink-3)" }}>
{product.type} · {product.kind} · cadence every {cfg?.cadenceDays}d
</div>
</div>
<div style={{ textAlign: "right" }}>
<div className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>LAST CHECKED</div>
<div className="serif" style={{ fontSize: 18 }}>
{last ? `${helpers.daysSinceCheck(product)}d ago` : "Never"}
</div>
</div>
</div>
<div style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 10, fontStyle: "italic" }}>
{ml.desc}
</div>
</div>
<div
style={{
display: "grid",
gridTemplateColumns: auditMode === "presence" ? "1fr 1fr 1fr" : "1fr 1fr",
gap: 16,
marginTop: 24,
}}
>
<Field
label={
product.kind === "discrete"
? `Count now (${cfg?.unit})`
: auditMode === "weigh"
? `Weight now (${cfg?.unit})`
: `Estimate now (${cfg?.unit})`
}
>
<Input
type="number"
step={product.kind === "discrete" ? "1" : "0.1"}
value={value}
onChange={(e) => setValue(e.target.value)}
/>
</Field>
<Field label="Date">
<Input type="date" value={date} onChange={(e) => setDate(e.target.value)} />
</Field>
{auditMode === "presence" && (
<Field label="Confirmed by">
<Select
value={confirmedBy}
onChange={(e) => setConfirmedBy(e.target.value as typeof confirmedBy)}
>
<option value="SKU">SKU label</option>
<option value="asset">Asset tag</option>
<option value="visual">Visual ID</option>
</Select>
</Field>
)}
</div>
<div
style={{
marginTop: 20,
padding: 14,
background: "var(--surface)",
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
display: "grid",
gridTemplateColumns: "1fr 1fr 1fr",
gap: 16,
}}
>
<div>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>Was</div>
<div className="serif" style={{ fontSize: 22 }}>
{prevValue} {cfg?.unit}
</div>
</div>
<div>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>Now</div>
<div className="serif" style={{ fontSize: 22, color: "var(--sage)" }}>
{value} {cfg?.unit}
</div>
</div>
<div>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>Δ since last</div>
<div
className="serif"
style={{
fontSize: 22,
color: delta < 0 ? "var(--terracotta)" : "var(--ink)",
}}
>
{delta.toFixed(product.kind === "discrete" ? 0 : 2)} {cfg?.unit}
</div>
</div>
</div>
</div>
<ModalFooter>
<div style={{ fontSize: 12, color: "var(--ink-3)" }}>
Next audit due in {cfg?.cadenceDays}d
</div>
<div style={{ display: "flex", gap: 8 }}>
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
<Btn
variant="primary"
icon="check"
disabled={audit.isPending}
onClick={() => audit.mutate()}
>
{audit.isPending ? "Saving…" : "Save audit"}
</Btn>
</div>
</ModalFooter>
</div>
</ModalBackdrop>
);
}
+273
View File
@@ -0,0 +1,273 @@
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "../../api.js";
import { Btn, Field, Input } from "../primitives/index.js";
import { ModalBackdrop, ModalHeader, ModalFooter } from "./AddProductFlow.js";
export function AddBrandModal({ onClose }: { onClose: () => void }) {
const qc = useQueryClient();
const [name, setName] = useState("");
const create = useMutation({
mutationFn: () => api.createBrand(name.trim()),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["bootstrap"] });
onClose();
},
});
return (
<ModalBackdrop onClose={onClose}>
<div
style={{
width: "min(480px, 96vw)",
margin: "40px 20px",
background: "var(--bg)",
border: "1px solid var(--line)",
borderRadius: "var(--r-lg)",
boxShadow: "var(--shadow-lg)",
}}
>
<ModalHeader title="Add a brand" eyebrow="Catalog" onClose={onClose} />
<div style={{ padding: 32 }}>
<Field label="Brand name">
<Input
autoFocus
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. Foxglove Farms"
/>
</Field>
</div>
<ModalFooter>
<div />
<div style={{ display: "flex", gap: 8 }}>
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
<Btn
variant="primary"
icon="check"
disabled={!name.trim() || create.isPending}
onClick={() => create.mutate()}
>
{create.isPending ? "Saving…" : "Add brand"}
</Btn>
</div>
</ModalFooter>
</div>
</ModalBackdrop>
);
}
export function EditBinModal({
bin,
onClose,
}: {
bin: { id: string; name: string; location: string | null; capacity: number };
onClose: () => void;
}) {
const qc = useQueryClient();
const [name, setName] = useState(bin.name);
const [location, setLocation] = useState(bin.location ?? "");
const [capacity, setCapacity] = useState(bin.capacity);
const update = useMutation({
mutationFn: () =>
api.updateBin(bin.id, { name: name.trim(), location: location.trim(), capacity }),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["bootstrap"] });
onClose();
},
});
return (
<ModalBackdrop onClose={onClose}>
<div
style={{
width: "min(560px, 96vw)",
margin: "40px 20px",
background: "var(--bg)",
border: "1px solid var(--line)",
borderRadius: "var(--r-lg)",
boxShadow: "var(--shadow-lg)",
}}
>
<ModalHeader title="Edit bin" eyebrow="Storage" onClose={onClose} />
<div style={{ padding: 32, display: "grid", gap: 16 }}>
<Field label="Bin name">
<Input
autoFocus
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. Top Drawer"
/>
</Field>
<div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 16 }}>
<Field label="Location (optional)">
<Input
value={location}
onChange={(e) => setLocation(e.target.value)}
placeholder="e.g. Bedroom"
/>
</Field>
<Field label="Capacity">
<Input
type="number"
min={1}
step={1}
value={capacity}
onChange={(e) => setCapacity(Math.max(1, Math.floor(+e.target.value || 1)))}
/>
</Field>
</div>
</div>
<ModalFooter>
<div />
<div style={{ display: "flex", gap: 8 }}>
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
<Btn
variant="primary"
icon="check"
disabled={!name.trim() || update.isPending}
onClick={() => update.mutate()}
>
{update.isPending ? "Saving…" : "Save changes"}
</Btn>
</div>
</ModalFooter>
</div>
</ModalBackdrop>
);
}
export function AddBinModal({ onClose }: { onClose: () => void }) {
const qc = useQueryClient();
const [name, setName] = useState("");
const [location, setLocation] = useState("");
const [capacity, setCapacity] = useState(10);
const create = useMutation({
mutationFn: () =>
api.createBin({ name: name.trim(), location: location.trim(), capacity }),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["bootstrap"] });
onClose();
},
});
return (
<ModalBackdrop onClose={onClose}>
<div
style={{
width: "min(560px, 96vw)",
margin: "40px 20px",
background: "var(--bg)",
border: "1px solid var(--line)",
borderRadius: "var(--r-lg)",
boxShadow: "var(--shadow-lg)",
}}
>
<ModalHeader title="Add a bin" eyebrow="Storage" onClose={onClose} />
<div style={{ padding: 32, display: "grid", gap: 16 }}>
<Field label="Bin name">
<Input
autoFocus
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. Top Drawer"
/>
</Field>
<div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 16 }}>
<Field label="Location (optional)">
<Input
value={location}
onChange={(e) => setLocation(e.target.value)}
placeholder="e.g. Bedroom"
/>
</Field>
<Field label="Capacity">
<Input
type="number"
min={1}
step={1}
value={capacity}
onChange={(e) => setCapacity(Math.max(1, Math.floor(+e.target.value || 1)))}
/>
</Field>
</div>
</div>
<ModalFooter>
<div />
<div style={{ display: "flex", gap: 8 }}>
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
<Btn
variant="primary"
icon="check"
disabled={!name.trim() || create.isPending}
onClick={() => create.mutate()}
>
{create.isPending ? "Saving…" : "Add bin"}
</Btn>
</div>
</ModalFooter>
</div>
</ModalBackdrop>
);
}
export function AddShopModal({ onClose }: { onClose: () => void }) {
const qc = useQueryClient();
const [name, setName] = useState("");
const [location, setLocation] = useState("");
const create = useMutation({
mutationFn: () => api.createShop({ name: name.trim(), location: location.trim() }),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["bootstrap"] });
onClose();
},
});
return (
<ModalBackdrop onClose={onClose}>
<div
style={{
width: "min(560px, 96vw)",
margin: "40px 20px",
background: "var(--bg)",
border: "1px solid var(--line)",
borderRadius: "var(--r-lg)",
boxShadow: "var(--shadow-lg)",
}}
>
<ModalHeader title="Add a shop" eyebrow="Catalog" onClose={onClose} />
<div style={{ padding: 32, display: "grid", gap: 16 }}>
<Field label="Shop name">
<Input
autoFocus
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. Greenleaf Co-op"
/>
</Field>
<Field label="Location (optional)">
<Input
value={location}
onChange={(e) => setLocation(e.target.value)}
placeholder="e.g. Capitol Hill"
/>
</Field>
</div>
<ModalFooter>
<div />
<div style={{ display: "flex", gap: 8 }}>
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
<Btn
variant="primary"
icon="check"
disabled={!name.trim() || create.isPending}
onClick={() => create.mutate()}
>
{create.isPending ? "Saving…" : "Add shop"}
</Btn>
</div>
</ModalFooter>
</div>
</ModalBackdrop>
);
}
+172
View File
@@ -0,0 +1,172 @@
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Bootstrap, Product } from "../../types.js";
import { helpers, TODAY_STR } from "../../types.js";
import { remainingShort } from "../../stats.js";
import { fmt } from "../../format.js";
import { api } from "../../api.js";
import { Btn, Field, Icon, Input, Select, Textarea } from "../primitives/index.js";
import { ScanField } from "../ScanField.js";
import { ModalBackdrop, ModalHeader, ModalFooter } from "./AddProductFlow.js";
export function ConsumeFlow({
data,
onClose,
product: initialProduct,
}: {
data: Bootstrap;
onClose: () => void;
product: Product | null;
}) {
const qc = useQueryClient();
const active = data.products.filter((p) => p.status === "active");
const [productId, setProductId] = useState(initialProduct?.id ?? active[0]?.id ?? "");
const [rating, setRating] = useState(4);
const [notes, setNotes] = useState("");
const [date, setDate] = useState(TODAY_STR);
const product = data.products.find((p) => p.id === productId);
const finish = useMutation({
mutationFn: () => api.finishProduct(productId, { date, rating, notes }),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["bootstrap"] });
onClose();
},
});
if (!product) return null;
const bin = data.bins.find((b) => b.id === product.binId);
const lifespan = Math.round((+new Date(date) - +new Date(product.purchaseDate)) / 86_400_000);
return (
<ModalBackdrop onClose={onClose}>
<div
style={{
width: "min(720px, 96vw)",
margin: "40px 20px",
background: "var(--bg)",
border: "1px solid var(--line)",
borderRadius: "var(--r-lg)",
boxShadow: "var(--shadow-lg)",
}}
>
<ModalHeader title="Mark as consumed" eyebrow="Archive · used up" onClose={onClose} />
<div style={{ padding: 32 }}>
<ScanField
products={active}
matchedProduct={product ?? null}
onMatch={setProductId}
/>
<div style={{ marginTop: 16 }}>
<Field label="Or pick from list">
<Select value={productId} onChange={(e) => setProductId(e.target.value)}>
{active.map((p) => (
<option key={p.id} value={p.id}>
{p.name} {helpers.brandName(data, p.brandId)} ({remainingShort(p)} left)
</option>
))}
</Select>
</Field>
</div>
<div
style={{
marginTop: 16,
padding: 16,
background: "var(--bg-2)",
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<div>
<div className="serif" style={{ fontSize: 22, fontWeight: 500 }}>
{product.name}
</div>
<div style={{ fontSize: 12, color: "var(--ink-3)" }}>
{helpers.brandName(data, product.brandId)} · {bin?.name} · purchased{" "}
{fmt.dateShort(product.purchaseDate)}
</div>
</div>
<div style={{ textAlign: "right" }}>
<div className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>LASTED</div>
<div className="serif" style={{ fontSize: 24 }}>{lifespan} days</div>
</div>
</div>
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 24 }}>
<Field label="Date finished">
<Input type="date" value={date} onChange={(e) => setDate(e.target.value)} />
</Field>
<Field label="Rating">
<div
style={{
display: "flex",
gap: 4,
alignItems: "center",
padding: "10px 12px",
background: "var(--bg)",
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
}}
>
{[1, 2, 3, 4, 5].map((n) => (
<button
key={n}
onClick={() => setRating(n)}
style={{ border: "none", background: "transparent", cursor: "pointer", padding: 2 }}
>
<Icon
name="star"
size={20}
color={n <= rating ? "var(--amber)" : "var(--ink-4)"}
/>
</button>
))}
<span
style={{
marginLeft: "auto",
fontSize: 12,
color: "var(--ink-3)",
fontFamily: "var(--mono)",
}}
>
{rating}/5
</span>
</div>
</Field>
</div>
<div style={{ marginTop: 16 }}>
<Field label="Final notes" hint="Flavor, effects, would you rebuy">
<Textarea
value={notes}
onChange={(e) => setNotes(e.target.value)}
placeholder="What stood out?"
/>
</Field>
</div>
</div>
<ModalFooter>
<div />
<div style={{ display: "flex", gap: 8 }}>
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
<Btn
variant="primary"
icon="check"
disabled={finish.isPending}
onClick={() => finish.mutate()}
>
{finish.isPending ? "Saving…" : "Mark consumed"}
</Btn>
</div>
</ModalFooter>
</div>
</ModalBackdrop>
);
}
+125
View File
@@ -0,0 +1,125 @@
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Bootstrap, Product } from "../../types.js";
import { helpers, TODAY_STR } from "../../types.js";
import { remainingShort } from "../../stats.js";
import { api } from "../../api.js";
import { Btn, Field, Input, Select, Textarea } from "../primitives/index.js";
import { ModalBackdrop, ModalHeader, ModalFooter } from "./AddProductFlow.js";
const REASONS: [string, string][] = [
["lost", "Lost / misplaced"],
["damaged", "Damaged"],
["expired", "Expired"],
["gifted", "Gifted away"],
["other", "Other"],
];
export function MarkGoneFlow({
data,
onClose,
product: initialProduct,
}: {
data: Bootstrap;
onClose: () => void;
product: Product | null;
}) {
const qc = useQueryClient();
const active = data.products.filter((p) => p.status === "active");
const [productId, setProductId] = useState(initialProduct?.id ?? active[0]?.id ?? "");
const [reason, setReason] = useState("lost");
const [notes, setNotes] = useState("");
const [date, setDate] = useState(TODAY_STR);
const product = data.products.find((p) => p.id === productId);
const mark = useMutation({
mutationFn: () => api.markGone(productId, { date, reason, notes }),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["bootstrap"] });
onClose();
},
});
if (!product) return null;
return (
<ModalBackdrop onClose={onClose}>
<div
style={{
width: "min(640px, 96vw)",
margin: "40px 20px",
background: "var(--bg)",
border: "1px solid var(--line)",
borderRadius: "var(--r-lg)",
boxShadow: "var(--shadow-lg)",
}}
>
<ModalHeader
title="Mark as gone"
eyebrow="Archive · not consumed"
eyebrowColor="var(--terracotta)"
onClose={onClose}
/>
<div style={{ padding: 32 }}>
<div
style={{
fontSize: 13,
color: "var(--ink-2)",
marginBottom: 20,
padding: 14,
background: "var(--amber-soft)",
borderRadius: "var(--r-md)",
}}
>
Use this when an item is lost, damaged, expired, or gifted away. Counts as{" "}
<strong>spend</strong> but not as <strong>consumption</strong>, so daily averages stay accurate.
</div>
<Field label="Product">
<Select value={productId} onChange={(e) => setProductId(e.target.value)}>
{active.map((p) => (
<option key={p.id} value={p.id}>
{p.name} {helpers.brandName(data, p.brandId)} ({remainingShort(p)} left)
</option>
))}
</Select>
</Field>
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 16 }}>
<Field label="Reason">
<Select value={reason} onChange={(e) => setReason(e.target.value)}>
{REASONS.map(([k, l]) => (
<option key={k} value={k}>{l}</option>
))}
</Select>
</Field>
<Field label="Date">
<Input type="date" value={date} onChange={(e) => setDate(e.target.value)} />
</Field>
</div>
<div style={{ marginTop: 16 }}>
<Field label="Notes (optional)" hint="What happened">
<Textarea
value={notes}
onChange={(e) => setNotes(e.target.value)}
placeholder="e.g. Pack went through the wash"
/>
</Field>
</div>
</div>
<ModalFooter>
<div />
<div style={{ display: "flex", gap: 8 }}>
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
<Btn variant="danger" icon="bin" disabled={mark.isPending} onClick={() => mark.mutate()}>
{mark.isPending ? "Saving…" : "Mark gone"}
</Btn>
</div>
</ModalFooter>
</div>
</ModalBackdrop>
);
}
+409
View File
@@ -0,0 +1,409 @@
import type { CSSProperties, ReactNode, ButtonHTMLAttributes, InputHTMLAttributes, SelectHTMLAttributes, TextareaHTMLAttributes } from "react";
// ─── Icons ─────────────────────────────────────────────────────────
const ICON_PATHS: Record<string, string> = {
home: "M3 11l9-8 9 8M5 9v12h5v-7h4v7h5V9",
box: "M3 7l9-4 9 4v10l-9 4-9-4V7zM3 7l9 4 9-4M12 11v10",
chart: "M3 21V3M3 21h18M7 17v-7M11 17v-4M15 17v-9M19 17v-2",
plus: "M12 5v14M5 12h14",
check: "M5 13l4 4L19 7",
settings:
"M12 3v3M12 18v3M5 5l2 2M17 17l2 2M3 12h3M18 12h3M5 19l2-2M17 7l2-2M12 8a4 4 0 100 8 4 4 0 000-8z",
search: "M11 19a8 8 0 100-16 8 8 0 000 16zM21 21l-4-4",
filter: "M3 5h18M6 12h12M10 19h4",
bin: "M4 7h16M9 7V4h6v3M6 7v13h12V7",
leaf: "M5 19c0-7 5-14 14-14 0 9-5 14-14 14zM5 19l7-7",
flame: "M12 3c1 4 4 5 4 9a4 4 0 11-8 0c0-2 2-3 2-6 0-1 1-2 2-3z",
droplet: "M12 3l5 7a5 5 0 11-10 0l5-7z",
arrow: "M5 12h14M13 5l7 7-7 7",
arrowDown: "M12 5v14M5 13l7 7 7-7",
close: "M6 6l12 12M18 6L6 18",
edit: "M4 20h4l10-10-4-4L4 16v4zM14 6l4 4",
star: "M12 3l3 6 7 1-5 5 1 7-6-3-6 3 1-7-5-5 7-1z",
calendar: "M5 5h14v15H5zM3 10h18M9 3v4M15 3v4",
tag: "M3 12V3h9l9 9-9 9-9-9zM7 7h.01",
shop: "M4 9V4h16v5M4 9v11h16V9M4 9h16M10 20v-6h4v6",
};
export function Icon({
name,
size = 18,
color = "currentColor",
}: {
name: string;
size?: number;
color?: string;
}) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke={color}
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
style={{ flexShrink: 0 }}
>
<path d={ICON_PATHS[name] ?? ""} />
</svg>
);
}
// ─── Sparkline / BarChart / Donut ──────────────────────────────────
export function Sparkline({
values,
width = 240,
height = 32,
color = "var(--ink)",
fill = false,
}: {
values: number[];
width?: number;
height?: number;
color?: string;
fill?: boolean;
}) {
if (!values.length) return null;
const max = Math.max(...values, 0.001);
const min = Math.min(...values, 0);
const span = max - min || 1;
const step = width / (values.length - 1 || 1);
const pts = values.map((v, i) => [i * step, height - ((v - min) / span) * (height - 4) - 2] as const);
const path = pts.map((p, i) => (i === 0 ? "M" : "L") + p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" ");
const fillPath = fill ? path + ` L ${width} ${height} L 0 ${height} Z` : null;
// width prop defines the path's coordinate space; the rendered SVG stretches
// to fill its container so sparklines grow with their stat card.
return (
<svg
width="100%"
height={height}
viewBox={`0 0 ${width} ${height}`}
preserveAspectRatio="none"
style={{ display: "block", overflow: "visible" }}
>
{fillPath && <path d={fillPath} fill={color} opacity="0.12" vectorEffect="non-scaling-stroke" />}
<path
d={path}
stroke={color}
strokeWidth="1.5"
fill="none"
strokeLinecap="round"
strokeLinejoin="round"
vectorEffect="non-scaling-stroke"
/>
</svg>
);
}
export function BarChart({
data,
height = 160,
color = "var(--sage)",
labels = false,
}: {
data: { value: number; label?: string; muted?: boolean }[];
height?: number;
color?: string;
labels?: boolean;
}) {
if (!data.length) return null;
const max = Math.max(...data.map((d) => d.value), 0.001);
return (
<div style={{ display: "flex", alignItems: "flex-end", gap: 2, height, width: "100%" }}>
{data.map((d, i) => (
<div
key={i}
style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 4, minWidth: 0 }}
>
<div
style={{
width: "100%",
height: `${(d.value / max) * 100}%`,
background: d.value > 0 ? color : "var(--line)",
borderRadius: "2px 2px 0 0",
minHeight: d.value > 0 ? 2 : 1,
opacity: d.muted ? 0.4 : 1,
}}
/>
{labels && d.label != null && (
<div style={{ fontSize: 9, color: "var(--ink-3)", fontFamily: "var(--mono)" }}>{d.label}</div>
)}
</div>
))}
</div>
);
}
export function Donut({
segments,
size = 160,
thickness = 22,
}: {
segments: { label: string; value: number; color: string }[];
size?: number;
thickness?: number;
}) {
const total = segments.reduce((s, x) => s + x.value, 0) || 1;
const r = size / 2 - thickness / 2;
const c = 2 * Math.PI * r;
let offset = 0;
return (
<svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: "rotate(-90deg)" }}>
<circle
cx={size / 2}
cy={size / 2}
r={r}
stroke="var(--line)"
strokeWidth={thickness}
fill="none"
opacity="0.3"
/>
{segments.map((s, i) => {
const len = (s.value / total) * c;
const dash = `${len} ${c - len}`;
const el = (
<circle
key={i}
cx={size / 2}
cy={size / 2}
r={r}
stroke={s.color}
strokeWidth={thickness}
fill="none"
strokeDasharray={dash}
strokeDashoffset={-offset}
strokeLinecap="butt"
/>
);
offset += len;
return el;
})}
</svg>
);
}
// ─── Card / Stat / Pill ────────────────────────────────────────────
export function Card({
children,
style,
padded = true,
}: {
children: ReactNode;
style?: CSSProperties;
padded?: boolean;
}) {
return (
<div
style={{
background: "var(--surface)",
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
padding: padded ? 24 : 0,
...style,
}}
>
{children}
</div>
);
}
export function Stat({
label,
value,
unit,
sub,
spark,
accent,
big,
}: {
label: string;
value: ReactNode;
unit?: string;
sub?: ReactNode;
spark?: ReactNode;
accent?: string;
big?: boolean;
}) {
return (
<div
style={{
background: "var(--surface)",
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
padding: 24,
display: "flex",
flexDirection: "column",
gap: 10,
minWidth: 0,
}}
>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>{label}</div>
<div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
<div
className="serif"
style={{
fontSize: big ? 44 : 32,
lineHeight: 1,
color: accent ?? "var(--ink)",
fontWeight: 500,
letterSpacing: "-0.01em",
}}
>
{value}
</div>
{unit && <div style={{ fontSize: 13, color: "var(--ink-3)", fontFamily: "var(--mono)" }}>{unit}</div>}
</div>
{sub && <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{sub}</div>}
{spark && <div style={{ marginTop: 4 }}>{spark}</div>}
</div>
);
}
type PillTone = "neutral" | "sage" | "terra" | "amber" | "outline";
export function Pill({
children,
tone = "neutral",
style,
}: {
children: ReactNode;
tone?: PillTone;
style?: CSSProperties;
}) {
const tones: Record<PillTone, { bg: string; color: string; border?: string }> = {
neutral: { bg: "var(--bg-3)", color: "var(--ink-2)" },
sage: { bg: "var(--sage-soft)", color: "var(--sage)" },
terra: { bg: "var(--terracotta-soft)", color: "var(--terracotta)" },
amber: { bg: "var(--amber-soft)", color: "oklch(48% 0.10 75)" },
outline: { bg: "transparent", color: "var(--ink-2)", border: "1px solid var(--line-strong)" },
};
const t = tones[tone];
return (
<span
style={{
display: "inline-flex",
alignItems: "center",
gap: 4,
padding: "3px 8px",
borderRadius: 999,
background: t.bg,
color: t.color,
fontSize: 11,
fontWeight: 500,
letterSpacing: "0.02em",
border: t.border ?? "1px solid transparent",
...style,
}}
>
{children}
</span>
);
}
// ─── Button ────────────────────────────────────────────────────────
type BtnVariant = "primary" | "secondary" | "ghost" | "danger" | "sage";
export function Btn({
children,
variant = "ghost",
icon,
onClick,
style,
type,
disabled,
}: {
children?: ReactNode;
variant?: BtnVariant;
icon?: string;
onClick?: ButtonHTMLAttributes<HTMLButtonElement>["onClick"];
style?: CSSProperties;
type?: "button" | "submit" | "reset";
disabled?: boolean;
}) {
const variants: Record<BtnVariant, CSSProperties> = {
primary: disabled
? { background: "var(--bg-3)", color: "var(--ink-3)", border: "1px solid var(--line-strong)" }
: { background: "var(--ink)", color: "var(--bg)", border: "1px solid var(--ink)" },
secondary: { background: "var(--surface)", color: "var(--ink)", border: "1px solid var(--line-strong)" },
ghost: { background: "transparent", color: "var(--ink-2)", border: "1px solid transparent" },
danger: { background: "var(--terracotta)", color: "oklch(98% 0.01 40)", border: "1px solid var(--terracotta)" },
sage: { background: "var(--sage)", color: "oklch(98% 0.01 145)", border: "1px solid var(--sage)" },
};
const v = variants[variant];
return (
<button
type={type}
onClick={onClick}
disabled={disabled}
style={{
display: "inline-flex",
alignItems: "center",
gap: 6,
padding: "8px 14px",
borderRadius: "var(--r-md)",
fontSize: 13,
fontWeight: 600,
transition: "all 120ms",
cursor: disabled ? "not-allowed" : "pointer",
...v,
...style,
}}
>
{icon && <Icon name={icon} size={14} />}
{children}
</button>
);
}
// ─── Field / Input / Select / Textarea ────────────────────────────
export const inputStyle: CSSProperties = {
background: "var(--bg)",
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
padding: "10px 12px",
fontSize: 13,
color: "var(--ink)",
outline: "none",
fontFamily: "var(--sans)",
width: "100%",
};
export function Field({
label,
children,
hint,
span = 1,
}: {
label: string;
children: ReactNode;
hint?: string;
span?: number;
}) {
return (
<label style={{ display: "flex", flexDirection: "column", gap: 6, gridColumn: `span ${span}` }}>
<span className="smallcaps" style={{ color: "var(--ink-3)" }}>{label}</span>
{children}
{hint && <span style={{ fontSize: 11, color: "var(--ink-3)" }}>{hint}</span>}
</label>
);
}
export function Input(props: InputHTMLAttributes<HTMLInputElement>) {
const { style, ...rest } = props;
return <input style={{ ...inputStyle, ...style }} {...rest} />;
}
export function Select(props: SelectHTMLAttributes<HTMLSelectElement>) {
const { style, children, ...rest } = props;
return (
<select style={{ ...inputStyle, appearance: "auto", ...style }} {...rest}>
{children}
</select>
);
}
export function Textarea(props: TextareaHTMLAttributes<HTMLTextAreaElement>) {
const { style, ...rest } = props;
return <textarea style={{ ...inputStyle, minHeight: 80, resize: "vertical", ...style }} {...rest} />;
}
+49
View File
@@ -0,0 +1,49 @@
// fmt.* — verbatim port from primitives.jsx
export const fmt = {
g(n: number | null | undefined): string {
if (n == null) return "—";
const trimmed = (+n).toFixed(2).replace(/\.?0+$/, "");
return `${trimmed || "0"} g`;
},
money(n: number | null | undefined): string {
if (n == null) return "—";
return `$${(+n).toFixed(2)}`;
},
moneyShort(n: number | null | undefined): string {
if (n == null) return "—";
return n >= 100 ? `$${Math.round(n)}` : `$${(+n).toFixed(2)}`;
},
pct(n: number | null | undefined): string {
if (n == null) return "—";
return `${(+n).toFixed(1)}%`;
},
date(s: string | null | undefined): string {
if (!s) return "—";
const d = new Date(s);
return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
},
dateShort(s: string | null | undefined): string {
if (!s) return "—";
const d = new Date(s);
return d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
},
daysAgo(s: string | null | undefined): string {
if (!s) return "—";
const ms = Date.now() - new Date(s).getTime();
const d = Math.floor(ms / 86_400_000);
if (d === 0) return "today";
if (d === 1) return "yesterday";
if (d < 30) return `${d}d ago`;
if (d < 365) return `${Math.floor(d / 30)}mo ago`;
return `${Math.floor(d / 365)}y ago`;
},
};
export const TYPE_GLYPHS: Record<string, string> = {
Flower: "✿",
Concentrate: "◆",
Edible: "◐",
Vaporizer: "▢",
"Pre-roll": "│",
Tincture: "◯",
};
+21
View File
@@ -0,0 +1,21 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { App } from "./App.js";
import "./tokens.css";
import "./styles/global.css";
const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 30_000, refetchOnWindowFocus: false } },
});
const STORED_THEME = (localStorage.getItem("apothecary.theme") ?? "light") as "light" | "dark";
document.documentElement.dataset.theme = STORED_THEME;
createRoot(document.getElementById("root")!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</StrictMode>,
);
+291
View File
@@ -0,0 +1,291 @@
// computeStats — ported from primitives.jsx:41-235
// Derives daily/weekly/monthly grams from purchase + audit history,
// using estimated remaining for active items and full weight for consumed.
// Gone items contribute spend but NOT grams (so daily averages stay clean).
import type { Bootstrap, Product } from "./types.js";
import { TYPES, TODAY_STR, helpers } from "./types.js";
export interface Stats {
dailyAvg: number;
weeklyAvg: number;
monthlyAvg: number;
totalSpend: number;
avgPerGram: number;
spend7: number;
spend30: number;
spend90: number;
goneSpend: number;
inventoryValue: number;
inventoryGrams: number;
totalGrams: number;
thcLast7: number;
thcLast30: number;
avgLifespan: number;
favShop: [string, number];
favBrand: [string, number];
typeBreakdown: Record<string, number>;
daysOfSupply: number;
avgGap: number;
series7: { date: string; grams: number }[];
series30: { date: string; grams: number }[];
series90: { date: string; grams: number }[];
activeCount: number;
consumedCount: number;
goneCount: number;
archivedCount: number;
overdueAudits: Product[];
lowStockBulk: Product[];
lowStockDiscreteGroups: {
key: string;
name: string;
type: string;
brandId: string | null;
items: Product[];
totalCount: number;
}[];
}
export function computeStats(data: Bootstrap): Stats {
const today = new Date(data.today || TODAY_STR);
const todayStr = today.toISOString().slice(0, 10);
const products = data.products;
const dayKey = (d: Date) => d.toISOString().slice(0, 10);
const active = products.filter((p) => p.status === "active");
const consumed = products.filter((p) => p.status === "consumed" && p.consumedDate);
const gone = products.filter((p) => p.status === "gone");
const purchasesIn = (days: number) => {
const cutoff = new Date(today);
cutoff.setDate(cutoff.getDate() - days);
return products.filter((p) => new Date(p.purchaseDate) >= cutoff);
};
const last7p = purchasesIn(7);
const last30p = purchasesIn(30);
const last90p = purchasesIn(90);
const bulkGrams = (p: Product): number => {
if (p.type === "Tincture" || p.type === "Edible") return 0;
if (p.kind === "bulk") return p.weight;
return (p.countOriginal || 0) * (p.unitWeight || 0);
};
const bulkGramsConsumed = (p: Product): number => {
if (p.type === "Tincture" || p.type === "Edible") return 0;
if (p.kind === "bulk") return p.weight;
return (p.countOriginal || 0) * (p.unitWeight || 0);
};
const bulkGramsUsedSoFar = (p: Product): number => {
if (p.type === "Tincture" || p.type === "Edible") return 0;
if (p.kind === "bulk") {
const est = helpers.estimatedRemaining(p, todayStr);
return Math.max(0, p.weight - est);
}
const cur = p.countLastAudit ?? p.countOriginal;
return Math.max(0, p.countOriginal - cur) * (p.unitWeight || 0);
};
const dailyGramsAttribution: Record<string, number> = {};
consumed.forEach((p) => {
const g = bulkGramsConsumed(p);
if (g <= 0 || !p.consumedDate) return;
const start = new Date(p.purchaseDate);
const end = new Date(p.consumedDate);
const days = Math.max(1, Math.round((+end - +start) / 86_400_000));
const perDay = g / days;
for (let i = 0; i < days; i++) {
const d = new Date(start);
d.setDate(d.getDate() + i);
const k = dayKey(d);
dailyGramsAttribution[k] = (dailyGramsAttribution[k] || 0) + perDay;
}
});
active.forEach((p) => {
const used = bulkGramsUsedSoFar(p);
if (used <= 0) return;
const start = new Date(p.purchaseDate);
const days = Math.max(1, Math.round((+today - +start) / 86_400_000));
const perDay = used / days;
for (let i = 0; i < days; i++) {
const d = new Date(start);
d.setDate(d.getDate() + i);
const k = dayKey(d);
dailyGramsAttribution[k] = (dailyGramsAttribution[k] || 0) + perDay;
}
});
const seriesFor = (days: number) => {
const out: { date: string; grams: number }[] = [];
for (let i = days - 1; i >= 0; i--) {
const d = new Date(today);
d.setDate(d.getDate() - i);
const k = dayKey(d);
out.push({ date: k, grams: dailyGramsAttribution[k] || 0 });
}
return out;
};
const series7 = seriesFor(7);
const series30 = seriesFor(30);
const series90 = seriesFor(90);
const sumG = (xs: { grams: number }[]) => xs.reduce((s, x) => s + x.grams, 0);
const dailyAvg = sumG(series30) / 30;
const weeklyAvg = sumG(series30) / (30 / 7);
const monthlyAvg = sumG(series90) / 3;
const totalSpend = products.reduce((s, p) => s + p.price, 0);
const goneSpend = gone.reduce((s, p) => s + p.price, 0);
const totalGrams = products.reduce((s, p) => s + bulkGrams(p), 0);
const avgPerGram = totalGrams ? totalSpend / totalGrams : 0;
const spend30 = last30p.reduce((s, p) => s + p.price, 0);
const spend7 = last7p.reduce((s, p) => s + p.price, 0);
const spend90 = last90p.reduce((s, p) => s + p.price, 0);
const inventoryValue = active.reduce(
(s, p) => s + p.price * helpers.pctRemaining(p, todayStr),
0,
);
// Grams currently on hand: bulk uses estimated remaining; discrete uses
// (units × per-unit weight). Tincture (ml) and edibles (count) are excluded
// to match the existing `bulkGrams` convention used for $/g and totals.
const inventoryGrams = active.reduce((s, p) => {
if (p.type === "Tincture" || p.type === "Edible") return s;
if (p.kind === "bulk") return s + helpers.estimatedRemaining(p, todayStr);
const cur = p.countLastAudit ?? p.countOriginal;
return s + cur * (p.unitWeight || 0);
}, 0);
const avgThc =
products.length > 0 ? products.reduce((s, p) => s + p.thc, 0) / products.length : 20;
const thcLast7 = Math.round(sumG(series7) * avgThc * 10);
const thcLast30 = Math.round(sumG(series30) * avgThc * 10);
const lifespans = consumed.map((p) =>
Math.max(
1,
Math.round((+new Date(p.consumedDate!) - +new Date(p.purchaseDate)) / 86_400_000),
),
);
const avgLifespan =
lifespans.length > 0 ? lifespans.reduce((a, b) => a + b, 0) / lifespans.length : 0;
const shopCount: Record<string, number> = {};
const brandCount: Record<string, number> = {};
products.forEach((p) => {
if (p.shopId) shopCount[p.shopId] = (shopCount[p.shopId] || 0) + 1;
if (p.brandId) brandCount[p.brandId] = (brandCount[p.brandId] || 0) + 1;
});
const topShopEntry = Object.entries(shopCount).sort((a, b) => b[1] - a[1])[0];
const topBrandEntry = Object.entries(brandCount).sort((a, b) => b[1] - a[1])[0];
const favShop: [string, number] = topShopEntry
? [helpers.shopName(data, topShopEntry[0]), topShopEntry[1]]
: ["—", 0];
const favBrand: [string, number] = topBrandEntry
? [helpers.brandName(data, topBrandEntry[0]), topBrandEntry[1]]
: ["—", 0];
const typeBreakdown: Record<string, number> = {};
active.forEach((p) => {
let g: number;
if (p.type === "Tincture") g = helpers.estimatedRemaining(p, todayStr) * 0.5;
else if (p.type === "Edible")
g = (p.countLastAudit ?? p.countOriginal) * 0.3;
else if (p.kind === "bulk") g = helpers.estimatedRemaining(p, todayStr);
else g = (p.countLastAudit ?? p.countOriginal) * (p.unitWeight || 0);
if (g > 0) typeBreakdown[p.type] = (typeBreakdown[p.type] || 0) + g;
});
const flowerEquivalent = active
.filter((p) => p.type === "Flower" || p.type === "Pre-roll")
.reduce((s, p) => {
if (p.kind === "bulk") return s + helpers.estimatedRemaining(p, todayStr);
return s + (p.countLastAudit ?? p.countOriginal) * (p.unitWeight || 0);
}, 0);
const daysOfSupply = dailyAvg > 0 ? flowerEquivalent / dailyAvg : 0;
const sortedDates = [...products]
.sort((a, b) => +new Date(a.purchaseDate) - +new Date(b.purchaseDate))
.map((p) => new Date(p.purchaseDate));
const gaps: number[] = [];
for (let i = 1; i < sortedDates.length; i++) {
gaps.push((+sortedDates[i]! - +sortedDates[i - 1]!) / 86_400_000);
}
const avgGap = gaps.length > 0 ? gaps.reduce((a, b) => a + b, 0) / gaps.length : 0;
const overdueAudits = active.filter((p) => helpers.auditOverdue(p, todayStr));
const lowStockBulk = active.filter(
(p) => p.kind === "bulk" && helpers.pctRemaining(p, todayStr) < 0.25,
);
const discreteBrandGroups: Record<
string,
{ key: string; name: string; type: string; brandId: string | null; items: Product[]; totalCount: number }
> = {};
active
.filter((p) => p.kind === "discrete")
.forEach((p) => {
const k = `${p.brandId}|${p.type}|${p.name}`;
if (!discreteBrandGroups[k]) {
discreteBrandGroups[k] = {
key: k,
name: p.name,
type: p.type,
brandId: p.brandId,
items: [],
totalCount: 0,
};
}
discreteBrandGroups[k].items.push(p);
discreteBrandGroups[k].totalCount += p.countLastAudit ?? p.countOriginal;
});
const lowStockDiscreteGroups = Object.values(discreteBrandGroups).filter(
(g) => g.totalCount <= 2,
);
return {
dailyAvg,
weeklyAvg,
monthlyAvg,
totalSpend,
avgPerGram,
spend7,
spend30,
spend90,
goneSpend,
inventoryValue,
inventoryGrams,
totalGrams,
thcLast7,
thcLast30,
avgLifespan,
favShop,
favBrand,
typeBreakdown,
daysOfSupply,
avgGap,
series7,
series30,
series90,
activeCount: active.length,
consumedCount: consumed.length,
goneCount: gone.length,
archivedCount: consumed.length + gone.length,
overdueAudits,
lowStockBulk,
lowStockDiscreteGroups,
};
}
// Display helpers used throughout the UI
export function remainingShort(p: Product): string {
const cfg = TYPES.find((t) => t.id === p.type);
if (p.kind === "discrete") {
const cur = p.countLastAudit ?? p.countOriginal;
return `${cur} ct`;
}
const est = helpers.estimatedRemaining(p);
const trimmed = est.toFixed(2).replace(/\.?0+$/, "") || "0";
return `${trimmed} ${cfg?.unit ?? "g"}`;
}
+104
View File
@@ -0,0 +1,104 @@
/* App chrome — ported from Apothecary - Inventory.html lines 1186 */
.app-shell {
min-height: 100vh;
display: grid;
grid-template-columns: 264px 1fr;
}
.sidebar {
border-right: 1px solid var(--line);
background: var(--bg-2);
padding: 28px 18px;
display: flex;
flex-direction: column;
gap: 4px;
position: sticky;
top: 0;
height: 100vh;
overflow: auto;
}
.brand {
display: flex;
align-items: center;
gap: 10px;
padding: 0 8px 28px;
}
.brand-mark {
width: 40px;
height: 40px;
border-radius: 50%;
border: 1px solid var(--ink);
display: flex;
align-items: center;
justify-content: center;
font-family: var(--serif);
font-size: 22px;
font-style: italic;
color: var(--ink);
}
.nav-link {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 12px;
border-radius: var(--r-md);
color: var(--ink-2);
cursor: pointer;
font-size: 14px;
font-weight: 500;
border: none;
background: transparent;
text-align: left;
transition: background 100ms;
}
.nav-link:hover {
background: var(--bg-3);
color: var(--ink);
}
.nav-link.active {
background: var(--surface);
color: var(--ink);
box-shadow: var(--shadow-sm);
border: 1px solid var(--line);
}
.nav-section {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.12em;
color: var(--ink-3);
padding: 16px 12px 6px;
font-weight: 500;
}
.inv-row:hover {
background: var(--bg-2);
}
@media (max-width: 880px) {
.app-shell {
grid-template-columns: 1fr;
}
.sidebar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
top: auto;
height: auto;
flex-direction: row;
padding: 8px 12px;
border-top: 1px solid var(--line);
border-right: none;
z-index: 30;
overflow-x: auto;
}
.brand,
.nav-section {
display: none;
}
.nav-link {
white-space: nowrap;
padding: 8px 12px;
}
.main {
padding-bottom: 60px;
}
}
+113
View File
@@ -0,0 +1,113 @@
/* Apothecary / Botanical design tokens
Warm earthy neutrals — parchment, ink, sage, terracotta */
:root {
/* Surfaces — parchment-toned */
--bg: oklch(96% 0.012 80); /* parchment */
--bg-2: oklch(93% 0.014 80); /* slightly darker parchment */
--bg-3: oklch(89% 0.016 78); /* card divider, hover */
--surface: oklch(98% 0.008 82); /* card surface */
--surface-sunken: oklch(91% 0.014 80);
/* Ink — warm near-blacks */
--ink: oklch(22% 0.012 60); /* primary text */
--ink-2: oklch(38% 0.012 60); /* secondary text */
--ink-3: oklch(56% 0.014 65); /* tertiary, captions */
--ink-4: oklch(72% 0.014 70); /* faint, dividers */
/* Lines */
--line: oklch(82% 0.014 75);
--line-strong: oklch(68% 0.016 70);
/* Accents — share chroma 0.08, lightness 52% */
--sage: oklch(52% 0.06 145); /* primary action / good */
--sage-2: oklch(64% 0.05 145);
--sage-soft: oklch(88% 0.03 145);
--terracotta: oklch(58% 0.10 40); /* warning / consumed */
--terracotta-soft: oklch(90% 0.04 40);
--amber: oklch(68% 0.10 75); /* low stock / attention */
--amber-soft: oklch(91% 0.04 75);
--plum: oklch(48% 0.06 340); /* secondary accent */
/* Typography */
--serif: "Cormorant Garamond", "GT Sectra", "Playfair Display", Georgia, serif;
--sans: "Inter", "Söhne", -apple-system, BlinkMacSystemFont, sans-serif;
--mono: "JetBrains Mono", "IBM Plex Mono", ui-monospace, Menlo, monospace;
/* Radii */
--r-sm: 4px;
--r-md: 8px;
--r-lg: 14px;
--r-xl: 20px;
/* Shadow — subtle */
--shadow-sm: 0 1px 2px oklch(20% 0.02 60 / 0.06);
--shadow-md: 0 2px 8px oklch(20% 0.02 60 / 0.08);
--shadow-lg: 0 8px 24px oklch(20% 0.02 60 / 0.10);
}
[data-theme="dark"] {
--bg: oklch(20% 0.012 60);
--bg-2: oklch(23% 0.012 60);
--bg-3: oklch(27% 0.014 65);
--surface: oklch(25% 0.012 60);
--surface-sunken: oklch(18% 0.012 60);
--ink: oklch(94% 0.008 80);
--ink-2: oklch(78% 0.012 75);
--ink-3: oklch(62% 0.014 70);
--ink-4: oklch(46% 0.014 65);
--line: oklch(34% 0.014 65);
--line-strong: oklch(48% 0.016 65);
--sage: oklch(70% 0.07 145);
--sage-2: oklch(60% 0.06 145);
--sage-soft: oklch(32% 0.04 145);
--terracotta: oklch(70% 0.10 40);
--terracotta-soft: oklch(32% 0.05 40);
--amber: oklch(78% 0.10 75);
--amber-soft: oklch(32% 0.05 75);
}
* { box-sizing: border-box; }
html, body {
margin: 0;
padding: 0;
background: var(--bg);
color: var(--ink);
font-family: var(--sans);
font-size: 14px;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
button { font-family: inherit; cursor: pointer; }
input, select, textarea { font-family: inherit; }
/* Subtle parchment texture */
.parchment {
background-image:
radial-gradient(oklch(85% 0.03 75 / 0.15) 1px, transparent 1px),
radial-gradient(oklch(80% 0.03 75 / 0.10) 1px, transparent 1px);
background-size: 24px 24px, 36px 36px;
background-position: 0 0, 12px 18px;
}
/* Utility */
.serif { font-family: var(--serif); font-weight: 500; }
.mono { font-family: var(--mono); font-feature-settings: "ss01", "cv11"; }
.smallcaps {
text-transform: uppercase;
letter-spacing: 0.12em;
font-size: 11px;
font-weight: 500;
}
.hairline { border-top: 1px solid var(--line); }
+155
View File
@@ -0,0 +1,155 @@
export type ProductStatus = "active" | "consumed" | "gone";
export type ProductKind = "bulk" | "discrete";
export type AuditMode = "weigh" | "estimate" | "presence";
export interface Audit {
date: string;
mode: AuditMode;
value: number;
prev: number | null;
confirmedBy: string | null;
}
export interface Product {
id: string;
sku: string;
assetTag: string | null;
name: string;
brandId: string | null;
shopId: string | null;
binId: string | null;
type: string;
kind: ProductKind;
weight: number;
lastAuditWeight: number | null;
countOriginal: number;
countLastAudit: number | null;
unitWeight: number;
price: number;
thc: number;
cbd: number;
totalCannabinoids: number;
purchaseDate: string;
status: ProductStatus;
consumedDate: string | null;
goneDate: string | null;
rating: number | null;
notes: string | null;
strainId: string | null;
audits: Audit[];
}
export interface Strain {
id: string;
name: string;
brandId: string | null;
type: string;
defaultThc: number | null;
defaultCbd: number | null;
defaultTotalCannabinoids: number | null;
notes: string | null;
}
export interface Brand {
id: string;
name: string;
}
export interface Shop {
id: string;
name: string;
location: string | null;
}
export interface Bin {
id: string;
name: string;
location: string | null;
capacity: number;
}
export interface TypeConfig {
id: string;
kind: ProductKind;
auditMode: AuditMode;
cadenceDays: number;
unit: string;
weighable: boolean;
}
export interface Bootstrap {
products: Product[];
brands: Brand[];
shops: Shop[];
bins: Bin[];
strains: Strain[];
today: string;
}
// Type config lives client-side — static, not user data.
// Mirrors data.js TYPES array.
export const TYPES: TypeConfig[] = [
{ id: "Flower", kind: "bulk", auditMode: "weigh", cadenceDays: 14, unit: "g", weighable: true },
{ id: "Concentrate", kind: "bulk", auditMode: "estimate", cadenceDays: 21, unit: "g", weighable: true },
{ id: "Tincture", kind: "bulk", auditMode: "estimate", cadenceDays: 30, unit: "ml", weighable: false },
{ id: "Pre-roll", kind: "discrete", auditMode: "presence", cadenceDays: 30, unit: "ct", weighable: false },
{ id: "Edible", kind: "discrete", auditMode: "presence", cadenceDays: 60, unit: "ct", weighable: false },
{ id: "Vaporizer", kind: "discrete", auditMode: "presence", cadenceDays: 30, unit: "ct", weighable: false },
];
export const TODAY_STR = "2026-04-25";
// Helpers — match data.js DATA_HELPERS API
export const helpers = {
shopName(data: { shops: Shop[] }, id: string | null): string {
return data.shops.find((s) => s.id === id)?.name ?? "—";
},
brandName(data: { brands: Brand[] }, id: string | null): string {
return data.brands.find((b) => b.id === id)?.name ?? "—";
},
typeConfig(id: string): TypeConfig {
return TYPES.find((t) => t.id === id) ?? TYPES[0]!;
},
daysSince(iso: string | null, today = TODAY_STR): number {
if (!iso) return Infinity;
return Math.floor((+new Date(today) - +new Date(iso)) / 86_400_000);
},
lastAudit(p: Product): Audit | null {
return p.audits.length > 0 ? p.audits[p.audits.length - 1]! : null;
},
daysSinceCheck(p: Product, today = TODAY_STR): number {
const last = p.audits.length > 0 ? p.audits[p.audits.length - 1]!.date : p.purchaseDate;
return Math.floor((+new Date(today) - +new Date(last)) / 86_400_000);
},
auditOverdue(p: Product, today = TODAY_STR): boolean {
if (p.status !== "active") return false;
const cfg = TYPES.find((t) => t.id === p.type);
if (!cfg) return false;
return this.daysSinceCheck(p, today) >= cfg.cadenceDays;
},
estimatedRemaining(p: Product, today = TODAY_STR): number {
if (p.status !== "active") return 0;
if (p.kind === "discrete") {
return p.countLastAudit ?? p.countOriginal;
}
const last = this.lastAudit(p);
const baseDate = last ? last.date : p.purchaseDate;
const baseValue = last ? last.value : p.weight;
const daysSinceBase = Math.max(
0,
Math.floor((+new Date(today) - +new Date(baseDate)) / 86_400_000),
);
const expectedLifespan =
p.type === "Flower" ? 35 : p.type === "Concentrate" ? 40 : 90;
const dailyBurn = p.weight / expectedLifespan;
return Math.max(0, baseValue - dailyBurn * daysSinceBase);
},
pctRemaining(p: Product, today = TODAY_STR): number {
if (p.kind === "discrete") {
const cur = p.countLastAudit ?? p.countOriginal;
return p.countOriginal > 0 ? cur / p.countOriginal : 0;
}
const est = this.estimatedRemaining(p, today);
return p.weight > 0 ? est / p.weight : 0;
},
};
+233
View File
@@ -0,0 +1,233 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Bootstrap, Bin, Product } from "../types.js";
import { helpers, TODAY_STR } from "../types.js";
import { remainingShort } from "../stats.js";
import { fmt, TYPE_GLYPHS } from "../format.js";
import { api } from "../api.js";
import { Btn, Card, Pill, Icon } from "../components/primitives/index.js";
export function BinsView({
data,
onSelectProduct,
onAddBin,
onEditBin,
}: {
data: Bootstrap;
onSelectProduct: (p: Product) => void;
onAddBin: () => void;
onEditBin: (bin: Bin) => void;
}) {
const qc = useQueryClient();
const remove = useMutation({
mutationFn: (id: string) => api.deleteBin(id),
onSuccess: () => qc.invalidateQueries({ queryKey: ["bootstrap"] }),
});
const handleDelete = (binId: string, binName: string, activeCount: number) => {
const msg =
activeCount > 0
? `Delete "${binName}"? ${activeCount} active product${activeCount === 1 ? "" : "s"} will be moved to Unassigned.`
: `Delete "${binName}"?`;
if (window.confirm(msg)) remove.mutate(binId);
};
return (
<div
style={{
padding: "clamp(32px, 3vw, 64px) clamp(40px, 3vw, 80px) 80px",
maxWidth: 2400,
margin: "0 auto",
}}
>
<div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 24 }}>
<div>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>{data.bins.length} bins</div>
<h1
className="serif"
style={{ fontSize: 44, margin: "6px 0 0", fontWeight: 500, letterSpacing: "-0.02em" }}
>
Bins & storage
</h1>
</div>
<Btn variant="secondary" icon="plus" onClick={onAddBin}>New bin</Btn>
</div>
<div style={{ fontSize: 14, color: "var(--ink-2)", marginBottom: 24, maxWidth: 600 }}>
Where each active product physically lives. Archived items aren't assigned to a bin.
</div>
{data.bins.length === 0 && (
<Card style={{ padding: 60, textAlign: "center" }}>
<div className="serif" style={{ fontSize: 22, marginBottom: 6 }}>No bins yet</div>
<div style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 18 }}>
Add a bin to start placing products somewhere.
</div>
<Btn variant="primary" icon="plus" onClick={onAddBin}>Add your first bin</Btn>
</Card>
)}
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fill, minmax(380px, 1fr))",
gap: 14,
}}
>
{data.bins.map((bin) => {
const items = data.products.filter((p) => p.binId === bin.id && p.status === "active");
const fillPct = items.length / bin.capacity;
const totalValue = items.reduce(
(s, p) => s + p.price * helpers.pctRemaining(p, TODAY_STR),
0,
);
return (
<Card key={bin.id} padded={false} style={{ display: "flex", flexDirection: "column" }}>
<div style={{ padding: "20px 22px 16px", borderBottom: "1px solid var(--line)" }}>
<div
style={{
display: "flex",
alignItems: "baseline",
justifyContent: "space-between",
marginBottom: 4,
gap: 8,
}}
>
<h3 className="serif" style={{ fontSize: 24, margin: 0, fontWeight: 500 }}>
{bin.name}
</h3>
<div style={{ display: "flex", alignItems: "center", gap: 6 }}>
<Pill tone="outline">{items.length} / {bin.capacity}</Pill>
<button
onClick={() => onEditBin(bin)}
title="Edit bin"
aria-label={`Edit bin ${bin.name}`}
style={{
background: "transparent",
border: "none",
padding: 4,
borderRadius: "var(--r-sm)",
cursor: "pointer",
color: "var(--ink-3)",
display: "inline-flex",
}}
>
<Icon name="edit" size={14} />
</button>
<button
onClick={() => handleDelete(bin.id, bin.name, items.length)}
title="Remove bin"
aria-label={`Remove bin ${bin.name}`}
disabled={remove.isPending}
style={{
background: "transparent",
border: "none",
padding: 4,
borderRadius: "var(--r-sm)",
cursor: remove.isPending ? "wait" : "pointer",
color: "var(--ink-3)",
display: "inline-flex",
}}
>
<Icon name="bin" size={14} />
</button>
</div>
</div>
<div
style={{
fontSize: 12,
color: "var(--ink-3)",
display: "flex",
justifyContent: "space-between",
}}
>
<span>{bin.location}</span>
<span className="mono">{fmt.money(totalValue)}</span>
</div>
<div
style={{
marginTop: 12,
height: 4,
background: "var(--bg-3)",
borderRadius: 2,
overflow: "hidden",
}}
>
<div
style={{
width: `${Math.min(fillPct, 1) * 100}%`,
height: "100%",
background:
fillPct > 0.9
? "var(--terracotta)"
: fillPct > 0.7
? "var(--amber)"
: "var(--sage)",
}}
/>
</div>
</div>
<div style={{ padding: 8, flex: 1 }}>
{items.length === 0 && (
<div
style={{
padding: 30,
textAlign: "center",
fontSize: 12,
color: "var(--ink-3)",
fontStyle: "italic",
}}
>
Empty
</div>
)}
{items.map((p) => (
<div
key={p.id}
onClick={() => onSelectProduct(p)}
style={{
display: "flex",
alignItems: "center",
gap: 10,
padding: "8px 14px",
borderRadius: "var(--r-sm)",
cursor: "pointer",
}}
>
<div
style={{
fontFamily: "var(--serif)",
fontSize: 18,
color: "var(--ink-3)",
width: 18,
}}
>
{TYPE_GLYPHS[p.type]}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div
style={{
fontSize: 13,
fontWeight: 500,
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
}}
>
{p.name}
</div>
<div style={{ fontSize: 11, color: "var(--ink-3)" }}>
{helpers.brandName(data, p.brandId)}
</div>
</div>
<div className="mono" style={{ fontSize: 11, color: "var(--ink-2)" }}>
{remainingShort(p)}
</div>
</div>
))}
</div>
</Card>
);
})}
</div>
</div>
);
}
+72
View File
@@ -0,0 +1,72 @@
import type { Bootstrap } from "../types.js";
import { Btn, Card, Pill } from "../components/primitives/index.js";
export function BrandsView({
data,
onAddBrand,
}: {
data: Bootstrap;
onAddBrand: () => void;
}) {
return (
<div
style={{
padding: "clamp(32px, 3vw, 64px) clamp(40px, 3vw, 80px) 80px",
maxWidth: 2400,
margin: "0 auto",
}}
>
<div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 24 }}>
<div>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>
{data.brands.length} brand{data.brands.length === 1 ? "" : "s"}
</div>
<h1
className="serif"
style={{ fontSize: 44, margin: "6px 0 0", fontWeight: 500, letterSpacing: "-0.02em" }}
>
Brands
</h1>
</div>
<Btn variant="primary" icon="plus" onClick={onAddBrand}>New brand</Btn>
</div>
<div style={{ fontSize: 14, color: "var(--ink-2)", marginBottom: 24, maxWidth: 600 }}>
Brands you've purchased from. Used in the brand dropdown when adding a new product.
</div>
{data.brands.length === 0 ? (
<Card style={{ padding: 60, textAlign: "center" }}>
<div className="serif" style={{ fontSize: 22, marginBottom: 6 }}>No brands yet</div>
<div style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 18 }}>
Add a brand to start tagging your purchases.
</div>
<Btn variant="primary" icon="plus" onClick={onAddBrand}>Add your first brand</Btn>
</Card>
) : (
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))",
gap: 14,
}}
>
{data.brands.map((b) => {
const count = data.products.filter((p) => p.brandId === b.id).length;
return (
<Card key={b.id} style={{ display: "flex", alignItems: "center", gap: 12 }}>
<div style={{ flex: 1, minWidth: 0 }}>
<div className="serif" style={{ fontSize: 22, fontWeight: 500, lineHeight: 1.1 }}>
{b.name}
</div>
</div>
<Pill tone="outline">
{count} purchase{count === 1 ? "" : "s"}
</Pill>
</Card>
);
})}
</div>
)}
</div>
);
}
+271
View File
@@ -0,0 +1,271 @@
import type { Bootstrap } from "../types.js";
import { helpers } from "../types.js";
import type { Stats } from "../stats.js";
import { fmt } from "../format.js";
import { BarChart, Card } from "../components/primitives/index.js";
export function ChartsView({ data, stats }: { data: Bootstrap; stats: Stats }) {
const series = stats.series90.map((s) => ({ date: s.date, grams: s.grams }));
const spendByMonth: Record<string, number> = {};
data.products.forEach((p) => {
const k = p.purchaseDate.slice(0, 7);
spendByMonth[k] = (spendByMonth[k] ?? 0) + p.price;
});
const months = Object.entries(spendByMonth).sort();
const spendByShop: Record<string, number> = {};
data.products.forEach((p) => {
const name = helpers.shopName(data, p.shopId);
spendByShop[name] = (spendByShop[name] ?? 0) + p.price;
});
const shopRanked = Object.entries(spendByShop).sort((a, b) => b[1] - a[1]);
const shopMax = shopRanked[0]?.[1] ?? 1;
const monthMax = Math.max(...months.map((x) => x[1]), 1);
return (
<div
style={{
padding: "clamp(32px, 3vw, 64px) clamp(40px, 3vw, 80px) 80px",
maxWidth: 2400,
margin: "0 auto",
}}
>
<div style={{ marginBottom: 24 }}>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>Last 90 days</div>
<h1
className="serif"
style={{ fontSize: 44, margin: "6px 0 0", fontWeight: 500, letterSpacing: "-0.02em" }}
>
Patterns & spend
</h1>
</div>
<Card style={{ marginBottom: 14 }}>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "baseline",
marginBottom: 18,
}}
>
<div className="serif" style={{ fontSize: 22 }}>Daily grams · 90 days</div>
<div style={{ display: "flex", gap: 24, fontSize: 12, color: "var(--ink-3)" }}>
<div>
Total{" "}
<span className="serif" style={{ fontSize: 18, color: "var(--ink)" }}>
{series.reduce((s, e) => s + e.grams, 0).toFixed(1)} g
</span>
</div>
<div>
Avg{" "}
<span className="serif" style={{ fontSize: 18, color: "var(--ink)" }}>
{(series.reduce((s, e) => s + e.grams, 0) / 90).toFixed(2)} g/day
</span>
</div>
<div>
Items finished{" "}
<span className="serif" style={{ fontSize: 18, color: "var(--ink)" }}>{stats.consumedCount}</span>
</div>
{stats.goneCount > 0 && (
<div>
Items gone{" "}
<span className="serif" style={{ fontSize: 18, color: "var(--ink)" }}>{stats.goneCount}</span>
</div>
)}
</div>
</div>
<BarChart data={series.map((s) => ({ value: s.grams }))} height={180} color="var(--sage)" />
</Card>
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
<Card>
<div className="serif" style={{ fontSize: 22, marginBottom: 18 }}>Spend by month</div>
<div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
{months.map(([m, v]) => {
const d = new Date(m + "-01");
return (
<div key={m} style={{ display: "flex", alignItems: "center", gap: 12 }}>
<div className="smallcaps" style={{ color: "var(--ink-3)", width: 60 }}>
{d.toLocaleDateString("en-US", { month: "short", year: "2-digit" })}
</div>
<div
style={{
flex: 1,
height: 24,
background: "var(--bg-2)",
borderRadius: 4,
position: "relative",
}}
>
<div
style={{
width: `${(v / monthMax) * 100}%`,
height: "100%",
background: "var(--terracotta)",
borderRadius: 4,
opacity: 0.85,
}}
/>
</div>
<div className="mono" style={{ width: 70, textAlign: "right", fontSize: 13 }}>
{fmt.moneyShort(v)}
</div>
</div>
);
})}
</div>
</Card>
<Card>
<div className="serif" style={{ fontSize: 22, marginBottom: 18 }}>Spend by shop</div>
<div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
{shopRanked.map(([s, v]) => (
<div key={s} style={{ display: "flex", alignItems: "center", gap: 12 }}>
<div style={{ flex: 1.5, fontSize: 13, color: "var(--ink-2)" }}>{s}</div>
<div
style={{
flex: 2,
height: 8,
background: "var(--bg-2)",
borderRadius: 4,
position: "relative",
}}
>
<div
style={{
width: `${(v / shopMax) * 100}%`,
height: "100%",
background: "var(--sage)",
borderRadius: 4,
}}
/>
</div>
<div className="mono" style={{ width: 70, textAlign: "right", fontSize: 13 }}>
{fmt.moneyShort(v)}
</div>
</div>
))}
</div>
</Card>
</div>
<Card>
<div className="serif" style={{ fontSize: 22, marginBottom: 6 }}>Inferred consumption heatmap</div>
<div style={{ fontSize: 12, color: "var(--ink-3)", marginBottom: 18 }}>
13 weeks · darker = higher inferred daily use, prorated across each item's lifespan
</div>
<Heatmap series={series} />
</Card>
</div>
);
}
function Heatmap({ series }: { series: { date: string; grams: number }[] }) {
const first = new Date(series[0]!.date);
const offset = first.getDay();
const cells: ({ date: string; grams: number } | null)[] = [];
for (let i = 0; i < offset; i++) cells.push(null);
series.forEach((s) => cells.push(s));
while (cells.length < 13 * 7) cells.push(null);
const max = Math.max(...series.map((s) => s.grams), 0.001);
const colorFor = (g: number) => {
if (g === 0) return "var(--bg-3)";
const t = g / max;
return `oklch(${72 - t * 30}% ${0.04 + t * 0.06} 145)`;
};
const days = ["S", "M", "T", "W", "T", "F", "S"];
return (
<div style={{ display: "flex", gap: 8, alignItems: "flex-start" }}>
<div style={{ display: "flex", flexDirection: "column", gap: 3, paddingTop: 18 }}>
{days.map((d, i) => (
<div
key={i}
style={{ height: 14, fontSize: 9, color: "var(--ink-3)", fontFamily: "var(--mono)" }}
>
{d}
</div>
))}
</div>
<div style={{ flex: 1 }}>
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(13, 1fr)",
gap: 3,
marginBottom: 4,
}}
>
{Array.from({ length: 13 }).map((_, w) => {
const firstDay = cells[w * 7];
return (
<div
key={w}
style={{
fontSize: 9,
color: "var(--ink-3)",
fontFamily: "var(--mono)",
textAlign: "center",
}}
>
{firstDay && new Date(firstDay.date).getDate() <= 7
? new Date(firstDay.date).toLocaleDateString("en-US", { month: "short" })
: ""}
</div>
);
})}
</div>
<div
style={{
display: "grid",
gridTemplateRows: "repeat(7, 1fr)",
gridAutoFlow: "column",
gap: 3,
}}
>
{cells.map((c, i) => (
<div
key={i}
title={c ? `${c.date}: ${c.grams.toFixed(2)}g` : ""}
style={{
aspectRatio: "1",
minHeight: 14,
background: c ? colorFor(c.grams) : "transparent",
borderRadius: 2,
}}
/>
))}
</div>
<div
style={{
display: "flex",
justifyContent: "flex-end",
alignItems: "center",
gap: 6,
marginTop: 14,
fontSize: 10,
color: "var(--ink-3)",
fontFamily: "var(--mono)",
}}
>
<span>Less</span>
{[0, 0.25, 0.5, 0.75, 1].map((t) => (
<div
key={t}
style={{
width: 14,
height: 14,
background: t === 0 ? "var(--bg-3)" : `oklch(${72 - t * 30}% ${0.04 + t * 0.06} 145)`,
borderRadius: 2,
}}
/>
))}
<span>More</span>
</div>
</div>
</div>
);
}
+414
View File
@@ -0,0 +1,414 @@
import type { Bootstrap, Product } from "../types.js";
import { helpers, TODAY_STR } from "../types.js";
import type { Stats } from "../stats.js";
import { remainingShort } from "../stats.js";
import { fmt } from "../format.js";
import { Btn, Card, Stat, Pill, Sparkline, BarChart, Donut } from "../components/primitives/index.js";
const TYPE_COLORS: Record<string, string> = {
Flower: "var(--sage)",
Concentrate: "var(--terracotta)",
Edible: "var(--amber)",
Vaporizer: "var(--plum)",
"Pre-roll": "oklch(50% 0.06 200)",
Tincture: "oklch(55% 0.06 270)",
};
export function Dashboard({
data,
stats,
onAuditProduct,
onSelectProduct,
}: {
data: Bootstrap;
stats: Stats;
onAuditProduct: (p: Product) => void;
onSelectProduct: (p: Product) => void;
}) {
const series30 = stats.series30.map((d) => ({ value: d.grams, label: "" }));
const last7Series = stats.series7.map((l) => l.grams);
const last30Series = stats.series30.map((d) => d.grams);
const segments = Object.entries(stats.typeBreakdown).map(([k, v]) => ({
label: k,
value: v,
color: TYPE_COLORS[k] ?? "var(--ink-3)",
}));
const overdue = stats.overdueAudits;
const lowBulk = stats.lowStockBulk;
const lowDiscrete = stats.lowStockDiscreteGroups;
return (
<div
style={{
padding: "clamp(32px, 3vw, 64px) clamp(40px, 3vw, 80px) 80px",
maxWidth: 2400,
margin: "0 auto",
}}
>
<div style={{ marginBottom: 24 }}>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>Saturday · April 25, 2026</div>
<h1
className="serif"
style={{
fontSize: 48,
margin: "8px 0 0",
fontWeight: 500,
letterSpacing: "-0.02em",
lineHeight: 1.1,
}}
>
Good evening.
</h1>
</div>
<div style={{ fontSize: 14, color: "var(--ink-2)", marginBottom: 28, maxWidth: 700 }}>
{stats.activeCount} active items across {data.bins.length} bins · {stats.consumedCount} consumed ·{" "}
{stats.goneCount} gone.
{overdue.length > 0 && (
<span style={{ color: "var(--terracotta)" }}>
{" "}· {overdue.length} audit{overdue.length === 1 ? "" : "s"} overdue.
</span>
)}
</div>
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(4, 1fr)",
gap: 18,
marginBottom: 18,
}}
>
<Stat
label="Daily average"
value={stats.dailyAvg.toFixed(2)}
unit="g / day"
sub={`${fmt.g(stats.weeklyAvg)} weekly · ${fmt.g(stats.monthlyAvg)} monthly`}
spark={<Sparkline values={last30Series} width={240} height={28} color="var(--sage)" fill />}
/>
<Stat
label="Avg cost per gram"
value={fmt.money(stats.avgPerGram)}
sub={`Across ${data.products.length} purchases`}
/>
<Stat
label="30-day spend"
value={fmt.moneyShort(stats.spend30)}
sub={
stats.goneSpend > 0
? `${fmt.money(stats.goneSpend)} lost to gone items`
: `7-day: ${fmt.money(stats.spend7)} · 90-day: ${fmt.money(stats.spend90)}`
}
/>
<Stat
label="THC last 7 days"
value={stats.thcLast7.toLocaleString()}
unit="mg"
sub={`Last 30: ${(stats.thcLast30 / 1000).toFixed(1)} g THC`}
spark={<Sparkline values={last7Series} width={240} height={28} color="var(--terracotta)" />}
/>
</div>
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(4, 1fr)",
gap: 18,
marginBottom: 18,
}}
>
<Stat
label="Inventory value"
value={fmt.money(stats.inventoryValue)}
sub={`${stats.activeCount} active item${stats.activeCount === 1 ? "" : "s"} on hand`}
/>
<Stat
label="Inventory on hand"
value={stats.inventoryGrams.toFixed(stats.inventoryGrams >= 10 ? 1 : 2)}
unit="g"
sub="Estimated remaining across active jars"
/>
<Stat
label="Spent all-time"
value={fmt.money(stats.totalSpend)}
sub={`${data.products.length} purchase${data.products.length === 1 ? "" : "s"}${stats.goneSpend > 0 ? ` · ${fmt.money(stats.goneSpend)} lost` : ""}`}
/>
<Stat
label="Purchased all-time"
value={stats.totalGrams.toFixed(stats.totalGrams >= 10 ? 1 : 2)}
unit="g"
sub="Lifetime weight purchased (excl. tinctures, edibles)"
/>
</div>
{overdue.length > 0 && (
<Card
style={{
marginBottom: 18,
borderColor: "var(--amber)",
background: "var(--amber-soft)",
}}
>
<div style={{ display: "flex", alignItems: "center", gap: 18, flexWrap: "wrap" }}>
<div style={{ flex: 1, minWidth: 240 }}>
<div className="smallcaps" style={{ color: "oklch(48% 0.10 75)" }}>Audit overdue</div>
<div className="serif" style={{ fontSize: 20, marginTop: 4, color: "var(--ink)" }}>
{overdue.length} item{overdue.length === 1 ? "" : "s"} haven't been checked in a while
</div>
<div style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 4 }}>
{overdue.slice(0, 3).map((p) => p.name).join(" · ")}
{overdue.length > 3 && ` · +${overdue.length - 3} more`}
</div>
</div>
<Btn variant="secondary" icon="check" onClick={() => onAuditProduct(overdue[0]!)}>
Run audit
</Btn>
</div>
</Card>
)}
<div
style={{
display: "grid",
gridTemplateColumns: "2fr 1fr",
gap: 18,
marginBottom: 18,
}}
>
<Card>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "baseline",
marginBottom: 18,
}}
>
<div>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>Consumption</div>
<div className="serif" style={{ fontSize: 22, marginTop: 4 }}>Last 30 days</div>
</div>
<div style={{ display: "flex", gap: 16, fontSize: 12, color: "var(--ink-3)" }}>
<div>
<span style={{ color: "var(--ink)" }} className="serif">
{fmt.g(stats.series30.reduce((s, l) => s + l.grams, 0))}
</span>{" "}
est. total
</div>
<div>
<span style={{ color: "var(--ink)" }} className="serif">
{stats.avgGap.toFixed(0)}
</span>{" "}
day avg between buys
</div>
</div>
</div>
<BarChart data={series30} height={140} color="var(--sage)" />
<div
style={{
display: "flex",
justifyContent: "space-between",
marginTop: 8,
fontSize: 10,
color: "var(--ink-3)",
fontFamily: "var(--mono)",
}}
>
<span>30 days ago</span>
<span>15 days ago</span>
<span>today</span>
</div>
</Card>
<Card>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>By type · grams on hand</div>
<div className="serif" style={{ fontSize: 22, marginTop: 4, marginBottom: 16 }}>Inventory</div>
<div style={{ display: "flex", alignItems: "center", gap: 20 }}>
<Donut segments={segments} size={140} thickness={20} />
<div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 8 }}>
{segments.map((s) => (
<div key={s.label} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12 }}>
<div style={{ width: 8, height: 8, borderRadius: 2, background: s.color }} />
<div style={{ flex: 1, color: "var(--ink-2)" }}>{s.label}</div>
<div className="mono" style={{ color: "var(--ink)" }}>{s.value.toFixed(1)}g</div>
</div>
))}
</div>
</div>
</Card>
</div>
<div
style={{
display: "grid",
gridTemplateColumns: "1fr 1fr 1fr",
gap: 18,
marginBottom: 18,
}}
>
<Stat
label="Days of supply"
value={Math.round(stats.daysOfSupply)}
unit="days"
sub="Flower & pre-rolls at current pace"
/>
<Stat
label="Avg lifespan"
value={Math.round(stats.avgLifespan)}
unit="days"
sub="From purchase to finished"
/>
<Stat
label="Days between buys"
value={stats.avgGap.toFixed(1)}
unit="days"
sub="Average across all purchases"
/>
</div>
<div
style={{
display: "grid",
gridTemplateColumns: "1fr 1fr 1.4fr",
gap: 18,
}}
>
<Card>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>Favorite shop</div>
<div className="serif" style={{ fontSize: 40, marginTop: 12, fontWeight: 500, lineHeight: 1.05 }}>
{stats.favShop[0]}
</div>
<div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 10 }}>
{stats.favShop[1]} of {data.products.length} purchases
</div>
</Card>
<Card>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>Favorite brand</div>
<div className="serif" style={{ fontSize: 40, marginTop: 12, fontWeight: 500, lineHeight: 1.05 }}>
{stats.favBrand[0]}
</div>
<div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 10 }}>
{stats.favBrand[1]} purchases
</div>
</Card>
<Card padded={false}>
<div
style={{
padding: "24px 24px 14px",
display: "flex",
justifyContent: "space-between",
alignItems: "baseline",
}}
>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>Low stock · running out</div>
<div style={{ fontSize: 11, color: "var(--ink-3)" }}>
{lowBulk.length + lowDiscrete.length} item
{lowBulk.length + lowDiscrete.length === 1 ? "" : "s"}
</div>
</div>
<div>
{lowBulk.length + lowDiscrete.length === 0 && (
<div style={{ padding: "0 24px 24px", fontSize: 13, color: "var(--ink-3)" }}>
Nothing running low.
</div>
)}
{lowBulk.slice(0, 3).map((p) => {
const pct = helpers.pctRemaining(p, TODAY_STR);
return (
<div
key={p.id}
onClick={() => onSelectProduct(p)}
style={{
padding: "12px 24px",
borderTop: "1px solid var(--line)",
display: "flex",
alignItems: "center",
gap: 12,
cursor: "pointer",
}}
>
<div style={{ flex: 1, minWidth: 0 }}>
<div
style={{
fontSize: 13,
fontWeight: 500,
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
}}
>
{p.name}
</div>
<div style={{ fontSize: 11, color: "var(--ink-3)" }}>
{helpers.brandName(data, p.brandId)} · {p.type}
</div>
</div>
<div
style={{
width: 60,
height: 4,
background: "var(--bg-3)",
borderRadius: 2,
overflow: "hidden",
}}
>
<div
style={{
width: `${pct * 100}%`,
height: "100%",
background: pct < 0.15 ? "var(--terracotta)" : "var(--amber)",
}}
/>
</div>
<div
className="mono"
style={{ fontSize: 11, color: "var(--ink-2)", width: 60, textAlign: "right" }}
>
{remainingShort(p)}
</div>
</div>
);
})}
{lowDiscrete.slice(0, 2).map((g) => (
<div
key={g.key}
onClick={() => onSelectProduct(g.items[0]!)}
style={{
padding: "12px 24px",
borderTop: "1px solid var(--line)",
display: "flex",
alignItems: "center",
gap: 12,
cursor: "pointer",
}}
>
<div style={{ flex: 1, minWidth: 0 }}>
<div
style={{
fontSize: 13,
fontWeight: 500,
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
}}
>
{g.name}
</div>
<div style={{ fontSize: 11, color: "var(--ink-3)" }}>
{helpers.brandName(data, g.brandId)} · {g.type}
</div>
</div>
<Pill tone="amber" style={{ fontSize: 10 }}>
{g.totalCount} left
</Pill>
</div>
))}
</div>
</Card>
</div>
</div>
);
}
+508
View File
@@ -0,0 +1,508 @@
import { useEffect, useMemo, useState } from "react";
import type { Bootstrap, Product } from "../types.js";
import { TYPES, helpers, TODAY_STR } from "../types.js";
import { remainingShort } from "../stats.js";
import { fmt, TYPE_GLYPHS } from "../format.js";
import { Btn, Card, Pill, Icon, Select, inputStyle } from "../components/primitives/index.js";
type FilterKey = "active" | "consumed" | "gone" | "all";
type SortKey = "recent" | "name" | "thc" | "remaining" | "price" | "audit";
type ViewKey = "flat" | "grouped";
const GRID_COLS = "32px 2fr 1fr 1fr 0.6fr 0.6fr 0.9fr 0.9fr 0.8fr";
export function Inventory({
data,
onSelectProduct,
onAddProduct,
onAuditNew,
}: {
data: Bootstrap;
onSelectProduct: (p: Product) => void;
onAddProduct: () => void;
onAuditNew: () => void;
}) {
const [filter, setFilter] = useState<FilterKey>("active");
const [typeFilter, setTypeFilter] = useState<string>("all");
const [sortBy, setSortBy] = useState<SortKey>("recent");
const [search, setSearch] = useState("");
const [view, setView] = useState<ViewKey>(
() => (localStorage.getItem("apothecary.inventoryView") as ViewKey | null) ?? "flat",
);
useEffect(() => {
localStorage.setItem("apothecary.inventoryView", view);
}, [view]);
const sortFn = (a: Product, b: Product) => {
if (sortBy === "recent") return +new Date(b.purchaseDate) - +new Date(a.purchaseDate);
if (sortBy === "name") return a.name.localeCompare(b.name);
if (sortBy === "thc") return b.thc - a.thc;
if (sortBy === "remaining")
return helpers.estimatedRemaining(b, TODAY_STR) - helpers.estimatedRemaining(a, TODAY_STR);
if (sortBy === "price") return b.price - a.price;
if (sortBy === "audit")
return helpers.daysSinceCheck(b, TODAY_STR) - helpers.daysSinceCheck(a, TODAY_STR);
return 0;
};
const filteredProducts = useMemo(() => {
let products = data.products;
if (filter === "active") products = products.filter((p) => p.status === "active");
else if (filter === "consumed") products = products.filter((p) => p.status === "consumed");
else if (filter === "gone") products = products.filter((p) => p.status === "gone");
if (typeFilter !== "all") products = products.filter((p) => p.type === typeFilter);
if (search) {
const q = search.toLowerCase();
products = products.filter((p) => {
const brand = helpers.brandName(data, p.brandId).toLowerCase();
const shop = helpers.shopName(data, p.shopId).toLowerCase();
return (
p.name.toLowerCase().includes(q) ||
brand.includes(q) ||
shop.includes(q) ||
p.sku.toLowerCase().includes(q)
);
});
}
return products;
}, [data, filter, typeFilter, search]);
const sortedProducts = useMemo(
() => [...filteredProducts].sort(sortFn),
[filteredProducts, sortBy],
);
// For grouped mode: bucket by strainId. Products without a strainId fall
// into an "Unlinked" bucket at the end. Within each group, sort by sortFn.
type Group = {
strainId: string | null;
label: string;
brand: string;
type: string;
products: Product[];
};
const groups: Group[] = useMemo(() => {
const byStrain = new Map<string | null, Product[]>();
for (const p of filteredProducts) {
const arr = byStrain.get(p.strainId) ?? [];
arr.push(p);
byStrain.set(p.strainId, arr);
}
const out: Group[] = [];
for (const [strainId, products] of byStrain.entries()) {
const first = products[0]!;
// Prefer the strain's canonical name when available so casing is
// consistent regardless of which product was added first.
const strain = strainId ? data.strains.find((s) => s.id === strainId) : null;
out.push({
strainId,
label: strain?.name ?? first.name,
brand: helpers.brandName(data, first.brandId),
type: first.type,
products: [...products].sort(sortFn),
});
}
// Order groups by their most-recent purchase date desc so newest strains float up.
out.sort((a, b) => {
if (a.strainId === null) return 1;
if (b.strainId === null) return -1;
const aMax = Math.max(...a.products.map((p) => +new Date(p.purchaseDate)));
const bMax = Math.max(...b.products.map((p) => +new Date(p.purchaseDate)));
return bMax - aMax;
});
return out;
}, [filteredProducts, data, sortBy]);
return (
<div
style={{
padding: "clamp(32px, 3vw, 64px) clamp(40px, 3vw, 80px) 80px",
maxWidth: 2400,
margin: "0 auto",
}}
>
<div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 24 }}>
<div>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>
{sortedProducts.length} item{sortedProducts.length === 1 ? "" : "s"}
</div>
<h1
className="serif"
style={{ fontSize: 44, margin: "6px 0 0", fontWeight: 500, letterSpacing: "-0.02em" }}
>
Inventory
</h1>
</div>
<div style={{ display: "flex", gap: 8 }}>
<Btn variant="secondary" icon="check" onClick={onAuditNew}>Audit</Btn>
<Btn variant="primary" icon="plus" onClick={onAddProduct}>New product</Btn>
</div>
</div>
<Card style={{ marginBottom: 14, padding: 14 }}>
<div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
<Segmented<FilterKey>
value={filter}
options={[
["active", "Active"],
["consumed", "Consumed"],
["gone", "Gone"],
["all", "All"],
]}
onChange={setFilter}
/>
<Segmented<ViewKey>
value={view}
options={[
["flat", "Flat"],
["grouped", "Grouped"],
]}
onChange={setView}
/>
<div
style={{
flex: 1,
minWidth: 220,
display: "flex",
alignItems: "center",
gap: 8,
background: "var(--bg-2)",
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
padding: "0 10px",
}}
>
<Icon name="search" size={14} color="var(--ink-3)" />
<input
placeholder="Search by name, brand, shop, SKU…"
value={search}
onChange={(e) => setSearch(e.target.value)}
style={{
border: "none",
outline: "none",
background: "transparent",
padding: "8px 0",
fontSize: 13,
flex: 1,
color: "var(--ink)",
}}
/>
</div>
<Select
value={typeFilter}
onChange={(e) => setTypeFilter(e.target.value)}
style={{ ...inputStyle, width: "auto", padding: "8px 10px" }}
>
<option value="all">All types</option>
{TYPES.map((t) => (
<option key={t.id} value={t.id}>{t.id}</option>
))}
</Select>
<Select
value={sortBy}
onChange={(e) => setSortBy(e.target.value as SortKey)}
style={{ ...inputStyle, width: "auto", padding: "8px 10px" }}
>
<option value="recent">Recent first</option>
<option value="name">Name (AZ)</option>
<option value="thc">THC % (high)</option>
<option value="remaining">Remaining (high)</option>
<option value="price">Price (high)</option>
<option value="audit">Audit overdue first</option>
</Select>
</div>
</Card>
<Card padded={false}>
<HeaderRow />
{sortedProducts.length === 0 && (
<div style={{ padding: 60, textAlign: "center", color: "var(--ink-3)" }}>
No items match these filters.
</div>
)}
{view === "flat" &&
sortedProducts.map((p) => (
<ProductRow key={p.id} p={p} data={data} onSelect={onSelectProduct} />
))}
{view === "grouped" &&
groups.map((g) => (
<div key={g.strainId ?? "unlinked"}>
<GroupHeader group={g} />
{g.products.map((p) => (
<ProductRow key={p.id} p={p} data={data} onSelect={onSelectProduct} indented />
))}
</div>
))}
</Card>
</div>
);
}
function Segmented<T extends string>({
value,
options,
onChange,
}: {
value: T;
options: [T, string][];
onChange: (v: T) => void;
}) {
return (
<div
style={{
display: "inline-flex",
background: "var(--bg-2)",
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
padding: 3,
}}
>
{options.map(([k, l]) => (
<button
key={k}
onClick={() => onChange(k)}
style={{
padding: "6px 14px",
fontSize: 12,
fontWeight: 500,
borderRadius: 6,
border: "none",
background: value === k ? "var(--surface)" : "transparent",
color: value === k ? "var(--ink)" : "var(--ink-3)",
boxShadow: value === k ? "var(--shadow-sm)" : "none",
cursor: "pointer",
}}
>
{l}
</button>
))}
</div>
);
}
function HeaderRow() {
return (
<div
style={{
display: "grid",
gridTemplateColumns: GRID_COLS,
columnGap: 16,
padding: "12px 20px",
borderBottom: "1px solid var(--line)",
background: "var(--bg-2)",
fontSize: 11,
color: "var(--ink-3)",
textTransform: "uppercase",
letterSpacing: "0.08em",
}}
>
<div></div>
<div>Product</div>
<div>Brand</div>
<div>Shop</div>
<div>THC %</div>
<div>Price</div>
<div>Remaining</div>
<div>Last checked</div>
<div>Bin</div>
</div>
);
}
function GroupHeader({
group,
}: {
group: {
strainId: string | null;
label: string;
brand: string;
type: string;
products: Product[];
};
}) {
// Aggregate remaining: bulk uses estimatedRemaining; discrete uses unitWeight × count.
// Counts use status === "active" only — archived rows shouldn't inflate "on hand."
const active = group.products.filter((p) => p.status === "active");
const totalRemaining = active.reduce((s, p) => {
if (p.kind === "bulk") return s + helpers.estimatedRemaining(p, TODAY_STR);
const cur = p.countLastAudit ?? p.countOriginal;
return s + cur * (p.unitWeight || 0);
}, 0);
const totalCount = active.length;
const lastBuy = group.products.reduce((max, p) => {
const t = +new Date(p.purchaseDate);
return t > max ? t : max;
}, 0);
const cfg = TYPES.find((t) => t.id === group.type);
return (
<div
style={{
display: "flex",
alignItems: "baseline",
justifyContent: "space-between",
gap: 16,
padding: "16px 20px 10px",
borderBottom: "1px solid var(--line)",
background: "var(--bg-2)",
}}
>
<div style={{ display: "flex", alignItems: "baseline", gap: 12, minWidth: 0 }}>
<div style={{ fontFamily: "var(--serif)", fontSize: 18, color: "var(--ink-3)", width: 18 }}>
{TYPE_GLYPHS[group.type]}
</div>
<div className="serif" style={{ fontSize: 22, fontWeight: 500, lineHeight: 1.1 }}>
{group.strainId === null ? "Unlinked" : group.label}
</div>
<div style={{ fontSize: 12, color: "var(--ink-3)" }}>
{group.brand} · {group.type}
</div>
</div>
<div style={{ display: "flex", alignItems: "baseline", gap: 18, fontSize: 12, color: "var(--ink-3)" }}>
<div>
<span className="mono" style={{ color: "var(--ink-2)" }}>
{totalCount}
</span>{" "}
{totalCount === 1 ? "active" : "active"}
{group.products.length !== totalCount && (
<span style={{ color: "var(--ink-4)" }}> / {group.products.length} total</span>
)}
</div>
<div>
<span className="mono" style={{ color: "var(--ink-2)" }}>
{totalRemaining.toFixed(2).replace(/\.?0+$/, "") || "0"}
</span>{" "}
{cfg?.unit ?? "g"} on hand
</div>
{lastBuy > 0 && (
<div>
last buy <span className="mono" style={{ color: "var(--ink-2)" }}>{fmt.dateShort(new Date(lastBuy).toISOString())}</span>
</div>
)}
</div>
</div>
);
}
function ProductRow({
p,
data,
onSelect,
indented = false,
}: {
p: Product;
data: Bootstrap;
onSelect: (p: Product) => void;
indented?: boolean;
}) {
const bin = data.bins.find((b) => b.id === p.binId);
const pctRemaining = helpers.pctRemaining(p, TODAY_STR);
const overdue = helpers.auditOverdue(p, TODAY_STR);
const sinceCheck = helpers.daysSinceCheck(p, TODAY_STR);
const last = helpers.lastAudit(p);
const isInactive = p.status !== "active";
return (
<div
onClick={() => onSelect(p)}
className="inv-row"
style={{
display: "grid",
gridTemplateColumns: GRID_COLS,
columnGap: 16,
padding: indented ? "14px 20px 14px 36px" : "14px 20px",
borderBottom: "1px solid var(--line)",
alignItems: "center",
cursor: "pointer",
opacity: isInactive ? 0.55 : 1,
fontSize: 13,
borderLeft: indented ? "2px solid var(--bg-3)" : "none",
}}
>
<div
style={{
fontFamily: "var(--serif)",
fontSize: 18,
color: "var(--ink-3)",
opacity: indented ? 0.5 : 1,
}}
>
{TYPE_GLYPHS[p.type]}
</div>
<div style={{ minWidth: 0 }}>
<div
style={{
fontWeight: 500,
color: "var(--ink)",
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
}}
>
{p.name}
{p.status === "consumed" && (
<Pill tone="terra" style={{ marginLeft: 6, fontSize: 10 }}>Consumed</Pill>
)}
{p.status === "gone" && (
<Pill tone="amber" style={{ marginLeft: 6, fontSize: 10 }}>Gone</Pill>
)}
{p.status === "active" && overdue && (
<Pill tone="amber" style={{ marginLeft: 6, fontSize: 10 }}>Audit due</Pill>
)}
</div>
<div style={{ fontSize: 11, color: "var(--ink-3)", fontFamily: "var(--mono)" }}>
{p.sku}
{p.assetTag ? ` · ${p.assetTag}` : ""}
</div>
</div>
<div style={{ color: "var(--ink-2)" }}>{helpers.brandName(data, p.brandId)}</div>
<div style={{ color: "var(--ink-3)", fontSize: 12 }}>{helpers.shopName(data, p.shopId)}</div>
<div style={{ fontFamily: "var(--mono)", color: "var(--ink-2)" }}>{p.thc.toFixed(1)}</div>
<div style={{ fontFamily: "var(--mono)" }}>{fmt.money(p.price)}</div>
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "flex-start",
gap: 4,
}}
>
<div style={{ fontFamily: "var(--mono)", fontSize: 12 }}>{remainingShort(p)}</div>
{p.status === "active" && p.kind === "bulk" && (
<div style={{ width: 80, height: 5, background: "var(--bg-3)", borderRadius: 2 }}>
<div
style={{
width: `${pctRemaining * 100}%`,
height: "100%",
background:
pctRemaining < 0.25
? "var(--terracotta)"
: pctRemaining < 0.5
? "var(--amber)"
: "var(--sage)",
borderRadius: 2,
}}
/>
</div>
)}
</div>
<div style={{ fontSize: 11, color: overdue ? "var(--terracotta)" : "var(--ink-3)" }}>
{p.status !== "active" ? (
<span style={{ fontStyle: "italic" }}>archived</span>
) : last ? (
<span>
<span className="mono">{sinceCheck}d</span> ago · {last.mode}
</span>
) : (
<span style={{ fontStyle: "italic" }}>never</span>
)}
</div>
<div style={{ fontSize: 12, color: "var(--ink-3)" }}>
{bin ? bin.name : <span style={{ fontStyle: "italic" }}></span>}
</div>
</div>
);
}
+113
View File
@@ -0,0 +1,113 @@
import type { Bootstrap } from "../types.js";
import { Btn, Card, Stat } from "../components/primitives/index.js";
export type ThemeKey = "light" | "dark";
export function SettingsView({
data,
theme,
onThemeChange,
}: {
data: Bootstrap;
theme: ThemeKey;
onThemeChange: (t: ThemeKey) => void;
}) {
return (
<div
style={{
padding: "clamp(32px, 3vw, 64px) clamp(40px, 3vw, 80px) 80px",
maxWidth: 1400,
margin: "0 auto",
}}
>
<div style={{ marginBottom: 24 }}>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>Settings</div>
<h1
className="serif"
style={{ fontSize: 44, margin: "6px 0 0", fontWeight: 500, letterSpacing: "-0.02em" }}
>
Preferences
</h1>
</div>
<Card style={{ marginBottom: 14 }}>
<div className="serif" style={{ fontSize: 22, marginBottom: 16 }}>Appearance</div>
<div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
<SettingRow label="Theme" hint="Light parchment or dim ink">
<div
style={{
display: "inline-flex",
background: "var(--bg-2)",
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
padding: 3,
}}
>
{(["light", "dark"] as const).map((t) => (
<button
key={t}
onClick={() => onThemeChange(t)}
style={{
padding: "6px 14px",
fontSize: 12,
fontWeight: 500,
borderRadius: 6,
border: "none",
background: theme === t ? "var(--surface)" : "transparent",
color: theme === t ? "var(--ink)" : "var(--ink-3)",
cursor: "pointer",
textTransform: "capitalize",
}}
>
{t}
</button>
))}
</div>
</SettingRow>
</div>
</Card>
<Card style={{ marginBottom: 14 }}>
<div className="serif" style={{ fontSize: 22, marginBottom: 16 }}>Library</div>
<div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 16 }}>
<Stat label="Active" value={data.products.filter((p) => p.status === "active").length} />
<Stat label="Consumed" value={data.products.filter((p) => p.status === "consumed").length} />
<Stat label="Gone" value={data.products.filter((p) => p.status === "gone").length} />
<Stat label="Bins" value={data.bins.length} />
</div>
<div style={{ display: "flex", gap: 8 }}>
<Btn variant="secondary">Export CSV</Btn>
<Btn variant="secondary">Export JSON</Btn>
</div>
</Card>
</div>
);
}
function SettingRow({
label,
hint,
children,
}: {
label: string;
hint?: string;
children: React.ReactNode;
}) {
return (
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
paddingBottom: 14,
borderBottom: "1px solid var(--line)",
}}
>
<div style={{ flex: 1 }}>
<div style={{ fontSize: 13, fontWeight: 500 }}>{label}</div>
{hint && <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{hint}</div>}
</div>
{children}
</div>
);
}
+77
View File
@@ -0,0 +1,77 @@
import type { Bootstrap } from "../types.js";
import { Btn, Card, Pill } from "../components/primitives/index.js";
export function ShopsView({
data,
onAddShop,
}: {
data: Bootstrap;
onAddShop: () => void;
}) {
return (
<div
style={{
padding: "clamp(32px, 3vw, 64px) clamp(40px, 3vw, 80px) 80px",
maxWidth: 2400,
margin: "0 auto",
}}
>
<div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 24 }}>
<div>
<div className="smallcaps" style={{ color: "var(--ink-3)" }}>
{data.shops.length} shop{data.shops.length === 1 ? "" : "s"}
</div>
<h1
className="serif"
style={{ fontSize: 44, margin: "6px 0 0", fontWeight: 500, letterSpacing: "-0.02em" }}
>
Shops
</h1>
</div>
<Btn variant="primary" icon="plus" onClick={onAddShop}>New shop</Btn>
</div>
<div style={{ fontSize: 14, color: "var(--ink-2)", marginBottom: 24, maxWidth: 600 }}>
Where you've purchased from. Used in the shop dropdown when adding a new product.
</div>
{data.shops.length === 0 ? (
<Card style={{ padding: 60, textAlign: "center" }}>
<div className="serif" style={{ fontSize: 22, marginBottom: 6 }}>No shops yet</div>
<div style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 18 }}>
Add a shop to start logging where each purchase came from.
</div>
<Btn variant="primary" icon="plus" onClick={onAddShop}>Add your first shop</Btn>
</Card>
) : (
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))",
gap: 14,
}}
>
{data.shops.map((s) => {
const count = data.products.filter((p) => p.shopId === s.id).length;
return (
<Card key={s.id} style={{ display: "flex", alignItems: "center", gap: 12 }}>
<div style={{ flex: 1, minWidth: 0 }}>
<div className="serif" style={{ fontSize: 22, fontWeight: 500, lineHeight: 1.1 }}>
{s.name}
</div>
{s.location && (
<div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>
{s.location}
</div>
)}
</div>
<Pill tone="outline">
{count} purchase{count === 1 ? "" : "s"}
</Pill>
</Card>
);
})}
</div>
)}
</div>
);
}
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"jsx": "react-jsx",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"allowImportingTsExtensions": false,
"useDefineForClassFields": true
},
"include": ["src/**/*"]
}
+15
View File
@@ -0,0 +1,15 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
server: {
port: 5173,
proxy: {
"/api": {
target: "http://localhost:4000",
changeOrigin: true,
},
},
},
});
+25
View File
@@ -0,0 +1,25 @@
# CODING AGENTS: READ THIS FIRST
This is a **handoff bundle** from Claude Design (claude.ai/design).
A user mocked up designs in HTML/CSS/JS using an AI design tool, then exported this bundle so a coding agent can implement the designs for real.
## What you should do — IMPORTANT
**Read the chat transcripts first.** There are 1 chat transcript(s) in `weed-tracker/chats/`. The transcripts show the full back-and-forth between the user and the design assistant — they tell you **what the user actually wants** and **where they landed** after iterating. Don't skip them. The final HTML files are the output, but the chat is where the intent lives.
**Read `weed-tracker/project/Apothecary - Inventory.html` in full.** The user had this file open when they triggered the handoff, so it's almost certainly the primary design they want built. Read it top to bottom — don't skim. Then **follow its imports**: open every file it pulls in (shared components, CSS, scripts) so you understand how the pieces fit together before you start implementing.
**If anything is ambiguous, ask the user to confirm before you start implementing.** It's much cheaper to clarify scope up front than to build the wrong thing.
## About the design files
The design medium is **HTML/CSS/JS** — these are prototypes, not production code. Your job is to **recreate them pixel-perfectly** in whatever technology makes sense for the target codebase (React, Vue, native, whatever fits). Match the visual output; don't copy the prototype's internal structure unless it happens to fit.
**Don't render these files in a browser or take screenshots unless the user asks you to.** Everything you need — dimensions, colors, layout rules — is spelled out in the source. Read the HTML and CSS directly; a screenshot won't tell you anything they don't.
## Bundle contents
- `weed-tracker/README.md` — this file
- `weed-tracker/chats/` — conversation transcripts (read these!)
- `weed-tracker/project/` — the `Weed Tracker` project files (HTML prototypes, assets, components)
+819
View File
@@ -0,0 +1,819 @@
# Weed Inventory Tracker
_Started 2026-04-25 14:53 UTC_
---
## User
I want to create an inventory system for personal weed tracking
Dashboard:
- Should contain interesting stats like grams consumed daily, weekly, monthly / average $ per gram / average spend, etc
Inventory:
Should be somewhat of a standard inventory system. Products have SKUs and sometimes asset tags if we don't have SKUs
Products have name, price, weight (g), THC%, CBD%, Total Cannabinoids %, shop (where we bought it), brand (who made it), type (concentrate, bud, edible, vaporizer, etc), purchase date
We can mark products as gone / consumed, but that does not necessarily mean that they are not tracked anymore. They just do not live within a bin anymore (they're gone)
## Assistant
I'll help you design a personal inventory tracking system. Before I start building, I have some questions to make sure I design this right for you.
_[tool: questions_v2]_
## User
Questions answered:
- output_format: Both — prototype + deck
- platform: Responsive (works everywhere)
- design_context: No, design something original for me
- aesthetic: Apothecary / botanical (warm, earthy, refined)
- color_palette: Earthy / warm neutrals
- screens: Dashboard with stats, Inventory list (all products), Single product detail view, Add new product flow, Mark as consumed flow, Bins / storage view, Spend over time / charts, Filters & search, Settings
- stats_priorities: Daily/weekly/monthly grams, Avg $ per gram, Avg spend per period, THC consumed (mg), Consumption streaks / patterns, Current inventory value, Favorite shop / brand, Type breakdown (bud vs concentrate, etc), Cost per session / day estimate, Days of supply remaining
- bins: Physical bins (e.g. 'Top drawer', 'Safe')
- consumed_tracking: Date finished + final notes (rating, etc)
- variations: 2-3 directions to compare
- tweaks: None / decide for me
- tone: Decide for me
## Assistant
I've got everything I need. Let me lay out the plan and start building.
**Aesthetic commitment** — Apothecary / botanical, warm earthy neutrals. Type pairing: **Fraktur Mono / Söhne**-feeling pairing... actually, let me commit: **GT Sectra Display** (or similar — I'll use **Cormorant Garamond** for serif headers + **JetBrains Mono** for data/SKUs + **Inter** for UI). Palette: parchment/bone background (oklch warm off-white), deep ink, sage green accent, terracotta accent for warnings/consumed states.
**Plan:**
1. Build prototype first (responsive, all 9 screens, 2-3 variations as tweaks)
2. Then build the pitch deck showing the concept
3. Both share the visual language
Let me set up the project structure.
_[tool: update_todos]_
_[tool: copy_starter_component]_
_[tool: copy_starter_component]_
_[tool: write_file]_
_[tool: write_file]_
Now the main app file and components:
_[tool: write_file]_
Now the screens:
_[tool: write_file]_
_[tool: snip]_
_[tool: write_file]_
_[tool: snip]_
_[tool: write_file]_
_[tool: show_html]_
_[tool: snip]_
_[tool: show_html]_
_[tool: get_webview_logs]_
I need to fix the `padded` prop being passed to DOM, then build the deck.
_[tool: snip]_
_[tool: str_replace_edit]_
_[tool: snip]_
Now let me build the pitch deck:
_[tool: write_file]_
_[tool: register_assets]_
_[tool: snip]_
_[tool: done]_
_[tool: fork_verifier_agent]_
I built two pieces under the **Apothecary** concept — warm parchment, deep ink, sage + terracotta accents, Cormorant Garamond serif paired with Inter and JetBrains Mono.
**Prototype** (`Apothecary - Inventory.html`)
- All 9 screens: dashboard, inventory list, product detail (right-drawer), add product, log session / mark consumed, bins, patterns/charts (90-day bars + spend by month/shop + heatmap), settings, plus filters & search
- Full product schema: SKU, optional asset tag, name, brand, shop, type, weight, price, THC%, CBD%, total cannabinoids, purchase date, bin
- Consumed items stay in the archive with rating + final notes
- **3 dashboard variants** as tweaks (Editorial / Data-dense / Minimal), plus light/dark and a tone switch (Botanical / Neutral / Discreet code-name mode)
**Deck** (`Apothecary - Deck.html`)
- 13 slides, 1920×1080, parallel section-header style, alternating light parchment / ink / sage / terracotta backgrounds for visual rhythm
**Caveats / next steps**
- Form submissions are non-persistent (mock data) — wire to localStorage when you're ready
- No barcode/receipt scanner yet (in roadmap on slide 12)
- Charts are hand-rolled SVG — fine for prototyping, swap for a real library if you build this
## User
Couple thoughts
1. Let's do away with the idea of sessions. It's not likely that heavy users will bother will tracking every single session, and it's not likely that moderate to light users will bother using this product at all
2. I like the theme, but the buttons can be hard to read especially when adding a new product for example the submit button is very light and impossible to read
## Assistant
_[tool: snip]_
_[tool: read_file]_
Good points. Let me address both:
1. Replace "Sessions" with simpler tracking — just decrement remaining when something gets used (or skip entirely and rely on "mark finished" + purchase patterns)
2. Fix button contrast — the "primary" button uses `--ink` which is correct, but the issue is likely text color in dark mode or the danger button. Let me audit.
_[tool: snip]_
_[tool: read_file]_
I see the issue — `var(--bg)` on the primary button is parchment (light) on `var(--ink)` (dark) which should be fine, BUT the disabled state at opacity 0.4 makes the "Save product" button unreadable until name is filled. Let me fix both: remove sessions concept, and improve disabled button contrast.
_[tool: snip]_
_[tool: str_replace_edit]_
_[tool: snip]_
Now remove sessions — replace ConsumeFlow with a simpler "Mark finished" + "Use some" flow, and rework dashboard stats away from session-based metrics.
_[tool: snip]_
_[tool: str_replace_edit]_
_[tool: snip]_
Now rework the dashboard stats and data model to remove session-based metrics, and update the deck/copy that references "sessions".
_[tool: snip]_
_[tool: read_file]_
I'll rework stats around purchases-only (no session log). The approach: derive daily/weekly/monthly grams from purchase patterns over time (grams purchased ÷ days in period), drop streak entirely, and replace "cost per session" with "average lifespan" (days between purchase and consumed).
_[tool: snip]_
_[tool: str_replace_edit]_
_[tool: snip]_
_[tool: read_file]_
_[tool: snip]_
_[tool: str_replace_edit]_
_[tool: snip]_
_[tool: grep]_
_[tool: snip]_
_[tool: read_file]_
_[tool: snip]_
_[tool: str_replace_edit]_
_[tool: str_replace_edit]_
_[tool: str_replace_edit]_
_[tool: str_replace_edit]_
_[tool: str_replace_edit]_
_[tool: str_replace_edit]_
_[tool: snip]_
_[tool: grep]_
_[tool: grep]_
I need to remove the user's request to track sessions/streaks since they only asked for "date finished + final notes" — not session-level tracking. Let me clean these up.
_[tool: snip]_
_[tool: read_file]_
I see — the inventory HTML has its own data.log references and dashboard variants. Since the user said "date finished + final notes" (not session journaling), I should remove the consumption log entirely and pivot stats to be derived from purchase + finished dates only. Let me look at the full picture first.
_[tool: grep]_
_[tool: grep]_
Now I understand the full scope. The user only wants "date finished + final notes" — they don't track sessions/streaks. I need to:
1. Replace data.log with derived series from purchase/consumed dates
2. Remove session/streak references
3. Update stats accordingly
_[tool: read_file]_
Now I'll completely refactor the data model to drop the consumption log (since user only wants date finished + final notes), and derive all stats from purchase + finished records.
_[tool: grep]_
Good, computeStats already exists. Let me look at it.
_[tool: read_file]_
Good — computeStats already provides `series7`, `series30`, `series90`, `avgLifespan`, `avgGap`, `consumedCount` (likely). Let me check the return + cleanup the remaining stale references.
_[tool: read_file]_
Now let me fix all the remaining session/streak/log references in screens-2.jsx and Apothecary - Inventory.html (the dashboard variants and patterns screen):
_[tool: read_file]_
Let me see the heatmap part too:
_[tool: read_file]_
Now I'll fix the ChartsView to use stats.series90 instead of building from data.log:
_[tool: str_replace_edit]_
_[tool: str_replace_edit]_
_[tool: str_replace_edit]_
Now fix the Inventory.html dashboard variants and remove `Log session` references:
_[tool: read_file]_
Now let me see the minimal dashboard and finish reading:
_[tool: read_file]_
Now I'll fix all references in Inventory.html:
_[tool: str_replace_edit]_
Now let me also clean up the data.js to remove the LOG (no longer needed) and find any other stale references. Let me also check ConsumeFlow's copy:
_[tool: grep]_
_[tool: str_replace_edit]_
_[tool: snip]_
_[tool: str_replace_edit]_
Let me read what's around the second "Streak" reference and apply edits more uniquely:
_[tool: read_file]_
There's only one literal "Streak" but probably another. Let me search:
_[tool: grep]_
Now let me apply edits with proper unique context:
_[tool: str_replace_edit]_
Now let me check primitives.jsx for any leftover stats keys (thcLast7 should still work — uses series7), and verify the inventory loads:
_[tool: grep]_
All cleaned up. Let me verify the prototype loads:
_[tool: done]_
Clean. Let me also verify the deck:
_[tool: show_html]_
_[tool: get_webview_logs]_
Both files load cleanly. I've removed all the session/streak tracking that crept in — your spec was "date finished + final notes," not session journaling.
**What changed:**
- Dropped the synthetic 90-day session log; daily/weekly/monthly grams are now **inferred** by prorating each item's used weight across its lifespan (purchase → finished, or purchase → today for active items)
- Replaced "Cost per session" / "Log streak" stats with **Avg lifespan** (days from purchase to finished) and **Avg days between buys**
- "Log session" buttons → "Mark finished" everywhere
- Heatmap relabeled "Inferred consumption"
- Deck slide updated to match
_[tool: fork_verifier_agent]_
Done. The tracker now matches your spec: products are tracked from purchase to finished date with rating + final notes, and all dashboard stats derive from those records — no per-session logging.
## User
Verifier agent check completed
## Assistant
Let me investigate both issues:
_[tool: grep]_
Confirmed — let me see how Btn spreads `v`:
_[tool: read_file]_
Confirmed: `...v` spreads `bg` (not a CSS prop) into the style. Fix the variants to use `background`:
_[tool: str_replace_edit]_
Now fix the dashboard greeting layout. Let me look at the header:
_[tool: read_file]_
The header layout looks fine to me — but verifier reports overlap. The issue: `marginBottom: 8` on the row might not give enough space, and the Btn flex container could wrap. Let me add `flexWrap: nowrap` and proper alignment plus more bottom margin:
_[tool: str_replace_edit]_
Now verify the fix:
_[tool: done]_
_[tool: fork_verifier_agent]_
Fixed both bugs:
- **Button contrast** — variants map used `bg:` instead of `background:`, so the spread never set the button's background. Renamed throughout.
- **Header overlap** — slightly reduced the greeting (44→36px), tightened line-height, switched the row to `align-items: center` with `flex-wrap` and `flex-shrink: 0` on the buttons so they can't squeeze the title into a wrap.
## User
Verifier agent check completed
## Assistant
All clear — both fixes verified.
## User
Okay, I think we have a really good start to this. I have a number of thoughts to flesh it out a bit
1. I noticed that you included a low stock running out section, but we removed the sessions which told us how much of a particular product that we have. I think that this adds some interesting depth. For example we can have multiple of 1 product; for a example a particular pre roll that we like where we have multiple versus a jar of a particular strain. It's easy to tell how many we have left at all times versus bud where we will show as having 14g for example until the day I mark it as completely consumed. I think we should prompt an audit on a product after say 30 days where we re-weigh the product. This should be based on product type though. Edibles, pre-rolls we should just confirm whether it's still there or not (require entering serial or asset to confirm) whereas bud would get reweighed and wax would get estimated
2. We do not currently have a way to add a new shop
3. Brands should be similar to shops where they are a dropdown and we should similarly add a section to add a new brand
## Assistant
Great direction. Let me think through the model changes before coding:
**Multi-unit products** — items like pre-rolls/edibles have a `count` (e.g. 5 pre-rolls). Bud/wax have `weight` only. Tracking different product types differently:
- **Discrete (count-based):** Pre-roll, Edible, Vaporizer → track `quantity` (units left). Audit = "do you still have N?" with SKU/asset confirmation.
- **Bulk (weight-based):** Flower, Concentrate, Tincture → track `remaining` weight. Audit = re-weigh (Flower) or estimate (Concentrate/Tincture).
**Audits** — after 30 days since purchase or last audit, prompt re-weigh/re-count. Track audit history with date + value.
**Shops & brands** — both become managed lists with "+ Add new" inline in dropdowns, plus a Settings section to manage them.
Let me ask a couple of quick clarifications before I build:
_[tool: questions_v2]_
## User
Questions answered:
- audit_trigger: Configurable per-type cadence (e.g. flower 14d, edibles 60d)
- audit_surface: Inline badge on each product in inventory + dashboard banner
- audit_confirm_method: Type SKU or asset tag
- discrepancy: The point is not to find a discrepancy with weights. We are checking weights (for certain types) to better track inventory and usage. We are checking whether or not the item is still there for other types like edibles and pre rolls that is more where we will find a discrepancy. If one is found then we should have a modal that gives the option to mark it as consumed or gone. Difference is gone counts as money spent but not weed consumed (for metrics)
- shop_brand_metadata: New Shop (Name + Location), New Brand (Name)
- low_stock_logic: For edibles and prerolls we should do count less than or equal to 2, but do it by brand rather than strain (sku). For wax and bud do it by original % (25)
- remaining_display: Show estimated remaining (decays based on avg lifespan) + actual last audit
## Assistant
Great answers. Let me plan the build:
_[tool: update_todos]_
_[tool: snip]_
_[tool: read_file]_
Now I'll rewrite data.js with the new model:
**Model decisions:**
- `kind: "bulk"` (Flower, Concentrate, Tincture) — track `weight` (g/ml)
- `kind: "discrete"` (Pre-roll, Edible, Vaporizer) — track `count` (units)
- `unitWeight` for discrete bulk-equivalent (e.g. each pre-roll = 1g)
- `audits[]``{date, type: "weigh"|"presence", value, byUser}`
- `auditCadenceDays` per type (Flower 14, Concentrate 21, Tincture 30, Pre-roll 30, Edible 60, Vaporizer 30)
- `consumed` (used up via use) vs `gone` (lost / discarded — counts as $ but not consumption)
- Shops: `[{id, name, location}]`, Brands: `[{id, name}]`
_[tool: write_file]_
_[tool: snip]_
_[tool: read_file]_
_[tool: snip]_
_[tool: read_file]_
Now rewrite computeStats for the new model. Key changes:
- `p.status` (active/consumed/gone) instead of `p.consumed`
- bulk: use estimatedRemaining decay; discrete: use countLastAudit × unitWeight for grams
- Gone items: count $ but NOT grams in consumption stats
- favShop/favBrand keyed by shopId/brandId — return name+count
- typeBreakdown by total est. grams (discrete uses count × unitWeight)
- New: overdueAudits count
_[tool: str_replace_edit]_
_[tool: snip]_
_[tool: grep]_
_[tool: snip]_
Lots of references. Let me read screens-1.jsx fully and rewrite it cleanly:
_[tool: read_file]_
_[tool: snip]_
Now let me check the rest of the codebase to see what needs updating:
_[tool: list_files]_
_[tool: grep]_
Let me check data.js and the main HTML file to understand the current state:
_[tool: read_file]_
_[tool: snip]_
Now let me check the main HTML, primitives, and screens-2:
_[tool: read_file]_
_[tool: read_file]_
_[tool: snip]_
Now I have a complete picture. The data model has `status: "active" | "consumed" | "gone"` but `screens-1.jsx` still uses old `p.consumed`, `p.remaining`, `p.weight` patterns and references `data.products[].brand`/`shop` strings. I need to rewrite screens-1.jsx to use the new model.
Let me look at screens-2.jsx briefly to see how it's structured and check for existing usage patterns:
_[tool: read_file]_
_[tool: snip]_
Now I have the full picture. The screens use the OLD model (`p.consumed`, `p.brand`, `p.shop`, `p.remaining`, `p.weight`) but data.js uses the NEW model (`p.status`, `p.brandId`, `p.shopId`, `p.kind`, `p.countLastAudit`, etc.). I need to update all three screens files plus the main HTML to use the new model. Let me also check tokens.css briefly and then rewrite.
_[tool: read_file]_
_[tool: snip]_
Now let me look at the user's most recent ask. I should scroll back to see what they want me to do. Let me check what's going on with the file currently — does it have errors?
_[tool: show_html]_
_[tool: get_webview_logs]_
No errors so far. Let me screenshot to see the actual rendered state:
_[tool: save_screenshot]_
_[tool: view_image]_
_[tool: snip]_
The page renders but the data shows 0g/0$ everywhere because the screens are reading the OLD model fields (`p.consumed`, `p.brand`, `p.shop`, `p.remaining`, `p.weight` for grams) which no longer exist directly. I need to update screens-1.jsx, screens-2.jsx, and the main HTML to use the new model with `status`, `brandId`/`shopId` lookups, and helpers for est-remaining and discrete vs bulk.
Let me delete the old screen files and clean rewrite them. First screens-1.jsx (Dashboard, Inventory, ProductDetail):
_[tool: write_file]_
_[tool: snip]_
Now let me write a smaller screens-2.jsx replacement and a separate screens-3.jsx for the audit/mark-gone modals. First update screens-2:
_[tool: write_file]_
_[tool: snip]_
Now update the main HTML to wire up the new modals (audit, mark-gone) and update the dense/minimal dashboard variants to use the new model:
_[tool: str_replace_edit]_
_[tool: str_replace_edit]_
_[tool: str_replace_edit]_
_[tool: str_replace_edit]_
_[tool: snip]_
Now I need to fix the dense and minimal dashboard variants in the HTML — they still reference `p.consumed`, `p.brand`, `p.shop`, `p.remaining`. Let me update those:
_[tool: str_replace_edit]_
_[tool: str_replace_edit]_
_[tool: str_replace_edit]_
_[tool: snip]_
_[tool: show_html]_
_[tool: snip]_
_[tool: get_webview_logs]_
_[tool: snip]_
_[tool: save_screenshot]_
_[tool: snip]_
_[tool: view_image]_
_[tool: snip]_
The screen looks like an old cached state. The data showing "0.00 g/day" "0g weekly" suggests the new data with audits + decay isn't computing consumption. Let me look at the issue: the screenshot may have been cached. Let me reload and check fresh:
_[tool: save_screenshot]_
Hmm — `screenshot` after `location.reload()` doesn't actually wait for the reload before screenshotting (the screenshot may capture mid-reload). Let me wait:
_[tool: show_html]_
Now wait + screenshot:
_[tool: save_screenshot]_
_[tool: view_image]_
Same render — but the new dashboard should now show "Mark finished" + "Audit" buttons (3 buttons), and counts like "consumed/gone". Looking at the header: "5 bins · 17.9 g on hand · 0 archived" — that's old! Plus only 2 buttons. The new screens-1.jsx isn't loading. Let me check `eval_js` for loaded:
_[tool: eval_js]_
Dashboard exists, but `H` (DATA_HELPERS) is undefined and the products don't have brandId. The data.js isn't the new one I read. Wait — I read data.js as new, but at runtime it's old? Let me check:
_[tool: eval_js]_
The data.js in the cached webview is the OLD version. But I rewrote it. Let me verify the file on disk:
_[tool: grep]_
File on disk is correct. The webview cached the old version. Let me hard reload:
_[tool: eval_js]_
Right, but DATA_HELPERS is undefined and SAMPLE_DATA has old fields. So data.js is being served stale. Let me cache-bust by adding a version comment-edit, or by checking what's actually happening — let me reload the iframe with a hard reload:
_[tool: eval_js]_
So the FILE is fine, but the webview cached an older version. Cache-busting via a query param works. The iframe just held an old script. Let me force reload the page (and verify):
_[tool: show_html]_
_[tool: sleep]_
_[tool: eval_js]_
Hmm. Despite the network fetching fresh data, the script tag itself loads stale. There must be a syntax error in data.js causing it to fail silently then fall back to old. Let me check console:
_[tool: get_webview_logs]_
No errors but DATA_HELPERS is undefined. So data.js executes but the helpers aren't being attached? Let me check if SAMPLE_DATA itself has new structure:
_[tool: eval_js]_
SAMPLE_DATA has both old AND new keys: it has top-level `shops`, `brands`, `types` (new) but products use OLD `brand`, `shop` strings. That means data.js was edited inconsistently. Let me look at data.js carefully:
_[tool: read_file]_
So data.js should produce products with `brandId`, `kind`, etc. But what the iframe runtime shows is a product with old `brand`/`shop` and no `kind`. There must be TWO data.js loads — let me look at the HTML:
_[tool: grep]_
Single data.js. The runtime shows old keys. Let me check — does data.js have a stale section that sets old keys? Maybe I added new `BRANDS` array but didn't actually change the products inside the function:
_[tool: grep]_
No old fields exist in source. The runtime is using a stale cached version. Let me cache-bust the script tag:
_[tool: str_replace_edit]_
Wait — earlier `eval_js` of fetch directly showed `data.js?bust=...` HAS DATA_HELPERS. So fresh fetch is fine. The script tag without query string was returning OLD content. That's a service-worker caching issue or similar. The query-string bust should fix it.
_[tool: grep]_
Let me bust those too and verify:
_[tool: str_replace_edit]_
Now let me verify everything renders:
_[tool: show_html]_
_[tool: sleep]_
_[tool: eval_js]_
DATA_HELPERS is now loaded, products have new fields. Let me check console + screenshot:
_[tool: get_webview_logs]_
Clean. Let me screenshot:
_[tool: save_screenshot]_
_[tool: view_image]_
_[tool: snip]_
Looking at the dashboard now:
**Issues:**
1. "Good evening" overlaps with "Cuts of... 5 bins · 17.9 g on hand · 0 archived" subtitle
2. All stats show 0: "0.00 g/day", "$0.00 avg cost per gram", "0 mg THC last 7 days" — but "30-day spend $555". The compute is broken for consumption (which derives from audits + estimated decay).
3. The header still says "17.9 g on hand" — but with new estimated-remaining decay, this should reflect estimated total.
Let me read the Dashboard component:
_[tool: grep]_
Code references `stats.activeCount`, `stats.consumedCount`, `stats.goneCount`, `stats.dailyAvg`. Let me check computeStats:
_[tool: grep]_
Let me look at how series30 (consumption) is computed:
_[tool: read_file]_
OK so computeStats is rich and should produce non-zero numbers. But UI shows 0.00. Let me check what's actually returned at runtime:
_[tool: eval_js]_
So the numbers are correctly computed: 0.49 g/day, $18/g, $639 spend30, 1473mg THC last 7, etc. But the UI shows 0. So screens-1.jsx is rendering with the old data? Let me check what stats the React component actually sees — the React app's `useMemo` may have cached old stats. The `data` reference might still be stale. Actually — React stale closure: `data = window.SAMPLE_DATA` was captured before the new data.js loaded. But it should re-render now.
Actually I bet what's rendering on screen is from a render BEFORE data.js loaded fresh. Let me force a real reload:
_[tool: save_screenshot]_
Hmm actually looking back — in eval_js the `computeStats` call returned correct values right now. So why does the screenshot show 0? Maybe my reload screenshot races. Let me wait then evaluate the DOM:
_[tool: sleep]_
Wait actually let me check. After `location.reload()`, the page reloads and `computeStats` would run on data with fresh helpers. But reload may have lost iframe state. Let me re-show + grab fresh screenshot:
_[tool: show_html]_
_[tool: sleep]_
Going to check the DOM:
_[tool: eval_js]_
Now the dashboard renders correctly with new stats: 15 active, 4 consumed, 2 gone, 0.49 g/day, $17.96/g, $639 spend, 1473mg THC, audit overdue alert for Slate Cherry.
Now let me screenshot:
_[tool: save_screenshot]_
Header says "Cuts of..." was likely an old screenshot rendering issue. Let me view:
_[tool: view_image]_
_[tool: snip]_
The screenshot shows a STALE render — innerText reports the correct content (15 active, 4 consumed, 2 gone, 0.49 g/day, $17.96/g, $639) but the image shows the OLD render (15 items, 17.9g on hand, 0.00 g/day, $0.00, $555).
This is `save_screenshot` capturing a stale rasterization. The DOM is correct. Let me try again with extra delay:
_[tool: save_screenshot]_
Wait — the discrepancy is clear: innerText shows "21 items" and "15 active items"; screenshot shows "15 items" (sidebar) and old text. So this is two different DOMs being measured. innerText was after fresh reload; screenshot may have triggered a NEW reload that hasn't completed.
Actually `show_html` reloads. Looking at sidebar in screenshot: "v0.4 · 15 items" — this is OLD count. After my data update there are 21 products. So the screenshot is from BEFORE the refresh. The verifier's iframe may be different from eval_js iframe.
Let me try `multi_screenshot` which reuses the existing rendered DOM:
_[tool: multi_screenshot]_
Now the dashboard renders correctly! Stats are populated: 0.49 g/day, $17.96/g, $639 spend, 1,473mg THC, audit overdue alert for Slate Cherry, sparkline visible.
But I see one issue: **"Good evening." overlaps with the subtitle text** — "Good evening." block height collides with the active-items line. The h1 has `lineHeight: 1.1` and `margin: "6px 0 0"`, then below is a div with `marginBottom: 28`. Let me check the structure:
_[tool: read_file]_
The header div uses `alignItems: "center"`. With "Good evening." being two lines wrapped (because the buttons take width and the title flexs to 2 lines), it goes below the buttons. The subtitle below then overlaps because of the negative-ish lineHeight.
Actually looking again — "Good evening." is wrapping to two lines. That's because the title container is too narrow. Buttons take 3 of them now. Let me make this responsive — let the heading not wrap, and shrink:
_[tool: str_replace_edit]_
Now done:
_[tool: done]_
The dashboard now renders correctly with the new data model — 15 active / 4 consumed / 2 gone items, 0.49 g/day average, $17.96/g cost, $639 30-day spend, an audit-overdue card flagging Slate Cherry, and the new "Audit" button alongside Mark finished. Cache-busted script tags so the iframe picks up the fresh JS.
_[tool: fork_verifier_agent]_
Dashboard's working with the audit + gone/consumed split. Let me know if you want me to keep going on the rest of the screens (Inventory list with audit badges, the AuditModal, etc.) or pause here.
## User
Apply comment
## Assistant
Let me look at that slide:
_[tool: grep]_
Let me see the full line:
_[tool: read_file]_
The text is corrupted — "the cabinet you'veidn't realize you were on." is gibberish. Let me fix it to something clear:
_[tool: str_replace_edit]_
Fixed — that sentence was garbled (the second half was corrupted text). Now reads cleanly: "The morning glance. Daily averages, spend trends, days of supply — everything you need to see in a single look."
_[tool: done]_
_[tool: snip]_
Fixed the garbled sentence. The font-size warnings are decorative micro-labels (mono captions, eyebrow text) — intentional design choices, not real problems.
## User
Apply comment
## Assistant
The "Dashboard." title at 200px is way too big and getting clipped by the slide bounds. Let me check the slide and fix:
_[tool: grep]_
_[tool: snip]_
Let me check slide-pad layout — likely set to flex column with center-justify, but the 200px text overflows. Let me look at the slide-pad CSS and the deck-stage size:
_[tool: grep]_
_[tool: snip]_
The 200px section titles are too big for the slide. With slide-pad padding 100px, the available width is 1720px, but more critically the height with `justify-content: center` plus 200px line-height pushes content out. Let me reduce to 160px which still feels strong:
_[tool: str_replace_edit]_
_[tool: done]_
_[tool: snip]_
Brought the section titles down from 200px to 160px so they fit cleanly within the slide.
## User
No I think it's the color that makes it invisible lol
## Assistant
Ha — let me check. The slide is `.bg-ink` (dark) and `.h-display` color likely defaults to `var(--ink)` which is also dark on dark.
_[tool: grep]_
Confirmed — `.h-display` color is `var(--ink)` which is dark, on a `bg-ink` (also dark) background. The `.bg-ink .h2, .bg-ink .h1` rule covers h1/h2 but NOT `.h-display`. Same issue exists for `.bg-sage` and `.bg-terra`. Let me fix:
_[tool: str_replace_edit]_
_[tool: str_replace_edit]_
_[tool: snip]_
You were right — `.h-display` color was `var(--ink)` which made it invisible on the dark, sage, and terra backgrounds. Added it to the override rules alongside `.h1` and `.h2`.
_[tool: done]_
_[tool: snip]_
Section titles should now be visible on all three colored section dividers.
+411
View File
@@ -0,0 +1,411 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Apothecary — A personal inventory system</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;500;600;700&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="tokens.css" />
<style>
body { background: #1a1a1a; }
deck-stage { background: #1a1a1a; }
deck-stage > section {
background: var(--bg);
color: var(--ink);
font-family: var(--sans);
overflow: hidden;
display: flex;
}
.slide-pad { padding: 100px; width: 100%; height: 100%; display: flex; flex-direction: column; box-sizing: border-box; }
.eyebrow {
font-family: var(--mono);
font-size: 22px;
text-transform: uppercase;
letter-spacing: 0.16em;
color: var(--ink-3);
font-weight: 500;
}
.h-display {
font-family: var(--serif);
font-size: 140px;
font-weight: 500;
line-height: 0.95;
letter-spacing: -0.025em;
color: var(--ink);
}
.h1 {
font-family: var(--serif);
font-size: 96px;
font-weight: 500;
line-height: 1;
letter-spacing: -0.02em;
color: var(--ink);
}
.h2 {
font-family: var(--serif);
font-size: 64px;
font-weight: 500;
line-height: 1.05;
letter-spacing: -0.015em;
color: var(--ink);
}
.body {
font-size: 34px;
line-height: 1.45;
color: var(--ink-2);
text-wrap: pretty;
}
.small {
font-size: 28px;
line-height: 1.45;
color: var(--ink-2);
}
.micro {
font-size: 24px;
color: var(--ink-3);
}
.mono-label {
font-family: var(--mono);
font-size: 22px;
text-transform: uppercase;
letter-spacing: 0.12em;
color: var(--ink-3);
}
.hairline { border-top: 1px solid var(--line); }
.footer {
position: absolute;
bottom: 60px;
left: 100px;
right: 100px;
display: flex;
justify-content: space-between;
font-family: var(--mono);
font-size: 18px;
color: var(--ink-3);
letter-spacing: 0.08em;
text-transform: uppercase;
}
.swatch-card {
background: var(--surface);
border: 1px solid var(--line);
border-radius: 14px;
padding: 36px;
}
.stat-display {
font-family: var(--serif);
font-size: 200px;
font-weight: 400;
line-height: 0.9;
letter-spacing: -0.03em;
color: var(--ink);
}
.quote {
font-family: var(--serif);
font-size: 76px;
font-weight: 400;
font-style: italic;
line-height: 1.2;
letter-spacing: -0.015em;
color: var(--ink);
text-wrap: balance;
}
.bg-parchment { background: var(--bg-2); }
.bg-ink { background: var(--ink); color: var(--bg); }
.bg-ink .h2, .bg-ink .h1, .bg-ink .h-display { color: var(--bg); }
.bg-ink .eyebrow, .bg-ink .micro, .bg-ink .body, .bg-ink .small { color: oklch(80% 0.012 75); }
.bg-sage { background: oklch(45% 0.06 145); color: oklch(95% 0.02 145); }
.bg-sage .h1, .bg-sage .h2, .bg-sage .h-display, .bg-sage .quote { color: oklch(96% 0.02 145); }
.bg-sage .eyebrow, .bg-sage .body, .bg-sage .micro { color: oklch(85% 0.04 145); }
.bg-terra { background: oklch(48% 0.10 40); color: oklch(96% 0.02 40); }
.bg-terra .h1, .bg-terra .h2, .bg-terra .h-display { color: oklch(96% 0.02 40); }
.bg-terra .eyebrow, .bg-terra .body, .bg-terra .micro { color: oklch(86% 0.04 40); }
</style>
</head>
<body>
<deck-stage width="1920" height="1080">
<!-- 01 — Cover -->
<section data-label="01 Cover" style="position: relative; flex-direction: column; justify-content: space-between;">
<div class="slide-pad" style="justify-content: space-between;">
<div style="display: flex; align-items: center; gap: 14px;">
<div style="width: 56px; height: 56px; border-radius: 50%; border: 1.5px solid var(--ink); display: flex; align-items: center; justify-content: center; font-family: var(--serif); font-size: 30px; font-style: italic;">A</div>
<div>
<div style="font-family: var(--serif); font-size: 32px; font-weight: 500; line-height: 1;">Apothecary</div>
<div class="mono-label" style="font-size: 16px;">A personal log</div>
</div>
</div>
<div>
<div class="eyebrow" style="margin-bottom: 28px;">Concept · Apr 2026</div>
<div class="h-display" style="font-style: italic;">A quiet, careful<br/>record of what's<br/>in your cabinet.</div>
<div class="body" style="margin-top: 36px; max-width: 1100px; font-size: 36px;">
A personal inventory system for keeping clean, professional records of cannabis purchases — what you have, where it lives, what you've used, and what's worth buying again.
</div>
</div>
<div style="display: flex; justify-content: space-between; align-items: flex-end;">
<div class="micro">For personal use · Local-first · No accounts</div>
<div class="mono-label" style="font-size: 16px;">v0.4 · CONCEPT DECK</div>
</div>
</div>
</section>
<!-- 02 — Why -->
<section data-label="02 Why this exists">
<div class="slide-pad">
<div class="eyebrow">Why this exists</div>
<div class="h1" style="margin-top: 32px; max-width: 1500px;">Notes apps and spreadsheets can't keep up with a real apothecary.</div>
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 60px; margin-top: 100px; padding-top: 60px; border-top: 1px solid var(--line);">
<div>
<div class="mono-label" style="margin-bottom: 20px;">01 Memory fades</div>
<div class="small">You forget what you paid, where you bought it, or whether the last batch was any good.</div>
</div>
<div>
<div class="mono-label" style="margin-bottom: 20px;">02 Spend goes unmeasured</div>
<div class="small">Without a real per-gram view, it's easy to over-pay and not realize the trend.</div>
</div>
<div>
<div class="mono-label" style="margin-bottom: 20px;">03 Habits are invisible</div>
<div class="small">Daily, weekly, and monthly use are hard to see clearly without a structured log.</div>
</div>
</div>
</div>
</section>
<!-- 03 — Big stat -->
<section data-label="03 The market" class="bg-parchment">
<div class="slide-pad" style="justify-content: center;">
<div class="eyebrow" style="margin-bottom: 40px;">The premise</div>
<div class="stat-display">$1,847</div>
<div class="h2" style="margin-top: 30px; max-width: 1300px;">is what a moderate consumer might spend in a year — without a single line item to show for it.</div>
<div class="micro" style="margin-top: 60px;">Apothecary turns that into a record you actually own.</div>
</div>
</section>
<!-- 04 — What it is -->
<section data-label="04 What it is">
<div class="slide-pad">
<div class="eyebrow">What it is</div>
<div class="h1" style="margin-top: 32px;">An inventory system,<br/><span style="font-style: italic; color: var(--ink-2);">designed like a library catalog.</span></div>
<div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 40px; margin-top: 80px;">
<div class="swatch-card">
<div class="mono-label">Every item is tracked</div>
<div class="h2" style="font-size: 42px; margin-top: 14px;">SKU, asset tag, weight, THC, CBD, total cannabinoids, shop, brand, type, date.</div>
</div>
<div class="swatch-card">
<div class="mono-label">Every item has a place</div>
<div class="h2" style="font-size: 42px; margin-top: 14px;">Physical bins — Top Drawer, Apothecary Box, The Safe — with capacity limits.</div>
</div>
<div class="swatch-card">
<div class="mono-label">Mark when finished</div>
<div class="h2" style="font-size: 42px; margin-top: 14px;">Date finished, rating, and final notes — the archive becomes a tasting library.</div>
</div>
<div class="swatch-card">
<div class="mono-label">Nothing leaves the archive</div>
<div class="h2" style="font-size: 42px; margin-top: 14px;">Consumed items keep their record — final notes, rating, lifespan, all preserved.</div>
</div>
</div>
</div>
</section>
<!-- 05 — Section header -->
<section data-label="05 Section: Dashboard" class="bg-ink">
<div class="slide-pad" style="justify-content: center; align-items: flex-start;">
<div class="mono-label" style="color: oklch(70% 0.04 145);">Part 01 / 03</div>
<div class="h-display" style="font-size: 160px; margin-top: 24px;">Dashboard.</div>
<div class="body" style="margin-top: 40px; max-width: 1200px; font-size: 36px; color: oklch(80% 0.012 75);">The morning glance. Daily averages, spend trends, days of supply — everything you need to see in a single look.</div>
</div>
</section>
<!-- 06 — Stats showcase -->
<section data-label="06 The numbers">
<div class="slide-pad">
<div class="eyebrow">What the dashboard answers</div>
<div class="h2" style="margin-top: 28px; max-width: 1500px;">Ten quiet questions you've never asked out loud.</div>
<div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 1px; margin-top: 80px; background: var(--line); border: 1px solid var(--line); border-radius: 14px; overflow: hidden;">
<div style="background: var(--surface); padding: 36px;"><div class="mono-label" style="font-size: 18px; margin-bottom: 12px;">Daily avg</div><div style="font-family: var(--serif); font-size: 56px; line-height: 1;">0.52<span style="font-size: 22px; color: var(--ink-3); margin-left: 6px;">g</span></div></div>
<div style="background: var(--surface); padding: 36px;"><div class="mono-label" style="font-size: 18px; margin-bottom: 12px;">Avg $/g</div><div style="font-family: var(--serif); font-size: 56px; line-height: 1;">$13.40</div></div>
<div style="background: var(--surface); padding: 36px;"><div class="mono-label" style="font-size: 18px; margin-bottom: 12px;">30d spend</div><div style="font-family: var(--serif); font-size: 56px; line-height: 1;">$284</div></div>
<div style="background: var(--surface); padding: 36px;"><div class="mono-label" style="font-size: 18px; margin-bottom: 12px;">7d THC</div><div style="font-family: var(--serif); font-size: 56px; line-height: 1;">766<span style="font-size: 22px; color: var(--ink-3); margin-left: 6px;">mg</span></div></div>
<div style="background: var(--surface); padding: 36px;"><div class="mono-label" style="font-size: 18px; margin-bottom: 12px;">Avg lifespan</div><div style="font-family: var(--serif); font-size: 56px; line-height: 1;">37<span style="font-size: 22px; color: var(--ink-3); margin-left: 6px;">d</span></div></div>
<div style="background: var(--surface); padding: 36px;"><div class="mono-label" style="font-size: 18px; margin-bottom: 12px;">Inv. value</div><div style="font-family: var(--serif); font-size: 56px; line-height: 1;">$398</div></div>
<div style="background: var(--surface); padding: 36px;"><div class="mono-label" style="font-size: 18px; margin-bottom: 12px;">Days supply</div><div style="font-family: var(--serif); font-size: 56px; line-height: 1;">28<span style="font-size: 22px; color: var(--ink-3); margin-left: 6px;">d</span></div></div>
<div style="background: var(--surface); padding: 36px;"><div class="mono-label" style="font-size: 18px; margin-bottom: 12px;">Avg gap</div><div style="font-family: var(--serif); font-size: 56px; line-height: 1;">8.4<span style="font-size: 22px; color: var(--ink-3); margin-left: 6px;">d</span></div></div>
<div style="background: var(--surface); padding: 36px;"><div class="mono-label" style="font-size: 18px; margin-bottom: 12px;">Top shop</div><div style="font-family: var(--serif); font-size: 36px; line-height: 1.05; margin-top: 14px;">Greenleaf Co-op</div></div>
<div style="background: var(--surface); padding: 36px;"><div class="mono-label" style="font-size: 18px; margin-bottom: 12px;">Top brand</div><div style="font-family: var(--serif); font-size: 36px; line-height: 1.05; margin-top: 14px;">Foxglove Farms</div></div>
</div>
</div>
</section>
<!-- 07 — Section header -->
<section data-label="07 Section: Inventory" class="bg-sage">
<div class="slide-pad" style="justify-content: center; align-items: flex-start;">
<div class="mono-label">Part 02 / 03</div>
<div class="h-display" style="font-size: 160px; margin-top: 24px;">Inventory.</div>
<div class="body" style="margin-top: 40px; max-width: 1200px; font-size: 36px;">Each product gets a SKU, an optional asset tag, a bin, a price, a chemistry. The catalog of a small, careful library.</div>
</div>
</section>
<!-- 08 — Product anatomy -->
<section data-label="08 Product anatomy">
<div class="slide-pad">
<div class="eyebrow">Anatomy of a product</div>
<div class="h2" style="margin-top: 28px;">Every entry, comprehensive.</div>
<div style="display: grid; grid-template-columns: 1.4fr 1fr; gap: 80px; margin-top: 60px; align-items: flex-start;">
<div style="border: 1px solid var(--line); border-radius: 14px; padding: 50px; background: var(--surface);">
<div class="mono-label" style="font-size: 18px;">◆ Concentrate · Active</div>
<div style="font-family: var(--serif); font-size: 72px; font-weight: 500; line-height: 1; margin-top: 14px; letter-spacing: -0.02em;">Indigo Cellar<br/>Live Rosin</div>
<div class="small" style="margin-top: 14px; font-size: 28px;">Heirloom Botanicals · from The Field House</div>
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 1px; margin-top: 50px; background: var(--line); border: 1px solid var(--line); border-radius: 10px; overflow: hidden;">
<div style="background: var(--surface); padding: 22px;"><div class="mono-label" style="font-size: 14px;">Price</div><div style="font-family: var(--serif); font-size: 38px; margin-top: 8px;">$65</div></div>
<div style="background: var(--surface); padding: 22px;"><div class="mono-label" style="font-size: 14px;">Weight</div><div style="font-family: var(--serif); font-size: 38px; margin-top: 8px;">1.0 g</div></div>
<div style="background: var(--surface); padding: 22px;"><div class="mono-label" style="font-size: 14px;">THC</div><div style="font-family: var(--serif); font-size: 38px; margin-top: 8px;">78.4%</div></div>
<div style="background: var(--surface); padding: 22px;"><div class="mono-label" style="font-size: 14px;">CBD</div><div style="font-family: var(--serif); font-size: 38px; margin-top: 8px;">0.2%</div></div>
</div>
<div style="margin-top: 30px; font-family: var(--mono); font-size: 22px; color: var(--ink-3); display: flex; gap: 24px;">
<span>SKU-A39FQX</span>
<span>·</span>
<span>AT-0042</span>
<span>·</span>
<span>The Safe</span>
</div>
</div>
<div>
<div class="mono-label" style="margin-bottom: 30px;">Tracked fields</div>
<ul style="list-style: none; padding: 0; margin: 0; font-size: 26px; line-height: 1.9; color: var(--ink-2);">
<li>— Name &amp; brand</li>
<li>— SKU + optional asset tag</li>
<li>— Type (flower, concentrate, edible, vape, pre-roll, tincture)</li>
<li>— Shop &amp; purchase date</li>
<li>— Price + computed cost-per-gram</li>
<li>— Weight, THC%, CBD%, total cannabinoids%</li>
<li>— Bin location &amp; remaining quantity</li>
<li>— Final notes &amp; rating after consumed</li>
</ul>
</div>
</div>
</div>
</section>
<!-- 09 — Bins -->
<section data-label="09 Bins" class="bg-parchment">
<div class="slide-pad">
<div class="eyebrow">Storage</div>
<div class="h1" style="margin-top: 32px;">Every product knows<br/>where it lives.</div>
<div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 24px; margin-top: 90px;">
<div style="background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 28px; aspect-ratio: 0.85; display: flex; flex-direction: column;">
<div class="mono-label" style="font-size: 16px;">Bin 01</div>
<div style="font-family: var(--serif); font-size: 40px; font-weight: 500; line-height: 1.05; margin-top: 14px;">Top Drawer</div>
<div class="micro" style="margin-top: 8px;">Bedroom</div>
<div style="flex: 1;"></div>
<div style="height: 4px; background: oklch(85% 0.02 75); border-radius: 2px; margin-bottom: 10px;"><div style="width: 30%; height: 100%; background: var(--sage); border-radius: 2px;"></div></div>
<div class="mono-label" style="font-size: 14px;">4 / 14</div>
</div>
<div style="background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 28px; aspect-ratio: 0.85; display: flex; flex-direction: column;">
<div class="mono-label" style="font-size: 16px;">Bin 02</div>
<div style="font-family: var(--serif); font-size: 40px; font-weight: 500; line-height: 1.05; margin-top: 14px;">Apothecary Box</div>
<div class="micro" style="margin-top: 8px;">Office shelf</div>
<div style="flex: 1;"></div>
<div style="height: 4px; background: oklch(85% 0.02 75); border-radius: 2px; margin-bottom: 10px;"><div style="width: 20%; height: 100%; background: var(--sage); border-radius: 2px;"></div></div>
<div class="mono-label" style="font-size: 14px;">2 / 10</div>
</div>
<div style="background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 28px; aspect-ratio: 0.85; display: flex; flex-direction: column;">
<div class="mono-label" style="font-size: 16px;">Bin 03</div>
<div style="font-family: var(--serif); font-size: 40px; font-weight: 500; line-height: 1.05; margin-top: 14px;">The Safe</div>
<div class="micro" style="margin-top: 8px;">Closet</div>
<div style="flex: 1;"></div>
<div style="height: 4px; background: oklch(85% 0.02 75); border-radius: 2px; margin-bottom: 10px;"><div style="width: 38%; height: 100%; background: var(--sage); border-radius: 2px;"></div></div>
<div class="mono-label" style="font-size: 14px;">3 / 8</div>
</div>
<div style="background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 28px; aspect-ratio: 0.85; display: flex; flex-direction: column;">
<div class="mono-label" style="font-size: 16px;">Bin 04</div>
<div style="font-family: var(--serif); font-size: 40px; font-weight: 500; line-height: 1.05; margin-top: 14px;">Travel Tin</div>
<div class="micro" style="margin-top: 8px;">Backpack</div>
<div style="flex: 1;"></div>
<div style="height: 4px; background: oklch(85% 0.02 75); border-radius: 2px; margin-bottom: 10px;"><div style="width: 50%; height: 100%; background: var(--amber); border-radius: 2px;"></div></div>
<div class="mono-label" style="font-size: 14px;">2 / 4</div>
</div>
<div style="background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 28px; aspect-ratio: 0.85; display: flex; flex-direction: column;">
<div class="mono-label" style="font-size: 16px;">Bin 05</div>
<div style="font-family: var(--serif); font-size: 40px; font-weight: 500; line-height: 1.05; margin-top: 14px;">Cold Storage</div>
<div class="micro" style="margin-top: 8px;">Fridge — back</div>
<div style="flex: 1;"></div>
<div style="height: 4px; background: oklch(85% 0.02 75); border-radius: 2px; margin-bottom: 10px;"><div style="width: 17%; height: 100%; background: var(--sage); border-radius: 2px;"></div></div>
<div class="mono-label" style="font-size: 14px;">1 / 6</div>
</div>
</div>
<div class="micro" style="margin-top: 60px; max-width: 1400px;">When a product is consumed, it leaves its bin but stays in the archive — keeping the record of what worked, what didn't, and what's worth a rebuy.</div>
</div>
</section>
<!-- 10 — Section: Habit -->
<section data-label="10 Section: Patterns" class="bg-terra">
<div class="slide-pad" style="justify-content: center; align-items: flex-start;">
<div class="mono-label">Part 03 / 03</div>
<div class="h-display" style="font-size: 160px; margin-top: 24px;">Patterns.</div>
<div class="body" style="margin-top: 40px; max-width: 1200px; font-size: 36px;">Where the data quietly becomes useful — habits made visible, spend made measurable.</div>
</div>
</section>
<!-- 11 — Quote -->
<section data-label="11 Quote">
<div class="slide-pad" style="justify-content: center;">
<div style="max-width: 1500px;">
<div class="quote">"You can't keep<br/>what you don't<br/>write down."</div>
<div class="mono-label" style="margin-top: 60px;">— Operating principle</div>
</div>
</div>
</section>
<!-- 12 — Roadmap / next -->
<section data-label="12 Next">
<div class="slide-pad">
<div class="eyebrow">What's next</div>
<div class="h1" style="margin-top: 32px;">Three releases<br/>to feel done.</div>
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 60px; margin-top: 100px; padding-top: 50px; border-top: 1px solid var(--line);">
<div>
<div class="mono-label">v0.5 · May</div>
<div class="h2" style="font-size: 44px; margin-top: 16px;">Add &amp; consume</div>
<div class="small" style="margin-top: 18px; font-size: 26px;">Polish on the entry forms, barcode &amp; receipt photo capture, faster bulk add.</div>
</div>
<div>
<div class="mono-label">v0.7 · July</div>
<div class="h2" style="font-size: 44px; margin-top: 16px;">Charts &amp; export</div>
<div class="small" style="margin-top: 18px; font-size: 26px;">Heatmap, monthly spend, shop comparisons. CSV &amp; JSON export with no cloud.</div>
</div>
<div>
<div class="mono-label">v1.0 · September</div>
<div class="h2" style="font-size: 44px; margin-top: 16px;">Mobile app</div>
<div class="small" style="margin-top: 18px; font-size: 26px;">Native iOS / Android with biometric lock. Same local-first principle.</div>
</div>
</div>
</div>
</section>
<!-- 13 — End -->
<section data-label="13 End" class="bg-ink">
<div class="slide-pad" style="justify-content: space-between;">
<div style="display: flex; align-items: center; gap: 14px;">
<div style="width: 56px; height: 56px; border-radius: 50%; border: 1.5px solid var(--bg); display: flex; align-items: center; justify-content: center; font-family: var(--serif); font-size: 30px; font-style: italic; color: var(--bg);">A</div>
<div>
<div style="font-family: var(--serif); font-size: 32px; font-weight: 500; line-height: 1; color: var(--bg);">Apothecary</div>
<div class="mono-label" style="font-size: 16px; color: oklch(70% 0.04 145);">A personal log</div>
</div>
</div>
<div>
<div class="h-display" style="font-style: italic; color: var(--bg); font-size: 180px;">Keep<br/>a record.</div>
<div class="body" style="margin-top: 50px; font-size: 36px; color: oklch(80% 0.012 75); max-width: 1100px;">A small, careful inventory of a small, careful library.</div>
</div>
<div style="display: flex; justify-content: space-between; align-items: flex-end;">
<div class="mono-label" style="color: oklch(70% 0.04 145);">Live prototype available</div>
<div class="mono-label" style="color: oklch(70% 0.04 145); font-size: 16px;">END · 13 / 13</div>
</div>
</div>
</section>
</deck-stage>
<script src="deck-stage.js"></script>
</body>
</html>
@@ -0,0 +1,405 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Apothecary — Personal Inventory</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;500;600&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="tokens.css" />
<style>
/* App chrome */
.app-shell {
min-height: 100vh;
display: grid;
grid-template-columns: 220px 1fr;
}
.sidebar {
border-right: 1px solid var(--line);
background: var(--bg-2);
padding: 28px 18px;
display: flex;
flex-direction: column;
gap: 4px;
position: sticky;
top: 0;
height: 100vh;
overflow: auto;
}
.brand {
display: flex;
align-items: center;
gap: 10px;
padding: 0 8px 28px;
}
.brand-mark {
width: 32px; height: 32px;
border-radius: 50%;
border: 1px solid var(--ink);
display: flex; align-items: center; justify-content: center;
font-family: var(--serif);
font-size: 18px;
font-style: italic;
color: var(--ink);
}
.nav-link {
display: flex; align-items: center; gap: 10px;
padding: 9px 12px;
border-radius: var(--r-md);
color: var(--ink-2);
cursor: pointer;
font-size: 13px;
font-weight: 500;
border: none;
background: transparent;
text-align: left;
transition: background 100ms;
}
.nav-link:hover { background: var(--bg-3); color: var(--ink); }
.nav-link.active { background: var(--surface); color: var(--ink); box-shadow: var(--shadow-sm); border: 1px solid var(--line); }
.nav-section {
font-size: 10px; text-transform: uppercase;
letter-spacing: 0.12em;
color: var(--ink-3);
padding: 16px 12px 6px;
font-weight: 500;
}
.inv-row:hover { background: var(--bg-2); }
@media (max-width: 880px) {
.app-shell { grid-template-columns: 1fr; }
.sidebar {
position: fixed; bottom: 0; left: 0; right: 0; top: auto;
height: auto;
flex-direction: row;
padding: 8px 12px;
border-top: 1px solid var(--line);
border-right: none;
z-index: 30;
overflow-x: auto;
}
.brand, .nav-section { display: none; }
.nav-link { white-space: nowrap; padding: 8px 12px; }
.main { padding-bottom: 60px; }
}
</style>
</head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js" integrity="sha384-hD6/rw4ppMLGNu3tX5cjIb+uRZ7UkRJ6BPkLpg4hAu/6onKUg4lLsHAs9EBPT82L" crossorigin="anonymous"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js" integrity="sha384-u6aeetuaXnQ38mYT8rp6sbXaQe3NL9t+IBXmnYxwkUI2Hw4bsp2Wvmx4yRQF1uAm" crossorigin="anonymous"></script>
<script src="https://unpkg.com/@babel/standalone@7.29.0/babel.min.js" integrity="sha384-m08KidiNqLdpJqLq95G/LEi8Qvjl/xUYll3QILypMoQ65QorJ9Lvtp2RXYGBFj1y" crossorigin="anonymous"></script>
<script src="data.js?v=4"></script>
<script type="text/babel" src="primitives.jsx?v=4"></script>
<script type="text/babel" src="screens-1.jsx?v=4"></script>
<script type="text/babel" src="screens-2.jsx?v=4"></script>
<script type="text/babel" src="tweaks-panel.jsx?v=4"></script>
<script type="text/babel">
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
"theme": "light",
"dashboard": "editorial",
"tone": "botanical",
"accent": "sage"
}/*EDITMODE-END*/;
const NAV = [
{ key: "dashboard", label: "Dashboard", icon: "home" },
{ key: "inventory", label: "Inventory", icon: "box" },
{ key: "bins", label: "Bins", icon: "bin" },
{ key: "charts", label: "Patterns", icon: "chart" },
{ key: "settings", label: "Settings", icon: "settings" }
];
const TONE_LABELS = {
botanical: { brand: "Apothecary", tagline: "A personal log" },
neutral: { brand: "Inventory", tagline: "Personal stockkeeping" },
discreet: { brand: "The Cabinet", tagline: "Private register" }
};
function App() {
const [tweaks, setTweaks] = useTweaks(TWEAK_DEFAULTS);
const [view, setView] = React.useState("dashboard");
const [selected, setSelected] = React.useState(null);
const [modal, setModal] = React.useState(null); // 'add' | 'consume' | 'gone' | 'audit'
const [modalProduct, setModalProduct] = React.useState(null);
const [tweaksOpen, setTweaksOpen] = React.useState(false);
const data = window.SAMPLE_DATA;
const stats = React.useMemo(() => computeStats(data), [data]);
// Apply theme
React.useEffect(() => {
document.documentElement.setAttribute("data-theme", tweaks.theme);
}, [tweaks.theme]);
// Tweaks toggle wiring
React.useEffect(() => {
const handler = (e) => {
if (e.data?.type === "__activate_edit_mode") setTweaksOpen(true);
if (e.data?.type === "__deactivate_edit_mode") setTweaksOpen(false);
};
window.addEventListener("message", handler);
window.parent.postMessage({type: "__edit_mode_available"}, "*");
return () => window.removeEventListener("message", handler);
}, []);
const labels = TONE_LABELS[tweaks.tone] || TONE_LABELS.botanical;
const onNav = (target) => {
if (target === "add") { setModalProduct(null); setModal("add"); }
else if (target === "consume") { setModalProduct(null); setModal("consume"); }
else if (target === "gone") { setModalProduct(null); setModal("gone"); }
else if (target === "audit") { setModalProduct(null); setModal("audit"); }
else setView(target);
};
const openAudit = (p) => { setModalProduct(p); setModal("audit"); };
const openGone = (p) => { setModalProduct(p); setSelected(null); setModal("gone"); };
const openConsume = (p) => { setModalProduct(p); setSelected(null); setModal("consume"); };
const handleSave = () => {
setModal(null);
};
return (
<div className="app-shell" data-screen-label="App">
{/* Sidebar */}
<aside className="sidebar">
<div className="brand">
<div className="brand-mark">A</div>
<div>
<div className="serif" style={{fontSize: 18, fontWeight: 500, lineHeight: 1}}>{labels.brand}</div>
<div style={{fontSize: 10, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.1em"}}>{labels.tagline}</div>
</div>
</div>
<div className="nav-section">Workspace</div>
{NAV.map(n => (
<button key={n.key} className={"nav-link " + (view === n.key ? "active" : "")} onClick={() => setView(n.key)}>
<Icon name={n.icon} size={16} />
{n.label}
</button>
))}
<div className="nav-section">Quick</div>
<button className="nav-link" onClick={() => setModal("add")}>
<Icon name="plus" size={16} /> Add product
</button>
<button className="nav-link" onClick={() => setModal("consume")}>
<Icon name="check" size={16} /> Mark finished
</button>
<div style={{flex: 1}} />
<div style={{padding: 12, fontSize: 11, color: "var(--ink-3)", borderTop: "1px solid var(--line)", marginTop: 12}}>
<div className="mono">v0.4 · {data.products.length} items</div>
<div style={{marginTop: 4}}>Local-only · Apr 2026</div>
</div>
</aside>
{/* Main */}
<main className="main parchment" style={{minWidth: 0}}>
{view === "dashboard" && (
<DashboardSwitch
variant={tweaks.dashboard}
data={data}
stats={stats}
onNav={onNav}
onSelectProduct={setSelected}
onAudit={openAudit}
/>
)}
{view === "inventory" && <Inventory data={data} onSelectProduct={setSelected} onNav={onNav} />}
{view === "bins" && <BinsView data={data} onSelectProduct={setSelected} />}
{view === "charts" && <ChartsView data={data} stats={stats} />}
{view === "settings" && <SettingsView data={data} tweaks={tweaks} onTweakChange={(k,v) => setTweaks({...tweaks, [k]: v})} />}
</main>
{selected && (
<ProductDetail
product={selected}
data={data}
onClose={() => setSelected(null)}
onConsume={openConsume}
onMarkGone={openGone}
onAudit={openAudit}
onEdit={() => {}}
/>
)}
{modal === "add" && <AddProductFlow data={data} onClose={() => setModal(null)} onSave={handleSave} />}
{modal === "consume" && <ConsumeFlow data={data} onClose={() => setModal(null)} product={modalProduct} />}
{modal === "gone" && <MarkGoneFlow data={data} onClose={() => setModal(null)} product={modalProduct} />}
{modal === "audit" && <AuditFlow data={data} onClose={() => setModal(null)} product={modalProduct} />}
{tweaksOpen && (
<TweaksPanel onClose={() => setTweaksOpen(false)} title="Tweaks">
<TweakSection title="Appearance">
<TweakRadio label="Theme" value={tweaks.theme} options={[["light","Light"],["dark","Dark"]]} onChange={v => setTweaks({...tweaks, theme: v})} />
<TweakRadio label="Dashboard layout" value={tweaks.dashboard} options={[["editorial","Editorial"],["dense","Data-dense"],["minimal","Minimal"]]} onChange={v => setTweaks({...tweaks, dashboard: v})} />
</TweakSection>
<TweakSection title="Copy">
<TweakRadio label="Tone" value={tweaks.tone} options={[["botanical","Botanical"],["neutral","Neutral"],["discreet","Discreet"]]} onChange={v => setTweaks({...tweaks, tone: v})} />
</TweakSection>
</TweaksPanel>
)}
</div>
);
}
// Switches between 3 dashboard variants
const DashboardSwitch = ({variant, ...props}) => {
if (variant === "dense") return <DashboardDense {...props} />;
if (variant === "minimal") return <DashboardMinimal {...props} />;
return <Dashboard {...props} />;
};
// Variation 2: data-dense
const DashboardDense = ({data, stats, onNav, onSelectProduct}) => {
const series = stats.series90.map(s => ({date: s.date, value: s.grams}));
return (
<div style={{padding: "20px 28px 60px"}}>
<div style={{display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18, paddingBottom: 14, borderBottom: "1px solid var(--line)"}}>
<div style={{display: "flex", alignItems: "baseline", gap: 16}}>
<h1 className="mono" style={{fontSize: 13, margin: 0, color: "var(--ink-2)", textTransform: "uppercase", letterSpacing: "0.08em"}}>Dashboard / 2026-04-25</h1>
<span style={{fontSize: 11, color: "var(--ink-3)"}}>· {stats.activeCount} active · {stats.consumedCount} archived</span>
</div>
<div style={{display: "flex", gap: 6}}>
<Btn variant="secondary" icon="plus" onClick={() => onNav("add")}>Product</Btn>
<Btn variant="primary" icon="check" onClick={() => onNav("consume")}>Finish</Btn>
</div>
</div>
<div style={{display: "grid", gridTemplateColumns: "repeat(8, 1fr)", gap: 1, background: "var(--line)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", overflow: "hidden", marginBottom: 14}}>
{[
["DAILY g", stats.dailyAvg.toFixed(2)],
["WEEKLY g", stats.weeklyAvg.toFixed(1)],
["MONTHLY g", stats.monthlyAvg.toFixed(1)],
["AVG $/g", fmt.money(stats.avgPerGram)],
["30D SPEND", fmt.moneyShort(stats.spend30)],
["INV VALUE", fmt.moneyShort(stats.inventoryValue)],
["7D THC mg", stats.thcLast7],
["DAYS SUPPLY", Math.round(stats.daysOfSupply)]
].map(([l, v]) => (
<div key={l} style={{padding: "12px 14px", background: "var(--surface)"}}>
<div className="mono" style={{fontSize: 10, color: "var(--ink-3)", letterSpacing: "0.04em"}}>{l}</div>
<div className="mono" style={{fontSize: 20, marginTop: 4, fontWeight: 500}}>{v}</div>
</div>
))}
</div>
<div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14}}>
<Card padded={false}>
<div style={{padding: "12px 16px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between"}}>
<span className="mono" style={{fontSize: 11, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.08em"}}>g / day · 90d</span>
<span className="mono" style={{fontSize: 11, color: "var(--ink-2)"}}>{series.reduce((s,e)=>s+e.value,0).toFixed(1)} g total</span>
</div>
<div style={{padding: 14}}>
<BarChart data={series} height={120} color="var(--sage)" />
</div>
</Card>
<Card padded={false}>
<div style={{padding: "12px 16px", borderBottom: "1px solid var(--line)"}}>
<span className="mono" style={{fontSize: 11, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.08em"}}>recent purchases</span>
</div>
<div>
{[...data.products].sort((a,b)=>new Date(b.purchaseDate)-new Date(a.purchaseDate)).slice(0, 5).map(p => (
<div key={p.id} onClick={() => onSelectProduct(p)} style={{padding: "10px 16px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center", cursor: "pointer", fontSize: 12}}>
<div>
<div style={{fontWeight: 500, fontSize: 13}}>{p.name}</div>
<div style={{fontSize: 11, color: "var(--ink-3)"}}>{window.DATA_HELPERS.brandName(data, p.brandId)} · {window.DATA_HELPERS.shopName(data, p.shopId)}</div>
</div>
<div className="mono" style={{textAlign: "right"}}>
<div>{fmt.money(p.price)}</div>
<div style={{fontSize: 10, color: "var(--ink-3)"}}>{fmt.dateShort(p.purchaseDate)}</div>
</div>
</div>
))}
</div>
</Card>
</div>
<Card padded={false}>
<div style={{padding: "12px 16px", borderBottom: "1px solid var(--line)"}}>
<span className="mono" style={{fontSize: 11, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.08em"}}>active inventory · {stats.activeCount} rows</span>
</div>
<div style={{display: "grid", gridTemplateColumns: "2fr 1fr 0.6fr 0.6fr 0.6fr 0.8fr", padding: "8px 16px", borderBottom: "1px solid var(--line)", fontSize: 10, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.08em", fontFamily: "var(--mono)"}}>
<div>NAME / SKU</div><div>BRAND</div><div style={{textAlign: "right"}}>THC%</div><div style={{textAlign: "right"}}>$</div><div style={{textAlign: "right"}}>REM g</div><div>BIN</div>
</div>
{data.products.filter(p=>p.status==="active").slice(0, 8).map(p => {
const bin = data.bins.find(b => b.id === p.binId);
return (
<div key={p.id} onClick={() => onSelectProduct(p)} className="inv-row" style={{display: "grid", gridTemplateColumns: "2fr 1fr 0.6fr 0.6fr 0.6fr 0.8fr", padding: "8px 16px", borderBottom: "1px solid var(--line)", fontSize: 12, cursor: "pointer", alignItems: "center"}}>
<div>
<div style={{fontWeight: 500}}>{p.name}</div>
<div className="mono" style={{fontSize: 10, color: "var(--ink-3)"}}>{p.sku}</div>
</div>
<div style={{color: "var(--ink-2)"}}>{window.DATA_HELPERS.brandName(data, p.brandId)}</div>
<div className="mono" style={{textAlign: "right"}}>{p.thc.toFixed(1)}</div>
<div className="mono" style={{textAlign: "right"}}>{fmt.money(p.price)}</div>
<div className="mono" style={{textAlign: "right"}}>{window.remainingShort(p)}</div>
<div style={{fontSize: 11, color: "var(--ink-3)"}}>{bin?.name || "—"}</div>
</div>
);
})}
</Card>
</div>
);
};
// Variation 3: minimal / editorial-quiet
const DashboardMinimal = ({data, stats, onNav, onSelectProduct}) => {
return (
<div style={{padding: "80px 60px", maxWidth: 900, margin: "0 auto"}}>
<div style={{textAlign: "center", marginBottom: 80}}>
<div className="smallcaps" style={{color: "var(--ink-3)", marginBottom: 20}}>Saturday · April 25, 2026</div>
<div className="serif" style={{fontSize: 96, fontWeight: 400, letterSpacing: "-0.03em", lineHeight: 1, fontStyle: "italic"}}>
{stats.dailyAvg.toFixed(2)}<span style={{fontSize: 36, fontStyle: "normal", color: "var(--ink-3)", marginLeft: 8}}>g/day</span>
</div>
<div style={{marginTop: 20, fontSize: 14, color: "var(--ink-2)", maxWidth: 520, margin: "20px auto 0"}}>
{stats.activeCount} items in your cabinet, valued around {fmt.moneyShort(stats.inventoryValue)}, with roughly {Math.round(stats.daysOfSupply)} days of flower at this pace.
</div>
<div style={{marginTop: 8, fontSize: 13, color: "var(--ink-3)", maxWidth: 520, margin: "8px auto 0"}}>
{stats.consumedCount} items archived · avg lifespan {Math.round(stats.avgLifespan)} days.
</div>
</div>
<div style={{display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 0, marginBottom: 80}}>
{[
["Avg $ per gram", fmt.money(stats.avgPerGram)],
["30-day spend", fmt.moneyShort(stats.spend30)],
["7-day THC", `${stats.thcLast7} mg`]
].map(([l,v], i) => (
<div key={l} style={{textAlign: "center", padding: "0 20px", borderRight: i < 2 ? "1px solid var(--line)" : "none"}}>
<div className="smallcaps" style={{color: "var(--ink-3)", marginBottom: 10}}>{l}</div>
<div className="serif" style={{fontSize: 36, fontWeight: 500}}>{v}</div>
</div>
))}
</div>
<div style={{borderTop: "1px solid var(--line)", paddingTop: 40}}>
<div style={{display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 18}}>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>Recent additions</div>
<button onClick={() => onNav("inventory")} style={{background: "none", border: "none", fontSize: 12, color: "var(--ink-2)", cursor: "pointer", textDecoration: "underline"}}>See all </button>
</div>
{[...data.products].filter(p=>p.status==="active").sort((a,b)=>new Date(b.purchaseDate)-new Date(a.purchaseDate)).slice(0, 5).map(p => (
<div key={p.id} onClick={() => onSelectProduct(p)} style={{display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "20px 0", borderBottom: "1px solid var(--line)", cursor: "pointer"}}>
<div>
<div className="serif" style={{fontSize: 24, fontWeight: 500}}>{p.name}</div>
<div style={{fontSize: 12, color: "var(--ink-3)", marginTop: 2}}>{window.DATA_HELPERS.brandName(data, p.brandId)} · {window.DATA_HELPERS.shopName(data, p.shopId)} · {fmt.dateShort(p.purchaseDate)}</div>
</div>
<div className="mono" style={{fontSize: 13, color: "var(--ink-2)"}}>{window.remainingShort(p)} · {fmt.money(p.price)}</div>
</div>
))}
</div>
<div style={{marginTop: 60, display: "flex", gap: 12, justifyContent: "center"}}>
<Btn variant="secondary" icon="plus" onClick={() => onNav("add")}>Add product</Btn>
<Btn variant="primary" icon="check" onClick={() => onNav("consume")}>Mark finished</Btn>
</div>
</div>
);
};
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

+378
View File
@@ -0,0 +1,378 @@
// Sample inventory data
window.SAMPLE_DATA = (function() {
const TODAY = "2026-04-25";
const daysAgo = (n) => {
const d = new Date(TODAY); d.setDate(d.getDate() - n);
return d.toISOString().slice(0, 10);
};
// Shops are objects now
const SHOPS = [
{ id: "shp-01", name: "Greenleaf Co-op", location: "Capitol Hill" },
{ id: "shp-02", name: "Verdant Apothecary", location: "Ballard" },
{ id: "shp-03", name: "The Field House", location: "Fremont" },
{ id: "shp-04", name: "Northstar Dispensary",location: "Roosevelt" },
{ id: "shp-05", name: "Wildwood Provisions", location: "West Seattle" }
];
// Brands are objects too
const BRANDS = [
{ id: "brd-01", name: "Foxglove Farms" },
{ id: "brd-02", name: "Slow Burn" },
{ id: "brd-03", name: "Heirloom Botanicals" },
{ id: "brd-04", name: "Terra Vera" },
{ id: "brd-05", name: "North Field" },
{ id: "brd-06", name: "Cinder & Sage" },
{ id: "brd-07", name: "Old Forest" },
{ id: "brd-08", name: "Marigold Ext." }
];
// Type config — kind + audit cadence
// bulk: track weight (g) — audit re-weighs (or estimates for concentrate)
// discrete: track count (units) — audit confirms presence by SKU/asset
const TYPES = [
{ id: "Flower", kind: "bulk", auditMode: "weigh", cadenceDays: 14, unit: "g", weighable: true },
{ id: "Concentrate", kind: "bulk", auditMode: "estimate", cadenceDays: 21, unit: "g", weighable: true },
{ id: "Tincture", kind: "bulk", auditMode: "estimate", cadenceDays: 30, unit: "ml", weighable: false },
{ id: "Pre-roll", kind: "discrete", auditMode: "presence", cadenceDays: 30, unit: "ct", weighable: false },
{ id: "Edible", kind: "discrete", auditMode: "presence", cadenceDays: 60, unit: "ct", weighable: false },
{ id: "Vaporizer", kind: "discrete", auditMode: "presence", cadenceDays: 30, unit: "ct", weighable: false }
];
const BINS = [
{ id: "bin-01", name: "Top Drawer", location: "Bedroom", capacity: 14 },
{ id: "bin-02", name: "Apothecary Box", location: "Office shelf", capacity: 10 },
{ id: "bin-03", name: "The Safe", location: "Closet", capacity: 8 },
{ id: "bin-04", name: "Travel Tin", location: "Backpack", capacity: 4 },
{ id: "bin-05", name: "Cold Storage", location: "Fridge — back", capacity: 6 }
];
let n = 1;
const mk = (o) => {
const id = "prd-" + String(n).padStart(4, "0");
n++;
const sku = o.sku || ("SKU-" + Math.random().toString(36).slice(2, 8).toUpperCase());
return {
id,
sku,
assetTag: null,
name: "",
brandId: null,
shopId: null,
type: "Flower",
kind: "bulk", // "bulk" or "discrete"
// Bulk fields
weight: 0, // total at purchase (g/ml)
lastAuditWeight: null, // last measured weight
// Discrete fields
countOriginal: 0, // units at purchase
countLastAudit: null, // units confirmed at last audit
unitWeight: 0, // bulk-equivalent grams per unit (for grams stats)
// Pricing
price: 0,
thc: 0,
cbd: 0,
totalCannabinoids: 0,
purchaseDate: TODAY,
binId: "bin-01",
// Lifecycle
status: "active", // "active" | "consumed" | "gone"
consumedDate: null,
goneDate: null,
rating: null,
notes: null,
// Audits — newest last
audits: [],
...o
};
};
const products = [];
// ─── BULK: FLOWER ────────────────────────────────────────────────
products.push(mk({
name: "Garden Ghost", brandId: "brd-01", shopId: "shp-01",
type: "Flower", kind: "bulk",
weight: 3.5, lastAuditWeight: 2.4,
price: 48, thc: 24.6, cbd: 0.3, totalCannabinoids: 28.4,
purchaseDate: daysAgo(17), binId: "bin-01",
audits: [
{ date: daysAgo(10), mode: "weigh", value: 3.0, prev: 3.5 },
{ date: daysAgo(3), mode: "weigh", value: 2.4, prev: 3.0 }
]
}));
products.push(mk({
name: "Honeydew Pine", brandId: "brd-02", shopId: "shp-02",
type: "Flower", kind: "bulk",
weight: 7, lastAuditWeight: 5.6,
price: 85, thc: 21.0, cbd: 0.5, totalCannabinoids: 25.1,
purchaseDate: daysAgo(11), binId: "bin-01",
audits: [
{ date: daysAgo(2), mode: "weigh", value: 5.6, prev: 7.0 }
]
}));
products.push(mk({
name: "Late Pear", brandId: "brd-01", shopId: "shp-01",
type: "Flower", kind: "bulk",
weight: 3.5, lastAuditWeight: 3.5,
price: 50, thc: 25.2, cbd: 0.2, totalCannabinoids: 28.9,
purchaseDate: daysAgo(6), binId: "bin-05"
// recently bought, no audit yet
}));
products.push(mk({
name: "Copper Fennel", brandId: "brd-02", shopId: "shp-02",
type: "Flower", kind: "bulk",
weight: 3.5, lastAuditWeight: 0.5,
price: 42, thc: 20.4, cbd: 0.5, totalCannabinoids: 24.0,
purchaseDate: daysAgo(26), binId: "bin-01",
audits: [
{ date: daysAgo(12), mode: "weigh", value: 1.6, prev: 3.5 },
{ date: daysAgo(2), mode: "weigh", value: 0.5, prev: 1.6 }
]
}));
// Overdue audit — Flower past 14d cadence
products.push(mk({
name: "Slate Cherry", brandId: "brd-06", shopId: "shp-04",
type: "Flower", kind: "bulk",
weight: 3.5, lastAuditWeight: 3.5,
price: 46, thc: 22.8, cbd: 0.4, totalCannabinoids: 26.5,
purchaseDate: daysAgo(22), binId: "bin-01"
// No audit since purchase, 22d > 14d cadence → overdue
}));
// ─── BULK: CONCENTRATE ──────────────────────────────────────────
products.push(mk({
name: "Indigo Cellar Live Rosin", brandId: "brd-03", shopId: "shp-03",
type: "Concentrate", kind: "bulk",
weight: 1, lastAuditWeight: 0.6,
price: 65, thc: 78.4, cbd: 0.2, totalCannabinoids: 84.0,
purchaseDate: daysAgo(28), binId: "bin-03",
assetTag: "AT-0042",
audits: [
{ date: daysAgo(15), mode: "estimate", value: 0.8, prev: 1.0 },
{ date: daysAgo(2), mode: "estimate", value: 0.6, prev: 0.8 }
]
}));
products.push(mk({
name: "Slate Apricot Hash", brandId: "brd-04", shopId: "shp-04",
type: "Concentrate", kind: "bulk",
weight: 2, lastAuditWeight: 1.4,
price: 80, thc: 62.0, cbd: 1.1, totalCannabinoids: 70.5,
purchaseDate: daysAgo(23), binId: "bin-03",
audits: [
{ date: daysAgo(8), mode: "estimate", value: 1.4, prev: 2.0 }
]
}));
products.push(mk({
name: "Birchwater Live Resin", brandId: "brd-03", shopId: "shp-04",
type: "Concentrate", kind: "bulk",
weight: 1, lastAuditWeight: 1.0,
price: 70, thc: 76.0, cbd: 0.3, totalCannabinoids: 82.1,
purchaseDate: daysAgo(4), binId: "bin-03"
}));
// ─── BULK: TINCTURE ─────────────────────────────────────────────
products.push(mk({
name: "Nightjar Tincture 30ml", brandId: "brd-08", shopId: "shp-02",
type: "Tincture", kind: "bulk",
weight: 30, lastAuditWeight: 22,
price: 60, thc: 0.5, cbd: 18.0, totalCannabinoids: 19.2,
purchaseDate: daysAgo(62), binId: "bin-02",
audits: [
{ date: daysAgo(31), mode: "estimate", value: 26, prev: 30 },
{ date: daysAgo(5), mode: "estimate", value: 22, prev: 26 }
]
}));
// ─── DISCRETE: PRE-ROLLS ───────────────────────────────────────
products.push(mk({
name: "Mossback Pre-rolls", brandId: "brd-07", shopId: "shp-03",
type: "Pre-roll", kind: "discrete",
countOriginal: 5, countLastAudit: 3, unitWeight: 0.7,
price: 38, thc: 19.8, cbd: 0.4, totalCannabinoids: 23.0,
purchaseDate: daysAgo(9), binId: "bin-04",
audits: [
{ date: daysAgo(2), mode: "presence", value: 3, prev: 5, confirmedBy: "SKU" }
]
}));
products.push(mk({
name: "Mossback Pre-rolls", brandId: "brd-07", shopId: "shp-03",
type: "Pre-roll", kind: "discrete",
countOriginal: 5, countLastAudit: 5, unitWeight: 0.7,
price: 38, thc: 19.8, cbd: 0.4, totalCannabinoids: 23.0,
purchaseDate: daysAgo(3), binId: "bin-04"
}));
products.push(mk({
name: "Quiet Meadow Singles", brandId: "brd-05", shopId: "shp-05",
type: "Pre-roll", kind: "discrete",
countOriginal: 3, countLastAudit: 1, unitWeight: 1.0,
price: 24, thc: 22.0, cbd: 0.3, totalCannabinoids: 25.0,
purchaseDate: daysAgo(34), binId: "bin-04",
audits: [
{ date: daysAgo(20), mode: "presence", value: 2, prev: 3, confirmedBy: "SKU" },
{ date: daysAgo(2), mode: "presence", value: 1, prev: 2, confirmedBy: "SKU" }
]
}));
// ─── DISCRETE: EDIBLES ─────────────────────────────────────────
products.push(mk({
name: "Ember Lily Gummies (10 ct)", brandId: "brd-06", shopId: "shp-01",
type: "Edible", kind: "discrete",
countOriginal: 10, countLastAudit: 6, unitWeight: 0,
price: 22, thc: 5.0, cbd: 1.0, totalCannabinoids: 6.4,
purchaseDate: daysAgo(20), binId: "bin-02",
audits: [
{ date: daysAgo(5), mode: "presence", value: 6, prev: 10, confirmedBy: "SKU" }
]
}));
products.push(mk({
name: "Marigold Mints (20 ct)", brandId: "brd-08", shopId: "shp-02",
type: "Edible", kind: "discrete",
countOriginal: 20, countLastAudit: 14, unitWeight: 0,
price: 28, thc: 2.5, cbd: 0, totalCannabinoids: 3.0,
purchaseDate: daysAgo(48), binId: "bin-02",
audits: [
{ date: daysAgo(7), mode: "presence", value: 14, prev: 20, confirmedBy: "SKU" }
]
}));
// ─── DISCRETE: VAPORIZER ───────────────────────────────────────
products.push(mk({
name: "Quiet Meadow Disposable", brandId: "brd-05", shopId: "shp-05",
type: "Vaporizer", kind: "discrete",
countOriginal: 1, countLastAudit: 1, unitWeight: 1.0,
price: 55, thc: 84.0, cbd: 0.1, totalCannabinoids: 88.2,
purchaseDate: daysAgo(14), binId: "bin-04",
audits: [
{ date: daysAgo(1), mode: "presence", value: 1, prev: 1, confirmedBy: "SKU" }
]
}));
// ─── CONSUMED (used up — counts as consumption) ─────────────────
products.push(mk({
name: "Oolong 19", brandId: "brd-04", shopId: "shp-01",
type: "Flower", kind: "bulk",
weight: 3.5, lastAuditWeight: 0,
price: 46, thc: 23.0, cbd: 0.4, totalCannabinoids: 27.0,
purchaseDate: daysAgo(66), binId: null,
status: "consumed", consumedDate: daysAgo(31),
rating: 4, notes: "Smooth, citrusy. Daytime favorite."
}));
products.push(mk({
name: "Stonefruit OG", brandId: "brd-07", shopId: "shp-03",
type: "Flower", kind: "bulk",
weight: 7, lastAuditWeight: 0,
price: 78, thc: 22.5, cbd: 0.6, totalCannabinoids: 26.4,
purchaseDate: daysAgo(103), binId: null,
status: "consumed", consumedDate: daysAgo(56),
rating: 5, notes: "Best of the season. Rebuy."
}));
products.push(mk({
name: "Lavender Coast", brandId: "brd-01", shopId: "shp-05",
type: "Flower", kind: "bulk",
weight: 3.5, lastAuditWeight: 0,
price: 44, thc: 19.0, cbd: 0.8, totalCannabinoids: 22.2,
purchaseDate: daysAgo(80), binId: null,
status: "consumed", consumedDate: daysAgo(47),
rating: 3, notes: "Mellow but underwhelming."
}));
products.push(mk({
name: "Violet Tea", brandId: "brd-06", shopId: "shp-04",
type: "Flower", kind: "bulk",
weight: 3.5, lastAuditWeight: 0,
price: 50, thc: 24.1, cbd: 0.3, totalCannabinoids: 28.0,
purchaseDate: daysAgo(55), binId: null,
status: "consumed", consumedDate: daysAgo(21),
rating: 4, notes: "Floral nose, nice evenings."
}));
// ─── GONE (lost / damaged — counts as $ spent, NOT consumption) ─
products.push(mk({
name: "Quiet Meadow Singles", brandId: "brd-05", shopId: "shp-05",
type: "Pre-roll", kind: "discrete",
countOriginal: 3, countLastAudit: 0, unitWeight: 1.0,
price: 24, thc: 22.0, cbd: 0.3, totalCannabinoids: 25.0,
purchaseDate: daysAgo(72), binId: null,
status: "gone", goneDate: daysAgo(40),
notes: "Pack went through the wash. Lesson learned.",
audits: [
{ date: daysAgo(40), mode: "presence", value: 0, prev: 3, confirmedBy: "lost" }
]
}));
products.push(mk({
name: "Ember Lily Gummies (10 ct)", brandId: "brd-06", shopId: "shp-01",
type: "Edible", kind: "discrete",
countOriginal: 10, countLastAudit: 4, unitWeight: 0,
price: 22, thc: 5.0, cbd: 1.0, totalCannabinoids: 6.4,
purchaseDate: daysAgo(95), binId: null,
status: "gone", goneDate: daysAgo(15),
notes: "Expired. Tossed the rest."
}));
return {
products,
bins: BINS,
shops: SHOPS,
brands: BRANDS,
types: TYPES,
today: TODAY
};
})();
// Helpers — exported so screens can use consistent logic
window.DATA_HELPERS = {
shopName: (data, id) => data.shops.find(s => s.id === id)?.name || "—",
brandName: (data, id) => data.brands.find(b => b.id === id)?.name || "—",
typeConfig: (data, id) => data.types.find(t => t.id === id) || data.types[0],
// Days since a given ISO date string
daysSince: (iso, today = "2026-04-25") => {
if (!iso) return Infinity;
return Math.floor((new Date(today) - new Date(iso)) / 86400000);
},
// Last audit record (newest)
lastAudit: (p) => p.audits && p.audits.length ? p.audits[p.audits.length - 1] : null,
// Days since last audit (or since purchase if none)
daysSinceCheck: (p, today = "2026-04-25") => {
const last = p.audits && p.audits.length ? p.audits[p.audits.length - 1].date : p.purchaseDate;
return Math.floor((new Date(today) - new Date(last)) / 86400000);
},
// Is audit overdue based on per-type cadence
auditOverdue: (data, p, today = "2026-04-25") => {
if (p.status !== "active") return false;
const cfg = data.types.find(t => t.id === p.type);
if (!cfg) return false;
return window.DATA_HELPERS.daysSinceCheck(p, today) >= cfg.cadenceDays;
},
// Estimated remaining (bulk: decay from last audit; discrete: countLastAudit)
estimatedRemaining: (p, today = "2026-04-25") => {
if (p.status !== "active") return 0;
if (p.kind === "discrete") {
return p.countLastAudit != null ? p.countLastAudit : p.countOriginal;
}
// Bulk: linear decay between last audit and average lifespan estimate
const last = window.DATA_HELPERS.lastAudit(p);
const baseDate = last ? last.date : p.purchaseDate;
const baseValue = last ? last.value : p.weight;
const daysSinceBase = Math.max(0, Math.floor((new Date(today) - new Date(baseDate)) / 86400000));
// Decay rate: assume original weight is consumed over (purchase → expected lifespan ~ 35d for flower, 40 concentrate, 90 tincture)
const expectedLifespan = p.type === "Flower" ? 35 : p.type === "Concentrate" ? 40 : 90;
const dailyBurn = p.weight / expectedLifespan;
const est = Math.max(0, baseValue - dailyBurn * daysSinceBase);
return est;
},
// Original-percent remaining (for low-stock on bulk)
pctRemaining: (p, today = "2026-04-25") => {
if (p.kind === "discrete") {
const cur = p.countLastAudit != null ? p.countLastAudit : p.countOriginal;
return p.countOriginal > 0 ? cur / p.countOriginal : 0;
}
const est = window.DATA_HELPERS.estimatedRemaining(p, today);
return p.weight > 0 ? est / p.weight : 0;
}
};
+619
View File
@@ -0,0 +1,619 @@
/**
* <deck-stage> — reusable web component for HTML decks.
*
* Handles:
* (a) speaker notes — reads <script type="application/json" id="speaker-notes">
* and posts {slideIndexChanged: N} to the parent window on nav.
* (b) keyboard navigation — ←/→, PgUp/PgDn, Space, Home/End, number keys.
* (c) press R to reset to slide 0 (with a tasteful keyboard hint).
* (d) bottom-center overlay showing slide count + hints, fades out on idle.
* (e) auto-scaling — inner canvas is a fixed design size (default 1920×1080)
* scaled with `transform: scale()` to fit the viewport, letterboxed.
* Set the `noscale` attribute to render at authored size (1:1) — the
* PPTX exporter sets this so its DOM capture sees unscaled geometry.
* (f) print — `@media print` lays every slide out as its own page at the
* design size, so the browser's Print → Save as PDF produces a clean
* one-page-per-slide PDF with no extra setup.
*
* Slides are HIDDEN, not unmounted. Non-active slides stay in the DOM with
* `visibility: hidden` + `opacity: 0`, so their state (videos, iframes,
* form inputs, React trees) is preserved across navigation.
*
* Lifecycle event — the component dispatches a `slidechange` CustomEvent on
* itself whenever the active slide changes (including the initial mount).
* The event bubbles and composes out of shadow DOM, so you can listen on
* the <deck-stage> element or on document:
*
* document.querySelector('deck-stage').addEventListener('slidechange', (e) => {
* e.detail.index // new 0-based index
* e.detail.previousIndex // previous index, or -1 on init
* e.detail.total // total slide count
* e.detail.slide // the new active slide element
* e.detail.previousSlide // the prior slide element, or null on init
* e.detail.reason // 'init' | 'keyboard' | 'click' | 'tap' | 'api'
* });
*
* Persistence: none at the deck level. The host app keeps the current slide
* in its own URL (?slide=) and re-delivers it via location.hash on load, so a
* bare load with no hash always starts at slide 1.
*
* Usage:
* <deck-stage width="1920" height="1080">
* <section data-label="Title">...</section>
* <section data-label="Agenda">...</section>
* </deck-stage>
*
* Slides are the direct element children of <deck-stage>. Each slide is
* automatically tagged with:
* - data-screen-label="NN Label" (1-indexed, for comment flow)
* - data-om-validate="no_overflowing_text,no_overlapping_text,slide_sized_text"
*/
(() => {
const DESIGN_W_DEFAULT = 1920;
const DESIGN_H_DEFAULT = 1080;
const OVERLAY_HIDE_MS = 1800;
const VALIDATE_ATTR = 'no_overflowing_text,no_overlapping_text,slide_sized_text';
const pad2 = (n) => String(n).padStart(2, '0');
const stylesheet = `
:host {
position: fixed;
inset: 0;
display: block;
background: #000;
color: #fff;
font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Arial, sans-serif;
overflow: hidden;
}
.stage {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
}
.canvas {
position: relative;
transform-origin: center center;
flex-shrink: 0;
background: #fff;
will-change: transform;
}
/* Slides live in light DOM (via <slot>) so authored CSS still applies.
We absolutely position each slotted child to stack them. */
::slotted(*) {
position: absolute !important;
inset: 0 !important;
width: 100% !important;
height: 100% !important;
box-sizing: border-box !important;
overflow: hidden;
opacity: 0;
pointer-events: none;
visibility: hidden;
}
::slotted([data-deck-active]) {
opacity: 1;
pointer-events: auto;
visibility: visible;
}
/* Tap zones for mobile — back/forward thirds like Stories.
Transparent, no visible UI, don't block the overlay. */
.tapzones {
position: fixed;
inset: 0;
display: flex;
z-index: 2147482000;
pointer-events: none;
}
.tapzone {
flex: 1;
pointer-events: auto;
-webkit-tap-highlight-color: transparent;
}
/* Only activate tap zones on coarse pointers (touch devices). */
@media (hover: hover) and (pointer: fine) {
.tapzones { display: none; }
}
.overlay {
position: fixed;
left: 50%;
bottom: 22px;
transform: translate(-50%, 6px) scale(0.92);
filter: blur(6px);
display: flex;
align-items: center;
gap: 4px;
padding: 4px;
background: #000;
color: #fff;
border-radius: 999px;
font-size: 12px;
font-feature-settings: "tnum" 1;
letter-spacing: 0.01em;
opacity: 0;
pointer-events: none;
transition: opacity 260ms ease, transform 260ms cubic-bezier(.2,.8,.2,1), filter 260ms ease;
transform-origin: center bottom;
z-index: 2147483000;
user-select: none;
}
.overlay[data-visible] {
opacity: 1;
pointer-events: auto;
transform: translate(-50%, 0) scale(1);
filter: blur(0);
}
.btn {
appearance: none;
-webkit-appearance: none;
background: transparent;
border: 0;
margin: 0;
padding: 0;
color: inherit;
font: inherit;
cursor: default;
display: inline-flex;
align-items: center;
justify-content: center;
height: 28px;
min-width: 28px;
border-radius: 999px;
color: rgba(255,255,255,0.72);
transition: background 140ms ease, color 140ms ease;
-webkit-tap-highlight-color: transparent;
}
.btn:hover { background: rgba(255,255,255,0.12); color: #fff; }
.btn:active { background: rgba(255,255,255,0.18); }
.btn:focus { outline: none; }
.btn:focus-visible { outline: none; }
.btn::-moz-focus-inner { border: 0; }
.btn svg { width: 14px; height: 14px; display: block; }
.btn.reset {
font-size: 11px;
font-weight: 500;
letter-spacing: 0.02em;
padding: 0 10px 0 12px;
gap: 6px;
color: rgba(255,255,255,0.72);
}
.btn.reset .kbd {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 16px;
height: 16px;
padding: 0 4px;
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1;
color: rgba(255,255,255,0.88);
background: rgba(255,255,255,0.12);
border-radius: 4px;
}
.count {
font-variant-numeric: tabular-nums;
color: #fff;
font-weight: 500;
padding: 0 8px;
min-width: 42px;
text-align: center;
font-size: 12px;
}
.count .sep { color: rgba(255,255,255,0.45); margin: 0 3px; font-weight: 400; }
.count .total { color: rgba(255,255,255,0.55); }
.divider {
width: 1px;
height: 14px;
background: rgba(255,255,255,0.18);
margin: 0 2px;
}
/* ── Print: one page per slide, no chrome ────────────────────────────
The screen layout stacks every slide at inset:0 inside a scaled
canvas; for print we want them in document flow at the authored
design size so the browser paginates one slide per sheet. The
@page size is set from the width/height attributes via the inline
<style id="deck-stage-print-page"> that connectedCallback injects
into <head> (the @page at-rule has no effect inside shadow DOM). */
@media print {
:host {
position: static;
inset: auto;
background: none;
overflow: visible;
color: inherit;
}
.stage { position: static; display: block; }
.canvas {
transform: none !important;
width: auto !important;
height: auto !important;
background: none;
will-change: auto;
}
::slotted(*) {
position: relative !important;
inset: auto !important;
width: var(--deck-design-w) !important;
height: var(--deck-design-h) !important;
box-sizing: border-box !important;
opacity: 1 !important;
visibility: visible !important;
pointer-events: auto;
break-after: page;
page-break-after: always;
break-inside: avoid;
overflow: hidden;
}
::slotted(*:last-child) {
break-after: auto;
page-break-after: auto;
}
.overlay, .tapzones { display: none !important; }
}
`;
class DeckStage extends HTMLElement {
static get observedAttributes() { return ['width', 'height', 'noscale']; }
constructor() {
super();
this._root = this.attachShadow({ mode: 'open' });
this._index = 0;
this._slides = [];
this._notes = [];
this._hideTimer = null;
this._mouseIdleTimer = null;
this._onKey = this._onKey.bind(this);
this._onResize = this._onResize.bind(this);
this._onSlotChange = this._onSlotChange.bind(this);
this._onMouseMove = this._onMouseMove.bind(this);
this._onTapBack = this._onTapBack.bind(this);
this._onTapForward = this._onTapForward.bind(this);
}
get designWidth() {
return parseInt(this.getAttribute('width'), 10) || DESIGN_W_DEFAULT;
}
get designHeight() {
return parseInt(this.getAttribute('height'), 10) || DESIGN_H_DEFAULT;
}
connectedCallback() {
this._render();
this._loadNotes();
this._syncPrintPageRule();
window.addEventListener('keydown', this._onKey);
window.addEventListener('resize', this._onResize);
window.addEventListener('mousemove', this._onMouseMove, { passive: true });
// Initial collection + layout happens via slotchange, which fires on mount.
}
disconnectedCallback() {
window.removeEventListener('keydown', this._onKey);
window.removeEventListener('resize', this._onResize);
window.removeEventListener('mousemove', this._onMouseMove);
if (this._hideTimer) clearTimeout(this._hideTimer);
if (this._mouseIdleTimer) clearTimeout(this._mouseIdleTimer);
}
attributeChangedCallback() {
if (this._canvas) {
this._canvas.style.width = this.designWidth + 'px';
this._canvas.style.height = this.designHeight + 'px';
this._canvas.style.setProperty('--deck-design-w', this.designWidth + 'px');
this._canvas.style.setProperty('--deck-design-h', this.designHeight + 'px');
this._fit();
this._syncPrintPageRule();
}
}
_render() {
const style = document.createElement('style');
style.textContent = stylesheet;
const stage = document.createElement('div');
stage.className = 'stage';
const canvas = document.createElement('div');
canvas.className = 'canvas';
canvas.style.width = this.designWidth + 'px';
canvas.style.height = this.designHeight + 'px';
canvas.style.setProperty('--deck-design-w', this.designWidth + 'px');
canvas.style.setProperty('--deck-design-h', this.designHeight + 'px');
const slot = document.createElement('slot');
slot.addEventListener('slotchange', this._onSlotChange);
canvas.appendChild(slot);
stage.appendChild(canvas);
// Tap zones (mobile): left third = back, right third = forward.
const tapzones = document.createElement('div');
tapzones.className = 'tapzones export-hidden';
tapzones.setAttribute('aria-hidden', 'true');
tapzones.setAttribute('data-noncommentable', '');
const tzBack = document.createElement('div');
tzBack.className = 'tapzone tapzone--back';
const tzMid = document.createElement('div');
tzMid.className = 'tapzone tapzone--mid';
tzMid.style.pointerEvents = 'none';
const tzFwd = document.createElement('div');
tzFwd.className = 'tapzone tapzone--fwd';
tzBack.addEventListener('click', this._onTapBack);
tzFwd.addEventListener('click', this._onTapForward);
tapzones.append(tzBack, tzMid, tzFwd);
// Overlay: compact, solid black, with clickable controls.
const overlay = document.createElement('div');
overlay.className = 'overlay export-hidden';
overlay.setAttribute('role', 'toolbar');
overlay.setAttribute('aria-label', 'Deck controls');
overlay.setAttribute('data-noncommentable', '');
overlay.innerHTML = `
<button class="btn prev" type="button" aria-label="Previous slide" title="Previous (←)">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 3L5 8l5 5"/></svg>
</button>
<span class="count" aria-live="polite"><span class="current">1</span><span class="sep">/</span><span class="total">1</span></span>
<button class="btn next" type="button" aria-label="Next slide" title="Next (→)">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 3l5 5-5 5"/></svg>
</button>
<span class="divider"></span>
<button class="btn reset" type="button" aria-label="Reset to first slide" title="Reset (R)">Reset<span class="kbd">R</span></button>
`;
overlay.querySelector('.prev').addEventListener('click', () => this._go(this._index - 1, 'click'));
overlay.querySelector('.next').addEventListener('click', () => this._go(this._index + 1, 'click'));
overlay.querySelector('.reset').addEventListener('click', () => this._go(0, 'click'));
this._root.append(style, stage, tapzones, overlay);
this._canvas = canvas;
this._slot = slot;
this._overlay = overlay;
this._countEl = overlay.querySelector('.current');
this._totalEl = overlay.querySelector('.total');
}
/** @page must live in the document stylesheet — it's a no-op inside
* shadow DOM. Inject/update a single <head> style tag so the print
* sheet matches the design size and Save-as-PDF yields one slide per
* page with no margins. */
_syncPrintPageRule() {
const id = 'deck-stage-print-page';
let tag = document.getElementById(id);
if (!tag) {
tag = document.createElement('style');
tag.id = id;
document.head.appendChild(tag);
}
tag.textContent =
'@page { size: ' + this.designWidth + 'px ' + this.designHeight + 'px; margin: 0; } ' +
'@media print { html, body { margin: 0 !important; padding: 0 !important; background: none !important; overflow: visible !important; height: auto !important; } ' +
'* { -webkit-print-color-adjust: exact; print-color-adjust: exact; } }';
}
_onSlotChange() {
this._collectSlides();
this._restoreIndex();
this._applyIndex({ showOverlay: false, broadcast: true, reason: 'init' });
this._fit();
}
_collectSlides() {
const assigned = this._slot.assignedElements({ flatten: true });
this._slides = assigned.filter((el) => {
// Skip template/style/script nodes even if someone slots them.
const tag = el.tagName;
return tag !== 'TEMPLATE' && tag !== 'SCRIPT' && tag !== 'STYLE';
});
this._slides.forEach((slide, i) => {
const n = i + 1;
// Determine a label for comment flow: prefer explicit data-label,
// then an existing data-screen-label, then first heading, else "Slide".
let label = slide.getAttribute('data-label');
if (!label) {
const existing = slide.getAttribute('data-screen-label');
if (existing) {
// Strip any leading number the author may have included.
label = existing.replace(/^\s*\d+\s*/, '').trim() || existing;
}
}
if (!label) {
const h = slide.querySelector('h1, h2, h3, [data-title]');
if (h) label = (h.textContent || '').trim().slice(0, 40);
}
if (!label) label = 'Slide';
slide.setAttribute('data-screen-label', `${pad2(n)} ${label}`);
// Validation attribute for comment flow / auto-checks.
if (!slide.hasAttribute('data-om-validate')) {
slide.setAttribute('data-om-validate', VALIDATE_ATTR);
}
slide.setAttribute('data-deck-slide', String(i));
});
if (this._totalEl) this._totalEl.textContent = String(this._slides.length || 1);
if (this._index >= this._slides.length) this._index = Math.max(0, this._slides.length - 1);
}
_loadNotes() {
const tag = document.getElementById('speaker-notes');
if (!tag) { this._notes = []; return; }
try {
const parsed = JSON.parse(tag.textContent || '[]');
if (Array.isArray(parsed)) this._notes = parsed;
} catch (e) {
console.warn('[deck-stage] Failed to parse #speaker-notes JSON:', e);
this._notes = [];
}
}
_restoreIndex() {
// The host's ?slide= param is delivered as a #<int> hash (1-indexed) on
// the iframe src. No hash → slide 1; the deck itself keeps no position
// state across loads.
const h = (location.hash || '').match(/^#(\d+)$/);
if (h) {
const n = parseInt(h[1], 10) - 1;
if (n >= 0 && n < this._slides.length) this._index = n;
}
}
_applyIndex({ showOverlay = true, broadcast = true, reason = 'init' } = {}) {
if (!this._slides.length) return;
const prev = this._prevIndex == null ? -1 : this._prevIndex;
const curr = this._index;
// Keep the iframe's own hash in sync so an in-iframe location.reload()
// (reload banner path in viewer-handle.ts) lands on the current slide,
// not the stale deep-link hash from initial load.
try { history.replaceState(null, '', '#' + (curr + 1)); } catch (e) {}
this._slides.forEach((s, i) => {
if (i === curr) s.setAttribute('data-deck-active', '');
else s.removeAttribute('data-deck-active');
});
if (this._countEl) this._countEl.textContent = String(curr + 1);
if (broadcast) {
// (1) Legacy: host-window postMessage for speaker-notes renderers.
try { window.postMessage({ slideIndexChanged: curr }, '*'); } catch (e) {}
// (2) In-page CustomEvent on the <deck-stage> element itself.
// Bubbles and composes out of shadow DOM so slide code can listen:
// document.querySelector('deck-stage').addEventListener('slidechange', e => {
// e.detail.index, e.detail.previousIndex, e.detail.total, e.detail.slide, e.detail.reason
// });
const detail = {
index: curr,
previousIndex: prev,
total: this._slides.length,
slide: this._slides[curr] || null,
previousSlide: prev >= 0 ? (this._slides[prev] || null) : null,
reason: reason, // 'init' | 'keyboard' | 'click' | 'tap' | 'api'
};
this.dispatchEvent(new CustomEvent('slidechange', {
detail,
bubbles: true,
composed: true,
}));
}
this._prevIndex = curr;
if (showOverlay) this._flashOverlay();
}
_flashOverlay() {
if (!this._overlay) return;
this._overlay.setAttribute('data-visible', '');
if (this._hideTimer) clearTimeout(this._hideTimer);
this._hideTimer = setTimeout(() => {
this._overlay.removeAttribute('data-visible');
}, OVERLAY_HIDE_MS);
}
_fit() {
if (!this._canvas) return;
// PPTX export sets noscale so the DOM capture sees authored-size
// geometry — the scaled canvas is in shadow DOM, so the exporter's
// resetTransformSelector can't reach .canvas.style.transform directly.
if (this.hasAttribute('noscale')) {
this._canvas.style.transform = 'none';
return;
}
const vw = window.innerWidth;
const vh = window.innerHeight;
const s = Math.min(vw / this.designWidth, vh / this.designHeight);
this._canvas.style.transform = `scale(${s})`;
}
_onResize() { this._fit(); }
_onMouseMove() {
// Keep overlay visible while mouse moves; hide after idle.
this._flashOverlay();
}
_onTapBack(e) {
e.preventDefault();
this._go(this._index - 1, 'tap');
}
_onTapForward(e) {
e.preventDefault();
this._go(this._index + 1, 'tap');
}
_onKey(e) {
// Ignore when the user is typing.
const t = e.target;
if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return;
if (e.metaKey || e.ctrlKey || e.altKey) return;
const key = e.key;
let handled = true;
if (key === 'ArrowRight' || key === 'PageDown' || key === ' ' || key === 'Spacebar') {
this._go(this._index + 1, 'keyboard');
} else if (key === 'ArrowLeft' || key === 'PageUp') {
this._go(this._index - 1, 'keyboard');
} else if (key === 'Home') {
this._go(0, 'keyboard');
} else if (key === 'End') {
this._go(this._slides.length - 1, 'keyboard');
} else if (key === 'r' || key === 'R') {
this._go(0, 'keyboard');
} else if (/^[0-9]$/.test(key)) {
// 1..9 jump to that slide; 0 jumps to 10.
const n = key === '0' ? 9 : parseInt(key, 10) - 1;
if (n < this._slides.length) this._go(n, 'keyboard');
} else {
handled = false;
}
if (handled) {
e.preventDefault();
this._flashOverlay();
}
}
_go(i, reason = 'api') {
if (!this._slides.length) return;
const clamped = Math.max(0, Math.min(this._slides.length - 1, i));
if (clamped === this._index) {
this._flashOverlay();
return;
}
this._index = clamped;
this._applyIndex({ showOverlay: true, broadcast: true, reason });
}
// Public API ------------------------------------------------------------
/** Current slide index (0-based). */
get index() { return this._index; }
/** Total slide count. */
get length() { return this._slides.length; }
/** Programmatically navigate. */
goTo(i) { this._go(i, 'api'); }
next() { this._go(this._index + 1, 'api'); }
prev() { this._go(this._index - 1, 'api'); }
reset() { this._go(0, 'api'); }
}
if (!customElements.get('deck-stage')) {
customElements.define('deck-stage', DeckStage);
}
})();
+457
View File
@@ -0,0 +1,457 @@
// Shared utilities + small primitives
// Exported via window at bottom
const fmt = {
g: (n) => (n == null ? "—" : `${(+n).toFixed(2).replace(/\.?0+$/, "") || "0"} g`),
money: (n) => (n == null ? "—" : `$${(+n).toFixed(2)}`),
moneyShort: (n) => (n == null ? "—" : n >= 100 ? `$${Math.round(n)}` : `$${(+n).toFixed(2)}`),
pct: (n) => (n == null ? "—" : `${(+n).toFixed(1)}%`),
date: (s) => {
if (!s) return "—";
const d = new Date(s);
return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
},
dateShort: (s) => {
if (!s) return "—";
const d = new Date(s);
return d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
},
daysAgo: (s) => {
if (!s) return "—";
const ms = Date.now() - new Date(s).getTime();
const d = Math.floor(ms / 86400000);
if (d === 0) return "today";
if (d === 1) return "yesterday";
if (d < 30) return `${d}d ago`;
if (d < 365) return `${Math.floor(d/30)}mo ago`;
return `${Math.floor(d/365)}y ago`;
}
};
const TYPE_GLYPHS = {
"Flower": "✿",
"Concentrate": "◆",
"Edible": "◐",
"Vaporizer": "▢",
"Pre-roll": "│",
"Tincture": "◯"
};
// Compute aggregate stats — derived from purchases + consumed/gone records + audits
function computeStats(data) {
const today = new Date(data.today || "2026-04-25");
const todayStr = today.toISOString().slice(0, 10);
const products = data.products;
const H = window.DATA_HELPERS;
const dayKey = (d) => d.toISOString().slice(0, 10);
const active = products.filter(p => p.status === "active");
const consumed = products.filter(p => p.status === "consumed" && p.consumedDate);
const gone = products.filter(p => p.status === "gone");
// Window helper for purchases
const purchasesIn = (days) => {
const cutoff = new Date(today); cutoff.setDate(cutoff.getDate() - days);
return products.filter(p => new Date(p.purchaseDate) >= cutoff);
};
const last7p = purchasesIn(7);
const last30p = purchasesIn(30);
const last90p = purchasesIn(90);
// Bulk-grams equivalent: bulk uses weight (or ml for tincture, ignored from grams);
// discrete uses unitWeight × units consumed
const bulkGrams = (p) => {
if (p.type === "Tincture" || p.type === "Edible") return 0; // not "weed grams"
if (p.kind === "bulk") return p.weight;
return (p.countOriginal || 0) * (p.unitWeight || 0);
};
const bulkGramsConsumed = (p) => {
// For consumed products: full weight equivalent
if (p.type === "Tincture" || p.type === "Edible") return 0;
if (p.kind === "bulk") return p.weight;
return (p.countOriginal || 0) * (p.unitWeight || 0);
};
const bulkGramsUsedSoFar = (p) => {
// For active products: estimated grams used to date
if (p.type === "Tincture" || p.type === "Edible") return 0;
if (p.kind === "bulk") {
const est = H.estimatedRemaining(p, todayStr);
return Math.max(0, p.weight - est);
}
// discrete: (original - current) × unitWeight
const cur = p.countLastAudit != null ? p.countLastAudit : p.countOriginal;
return Math.max(0, (p.countOriginal - cur)) * (p.unitWeight || 0);
};
// Daily attribution: spread used grams over (purchase → consumed/today) for consumed/active.
// GONE items contribute $0 NOT grams (they were lost, not used).
const dailyGramsAttribution = {};
consumed.forEach(p => {
const g = bulkGramsConsumed(p);
if (g <= 0) return;
const start = new Date(p.purchaseDate);
const end = new Date(p.consumedDate);
const days = Math.max(1, Math.round((end - start) / 86400000));
const perDay = g / days;
for (let i = 0; i < days; i++) {
const d = new Date(start); d.setDate(d.getDate() + i);
dailyGramsAttribution[dayKey(d)] = (dailyGramsAttribution[dayKey(d)] || 0) + perDay;
}
});
active.forEach(p => {
const used = bulkGramsUsedSoFar(p);
if (used <= 0) return;
const start = new Date(p.purchaseDate);
const days = Math.max(1, Math.round((today - start) / 86400000));
const perDay = used / days;
for (let i = 0; i < days; i++) {
const d = new Date(start); d.setDate(d.getDate() + i);
dailyGramsAttribution[dayKey(d)] = (dailyGramsAttribution[dayKey(d)] || 0) + perDay;
}
});
const seriesFor = (days) => {
const out = [];
for (let i = days - 1; i >= 0; i--) {
const d = new Date(today); d.setDate(d.getDate() - i);
const k = dayKey(d);
out.push({ date: k, grams: dailyGramsAttribution[k] || 0 });
}
return out;
};
const series7 = seriesFor(7);
const series30 = seriesFor(30);
const series90 = seriesFor(90);
const sumG = (xs) => xs.reduce((s, x) => s + x.grams, 0);
const dailyAvg = sumG(series30) / 30;
const weeklyAvg = sumG(series30) / (30/7);
const monthlyAvg = sumG(series90) / 3;
// Spend
const totalSpend = products.reduce((s, p) => s + p.price, 0);
const goneSpend = gone.reduce((s, p) => s + p.price, 0);
const totalGrams = products.reduce((s, p) => s + bulkGrams(p), 0);
const avgPerGram = totalGrams ? totalSpend / totalGrams : 0;
const spend30 = last30p.reduce((s, p) => s + p.price, 0);
const spend7 = last7p.reduce((s, p) => s + p.price, 0);
const spend90 = last90p.reduce((s, p) => s + p.price, 0);
// Inventory value (active, prorated by est. remaining %)
const inventoryValue = active.reduce((s, p) => {
return s + p.price * H.pctRemaining(p, todayStr);
}, 0);
// THC mg using avg THC of products
const avgThc = products.length ? products.reduce((s,p)=>s+p.thc,0) / products.length : 20;
const thcLast7 = Math.round(sumG(series7) * avgThc * 10);
const thcLast30 = Math.round(sumG(series30) * avgThc * 10);
// Avg lifespan of consumed
const lifespans = consumed.map(p => Math.max(1, Math.round((new Date(p.consumedDate) - new Date(p.purchaseDate))/86400000)));
const avgLifespan = lifespans.length ? lifespans.reduce((a,b)=>a+b,0) / lifespans.length : 0;
// Favorite shop / brand — keyed by id, look up name
const shopCount = {};
const brandCount = {};
products.forEach(p => {
if (p.shopId) shopCount[p.shopId] = (shopCount[p.shopId] || 0) + 1;
if (p.brandId) brandCount[p.brandId] = (brandCount[p.brandId] || 0) + 1;
});
const topShopEntry = Object.entries(shopCount).sort((a,b)=>b[1]-a[1])[0];
const topBrandEntry = Object.entries(brandCount).sort((a,b)=>b[1]-a[1])[0];
const favShop = topShopEntry ? [H.shopName(data, topShopEntry[0]), topShopEntry[1]] : ["—", 0];
const favBrand = topBrandEntry ? [H.brandName(data, topBrandEntry[0]), topBrandEntry[1]] : ["—", 0];
// Type breakdown by est. grams on hand (active only)
const typeBreakdown = {};
active.forEach(p => {
let g;
if (p.type === "Tincture") g = H.estimatedRemaining(p, todayStr) * 0.5; // ml → display weight rough
else if (p.type === "Edible") g = (p.countLastAudit != null ? p.countLastAudit : p.countOriginal) * 0.3; // each gummy ~0.3g for chart only
else if (p.kind === "bulk") g = H.estimatedRemaining(p, todayStr);
else g = (p.countLastAudit != null ? p.countLastAudit : p.countOriginal) * (p.unitWeight || 0);
if (g > 0) typeBreakdown[p.type] = (typeBreakdown[p.type] || 0) + g;
});
// Flower-equivalent supply
const flowerEquivalent = active
.filter(p => p.type === "Flower" || p.type === "Pre-roll")
.reduce((s, p) => {
if (p.kind === "bulk") return s + H.estimatedRemaining(p, todayStr);
return s + (p.countLastAudit != null ? p.countLastAudit : p.countOriginal) * (p.unitWeight || 0);
}, 0);
const daysOfSupply = dailyAvg > 0 ? flowerEquivalent / dailyAvg : 0;
// Avg days between buys
const sortedDates = [...products].sort((a,b)=>new Date(a.purchaseDate)-new Date(b.purchaseDate)).map(p => new Date(p.purchaseDate));
const gaps = [];
for (let i = 1; i < sortedDates.length; i++) {
gaps.push((sortedDates[i] - sortedDates[i-1]) / 86400000);
}
const avgGap = gaps.length ? gaps.reduce((a,b)=>a+b,0)/gaps.length : 0;
// ─── Audits & low stock ───────────────────────────────────────
const overdueAudits = active.filter(p => H.auditOverdue(data, p, todayStr));
// Low stock:
// - Bulk: pctRemaining < 0.25
// - Discrete: GROUPED BY (brand + type) — total count ≤ 2
const lowStockBulk = active.filter(p => p.kind === "bulk" && H.pctRemaining(p, todayStr) < 0.25);
const discreteBrandGroups = {};
active.filter(p => p.kind === "discrete").forEach(p => {
const k = `${p.brandId}|${p.type}|${p.name}`;
if (!discreteBrandGroups[k]) {
discreteBrandGroups[k] = {
key: k, name: p.name, type: p.type, brandId: p.brandId,
items: [], totalCount: 0
};
}
discreteBrandGroups[k].items.push(p);
discreteBrandGroups[k].totalCount += (p.countLastAudit != null ? p.countLastAudit : p.countOriginal);
});
const lowStockDiscreteGroups = Object.values(discreteBrandGroups).filter(g => g.totalCount <= 2);
return {
dailyAvg, weeklyAvg, monthlyAvg,
totalSpend, avgPerGram, spend7, spend30, spend90, goneSpend,
inventoryValue,
thcLast7, thcLast30,
avgLifespan,
favShop, favBrand,
typeBreakdown,
daysOfSupply,
avgGap,
series7, series30, series90,
activeCount: active.length,
consumedCount: consumed.length,
goneCount: gone.length,
archivedCount: consumed.length + gone.length,
overdueAudits,
lowStockBulk,
lowStockDiscreteGroups
};
}
// Subtle inline icons (1px stroke)
const Icon = ({name, size = 18, color = "currentColor"}) => {
const paths = {
home: "M3 11l9-8 9 8M5 9v12h5v-7h4v7h5V9",
box: "M3 7l9-4 9 4v10l-9 4-9-4V7zM3 7l9 4 9-4M12 11v10",
chart: "M3 21V3M3 21h18M7 17v-7M11 17v-4M15 17v-9M19 17v-2",
plus: "M12 5v14M5 12h14",
check: "M5 13l4 4L19 7",
settings: "M12 3v3M12 18v3M5 5l2 2M17 17l2 2M3 12h3M18 12h3M5 19l2-2M17 7l2-2M12 8a4 4 0 100 8 4 4 0 000-8z",
search: "M11 19a8 8 0 100-16 8 8 0 000 16zM21 21l-4-4",
filter: "M3 5h18M6 12h12M10 19h4",
bin: "M4 7h16M9 7V4h6v3M6 7v13h12V7",
leaf: "M5 19c0-7 5-14 14-14 0 9-5 14-14 14zM5 19l7-7",
flame: "M12 3c1 4 4 5 4 9a4 4 0 11-8 0c0-2 2-3 2-6 0-1 1-2 2-3z",
droplet: "M12 3l5 7a5 5 0 11-10 0l5-7z",
arrow: "M5 12h14M13 5l7 7-7 7",
arrowDown: "M12 5v14M5 13l7 7 7-7",
close: "M6 6l12 12M18 6L6 18",
edit: "M4 20h4l10-10-4-4L4 16v4zM14 6l4 4",
star: "M12 3l3 6 7 1-5 5 1 7-6-3-6 3 1-7-5-5 7-1z",
calendar: "M5 5h14v15H5zM3 10h18M9 3v4M15 3v4",
tag: "M3 12V3h9l9 9-9 9-9-9zM7 7h.01"
};
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{flexShrink: 0}}>
<path d={paths[name] || ""} />
</svg>
);
};
// Sparkline
const Sparkline = ({values, width = 120, height = 32, color = "var(--ink)", fill = false}) => {
if (!values || values.length === 0) return null;
const max = Math.max(...values, 0.001);
const min = Math.min(...values, 0);
const span = max - min || 1;
const step = width / (values.length - 1 || 1);
const pts = values.map((v, i) => [i * step, height - ((v - min) / span) * (height - 4) - 2]);
const path = pts.map((p, i) => (i === 0 ? "M" : "L") + p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" ");
const fillPath = fill ? path + ` L ${width} ${height} L 0 ${height} Z` : null;
return (
<svg width={width} height={height} style={{display: "block", overflow: "visible"}}>
{fillPath && <path d={fillPath} fill={color} opacity="0.12" />}
<path d={path} stroke={color} strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
</svg>
);
};
// Bar chart
const BarChart = ({data, height = 160, color = "var(--sage)", labels = false}) => {
if (!data || !data.length) return null;
const max = Math.max(...data.map(d => d.value), 0.001);
return (
<div style={{display: "flex", alignItems: "flex-end", gap: 2, height, width: "100%"}}>
{data.map((d, i) => (
<div key={i} style={{flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 4, minWidth: 0}}>
<div style={{
width: "100%",
height: `${(d.value / max) * 100}%`,
background: d.value > 0 ? color : "var(--line)",
borderRadius: "2px 2px 0 0",
minHeight: d.value > 0 ? 2 : 1,
opacity: d.muted ? 0.4 : 1
}} />
{labels && <div style={{fontSize: 9, color: "var(--ink-3)", fontFamily: "var(--mono)"}}>{d.label}</div>}
</div>
))}
</div>
);
};
// Donut chart
const Donut = ({segments, size = 160, thickness = 22}) => {
const total = segments.reduce((s, x) => s + x.value, 0);
const r = size / 2 - thickness / 2;
const c = 2 * Math.PI * r;
let offset = 0;
return (
<svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{transform: "rotate(-90deg)"}}>
<circle cx={size/2} cy={size/2} r={r} stroke="var(--line)" strokeWidth={thickness} fill="none" opacity="0.3" />
{segments.map((s, i) => {
const len = (s.value / total) * c;
const dash = `${len} ${c - len}`;
const el = (
<circle key={i} cx={size/2} cy={size/2} r={r} stroke={s.color} strokeWidth={thickness} fill="none"
strokeDasharray={dash} strokeDashoffset={-offset} strokeLinecap="butt" />
);
offset += len;
return el;
})}
</svg>
);
};
// Reusable card
const Card = ({children, style, padded = true, ...rest}) => {
const { padded: _ignored, ...domProps } = rest;
return (
<div {...domProps} style={{
background: "var(--surface)",
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
padding: padded ? 20 : 0,
...style
}}>{children}</div>
);
};
// Stat card
const Stat = ({label, value, unit, sub, spark, accent, big}) => (
<div style={{
background: "var(--surface)",
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
padding: 18,
display: "flex",
flexDirection: "column",
gap: 8,
minWidth: 0
}}>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>{label}</div>
<div style={{display: "flex", alignItems: "baseline", gap: 6}}>
<div className="serif" style={{fontSize: big ? 44 : 32, lineHeight: 1, color: accent || "var(--ink)", fontWeight: 500, letterSpacing: "-0.01em"}}>{value}</div>
{unit && <div style={{fontSize: 13, color: "var(--ink-3)", fontFamily: "var(--mono)"}}>{unit}</div>}
</div>
{sub && <div style={{fontSize: 12, color: "var(--ink-3)"}}>{sub}</div>}
{spark && <div style={{marginTop: 4}}>{spark}</div>}
</div>
);
// Pill / badge
const Pill = ({children, tone = "neutral", style}) => {
const tones = {
neutral: { bg: "var(--bg-3)", color: "var(--ink-2)" },
sage: { bg: "var(--sage-soft)", color: "var(--sage)" },
terra: { bg: "var(--terracotta-soft)", color: "var(--terracotta)" },
amber: { bg: "var(--amber-soft)", color: "oklch(48% 0.10 75)" },
outline: { bg: "transparent", color: "var(--ink-2)", border: "1px solid var(--line-strong)" }
};
const t = tones[tone] || tones.neutral;
return (
<span style={{
display: "inline-flex",
alignItems: "center",
gap: 4,
padding: "3px 8px",
borderRadius: 999,
background: t.bg,
color: t.color,
fontSize: 11,
fontWeight: 500,
letterSpacing: "0.02em",
border: t.border || "1px solid transparent",
...style
}}>{children}</span>
);
};
// Button — high contrast across themes
const Btn = ({children, variant = "ghost", icon, onClick, style, type, disabled}) => {
// Disabled: keep solid surface, dim the text only — never become low-contrast on bg
const variants = {
primary: disabled
? { background: "var(--bg-3)", color: "var(--ink-3)", border: "1px solid var(--line-strong)" }
: { background: "var(--ink)", color: "var(--bg)", border: "1px solid var(--ink)" },
secondary: { background: "var(--surface)", color: "var(--ink)", border: "1px solid var(--line-strong)" },
ghost: { background: "transparent", color: "var(--ink-2)", border: "1px solid transparent" },
danger: { background: "var(--terracotta)", color: "oklch(98% 0.01 40)", border: "1px solid var(--terracotta)" },
sage: { background: "var(--sage)", color: "oklch(98% 0.01 145)", border: "1px solid var(--sage)" }
};
const v = variants[variant];
return (
<button type={type} onClick={onClick} disabled={disabled} style={{
display: "inline-flex",
alignItems: "center",
gap: 6,
padding: "8px 14px",
borderRadius: "var(--r-md)",
fontSize: 13,
fontWeight: 600,
transition: "all 120ms",
cursor: disabled ? "not-allowed" : "pointer",
...v,
...style
}}>
{icon && <Icon name={icon} size={14} />}
{children}
</button>
);
};
// Field
const Field = ({label, children, hint, span = 1}) => (
<label style={{display: "flex", flexDirection: "column", gap: 6, gridColumn: `span ${span}`}}>
<span className="smallcaps" style={{color: "var(--ink-3)"}}>{label}</span>
{children}
{hint && <span style={{fontSize: 11, color: "var(--ink-3)"}}>{hint}</span>}
</label>
);
const inputStyle = {
background: "var(--bg)",
border: "1px solid var(--line)",
borderRadius: "var(--r-md)",
padding: "10px 12px",
fontSize: 13,
color: "var(--ink)",
outline: "none",
fontFamily: "var(--sans)",
width: "100%"
};
const Input = (props) => <input style={inputStyle} {...props} />;
const Select = ({children, ...rest}) => <select style={{...inputStyle, appearance: "auto"}} {...rest}>{children}</select>;
const Textarea = (props) => <textarea style={{...inputStyle, minHeight: 80, resize: "vertical"}} {...props} />;
Object.assign(window, {
fmt, computeStats, TYPE_GLYPHS,
Icon, Sparkline, BarChart, Donut,
Card, Stat, Pill, Btn, Field, Input, Select, Textarea, inputStyle
});
+578
View File
@@ -0,0 +1,578 @@
// Dashboard, Inventory, Product detail screens
const H = window.DATA_HELPERS;
const TODAY_STR = "2026-04-25";
// ─── Helpers shared across screens ─────────────────────────────────
const remainingDisplay = (p) => {
const cfg = window.SAMPLE_DATA.types.find(t => t.id === p.type);
if (p.kind === "discrete") {
const cur = p.countLastAudit != null ? p.countLastAudit : p.countOriginal;
return `${cur} / ${p.countOriginal} ${cfg?.unit || "ct"}`;
}
const est = H.estimatedRemaining(p, TODAY_STR);
return `${est.toFixed(2).replace(/\.?0+$/,"")} / ${p.weight} ${cfg?.unit || "g"}`;
};
const remainingShort = (p) => {
if (p.kind === "discrete") {
const cur = p.countLastAudit != null ? p.countLastAudit : p.countOriginal;
return `${cur} ct`;
}
const cfg = window.SAMPLE_DATA.types.find(t => t.id === p.type);
const est = H.estimatedRemaining(p, TODAY_STR);
return `${est.toFixed(2).replace(/\.?0+$/,"") || "0"} ${cfg?.unit || "g"}`;
};
const Dashboard = ({data, stats, onNav, onSelectProduct, onAudit, onMarkGone}) => {
const series30 = stats.series30.map(d => ({ date: d.date, value: d.grams, label: "" }));
// Type breakdown
const typeColors = {
"Flower": "var(--sage)",
"Concentrate": "var(--terracotta)",
"Edible": "var(--amber)",
"Vaporizer": "var(--plum)",
"Pre-roll": "oklch(50% 0.06 200)",
"Tincture": "oklch(55% 0.06 270)"
};
const segments = Object.entries(stats.typeBreakdown).map(([k, v]) => ({
label: k, value: v, color: typeColors[k] || "var(--ink-3)"
}));
// Sparklines
const last7Series = stats.series7.map(l => l.grams);
const last30Series = series30.map(d => d.value);
const overdue = stats.overdueAudits;
const lowBulk = stats.lowStockBulk;
const lowDiscrete = stats.lowStockDiscreteGroups;
return (
<div style={{padding: "32px 40px 80px", maxWidth: 1400, margin: "0 auto"}}>
{/* Header */}
<div style={{display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24, marginBottom: 16, flexWrap: "wrap"}}>
<div style={{minWidth: 0}}>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>Saturday · April 25, 2026</div>
<h1 className="serif" style={{fontSize: 36, margin: "6px 0 0", fontWeight: 500, letterSpacing: "-0.02em", lineHeight: 1.1, whiteSpace: "nowrap"}}>Good evening.</h1>
</div>
<div style={{display: "flex", gap: 8, flexShrink: 0}}>
<Btn variant="secondary" icon="plus" onClick={() => onNav("add")}>New product</Btn>
<Btn variant="secondary" icon="check" onClick={() => onNav("audit")}>Audit</Btn>
<Btn variant="primary" icon="check" onClick={() => onNav("consume")}>Mark finished</Btn>
</div>
</div>
<div style={{fontSize: 14, color: "var(--ink-2)", marginBottom: 28, maxWidth: 700}}>
{stats.activeCount} active items across {data.bins.length} bins · {stats.consumedCount} consumed · {stats.goneCount} gone.
{overdue.length > 0 && <span style={{color: "var(--terracotta)"}}> · {overdue.length} audit{overdue.length === 1 ? "" : "s"} overdue.</span>}
</div>
{/* Top stats row */}
<div style={{display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 14}}>
<Stat
label="Daily average"
value={stats.dailyAvg.toFixed(2)}
unit="g / day"
sub={`${fmt.g(stats.weeklyAvg)} weekly · ${fmt.g(stats.monthlyAvg)} monthly`}
spark={<Sparkline values={last30Series} width={240} height={28} color="var(--sage)" fill />}
/>
<Stat
label="Avg cost per gram"
value={fmt.money(stats.avgPerGram)}
sub={`Across ${data.products.length} purchases`}
/>
<Stat
label="30-day spend"
value={fmt.moneyShort(stats.spend30)}
sub={`Inventory value: ${fmt.money(stats.inventoryValue)}${stats.goneSpend > 0 ? ` · ${fmt.money(stats.goneSpend)} lost` : ""}`}
/>
<Stat
label="THC last 7 days"
value={stats.thcLast7.toLocaleString()}
unit="mg"
sub={`Last 30: ${(stats.thcLast30/1000).toFixed(1)} g THC`}
spark={<Sparkline values={last7Series} width={240} height={28} color="var(--terracotta)" />}
/>
</div>
{/* Audit alert strip */}
{overdue.length > 0 && (
<Card style={{marginBottom: 14, borderColor: "var(--amber)", background: "var(--amber-soft)"}}>
<div style={{display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap"}}>
<div style={{flex: 1, minWidth: 240}}>
<div className="smallcaps" style={{color: "oklch(48% 0.10 75)"}}>Audit overdue</div>
<div className="serif" style={{fontSize: 20, marginTop: 4, color: "var(--ink)"}}>
{overdue.length} item{overdue.length === 1 ? "" : "s"} haven't been checked in a while
</div>
<div style={{fontSize: 12, color: "var(--ink-2)", marginTop: 4}}>
{overdue.slice(0, 3).map(p => p.name).join(" · ")}
{overdue.length > 3 && ` · +${overdue.length - 3} more`}
</div>
</div>
<Btn variant="secondary" icon="check" onClick={() => onAudit && onAudit(overdue[0])}>Run audit</Btn>
</div>
</Card>
)}
{/* Main grid */}
<div style={{display: "grid", gridTemplateColumns: "2fr 1fr", gap: 14, marginBottom: 14}}>
{/* Consumption chart */}
<Card>
<div style={{display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 18}}>
<div>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>Consumption</div>
<div className="serif" style={{fontSize: 22, marginTop: 4}}>Last 30 days</div>
</div>
<div style={{display: "flex", gap: 16, fontSize: 12, color: "var(--ink-3)"}}>
<div><span style={{color: "var(--ink)"}} className="serif" >{fmt.g(stats.series30.reduce((s,l)=>s+l.grams,0))}</span> est. total</div>
<div><span style={{color: "var(--ink)"}} className="serif">{stats.avgGap.toFixed(0)}</span> day avg between buys</div>
</div>
</div>
<BarChart data={series30.map(d => ({...d, label: ""}))} height={140} color="var(--sage)" />
<div style={{display: "flex", justifyContent: "space-between", marginTop: 8, fontSize: 10, color: "var(--ink-3)", fontFamily: "var(--mono)"}}>
<span>30 days ago</span>
<span>15 days ago</span>
<span>today</span>
</div>
</Card>
{/* Type breakdown */}
<Card>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>By type · grams on hand</div>
<div className="serif" style={{fontSize: 22, marginTop: 4, marginBottom: 16}}>Inventory</div>
<div style={{display: "flex", alignItems: "center", gap: 20}}>
<Donut segments={segments} size={140} thickness={20} />
<div style={{flex: 1, display: "flex", flexDirection: "column", gap: 8}}>
{segments.map(s => (
<div key={s.label} style={{display: "flex", alignItems: "center", gap: 8, fontSize: 12}}>
<div style={{width: 8, height: 8, borderRadius: 2, background: s.color}} />
<div style={{flex: 1, color: "var(--ink-2)"}}>{s.label}</div>
<div className="mono" style={{color: "var(--ink)"}}>{s.value.toFixed(1)}g</div>
</div>
))}
</div>
</div>
</Card>
</div>
<div style={{display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14, marginBottom: 14}}>
<Stat
label="Days of supply"
value={Math.round(stats.daysOfSupply)}
unit="days"
sub="Flower & pre-rolls at current pace"
/>
<Stat
label="Avg lifespan"
value={Math.round(stats.avgLifespan)}
unit="days"
sub="From purchase to finished"
/>
<Stat
label="Days between buys"
value={stats.avgGap.toFixed(1)}
unit="days"
sub="Average across all purchases"
/>
</div>
{/* Bottom row: shop + brand + low stock */}
<div style={{display: "grid", gridTemplateColumns: "1fr 1fr 1.4fr", gap: 14}}>
<Card>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>Favorite shop</div>
<div className="serif" style={{fontSize: 28, marginTop: 6, fontWeight: 500}}>{stats.favShop[0]}</div>
<div style={{fontSize: 12, color: "var(--ink-3)", marginTop: 4}}>{stats.favShop[1]} of {data.products.length} purchases</div>
</Card>
<Card>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>Favorite brand</div>
<div className="serif" style={{fontSize: 28, marginTop: 6, fontWeight: 500}}>{stats.favBrand[0]}</div>
<div style={{fontSize: 12, color: "var(--ink-3)", marginTop: 4}}>{stats.favBrand[1]} purchases</div>
</Card>
<Card padded={false}>
<div style={{padding: "20px 20px 12px", display: "flex", justifyContent: "space-between", alignItems: "baseline"}}>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>Low stock · running out</div>
<div style={{fontSize: 11, color: "var(--ink-3)"}}>{lowBulk.length + lowDiscrete.length} item{(lowBulk.length + lowDiscrete.length) === 1 ? "" : "s"}</div>
</div>
<div>
{(lowBulk.length + lowDiscrete.length) === 0 && <div style={{padding: "0 20px 20px", fontSize: 13, color: "var(--ink-3)"}}>Nothing running low.</div>}
{lowBulk.slice(0, 3).map(p => {
const pct = H.pctRemaining(p, TODAY_STR);
return (
<div key={p.id} onClick={() => onSelectProduct(p)} style={{padding: "10px 20px", borderTop: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 12, cursor: "pointer"}}>
<div style={{flex: 1, minWidth: 0}}>
<div style={{fontSize: 13, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"}}>{p.name}</div>
<div style={{fontSize: 11, color: "var(--ink-3)"}}>{H.brandName(data, p.brandId)} · {p.type}</div>
</div>
<div style={{width: 60, height: 4, background: "var(--bg-3)", borderRadius: 2, overflow: "hidden"}}>
<div style={{width: `${pct * 100}%`, height: "100%", background: pct < 0.15 ? "var(--terracotta)" : "var(--amber)"}} />
</div>
<div className="mono" style={{fontSize: 11, color: "var(--ink-2)", width: 60, textAlign: "right"}}>{remainingShort(p)}</div>
</div>
);
})}
{lowDiscrete.slice(0, 2).map(g => (
<div key={g.key} onClick={() => onSelectProduct(g.items[0])} style={{padding: "10px 20px", borderTop: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 12, cursor: "pointer"}}>
<div style={{flex: 1, minWidth: 0}}>
<div style={{fontSize: 13, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"}}>{g.name}</div>
<div style={{fontSize: 11, color: "var(--ink-3)"}}>{H.brandName(data, g.brandId)} · {g.type}</div>
</div>
<Pill tone="amber" style={{fontSize: 10}}>{g.totalCount} left</Pill>
</div>
))}
</div>
</Card>
</div>
</div>
);
};
// ─── INVENTORY ─────────────────────────────────────────────────────
const Inventory = ({data, onSelectProduct, onNav}) => {
const [filter, setFilter] = React.useState("active"); // active | consumed | gone | all
const [typeFilter, setTypeFilter] = React.useState("all");
const [sortBy, setSortBy] = React.useState("recent");
const [search, setSearch] = React.useState("");
let products = data.products;
if (filter === "active") products = products.filter(p => p.status === "active");
else if (filter === "consumed") products = products.filter(p => p.status === "consumed");
else if (filter === "gone") products = products.filter(p => p.status === "gone");
if (typeFilter !== "all") products = products.filter(p => p.type === typeFilter);
if (search) {
const q = search.toLowerCase();
products = products.filter(p => {
const brand = H.brandName(data, p.brandId).toLowerCase();
const shop = H.shopName(data, p.shopId).toLowerCase();
return p.name.toLowerCase().includes(q) ||
brand.includes(q) ||
shop.includes(q) ||
p.sku.toLowerCase().includes(q);
});
}
products = [...products].sort((a, b) => {
if (sortBy === "recent") return new Date(b.purchaseDate) - new Date(a.purchaseDate);
if (sortBy === "name") return a.name.localeCompare(b.name);
if (sortBy === "thc") return b.thc - a.thc;
if (sortBy === "remaining") return H.estimatedRemaining(b, TODAY_STR) - H.estimatedRemaining(a, TODAY_STR);
if (sortBy === "price") return b.price - a.price;
if (sortBy === "audit") return H.daysSinceCheck(b, TODAY_STR) - H.daysSinceCheck(a, TODAY_STR);
return 0;
});
return (
<div style={{padding: "32px 40px 80px", maxWidth: 1400, margin: "0 auto"}}>
<div style={{display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 24}}>
<div>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>{products.length} items</div>
<h1 className="serif" style={{fontSize: 44, margin: "6px 0 0", fontWeight: 500, letterSpacing: "-0.02em"}}>Inventory</h1>
</div>
<div style={{display: "flex", gap: 8}}>
<Btn variant="secondary" icon="check" onClick={() => onNav("audit")}>Audit</Btn>
<Btn variant="primary" icon="plus" onClick={() => onNav("add")}>New product</Btn>
</div>
</div>
{/* Toolbar */}
<Card style={{marginBottom: 14, padding: 14}}>
<div style={{display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap"}}>
{/* Tabs */}
<div style={{display: "inline-flex", background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", padding: 3}}>
{[["active", "Active"], ["consumed", "Consumed"], ["gone", "Gone"], ["all", "All"]].map(([k, l]) => (
<button key={k} onClick={() => setFilter(k)} style={{
padding: "6px 14px",
fontSize: 12,
fontWeight: 500,
borderRadius: 6,
border: "none",
background: filter === k ? "var(--surface)" : "transparent",
color: filter === k ? "var(--ink)" : "var(--ink-3)",
boxShadow: filter === k ? "var(--shadow-sm)" : "none",
cursor: "pointer"
}}>{l}</button>
))}
</div>
{/* Search */}
<div style={{flex: 1, minWidth: 220, display: "flex", alignItems: "center", gap: 8, background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", padding: "0 10px"}}>
<Icon name="search" size={14} color="var(--ink-3)" />
<input
placeholder="Search by name, brand, shop, SKU…"
value={search}
onChange={e => setSearch(e.target.value)}
style={{border: "none", outline: "none", background: "transparent", padding: "8px 0", fontSize: 13, flex: 1, color: "var(--ink)"}}
/>
</div>
<Select value={typeFilter} onChange={e => setTypeFilter(e.target.value)} style={{...inputStyle, width: "auto", padding: "8px 10px"}}>
<option value="all">All types</option>
{data.types.map(t => <option key={t.id} value={t.id}>{t.id}</option>)}
</Select>
<Select value={sortBy} onChange={e => setSortBy(e.target.value)} style={{...inputStyle, width: "auto", padding: "8px 10px"}}>
<option value="recent">Recent first</option>
<option value="name">Name (AZ)</option>
<option value="thc">THC % (high)</option>
<option value="remaining">Remaining (high)</option>
<option value="price">Price (high)</option>
<option value="audit">Audit overdue first</option>
</Select>
</div>
</Card>
{/* Table */}
<Card padded={false}>
<div style={{display: "grid", gridTemplateColumns: "32px 2fr 1fr 1fr 0.6fr 0.6fr 0.9fr 0.9fr 0.8fr", padding: "12px 20px", borderBottom: "1px solid var(--line)", background: "var(--bg-2)", fontSize: 11, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.08em"}}>
<div></div>
<div>Product</div>
<div>Brand</div>
<div>Shop</div>
<div style={{textAlign: "right"}}>THC %</div>
<div style={{textAlign: "right"}}>Price</div>
<div style={{textAlign: "right"}}>Remaining</div>
<div>Last checked</div>
<div>Bin</div>
</div>
{products.length === 0 && (
<div style={{padding: 60, textAlign: "center", color: "var(--ink-3)"}}>No items match these filters.</div>
)}
{products.map(p => {
const bin = data.bins.find(b => b.id === p.binId);
const pctRemaining = H.pctRemaining(p, TODAY_STR);
const overdue = H.auditOverdue(data, p, TODAY_STR);
const sinceCheck = H.daysSinceCheck(p, TODAY_STR);
const last = H.lastAudit(p);
const isInactive = p.status !== "active";
return (
<div key={p.id} onClick={() => onSelectProduct(p)} className="inv-row" style={{
display: "grid",
gridTemplateColumns: "32px 2fr 1fr 1fr 0.6fr 0.6fr 0.9fr 0.9fr 0.8fr",
padding: "14px 20px",
borderBottom: "1px solid var(--line)",
alignItems: "center",
cursor: "pointer",
opacity: isInactive ? 0.55 : 1,
fontSize: 13
}}>
<div style={{fontFamily: "var(--serif)", fontSize: 18, color: "var(--ink-3)"}}>{TYPE_GLYPHS[p.type]}</div>
<div style={{minWidth: 0}}>
<div style={{fontWeight: 500, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"}}>
{p.name}
{p.status === "consumed" && <Pill tone="terra" style={{marginLeft: 6, fontSize: 10}}>Consumed</Pill>}
{p.status === "gone" && <Pill tone="amber" style={{marginLeft: 6, fontSize: 10}}>Gone</Pill>}
{p.status === "active" && overdue && <Pill tone="amber" style={{marginLeft: 6, fontSize: 10}}>Audit due</Pill>}
</div>
<div style={{fontSize: 11, color: "var(--ink-3)", fontFamily: "var(--mono)"}}>{p.sku}{p.assetTag ? ` · ${p.assetTag}` : ""}</div>
</div>
<div style={{color: "var(--ink-2)"}}>{H.brandName(data, p.brandId)}</div>
<div style={{color: "var(--ink-3)", fontSize: 12}}>{H.shopName(data, p.shopId)}</div>
<div style={{textAlign: "right", fontFamily: "var(--mono)", color: "var(--ink-2)"}}>{p.thc.toFixed(1)}</div>
<div style={{textAlign: "right", fontFamily: "var(--mono)"}}>{fmt.money(p.price)}</div>
<div style={{textAlign: "right", display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 4}}>
<div style={{fontFamily: "var(--mono)", fontSize: 12}}>{remainingShort(p)}</div>
{p.status === "active" && p.kind === "bulk" && (
<div style={{width: 50, height: 3, background: "var(--bg-3)", borderRadius: 2}}>
<div style={{width: `${pctRemaining*100}%`, height: "100%", background: pctRemaining < 0.25 ? "var(--terracotta)" : pctRemaining < 0.5 ? "var(--amber)" : "var(--sage)", borderRadius: 2}} />
</div>
)}
</div>
<div style={{fontSize: 11, color: overdue ? "var(--terracotta)" : "var(--ink-3)"}}>
{p.status !== "active"
? <span style={{fontStyle: "italic"}}>archived</span>
: last
? <span><span className="mono">{sinceCheck}d</span> ago · {last.mode}</span>
: <span style={{fontStyle: "italic"}}>never</span>}
</div>
<div style={{fontSize: 12, color: "var(--ink-3)"}}>{bin ? bin.name : <span style={{fontStyle: "italic"}}>—</span>}</div>
</div>
);
})}
</Card>
</div>
);
};
// ─── PRODUCT DETAIL ────────────────────────────────────────────────
const ProductDetail = ({product, data, onClose, onConsume, onMarkGone, onAudit, onEdit}) => {
const bin = data.bins.find(b => b.id === product.binId);
const cfg = data.types.find(t => t.id === product.type);
const pctRemaining = H.pctRemaining(product, TODAY_STR);
const est = H.estimatedRemaining(product, TODAY_STR);
const last = H.lastAudit(product);
const overdue = H.auditOverdue(data, product, TODAY_STR);
const sinceCheck = H.daysSinceCheck(product, TODAY_STR);
const isActive = product.status === "active";
return (
<div style={{position: "fixed", inset: 0, background: "oklch(20% 0.02 60 / 0.4)", zIndex: 50, display: "flex", justifyContent: "flex-end"}} onClick={onClose}>
<div onClick={e => e.stopPropagation()} style={{
width: "min(720px, 100vw)",
height: "100%",
background: "var(--bg)",
borderLeft: "1px solid var(--line)",
overflow: "auto",
boxShadow: "var(--shadow-lg)"
}}>
{/* Header */}
<div style={{padding: "20px 32px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", justifyContent: "space-between", position: "sticky", top: 0, background: "var(--bg)", zIndex: 1}}>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>Product · {product.sku}</div>
<div style={{display: "flex", gap: 6}}>
{isActive && <Btn variant="ghost" icon="check" onClick={() => onAudit(product)}>Audit</Btn>}
{isActive && <Btn variant="secondary" icon="check" onClick={() => onConsume(product)}>Mark finished</Btn>}
{isActive && <Btn variant="ghost" icon="bin" onClick={() => onMarkGone(product)}>Mark gone</Btn>}
<Btn variant="ghost" icon="close" onClick={onClose} />
</div>
</div>
<div style={{padding: "32px 32px 60px"}}>
{/* Identity */}
<div style={{display: "flex", alignItems: "baseline", gap: 16, marginBottom: 8}}>
<div className="serif" style={{fontSize: 18, color: "var(--ink-3)"}}>{TYPE_GLYPHS[product.type]} {product.type}</div>
{product.status === "consumed" && <Pill tone="terra">Consumed · {fmt.daysAgo(product.consumedDate)}</Pill>}
{product.status === "gone" && <Pill tone="amber">Gone · {fmt.daysAgo(product.goneDate)}</Pill>}
{isActive && overdue && <Pill tone="amber">Audit overdue · {sinceCheck}d</Pill>}
</div>
<h1 className="serif" style={{fontSize: 48, margin: "0 0 4px", fontWeight: 500, letterSpacing: "-0.02em", lineHeight: 1.1}}>{product.name}</h1>
<div style={{fontSize: 16, color: "var(--ink-2)"}}>{H.brandName(data, product.brandId)} · from {H.shopName(data, product.shopId)}</div>
{/* Hero stats */}
<div style={{display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 1, marginTop: 32, background: "var(--line)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", overflow: "hidden"}}>
{[
["Price", fmt.money(product.price)],
[product.kind === "discrete" ? "Quantity" : "Size",
product.kind === "discrete"
? `${product.countOriginal} ${cfg?.unit || "ct"}`
: `${product.weight} ${cfg?.unit || "g"}`
],
["THC", `${product.thc.toFixed(1)}%`],
["CBD", `${product.cbd.toFixed(1)}%`]
].map(([l, v]) => (
<div key={l} style={{padding: "18px 16px", background: "var(--surface)"}}>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>{l}</div>
<div className="serif" style={{fontSize: 26, marginTop: 4, fontWeight: 500}}>{v}</div>
</div>
))}
</div>
{/* Remaining + audit */}
{isActive && (
<div style={{marginTop: 20}}>
<div style={{display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8}}>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>
{product.kind === "discrete" ? "Units remaining" : "Estimated remaining"}
</div>
<div style={{fontFamily: "var(--mono)", fontSize: 13}}>
{product.kind === "discrete"
? `${product.countLastAudit != null ? product.countLastAudit : product.countOriginal} of ${product.countOriginal}`
: `${est.toFixed(2)} of ${product.weight} ${cfg?.unit || "g"}`}
<span style={{color: "var(--ink-3)", marginLeft: 8}}>{Math.round(pctRemaining*100)}%</span>
</div>
</div>
<div style={{height: 8, background: "var(--bg-3)", borderRadius: 4, overflow: "hidden"}}>
<div style={{width: `${pctRemaining*100}%`, height: "100%", background: pctRemaining < 0.25 ? "var(--terracotta)" : pctRemaining < 0.5 ? "var(--amber)" : "var(--sage)"}} />
</div>
{product.kind === "bulk" && last && (
<div style={{fontSize: 11, color: "var(--ink-3)", marginTop: 6, fontStyle: "italic"}}>
Estimated by linear decay since last {last.mode} on {fmt.dateShort(last.date)} ({last.value}{cfg?.unit}). Re-audit to update.
</div>
)}
</div>
)}
{/* Audit history */}
<div style={{marginTop: 36}}>
<div style={{display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 12}}>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>Audit history</div>
{isActive && <button onClick={() => onAudit(product)} style={{background: "none", border: "none", fontSize: 12, color: "var(--ink-2)", cursor: "pointer", textDecoration: "underline"}}>+ New audit</button>}
</div>
{(!product.audits || product.audits.length === 0) ? (
<div style={{fontSize: 13, color: "var(--ink-3)", fontStyle: "italic", padding: "12px 0"}}>
No audits recorded. Cadence for {product.type}: every {cfg?.cadenceDays || "—"} days.
</div>
) : (
<div style={{display: "flex", flexDirection: "column", gap: 0, border: "1px solid var(--line)", borderRadius: "var(--r-md)", overflow: "hidden"}}>
{[...product.audits].reverse().map((a, i) => (
<div key={i} style={{padding: "12px 16px", borderBottom: i < product.audits.length - 1 ? "1px solid var(--line)" : "none", display: "flex", alignItems: "center", gap: 12, background: "var(--surface)"}}>
<div style={{width: 8, height: 8, borderRadius: "50%", background: a.mode === "weigh" ? "var(--sage)" : a.mode === "estimate" ? "var(--amber)" : "var(--plum)"}} />
<div style={{flex: 1}}>
<div style={{fontSize: 13, fontWeight: 500}}>
{a.mode === "weigh" && "Weighed"}
{a.mode === "estimate" && "Estimated"}
{a.mode === "presence" && (a.confirmedBy === "lost" ? "Marked lost" : "Confirmed presence")}
</div>
<div style={{fontSize: 11, color: "var(--ink-3)"}}>{fmt.date(a.date)} · {fmt.daysAgo(a.date)}</div>
</div>
<div className="mono" style={{fontSize: 13, textAlign: "right"}}>
<div>{a.value} {cfg?.unit}</div>
<div style={{fontSize: 10, color: "var(--ink-3)"}}>was {a.prev} {cfg?.unit}</div>
</div>
</div>
))}
</div>
)}
</div>
{/* Details list */}
<div style={{marginTop: 36}}>
<div className="smallcaps" style={{color: "var(--ink-3)", marginBottom: 12}}>Details</div>
<div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: "14px 32px"}}>
{[
["SKU", <span className="mono">{product.sku}</span>],
["Asset tag", product.assetTag ? <span className="mono">{product.assetTag}</span> : <span style={{color: "var(--ink-3)"}}>None</span>],
["Type", `${product.type} · ${product.kind}`],
["Brand", H.brandName(data, product.brandId)],
["Shop", H.shopName(data, product.shopId)],
["Total cannabinoids", `${product.totalCannabinoids.toFixed(1)}%`],
["Purchase date", fmt.date(product.purchaseDate)],
["Bin", bin ? `${bin.name} — ${bin.location}` : <span style={{color: "var(--ink-3)"}}>—</span>],
["Audit cadence", `Every ${cfg?.cadenceDays || "—"} days · ${cfg?.auditMode || "—"}`],
["Cost per gram",
product.kind === "bulk" && product.weight > 0
? fmt.money(product.price / product.weight)
: product.kind === "discrete" && product.unitWeight > 0
? `${fmt.money(product.price / (product.countOriginal * product.unitWeight))} (effective)`
: "—"
],
...(product.status === "consumed" ? [
["Date finished", fmt.date(product.consumedDate)],
["Lasted", `${Math.round((new Date(product.consumedDate) - new Date(product.purchaseDate))/86400000)} days`]
] : []),
...(product.status === "gone" ? [
["Date gone", fmt.date(product.goneDate)],
["After", `${Math.round((new Date(product.goneDate) - new Date(product.purchaseDate))/86400000)} days`]
] : [])
].map(([l, v], i) => (
<div key={i} style={{display: "flex", justifyContent: "space-between", paddingBottom: 12, borderBottom: "1px solid var(--line)"}}>
<span style={{color: "var(--ink-3)", fontSize: 12}}>{l}</span>
<span style={{fontSize: 13, fontWeight: 500, textAlign: "right"}}>{v}</span>
</div>
))}
</div>
</div>
{/* Final notes */}
{(product.status === "consumed" || product.status === "gone") && (
<div style={{marginTop: 36, padding: 24, background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: "var(--r-md)"}}>
<div style={{display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 12}}>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>{product.status === "gone" ? "Why it's gone" : "Final notes"}</div>
{product.status === "consumed" && (
<div style={{display: "flex", gap: 2}}>
{[1,2,3,4,5].map(n => (
<Icon key={n} name="star" size={14} color={n <= (product.rating || 0) ? "var(--amber)" : "var(--ink-4)"} />
))}
</div>
)}
</div>
<div className="serif" style={{fontSize: 18, lineHeight: 1.5, color: "var(--ink-2)", fontStyle: "italic"}}>
"{product.notes || 'No notes recorded.'}"
</div>
</div>
)}
</div>
</div>
</div>
);
};
Object.assign(window, { Dashboard, Inventory, ProductDetail, remainingDisplay, remainingShort });
+664
View File
@@ -0,0 +1,664 @@
// Add Product, Mark Consumed/Gone, Audit, Bins, Charts, Settings
const AddProductFlow = ({data, onClose, onSave}) => {
const [form, setForm] = React.useState({
name: "", brandId: data.brands[0].id, shopId: data.shops[0].id, type: "Flower",
weight: 3.5, countOriginal: 1, unitWeight: 0.7,
price: 45, thc: 22, cbd: 0.4, totalCannabinoids: 26,
purchaseDate: "2026-04-25", binId: data.bins[0].id,
sku: "", assetTag: ""
});
const update = (k, v) => setForm(f => ({...f, [k]: v}));
const cfg = data.types.find(t => t.id === form.type);
const isDiscrete = cfg?.kind === "discrete";
const cpg = !isDiscrete && form.weight > 0 ? form.price / form.weight : 0;
return (
<div style={{position: "fixed", inset: 0, background: "oklch(20% 0.02 60 / 0.4)", zIndex: 50, display: "flex", justifyContent: "center", alignItems: "flex-start", overflow: "auto"}} onClick={onClose}>
<div onClick={e => e.stopPropagation()} style={{
width: "min(840px, 96vw)", margin: "40px 20px", background: "var(--bg)",
border: "1px solid var(--line)", borderRadius: "var(--r-lg)", boxShadow: "var(--shadow-lg)"
}}>
<div style={{padding: "20px 32px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center"}}>
<div>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>New entry</div>
<h2 className="serif" style={{fontSize: 28, margin: "4px 0 0", fontWeight: 500}}>Add a product</h2>
</div>
<Btn variant="ghost" icon="close" onClick={onClose} />
</div>
<div style={{padding: 32}}>
<div className="smallcaps" style={{color: "var(--ink-3)", marginBottom: 16}}>Identity</div>
<div style={{display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16, marginBottom: 28}}>
<Field label="Product name" span={2}><Input value={form.name} placeholder="e.g. Garden Ghost" onChange={e => update("name", e.target.value)} /></Field>
<Field label="Brand"><Select value={form.brandId} onChange={e => update("brandId", e.target.value)}>{data.brands.map(b => <option key={b.id} value={b.id}>{b.name}</option>)}</Select></Field>
<Field label="Shop"><Select value={form.shopId} onChange={e => update("shopId", e.target.value)}>{data.shops.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}</Select></Field>
<Field label="Type"><Select value={form.type} onChange={e => update("type", e.target.value)}>{data.types.map(t => <option key={t.id} value={t.id}>{t.id} ({t.kind})</option>)}</Select></Field>
<Field label="Bin"><Select value={form.binId} onChange={e => update("binId", e.target.value)}>{data.bins.map(b => <option key={b.id} value={b.id}>{b.name} {b.location}</option>)}</Select></Field>
<Field label="SKU" hint="Leave blank — we'll generate one"><Input value={form.sku} placeholder="SKU-…" onChange={e => update("sku", e.target.value)} /></Field>
<Field label="Asset tag (optional)" hint="If you've physically tagged the item"><Input value={form.assetTag} placeholder="AT-0000" onChange={e => update("assetTag", e.target.value)} /></Field>
</div>
<div className="smallcaps" style={{color: "var(--ink-3)", marginBottom: 16}}>Acquisition</div>
<div style={{display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginBottom: 8}}>
{isDiscrete ? (
<>
<Field label={`Quantity (${cfg.unit})`}><Input type="number" step="1" value={form.countOriginal} onChange={e => update("countOriginal", +e.target.value)} /></Field>
<Field label="Per-unit weight (g)" hint="For grams stats"><Input type="number" step="0.1" value={form.unitWeight} onChange={e => update("unitWeight", +e.target.value)} /></Field>
</>
) : (
<Field label={`Size (${cfg?.unit || "g"})`} span={2}><Input type="number" step="0.1" value={form.weight} onChange={e => update("weight", +e.target.value)} /></Field>
)}
<Field label="Price ($)"><Input type="number" step="0.01" value={form.price} onChange={e => update("price", +e.target.value)} /></Field>
<Field label="Purchase date"><Input type="date" value={form.purchaseDate} onChange={e => update("purchaseDate", e.target.value)} /></Field>
</div>
{!isDiscrete && cpg > 0 && (
<div style={{marginTop: 12, fontSize: 12, color: "var(--ink-3)"}}>
Cost per {cfg?.unit || "g"}: <span className="mono" style={{color: "var(--ink-2)"}}>{fmt.money(cpg)}</span>
</div>
)}
<div className="smallcaps" style={{color: "var(--ink-3)", margin: "28px 0 16px"}}>Cannabinoid profile</div>
<div style={{display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16}}>
<Field label="THC %"><Input type="number" step="0.1" value={form.thc} onChange={e => update("thc", +e.target.value)} /></Field>
<Field label="CBD %"><Input type="number" step="0.1" value={form.cbd} onChange={e => update("cbd", +e.target.value)} /></Field>
<Field label="Total cannabinoids %"><Input type="number" step="0.1" value={form.totalCannabinoids} onChange={e => update("totalCannabinoids", +e.target.value)} /></Field>
</div>
</div>
<div style={{padding: "16px 32px", borderTop: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center", background: "var(--bg-2)", borderRadius: "0 0 var(--r-lg) var(--r-lg)"}}>
<div style={{fontSize: 12, color: "var(--ink-3)"}}>
{form.name ? `"${form.name}" → ${data.bins.find(b=>b.id===form.binId)?.name}.` : "Fill in the name to continue."}
</div>
<div style={{display: "flex", gap: 8}}>
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
<Btn variant="primary" icon="check" disabled={!form.name} onClick={() => onSave(form)}>Save product</Btn>
</div>
</div>
</div>
</div>
);
};
// ─── CONSUME (mark finished) ──────────────────────────────────────
const ConsumeFlow = ({data, onClose, product: initialProduct}) => {
const active = data.products.filter(p => p.status === "active");
const [productId, setProductId] = React.useState(initialProduct?.id || active[0]?.id);
const [rating, setRating] = React.useState(4);
const [notes, setNotes] = React.useState("");
const [date, setDate] = React.useState("2026-04-25");
const product = data.products.find(p => p.id === productId);
if (!product) return null;
const bin = data.bins.find(b => b.id === product.binId);
const lifespan = Math.round((new Date(date) - new Date(product.purchaseDate))/86400000);
return (
<div style={{position: "fixed", inset: 0, background: "oklch(20% 0.02 60 / 0.4)", zIndex: 50, display: "flex", justifyContent: "center", alignItems: "flex-start", overflow: "auto"}} onClick={onClose}>
<div onClick={e => e.stopPropagation()} style={{
width: "min(720px, 96vw)", margin: "40px 20px", background: "var(--bg)",
border: "1px solid var(--line)", borderRadius: "var(--r-lg)", boxShadow: "var(--shadow-lg)"
}}>
<div style={{padding: "20px 32px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center"}}>
<div>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>Archive · used up</div>
<h2 className="serif" style={{fontSize: 28, margin: "4px 0 0", fontWeight: 500}}>Mark as finished</h2>
</div>
<Btn variant="ghost" icon="close" onClick={onClose} />
</div>
<div style={{padding: 32}}>
<Field label="Product">
<Select value={productId} onChange={e => setProductId(e.target.value)}>
{active.map(p => <option key={p.id} value={p.id}>{p.name} {H.brandName(data, p.brandId)} ({remainingShort(p)} left)</option>)}
</Select>
</Field>
<div style={{marginTop: 16, padding: 16, background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", display: "flex", justifyContent: "space-between", alignItems: "center"}}>
<div>
<div className="serif" style={{fontSize: 22, fontWeight: 500}}>{product.name}</div>
<div style={{fontSize: 12, color: "var(--ink-3)"}}>{H.brandName(data, product.brandId)} · {bin?.name} · purchased {fmt.dateShort(product.purchaseDate)}</div>
</div>
<div style={{textAlign: "right"}}>
<div className="mono" style={{fontSize: 11, color: "var(--ink-3)"}}>LASTED</div>
<div className="serif" style={{fontSize: 24}}>{lifespan} days</div>
</div>
</div>
<div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 24}}>
<Field label="Date finished"><Input type="date" value={date} onChange={e => setDate(e.target.value)} /></Field>
<Field label="Rating">
<div style={{display: "flex", gap: 4, alignItems: "center", padding: "10px 12px", background: "var(--bg)", border: "1px solid var(--line)", borderRadius: "var(--r-md)"}}>
{[1,2,3,4,5].map(n => (
<button key={n} onClick={() => setRating(n)} style={{border: "none", background: "transparent", cursor: "pointer", padding: 2}}>
<Icon name="star" size={20} color={n <= rating ? "var(--amber)" : "var(--ink-4)"} />
</button>
))}
<span style={{marginLeft: "auto", fontSize: 12, color: "var(--ink-3)", fontFamily: "var(--mono)"}}>{rating}/5</span>
</div>
</Field>
</div>
<div style={{marginTop: 16}}>
<Field label="Final notes" hint="Flavor, effects, would you rebuy">
<Textarea value={notes} onChange={e => setNotes(e.target.value)} placeholder="What stood out?" />
</Field>
</div>
</div>
<div style={{padding: "16px 32px", borderTop: "1px solid var(--line)", display: "flex", justifyContent: "flex-end", gap: 8, background: "var(--bg-2)", borderRadius: "0 0 var(--r-lg) var(--r-lg)"}}>
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
<Btn variant="primary" icon="check" onClick={onClose}>Mark finished</Btn>
</div>
</div>
</div>
);
};
// ─── MARK GONE (lost / damaged / expired) ─────────────────────────
const MarkGoneFlow = ({data, onClose, product: initialProduct}) => {
const active = data.products.filter(p => p.status === "active");
const [productId, setProductId] = React.useState(initialProduct?.id || active[0]?.id);
const [reason, setReason] = React.useState("lost");
const [notes, setNotes] = React.useState("");
const [date, setDate] = React.useState("2026-04-25");
const product = data.products.find(p => p.id === productId);
if (!product) return null;
const reasons = [
["lost", "Lost / misplaced"],
["damaged", "Damaged"],
["expired", "Expired"],
["gifted", "Gifted away"],
["other", "Other"]
];
return (
<div style={{position: "fixed", inset: 0, background: "oklch(20% 0.02 60 / 0.4)", zIndex: 50, display: "flex", justifyContent: "center", alignItems: "flex-start", overflow: "auto"}} onClick={onClose}>
<div onClick={e => e.stopPropagation()} style={{
width: "min(640px, 96vw)", margin: "40px 20px", background: "var(--bg)",
border: "1px solid var(--line)", borderRadius: "var(--r-lg)", boxShadow: "var(--shadow-lg)"
}}>
<div style={{padding: "20px 32px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center"}}>
<div>
<div className="smallcaps" style={{color: "var(--terracotta)"}}>Archive · not consumed</div>
<h2 className="serif" style={{fontSize: 28, margin: "4px 0 0", fontWeight: 500}}>Mark as gone</h2>
</div>
<Btn variant="ghost" icon="close" onClick={onClose} />
</div>
<div style={{padding: 32}}>
<div style={{fontSize: 13, color: "var(--ink-2)", marginBottom: 20, padding: 14, background: "var(--amber-soft)", borderRadius: "var(--r-md)"}}>
Use this when an item is lost, damaged, expired, or gifted away. Counts as <strong>spend</strong> but not as <strong>consumption</strong>, so daily averages stay accurate.
</div>
<Field label="Product">
<Select value={productId} onChange={e => setProductId(e.target.value)}>
{active.map(p => <option key={p.id} value={p.id}>{p.name} {H.brandName(data, p.brandId)} ({remainingShort(p)} left)</option>)}
</Select>
</Field>
<div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 16}}>
<Field label="Reason">
<Select value={reason} onChange={e => setReason(e.target.value)}>
{reasons.map(([k,l]) => <option key={k} value={k}>{l}</option>)}
</Select>
</Field>
<Field label="Date">
<Input type="date" value={date} onChange={e => setDate(e.target.value)} />
</Field>
</div>
<div style={{marginTop: 16}}>
<Field label="Notes (optional)" hint="What happened">
<Textarea value={notes} onChange={e => setNotes(e.target.value)} placeholder="e.g. Pack went through the wash" />
</Field>
</div>
</div>
<div style={{padding: "16px 32px", borderTop: "1px solid var(--line)", display: "flex", justifyContent: "flex-end", gap: 8, background: "var(--bg-2)", borderRadius: "0 0 var(--r-lg) var(--r-lg)"}}>
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
<Btn variant="danger" icon="bin" onClick={onClose}>Mark gone</Btn>
</div>
</div>
</div>
);
};
// ─── AUDIT MODAL ──────────────────────────────────────────────────
const AuditFlow = ({data, onClose, product: initialProduct}) => {
const overdueFirst = [...data.products]
.filter(p => p.status === "active")
.sort((a, b) => H.daysSinceCheck(b) - H.daysSinceCheck(a));
const [productId, setProductId] = React.useState(initialProduct?.id || overdueFirst[0]?.id);
const [date, setDate] = React.useState("2026-04-25");
const product = data.products.find(p => p.id === productId);
const cfg = product ? data.types.find(t => t.id === product.type) : null;
// For bulk: weighed/estimated value. For discrete: count + confirmedBy.
const last = product ? H.lastAudit(product) : null;
const initialValue = product
? (product.kind === "discrete"
? (product.countLastAudit != null ? product.countLastAudit : product.countOriginal)
: H.estimatedRemaining(product, "2026-04-25").toFixed(2))
: 0;
const [value, setValue] = React.useState(initialValue);
const [confirmedBy, setConfirmedBy] = React.useState("SKU");
React.useEffect(() => {
if (product) {
setValue(product.kind === "discrete"
? (product.countLastAudit != null ? product.countLastAudit : product.countOriginal)
: H.estimatedRemaining(product, "2026-04-25").toFixed(2));
}
}, [productId]);
if (!product) return null;
const auditMode = cfg?.auditMode || "weigh";
const prevValue = product.kind === "discrete"
? (product.countLastAudit != null ? product.countLastAudit : product.countOriginal)
: (last ? last.value : product.weight);
const auditModeLabels = {
weigh: { title: "Reweigh on a scale", desc: "Place the jar (minus tare) and record the new weight." },
estimate: { title: "Visual estimate", desc: "Eyeball the remaining amount — quick and approximate." },
presence: { title: "Confirm presence", desc: "Verify the item is still where you left it. Count units if applicable." }
};
const ml = auditModeLabels[auditMode];
return (
<div style={{position: "fixed", inset: 0, background: "oklch(20% 0.02 60 / 0.4)", zIndex: 50, display: "flex", justifyContent: "center", alignItems: "flex-start", overflow: "auto"}} onClick={onClose}>
<div onClick={e => e.stopPropagation()} style={{
width: "min(720px, 96vw)", margin: "40px 20px", background: "var(--bg)",
border: "1px solid var(--line)", borderRadius: "var(--r-lg)", boxShadow: "var(--shadow-lg)"
}}>
<div style={{padding: "20px 32px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center"}}>
<div>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>Audit</div>
<h2 className="serif" style={{fontSize: 28, margin: "4px 0 0", fontWeight: 500}}>{ml.title}</h2>
</div>
<Btn variant="ghost" icon="close" onClick={onClose} />
</div>
<div style={{padding: 32}}>
<Field label="Product">
<Select value={productId} onChange={e => setProductId(e.target.value)}>
{overdueFirst.map(p => {
const od = H.auditOverdue(data, p);
const sc = H.daysSinceCheck(p);
return <option key={p.id} value={p.id}>{od ? "⚠ " : ""}{p.name} {H.brandName(data, p.brandId)} · {sc}d since check</option>;
})}
</Select>
</Field>
<div style={{marginTop: 16, padding: 16, background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: "var(--r-md)"}}>
<div style={{display: "flex", justifyContent: "space-between", alignItems: "center"}}>
<div>
<div className="serif" style={{fontSize: 20, fontWeight: 500}}>{product.name}</div>
<div style={{fontSize: 12, color: "var(--ink-3)"}}>
{product.type} · {product.kind} · cadence every {cfg?.cadenceDays}d
</div>
</div>
<div style={{textAlign: "right"}}>
<div className="mono" style={{fontSize: 11, color: "var(--ink-3)"}}>LAST CHECKED</div>
<div className="serif" style={{fontSize: 18}}>{last ? `${H.daysSinceCheck(product)}d ago` : "Never"}</div>
</div>
</div>
<div style={{fontSize: 12, color: "var(--ink-2)", marginTop: 10, fontStyle: "italic"}}>{ml.desc}</div>
</div>
<div style={{display: "grid", gridTemplateColumns: auditMode === "presence" ? "1fr 1fr 1fr" : "1fr 1fr", gap: 16, marginTop: 24}}>
<Field label={
product.kind === "discrete"
? `Count now (${cfg?.unit})`
: auditMode === "weigh" ? `Weight now (${cfg?.unit})` : `Estimate now (${cfg?.unit})`
}>
<Input
type="number"
step={product.kind === "discrete" ? "1" : "0.1"}
value={value}
onChange={e => setValue(e.target.value)}
/>
</Field>
<Field label="Date"><Input type="date" value={date} onChange={e => setDate(e.target.value)} /></Field>
{auditMode === "presence" && (
<Field label="Confirmed by">
<Select value={confirmedBy} onChange={e => setConfirmedBy(e.target.value)}>
<option value="SKU">SKU label</option>
<option value="asset">Asset tag</option>
<option value="visual">Visual ID</option>
</Select>
</Field>
)}
</div>
<div style={{marginTop: 20, padding: 14, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16}}>
<div>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>Was</div>
<div className="serif" style={{fontSize: 22}}>{prevValue} {cfg?.unit}</div>
</div>
<div>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>Now</div>
<div className="serif" style={{fontSize: 22, color: "var(--sage)"}}>{value} {cfg?.unit}</div>
</div>
<div>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>Δ since last</div>
<div className="serif" style={{fontSize: 22, color: (+value - +prevValue) < 0 ? "var(--terracotta)" : "var(--ink)"}}>
{(+value - +prevValue).toFixed(product.kind === "discrete" ? 0 : 2)} {cfg?.unit}
</div>
</div>
</div>
</div>
<div style={{padding: "16px 32px", borderTop: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center", background: "var(--bg-2)", borderRadius: "0 0 var(--r-lg) var(--r-lg)"}}>
<div style={{fontSize: 12, color: "var(--ink-3)"}}>Next audit due in {cfg?.cadenceDays}d</div>
<div style={{display: "flex", gap: 8}}>
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
<Btn variant="primary" icon="check" onClick={onClose}>Save audit</Btn>
</div>
</div>
</div>
</div>
);
};
// ─── BINS ─────────────────────────────────────────────────────────
const BinsView = ({data, onSelectProduct}) => {
return (
<div style={{padding: "32px 40px 80px", maxWidth: 1400, margin: "0 auto"}}>
<div style={{display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 24}}>
<div>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>{data.bins.length} bins</div>
<h1 className="serif" style={{fontSize: 44, margin: "6px 0 0", fontWeight: 500, letterSpacing: "-0.02em"}}>Bins & storage</h1>
</div>
<Btn variant="secondary" icon="plus">New bin</Btn>
</div>
<div style={{fontSize: 14, color: "var(--ink-2)", marginBottom: 24, maxWidth: 600}}>
Where each active product physically lives. Archived items aren't assigned to a bin.
</div>
<div style={{display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(380px, 1fr))", gap: 14}}>
{data.bins.map(bin => {
const items = data.products.filter(p => p.binId === bin.id && p.status === "active");
const fillPct = items.length / bin.capacity;
const totalValue = items.reduce((s, p) => s + p.price * H.pctRemaining(p, "2026-04-25"), 0);
return (
<Card key={bin.id} padded={false} style={{display: "flex", flexDirection: "column"}}>
<div style={{padding: "20px 22px 16px", borderBottom: "1px solid var(--line)"}}>
<div style={{display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 4}}>
<h3 className="serif" style={{fontSize: 24, margin: 0, fontWeight: 500}}>{bin.name}</h3>
<Pill tone="outline">{items.length} / {bin.capacity}</Pill>
</div>
<div style={{fontSize: 12, color: "var(--ink-3)", display: "flex", justifyContent: "space-between"}}>
<span>{bin.location}</span>
<span className="mono">{fmt.money(totalValue)}</span>
</div>
<div style={{marginTop: 12, height: 4, background: "var(--bg-3)", borderRadius: 2, overflow: "hidden"}}>
<div style={{width: `${Math.min(fillPct, 1)*100}%`, height: "100%", background: fillPct > 0.9 ? "var(--terracotta)" : fillPct > 0.7 ? "var(--amber)" : "var(--sage)"}} />
</div>
</div>
<div style={{padding: 8, flex: 1}}>
{items.length === 0 && <div style={{padding: 30, textAlign: "center", fontSize: 12, color: "var(--ink-3)", fontStyle: "italic"}}>Empty</div>}
{items.map(p => (
<div key={p.id} onClick={() => onSelectProduct(p)} style={{display: "flex", alignItems: "center", gap: 10, padding: "8px 14px", borderRadius: "var(--r-sm)", cursor: "pointer"}}>
<div style={{fontFamily: "var(--serif)", fontSize: 18, color: "var(--ink-3)", width: 18}}>{TYPE_GLYPHS[p.type]}</div>
<div style={{flex: 1, minWidth: 0}}>
<div style={{fontSize: 13, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"}}>{p.name}</div>
<div style={{fontSize: 11, color: "var(--ink-3)"}}>{H.brandName(data, p.brandId)}</div>
</div>
<div className="mono" style={{fontSize: 11, color: "var(--ink-2)"}}>{remainingShort(p)}</div>
</div>
))}
</div>
</Card>
);
})}
</div>
</div>
);
};
// ─── CHARTS ───────────────────────────────────────────────────────
const ChartsView = ({data, stats}) => {
const series = stats.series90.map(s => ({date: s.date, grams: s.grams, label: ""}));
const spendByMonth = {};
data.products.forEach(p => {
const k = p.purchaseDate.slice(0, 7);
spendByMonth[k] = (spendByMonth[k] || 0) + p.price;
});
const months = Object.entries(spendByMonth).sort();
const spendByShop = {};
data.products.forEach(p => {
const name = H.shopName(data, p.shopId);
spendByShop[name] = (spendByShop[name] || 0) + p.price;
});
const shopRanked = Object.entries(spendByShop).sort((a,b) => b[1]-a[1]);
return (
<div style={{padding: "32px 40px 80px", maxWidth: 1400, margin: "0 auto"}}>
<div style={{marginBottom: 24}}>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>Last 90 days</div>
<h1 className="serif" style={{fontSize: 44, margin: "6px 0 0", fontWeight: 500, letterSpacing: "-0.02em"}}>Patterns & spend</h1>
</div>
<Card style={{marginBottom: 14}}>
<div style={{display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 18}}>
<div className="serif" style={{fontSize: 22}}>Daily grams · 90 days</div>
<div style={{display: "flex", gap: 24, fontSize: 12, color: "var(--ink-3)"}}>
<div>Total <span className="serif" style={{fontSize: 18, color: "var(--ink)"}}>{series.reduce((s,e)=>s+e.grams,0).toFixed(1)} g</span></div>
<div>Avg <span className="serif" style={{fontSize: 18, color: "var(--ink)"}}>{(series.reduce((s,e)=>s+e.grams,0)/90).toFixed(2)} g/day</span></div>
<div>Items finished <span className="serif" style={{fontSize: 18, color: "var(--ink)"}}>{stats.consumedCount}</span></div>
{stats.goneCount > 0 && <div>Items gone <span className="serif" style={{fontSize: 18, color: "var(--ink)"}}>{stats.goneCount}</span></div>}
</div>
</div>
<BarChart data={series.map(s => ({value: s.grams, label: ""}))} height={180} color="var(--sage)" />
</Card>
<div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14}}>
<Card>
<div className="serif" style={{fontSize: 22, marginBottom: 18}}>Spend by month</div>
<div style={{display: "flex", flexDirection: "column", gap: 14}}>
{months.map(([m, v]) => {
const max = Math.max(...months.map(x => x[1]));
const d = new Date(m + "-01");
return (
<div key={m} style={{display: "flex", alignItems: "center", gap: 12}}>
<div className="smallcaps" style={{color: "var(--ink-3)", width: 60}}>{d.toLocaleDateString("en-US", {month: "short", year: "2-digit"})}</div>
<div style={{flex: 1, height: 24, background: "var(--bg-2)", borderRadius: 4, position: "relative"}}>
<div style={{width: `${(v/max)*100}%`, height: "100%", background: "var(--terracotta)", borderRadius: 4, opacity: 0.85}} />
</div>
<div className="mono" style={{width: 70, textAlign: "right", fontSize: 13}}>{fmt.moneyShort(v)}</div>
</div>
);
})}
</div>
</Card>
<Card>
<div className="serif" style={{fontSize: 22, marginBottom: 18}}>Spend by shop</div>
<div style={{display: "flex", flexDirection: "column", gap: 14}}>
{shopRanked.map(([s, v]) => {
const max = shopRanked[0][1];
return (
<div key={s} style={{display: "flex", alignItems: "center", gap: 12}}>
<div style={{flex: 1.5, fontSize: 13, color: "var(--ink-2)"}}>{s}</div>
<div style={{flex: 2, height: 8, background: "var(--bg-2)", borderRadius: 4, position: "relative"}}>
<div style={{width: `${(v/max)*100}%`, height: "100%", background: "var(--sage)", borderRadius: 4}} />
</div>
<div className="mono" style={{width: 70, textAlign: "right", fontSize: 13}}>{fmt.moneyShort(v)}</div>
</div>
);
})}
</div>
</Card>
</div>
<Card>
<div className="serif" style={{fontSize: 22, marginBottom: 6}}>Inferred consumption heatmap</div>
<div style={{fontSize: 12, color: "var(--ink-3)", marginBottom: 18}}>13 weeks · darker = higher inferred daily use, prorated across each item's lifespan</div>
<Heatmap series={series} />
</Card>
</div>
);
};
const Heatmap = ({series}) => {
const first = new Date(series[0].date);
const offset = first.getDay();
const cells = [];
for (let i = 0; i < offset; i++) cells.push(null);
series.forEach(s => cells.push(s));
while (cells.length < 13 * 7) cells.push(null);
const max = Math.max(...series.map(s => s.grams), 0.001);
const colorFor = (g) => {
if (g === 0) return "var(--bg-3)";
const t = g / max;
return `oklch(${72 - t * 30}% ${0.04 + t * 0.06} 145)`;
};
const days = ["S","M","T","W","T","F","S"];
return (
<div style={{display: "flex", gap: 8, alignItems: "flex-start"}}>
<div style={{display: "flex", flexDirection: "column", gap: 3, paddingTop: 18}}>
{days.map((d, i) => <div key={i} style={{height: 14, fontSize: 9, color: "var(--ink-3)", fontFamily: "var(--mono)"}}>{d}</div>)}
</div>
<div style={{flex: 1}}>
<div style={{display: "grid", gridTemplateColumns: "repeat(13, 1fr)", gap: 3, marginBottom: 4}}>
{Array.from({length: 13}).map((_, w) => {
const firstDay = cells[w * 7];
return <div key={w} style={{fontSize: 9, color: "var(--ink-3)", fontFamily: "var(--mono)", textAlign: "center"}}>{firstDay && new Date(firstDay.date).getDate() <= 7 ? new Date(firstDay.date).toLocaleDateString("en-US", {month: "short"}) : ""}</div>;
})}
</div>
<div style={{display: "grid", gridTemplateRows: "repeat(7, 1fr)", gridAutoFlow: "column", gap: 3}}>
{cells.map((c, i) => (
<div key={i} title={c ? `${c.date}: ${c.grams.toFixed(2)}g` : ""} style={{
aspectRatio: "1",
minHeight: 14,
background: c ? colorFor(c.grams) : "transparent",
borderRadius: 2
}} />
))}
</div>
<div style={{display: "flex", justifyContent: "flex-end", alignItems: "center", gap: 6, marginTop: 14, fontSize: 10, color: "var(--ink-3)", fontFamily: "var(--mono)"}}>
<span>Less</span>
{[0, 0.25, 0.5, 0.75, 1].map(t => (
<div key={t} style={{width: 14, height: 14, background: t === 0 ? "var(--bg-3)" : `oklch(${72 - t * 30}% ${0.04 + t * 0.06} 145)`, borderRadius: 2}} />
))}
<span>More</span>
</div>
</div>
</div>
);
};
// ─── SETTINGS ─────────────────────────────────────────────────────
const SettingsView = ({data, tweaks, onTweakChange}) => {
return (
<div style={{padding: "32px 40px 80px", maxWidth: 800, margin: "0 auto"}}>
<div style={{marginBottom: 24}}>
<div className="smallcaps" style={{color: "var(--ink-3)"}}>Settings</div>
<h1 className="serif" style={{fontSize: 44, margin: "6px 0 0", fontWeight: 500, letterSpacing: "-0.02em"}}>Preferences</h1>
</div>
<Card style={{marginBottom: 14}}>
<div className="serif" style={{fontSize: 22, marginBottom: 16}}>Appearance</div>
<div style={{display: "flex", flexDirection: "column", gap: 14}}>
<SettingRow label="Theme" hint="Light parchment or dim ink">
<div style={{display: "inline-flex", background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", padding: 3}}>
{["light", "dark"].map(t => (
<button key={t} onClick={() => onTweakChange("theme", t)} style={{padding: "6px 14px", fontSize: 12, fontWeight: 500, borderRadius: 6, border: "none", background: tweaks.theme === t ? "var(--surface)" : "transparent", color: tweaks.theme === t ? "var(--ink)" : "var(--ink-3)", cursor: "pointer", textTransform: "capitalize"}}>{t}</button>
))}
</div>
</SettingRow>
<SettingRow label="Dashboard layout" hint="Editorial leans on type; data-dense packs more in">
<div style={{display: "inline-flex", background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", padding: 3}}>
{[["editorial","Editorial"], ["dense","Data-dense"], ["minimal","Minimal"]].map(([k,l]) => (
<button key={k} onClick={() => onTweakChange("dashboard", k)} style={{padding: "6px 14px", fontSize: 12, fontWeight: 500, borderRadius: 6, border: "none", background: tweaks.dashboard === k ? "var(--surface)" : "transparent", color: tweaks.dashboard === k ? "var(--ink)" : "var(--ink-3)", cursor: "pointer"}}>{l}</button>
))}
</div>
</SettingRow>
<SettingRow label="Tone">
<Select value={tweaks.tone} onChange={e => onTweakChange("tone", e.target.value)} style={{...inputStyle, width: 200}}>
<option value="botanical">Botanical (default)</option>
<option value="neutral">Neutral inventory</option>
<option value="discreet">Discreet (code names)</option>
</Select>
</SettingRow>
</div>
</Card>
{/* Shops */}
<Card style={{marginBottom: 14}}>
<div style={{display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14}}>
<div className="serif" style={{fontSize: 22}}>Shops</div>
<Btn variant="ghost" icon="plus">Add shop</Btn>
</div>
<div style={{border: "1px solid var(--line)", borderRadius: "var(--r-md)", overflow: "hidden"}}>
{data.shops.map((s, i) => {
const count = data.products.filter(p => p.shopId === s.id).length;
return (
<div key={s.id} style={{padding: "12px 16px", borderBottom: i < data.shops.length-1 ? "1px solid var(--line)" : "none", display: "flex", alignItems: "center", gap: 12}}>
<div style={{flex: 1}}>
<div style={{fontSize: 14, fontWeight: 500}}>{s.name}</div>
<div style={{fontSize: 11, color: "var(--ink-3)"}}>{s.location}</div>
</div>
<Pill tone="outline">{count} purchase{count===1?"":"s"}</Pill>
<Btn variant="ghost" icon="edit" />
</div>
);
})}
</div>
</Card>
{/* Brands */}
<Card style={{marginBottom: 14}}>
<div style={{display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14}}>
<div className="serif" style={{fontSize: 22}}>Brands</div>
<Btn variant="ghost" icon="plus">Add brand</Btn>
</div>
<div style={{display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 8}}>
{data.brands.map(b => {
const count = data.products.filter(p => p.brandId === b.id).length;
return (
<div key={b.id} style={{padding: "10px 14px", border: "1px solid var(--line)", borderRadius: "var(--r-md)", display: "flex", alignItems: "center", gap: 12}}>
<div style={{flex: 1, fontSize: 13, fontWeight: 500}}>{b.name}</div>
<span className="mono" style={{fontSize: 11, color: "var(--ink-3)"}}>{count}</span>
</div>
);
})}
</div>
</Card>
<Card style={{marginBottom: 14}}>
<div className="serif" style={{fontSize: 22, marginBottom: 16}}>Library</div>
<div style={{display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 16}}>
<Stat label="Active" value={data.products.filter(p=>p.status==="active").length} />
<Stat label="Consumed" value={data.products.filter(p=>p.status==="consumed").length} />
<Stat label="Gone" value={data.products.filter(p=>p.status==="gone").length} />
<Stat label="Bins" value={data.bins.length} />
</div>
<div style={{fontSize: 12, color: "var(--ink-3)"}}>All data is stored locally. Export anytime.</div>
<div style={{display: "flex", gap: 8, marginTop: 12}}>
<Btn variant="secondary">Export CSV</Btn>
<Btn variant="secondary">Export JSON</Btn>
<Btn variant="ghost" style={{color: "var(--terracotta)"}}>Reset all data</Btn>
</div>
</Card>
</div>
);
};
const SettingRow = ({label, hint, children}) => (
<div style={{display: "flex", alignItems: "center", justifyContent: "space-between", paddingBottom: 14, borderBottom: "1px solid var(--line)"}}>
<div style={{flex: 1}}>
<div style={{fontSize: 13, fontWeight: 500}}>{label}</div>
{hint && <div style={{fontSize: 12, color: "var(--ink-3)", marginTop: 2}}>{hint}</div>}
</div>
{children}
</div>
);
Object.assign(window, { AddProductFlow, ConsumeFlow, MarkGoneFlow, AuditFlow, BinsView, ChartsView, SettingsView });
+113
View File
@@ -0,0 +1,113 @@
/* Apothecary / Botanical design tokens
Warm earthy neutrals — parchment, ink, sage, terracotta */
:root {
/* Surfaces — parchment-toned */
--bg: oklch(96% 0.012 80); /* parchment */
--bg-2: oklch(93% 0.014 80); /* slightly darker parchment */
--bg-3: oklch(89% 0.016 78); /* card divider, hover */
--surface: oklch(98% 0.008 82); /* card surface */
--surface-sunken: oklch(91% 0.014 80);
/* Ink — warm near-blacks */
--ink: oklch(22% 0.012 60); /* primary text */
--ink-2: oklch(38% 0.012 60); /* secondary text */
--ink-3: oklch(56% 0.014 65); /* tertiary, captions */
--ink-4: oklch(72% 0.014 70); /* faint, dividers */
/* Lines */
--line: oklch(82% 0.014 75);
--line-strong: oklch(68% 0.016 70);
/* Accents — share chroma 0.08, lightness 52% */
--sage: oklch(52% 0.06 145); /* primary action / good */
--sage-2: oklch(64% 0.05 145);
--sage-soft: oklch(88% 0.03 145);
--terracotta: oklch(58% 0.10 40); /* warning / consumed */
--terracotta-soft: oklch(90% 0.04 40);
--amber: oklch(68% 0.10 75); /* low stock / attention */
--amber-soft: oklch(91% 0.04 75);
--plum: oklch(48% 0.06 340); /* secondary accent */
/* Typography */
--serif: "Cormorant Garamond", "GT Sectra", "Playfair Display", Georgia, serif;
--sans: "Inter", "Söhne", -apple-system, BlinkMacSystemFont, sans-serif;
--mono: "JetBrains Mono", "IBM Plex Mono", ui-monospace, Menlo, monospace;
/* Radii */
--r-sm: 4px;
--r-md: 8px;
--r-lg: 14px;
--r-xl: 20px;
/* Shadow — subtle */
--shadow-sm: 0 1px 2px oklch(20% 0.02 60 / 0.06);
--shadow-md: 0 2px 8px oklch(20% 0.02 60 / 0.08);
--shadow-lg: 0 8px 24px oklch(20% 0.02 60 / 0.10);
}
[data-theme="dark"] {
--bg: oklch(20% 0.012 60);
--bg-2: oklch(23% 0.012 60);
--bg-3: oklch(27% 0.014 65);
--surface: oklch(25% 0.012 60);
--surface-sunken: oklch(18% 0.012 60);
--ink: oklch(94% 0.008 80);
--ink-2: oklch(78% 0.012 75);
--ink-3: oklch(62% 0.014 70);
--ink-4: oklch(46% 0.014 65);
--line: oklch(34% 0.014 65);
--line-strong: oklch(48% 0.016 65);
--sage: oklch(70% 0.07 145);
--sage-2: oklch(60% 0.06 145);
--sage-soft: oklch(32% 0.04 145);
--terracotta: oklch(70% 0.10 40);
--terracotta-soft: oklch(32% 0.05 40);
--amber: oklch(78% 0.10 75);
--amber-soft: oklch(32% 0.05 75);
}
* { box-sizing: border-box; }
html, body {
margin: 0;
padding: 0;
background: var(--bg);
color: var(--ink);
font-family: var(--sans);
font-size: 14px;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
button { font-family: inherit; cursor: pointer; }
input, select, textarea { font-family: inherit; }
/* Subtle parchment texture */
.parchment {
background-image:
radial-gradient(oklch(85% 0.03 75 / 0.15) 1px, transparent 1px),
radial-gradient(oklch(80% 0.03 75 / 0.10) 1px, transparent 1px);
background-size: 24px 24px, 36px 36px;
background-position: 0 0, 12px 18px;
}
/* Utility */
.serif { font-family: var(--serif); font-weight: 500; }
.mono { font-family: var(--mono); font-feature-settings: "ss01", "cv11"; }
.smallcaps {
text-transform: uppercase;
letter-spacing: 0.12em;
font-size: 11px;
font-weight: 500;
}
.hairline { border-top: 1px solid var(--line); }
+419
View File
@@ -0,0 +1,419 @@
// tweaks-panel.jsx
// Reusable Tweaks shell + form-control helpers.
//
// Owns the host protocol (listens for __activate_edit_mode / __deactivate_edit_mode,
// posts __edit_mode_available / __edit_mode_set_keys / __edit_mode_dismissed) so
// individual prototypes don't re-roll it. Ships a consistent set of controls so you
// don't hand-draw <input type="range">, segmented radios, steppers, etc.
//
// Usage (in an HTML file that loads React + Babel):
//
// const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
// "primaryColor": "#D97757",
// "fontSize": 16,
// "density": "regular",
// "dark": false
// }/*EDITMODE-END*/;
//
// function App() {
// const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
// return (
// <div style={{ fontSize: t.fontSize, color: t.primaryColor }}>
// Hello
// <TweaksPanel>
// <TweakSection label="Typography" />
// <TweakSlider label="Font size" value={t.fontSize} min={10} max={32} unit="px"
// onChange={(v) => setTweak('fontSize', v)} />
// <TweakRadio label="Density" value={t.density}
// options={['compact', 'regular', 'comfy']}
// onChange={(v) => setTweak('density', v)} />
// <TweakSection label="Theme" />
// <TweakColor label="Primary" value={t.primaryColor}
// onChange={(v) => setTweak('primaryColor', v)} />
// <TweakToggle label="Dark mode" value={t.dark}
// onChange={(v) => setTweak('dark', v)} />
// </TweaksPanel>
// </div>
// );
// }
//
// ─────────────────────────────────────────────────────────────────────────────
const __TWEAKS_STYLE = `
.twk-panel{position:fixed;right:16px;bottom:16px;z-index:2147483646;width:280px;
max-height:calc(100vh - 32px);display:flex;flex-direction:column;
background:rgba(250,249,247,.78);color:#29261b;
-webkit-backdrop-filter:blur(24px) saturate(160%);backdrop-filter:blur(24px) saturate(160%);
border:.5px solid rgba(255,255,255,.6);border-radius:14px;
box-shadow:0 1px 0 rgba(255,255,255,.5) inset,0 12px 40px rgba(0,0,0,.18);
font:11.5px/1.4 ui-sans-serif,system-ui,-apple-system,sans-serif;overflow:hidden}
.twk-hd{display:flex;align-items:center;justify-content:space-between;
padding:10px 8px 10px 14px;cursor:move;user-select:none}
.twk-hd b{font-size:12px;font-weight:600;letter-spacing:.01em}
.twk-x{appearance:none;border:0;background:transparent;color:rgba(41,38,27,.55);
width:22px;height:22px;border-radius:6px;cursor:default;font-size:13px;line-height:1}
.twk-x:hover{background:rgba(0,0,0,.06);color:#29261b}
.twk-body{padding:2px 14px 14px;display:flex;flex-direction:column;gap:10px;
overflow-y:auto;overflow-x:hidden;min-height:0;
scrollbar-width:thin;scrollbar-color:rgba(0,0,0,.15) transparent}
.twk-body::-webkit-scrollbar{width:8px}
.twk-body::-webkit-scrollbar-track{background:transparent;margin:2px}
.twk-body::-webkit-scrollbar-thumb{background:rgba(0,0,0,.15);border-radius:4px;
border:2px solid transparent;background-clip:content-box}
.twk-body::-webkit-scrollbar-thumb:hover{background:rgba(0,0,0,.25);
border:2px solid transparent;background-clip:content-box}
.twk-row{display:flex;flex-direction:column;gap:5px}
.twk-row-h{flex-direction:row;align-items:center;justify-content:space-between;gap:10px}
.twk-lbl{display:flex;justify-content:space-between;align-items:baseline;
color:rgba(41,38,27,.72)}
.twk-lbl>span:first-child{font-weight:500}
.twk-val{color:rgba(41,38,27,.5);font-variant-numeric:tabular-nums}
.twk-sect{font-size:10px;font-weight:600;letter-spacing:.06em;text-transform:uppercase;
color:rgba(41,38,27,.45);padding:10px 0 0}
.twk-sect:first-child{padding-top:0}
.twk-field{appearance:none;width:100%;height:26px;padding:0 8px;
border:.5px solid rgba(0,0,0,.1);border-radius:7px;
background:rgba(255,255,255,.6);color:inherit;font:inherit;outline:none}
.twk-field:focus{border-color:rgba(0,0,0,.25);background:rgba(255,255,255,.85)}
select.twk-field{padding-right:22px;
background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'><path fill='rgba(0,0,0,.5)' d='M0 0h10L5 6z'/></svg>");
background-repeat:no-repeat;background-position:right 8px center}
.twk-slider{appearance:none;-webkit-appearance:none;width:100%;height:4px;margin:6px 0;
border-radius:999px;background:rgba(0,0,0,.12);outline:none}
.twk-slider::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;
width:14px;height:14px;border-radius:50%;background:#fff;
border:.5px solid rgba(0,0,0,.12);box-shadow:0 1px 3px rgba(0,0,0,.2);cursor:default}
.twk-slider::-moz-range-thumb{width:14px;height:14px;border-radius:50%;
background:#fff;border:.5px solid rgba(0,0,0,.12);box-shadow:0 1px 3px rgba(0,0,0,.2);cursor:default}
.twk-seg{position:relative;display:flex;padding:2px;border-radius:8px;
background:rgba(0,0,0,.06);user-select:none}
.twk-seg-thumb{position:absolute;top:2px;bottom:2px;border-radius:6px;
background:rgba(255,255,255,.9);box-shadow:0 1px 2px rgba(0,0,0,.12);
transition:left .15s cubic-bezier(.3,.7,.4,1),width .15s}
.twk-seg.dragging .twk-seg-thumb{transition:none}
.twk-seg button{appearance:none;position:relative;z-index:1;flex:1;border:0;
background:transparent;color:inherit;font:inherit;font-weight:500;height:22px;
border-radius:6px;cursor:default;padding:0}
.twk-toggle{position:relative;width:32px;height:18px;border:0;border-radius:999px;
background:rgba(0,0,0,.15);transition:background .15s;cursor:default;padding:0}
.twk-toggle[data-on="1"]{background:#34c759}
.twk-toggle i{position:absolute;top:2px;left:2px;width:14px;height:14px;border-radius:50%;
background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.25);transition:transform .15s}
.twk-toggle[data-on="1"] i{transform:translateX(14px)}
.twk-num{display:flex;align-items:center;height:26px;padding:0 0 0 8px;
border:.5px solid rgba(0,0,0,.1);border-radius:7px;background:rgba(255,255,255,.6)}
.twk-num-lbl{font-weight:500;color:rgba(41,38,27,.6);cursor:ew-resize;
user-select:none;padding-right:8px}
.twk-num input{flex:1;min-width:0;height:100%;border:0;background:transparent;
font:inherit;font-variant-numeric:tabular-nums;text-align:right;padding:0 8px 0 0;
outline:none;color:inherit;-moz-appearance:textfield}
.twk-num input::-webkit-inner-spin-button,.twk-num input::-webkit-outer-spin-button{
-webkit-appearance:none;margin:0}
.twk-num-unit{padding-right:8px;color:rgba(41,38,27,.45)}
.twk-btn{appearance:none;height:26px;padding:0 12px;border:0;border-radius:7px;
background:rgba(0,0,0,.78);color:#fff;font:inherit;font-weight:500;cursor:default}
.twk-btn:hover{background:rgba(0,0,0,.88)}
.twk-btn.secondary{background:rgba(0,0,0,.06);color:inherit}
.twk-btn.secondary:hover{background:rgba(0,0,0,.1)}
.twk-swatch{appearance:none;-webkit-appearance:none;width:56px;height:22px;
border:.5px solid rgba(0,0,0,.1);border-radius:6px;padding:0;cursor:default;
background:transparent;flex-shrink:0}
.twk-swatch::-webkit-color-swatch-wrapper{padding:0}
.twk-swatch::-webkit-color-swatch{border:0;border-radius:5.5px}
.twk-swatch::-moz-color-swatch{border:0;border-radius:5.5px}
`;
// ── useTweaks ───────────────────────────────────────────────────────────────
// Single source of truth for tweak values. setTweak persists via the host
// (__edit_mode_set_keys → host rewrites the EDITMODE block on disk).
function useTweaks(defaults) {
const [values, setValues] = React.useState(defaults);
const setTweak = React.useCallback((key, val) => {
setValues((prev) => ({ ...prev, [key]: val }));
window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: val } }, '*');
}, []);
return [values, setTweak];
}
// ── TweaksPanel ─────────────────────────────────────────────────────────────
// Floating shell. Registers the protocol listener BEFORE announcing
// availability — if the announce ran first, the host's activate could land
// before our handler exists and the toolbar toggle would silently no-op.
// The close button posts __edit_mode_dismissed so the host's toolbar toggle
// flips off in lockstep; the host echoes __deactivate_edit_mode back which
// is what actually hides the panel.
function TweaksPanel({ title = 'Tweaks', children }) {
const [open, setOpen] = React.useState(false);
const dragRef = React.useRef(null);
const offsetRef = React.useRef({ x: 16, y: 16 });
const PAD = 16;
const clampToViewport = React.useCallback(() => {
const panel = dragRef.current;
if (!panel) return;
const w = panel.offsetWidth, h = panel.offsetHeight;
const maxRight = Math.max(PAD, window.innerWidth - w - PAD);
const maxBottom = Math.max(PAD, window.innerHeight - h - PAD);
offsetRef.current = {
x: Math.min(maxRight, Math.max(PAD, offsetRef.current.x)),
y: Math.min(maxBottom, Math.max(PAD, offsetRef.current.y)),
};
panel.style.right = offsetRef.current.x + 'px';
panel.style.bottom = offsetRef.current.y + 'px';
}, []);
React.useEffect(() => {
if (!open) return;
clampToViewport();
if (typeof ResizeObserver === 'undefined') {
window.addEventListener('resize', clampToViewport);
return () => window.removeEventListener('resize', clampToViewport);
}
const ro = new ResizeObserver(clampToViewport);
ro.observe(document.documentElement);
return () => ro.disconnect();
}, [open, clampToViewport]);
React.useEffect(() => {
const onMsg = (e) => {
const t = e?.data?.type;
if (t === '__activate_edit_mode') setOpen(true);
else if (t === '__deactivate_edit_mode') setOpen(false);
};
window.addEventListener('message', onMsg);
window.parent.postMessage({ type: '__edit_mode_available' }, '*');
return () => window.removeEventListener('message', onMsg);
}, []);
const dismiss = () => {
setOpen(false);
window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*');
};
const onDragStart = (e) => {
const panel = dragRef.current;
if (!panel) return;
const r = panel.getBoundingClientRect();
const sx = e.clientX, sy = e.clientY;
const startRight = window.innerWidth - r.right;
const startBottom = window.innerHeight - r.bottom;
const move = (ev) => {
offsetRef.current = {
x: startRight - (ev.clientX - sx),
y: startBottom - (ev.clientY - sy),
};
clampToViewport();
};
const up = () => {
window.removeEventListener('mousemove', move);
window.removeEventListener('mouseup', up);
};
window.addEventListener('mousemove', move);
window.addEventListener('mouseup', up);
};
if (!open) return null;
return (
<>
<style>{__TWEAKS_STYLE}</style>
<div ref={dragRef} className="twk-panel"
style={{ right: offsetRef.current.x, bottom: offsetRef.current.y }}>
<div className="twk-hd" onMouseDown={onDragStart}>
<b>{title}</b>
<button className="twk-x" aria-label="Close tweaks"
onMouseDown={(e) => e.stopPropagation()}
onClick={dismiss}></button>
</div>
<div className="twk-body">{children}</div>
</div>
</>
);
}
// ── Layout helpers ──────────────────────────────────────────────────────────
function TweakSection({ label, children }) {
return (
<>
<div className="twk-sect">{label}</div>
{children}
</>
);
}
function TweakRow({ label, value, children, inline = false }) {
return (
<div className={inline ? 'twk-row twk-row-h' : 'twk-row'}>
<div className="twk-lbl">
<span>{label}</span>
{value != null && <span className="twk-val">{value}</span>}
</div>
{children}
</div>
);
}
// ── Controls ────────────────────────────────────────────────────────────────
function TweakSlider({ label, value, min = 0, max = 100, step = 1, unit = '', onChange }) {
return (
<TweakRow label={label} value={`${value}${unit}`}>
<input type="range" className="twk-slider" min={min} max={max} step={step}
value={value} onChange={(e) => onChange(Number(e.target.value))} />
</TweakRow>
);
}
function TweakToggle({ label, value, onChange }) {
return (
<div className="twk-row twk-row-h">
<div className="twk-lbl"><span>{label}</span></div>
<button type="button" className="twk-toggle" data-on={value ? '1' : '0'}
role="switch" aria-checked={!!value}
onClick={() => onChange(!value)}><i /></button>
</div>
);
}
function TweakRadio({ label, value, options, onChange }) {
const trackRef = React.useRef(null);
const [dragging, setDragging] = React.useState(false);
const opts = options.map((o) => (typeof o === 'object' ? o : { value: o, label: o }));
const idx = Math.max(0, opts.findIndex((o) => o.value === value));
const n = opts.length;
// The active value is read by pointer-move handlers attached for the lifetime
// of a drag — ref it so a stale closure doesn't fire onChange for every move.
const valueRef = React.useRef(value);
valueRef.current = value;
const segAt = (clientX) => {
const r = trackRef.current.getBoundingClientRect();
const inner = r.width - 4;
const i = Math.floor(((clientX - r.left - 2) / inner) * n);
return opts[Math.max(0, Math.min(n - 1, i))].value;
};
const onPointerDown = (e) => {
setDragging(true);
const v0 = segAt(e.clientX);
if (v0 !== valueRef.current) onChange(v0);
const move = (ev) => {
if (!trackRef.current) return;
const v = segAt(ev.clientX);
if (v !== valueRef.current) onChange(v);
};
const up = () => {
setDragging(false);
window.removeEventListener('pointermove', move);
window.removeEventListener('pointerup', up);
};
window.addEventListener('pointermove', move);
window.addEventListener('pointerup', up);
};
return (
<TweakRow label={label}>
<div ref={trackRef} role="radiogroup" onPointerDown={onPointerDown}
className={dragging ? 'twk-seg dragging' : 'twk-seg'}>
<div className="twk-seg-thumb"
style={{ left: `calc(2px + ${idx} * (100% - 4px) / ${n})`,
width: `calc((100% - 4px) / ${n})` }} />
{opts.map((o) => (
<button key={o.value} type="button" role="radio" aria-checked={o.value === value}>
{o.label}
</button>
))}
</div>
</TweakRow>
);
}
function TweakSelect({ label, value, options, onChange }) {
return (
<TweakRow label={label}>
<select className="twk-field" value={value} onChange={(e) => onChange(e.target.value)}>
{options.map((o) => {
const v = typeof o === 'object' ? o.value : o;
const l = typeof o === 'object' ? o.label : o;
return <option key={v} value={v}>{l}</option>;
})}
</select>
</TweakRow>
);
}
function TweakText({ label, value, placeholder, onChange }) {
return (
<TweakRow label={label}>
<input className="twk-field" type="text" value={value} placeholder={placeholder}
onChange={(e) => onChange(e.target.value)} />
</TweakRow>
);
}
function TweakNumber({ label, value, min, max, step = 1, unit = '', onChange }) {
const clamp = (n) => {
if (min != null && n < min) return min;
if (max != null && n > max) return max;
return n;
};
const startRef = React.useRef({ x: 0, val: 0 });
const onScrubStart = (e) => {
e.preventDefault();
startRef.current = { x: e.clientX, val: value };
const decimals = (String(step).split('.')[1] || '').length;
const move = (ev) => {
const dx = ev.clientX - startRef.current.x;
const raw = startRef.current.val + dx * step;
const snapped = Math.round(raw / step) * step;
onChange(clamp(Number(snapped.toFixed(decimals))));
};
const up = () => {
window.removeEventListener('pointermove', move);
window.removeEventListener('pointerup', up);
};
window.addEventListener('pointermove', move);
window.addEventListener('pointerup', up);
};
return (
<div className="twk-num">
<span className="twk-num-lbl" onPointerDown={onScrubStart}>{label}</span>
<input type="number" value={value} min={min} max={max} step={step}
onChange={(e) => onChange(clamp(Number(e.target.value)))} />
{unit && <span className="twk-num-unit">{unit}</span>}
</div>
);
}
function TweakColor({ label, value, onChange }) {
return (
<div className="twk-row twk-row-h">
<div className="twk-lbl"><span>{label}</span></div>
<input type="color" className="twk-swatch" value={value}
onChange={(e) => onChange(e.target.value)} />
</div>
);
}
function TweakButton({ label, onClick, secondary = false }) {
return (
<button type="button" className={secondary ? 'twk-btn secondary' : 'twk-btn'}
onClick={onClick}>{label}</button>
);
}
Object.assign(window, {
useTweaks, TweaksPanel, TweakSection, TweakRow,
TweakSlider, TweakToggle, TweakRadio, TweakSelect,
TweakText, TweakNumber, TweakColor, TweakButton,
});