Guest User

Untitled

a guest
Apr 22nd, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.98 KB | None | 0 0
  1. //A Utility class to process Stock Item records from the Stock Item Handler
  2. public with sharing class StockItemHandler {
  3.  
  4. //Default Constructor
  5. public void StockItemHandler() {
  6. }
  7.  
  8. //Check for duplicate stock items before insert and display an error to user if a duplicate is found
  9. public void OnBeforeInsert(List<Stock_Item__c> stockItems){
  10.  
  11. //Create a set to hold new stock items being inserted
  12. Set<String> newStockSet = new Set<String>();
  13.  
  14. //Create a set to hold stock items in the database (db)
  15. Set<String> dbStockSet = new Set<String>();
  16.  
  17. //Create an error variable and assign value
  18. String errorMsg = 'This item name is already entered in the system. Please enter a unique item name.';
  19.  
  20. for (Stock_Item__c s : stockItems) // Loop through all of the records for insert
  21. newStockSet.add(s.Item_Name__c); // Add each item name to the newStockSet
  22.  
  23. for (Stock_Item__c dbStock : [SELECT Item_Name__c //Loop through stock items in the database
  24. FROM Stock_Item__c
  25. WHERE Item_Name__c IN :newStockSet]){
  26. dbStockSet.add(dbStock.Item_Name__c.toUpperCase()); // Add values to the dbStockSet that match an item being inserted
  27. }
  28.  
  29. for (Stock_Item__c s : stockItems){ // Loop through all of the records for insert
  30. if(dbStockSet.contains(s.Item_Name__c.toUpperCase())) // If the item name is already in the dbStockSet, we have a duplicate item
  31. s.addError(errorMsg); // So, add an error to the record
  32. }
  33. }
  34.  
  35. //Check stock on hand before a stock item can be deleted
  36. public void OnBeforeDelete(List<Stock_Item__c> stockItems){
  37.  
  38. // Create a list to hold new cases for insertion.
  39. List<Case> casesToCreate = new List<Case>();
  40.  
  41. for(Stock_Item__c s : stockItems){ // Loop through all of the records being deleted
  42. if(s.Stock_on_Hand__c <> 0){ // If the stock on hand is greater than zero, we need to alert someone
  43. Case newCase = new Case(); // So, create a new case for the deleted item
  44. newCase.Status = 'New';
  45. newCase.Subject = 'Item with Stock on Hand DELETED'; // Set the field values for the new case record
  46. newCase.Description = 'Item Name: ' + s.Item_Name__c + '; Stock Item Id: ' + s.Id + '; Number on Hand: ' + s.Stock_on_Hand__c;
  47. casesToCreate.add(newCase); // Add new case to the casesToCreate list
  48. }
  49. }
  50. insert casesToCreate; //DML call to insert list of new case records
  51. }
  52. }
Add Comment
Please, Sign In to add comment