Skip to main content
Version: 1.0.0

downloadVariantJsonsHttps

Function Name: downloadVariantJsonsHttp

Trigger: HTTPS (onRequest)

Purpose: Manages the download of product data and automatic generation of Excel reports for optical products from the Safilo catalog. Processes SKUs with result='Orderable', downloads JSON data and images, generates Excel reports, and automatically sends quotation request emails to administrators.

Detailed Functionalityโ€‹

This Firebase Function performs a comprehensive data processing workflow for product catalogs:

1. CATALOG DATA RETRIEVALโ€‹

  • Receives catalog order ID from HTTP request
  • Retrieves document from 'CatalogOrders' Firestore collection
  • Utilizes Firebase Storage bucket 'arshades-7e18a.appspot.com'

2. SKU EXTRACTIONโ€‹

  • Filters only elements with result = 'Orderable' (regardless of isSelected value)
  • Extracts SKU codes from filtered elements
  • Removes duplicates to avoid multiple processing

3. BATCH PROCESSINGโ€‹

  • Processes SKUs in batches of 20 elements to optimize performance
  • Each batch is processed in parallel for maximum efficiency
  • Implements 200ms delay between API calls to avoid overload

4. JSON DOWNLOAD AND MANAGEMENTโ€‹

  • NEW API: https://commportal-api.safilo.com/damAPI/damitems/AUTH.../spaarkly.getModels?sizeCode={sku}
  • Checks existence in Storage: ARS_Library_Product_Data/{skuCode}/json/{skuCode}.json
  • If not exists: downloads, saves temporarily, uploads to Storage with UUID token
  • If exists: uses existing file to extract image parameters

5. IMAGE DOWNLOAD AND OPTIMIZATIONโ€‹

  • Extracts modelCode, colorCode, lensCode from JSON for each SKU
  • Downloads 2 images (detail=00 frontal, detail=04 lateral)
  • API: https://safilo-pd-cdn002.safilo.com/damapi/damimage/public/sfcc.getimagenofb
  • Optimizes images: resizes to 120x120px, JPEG quality 90%, progressive format
  • Fallback: Sharp โ†’ Jimp โ†’ original buffer
  • Storage: ARS_Library_Product_Data/{skuCode}/thumbnail/{modelCode}_{colorCode}_{lensCode}_{detail}.jpg

6. AUTOMATIC EXCEL REPORT GENERATIONโ€‹

  • Always generates Excel report automatically at the end of processing
  • Includes: skuCode, Style Description, frontal image (00), lateral image (04)
  • Downloads images from URLs (Firebase Storage or API) into memory
  • Optimizes images with Sharp/Jimp (120x120px, JPEG 90%)
  • Creates Excel with ExcelJS: 4 columns (SKU, Description, Img00, Img04)
  • Cell dimensions: width 18-30 units, height 75 points
  • Image positioning: tl/br coordinates for automatic fit
  • Bold headers, fixed row height
  • Saves Excel to Storage: Orders/{orderId}/Orders-orderid-report.xlsx
  • Generates UUID token for public access

7. API ERROR HANDLINGโ€‹

  • Detects errors during API calls (JSON and images)
  • Updates order status from "processing_addition" to "error" on errors
  • Adds "status" field with value "Failed - API json/images" to elements with result="Orderable"
  • Returns status code 500 instead of 200 when API errors occur
  • SPECIFIC HTTP 410 (Gone) HANDLING:
    • Error 410 indicates image no longer available on Safilo server
    • Not considered critical system error, only resource unavailability
    • Processing continues normally for other SKUs
    • Statistics distinguish between technical errors (failed) and unavailable images (unavailable)

8. AUTOMATIC QUOTATION REQUEST EMAILโ€‹

  • Automatically sends quotation request email when Excel report generated successfully
  • Condition: must exist excelResult with valid downloadUrl, token and fileName
  • Sends TWO distinct emails:
    • Administrator email: Template with key 13ef.8598f19fbcc5adb.k1.e8a28620-50ea-11f0-9c4e-dad70ff08860.197a19bc782
    • User confirmation email: Template with key 13ef.8598f19fbcc5adb.k1.9337a850-5e23-11f0-9e15-dad70ff08860.197f8418755
  • Uses sendQuotationRequestEmailHttp function for ZeptoMail sending
  • Robust error handling: if email sending fails, it's logged but doesn't interrupt process

