Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98801089e5 | ||
|
|
4f6c68ad29 |
@@ -90,6 +90,7 @@ export function initializeDatabase(sqlite: Database) {
|
||||
customer_id TEXT NOT NULL REFERENCES users(id),
|
||||
shipping_address_id TEXT NOT NULL REFERENCES addresses(id),
|
||||
status TEXT NOT NULL,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
@@ -119,4 +120,8 @@ export function initializeDatabase(sqlite: Database) {
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
`);
|
||||
|
||||
if (tableExists(sqlite, "orders") && !columnExists(sqlite, "orders", "notes")) {
|
||||
sqlite.exec(`ALTER TABLE orders ADD COLUMN notes TEXT NOT NULL DEFAULT ''`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ export const orders = sqliteTable("orders", {
|
||||
customerId: text("customer_id").notNull().references(() => users.id),
|
||||
shippingAddressId: text("shipping_address_id").notNull().references(() => addresses.id),
|
||||
status: text("status").notNull(),
|
||||
notes: text("notes").notNull().default(""),
|
||||
createdAt: text("created_at").notNull(),
|
||||
updatedAt: text("updated_at").notNull()
|
||||
});
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import type { AppWithContext } from "../app";
|
||||
import { buildApp } from "../app";
|
||||
import { createUser } from "../users/user-repository";
|
||||
|
||||
let app: AppWithContext;
|
||||
let employeeCookie = "";
|
||||
let customerCookie = "";
|
||||
|
||||
function firstHeader(value: string | string[] | undefined): string {
|
||||
return Array.isArray(value) ? value[0] ?? "" : value ?? "";
|
||||
}
|
||||
|
||||
async function login(username: string) {
|
||||
const response = await app.inject({ method: "POST", url: "/api/login", payload: { username } });
|
||||
return firstHeader(response.headers["set-cookie"]);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
app = await buildApp(":memory:");
|
||||
|
||||
await createUser(app.dbContext, {
|
||||
username: "dev-employee",
|
||||
name: "Dev Employee",
|
||||
email: "dev.employee@example.com",
|
||||
role: "employee"
|
||||
});
|
||||
|
||||
employeeCookie = await login("dev-employee");
|
||||
customerCookie = await login("john-smith");
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("assignment 2 internal order notes", () => {
|
||||
test("allows employee users to attach notes to an order", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_1/notes",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { notes: "Follow up with warehouse before shipping." }
|
||||
});
|
||||
|
||||
const order = response.json();
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(order.orderNumber).toBe("ORD-1001");
|
||||
expect(order.notes).toBe("Follow up with warehouse before shipping.");
|
||||
expect(order.items).toHaveLength(2);
|
||||
});
|
||||
|
||||
test("returns persisted notes when the order is viewed later", async () => {
|
||||
const updateResponse = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_1/notes",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { notes: "Customer requested gift receipt." }
|
||||
});
|
||||
|
||||
expect(updateResponse.statusCode).toBe(200);
|
||||
|
||||
const detailResponse = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/orders/order_1",
|
||||
headers: { cookie: employeeCookie }
|
||||
});
|
||||
|
||||
expect(detailResponse.statusCode).toBe(200);
|
||||
expect(detailResponse.json().notes).toBe("Customer requested gift receipt.");
|
||||
});
|
||||
|
||||
test("rejects customer users when attaching notes", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_1/notes",
|
||||
headers: { cookie: customerCookie },
|
||||
payload: { notes: "Customer should not be able to add this." }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
test("rejects empty notes", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_1/notes",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { notes: " " }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
test("rejects notes beyond the accepted length limit", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_1/notes",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { notes: "x".repeat(1001) }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
@@ -96,6 +96,7 @@ export async function findOrderDetail(context: DatabaseContext, orderId: string)
|
||||
id: header.order.id,
|
||||
orderNumber: header.order.orderNumber,
|
||||
status: header.order.status as OrderDetail["status"],
|
||||
notes: header.order.notes,
|
||||
createdAt: header.order.createdAt,
|
||||
updatedAt: header.order.updatedAt,
|
||||
customer: {
|
||||
@@ -131,6 +132,10 @@ export async function updateOrderStatus(context: DatabaseContext, orderId: strin
|
||||
await context.db.update(orders).set({ status, updatedAt }).where(eq(orders.id, orderId));
|
||||
}
|
||||
|
||||
export async function updateOrderNotes(context: DatabaseContext, orderId: string, notes: string, updatedAt: string) {
|
||||
await context.db.update(orders).set({ notes, updatedAt }).where(eq(orders.id, orderId));
|
||||
}
|
||||
|
||||
export async function updateOrderAddress(context: DatabaseContext, orderId: string, address: Address) {
|
||||
const [row] = await context.db.select({ shippingAddressId: orders.shippingAddressId }).from(orders).where(eq(orders.id, orderId));
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getOrder } from "./get-order";
|
||||
import { listAuditEvents } from "./list-audit-events";
|
||||
import { listOrders } from "./list-orders";
|
||||
import { changeOrderItemQuantity } from "./update-order-item";
|
||||
import { changeOrderNotes } from "./update-notes";
|
||||
import { changeShippingAddress } from "./update-shipping-address";
|
||||
|
||||
interface OrderRouteOptions {
|
||||
@@ -29,6 +30,10 @@ interface QuantityBody {
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
interface NotesBody {
|
||||
notes: string;
|
||||
}
|
||||
|
||||
interface CancelBody {
|
||||
reason?: string;
|
||||
}
|
||||
@@ -95,6 +100,31 @@ export const registerOrderRoutes: FastifyPluginAsync<OrderRouteOptions> = async
|
||||
return result.order;
|
||||
});
|
||||
|
||||
app.post<{ Params: IdParams; Body: NotesBody }>("/orders/:orderId/notes", {
|
||||
schema: {
|
||||
body: {
|
||||
type: "object",
|
||||
required: ["notes"],
|
||||
properties: {
|
||||
notes: { type: "string" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}, async (request, reply) => {
|
||||
const currentUser = (request as AuthenticatedRequest).currentUser;
|
||||
const result = await changeOrderNotes(options.db, {
|
||||
orderId: request.params.orderId,
|
||||
notes: request.body.notes,
|
||||
actor: currentUser.username
|
||||
});
|
||||
|
||||
if (result.statusCode !== 200) {
|
||||
return reply.code(result.statusCode).send({ message: result.message });
|
||||
}
|
||||
|
||||
return result.order;
|
||||
});
|
||||
|
||||
app.post<{ Params: IdParams; Body: Address }>("/orders/:orderId/shipping-address", {
|
||||
schema: {
|
||||
body: {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { DatabaseContext } from "../db/database";
|
||||
import { appendAuditEvent, findOrderDetail, updateOrderNotes } from "./order-repository";
|
||||
|
||||
export const NOTES_MAX_LENGTH = 1000;
|
||||
|
||||
export async function changeOrderNotes(
|
||||
context: DatabaseContext,
|
||||
input: {
|
||||
orderId: string;
|
||||
notes: string;
|
||||
actor: string;
|
||||
}
|
||||
) {
|
||||
const order = await findOrderDetail(context, input.orderId);
|
||||
|
||||
if (!order) {
|
||||
return { statusCode: 404, message: "Order not found." } as const;
|
||||
}
|
||||
|
||||
const notes = input.notes.trim();
|
||||
|
||||
if (notes.length === 0) {
|
||||
return { statusCode: 400, message: "Notes cannot be empty." } as const;
|
||||
}
|
||||
|
||||
if (notes.length > NOTES_MAX_LENGTH) {
|
||||
return { statusCode: 400, message: `Notes cannot exceed ${NOTES_MAX_LENGTH} characters.` } as const;
|
||||
}
|
||||
|
||||
const updatedAt = new Date().toISOString();
|
||||
await updateOrderNotes(context, input.orderId, notes, updatedAt);
|
||||
await appendAuditEvent(context, {
|
||||
orderId: input.orderId,
|
||||
actor: input.actor,
|
||||
type: "order.notes_updated",
|
||||
message: "Updated internal notes.",
|
||||
createdAt: updatedAt
|
||||
});
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
order: await findOrderDetail(context, input.orderId)
|
||||
} as const;
|
||||
}
|
||||
@@ -28,6 +28,13 @@ export function updateShippingAddress(orderId: string, address: Address) {
|
||||
});
|
||||
}
|
||||
|
||||
export function updateOrderNotes(orderId: string, notes: string) {
|
||||
return apiRequest<OrderDetail>(`/api/orders/${orderId}/notes`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ notes })
|
||||
});
|
||||
}
|
||||
|
||||
export function cancelOrder(orderId: string, reason?: string) {
|
||||
return apiRequest<OrderDetail>(`/api/orders/${orderId}/cancel`, {
|
||||
method: "POST",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Address, AuditEvent, OrderDetail } from "@orderops/shared";
|
||||
import { AuditTimeline } from "./audit-timeline";
|
||||
import { OrderItemsPanel } from "./order-items-panel";
|
||||
import { OrderNotesPanel } from "./order-notes";
|
||||
import { OrderSummaryPanel } from "./order-summary";
|
||||
import { ShippingAddressForm } from "./shipping-address-form";
|
||||
|
||||
@@ -9,6 +10,7 @@ interface OrderDetailPageProps {
|
||||
auditEvents: AuditEvent[];
|
||||
onUpdateQuantity: (itemId: string, quantity: number) => Promise<void>;
|
||||
onSaveAddress: (address: Address) => Promise<void>;
|
||||
onSaveNotes: (notes: string) => Promise<void>;
|
||||
onCancel: () => Promise<void>;
|
||||
}
|
||||
|
||||
@@ -17,11 +19,13 @@ export function OrderDetailPage({
|
||||
auditEvents,
|
||||
onUpdateQuantity,
|
||||
onSaveAddress,
|
||||
onSaveNotes,
|
||||
onCancel
|
||||
}: OrderDetailPageProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<OrderSummaryPanel order={order} />
|
||||
<OrderNotesPanel notes={order.notes} onSave={onSaveNotes} />
|
||||
<div className="flex justify-end">
|
||||
<button className="rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white" onClick={() => void onCancel()} type="button">
|
||||
Cancel order
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useState } from "react";
|
||||
|
||||
export const NOTES_MAX_LENGTH = 1000;
|
||||
|
||||
interface OrderNotesProps {
|
||||
notes: string;
|
||||
onSave: (notes: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export function OrderNotesPanel({ notes, onSave }: OrderNotesProps) {
|
||||
const [draft, setDraft] = useState(notes);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const trimmed = draft.trim();
|
||||
const isDisabled = isSaving || trimmed.length === 0 || trimmed === notes;
|
||||
|
||||
async function handleSave() {
|
||||
if (isDisabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSaving(true);
|
||||
try {
|
||||
await onSave(trimmed);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h3 className="text-sm font-semibold text-slate-700">Internal notes</h3>
|
||||
<span className="text-xs text-slate-500">{draft.length}/{NOTES_MAX_LENGTH}</span>
|
||||
</div>
|
||||
{notes ? (
|
||||
<p className="mb-3 whitespace-pre-wrap text-sm text-slate-700">{notes}</p>
|
||||
) : (
|
||||
<p className="mb-3 text-sm text-slate-400">No internal notes yet. Add context for teammates following up on this order.</p>
|
||||
)}
|
||||
<textarea
|
||||
className="w-full resize-y rounded-lg border border-slate-300 px-3 py-2 text-sm text-slate-900 focus:border-blue-500 focus:outline-none"
|
||||
maxLength={NOTES_MAX_LENGTH}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
placeholder="Add internal notes..."
|
||||
rows={3}
|
||||
value={draft}
|
||||
/>
|
||||
<div className="mt-3 flex justify-end">
|
||||
<button
|
||||
className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={isDisabled}
|
||||
onClick={() => void handleSave()}
|
||||
type="button"
|
||||
>
|
||||
{isSaving ? "Saving..." : "Save notes"}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { useEffect, useState } from "react";
|
||||
import type { Address, AuditEvent, OrderDetail } from "@orderops/shared";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { Toast } from "../ui/toast";
|
||||
import { cancelOrder, getOrder, listAuditEvents, updateOrderItemQuantity, updateShippingAddress } from "./order-api";
|
||||
import { cancelOrder, getOrder, listAuditEvents, updateOrderItemQuantity, updateOrderNotes, updateShippingAddress } from "./order-api";
|
||||
import { OrderDetailPage } from "./order-detail-page";
|
||||
|
||||
interface ToastState {
|
||||
@@ -86,6 +86,7 @@ export function OrderPage() {
|
||||
auditEvents={auditEvents}
|
||||
onUpdateQuantity={(itemId, quantity) => runAction(() => updateOrderItemQuantity(order.id, itemId, quantity), "Quantity saved.")}
|
||||
onSaveAddress={(address: Address) => runAction(() => updateShippingAddress(order.id, address), "Shipping address saved.")}
|
||||
onSaveNotes={(notes: string) => runAction(() => updateOrderNotes(order.id, notes), "Notes saved.")}
|
||||
onCancel={() => runAction(() => cancelOrder(order.id), "Order cancelled.")}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -17,6 +17,7 @@ export interface OrderDetail {
|
||||
id: string;
|
||||
orderNumber: string;
|
||||
status: OrderStatus;
|
||||
notes: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
customer: CustomerSummary;
|
||||
|
||||
Reference in New Issue
Block a user