Record Transactions
Advanced · Write the code · from Build an Inventory Management System with SQLite
From the lesson: Step 3: Record Buy and Sell Transactions
Transactions are the heart of inventory management. Every time you buy stock from a supplier, the quantity goes up. Every time you sell to a customer, it goes down. We need a function that records the transaction and updates the product's quantity in one operation.
Read this part of the lessonWrite a function record_transaction(cursor, product_id, trans_type, quantity) that:
1. If trans_type is "buy": increase the product's quantity and insert a transaction record.
2. If trans_type is "sell": check current stock first. If stock >= quantity, decrease it and insert a record. Otherwise, print "Insufficient stock for product {product_id}" and return False.
3. Return True on success, False on failure.
Test it by adding a product, buying 100 units, selling 30 units, then attempting to sell 200 units (should fail). Print the product's quantity after each operation.
More Inventory System exercises
- Create the Database SchemaAdvanced
- Write the Add Product FunctionAdvanced
- Stock Level ReportAdvanced
- Low Stock Alert SystemAdvanced
- Transaction History ReportAdvanced
- The Complete InventorySystem ClassAdvanced
All Python exercises · 50 practice problems · Practical Projects quiz