inventory1

This commit is contained in:
2026-03-14 21:10:35 -05:00
parent df3f1412f6
commit d21e2e3c0b
21 changed files with 1492 additions and 7 deletions

View File

@@ -0,0 +1,115 @@
import { permissions } from "@mrp/shared";
import { inventoryItemStatuses, inventoryItemTypes, inventoryUnitsOfMeasure } from "@mrp/shared/dist/inventory/types.js";
import { Router } from "express";
import { z } from "zod";
import { fail, ok } from "../../lib/http.js";
import { requirePermissions } from "../../lib/rbac.js";
import {
createInventoryItem,
getInventoryItemById,
listInventoryItemOptions,
listInventoryItems,
updateInventoryItem,
} from "./service.js";
const bomLineSchema = z.object({
componentItemId: z.string().trim().min(1),
quantity: z.number().positive(),
unitOfMeasure: z.enum(inventoryUnitsOfMeasure),
notes: z.string(),
position: z.number().int().nonnegative(),
});
const inventoryItemSchema = z.object({
sku: z.string().trim().min(1).max(64),
name: z.string().trim().min(1).max(160),
description: z.string(),
type: z.enum(inventoryItemTypes),
status: z.enum(inventoryItemStatuses),
unitOfMeasure: z.enum(inventoryUnitsOfMeasure),
isSellable: z.boolean(),
isPurchasable: z.boolean(),
defaultCost: z.number().nonnegative().nullable(),
notes: z.string(),
bomLines: z.array(bomLineSchema),
});
const inventoryListQuerySchema = z.object({
q: z.string().optional(),
status: z.enum(inventoryItemStatuses).optional(),
type: z.enum(inventoryItemTypes).optional(),
});
function getRouteParam(value: unknown) {
return typeof value === "string" ? value : null;
}
export const inventoryRouter = Router();
inventoryRouter.get("/items", requirePermissions([permissions.inventoryRead]), async (request, response) => {
const parsed = inventoryListQuerySchema.safeParse(request.query);
if (!parsed.success) {
return fail(response, 400, "INVALID_INPUT", "Inventory filters are invalid.");
}
return ok(
response,
await listInventoryItems({
query: parsed.data.q,
status: parsed.data.status,
type: parsed.data.type,
})
);
});
inventoryRouter.get("/items/options", requirePermissions([permissions.inventoryRead]), async (_request, response) => {
return ok(response, await listInventoryItemOptions());
});
inventoryRouter.get("/items/:itemId", requirePermissions([permissions.inventoryRead]), async (request, response) => {
const itemId = getRouteParam(request.params.itemId);
if (!itemId) {
return fail(response, 400, "INVALID_INPUT", "Inventory item id is invalid.");
}
const item = await getInventoryItemById(itemId);
if (!item) {
return fail(response, 404, "INVENTORY_ITEM_NOT_FOUND", "Inventory item was not found.");
}
return ok(response, item);
});
inventoryRouter.post("/items", requirePermissions([permissions.inventoryWrite]), async (request, response) => {
const parsed = inventoryItemSchema.safeParse(request.body);
if (!parsed.success) {
return fail(response, 400, "INVALID_INPUT", "Inventory item payload is invalid.");
}
const item = await createInventoryItem(parsed.data);
if (!item) {
return fail(response, 400, "INVALID_INPUT", "Inventory item BOM references are invalid.");
}
return ok(response, item, 201);
});
inventoryRouter.put("/items/:itemId", requirePermissions([permissions.inventoryWrite]), async (request, response) => {
const itemId = getRouteParam(request.params.itemId);
if (!itemId) {
return fail(response, 400, "INVALID_INPUT", "Inventory item id is invalid.");
}
const parsed = inventoryItemSchema.safeParse(request.body);
if (!parsed.success) {
return fail(response, 400, "INVALID_INPUT", "Inventory item payload is invalid.");
}
const item = await updateInventoryItem(itemId, parsed.data);
if (!item) {
return fail(response, 400, "INVALID_INPUT", "Inventory item or BOM references are invalid.");
}
return ok(response, item);
});

View File

