40 lines
2.3 KiB
TypeScript
40 lines
2.3 KiB
TypeScript
import type { FastifyInstance } from "fastify";
|
|
import { eq, and } from "drizzle-orm";
|
|
import { shipments as shipmentsTable, assets as assetsTable } from "@sankofa/schema";
|
|
|
|
export async function shipmentsRoutes(app: FastifyInstance) {
|
|
const db = app.db;
|
|
app.get("/", async (req, reply) => {
|
|
const orgId = app.orgId(req);
|
|
const list = await db.select().from(shipmentsTable).where(eq(shipmentsTable.orgId, orgId));
|
|
return reply.send(list);
|
|
});
|
|
app.get<{ Params: { id: string } }>("/:id", async (req, reply) => {
|
|
const orgId = app.orgId(req);
|
|
const [row] = await db.select().from(shipmentsTable).where(and(eq(shipmentsTable.id, req.params.id), eq(shipmentsTable.orgId, orgId)));
|
|
if (!row) return reply.notFound();
|
|
return reply.send(row);
|
|
});
|
|
app.post<{ Body: { purchaseOrderId: string; tracking?: string } }>("/", async (req, reply) => {
|
|
const orgId = app.orgId(req);
|
|
const [inserted] = await db.insert(shipmentsTable).values({ orgId, purchaseOrderId: req.body.purchaseOrderId, tracking: req.body.tracking ?? null }).returning();
|
|
return reply.code(201).send(inserted);
|
|
});
|
|
app.patch<{ Params: { id: string }; Body: { tracking?: string; status?: string } }>("/:id", async (req, reply) => {
|
|
const orgId = app.orgId(req);
|
|
const [updated] = await db.update(shipmentsTable).set({ ...req.body, updatedAt: new Date() }).where(and(eq(shipmentsTable.id, req.params.id), eq(shipmentsTable.orgId, orgId))).returning();
|
|
if (!updated) return reply.notFound();
|
|
return reply.send(updated);
|
|
});
|
|
app.post<{ Params: { id: string }; Body: { assetIds: string[] } }>("/:id/receive", async (req, reply) => {
|
|
const orgId = app.orgId(req);
|
|
const [shipment] = await db.select().from(shipmentsTable).where(and(eq(shipmentsTable.id, req.params.id), eq(shipmentsTable.orgId, orgId)));
|
|
if (!shipment) return reply.notFound();
|
|
for (const assetId of req.body.assetIds || []) {
|
|
await db.update(assetsTable).set({ status: "received", updatedAt: new Date() }).where(and(eq(assetsTable.id, assetId), eq(assetsTable.orgId, orgId)));
|
|
}
|
|
await db.update(shipmentsTable).set({ status: "received", updatedAt: new Date() }).where(and(eq(shipmentsTable.id, req.params.id), eq(shipmentsTable.orgId, orgId)));
|
|
return reply.send({ status: "received" });
|
|
});
|
|
}
|