Fix email unconfirmed login flow with OTP resend and update email API field names

This commit is contained in:
dwindown
2026-01-02 19:33:51 +07:00
parent 8f46c5cfd9
commit eee6339074
13 changed files with 668 additions and 65 deletions

358
EMAIL-TEMPLATE-SYSTEM.md Normal file
View File

@@ -0,0 +1,358 @@
# Unified Email Template System
## Overview
All emails now use a **single master template** for consistent branding and design. The master template wraps content-only HTML from database templates.
## Architecture
```
Database Template (content only)
Process Shortcodes ({nama}, {platform_name}, etc.)
EmailTemplateRenderer.render() - wraps with master template
Complete HTML Email sent via provider
```
## Master Template
**Location:** `supabase/shared/email-template-renderer.ts`
**Features:**
- Brutalist design (black borders, hard shadows)
- Responsive layout (600px max width)
- `.tiptap-content` wrapper for auto-styling
- Header with brand name + notification ID
- Footer with unsubscribe links
- All CSS included (no external dependencies)
**CSS Classes for Content:**
- `.tiptap-content h1, h2, h3` - Headings
- `.tiptap-content p` - Paragraphs
- `.tiptap-content a` - Links (underlined, bold)
- `.tiptap-content ul, ol` - Lists
- `.tiptap-content table` - Tables with brutalist borders
- `.btn` - Buttons with hard shadow
- `.otp-box` - OTP codes with dashed border
- `.alert-success, .alert-danger, .alert-info` - Colored alert boxes
## Database Templates
### Format
**CORRECT** (content-only):
```html
<h1>Payment Successful!</h1>
<p>Hello <strong>{nama}</strong>, your payment has been confirmed.</p>
<table>
<thead>
<tr>
<th>Parameter</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Order ID</td>
<td>{order_id}</td>
</tr>
</tbody>
</table>
```
**WRONG** (full HTML):
```html
<!DOCTYPE html>
<html>
<head>...</head>
<body>
<h1>Payment Successful!</h1>
...
</body>
</html>
```
### Why Content-Only?
The master template provides:
- Email client compatibility (resets, Outlook fixes)
- Consistent header/footer
- Responsive wrapper
- Brutalist styling
Your content just needs the **body HTML** - no `<html>`, `<head>`, or `<body>` tags.
## Usage in Edge Functions
### Auth OTP (`send-auth-otp`)
```typescript
import { EmailTemplateRenderer } from "../shared/email-template-renderer.ts";
// Fetch template from database
const template = await supabase
.from("notification_templates")
.select("*")
.eq("key", "auth_email_verification")
.single();
// Process shortcodes
let htmlContent = template.email_body_html;
Object.entries(templateVars).forEach(([key, value]) => {
htmlContent = htmlContent.replace(new RegExp(`{${key}}`, 'g'), value);
});
// Wrap with master template
const htmlBody = EmailTemplateRenderer.render({
subject: template.email_subject,
content: htmlContent,
brandName: settings.platform_name || 'ACCESS HUB',
});
// Send via send-email-v2
await fetch(`${supabaseUrl}/functions/v1/send-email-v2`, {
method: 'POST',
body: JSON.stringify({
to: email,
html_body: htmlBody,
// ... other fields
}),
});
```
### Other Notifications (`send-notification`)
```typescript
import { EmailTemplateRenderer } from "../shared/email-template-renderer.ts";
// Fetch template and process shortcodes
const htmlContent = replaceVariables(template.body_html || template.body_text, allVariables);
// Wrap with master template
const htmlBody = EmailTemplateRenderer.render({
subject: subject,
content: htmlContent,
brandName: settings.brand_name || "ACCESS HUB",
});
// Send via provider (SMTP, Resend, etc.)
await sendViaSMTP({ html: htmlBody, ... });
```
## Available Shortcodes
See `ShortcodeProcessor.DEFAULT_DATA` in `supabase/shared/email-template-renderer.ts`:
**User:**
- `{nama}` - User name
- `{email}` - User email
**Order:**
- `{order_id}` - Order ID
- `{tanggal_pesanan}` - Order date
- `{total}` - Total amount
- `{metode_pembayaran}` - Payment method
**Product:**
- `{produk}` - Product name
- `{kategori_produk}` - Product category
**Access:**
- `{link_akses}` - Access link
- `{username_akses}` - Access username
- `{password_akses}` - Access password
**Consulting:**
- `{tanggal_konsultasi}` - Consultation date
- `{jam_konsultasi}` - Consultation time
- `{link_meet}` - Meeting link
**And many more...**
## Creating New Templates
### 1. Design Content-Only HTML
Use brutalist components:
```html
<h1>Welcome!</h1>
<p>Hello <strong>{nama}</strong>, welcome to <strong>{platform_name}</strong>!</p>
<h2>Your Details</h2>
<table>
<thead>
<tr>
<th>Field</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Email</td>
<td>{email}</td>
</tr>
<tr>
<td>Plan</td>
<td>{plan_name}</td>
</tr>
</tbody>
</table>
<p style="margin-top: 30px;">
<a href="{dashboard_link}" class="btn btn-full">
Go to Dashboard
</a>
</p>
<blockquote class="alert-success">
<strong>Success!</strong> Your account is ready to use.
</blockquote>
```
### 2. Add to Database
```sql
INSERT INTO notification_templates (
key,
name,
is_active,
email_subject,
email_body_html
) VALUES (
'welcome_email',
'Welcome Email',
true,
'Welcome to {platform_name}!',
'---<h1>Welcome!</h1>...---'
);
```
### 3. Use in Edge Function
```typescript
const template = await getTemplate('welcome_email');
const htmlContent = processShortcodes(template.body_html, {
nama: user.name,
platform_name: settings.brand_name,
email: user.email,
plan_name: user.plan,
dashboard_link: 'https://...',
});
const htmlBody = EmailTemplateRenderer.render({
subject: template.subject,
content: htmlContent,
brandName: settings.brand_name,
});
```
## Migration Notes
### Old Templates (Self-Contained HTML)
If you have old templates with full HTML:
**Before:**
```html
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial; }
.container { max-width: 600px; }
h1 { color: #0066cc; }
</style>
</head>
<body>
<div class="container">
<h1>Welcome!</h1>
<p>Hello...</p>
</div>
</body>
</html>
```
**After (Content-Only):**
```html
<h1>Welcome!</h1>
<p>Hello...</p>
```
Remove:
- `<!DOCTYPE html>`
- `<html>`, `<head>`, `<body>` tags
- `<style>` blocks
- Container `<div>` wrappers
- Header/footer HTML
Keep:
- Content HTML only
- Shortcode placeholders `{variable}`
- Inline styles for special cases (rare)
## Benefits
**Consistent Branding** - All emails have same header/footer
**Single Source of Truth** - One master template controls design
**Easy Updates** - Change design in one place
**Email Client Compatible** - Master template has all the fixes
**Less Duplication** - No more reinventing styles per template
**Auto-Styling** - `.tiptap-content` CSS makes content look good
## Files
- `supabase/shared/email-template-renderer.ts` - Master template + renderer
- `supabase/functions/send-auth-otp/index.ts` - Uses master template
- `supabase/functions/send-notification/index.ts` - Uses master template
- `supabase/migrations/20250102000005_fix_auth_email_template_content_only.sql` - Auth template update
- `email-master-template.html` - Visual reference of master template
## Testing
### Test Master Template
```bash
# Test with curl
curl -X POST https://lovable.backoffice.biz.id/functions/v1/send-auth-otp \
-H "Authorization: Bearer YOUR_SERVICE_KEY" \
-H "Content-Type: application/json" \
-d '{"user_id":"TEST_ID","email":"test@example.com"}'
```
### Expected Result
Email should have:
- Black header with "ACCESS HUB" logo
- Notification ID (NOTIF #XXXXXX)
- Content styled with brutalist design
- Gray footer with unsubscribe links
- Responsive on mobile
## Troubleshooting
### Email Has No Styling
**Cause:** Template has full HTML, getting double-wrapped
**Fix:** Remove `<html>`, `<head>`, `<body>` from database template
### Styling Not Applied
**Cause:** Content not in `.tiptap-content` wrapper
**Fix:** Master template automatically wraps `{{content}}` in `.tiptap-content` div
### Broken Layout
**Cause:** Old template has container divs/wrappers
**Fix:** Remove container divs, keep only content HTML
---
**Status:** ✅ Unified system active
**Last Updated:** 2025-01-02

View File

@@ -197,12 +197,12 @@ export function IntegrasiTab() {
try { try {
const { data, error } = await supabase.functions.invoke('send-email-v2', { const { data, error } = await supabase.functions.invoke('send-email-v2', {
body: { body: {
to: testEmail, recipient: testEmail,
api_token: settings.api_token, api_token: settings.api_token,
from_name: settings.from_name, from_name: settings.from_name,
from_email: settings.from_email, from_email: settings.from_email,
subject: 'Test Email dari Access Hub', subject: 'Test Email dari Access Hub',
html_body: ` content: `
<h2>Test Email</h2> <h2>Test Email</h2>
<p>Ini adalah email uji coba dari aplikasi Access Hub Anda.</p> <p>Ini adalah email uji coba dari aplikasi Access Hub Anda.</p>
<p>Jika Anda menerima email ini, konfigurasi Mailketing API sudah berfungsi dengan baik!</p> <p>Jika Anda menerima email ini, konfigurasi Mailketing API sudah berfungsi dengan baik!</p>

View File

@@ -509,12 +509,12 @@ export function NotifikasiTab() {
// Send test email using send-email-v2 // Send test email using send-email-v2
const { data, error } = await supabase.functions.invoke('send-email-v2', { const { data, error } = await supabase.functions.invoke('send-email-v2', {
body: { body: {
to: template.test_email, recipient: template.test_email,
api_token: emailData.api_token, api_token: emailData.api_token,
from_name: emailData.from_name, from_name: emailData.from_name,
from_email: emailData.from_email, from_email: emailData.from_email,
subject: processedSubject, subject: processedSubject,
html_body: fullHtml, content: fullHtml,
}, },
}); });

View File

@@ -12,6 +12,7 @@ interface AuthContextType {
signOut: () => Promise<void>; signOut: () => Promise<void>;
sendAuthOTP: (userId: string, email: string) => Promise<{ success: boolean; message: string }>; sendAuthOTP: (userId: string, email: string) => Promise<{ success: boolean; message: string }>;
verifyAuthOTP: (userId: string, otpCode: string) => Promise<{ success: boolean; message: string }>; verifyAuthOTP: (userId: string, otpCode: string) => Promise<{ success: boolean; message: string }>;
getUserByEmail: (email: string) => Promise<{ success: boolean; user_id?: string; email_confirmed?: boolean; message?: string }>;
} }
const AuthContext = createContext<AuthContextType | undefined>(undefined); const AuthContext = createContext<AuthContextType | undefined>(undefined);
@@ -173,8 +174,50 @@ export function AuthProvider({ children }: { children: ReactNode }) {
} }
}; };
const getUserByEmail = async (email: string) => {
try {
const { data: { session } } = await supabase.auth.getSession();
const token = session?.access_token || import.meta.env.VITE_SUPABASE_ANON_KEY;
console.log('Getting user by email:', email);
const response = await fetch(
`${import.meta.env.VITE_SUPABASE_URL}/functions/v1/get-user-by-email`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ email }),
}
);
console.log('Get user response status:', response.status);
if (!response.ok) {
const errorText = await response.text();
console.error('Get user request failed:', response.status, errorText);
return {
success: false,
message: `HTTP ${response.status}: ${errorText}`
};
}
const result = await response.json();
console.log('Get user result:', result);
return result;
} catch (error: any) {
console.error('Error getting user by email:', error);
return {
success: false,
message: error.message || 'Failed to lookup user'
};
}
};
return ( return (
<AuthContext.Provider value={{ user, session, loading, isAdmin, signIn, signUp, signOut, sendAuthOTP, verifyAuthOTP }}> <AuthContext.Provider value={{ user, session, loading, isAdmin, signIn, signUp, signOut, sendAuthOTP, verifyAuthOTP, getUserByEmail }}>
{children} {children}
</AuthContext.Provider> </AuthContext.Provider>
); );

View File

@@ -23,7 +23,7 @@ export default function Auth() {
const [pendingUserId, setPendingUserId] = useState<string | null>(null); const [pendingUserId, setPendingUserId] = useState<string | null>(null);
const [resendCountdown, setResendCountdown] = useState(0); const [resendCountdown, setResendCountdown] = useState(0);
const [isResendOTP, setIsResendOTP] = useState(false); // Track if this is resend OTP for existing user const [isResendOTP, setIsResendOTP] = useState(false); // Track if this is resend OTP for existing user
const { signIn, signUp, user, sendAuthOTP, verifyAuthOTP } = useAuth(); const { signIn, signUp, user, sendAuthOTP, verifyAuthOTP, getUserByEmail } = useAuth();
const navigate = useNavigate(); const navigate = useNavigate();
useEffect(() => { useEffect(() => {
@@ -58,18 +58,42 @@ export default function Auth() {
if (isLogin) { if (isLogin) {
const { error } = await signIn(email, password); const { error } = await signIn(email, password);
if (error) { if (error) {
console.log('Login error:', error.message);
// Check if error is due to unconfirmed email // Check if error is due to unconfirmed email
if (error.message.includes('Email not confirmed') || error.message.includes('Email not verified')) { // Supabase returns various error messages for unconfirmed email
toast({ const isUnconfirmedEmail =
title: 'Email Belum Dikonfirmasi', error.message.includes('Email not confirmed') ||
description: 'Kirim ulang kode verifikasi ke email Anda?', error.message.includes('Email not verified') ||
variant: 'destructive' error.message.includes('Email not confirmed') ||
}); error.message.toLowerCase().includes('email') && error.message.toLowerCase().includes('not confirmed') ||
// Switch to OTP resend flow error.message.toLowerCase().includes('unconfirmed');
console.log('Is unconfirmed email?', isUnconfirmedEmail);
if (isUnconfirmedEmail) {
// Get user by email to fetch user_id
console.log('Fetching user by email for OTP resend...');
const userResult = await getUserByEmail(email);
console.log('User lookup result:', userResult);
if (userResult.success && userResult.user_id) {
setPendingUserId(userResult.user_id);
setIsResendOTP(true); setIsResendOTP(true);
setShowOTP(true); setShowOTP(true);
// Get user ID from error or fetch it setResendCountdown(0); // Allow immediate resend on first attempt
// For now, we'll handle it in the OTP resend button toast({
title: 'Email Belum Dikonfirmasi',
description: 'Silakan verifikasi email Anda. Kami akan mengirimkan kode OTP.',
});
} else {
toast({
title: 'Error',
description: 'User tidak ditemukan. Silakan daftar terlebih dahulu.',
variant: 'destructive'
});
}
setLoading(false); setLoading(false);
return; return;
} }

View File

@@ -1,5 +1,6 @@
import { serve } from "https://deno.land/std@0.190.0/http/server.ts"; import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2"; import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
import { EmailTemplateRenderer } from "../shared/email-template-renderer.ts";
const corsHeaders = { const corsHeaders = {
"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Origin": "*",
@@ -82,6 +83,14 @@ serve(async (req: Request): Promise<Response> => {
.select("*") .select("*")
.single(); .single();
// Get platform settings for brand_name
const { data: platformSettings } = await supabase
.from("platform_settings")
.select("brand_name")
.single();
const brandName = platformSettings?.brand_name || "ACCESS HUB";
let notifyError = null; let notifyError = null;
if (template && emailSettings?.api_token) { if (template && emailSettings?.api_token) {
@@ -98,6 +107,7 @@ serve(async (req: Request): Promise<Response> => {
jam_konsultasi: `${slot.start_time.substring(0, 5)} - ${slot.end_time.substring(0, 5)} WIB`, jam_konsultasi: `${slot.start_time.substring(0, 5)} - ${slot.end_time.substring(0, 5)} WIB`,
link_meet: slot.meet_link || "Akan diinformasikan", link_meet: slot.meet_link || "Akan diinformasikan",
jenis_konsultasi: slot.topic_category, jenis_konsultasi: slot.topic_category,
platform_name: brandName,
}; };
// Process shortcodes in template // Process shortcodes in template
@@ -110,15 +120,22 @@ serve(async (req: Request): Promise<Response> => {
emailSubject = emailSubject.replace(regex, String(value)); emailSubject = emailSubject.replace(regex, String(value));
}); });
// Wrap with master template
const fullHtml = EmailTemplateRenderer.render({
subject: emailSubject,
content: emailBody,
brandName: brandName,
});
// Send via send-email-v2 (Mailketing API) // Send via send-email-v2 (Mailketing API)
const { error: emailError } = await supabase.functions.invoke("send-email-v2", { const { error: emailError } = await supabase.functions.invoke("send-email-v2", {
body: { body: {
to: profile.email, recipient: profile.email,
api_token: emailSettings.api_token, api_token: emailSettings.api_token,
from_name: emailSettings.from_name || "Access Hub", from_name: emailSettings.from_name || brandName,
from_email: emailSettings.from_email || "noreply@with.dwindi.com", from_email: emailSettings.from_email || "noreply@with.dwindi.com",
subject: emailSubject, subject: emailSubject,
html_body: emailBody, content: fullHtml,
}, },
}); });

View File

@@ -0,0 +1,97 @@
import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};
interface GetUserRequest {
email: string;
}
serve(async (req: Request) => {
if (req.method === "OPTIONS") {
return new Response(null, { headers: corsHeaders });
}
try {
const { email }: GetUserRequest = await req.json();
// Validate required fields
if (!email) {
return new Response(
JSON.stringify({ success: false, message: "Missing required field: email" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Basic email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return new Response(
JSON.stringify({ success: false, message: "Invalid email format" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Initialize Supabase client with service role
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const supabase = createClient(supabaseUrl, supabaseServiceKey, {
auth: {
autoRefreshToken: false,
persistSession: false
}
});
console.log(`Looking up user with email: ${email}`);
// Get user by email from auth.users
const { data: { users }, error } = await supabase.auth.admin.listUsers();
if (error) {
console.error('Error listing users:', error);
throw new Error(`Failed to lookup user: ${error.message}`);
}
// Find user with matching email
const user = users?.find(u => u.email === email);
if (!user) {
console.log('User not found:', email);
return new Response(
JSON.stringify({
success: false,
message: "User not found",
user_id: null
}),
{ status: 404, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
console.log('User found:', { id: user.id, email: user.email, emailConfirmed: user.email_confirmed_at });
return new Response(
JSON.stringify({
success: true,
user_id: user.id,
email_confirmed: !!user.email_confirmed_at,
created_at: user.created_at
}),
{ status: 200, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
} catch (error: any) {
console.error("Error getting user by email:", error);
return new Response(
JSON.stringify({
success: false,
message: error.message || "Failed to lookup user",
user_id: null
}),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
});

View File

@@ -84,6 +84,19 @@ serve(async (req: Request) => {
throw new Error('Notification settings not configured'); throw new Error('Notification settings not configured');
} }
// Get platform settings for brand_name
const { data: platformSettings, error: platformError } = await supabase
.from('platform_settings')
.select('brand_name')
.single();
if (platformError) {
console.error('Error fetching platform settings:', platformError);
// Continue with fallback if platform settings not found
}
const brandName = platformSettings?.brand_name || settings.platform_name || 'ACCESS HUB';
// Get email template // Get email template
console.log('Fetching email template with key: auth_email_verification'); console.log('Fetching email template with key: auth_email_verification');
@@ -110,7 +123,7 @@ serve(async (req: Request) => {
// Prepare template variables // Prepare template variables
const templateVars = { const templateVars = {
platform_name: settings.platform_name || 'Platform', platform_name: brandName,
nama: user.user_metadata?.name || user.email || 'Pengguna', nama: user.user_metadata?.name || user.email || 'Pengguna',
email: email, email: email,
otp_code: otpCode, otp_code: otpCode,
@@ -135,7 +148,7 @@ serve(async (req: Request) => {
const htmlBody = EmailTemplateRenderer.render({ const htmlBody = EmailTemplateRenderer.render({
subject: subject, subject: subject,
content: htmlContent, content: htmlContent,
brandName: settings.platform_name || 'ACCESS HUB', brandName: brandName,
}); });
// Send email via send-email-v2 // Send email via send-email-v2
@@ -157,12 +170,12 @@ serve(async (req: Request) => {
// Log email details (truncate HTML body for readability) // Log email details (truncate HTML body for readability)
console.log('Email payload:', { console.log('Email payload:', {
to: email, recipient: email,
from_name: settings.from_name || settings.platform_name || 'Admin', from_name: settings.from_name || brandName,
from_email: settings.from_email || 'noreply@example.com', from_email: settings.from_email || 'noreply@example.com',
subject: subject, subject: subject,
html_body_length: htmlBody.length, content_length: htmlBody.length,
html_body_preview: htmlBody.substring(0, 200), content_preview: htmlBody.substring(0, 200),
}); });
const emailResponse = await fetch(`${supabaseUrl}/functions/v1/send-email-v2`, { const emailResponse = await fetch(`${supabaseUrl}/functions/v1/send-email-v2`, {
@@ -172,12 +185,12 @@ serve(async (req: Request) => {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ body: JSON.stringify({
to: email, recipient: email,
api_token: apiToken, api_token: apiToken,
from_name: settings.from_name || settings.platform_name || 'Admin', from_name: settings.from_name || brandName,
from_email: settings.from_email || 'noreply@example.com', from_email: settings.from_email || 'noreply@example.com',
subject: subject, subject: subject,
html_body: htmlBody, content: htmlBody,
}), }),
}); });

View File

@@ -143,12 +143,12 @@ serve(async (req: Request): Promise<Response> => {
// Send via send-email-v2 (Mailketing API) // Send via send-email-v2 (Mailketing API)
const { error: emailError } = await supabase.functions.invoke("send-email-v2", { const { error: emailError } = await supabase.functions.invoke("send-email-v2", {
body: { body: {
to: profile.email, recipient: profile.email,
api_token: smtpSettings.api_token, api_token: smtpSettings.api_token,
from_name: smtpSettings.from_name || platformSettings?.brand_name || "Access Hub", from_name: smtpSettings.from_name || platformSettings?.brand_name || "Access Hub",
from_email: smtpSettings.from_email || "noreply@with.dwindi.com", from_email: smtpSettings.from_email || "noreply@with.dwindi.com",
subject: emailSubject, subject: emailSubject,
html_body: emailBody, content: emailBody,
}, },
}); });

View File

@@ -6,33 +6,35 @@ const corsHeaders = {
}; };
interface EmailRequest { interface EmailRequest {
to: string; recipient: string;
api_token: string; api_token: string;
from_name: string; from_name: string;
from_email: string; from_email: string;
subject: string; subject: string;
html_body: string; content: string;
} }
// Send via Mailketing API // Send via Mailketing API
async function sendViaMailketing(request: EmailRequest): Promise<{ success: boolean; message: string }> { async function sendViaMailketing(request: EmailRequest): Promise<{ success: boolean; message: string }> {
const { to, api_token, from_name, from_email, subject, html_body } = request; const { recipient, api_token, from_name, from_email, subject, content } = request;
const formData = new FormData(); // Build form-encoded body (http_build_query format)
formData.append('to', to); const params = new URLSearchParams();
formData.append('from_name', from_name); params.append('api_token', api_token);
formData.append('from_email', from_email); params.append('from_name', from_name);
formData.append('subject', subject); params.append('from_email', from_email);
formData.append('html_body', html_body); params.append('recipient', recipient);
params.append('subject', subject);
params.append('content', content);
console.log(`Sending email via Mailketing to ${to}`); console.log(`Sending email via Mailketing to ${recipient}`);
const response = await fetch('https://api.mailketing.co/v1/send', { const response = await fetch('https://api.mailketing.co.id/api/v1/send', {
method: 'POST', method: 'POST',
headers: { headers: {
'Authorization': `Bearer ${api_token}`, 'Content-Type': 'application/x-www-form-urlencoded',
}, },
body: formData, body: params.toString(),
}); });
if (!response.ok) { if (!response.ok) {
@@ -46,7 +48,7 @@ async function sendViaMailketing(request: EmailRequest): Promise<{ success: bool
return { return {
success: true, success: true,
message: result.message || 'Email sent successfully via Mailketing' message: result.response || 'Email sent successfully via Mailketing'
}; };
} }
@@ -59,23 +61,23 @@ serve(async (req: Request): Promise<Response> => {
const body: EmailRequest = await req.json(); const body: EmailRequest = await req.json();
// Validate required fields // Validate required fields
if (!body.to || !body.api_token || !body.from_name || !body.from_email || !body.subject || !body.html_body) { if (!body.recipient || !body.api_token || !body.from_name || !body.from_email || !body.subject || !body.content) {
return new Response( return new Response(
JSON.stringify({ success: false, message: "Missing required fields: to, api_token, from_name, from_email, subject, html_body" }), JSON.stringify({ success: false, message: "Missing required fields: recipient, api_token, from_name, from_email, subject, content" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } } { status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
); );
} }
// Basic email validation // Basic email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(body.to) || !emailRegex.test(body.from_email)) { if (!emailRegex.test(body.recipient) || !emailRegex.test(body.from_email)) {
return new Response( return new Response(
JSON.stringify({ success: false, message: "Invalid email format" }), JSON.stringify({ success: false, message: "Invalid email format" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } } { status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
); );
} }
console.log(`Attempting to send email to: ${body.to}`); console.log(`Attempting to send email to: ${body.recipient}`);
console.log(`From: ${body.from_name} <${body.from_email}>`); console.log(`From: ${body.from_name} <${body.from_email}>`);
console.log(`Subject: ${body.subject}`); console.log(`Subject: ${body.subject}`);

View File

@@ -1,5 +1,6 @@
import { serve } from "https://deno.land/std@0.190.0/http/server.ts"; import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2"; import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
import { EmailTemplateRenderer } from "../shared/email-template-renderer.ts";
const corsHeaders = { const corsHeaders = {
"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Origin": "*",
@@ -246,7 +247,14 @@ serve(async (req: Request): Promise<Response> => {
}; };
const subject = replaceVariables(template.subject, allVariables); const subject = replaceVariables(template.subject, allVariables);
const htmlBody = replaceVariables(template.body_html || template.body_text || "", allVariables); const htmlContent = replaceVariables(template.body_html || template.body_text || "", allVariables);
// Wrap with master template for consistent branding
const htmlBody = EmailTemplateRenderer.render({
subject: subject,
content: htmlContent,
brandName: settings.brand_name || "ACCESS HUB",
});
const emailPayload: EmailPayload = { const emailPayload: EmailPayload = {
to: recipient_email, to: recipient_email,

View File

@@ -0,0 +1,40 @@
-- ============================================================================
-- Fix Auth OTP Email Template - Content Only (for master template wrapper)
-- ============================================================================
-- Update auth_email_verification template to be content-only
-- This will be wrapped by EmailTemplateRenderer with master template
UPDATE notification_templates
SET
email_subject = 'Kode Verifikasi Email Anda - {platform_name}',
email_body_html = '---
<h1>🔐 Verifikasi Email</h1>
<p>Halo <strong>{nama}</strong>, terima kasih telah mendaftar di <strong>{platform_name}</strong>! Gunakan kode OTP berikut untuk memverifikasi alamat email Anda:</p>
<div class="otp-box">{otp_code}</div>
<p>Kode ini akan kedaluwarsa dalam <strong>{expiry_minutes} menit</strong>.</p>
<h3>Cara menggunakan:</h3>
<ol>
<li>Salin kode 6 digit di atas</li>
<li>Kembali ke halaman pendaftaran</li>
<li>Masukkan kode tersebut pada form verifikasi</li>
</ol>
<blockquote class="alert-info">
<strong>Info:</strong> Jika Anda tidak merasa mendaftar di {platform_name}, abaikan email ini dengan aman.
</blockquote>
---'
WHERE key = 'auth_email_verification';
-- Add comment documenting the change
COMMENT ON COLUMN notification_templates.email_body_html IS
'For templates wrapped with master template: Store ONLY content HTML (no <html>, <head>, <body> tags).
Use {variable} placeholders for dynamic data. Content will be auto-styled by .tiptap-content CSS.';
-- Return success message
DO $$
BEGIN
RAISE NOTICE 'Auth email template updated to content-only format for master template wrapper';
END $$;

View File

@@ -37,14 +37,14 @@ export class EmailTemplateRenderer {
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
} }
.email-content h1 { .tiptap-content h1 {
font-size: 28px; font-size: 28px;
font-weight: 800; font-weight: 800;
margin: 0 0 20px 0; margin: 0 0 20px 0;
letter-spacing: -1px; letter-spacing: -1px;
line-height: 1.1; line-height: 1.1;
} }
.email-content h2 { .tiptap-content h2 {
font-size: 20px; font-size: 20px;
font-weight: 700; font-weight: 700;
margin: 25px 0 15px 0; margin: 25px 0 15px 0;
@@ -54,43 +54,43 @@ export class EmailTemplateRenderer {
padding-bottom: 5px; padding-bottom: 5px;
display: inline-block; display: inline-block;
} }
.email-content h3 { .tiptap-content h3 {
font-size: 18px; font-size: 18px;
font-weight: 700; font-weight: 700;
margin: 20px 0 10px 0; margin: 20px 0 10px 0;
color: #333; color: #333;
} }
.email-content p { .tiptap-content p {
font-size: 16px; font-size: 16px;
line-height: 1.6; line-height: 1.6;
margin: 0 0 20px 0; margin: 0 0 20px 0;
color: #333; color: #333;
} }
.email-content a { .tiptap-content a {
color: #000000; color: #000000;
text-decoration: underline; text-decoration: underline;
font-weight: 700; font-weight: 700;
text-underline-offset: 3px; text-underline-offset: 3px;
} }
.email-content ul, .email-content ol { .tiptap-content ul, .tiptap-content ol {
margin: 0 0 20px 0; margin: 0 0 20px 0;
padding-left: 20px; padding-left: 20px;
} }
.email-content li { .tiptap-content li {
margin-bottom: 8px; margin-bottom: 8px;
font-size: 16px; font-size: 16px;
padding-left: 5px; padding-left: 5px;
} }
.email-content table { .tiptap-content table {
width: 100%; width: 100%;
border: 2px solid #000; border: 2px solid #000;
margin-bottom: 25px; margin-bottom: 25px;
border-collapse: collapse; border-collapse: collapse;
} }
.email-content th { .tiptap-content th {
background-color: #000; background-color: #000;
color: #FFF; color: #FFF;
padding: 12px; padding: 12px;
@@ -100,13 +100,13 @@ export class EmailTemplateRenderer {
font-weight: 700; font-weight: 700;
border: 1px solid #000; border: 1px solid #000;
} }
.email-content td { .tiptap-content td {
padding: 12px; padding: 12px;
border: 1px solid #000; border: 1px solid #000;
font-size: 15px; font-size: 15px;
vertical-align: top; vertical-align: top;
} }
.email-content tr:nth-child(even) td { .tiptap-content tr:nth-child(even) td {
background-color: #F8F8F8; background-color: #F8F8F8;
} }
@@ -129,14 +129,14 @@ export class EmailTemplateRenderer {
box-shadow: 2px 2px 0px 0px #000000; box-shadow: 2px 2px 0px 0px #000000;
} }
.email-content pre { .tiptap-content pre {
background-color: #F4F4F5; background-color: #F4F4F5;
border: 2px solid #000; border: 2px solid #000;
padding: 15px; padding: 15px;
overflow-x: auto; overflow-x: auto;
margin-bottom: 20px; margin-bottom: 20px;
} }
.email-content code { .tiptap-content code {
font-family: 'Courier New', Courier, monospace; font-family: 'Courier New', Courier, monospace;
font-size: 14px; font-size: 14px;
color: #E11D48; color: #E11D48;
@@ -157,7 +157,7 @@ export class EmailTemplateRenderer {
color: #000; color: #000;
} }
.email-content blockquote { .tiptap-content blockquote {
margin: 0 0 20px 0; margin: 0 0 20px 0;
padding: 15px 20px; padding: 15px 20px;
border-left: 6px solid #000; border-left: 6px solid #000;
@@ -205,7 +205,8 @@ export class EmailTemplateRenderer {
<tr> <tr>
<td class="content-padding" style="padding: 40px 40px 60px 40px;"> <td class="content-padding" style="padding: 40px 40px 60px 40px;">
<div class="email-content"> <!-- DYNAMIC CONTENT WRAPPER (.tiptap-content) -->
<div class="tiptap-content">
{{content}} {{content}}
</div> </div>
</td> </td>