diff --git a/backend/src/db/bookkeeping.ts b/backend/src/db/bookkeeping.ts index 5de3d36d..2f77abe2 100644 --- a/backend/src/db/bookkeeping.ts +++ b/backend/src/db/bookkeeping.ts @@ -14,7 +14,7 @@ import { cleanItem } from "./cleanItem"; import { TABLE_BOOKKEEPING } from "./tableNames"; import { classifyMandatoryPayment } from "../finance/mandatoryPayments"; import { isOwnerWithdrawalReportExempt } from "../finance/ownerPay"; -import { deriveInventoryItems, inventoryItemId, inventoryItemSeed } from "../finance/inventory"; +import { deriveInventoryItems, dismissedInventorySeedId, inventoryItemId, inventoryItemSeed } from "../finance/inventory"; import { BOOKKEEPING_AUDIT_PARTITION_PREFIX, BOOKKEEPING_AUDIT_STORAGE_VERSION, @@ -355,14 +355,17 @@ export async function putBookkeepingTransactionWithItems( * physical purchase shows up in the inventory without a manual scan. Runs * after the ledger write and is intentionally not atomic with it: entries are * keyed by transaction/allocation seed and existing entries are left - * untouched, so manual inventory edits survive and a failed sync is repaired - * by the next "Scan ledger". + * untouched, so manual inventory edits survive. Seeds the operator dismissed + * (removed item, or a manual split replacing the automatic entry) never come + * back; the monthly report sweep repairs anything else that failed. */ export async function syncInventoryForTransactions( client: DynamoDBDocumentClient, transactions: readonly Record[], ) { for (const candidate of deriveInventoryItems(transactions)) { + const seed = inventoryItemSeed(candidate.transactionId, candidate.allocationId); + if (await getBookkeepingItem(client, "inventoryDismissed", dismissedInventorySeedId(seed))) continue; const entry: Record = { id: inventoryItemId(candidate.transactionId, candidate.allocationId), transactionId: candidate.transactionId, @@ -375,16 +378,83 @@ export async function syncInventoryForTransactions( currency: candidate.currency, amountEur: candidate.amountEur, status: "in-use", + usage: "active", }; await putBookkeepingItem( client, "inventory", Object.fromEntries(Object.entries(entry).filter(([, child]) => child !== undefined)), - inventoryItemSeed(candidate.transactionId, candidate.allocationId), + seed, ); } } +/** + * Catch-up sweep over the whole ledger: create inventory entries for physical + * purchases that have none yet. Respects dismissed seeds, so operator + * deletions and manual splits are never undone. Runs when the monthly + * report archive is generated and via POST /api/bookkeeping/inventory/sweep. + */ +export async function sweepInventory( + client: DynamoDBDocumentClient, +): Promise<{ matched: number; created: Record[] }> { + const [transactions, existing, dismissed] = await Promise.all([ + listTransactions(client), + listBookkeepingItems(client, "inventory"), + listBookkeepingItems(client, "inventoryDismissed"), + ]); + const known = new Set([ + ...dismissed.map((item) => String(item.seed || "")), + ...existing.map((item) => + inventoryItemSeed(String(item.transactionId || ""), typeof item.allocationId === "string" ? item.allocationId : undefined), + ), + ]); + const candidates = deriveInventoryItems(transactions).filter( + (candidate) => !known.has(inventoryItemSeed(candidate.transactionId, candidate.allocationId)), + ); + const created: Record[] = []; + for (const candidate of candidates) { + const seed = inventoryItemSeed(candidate.transactionId, candidate.allocationId); + const entry: Record = { + id: inventoryItemId(candidate.transactionId, candidate.allocationId), + transactionId: candidate.transactionId, + allocationId: candidate.allocationId, + name: candidate.name, + type: candidate.type, + vendor: candidate.vendor, + acquisitionDate: candidate.acquisitionDate, + amount: candidate.amount, + currency: candidate.currency, + amountEur: candidate.amountEur, + status: "in-use", + usage: "active", + }; + const { item, duplicate } = await putBookkeepingItem( + client, + "inventory", + Object.fromEntries(Object.entries(entry).filter(([, child]) => child !== undefined)), + seed, + ); + if (!duplicate) created.push(item); + } + return { matched: candidates.length, created }; +} + +/** Record that a (transaction, allocation) seed must not be re-derived. */ +export async function dismissInventorySeed( + client: DynamoDBDocumentClient, + seed: string, + context: { transactionId: string; allocationId?: string; manual?: boolean }, +) { + await putBookkeepingItem(client, "inventoryDismissed", { + id: dismissedInventorySeedId(seed), + seed, + transactionId: context.transactionId, + ...(context.allocationId !== undefined ? { allocationId: context.allocationId } : {}), + ...(context.manual ? { manual: true } : {}), + }, dismissedInventorySeedId(seed)); +} + async function getBookkeepingItemRaw( client: DynamoDBDocumentClient, kind: string, diff --git a/backend/src/finance/inventory.ts b/backend/src/finance/inventory.ts index 277668e2..74dea337 100644 --- a/backend/src/finance/inventory.ts +++ b/backend/src/finance/inventory.ts @@ -14,12 +14,17 @@ export const INVENTORY_TYPES = [ ] as const; export type InventoryType = (typeof INVENTORY_TYPES)[number]; -export const INVENTORY_STATUSES = ["in-use", "disposed"] as const; +export const INVENTORY_STATUSES = ["in-use", "disposed", "returned"] as const; export type InventoryStatus = (typeof INVENTORY_STATUSES)[number]; -// A disposal is the exit record for an inventory item: sold off or -// decommissioned (scrapped, recycled, given away without payment). -export const INVENTORY_DISPOSAL_KINDS = ["sold", "decommissioned"] as const; +// Whether the item is actively used day to day or sits idle: still owned, +// still on the balance, just not in daily use. +export const INVENTORY_USAGES = ["active", "idle"] as const; +export type InventoryUsage = (typeof INVENTORY_USAGES)[number]; + +// An exit record for an inventory item: sold off, decommissioned (scrapped, +// recycled, given away without payment), or returned to the vendor. +export const INVENTORY_DISPOSAL_KINDS = ["sold", "decommissioned", "returned"] as const; export type InventoryDisposalKind = (typeof INVENTORY_DISPOSAL_KINDS)[number]; export type InventoryDisposal = { @@ -84,6 +89,13 @@ export function inventoryItemId(transactionId: string, allocationId?: string) { return createHash("sha256").update(inventoryItemSeed(transactionId, allocationId)).digest("hex"); } +export type InventoryImage = { url: string; caption?: string }; + +/** Id of the tombstone that keeps a dismissed (transaction, allocation) seed out of future derivations. */ +export function dismissedInventorySeedId(seed: string) { + return createHash("sha256").update(`inventory-dismissed:${seed}`).digest("hex"); +} + type TransactionLike = { id?: unknown; voidStatus?: unknown; @@ -226,21 +238,19 @@ export function inventorySourceRecord( } /** - * Disposal records drive the item status: any record means disposed, and the - * disposed date is the latest record's date. Returns the writable fields for - * updateBookkeepingItem; `disposedDate: undefined` removes the stale stamp - * when the last record is gone. + * Exit records drive the item status: the latest record by date wins, so a + * returned item that is later sold flips to disposed. Returns the writable + * fields for updateBookkeepingItem; the date fields are always present (with + * undefined clearing the stale stamp when the records no longer imply them). */ export function deriveInventoryDisposalState( disposals: readonly InventoryDisposal[], -): { disposals: InventoryDisposal[]; status: InventoryStatus; disposedDate?: string } { - const disposed = disposals.length > 0; +): { disposals: InventoryDisposal[]; status: InventoryStatus; disposedDate?: string; returnedDate?: string } { const records = [...disposals]; - return { - disposals: records, - status: disposed ? "disposed" : "in-use", - disposedDate: disposed - ? records.reduce((latest, record) => (record.date > latest ? record.date : latest), records[0].date) - : undefined, - }; + if (!records.length) + return { disposals: records, status: "in-use", disposedDate: undefined, returnedDate: undefined }; + const latest = records.reduce((a, b) => (b.date > a.date ? b : a), records[0]); + if (latest.kind === "returned") + return { disposals: records, status: "returned", returnedDate: latest.date, disposedDate: undefined }; + return { disposals: records, status: "disposed", disposedDate: latest.date, returnedDate: undefined }; } diff --git a/backend/src/routes/bookkeepingInventory.ts b/backend/src/routes/bookkeepingInventory.ts index bfb60013..3b16cbe1 100644 --- a/backend/src/routes/bookkeepingInventory.ts +++ b/backend/src/routes/bookkeepingInventory.ts @@ -4,20 +4,21 @@ import type { LambdaEvent, LambdaResponse } from "../types"; import { BookkeepingItemLockedError, deleteBookkeepingItem, + dismissInventorySeed, getBookkeepingItem, listBookkeepingItems, listTransactions, putBookkeepingItem, + sweepInventory, updateBookkeepingItem, } from "../db/bookkeeping"; import { json, parse } from "./bookkeepingShared"; import { realDate } from "../sponsorCrm/model"; import { - DEFAULT_INVENTORY_FROM_YEAR, INVENTORY_DISPOSAL_KINDS, INVENTORY_TYPES, + INVENTORY_USAGES, deriveInventoryDisposalState, - deriveInventoryItems, inventoryItemId, inventoryItemSeed, inventorySourceRecord, @@ -45,12 +46,30 @@ function validateInventoryEdit(input: Record): string[] { errors.push("name"); if (input.type !== undefined && !INVENTORY_TYPES.includes(String(input.type) as InventoryType)) errors.push("type"); - // Status and disposedDate follow the disposal records; editing them + if (input.usage !== undefined && !INVENTORY_USAGES.includes(String(input.usage) as (typeof INVENTORY_USAGES)[number])) + errors.push("usage"); + // Status and exit dates follow the disposal records; editing them // directly is rejected so clients cannot fight the derivation. if (input.status !== undefined) errors.push("status"); if (input.disposedDate !== undefined) errors.push("disposedDate"); + if (input.returnedDate !== undefined) errors.push("returnedDate"); if (input.notes !== undefined && input.notes !== null && (typeof input.notes !== "string" || input.notes.length > 2000)) errors.push("notes"); + if (input.addImage !== undefined) { + const image = input.addImage as Record; + if (!image || typeof image !== "object" || Array.isArray(image)) + errors.push("addImage"); + else { + if (typeof image.url !== "string" || !/^https?:\/\/\S+$/.test(image.url) || image.url.length > 1000) + errors.push("addImage.url"); + if (image.caption !== undefined && image.caption !== null + && (typeof image.caption !== "string" || image.caption.length > 200)) + errors.push("addImage.caption"); + } + } + if (input.removeImageUrl !== undefined + && (typeof input.removeImageUrl !== "string" || !input.removeImageUrl.trim())) + errors.push("removeImageUrl"); return errors; } @@ -112,51 +131,78 @@ export async function handleBookkeepingInventoryRoutes( return json(200, { items: items.map(publicInventoryItem) }); } - if (path === "/api/bookkeeping/inventory/import" && method === "POST") { - const body = parse(event.body || null) || {}; - const fromYear = Number(body.fromYear ?? DEFAULT_INVENTORY_FROM_YEAR); - if (!Number.isSafeInteger(fromYear) || fromYear < 2000 || fromYear > 2100) - return json(400, { error: "Invalid fromYear", fields: ["fromYear"] }); - const apply = body.apply === true; - const [transactions, existing] = await Promise.all([ - listTransactions(client), - listBookkeepingItems(client, "inventory"), - ]); - const known = new Set( - existing.map((item) => - inventoryItemSeed(String(item.transactionId || ""), typeof item.allocationId === "string" ? item.allocationId : undefined), - ), - ); - const candidates = deriveInventoryItems(transactions, { fromYear }).filter( - (candidate) => !known.has(inventoryItemSeed(candidate.transactionId, candidate.allocationId)), - ); - const created: Record[] = []; - if (apply) { - for (const candidate of candidates) { - const { item, duplicate } = await putBookkeepingItem(client, "inventory", stripUndefined({ - id: inventoryItemId(candidate.transactionId, candidate.allocationId), - transactionId: candidate.transactionId, - allocationId: candidate.allocationId, - name: candidate.name, - type: candidate.type, - vendor: candidate.vendor, - acquisitionDate: candidate.acquisitionDate, - amount: candidate.amount, - currency: candidate.currency, - amountEur: candidate.amountEur, - status: "in-use", - }), inventoryItemSeed(candidate.transactionId, candidate.allocationId)); - if (!duplicate) created.push(publicInventoryItem(item)); - } - } - return json(apply ? 201 : 200, { - dryRun: !apply, - matched: candidates.length, - created: created.length, - items: apply ? created : candidates, + if (path === "/api/bookkeeping/inventory/sweep" && method === "POST") { + const result = await sweepInventory(client); + return json(201, { + matched: result.matched, + created: result.created.length, + items: result.created.map(publicInventoryItem), }); } + // Record an inventory item for a purchase picked from the ledger. One + // invoice can yield several items (one payment, two things), and every + // item keeps the same invoice as its source record. + if (path === "/api/bookkeeping/inventory/items" && method === "POST") { + const body = parse(event.body || null); + if (!body) return json(400, { error: "Invalid JSON" }); + const transactionId = typeof body.transactionId === "string" ? body.transactionId.trim() : ""; + if (!transactionId) return json(400, { error: "transactionId is required", fields: ["transactionId"] }); + const transaction = await getBookkeepingItem(client, "bookkeeping", transactionId); + if (!transaction || transaction.voidStatus === "voided") + return json(404, { error: "Transaction not found", fields: ["transactionId"] }); + const allocationId = typeof body.allocationId === "string" && body.allocationId.trim() + ? body.allocationId.trim() + : undefined; + const source = inventorySourceRecord({ transactionId, allocationId }, transaction); + if (allocationId && !source) + return json(400, { error: "Unknown allocation row", fields: ["allocationId"] }); + const name = typeof body.name === "string" && body.name.trim() + ? body.name.trim() + : String(source?.description || ""); + if (!name || name.length > 300) + return json(400, { error: "name is required", fields: ["name"] }); + if (body.type !== undefined && !INVENTORY_TYPES.includes(String(body.type) as InventoryType)) + return json(400, { error: "Invalid inventory item", fields: ["type"] }); + if (body.usage !== undefined && !INVENTORY_USAGES.includes(String(body.usage) as (typeof INVENTORY_USAGES)[number])) + return json(400, { error: "Invalid inventory item", fields: ["usage"] }); + if (body.notes !== undefined && body.notes !== null + && (typeof body.notes !== "string" || body.notes.length > 2000)) + return json(400, { error: "Invalid inventory item", fields: ["notes"] }); + if (!allocationId) { + // A payment without invoice rows derives one automatic transaction-level + // item; recording items by hand replaces it. Dismiss that seed so the + // automatic entry never comes back alongside the hand-recorded ones, + // but refuse while the automatic item still exists. + const existing = await listBookkeepingItems(client, "inventory"); + const clash = existing.find((item) => + String(item.transactionId || "") === transactionId && !item.allocationId && !item.manual); + if (clash) + return json(409, { error: "This invoice already has an inventory item; remove that one first to record its items separately." }); + await dismissInventorySeed(client, inventoryItemSeed(transactionId), { transactionId }); + } + const { item } = await putBookkeepingItem(client, "inventory", stripUndefined({ + id: inventoryItemId(transactionId, allocationId ?? `manual:${randomUUID()}`), + transactionId, + allocationId, + manual: true, + name, + type: typeof body.type === "string" ? String(body.type) : "other", + vendor: String(source?.counterparty ?? ""), + acquisitionDate: String(source?.date ?? ""), + amount: source?.amount, + currency: source?.currency, + amountEur: source?.amountEur, + status: "in-use", + usage: typeof body.usage === "string" ? String(body.usage) : "active", + ...(body.notes !== undefined && body.notes !== null && String(body.notes).trim() + ? { notes: String(body.notes).trim() } + : {}), + })); + const [enriched] = await enrichWithSource(client, [publicInventoryItem(item)]); + return json(201, enriched); + } + const item = path.match(/^\/api\/bookkeeping\/inventory\/([^/]+)$/); if (item) { const id = decodeURIComponent(item[1]); @@ -182,8 +228,27 @@ export async function handleBookkeepingInventoryRoutes( const value: Record = {}; if (body.name !== undefined) value.name = String(body.name).trim(); if (body.type !== undefined) value.type = String(body.type); + if (body.usage !== undefined) value.usage = String(body.usage); if (body.notes !== undefined) value.notes = body.notes === null || !String(body.notes).trim() ? undefined : String(body.notes); + if (body.addImage !== undefined || body.removeImageUrl !== undefined) { + const existingImages = await getBookkeepingItem(client, "inventory", id); + if (!existingImages) return json(404, { error: "Not found" }); + const current = (Array.isArray(existingImages.images) ? existingImages.images : []) + .filter((image): image is Record => Boolean(image) && typeof image === "object"); + const removeUrl = typeof body.removeImageUrl === "string" ? body.removeImageUrl : ""; + let next = current.filter((image) => image.url !== removeUrl); + if (body.addImage !== undefined) { + if (next.length >= 8) + return json(409, { error: "An item keeps at most 8 pictures." }); + const image = body.addImage as Record; + const record: Record = { url: String(image.url) }; + if (typeof image.caption === "string" && image.caption.trim()) + record.caption = image.caption.trim(); + next = [...next, record]; + } + value.images = next; + } if (body.disposal !== undefined || body.removeDisposalId !== undefined) { const existing = await getBookkeepingItem(client, "inventory", id); if (!existing) return json(404, { error: "Not found" }); @@ -234,9 +299,26 @@ export async function handleBookkeepingInventoryRoutes( } } if (method === "DELETE") { + let removed: Record | null = null; try { - const existing = await deleteBookkeepingItem(client, "inventory", id); - return existing ? { statusCode: 204, headers: {}, body: "" } : json(404, { error: "Not found" }); + removed = await deleteBookkeepingItem(client, "inventory", id); + if (removed) { + // Tombstone the seed so the sweep and later ledger writes never + // re-derive this item. Removal is deliberate (API or CLI only, no + // UI affordance), and the tombstone makes it stick. + const transactionId = String(removed.transactionId || ""); + const allocationId = typeof removed.allocationId === "string" ? removed.allocationId : undefined; + await dismissInventorySeed( + client, + inventoryItemSeed(transactionId, allocationId), + { + transactionId, + ...(allocationId !== undefined ? { allocationId } : {}), + ...(removed.manual ? { manual: true } : {}), + }, + ); + } + return removed ? { statusCode: 204, headers: {}, body: "" } : json(404, { error: "Not found" }); } catch (error) { if (error instanceof BookkeepingItemLockedError) return json(409, { error: "Inventory item changed; refresh and retry." }); diff --git a/backend/src/routes/bookkeepingReports.ts b/backend/src/routes/bookkeepingReports.ts index f2ff18d1..f8d6326c 100644 --- a/backend/src/routes/bookkeepingReports.ts +++ b/backend/src/routes/bookkeepingReports.ts @@ -14,6 +14,7 @@ import { markReportGenerated, putBookkeepingItem, removeDocumentReportReference, + sweepInventory, type BookkeepingItem, } from "../db/bookkeeping"; import { preflightOrganizations } from '../vies/service'; @@ -255,6 +256,9 @@ export async function handleBookkeepingReportRoutes( if (error instanceof MonthGateError) return json(409, { reportPeriod: month, error: error.message, blockers: error.blockers }); throw error; } + // Generating the pack is the monthly bookkeeping landmark: catch the + // inventory up on every physical purchase seen since the last run. + const inventorySweep = await sweepInventory(client); if (report.archiveDocumentId) { const doc = await getBookkeepingItem( client, @@ -270,7 +274,7 @@ export async function handleBookkeepingReportRoutes( }), { expiresIn: 300 }, ); - return json(200, { reportPeriod: month, downloadUrl: url, expiresIn: 300, duplicate: true, vatPreflight: await vatPreflightSummary(client) }); + return json(200, { reportPeriod: month, downloadUrl: url, expiresIn: 300, duplicate: true, inventoryItemsAdded: inventorySweep.created.length, vatPreflight: await vatPreflightSummary(client) }); } } const transactionIds = Array.isArray(report.transactionIds) @@ -422,7 +426,7 @@ export async function handleBookkeepingReportRoutes( }), { expiresIn: 300 }, ); - return json(201, { reportPeriod: month, downloadUrl: url, expiresIn: 300, vatPreflight: await vatPreflightSummary(client) }); + return json(201, { reportPeriod: month, downloadUrl: url, expiresIn: 300, inventoryItemsAdded: inventorySweep.created.length, vatPreflight: await vatPreflightSummary(client) }); } return null; } diff --git a/backend/tests/bookkeeping-inventory.test.ts b/backend/tests/bookkeeping-inventory.test.ts index e316d06b..f02d8f62 100644 --- a/backend/tests/bookkeeping-inventory.test.ts +++ b/backend/tests/bookkeeping-inventory.test.ts @@ -3,7 +3,7 @@ import assert from 'node:assert'; import { handler } from '../src/handler'; import { getClient } from '../src/db/client'; import { startLocal, stopLocal, createTables } from '../scripts/local-dynamodb'; -import { putBookkeepingItem, putBookkeepingTransactionWithItems, updateBookkeepingTransaction, getBookkeepingItem } from '../src/db/bookkeeping'; +import { putBookkeepingItem, putBookkeepingTransactionWithItems, sweepInventory, updateBookkeepingTransaction, getBookkeepingItem } from '../src/db/bookkeeping'; import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; import { classifyPhysicalItem, @@ -101,7 +101,7 @@ describe('inventory API', () => { }); after(stopLocal); - it('imports physical purchases from the ledger, idempotently', async () => { + it('sweeps physical purchases from the ledger, idempotently', async () => { await putBookkeepingItem(client, 'bookkeeping', { ...transaction({ description: 'Laptop', amount: '1813.58' }), id: 'inv-tx-laptop' }); await putBookkeepingItem(client, 'bookkeeping', { ...transaction({ description: 'Mailchimp Standard plan' }), id: 'inv-tx-subscription' }); await putBookkeepingItem(client, 'bookkeeping', { ...transaction({ @@ -112,22 +112,20 @@ describe('inventory API', () => { ], }), id: 'inv-tx-split' }); - const dry = JSON.parse((await invoke('POST', '/api/bookkeeping/inventory/import', {})).body); - assert.equal(dry.dryRun, true); - assert.equal(dry.matched, 3); - assert.equal(dry.created, 0); - const listed = JSON.parse((await invoke('GET', '/api/bookkeeping/inventory')).body); - assert.deepEqual(listed.items, []); - - const applied = JSON.parse((await invoke('POST', '/api/bookkeeping/inventory/import', { apply: true })).body); - assert.equal(applied.created, 3); - const names = applied.items.map((item: any) => item.name).sort(); + const first = await sweepInventory(client); + assert.equal(first.matched, 3); + assert.equal(first.created.length, 3); + const names = first.created.map((item) => String(item.name)).sort(); assert.deepEqual(names, ['Laptop', 'Lenovo ThinkCentre M920q', 'UGREEN video capture card']); - assert.ok(applied.items.every((item: any) => item.status === 'in-use')); + assert.ok(first.created.every((item) => item.status === 'in-use' && item.usage === 'active')); - const again = JSON.parse((await invoke('POST', '/api/bookkeeping/inventory/import', { apply: true })).body); + const again = await sweepInventory(client); assert.equal(again.matched, 0); - assert.equal(again.created, 0); + assert.equal(again.created.length, 0); + + const swept = JSON.parse((await invoke('POST', '/api/bookkeeping/inventory/sweep', {})).body); + assert.equal(swept.created, 0); + assert.deepEqual(swept.items, []); const stored = JSON.parse((await invoke('GET', '/api/bookkeeping/inventory')).body); assert.equal(stored.items.length, 3); assert.ok(stored.items.every((item: any) => item.transactionId && item.acquisitionDate)); @@ -161,6 +159,12 @@ describe('inventory API', () => { const statusPut = await invoke('PUT', `/api/bookkeeping/inventory/${item.id}`, { status: 'disposed' }); assert.equal(statusPut.statusCode, 400); assert.deepEqual(JSON.parse(statusPut.body).fields, ['status']); + const returnedDatePut = await invoke('PUT', `/api/bookkeeping/inventory/${item.id}`, { returnedDate: '2027-01-01' }); + assert.equal(returnedDatePut.statusCode, 400); + assert.deepEqual(JSON.parse(returnedDatePut.body).fields, ['returnedDate']); + const usagePut = await invoke('PUT', `/api/bookkeeping/inventory/${item.id}`, { usage: 'sometimes' }); + assert.equal(usagePut.statusCode, 400); + assert.deepEqual(JSON.parse(usagePut.body).fields, ['usage']); // Ledger-seeded fields are not editable; naming none is a read-back. const noop = await invoke('PUT', `/api/bookkeeping/inventory/${item.id}`, { amount: '1.00' }); assert.equal(noop.statusCode, 200); @@ -221,6 +225,107 @@ describe('inventory API', () => { assert.equal(later.disposals.length, 2); }); + it('records a return, and a later sale takes over the status', async () => { + const items = JSON.parse((await invoke('GET', '/api/bookkeeping/inventory')).body).items; + const item = items.find((candidate: any) => candidate.name === 'Lenovo ThinkCentre M920q'); + const returned = JSON.parse((await invoke('PUT', `/api/bookkeeping/inventory/${item.id}`, { + disposal: { kind: 'returned', date: '2026-12-01', notes: 'refund received' }, + })).body); + assert.equal(returned.status, 'returned'); + assert.equal(returned.returnedDate, '2026-12-01'); + assert.equal(returned.disposedDate, undefined); + assert.equal(returned.disposals[0].kind, 'returned'); + assert.equal(returned.disposals[0].proceeds, undefined); + + const sold = JSON.parse((await invoke('PUT', `/api/bookkeeping/inventory/${item.id}`, { + disposal: { kind: 'sold', date: '2027-01-15', proceeds: '100' }, + })).body); + assert.equal(sold.status, 'disposed'); + assert.equal(sold.disposedDate, '2027-01-15'); + assert.equal(sold.returnedDate, undefined); + assert.equal(sold.disposals.length, 2); + }); + + it('tracks whether an item is actively used', async () => { + const items = JSON.parse((await invoke('GET', '/api/bookkeeping/inventory')).body).items; + const item = items.find((candidate: any) => candidate.name === 'Laptop'); + const idle = JSON.parse((await invoke('PUT', `/api/bookkeeping/inventory/${item.id}`, { usage: 'idle' })).body); + assert.equal(idle.usage, 'idle'); + assert.equal(idle.status, 'in-use'); + const active = JSON.parse((await invoke('PUT', `/api/bookkeeping/inventory/${item.id}`, { usage: 'active' })).body); + assert.equal(active.usage, 'active'); + }); + + it('keeps pictures on an item', async () => { + const items = JSON.parse((await invoke('GET', '/api/bookkeeping/inventory')).body).items; + const item = items.find((candidate: any) => candidate.name === 'Laptop'); + const bad = await invoke('PUT', `/api/bookkeeping/inventory/${item.id}`, { addImage: { url: 'not-a-url' } }); + assert.equal(bad.statusCode, 400); + assert.deepEqual(JSON.parse(bad.body).fields, ['addImage.url']); + + const first = JSON.parse((await invoke('PUT', `/api/bookkeeping/inventory/${item.id}`, { + addImage: { url: 'https://m.media-amazon.com/images/front.jpg', caption: 'front' }, + })).body); + assert.equal(first.images.length, 1); + assert.equal(first.images[0].url, 'https://m.media-amazon.com/images/front.jpg'); + assert.equal(first.images[0].caption, 'front'); + + const second = JSON.parse((await invoke('PUT', `/api/bookkeeping/inventory/${item.id}`, { + addImage: { url: 'https://example.com/back.jpg' }, + })).body); + assert.equal(second.images.length, 2); + + const removed = JSON.parse((await invoke('PUT', `/api/bookkeeping/inventory/${item.id}`, { + removeImageUrl: 'https://m.media-amazon.com/images/front.jpg', + })).body); + assert.equal(removed.images.length, 1); + assert.equal(removed.images[0].url, 'https://example.com/back.jpg'); + }); + + it('records items by hand from an invoice and splits one payment into several', async () => { + await putBookkeepingTransactionWithItems( + client, + { ...transaction({ description: 'Headphones and webcam', amount: '150.00' }), id: 'inv-tx-duo' }, + [], + ); + // The automatic transaction-level item exists, so hand-recording is refused. + const denied = await invoke('POST', '/api/bookkeeping/inventory/items', { transactionId: 'inv-tx-duo' }); + assert.equal(denied.statusCode, 409); + + const unknown = await invoke('POST', '/api/bookkeeping/inventory/items', { transactionId: 'inv-tx-missing' }); + assert.equal(unknown.statusCode, 404); + const badType = await invoke('POST', '/api/bookkeeping/inventory/items', { transactionId: 'inv-tx-duo', name: 'X', type: 'vehicle' }); + assert.equal(badType.statusCode, 400); + + // Remove the automatic item, then record the two real items it stands for. + const listed = JSON.parse((await invoke('GET', '/api/bookkeeping/inventory')).body); + const automatic = listed.items.find((candidate: any) => candidate.transactionId === 'inv-tx-duo'); + const removed = await invoke('DELETE', `/api/bookkeeping/inventory/${automatic.id}`); + assert.equal(removed.statusCode, 204); + + const one = JSON.parse((await invoke('POST', '/api/bookkeeping/inventory/items', { + transactionId: 'inv-tx-duo', name: 'Sennheiser HD 450BT', type: 'audio', + })).body); + assert.equal(one.manual, true); + assert.equal(one.status, 'in-use'); + assert.equal(one.usage, 'active'); + assert.equal(one.source.transactionId, 'inv-tx-duo'); + assert.equal(one.source.amount, '150.00'); + assert.equal(one.amount, '150.00'); + const two = JSON.parse((await invoke('POST', '/api/bookkeeping/inventory/items', { + transactionId: 'inv-tx-duo', name: 'Logitech C920', type: 'accessory', notes: 'studio camera', + })).body); + assert.equal(two.notes, 'studio camera'); + assert.notEqual(one.id, two.id); + + // Both items share the invoice, and the sweep never re-adds the automatic one. + const after = JSON.parse((await invoke('GET', '/api/bookkeeping/inventory')).body); + const duo = after.items.filter((candidate: any) => candidate.transactionId === 'inv-tx-duo'); + assert.equal(duo.length, 2); + const swept = await sweepInventory(client); + assert.equal(swept.created.some((candidate) => candidate.transactionId === 'inv-tx-duo'), false); + }); + it('rejects a stale optimistic-concurrency version with 409', async () => { const items = JSON.parse((await invoke('GET', '/api/bookkeeping/inventory')).body).items; const item = items[0]; diff --git a/cli/src/commands/bookkeeping.mjs b/cli/src/commands/bookkeeping.mjs index 804db558..dc79407d 100644 --- a/cli/src/commands/bookkeeping.mjs +++ b/cli/src/commands/bookkeeping.mjs @@ -53,12 +53,12 @@ Usage its date, amount and provider, so the row details can suggest a match. --retry also re-reads documents an earlier run could not read. - dataops bookkeeping inventory-import [--since YYYY] [--apply] - Find physical purchases (computers, phones, audio, furniture, accessories) - among ledger expenses and add them to the inventory. One payment that - bought several things adds one item per invoice allocation row. Idempotent: - purchases already in the inventory are skipped. Dry-run by default; --apply - adds the items. --since sets the first year (default 2022). + dataops bookkeeping inventory-sync + Catch the inventory up with the ledger: add items for physical purchases + (computers, phones, audio, furniture, accessories) that have none yet. One + payment that bought several things adds one item per invoice allocation + row. Idempotent; items you removed or recorded by hand are never + re-added. The monthly report pack runs the same sweep automatically. To void or restore a duplicate ledger row during month reconciliation (admin only): dataops reconcile void-ledger --period YYYY-MM --reason TEXT --duplicate-of [--yes] @@ -448,28 +448,20 @@ export async function set(args, io) { return result; } -export async function inventoryImport(args, io) { +export async function inventorySync(args, io) { const api = apiFor(args); - const fromYear = args.since ? String(args.since).slice(0, 4) : undefined; - if (fromYear && !/^\d{4}$/.test(fromYear)) - throw new UsageError("--since needs a four-digit year, e.g. --since 2022."); - const result = await api.post("/api/bookkeeping/inventory/import", { - ...(fromYear ? { fromYear: Number(fromYear) } : {}), - apply: Boolean(args.apply), - }); + const result = await api.post("/api/bookkeeping/inventory/sweep", {}); const outcome = { - mode: args.apply ? "apply" : "dry-run", matched: result.matched, created: result.created, items: result.items, }; if (!args.json) { - io.print(`${outcome.mode}: ${result.created} new ${result.created === 1 ? "item" : "items"} from ${result.matched} physical ${result.matched === 1 ? "purchase" : "purchases"}`); + io.print(`${result.created} new ${result.created === 1 ? "item" : "items"} from ${result.matched} physical ${result.matched === 1 ? "purchase" : "purchases"}`); for (const item of result.items) io.print(` ${item.acquisitionDate} ${String(item.type || "").padEnd(10)} ${item.name}${item.allocationId ? " (allocation)" : ""}`); - if (!args.apply) io.print("Dry run. Pass --apply to add these to the inventory."); } return outcome; } -export const commands = { show, set, sync, classify, facts, "add-income": addIncome, "inventory-import": inventoryImport }; +export const commands = { show, set, sync, classify, facts, "add-income": addIncome, "inventory-sync": inventorySync }; diff --git a/frontend/src/styles/bookkeeping.css b/frontend/src/styles/bookkeeping.css index b61c3c01..9cf133e9 100644 --- a/frontend/src/styles/bookkeeping.css +++ b/frontend/src/styles/bookkeeping.css @@ -354,6 +354,8 @@ tr.bk-month__totals-row > th { .bk-inv-status > * + * { margin-top: var(--dk-space-1); } .bk-inv-badge { font-size: var(--dk-text-xs); color: var(--dk-text-secondary); } .bk-inv-badge--disposed { color: var(--dk-danger-text); } +.bk-inv-badge--returned { color: var(--dk-text-secondary); font-style: italic; } +.bk-inv-usage { font-size: var(--dk-text-xs); } /* Dispose reads as text until hovered: the row already carries enough chrome (type, note, remove) without a boxed button on every line. */ .bk-inv-status .bk-inv-dispose { padding: 0; border: none; background: none; color: var(--dk-text-secondary); } @@ -366,6 +368,35 @@ tr.bk-month__totals-row > th { .bk-inv-disposal-remove:hover { color: var(--dk-danger-text); } .bk-inv-dispose { display: flex; flex-wrap: wrap; align-items: center; gap: var(--dk-space-3); font-size: var(--dk-text-sm); } .bk-inv-dispose label { display: inline-flex; align-items: center; gap: var(--dk-space-2); color: var(--dk-text-secondary); } +/* The "Add picture…" affordance reads like the provenance link next to it. */ +.bk-inv-picture { padding: 0; border: none; background: none; color: var(--dk-text-secondary); font-size: var(--dk-text-xs); cursor: pointer; } +.bk-inv-picture:hover { color: var(--dk-accent-hover); text-decoration: underline; } +.bk-inv-images { display: flex; flex-wrap: wrap; align-items: center; gap: var(--dk-space-2); font-size: var(--dk-text-xs); color: var(--dk-text-secondary); } +.bk-inv-image { display: inline-flex; align-items: center; gap: var(--dk-space-1); } +.bk-inv-thumb { height: 44px; max-width: 88px; border-radius: var(--dk-radius-sm); object-fit: cover; } +.bk-inv-image-remove { color: var(--dk-text-secondary); } +.bk-inv-image-remove:hover { color: var(--dk-danger-text); } +.bk-inv-image-form { display: inline-flex; flex-wrap: wrap; align-items: center; gap: var(--dk-space-2); } +.bk-inv-image-form label { display: inline-flex; align-items: center; gap: var(--dk-space-1); color: var(--dk-text-secondary); } +.bk-inv-image-form .bk-inv-image-url { width: 16em; } + +/* Add-to-inventory picker inside its own dialog. */ +.bk-add-dialog { max-width: 640px; width: calc(100vw - 2 * var(--dk-space-4)); } +.bk-add-picker { display: flex; flex-direction: column; gap: var(--dk-space-2); } +.bk-add-search { width: 100%; } +.bk-add-options { display: flex; flex-direction: column; max-height: 50vh; overflow-y: auto; } +.bk-add-option { display: grid; grid-template-columns: 5.5rem 1fr auto 5.5rem; gap: var(--dk-space-2); align-items: baseline; + padding: var(--dk-space-2); border: none; background: none; text-align: left; cursor: pointer; + border-radius: var(--dk-radius-sm); font-size: var(--dk-text-sm); } +.bk-add-option:hover { background: var(--dk-bg-hover); } +.bk-add-date { color: var(--dk-text-secondary); font-variant-numeric: tabular-nums; } +.bk-add-what { color: var(--dk-text-primary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.bk-add-vendor { color: var(--dk-text-secondary); } +.bk-add-amount { color: var(--dk-text-primary); text-align: right; font-variant-numeric: tabular-nums; } +.bk-add-invoice { font-size: var(--dk-text-sm); color: var(--dk-text-secondary); } +.bk-add-picker label { display: flex; flex-direction: column; gap: var(--dk-space-1); color: var(--dk-text-secondary); font-size: var(--dk-text-sm); } +.bk-add-actions { display: flex; gap: var(--dk-space-2); } +.bk-add-loading { color: var(--dk-text-secondary); font-size: var(--dk-text-sm); } @media (max-width: 820px) { .bk-inv-what { min-width: 10em; } diff --git a/frontend/src/surfaces/finance/bookkeeping-inventory.js b/frontend/src/surfaces/finance/bookkeeping-inventory.js index 809bd0d7..0ead3a02 100644 --- a/frontend/src/surfaces/finance/bookkeeping-inventory.js +++ b/frontend/src/surfaces/finance/bookkeeping-inventory.js @@ -1,22 +1,25 @@ -// Inventory: physical purchases derived from the ledger, so the balance shows -// what hardware, phones, audio and furniture the company owns. The view is a -// table over /api/bookkeeping/inventory; "Scan ledger" runs the import that -// turns 2022+ expenses (and per-invoice allocation rows) into items. Every -// item links back to the ledger record it came from, and selling or -// decommissioning writes a disposal record so exits are documented too. +// Inventory: physical purchases derived from bookkeeping invoices, so the +// balance shows what hardware, phones, audio and furniture the company owns. +// The view is a table over /api/bookkeeping/inventory; new physical purchases +// land automatically, and "Add" records an item for a picked invoice. Every +// item links back to the invoice it came from, and returns, sales and +// decommissioning write exit records so items leaving the balance are +// documented too. import { html } from "./shared.js"; import { formatAmount } from "./bookkeeping-format.js"; -const TYPES = ["computer", "phone", "audio", "furniture", "accessory", "other"]; -const DISPOSAL_KINDS = ["sold", "decommissioned"]; -const DISPOSAL_LABELS = { sold: "sold", decommissioned: "decommissioned" }; +export const INVENTORY_TYPES = ["computer", "phone", "audio", "furniture", "accessory", "other"]; +const EXIT_KINDS = ["sold", "decommissioned", "returned"]; +const EXIT_LABELS = { sold: "sold", decommissioned: "decommissioned", returned: "returned" }; +const USAGES = ["active", "idle"]; export function createBookkeepingInventory({ surface, api, escapeHtml, safeAction, setStatus, todayIsoDate, openTransaction }) { const host = surface.querySelector("[data-inventory]"); - const scanButton = surface.querySelector("[data-inventory-scan]"); let items = []; - // The in-row disposal form: one item records its exit at a time. - let disposeForm = null; + // The in-row exit form (return / sale / decommission) and the in-row + // picture form: one item records one of them at a time. + let exitForm = null; + let imageForm = null; const today = () => todayIsoDate?.() || new Date().toISOString().slice(0, 10); const eurValue = (item) => { @@ -29,20 +32,23 @@ export function createBookkeepingInventory({ surface, api, escapeHtml, safeActio : formatAmount(eurValue(item), "EUR"); const sorted = () => [...items].sort((a, b) => String(b.acquisitionDate || "").localeCompare(String(a.acquisitionDate || ""))); - const disposalsOf = (item) => (Array.isArray(item.disposals) ? item.disposals : []); + const exitsOf = (item) => (Array.isArray(item.disposals) ? item.disposals : []); + const imagesOf = (item) => (Array.isArray(item.images) ? item.images : []); - // One quiet provenance line under the item name: the vendor and a link to - // the ledger record the item was derived from. Clicking anywhere on the - // record (not its controls) opens that ledger record too. + // One quiet provenance line under the item name: the vendor, a link to + // the invoice the item came from, and the picture affordance. Clicking + // anywhere on the record (not its controls) opens that invoice too. function metaMarkup(item) { const source = item.source; const parts = [ item.vendor ? html`${escapeHtml(item.vendor)}` : "", source ? html`` : "", - ].filter(Boolean); - if (!parts.length) return ""; + title="Open the invoice from ${escapeHtml(source.date || item.acquisitionDate || "")}" + aria-label="Open the invoice for ${escapeHtml(item.name)}">↳ invoice: ${escapeHtml(source.description || item.name)}` : "", + html``, + ]; return html`${parts.join(html` · `)}`; } @@ -50,46 +56,84 @@ export function createBookkeepingInventory({ surface, api, escapeHtml, safeActio if (item.status === "disposed") { return html`disposed${item.disposedDate ? html` · ${escapeHtml(item.disposedDate)}` : ""}`; } - return html`in use - + `; } - function disposalsMarkup(item) { - const records = disposalsOf(item); + function exitsMarkup(item) { + const records = exitsOf(item); if (!records.length) return ""; - return html` + return html` ${records.map((record) => html` - ${DISPOSAL_LABELS[record.kind] || escapeHtml(String(record.kind))} ${escapeHtml(String(record.date))} + ${EXIT_LABELS[record.kind] || escapeHtml(String(record.kind))} ${escapeHtml(String(record.date))} ${record.proceeds ? html` · proceeds ${formatAmount(String(record.proceeds), String(record.currency || "EUR"))}` : ""} ${record.notes ? html` · ${escapeHtml(String(record.notes))}` : ""} + title="Remove this exit record" aria-label="Remove the ${escapeHtml(String(record.kind))} record">✕ + `).join("")} + `; + } + + function imageFormMarkup(item) { + if (imageForm?.itemId !== item.id) return ""; + return html` + + + + + `; + } + + function imagesMarkup(item) { + const images = imagesOf(item); + if (!images.length && imageForm?.itemId !== item.id) return ""; + return html` + ${images.map((image) => html` + ${escapeHtml(String(image.caption || item.name))} + ${image.caption ? html`${escapeHtml(String(image.caption))}` : ""} + `).join("")} + ${imageFormMarkup(item)} `; } - function disposeFormMarkup(item) { - if (disposeForm?.itemId !== item.id) return ""; - const sold = disposeForm.kind === "sold"; - return html` + function exitFormMarkup(item) { + if (exitForm?.itemId !== item.id) return ""; + const sold = exitForm.kind === "sold"; + return html` - - ${sold ? html` + ${sold ? html`` : ""} - + `; } function rowMarkup(item) { - const disposed = item.status === "disposed"; - return html` + const exited = item.status !== "in-use"; + return html` ${escapeHtml(item.acquisitionDate || "")} ${escapeHtml(item.name)} @@ -97,7 +141,7 @@ export function createBookkeepingInventory({ surface, api, escapeHtml, safeActio ${amountText(item)} @@ -106,10 +150,6 @@ export function createBookkeepingInventory({ surface, api, escapeHtml, safeActio - - - `; } @@ -118,8 +158,8 @@ export function createBookkeepingInventory({ surface, api, escapeHtml, safeActio const year = yearSelect?.value || ""; const visible = sorted().filter((item) => !year || String(item.acquisitionDate || "").startsWith(year)); const years = [...new Set(sorted().map((item) => String(item.acquisitionDate || "").slice(0, 4)).filter(Boolean))]; - const inUse = visible.filter((item) => item.status !== "disposed"); - const total = inUse.reduce((sum, item) => sum + (eurValue(item) || 0), 0); + const onBalance = visible.filter((item) => item.status === "in-use"); + const total = onBalance.reduce((sum, item) => sum + (eurValue(item) || 0), 0); if (yearSelect) { const previous = yearSelect.value; yearSelect.innerHTML = ['', @@ -129,19 +169,19 @@ export function createBookkeepingInventory({ surface, api, escapeHtml, safeActio if (!items.length) { host.innerHTML = html`

No inventory yet

-

Scan the ledger to find physical purchases since 2022.

+

Physical purchases land here automatically; use Add to record one from an invoice.

`; return; } host.innerHTML = html`

${visible.length === items.length ? `${items.length} items` : `${visible.length} of ${items.length} items`} · - in use: ${formatAmount(total.toFixed(2), "EUR")} + on balance: ${formatAmount(total.toFixed(2), "EUR")}

- + - ${visible.map((item) => rowMarkup(item) + disposeFormMarkup(item) + disposalsMarkup(item)).join("")} + ${visible.map((item) => rowMarkup(item) + exitFormMarkup(item) + exitsMarkup(item) + imagesMarkup(item)).join("")}
AcquiredItemTypePaidStatusNote
AcquiredItemTypePaidStatusNote
`; } @@ -155,14 +195,16 @@ export function createBookkeepingInventory({ surface, api, escapeHtml, safeActio return saved; } - function submitDisposal() { - if (!disposeForm) return; - const form = disposeForm; + const EXIT_MESSAGES = { sold: "Recorded the sale.", decommissioned: "Recorded the decommissioning.", returned: "Recorded the return." }; + + function submitExit() { + if (!exitForm) return; + const form = exitForm; if (!form.date) { - setStatus("Pick a disposal date."); + setStatus("Pick a date for the record."); return; } - disposeForm = null; + exitForm = null; safeAction(async () => { await save(form.itemId, { disposal: { kind: form.kind, @@ -170,8 +212,26 @@ export function createBookkeepingInventory({ surface, api, escapeHtml, safeActio proceeds: form.kind === "sold" ? String(form.proceeds || "").trim() : undefined, notes: String(form.notes || "").trim() || undefined, } }); - setStatus(form.kind === "sold" ? "Recorded the sale." : "Recorded the decommissioning."); - }, "Could not record the disposal"); + setStatus(EXIT_MESSAGES[form.kind] || "Recorded the exit."); + }, "Could not record the exit"); + } + + function submitImage() { + if (!imageForm) return; + const form = imageForm; + const url = String(form.url || "").trim(); + if (!/^https?:\/\/\S+$/.test(url)) { + setStatus("Paste a picture link starting with http(s)://."); + return; + } + imageForm = null; + safeAction(async () => { + await save(form.itemId, { addImage: { + url, + ...(String(form.caption || "").trim() ? { caption: String(form.caption).trim() } : {}), + } }); + setStatus("Picture attached."); + }, "Could not attach the picture"); } host.addEventListener("change", (event) => { @@ -179,12 +239,12 @@ export function createBookkeepingInventory({ surface, api, escapeHtml, safeActio render(); return; } - const disposalField = event.target.closest("[data-inv-disposal]"); - if (disposalField) { + const exitField = event.target.closest("[data-inv-disposal]"); + if (exitField) { // The kind decides whether proceeds apply; other form fields only // update the draft, they never re-render mid-typing. - if (disposeForm && disposalField.dataset.invDisposal === "kind") { - disposeForm.kind = String(disposalField.value || "sold"); + if (exitForm && exitField.dataset.invDisposal === "kind") { + exitForm.kind = String(exitField.value || "sold"); render(); } return; @@ -198,6 +258,7 @@ export function createBookkeepingInventory({ surface, api, escapeHtml, safeActio field.disabled = true; safeAction(async () => { if (field.dataset.invField === "type") await save(item.id, { type: value }); + else if (field.dataset.invField === "usage") await save(item.id, { usage: value || "active" }); else if (field.dataset.invField === "notes") await save(item.id, { notes: value || null }); field.disabled = false; setStatus("Inventory updated."); @@ -212,17 +273,24 @@ export function createBookkeepingInventory({ surface, api, escapeHtml, safeActio } const disposeButton = event.target.closest("[data-inv-dispose]"); if (disposeButton) { - disposeForm = { itemId: disposeButton.dataset.invDispose, kind: "sold", date: today(), proceeds: "", notes: "" }; + imageForm = null; + exitForm = { + itemId: disposeButton.dataset.invDispose, + kind: disposeButton.dataset.invKind === "returned" ? "returned" : "sold", + date: today(), + proceeds: "", + notes: "", + }; render(); return; } if (event.target.closest("[data-inv-disposal-cancel]")) { - disposeForm = null; + exitForm = null; render(); return; } if (event.target.closest("[data-inv-disposal-save]")) { - submitDisposal(); + submitExit(); return; } const removeDisposal = event.target.closest("[data-inv-disposal-remove]"); @@ -232,23 +300,38 @@ export function createBookkeepingInventory({ surface, api, escapeHtml, safeActio if (!item) return; safeAction(async () => { await save(item.id, { removeDisposalId: removeDisposal.dataset.invDisposalRemove }); - setStatus("Disposal record removed."); - }, "Could not remove the disposal record"); + setStatus("Exit record removed."); + }, "Could not remove the exit record"); + return; + } + const imageAdd = event.target.closest("[data-inv-image-add]"); + if (imageAdd) { + exitForm = null; + imageForm = { itemId: imageAdd.dataset.invImageAdd, url: "", caption: "" }; + render(); return; } - const button = event.target.closest("[data-inv-remove]"); - if (button) { - const item = items.find((candidate) => candidate.id === button.dataset.invRemove); - if (!item || !globalThis.confirm?.(`Remove ${item.name} from the inventory?`)) return; + if (event.target.closest("[data-inv-image-cancel]")) { + imageForm = null; + render(); + return; + } + if (event.target.closest("[data-inv-image-save]")) { + submitImage(); + return; + } + const imageRemove = event.target.closest("[data-inv-image-remove]"); + if (imageRemove) { + const row = imageRemove.closest("[data-inv]"); + const item = items.find((candidate) => candidate.id === row?.dataset.inv); + if (!item) return; safeAction(async () => { - await api(`/inventory/${encodeURIComponent(item.id)}`, { method: "DELETE" }); - items = items.filter((candidate) => candidate.id !== item.id); - render(); - setStatus(`Removed ${item.name} from the inventory.`); - }, "Could not remove the inventory item"); + await save(item.id, { removeImageUrl: imageRemove.dataset.invImageRemove }); + setStatus("Picture removed."); + }, "Could not remove the picture"); return; } - // The record itself opens the ledger entry it was derived from; clicks + // The record itself opens the invoice it was derived from; clicks // inside its controls (type select, note input) stay edits. if (event.target.closest("input, select, button, a")) return; const row = event.target.closest("[data-inv]"); @@ -259,28 +342,14 @@ export function createBookkeepingInventory({ surface, api, escapeHtml, safeActio host.addEventListener("input", (event) => { if (event.target.closest("[data-inv-year]")) render(); - const disposalField = event.target.closest("[data-inv-disposal]"); - if (disposalField && disposeForm && disposalField.dataset.invDisposal !== "kind") - disposeForm[disposalField.dataset.invDisposal] = disposalField.value; + const exitField = event.target.closest("[data-inv-disposal]"); + if (exitField && exitForm && exitField.dataset.invDisposal !== "kind") + exitForm[exitField.dataset.invDisposal] = exitField.value; + const imageField = event.target.closest("[data-inv-image]"); + if (imageField && imageForm) + imageForm[imageField.dataset.invImage] = imageField.value; }); - scanButton.addEventListener("click", () => - safeAction(async () => { - scanButton.disabled = true; - try { - const result = await api("/inventory/import", { - method: "POST", - body: JSON.stringify({ apply: true }), - }); - setStatus(result.created - ? `Added ${result.created} item${result.created === 1 ? "" : "s"} from the ledger.` - : `No new physical purchases (${result.matched} matched, all already present).`); - await load(); - } finally { - scanButton.disabled = false; - } - }, "Could not scan the ledger")); - async function load() { const result = await api("/inventory"); items = result.items || []; diff --git a/frontend/src/surfaces/finance/inventory.js b/frontend/src/surfaces/finance/inventory.js index 8a007b24..9fd78dd8 100644 --- a/frontend/src/surfaces/finance/inventory.js +++ b/frontend/src/surfaces/finance/inventory.js @@ -1,9 +1,10 @@ // Inventory surface: the company's physical property at /invertory, fully -// separate from the bookkeeping ledger surface. Items derive from ledger -// expenses (2022+), each row keeps its provenance link, and the record dialog -// fetches the original ledger transaction directly instead of reaching into -// the bookkeeping surface. -import { createBookkeepingInventory } from "./bookkeeping-inventory.js"; +// separate from the bookkeeping ledger surface. Items derive from bookkeeping +// invoices (2022+), each row keeps its provenance link, and the record dialog +// fetches the original invoice transaction directly instead of reaching into +// the bookkeeping surface. "Add" records an item by hand for a picked +// invoice — one invoice can yield several items that share it. +import { createBookkeepingInventory, INVENTORY_TYPES } from "./bookkeeping-inventory.js"; import { createBookkeepingTransactionModal } from "./bookkeeping-transaction-modal.js"; import { INVOICE_SOURCE_PREFIX, @@ -17,13 +18,21 @@ import { html } from "./shared.js"; export function inventorySurfaceMarkup() { return html`

Inventory

- +
-

Physical purchases from the ledger since 2022 — computers, phones, audio, furniture. Scan the ledger after new expenses land.

+

Physical purchases from bookkeeping invoices since 2022 — computers, phones, + audio, furniture. New purchases land here automatically; Add records one by hand.

Loading inventory…
- `; + + +
+

Add to inventory

+

Pick the invoice the item was bought on.

+
+
+
`; } export function createInventorySurface(context) { @@ -138,7 +147,7 @@ export function createInventorySurface(context) { selectedId = id; transactionModal.render(record); } catch (error) { - setStatus(`Could not open the ledger record: ${error.message}`); + setStatus(`Could not open the invoice: ${error.message}`); } } @@ -151,6 +160,142 @@ export function createInventorySurface(context) { todayIsoDate, openTransaction, }); + + // The Add picker: pick an invoice from the ledger list, then describe the + // item it stands for. The form stays open so one payment that bought two + // things records both, sharing the invoice as their source. + const addDialog = surface.querySelector("[data-inventory-add-dialog]"); + const addPicker = addDialog.querySelector("[data-add-picker]"); + const addHint = addDialog.querySelector("[data-add-hint]"); + let addState = null; + const money = (value) => formatAmount(String(Math.abs(Number(value || 0))), "EUR"); + + function renderAddPicker() { + if (!addState?.transactions) { + addPicker.innerHTML = html`

Loading invoices…

`; + return; + } + if (!addState.transaction) { + const query = String(addState.query || "").trim().toLowerCase(); + const matches = addState.transactions + .filter((tx) => !query || `${tx.description || ""} ${tx.counterparty || ""}`.toLowerCase().includes(query)) + .slice(0, 50); + addHint.textContent = "Pick the invoice the item was bought on."; + addPicker.innerHTML = html` + ${matches.length ? html`
${matches.map((tx) => html``).join("")}
` + : html`

No invoice matches.

`}`; + // Re-rendering on every keystroke replaces the input; put the caret + // back so typing continues at the end. + const search = addPicker.querySelector("[data-add-search]"); + if (search) { + search.focus(); + const end = search.value.length; + search.setSelectionRange(end, end); + } + return; + } + const tx = addState.transaction; + addHint.textContent = "Describe the item this invoice bought. Keep the form open to record another item from the same invoice."; + addPicker.innerHTML = html`

${escapeHtml(String(tx.paidDate || tx.transactionDate || ""))} · + ${escapeHtml(String(tx.counterparty || ""))} · ${money(tx.amountEur || tx.amount)} — + ${escapeHtml(String(tx.description || "(no description)"))}

+ + + +
+ + + +
`; + } + + async function addFromInvoice() { + const tx = addState?.transaction; + if (!tx) return; + const name = String(addState.name || "").trim(); + const type = String(addState.type || ""); + const notes = String(addState.notes || "").trim(); + // No name means the backend names the item from the invoice description. + await api("/inventory/items", { + method: "POST", + body: JSON.stringify({ + transactionId: tx.id, + ...(name ? { name } : {}), + ...(type ? { type } : {}), + ...(notes ? { notes } : {}), + }), + }); + setStatus(`Added ${name || tx.description || "the item"} to the inventory.`); + addState.name = ""; + addState.notes = ""; + renderAddPicker(); + await inventory.renderInventory(); + } + + addPicker.addEventListener("click", (event) => { + const option = event.target.closest("[data-add-tx]"); + if (option) { + addState.transaction = addState.transactions.find((tx) => tx.id === option.dataset.addTx) || null; + renderAddPicker(); + return; + } + if (event.target.closest("[data-add-back]")) { + addState.transaction = null; + renderAddPicker(); + return; + } + if (event.target.closest("[data-add-close]")) { + addDialog.close(); + return; + } + if (event.target.closest("[data-add-save]")) { + void safeAction(addFromInvoice, "Could not add the item"); + } + }); + + addPicker.addEventListener("input", (event) => { + const search = event.target.closest("[data-add-search]"); + if (search) { + addState.query = search.value; + renderAddPicker(); + return; + } + const field = event.target.closest("[data-add-field]"); + if (field && addState) addState[field.dataset.addField] = field.value; + }); + + surface.querySelector("[data-inventory-add]").addEventListener("click", () => { + addState = addState && addState.transactions ? addState : { transactions: null, query: "", transaction: null, name: "", type: "", notes: "" }; + addState.transaction = null; + renderAddPicker(); + addDialog.showModal(); + if (!addState.transactions) { + void safeAction(async () => { + const result = await api("/transactions"); + if (addState) addState.transactions = (result.items || []) + .filter((tx) => tx.entryType === "expense" && tx.voidStatus !== "voided"); + renderAddPicker(); + }, "Could not load invoices"); + } + }); + await inventory.renderInventory(); } diff --git a/frontend/test/bookkeeping-inventory-nav.test.mjs b/frontend/test/bookkeeping-inventory-nav.test.mjs index 2ba46d22..96ae323d 100644 --- a/frontend/test/bookkeeping-inventory-nav.test.mjs +++ b/frontend/test/bookkeeping-inventory-nav.test.mjs @@ -50,9 +50,12 @@ test("the bookkeeping surface has no inventory section left", () => { assert.doesNotMatch(markup, /data-inventory\b/); }); -test("the inventory surface owns its scan action, table host and record dialog", () => { +test("the inventory surface owns its add action, table host and dialogs", () => { const markup = inventorySurfaceMarkup(); - assert.match(markup, /data-inventory-scan/); + assert.match(markup, /data-inventory-add\b/); + assert.doesNotMatch(markup, /data-inventory-scan/); + assert.doesNotMatch(markup, /Scan ledger/); assert.match(markup, /data-inventory\b/); assert.match(markup, /]*data-inventory-transaction-dialog/); + assert.match(markup, /]*data-inventory-add-dialog/); }); diff --git a/frontend/test/bookkeeping-inventory.test.mjs b/frontend/test/bookkeeping-inventory.test.mjs index 8b6eff61..8dd8a952 100644 --- a/frontend/test/bookkeeping-inventory.test.mjs +++ b/frontend/test/bookkeeping-inventory.test.mjs @@ -12,12 +12,12 @@ function fakeHost() { }; } -const node = (dataset, row) => ({ dataset, closest: (probe) => (row && probe === "[data-inv]" ? row : null) }); +const row = (id) => ({ dataset: { inv: id }, closest: (probe) => (probe === "[data-inv]" ? { dataset: { inv: id } } : null) }); const laptop = { id: "inv-laptop", transactionId: "tx-1", name: "Laptop", type: "computer", vendor: "Amazon", acquisitionDate: "2026-03-19", amount: "1813.58", - currency: "EUR", amountEur: "1813.58", status: "in-use", + currency: "EUR", amountEur: "1813.58", status: "in-use", usage: "active", source: { transactionId: "tx-1", description: "MacBook Pro 14", counterparty: "Amazon", date: "2026-03-19", amount: "1813.58", currency: "EUR", amountEur: "1813.58", @@ -30,14 +30,10 @@ const headset = { disposals: [{ id: "d-1", kind: "sold", date: "2026-09-01", proceeds: "20.00", currency: "EUR", notes: "eBay" }], }; -function mount({ inventoryPages, putResponses = [], deletes = [] } = {}) { +function mount({ inventoryPages, putResponses = [] } = {}) { const host = fakeHost(); - const scanButton = { disabled: false, addEventListener(name, handler) { host.listeners.set(`scan:${name}`, handler); } }; const surface = { - querySelector: (selector) => - selector === "[data-inventory]" ? host - : selector === "[data-inventory-scan]" ? scanButton - : null, + querySelector: (selector) => (selector === "[data-inventory]" ? host : null), }; const status = []; const calls = []; @@ -47,8 +43,6 @@ function mount({ inventoryPages, putResponses = [], deletes = [] } = {}) { calls.push([path, options.method || "GET", options.body ? JSON.parse(options.body) : undefined]); if (path === "/inventory") return { items: inventoryPages[Math.min(page++, inventoryPages.length - 1)] }; if (path.startsWith("/inventory/") && options.method === "PUT") return putResponses.shift() ?? { ...laptop, ...JSON.parse(options.body) }; - if (path.startsWith("/inventory/") && options.method === "DELETE") { deletes.push(path); return undefined; } - if (path === "/inventory/import") return { dryRun: false, matched: 1, created: 1, items: [laptop] }; throw new Error(`unexpected ${options.method || "GET"} ${path}`); }; const errors = []; @@ -61,54 +55,50 @@ function mount({ inventoryPages, putResponses = [], deletes = [] } = {}) { todayIsoDate: () => "2037-03-15", openTransaction: (id) => opened.push(id), }); - // A click on a node whose closest() answers every probed selector. - const click = (probes) => - host.listeners.get("click")({ target: { closest: (probe) => probes[probe] ?? null } }); - const change = (dataset, value) => - host.listeners.get("change")({ target: { - closest: (probe) => (probe === "[data-inv-disposal]" ? { dataset, value } : null), - } }); - const type = (dataset, value) => - host.listeners.get("input")({ target: { - closest: (probe) => (probe === "[data-inv-disposal]" ? { dataset, value } : null), - } }); - return { view, host, calls, status, errors, opened, click, change, type, scanClick: () => host.listeners.get("scan:click")() }; + // A target whose closest() answers every probed selector from one map. + const dispatch = (name, probes, extra = {}) => + host.listeners.get(name)({ target: { closest: (probe) => probes[probe] ?? null, ...extra } }); + const click = (probes) => dispatch("click", probes); + const probe = (selector, value) => ({ [selector]: { dataset: {}, value } }); + const change = (selector, dataset, value, rowId) => dispatch("change", { + "[data-inv-year]": null, + [selector]: { dataset, value, closest: (p) => (p === "[data-inv]" && rowId ? row(rowId) : null) }, + }); + const type = (selector, dataset, value) => dispatch("input", { [selector]: { dataset, value } }); + return { view, host, calls, status, errors, opened, click, change, type, probe }; } const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); -test("loads the inventory and renders items with the in-use total", async () => { +test("loads the inventory and renders items with the on-balance total", async () => { const { view, host } = mount({ inventoryPages: [[laptop, headset]] }); await view.renderInventory(); assert.match(host.innerHTML, /Laptop/); assert.match(host.innerHTML, /Stereo Headset/); assert.match(host.innerHTML, /2 items/); - assert.match(host.innerHTML, /in use: €1,813\.58/); + assert.match(host.innerHTML, /on balance: €1,813\.58/); assert.match(host.innerHTML, /is-disposed/); }); -test("an empty inventory explains how to fill it", async () => { +test("an empty inventory explains that purchases land automatically", async () => { const { view, host } = mount({ inventoryPages: [[]] }); await view.renderInventory(); assert.match(host.innerHTML, /No inventory yet/); - assert.match(host.innerHTML, /Scan the ledger/); + assert.match(host.innerHTML, /land here automatically/); }); -test("scan applies the import, reports the outcome and reloads", async () => { - const { view, host, calls, status, scanClick } = mount({ inventoryPages: [[], [laptop]] }); +test("the table has no per-row removal affordance", async () => { + const { view, host } = mount({ inventoryPages: [[laptop]] }); await view.renderInventory(); - scanClick(); - await flush(); - assert.deepEqual(calls[1], ["/inventory/import", "POST", { apply: true }]); - assert.match(status.at(-1), /Added 1 item from the ledger\./); - assert.match(host.innerHTML, /Laptop/); + assert.doesNotMatch(host.innerHTML, /data-inv-remove/); + assert.doesNotMatch(host.innerHTML, /bk-inv-remove/); }); -test("each item links back to the ledger record it came from", async () => { +test("each item links back to the invoice it came from", async () => { const { view, host, opened, click } = mount({ inventoryPages: [[laptop]] }); await view.renderInventory(); - assert.match(host.innerHTML, /↳ ledger: MacBook Pro 14/); - click({ "[data-inv-source]": node({ invSource: "tx-1" }) }); + assert.match(host.innerHTML, /↳ invoice: MacBook Pro 14/); + click({ "[data-inv-source]": { dataset: { invSource: "tx-1" } } }); assert.deepEqual(opened, ["tx-1"]); }); @@ -119,10 +109,10 @@ test("recording a sale sends a disposal with proceeds and derives the disposed s disposals: [{ id: "d-9", kind: "sold", date: "2037-03-15", proceeds: "250", currency: "EUR" }] }], }); await view.renderInventory(); - click({ "[data-inv-dispose]": node({ invDispose: laptop.id }) }); + click({ "[data-inv-dispose]": { dataset: { invDispose: laptop.id, invKind: "sold" } } }); assert.match(host.innerHTML, /bk-inv-dispose/); - type({ invDisposal: "proceeds" }, "250"); - click({ "[data-inv-disposal-save]": node({}) }); + type("[data-inv-disposal]", { invDisposal: "proceeds" }, "250"); + click({ "[data-inv-disposal-save]": { dataset: {} } }); await flush(); assert.deepEqual(calls.at(-1), [`/inventory/${laptop.id}`, "PUT", { disposal: { kind: "sold", date: "2037-03-15", proceeds: "250" }, @@ -134,6 +124,25 @@ test("recording a sale sends a disposal with proceeds and derives the disposed s assert.match(host.innerHTML, /proceeds/); }); +test("recording a return needs no proceeds and sends the returned kind", async () => { + const { view, host, calls, status, click } = mount({ + inventoryPages: [[laptop]], + putResponses: [{ ...laptop, status: "returned", returnedDate: "2037-03-15", + disposals: [{ id: "d-7", kind: "returned", date: "2037-03-15" }] }], + }); + await view.renderInventory(); + click({ "[data-inv-dispose]": { dataset: { invDispose: laptop.id, invKind: "returned" } } }); + assert.match(host.innerHTML, /value="returned"/); + assert.doesNotMatch(host.innerHTML, /Proceeds/); + click({ "[data-inv-disposal-save]": { dataset: {} } }); + await flush(); + assert.deepEqual(calls.at(-1), [`/inventory/${laptop.id}`, "PUT", { + disposal: { kind: "returned", date: "2037-03-15" }, + }]); + assert.match(status.at(-1), /Recorded the return\./); + assert.match(host.innerHTML, /returned · 2037-03-15/); +}); + test("a decommission form has no proceeds field and sends the decommissioned kind", async () => { const { view, host, calls, click, change } = mount({ inventoryPages: [[laptop]], @@ -141,37 +150,45 @@ test("a decommission form has no proceeds field and sends the decommissioned kin disposals: [{ id: "d-8", kind: "decommissioned", date: "2037-03-15" }] }], }); await view.renderInventory(); - click({ "[data-inv-dispose]": node({ invDispose: laptop.id }) }); + click({ "[data-inv-dispose]": { dataset: { invDispose: laptop.id, invKind: "sold" } } }); assert.match(host.innerHTML, /Proceeds/); - change({ invDisposal: "kind" }, "decommissioned"); + change("[data-inv-disposal]", { invDisposal: "kind" }, "decommissioned"); assert.doesNotMatch(host.innerHTML, /Proceeds/); - click({ "[data-inv-disposal-save]": node({}) }); + click({ "[data-inv-disposal-save]": { dataset: {} } }); await flush(); assert.deepEqual(calls.at(-1), [`/inventory/${laptop.id}`, "PUT", { disposal: { kind: "decommissioned", date: "2037-03-15" }, }]); }); -test("cancel closes the dispose form without writing", async () => { +test("cancel closes the exit form without writing", async () => { const { view, calls, click } = mount({ inventoryPages: [[laptop]] }); await view.renderInventory(); - click({ "[data-inv-dispose]": node({ invDispose: laptop.id }) }); - click({ "[data-inv-disposal-cancel]": node({}) }); + click({ "[data-inv-dispose]": { dataset: { invDispose: laptop.id, invKind: "sold" } } }); + click({ "[data-inv-disposal-cancel]": { dataset: {} } }); assert.deepEqual(calls.filter(([, method]) => method === "PUT"), []); }); -test("a sale without a date is rejected before any request", async () => { +test("an exit without a date is rejected before any request", async () => { const { view, status, calls, click, type } = mount({ inventoryPages: [[laptop]] }); await view.renderInventory(); - click({ "[data-inv-dispose]": node({ invDispose: laptop.id }) }); - type({ invDisposal: "date" }, ""); - click({ "[data-inv-disposal-save]": node({}) }); + click({ "[data-inv-dispose]": { dataset: { invDispose: laptop.id, invKind: "sold" } } }); + type("[data-inv-disposal]", { invDisposal: "date" }, ""); + click({ "[data-inv-disposal-save]": { dataset: {} } }); await flush(); - assert.match(status.at(-1), /Pick a disposal date\./); + assert.match(status.at(-1), /Pick a date/); assert.deepEqual(calls.filter(([, method]) => method === "PUT"), []); }); -test("removing the last disposal record puts the item back in use", async () => { +test("the usage select records whether an item is actively used", async () => { + const { view, calls, change } = mount({ inventoryPages: [[laptop]] }); + await view.renderInventory(); + change("[data-inv-field]", { invField: "usage" }, "idle", laptop.id); + await flush(); + assert.deepEqual(calls.at(-1), [`/inventory/${laptop.id}`, "PUT", { usage: "idle" }]); +}); + +test("removing the last exit record puts the item back on balance", async () => { const { view, host, calls, click } = mount({ inventoryPages: [[headset]], putResponses: [{ ...headset, status: "in-use", disposedDate: undefined, disposals: [] }], @@ -180,57 +197,65 @@ test("removing the last disposal record puts the item back in use", async () => assert.match(host.innerHTML, /sold<\/strong> 2026-09-01/); assert.match(host.innerHTML, /proceeds/); click({ - "[data-inv-disposal-remove]": node({ invDisposalRemove: "d-1" }, node({ inv: headset.id })), + "[data-inv-disposal-remove]": { dataset: { invDisposalRemove: "d-1" }, closest: (p) => (p === "[data-inv]" ? row(headset.id) : null) }, }); await flush(); assert.deepEqual(calls.at(-1), [`/inventory/${headset.id}`, "PUT", { removeDisposalId: "d-1" }]); }); -test("removal confirms first and drops the row", async () => { - const { view, host, calls, click } = mount({ inventoryPages: [[laptop]] }); - const originalConfirm = globalThis.confirm; - globalThis.confirm = () => true; - try { - await view.renderInventory(); - click({ "[data-inv-remove]": node({ invRemove: laptop.id }) }); - await flush(); - assert.deepEqual(calls.at(-1), [`/inventory/${laptop.id}`, "DELETE", undefined]); - assert.doesNotMatch(host.innerHTML, /Laptop/); - } finally { - globalThis.confirm = originalConfirm; - } -}); +test("a picture is attached by link, shown as a thumbnail, and removable", async () => { + const { view, host, calls, status, click, type } = mount({ + inventoryPages: [ + [laptop], + [{ ...laptop, images: [{ url: "https://m.media-amazon.com/images/front.jpg", caption: "front" }] }], + [{ ...laptop, images: [{ url: "https://m.media-amazon.com/images/front.jpg", caption: "front" }, { url: "https://example.com/back.jpg" }] }], + [{ ...laptop, images: [{ url: "https://example.com/back.jpg" }] }], + ], + }); + await view.renderInventory(); + click({ "[data-inv-image-add]": { dataset: { invImageAdd: laptop.id } } }); + assert.match(host.innerHTML, /bk-inv-image-form/); + // A malformed link is rejected before any request. + type("[data-inv-image]", { invImage: "url" }, "not-a-url"); + click({ "[data-inv-image-save]": { dataset: {} } }); + await flush(); + assert.match(status.at(-1), /picture link/); + assert.deepEqual(calls.filter(([, method]) => method === "PUT"), []); -test("declined confirmation leaves the row in place", async () => { - const { view, host, calls, click } = mount({ inventoryPages: [[laptop]] }); - const originalConfirm = globalThis.confirm; - globalThis.confirm = () => false; - try { - await view.renderInventory(); - click({ "[data-inv-remove]": node({ invRemove: laptop.id }) }); - await flush(); - assert.deepEqual(calls.filter(([, method]) => method === "DELETE"), []); - assert.match(host.innerHTML, /Laptop/); - } finally { - globalThis.confirm = originalConfirm; - } + type("[data-inv-image]", { invImage: "url" }, "https://m.media-amazon.com/images/front.jpg"); + type("[data-inv-image]", { invImage: "caption" }, "front"); + click({ "[data-inv-image-save]": { dataset: {} } }); + await flush(); + assert.deepEqual(calls.at(-1), [`/inventory/${laptop.id}`, "PUT", { + addImage: { url: "https://m.media-amazon.com/images/front.jpg", caption: "front" }, + }]); + assert.match(status.at(-1), /Picture attached\./); + await view.renderInventory(); + assert.match(host.innerHTML, /bk-inv-thumb/); + assert.match(host.innerHTML, /front/); + + await view.renderInventory(); + click({ "[data-inv-image-remove]": { dataset: { invImageRemove: "https://m.media-amazon.com/images/front.jpg" }, closest: (p) => (p === "[data-inv]" ? row(laptop.id) : null) } }); + await flush(); + assert.deepEqual(calls.at(-1), [`/inventory/${laptop.id}`, "PUT", { removeImageUrl: "https://m.media-amazon.com/images/front.jpg" }]); + assert.match(status.at(-1), /Picture removed\./); }); -test("clicking the record opens the ledger record it came from", async () => { +test("clicking the record opens the invoice it came from", async () => { const { view, click, opened } = mount({ inventoryPages: [[laptop]] }); await view.renderInventory(); click({ "[data-inv]": { dataset: { inv: laptop.id } } }); assert.deepEqual(opened, [laptop.source.transactionId]); }); -test("clicks inside the note or type controls never open the ledger", async () => { +test("clicks inside the note or type controls never open the invoice", async () => { const { view, click, opened } = mount({ inventoryPages: [[laptop]] }); await view.renderInventory(); click({ "input, select, button, a": { dataset: {} } }); assert.deepEqual(opened, []); }); -test("a record without a ledger source is not clickable", async () => { +test("a record without an invoice source is not clickable", async () => { const orphan = { ...laptop, id: "inv-orphan", source: undefined }; const { view, host, click, opened } = mount({ inventoryPages: [[laptop, orphan]] }); await view.renderInventory();