Technical Featuresโ€‹

  • TIMEOUT: 540 seconds (9 minutes) for long processing
  • MEMORY: 1GiB to handle images and Excel files
  • REGION: europe-central2 for optimal performance
  • CORS: Enabled for frontend calls
  • ERROR HANDLING: Detailed logging, robust fallbacks, response with errorDescription
  • OPTIMIZATION: Parallel calls, intelligent cache, batch processing
  • SECURITY: UUID tokens for controlled file access
  • FORMAT: Excel XLSX with embedded images, professional layout

Storage Structureโ€‹

ARS_Library_Product_Data/
โ”œโ”€โ”€ {skuCode}/
โ”‚ โ”œโ”€โ”€ json/
โ”‚ โ”‚ โ””โ”€โ”€ {skuCode}.json
โ”‚ โ””โ”€โ”€ thumbnail/
โ”‚ โ”œโ”€โ”€ {modelCode}_{colorCode}_{lensCode}_00.jpg
โ”‚ โ””โ”€โ”€ {modelCode}_{colorCode}_{lensCode}_04.jpg
โ””โ”€โ”€ Orders/
โ””โ”€โ”€ {orderId}/
โ””โ”€โ”€ Orders-orderid-report.xlsx

Input (Payload):โ€‹

{
"orderId": "xq02X2a6CEFVoQtZd5Pa"
}

Parameters:

  • orderId (string, required): ID of the catalog order document in the 'CatalogOrders' collection

Output (Success):โ€‹

{
"success": true,
"message": "Processing completed: 5 new JSONs, 2 existing JSONs, 0 failed. Images: 8 new, 4 existing, 2 failed (partial only). 1 images not available on server (HTTP 410).",
"stats": {
"totalItems": 7,
"processedItems": 7,
"json": {
"new": 5,
"skipped": 2,
"failed": 0
},
"images": {
"new": 8,
"skipped": 4,
"failed": 2,
"unavailable": 1
},
"hasApiError": false,
"skusWithCriticalErrors": 0
},
"excelReport": {
"fileName": "Orders-xq02X2a6CEFVoQtZd5Pa-report.xlsx",
"downloadUrl": "https://firebasestorage.googleapis.com/v0/b/arshades-7e18a.appspot.com/o/Orders%2Fxq02X2a6CEFVoQtZd5Pa%2FOrders-xq02X2a6CEFVoQtZd5Pa-report.xlsx?alt=media&token=uuid-token",
"token": "uuid-token"
}
}

Response Properties:

  • success (boolean): Indicates if the operation was completed successfully
  • message (string): Descriptive message of the processing results
  • stats (object): Detailed statistics of processed items
    • totalItems (number): Total number of SKUs to process
    • processedItems (number): Number of SKUs actually processed
    • json (object): JSON download statistics (new, skipped, failed)
    • images (object): Image download statistics (new, skipped, failed, unavailable)
    • hasApiError (boolean): Indicates if there were critical API errors
    • skusWithCriticalErrors (number): Number of SKUs with critical errors
  • excelReport (object): Excel report information
    • fileName (string): Name of the generated Excel file
    • downloadUrl (string): Public URL for Excel file download
    • token (string): UUID token for file access

This output is returned in the HTTP response (Postman, browser, curl).

Testingโ€‹

URL (if HTTPS): http://127.0.0.1:5001/arshadesstaging/europe-central2/downloadVariantJsonsHttp

Test with Emulator:

  1. Start the Firebase emulator: firebase emulators:start --only functions
  2. Ensure you're using Node.js version 20: nvm use 20
  3. Test with curl:
curl -X POST "http://127.0.0.1:5001/arshadesstaging/europe-central2/downloadVariantJsonsHttp" \
-H "Content-Type: application/json" \
-d '{"orderId": "xq02X2a6CEFVoQtZd5Pa"}'

Postman Testing:

Deploy Command:โ€‹

firebase deploy --only functions:downloadVariantJsonsHttp

Production URL:โ€‹

downloadVariantJsonsHttp: https://europe-central2-arshades-7e18a.cloudfunctions.net/downloadVariantJsonsHttp