Compare commits

..
Author SHA1 Message Date
derrick 31b367e3a3 add:assignment 4 tests
Runner Test / test (push) Successful in 16s
2026-10-02 16:54:39 +09:00
derrick 877eb9e09a Merge pull request 'Fix Item Quantity Update Constraints' (#21) from fix/dg-3-item-quantity-update-constraints into master
Runner Test / test (push) Successful in 16s
Reviewed-on: #21
2026-10-02 07:52:27 +00:00
derrick 6d3570909a update:item quantity change conditional
Runner Test / test (push) Successful in 17s
Runner Test / test (pull_request) Successful in 17s
2026-10-02 16:49:25 +09:00
derrick 82ed809f32 update:remove unused check
Runner Test / test (push) Failing after 15s
2026-09-27 22:05:51 +09:00
derrick 0e1e64b6ca add:assignment 3 tests
Runner Test / test (push) Failing after 14s
2026-09-27 22:04:59 +09:00
derrick 8235ceb61f Merge pull request 'Feature Internal Order Notes' (#12) from feat/dg-2-internal-order-notes into master
Runner Test / test (push) Failing after 14s
Reviewed-on: #12
2026-09-25 03:47:36 +00:00
derrick 698a49ae82 add:order notes ui component
Runner Test / test (push) Successful in 17s
Runner Test / test (pull_request) Successful in 16s
2026-09-24 22:35:55 +09:00
derrick 97438aaa56 add:order notes crud 2026-09-24 21:07:19 +09:00
derrick 2e2694354d add:notes column to orders 2026-09-24 18:09:20 +09:00
derrick 79b485db56 add:assignment 2 tests
Runner Test / test (push) Failing after 17s
2026-09-20 00:14:31 +09:00
derrick 4c0783091a update:PR template
Runner Test / test (push) Successful in 15s
2026-09-18 14:27:53 +09:00
derrick 12a262e640 Merge pull request 'Fix case-insensitive search query on order page' (#7) from fix/dg1-order-search-behavior into master
Runner Test / test (push) Successful in 16s
Reviewed-on: #7
2026-09-18 05:23:22 +00:00
derrick 32931e697f update:apply lowercase to query+column
Runner Test / test (push) Successful in 17s
Runner Test / test (pull_request) Successful in 16s
2026-09-17 18:02:25 +09:00
derrick 0cfe045afa update:progress agents file for assignment 2026-09-17 17:48:01 +09:00
22 changed files with 463 additions and 430 deletions
-2
View File
@@ -5,7 +5,6 @@ Describe problem and user or business impact.
## Ticket / Assignment ## Ticket / Assignment
- Ticket: - Ticket:
- Assignment:
## What changed ## What changed
@@ -18,7 +17,6 @@ Describe problem and user or business impact.
List exact commands and manual checks. List exact commands and manual checks.
```bash ```bash
bun run check
bun run test bun run test
bun run build:web bun run build:web
``` ```
+1
View File
@@ -8,3 +8,4 @@ bun.lock
*.sqlite-wal *.sqlite-wal
dist dist
coverage coverage
pi-session*
+4 -1
View File
@@ -1,5 +1,9 @@
# Typescript Full Stack App Agent # 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 ## Output Rules
### Response Style ### Response Style
@@ -176,4 +180,3 @@ Skip `discover_context` for narrow tasks with explicit file targets.
### Boundaries ### Boundaries
- Recon is read-only unless user requested implementation. - Recon is read-only unless user requested implementation.
- Do not treat scout output as complete when evidence suggests missing files. - Do not treat scout output as complete when evidence suggests missing files.
-1
View File
@@ -28,7 +28,6 @@ bun run dev:web
Common checks: Common checks:
```bash ```bash
bun run check
bun run test bun run test
bun run build:web bun run build:web
``` ```
+5 -9
View File
@@ -21,7 +21,6 @@ function resetLegacySchema(sqlite: Database) {
DROP TABLE IF EXISTS sessions; DROP TABLE IF EXISTS sessions;
DROP TABLE IF EXISTS audit_events; DROP TABLE IF EXISTS audit_events;
DROP TABLE IF EXISTS refunds; DROP TABLE IF EXISTS refunds;
DROP TABLE IF EXISTS order_notes;
DROP TABLE IF EXISTS order_items; DROP TABLE IF EXISTS order_items;
DROP TABLE IF EXISTS orders; DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS inventory; DROP TABLE IF EXISTS inventory;
@@ -91,6 +90,7 @@ export function initializeDatabase(sqlite: Database) {
customer_id TEXT NOT NULL REFERENCES users(id), customer_id TEXT NOT NULL REFERENCES users(id),
shipping_address_id TEXT NOT NULL REFERENCES addresses(id), shipping_address_id TEXT NOT NULL REFERENCES addresses(id),
status TEXT NOT NULL, status TEXT NOT NULL,
notes TEXT,
created_at TEXT NOT NULL, created_at TEXT NOT NULL,
updated_at TEXT NOT NULL updated_at TEXT NOT NULL
); );
@@ -103,14 +103,6 @@ export function initializeDatabase(sqlite: Database) {
unit_price_cents INTEGER NOT NULL 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 ( CREATE TABLE IF NOT EXISTS refunds (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
order_id TEXT NOT NULL REFERENCES orders(id), order_id TEXT NOT NULL REFERENCES orders(id),
@@ -128,4 +120,8 @@ export function initializeDatabase(sqlite: Database) {
created_at TEXT NOT NULL created_at TEXT NOT NULL
); );
`); `);
if (!columnExists(sqlite, "orders", "notes")) {
sqlite.exec("ALTER TABLE orders ADD COLUMN notes TEXT");
}
} }
+1 -8
View File
@@ -9,6 +9,7 @@ export const orders = sqliteTable("orders", {
customerId: text("customer_id").notNull().references(() => users.id), customerId: text("customer_id").notNull().references(() => users.id),
shippingAddressId: text("shipping_address_id").notNull().references(() => addresses.id), shippingAddressId: text("shipping_address_id").notNull().references(() => addresses.id),
status: text("status").notNull(), status: text("status").notNull(),
notes: text("notes"),
createdAt: text("created_at").notNull(), createdAt: text("created_at").notNull(),
updatedAt: text("updated_at").notNull() updatedAt: text("updated_at").notNull()
}); });
@@ -20,11 +21,3 @@ export const orderItems = sqliteTable("order_items", {
quantity: integer("quantity").notNull(), quantity: integer("quantity").notNull(),
unitPriceCents: integer("unit_price_cents").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()
});
-29
View File
@@ -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;
}
@@ -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);
});
});
+12 -49
View File
@@ -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 { and, asc, desc, eq, inArray, or, sql } from "drizzle-orm";
import type { DatabaseContext } from "../db/database"; 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 { function toAddress(row: typeof addresses.$inferSelect): Address {
return { return {
@@ -35,13 +35,13 @@ function toOrderItemDetail(row: {
} }
export async function listOrderSummaries(context: DatabaseContext, query?: string) { export async function listOrderSummaries(context: DatabaseContext, query?: string) {
const search = query?.trim(); const search = query?.trim().toLowerCase();
const filters = search const filters = search
? or( ? or(
sql`instr(${orders.orderNumber}, ${search}) > 0`, sql`instr(lower(${orders.orderNumber}), ${search}) > 0`,
sql`instr(${users.name}, ${search}) > 0`, sql`instr(lower(${users.name}), ${search}) > 0`,
sql`instr(${users.email}, ${search}) > 0` sql`instr(lower(${users.email}), ${search}) > 0`
) )
: undefined; : undefined;
@@ -92,64 +92,23 @@ export async function findOrderDetail(context: DatabaseContext, orderId: string)
.where(eq(orderItems.orderId, orderId)) .where(eq(orderItems.orderId, orderId))
.orderBy(asc(orderItems.id)); .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 { return {
id: header.order.id, id: header.order.id,
orderNumber: header.order.orderNumber, orderNumber: header.order.orderNumber,
status: header.order.status as OrderDetail["status"], status: header.order.status as OrderDetail["status"],
createdAt: header.order.createdAt, createdAt: header.order.createdAt,
updatedAt: header.order.updatedAt, updatedAt: header.order.updatedAt,
notes: header.order.notes,
customer: { customer: {
id: header.customer.id, id: header.customer.id,
name: header.customer.name, name: header.customer.name,
email: header.customer.email email: header.customer.email
}, },
shippingAddress: toAddress(header.address), shippingAddress: toAddress(header.address),
items: itemRows.map(toOrderItemDetail), items: itemRows.map(toOrderItemDetail)
notes
} satisfies OrderDetail; } 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) { export async function findOrderItemRecord(context: DatabaseContext, orderId: string, itemId: string) {
const [row] = await context.db const [row] = await context.db
.select({ order: orders, item: orderItems, inventory }) .select({ order: orders, item: orderItems, inventory })
@@ -165,6 +124,10 @@ export async function updateOrderItemQuantity(context: DatabaseContext, itemId:
await context.db.update(orderItems).set({ quantity }).where(eq(orderItems.id, itemId)); 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) { export async function updateOrderTimestamp(context: DatabaseContext, orderId: string, updatedAt: string) {
await context.db.update(orders).set({ updatedAt }).where(eq(orders.id, orderId)); await context.db.update(orders).set({ updatedAt }).where(eq(orders.id, orderId));
} }
+28 -29
View File
@@ -2,12 +2,11 @@ import type { Address, AuthUser } from "@orderops/shared";
import type { FastifyPluginAsync, FastifyRequest } from "fastify"; import type { FastifyPluginAsync, FastifyRequest } from "fastify";
import { requireEmployeeUser } from "../auth/current-user"; import { requireEmployeeUser } from "../auth/current-user";
import type { DatabaseContext } from "../db/database"; import type { DatabaseContext } from "../db/database";
import { addOrderNote } from "./add-order-note";
import { cancelOrder } from "./cancel-order"; import { cancelOrder } from "./cancel-order";
import { getOrder } from "./get-order"; import { getOrder } from "./get-order";
import { listAuditEvents } from "./list-audit-events"; import { listAuditEvents } from "./list-audit-events";
import { listOrders } from "./list-orders"; import { listOrders } from "./list-orders";
import { changeOrderItemQuantity } from "./update-order-item"; import { changeOrderItemQuantity, updateOrderNotes } from "./update-order-item";
import { changeShippingAddress } from "./update-shipping-address"; import { changeShippingAddress } from "./update-shipping-address";
interface OrderRouteOptions { interface OrderRouteOptions {
@@ -34,8 +33,8 @@ interface CancelBody {
reason?: string; reason?: string;
} }
interface NoteBody { interface NotesBody {
body: string; notes: string;
} }
type AuthenticatedRequest = FastifyRequest & { currentUser: AuthUser }; 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.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", { app.post<{ Params: OrderItemParams; Body: QuantityBody }>("/orders/:orderId/items/:itemId/quantity", {
schema: { schema: {
body: { body: {
@@ -125,6 +99,31 @@ export const registerOrderRoutes: FastifyPluginAsync<OrderRouteOptions> = async
return result.order; 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", { app.post<{ Params: IdParams; Body: Address }>("/orders/:orderId/shipping-address", {
schema: { schema: {
body: { 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 -1
View File
@@ -1,7 +1,7 @@
import type { OrderStatus } from "@orderops/shared/order-status"; import type { OrderStatus } from "@orderops/shared/order-status";
export function canEditOrderItems(status: OrderStatus) { export function canEditOrderItems(status: OrderStatus) {
return status === "pending" || status === "processing"; return status === "pending";
} }
export function canEditShippingAddress(status: OrderStatus) { export function canEditShippingAddress(status: OrderStatus) {
+1 -161
View File
@@ -1,15 +1,11 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"; 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 type { AppWithContext } from "../app";
import { buildApp } from "../app"; import { buildApp } from "../app";
import { orderNotes, users } from "../db/schema";
import { createUser } from "../users/user-repository"; import { createUser } from "../users/user-repository";
let app: AppWithContext; let app: AppWithContext;
let employeeCookie = ""; let employeeCookie = "";
let customerCookie = ""; let customerCookie = "";
let employeeId = "";
async function login(username: string) { async function login(username: string) {
const response = await app.inject({ method: "POST", url: "/api/login", payload: { username } }); const response = await app.inject({ method: "POST", url: "/api/login", payload: { username } });
@@ -19,14 +15,13 @@ async function login(username: string) {
beforeEach(async () => { beforeEach(async () => {
app = await buildApp(":memory:"); app = await buildApp(":memory:");
const employee = await createUser(app.dbContext, { await createUser(app.dbContext, {
username: "dev-employee", username: "dev-employee",
name: "Dev Employee", name: "Dev Employee",
email: "dev.employee@example.com", email: "dev.employee@example.com",
role: "employee" role: "employee"
}); });
employeeId = employee.id;
employeeCookie = await login("dev-employee"); employeeCookie = await login("dev-employee");
customerCookie = await login("john-smith"); customerCookie = await login("john-smith");
}); });
@@ -35,161 +30,6 @@ afterEach(async () => {
await app.close(); 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", () => { describe("order routes", () => {
test("rejects customer access", async () => { test("rejects customer access", async () => {
const response = await app.inject({ method: "GET", url: "/api/orders", headers: { cookie: customerCookie } }); const response = await app.inject({ method: "GET", url: "/api/orders", headers: { cookie: customerCookie } });
+42 -1
View File
@@ -1,6 +1,6 @@
import type { DatabaseContext } from "../db/database"; import type { DatabaseContext } from "../db/database";
import { canEditOrderItems } from "./order-status"; 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( export async function changeOrderItemQuantity(
context: DatabaseContext, context: DatabaseContext,
@@ -47,3 +47,44 @@ export async function changeOrderItemQuantity(
order: await findOrderDetail(context, input.orderId) order: await findOrderDetail(context, input.orderId)
} as const; } 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;
}
File diff suppressed because one or more lines are too long
+8 -8
View File
@@ -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"; import { apiRequest } from "../lib/api-client";
export function listOrders(query: string) { export function listOrders(query: string) {
@@ -14,13 +14,6 @@ export function listAuditEvents(orderId: string) {
return apiRequest<AuditEvent[]>(`/api/orders/${orderId}/audit-events`); 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) { export function updateOrderItemQuantity(orderId: string, itemId: string, quantity: number) {
return apiRequest<OrderDetail>(`/api/orders/${orderId}/items/${itemId}/quantity`, { return apiRequest<OrderDetail>(`/api/orders/${orderId}/items/${itemId}/quantity`, {
method: "POST", 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) { export function updateShippingAddress(orderId: string, address: Address) {
return apiRequest<OrderDetail>(`/api/orders/${orderId}/shipping-address`, { return apiRequest<OrderDetail>(`/api/orders/${orderId}/shipping-address`, {
method: "POST", method: "POST",
+5 -5
View File
@@ -1,7 +1,7 @@
import type { Address, AuditEvent, OrderDetail } from "@orderops/shared"; import type { Address, AuditEvent, OrderDetail } from "@orderops/shared";
import { AuditTimeline } from "./audit-timeline"; import { AuditTimeline } from "./audit-timeline";
import { OrderItemsPanel } from "./order-items-panel"; import { OrderItemsPanel } from "./order-items-panel";
import { OrderNotesPanel } from "./order-notes-panel"; import { OrderNotes } from "./order-notes";
import { OrderSummaryPanel } from "./order-summary"; import { OrderSummaryPanel } from "./order-summary";
import { ShippingAddressForm } from "./shipping-address-form"; import { ShippingAddressForm } from "./shipping-address-form";
@@ -10,8 +10,8 @@ interface OrderDetailPageProps {
auditEvents: AuditEvent[]; auditEvents: AuditEvent[];
onUpdateQuantity: (itemId: string, quantity: number) => Promise<void>; onUpdateQuantity: (itemId: string, quantity: number) => Promise<void>;
onSaveAddress: (address: Address) => Promise<void>; onSaveAddress: (address: Address) => Promise<void>;
onSaveNotes: (notes: string) => Promise<void>;
onCancel: () => Promise<void>; onCancel: () => Promise<void>;
onAddNote: (body: string) => Promise<void>;
} }
export function OrderDetailPage({ export function OrderDetailPage({
@@ -19,8 +19,8 @@ export function OrderDetailPage({
auditEvents, auditEvents,
onUpdateQuantity, onUpdateQuantity,
onSaveAddress, onSaveAddress,
onCancel, onSaveNotes,
onAddNote onCancel
}: OrderDetailPageProps) { }: OrderDetailPageProps) {
return ( return (
<div className="space-y-4"> <div className="space-y-4">
@@ -32,7 +32,7 @@ export function OrderDetailPage({
</div> </div>
<OrderItemsPanel order={order} onUpdateQuantity={onUpdateQuantity} /> <OrderItemsPanel order={order} onUpdateQuantity={onUpdateQuantity} />
<ShippingAddressForm order={order} onSave={onSaveAddress} /> <ShippingAddressForm order={order} onSave={onSaveAddress} />
<OrderNotesPanel key={order.id} order={order} onAddNote={onAddNote} /> <OrderNotes order={order} onSave={onSaveNotes} />
<AuditTimeline events={auditEvents} /> <AuditTimeline events={auditEvents} />
</div> </div>
); );
-90
View File
@@ -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>
);
}
+37
View File
@@ -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>
);
}
+11 -25
View File
@@ -2,7 +2,7 @@ import { useEffect, useState } from "react";
import type { Address, AuditEvent, OrderDetail } from "@orderops/shared"; import type { Address, AuditEvent, OrderDetail } from "@orderops/shared";
import { Link, useParams } from "react-router-dom"; import { Link, useParams } from "react-router-dom";
import { Toast } from "../ui/toast"; 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"; import { OrderDetailPage } from "./order-detail-page";
interface ToastState { interface ToastState {
@@ -72,31 +72,17 @@ export function OrderPage() {
} }
} }
async function handleAddNote(body: string) { async function handleUpdateQuantity(itemId: string, quantity: number) {
try { if (!order) {
if (!orderId) { return;
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 { if (order.status !== "pending") {
await refreshOrder(orderId); setToast({ message: "Order items cannot be changed for this order status.", variant: "error" });
setToast({ message: "Note added.", variant: "success" }); return;
} catch {
setToast({
message: "Note saved, but the page didn't refresh — reload to see it.",
variant: "error"
});
} }
await runAction(() => updateOrderItemQuantity(order.id, itemId, quantity), "Quantity saved.");
} }
return ( return (
@@ -111,10 +97,10 @@ export function OrderPage() {
<OrderDetailPage <OrderDetailPage
order={order} order={order}
auditEvents={auditEvents} 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.")} 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.")} onCancel={() => runAction(() => cancelOrder(order.id), "Order cancelled.")}
onAddNote={handleAddNote}
/> />
) : null} ) : null}
</div> </div>
+1 -10
View File
@@ -13,23 +13,14 @@ export interface OrderItemDetail {
availableQuantity: number; availableQuantity: number;
} }
export interface Note {
id: string;
orderId: string;
body: string;
authorUserId: string;
authorName: string;
createdAt: string;
}
export interface OrderDetail { export interface OrderDetail {
id: string; id: string;
orderNumber: string; orderNumber: string;
status: OrderStatus; status: OrderStatus;
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
notes: string | null;
customer: CustomerSummary; customer: CustomerSummary;
shippingAddress: Address; shippingAddress: Address;
items: OrderItemDetail[]; items: OrderItemDetail[];
notes: Note[];
} }