All files / components/common EmailTemplateEditDialog.tsx

49.54% Statements 55/111
47.5% Branches 38/80
21.05% Functions 8/38
50% Lines 49/98

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463                                                        2x                                                               2x         31x 31x 31x 31x 31x 31x   31x 31x   31x 15x 1x                   31x     1x                                       31x                                       31x                                         31x       31x                         31x 1x   1x 1x   1x 1x   1x   13x 7x       1x 1x 1x 1x   1x   1x                                           31x 15x 1x           1x 1x 1x       31x 31x   31x       31x       31x                                                   31x   2x   31x                                                                                                                               14x                                                                                                                                                                                                                                                                    
import { useState, useEffect } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { AppDialog } from '@/components/common/AppDialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useToast } from '@/hooks/use-toast';
import { emailService, type EmailTemplate, type EmailTemplateUpdate } from '@/services/email.service';
import { adminService, type Configuration } from '@/services/admin.service';
import { useQuery } from '@tanstack/react-query';
import { Loader2, Send, CheckCircle2, XCircle } from 'lucide-react';
 
interface EmailTemplateEditDialogProps {
    template: EmailTemplate | null;
    open: boolean;
    onOpenChange: (open: boolean) => void;
}
 
// Hardcoded template variables per template type
const TEMPLATE_VARIABLES: Record<string, string[]> = {
    email_verification: [
        'app_name',
        'app_url',
        'user_name',
        'user_email',
        'verification_url',
        'token',
        'expires_at',
    ],
    password_reset: [
        'app_name',
        'app_url',
        'user_name',
        'user_email',
        'reset_url',
        'token',
        'expires_at',
    ],
    invitation: [
        'app_name',
        'app_url',
        'user_name',
        'user_email',
        'invitation_url',
        'token',
        'account_name',
        'invited_by',
        'expires_at',
    ],
};
 
