Fs fix search order v2 #17

Open
notsicilian wants to merge 3 commits from fs-fix-search-order-v2 into master
10 changed files with 159 additions and 1 deletions
Showing only changes of commit 98801089e5 - Show all commits
+5
View File
@@ -90,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 NOT NULL DEFAULT '',
created_at TEXT NOT NULL, created_at TEXT NOT NULL,
updated_at TEXT NOT NULL updated_at TEXT NOT NULL
); );
@@ -119,4 +120,8 @@ export function initializeDatabase(sqlite: Database) {
created_at TEXT NOT NULL created_at TEXT NOT NULL
); );
`); `);
if (tableExists(sqlite, "orders") && !columnExists(sqlite, "orders", "notes")) {
sqlite.exec(`ALTER TABLE orders ADD COLUMN notes TEXT NOT NULL DEFAULT ''`);
}
} }
+1
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").notNull().default(""),
createdAt: text("created_at").notNull(), createdAt: text("created_at").notNull(),
updatedAt: text("updated_at").notNull() updatedAt: text("updated_at").notNull()
}); });
+5
View File
@@ -96,6 +96,7 @@ export async function findOrderDetail(context: DatabaseContext, orderId: string)
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"],
notes: header.order.notes,
createdAt: header.order.createdAt, createdAt: header.order.createdAt,
updatedAt: header.order.updatedAt, updatedAt: header.order.updatedAt,
customer: { customer: {
@@ -131,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));
+30
View File
@@ -7,6 +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 { changeOrderNotes } from "./update-notes";
import { changeShippingAddress } from "./update-shipping-address"; import { changeShippingAddress } from "./update-shipping-address";
interface OrderRouteOptions { interface OrderRouteOptions {
@@ -29,6 +30,10 @@ interface QuantityBody {
quantity: number; quantity: number;
} }
interface NotesBody {
notes: string;
}
interface CancelBody { interface CancelBody {
reason?: string; reason?: string;
} }
@@ -95,6 +100,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: Address }>("/orders/:orderId/shipping-address", { app.post<{ Params: IdParams; Body: Address }>("/orders/:orderId/shipping-address", {
schema: { schema: {
body: { body: {
+44
View File
@@ -0,0 +1,44 @@
import type { DatabaseContext } from "../db/database";
import { appendAuditEvent, findOrderDetail, updateOrderNotes } from "./order-repository";
export const NOTES_MAX_LENGTH = 1000;
export async function changeOrderNotes(
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.length === 0) {
return { statusCode: 400, message: "Notes cannot be empty." } as const;
}
if (notes.length > NOTES_MAX_LENGTH) {
return { statusCode: 400, message: `Notes cannot exceed ${NOTES_MAX_LENGTH} characters.` } 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
});
return {
statusCode: 200,
order: await findOrderDetail(context, input.orderId)
} as const;
}
+7
View File
@@ -28,6 +28,13 @@ 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",
@@ -1,6 +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";
import { OrderSummaryPanel } from "./order-summary"; import { OrderSummaryPanel } from "./order-summary";
import { ShippingAddressForm } from "./shipping-address-form"; import { ShippingAddressForm } from "./shipping-address-form";
@@ -9,6 +10,7 @@ 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>;
} }
@@ -17,11 +19,13 @@ export function OrderDetailPage({
auditEvents, auditEvents,
onUpdateQuantity, onUpdateQuantity,
onSaveAddress, onSaveAddress,
onSaveNotes,
onCancel onCancel
}: OrderDetailPageProps) { }: OrderDetailPageProps) {
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<OrderSummaryPanel order={order} /> <OrderSummaryPanel order={order} />
<OrderNotesPanel notes={order.notes} onSave={onSaveNotes} />
<div className="flex justify-end"> <div className="flex justify-end">
<button className="rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white" onClick={() => void onCancel()} type="button"> <button className="rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white" onClick={() => void onCancel()} type="button">
Cancel order Cancel order
+60
View File
@@ -0,0 +1,60 @@
import { useState } from "react";
export const NOTES_MAX_LENGTH = 1000;
interface OrderNotesProps {
notes: string;
onSave: (notes: string) => Promise<void>;
}
export function OrderNotesPanel({ notes, onSave }: OrderNotesProps) {
const [draft, setDraft] = useState(notes);
const [isSaving, setIsSaving] = useState(false);
const trimmed = draft.trim();
const isDisabled = isSaving || trimmed.length === 0 || trimmed === notes;
async function handleSave() {
if (isDisabled) {
return;
}
setIsSaving(true);
try {
await onSave(trimmed);
} finally {
setIsSaving(false);
}
}
return (
<section className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
<div className="mb-3 flex items-center justify-between">
<h3 className="text-sm font-semibold text-slate-700">Internal notes</h3>
<span className="text-xs text-slate-500">{draft.length}/{NOTES_MAX_LENGTH}</span>
</div>
{notes ? (
<p className="mb-3 whitespace-pre-wrap text-sm text-slate-700">{notes}</p>
) : (
<p className="mb-3 text-sm text-slate-400">No internal notes yet. Add context for teammates following up on this order.</p>
)}
<textarea
className="w-full resize-y rounded-lg border border-slate-300 px-3 py-2 text-sm text-slate-900 focus:border-blue-500 focus:outline-none"
maxLength={NOTES_MAX_LENGTH}
onChange={(event) => setDraft(event.target.value)}
placeholder="Add internal notes..."
rows={3}
value={draft}
/>
<div className="mt-3 flex justify-end">
<button
className="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-50"
disabled={isDisabled}
onClick={() => void handleSave()}
type="button"
>
{isSaving ? "Saving..." : "Save notes"}
</button>
</div>
</section>
);
}
+2 -1
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, 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,6 +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(() => updateOrderNotes(order.id, notes), "Notes saved.")}
onCancel={() => runAction(() => cancelOrder(order.id), "Order cancelled.")} onCancel={() => runAction(() => cancelOrder(order.id), "Order cancelled.")}
/> />
) : null} ) : null}
+1
View File
@@ -17,6 +17,7 @@ export interface OrderDetail {
id: string; id: string;
orderNumber: string; orderNumber: string;
status: OrderStatus; status: OrderStatus;
notes: string;
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
customer: CustomerSummary; customer: CustomerSummary;