sendQuotationRequestEmailHttp
| Admin Notification | User Confirmation |
|---|---|
![]() | ![]() |
- 🇬🇧 English
- 🇮🇹 Italian
Function Name: sendQuotationRequestEmailHttp
Author: Domenico Cerone Creation Date: 25/09/2025
Last Reviewer: Domenico Cerone
Trigger: HTTPS (onRequest)
Purpose: Manages the automatic sending of quotation request emails via ZeptoMail when a catalog order processing is completed with Excel report generation. Sends dual emails to administrators (with Excel attachment) and confirmation to the requesting user.
Detailed Functionality​
This Firebase Function handles the complete email workflow for quotation requests through a dual notification system:
1. AUTOMATIC TRIGGER​
- Called automatically by downloadVariantJsonsHttps.js ONLY when Excel has been generated
- Required condition: must exist
excelResultwith valid downloadUrl, token and fileName - Activation ONLY in cases of successful Excel generation (regardless of previous API errors)
2. ORDER DATA RETRIEVAL​
- Accesses 'CatalogOrders' collection using provided orderId
- Verifies document existence and 'excelReportUrl' property
- Extracts necessary data: timestamp, profile, excelReportUrl, excelReportFileName
- Retrieves ordering user's full name from 'Profiles' collection using 'profile' field as document ID
3. ORDERING USER PROFILE RETRIEVAL​
- Uses 'profile' field from order (e.g., "92mt@live.it") as document ID
- Accesses 'Profiles' collection to retrieve firstName and lastName of ordering user
- Combines firstName and lastName to create full name (e.g., "Michele Telesca")
- Fallback handling: if profile not found or data missing, uses email as fallback
- Detailed logging to track profile retrieval process
- Full name used for both admin email and user confirmation email
4. NOTIFICATION PREFERENCE CHECK​
- Checks if the user has enabled the sendQuotationRequestEmailHttp notification in their notification preferences
- Verifies
notification_types.sendQuotationRequestEmailHttpfield in the profile - If notification is disabled (false): returns success without sending email
- If notification is enabled (true): proceeds with administrator recipients retrieval
- Provides clear logging about notification preference status
5. ADMINISTRATOR RECIPIENTS RETRIEVAL​
- Executes query on 'Profiles' collection with filter: role == 'Admin'
- For each administrator found, extracts only '_email'
- Creates recipient array using email as both address and name
- If no admin found: terminates with 'NO_ADMIN_FOUND' error
- If query error: terminates with 'NO_ADMIN_FOUND' error
- Detailed logging with admin count and their emails
6. DATE FORMATTING​
- Converts Firestore timestamp to readable English format
- Format: "June 20, 2025 at 5:56 PM" (month day year hours:minutes)
- Handles missing timestamp cases with fallback "Date not available"
7. ATTACHMENT DOWNLOAD AND PREPARATION​
- Downloads Excel file from Firebase Storage URL (excelReportUrl)
- Converts file to base64 format for email attachment
- 30-second timeout for download with robust error handling
- Verifies file size and validity of downloaded file
8. ADMIN EMAIL ZEPTOMAIL CONFIGURATION​
- Template key:
13ef.8598f19fbcc5adb.k1.e8a28620-50ea-11f0-9c4e-dad70ff08860.197a19bc782 - Sender: no-reply@arshades.com (noreply)
- Recipients: ALL users with role='Admin' from Profiles collection
- Merge data:
- date: formatted timestamp date of the order
profile: full name of ordering user (e.g., "Michele Telesca") retrieved from Profiles collection
9. USER EMAIL ZEPTOMAIL CONFIGURATION​
- Template key:
13ef.8598f19fbcc5adb.k1.9337a850-5e23-11f0-9e15-dad70ff08860.197f8418755 - Sender: no-reply@arshades.com (noreply)
- Recipient: user who made the request ('profile' field from CatalogOrders)
- Merge data:
profile: user's full name (e.g., "Michele Telesca") or email if name not available
- Message: "Hello {{profile}}, Request for quotation sent successfully!"
- Sent immediately after admin email to confirm request to user
10. ATTACHMENT HANDLING​
- File name: excelReportFileName (default: "report.xlsx")
- MIME type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
- Content: Excel file converted to base64
- Maximum manageable size: limited by available memory
- Attachment ONLY to admin email, NOT to user confirmation email
11. MULTIPLE EMAIL SENDING AND CONFIRMATION​
- First email: simultaneous sending to all administrators in single API call
- Second email: immediate sending to user for request confirmation
- Logging with recipient count and email list for traceability
- Asynchronous handling with Promise for optimal performance
- Returns results of both sends in response
12. ERROR HANDLING AND LOGGING​
- Detailed logging for each phase of the process
- Separate error handling: order not found, Excel missing, admins not found, download failed, sending failed
- Structured return with success/failure, admin count and email list
- If no admin found: returns error instead of sending email
- Does not interrupt main process in case of email error
- Separate tracking of sending results for admin email and user email
Technical Features​
- PROTOCOL: HTTPS with TLS for security
- TIMEOUT: 30 seconds for attachment downloads
- FORMAT: Custom HTML email templates (2 different templates)
- ATTACHMENTS: Complete support for Excel files (.xlsx)
- ENCODING: Base64 for binary attachments
- LOCALIZATION: Date in English format
- LOGGING: Complete for debugging and monitoring
- RESILIENCE: Non-blocking error handling
Integration​
- Called by: downloadVariantJsonsHttps.js
- Input: orderId (string)
- Output: {success: boolean, message: string, emailResult?: object, userEmailResult?: object, error?: string}
- Dependencies: Firebase Firestore, ZeptoMail, Axios
Input (Payload):​
{
"orderId": "xq02X2a6CEFVoQtZd5Pa"
}
Parameters:
orderId(string, required): ID of the catalog order document in the 'CatalogOrders' collection
Output (Success):​
{
"success": true,
"message": "Quotation request email sent successfully to 3 administrators and to user Michele Telesca for order xq02X2a6CEFVoQtZd5Pa",
"emailResult": {
"request_id": "1234567890abcdef",
"message": "Email sent successfully"
},
"userEmailResult": {
"request_id": "abcdef1234567890",
"message": "User confirmation email sent successfully"
},
"attachmentIncluded": true,
"adminCount": 3,
"adminEmails": [
"admin1@arshades.com",
"admin2@arshades.com",
"admin3@arshades.com"
]
}
Response Properties:
success(boolean): Indicates if the operation was completed successfullymessage(string): Descriptive message of the email sending resultsemailResult(object): Complete response from admin email sendinguserEmailResult(object): Complete response from user confirmation email sendingattachmentIncluded(boolean): Indicates if Excel attachment was includedadminCount(number): Number of administrators who received the emailadminEmails(array): List of administrator emails that received the notification
This output is returned in the HTTP response (Postman, browser, curl).
Testing​
URL (if HTTPS): http://127.0.0.1:5001/arshadesstaging/europe-central2/sendQuotationRequestEmailHttp
Test with Emulator:
- Start the Firebase emulator:
firebase emulators:start --only functions - Ensure you're using Node.js version 20:
nvm use 20 - Test with curl:
curl -X POST "http://127.0.0.1:5001/arshadesstaging/europe-central2/sendQuotationRequestEmailHttp" \
-H "Content-Type: application/json" \
-d '{"orderId": "xq02X2a6CEFVoQtZd5Pa"}'
Postman Testing:
- Method: POST
- URL: http://127.0.0.1:5001/arshadesstaging/europe-central2/sendQuotationRequestEmailHttp
- Headers:
- Key:
Content-Type - Value:
application/json
- Key:
- Body: raw JSON (see examples above)
Deploy Command:​
firebase deploy --only functions:sendQuotationRequestEmailHttp
Production URL:​
sendQuotationRequestEmailHttp: https://europe-central2-arshades-7e18a.cloudfunctions.net/sendQuotationRequestEmailHttp
Function Name: sendQuotationRequestEmailHttp
Autore: Domenico Cerone Data di creazione: 25/09/2025
Last Reviewer: Domenico Cerone
Trigger: HTTPS (onRequest)
Purpose: Gestisce l'invio automatico di email di richiesta quotazione tramite ZeptoMail quando viene completata l'elaborazione di un ordine catalogo con generazione del report Excel. Invia email dual agli amministratori (con allegato Excel) e conferma all'utente richiedente.
Funzionamento Dettagliato​
Questa Firebase Function gestisce il flusso email completo per le richieste di quotazione attraverso un sistema di notifica dual:
1. TRIGGER AUTOMATICO​
- Viene chiamato automaticamente da downloadVariantJsonsHttps.js SOLO quando l'Excel è stato generato
- Condizione necessaria: deve esistere
excelResultcon downloadUrl, token e fileName validi - Attivazione SOLO nei casi di generazione Excel riuscita (indipendentemente da errori API precedenti)
2. RECUPERO DATI ORDINE​
- Accede alla collezione 'CatalogOrders' usando l'orderId fornito
- Verifica l'esistenza del documento e della proprietà 'excelReportUrl'
- Estrae i dati necessari: timestamp, profile, excelReportUrl, excelReportFileName
- Recupera il nome completo dell'utente dalla collezione 'Profiles' usando il campo 'profile' come ID documento
3. RECUPERO PROFILO UTENTE ORDINANTE​
- Utilizza il campo 'profile' dall'ordine (es. "92mt@live.it") come ID documento
- Accede alla collezione 'Profiles' per recuperare firstName e lastName dell'utente che ha fatto l'ordine
- Combina firstName e lastName per creare il nome completo (es. "Michele Telesca")
- Gestione fallback: se profilo non trovato o dati mancanti, usa l'email come fallback
- Logging dettagliato per tracciare il processo di recupero profilo
- Il nome completo viene utilizzato sia per l'email agli admin che per l'email di conferma all'utente
4. CONTROLLO PREFERENZE NOTIFICHE​
- Controlla se l'utente ha abilitato sendQuotationRequestEmailHttp nelle sue preferenze di notifica
- Verifica il campo
notification_types.sendQuotationRequestEmailHttpnel profilo - Se la notifica è disabilitata (false): restituisce successo senza inviare email
- Se la notifica è abilitata (true): procede con il recupero dei destinatari amministratori
- Fornisce logging chiaro sullo stato delle preferenze di notifica
5. RECUPERO AMMINISTRATORI DESTINATARI​
- Esegue query sulla collezione 'Profiles' con filtro: role == 'Admin'
- Per ogni amministratore trovato, estrae solo '_email'
- Crea array di destinatari usando l'email sia come indirizzo che come nome
- Se nessun admin trovato: termina con errore 'NO_ADMIN_FOUND'
- Se errore nella query: termina con errore 'NO_ADMIN_FOUND'
- Logging dettagliato con conteggio admin trovati e loro email
6. FORMATTAZIONE DATA​
- Converte il timestamp Firestore in formato leggibile inglese
- Formato: "June 20, 2025 at 5:56 PM" (mese giorno anno ore:minuti)
- Gestisce casi di timestamp mancante con fallback "Date not available"
7. DOWNLOAD E PREPARAZIONE ALLEGATO​
- Scarica il file Excel dall'URL di Firebase Storage (excelReportUrl)
- Converte il file in formato base64 per l'allegato email
- Timeout di 30 secondi per il download con gestione errori robusta
- Verifica dimensione e validità del file scaricato
8. CONFIGURAZIONE EMAIL ZEPTOMAIL PER ADMIN​
- Template key:
13ef.8598f19fbcc5adb.k1.e8a28620-50ea-11f0-9c4e-dad70ff08860.197a19bc782 - Mittente: no-reply@arshades.com (noreply)
- Destinatari: TUTTI gli utenti con role='Admin' dalla collezione Profiles
- Dati template:
- date: data formattata del timestamp dell'ordine
profile: nome completo dell'utente ordinante (es. "Michele Telesca") recuperato dalla collezione Profiles
9. CONFIGURAZIONE EMAIL ZEPTOMAIL PER UTENTE​
- Template key:
13ef.8598f19fbcc5adb.k1.9337a850-5e23-11f0-9e15-dad70ff08860.197f8418755 - Mittente: no-reply@arshades.com (noreply)
- Destinatario: l'utente che ha fatto la richiesta (campo 'profile' da CatalogOrders)
- Dati template:
profile: nome completo dell'utente (es. "Michele Telesca") o email se nome non disponibile
- Messaggio: "Hello {{profile}}, Request for quotation sent successfully!"
- Inviata subito dopo l'email agli admin per confermare la richiesta all'utente
10. GESTIONE ALLEGATO​
- Nome file: excelReportFileName (default: "report.xlsx")
- MIME type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
- Contenuto: file Excel convertito in base64
- Dimensione massima gestibile: limitata dalla memoria disponibile
- Allegato SOLO all'email per gli admin, NON all'email di conferma per l'utente
11. INVIO EMAIL MULTIPLO E CONFERMA​
- Prima email: invio simultaneo a tutti gli amministratori in una singola chiamata API
- Seconda email: invio immediato all'utente per conferma richiesta
- Logging con conteggio destinatari e lista email per tracciabilitÃ
- Gestione asincrona con Promise per performance ottimali
- Ritorno risultati di entrambi gli invii nella risposta
12. GESTIONE ERRORI E LOGGING​
- Logging dettagliato per ogni fase del processo
- Gestione separata degli errori: ordine non trovato, Excel mancante, admin non trovati, download fallito, invio fallito
- Ritorno strutturato con success/failure, conteggio admin e lista email
- Se nessun admin trovato: ritorna errore invece di inviare email
- Non interrompe il processo principale in caso di errore email
- Tracciamento separato dei risultati di invio per email admin e email utente
Caratteristiche Tecniche​
- PROTOCOLLO: HTTPS con TLS per sicurezza
- TIMEOUT: 30 secondi per download allegati
- FORMATO: Template email HTML personalizzato (2 template diversi)
- ALLEGATI: Supporto completo per file Excel (.xlsx)
- ENCODING: Base64 per allegati binari
- LOCALIZZAZIONE: Data in formato inglese
- LOGGING: Completo per debugging e monitoraggio
- RESILIENZA: Gestione errori non bloccante
Integrazione​
- Chiamato da: downloadVariantJsonsHttps.js
- Input: orderId (string)
- Output: {success: boolean, message: string, emailResult?: object, userEmailResult?: object, error?: string}
- Dipendenze: Firebase Firestore, ZeptoMail, Axios
Input (Payload):​
{
"orderId": "xq02X2a6CEFVoQtZd5Pa"
}
Parametri:
orderId(string, richiesto): ID del documento dell'ordine catalogo nella collezione 'CatalogOrders'
Output (Success):​
{
"success": true,
"message": "Email di richiesta quotazione inviata con successo a 3 amministratori e all'utente Michele Telesca per ordine xq02X2a6CEFVoQtZd5Pa",
"emailResult": {
"request_id": "1234567890abcdef",
"message": "Email sent successfully"
},
"userEmailResult": {
"request_id": "abcdef1234567890",
"message": "User confirmation email sent successfully"
},
"attachmentIncluded": true,
"adminCount": 3,
"adminEmails": [
"admin1@arshades.com",
"admin2@arshades.com",
"admin3@arshades.com"
]
}
Proprietà della Risposta:
success(boolean): Indica se l'operazione è stata completata con successomessage(string): Messaggio descrittivo dei risultati dell'invio emailemailResult(object): Risposta completa dall'invio email agli amministratoriuserEmailResult(object): Risposta completa dall'invio email di conferma all'utenteattachmentIncluded(boolean): Indica se l'allegato Excel è stato inclusoadminCount(number): Numero di amministratori che hanno ricevuto l'emailadminEmails(array): Lista delle email degli amministratori che hanno ricevuto la notifica
Questo output viene restituito nella risposta HTTP (Postman, browser, curl).
Testing​
URL (if HTTPS): http://127.0.0.1:5001/arshadesstaging/europe-central2/sendQuotationRequestEmailHttp
Test con Emulatore:
- Avvia l'emulatore Firebase:
firebase emulators:start --only functions - Assicurati di usare Node.js versione 20:
nvm use 20 - Test con curl:
curl -X POST "http://127.0.0.1:5001/arshadesstaging/europe-central2/sendQuotationRequestEmailHttp" \
-H "Content-Type: application/json" \
-d '{"orderId": "xq02X2a6CEFVoQtZd5Pa"}'
Test con Postman:
- Metodo: POST
- URL: http://127.0.0.1:5001/arshadesstaging/europe-central2/sendQuotationRequestEmailHttp
- Headers:
- Key:
Content-Type - Value:
application/json
- Key:
- Body: raw JSON (vedi esempi sopra)
Deploy Command:​
firebase deploy --only functions:sendQuotationRequestEmailHttp
URL di Produzione:​
sendQuotationRequestEmailHttp: https://europe-central2-arshades-7e18a.cloudfunctions.net/sendQuotationRequestEmailHttp

