Home > Net >  The best way to calculate total money from multiple orders
The best way to calculate total money from multiple orders

Time:08-28

Let's say i have an multi-restaurant food order app. I'm storing orders in Firestore as documents.

Each order object/document contains:

total: double
deliveredByUid: str
restaurantId: str

I wanna see anytime during the day, the totals of every Driver to each Restaurant like so:

robert: mcdonalds: 10
        kfc: 20

alex: mcdonalds: 35
      kfc: 10

What is the best way of calculating the totals of all the orders? I currently thinking of the following:

  1. The safest and easiest method but expensive: Each time i need to know the totals i just query all the documents in that day and calculate them 1 by 1

  2. Cloud Functions method: Each time an order has been added/removed modify a value in a Realtime database specific child: /totals/driverId/placeId

  3. Manual totals: Each time a driver complete an order and write its id to the order object, make another write to the Realtime database specific child.

Edit: added the whole order object because i was asked to. enter image description here

CodePudding user response:

What I would most likely do is make sure orders are completely atomic (or as atomic as they can be). Most likely, I'd perform the order on the client within a transaction or batch write (both are atomic) that would not only create this document in question but also update the delivery driver's document by incrementing their running total. Depending on how extensible I wanted to get, I may even create subcollections within the user's document that represented chunks of time if I wanted to be able to record totals by month or year, or whatever. You really want to think this one through now.

The reason I'd advise against your suggested pattern is because it's not atomic. If the operation succeeds on the client, there is no guarantee it will succeed in the cloud. If you make both writes part of the same transaction then they could never be out of sync and you could guarantee that the total will always be accurate.

  • Related