-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
148 lines (127 loc) · 4.95 KB
/
Copy pathroute.ts
File metadata and controls
148 lines (127 loc) · 4.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import { eq } from "drizzle-orm";
import { NextResponse, type NextRequest } from "next/server";
import { db } from "@/lib/db";
import { order, orderHistory } from "@/lib/db/schema";
import {
ensureFinanceSettingsRow,
getActiveQuarter,
orderTotalCents,
restoreGiftFundForDeletion,
validateOrderBalance,
} from "@/lib/finance/finance";
import { getSessionUser } from "@/lib/auth/session";
import { orderInputSchema } from "@/lib/validation";
function parseOrderId(params: { id: string }) {
const orderId = Number(params.id);
if (!Number.isInteger(orderId)) return null;
return orderId;
}
function isLockedOrderStatus(status: string) {
return status === "approved" || status === "ordered";
}
function memberCanModifyOrder(existing: { userId: string; status: string }, userId: string) {
return existing.userId === userId && !isLockedOrderStatus(existing.status);
}
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const user = await getSessionUser();
if (!user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const orderId = parseOrderId(await params);
if (orderId == null) {
return NextResponse.json({ error: "Invalid order id" }, { status: 400 });
}
const existing = db.select().from(order).where(eq(order.id, orderId)).get();
if (!existing) {
return NextResponse.json({ error: "Order not found" }, { status: 404 });
}
if (!memberCanModifyOrder(existing, user.id)) {
return NextResponse.json({ error: "This order cannot be edited" }, { status: 403 });
}
const body = await req.json().catch(() => null);
const parsed = orderInputSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: "Invalid input", issues: parsed.error.flatten() },
{ status: 400 }
);
}
const d = parsed.data;
ensureFinanceSettingsRow();
const unitCostCents = Math.round(d.unitCost * 100);
const totalCostCents = orderTotalCents(d.quantity, unitCostCents, d.fundType);
const balanceCheck = validateOrderBalance(d.fundType, d.stfBucketId, totalCostCents);
if (!balanceCheck.ok) {
return NextResponse.json({ error: balanceCheck.message }, { status: 400 });
}
const activeQuarter = d.fundType === "STF" ? getActiveQuarter() : null;
if (d.fundType === "STF" && !activeQuarter) {
return NextResponse.json(
{ error: "No active STF school year is configured. Contact an officer." },
{ status: 400 }
);
}
const updated = db
.update(order)
.set({
fundType: d.fundType,
stfBucketId: d.fundType === "STF" ? d.stfBucketId! : null,
quarterId: activeQuarter?.id ?? null,
vendor: d.vendor,
link: d.link,
itemName: d.itemName,
partNumber: d.partNumber?.trim() || null,
quantity: d.quantity,
unitCostCents,
notes: d.notes?.trim() || null,
status: "pending",
denialComment: null,
reviewedBy: null,
reviewedAt: null,
})
.where(eq(order.id, orderId))
.returning()
.get();
db.insert(orderHistory)
.values({
orderId,
fromStatus: existing.status,
toStatus: "pending",
changedBy: user.id,
note: existing.status === "denied" ? "Resubmitted by requester" : "Edited by requester",
})
.run();
return NextResponse.json({ order: updated });
}
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const user = await getSessionUser();
if (!user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const orderId = parseOrderId(await params);
if (orderId == null) {
return NextResponse.json({ error: "Invalid order id" }, { status: 400 });
}
const existing = db.select().from(order).where(eq(order.id, orderId)).get();
if (!existing) {
return NextResponse.json({ error: "Order not found" }, { status: 404 });
}
const isAdmin = user.role === "admin";
if (isLockedOrderStatus(existing.status)) {
if (!isAdmin) {
return NextResponse.json({ error: "This order cannot be deleted" }, { status: 403 });
}
} else if (!memberCanModifyOrder(existing, user.id)) {
return NextResponse.json({ error: "This order cannot be deleted" }, { status: 403 });
}
if (isLockedOrderStatus(existing.status) && existing.fundType === "Gift") {
const totalCostCents = orderTotalCents(
existing.quantity,
existing.unitCostCents,
existing.fundType
);
restoreGiftFundForDeletion(orderId, totalCostCents, user.id);
}
db.delete(order).where(eq(order.id, orderId)).run();
return new NextResponse(null, { status: 204 });
}