Custom conflict resolution advice

Hi,

I have an invoicing and inventory management application and I bumped into an issue when updating a product stock property.

Let’s say I have this product model object:

class Product: Object {
@Persisted var _id: UUID
@Persisted var name: String
@Persisted var price: Decimal128
@Persisted var stock: Decimal128
}

Whenever a purchase is made, the stock property is increased and, when a new sale is created, the stock value decreases.

If we assume that current stock = 10 and add a new purchase of 5, the new stock value is 15. This value should be synced to Atlas backend. But, if the user that creates the above purchase document is offline and during this time another user creates a sale document that takes out 3 product units, when eventually both of them will be online, one user’s product stock will be 15 and another one’s will be 7. And the correct value is 10 + 5 - 3 = 12.

What I did was to add another property @Persisted var stockQueue: Decimal128 where to save all the new values from sale and purchase documents and have a trigger on Atlas that, when data is synced, adds its value to @Persisted var stock: Decimal128 property and then sets stockQueue back to zero. This way, stock property could be the single source of truth and all clients will always have an up to date value.

Does anybody have a better solution about how to handle this?

Thank you!