Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. trigger PopulateAccount on Account (before insert, before update) {
  2.  
  3. if(Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)){
  4. //Find Ownership according to the Salesperson_Code__c
  5. Set<Integer> SAPID = new set<Integer>();
  6. Set<String> SAPIDOwner = new set<String>();
  7. Map<Integer,User> userIdObj = new map<Integer,User>();
  8. Map<String,User> ownerIdObj = new map<String,User>();
  9. if (trigger.isBefore && trigger.isUpdate){
  10. for (Account acc:trigger.New){
  11. if((trigger.oldMap.get(acc.Id).ownerId != trigger.newMap.get(acc.Id).ownerId) && (acc.ownerId != null)){
  12. SAPIDOwner.add(acc.ownerId);
  13. } else {
  14. if(acc.Salesperson_Code__c != null){
  15. SAPID.add(acc.Salesperson_Code__c.intValue());
  16. }
  17. }
  18. }
  19. }else{
  20. for(Account acc:trigger.New){
  21. if(acc.Salesperson_Code__c == null){
  22. SAPIDOwner.add(acc.ownerId);//Admin?
  23. }else{
  24. if(acc.Salesperson_Code__c != null){
  25. SAPID.add(acc.Salesperson_Code__c.intValue());
  26. }
  27. }
  28. }
  29. }
  30. if(SAPID.size() > 0){
  31. for (User userSAP : [SELECT Id,Salesperson_Code__c FROM user WHERE Salesperson_Code__c =:SAPID]){
  32. userIdObj.put(userSAP.Salesperson_Code__c.intValue(),userSAP);
  33. }
  34. }
  35. if(SAPIDOwner.size() > 0){
  36. for (User ownerObj: [SELECT Id,Salesperson_Code__c FROM user WHERE Id =:SAPIDOwner]){
  37. ownerIdObj.put(ownerObj.Id,ownerObj);
  38. }
  39. if(ownerIdObj.size()>0){
  40. for(Account acc1:trigger.New){
  41. acc1.Salesperson_Code__c = ownerIdObj.get(acc1.ownerID).Salesperson_Code__c;
  42. }
  43.  
  44. }
  45. }else{
  46. if(userIdObj.size() > 0){
  47. for(Account acc1:trigger.New){
  48. if(acc1.Salesperson_Code__c != null){
  49. if(userIdObj.get(acc1.Salesperson_Code__c.intValue()) != null){
  50. acc1.ownerID = userIdObj.get(acc1.Salesperson_Code__c.intValue()).Id;
  51. }
  52. }
  53.  
  54. }
  55. }else{
  56. List<User> users = [SELECT Id,username FROM user];
  57. User SAPIntegration = new User();
  58. for (User SAP:users){
  59. if (SAP.username == 'admin@company.com'){
  60. SAPIntegration = SAP; break;
  61. }
  62. }
  63. if(SAPIntegration.username == 'manuele@aircobrands.com.au'){
  64. for (Account acc1:trigger.New){
  65. acc1.ownerId = SAPIntegration.Id;
  66. }
  67. }
  68. }
  69. }
  70.  
  71. }
  72. //END Find Ownership according to the Salesperson_Code__c
  73. }//END of trigger
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement