Track Inventory Levels
By the end of this lesson, you'll be able to:
- Write an InventoryService class with a method to record initial stock
- Query total stock for a product summed across every warehouse
- Explain how a relationship query reaches from product to its stock records
Prerequisites: "Design the Stock Model"
Recording initial stock
public class InventoryService {
public Warehouse_Stock__c receiveStock(Id productId, String warehouseName, Decimal quantity) {
Warehouse_Stock__c stock = new Warehouse_Stock__c(
Product__c = productId,
Warehouse_Name__c = warehouseName,
Quantity_On_Hand__c = quantity
);
insert stock;
return stock;
}
}
This is Module 22's service-class pattern, applied to a new object — InventoryService is the single entry point for every inventory operation, exactly like LibraryService was for library operations.
Summing stock across every warehouse
public Decimal getTotalStock(Id productId) {
AggregateResult result = [
SELECT SUM(Quantity_On_Hand__c) totalQty
FROM Warehouse_Stock__c
WHERE Product__c = :productId
];
return (Decimal) result.get('totalQty');
}
This is Module 20's SUM() aggregate function, put to real use — instead of querying every Warehouse_Stock__c record and adding them up in an Apex loop, the database computes the total directly.
Listing stock by warehouse
public List<Warehouse_Stock__c> getStockByWarehouse(Id productId) {
return [
SELECT Id, Warehouse_Name__c, Quantity_On_Hand__c
FROM Warehouse_Stock__c
WHERE Product__c = :productId
ORDER BY Warehouse_Name__c
];
}
This answers a different, complementary question from getTotalStock — not "how much in total?" but "how much where?" — both useful views over the exact same underlying Warehouse_Stock__c records.
Exercise
Add a getWarehouseCount(Id productId) method returning how many distinct warehouses currently stock a product, using COUNT().
Show hint
SELECT COUNT() FROM Warehouse_Stock__c WHERE Product__c = :productId
Track Inventory Levels Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
This lesson builds InventoryService's foundation — recording initial stock, and answering "how much of this product do we have, total, across every warehouse?"