Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
12c4bc62c1 | ||
|
|
31b367e3a3 | ||
|
|
877eb9e09a | ||
|
|
6d3570909a | ||
|
|
82ed809f32 | ||
|
|
0e1e64b6ca | ||
|
|
8235ceb61f | ||
|
|
698a49ae82 | ||
|
|
97438aaa56 | ||
|
|
2e2694354d | ||
|
|
79b485db56 | ||
|
|
4c0783091a | ||
|
|
12a262e640 | ||
|
|
32931e697f | ||
|
|
0cfe045afa |
@@ -5,7 +5,6 @@ Describe problem and user or business impact.
|
||||
## Ticket / Assignment
|
||||
|
||||
- Ticket:
|
||||
- Assignment:
|
||||
|
||||
## What changed
|
||||
|
||||
@@ -18,7 +17,6 @@ Describe problem and user or business impact.
|
||||
List exact commands and manual checks.
|
||||
|
||||
```bash
|
||||
bun run check
|
||||
bun run test
|
||||
bun run build:web
|
||||
```
|
||||
|
||||
@@ -8,3 +8,4 @@ bun.lock
|
||||
*.sqlite-wal
|
||||
dist
|
||||
coverage
|
||||
pi-session*
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# Typescript Full Stack App Agent
|
||||
|
||||
## Coding Conventions
|
||||
- Before planning any code plan, check the `CONTRIBUTING.md` file in the root directory of the project to understand and apply coding conventions for this project
|
||||
- Instead of reading and parsing the `CONTRIBUTING.md` every time, cache the findings of `CONTRIBUTING.md` and refer to this cache'd file whenever checking the conventions is required
|
||||
|
||||
## Output Rules
|
||||
|
||||
### Response Style
|
||||
@@ -176,4 +180,3 @@ Skip `discover_context` for narrow tasks with explicit file targets.
|
||||
### Boundaries
|
||||
- Recon is read-only unless user requested implementation.
|
||||
- Do not treat scout output as complete when evidence suggests missing files.
|
||||
|
||||
|
||||
@@ -28,7 +28,6 @@ bun run dev:web
|
||||
Common checks:
|
||||
|
||||
```bash
|
||||
bun run check
|
||||
bun run test
|
||||
bun run build:web
|
||||
```
|
||||
|
||||
@@ -21,7 +21,6 @@ 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;
|
||||
@@ -91,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,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
@@ -103,14 +103,6 @@ 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),
|
||||
@@ -128,4 +120,8 @@ export function initializeDatabase(sqlite: Database) {
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
`);
|
||||
|
||||
if (!columnExists(sqlite, "orders", "notes")) {
|
||||
sqlite.exec("ALTER TABLE orders ADD COLUMN notes TEXT");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"),
|
||||
createdAt: text("created_at").notNull(),
|
||||
updatedAt: text("updated_at").notNull()
|
||||
});
|
||||
@@ -20,11 +21,3 @@ 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()
|
||||
});
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
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,5 +1,5 @@
|
||||
import { canCancelOrder, orderCancellationBlockedMessage } from "@orderops/shared/order-status";
|
||||
import type { DatabaseContext } from "../db/database";
|
||||
import { canCancelOrder } from "./order-status";
|
||||
import { appendAuditEvent, findOrderDetail, updateOrderStatus } from "./order-repository";
|
||||
|
||||
export async function cancelOrder(
|
||||
@@ -17,7 +17,7 @@ export async function cancelOrder(
|
||||
}
|
||||
|
||||
if (!canCancelOrder(order.status)) {
|
||||
return { statusCode: 400, message: "Order cannot be cancelled for this order status." } as const;
|
||||
return { statusCode: 400, message: orderCancellationBlockedMessage } as const;
|
||||
}
|
||||
|
||||
const updatedAt = new Date().toISOString();
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
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 3 quantity validation", () => {
|
||||
test("allows quantity changes for pending orders", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_1/items/item_1/quantity",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { quantity: 5 }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().items.find((item: { id: string }) => item.id === "item_1")?.quantity).toBe(5);
|
||||
});
|
||||
|
||||
test("rejects quantity changes for processing orders", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_2/items/item_3/quantity",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { quantity: 2 }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
test("rejects quantity changes for shipped orders", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_3/items/item_4/quantity",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { quantity: 1 }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
test("rejects quantity outside the allowed range", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_1/items/item_1/quantity",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { quantity: 0 }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
test("rejects quantity above effective inventory", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_1/items/item_1/quantity",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { quantity: 9 }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Address, AuditEvent, Note, OrderDetail, OrderItemDetail, OrderSummary } from "@orderops/shared";
|
||||
import type { Address, AuditEvent, 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, orderNotes, orders, products, users } from "../db/schema";
|
||||
import { addresses, auditEvents, inventory, orderItems, orders, products, users } from "../db/schema";
|
||||
|
||||
function toAddress(row: typeof addresses.$inferSelect): Address {
|
||||
return {
|
||||
@@ -35,13 +35,13 @@ function toOrderItemDetail(row: {
|
||||
}
|
||||
|
||||
export async function listOrderSummaries(context: DatabaseContext, query?: string) {
|
||||
const search = query?.trim();
|
||||
const search = query?.trim().toLowerCase();
|
||||
|
||||
const filters = search
|
||||
? or(
|
||||
sql`instr(${orders.orderNumber}, ${search}) > 0`,
|
||||
sql`instr(${users.name}, ${search}) > 0`,
|
||||
sql`instr(${users.email}, ${search}) > 0`
|
||||
sql`instr(lower(${orders.orderNumber}), ${search}) > 0`,
|
||||
sql`instr(lower(${users.name}), ${search}) > 0`,
|
||||
sql`instr(lower(${users.email}), ${search}) > 0`
|
||||
)
|
||||
: undefined;
|
||||
|
||||
@@ -92,64 +92,23 @@ 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,
|
||||
status: header.order.status as OrderDetail["status"],
|
||||
createdAt: header.order.createdAt,
|
||||
updatedAt: header.order.updatedAt,
|
||||
notes: header.order.notes,
|
||||
customer: {
|
||||
id: header.customer.id,
|
||||
name: header.customer.name,
|
||||
email: header.customer.email
|
||||
},
|
||||
shippingAddress: toAddress(header.address),
|
||||
items: itemRows.map(toOrderItemDetail),
|
||||
notes
|
||||
items: itemRows.map(toOrderItemDetail)
|
||||
} 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 })
|
||||
@@ -158,13 +117,24 @@ export async function findOrderItemRecord(context: DatabaseContext, orderId: str
|
||||
.leftJoin(inventory, eq(orderItems.productId, inventory.productId))
|
||||
.where(and(eq(orderItems.id, itemId), eq(orderItems.orderId, orderId)));
|
||||
|
||||
return row ?? null;
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
...row,
|
||||
order: { ...row.order, status: row.order.status as OrderDetail["status"] }
|
||||
};
|
||||
}
|
||||
|
||||
export async function updateOrderItemQuantity(context: DatabaseContext, itemId: string, quantity: number) {
|
||||
await context.db.update(orderItems).set({ quantity }).where(eq(orderItems.id, itemId));
|
||||
}
|
||||
|
||||
export async function updateOrderNotes(context: DatabaseContext, orderId: string, notes: string) {
|
||||
await context.db.update(orders).set({ notes }).where(eq(orders.id, orderId));
|
||||
}
|
||||
|
||||
export async function updateOrderTimestamp(context: DatabaseContext, orderId: string, updatedAt: string) {
|
||||
await context.db.update(orders).set({ updatedAt }).where(eq(orders.id, orderId));
|
||||
}
|
||||
|
||||
@@ -2,12 +2,11 @@ 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";
|
||||
import { listOrders } from "./list-orders";
|
||||
import { changeOrderItemQuantity } from "./update-order-item";
|
||||
import { changeOrderItemQuantity, updateOrderNotes } from "./update-order-item";
|
||||
import { changeShippingAddress } from "./update-shipping-address";
|
||||
|
||||
interface OrderRouteOptions {
|
||||
@@ -34,8 +33,8 @@ interface CancelBody {
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
interface NoteBody {
|
||||
body: string;
|
||||
interface NotesBody {
|
||||
notes: string;
|
||||
}
|
||||
|
||||
type AuthenticatedRequest = FastifyRequest & { currentUser: AuthUser };
|
||||
@@ -74,31 +73,6 @@ 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: {
|
||||
@@ -125,6 +99,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", maxLength: 1000 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}, async (request, reply) => {
|
||||
const currentUser = (request as AuthenticatedRequest).currentUser;
|
||||
const result = await updateOrderNotes(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,108 @@
|
||||
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 4 order lifecycle rules", () => {
|
||||
test("keeps quantity editing blocked for processing orders", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_2/items/item_3/quantity",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { quantity: 2 }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
test("allows address editing for processing orders", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_2/shipping-address",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: {
|
||||
fullName: "Jane Doe",
|
||||
line1: "50 New Street",
|
||||
line2: null,
|
||||
city: "Oakland",
|
||||
state: "CA",
|
||||
postalCode: "94607",
|
||||
country: "US"
|
||||
}
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().shippingAddress.city).toBe("Oakland");
|
||||
});
|
||||
|
||||
test("allows cancellation for processing orders", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_2/cancel",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { reason: "Customer request" }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().status).toBe("cancelled");
|
||||
});
|
||||
|
||||
test("blocks address editing for shipped orders", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_3/shipping-address",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: {
|
||||
fullName: "John Smith",
|
||||
line1: "77 Final Mile Road",
|
||||
line2: null,
|
||||
city: "Denver",
|
||||
state: "CO",
|
||||
postalCode: "80202",
|
||||
country: "US"
|
||||
}
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
test("blocks cancellation for shipped orders", async () => {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/orders/order_3/cancel",
|
||||
headers: { cookie: employeeCookie },
|
||||
payload: { reason: "Late request" }
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
import type { OrderStatus } from "@orderops/shared/order-status";
|
||||
|
||||
export function canEditOrderItems(status: OrderStatus) {
|
||||
return status === "pending" || status === "processing";
|
||||
}
|
||||
|
||||
export function canEditShippingAddress(status: OrderStatus) {
|
||||
return status === "pending" || status === "processing";
|
||||
}
|
||||
|
||||
export function canCancelOrder(status: OrderStatus) {
|
||||
return status === "pending" || status === "processing";
|
||||
}
|
||||
@@ -1,15 +1,11 @@
|
||||
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 } });
|
||||
@@ -19,14 +15,13 @@ async function login(username: string) {
|
||||
beforeEach(async () => {
|
||||
app = await buildApp(":memory:");
|
||||
|
||||
const employee = await createUser(app.dbContext, {
|
||||
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");
|
||||
});
|
||||
@@ -35,161 +30,6 @@ 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 } });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { canEditOrderItems, orderItemsLockedMessage } from "@orderops/shared/order-status";
|
||||
import type { DatabaseContext } from "../db/database";
|
||||
import { canEditOrderItems } from "./order-status";
|
||||
import { appendAuditEvent, findOrderDetail, findOrderItemRecord, updateOrderItemQuantity, updateOrderTimestamp } from "./order-repository";
|
||||
import { appendAuditEvent, findOrderDetail, findOrderItemRecord, updateOrderItemQuantity, updateOrderNotes as saveOrderNotes, updateOrderTimestamp } from "./order-repository";
|
||||
|
||||
export async function changeOrderItemQuantity(
|
||||
context: DatabaseContext,
|
||||
@@ -17,8 +17,8 @@ export async function changeOrderItemQuantity(
|
||||
return { statusCode: 404, message: "Order item not found." } as const;
|
||||
}
|
||||
|
||||
if (!canEditOrderItems(row.order.status as never)) {
|
||||
return { statusCode: 400, message: "Order items cannot be changed for this order status." } as const;
|
||||
if (!canEditOrderItems(row.order.status)) {
|
||||
return { statusCode: 400, message: orderItemsLockedMessage } as const;
|
||||
}
|
||||
|
||||
if (input.quantity < 1 || input.quantity > 10) {
|
||||
@@ -47,3 +47,44 @@ export async function changeOrderItemQuantity(
|
||||
order: await findOrderDetail(context, input.orderId)
|
||||
} as const;
|
||||
}
|
||||
|
||||
export async function updateOrderNotes(
|
||||
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) {
|
||||
return { statusCode: 400, message: "Notes cannot be empty." } as const;
|
||||
}
|
||||
|
||||
if (notes.length > 1000) {
|
||||
return { statusCode: 400, message: "Notes must be 1000 characters or fewer." } as const;
|
||||
}
|
||||
|
||||
const updatedAt = new Date().toISOString();
|
||||
await saveOrderNotes(context, input.orderId, notes);
|
||||
await updateOrderTimestamp(context, input.orderId, updatedAt);
|
||||
await appendAuditEvent(context, {
|
||||
orderId: input.orderId,
|
||||
actor: input.actor,
|
||||
type: "order.notes_updated",
|
||||
message: "Updated internal order notes.",
|
||||
createdAt: updatedAt
|
||||
});
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
order: await findOrderDetail(context, input.orderId)
|
||||
} as const;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Address } from "@orderops/shared/address";
|
||||
import { canEditShippingAddress, shippingAddressLockedMessage } from "@orderops/shared/order-status";
|
||||
import type { DatabaseContext } from "../db/database";
|
||||
import { canEditShippingAddress } from "./order-status";
|
||||
import { appendAuditEvent, findOrderDetail, updateOrderAddress, updateOrderTimestamp } from "./order-repository";
|
||||
|
||||
export async function changeShippingAddress(
|
||||
@@ -18,7 +18,7 @@ export async function changeShippingAddress(
|
||||
}
|
||||
|
||||
if (!canEditShippingAddress(order.status)) {
|
||||
return { statusCode: 400, message: "Shipping address cannot be changed for this order status." } as const;
|
||||
return { statusCode: 400, message: shippingAddressLockedMessage } as const;
|
||||
}
|
||||
|
||||
const updatedAt = new Date().toISOString();
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,4 +1,4 @@
|
||||
import type { Address, AuditEvent, Note, OrderDetail, OrderSummary } from "@orderops/shared";
|
||||
import type { Address, AuditEvent, OrderDetail, OrderSummary } from "@orderops/shared";
|
||||
import { apiRequest } from "../lib/api-client";
|
||||
|
||||
export function listOrders(query: string) {
|
||||
@@ -14,13 +14,6 @@ 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",
|
||||
@@ -28,6 +21,13 @@ export function updateOrderItemQuantity(orderId: string, itemId: string, quantit
|
||||
});
|
||||
}
|
||||
|
||||
export function updateOrderNotes(orderId: string, notes: string) {
|
||||
return apiRequest<OrderDetail>(`/api/orders/${orderId}/notes`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ notes })
|
||||
});
|
||||
}
|
||||
|
||||
export function updateShippingAddress(orderId: string, address: Address) {
|
||||
return apiRequest<OrderDetail>(`/api/orders/${orderId}/shipping-address`, {
|
||||
method: "POST",
|
||||
|
||||
@@ -1,7 +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 { OrderNotes } from "./order-notes";
|
||||
import { OrderSummaryPanel } from "./order-summary";
|
||||
import { ShippingAddressForm } from "./shipping-address-form";
|
||||
|
||||
@@ -10,8 +10,8 @@ interface OrderDetailPageProps {
|
||||
auditEvents: AuditEvent[];
|
||||
onUpdateQuantity: (itemId: string, quantity: number) => Promise<void>;
|
||||
onSaveAddress: (address: Address) => Promise<void>;
|
||||
onSaveNotes: (notes: string) => Promise<void>;
|
||||
onCancel: () => Promise<void>;
|
||||
onAddNote: (body: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export function OrderDetailPage({
|
||||
@@ -19,8 +19,8 @@ export function OrderDetailPage({
|
||||
auditEvents,
|
||||
onUpdateQuantity,
|
||||
onSaveAddress,
|
||||
onCancel,
|
||||
onAddNote
|
||||
onSaveNotes,
|
||||
onCancel
|
||||
}: OrderDetailPageProps) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -32,7 +32,7 @@ export function OrderDetailPage({
|
||||
</div>
|
||||
<OrderItemsPanel order={order} onUpdateQuantity={onUpdateQuantity} />
|
||||
<ShippingAddressForm order={order} onSave={onSaveAddress} />
|
||||
<OrderNotesPanel key={order.id} order={order} onAddNote={onAddNote} />
|
||||
<OrderNotes order={order} onSave={onSaveNotes} />
|
||||
<AuditTimeline events={auditEvents} />
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useState } from "react";
|
||||
import type { OrderDetail } from "@orderops/shared";
|
||||
|
||||
interface OrderNotesProps {
|
||||
order: OrderDetail;
|
||||
onSave: (notes: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export function OrderNotes({ order, onSave }: OrderNotesProps) {
|
||||
const [notes, setNotes] = useState(order.notes ?? "");
|
||||
|
||||
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>
|
||||
<form
|
||||
className="space-y-3"
|
||||
onSubmit={async (event) => {
|
||||
event.preventDefault();
|
||||
await onSave(notes);
|
||||
}}
|
||||
>
|
||||
<label className="block text-sm text-slate-700">
|
||||
<span className="mb-1 block">Notes</span>
|
||||
<textarea
|
||||
className="w-full resize-none rounded-lg border border-slate-300 px-3 py-2"
|
||||
rows={5}
|
||||
value={notes}
|
||||
onChange={(event) => setNotes(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button className="rounded-md bg-slate-900 px-4 py-2 text-sm font-medium text-white" type="submit">
|
||||
Save notes
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { Address, AuditEvent, OrderDetail } from "@orderops/shared";
|
||||
import { canEditOrderItems, orderItemsLockedMessage, type Address, type AuditEvent, type OrderDetail } from "@orderops/shared";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { Toast } from "../ui/toast";
|
||||
import { addOrderNote, 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 {
|
||||
@@ -72,31 +72,17 @@ 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;
|
||||
async function handleUpdateQuantity(itemId: string, quantity: number) {
|
||||
if (!order) {
|
||||
return;
|
||||
}
|
||||
|
||||
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"
|
||||
});
|
||||
if (!canEditOrderItems(order.status)) {
|
||||
setToast({ message: orderItemsLockedMessage, variant: "error" });
|
||||
return;
|
||||
}
|
||||
|
||||
await runAction(() => updateOrderItemQuantity(order.id, itemId, quantity), "Quantity saved.");
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -111,10 +97,10 @@ export function OrderPage() {
|
||||
<OrderDetailPage
|
||||
order={order}
|
||||
auditEvents={auditEvents}
|
||||
onUpdateQuantity={(itemId, quantity) => runAction(() => updateOrderItemQuantity(order.id, itemId, quantity), "Quantity saved.")}
|
||||
onUpdateQuantity={handleUpdateQuantity}
|
||||
onSaveAddress={(address: Address) => runAction(() => updateShippingAddress(order.id, address), "Shipping address saved.")}
|
||||
onSaveNotes={(notes) => runAction(() => updateOrderNotes(order.id, notes), "Notes saved.")}
|
||||
onCancel={() => runAction(() => cancelOrder(order.id), "Order cancelled.")}
|
||||
onAddNote={handleAddNote}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -13,23 +13,14 @@ 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;
|
||||
status: OrderStatus;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
notes: string | null;
|
||||
customer: CustomerSummary;
|
||||
shippingAddress: Address;
|
||||
items: OrderItemDetail[];
|
||||
notes: Note[];
|
||||
}
|
||||
|
||||
@@ -1,3 +1,23 @@
|
||||
export const orderStatuses = ["pending", "processing", "shipped", "cancelled", "refunded"] as const;
|
||||
|
||||
export type OrderStatus = (typeof orderStatuses)[number];
|
||||
|
||||
const orderItemsEditableStatuses: readonly OrderStatus[] = ["pending"];
|
||||
const shippingAddressEditableStatuses: readonly OrderStatus[] = ["pending", "processing"];
|
||||
const orderCancellableStatuses: readonly OrderStatus[] = ["pending", "processing"];
|
||||
|
||||
export const orderItemsLockedMessage = "Order items cannot be changed for this order status.";
|
||||
export const shippingAddressLockedMessage = "Shipping address cannot be changed for this order status.";
|
||||
export const orderCancellationBlockedMessage = "Order cannot be cancelled for this order status.";
|
||||
|
||||
export function canEditOrderItems(status: OrderStatus) {
|
||||
return orderItemsEditableStatuses.includes(status);
|
||||
}
|
||||
|
||||
export function canEditShippingAddress(status: OrderStatus) {
|
||||
return shippingAddressEditableStatuses.includes(status);
|
||||
}
|
||||
|
||||
export function canCancelOrder(status: OrderStatus) {
|
||||
return orderCancellableStatuses.includes(status);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user