Spaces:
Running
Running
File size: 14,834 Bytes
72eef4f 85354fe 72eef4f 85354fe 72eef4f 85354fe 72eef4f 85354fe 72eef4f 85354fe 72eef4f 85354fe 72eef4f 85354fe 72eef4f 85354fe 72eef4f 85354fe 72eef4f |
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 |
# your_app/email_utils.py
from flask import current_app
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
from .general_utils import backfill_orders
def send_order_confirmation_email(order, user):
"""
Constructs and sends order confirmation emails to the customer and a notification
to the client/admin using the Brevo API.
Args:
order (dict): The complete order document, including 'populated_items'.
user (dict): The user document, containing 'email' and 'company_name'.
"""
# Setup Brevo API client from Flask app config
configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-key'] = current_app.config['BREVO_API_KEY']
api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration))
# --- Common variables for emails ---
sender_email = current_app.config['SENDER_EMAIL']
sender_name = "Matax Express" # You can customize this
client_admin_email = current_app.config['CLIENT_ADMIN_EMAIL']
customer_email = user['email']
contact_person = user['contactPerson']
order_id_str = str(order['serial_no'])
# --- Common portal footer ---
portal_footer = """
<p style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #cccccc; font-size: 14px;">
Remember, you can place new orders, view your order history, manage your cart, and even use our AI-powered quick order feature at our customer portal:
<br>
<a href="https://matax-express.vercel.app/" style="color: #007bff;">https://matax-express.vercel.app/</a>
</p>
"""
# --- Generate HTML table of ordered items ---
items_html = "<table border='1' cellpadding='5' cellspacing='0' style='border-collapse: collapse; width: 100%;'><tr><th style='text-align: left;'>Product</th><th style='text-align: center;'>Quantity</th></tr>"
for item in order['populated_items']:
if item['mode'] == 'weight':
item['mode']='lb'
items_html += f"<tr><td>{item['name']}</td><td style='text-align: center;'>{item['quantity']} {item['mode']}</td></tr>"
items_html += "</table>"
# --- 1. Prepare Email for the Customer ---
customer_subject = f"Your Order Confirmation - #{order_id_str}"
customer_html_content = f"""
<html><body>
<h1>Thank You for Your Order, {contact_person}!</h1>
<p>We have successfully received your order #{order_id_str}. Here are the details:</p>
<h2>Order Summary</h2>
{items_html}
<h2>Delivery Details</h2>
<p><strong>Delivery Date:</strong> {order['delivery_date']}</p>
<p><strong>Delivery Address:</strong> {order['delivery_address']}</p>
<p><strong>Contact Number:</strong> {order['mobile_number']}</p>
<p><strong>Additional Info:</strong> {order.get('additional_info') or 'N/A'}</p>
<p>Thank you for your business!</p>
{portal_footer}
</body></html>
"""
send_smtp_email_customer = sib_api_v3_sdk.SendSmtpEmail(
to=[{"email": customer_email, "name": contact_person}],
sender={"email": sender_email, "name": sender_name},
subject=customer_subject,
html_content=customer_html_content
)
# --- 2. Prepare Email for the Client/Admin ---
client_subject = f"New Order Received - #{order_id_str} from {contact_person}"
client_html_content = f"""
<html><body>
<h1>New Order Received!</h1>
<p>A new order #{order_id_str} has been placed by <strong>{contact_person}</strong>.</p>
<h2>Order Details</h2>
{items_html}
<h2>Customer & Delivery Information</h2>
<p><strong>Company:</strong> {contact_person}</p>
<p><strong>Email:</strong> {customer_email}</p>
<p><strong>Delivery Date:</strong> {order['delivery_date']}</p>
<p><strong>Delivery Address:</strong> {order['delivery_address']}</p>
<p><strong>Contact Number:</strong> {order['mobile_number']}</p>
<p><strong>Additional Info:</strong> {order.get('additional_info') or 'N/A'}</p>
<p><strong>Total Amount:</strong> ${order.get('total_amount', 0):.2f}</p>
<p>This order has also been sent for PO creation in Xero.</p>
</body></html>
"""
send_smtp_email_client = sib_api_v3_sdk.SendSmtpEmail(
to=[{"email": client_admin_email}],
sender={"email": sender_email, "name": sender_name},
subject=client_subject,
html_content=client_html_content
)
# --- 3. Send both emails ---
api_instance.send_transac_email(send_smtp_email_customer)
current_app.logger.info(f"Order confirmation sent to {customer_email} for order {order_id_str}")
api_instance.send_transac_email(send_smtp_email_client)
current_app.logger.info(f"New order notification sent to {client_admin_email} for order {order_id_str}")
# +++ START: NEW EMAIL FUNCTIONS +++
def send_registration_email(user_data):
"""Sends a welcome/application pending email upon registration."""
configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-key'] = current_app.config['BREVO_API_KEY']
api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration))
sender_email = current_app.config['SENDER_EMAIL']
sender_name = "Matax Express"
recipient_email = user_data['email']
recipient_name = user_data.get('contactPerson', user_data.get('businessName', 'New User'))
# --- Common portal footer ---
portal_footer = f"""
<p style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #cccccc; font-size: 14px;">
Once your account is approved, you can place orders, view your order history, manage your cart, and use our AI-powered quick order feature at our customer portal:
<br>
<a href="https://matax-express.vercel.app/" style="color: #007bff;">https://matax-express.vercel.app/</a>
</p>
"""
subject = "your application is under process"
html_content = f"""
<html><body>
<h1>Welcome to Matax Express, {recipient_name}!</h1>
<p>Thank you for registering. Your application is currently under review by our team.</p>
<p>We will notify you via email as soon as your account is approved.</p>
<p>Thank you for your patience.</p>
<p>Best regards,<br>The Matax Express Team</p>
{portal_footer}
</body></html>
"""
send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(
to=[{ "email": recipient_email, "name": recipient_name }],
sender={ "email": sender_email, "name": sender_name },
subject=subject,
html_content=html_content
)
try:
api_instance.send_transac_email(send_smtp_email)
current_app.logger.info(f"Registration email sent to {recipient_email}")
except ApiException as e:
current_app.logger.error(f"Failed to send registration email to {recipient_email}: {e}")
def send_registration_admin_notification(registration_data):
"""Sends a notification to the admin with the new client's details."""
configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-key'] = current_app.config['BREVO_API_KEY']
api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration))
sender_email = current_app.config['SENDER_EMAIL']
sender_name = "Matax Express System"
admin_email = current_app.config['CLIENT_ADMIN_EMAIL']
# Format the details as requested
history_details = (
f"--- Client Application Details ---\n"
f"Business Name: {registration_data.get('businessName')}\n"
f"Contact Person: {registration_data.get('contactPerson')}\n"
f"Email: {registration_data.get('email')}\n"
f"Phone: {registration_data.get('phoneNumber')}\n"
f"Company Website: {registration_data.get('companyWebsite')}\n"
f"Business Address: {registration_data.get('businessAddress')}\n"
f"Business Type: {registration_data.get('businessType')}\n"
f"Years Operating: {registration_data.get('yearsOperating')}\n"
f"Number of Locations: {registration_data.get('numLocations')}\n"
f"Estimated Weekly Volume: {registration_data.get('estimatedVolume')}\n\n"
f"--- Logistics Information ---\n"
f"Preferred Delivery Times: {registration_data.get('preferredDeliveryTimes')}\n"
f"Has Loading Dock: {registration_data.get('hasLoadingDock')}\n"
f"Special Delivery Instructions: {registration_data.get('specialDeliveryInstructions')}\n"
f"Minimum Quantity Requirements: {registration_data.get('minQuantityRequirements')}\n\n"
f"--- Service & Billing ---\n"
f"Reason for Switching: {registration_data.get('reasonForSwitch')}\n"
f"Preferred Payment Method: {registration_data.get('paymentMethod')}\n\n"
f"--- Additional Notes ---\n"
f"{registration_data.get('additionalNotes')}"
)
subject = f"New Client Application: {registration_data.get('businessName')}"
# Use <pre> tag to preserve formatting in HTML email
html_content = f"""
<html><body>
<h1>New Client Application Received</h1>
<p>A new client has submitted an application for an account. Please review the details below and approve them in the admin panel if applicable.</p>
<hr>
<pre style="font-family: monospace; font-size: 14px;">{history_details}</pre>
</body></html>
"""
send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(
to=[{ "email": admin_email }],
sender={ "email": sender_email, "name": sender_name },
subject=subject,
html_content=html_content
)
try:
api_instance.send_transac_email(send_smtp_email)
current_app.logger.info(f"Admin notification for new registration '{registration_data.get('email')}' sent to {admin_email}")
except ApiException as e:
current_app.logger.error(f"Failed to send admin notification email for registration '{registration_data.get('email')}': {e}")
def send_login_notification_email(user):
"""Sends a notification email upon successful login."""
configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-key'] = current_app.config['BREVO_API_KEY']
api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration))
sender_email = current_app.config['SENDER_EMAIL']
sender_name = "Matax Express"
recipient_email = user['email']
recipient_name = user.get('contactPerson', user.get('company_name', 'Valued Customer'))
# --- Common portal footer ---
portal_footer = """
<p style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #cccccc; font-size: 14px;">
You can place new orders, view your order history, manage your cart, and even use our AI-powered quick order feature at our customer portal:
<br>
<a href="https://matax-express.vercel.app/" style="color: #007bff;">https://matax-express.vercel.app/</a>
</p>
"""
subject = "New login.."
html_content = f"""
<html><body>
<h1>Security Alert: New Login</h1>
<p>Hello {recipient_name},</p>
<p>We detected a new login to your Matax Express account just now.</p>
<p>If this was you, you can safely disregard this email. If you do not recognize this activity, please change your password immediately and contact our support team.</p>
<p>Thank you for helping us keep your account secure.</p>
<p>Best regards,<br>The Matax Express Team</p>
{portal_footer}
</body></html>
"""
send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(
to=[{ "email": recipient_email, "name": recipient_name }],
sender={ "email": sender_email, "name": sender_name },
subject=subject,
html_content=html_content
)
try:
api_instance.send_transac_email(send_smtp_email)
current_app.logger.info(f"Login notification sent to {recipient_email}")
except ApiException as e:
current_app.logger.error(f"Failed to send login notification to {recipient_email}: {e}")
def send_cart_reminder_email(user, populated_items):
"""Sends a reminder for items left in the cart."""
configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-key'] = current_app.config['BREVO_API_KEY']
api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration))
sender_email = current_app.config['SENDER_EMAIL']
sender_name = "Matax Express"
recipient_email = user['email']
recipient_name = user.get('contactPerson', user.get('company_name', 'Valued Customer'))
# --- Common portal footer ---
portal_footer = """
<p style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #cccccc; font-size: 14px;">
To complete your order, or to place new ones, please visit our customer portal:
<br>
<a href="https://matax-express.vercel.app/" style="color: #007bff;">https://matax-express.vercel.app/</a>
</p>
"""
subject = "Your items are waiting for you!"
items_html = "<table border='1' cellpadding='5' cellspacing='0' style='border-collapse: collapse; width: 100%;'><tr><th style='text-align: left;'>Product</th><th style='text-align: center;'>Quantity</th></tr>"
for item in populated_items:
items_html += f"<tr><td>{item['product']['name']}</td><td style='text-align: center;'>{item['quantity']}</td></tr>"
items_html += "</table>"
html_content = f"""
<html><body>
<h1>Don't Forget Your Items, {recipient_name}!</h1>
<p>Your baby fruits are waiting to arrive! You have some delicious items waiting in your cart.</p>
<br>
{items_html}
<br>
<p>Ready to complete your order? Please log in to your account to view your cart.</p>
<p>These items are popular and might not be available for long!</p>
<p>Best regards,<br>The Matax Express Team</p>
{portal_footer}
</body></html>
"""
send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(
to=[{ "email": recipient_email, "name": recipient_name }],
sender={ "email": sender_email, "name": sender_name },
subject=subject,
html_content=html_content
)
try:
api_instance.send_transac_email(send_smtp_email)
current_app.logger.info(f"Cart reminder sent to {recipient_email}")
except ApiException as e:
current_app.logger.error(f"Failed to send cart reminder to {recipient_email}: {e}")
# +++ END: NEW EMAIL FUNCTIONS +++ |