Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 74 additions & 4 deletions backend/src/db/bookkeeping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<string, unknown>[],
) {
for (const candidate of deriveInventoryItems(transactions)) {
const seed = inventoryItemSeed(candidate.transactionId, candidate.allocationId);
if (await getBookkeepingItem(client, "inventoryDismissed", dismissedInventorySeedId(seed))) continue;
const entry: Record<string, unknown> = {
id: inventoryItemId(candidate.transactionId, candidate.allocationId),
transactionId: candidate.transactionId,
Expand All @@ -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<string, unknown>[] }> {
const [transactions, existing, dismissed] = await Promise.all([
listTransactions(client),
listBookkeepingItems(client, "inventory"),
listBookkeepingItems(client, "inventoryDismissed"),
]);
const known = new Set<string>([
...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<string, unknown>[] = [];
for (const candidate of candidates) {
const seed = inventoryItemSeed(candidate.transactionId, candidate.allocationId);
const entry: Record<string, unknown> = {
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,
Expand Down
44 changes: 27 additions & 17 deletions backend/src/finance/inventory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 };
}
Loading