diff --git a/apps/api/src/services/CampaignService.ts b/apps/api/src/services/CampaignService.ts
index 6ea24f4..01fd5a5 100644
--- a/apps/api/src/services/CampaignService.ts
+++ b/apps/api/src/services/CampaignService.ts
@@ -116,6 +116,11 @@ export class CampaignService {
}
if (data.segmentId !== undefined) {
+ // Prevent changing segment on scheduled campaigns
+ if (campaign.status === CampaignStatus.SCHEDULED) {
+ throw new HttpException(400, 'Cannot change segment for scheduled campaigns');
+ }
+
if (data.segmentId) {
const segment = await prisma.segment.findFirst({
where: {id: data.segmentId, projectId},
diff --git a/apps/api/src/services/DomainService.ts b/apps/api/src/services/DomainService.ts
index b25cba0..d837052 100644
--- a/apps/api/src/services/DomainService.ts
+++ b/apps/api/src/services/DomainService.ts
@@ -109,7 +109,28 @@ export class DomainService {
);
}
- // Check if domain is used in any campaigns
+ // Check if domain is used in any workflow steps (via templates)
+ const workflowStepsUsingDomain = await prisma.workflowStep.count({
+ where: {
+ workflow: {
+ projectId: domain.projectId,
+ },
+ template: {
+ from: {
+ contains: `@${domainName}`,
+ },
+ },
+ },
+ });
+
+ if (workflowStepsUsingDomain > 0) {
+ throw new HttpException(
+ 409,
+ `Cannot delete domain: it is currently used in ${workflowStepsUsingDomain} workflow step(s). Update the workflow templates first.`,
+ );
+ }
+
+ // Check if domain is used in any active campaigns
const campaignsUsingDomain = await prisma.campaign.count({
where: {
projectId: domain.projectId,
@@ -117,7 +138,7 @@ export class DomainService {
contains: `@${domainName}`,
},
status: {
- not: 'SENT', // Allow deletion if all campaigns using it are completed
+ in: ['DRAFT', 'SCHEDULED', 'SENDING'],
},
},
});
diff --git a/apps/api/src/services/SegmentService.ts b/apps/api/src/services/SegmentService.ts
index bfbe5d6..d393020 100644
--- a/apps/api/src/services/SegmentService.ts
+++ b/apps/api/src/services/SegmentService.ts
@@ -180,12 +180,12 @@ export class SegmentService {
// First verify segment exists and belongs to project
await this.get(projectId, segmentId);
- // Check if segment is used in any campaigns
+ // Check if segment is used in any active campaigns
const campaignsUsingSegment = await prisma.campaign.count({
where: {
segmentId,
status: {
- not: 'SENT', // Allow deletion if all campaigns using it are completed
+ in: ['DRAFT', 'SCHEDULED', 'SENDING'],
},
},
});
diff --git a/apps/api/src/services/WorkflowService.ts b/apps/api/src/services/WorkflowService.ts
index 17a5af3..9110d56 100644
--- a/apps/api/src/services/WorkflowService.ts
+++ b/apps/api/src/services/WorkflowService.ts
@@ -242,6 +242,16 @@ export class WorkflowService {
// Verify workflow exists and belongs to project
const workflow = await this.get(projectId, workflowId);
+ // Check if workflow has active executions
+ const activeExecutions = await this.hasActiveExecutions(workflowId);
+
+ if (activeExecutions > 0) {
+ throw new HttpException(
+ 409,
+ `Cannot delete workflow: it has ${activeExecutions} active execution(s). Please wait for them to complete or cancel them first.`,
+ );
+ }
+
await prisma.workflow.delete({
where: {id: workflowId},
});
diff --git a/apps/landing/src/lib/network.ts b/apps/landing/src/lib/network.ts
index 55b844b..5c92a1b 100644
--- a/apps/landing/src/lib/network.ts
+++ b/apps/landing/src/lib/network.ts
@@ -11,6 +11,17 @@ interface TypedSchema extends ZodSchema {
_type: unknown;
}
+interface ApiResponse {
+ message?: string;
+ error?: {
+ message?: string;
+ code?: string;
+ [key: string]: unknown;
+ };
+
+ [key: string]: unknown;
+}
+
export class network {
/**
* Fetcher function that includes toast support
@@ -31,13 +42,14 @@ export class network {
credentials: 'include',
});
- const res = await response.json();
+ 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;
+ return res as T;
}
}
diff --git a/apps/web/src/components/DashboardLayout.tsx b/apps/web/src/components/DashboardLayout.tsx
index cd61146..afd81e9 100644
--- a/apps/web/src/components/DashboardLayout.tsx
+++ b/apps/web/src/components/DashboardLayout.tsx
@@ -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 && (
@@ -680,6 +710,16 @@ export default function CampaignDetailsPage() {
confirmText="Send Now"
variant="default"
/>
+
+
);
}
diff --git a/apps/web/src/pages/campaigns/index.tsx b/apps/web/src/pages/campaigns/index.tsx
index 0fbb928..aac0cae 100644
--- a/apps/web/src/pages/campaigns/index.tsx
+++ b/apps/web/src/pages/campaigns/index.tsx
@@ -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('ALL');
const [showCancelDialog, setShowCancelDialog] = useState(false);
const [campaignToCancel, setCampaignToCancel] = useState(null);
+ const [showDeleteDialog, setShowDeleteDialog] = useState(false);
+ const [campaignToDelete, setCampaignToDelete] = useState(null);
const {data, mutate, isLoading} = useSWR(
`/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 (
<>
@@ -266,6 +282,19 @@ export default function CampaignsPage() {
+ {campaign.status === 'DRAFT' && (
+ {
+ setCampaignToDelete(campaign.id);
+ setShowDeleteDialog(true);
+ }}
+ >
+
+
+ )}
+
{(campaign.status === 'SCHEDULED' || campaign.status === 'SENDING') && (
+
+
>
);
diff --git a/apps/web/src/pages/templates/[id].tsx b/apps/web/src/pages/templates/[id].tsx
index 1aecd5f..8ca9079 100644
--- a/apps/web/src/pages/templates/[id].tsx
+++ b/apps/web/src/pages/templates/[id].tsx
@@ -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>({});
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('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 (
@@ -155,6 +162,10 @@ export default function TemplateEditorPage() {
{!hasChanges && !isSubmitting && All changes saved}
{hasChanges && !isSubmitting && Unsaved changes}
+ setShowDeleteDialog(true)}>
+
+ Delete
+
{isSubmitting ? 'Saving...' : 'Save Changes'}
@@ -177,8 +188,8 @@ export default function TemplateEditorPage() {
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() {
setDescription(e.target.value)}
+ value={editedTemplate.description || ''}
+ onChange={e => setEditedTemplate({...editedTemplate, description: e.target.value})}
placeholder="Sent to new subscribers"
/>
-
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() {
{
- setBody(newBody);
- setHasChanges(true);
- }}
+ value={editedTemplate.body || ''}
+ onChange={body => setEditedTemplate({...editedTemplate, body})}
placeholder="Welcome!
Thanks for subscribing to our newsletter.
"
canUploadImages={true}
- subject={subject}
- from={from}
- replyTo={replyTo}
+ subject={editedTemplate.subject}
+ from={editedTemplate.from}
+ replyTo={editedTemplate.replyTo || undefined}
/>
@@ -267,6 +278,17 @@ export default function TemplateEditorPage() {
{/* Sticky Save Bar */}
+
+ {/* Delete Template Confirmation */}
+
);
}
diff --git a/apps/web/src/pages/workflows/[id].tsx b/apps/web/src/pages/workflows/[id].tsx
index 95317ac..4859696 100644
--- a/apps/web/src/pages/workflows/[id].tsx
+++ b/apps/web/src/pages/workflows/[id].tsx
@@ -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(null);
const [showCancelAllDialog, setShowCancelAllDialog] = useState(false);
const [executionToCancel, setExecutionToCancel] = useState(null);
const [isCancelling, setIsCancelling] = useState(false);
+ const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const {data: workflow, mutate} = useSWR(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() {
-
setShowTestDialog(true)}>
-
- Test
-
setShowSettingsDialog(true)}>
Settings
+
setShowDeleteDialog(true)}>
+
+ Delete
+
{workflow.enabled ? (
<>
@@ -653,7 +662,6 @@ export default function WorkflowEditorPage() {
onOpenChange={setShowSettingsDialog}
onSave={handleUpdateSettings}
/>
-
{editingStep && (
+
+ {/* Delete Workflow Confirmation */}
+
>
)}
@@ -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(
- '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 (
-
- );
-}
-
// Add Step Dialog Component
interface AddStepDialogProps {
open: boolean;