Vending Machine
Atomic purchase and credit ownership
A sale moves money and stock together. Validate product existence, stock, and affordability before decrementing anything. This preserves the customer's credit when a selection fails.
struct Sale {std::string code;Int change;};
// Construct the result before resetting session credit to zero.Returning a catalog map by value copies nested Product records too. Returning a reference would let clients change price or replenish stock without a supported operation. Distinguish unknown products (out_of_range) from valid products that cannot currently be sold (invalid_argument). Integer units keep change exact. The core conservation check is inserted money equals sale price plus change plus remaining credit/refunds; decrementing credit before validation would violate it.
C++ contract conventions: numeric values use signed Int (long long); all inputs and intermediate arithmetic are within its representable range. Opt<T> means std::optional<T> and absence is std::nullopt; Vec<T> means std::vector<T>. Invalid documented arguments throw std::invalid_argument. Inputs passed by const reference remain caller owned. Returned containers and records own their contents. Calls use the declared C++ parameter types. Implicit conversions performed by the caller are outside the runtime validation contract. Unless a lesson states otherwise, string ordering is lexicographic over Unicode code points (Text) or UTF-8 identifiers (std::string).
Put it into practice
Implement the exercise in a full-screen workspace, then run its tests.