ADDED: new add notes feature for orders backend and frontend
Runner Test / test (push) Failing after 17s
Runner Test / test (pull_request) Failing after 16s

This commit is contained in:
Lena Deriso
2026-09-22 23:06:01 -04:00
parent e493d1592b
commit c5215daedb
12 changed files with 425 additions and 8 deletions
+9
View File
@@ -21,6 +21,7 @@ function resetLegacySchema(sqlite: Database) {
DROP TABLE IF EXISTS sessions;
DROP TABLE IF EXISTS audit_events;
DROP TABLE IF EXISTS refunds;
DROP TABLE IF EXISTS order_notes;
DROP TABLE IF EXISTS order_items;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS inventory;
@@ -102,6 +103,14 @@ export function initializeDatabase(sqlite: Database) {
unit_price_cents INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS order_notes (
id TEXT PRIMARY KEY,
order_id TEXT NOT NULL REFERENCES orders(id),
body TEXT NOT NULL,
author_user_id TEXT NOT NULL REFERENCES users(id),
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS refunds (
id TEXT PRIMARY KEY,
order_id TEXT NOT NULL REFERENCES orders(id),
+8
View File
@@ -20,3 +20,11 @@ export const orderItems = sqliteTable("order_items", {
quantity: integer("quantity").notNull(),
unitPriceCents: integer("unit_price_cents").notNull()
});
export const orderNotes = sqliteTable("order_notes", {
id: text("id").primaryKey(),
orderId: text("order_id").notNull().references(() => orders.id),
body: text("body").notNull(),
authorUserId: text("author_user_id").notNull().references(() => users.id),
createdAt: text("created_at").notNull()
});
+29
View File
@@ -0,0 +1,29 @@
import type { DatabaseContext } from "../db/database";
import { findOrderDetail, insertOrderNote } from "./order-repository";
export async function addOrderNote(
context: DatabaseContext,
input: {
orderId: string;
authorUserId: string;
body: string;
}
) {
if (!input.body.trim() || input.body.length >= 2000) {
return { statusCode: 400, message: "Note must be non-empty and less than 2000 characters." } as const;
}
const order = await findOrderDetail(context, input.orderId);
if (!order) {
return { statusCode: 404, message: "Order not found." } as const;
}
const note = await insertOrderNote(context, input);
if (!note) {
return { statusCode: 404, message: "Author not found." } as const;
}
return { statusCode: 200, note } as const;
}
+45 -3
View File
@@ -1,7 +1,7 @@
import type { Address, AuditEvent, OrderDetail, OrderItemDetail, OrderSummary } from "@orderops/shared";
import type { Address, AuditEvent, Note, OrderDetail, OrderItemDetail, OrderSummary } from "@orderops/shared";
import { and, asc, desc, eq, inArray, or, sql } from "drizzle-orm";
import type { DatabaseContext } from "../db/database";
import { addresses, auditEvents, inventory, orderItems, orders, products, users } from "../db/schema";
import { addresses, auditEvents, inventory, orderItems, orderNotes, orders, products, users } from "../db/schema";
function toAddress(row: typeof addresses.$inferSelect): Address {
return {
@@ -92,6 +92,20 @@ export async function findOrderDetail(context: DatabaseContext, orderId: string)
.where(eq(orderItems.orderId, orderId))
.orderBy(asc(orderItems.id));
const notes = await context.db
.select({
id: orderNotes.id,
orderId: orderNotes.orderId,
body: orderNotes.body,
authorUserId: orderNotes.authorUserId,
authorName: users.name,
createdAt: orderNotes.createdAt
})
.from(orderNotes)
.innerJoin(users, eq(orderNotes.authorUserId, users.id))
.where(eq(orderNotes.orderId, orderId))
.orderBy(desc(orderNotes.createdAt));
return {
id: header.order.id,
orderNumber: header.order.orderNumber,
@@ -104,10 +118,38 @@ export async function findOrderDetail(context: DatabaseContext, orderId: string)
email: header.customer.email
},
shippingAddress: toAddress(header.address),
items: itemRows.map(toOrderItemDetail)
items: itemRows.map(toOrderItemDetail),
notes
} satisfies OrderDetail;
}
export async function insertOrderNote(
context: DatabaseContext,
input: {
orderId: string;
authorUserId: string;
body: string;
}
) {
const [author] = await context.db.select({ name: users.name }).from(users).where(eq(users.id, input.authorUserId));
if (!author) {
return null;
}
const note = {
id: crypto.randomUUID(),
orderId: input.orderId,
body: input.body,
authorUserId: input.authorUserId,
createdAt: new Date().toISOString()
} satisfies typeof orderNotes.$inferInsert;
await context.db.insert(orderNotes).values(note);
return { ...note, authorName: author.name } satisfies Note;
}
export async function findOrderItemRecord(context: DatabaseContext, orderId: string, itemId: string) {
const [row] = await context.db
.select({ order: orders, item: orderItems, inventory })
+30
View File
@@ -2,6 +2,7 @@ import type { Address, AuthUser } from "@orderops/shared";
import type { FastifyPluginAsync, FastifyRequest } from "fastify";
import { requireEmployeeUser } from "../auth/current-user";
import type { DatabaseContext } from "../db/database";
import { addOrderNote } from "./add-order-note";
import { cancelOrder } from "./cancel-order";
import { getOrder } from "./get-order";
import { listAuditEvents } from "./list-audit-events";
@@ -33,6 +34,10 @@ interface CancelBody {
reason?: string;
}
interface NoteBody {
body: string;
}
type AuthenticatedRequest = FastifyRequest & { currentUser: AuthUser };
export const registerOrderRoutes: FastifyPluginAsync<OrderRouteOptions> = async (app, options) => {
@@ -69,6 +74,31 @@ export const registerOrderRoutes: FastifyPluginAsync<OrderRouteOptions> = async
app.get<{ Params: IdParams }>("/orders/:orderId/audit-events", async (request) => listAuditEvents(options.db, request.params.orderId));
app.post<{ Params: IdParams; Body: NoteBody }>("/orders/:orderId/notes", {
schema: {
body: {
type: "object",
required: ["body"],
properties: {
body: { type: "string", minLength: 1, maxLength: 1999 }
}
}
}
}, async (request, reply) => {
const currentUser = (request as AuthenticatedRequest).currentUser;
const result = await addOrderNote(options.db, {
orderId: request.params.orderId,
authorUserId: currentUser.id,
body: request.body.body
});
if (result.statusCode !== 200) {
return reply.code(result.statusCode).send({ message: result.message });
}
return result.note;
});
app.post<{ Params: OrderItemParams; Body: QuantityBody }>("/orders/:orderId/items/:itemId/quantity", {
schema: {
body: {
+161 -1
View File
@@ -1,11 +1,15 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import type { Note, OrderDetail } from "@orderops/shared";
import { eq } from "drizzle-orm";
import type { AppWithContext } from "../app";
import { buildApp } from "../app";
import { orderNotes, users } from "../db/schema";
import { createUser } from "../users/user-repository";
let app: AppWithContext;
let employeeCookie = "";
let customerCookie = "";
let employeeId = "";
async function login(username: string) {
const response = await app.inject({ method: "POST", url: "/api/login", payload: { username } });
@@ -15,13 +19,14 @@ async function login(username: string) {
beforeEach(async () => {
app = await buildApp(":memory:");
await createUser(app.dbContext, {
const employee = await createUser(app.dbContext, {
username: "dev-employee",
name: "Dev Employee",
email: "dev.employee@example.com",
role: "employee"
});
employeeId = employee.id;
employeeCookie = await login("dev-employee");
customerCookie = await login("john-smith");
});
@@ -30,6 +35,161 @@ afterEach(async () => {
await app.close();
});
describe("order notes", () => {
async function createNote(orderId: string, body: string) {
const response = await app.inject({
method: "POST",
url: `/api/orders/${orderId}/notes`,
headers: { cookie: employeeCookie },
payload: { body }
});
expect(response.statusCode).toBe(200);
return response.json<Note>();
}
async function getNotes(orderId: string) {
const response = await app.inject({
method: "GET",
url: `/api/orders/${orderId}`,
headers: { cookie: employeeCookie }
});
expect(response.statusCode).toBe(200);
return response.json<OrderDetail>().notes;
}
test("creates a note and retrieves it with its order", async () => {
expect(await getNotes("order_1")).toEqual([]);
const startedAt = Date.now();
const note = await createNote("order_1", "Call the warehouse before shipping.");
expect(note.id).toBeTruthy();
expect(note.orderId).toBe("order_1");
expect(note.body).toBe("Call the warehouse before shipping.");
expect(note.authorUserId).toBe(employeeId);
expect(note.authorName).toBe("Dev Employee");
expect(Date.parse(note.createdAt)).toBeGreaterThanOrEqual(startedAt);
expect(Date.parse(note.createdAt)).toBeLessThanOrEqual(Date.now());
expect(await getNotes("order_1")).toEqual([note]);
});
test("resolves the author's current display name when retrieving notes", async () => {
const note = await createNote("order_1", "Waiting for confirmation.");
await app.dbContext.db.update(users).set({ name: "Updated Employee" }).where(eq(users.id, employeeId));
expect(await getNotes("order_1")).toEqual([{ ...note, authorName: "Updated Employee" }]);
});
test("uses session authorship instead of an author supplied in the payload", async () => {
const otherEmployee = await createUser(app.dbContext, {
username: "other-employee",
name: "Other Employee",
email: "other.employee@example.com",
role: "employee"
});
const response = await app.inject({
method: "POST",
url: "/api/orders/order_1/notes",
headers: { cookie: employeeCookie },
payload: { body: "Internal context", authorUserId: otherEmployee.id, authorName: otherEmployee.name }
});
expect(response.statusCode).toBe(200);
const note = response.json<Note>();
expect(note.authorUserId).toBe(employeeId);
expect(note.authorName).toBe("Dev Employee");
expect(await getNotes("order_1")).toEqual([note]);
});
test("rejects customers and anonymous users from adding or reading order notes", async () => {
const note = await createNote("order_1", "Employee-only context");
for (const access of [{ cookie: customerCookie, statusCode: 403 }, { cookie: "", statusCode: 401 }]) {
const headers = { cookie: access.cookie };
const createResponse = await app.inject({
method: "POST",
url: "/api/orders/order_1/notes",
headers,
payload: { body: "Unauthorized note" }
});
const readResponse = await app.inject({ method: "GET", url: "/api/orders/order_1", headers });
expect(createResponse.statusCode).toBe(access.statusCode);
expect(readResponse.statusCode).toBe(access.statusCode);
expect(readResponse.body).not.toContain(note.body);
}
expect(await getNotes("order_1")).toEqual([note]);
});
for (const { label, body } of [
{ label: "empty", body: "" },
{ label: "whitespace-only", body: " \n\t " },
{ label: "2000-character", body: "x".repeat(2000) },
{ label: "over-length", body: "x".repeat(2001) }
]) {
test(`rejects ${label} notes without saving them`, async () => {
const response = await app.inject({
method: "POST",
url: "/api/orders/order_1/notes",
headers: { cookie: employeeCookie },
payload: { body }
});
expect(response.statusCode).toBe(400);
expect(await getNotes("order_1")).toEqual([]);
});
}
test("accepts a note just below the 2000-character limit", async () => {
const body = "x".repeat(1999);
const note = await createNote("order_1", body);
expect(note.body).toBe(body);
expect(await getNotes("order_1")).toEqual([note]);
});
test("returns not found when adding a note to a missing order", async () => {
const response = await app.inject({
method: "POST",
url: "/api/orders/missing-order/notes",
headers: { cookie: employeeCookie },
payload: { body: "Follow up" }
});
expect(response.statusCode).toBe(404);
expect(response.json<{ message: string }>()).toEqual({ message: "Order not found." });
expect(await app.dbContext.db.select().from(orderNotes)).toEqual([]);
});
test("returns notes newest first regardless of insertion order", async () => {
const middle = await createNote("order_1", "Middle note");
const newest = await createNote("order_1", "Newest note");
const oldest = await createNote("order_1", "Oldest note");
// Fixed timestamps keep ordering independent of clock resolution and test speed.
for (const [note, createdAt] of [
[middle, "2026-01-02T00:00:00.000Z"],
[newest, "2026-01-03T00:00:00.000Z"],
[oldest, "2026-01-01T00:00:00.000Z"]
] as const) {
await app.dbContext.db.update(orderNotes).set({ createdAt }).where(eq(orderNotes.id, note.id));
}
expect((await getNotes("order_1")).map((note) => note.id)).toEqual([newest.id, middle.id, oldest.id]);
});
test("keeps notes isolated to their own orders", async () => {
const first = await createNote("order_1", "First order context");
const second = await createNote("order_2", "Second order context");
expect(await getNotes("order_1")).toEqual([first]);
expect(await getNotes("order_2")).toEqual([second]);
expect(await getNotes("order_3")).toEqual([]);
});
});
describe("order routes", () => {
test("rejects customer access", async () => {
const response = await app.inject({ method: "GET", url: "/api/orders", headers: { cookie: customerCookie } });