NestifyCode
ย ยทย Flutterflow expert

Multiple firebase documents update using CUSTOM CODE

I created custon action to update firebase documents simulteneously by providing it with json list consisting of Ids and the updating data

// Automatic FlutterFlow imports
import '/backend/backend.dart';
import '/backend/schema/structs/index.dart';
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/actions/index.dart'; // Imports other custom actions
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom action code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

// import 'package:cloud_firestore/cloud_firestore.dart';
// import 'dart:math' show max;

Future<String> updateMultipleInventoryDocumentsOnFirebase(
    List<dynamic> jsonListWithIDsAndQuantities) async {
  // Create a reference to the Firebase Firestore collection
  FirebaseFirestore db = FirebaseFirestore.instance;

  // Verify that the list contains maps of strings and dynamics
  if (jsonListWithIDsAndQuantities
      .any((item) => item is! Map<String, dynamic>)) {
    return "Invalid input: All items must be of type Map<String, dynamic>.";
  }

  // Process each item in the JSON list
  for (var item in jsonListWithIDsAndQuantities) {
    Map<String, dynamic> inventoryItem = item as Map<String, dynamic>;
    String? id = inventoryItem['id'] as String?;
    double? quantitySold = inventoryItem['itemQuantity'] as double?;

    if (id == null || quantitySold == null) {
      continue; // Skip this iteration if id or itemQuantity is missing
    }

    try {
      // Query the inventory document with the respective id
      var inventoryQuery = db
          .collection('inventory')
          .where('product_ID', isEqualTo: id)
          .limit(1);

      var inventorySnapshot = await inventoryQuery.get();

      if (inventorySnapshot.docs.isNotEmpty) {
        var inventoryDocument = inventorySnapshot.docs.first;
        var currentQuantity =
            inventoryDocument.data()['quantityInStock'] as double? ?? 0.0;
        var newQuantityInStock = currentQuantity - quantitySold;

        // Ensure inventory doesn't go negative
        newQuantityInStock = max<double>(0.0, newQuantityInStock);

        // Update the inventory document with the new inventory level
        await db
            .collection('inventory')
            .doc(inventoryDocument.id)
            .update({'quantityInStock': newQuantityInStock});
      } else {
        print('Inventory for product_ID $id not found in database.');
      }
    } catch (e) {
      print('Error updating inventory for ID $id: $e');
      return "Failed to update some inventory items due to an error.";
    }
  }

  return "Inventory updated successfully";
}
7