Add design approval workflow infrastructure: PATCH endpoint, email notifications, and message types
- Add PATCH method to /api/designs/[id]/route.ts for status updates - Create sendDesignReadyForReview email template for customer notifications - Enhance /api/designs/[id]/messages to support messageType field (MESSAGE | CHANGE_REQUEST) - Add database migration for messageType field with MESSAGE default This completes the backend infrastructure for the multi-step design approval workflow: 1. Admin edits and sends design to customer for review 2. Customer approves design or requests changes 3. Admin receives notifications for change requests Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Haiku 4.5
parent
4d124b1550
commit
ac27cc554b
@@ -0,0 +1,100 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import dynamic from 'next/dynamic';
|
||||
|
||||
interface DesignApproval {
|
||||
id: string;
|
||||
customerEmail: string;
|
||||
customerName: string | null;
|
||||
productId: string;
|
||||
product: {
|
||||
id: string;
|
||||
name: string;
|
||||
basePrice: number;
|
||||
personalisedPrice: number;
|
||||
onSale: boolean;
|
||||
effectivePrice: number;
|
||||
colors: string[];
|
||||
sizes: string[];
|
||||
showOnPersonalised: boolean;
|
||||
imageUrl: string | null;
|
||||
imageUrlBack: string | null;
|
||||
photoRecolorable: boolean;
|
||||
colorPhotos: Record<string, string>;
|
||||
colorPhotosBack: Record<string, string>;
|
||||
printArea: string;
|
||||
printAreaBack: string | null;
|
||||
mockup: string;
|
||||
referenceWidthCm: number | null;
|
||||
referenceHeightCm: number | null;
|
||||
};
|
||||
designJson: string;
|
||||
color: string;
|
||||
size: string | null;
|
||||
status: string;
|
||||
}
|
||||
|
||||
const DesignCanvas = dynamic(() => import('@/components/DesignCanvas'), { ssr: false });
|
||||
|
||||
export default function EditDesignPage({ params }: { params: { id: string } }) {
|
||||
const router = useRouter();
|
||||
const [design, setDesign] = useState<DesignApproval | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [sending, setSending] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetch(`/api/designs/${params.id}`)
|
||||
.then((r) => r.json())
|
||||
.then(setDesign)
|
||||
.finally(() => setLoading(false));
|
||||
}, [params.id]);
|
||||
|
||||
const handleSendToCustomer = async () => {
|
||||
setSending(true);
|
||||
try {
|
||||
const res = await fetch(`/api/designs/${params.id}/send-to-customer`, {
|
||||
method: 'POST',
|
||||
});
|
||||
if (res.ok) {
|
||||
router.push(`/admin/designs/${params.id}`);
|
||||
} else {
|
||||
alert('Failed to send to customer');
|
||||
}
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <div className="p-6">Loading...</div>;
|
||||
if (!design) return <div className="p-6 text-sm text-muted">Design not found.</div>;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-paper">
|
||||
<div className="mx-auto max-w-7xl px-6 py-8">
|
||||
<Link href={`/admin/designs/${params.id}`} className="text-sm text-clay hover:text-clay-dark mb-4 inline-block">
|
||||
← Back to design approval
|
||||
</Link>
|
||||
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="font-display text-3xl mb-2">{design.product.name}</h1>
|
||||
<p className="text-sm text-muted">Editing design for {design.customerName || design.customerEmail}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleSendToCustomer}
|
||||
disabled={sending}
|
||||
className="bg-clay px-6 py-3 text-sm font-medium text-paper hover:bg-clay-dark disabled:opacity-60"
|
||||
>
|
||||
{sending ? 'Sending…' : 'Send to Customer for Review'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Full Design Canvas */}
|
||||
<DesignCanvas product={design.product} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { useState, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import DesignApprovalChat from '@/components/DesignApprovalChat';
|
||||
import AdminDesignEditor from '@/components/AdminDesignEditor';
|
||||
|
||||
interface DesignApproval {
|
||||
id: string;
|
||||
@@ -34,7 +33,6 @@ export default function DesignDetailPage({ params }: { params: { id: string } })
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [approving, setApproving] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [editingDesign, setEditingDesign] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetch(`/api/designs/${params.id}`)
|
||||
@@ -75,19 +73,6 @@ export default function DesignDetailPage({ params }: { params: { id: string } })
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditorSave = (designJson: string, previewUrl: string) => {
|
||||
setDesign((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
designJson,
|
||||
designPreviewUrl: previewUrl,
|
||||
}
|
||||
: null
|
||||
);
|
||||
setEditingDesign(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-6xl px-6 py-12">
|
||||
<Link href="/admin/designs" className="text-sm text-clay hover:text-clay-dark mb-4 inline-block">
|
||||
@@ -100,27 +85,18 @@ export default function DesignDetailPage({ params }: { params: { id: string } })
|
||||
{/* Design Preview & Editor */}
|
||||
<div className="border border-line bg-surface p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<p className="tag-label">Design Editor</p>
|
||||
{!editingDesign && design.status === 'PENDING' && (
|
||||
<button
|
||||
onClick={() => setEditingDesign(true)}
|
||||
className="text-xs px-3 py-1 border border-clay text-clay hover:bg-clay/10"
|
||||
<p className="tag-label">Design Preview</p>
|
||||
{design.status === 'PENDING' && (
|
||||
<Link
|
||||
href={`/admin/designs/${params.id}/edit`}
|
||||
className="text-xs px-3 py-2 border border-clay text-clay hover:bg-clay/10 inline-block"
|
||||
>
|
||||
Edit design
|
||||
</button>
|
||||
Open full editor →
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{editingDesign ? (
|
||||
<AdminDesignEditor
|
||||
designId={params.id}
|
||||
designJson={design.designJson}
|
||||
designPreviewUrl={design.designPreviewUrl}
|
||||
placementPreviewUrl={design.placementPreviewUrl}
|
||||
onSave={handleEditorSave}
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<p className="text-sm text-muted mb-2">Design preview (transparent)</p>
|
||||
<img
|
||||
@@ -163,7 +139,6 @@ export default function DesignDetailPage({ params }: { params: { id: string } })
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Customer Details & Chat */}
|
||||
|
||||
@@ -27,24 +27,30 @@ export async function POST(
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const { sender, body } = await req.json();
|
||||
const { sender, body, role, message, messageType } = await req.json();
|
||||
|
||||
if (!sender || !body) {
|
||||
// Support both old format (sender/body) and new format (role/message/messageType)
|
||||
const finalSender = role || sender;
|
||||
const finalBody = message || body;
|
||||
const finalMessageType = messageType || 'MESSAGE';
|
||||
|
||||
if (!finalSender || !finalBody) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Missing required fields' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const message = await prisma.designApprovalMessage.create({
|
||||
const created = await prisma.designApprovalMessage.create({
|
||||
data: {
|
||||
designId: params.id,
|
||||
sender,
|
||||
body,
|
||||
sender: finalSender,
|
||||
body: finalBody,
|
||||
messageType: finalMessageType,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(message);
|
||||
return NextResponse.json(created);
|
||||
} catch (err) {
|
||||
console.error('Error creating message:', err);
|
||||
return NextResponse.json(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { getCurrentAdmin } from '@/lib/auth';
|
||||
import { getCurrentAdmin, getCurrentCustomer } from '@/lib/auth';
|
||||
|
||||
export async function GET(
|
||||
req: Request,
|
||||
@@ -26,6 +26,34 @@ export async function GET(
|
||||
}
|
||||
}
|
||||
|
||||
export async function PATCH(
|
||||
req: Request,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const customer = await getCurrentCustomer();
|
||||
if (!customer) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { status } = await req.json();
|
||||
|
||||
const updated = await prisma.designApproval.update({
|
||||
where: { id: params.id },
|
||||
data: { status },
|
||||
include: { product: true, messages: { orderBy: { createdAt: 'asc' } } },
|
||||
});
|
||||
|
||||
return NextResponse.json(updated);
|
||||
} catch (err) {
|
||||
console.error('Error updating design:', err);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to update design' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
req: Request,
|
||||
{ params }: { params: { id: string } }
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { getCurrentAdmin } from '@/lib/auth';
|
||||
import { sendDesignReadyForReview } from '@/lib/mail';
|
||||
|
||||
export async function POST(
|
||||
req: Request,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const admin = await getCurrentAdmin();
|
||||
if (!admin) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const design = await prisma.designApproval.findUnique({
|
||||
where: { id: params.id },
|
||||
include: { product: true },
|
||||
});
|
||||
|
||||
if (!design) {
|
||||
return NextResponse.json({ error: 'Design not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Update status to IN_REVIEW
|
||||
const updated = await prisma.designApproval.update({
|
||||
where: { id: params.id },
|
||||
data: { status: 'IN_REVIEW' },
|
||||
include: { product: true, messages: { orderBy: { createdAt: 'asc' } } },
|
||||
});
|
||||
|
||||
// Send email to customer
|
||||
await sendDesignReadyForReview({
|
||||
customerName: design.customerName || 'Customer',
|
||||
customerEmail: design.customerEmail,
|
||||
productName: design.product.name,
|
||||
reviewLink: `${process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'}/designs/${params.id}/review`,
|
||||
});
|
||||
|
||||
return NextResponse.json(updated);
|
||||
} catch (err) {
|
||||
console.error('Error sending design to customer:', err);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to send design' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useCart } from '@/lib/cartStore';
|
||||
|
||||
interface DesignApproval {
|
||||
id: string;
|
||||
customerEmail: string;
|
||||
customerName: string | null;
|
||||
productId: string;
|
||||
product: {
|
||||
id: string;
|
||||
name: string;
|
||||
basePrice: number;
|
||||
personalisedPrice: number;
|
||||
effectivePrice: number;
|
||||
};
|
||||
designJson: string;
|
||||
designPreviewUrl: string;
|
||||
placementPreviewUrl: string | null;
|
||||
color: string;
|
||||
size: string | null;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export default function DesignReviewPage({ params }: { params: { id: string } }) {
|
||||
const [design, setDesign] = useState<DesignApproval | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [approving, setApproving] = useState(false);
|
||||
const [changingMessage, setChangingMessage] = useState('');
|
||||
const [sendingChanges, setSendingChanges] = useState(false);
|
||||
const addItem = useCart((s) => s.addItem);
|
||||
|
||||
useEffect(() => {
|
||||
fetch(`/api/designs/${params.id}`)
|
||||
.then((r) => r.json())
|
||||
.then(setDesign)
|
||||
.finally(() => setLoading(false));
|
||||
}, [params.id]);
|
||||
|
||||
const handleApprove = async () => {
|
||||
if (!design) return;
|
||||
setApproving(true);
|
||||
try {
|
||||
const res = await fetch(`/api/designs/${params.id}/approve`, { method: 'POST' });
|
||||
if (res.ok) {
|
||||
const updated = await res.json();
|
||||
setDesign(updated);
|
||||
|
||||
// Add to cart
|
||||
addItem({
|
||||
productId: design.productId,
|
||||
color: design.color,
|
||||
size: design.size,
|
||||
designJson: design.designJson,
|
||||
quantity: 1,
|
||||
});
|
||||
|
||||
alert('Design approved! Added to your bag.');
|
||||
}
|
||||
} finally {
|
||||
setApproving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRequestChanges = async () => {
|
||||
if (!changingMessage.trim()) {
|
||||
alert('Please provide feedback for the design changes');
|
||||
return;
|
||||
}
|
||||
|
||||
setSendingChanges(true);
|
||||
try {
|
||||
const res = await fetch(`/api/designs/${params.id}/messages`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
message: changingMessage,
|
||||
role: 'CUSTOMER',
|
||||
messageType: 'CHANGE_REQUEST',
|
||||
}),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
// Update status back to PENDING so admin can see it
|
||||
await fetch(`/api/designs/${params.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ status: 'PENDING' }),
|
||||
});
|
||||
|
||||
alert('Changes requested! The admin has been notified.');
|
||||
setChangingMessage('');
|
||||
// Reload design
|
||||
const updated = await fetch(`/api/designs/${params.id}`).then((r) => r.json());
|
||||
setDesign(updated);
|
||||
}
|
||||
} finally {
|
||||
setSendingChanges(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <div className="p-6">Loading...</div>;
|
||||
if (!design) return <div className="p-6 text-sm text-muted">Design not found.</div>;
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-4xl px-6 py-12">
|
||||
<Link href="/" className="text-sm text-clay hover:text-clay-dark mb-6 inline-block">
|
||||
← Back to shop
|
||||
</Link>
|
||||
|
||||
<h1 className="font-display text-3xl mb-2">{design.product.name}</h1>
|
||||
<p className="text-muted mb-8">Review your personalized design</p>
|
||||
|
||||
<div className="grid gap-8 md:grid-cols-2">
|
||||
{/* Design Preview */}
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<p className="text-sm text-muted mb-2">Design preview</p>
|
||||
<img
|
||||
src={design.designPreviewUrl}
|
||||
alt="design preview"
|
||||
className="w-full border border-line"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{design.placementPreviewUrl && (
|
||||
<div>
|
||||
<p className="text-sm text-muted mb-2">Design on product</p>
|
||||
<img
|
||||
src={design.placementPreviewUrl}
|
||||
alt="placement preview"
|
||||
className="w-full border border-line"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="space-y-6">
|
||||
<div className="border border-line bg-surface p-6">
|
||||
<p className="tag-label mb-4">Order Summary</p>
|
||||
<div className="space-y-3 text-sm mb-6">
|
||||
<p>
|
||||
<strong>Product:</strong> {design.product.name}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Color:</strong> {design.color}
|
||||
</p>
|
||||
{design.size && (
|
||||
<p>
|
||||
<strong>Size:</strong> {design.size}
|
||||
</p>
|
||||
)}
|
||||
<p className="border-t border-line pt-3">
|
||||
<strong>Price:</strong> £{(design.product.effectivePrice / 100).toFixed(2)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleApprove}
|
||||
disabled={approving}
|
||||
className="w-full bg-clay px-4 py-3 text-sm font-medium text-paper hover:bg-clay-dark disabled:opacity-60 mb-3"
|
||||
>
|
||||
{approving ? 'Processing…' : 'Approve & Add to Bag'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Request Changes */}
|
||||
<div className="border border-line bg-surface p-6">
|
||||
<p className="tag-label mb-4">Request Changes</p>
|
||||
<textarea
|
||||
value={changingMessage}
|
||||
onChange={(e) => setChangingMessage(e.target.value)}
|
||||
placeholder="Describe what you'd like to change..."
|
||||
className="w-full border border-line bg-paper px-3 py-2 text-sm mb-3 min-h-24"
|
||||
/>
|
||||
<button
|
||||
onClick={handleRequestChanges}
|
||||
disabled={sendingChanges || !changingMessage.trim()}
|
||||
className="w-full border border-ink px-4 py-3 text-sm font-medium text-ink hover:border-clay hover:bg-clay hover:text-paper disabled:opacity-60"
|
||||
>
|
||||
{sendingChanges ? 'Sending…' : 'Send Changes to Admin'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -240,3 +240,38 @@ export async function sendDesignApprovedEmail({
|
||||
return { sent: false as const, reason: err instanceof Error ? err.message : 'Unknown error sending email' };
|
||||
}
|
||||
}
|
||||
|
||||
type SendDesignReadyForReviewArgs = {
|
||||
customerName: string;
|
||||
customerEmail: string;
|
||||
productName: string;
|
||||
reviewLink: string;
|
||||
};
|
||||
|
||||
export async function sendDesignReadyForReview({
|
||||
customerName,
|
||||
customerEmail,
|
||||
productName,
|
||||
reviewLink,
|
||||
}: SendDesignReadyForReviewArgs) {
|
||||
if (!process.env.SMTP_HOST) {
|
||||
return { sent: false, reason: 'SMTP not configured — set SMTP_HOST etc. in .env' as const };
|
||||
}
|
||||
|
||||
const transporter = getTransporter();
|
||||
|
||||
const greeting = customerName ? `Hi ${customerName},` : 'Hi,';
|
||||
|
||||
try {
|
||||
await transporter.sendMail({
|
||||
from: process.env.MAIL_FROM ?? process.env.SMTP_USER,
|
||||
to: customerEmail,
|
||||
subject: `Your ${productName} design is ready for review`,
|
||||
text: `${greeting}\n\nYour ${productName} design is ready for you to review and approve.\n\nReview it here:\n${reviewLink}\n\nYou can approve the design to proceed to checkout, or request changes from the admin.\n\n— Craft2Prints`,
|
||||
html: `<p>${greeting}</p><p>Your ${productName} design is ready for you to review and approve.</p><p><a href="${reviewLink}">${reviewLink}</a></p><p>You can approve the design to proceed to checkout, or request changes from the admin.</p><p>— Craft2Prints</p>`,
|
||||
});
|
||||
return { sent: true as const };
|
||||
} catch (err) {
|
||||
return { sent: false as const, reason: err instanceof Error ? err.message : 'Unknown error sending email' };
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user