buli
2022-04-25 4cf305347ea6f6a73e03fa9427a3de80ca35ae7a
force-app/main/default/classes/NewAndEditBaseController.cls
@@ -109,6 +109,9 @@
        }else{
            rtTypeId = ApexPages.currentPage().getParameters().get('RecordType');
        }
        AssignValueFromUrl(ApexPages.currentPage().getParameters(),obj);
        PIHelper.PIIntegration piIntegration = PIHelper.getPIIntegrationInfo(sobjectTypeValue);
        //layoutEncryptedAPIList = piIntegration.PIFields;
        encryptedAPIList = piIntegration.PIFields;
@@ -119,6 +122,7 @@
            SaveAndNewButtonUrl = String.format('/setup/ui/recordtypeselect.jsp?ent={0}&retURL=/{1}/o&save_new_url=/{1}/e?retURL=%2F{1}%2Fo', new String[]{sobjectTypeValue,sobjectPrefix});
        }
        system.debug('piIntegration.PIDetails='+piIntegration.PIDetails);
        for (PI_Field_Policy_Detail__c PIDetail : piIntegration.PIDetails) {
            
            AWSToSobjectNonEncryptedMap.put(PIDetail.AWS_Field_API__c, PIDetail.SF_Field_API_Name__c);
@@ -127,6 +131,7 @@
        System.debug(new List<string>(AWSToSobjectNonEncryptedMap.keySet()));
        system.debug('AWSToSobjectNonEncryptedMapJson=');
        system.debug(AWSToSobjectNonEncryptedMapJson);
        system.debug('AWSToSobjectEncryptedMap='+AWSToSobjectEncryptedMap);
        try{
            LayoutDescriberHelper.LayoutWrapper LayoutWrapperValue = LayoutDescriberHelper.describeSectionWithFieldsWrapper(rtTypeId, sobjectTypeValue,'classic');
            layoutSections = LayoutWrapperValue.layoutSections;         
@@ -158,6 +163,147 @@
            layoutEncryptedAPIList = piIntegration.PIFields;
            system.debug('Exception from get layout service:'+e.getmessage());
        }
    }
    // 从url参数赋值到当前页面
    public static void AssignValueFromUrl(Map<string,string> mso, sobject sobj){
        String sobject_name = sobj.getSObjectType().getDescribe().getName();
        Map<string,object> temp = new Map<string,object>();
        Map<string,FieldDefinition> fdm = new Map<string,FieldDefinition>();
        List<FieldDefinition> fds = [SELECT Id, DurableId, QualifiedApiName,ValueTypeId , EntityDefinitionId, NamespacePrefix,EntityDefinition.NamespacePrefix, DeveloperName, MasterLabel, Label FROM FieldDefinition where EntityDefinition.QualifiedApiName = :sobject_name];
        for(FieldDefinition fd : fds){
            //system.debug(fd.DurableId);
            fdm.put(fd.DurableId.split('\\.')[1],fd);
        }
        for(string key : mso.keySet()){
            if (key.toLowerCase() == 'id') {
                System.debug('skip id assign');
                continue;
            }
            string new_key = key;
            system.debug('new_key='+new_key);
            if(new_key.contains('_lkid')){
                new_key = new_key.replace('_lkid', '');
                new_key = new_key.substring(2);
            }else{
                if(temp.containsKey(new_key)){
                    continue;
                }
            }
            system.debug('now new_key='+new_key);
            if(fdm.containsKey(new_key)){
                system.debug('fdm.get(new_key)='+fdm.get(new_key));
                string val_str = mso.get(key);
                system.debug('val_str='+val_str);
                /*无需做decode,sf内部已经做好
                try{
                    val_str = EncodingUtil.urlDecode(mso.get(key),'UTF-8');
                }catch(Exception e){
                    continue;
                    system.debug('Exception from get Key:'+e.getMessage());
                    system.debug(e.getStackTraceString());
                } */
                object val = null;
                string type_id = fdm.get(new_key).ValueTypeId;
                // address, boolean, date, datetime, double, id, location, string, time
                if(string.isBlank(val_str)){
                    val = null;
                }else if(type_id == 'boolean'){
                    if(val_str == '1'){
                        val = true;
                    }else{
                        val = boolean.valueOf(val_str);
                    }
                }else if(type_id == 'date'){
                    //
                      try{
                        val = date.parse(val_str);
                    }catch(Exception e){
                        system.debug('val_str='+val_str);
                        system.debug(e.getMessage());
                        system.debug(e.getStackTraceString());
                        try{
                            val = date.valueOf(val_str);
                        }catch(Exception ee){
                            system.debug('val_str='+val_str);
                            system.debug(ee.getMessage());
                            system.debug(ee.getStackTraceString());
                            continue;
                        }
                    }
                }else if(type_id == 'datetime'){
                    //
                      try{
                        val = datetime.parse(val_str);
                    }catch(Exception e){
                        system.debug('val_str='+val_str);
                        system.debug(e.getMessage());
                        system.debug(e.getStackTraceString());
                        try{
                            val = datetime.valueOf(val_str);
                        }catch(Exception ee){
                            system.debug('val_str='+val_str);
                            system.debug(ee.getMessage());
                            system.debug(ee.getStackTraceString());
                            continue;
                        }
                    }
                }else if(type_id == 'double' || type_id == 'number'){
                    try{
                        val = decimal.valueOf(val_str.replace(',', ''));
                    }catch(Exception ee){
                        system.debug('val_str='+val_str);
                        system.debug(ee.getMessage());
                        system.debug(ee.getStackTraceString());
                        continue;
                    }
                }else if(type_id == 'id' || type_id == 'string'){
                    val = val_str;
                }else{
                    system.debug('type_id='+type_id+' is not support to convert');
                    continue;
                }
                temp.put(fdm.get(new_key).QualifiedApiName,val);
            }else{
                system.debug(key+' is not in fdm');
            }
        }
        for(string key : temp.keySet()){
            system.debug('assign '+key+'='+temp.get(key));
            try{
                sobj.put(key, temp.get(key));
            }catch(Exception e){
                system.debug(e.getMessage());
                system.debug(e.getStackTraceString());
            }
        }
    }
    public static boolean IsCurrentUserAdministrator()
    {
        return IsAdministrator(UserInfo.getUserId());
    }
    public static boolean IsAdministrator(Id user_id)
    {
        return IsAdministrator(new List<id>{user_id}).get(user_id);
    }
    public static Map<id,boolean> IsAdministrator(List<id> user_ids)
    {
        Map<id,User> pfs = new Map<id,User>([select id from User where id in :user_ids and profileid in ( SELECT profileId  FROM PermissionSet WHERE IsOwnedByProfile = true AND IsCustom = false and permissionsmanageusers = true)]);
        Map<id,boolean> res = new Map<id,boolean>();
        for(Id uid: user_ids){
            res.put(uid, pfs.containsKey(uid));
        }
        return res;
    }
    public static string GetReferenceField(string f){
@@ -198,7 +344,12 @@
        Map<String, Schema.SObjectField> fieldAPIToTypeMap = leadSchema.getDescribe().fields.getMap();
        Map<String,Object> fieldValueMap = (Map<String,Object>)JSON.deserializeUntyped(leadJson);
        
      string rtid = null;
        if (fieldValueMap.containsKey('RecordTypeId')) {
            rtid = String.valueOf(fieldValueMap.get('RecordTypeId'));
        }
        List<string> invalid_fields = GetInvalidFieldFromLayout(rtid,sobjectTypeValue);
        Boolean isClone = false;
        //2. Save Record Process
        String status = 'success';    
@@ -210,6 +361,12 @@
            
            for (String fieldAPI: fieldValueMap.keySet()) {
                system.debug('field API='+fieldAPI);
                if(invalid_fields.contains(fieldAPI) && !IsCurrentUserAdministrator()){
                    system.debug(fieldAPI+' is invalid');
                    continue;
                }
                if(!fieldAPIToTypeMap.containskey(fieldAPI)){
                    continue;
                }
@@ -238,7 +395,7 @@
                    leadInfo.put(fieldAPI,fieldValue);
                }                  
            }
            system.debug('for (String fieldAPI: fieldValueMap.keySet()) end');
            awsDataId = (String)leadInfo.get('AWS_Data_Id__c');
            if (string.isBlank(awsDataId)) {
@@ -312,4 +469,36 @@
        }
    }
    
    public static List<string> GetInvalidFieldFromLayout(string rtid, string sobject_name){
        List<Metadata.LayoutSection> sections = MetaDataUtility.GetRecordTypePageLayout(rtid, sobject_name);
        List<string> ls = new List<string>();
        if (sections == null) {
            System.debug('sections=null');
            return ls;
        }
        system.debug(Json.serialize(sections));
        for (Metadata.LayoutSection section : sections) {
            if (section.layoutColumns != null) {
                for (Metadata.LayoutColumn layoutColumn : section.layoutColumns) {
                    if(layoutColumn.layoutItems != null){
                        for (Metadata.LayoutItem item : layoutColumn.layoutItems) {
                            System.debug(item);
                            if(item.field==null)continue;
                            if (item.behavior == Metadata.UiBehavior.READONLY  ) {
                                ls.add(item.field);
                            }
                        }
                    }
                }
            }
        }
        return ls;
    }
}