wacrm/src/app/(dashboard)/broadcasts/new/page.tsx
Arnas Donauskas 296a905976
feat(broadcasts) C: custom-field audience, exclude tags, live preview
Stacked on PR B (#22). Merge A → B → C in order.

Step 2 — Audience
- Implement the "Custom Field" audience option (was a stub): field
  picker + operator (is / is not / contains) + value input. Estimated
  count query joins contact_custom_values with the operator mapped
  to eq / neq / ilike. PostgREST ilike handles "contains" case-
  insensitively.
- New "Exclude contacts with these tags" section — applies to every
  audience type. Estimated count subtracts excluded contacts
  client-side against the resolved base set.
- Switching audience type clears stale shape fields (tagIds /
  customField / csvContacts) so old selections don't leak across.

Step 3 — Personalize
- Add "Custom Field" mapping option alongside static + contact field.
- Live Preview now pulls the most recent real contact (+ their custom
  values) instead of hard-coded sample data. Falls back to sample if
  the user has no contacts yet. Rendered in a WhatsApp-style bubble
  so the user gets a realistic feel for how the recipient sees it.

Hook — use-broadcast-sending
- AudienceConfig gains customField + excludeTagIds.
- resolveAudience: custom-field branch + exclude-tag subtraction
  applied after the base resolution (works for all / tags / custom
  field).
- resolveVariables accepts a pre-built (fieldId → value) map per
  contact. Before the send loop we bulk-fetch contact_custom_values
  for all resolved contacts in one query (paged by 500 for PostgREST
  limits) so we never N+1 per recipient.

new/page.tsx — passes customField + excludeTagIds into the hook;
variables state widens to allow type='custom_field'.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 11:39:24 +03:00

219 lines
7.1 KiB
TypeScript

'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { createClient } from '@/lib/supabase/client';
import { toast } from 'sonner';
import { MessageTemplate } from '@/types';
import { Step1ChooseTemplate } from '@/components/broadcasts/step1-choose-template';
import { Step2SelectAudience } from '@/components/broadcasts/step2-select-audience';
import { Step3Personalize } from '@/components/broadcasts/step3-personalize';
import { Step4ScheduleSend } from '@/components/broadcasts/step4-schedule-send';
import { useBroadcastSending } from '@/hooks/use-broadcast-sending';
import { Check } from 'lucide-react';
const steps = [
{ label: 'Template', key: 'template' },
{ label: 'Audience', key: 'audience' },
{ label: 'Personalize', key: 'personalize' },
{ label: 'Send', key: 'send' },
] as const;
export default function NewBroadcastPage() {
const router = useRouter();
const { createAndSendBroadcast, isProcessing, progress } = useBroadcastSending();
const [currentStep, setCurrentStep] = useState(0);
const [template, setTemplate] = useState<MessageTemplate | null>(null);
const [audience, setAudience] = useState<{
type: 'all' | 'tags' | 'custom_field' | 'csv';
tagIds?: string[];
customField?: {
fieldId: string;
operator: 'is' | 'is_not' | 'contains';
value: string;
};
csvContacts?: { phone: string; name?: string }[];
excludeTagIds?: string[];
}>({ type: 'all' });
const [variables, setVariables] = useState<
Record<string, { type: 'static' | 'field' | 'custom_field'; value: string }>
>({});
const [name, setName] = useState('');
async function handleSend() {
if (!template) return;
try {
const broadcastId = await createAndSendBroadcast({
name,
template,
audience: {
type: audience.type,
tagIds: audience.tagIds,
customField: audience.customField,
csvContacts: audience.csvContacts,
excludeTagIds: audience.excludeTagIds,
},
variables,
});
router.push(`/broadcasts/${broadcastId}`);
} catch (err) {
console.error('Broadcast failed:', err);
}
}
/**
* Writes a draft broadcast row — no recipients, no sending. The user
* can revisit it via the list page to finish the flow later. We
* don't persist the in-progress audience/variable config here
* because the current schema doesn't carry it past `audience_filter`
* and `template_variables`; those are enough for the user to
* recognize the draft but not to exactly round-trip into the wizard.
* A full resume-draft UX is a future polish.
*/
async function handleSaveDraft() {
if (!template || !name.trim()) {
toast.error('Give the broadcast a name before saving a draft.');
return;
}
const supabase = createClient();
const {
data: { session },
} = await supabase.auth.getSession();
const user = session?.user;
if (!user) {
toast.error('Not signed in.');
return;
}
const { error } = await supabase.from('broadcasts').insert({
user_id: user.id,
name: name.trim(),
template_name: template.name,
template_language: template.language ?? 'en_US',
template_variables: variables,
audience_filter: {
type: audience.type,
tagIds: audience.tagIds,
},
status: 'draft',
total_recipients: 0,
sent_count: 0,
delivered_count: 0,
read_count: 0,
replied_count: 0,
failed_count: 0,
});
if (error) {
toast.error(`Failed to save draft: ${error.message}`);
return;
}
toast.success('Draft saved');
router.push('/broadcasts');
}
return (
<div className="mx-auto max-w-3xl space-y-8">
{/* Header */}
<div>
<h1 className="text-2xl font-bold text-white">New Broadcast</h1>
<p className="mt-1 text-sm text-slate-400">
Create and send a broadcast message to your contacts.
</p>
</div>
{/* Step Indicator */}
<div className="flex items-center justify-between">
{steps.map((step, index) => {
const isActive = index === currentStep;
const isCompleted = index < currentStep;
return (
<div key={step.key} className="flex flex-1 items-center">
<div className="flex items-center gap-2">
<div
className={`flex h-8 w-8 items-center justify-center rounded-full text-xs font-medium transition-all ${
isCompleted
? 'bg-emerald-500 text-white'
: isActive
? 'border-2 border-emerald-500 bg-emerald-500/10 text-emerald-400'
: 'border border-slate-700 bg-slate-800 text-slate-500'
}`}
>
{isCompleted ? <Check className="h-4 w-4" /> : index + 1}
</div>
<span
className={`hidden text-sm font-medium sm:block ${
isActive ? 'text-white' : isCompleted ? 'text-emerald-400' : 'text-slate-500'
}`}
>
{step.label}
</span>
</div>
{index < steps.length - 1 && (
<div
className={`mx-3 h-px flex-1 ${
index < currentStep ? 'bg-emerald-500' : 'bg-slate-800'
}`}
/>
)}
</div>
);
})}
</div>
{/* Step Content */}
<div className="relative min-h-[400px]">
<div
className="transition-all duration-300 ease-in-out"
style={{
opacity: isProcessing ? 0.6 : 1,
pointerEvents: isProcessing ? 'none' : 'auto',
}}
>
{currentStep === 0 && (
<Step1ChooseTemplate
selectedTemplate={template}
onSelect={setTemplate}
onNext={() => setCurrentStep(1)}
onBack={() => router.push('/broadcasts')}
/>
)}
{currentStep === 1 && (
<Step2SelectAudience
audience={audience}
onUpdate={setAudience}
onNext={() => setCurrentStep(2)}
onBack={() => setCurrentStep(0)}
/>
)}
{currentStep === 2 && template && (
<Step3Personalize
template={template}
variables={variables}
onUpdate={setVariables}
onNext={() => setCurrentStep(3)}
onBack={() => setCurrentStep(1)}
/>
)}
{currentStep === 3 && template && (
<Step4ScheduleSend
name={name}
onNameChange={setName}
template={template}
audience={audience}
onSend={handleSend}
onSaveDraft={handleSaveDraft}
onBack={() => setCurrentStep(2)}
isProcessing={isProcessing}
progress={progress}
/>
)}
</div>
</div>
</div>
);
}