I've been trying to get this firestore transaction to run but it always throws the same error. I've tried adding a return in the txn.get an txn.set and txn.update, yet it never works.
Here's the transaction I'm trying to get to work:
return db.runTransaction((txn) => {
// - - - Update inventory - - -
Products.forEach((product) => {
// Get existing product (if it exists)
const docref = db
.collection("Inventory")
.doc(product.Description + product.Batch);
return txn.get(docref).then((doc) => {
if (doc.exists) {
// Update values
const previous_amount = Number(doc.data().Cantidad);
const new_amount = 0;
if (MovementType == "Entrada") {
new_amount = previous_amount + product.Quantity;
} else {
new_amount = previous_amount - product.Quantity;
}
txn.update(docref, { Cantidad: new_amount });
} else if (MovementType == "Entrada") {
// Create document
txn.set(docref, {
Articulo: product.Description,
Cantidad: Number(product.Quantity),
Precio: product.Subtotal,
Lote: product.Batch,
FechaDeIngreso: new Date().toISOString(),
FechaDeCaducidad: product.ExpiryDate,
});
}
});
});
// - - - Register Movement - - -
const movementDocRef = db.collection("Movimientos").doc();
txn.set(movementDocRef, {
MovementType: MovementType,
Person: Person,
Products: Products,
Date: new Date().toISOString(),
Cfdi: Cfdi != null ? Cfdi.Id : null,
});
});