Lumen & Gesso / website · lumengesso.com / app / lib / customer-order-messages.ts
| 1 | import 'server-only'; |
| 2 | import { NextResponse, type NextRequest } from 'next/server'; |
| 3 | import { getCustomerUser } from '@/app/lib/lumen-auth'; |
| 4 | import { commerceDb } from '@/app/lib/commerce-db'; |
| 5 | import { sendEmail } from '@/app/lib/email'; |
| 6 | import { env } from '@/app/lib/env'; |
| 7 | import { displayOrderId } from '@/app/lib/orders'; |
| 8 | import { customerRevisions, orderMessageConfig, ORDER_MESSAGE_LIMIT, STUDIO_MESSAGE_STATUSES } from '@/app/lib/order-messages'; |
| 9 | |
| 10 | export async function receiveCustomerMessage(req: NextRequest, id: string, kind: 'revision' | 'message') { |
| 11 | const isRevision = kind === 'revision'; |
| 12 | |
| 13 | const user = await getCustomerUser(); |
| 14 | if (!user) return NextResponse.json({ error: 'unauthorized' }, { status: 401 }); |
| 15 | |
| 16 | let body: { note?: unknown; generationId?: unknown; question?: unknown } | null; |
| 17 | try { |
| 18 | body = await req.json(); |
| 19 | } catch { |
| 20 | return NextResponse.json({ error: 'invalid json' }, { status: 400 }); |
| 21 | } |
| 22 | const note = typeof body?.note === 'string' ? body.note.trim() : ''; |
| 23 | if (!note) return NextResponse.json({ error: 'Enter a message to send.' }, { status: 400 }); |
| 24 | if (note.length > ORDER_MESSAGE_LIMIT) { |
| 25 | return NextResponse.json({ error: `Messages must be ${ORDER_MESSAGE_LIMIT} characters or fewer.` }, { status: 400 }); |
| 26 | } |
| 27 | |
| 28 | const admin = commerceDb(); |
| 29 | const { data: order } = await admin |
| 30 | .from('orders') |
| 31 | .select('id, user_id, user_email, status, current_generation_id, config, revision_note, updated_at') |
| 32 | .eq('id', id) |
| 33 | .single(); |
| 34 | if (!order) return NextResponse.json({ error: 'order not found' }, { status: 404 }); |
| 35 | if (order.user_id !== user.id) return NextResponse.json({ error: 'forbidden' }, { status: 403 }); |
| 36 | if (isRevision ? order.status !== 'awaiting_approval' : !STUDIO_MESSAGE_STATUSES.includes(order.status)) { |
| 37 | return NextResponse.json({ error: isRevision ? 'This proof is no longer open for revisions.' : 'This order is closed to messages.' }, { status: 409 }); |
| 38 | } |
| 39 | const question = !isRevision && body?.question === true; |
| 40 | const reopensProof = order.status === 'awaiting_approval' && !question && (isRevision || !!order.current_generation_id); |
| 41 | if (question && (order.status !== 'awaiting_approval' || !order.current_generation_id)) { |
| 42 | return NextResponse.json({ error: 'This proof changed. Reload to ask a question about the current proof.' }, { status: 409 }); |
| 43 | } |
| 44 | if ((question || isRevision || reopensProof) && (question || body?.generationId !== undefined) && body?.generationId !== order.current_generation_id) { |
| 45 | return NextResponse.json({ error: 'A newer proof is available. Reload to review it.' }, { status: 409 }); |
| 46 | } |
| 47 | |
| 48 | const at = new Date().toISOString(); |
| 49 | |
| 50 | const history = orderMessageConfig(order.config); |
| 51 | const revisions = customerRevisions(order.config, order.revision_note, order.updated_at); |
| 52 | const config = reopensProof |
| 53 | ? { ...history, revisions: [...revisions, { note, at, ...(order.current_generation_id ? { generationId: order.current_generation_id } : {}) }], revisionDraft: null } |
| 54 | : { ...history, revisions, customerMessages: [...history.customerMessages, { |
| 55 | id: crypto.randomUUID(), note, at, |
| 56 | ...(question ? { question: true, generationId: order.current_generation_id } : {}), |
| 57 | }] }; |
| 58 | const { data: saved, error: saveError } = await admin |
| 59 | .from('orders') |
| 60 | .update(reopensProof ? { status: 'revision_requested', revision_note: note, config } : { config }) |
| 61 | .eq('id', id) |
| 62 | .eq('status', order.status) |
| 63 | .eq('updated_at', order.updated_at) |
| 64 | .select('id') |
| 65 | .maybeSingle(); |
| 66 | if (saveError) { |
| 67 | console.error('[customer order message] Could not save message', id, saveError.code); |
| 68 | return NextResponse.json({ error: 'Could not save your message.' }, { status: 500 }); |
| 69 | } |
| 70 | if (!saved) { |
| 71 | return NextResponse.json({ error: 'The order changed while you were editing. Reload and try again.' }, { status: 409 }); |
| 72 | } |
| 73 | |
| 74 | // Record the rejected generation after the order transition succeeds. |
| 75 | if (isRevision && order.current_generation_id) { |
| 76 | const { error } = await admin |
| 77 | .from('generations') |
| 78 | .update({ rejected_at: at }) |
| 79 | .eq('id', order.current_generation_id) |
| 80 | .eq('order_id', id); |
| 81 | if (error) console.error('[order revision] Could not mark old proof as rejected', id, error.code); |
| 82 | } |
| 83 | |
| 84 | const subject = isRevision ? 'Revision requested' : question ? 'Question about a proof' : reopensProof ? 'New proof feedback' : 'New customer message'; |
| 85 | const action = isRevision ? 'requested a revision' : question ? 'asked a question about a proof' : reopensProof ? 'left feedback on a proof' : 'sent a message'; |
| 86 | try { |
| 87 | await sendEmail({ |
| 88 | to: env.site.studioEmail(), |
| 89 | subject: `${subject} on ${displayOrderId(order.id)}`, |
| 90 | html: `<p><strong>${escapeHtml(order.user_email)}</strong> ${action} on ${displayOrderId(order.id)}.</p><blockquote>${escapeHtml(note).replace(/\r\n|\r|\n/g, '<br />')}</blockquote><p><a href="${env.site.url()}/admin/orders/${order.id}">Open in admin →</a></p>`, |
| 91 | text: `${order.user_email} ${action} on ${displayOrderId(order.id)}:\n\n${note}`, |
| 92 | }); |
| 93 | return NextResponse.json({ ok: true, emailSent: true, ...(reopensProof && !isRevision ? { proofReopened: true } : {}) }); |
| 94 | } catch { |
| 95 | console.error('[customer order message] Message saved but email failed', id); |
| 96 | return NextResponse.json({ ok: true, emailSent: false, ...(reopensProof && !isRevision ? { proofReopened: true } : {}) }); |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | function escapeHtml(s: string): string { |
| 101 | return s.replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!); |
| 102 | } |