I am try to deploy my code to firebase cloud function through flutterflow but it keep failing. Previously I managed to do it successfully but I deleted the function on flutterflow then deleted it on the firebase console because it was not deleted in the firebase console.
Then I added a new function on flutterflow, same code for the function but this time it failed.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
// To avoid deployment errors, do not call admin.initializeApp() in your code
const db = admin.firestore();
exports.updateInventoryOnPurchase = functions.firestore
.document('purchaseLine/{purchaseLineId}')
.onCreate(async (snapshot, context) => {
const data = snapshot.data();
const businessId = data.businessId;
const itemId = data.itemId;
const itemQty = data.itemQty;
console.log(`businessId: ${businessId}, itemId: ${itemId}, itemQty: ${itemQty}`);
// Reference to the inventory document
const inventoryRef = db.collection('inventory')
.where('businessId', '==', businessId)
.where('itemName', '==', itemId);
try {
// Use a Firestore transaction to update the itemStock field in the matching inventory document
await db.runTransaction(async (transaction) => {
const inventoryQuerySnapshot = await transaction.get(inventoryRef);
if (inventoryQuerySnapshot.empty) {
throw new Error('Inventory item not found');
}
inventoryQuerySnapshot.forEach((inventoryDoc) => {
const currentStock = inventoryDoc.data().itemStock || 0; // Default to 0 if field doesn't exist
const newStock = currentStock + itemQty;
// Update the itemStock field in the inventory document
transaction.update(inventoryDoc.ref, { itemStock: newStock });
});
});
console.log(`Inventory updated for item: ${itemId} with businessId: ${businessId}`);
} catch (error) {
console.error('Error updating inventory:', error);
}
});
Deploying function to cloud function from flutterflow.