export const EmailTemplateEditDialog = ({
    template,
    open,
    onOpenChange,
}: EmailTemplateEditDialogProps) => {
    const [formData, setFormData] = useState<EmailTemplateUpdate>({});
    const [testEmail, setTestEmail] = useState('');
    const [selectedProvider, setSelectedProvider] = useState<string>('auto');
    const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null);
    const [previewHtml, setPreviewHtml] = useState<string>('');
    const [previewLoading, setPreviewLoading] = useState(false);
 
    const queryClient = useQueryClient();
    const { toast } = useToast();
 
    useEffect(() => {
        if (template) {
            setFormData({
                subject: template.subject,
                html_body: template.html_body,
                text_body: template.text_body,
                enabled: template.enabled,
            });
        }
    }, [template]);
 
    // Fetch enabled email providers (system and account)
    const { data: providers } = useQuery({
        queryKey: ['providers', template?.account_id],
        queryFn: async () => {
            const systemConfigs = await adminService.getSystemConfigs('email_providers');
            let configs = [...systemConfigs];
 
            if (template?.account_id && template.account_id !== '00000000-0000-0000-0000-000000000000') {
                const accountConfigs = await adminService.getAccountConfigs(template.account_id, 'email_providers');
                configs = [...configs, ...accountConfigs];
            }
 
            // Filter enabled only and deduplicate by provider_name
            const uniqueProviders = new Map<string, Configuration>();
            configs.filter(c => c.enabled).forEach(c => {
                if (!uniqueProviders.has(c.provider_name)) {
                    uniqueProviders.set(c.provider_name, c);
                }
            });
            return Array.from(uniqueProviders.values());
        },
        enabled: !!template,
    });
 
    const updateMutation = useMutation({
        mutationFn: (data: EmailTemplateUpdate) =>
            emailService.updateEmailTemplate(template!.id, data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['email', 'templates'] });
            toast({
                title: 'Template Updated',
                description: 'Email template has been updated successfully.',
            });
            onOpenChange(false);
        },
        onError: (error: any) => {
            toast({
                title: 'Error',
                description: error.response?.data?.detail || 'Failed to update template.',
                variant: 'destructive',
            });
        },
    });
 
    const testEmailMutation = useMutation({
        mutationFn: (recipient: string) =>
            emailService.sendTestEmail(template!.id, {
                recipient_email: recipient,
                variables: {},
                provider: selectedProvider === 'auto' ? undefined : selectedProvider,
            }),
        onSuccess: (data) => {
            setTestEmail('');
            setTestResult({ success: true, message: data.message });
            // Clear message after 5 seconds
            setTimeout(() => setTestResult(null), 5000);
        },
        onError: (error: any) => {
            setTestResult({
                success: false,
                message: error.response?.data?.detail || 'Failed to send test email.'
            });
        },
    });
 
    const handleSave = () => {
        updateMutation.mutate(formData);
    };
 
    const handleSendTest = () => {
        if (!testEmail) {
            setTestResult({
                success: false,
                message: 'Please enter a recipient email address.'
            });
            return;
        }
        setTestResult(null);
        testEmailMutation.mutate(testEmail);
    };
 
    // Preview Logic
    const handlePreview = async (overrideData?: Partial<EmailTemplateUpdate>) => {
        Iif (!template) return;
 
        setPreviewLoading(true);
        try {
            // Create dummy variables for preview based on template type
            const variables: Record<string, string> = {};
            const keys = TEMPLATE_VARIABLES[template.template_type] || [];
 
            keys.forEach(key => {
                // Generate a dummy value for each variable
                const readableKey = key.split('_').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
                variables[key] = `[${readableKey}]`;
            });
 
            // If specific variables make sense to have realistic defaults, override them
            Eif (keys.includes('app_name')) variables['app_name'] = 'SnackBase';
            Eif (keys.includes('app_url')) variables['app_url'] = 'http://localhost:3000';
            Eif (keys.includes('user_name')) variables['user_name'] = 'John Doe';
            Eif (keys.includes('user_email')) variables['user_email'] = 'john@example.com';
 
            const dataToRender = overrideData || formData;
 
            const response = await emailService.renderEmailTemplate({
                template_type: template.template_type,
                variables,
                locale: template.locale,
                account_id: template.account_id,
                subject: dataToRender.subject || template.subject,
                html_body: dataToRender.html_body || template.html_body,
                text_body: dataToRender.text_body || template.text_body,
            });
 
            setPreviewHtml(response.html_body);
        } catch (error: any) {
            toast({
                title: 'Preview Failed',
                description: 'Could not generate preview.',
                variant: 'destructive',
            });
        } finally {
            setPreviewLoading(false);
        }
    };
 
    useEffect(() => {
        if (template && open) {
            const initialData = {
                subject: template.subject,
                html_body: template.html_body,
                text_body: template.text_body,
                enabled: template.enabled,
            };
            setFormData(initialData);
            setPreviewHtml(''); // Clear old preview
            handlePreview(initialData); // Use new data immediately
        }
    }, [template, open]);
 
    const [focusedField, setFocusedField] = useState<'subject' | 'html_body' | 'text_body' | null>('subject');
    const [cursorPosition, setCursorPosition] = useState<number | null>(null);
 
    const handleInputFocus = (field: 'subject' | 'html_body' | 'text_body') => {
        setFocusedField(field);
    };
 
    const handleInputSelect = (e: React.SyntheticEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        setCursorPosition(e.currentTarget.selectionStart);
    };
 
    const insertVariable = (variable: string) => {
        const varText = `{{${variable}}}`;
 
        setFormData((prev) => {
            const field = focusedField || 'subject';
            const currentValue = prev[field] || '';
 
            // If we have a cursor position and it's for the current field, insert there
            // Otherwise append to end
            const insertPos = cursorPosition !== null ? cursorPosition : currentValue.length;
 
            const newValue =
                currentValue.slice(0, insertPos) +
                varText +
                currentValue.slice(insertPos);
 
            // Update cursor position to be after inserted text
            setCursorPosition(insertPos + varText.length);
 
            return {
                ...prev,
                [field]: newValue,
            };
        });
    };
 
    if (!template) return null;
 
    const availableVariables = TEMPLATE_VARIABLES[template.template_type] || [];
 
    return (
        <AppDialog
            open={open}
            onOpenChange={onOpenChange}
            title={`Edit Template: ${template.template_type} (${template.locale})`}
            className="max-w-2xl"
            footer={
                <>
                    <div className="mr-auto flex items-center">
                        {template.is_builtin && (
                            <span className="text-xs text-muted-foreground bg-secondary px-2 py-1 rounded">
                                Built-in Template
                            </span>
                        )}
                        {testResult && (
                            <span className={`ml-4 text-sm flex items-center ${testResult.success ? 'text-green-600' : 'text-destructive'}`}>
                                {testResult.success ? (
                                    <CheckCircle2 className="h-4 w-4 mr-1" />
                                ) : (
                                    <XCircle className="h-4 w-4 mr-1" />
                                )}
                                {testResult.message}
                            </span>
                        )}
                    </div>
                    <Button variant="outline" onClick={() => onOpenChange(false)}>
                        Cancel
                    </Button>
                    <Button onClick={handleSave} disabled={updateMutation.isPending}>
                        {updateMutation.isPending ? (
                            <>
                                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                Saving...
                            </>
                        ) : (
                            'Save Changes'
                        )}
                    </Button>
                </>
            }
        >
            <div className="space-y-4">
                {/* Enabled Toggle & Vars */}
                <div className="flex items-center justify-between">
                    <Label htmlFor="enabled">Enabled</Label>
                    <Switch
                        id="enabled"
                        checked={formData.enabled ?? template.enabled}
                        onCheckedChange={(checked) =>
                            setFormData((prev) => ({ ...prev, enabled: checked }))
                        }
                    />
                </div>
 
                {/* Variable Selector */}
                {availableVariables.length > 0 && (
                    <div className="space-y-2">
                        <Label>Insert Variable</Label>
                        <Select onValueChange={insertVariable}>
                            <SelectTrigger>
                                <SelectValue placeholder={`Insert into ${focusedField || 'subject'}`} />
                            </SelectTrigger>
                            <SelectContent>
                                {availableVariables.map((variable) => (
                                    <SelectItem key={variable} value={variable}>
                                        {`{{${variable}}}`}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>
                )}
 
                {/* Subject */}
                <div className="space-y-2">
                    <Label htmlFor="subject">Subject</Label>
                    <Input
                        id="subject"
                        value={formData.subject ?? template.subject}
                        onChange={(e) =>
                            setFormData((prev) => ({ ...prev, subject: e.target.value }))
                        }
                        onFocus={() => handleInputFocus('subject')}
                        onSelect={handleInputSelect}
                        placeholder="Email subject line"
                    />
                </div>
 
                {/* HTML Body */}
                <div className="space-y-2">
                    <Label htmlFor="html_body">HTML Body</Label>
                    <Textarea
                        id="html_body"
                        value={formData.html_body ?? template.html_body}
                        onChange={(e) =>
                            setFormData((prev) => ({ ...prev, html_body: e.target.value }))
                        }
                        onFocus={() => handleInputFocus('html_body')}
                        onSelect={handleInputSelect}
                        placeholder="HTML email body"
                        className="font-mono text-sm resize-none min-h-[200px]"
                    />
                </div>
 
                {/* Text Body */}
                <div className="space-y-2">
                    <Label htmlFor="text_body">Text Body</Label>
                    <Textarea
                        id="text_body"
                        value={formData.text_body ?? template.text_body}
                        onChange={(e) =>
                            setFormData((prev) => ({ ...prev, text_body: e.target.value }))
                        }
                        onFocus={() => handleInputFocus('text_body')}
                        onSelect={handleInputSelect}
                        placeholder="Plain text email body"
                        className="font-mono text-sm min-h-[100px]"
                    />
                </div>
 
                {/* Preview */}
                <div className="space-y-2">
                    <div className="flex justify-between items-center">
                        <Label>Preview</Label>
                        <Button size="sm" variant="secondary" onClick={() => handlePreview()} disabled={previewLoading}>
                            {previewLoading ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : null}
                            Refresh Preview
                        </Button>
                    </div>
                    <div className="rounded-md border overflow-hidden bg-gray-50 dark:bg-gray-900" style={{ height: '300px' }}>
                        {previewHtml ? (
                            <iframe
                                srcDoc={previewHtml}
                                title="Email Preview"
                                className="w-full h-full border-0"
                                sandbox="allow-same-origin"
                            />
                        ) : (
                            <div className="flex items-center justify-center h-full text-muted-foreground">
                                Click Refresh to see preview
                            </div>
                        )}
                    </div>
                </div>
 
                {/* Test Email */}
                <div className="space-y-2 border-t pt-4">
                    <Label>Send Test Email</Label>
                    <div className="grid grid-cols-[1fr,2fr,auto] gap-2 items-end">
                        <div className="space-y-2">
                            <Label htmlFor="provider-select" className="text-xs text-muted-foreground">Provider</Label>
                            <Select value={selectedProvider} onValueChange={setSelectedProvider}>
                                <SelectTrigger id="provider-select">
                                    <SelectValue placeholder="Automatic" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="auto">Automatic (Default)</SelectItem>
                                    {providers?.map((provider) => (
                                        <SelectItem key={provider.provider_name} value={provider.provider_name}>
                                            {provider.display_name || provider.provider_name}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                        <div className="space-y-2">
                            <Label htmlFor="test_email" className="text-xs text-muted-foreground">Recipient</Label>
                            <Input
                                id="test_email"
                                type="email"
                                value={testEmail}
                                onChange={(e) => setTestEmail(e.target.value)}
                                placeholder="recipient@example.com"
                            />
                        </div>
                        <Button
                            onClick={handleSendTest}
                            disabled={testEmailMutation.isPending}
                            variant="outline"
                            className="mb-0.5"
                        >
                            {testEmailMutation.isPending ? (
                                <Loader2 className="h-4 w-4 animate-spin" />
                            ) : (
                                <Send className="h-4 w-4" />
                            )}
                            <span className="ml-2">Send</span>
                        </Button>
                    </div>
                </div>
            </div>
        </AppDialog>
    );
};