DocHub
Complete reference for all 52 exported Cloud Functions — triggers, callables, HTTP endpoints, scheduled jobs, and PubSub handlers

Functions Reference

All functions live in functions/index.js (11,390 lines). There are 52 exported functions across 5 categories.

Firestore Triggers (18)

These fire automatically when Firestore documents change.

Package Triggers

Function Event Path Description
onPackageCheckIn onWrite Packages/{packageId} Core invoice engine. When status changes to checkIn (from received/unprocessed/unloaded/inTransit), or clientID changes, creates or updates the invoice. Three branches: checkIn with no container, checkIn with container, or clientID-only change. Fetches items, categories, charges, discount codes, and calculates costs with 15% tax.
updatePackageStatusInContainer onUpdate Packages/{packageId} Syncs package status changes to the Container document’s invoices array.
onPackageUpdate onUpdate Packages/{packageId} When charges, containsPackages, dimensions, or itemID change on a checkIn/inTransit/unloaded package, recalculates invoice costs via Firestore transaction.
updateInvoiceOnPackageStatusChange onUpdate Packages/{packageId} Updates package status in invoice’s packages array using Firestore transaction. Sets isAllUnloaded flag. Has 3-retry with exponential backoff. Sends failure email on exhaustion. Memory: 256MB, Timeout: 60s, Instances: min 1, max 50.
validateNewPackageClientID onCreate Packages/{packageId} Validates clientID exists in Clients collection. If not found, marks package with “No Name” problem in scanHistory.
unloadedNotCheckedIn onCreate Packages/{docId} If new package has status=unloaded and unloadedNotCheckedIn=true, sends alert email with tracking number, client name, and container name.
detectDuplicatePackage onCreate Packages/{packageId} Queries for packages with same trackingNumber. If duplicates found, sends detailed HTML email with JSON attachments and logs to webLogs.

Invoice Triggers

Function Event Path Description
handlePackageStatusChange onUpdate Invoices/{invoiceId} When package status changes from inTransit/unloaded/clientPickUp back to checkIn, removes those packages from the invoice. Includes 3-minute container creation race condition guard, 5-second delay, and Firestore transaction for recalculation. Deletes invoice if no packages remain.
updateInvoiceStatusInPackages onUpdate Invoices/{invoiceId} When invoice status changes, batch-updates all packages’ invoiceStatus field.
handlePackageAddition onUpdate Invoices/{invoiceId} Handles duplicate packages in invoices, consolidation logic (removes sub-packages when main package is added using consolidation fee chargeID mIQbG4QoDRSHVRGKuFsJ), and recalculates totals.
handleInvoiceCreation onCreate Invoices/{invoiceId} Auto-approves/unapproves invoice based on whether all packages have no notes/photos/problems. 10-second delay before check.
handleInvoiceUpdate onUpdate Invoices/{invoiceId} Same as above but fires on package array changes (length or content change).
enqueueInvoiceForProcessing onUpdate Invoices/{invoiceID} When invoice becomes APPROVED + has squareCustomerId + isAllUnloaded=true + invoiceSent=false, publishes to PubSub topic process-invoice. Uses atomic Firestore transaction with PubSubQueue for deduplication. Memory: 8GB, Timeout: 540s, Instances: min 1, max 50.

Client Triggers

Function Event Path Description
updateSquareCustomerIdInInvoices onUpdate Clients/{clientId} When squareCustomerId changes on a client, batch-updates all their invoices with the new ID.

Container Triggers

Function Event Path Description
onContainerCreated onCreate Containers/{containerId} After 1-minute delay, publishes to PubSub topic process-container-tasks. Memory: 8GB, Timeout: 540s.
prepaidSendEmail onCreate Containers/{containerId} After 5-minute delay, generates prepaid customer space usage report (XLSX) for 21 hardcoded client IDs. Calculates cubic feet from dimensions. Saves to Storage and emails. Memory: 4GB, Timeout: 540s.
copyDataOnNewContainer onCreate Containers/{containerId} Copies 8th-to-last container and related data (packages, invoices) to archive database. Also copies User, Items, Clients without duplicates. Memory: 8GB, Timeout: 540s.

webLogs Triggers

Function Event Path Description
badScanAlert onCreate webLogs/{docId} When isBadScan=true, sends email with scan details, user info from User collection, and photo evidence from Firebase Storage.

HTTPS Callable Functions (11)

Invoked from the Flutter app via the Firebase Callable SDK.

