by tolien · 3y ago · 0 comments
> Just about everything about that receipt should be denormalized, AKA. the details about the receipt are all self contained in that 1 row.
The way I'd probably model this would be to mark the $16.95 pie as deleted/deprecated/no longer for sale and create a duplicate entry with the price changed to $17.95, rather than creating copies of all of the product details each time I record a sale.
That technically works, but it plays hell with reporting and stockkeeping. The latter of which isn't a problem for pizza, of course, but can be significant in other sectors. (Nobody wants to have to keep track of a stock of "$16.95 widgets" separate from a stock of identical "$17.95 widgets".)
But there's enough other data in a receipt/invoice which needs to not change after the invoice is created, like tax rates, that it really is best to make the whole thing self-contained and immutable. Being able to confidently make statements like "yes, this is exactly the same invoice that we presented to the customer 3 years ago, and nothing about it has changed" can be incredibly important as well.
A product is copied to a quote (or cart) item. A cart item is copied to an order item. A receipt or invoice is generated from an order and its items. The price of products and all their attributes can be changed without the SKU or identifier changing, but the quote, order, and invoice item is an immutable artifact.
The key problem with this system is order modifications. In order to modify an order you cancel and recreate the order from scratch. We get around this usually by piping the orders to a dedicated order management system and when orders are finalized/auth'd captured/shipped there is one final order modification that comes back to the system to capture the final state and we don't update orders continuously. This way customers see their final order state, but we don't have to cancel/recreate every change to the order along the way.
Is it a better way to do it than an audit log for changes? Maybe!
The ideal schema would probably have some sort of "product" and "product revision". Orders would reference a particular revision and menu/reporting would use the product (joining in the revision).
But in this case since there are likely legal requirements to have exact copies of receipts it may also be smart to just archive a "fully rendered" copy as well to ensure that a code cleanup doesn't change rounding and accidentally modify the data on old orders.
You can always prepare a bad report, I don't think that this schema or that schema will solve all problems, but having a schema which keeps a complete history of changes to its data should be better than one that just lets you run an UPDATE query to actually mess the price history up.