import nodemailer from 'nodemailer' import { getSystemSettings } from '@/lib/settings' interface EmailOptions { to: string subject: string html: string text?: string } class EmailServiceClass { private transporter: nodemailer.Transporter | null = null private isConfigured: boolean = false constructor() { this.initializeTransporter() } private initializeTransporter() { try { // Check if SMTP credentials are configured const smtpUser = process.env.SMTP_USER const smtpPass = process.env.SMTP_PASSWORD // Changed from SMTP_PASS if (!smtpUser || !smtpPass) { console.warn('SMTP credentials not configured. Email notifications will be disabled.') return } this.transporter = nodemailer.createTransport({ host: process.env.SMTP_HOST || 'smtp.gmail.com', port: parseInt(process.env.SMTP_PORT || '587'), secure: false, auth: { user: smtpUser, pass: smtpPass, }, }) this.isConfigured = true console.log('Email service initialized successfully') } catch (error) { console.error('Failed to initialize email service:', error) this.isConfigured = false } } async sendEmail({ to, subject, html, text }: EmailOptions) { if (!this.isConfigured || !this.transporter) { console.log(`Email would be sent to ${to}: ${subject}`) console.log('Email service not configured - skipping email send') return { messageId: 'not-configured', skipped: true } } try { const settings = await getSystemSettings() const mailOptions = { from: process.env.SMTP_FROM || `"${settings.siteName}" <${process.env.SMTP_USER}>`, // Use SMTP_FROM if available to, subject, html, text: text || this.htmlToText(html) } const result = await this.transporter.sendMail(mailOptions) console.log('Email sent successfully:', result.messageId) return result } catch (error) { console.error('Email sending failed:', error) // Don't throw error, just log it so the main process continues const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred' return { messageId: 'failed', error: errorMessage } } } private htmlToText(html: string): string { return html.replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim() } // Order confirmation email async sendOrderConfirmation(userEmail: string, userName: string, order: any) { const html = `
Hi ${userName},
Thank you for your order! We're excited to process it for you.
Order ID: #${order.id.slice(-8)}
Total: ₹${order.total.toFixed(2)}
Status: ${order.status}
Date: ${new Date(order.createdAt).toLocaleDateString()}
${item.product.name}
Quantity: ${item.quantity} | Price: ₹${item.price.toFixed(2)}
We'll send you another email when your order ships.
Thanks for shopping with us!
If you have any questions, reply to this email or contact our support team.
Hi ${userName},
Great news! You've earned a new commission.
Amount: ₹${commission.amount.toFixed(2)}
Level: ${commission.level}
Type: ${commission.type}
From: ${commission.fromUser.name}
Date: ${new Date(commission.createdAt).toLocaleDateString()}
This commission has been added to your wallet.
Keep up the great work building your network!
Hi ${userName},
Amazing news! You've achieved a new rank in our program.
${newRank.description}
This achievement reflects your dedication and success. Keep growing your network to unlock even more rewards!
Name: ${data.firstName} ${data.lastName}
Email: ${data.email}
Phone: ${data.phone}
Partnership Tier: ${data.partnershipTier}
Expected Customers: ${data.expectedCustomers}
Business Name: ${data.businessName || 'N/A'}
Business Type: ${data.businessType}
Experience: ${data.experience}
${data.address}
${data.city}, ${data.state} ${data.zipCode}
Motivation: ${data.motivation}
Marketing Plan: ${data.marketingPlan}
✅ User has been automatically created and approved as a MEMBER.
User ID: ${newUser.id}
Referral Code: ${newUser.referralCode}
Your partnership application has been approved
We're excited to welcome you as a ${data.partnershipTier} partner in the Padmaaja Rasooi family.
Website: ${process.env.NEXTAUTH_URL || 'http://localhost:3000'}
Email: ${data.email}
Password: ${randomPassword}
Your Referral Code: ${newUser.referralCode}
Tier: ${data.partnershipTier}
Required Members: Minimum 3 members must be added
Commission Structure: Earn commissions on all purchases made by your referrals
Thank you for joining Padmaaja Rasooi. We look forward to a successful partnership!
Best regards,
The Padmaaja Rasooi Team
Partner: ${partner.name} (${partner.email})
Partner Tier: ${partner.partnerTier || 'N/A'}
Current Members: ${partner.referrals.length + 1}
Min Required: ${partner.minReferrals}
Status: ${partner.referrals.length + 1 >= partner.minReferrals ? '✅ Meeting minimum requirement' : '⚠️ Building minimum members'}
Name: ${newMember.name}
Email: ${newMember.email}
Phone: ${newMember.phone}
User ID: ${newMember.id}
Referral Code: ${newMember.referralCode}
You've been added by our partner: ${partner.name}
Welcome to the Padmaaja Rasooi family! You've been added as a member by our partner ${partner.name}.
Website: ${process.env.NEXTAUTH_URL || 'http://localhost:3000'}
Email: ${memberData.email}
Password: ${randomPassword}
Important: Please change your password after first login for security.
If you have any questions, contact us at ${process.env.SUPPORT_EMAIL || 'info@padmajarice.com'}
Best regards,
The Padmaaja Rasooi Team
Dear ${wholesalerData.name},
Congratulations! Your wholesaler registration has been approved. You are now part of our exclusive wholesaler network.
You now have access to wholesale benefits
Email: ${wholesalerData.email}
Temporary Password: ${wholesalerData.password}
Important: Please change your password after first login.
Our team will contact you within 24 hours to assist with your first order and answer any questions.
For immediate assistance, contact us at ${process.env.SUPPORT_EMAIL || 'info@padmajarice.com'} or call our wholesaler hotline.
Best regards,
The Padmaaja Rasooi Wholesale Team
A new wholesaler has registered on the platform.
Name: ${wholesalerData.wholesalerName}
Email: ${wholesalerData.wholesalerEmail}
Business Name: ${wholesalerData.businessName}
Business Type: ${wholesalerData.businessType}
Phone: ${wholesalerData.phone}
Expected Volume: ${wholesalerData.expectedVolume}
Registration Date: ${wholesalerData.registrationDate}
The wholesaler has been automatically approved and given access to 25% wholesale discounts on bulk orders.
This is an automated notification from Padmaaja Rasooi
Part-Time Job Application Received
Thank you for applying for a part-time position with Padmaaja! We're excited about your interest in joining our team.
Preferred Role: ${partTimeData.preferredRole}
Application Status: Under Review
Email: ${partTimeData.email}
Password: ${partTimeData.password}
Please keep these credentials safe. You can use them to log in to your dashboard.
If you have any questions, feel free to contact our support team.
Best regards,
Padmaaja Team
© 2024 Padmaaja. All rights reserved.
Application received on ${partTimeData.registrationDate}
Name: ${partTimeData.applicantName}
Email: ${partTimeData.applicantEmail}
Phone: ${partTimeData.phone}
Preferred Role: ${partTimeData.preferredRole}
Available Hours: ${partTimeData.availableHours} per day
Available Days: ${partTimeData.availableDays}
${partTimeData.motivation}
Please review this application and contact the applicant for the next steps.
© 2024 Padmaaja Admin Panel
Thank you for your business inquiry
Dear ${data.customerName},
Thank you for your inquiry regarding bulk procurement ${data.productName ? `of ${data.productName}` : 'from Padmaaja Rasooi'}. We have received your detailed requirements and our team is reviewing them.
Priority Response: As a bulk inquiry, your request has been marked as high priority. Our business development team will reach out to you shortly.
Contact our B2B Sales Team:
This is an automated confirmation. Please do not reply to this email.
© 2024 Padmaaja Rasooi Pvt. Ltd. | Premium Rice & Grains
Immediate attention required
⏰ Response Required Within 24 Hours
Inquiry ID: ${data.inquiryId}
Submitted: ${new Date().toLocaleString('en-IN')} | Priority: HIGH
© 2024 Padmaaja Admin Panel