Branchwell

Lumen & Gesso / website · lumengesso.com / app / admin / orders-list.tsx

1'use client';
2
3import { useMemo, useState } from 'react';
4import Link from 'next/link';
5import { ORDER_STATUSES, displayOrderId, adminStatusLabel } from '@/app/lib/orders';
6import { OrderMessageTime } from '@/app/components/OrderMessageTime';
7
8type Row = {
9 id: string;
10 user_email: string;
11 status: string;
12 price_cents: number;
13 config: { styleId?: string; productId?: string; size?: string } | null;
14 created_at: string;
15 custom_style_url: string | null;
16 customerMessageAt: string | null;
17 prodigi_order_id: string | null;
18 printerUrl: string | null;
19};
20
21// Statuses that require us to do something:
22// pending_design — generate + publish a first preview
23// revision_requested — customer rejected, generate + publish a fresh one
24// approved — customer approved, do a final review and send
25// to printer (Prodigi isn't auto-triggered)
26const ATTENTION_STATUSES = ['pending_design', 'revision_requested', 'approved'];
27// pending_payment + abandoned = customer started checkout but never paid.
28// Not studio work — surfaced separately. (pending_payment is the in-flight
29// cart; abandoned is the same row after the 7-day pg_cron sweep.)
30const PRE_STUDIO = new Set(['pending_payment', 'abandoned']);
31
32type Category = 'attention' | 'active' | 'cancelled' | 'prestudio';
33
34function categoryOf({ status, customerMessageAt }: Row): Category {
35 if (status === 'cancelled') return 'cancelled';
36 if (PRE_STUDIO.has(status)) return 'prestudio';
37 if (ATTENTION_STATUSES.includes(status) || customerMessageAt) return 'attention';
38 return 'active';
39}
40
41const PAGE_SIZE = 25;
42
43function searchBlob(o: Row): string {
44 const cfg = o.config ?? {};
45 return [
46 o.id,
47 displayOrderId(o.id),
48 o.user_email,
49 o.status,
50 o.prodigi_order_id,
51 adminStatusLabel(o.status),
52 cfg.styleId,
53 cfg.productId,
54 cfg.size,
55 o.custom_style_url ? 'custom style' : '',
56 ].filter(Boolean).join(' ').toLowerCase();
57}
58
59export function AdminOrdersList({ orders }: { orders: Row[] }) {
60 const [query, setQuery] = useState('');
61 const [statusFilter, setStatusFilter] = useState<string>('all');
62
63 const q = query.trim().toLowerCase();
64 const filtering = q.length > 0 || statusFilter !== 'all';
65
66 const statusCounts = useMemo(() => {
67 const m = new Map<string, number>();
68 for (const o of orders) m.set(o.status, (m.get(o.status) ?? 0) + 1);
69 return m;
70 }, [orders]);
71
72 const filtered = useMemo(
73 () =>
74 orders.filter(o => {
75 if (statusFilter !== 'all' && o.status !== statusFilter) return false;
76 if (q && !searchBlob(o).includes(q)) return false;
77 return true;
78 }),
79 [orders, q, statusFilter],
80 );
81
82 const attention = orders.filter(o => categoryOf(o) === 'attention').sort((a, b) =>
83 Date.parse(b.customerMessageAt ?? b.created_at) - Date.parse(a.customerMessageAt ?? a.created_at));
84 const active = orders.filter(o => categoryOf(o) === 'active');
85 const cancelled = orders.filter(o => categoryOf(o) === 'cancelled');
86 const preStudio = orders.filter(o => categoryOf(o) === 'prestudio');
87
88 return (
89 <>
90 <div className="admin-toolbar">
91 <input
92 type="search"
93 className="admin-toolbar__search"
94 placeholder="Search by order ID, email, style, product…"
95 value={query}
96 onChange={e => setQuery(e.target.value)}
97 />
98 <select
99 className="admin-toolbar__select"
100 value={statusFilter}
101 onChange={e => setStatusFilter(e.target.value)}
102 aria-label="Filter by status"
103 >
104 <option value="all">All statuses ({orders.length})</option>
105 {ORDER_STATUSES.filter(s => statusCounts.has(s)).map(s => (
106 <option key={s} value={s}>
107 {adminStatusLabel(s)} ({statusCounts.get(s)})
108 </option>
109 ))}
110 </select>
111 {filtering && (
112 <button
113 type="button"
114 className="admin-toolbar__clear"
115 onClick={() => { setQuery(''); setStatusFilter('all'); }}
116 >
117 Clear
118 </button>
119 )}
120 </div>
121
122 {filtering ? (
123 <section style={{ marginTop: 24 }}>
124 <h2 style={{ fontSize: 18, marginBottom: 12 }}>
125 {filtered.length} {filtered.length === 1 ? 'result' : 'results'}
126 </h2>
127 {filtered.length === 0 ? (
128 <p style={{ color: 'var(--ink-soft)' }}>No orders match.</p>
129 ) : (
130 // Remount on filter change so paging resets to page 1.
131 <PaginatedList key={`${statusFilter}|${q}`} items={filtered} />
132 )}
133 </section>
134 ) : (
135 <>
136 <section style={{ marginTop: 24 }}>
137 <h2 style={{ fontSize: 18, marginBottom: 12 }}>Needs your attention ({attention.length})</h2>
138 {attention.length === 0 ? (
139 <p style={{ color: 'var(--ink-soft)' }}>Nothing waiting. ✓</p>
140 ) : (
141 <PaginatedList items={attention} />
142 )}
143 </section>
144
145 <section style={{ marginTop: 36 }}>
146 <h2 style={{ fontSize: 18, marginBottom: 12 }}>Active commissions ({active.length})</h2>
147 {active.length === 0 ? (
148 <p style={{ color: 'var(--ink-soft)' }}>No active commissions.</p>
149 ) : (
150 <PaginatedList items={active} />
151 )}
152 </section>
153
154 {cancelled.length > 0 && (
155 <section style={{ marginTop: 36 }}>
156 <h2 style={{ fontSize: 18, marginBottom: 4 }}>Cancelled ({cancelled.length})</h2>
157 <p style={{ color: 'var(--ink-soft)', fontSize: 13, marginTop: 0, marginBottom: 12 }}>
158 Refunded and closed. Kept for the record — not active work.
159 </p>
160 <PaginatedList items={cancelled} />
161 </section>
162 )}
163
164 {preStudio.length > 0 && (
165 <section style={{ marginTop: 36 }}>
166 <h2 style={{ fontSize: 18, marginBottom: 4 }}>Abandoned (pre-payment) ({preStudio.length})</h2>
167 <p style={{ color: 'var(--ink-soft)', fontSize: 13, marginTop: 0, marginBottom: 12 }}>
168 Customer started checkout but never paid. Not in the studio.
169 Rows older than 7 days are auto-swept to <code>abandoned</code>.
170 </p>
171 <PaginatedList items={preStudio} />
172 </section>
173 )}
174 </>
175 )}
176 </>
177 );
178}
179
180// Client-side pagination over an already-fetched list. The pager only
181// appears once a list exceeds PAGE_SIZE, so short sections (attention,
182// abandoned) render untouched. Callers remount via `key` to reset paging
183// when the underlying set changes (e.g. on a new search).
184function PaginatedList({ items, pageSize = PAGE_SIZE }: { items: Row[]; pageSize?: number }) {
185 const [page, setPage] = useState(1);
186 const pageCount = Math.max(1, Math.ceil(items.length / pageSize));
187 const current = Math.min(page, pageCount); // clamp if items shrank
188 const start = (current - 1) * pageSize;
189 const slice = items.slice(start, start + pageSize);
190
191 return (
192 <>
193 <ul className="orders__list">
194 {slice.map(o => <AdminRow key={o.id} order={o} />)}
195 </ul>
196 {items.length > pageSize && (
197 <div className="admin-pager">
198 <button
199 type="button"
200 className="admin-pager__btn"
201 disabled={current <= 1}
202 onClick={() => setPage(current - 1)}
203 >
204 ← Prev
205 </button>
206 <span className="admin-pager__status">
207 {start + 1}–{Math.min(start + pageSize, items.length)} of {items.length}
208 </span>
209 <button
210 type="button"
211 className="admin-pager__btn"
212 disabled={current >= pageCount}
213 onClick={() => setPage(current + 1)}
214 >
215 Next →
216 </button>
217 </div>
218 )}
219 </>
220 );
221}
222
223function AdminRow({ order }: { order: Row }) {
224 const cfg = order.config ?? {};
225 const hasCustomStyle = !!order.custom_style_url;
226 return (
227 <li className="orders__row">
228 <Link href={`/admin/orders/${order.id}`} className="orders__rowlink">
229 <div className="orders__rowtop">
230 <span>
231 <span className="orders__id">{displayOrderId(order.id)}</span>
232 <span style={{ marginLeft: 12, fontSize: 14 }}>{order.user_email}</span>
233 {order.customerMessageAt && categoryOf(order) === 'attention' && (
234 <span className="statuschip statuschip--revision_requested" style={{ marginLeft: 10 }}>
235 {['awaiting_approval', 'revision_requested'].includes(order.status) ? 'Customer feedback' : 'Customer message'}
236 {' · '}<OrderMessageTime at={order.customerMessageAt} />
237 </span>
238 )}
239 {hasCustomStyle && (
240 <span
241 className="statuschip statuschip--customstyle"
242 style={{ marginLeft: 10 }}
243 title="Customer paid for a custom style reference — open the order to see the uploaded image"
244 >
245 ✦ Custom style
246 </span>
247 )}
248 </span>
249 <span className={`statuschip statuschip--${order.status}`}>{adminStatusLabel(order.status)}</span>
250 </div>
251 <div className="orders__rowmeta">
252 <span>
253 {hasCustomStyle ? <em>custom</em> : (cfg.styleId ?? '—')} · {cfg.productId ?? '—'} {cfg.size ?? ''}
254 </span>
255 <span>${(order.price_cents / 100).toFixed(2)} · {new Date(order.created_at).toLocaleDateString()}</span>
256 </div>
257 </Link>
258 {order.printerUrl && (
259 <div className="admin-printer-row">
260 <span>Submitted to Prodigi · <strong>{order.prodigi_order_id}</strong></span>
261 <a href={order.printerUrl} target="_blank" rel="noopener noreferrer">View printer order ↗</a>
262 </div>
263 )}
264 </li>
265 );
266}