Function Memory Timeout Description
loadToContainer 8GB 540s Loads all checkIn packages into a container, updates status to inTransit, adds scanHistory entries, updates invoice containerIDs. Batch size: 125 packages, 3-retry commits.
addContainerIdToConsolidatedPackages 8GB 540s Adds containerID to all sub-packages referenced in containsPackages arrays.
sendInvoiceToSquare default default Manual send of invoice to Square API. Creates Order then Invoice. Logs to squareAPILog. Sets automaticallySent: 3 on success, 4 on failure.
updateClientInSquare default default Sends client updates to Make.com webhook.
addClientViaWebhook default default Creates new client via Make.com webhook. Returns squareCustomerId from response.
approveInvoices 8GB 540s Batch approves invoices (sets APPROVED, approveIsTicked:true), updates related packages. Batch limit: 450.
unapproveInvoices 8GB 540s Reverse of approve. Sets UNAPPROVED, approveIsTicked:false. Batch limit: 450.
deleteClientFromSquare default default Deletes customer from Square API.
splitInvoice default default Splits invoice: unloaded/pickedUp packages stay in original, others go to new invoice. Recalculates costs for both.
startNoPasswordPeriod default default Sets 10-minute no-password period in Temp/timer document.
sendForceUnloadEmail default default Sends alert email when packages are force-unloaded, with Roatan timezone (America/Chicago).

HTTPS onRequest Endpoints (5)

Public HTTP endpoints with CORS support.

Function Method Parameters Description
trackPackage GET ?trackingNumber=... Public package tracking API. Looks up by tracking number, handles consolidated packages, returns timeline with status history and estimated dates.
countTrackPackages GET ?referenceId=... or ?email=... or ?phoneNumber=... Looks up all packages for a client, groups by status category (received, checkin, inTransit, unloaded, clientPickUp).
sendFormattedEmailWithData GET ?clientID=...&containerID=...&test=0/1/2 Sends branded HTML package status email to client. Test param: 0=client only, 1=client+test, 2=test only.
addClientContact POST JSON body {referenceId, email?, phoneNumber?} Adds email/phone to client record by referenceId.
reportDuplicateLastName POST JSON body with customer details Receives duplicate last name reports from signup form. Sends styled email to admin about account creation requests matching existing last names.

PubSub Scheduled Functions (13)

Backup Jobs

Function Schedule Timezone Description
scheduledFirestoreExport 0 13,20 * * 1-5 America/New_York Mon-Fri at 1pm and 8pm ET. Exports Firestore to gs://maxproductionbackup/.
scheduledFirestoreExportWeekends 0 13,15,17,19,21,23,1,3,5,7 * * 0,6 America/New_York Sat-Sun every 2 hours. Exports Firestore to gs://maxproductionbackup/.
scheduledFirestoreExport2 0 13 * * * America/New_York Daily at 1pm ET. Exports to maxproductionbackup-weekly on Mondays, maxproductionbackup-daily other days.

Data Quality Checks (daily at 6:55am Asia/Manila)

Function Schedule Description
checkInvoicesDaily 55 6 * * * Checks invoices created within 8 weeks for: missing clientID, invoiceDate, status, squareCustomerId, packages; empty/duplicate packages; invalid status values. 8GB, us-central1.
checkPackagesDaily 55 6 * * * Checks packages for: missing trackingNumber, status, clientID, logistic; duplicate tracking numbers; FedEx tracking >12 chars. 8GB, us-central1.
checkClientsDaily 55 6 * * * Checks all clients for: missing clientID, referenceId, showID, squareCustomerId, location. 8GB, us-central1.
checkContainersDaily 55 6 * * * Checks all containers for: missing containerCreatedAt. 8GB, us-central1.

Reports

Function Schedule Timezone Description
dailyReportAggregator 0 7 * * * Asia/Manila Aggregates check results from checkResults collection and emails to developers.
dailyDataReport 0 13 * * * Asia/Manila Comprehensive daily ops report: receiving/checkin/transit/unloading/pickup counts, no-name packages, per-container breakdowns. 8GB.
weeklyLostPackagesEmail 0 7 * * 4 Asia/Manila Thursdays: packages with received/unprocessed status scanned before (latest container - 7 days).
weeklyUnloadedNotCheckedInEmail 0 7 * * 5 America/New_York Fridays: packages unloaded but never checked in (last 4 weeks).
dailyMissingContactsEmail 0 7 * * 4 America/New_York Thursdays: clients missing email/phone, categorized by missing both/email only/phone only.

System

Function Schedule Description
resetPasswordExpiry every 1 minutes Checks if password expiry timer has elapsed and resets isPasswordExpired to true in Temp/timer.

PubSub Topic-Triggered Functions (4)

Function Topic Memory Timeout Description
processInvoiceFromQueue process-invoice 8GB 540s, max 3 instances Calls processInvoiceInternal. On failure, adds to retry queue and sends failure email.
processContainerTaskJson process-container-tasks 8GB 540s Gathers unprocessed packages, loaded packages, and invoices as JSON, emails as attachments.
processContainerTaskXsl process-container-tasks 8GB 540s Same data but as XLSX attachments. Saves loaded packages XLSX to Firebase Storage at excelsheets/{containerName}-loaded-packages.xlsx.
processContainerTaskJsonForApp process-container-tasks 8GB 540s Saves combined packages JSON to Cloud Storage as json/packages.json.

Imported Functions (1)

Function Source Description
getClientData ./chatbot_function/get_client_data Client data retrieval for chatbot integration.