Compare commits

..
Author SHA1 Message Date
Abdulaziz Salim Said AL-GharbiandClaude Opus 5.5 bfe60631a5 add:internal order notes for employees
Runner Test / test (push) Successful in 16s
Runner Test / test (pull_request) Successful in 17s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 20:24:10 +04:00
11 changed files with 83 additions and 91 deletions
+3 -3
View File
@@ -90,7 +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 NOT NULL DEFAULT '', notes TEXT,
created_at TEXT NOT NULL, created_at TEXT NOT NULL,
updated_at TEXT NOT NULL updated_at TEXT NOT NULL
); );
@@ -121,8 +121,8 @@ export function initializeDatabase(sqlite: Database) {
); );
`); `);
// Existing local databases predate internal notes, so add the column in place. // Databases created before internal order notes existed keep their orders table, so add the column in place.
if (!columnExists(sqlite, "orders", "notes")) { if (!columnExists(sqlite, "orders", "notes")) {
sqlite.exec(`ALTER TABLE orders ADD COLUMN notes TEXT NOT NULL DEFAULT ''`); sqlite.exec("ALTER TABLE orders ADD COLUMN notes TEXT;");
} }
} }
+1 -1
View File
@@ -9,7 +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").notNull().default(""), notes: text("notes"),
createdAt: text("created_at").notNull(), createdAt: text("created_at").notNull(),
updatedAt: text("updated_at").notNull() updatedAt: text("updated_at").notNull()
}); });
+4 -4
View File
@@ -132,6 +132,10 @@ export async function updateOrderStatus(context: DatabaseContext, orderId: strin
await context.db.update(orders).set({ status, updatedAt }).where(eq(orders.id, orderId)); await context.db.update(orders).set({ status, updatedAt }).where(eq(orders.id, orderId));
} }
export async function updateOrderNotes(context: DatabaseContext, orderId: string, notes: string, updatedAt: string) {
await context.db.update(orders).set({ notes, updatedAt }).where(eq(orders.id, orderId));
}
export async function updateOrderAddress(context: DatabaseContext, orderId: string, address: Address) { export async function updateOrderAddress(context: DatabaseContext, orderId: string, address: Address) {
const [row] = await context.db.select({ shippingAddressId: orders.shippingAddressId }).from(orders).where(eq(orders.id, orderId)); const [row] = await context.db.select({ shippingAddressId: orders.shippingAddressId }).from(orders).where(eq(orders.id, orderId));
@@ -175,10 +179,6 @@ export async function appendAuditEvent(
}); });
} }
export async function updateOrderNotes(context: DatabaseContext, orderId: string, notes: string) {
await context.db.update(orders).set({ notes }).where(eq(orders.id, orderId));
}
async function findCustomerSummaryByOrderId(context: DatabaseContext, orderId: string) { async function findCustomerSummaryByOrderId(context: DatabaseContext, orderId: string) {
const [row] = await context.db const [row] = await context.db
.select({ customer: users }) .select({ customer: users })
+26 -25
View File
@@ -7,7 +7,7 @@ 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 } from "./update-order-item";
import { saveOrderNotes } from "./update-order-notes"; import { changeOrderNotes } from "./update-order-notes";
import { changeShippingAddress } from "./update-shipping-address"; import { changeShippingAddress } from "./update-shipping-address";
interface OrderRouteOptions { interface OrderRouteOptions {
@@ -139,6 +139,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" }
}
}
}
}, async (request, reply) => {
const currentUser = (request as AuthenticatedRequest).currentUser;
const result = await changeOrderNotes(options.db, {
orderId: request.params.orderId,
notes: request.body.notes,
actor: currentUser.username
});
if (result.statusCode !== 200) {
return reply.code(result.statusCode).send({ message: result.message });
}
return result.order;
});
app.post<{ Params: IdParams; Body: CancelBody }>("/orders/:orderId/cancel", { app.post<{ Params: IdParams; Body: CancelBody }>("/orders/:orderId/cancel", {
schema: { schema: {
body: { body: {
@@ -162,28 +187,4 @@ 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: {
// Empty and length rules are measured on the trimmed notes in saveOrderNotes.
notes: { type: "string" }
}
}
}
}, async (request, reply) => {
const result = await saveOrderNotes(options.db, {
orderId: request.params.orderId,
notes: request.body.notes
});
if (result.statusCode !== 200) {
return reply.code(result.statusCode).send({ message: result.message });
}
return result.order;
});
}; };
+20 -15
View File
@@ -1,35 +1,40 @@
import { orderNotesMaxLength } from "@orderops/shared"; import { maxOrderNotesLength } from "@orderops/shared";
import type { DatabaseContext } from "../db/database"; import type { DatabaseContext } from "../db/database";
import { findOrderDetail, updateOrderNotes, updateOrderTimestamp } from "./order-repository"; import { appendAuditEvent, findOrderDetail, updateOrderNotes } from "./order-repository";
// Notes are allowed for every order status: follow-up work often happens export async function changeOrderNotes(
// after an order has shipped, been cancelled, or been refunded.
export async function saveOrderNotes(
context: DatabaseContext, context: DatabaseContext,
input: { input: {
orderId: string; orderId: string;
notes: 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(); const notes = input.notes.trim();
if (!notes) { if (!notes) {
return { statusCode: 400, message: "Notes cannot be empty." } as const; return { statusCode: 400, message: "Notes cannot be empty." } as const;
} }
if (notes.length > orderNotesMaxLength) { if (notes.length > maxOrderNotesLength) {
return { statusCode: 400, message: `Notes must be ${orderNotesMaxLength} characters or fewer.` } as const; return { statusCode: 400, message: `Notes cannot be longer than ${maxOrderNotesLength} characters.` } as const;
}
const order = await findOrderDetail(context, input.orderId);
if (!order) {
return { statusCode: 404, message: "Order not found." } as const;
} }
const updatedAt = new Date().toISOString(); const updatedAt = new Date().toISOString();
await updateOrderNotes(context, input.orderId, notes); await updateOrderNotes(context, input.orderId, notes, updatedAt);
await updateOrderTimestamp(context, input.orderId, updatedAt); await appendAuditEvent(context, {
orderId: input.orderId,
actor: input.actor,
type: "order.notes_updated",
message: "Updated internal notes.",
createdAt: updatedAt
});
return { return {
statusCode: 200, statusCode: 200,
File diff suppressed because one or more lines are too long
+7 -7
View File
@@ -28,16 +28,16 @@ export function updateShippingAddress(orderId: string, address: Address) {
}); });
} }
export function updateOrderNotes(orderId: string, notes: string) {
return apiRequest<OrderDetail>(`/api/orders/${orderId}/notes`, {
method: "POST",
body: JSON.stringify({ notes })
});
}
export function cancelOrder(orderId: string, reason?: string) { export function cancelOrder(orderId: string, reason?: string) {
return apiRequest<OrderDetail>(`/api/orders/${orderId}/cancel`, { return apiRequest<OrderDetail>(`/api/orders/${orderId}/cancel`, {
method: "POST", method: "POST",
body: JSON.stringify({ reason }) body: JSON.stringify({ reason })
}); });
} }
export function saveOrderNotes(orderId: string, notes: string) {
return apiRequest<OrderDetail>(`/api/orders/${orderId}/notes`, {
method: "POST",
body: JSON.stringify({ notes })
});
}
+1 -1
View File
@@ -32,8 +32,8 @@ 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 notes={order.notes} onSaveNotes={onSaveNotes} />
<AuditTimeline events={auditEvents} /> <AuditTimeline events={auditEvents} />
<OrderNotesPanel order={order} onSave={onSaveNotes} />
</div> </div>
); );
} }
+15 -29
View File
@@ -1,54 +1,40 @@
import { useEffect, useState } from "react"; import { useState } from "react";
import { maxOrderNotesLength, type OrderDetail } from "@orderops/shared";
interface OrderNotesPanelProps { interface OrderNotesPanelProps {
notes: string; order: OrderDetail;
onSaveNotes: (notes: string) => Promise<void>; onSave: (notes: string) => Promise<void>;
} }
export function OrderNotesPanel({ notes, onSaveNotes }: OrderNotesPanelProps) { export function OrderNotesPanel({ order, onSave }: OrderNotesPanelProps) {
const [draft, setDraft] = useState(notes); const [notes, setNotes] = useState(order.notes ?? "");
const [isSaving, setIsSaving] = useState(false);
const canSubmit = draft.trim().length > 0 && draft !== notes && !isSaving;
// Show the stored notes again whenever the order is reloaded.
useEffect(() => {
setDraft(notes);
}, [notes]);
return ( return (
<section className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm"> <section className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
<h3 className="text-sm font-semibold text-slate-700">Internal notes</h3> <h3 className="mb-3 text-sm font-semibold text-slate-700">Internal notes</h3>
<p className="mb-3 text-xs text-slate-500">Visible to OrderOps employees only.</p>
<form <form
className="space-y-2" className="space-y-3"
onSubmit={async (event) => { onSubmit={async (event) => {
event.preventDefault(); event.preventDefault();
await onSave(notes);
if (!canSubmit) {
return;
}
setIsSaving(true);
await onSaveNotes(draft);
setIsSaving(false);
}} }}
> >
<label className="block text-sm text-slate-700"> <label className="block text-sm text-slate-700">
<span className="mb-1 block">Notes</span> <span className="mb-1 block">Notes for the OrderOps team</span>
<textarea <textarea
className="w-full rounded-lg border border-slate-300 px-3 py-2" className="w-full rounded-lg border border-slate-300 px-3 py-2"
placeholder="Add context for teammates following up on this order" maxLength={maxOrderNotesLength}
rows={4} rows={4}
value={draft} value={notes}
onChange={(event) => setDraft(event.target.value)} onChange={(event) => setNotes(event.target.value)}
/> />
</label> </label>
<button <button
className="rounded-md bg-slate-900 px-4 py-2 text-sm font-medium text-white disabled:opacity-50" className="rounded-md bg-slate-900 px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
disabled={!canSubmit} disabled={!notes.trim()}
type="submit" type="submit"
> >
{isSaving ? "Saving notes..." : "Save notes"} Save notes
</button> </button>
</form> </form>
</section> </section>
+2 -2
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 { cancelOrder, getOrder, listAuditEvents, saveOrderNotes, 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 {
@@ -86,7 +86,7 @@ export function OrderPage() {
auditEvents={auditEvents} auditEvents={auditEvents}
onUpdateQuantity={(itemId, quantity) => runAction(() => updateOrderItemQuantity(order.id, itemId, quantity), "Quantity saved.")} onUpdateQuantity={(itemId, quantity) => runAction(() => updateOrderItemQuantity(order.id, itemId, quantity), "Quantity saved.")}
onSaveAddress={(address: Address) => runAction(() => updateShippingAddress(order.id, address), "Shipping address saved.")} onSaveAddress={(address: Address) => runAction(() => updateShippingAddress(order.id, address), "Shipping address saved.")}
onSaveNotes={(notes: string) => runAction(() => saveOrderNotes(order.id, notes), "Internal notes saved.")} onSaveNotes={(notes: string) => runAction(() => updateOrderNotes(order.id, notes), "Notes saved.")}
onCancel={() => runAction(() => cancelOrder(order.id), "Order cancelled.")} onCancel={() => runAction(() => cancelOrder(order.id), "Order cancelled.")}
/> />
) : null} ) : null}
+3 -3
View File
@@ -3,8 +3,8 @@ import type { CustomerSummary } from "./customer";
import type { Money } from "./money"; import type { Money } from "./money";
import type { OrderStatus } from "./order-status"; import type { OrderStatus } from "./order-status";
// Shared so the API and the notes panel describe the same limit. // Internal order notes are capped so they stay a short follow-up context, not a document.
export const orderNotesMaxLength = 1000; export const maxOrderNotesLength = 1000;
export interface OrderItemDetail { export interface OrderItemDetail {
id: string; id: string;
@@ -25,5 +25,5 @@ export interface OrderDetail {
customer: CustomerSummary; customer: CustomerSummary;
shippingAddress: Address; shippingAddress: Address;
items: OrderItemDetail[]; items: OrderItemDetail[];
notes: string; notes: string | null;
} }