@@ -0,0 +1,327 @@
import type {
InventoryBomLineDto,
InventoryBomLineInput,
InventoryItemDetailDto,
InventoryItemInput,
InventoryItemStatus,
InventoryItemSummaryDto,
InventoryItemType,
InventoryUnitOfMeasure,
} from "@mrp/shared/dist/inventory/types.js";
import { prisma } from "../../lib/prisma.js";
type BomLineRecord = {
id: string;
quantity: number;
unitOfMeasure: string;
notes: string;
position: number;
componentItem: {
id: string;
sku: string;
name: string;
};
};
type InventoryDetailRecord = {
id: string;
sku: string;
name: string;
description: string;
type: string;
status: string;
unitOfMeasure: string;
isSellable: boolean;
isPurchasable: boolean;
defaultCost: number | null;
notes: string;
createdAt: Date;
updatedAt: Date;
bomLines: BomLineRecord[];
};
function mapBomLine(record: BomLineRecord): InventoryBomLineDto {
return {
id: record.id,
componentItemId: record.componentItem.id,
componentSku: record.componentItem.sku,
componentName: record.componentItem.name,
quantity: record.quantity,
unitOfMeasure: record.unitOfMeasure as InventoryUnitOfMeasure,
notes: record.notes,
position: record.position,
};
}
function mapSummary(record: {
id: string;
sku: string;
name: string;
type: string;
status: string;
unitOfMeasure: string;
isSellable: boolean;
isPurchasable: boolean;
updatedAt: Date;
_count: { bomLines: number };
}): InventoryItemSummaryDto {
return {
id: record.id,
sku: record.sku,
name: record.name,
type: record.type as InventoryItemType,
status: record.status as InventoryItemStatus,
unitOfMeasure: record.unitOfMeasure as InventoryUnitOfMeasure,
isSellable: record.isSellable,
isPurchasable: record.isPurchasable,
bomLineCount: record._count.bomLines,
updatedAt: record.updatedAt.toISOString(),
};
}
function mapDetail(record: InventoryDetailRecord): InventoryItemDetailDto {
return {
...mapSummary({
id: record.id,
sku: record.sku,
name: record.name,
type: record.type,
status: record.status,
unitOfMeasure: record.unitOfMeasure,
isSellable: record.isSellable,
isPurchasable: record.isPurchasable,
updatedAt: record.updatedAt,
_count: { bomLines: record.bomLines.length },
}),
description: record.description,
defaultCost: record.defaultCost,
notes: record.notes,
createdAt: record.createdAt.toISOString(),
bomLines: record.bomLines.slice().sort((a, b) => a.position - b.position).map(mapBomLine),
};
}
interface InventoryListFilters {
query?: string;
status?: InventoryItemStatus;
type?: InventoryItemType;
}
function buildWhereClause(filters: InventoryListFilters) {
const trimmedQuery = filters.query?.trim();
return {
...(filters.status ? { status: filters.status } : {}),
...(filters.type ? { type: filters.type } : {}),
...(trimmedQuery
? {
OR: [
{ sku: { contains: trimmedQuery } },
{ name: { contains: trimmedQuery } },
{ description: { contains: trimmedQuery } },
],
}
: {}),
};
}
function normalizeBomLines(bomLines: InventoryBomLineInput[]) {
return bomLines
.map((line, index) => ({
componentItemId: line.componentItemId,
quantity: line.quantity,
unitOfMeasure: line.unitOfMeasure,
notes: line.notes,
position: line.position ?? (index + 1) * 10,
}))
.filter((line) => line.componentItemId.trim().length > 0);
}
async function validateBomLines(parentItemId: string | null, bomLines: InventoryBomLineInput[]) {
const normalized = normalizeBomLines(bomLines);
if (normalized.some((line) => line.quantity <= 0)) {
return { ok: false as const, reason: "BOM line quantity must be greater than zero." };
}
if (parentItemId && normalized.some((line) => line.componentItemId === parentItemId)) {
return { ok: false as const, reason: "An item cannot reference itself in its BOM." };
}
const componentIds = [...new Set(normalized.map((line) => line.componentItemId))];
if (componentIds.length === 0) {
return { ok: true as const, bomLines: normalized };
}
const existingComponents = await prisma.inventoryItem.findMany({
where: {
id: {
in: componentIds,
},
},
select: {
id: true,
},
});
if (existingComponents.length !== componentIds.length) {
return { ok: false as const, reason: "One or more BOM components do not exist." };
}
return { ok: true as const, bomLines: normalized };
}
export async function listInventoryItems(filters: InventoryListFilters = {}) {
const items = await prisma.inventoryItem.findMany({
where: buildWhereClause(filters),
include: {
_count: {
select: {
bomLines: true,
},
},
},
orderBy: [{ sku: "asc" }],
});
return items.map(mapSummary);
}
export async function listInventoryItemOptions() {
const items = await prisma.inventoryItem.findMany({
where: {
status: {
not: "OBSOLETE",
},
},
select: {
id: true,
sku: true,
name: true,
},
orderBy: [{ sku: "asc" }],
});
return items.map((item) => ({
id: item.id,
sku: item.sku,
name: item.name,
}));
}
export async function getInventoryItemById(itemId: string) {
const item = await prisma.inventoryItem.findUnique({
where: { id: itemId },
include: {
bomLines: {
include: {
componentItem: {
select: {
id: true,
sku: true,
name: true,
},
},
},
orderBy: [{ position: "asc" }, { createdAt: "asc" }],
},
},
});
return item ? mapDetail(item) : null;
}
export async function createInventoryItem(payload: InventoryItemInput) {
const validatedBom = await validateBomLines(null, payload.bomLines);
if (!validatedBom.ok) {
return null;
}
const item = await prisma.inventoryItem.create({
data: {
sku: payload.sku,
name: payload.name,
description: payload.description,
type: payload.type,
status: payload.status,
unitOfMeasure: payload.unitOfMeasure,
isSellable: payload.isSellable,
isPurchasable: payload.isPurchasable,
defaultCost: payload.defaultCost,
notes: payload.notes,
bomLines: validatedBom.bomLines.length
? {
create: validatedBom.bomLines,
}
: undefined,
},
include: {
bomLines: {
include: {
componentItem: {
select: {
id: true,
sku: true,
name: true,
},
},
},
orderBy: [{ position: "asc" }, { createdAt: "asc" }],
},
},
});
return mapDetail(item);
}
export async function updateInventoryItem(itemId: string, payload: InventoryItemInput) {
const existingItem = await prisma.inventoryItem.findUnique({
where: { id: itemId },
});
if (!existingItem) {
return null;
}
const validatedBom = await validateBomLines(itemId, payload.bomLines);
if (!validatedBom.ok) {
return null;
}
const item = await prisma.inventoryItem.update({
where: { id: itemId },
data: {
sku: payload.sku,
name: payload.name,
description: payload.description,
type: payload.type,
status: payload.status,
unitOfMeasure: payload.unitOfMeasure,
isSellable: payload.isSellable,
isPurchasable: payload.isPurchasable,
defaultCost: payload.defaultCost,
notes: payload.notes,
bomLines: {
deleteMany: {},
create: validatedBom.bomLines,
},
},
include: {
bomLines: {
include: {
componentItem: {
select: {
id: true,
sku: true,
name: true,
},
},
},
orderBy: [{ position: "asc" }, { createdAt: "asc" }],
},
},
});
return mapDetail(item);
}