Li Jun
2022-04-19 2f183a6b0a83ec3f7d35375d5d25d200efc2a3e1
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
global abstract class NewAndEditBaseController {
 
    public List <LayoutDescriberHelper.LayoutSection > layoutSections{set;get;}
    public String layoutSectionsStr {get; set;}//for dynamic add readonly attribute 20220316 by Mingjie
    public String awsToken{set;get;}
    public static Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    public String sobjectTypeValue {private set; get;}
    public Boolean isNewMode{set;get;}
    public Boolean isCloneMode{protected set;get;}
    public String rtTypeId {get; set;}
    public String AWSDataId{set;get;}
    public String CurrentUserId{private set;get;}
    public String CurrentUserName{private set;get;}
 
    // 当前对象所有的加密字段集合
    public List<String> encryptedAPIList{private set;get;}
 
    // 当前页面中的加密字段集合
    public List<String> layoutEncryptedAPIList{private set;get;}
    //fieldLabel fieldAPI
    public String requiredFieldAPIListStr {get;private set;}
    public String fieldApiListStr {get;private set;}
 
 
    public String fieldAPIToLabelMapStr {get;private set;}
    public String staticResource {get; set;}
    public string SobjectName{get{return sobjectTypeValue;}}
    public string SobjectLabel{get;private set;}
 
    public Map<string,string> AWSToSobjectMap{
        get{
            Map<string,string> temp = new Map<string,string>();
            temp.putAll(AWSToSobjectNonEncryptedMap);
            temp.putAll(AWSToSobjectEncryptedMap);
            return temp;
        }
    }
    public string AWSToSobjectMapJson{get{return JSON.serialize(AWSToSobjectMap);}}
 
    public Map<string,string> AWSToSobjectNonEncryptedMap{get;private set;}
    public string AWSToSobjectNonEncryptedMapJson{get{return JSON.serialize(AWSToSobjectNonEncryptedMap);}}
    public string AWSToSobjectNonEncryptedMapKeySet{get{return JSON.serialize(new List<string>(AWSToSobjectNonEncryptedMap.keySet()));}}
 
    public Map<string,string> AWSToSobjectEncryptedMap{get;private set;}
    public string AWSToSobjectEncryptedMapJson{get{return JSON.serialize(AWSToSobjectMap);}}
 
    public final string ApiPrefix{get;private set;} 
 
    public String sobjectPrefix{get;private set;}
    public String SaveAndNewButtonUrl{get;private set;}
    @TestVisible
    public List<String> VLookUpFields{get;private set;}
    public String VLookUpFieldsJson{get{return Json.serialize(VLookUpFields);}}
    public List<String> LookUpOverrideFields{get;private set;}
    public string LookUpOverrideFieldsMapJson{get; set;}
    public string recordId{get;private set;}
    
    public NewAndEditBaseController(){
        ApiPrefix = 'PIBackApi';
        AWSToSobjectNonEncryptedMap = new Map<string,string>();
        AWSToSobjectEncryptedMap = new Map<string,string>();
        VLookUpFields = new List<String>();
        layoutEncryptedAPIList = new List<String>();
        LookUpOverrideFields = new List<String>();
        CurrentUserName = UserInfo.getName();
        CurrentUserId = UserInfo.getUserId();
    }
 
    @TestVisible protected virtual void Init(SObject obj){
        sobjectTypeValue = obj.getSObjectType().getDescribe().getName();
        SobjectLabel = obj.getSObjectType().getDescribe().getLabel();
        system.debug('obj='+sobjectTypeValue);
        
        isNewMode = true;
        isCloneMode = false;
        List<Sobject> lso = Database.query('select id from RecordType where SobjectType = :sobjectTypeValue');
        Map<string,string> mso = ApexPages.currentPage().getParameters();
        if(mso != null && mso.containsKey('newclone')){
            isCloneMode = true;
        }
        if(obj.Id != null){
            recordId = obj.Id;
            isNewMode = false;
            string sql = 'select Id';
            if (lso.size()>0) {
                sql += ',RecordTypeId';
            }
            sql += GenerateReferenceSql()+',AWS_Data_Id__c from '+sobjectTypeValue+' where id =\''+obj.Id+'\' ';
            System.debug('sql='+sql);
            Sobject leadData = Database.query(sql);
            if (lso.size()>0){
                rtTypeId = (String)leadData.get('RecordTypeId');
            }
            
            AWSDataId = (String)leadData.get('AWS_Data_Id__c');
 
            Map<String,String> sfIdToAWSIdMap = new Map<String,String>();
            for (string f : LookUpOverrideFields) {
                object o = leadData.get(f);
                System.debug('leadData.get('+f+')='+o);
                if (!String.isBlank(String.valueOf(o))) {
                    sfIdToAWSIdMap.put(String.valueOf(o).subString(0,15), String.valueOf(leadData.getSobject(GetReferenceField(f)).get('AWS_Data_Id__c')));
                }
            }
           
            LookUpOverrideFieldsMapJson = JSON.serialize(sfIdToAWSIdMap);
 
 
        }else{
            rtTypeId = ApexPages.currentPage().getParameters().get('RecordType');
        }
        PIHelper.PIIntegration piIntegration = PIHelper.getPIIntegrationInfo(sobjectTypeValue);
        //layoutEncryptedAPIList = piIntegration.PIFields;
        encryptedAPIList = piIntegration.PIFields;
        staticResource = JSON.serialize(piIntegration);
        sobjectPrefix = piIntegration.sobjectPrefix;
        SaveAndNewButtonUrl = string.format('/{0}/e', new string[]{sobjectPrefix});
        if (lso.size() > 1) {
            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});
        }
 
        for (PI_Field_Policy_Detail__c PIDetail : piIntegration.PIDetails) {
            
            AWSToSobjectNonEncryptedMap.put(PIDetail.AWS_Field_API__c, PIDetail.SF_Field_API_Name__c);
            AWSToSobjectEncryptedMap.put(PIDetail.AWS_Encrypted_Field_API__c, PIDetail.SF_Field_Encrypted_API__c);
        }
        System.debug(new List<string>(AWSToSobjectNonEncryptedMap.keySet()));
        system.debug('AWSToSobjectNonEncryptedMapJson=');
        system.debug(AWSToSobjectNonEncryptedMapJson);
        try{
            LayoutDescriberHelper.LayoutWrapper LayoutWrapperValue = LayoutDescriberHelper.describeSectionWithFieldsWrapper(rtTypeId, sobjectTypeValue,'classic');
            layoutSections = LayoutWrapperValue.layoutSections;         
            List<String> requiredFieldAPIList = LayoutWrapperValue.requiredFieldAPIList;
            Map<String,String> fieldAPIToLabelMap = LayoutWrapperValue.fieldAPIToLabelMap;
            List<String> fieldApiList = new List<String>(); 
            for (LayoutDescriberHelper.LayoutSection ls : layoutSections) {
                for (LayoutDescriberHelper.LayoutField lf : ls.layoutFields) {
                    if (lf.fieldAPI != '') {
                        System.debug('lf.fieldAPI='+lf.fieldAPI+' fieldType='+lf.fieldType);
                        fieldApiList.add(lf.fieldAPI);
                        if (lf.fieldType == 'reference') {
                            VLookUpFields.add(lf.fieldAPI);
                        }
 
                        //在view解密section中只需显示当前layout中的加密字段
                        if (encryptedAPIList.contains(lf.fieldAPI)) {
                             layoutEncryptedAPIList.add(lf.fieldAPI);
                         }
                    }
                }
            }
            layoutSectionsStr = JSON.serialize(layoutSections); //for dynamic add readonly attribute 20220316 by Mingjie
            fieldApiListStr = JSON.serialize(fieldApiList);
            fieldAPIToLabelMapStr = JSON.serialize(fieldAPIToLabelMap);
            requiredFieldAPIListStr = JSON.serialize(requiredFieldAPIList);
            //awsToken = AWSServiceTool.getAWSToken();
        }catch(Exception e){
            layoutEncryptedAPIList = piIntegration.PIFields;
            system.debug('Exception from get layout service:'+e.getmessage());
        }
    }
 
    public static string GetReferenceField(string f){
        if (f.endsWith('__c')) {
            return f.substring(0,f.length()-1)+'r';
        }
        else if(f.endsWith('Id') || f.endsWith('id') || f.endsWith('ID')) {
            return f.substring(0, f.length()-2);
        }
        else{
            return f;
        }
    }
 
    public string GenerateReferenceSql(){
        string res ='';
        for (string f : LookUpOverrideFields) {
            res += ','+f+','+GetReferenceField(f)+'.AWS_Data_Id__c';
        }
        return res;
    }
 
    global class Response{
        public String recordId{set;get;}
        public String message{set;get;}
        public String status{set;get;}
    }
 
    @RemoteAction
    global static Response save(Sobject sobj, String leadJson,String transId,Boolean isNew) {
        string sobjectTypeValue = sobj.getSObjectType().getDescribe().getName();
        System.debug('sobjectTypeValue:'+sobjectTypeValue+' Info:' + JSON.serialize(leadJson));
        System.debug('json length='+leadJson.length());
        System.debug('leadJson---------'+leadJson);
        System.debug('isNew---------'+isNew);
        //1. Prepare the payload for  Lead
        Schema.SObjectType leadSchema = schemaMap.get(sobjectTypeValue);
        Map<String, Schema.SObjectField> fieldAPIToTypeMap = leadSchema.getDescribe().fields.getMap();
        Map<String,Object> fieldValueMap = (Map<String,Object>)JSON.deserializeUntyped(leadJson);
        
        system.debug('enter Foo');
        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';    
        Response resp = new Response();
        String awsDataId = '';
        Savepoint sp = Database.setSavepoint();
        Sobject leadInfo = sobj;
        try{
            
            for (String fieldAPI: fieldValueMap.keySet()) {
                system.debug('field API='+fieldAPI);
                
                if(invalid_fields.contains(fieldAPI)){
                    system.debug(fieldAPI+' is invalid');
                    continue;
                }
                
                if(!fieldAPIToTypeMap.containskey(fieldAPI)){
                    continue;
                }
                Schema.DisplayType fielddataType = fieldAPIToTypeMap.get(fieldAPI).getDescribe().getType();  
                String fieldValue = String.valueOf(fieldValueMap.get(fieldAPI)); 
                system.debug('Field Type:'+fielddataType+' field Value='+fieldValue);
                if(String.valueOf(fielddataType)=='DATE'){
                    leadInfo.put(fieldAPI,(String.isBlank(fieldValue)||String.isEmpty(fieldValue))? null:Date.valueOf(fieldValue.replace('/', '-')));              
                }else if(String.valueOf(fielddataType)=='DATETIME'){
                    if(String.isNotBlank(fieldValue)&&fieldValue.contains('T')){
                        fieldValue = fieldValue.replace('T',' ');
                        leadInfo.put(fieldAPI, Datetime.valueOfGmt(fieldValue));
                    //20220405 By ChenYanan Start
                    }else if(String.isNotBlank(fieldValue))  {
                        fieldValue = fieldValue.replace('/', '-') + ':00';
                        leadInfo.put(fieldAPI, Datetime.valueOf(fieldValue));
                    //20220405 By ChenYanan End
                    }else{
                        leadInfo.put(fieldAPI, null);
                    }                    
                }else if(String.valueof(fielddataType)=='CURRENCY'|| String.valueof(fielddataType)=='PERCENT'||String.valueOf(fielddataType)=='Number'||String.valueOf(fielddataType)=='DOUBLE' ){
                    leadInfo.put(fieldAPI, (String.isBlank(fieldValue)||String.isEmpty(fieldValue))?null:Decimal.valueOf(fieldValue.replace(',', ''))); 
                } else if(String.valueof(fielddataType)=='BOOLEAN'){
                    leadInfo.put(fieldAPI, fieldValueMap.get(fieldAPI));
                }else {
                    leadInfo.put(fieldAPI,fieldValue);
                }                  
            }
 
            system.debug('for (String fieldAPI: fieldValueMap.keySet()) end');
            awsDataId = (String)leadInfo.get('AWS_Data_Id__c');
            if (string.isBlank(awsDataId)) {
                throw new DMLException('更新时AWS_Data_Id__c不能为空');
            }
            System.debug('awsDataId = ' + awsDataId);
            Sobject[] sobjects = Database.query('select id from '+sobjectTypeValue+' where AWS_Data_Id__c =:awsDataId');
            
            
            if(!isNew){
                isClone = sobjects.size() == 0;
            }
            System.debug('isNew---------'+isNew);
                       
            if(isNew || isClone){
                System.debug('leadInfozhj = ' + leadInfo);
                if(!Test.isRunningTest()){
                    insert leadInfo;
                }
            }else{
                System.debug('into update');
                System.debug('sobjects[0].id = ' + sobjects[0].id);
                leadInfo.put('Id',sobjects[0].id);//For testing;
                if(!Test.isRunningTest()){
                    update leadInfo;
                }
            }
            // //saveTransLog(transId, leadInfo.AWS_Data_Id__c, status, '');
            // Transaction_Log__c traLog = new Transaction_Log__c();
            // // AWS_Data_Id__c=AWSDataId,TransId__c=transId,JsonContent__c=leadJson,Status__c=status
            // traLog.AWS_Data_Id__c = AWSDataId;
            // traLog.TransId__c = transId;
            // traLog.JsonContent__c = leadJson;
            // traLog.Status__c = status;
            // insert traLog;
            resp.recordId = leadInfo.Id;
            // resp.message = 'success saveLead';
            resp.status = status;
            PIHelper.saveTransLog(sobjectTypeValue,awsDataId,leadInfo.Id,transId, leadJson ,status,'');
            // (String module,String awsDataId,String sfId, String transId,String content,String status,String respMsg)
            System.debug('respzhj = ' + resp);
            return resp;
 
        } catch(DmlException e) {
            Integer index = 0;
            System.debug(e.getNumDml());
            System.debug(e.getDmlFields(index));
            System.debug(e.getDmlId(index));
            System.debug(e.getDmlIndex(index));
            System.debug(e.getDmlMessage(index));
            System.debug(e.getDmlStatusCode(index));
            System.debug(e.getDmlType(index));
            system.debug(e.getMessage());
            system.debug(e.getStackTraceString());
 
            System.debug('into catch'+e.getMessage());
            Database.rollback(sp);
            resp.status = 'Exception';
            resp.message ='保存失败,原因:'+ e.getDmlMessage(index);
            PIHelper.saveTransLog(sobjectTypeValue,awsDataId,leadInfo.Id,transId, leadJson ,status,e.getMessage()+e.getStackTraceString());
            return resp;
            
        }catch(Exception e) {
            System.debug('into catch'+e.getMessage());
            Database.rollback(sp);
            resp.status = 'Exception';
            resp.message = e.getMessage()+e.getStackTraceString();
            PIHelper.saveTransLog(sobjectTypeValue,awsDataId,leadInfo.Id,transId, leadJson ,status,resp.message);
            // PIHelper.saveTransLog(sobjectTypeValue,(String)leadInfo.get('AWS_Data_Id__c'),transId, leadJson,status,e.getStackTraceString());
            return resp;
        }
    }
    
    public static List<string> GetInvalidFieldFromLayout(string rtid, string sobject_name){
        List<string> ls = new List<string>();
        string[] only_type = new string[]{'QIS_Report__c'};
        if(!only_type.contains(sobject_name)){
            system.debug('not allow');
            return ls;
        }
        
        List<Metadata.LayoutSection> sections = MetaDataUtility.GetRecordTypePageLayout(rtid, sobject_name);
        
        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;
    }
}