Files
dwindown 053465afa3 Fix email system and implement OTP confirmation flow
Email System Fixes:
- Fix email sending after payment: handle-order-paid now calls send-notification
  instead of send-email-v2 directly, properly processing template variables
- Fix order_created email timing: sent immediately after order creation,
  before payment QR code generation
- Update email templates to use short order ID (8 chars) instead of full UUID
- Add working "Akses Sekarang" buttons to payment_success and access_granted emails
- Add platform_url column to platform_settings for email links

OTP Verification Flow:
- Create dedicated /confirm-otp page for users who close registration modal
- Add link in checkout modal and email to dedicated OTP page
- Update OTP email template with better copywriting and dedicated page link
- Fix send-auth-otp to fetch platform settings for dynamic brand_name and platform_url
- Auto-login users after OTP verification in checkout flow

Admin Features:
- Add delete user functionality with cascade deletion of all related data
- Update IntegrasiTab to read/write email settings from platform_settings only
- Add test email template for email configuration testing

Cleanup:
- Remove obsolete send-consultation-reminder and send-test-email functions
- Update send-email-v2 to read email config from platform_settings
- Remove footer links (Ubah Preferensi/Unsubscribe) from email templates

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-03 18:02:25 +07:00

121 lines
3.9 KiB
TypeScript

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 SendOTPRequest {
user_id: string;
email: string;
}
serve(async (req: Request) => {
if (req.method === "OPTIONS") {
return new Response(null, { headers: corsHeaders });
}
try {
const { user_id, email }: SendOTPRequest = await req.json();
// Validate required fields
if (!user_id || !email) {
return new Response(
JSON.stringify({ success: false, message: "Missing required fields: user_id, email" }),
{ 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);
// Fetch platform settings for brand name and URL
const { data: platformSettings } = await supabase
.from('platform_settings')
.select('brand_name, platform_url')
.single();
const platformName = platformSettings?.brand_name || 'ACCESS HUB';
const platformUrl = platformSettings?.platform_url || 'https://access-hub.com';
console.log(`Generating OTP for user ${user_id}`);
// Generate 6-digit OTP code
const otpCode = Math.floor(100000 + Math.random() * 900000).toString();
// Calculate expiration time (15 minutes from now)
const expiresAt = new Date(Date.now() + 15 * 60 * 1000).toISOString();
// Store OTP in database
const { error: insertError } = await supabase
.from('auth_otps')
.insert({
user_id: user_id,
email: email,
otp_code: otpCode,
expires_at: expiresAt,
});
if (insertError) {
console.error('Error storing OTP:', insertError);
throw new Error(`Failed to store OTP: ${insertError.message}`);
}
console.log(`OTP generated and stored: ${otpCode}, expires at: ${expiresAt}`);
// Send OTP email using send-notification
const notificationUrl = `${supabaseUrl}/functions/v1/send-notification`;
const notificationResponse = await fetch(notificationUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${supabaseServiceKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
template_key: 'auth_email_verification',
recipient_email: email,
recipient_name: email.split('@')[0],
variables: {
nama: email.split('@')[0],
otp_code: otpCode,
email: email,
user_id: user_id,
expiry_minutes: '15',
platform_name: platformName,
platform_url: platformUrl
}
}),
});
if (!notificationResponse.ok) {
const errorText = await notificationResponse.text();
console.error('Error sending notification email:', notificationResponse.status, errorText);
throw new Error(`Failed to send OTP email: ${notificationResponse.status} ${errorText}`);
}
const notificationResult = await notificationResponse.json();
console.log('Notification sent successfully:', notificationResult);
return new Response(
JSON.stringify({
success: true,
message: "OTP sent successfully"
}),
{ status: 200, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
} catch (error: any) {
console.error("Error sending OTP:", error);
return new Response(
JSON.stringify({
success: false,
message: error.message || "Failed to send OTP"
}),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
});