1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
public without sharing class MetaDataUtility {
    public static Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
 
    public static List<Metadata.LayoutSection> GetRecordTypePageLayout(string record_type_id,string objectType){
        
        System.debug('record_type_id = ' + record_type_id);
        System.debug('objectType = ' + objectType);
        System.debug('UserInfo.getProfileId() = ' + UserInfo.getProfileId());
        Map<string,object> mso = null;
        string layout_name = GetRecordTypePageLayoutName(record_type_id,objectType,UserInfo.getProfileId());
        System.debug('layout_name = ' + layout_name);
        List<Metadata.LayoutSection>  temp =  GetLayoutSections(objectType,layout_name);
        System.debug('temp = ' + temp);
        List<Metadata.LayoutSection>  layoutSectionList = new List<Metadata.LayoutSection>();
        //7.20 张赫阳 判断当前用户是否是管理员 start
        Profile UserProfile = [SELECT Name,PermissionsModifyAllData  FROM Profile WHERE Id =: UserInfo.getProfileId() LIMIT 1];
        String ByPassProfileName = System.Label.AdminProfileName;
        //7.20 张赫阳 判断当前用户是否是管理员 end
        for(Metadata.LayoutSection section : temp){
            boolean a = false;
            for( Metadata.LayoutColumn c: section.layoutColumns){
                //system.debug(c);
                if(c.layoutItems != null && c.layoutItems.size() > 0 ){
                    a = true;
                    //7.20 张赫阳 添加permissonset start
                    for(Metadata.layoutItem item : c.layoutItems){
                        if(UserProfile.PermissionsModifyAllData){
                            if((item.behavior != Metadata.UiBehavior.Readonly || GetPermission(item.field, objectType))) {
 
                                if(item.behavior == Metadata.UiBehavior.Readonly){
                                    System.debug(item.field + item.behavior);
                                    item.behavior = Metadata.UiBehavior.Readonly;
                                    System.debug('发生权限变动==============》' + item.behavior);
                                }
                            }
                        }
 
                        if(ByPassProfileName == UserProfile.Name){
                            if(item.behavior == Metadata.UiBehavior.Readonly){
                                item.behavior = Metadata.UiBehavior.Edit;
                                System.debug('发生权限变动==============》' + item.behavior);
                            }
                        }
                        // System.debug(item.field + item.behavior);
                    } 
                    //7.20 张赫阳 添加permissonset end
                }
            }
            if(a){
                layoutSectionList.add(section);             
            }
        }
        System.debug('layoutSectionList' + layoutSectionList);
        return layoutSectionList;
    }
 
    //7.20 张赫阳 添加permissonset start
    public static Boolean GetPermission(String fieldName, String objectType){
        
        Schema.SObjectType sobjectSchema = schemaMap.get(objectType);
        Map<String, Schema.SObjectField> fieldMap = sobjectSchema.getDescribe().fields.getMap();
        system.debug(fieldMap.get(fieldName).getDescribe().isUpdateable());  
        return fieldMap.get(fieldName).getDescribe().isUpdateable();
    }
    //7.20 张赫阳 添加permissonset end
    
    /*[{
            "attributes": {
                "type": "Layout",
                "url": "/services/data/v53.0/tooling/sobjects/Layout/00h10000009iAb5AAE"
            },
            "Id": "00h10000009iAb5AAE",
            "Name": ".客户人员レイアウト",
            "TableEnumOrId": "01I10000000er3hEAA",
            "LayoutType": "Standard"
        }]
     */ 
    
    public static string GetTableOrEnumId(string objectType){
        
        Map<string,object> mso = null;
        string resp = null;
        string table_or_enum_id = objectType;
        if(objectType.endsWith('__c')){
            resp = ToolingQuery('SELECT id,DeveloperName from CustomObject where DeveloperName =\''+objectType.replace('__c', '')+'\'');
            if(resp == null){
                system.debug('resp is not ok');
                return null;
            }else{
                mso = (Map<string,object>)Json.deserializeUntyped(resp);
                if(integer.valueOf(mso.get('size')) > 0){
                    table_or_enum_id =  string.valueOf(((Map<string,object>)(((List<object>)mso.get('records'))[0])).get('Id')); 
                }else{
                    system.debug('no records');
                    return null;
                }
            }
        }
        
        return table_or_enum_id;
    }
    
    public static List<object> GetAllPageLayout(string objectType){
        string resp = null;
        Map<string,object> mso = null;
        
        
        string table_or_enum_id =  GetTableOrEnumId(objectType);
        
        if(string.isBlank(table_or_enum_id)){
            return new List<object>();
        }
        
        resp = ToolingQuery('SELECT id,name,TableEnumOrId,LayoutType  FROM Layout where TableEnumOrId = \''+table_or_enum_id+'\'');
        if(resp == null){
            system.debug('Layout where TableEnumOrId='+table_or_enum_id+' is null');
            return null;
        }else{
            mso = (Map<string,object>)Json.deserializeUntyped(resp);
            if(integer.valueOf(mso.get('size')) > 0){
                return (List<object>)mso.get('records');
            }else{
                system.debug('no records');
                return new List<object>();
            }
        }
    }
    
    
    public static string GetRecordTypePageLayoutName(string record_type_id,string objectType, string profile_id){
        
        if(!string.isBlank(objectType)){
            List<sobject> lso = [SELECT Id, Name, DeveloperName, SobjectType, IsActive, Description, BusinessProcessId FROM RecordType where SobjectType = :objectType];
            if(lso.size()==0){
                return string.valueOf(((Map<string,object>)(GetAllPageLayout(objectType)[0])).get('Name'));
            }
        }
        
        // 01210000000QfWdAAK
        string query = 'SELECT Layout.Name, Layout.TableEnumOrId, ProfileId, Profile.Name, RecordTypeId FROM ProfileLayout where id!=null ';
        if(!string.isBlank(record_type_id)){
            query += ' and RecordTypeId = \''+record_type_id+'\'';
        }
        
        if(!string.isBlank(objectType)){
            query += ' and TableEnumOrId = \''+ GetTableOrEnumId(objectType) +'\'';
        }
        
        if(!string.isBlank(profile_id)){
            query += ' and ProfileId = \''+profile_id+'\'';
        }
        //query += ' and Layout.Name = \''+'中文区块'+'\'';
        query += ' order by LastModifiedDate desc ';
        system.debug('query='+query);
        string s = ToolingQuery(query);
        if(string.isBlank(s)){
            system.debug('s is blank');
            return null;
        }else{
            Map<string,object> mso = (Map<string,object>)JSON.deserializeUntyped(s);
        
            if(integer.valueOf(mso.get('size')) > 0){
                List<object> records = ((List<object>)mso.get('records'));
            
                mso = (Map<string,object>)(records[0]);
                return string.valueOf(((Map<string,object>)(mso.get('Layout'))).get('Name'));
            }else{
                return null;
            }
        }
        
        
        
    }
    
    public static string ToolingQuery(string query){
        
        system.debug('query='+query);
        String baseURL = 'callout:SF_Rest_API/services/data/v41.0/tooling/query?q='+ query.replace(' ', '+');
        System.debug('baseURL = ' + baseURL);
        HttpResponse resp = null;
        HttpRequest req = new HttpRequest();         
        req.setMethod('GET');
        
        req.setHeader('Authorization', 'Bearer ' + UserInfo.getsessionid());  //deloitte-zhj 20231117 PIPL
        //req.setEndpoint(baseURL); 
        req.setEndpoint(baseURL); 
        
        Http client = new Http();    
        resp = client.send(req);
        system.debug('resp = ' + resp);
        system.debug(resp.getStatus());
        system.debug(resp.getStatusCode());
        if(resp.getStatus() == 'OK'){
            string s = resp.getBody();
            system.debug(resp.getBody());
            return s;
        }else{
            system.debug('status is not ok,error:'+resp.getBody());
            return null;
        }
        
    }
    
    public static List<Metadata.LayoutSection> GetLayoutSections(string object_name, string layout_name){
        List<String> componentNameList = new List<String>{object_name+'-'+layout_name};
        //通过Metadata.Operations.retrieve获取metadata
        //Metadata.Layout -> Metadata.LayoutSection -> Metadata.LayoutColumn objects -> Metadata.LayoutItem objects
        List<Metadata.Metadata> componentList = Metadata.Operations.retrieve(Metadata.MetadataType.Layout, componentNameList);
        if(componentList?.size() > 0){
            Metadata.Layout layout = (Metadata.Layout) componentList.get(0);
            List<Metadata.LayoutSection> layoutSectionList = layout.layoutSections;
            return layoutSectionList;
        }
        else{
            return null;
        }
        
    }
}