542 lines
21 KiB
TypeScript
542 lines
21 KiB
TypeScript
import {
|
|
Button,
|
|
Card,
|
|
CardContent,
|
|
CardDescription,
|
|
CardHeader,
|
|
CardTitle,
|
|
ConfirmDialog,
|
|
Input,
|
|
Label,
|
|
} from '@plunk/ui';
|
|
import type {Contact, Segment} from '@plunk/db';
|
|
import type {PaginatedResponse} from '@plunk/types';
|
|
import {DashboardLayout} from '../../components/DashboardLayout';
|
|
import {network} from '../../lib/network';
|
|
import {ArrowLeft, Database, Filter, MailCheck, MailX, RefreshCw, Save, Trash2, UserMinus, Users} from 'lucide-react';
|
|
import Link from 'next/link';
|
|
import {useRouter} from 'next/router';
|
|
import {useEffect, useState} from 'react';
|
|
import {toast} from 'sonner';
|
|
import useSWR from 'swr';
|
|
import type {FilterCondition} from '@plunk/types';
|
|
import {SegmentSchemas} from '@plunk/shared';
|
|
import {SegmentFilterBuilder} from '../../components/SegmentFilterBuilder';
|
|
import {ContactPicker} from '../../components/ContactPicker';
|
|
import dayjs from 'dayjs';
|
|
|
|
type SegmentType = 'DYNAMIC' | 'STATIC';
|
|
type SegmentWithType = Segment & {type: SegmentType};
|
|
|
|
// Count total filters in a condition (recursive)
|
|
function countFilters(condition: FilterCondition): number {
|
|
let count = 0;
|
|
for (const group of condition.groups) {
|
|
count += group.filters.length;
|
|
if (group.conditions) {
|
|
count += countFilters(group.conditions);
|
|
}
|
|
}
|
|
return count;
|
|
}
|
|
|
|
export default function SegmentDetailPage() {
|
|
const router = useRouter();
|
|
const {id} = router.query;
|
|
|
|
const {data: segment, mutate, isLoading} = useSWR<SegmentWithType>(id ? `/segments/${id}` : null);
|
|
const [contactsPage, setContactsPage] = useState(1);
|
|
const {
|
|
data: contactsData,
|
|
isLoading: isLoadingContacts,
|
|
mutate: mutateContacts,
|
|
} = useSWR<PaginatedResponse<Contact>>(id ? `/segments/${id}/contacts?page=${contactsPage}&pageSize=10` : null);
|
|
|
|
const [name, setName] = useState('');
|
|
const [description, setDescription] = useState('');
|
|
const [trackMembership, setTrackMembership] = useState(false);
|
|
const [condition, setCondition] = useState<FilterCondition>({
|
|
logic: 'AND',
|
|
groups: [{filters: [{field: 'subscribed', operator: 'equals', value: true}]}],
|
|
});
|
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
|
const [isComputing, setIsComputing] = useState(false);
|
|
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
|
|
|
// Static segment member management
|
|
const [pickedEmails, setPickedEmails] = useState<string[]>([]);
|
|
const [isAddingMembers, setIsAddingMembers] = useState(false);
|
|
const [removingEmail, setRemovingEmail] = useState<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
if (segment) {
|
|
setName(segment.name);
|
|
setDescription(segment.description || '');
|
|
setTrackMembership(segment.trackMembership);
|
|
setCondition(
|
|
(segment.condition as unknown as FilterCondition) || {
|
|
logic: 'AND',
|
|
groups: [{filters: [{field: 'subscribed', operator: 'equals', value: true}]}],
|
|
},
|
|
);
|
|
}
|
|
}, [segment]);
|
|
|
|
const handleSubmit = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
setIsSubmitting(true);
|
|
|
|
try {
|
|
await network.fetch<Segment, typeof SegmentSchemas.update>('PATCH', `/segments/${id}`, {
|
|
name,
|
|
description: description || undefined,
|
|
...(segment?.type !== 'STATIC' && {condition}),
|
|
trackMembership,
|
|
});
|
|
toast.success('Segment updated successfully');
|
|
void mutate();
|
|
} catch (error) {
|
|
toast.error(error instanceof Error ? error.message : 'Failed to update segment');
|
|
} finally {
|
|
setIsSubmitting(false);
|
|
}
|
|
};
|
|
|
|
const handleComputeMembership = async () => {
|
|
if (!trackMembership) {
|
|
toast.error('Membership tracking must be enabled to compute membership');
|
|
return;
|
|
}
|
|
|
|
setIsComputing(true);
|
|
try {
|
|
const result = await network.fetch<{added: number; removed: number; total: number}>(
|
|
'POST',
|
|
`/segments/${id}/compute`,
|
|
);
|
|
toast.success(`Membership updated: ${result.added} added, ${result.removed} removed, ${result.total} total`);
|
|
void mutate();
|
|
} catch (error) {
|
|
toast.error(error instanceof Error ? error.message : 'Failed to compute membership');
|
|
} finally {
|
|
setIsComputing(false);
|
|
}
|
|
};
|
|
|
|
const handleAddMembers = async () => {
|
|
if (pickedEmails.length === 0) {
|
|
toast.error('Select at least one contact');
|
|
return;
|
|
}
|
|
|
|
setIsAddingMembers(true);
|
|
try {
|
|
const result = await network.fetch<{added: number; notFound: string[]}, typeof SegmentSchemas.members>(
|
|
'POST',
|
|
`/segments/${id}/members`,
|
|
{emails: pickedEmails},
|
|
);
|
|
|
|
toast.success(`Added ${result.added} contact${result.added !== 1 ? 's' : ''} to segment`);
|
|
setPickedEmails([]);
|
|
void mutate();
|
|
void mutateContacts();
|
|
} catch (error) {
|
|
toast.error(error instanceof Error ? error.message : 'Failed to add contacts');
|
|
} finally {
|
|
setIsAddingMembers(false);
|
|
}
|
|
};
|
|
|
|
const handleRemoveMember = async (email: string) => {
|
|
setRemovingEmail(email);
|
|
try {
|
|
await network.fetch<{removed: number}, typeof SegmentSchemas.members>('DELETE', `/segments/${id}/members`, {
|
|
emails: [email],
|
|
});
|
|
toast.success(`Removed ${email} from segment`);
|
|
void mutate();
|
|
void mutateContacts();
|
|
} catch (error) {
|
|
toast.error(error instanceof Error ? error.message : 'Failed to remove contact');
|
|
} finally {
|
|
setRemovingEmail(null);
|
|
}
|
|
};
|
|
|
|
const handleDelete = async () => {
|
|
try {
|
|
await network.fetch('DELETE', `/segments/${id}`);
|
|
toast.success('Segment deleted successfully');
|
|
void router.push('/segments');
|
|
} catch (error) {
|
|
toast.error(error instanceof Error ? error.message : 'Failed to delete segment');
|
|
}
|
|
};
|
|
|
|
if (isLoading) {
|
|
return (
|
|
<DashboardLayout>
|
|
<div className="flex items-center justify-center py-12">
|
|
<div className="text-center">
|
|
<svg
|
|
className="h-8 w-8 animate-spin mx-auto text-neutral-900"
|
|
xmlns="http://www.w3.org/2000/svg"
|
|
fill="none"
|
|
viewBox="0 0 24 24"
|
|
>
|
|
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
|
<path
|
|
className="opacity-75"
|
|
fill="currentColor"
|
|
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
|
/>
|
|
</svg>
|
|
<p className="mt-2 text-sm text-neutral-500">Loading segment...</p>
|
|
</div>
|
|
</div>
|
|
</DashboardLayout>
|
|
);
|
|
}
|
|
|
|
if (!segment) {
|
|
return (
|
|
<DashboardLayout>
|
|
<div className="text-center py-12">
|
|
<h3 className="text-lg font-medium text-neutral-900 mb-2">Segment not found</h3>
|
|
<p className="text-neutral-500 mb-6">
|
|
The segment you're looking for doesn't exist or has been deleted.
|
|
</p>
|
|
<Link href="/segments">
|
|
<Button>
|
|
<ArrowLeft className="h-4 w-4" />
|
|
Back to Segments
|
|
</Button>
|
|
</Link>
|
|
</div>
|
|
</DashboardLayout>
|
|
);
|
|
}
|
|
|
|
const isStatic = segment.type === 'STATIC';
|
|
|
|
return (
|
|
<DashboardLayout>
|
|
<div className="space-y-6">
|
|
{/* Header */}
|
|
<div className="flex items-center justify-between">
|
|
<div className="flex items-center gap-4">
|
|
<Link href="/segments">
|
|
<Button variant="outline" size="sm">
|
|
<ArrowLeft className="h-4 w-4" />
|
|
</Button>
|
|
</Link>
|
|
<div>
|
|
<div className="flex items-center gap-2">
|
|
<h1 className="text-3xl font-bold text-neutral-900">{segment.name}</h1>
|
|
<span
|
|
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
|
isStatic ? 'bg-purple-100 text-purple-700' : 'bg-blue-100 text-blue-700'
|
|
}`}
|
|
>
|
|
{isStatic ? 'Static' : 'Dynamic'}
|
|
</span>
|
|
</div>
|
|
{segment.description && <p className="text-neutral-500 mt-1">{segment.description}</p>}
|
|
</div>
|
|
</div>
|
|
<Button variant="destructive" onClick={() => setShowDeleteDialog(true)}>
|
|
<Trash2 className="h-4 w-4" />
|
|
Delete Segment
|
|
</Button>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
|
{/* Edit Form */}
|
|
<div className="lg:col-span-2 space-y-6">
|
|
<form onSubmit={handleSubmit} className="space-y-6">
|
|
{/* Basic Info */}
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>Segment Details</CardTitle>
|
|
<CardDescription>Update segment name and description</CardDescription>
|
|
</CardHeader>
|
|
<CardContent className="space-y-4">
|
|
<div>
|
|
<Label htmlFor="name">Segment Name *</Label>
|
|
<Input
|
|
id="name"
|
|
type="text"
|
|
value={name}
|
|
onChange={e => setName(e.target.value)}
|
|
required
|
|
placeholder="e.g., Active Pro Users"
|
|
maxLength={100}
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<Label htmlFor="description">Description</Label>
|
|
<Input
|
|
id="description"
|
|
type="text"
|
|
value={description}
|
|
onChange={e => setDescription(e.target.value)}
|
|
placeholder="e.g., Users on pro plan who have been active in the last 30 days"
|
|
maxLength={500}
|
|
/>
|
|
</div>
|
|
|
|
<div className="flex items-start gap-3 p-4 bg-neutral-50 rounded-lg border border-neutral-200">
|
|
<input
|
|
id="trackMembership"
|
|
type="checkbox"
|
|
checked={trackMembership}
|
|
onChange={e => setTrackMembership(e.target.checked)}
|
|
className="mt-1 h-4 w-4 text-neutral-900 focus:ring-neutral-900 border-neutral-300 rounded"
|
|
/>
|
|
<div className="flex-1">
|
|
<Label htmlFor="trackMembership" className="font-medium cursor-pointer">
|
|
Track membership changes
|
|
</Label>
|
|
<p className="text-xs text-neutral-500 mt-1">
|
|
When enabled, segment entry and exit events will be tracked for use in workflows and analytics
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
|
|
{/* Filter Builder (DYNAMIC only) */}
|
|
{!isStatic && (
|
|
<Card>
|
|
<CardContent className="pt-6">
|
|
<SegmentFilterBuilder condition={condition} onChange={setCondition} />
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
|
|
{/* Actions */}
|
|
<div className="flex items-center justify-end">
|
|
<Button type="submit" disabled={isSubmitting}>
|
|
<Save className="h-4 w-4 mr-2" />
|
|
{isSubmitting ? 'Saving...' : 'Save Changes'}
|
|
</Button>
|
|
</div>
|
|
</form>
|
|
|
|
{/* Static member management */}
|
|
{isStatic && (
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>Add Members</CardTitle>
|
|
<CardDescription>Search and select contacts to add to this segment</CardDescription>
|
|
</CardHeader>
|
|
<CardContent className="space-y-4">
|
|
<ContactPicker
|
|
selected={pickedEmails}
|
|
onChange={setPickedEmails}
|
|
existing={contactsData?.data.map(c => c.email) ?? []}
|
|
placeholder="Search contacts to add..."
|
|
/>
|
|
<Button
|
|
type="button"
|
|
onClick={handleAddMembers}
|
|
disabled={isAddingMembers || pickedEmails.length === 0}
|
|
>
|
|
{isAddingMembers
|
|
? 'Adding...'
|
|
: `Add ${pickedEmails.length > 0 ? pickedEmails.length : ''} Contact${pickedEmails.length !== 1 ? 's' : ''}`}
|
|
</Button>
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
|
|
{/* Contacts */}
|
|
<Card>
|
|
<CardHeader>
|
|
<div className="flex items-center justify-between">
|
|
<div>
|
|
<CardTitle>{isStatic ? 'Members' : 'Matching Contacts'}</CardTitle>
|
|
<CardDescription>
|
|
{isStatic ? 'Contacts in this static segment' : "Contacts that match this segment's filters"}
|
|
</CardDescription>
|
|
</div>
|
|
{!isStatic && trackMembership && (
|
|
<Button variant="outline" size="sm" onClick={handleComputeMembership} disabled={isComputing}>
|
|
<RefreshCw className={`h-4 w-4 ${isComputing ? 'animate-spin' : ''}`} />
|
|
{isComputing ? 'Computing...' : 'Recompute'}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</CardHeader>
|
|
<CardContent>
|
|
{isLoadingContacts ? (
|
|
<div className="text-center py-8">
|
|
<p className="text-sm text-neutral-500">Loading contacts...</p>
|
|
</div>
|
|
) : contactsData?.data.length === 0 ? (
|
|
<div className="text-center py-8">
|
|
<Users className="h-12 w-12 text-neutral-400 mx-auto mb-4" />
|
|
<p className="text-neutral-500">
|
|
{isStatic ? 'No members in this segment yet' : 'No contacts match this segment'}
|
|
</p>
|
|
</div>
|
|
) : (
|
|
<>
|
|
<div className="space-y-2">
|
|
{contactsData?.data.map(contact => (
|
|
<div key={contact.id} className="flex items-center justify-between p-3 border rounded-lg">
|
|
<div className="flex items-center gap-2">
|
|
{contact.subscribed ? (
|
|
<MailCheck className="h-4 w-4 text-green-600" />
|
|
) : (
|
|
<MailX className="h-4 w-4 text-red-600" />
|
|
)}
|
|
<span className="text-sm font-medium">{contact.email}</span>
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
<Link href={`/contacts/${contact.id}`}>
|
|
<Button variant="ghost" size="sm">
|
|
View
|
|
</Button>
|
|
</Link>
|
|
{isStatic && (
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={() => handleRemoveMember(contact.email)}
|
|
disabled={removingEmail === contact.email}
|
|
className="text-red-600 hover:text-red-700 hover:bg-red-50"
|
|
>
|
|
<UserMinus className="h-4 w-4" />
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
|
|
{/* Pagination */}
|
|
{contactsData && contactsData.totalPages > 1 && (
|
|
<div className="flex items-center justify-between mt-4 pt-4 border-t">
|
|
<p className="text-sm text-neutral-500">
|
|
Page {contactsPage} of {contactsData.totalPages} ({contactsData.total} total)
|
|
</p>
|
|
<div className="flex items-center gap-2">
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => setContactsPage(p => p - 1)}
|
|
disabled={contactsPage === 1}
|
|
>
|
|
Previous
|
|
</Button>
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => setContactsPage(p => p + 1)}
|
|
disabled={contactsPage === contactsData.totalPages}
|
|
>
|
|
Next
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
|
|
{/* Metadata Sidebar */}
|
|
<div className="space-y-6">
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>Statistics</CardTitle>
|
|
</CardHeader>
|
|
<CardContent className="space-y-4">
|
|
<div className="flex items-center justify-between">
|
|
<div className="flex items-center gap-2">
|
|
<Users className="h-4 w-4 text-neutral-500" />
|
|
<span className="text-sm text-neutral-600">Members</span>
|
|
</div>
|
|
<span className="text-2xl font-bold text-neutral-900">{segment.memberCount}</span>
|
|
</div>
|
|
|
|
{!isStatic && (
|
|
<>
|
|
<div className="flex items-center justify-between">
|
|
<div className="flex items-center gap-2">
|
|
<Filter className="h-4 w-4 text-neutral-500" />
|
|
<span className="text-sm text-neutral-600">Filters</span>
|
|
</div>
|
|
<span className="text-lg font-semibold text-neutral-900">
|
|
{countFilters(segment.condition as unknown as FilterCondition)}
|
|
</span>
|
|
</div>
|
|
<div className="flex items-center justify-between">
|
|
<div className="flex items-center gap-2">
|
|
<Filter className="h-4 w-4 text-neutral-500" />
|
|
<span className="text-sm text-neutral-600">Groups</span>
|
|
</div>
|
|
<span className="text-lg font-semibold text-neutral-900">
|
|
{(segment.condition as unknown as FilterCondition)?.groups?.length || 0}
|
|
</span>
|
|
</div>
|
|
</>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle>Metadata</CardTitle>
|
|
</CardHeader>
|
|
<CardContent className="space-y-4">
|
|
<div className="flex items-start gap-3">
|
|
<Database className="h-5 w-5 text-neutral-500 mt-0.5" />
|
|
<div className="flex-1 min-w-0">
|
|
<p className="text-sm font-medium text-neutral-900">Segment ID</p>
|
|
<p className="text-xs text-neutral-500 font-mono break-all">{segment.id}</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<p className="text-sm font-medium text-neutral-900">Created</p>
|
|
<div className="group relative inline-block cursor-help">
|
|
<p className="text-sm text-neutral-500">{dayjs(segment.createdAt).fromNow()}</p>
|
|
<div className="hidden group-hover:block absolute z-10 w-48 p-2 bg-neutral-900 text-white text-xs rounded shadow-lg bottom-full left-0 mb-1 whitespace-nowrap">
|
|
{dayjs(segment.createdAt).format('DD MMMM YYYY, hh:mm')}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<p className="text-sm font-medium text-neutral-900">Last Updated</p>
|
|
<div className="group relative inline-block cursor-help">
|
|
<p className="text-sm text-neutral-500">{dayjs(segment.updatedAt).fromNow()}</p>
|
|
<div className="hidden group-hover:block absolute z-10 w-48 p-2 bg-neutral-900 text-white text-xs rounded shadow-lg bottom-full left-0 mb-1 whitespace-nowrap">
|
|
{dayjs(segment.updatedAt).format('DD MMMM YYYY, hh:mm')}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<ConfirmDialog
|
|
open={showDeleteDialog}
|
|
onOpenChange={setShowDeleteDialog}
|
|
onConfirm={handleDelete}
|
|
title="Delete Segment"
|
|
description="Are you sure you want to delete this segment? This action cannot be undone."
|
|
confirmText="Delete"
|
|
variant="destructive"
|
|
/>
|
|
</DashboardLayout>
|
|
);
|
|
}
|