Refactorings, error handling and logout
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import {useActiveProject} from '../lib/contexts/ActiveProjectProvider';
|
||||
import {useUser} from '../lib/hooks/useUser';
|
||||
import {network} from '../lib/network';
|
||||
import {
|
||||
Activity,
|
||||
BarChart3,
|
||||
@@ -60,7 +61,7 @@ const navigation: NavSection[] = [
|
||||
|
||||
export function DashboardLayout({children}: DashboardLayoutProps) {
|
||||
const router = useRouter();
|
||||
const {data: user} = useUser();
|
||||
const {data: user, mutate: mutateUser} = useUser();
|
||||
const {activeProject, availableProjects, setActiveProject} = useActiveProject();
|
||||
const [showProjectMenu, setShowProjectMenu] = useState(false);
|
||||
const [showUserMenu, setShowUserMenu] = useState(false);
|
||||
@@ -86,10 +87,31 @@ export function DashboardLayout({children}: DashboardLayoutProps) {
|
||||
}
|
||||
}, [showProjectMenu, showUserMenu]);
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('activeProjectId');
|
||||
void router.push('/auth/login');
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
// Call the logout endpoint to clear the cookie
|
||||
await network.fetch('GET', '/auth/logout');
|
||||
|
||||
// Clear local storage
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('activeProjectId');
|
||||
|
||||
// Clear SWR cache for user data
|
||||
await mutateUser(null, false);
|
||||
|
||||
// Close the menu
|
||||
setShowUserMenu(false);
|
||||
|
||||
// Redirect to login
|
||||
await router.push('/auth/login');
|
||||
} catch (error) {
|
||||
console.error('Logout failed:', error);
|
||||
// Even if the API call fails, try to redirect to login
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('activeProjectId');
|
||||
await mutateUser(null, false);
|
||||
await router.push('/auth/login');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -209,7 +231,11 @@ export function DashboardLayout({children}: DashboardLayoutProps) {
|
||||
{showUserMenu && (
|
||||
<div className="absolute bottom-full left-0 right-0 mb-1 bg-white border border-neutral-200 rounded-lg shadow-lg z-50 py-1">
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
void handleLogout();
|
||||
}}
|
||||
className="w-full flex items-center gap-2 px-3 py-2 text-sm hover:bg-neutral-50 transition-colors text-red-600"
|
||||
>
|
||||
<LogOut className="h-4 w-4" />
|
||||
|
||||
@@ -40,15 +40,16 @@ export interface DashboardStats {
|
||||
*/
|
||||
export function useDashboardStats(): DashboardStats {
|
||||
// Fetch activity stats (last 30 days by default)
|
||||
const {data: activityStats, error: activityError} = useSWR<ActivityStats>('/activity/stats');
|
||||
const {data: activityStats, error: activityError, isLoading: isLoadingActivity} = useSWR<ActivityStats>('/activity/stats');
|
||||
|
||||
// Fetch contacts (only need the total count)
|
||||
const {data: contactsData, error: contactsError} = useSWR<ContactsResponse>('/contacts?limit=1');
|
||||
const {data: contactsData, error: contactsError, isLoading: isLoadingContacts} = useSWR<ContactsResponse>('/contacts?limit=1');
|
||||
|
||||
// Fetch campaigns (only need the total count)
|
||||
const {data: campaignsData, error: campaignsError} = useSWR<CampaignsResponse>('/campaigns?pageSize=1');
|
||||
const {data: campaignsData, error: campaignsError, isLoading: isLoadingCampaigns} = useSWR<CampaignsResponse>('/campaigns?pageSize=1');
|
||||
|
||||
const isLoading = !activityStats && !contactsData && !campaignsData;
|
||||
// Still loading if ANY of the requests are still in progress
|
||||
const isLoading = isLoadingActivity || isLoadingContacts || isLoadingCampaigns;
|
||||
const error = activityError || contactsError || campaignsError;
|
||||
|
||||
return {
|
||||
|
||||
@@ -14,6 +14,11 @@ interface TypedSchema extends ZodSchema {
|
||||
|
||||
interface ApiResponse {
|
||||
message?: string;
|
||||
error?: {
|
||||
message?: string;
|
||||
code?: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
[key: string]: unknown;
|
||||
}
|
||||
@@ -52,7 +57,9 @@ export class network {
|
||||
const res = (await response.json()) as ApiResponse;
|
||||
|
||||
if (response.status >= 400) {
|
||||
throw new Error(res.message ?? 'Something went wrong!');
|
||||
// Extract error message from standardized error response or fall back to direct message property
|
||||
const errorMessage = res.error?.message ?? res.message ?? 'Something went wrong!';
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
return res as T;
|
||||
@@ -84,7 +91,9 @@ export class network {
|
||||
const res = (await response.json()) as ApiResponse;
|
||||
|
||||
if (response.status >= 400) {
|
||||
throw new Error(res.message ?? 'Something went wrong!');
|
||||
// Extract error message from standardized error response or fall back to direct message property
|
||||
const errorMessage = res.error?.message ?? res.message ?? 'Something went wrong!';
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
return res as T;
|
||||
|
||||
@@ -14,6 +14,10 @@ import {
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
Input,
|
||||
Label,
|
||||
Select,
|
||||
@@ -32,7 +36,7 @@ import {EmailEditor} from '../../components/EmailEditor';
|
||||
import {network} from '../../lib/network';
|
||||
import {formatFullDateTime, formatUTCDateTime, getUserTimezone, schedulePresets} from '../../lib/dateUtils';
|
||||
import {useChangeTracking} from '../../lib/hooks/useChangeTracking';
|
||||
import {ArrowLeft, Calendar, Mail, MousePointer, Save, Send, TestTube, TrendingUp, Users, XCircle} from 'lucide-react';
|
||||
import {ArrowLeft, Calendar, ChevronDown, Mail, MousePointer, Save, Send, TestTube, Trash2, TrendingUp, Users, XCircle} from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import {useRouter} from 'next/router';
|
||||
import {useEffect, useState} from 'react';
|
||||
@@ -91,6 +95,7 @@ export default function CampaignDetailsPage() {
|
||||
const [sendingTestEmail, setSendingTestEmail] = useState(false);
|
||||
const [showCancelDialog, setShowCancelDialog] = useState(false);
|
||||
const [showSendDialog, setShowSendDialog] = useState(false);
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
|
||||
// Automatically initialize edit fields when campaign is loaded and is a draft
|
||||
const isEditMode = campaign?.data.status === CampaignStatus.DRAFT;
|
||||
@@ -105,6 +110,16 @@ export default function CampaignDetailsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
try {
|
||||
await network.fetch('DELETE', `/campaigns/${id}`);
|
||||
toast.success('Campaign deleted successfully');
|
||||
void router.push('/campaigns');
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : 'Failed to delete campaign');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSend = async () => {
|
||||
try {
|
||||
await network.fetch<void>('POST', `/campaigns/${id}/send`);
|
||||
@@ -322,22 +337,37 @@ export default function CampaignDetailsPage() {
|
||||
{!hasChanges && !isSubmitting && <span className="text-sm text-neutral-500">All changes saved</span>}
|
||||
{hasChanges && !isSubmitting && <span className="text-sm text-amber-600">Unsaved changes</span>}
|
||||
<div className="flex gap-2">
|
||||
<Button type="button" variant="destructive" onClick={() => setShowDeleteDialog(true)}>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
Delete
|
||||
</Button>
|
||||
<Button type="submit" disabled={!hasChanges || isSubmitting} variant="outline">
|
||||
<Save className="h-4 w-4" />
|
||||
{isSubmitting ? 'Saving...' : 'Save'}
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={() => setIsTestEmailDialogOpen(true)}>
|
||||
<TestTube className="h-4 w-4" />
|
||||
Send Test
|
||||
</Button>
|
||||
<Button type="button" onClick={() => setShowSendDialog(true)}>
|
||||
<Send className="h-4 w-4" />
|
||||
Send Now
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={() => setIsScheduleDialogOpen(true)}>
|
||||
<Calendar className="h-4 w-4" />
|
||||
Schedule
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button type="button">
|
||||
<Send className="h-4 w-4" />
|
||||
Send
|
||||
<ChevronDown className="h-4 w-4 ml-1" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setIsTestEmailDialogOpen(true)}>
|
||||
<TestTube className="h-4 w-4 mr-2" />
|
||||
Send Test Email
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setShowSendDialog(true)}>
|
||||
<Send className="h-4 w-4 mr-2" />
|
||||
Send Now
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setIsScheduleDialogOpen(true)}>
|
||||
<Calendar className="h-4 w-4 mr-2" />
|
||||
Schedule for Later
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -680,6 +710,16 @@ export default function CampaignDetailsPage() {
|
||||
confirmText="Send Now"
|
||||
variant="default"
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={showDeleteDialog}
|
||||
onOpenChange={setShowDeleteDialog}
|
||||
onConfirm={handleDelete}
|
||||
title="Delete Campaign"
|
||||
description="Are you sure you want to delete this draft campaign? This action cannot be undone."
|
||||
confirmText="Delete Campaign"
|
||||
variant="destructive"
|
||||
/>
|
||||
</DashboardLayout>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import type {Campaign} from '@plunk/db';
|
||||
import {CampaignStatus} from '@plunk/db';
|
||||
import {DashboardLayout} from '../../components/DashboardLayout';
|
||||
import {network} from '../../lib/network';
|
||||
import {Calendar, Copy, Mail, Plus, Users} from 'lucide-react';
|
||||
import {Calendar, Copy, Mail, Plus, Trash2, Users} from 'lucide-react';
|
||||
import {NextSeo} from 'next-seo';
|
||||
import Link from 'next/link';
|
||||
import {useState} from 'react';
|
||||
@@ -37,6 +37,8 @@ export default function CampaignsPage() {
|
||||
const [statusFilter, setStatusFilter] = useState<string>('ALL');
|
||||
const [showCancelDialog, setShowCancelDialog] = useState(false);
|
||||
const [campaignToCancel, setCampaignToCancel] = useState<string | null>(null);
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
const [campaignToDelete, setCampaignToDelete] = useState<string | null>(null);
|
||||
|
||||
const {data, mutate, isLoading} = useSWR<PaginatedCampaigns>(
|
||||
`/campaigns?page=${page}&pageSize=20${statusFilter !== 'ALL' ? `&status=${statusFilter}` : ''}`,
|
||||
@@ -87,6 +89,20 @@ export default function CampaignsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!campaignToDelete) return;
|
||||
|
||||
try {
|
||||
await network.fetch('DELETE', `/campaigns/${campaignToDelete}`);
|
||||
toast.success('Campaign deleted successfully');
|
||||
void mutate();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : 'Failed to delete campaign');
|
||||
} finally {
|
||||
setCampaignToDelete(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<NextSeo title="Campaigns" />
|
||||
@@ -266,6 +282,19 @@ export default function CampaignsPage() {
|
||||
<Copy className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
{campaign.status === 'DRAFT' && (
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setCampaignToDelete(campaign.id);
|
||||
setShowDeleteDialog(true);
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{(campaign.status === 'SCHEDULED' || campaign.status === 'SENDING') && (
|
||||
<Button
|
||||
variant="destructive"
|
||||
@@ -314,6 +343,16 @@ export default function CampaignsPage() {
|
||||
confirmText="Cancel Campaign"
|
||||
variant="destructive"
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={showDeleteDialog}
|
||||
onOpenChange={setShowDeleteDialog}
|
||||
onConfirm={handleDelete}
|
||||
title="Delete Campaign"
|
||||
description="Are you sure you want to delete this draft campaign? This action cannot be undone."
|
||||
confirmText="Delete Campaign"
|
||||
variant="destructive"
|
||||
/>
|
||||
</DashboardLayout>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
ConfirmDialog,
|
||||
Input,
|
||||
Label,
|
||||
Select,
|
||||
@@ -20,7 +21,7 @@ import {EmailSettings} from '../../components/EmailSettings';
|
||||
import {EmailEditor} from '../../components/EmailEditor';
|
||||
import {network} from '../../lib/network';
|
||||
import {useChangeTracking} from '../../lib/hooks/useChangeTracking';
|
||||
import {ArrowLeft, Save} from 'lucide-react';
|
||||
import {ArrowLeft, Save, Trash2} from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import {useRouter} from 'next/router';
|
||||
import {useEffect, useState} from 'react';
|
||||
@@ -38,67 +39,63 @@ export default function TemplateEditorPage() {
|
||||
revalidateOnFocus: false,
|
||||
});
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [subject, setSubject] = useState('');
|
||||
const [from, setFrom] = useState('');
|
||||
const [fromName, setFromName] = useState('');
|
||||
const [replyTo, setReplyTo] = useState('');
|
||||
const [body, setBody] = useState('');
|
||||
const [type, setType] = useState<'MARKETING' | 'TRANSACTIONAL'>('MARKETING');
|
||||
const [editedTemplate, setEditedTemplate] = useState<Partial<Template>>({});
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [hasChanges, setHasChanges] = useState(false);
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
|
||||
// Load template data into form
|
||||
// Initialize edit fields when template loads
|
||||
useEffect(() => {
|
||||
if (template) {
|
||||
setName(template.name);
|
||||
setDescription(template.description ?? '');
|
||||
setSubject(template.subject);
|
||||
setFrom(template.from);
|
||||
setFromName(template.fromName ?? '');
|
||||
setReplyTo(template.replyTo ?? '');
|
||||
setBody(template.body);
|
||||
setType(template.type);
|
||||
if (template && Object.keys(editedTemplate).length === 0) {
|
||||
setEditedTemplate({
|
||||
name: template.name,
|
||||
description: template.description || '',
|
||||
subject: template.subject,
|
||||
body: template.body,
|
||||
from: template.from,
|
||||
fromName: template.fromName || '',
|
||||
replyTo: template.replyTo || '',
|
||||
type: template.type,
|
||||
});
|
||||
// Reset hasChanges when loading fresh data
|
||||
setHasChanges(false);
|
||||
}
|
||||
}, [template]);
|
||||
}, [template, editedTemplate]);
|
||||
|
||||
// Track changes
|
||||
useEffect(() => {
|
||||
if (!template) return;
|
||||
if (!template || Object.keys(editedTemplate).length === 0) return;
|
||||
|
||||
const changed =
|
||||
name !== template.name ||
|
||||
description !== (template.description ?? '') ||
|
||||
subject !== template.subject ||
|
||||
from !== template.from ||
|
||||
fromName !== (template.fromName ?? '') ||
|
||||
replyTo !== (template.replyTo ?? '') ||
|
||||
body !== template.body ||
|
||||
type !== template.type;
|
||||
editedTemplate.name !== template.name ||
|
||||
(editedTemplate.description || '') !== (template.description || '') ||
|
||||
editedTemplate.subject !== template.subject ||
|
||||
editedTemplate.body !== template.body ||
|
||||
editedTemplate.from !== template.from ||
|
||||
(editedTemplate.fromName || '') !== (template.fromName || '') ||
|
||||
(editedTemplate.replyTo || '') !== (template.replyTo || '') ||
|
||||
editedTemplate.type !== template.type;
|
||||
|
||||
setHasChanges(changed);
|
||||
}, [name, description, subject, from, fromName, replyTo, body, type, template]);
|
||||
}, [editedTemplate, template]);
|
||||
|
||||
// Warn before leaving page with unsaved changes
|
||||
useChangeTracking(hasChanges);
|
||||
|
||||
const handleSave = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const handleSave = async (e?: React.FormEvent) => {
|
||||
if (e) e.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
await network.fetch<Template, typeof TemplateSchemas.update>('PATCH', `/templates/${id}`, {
|
||||
name,
|
||||
description: description || undefined,
|
||||
subject,
|
||||
body,
|
||||
from,
|
||||
fromName: fromName || undefined,
|
||||
replyTo: replyTo || undefined,
|
||||
type,
|
||||
name: editedTemplate.name,
|
||||
description: editedTemplate.description || undefined,
|
||||
subject: editedTemplate.subject,
|
||||
body: editedTemplate.body,
|
||||
from: editedTemplate.from,
|
||||
fromName: editedTemplate.fromName || undefined,
|
||||
replyTo: editedTemplate.replyTo || undefined,
|
||||
type: editedTemplate.type,
|
||||
});
|
||||
|
||||
// Silent save - no toast notification
|
||||
@@ -111,6 +108,16 @@ export default function TemplateEditorPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
try {
|
||||
await network.fetch('DELETE', `/templates/${id}`);
|
||||
toast.success('Template deleted successfully');
|
||||
void router.push('/templates');
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : 'Failed to delete template');
|
||||
}
|
||||
};
|
||||
|
||||
if (!template) {
|
||||
return (
|
||||
<DashboardLayout>
|
||||
@@ -155,6 +162,10 @@ export default function TemplateEditorPage() {
|
||||
<div className="flex items-center gap-3">
|
||||
{!hasChanges && !isSubmitting && <span className="text-sm text-neutral-500">All changes saved</span>}
|
||||
{hasChanges && !isSubmitting && <span className="text-sm text-amber-600">Unsaved changes</span>}
|
||||
<Button type="button" variant="destructive" onClick={() => setShowDeleteDialog(true)}>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
Delete
|
||||
</Button>
|
||||
<Button type="submit" disabled={!hasChanges || isSubmitting}>
|
||||
<Save className="h-4 w-4" />
|
||||
{isSubmitting ? 'Saving...' : 'Save Changes'}
|
||||
@@ -177,8 +188,8 @@ export default function TemplateEditorPage() {
|
||||
<Input
|
||||
id="name"
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={e => setName(e.target.value)}
|
||||
value={editedTemplate.name || ''}
|
||||
onChange={e => setEditedTemplate({...editedTemplate, name: e.target.value})}
|
||||
required
|
||||
placeholder="Welcome Email"
|
||||
/>
|
||||
@@ -189,15 +200,18 @@ export default function TemplateEditorPage() {
|
||||
<Input
|
||||
id="description"
|
||||
type="text"
|
||||
value={description}
|
||||
onChange={e => setDescription(e.target.value)}
|
||||
value={editedTemplate.description || ''}
|
||||
onChange={e => setEditedTemplate({...editedTemplate, description: e.target.value})}
|
||||
placeholder="Sent to new subscribers"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="type">Type *</Label>
|
||||
<Select value={type} onValueChange={value => setType(value as 'MARKETING' | 'TRANSACTIONAL')}>
|
||||
<Select
|
||||
value={editedTemplate.type}
|
||||
onValueChange={value => setEditedTemplate({...editedTemplate, type: value as 'MARKETING' | 'TRANSACTIONAL'})}
|
||||
>
|
||||
<SelectTrigger id="type">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
@@ -216,8 +230,8 @@ export default function TemplateEditorPage() {
|
||||
<Input
|
||||
id="subject"
|
||||
type="text"
|
||||
value={subject}
|
||||
onChange={e => setSubject(e.target.value)}
|
||||
value={editedTemplate.subject || ''}
|
||||
onChange={e => setEditedTemplate({...editedTemplate, subject: e.target.value})}
|
||||
required
|
||||
placeholder="Welcome to our platform!"
|
||||
/>
|
||||
@@ -225,12 +239,12 @@ export default function TemplateEditorPage() {
|
||||
</div>
|
||||
|
||||
<EmailSettings
|
||||
from={from}
|
||||
fromName={fromName}
|
||||
replyTo={replyTo}
|
||||
onFromChange={setFrom}
|
||||
onFromNameChange={setFromName}
|
||||
onReplyToChange={setReplyTo}
|
||||
from={editedTemplate.from || ''}
|
||||
fromName={editedTemplate.fromName || ''}
|
||||
replyTo={editedTemplate.replyTo || ''}
|
||||
onFromChange={value => setEditedTemplate({...editedTemplate, from: value})}
|
||||
onFromNameChange={value => setEditedTemplate({...editedTemplate, fromName: value})}
|
||||
onReplyToChange={value => setEditedTemplate({...editedTemplate, replyTo: value})}
|
||||
fromNamePlaceholder={activeProject?.name || 'Your Company'}
|
||||
showFromNameHelpText
|
||||
layout="vertical"
|
||||
@@ -248,16 +262,13 @@ export default function TemplateEditorPage() {
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmailEditor
|
||||
value={body}
|
||||
onChange={newBody => {
|
||||
setBody(newBody);
|
||||
setHasChanges(true);
|
||||
}}
|
||||
value={editedTemplate.body || ''}
|
||||
onChange={body => setEditedTemplate({...editedTemplate, body})}
|
||||
placeholder="<h1>Welcome!</h1><p>Thanks for subscribing to our newsletter.</p>"
|
||||
canUploadImages={true}
|
||||
subject={subject}
|
||||
from={from}
|
||||
replyTo={replyTo}
|
||||
subject={editedTemplate.subject}
|
||||
from={editedTemplate.from}
|
||||
replyTo={editedTemplate.replyTo || undefined}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -267,6 +278,17 @@ export default function TemplateEditorPage() {
|
||||
|
||||
{/* Sticky Save Bar */}
|
||||
<StickySaveBar hasChanges={hasChanges} isSubmitting={isSubmitting} onSave={handleSave} />
|
||||
|
||||
{/* Delete Template Confirmation */}
|
||||
<ConfirmDialog
|
||||
open={showDeleteDialog}
|
||||
onOpenChange={setShowDeleteDialog}
|
||||
onConfirm={handleDelete}
|
||||
title="Delete Template"
|
||||
description="Are you sure you want to delete this template? This action cannot be undone."
|
||||
confirmText="Delete Template"
|
||||
variant="destructive"
|
||||
/>
|
||||
</DashboardLayout>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -38,7 +38,6 @@ import {
|
||||
Info,
|
||||
LogOut,
|
||||
Mail,
|
||||
Play,
|
||||
Plus,
|
||||
Power,
|
||||
PowerOff,
|
||||
@@ -115,11 +114,11 @@ export default function WorkflowEditorPage() {
|
||||
const {id} = router.query;
|
||||
const [activeTab, setActiveTab] = useState<'builder' | 'executions'>('builder');
|
||||
const [showSettingsDialog, setShowSettingsDialog] = useState(false);
|
||||
const [showTestDialog, setShowTestDialog] = useState(false);
|
||||
const [editingStep, setEditingStep] = useState<WorkflowStep | null>(null);
|
||||
const [showCancelAllDialog, setShowCancelAllDialog] = useState(false);
|
||||
const [executionToCancel, setExecutionToCancel] = useState<string | null>(null);
|
||||
const [isCancelling, setIsCancelling] = useState(false);
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
|
||||
const {data: workflow, mutate} = useSWR<WorkflowWithDetails>(id ? `/workflows/${id}` : null, {
|
||||
revalidateOnFocus: false,
|
||||
@@ -326,6 +325,16 @@ export default function WorkflowEditorPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
try {
|
||||
await network.fetch('DELETE', `/workflows/${id}`);
|
||||
toast.success('Workflow deleted successfully');
|
||||
void router.push('/workflows');
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : 'Failed to delete workflow');
|
||||
}
|
||||
};
|
||||
|
||||
// Listen for edit step events from the WorkflowBuilder
|
||||
useEffect(() => {
|
||||
const handleEditStepEvent = (event: Event) => {
|
||||
@@ -406,14 +415,14 @@ export default function WorkflowEditorPage() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" onClick={() => setShowTestDialog(true)}>
|
||||
<Play className="h-4 w-4" />
|
||||
Test
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setShowSettingsDialog(true)}>
|
||||
<Settings className="h-4 w-4" />
|
||||
Settings
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={() => setShowDeleteDialog(true)}>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
Delete
|
||||
</Button>
|
||||
<Button onClick={handleToggleEnabled}>
|
||||
{workflow.enabled ? (
|
||||
<>
|
||||
@@ -653,7 +662,6 @@ export default function WorkflowEditorPage() {
|
||||
onOpenChange={setShowSettingsDialog}
|
||||
onSave={handleUpdateSettings}
|
||||
/>
|
||||
<TestWorkflowDialog open={showTestDialog} onOpenChange={setShowTestDialog} workflowId={id as string} />
|
||||
{editingStep && (
|
||||
<EditStepDialog
|
||||
step={editingStep}
|
||||
@@ -722,6 +730,17 @@ export default function WorkflowEditorPage() {
|
||||
variant="destructive"
|
||||
isLoading={isCancelling}
|
||||
/>
|
||||
|
||||
{/* Delete Workflow Confirmation */}
|
||||
<ConfirmDialog
|
||||
open={showDeleteDialog}
|
||||
onOpenChange={setShowDeleteDialog}
|
||||
onConfirm={handleDelete}
|
||||
title="Delete Workflow"
|
||||
description="Are you sure you want to delete this workflow? This action cannot be undone."
|
||||
confirmText="Delete Workflow"
|
||||
variant="destructive"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</DashboardLayout>
|
||||
@@ -803,93 +822,6 @@ function SettingsDialog({workflow, open, onOpenChange, onSave}: SettingsDialogPr
|
||||
);
|
||||
}
|
||||
|
||||
// Test Workflow Dialog Component
|
||||
interface TestWorkflowDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
workflowId: string;
|
||||
}
|
||||
|
||||
function TestWorkflowDialog({open, onOpenChange, workflowId}: TestWorkflowDialogProps) {
|
||||
const [email, setEmail] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
// First, find or create the contact
|
||||
const contacts = await network.fetch<{contacts: {id: string; email: string}[]}>(
|
||||
'GET',
|
||||
`/contacts?search=${email}`,
|
||||
);
|
||||
let contactId = contacts.contacts.find(c => c.email === email)?.id;
|
||||
|
||||
if (!contactId) {
|
||||
const newContact = await network.fetch<{id: string}, typeof ContactSchemas.create>('POST', '/contacts', {
|
||||
email,
|
||||
subscribed: true,
|
||||
});
|
||||
contactId = newContact.id;
|
||||
}
|
||||
|
||||
// Start workflow execution
|
||||
await network.fetch<WorkflowExecution, typeof WorkflowSchemas.startExecution>(
|
||||
'POST',
|
||||
`/workflows/${workflowId}/executions`,
|
||||
{
|
||||
contactId,
|
||||
},
|
||||
);
|
||||
|
||||
toast.success('Workflow test started successfully');
|
||||
setEmail('');
|
||||
onOpenChange(false);
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : 'Failed to start workflow test');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Test Workflow</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<Label htmlFor="email">Test Email Address *</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={e => setEmail(e.target.value)}
|
||||
required
|
||||
placeholder="test@example.com"
|
||||
/>
|
||||
<p className="text-xs text-neutral-500 mt-1">
|
||||
The workflow will be executed for this email address. If the contact doesn't exist, it will be
|
||||
created.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? 'Starting...' : 'Start Test'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// Add Step Dialog Component
|
||||
interface AddStepDialogProps {
|
||||
open: boolean;
|
||||
|
||||
Reference in New Issue
Block a user