Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c5215daedb | ||
|
|
e493d1592b |
@@ -21,6 +21,7 @@ function resetLegacySchema(sqlite: Database) {
|
||||
DROP TABLE IF EXISTS sessions;
|
||||
DROP TABLE IF EXISTS audit_events;
|
||||
DROP TABLE IF EXISTS refunds;
|
||||
DROP TABLE IF EXISTS order_notes;
|
||||
DROP TABLE IF EXISTS order_items;
|
||||
DROP TABLE IF EXISTS orders;
|
||||
DROP TABLE IF EXISTS inventory;
|
||||
@@ -102,6 +103,14 @@ export function initializeDatabase(sqlite: Database) {
|
||||
unit_price_cents INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS order_notes (
|
||||
id TEXT PRIMARY KEY,
|
||||
order_id TEXT NOT NULL REFERENCES orders(id),
|
||||
body TEXT NOT NULL,
|
||||
author_user_id TEXT NOT NULL REFERENCES users(id),
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS refunds (
|
||||
id TEXT PRIMARY KEY,
|
||||
order_id TEXT NOT NULL REFERENCES orders(id),
|
||||
|
||||
@@ -20,3 +20,11 @@ export const orderItems = sqliteTable("order_items", {
|
||||
quantity: integer("quantity").notNull(),
|
||||
unitPriceCents: integer("unit_price_cents").notNull()
|
||||
});
|
||||
|
||||
export const orderNotes = sqliteTable("order_notes", {
|
||||
id: text("id").primaryKey(),
|
||||
orderId: text("order_id").notNull().references(() => orders.id),
|
||||
body: text("body").notNull(),
|
||||
authorUserId: text("author_user_id").notNull().references(() => users.id),
|
||||
createdAt: text("created_at").notNull()
|
||||
});
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { DatabaseContext } from "../db/database";
|
||||
import { findOrderDetail, insertOrderNote } from "./order-repository";
|
||||
|
||||
export async function addOrderNote(
|
||||
context: DatabaseContext,
|
||||
input: {
|
||||
orderId: string;
|
||||
authorUserId: string;
|
||||
body: string;
|
||||
}
|
||||
) {
|
||||
if (!input.body.trim() || input.body.length >= 2000) {
|
||||
return { statusCode: 400, message: "Note must be non-empty and less than 2000 characters." } as const;
|
||||
}
|
||||
|
||||
const order = await findOrderDetail(context, input.orderId);
|
||||
|
||||
if (!order) {
|
||||
return { statusCode: 404, message: "Order not found." } as const;
|
||||
}
|
||||
|
||||
const note = await insertOrderNote(context, input);
|
||||
|
||||
if (!note) {
|
||||
return { statusCode: 404, message: "Author not found." } as const;
|
||||
}
|
||||
|
||||
return { statusCode: 200, note } as const;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Address, AuditEvent, OrderDetail, OrderItemDetail, OrderSummary } from "@orderops/shared";
|
||||
import type { Address, AuditEvent, Note, OrderDetail, OrderItemDetail, OrderSummary } from "@orderops/shared";
|
||||
import { and, asc, desc, eq, inArray, or, sql } from "drizzle-orm";
|
||||
import type { DatabaseContext } from "../db/database";
|
||||
import { addresses, auditEvents, inventory, orderItems, orders, products, users } from "../db/schema";
|
||||
import { addresses, auditEvents, inventory, orderItems, orderNotes, orders, products, users } from "../db/schema";
|
||||
|
||||
function toAddress(row: typeof addresses.$inferSelect): Address {
|
||||
return {
|
||||
@@ -92,6 +92,20 @@ export async function findOrderDetail(context: DatabaseContext, orderId: string)
|
||||
.where(eq(orderItems.orderId, orderId))
|
||||
.orderBy(asc(orderItems.id));
|
||||
|
||||
const notes = await context.db
|
||||
.select({
|
||||
id: orderNotes.id,
|
||||
orderId: orderNotes.orderId,
|
||||
body: orderNotes.body,
|
||||
authorUserId: orderNotes.authorUserId,
|
||||
authorName: users.name,
|
||||
createdAt: orderNotes.createdAt
|
||||
})
|
||||
.from(orderNotes)
|
||||
.innerJoin(users, eq(orderNotes.authorUserId, users.id))
|
||||
.where(eq(orderNotes.orderId, orderId))
|
||||
.orderBy(desc(orderNotes.createdAt));
|
||||
|
||||
return {
|
||||
id: header.order.id,
|
||||
orderNumber: header.order.orderNumber,
|
||||
@@ -104,10 +118,38 @@ export async function findOrderDetail(context: DatabaseContext, orderId: string)
|
||||
email: header.customer.email
|
||||
},
|
||||
shippingAddress: toAddress(header.address),
|
||||
items: itemRows.map(toOrderItemDetail)
|
||||
items: itemRows.map(toOrderItemDetail),
|
||||
notes
|
||||
} satisfies OrderDetail;
|
||||
}
|
||||
|
||||
export async function insertOrderNote(
|
||||
context: DatabaseContext,
|
||||
input: {
|
||||
orderId: string;
|
||||
authorUserId: string;
|
||||
body: string;
|
||||
}
|
||||
) {
|
||||
const [author] = await context.db.select({ name: users.name }).from(users).where(eq(users.id, input.authorUserId));
|
||||
|
||||
if (!author) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const note = {
|
||||
id: crypto.randomUUID(),
|
||||
orderId: input.orderId,
|
||||
body: input.body,
|
||||
authorUserId: input.authorUserId,
|
||||
createdAt: new Date().toISOString()
|
||||
} satisfies typeof orderNotes.$inferInsert;
|
||||
|
||||
await context.db.insert(orderNotes).values(note);
|
||||
|
||||
return { ...note, authorName: author.name } satisfies Note;
|
||||
}
|
||||
|
||||
export async function findOrderItemRecord(context: DatabaseContext, orderId: string, itemId: string) {
|
||||
const [row] = await context.db
|
||||
.select({ order: orders, item: orderItems, inventory })
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Address, AuthUser } from "@orderops/shared";
|
||||
import type { FastifyPluginAsync, FastifyRequest } from "fastify";
|
||||
import { requireEmployeeUser } from "../auth/current-user";
|
||||
import type { DatabaseContext } from "../db/database";
|
||||
import { addOrderNote } from "./add-order-note";
|
||||
import { cancelOrder } from "./cancel-order";
|
||||
import { getOrder } from "./get-order";
|
||||
import { listAuditEvents } from "./list-audit-events";
|
||||
@@ -33,6 +34,10 @@ interface CancelBody {
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
interface NoteBody {
|
||||
body: string;
|
||||
}
|
||||
|
||||
type AuthenticatedRequest = FastifyRequest & { currentUser: AuthUser };
|
||||
|
||||
export const registerOrderRoutes: FastifyPluginAsync<OrderRouteOptions> = async (app, options) => {
|
||||
@@ -69,6 +74,31 @@ export const registerOrderRoutes: FastifyPluginAsync<OrderRouteOptions> = async
|
||||
|
||||
app.get<{ Params: IdParams }>("/orders/:orderId/audit-events", async (request) => listAuditEvents(options.db, request.params.orderId));
|
||||
|
||||
app.post<{ Params: IdParams; Body: NoteBody }>("/orders/:orderId/notes", {
|
||||
schema: {
|
||||
body: {
|
||||
type: "object",
|
||||
required: ["body"],
|
||||
properties: {
|
||||
body: { type: "string", minLength: 1, maxLength: 1999 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}, async (request, reply) => {
|
||||
const currentUser = (request as AuthenticatedRequest).currentUser;
|
||||
const result = await addOrderNote(options.db, {
|
||||
orderId: request.params.orderId,
|
||||
authorUserId: currentUser.id,
|
||||
body: request.body.body
|
||||
});
|
||||
|
||||
if (result.statusCode !== 200) {
|
||||
return reply.code(result.statusCode).send({ message: result.message });
|
||||
}
|
||||
|
||||
return result.note;
|
||||
});
|
||||
|
||||
app.post<{ Params: OrderItemParams; Body: QuantityBody }>("/orders/:orderId/items/:itemId/quantity", {
|
||||
schema: {
|
||||
body: {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
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 = "";
|
||||
|
||||
function firstHeader(value: string | string[] | undefined) {
|
||||
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");
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("assignment 1 search behavior", () => {
|
||||
test("searches orders case-insensitively by customer name", async () => {
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/orders?query=JOHN",
|
||||
headers: { cookie: employeeCookie }
|
||||
});
|
||||
|
||||
const orders = response.json();
|
||||
const orderNumbers = orders.map((order: { orderNumber: string }) => order.orderNumber);
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(orderNumbers).toContain("ORD-1001");
|
||||
expect(orderNumbers).toContain("ORD-1003");
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,15 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import type { Note, OrderDetail } from "@orderops/shared";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { AppWithContext } from "../app";
|
||||
import { buildApp } from "../app";
|
||||
import { orderNotes, users } from "../db/schema";
|
||||
import { createUser } from "../users/user-repository";
|
||||
|
||||
let app: AppWithContext;
|
||||
let employeeCookie = "";
|
||||
let customerCookie = "";
|
||||
let employeeId = "";
|
||||
|
||||
async function login(username: string) {
|
||||
const response = await app.inject({ method: "POST", url: "/api/login", payload: { username } });
|
||||
@@ -15,13 +19,14 @@ async function login(username: string) {
|
||||
beforeEach(async () => {
|
||||
app = await buildApp(":memory:");
|
||||
|
||||
await createUser(app.dbContext, {
|
||||
const employee = await createUser(app.dbContext, {
|
||||
username: "dev-employee",
|
||||
name: "Dev Employee",
|
||||
email: "dev.employee@example.com",
|
||||
role: "employee"
|
||||
});
|
||||
|
||||
employeeId = employee.id;
|
||||
employeeCookie = await login("dev-employee");
|
||||
customerCookie = await login("john-smith");
|
||||
});
|
||||
@@ -30,6 +35,161 @@ afterEach(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("order notes", () => {
|
||||
async function createNote(orderId: string, body: string) {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: `/api/orders/${orderId}/notes`,
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { body }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
return response.json<Note>();
|
||||
}
|
||||
|
||||
async function getNotes(orderId: string) {
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/orders/${orderId}`,
|
||||
headers: { cookie: employeeCookie }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
return response.json<OrderDetail>().notes;
|
||||
}
|
||||
|
||||
test("creates a note and retrieves it with its order", async () => {
|
||||
expect(await getNotes("order_1")).toEqual([]);
|
||||
const startedAt = Date.now();
|
||||
const note = await createNote("order_1", "Call the warehouse before shipping.");
|
||||
|
||||
expect(note.id).toBeTruthy();
|
||||
expect(note.orderId).toBe("order_1");
|
||||
expect(note.body).toBe("Call the warehouse before shipping.");
|
||||
expect(note.authorUserId).toBe(employeeId);
|
||||
expect(note.authorName).toBe("Dev Employee");
|
||||
expect(Date.parse(note.createdAt)).toBeGreaterThanOrEqual(startedAt);
|
||||
expect(Date.parse(note.createdAt)).toBeLessThanOrEqual(Date.now());
|
||||
expect(await getNotes("order_1")).toEqual([note]);
|
||||
});
|
||||
|
||||
test("resolves the author's current display name when retrieving notes", async () => {
|
||||
const note = await createNote("order_1", "Waiting for confirmation.");
|
||||
await app.dbContext.db.update(users).set({ name: "Updated Employee" }).where(eq(users.id, employeeId));
|
||||
|
||||
expect(await getNotes("order_1")).toEqual([{ ...note, authorName: "Updated Employee" }]);
|
||||
});
|
||||
|
||||
test("uses session authorship instead of an author supplied in the payload", async () => {
|
||||
const otherEmployee = await createUser(app.dbContext, {
|
||||
username: "other-employee",
|
||||
name: "Other Employee",
|
||||
email: "other.employee@example.com",
|
||||
role: "employee"
|
||||
});
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_1/notes",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { body: "Internal context", authorUserId: otherEmployee.id, authorName: otherEmployee.name }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const note = response.json<Note>();
|
||||
expect(note.authorUserId).toBe(employeeId);
|
||||
expect(note.authorName).toBe("Dev Employee");
|
||||
expect(await getNotes("order_1")).toEqual([note]);
|
||||
});
|
||||
|
||||
test("rejects customers and anonymous users from adding or reading order notes", async () => {
|
||||
const note = await createNote("order_1", "Employee-only context");
|
||||
|
||||
for (const access of [{ cookie: customerCookie, statusCode: 403 }, { cookie: "", statusCode: 401 }]) {
|
||||
const headers = { cookie: access.cookie };
|
||||
const createResponse = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_1/notes",
|
||||
headers,
|
||||
payload: { body: "Unauthorized note" }
|
||||
});
|
||||
const readResponse = await app.inject({ method: "GET", url: "/api/orders/order_1", headers });
|
||||
|
||||
expect(createResponse.statusCode).toBe(access.statusCode);
|
||||
expect(readResponse.statusCode).toBe(access.statusCode);
|
||||
expect(readResponse.body).not.toContain(note.body);
|
||||
}
|
||||
|
||||
expect(await getNotes("order_1")).toEqual([note]);
|
||||
});
|
||||
|
||||
for (const { label, body } of [
|
||||
{ label: "empty", body: "" },
|
||||
{ label: "whitespace-only", body: " \n\t " },
|
||||
{ label: "2000-character", body: "x".repeat(2000) },
|
||||
{ label: "over-length", body: "x".repeat(2001) }
|
||||
]) {
|
||||
test(`rejects ${label} notes without saving them`, async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_1/notes",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { body }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(await getNotes("order_1")).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
test("accepts a note just below the 2000-character limit", async () => {
|
||||
const body = "x".repeat(1999);
|
||||
const note = await createNote("order_1", body);
|
||||
|
||||
expect(note.body).toBe(body);
|
||||
expect(await getNotes("order_1")).toEqual([note]);
|
||||
});
|
||||
|
||||
test("returns not found when adding a note to a missing order", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/missing-order/notes",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { body: "Follow up" }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
expect(response.json<{ message: string }>()).toEqual({ message: "Order not found." });
|
||||
expect(await app.dbContext.db.select().from(orderNotes)).toEqual([]);
|
||||
});
|
||||
|
||||
test("returns notes newest first regardless of insertion order", async () => {
|
||||
const middle = await createNote("order_1", "Middle note");
|
||||
const newest = await createNote("order_1", "Newest note");
|
||||
const oldest = await createNote("order_1", "Oldest note");
|
||||
|
||||
// Fixed timestamps keep ordering independent of clock resolution and test speed.
|
||||
for (const [note, createdAt] of [
|
||||
[middle, "2026-01-02T00:00:00.000Z"],
|
||||
[newest, "2026-01-03T00:00:00.000Z"],
|
||||
[oldest, "2026-01-01T00:00:00.000Z"]
|
||||
] as const) {
|
||||
await app.dbContext.db.update(orderNotes).set({ createdAt }).where(eq(orderNotes.id, note.id));
|
||||
}
|
||||
|
||||
expect((await getNotes("order_1")).map((note) => note.id)).toEqual([newest.id, middle.id, oldest.id]);
|
||||
});
|
||||
|
||||
test("keeps notes isolated to their own orders", async () => {
|
||||
const first = await createNote("order_1", "First order context");
|
||||
const second = await createNote("order_2", "Second order context");
|
||||
|
||||
expect(await getNotes("order_1")).toEqual([first]);
|
||||
expect(await getNotes("order_2")).toEqual([second]);
|
||||
expect(await getNotes("order_3")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("order routes", () => {
|
||||
test("rejects customer access", async () => {
|
||||
const response = await app.inject({ method: "GET", url: "/api/orders", headers: { cookie: customerCookie } });
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,4 +1,4 @@
|
||||
import type { Address, AuditEvent, OrderDetail, OrderSummary } from "@orderops/shared";
|
||||
import type { Address, AuditEvent, Note, OrderDetail, OrderSummary } from "@orderops/shared";
|
||||
import { apiRequest } from "../lib/api-client";
|
||||
|
||||
export function listOrders(query: string) {
|
||||
@@ -14,6 +14,13 @@ export function listAuditEvents(orderId: string) {
|
||||
return apiRequest<AuditEvent[]>(`/api/orders/${orderId}/audit-events`);
|
||||
}
|
||||
|
||||
export function addOrderNote(orderId: string, body: string) {
|
||||
return apiRequest<Note>(`/api/orders/${orderId}/notes`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ body })
|
||||
});
|
||||
}
|
||||
|
||||
export function updateOrderItemQuantity(orderId: string, itemId: string, quantity: number) {
|
||||
return apiRequest<OrderDetail>(`/api/orders/${orderId}/items/${itemId}/quantity`, {
|
||||
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-panel";
|
||||
import { OrderSummaryPanel } from "./order-summary";
|
||||
import { ShippingAddressForm } from "./shipping-address-form";
|
||||
|
||||
@@ -10,6 +11,7 @@ interface OrderDetailPageProps {
|
||||
onUpdateQuantity: (itemId: string, quantity: number) => Promise<void>;
|
||||
onSaveAddress: (address: Address) => Promise<void>;
|
||||
onCancel: () => Promise<void>;
|
||||
onAddNote: (body: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export function OrderDetailPage({
|
||||
@@ -17,7 +19,8 @@ export function OrderDetailPage({
|
||||
auditEvents,
|
||||
onUpdateQuantity,
|
||||
onSaveAddress,
|
||||
onCancel
|
||||
onCancel,
|
||||
onAddNote
|
||||
}: OrderDetailPageProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -29,6 +32,7 @@ export function OrderDetailPage({
|
||||
</div>
|
||||
<OrderItemsPanel order={order} onUpdateQuantity={onUpdateQuantity} />
|
||||
<ShippingAddressForm order={order} onSave={onSaveAddress} />
|
||||
<OrderNotesPanel key={order.id} order={order} onAddNote={onAddNote} />
|
||||
<AuditTimeline events={auditEvents} />
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useState } from "react";
|
||||
import type { OrderDetail } from "@orderops/shared";
|
||||
|
||||
interface OrderNotesPanelProps {
|
||||
order: OrderDetail;
|
||||
onAddNote: (body: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export function OrderNotesPanel({ order, onAddNote }: OrderNotesPanelProps) {
|
||||
const [body, setBody] = useState("");
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const notes = [...order.notes].sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));
|
||||
|
||||
return (
|
||||
<section className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
|
||||
<h3 className="mb-3 text-sm font-semibold text-slate-700">Internal notes</h3>
|
||||
{notes.length ? (
|
||||
<ul className="space-y-3">
|
||||
{notes.map((note) => (
|
||||
<li key={note.id} className="rounded-lg border border-slate-200 p-3">
|
||||
<div className="text-xs text-slate-500">
|
||||
Author: {note.authorName} {"\u00b7"} <time dateTime={note.createdAt}>{new Date(note.createdAt).toLocaleString()}</time>
|
||||
</div>
|
||||
<p className="mt-1 whitespace-pre-wrap [overflow-wrap:anywhere] text-sm text-slate-900">{note.body}</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="text-sm text-slate-500">No internal notes yet.</p>
|
||||
)}
|
||||
<form
|
||||
className="mt-4 space-y-3"
|
||||
aria-busy={isPending}
|
||||
onSubmit={async (event) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (isPending) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!body.trim() || body.length >= 2000) {
|
||||
setError("Note must be non-empty and less than 2000 characters.");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsPending(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await onAddNote(body);
|
||||
setBody("");
|
||||
} catch (caught: unknown) {
|
||||
setError(caught instanceof Error ? caught.message : "Failed to add note.");
|
||||
} finally {
|
||||
setIsPending(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<label className="block text-sm text-slate-700">
|
||||
<span className="mb-1 block">Add an internal note</span>
|
||||
<textarea
|
||||
className="w-full rounded-lg border border-slate-300 px-3 py-2 disabled:opacity-50"
|
||||
rows={4}
|
||||
maxLength={1999}
|
||||
required
|
||||
disabled={isPending}
|
||||
value={body}
|
||||
onChange={(event) => {
|
||||
setBody(event.target.value);
|
||||
setError(null);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
{error ? (
|
||||
<div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
<button
|
||||
className="rounded-md bg-slate-900 px-4 py-2 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-50"
|
||||
type="submit"
|
||||
disabled={isPending || !body.trim()}
|
||||
>
|
||||
{isPending ? "Adding note..." : "Add note"}
|
||||
</button>
|
||||
</form>
|
||||
</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 { addOrderNote, cancelOrder, getOrder, listAuditEvents, updateOrderItemQuantity, updateShippingAddress } from "./order-api";
|
||||
import { OrderDetailPage } from "./order-detail-page";
|
||||
|
||||
interface ToastState {
|
||||
@@ -72,6 +72,33 @@ export function OrderPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAddNote(body: string) {
|
||||
try {
|
||||
if (!orderId) {
|
||||
throw new Error("Order not found.");
|
||||
}
|
||||
|
||||
setError(null);
|
||||
await addOrderNote(orderId, body);
|
||||
} catch (caught) {
|
||||
setToast({
|
||||
message: caught instanceof Error ? caught.message : "Failed to add note.",
|
||||
variant: "error"
|
||||
});
|
||||
throw caught;
|
||||
}
|
||||
|
||||
try {
|
||||
await refreshOrder(orderId);
|
||||
setToast({ message: "Note added.", variant: "success" });
|
||||
} catch {
|
||||
setToast({
|
||||
message: "Note saved, but the page didn't refresh — reload to see it.",
|
||||
variant: "error"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Link className="inline-flex text-sm font-medium text-blue-600 hover:text-blue-700" to="/orders">
|
||||
@@ -87,6 +114,7 @@ export function OrderPage() {
|
||||
onUpdateQuantity={(itemId, quantity) => runAction(() => updateOrderItemQuantity(order.id, itemId, quantity), "Quantity saved.")}
|
||||
onSaveAddress={(address: Address) => runAction(() => updateShippingAddress(order.id, address), "Shipping address saved.")}
|
||||
onCancel={() => runAction(() => cancelOrder(order.id), "Order cancelled.")}
|
||||
onAddNote={handleAddNote}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -13,6 +13,15 @@ export interface OrderItemDetail {
|
||||
availableQuantity: number;
|
||||
}
|
||||
|
||||
export interface Note {
|
||||
id: string;
|
||||
orderId: string;
|
||||
body: string;
|
||||
authorUserId: string;
|
||||
authorName: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface OrderDetail {
|
||||
id: string;
|
||||
orderNumber: string;
|
||||
@@ -22,4 +31,5 @@ export interface OrderDetail {
|
||||
customer: CustomerSummary;
|
||||
shippingAddress: Address;
|
||||
items: OrderItemDetail[];
|
||||
notes: Note[];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user