Compare commits

..
Author SHA1 Message Date
shawn 2c3353db19 add:internal order notes
Runner Test / test (push) Successful in 17s
Runner Test / test (pull_request) Successful in 16s
2026-09-21 19:15:10 +10:00
11 changed files with 93 additions and 85 deletions
+3 -3
View File
@@ -90,7 +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,
notes TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
@@ -121,8 +121,8 @@ export function initializeDatabase(sqlite: Database) {
);
`);
// Databases created before internal order notes existed keep their orders table, so add the column in place.
// Existing local databases predate internal notes, so add the column in place.
if (!columnExists(sqlite, "orders", "notes")) {
sqlite.exec("ALTER TABLE orders ADD COLUMN notes TEXT;");
sqlite.exec(`ALTER TABLE orders ADD COLUMN notes TEXT NOT NULL DEFAULT ''`);
}
}
+1 -1
View File
@@ -9,7 +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"),
notes: text("notes").notNull().default(""),
createdAt: text("created_at").notNull(),
updatedAt: text("updated_at").notNull()
});
+4 -4
View File
@@ -132,10 +132,6 @@ export async function updateOrderStatus(context: DatabaseContext, orderId: strin
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) {
const [row] = await context.db.select({ shippingAddressId: orders.shippingAddressId }).from(orders).where(eq(orders.id, orderId));
@@ -179,6 +175,10 @@ 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) {
const [row] = await context.db
.select({ customer: users })
+25 -26
View File
@@ -7,7 +7,7 @@ import { getOrder } from "./get-order";
import { listAuditEvents } from "./list-audit-events";
import { listOrders } from "./list-orders";
import { changeOrderItemQuantity } from "./update-order-item";
import { changeOrderNotes } from "./update-order-notes";
import { saveOrderNotes } from "./update-order-notes";
import { changeShippingAddress } from "./update-shipping-address";
interface OrderRouteOptions {
@@ -139,31 +139,6 @@ 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" }
}
}
}
}, 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", {
schema: {
body: {
@@ -187,4 +162,28 @@ 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: {
// 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;
});
};
+17 -22
View File
@@ -1,40 +1,35 @@
import { maxOrderNotesLength } from "@orderops/shared";
import { orderNotesMaxLength } from "@orderops/shared";
import type { DatabaseContext } from "../db/database";
import { appendAuditEvent, findOrderDetail, updateOrderNotes } from "./order-repository";
import { findOrderDetail, updateOrderNotes, updateOrderTimestamp } from "./order-repository";
export async function changeOrderNotes(
// Notes are allowed for every order status: follow-up work often happens
// after an order has shipped, been cancelled, or been refunded.
export async function saveOrderNotes(
context: DatabaseContext,
input: {
orderId: string;
notes: string;
actor: string;
}
) {
const notes = input.notes.trim();
if (!notes) {
return { statusCode: 400, message: "Notes cannot be empty." } as const;
}
if (notes.length > maxOrderNotesLength) {
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 notes = input.notes.trim();
if (!notes) {
return { statusCode: 400, message: "Notes cannot be empty." } as const;
}
if (notes.length > orderNotesMaxLength) {
return { statusCode: 400, message: `Notes must be ${orderNotesMaxLength} characters or fewer.` } as const;
}
const updatedAt = new Date().toISOString();
await updateOrderNotes(context, input.orderId, notes, updatedAt);
await appendAuditEvent(context, {
orderId: input.orderId,
actor: input.actor,
type: "order.notes_updated",
message: "Updated internal notes.",
createdAt: updatedAt
});
await updateOrderNotes(context, input.orderId, notes);
await updateOrderTimestamp(context, input.orderId, updatedAt);
return {
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) {
return apiRequest<OrderDetail>(`/api/orders/${orderId}/cancel`, {
method: "POST",
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>
<OrderItemsPanel order={order} onUpdateQuantity={onUpdateQuantity} />
<ShippingAddressForm order={order} onSave={onSaveAddress} />
<OrderNotesPanel notes={order.notes} onSaveNotes={onSaveNotes} />
<AuditTimeline events={auditEvents} />
<OrderNotesPanel order={order} onSave={onSaveNotes} />
</div>
);
}
+29 -15
View File
@@ -1,40 +1,54 @@
import { useState } from "react";
import { maxOrderNotesLength, type OrderDetail } from "@orderops/shared";
import { useEffect, useState } from "react";
interface OrderNotesPanelProps {
order: OrderDetail;
onSave: (notes: string) => Promise<void>;
notes: string;
onSaveNotes: (notes: string) => Promise<void>;
}
export function OrderNotesPanel({ order, onSave }: OrderNotesPanelProps) {
const [notes, setNotes] = useState(order.notes ?? "");
export function OrderNotesPanel({ notes, onSaveNotes }: OrderNotesPanelProps) {
const [draft, setDraft] = useState(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 (
<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>
<h3 className="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
className="space-y-3"
className="space-y-2"
onSubmit={async (event) => {
event.preventDefault();
await onSave(notes);
if (!canSubmit) {
return;
}
setIsSaving(true);
await onSaveNotes(draft);
setIsSaving(false);
}}
>
<label className="block text-sm text-slate-700">
<span className="mb-1 block">Notes for the OrderOps team</span>
<span className="mb-1 block">Notes</span>
<textarea
className="w-full rounded-lg border border-slate-300 px-3 py-2"
maxLength={maxOrderNotesLength}
placeholder="Add context for teammates following up on this order"
rows={4}
value={notes}
onChange={(event) => setNotes(event.target.value)}
value={draft}
onChange={(event) => setDraft(event.target.value)}
/>
</label>
<button
className="rounded-md bg-slate-900 px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
disabled={!notes.trim()}
disabled={!canSubmit}
type="submit"
>
Save notes
{isSaving ? "Saving notes..." : "Save notes"}
</button>
</form>
</section>
+2 -2
View File
@@ -2,7 +2,7 @@ import { useEffect, useState } from "react";
import type { Address, AuditEvent, OrderDetail } from "@orderops/shared";
import { Link, useParams } from "react-router-dom";
import { Toast } from "../ui/toast";
import { cancelOrder, getOrder, listAuditEvents, updateOrderItemQuantity, updateOrderNotes, updateShippingAddress } from "./order-api";
import { cancelOrder, getOrder, listAuditEvents, saveOrderNotes, updateOrderItemQuantity, updateShippingAddress } from "./order-api";
import { OrderDetailPage } from "./order-detail-page";
interface ToastState {
@@ -86,7 +86,7 @@ export function OrderPage() {
auditEvents={auditEvents}
onUpdateQuantity={(itemId, quantity) => runAction(() => updateOrderItemQuantity(order.id, itemId, quantity), "Quantity saved.")}
onSaveAddress={(address: Address) => runAction(() => updateShippingAddress(order.id, address), "Shipping address saved.")}
onSaveNotes={(notes: string) => runAction(() => updateOrderNotes(order.id, notes), "Notes saved.")}
onSaveNotes={(notes: string) => runAction(() => saveOrderNotes(order.id, notes), "Internal notes saved.")}
onCancel={() => runAction(() => cancelOrder(order.id), "Order cancelled.")}
/>
) : null}
+3 -3
View File
@@ -3,8 +3,8 @@ import type { CustomerSummary } from "./customer";
import type { Money } from "./money";
import type { OrderStatus } from "./order-status";
// Internal order notes are capped so they stay a short follow-up context, not a document.
export const maxOrderNotesLength = 1000;
// Shared so the API and the notes panel describe the same limit.
export const orderNotesMaxLength = 1000;
export interface OrderItemDetail {
id: string;
@@ -25,5 +25,5 @@ export interface OrderDetail {
customer: CustomerSummary;
shippingAddress: Address;
items: OrderItemDetail[];
notes: string | null;
notes: string;
}