public without sharing class AgencyReportHeaderHandler extends Oly_TriggerHandler { private Map newMap; private Map oldMap; private List newList; private List oldList; public AgencyReportHeaderHandler() { this.newMap = (Map) Trigger.newMap; this.oldMap = (Map) Trigger.oldMap; this.newList = (List) Trigger.new; this.oldList = (List) Trigger.old; } protected override void beforeInsert() { beforeExecute(); } protected override void beforeUpdate() { beforeExecute(); shareAgency_Report_Header_ToRole(this.newList); } protected override void afterInsert() { shareAgency_Report_Header_ToRole(this.newList); } protected override void afterUndelete() { shareAgency_Report_Header_ToRole(this.newList); } //Before処理 private void beforeExecute() { for(Agency_Report_Header__c nObj : newList) { nObj.Agency__c = nObj.Owner_Agency_ID__c; nObj.Agency_ID__c = String.valueOf(nObj.Owner_Agency_ID__c).substring(0,15); } } /** * 设定 apex share to role * @param accId UserRoleとGroupを取得するため */ private static void setAgency_Report_Header_Share(Id accId, List pList) { Id grpId = MergeAgencyActivityBatch.accIdGrpIdMap(accId); if(grpId != null) { List shareList = new List(); Set sharePIdSet = new Set(); for (Agency_Report_Header__Share share : [SELECT Id, ParentId FROM Agency_Report_Header__Share WHERE UserOrGroupId = :grpId AND RowCause = 'Manual']) { sharePIdSet.add(share.ParentId); } for (Id pId : pList) { if (sharePIdSet.contains(pId) == false) { Agency_Report_Header__Share apexShare = new Agency_Report_Header__Share( RowCause = 'Manual', ParentId = pId, UserOrGroupId = grpId, AccessLevel = 'Edit'); shareList.add(apexShare); } } if (System.Test.isRunningTest() && grpId == null) { // 没有造 User 的旧Test 也让可以过 return; } insert shareList; } } // afterInsert, afterUndelete /** * 一定要是同一经销商的 * @param nList {Id, Agency__c} */ public static void shareAgency_Report_Header_ToRole(List nList) { Set targetAgencyIdSet = new Set(); Map> tMap = new Map>(); for (Agency_Report_Header__c nObj : nList) { targetAgencyIdSet.add(nObj.Agency__c); List tList = tMap.get(nObj.Agency__c); if (tList == null) { tList = new List(); } tList.add(nObj.Id); tMap.put(nObj.Agency__c, tList); } if (targetAgencyIdSet.size() > 0) { List targetIdList = new List (targetAgencyIdSet); System.assertEquals(1, targetIdList.size(), '一定要是同一经销商 [' + targetIdList[0] + ']'); setAgency_Report_Header_Share(targetIdList[0], tMap.get(targetIdList[0])); } } }