Overview
PixelTech Colombia uses Firebase Cloud Functions to handle server-side operations including payment processing, email notifications, scheduled tasks, and webhooks. All functions are implemented in Node.js using the Firebase Functions SDK.Architecture
The functions are organized in modular files located infunctions/ directory:
Initialization
All functions share a single Firebase Admin SDK instance initialized infunctions/index.js:9-11:
Payment Functions
MercadoPago
Create Preference:createMercadoPagoPreference
- Type: Callable Function
- File:
functions/mercadopago.js:18 - Purpose: Creates a MercadoPago checkout preference with 30-minute expiration
- User authentication via Firebase Auth token
- Real-time price validation from Firestore
- Creates order with
PENDIENTE_PAGOstatus - Handles product variants (color, capacity)
- Automatic expiration after 30 minutes
mercadoPagoWebhook
- Type: HTTPS Request
- File:
functions/mercadopago.js:174 - Endpoint:
https://us-central1-pixeltechcol.cloudfunctions.net/mercadoPagoWebhook
functions/mercadopago.js:204-306):
- Receives payment notification
- Verifies payment status with MercadoPago API
- On Approved:
- Deducts inventory (with variant support)
- Updates treasury account balance
- Creates expense/income record
- Generates remission document
- Updates order status to
PAGADO
- On Rejected: Marks order as
RECHAZADO
ADDI
Create Checkout:createAddiCheckout
- Type: Callable Function
- File:
functions/addi.js:59 - Purpose: Creates ADDI “Buy Now, Pay Later” checkout
functions/addi.js:29-54):
addiWebhook
- Type: HTTPS Request with CORS
- File:
functions/addi.js:260 - Duplicate Protection: Checks
paymentStatus === 'PAID'before processing (functions/addi.js:281-284)
Sistecrédito
Create Checkout:createSistecreditoCheckout
- Type: Callable Function
- File:
functions/sistecredito.js:22 - Purpose: Colombian credit system integration
functions/sistecredito.js:15-17):
sistecreditoWebhook
- File:
functions/sistecredito.js:172 - Status Mapping:
Approved→PAGADO,Rejected/Cancelled/Failed→RECHAZADO
Cash on Delivery (COD)
Create Order:createCODOrder
- Type: Callable Function
- File:
functions/cod.js:4 - Purpose: Creates order with immediate stock deduction
- Sets
isStockDeducted: trueimmediately (functions/cod.js:103) - Creates remission document instantly (
functions/cod.js:127) - No webhook needed - order is created as
PENDIENTE(awaiting fulfillment)
functions/cod.js:45-128):
Email Functions
Order Confirmation
Function:sendOrderConfirmation
- Type: Firestore Trigger (onCreate)
- File:
functions/emails.js:222 - Trigger:
orders/{orderId}document creation
Dispatch Notification
Function:sendDispatchNotification
- Type: Firestore Trigger (onUpdate)
- File:
functions/emails.js:255 - Trigger: Order status changes to
dispatched,enviado,DESPACHADO, orEN_RUTA
functions/emails.js:36-219):
- Professional HTML design with brand colors
- Responsive layout (600px max-width)
- Dynamic tracking information
- Integrated WhatsApp support link
- Product images and details
functions/emails.js:5-13):
Scheduler Functions
Process Scheduled Transfers
Function:processScheduledTransfers
- Schedule: Daily at 00:05 AM (Colombia time)
- File:
functions/scheduler.js:11
functions/scheduler.js:22-115):
- Query
scheduled_transferswherestatus == 'PENDING'andscheduledDate <= now - For each transfer:
- Deduct from source account
- Add to target account
- Mark transfer as
COMPLETED - Create expense records for audit trail
- Handle failures gracefully (mark as
FAILED)
Cleanup Old Orders
Function:cleanupOldOrders
- Schedule: Every 24 hours
- File:
functions/scheduler.js:117 - Purpose: Removes abandoned orders older than 7 days
Cancel Abandoned Payments
Function:cancelAbandonedPayments
- Schedule: Every 15 minutes
- File:
functions/scheduler.js:157 - Purpose: Auto-cancels orders pending payment for >35 minutes
Check Expired Promotions
Function:checkExpiredPromotions
- Schedule: Every 60 minutes
- File:
functions/scheduler.js:217 - Purpose: Restores original prices when promotions expire
WhatsApp Functions
Webhook Handler
Function:whatsappWebhook
- Type: HTTPS Request
- File:
functions/whatsapp.js:65 - Purpose: Receives messages from WhatsApp Business API
functions/whatsapp.js:67-72):
functions/whatsapp.js:100-136):
- Active Hours: 8 PM to 7 AM (Colombia time)
- Cooldown: 12 hours between auto-replies to same user
- Message: “Nuestro equipo descansa en este momento…”
functions/whatsapp.js:40-62):
- Downloads images, audio from Meta API
- Uploads to Firebase Storage
- Makes files public and stores URL in Firestore
Send Message
Function:sendWhatsappMessage
- Type: Callable Function
- File:
functions/whatsapp.js:176 - Purpose: Admin panel sends messages to customers
Google Merchant Feed
Function:generateProductFeed
- Type: HTTPS Request
- File:
functions/google-merchant.js:32 - Endpoint: Public XML feed for Google Shopping
- Delta Caching: Only regenerates changed products (
functions/google-merchant.js:65-67) - Variant Support: Creates separate entries for color/capacity combinations
- Stock Sync: Reports exact inventory with
<g:sell_on_google_quantity>(functions/google-merchant.js:152) - Promotion Handling: Includes sale dates and pricing (
functions/google-merchant.js:95-101) - Shipping Calculation: Auto-applies free shipping threshold
functions/google-merchant.js:50-62):
?rebuild=true query parameter
Sitemap Generation
Function:sitemap
- Type: HTTPS Request
- File:
functions/sitemap.js:21 - Purpose: Dynamic XML sitemap for SEO
- Static pages (homepage, catalog, search)
- All categories with encoded URLs
- All active products with last modification dates
Product Sync Utilities
Function:touchProductTimestamp
- Type: Firestore Trigger (onWrite)
- File:
functions/sync.js:8 - Purpose: Auto-updates
last_updatedtimestamp on product changes
functions/sync.js:16-19):
Deployment
Environment Variables
Required.env configuration:
Deploy Commands
Testing Locally
Common Patterns
Inventory Management
All payment webhooks follow this pattern for stock deduction:Error Handling
Monitoring
Firebase Console
- Logs: Firebase Console → Functions → Logs
- Metrics: Request count, execution time, error rate
- Alerts: Configure alerts for error thresholds
Key Metrics to Monitor
- Webhook Success Rate: Should be >99%
- Email Delivery: Track
confirmationEmailSentanddispatchEmailSentflags - Scheduler Execution: Check daily logs for
processScheduledTransfers - Feed Generation Time: Should be under 5 seconds with caching
Security Best Practices
- Authentication: All callable functions verify
context.author validate Firebase tokens - Webhook Validation: MercadoPago payments verified against API before processing
- Price Validation: Always fetch real prices from Firestore, never trust client data
- Duplicate Prevention: Check
paymentStatusbefore processing webhooks - Transaction Safety: Use Firestore transactions for inventory updates