Spaces:
Running
Running
# 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 | |
import requests | |
# Define the function to get email details from Brevo | |
def get_email_details(message_id): | |
""" | |
Fetches the full details of a message using the Brevo API. | |
""" | |
# This is the specific Brevo API endpoint for fetching a message | |
api_url = f"https://api.brevo.com/v3/conversations/messages/{message_id}" | |
headers = { | |
"accept": "application/json", | |
"api-key": current_app.config['BREVO_API_KEY'] | |
} | |
print(f"📞 Calling Brevo API for messageId: {message_id}") | |
response = requests.get(api_url, headers=headers) | |
# Check if the API call was successful | |
if response.status_code == 200: | |
message_details = response.json() | |
# The email body is typically in the 'text' field of the response | |
return message_details.get('text', 'Email body not found in API response.') | |
else: | |
print(f"Error from Brevo API: {response.status_code} - {response.text}") | |
return None | |
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 +++ |