高章伟
2023-03-03 d8dc84a3d56df839895f1c417a4d9cbee763d262
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
/*
 * Author: Mingjie Yin
 * Created Date: 02/07/2022
 * Purpose: Utility class for describe layouts
 * Test Class: NewAndEditCaseController
 * History: 
 *      02/07/2022 - Mingjie Yin - Initial Code.
 * 
 * */
global without sharing class NewAndEditCaseController {
    public List <LayoutDescriberHelper.LayoutSection > layoutSections{set;get;}
    public String awsToken{set;get;}
    public static Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    public static String sobjectTypeValue = 'Case';
    public Boolean isNewMode{set;get;}
    public Boolean isCloneMode{protected set;get;}
    public String rtTypeId {get; set;}
    public String AWSDataId{set;get;}
    public String contactId{set;get;}//For Lookup field
    public List<String> encryptedAPIList{set;get;}   
    public String staticResource {get; set;}
    public String staticResourceContact {get; set;}
    public String requiredFieldAPIListStr {get; set;}
    public String fieldAPIToLabelMapStr {get; set;}
    public String Input_Required_Field_Msg{set;get;}
    public String PIPL_Name_Label{set;get;}
    public String PIPL_Input_Account_Error_Msg{set;get;}
    public String sobjectPrefix{set;get;}
    public String sobjecttypeForFrontEnd{set;get;}
    public String contactsInfo {set;get;}//key sfid;value awsid
    public String layoutSectionsStr {get; set;}
    public final string ApiPrefix{get;private set;} //Add By Yin Mingjie 20220404
    public Map<string,string> AWSToSobjectEncryptedMap{get;private set;}
    public string AWSToSobjectEncryptedMapJson{get{return JSON.serialize(AWSToSobjectEncryptedMap);}}
    public String sfRecordIdForEdit{set;get;}//Add By LiJun for Edit Record from NFM609, 20220510
    public String VLookUpFieldsJson{get;private set;}
    //zhj MEBG新方案改造 2022-11-29 start
    public String staticResourceV2 {get; set;}
    //zhj MEBG新方案改造 2022-11-29 end
    public NewAndEditCaseController(ApexPages.StandardController controller) {
        isNewMode = true;
        isCloneMode = false;
        Input_Required_Field_Msg = Label.Input_Required_Field_Msg;
        PIPL_Name_Label = Label.PIPL_Name_Label;
        PIPL_Input_Account_Error_Msg = label.PIPL_Input_Account_Error_Msg;
        sobjecttypeForFrontEnd = sobjectTypeValue;
        //获取所有字段
        List<String> fieldList = new List<String>(Schema.getGlobalDescribe().get('Case').getDescribe().fields.getMap().keyset());  
        // Add fields to controller. This is to avoid the SOQL error in visualforce page
        Map<string,string> mso = ApexPages.currentPage().getParameters();
        if(mso != null && mso.containsKey('newclone')){
            isCloneMode = true;
        }
        if (!Test.isRunningTest()) {
            controller.addFields(fieldList);
        }
        SObject obj = controller.getRecord();        
        if(obj.Id != null){
            //更新
            isNewMode = false;
            Case caseData = [select Id,RecordTypeId,AWS_Data_Id__c,ContactId,Contact.AWS_Data_Id__c from Case where id =: obj.Id];
            rtTypeId = caseData.RecordTypeId;
            AWSDataId = caseData.AWS_Data_Id__c;
            sfRecordIdForEdit = obj.Id;//Add By LiJun for Edit Record from NFM609, 20220510
            System.debug('AWSDataId=' + AWSDataId);
            Map<String,String> sfIdToAWSIdMap = new Map<String,String>();
            if(caseData.ContactId != null){
                sfIdToAWSIdMap.put(String.valueof(caseData.ContactId).subString(0,15),caseData.Contact.AWS_Data_Id__c);
            }
            // sfIdToAWSIdMap.put(String.valueof(caseData.ContactId).subString(0,15),caseData.Contact.AWS_Data_Id__c);
            
            contactsInfo = JSON.serialize(sfIdToAWSIdMap);
        }else{
            //新建
            // rtTypeId = ApexPages.currentPage().getParameters().get('RecordType');
            AssignValueFromUrl(mso,controller.getRecord());
            rtTypeId = mso.get('RecordType');
            obj.put('OwnerId',UserInfo.getUserId());
        }
        LayoutDescriberHelper.LayoutWrapper LayoutWrapperValue = LayoutDescriberHelper.describeSectionWithFieldsWrapper(rtTypeId, 'Case','classic');
        layoutSections = LayoutWrapperValue.layoutSections;
        List<String> requiredFieldAPIList = LayoutWrapperValue.requiredFieldAPIList;
        Map<String,String> fieldAPIToLabelMap = LayoutWrapperValue.fieldAPIToLabelMap;
        requiredFieldAPIListStr = JSON.serialize(requiredFieldAPIList);
        fieldAPIToLabelMapStr = JSON.serialize(fieldAPIToLabelMap);
        PIHelper.PIIntegration piIntegration = PIHelper.getPIIntegrationInfo('Case');
        staticResource = JSON.serialize(piIntegration);
        staticResourceContact = JSON.serialize(PIHelper.getPIIntegrationInfo('Contact'));
        encryptedAPIList = piIntegration.PIFields;
        sobjectPrefix = piIntegration.sobjectPrefix;
        layoutSectionsStr = JSON.serialize(layoutSections);
        AWSToSobjectEncryptedMap = new Map<String,String>();
        
        //获取lookup字段
        List<String> VLookUpFields = new List<String>();
        for (LayoutDescriberHelper.LayoutSection ls : layoutSections) {
            for (LayoutDescriberHelper.LayoutField lf : ls.layoutFields) {
                if (lf.fieldAPI != '' && lf.fieldType == 'reference') {
                    VLookUpFields.add(lf.fieldAPI);
                }
            }
        }
        VLookUpFieldsJson = Json.serialize(VLookUpFields);
        for (PI_Field_Policy_Detail__c PIDetail : piIntegration.PIDetails) {
            AWSToSobjectEncryptedMap.put(PIDetail.AWS_Field_API__c, PIDetail.SF_Field_API_Name__c);
        }
        //zhj MEBG新方案改造 2022-11-29 start
        staticResourceV2 = JSON.serialize(PIHelper.getPIIntegrationInfo('CaseV2'));
        //zhj MEBG新方案改造 2022-11-29 end
    }
    global class Response{
        public String recordId{set;get;}
        public String message{set;get;}
        public String status{set;get;}
    }
    @RemoteAction
    global static Response saveCase(String caseJson,String transId,Boolean isNew) {
        System.debug('Case Info:' + JSON.serialize(caseJson));
        //1. Prepare the payload for  Case
        Schema.SObjectType caseSchema = schemaMap.get(sobjectTypeValue);
        Map<String, Schema.SObjectField> fieldAPIToTypeMap = caseSchema.getDescribe().fields.getMap();
        Map<String,Object> fieldValueMap = (Map<String,Object>)JSON.deserializeUntyped(caseJson);
        Case caseInfo = new Case();
        //自定义格式转换
        for (String fieldAPI: fieldValueMap.keySet()) {
            system.debug('field API'+fieldAPI);
            if(!fieldAPIToTypeMap.containskey(fieldAPI)){
                continue;
            }
            Schema.DisplayType fielddataType = fieldAPIToTypeMap.get(fieldAPI).getDescribe().getType();  
            String fieldValue = String.valueOf(fieldValueMap.get(fieldAPI)); 
            if(String.valueOf(fielddataType)=='DATE'){
                caseInfo.put(fieldAPI,(String.isBlank(fieldValue)||String.isEmpty(fieldValue))? null:Date.valueOf(fieldValue.replace('/', '-')));              
                // caseInfo.put(fieldAPI, Date.valueOf(String.valueOf(fieldValueMap.get(fieldAPI)).replace('/', '-')));
            }else if(String.valueOf(fielddataType)=='DATETIME'){
                if(String.isNotBlank(fieldValue)&&fieldValue.contains('T')){
                    fieldValue = fieldValue.replace('T',' ');
                    caseInfo.put(fieldAPI, Datetime.valueOfGmt(fieldValue));
                }else{
                    caseInfo.put(fieldAPI, null);
                }  
                // String dt = String.valueOf(fieldValueMap.get(fieldAPI));
                // if(String.isNotBlank(dt)&&dt.contains('T')){
                //     dt = dt.replace('T',' ');
                //     caseInfo.put(fieldAPI, Datetime.valueOfGmt(dt));
                // }             
            // }else if(String.valueOf(fielddataType)=='Number'||String.valueOf(fielddataType)=='DOUBLE' ){
            //     caseInfo.put(fieldAPI, Decimal.valueOf(String.valueOf(fieldValueMap.get(fieldAPI))));
            }else if(String.valueof(fielddataType)=='CURRENCY'|| String.valueof(fielddataType)=='PERCENT'||String.valueOf(fielddataType)=='Number'||String.valueOf(fielddataType)=='DOUBLE' ){
                caseInfo.put(fieldAPI, (String.isBlank(fieldValue)||String.isEmpty(fieldValue))?null:Decimal.valueOf(fieldValue.replace(',', ''))); 
            } else if(String.valueof(fielddataType)=='BOOLEAN'){
                caseInfo.put(fieldAPI, fieldValueMap.get(fieldAPI));
            }else {
                caseInfo.put(fieldAPI, String.valueOf(fieldValueMap.get(fieldAPI)));
            }                  
        }
 
        System.debug('caseInfo='+caseInfo);
        System.debug('caseInfo.Account__c='+caseInfo.Account__c);
        if (!String.isBlank(caseInfo.ContactId) && (String.isBlank(caseInfo.Account__c) || Id.valueOf(caseInfo.Account__c).to15() =='000000000000000')) {
            if (Id.valueOf(caseInfo.ContactId).to15() !='000000000000000') {
                Contact c = [select id,AccountId from Contact where id = :caseInfo.ContactId];
                caseInfo.Account__c = c.AccountId;
            }
        }
        
        //2. Save Record Process
        String status = 'success';    
        Response resp = new Response();
        Savepoint sp = Database.setSavepoint();
        String rid = '';
        String awsDataId = '';
        String sfRecordId = '';
        Boolean isClone = false;
        try{
            System.debug('abcde');
            awsDataId = (String)caseInfo.get('AWS_Data_Id__c');
            sfRecordId = (String)caseInfo.get('Id');
            System.debug('awsDataId = ' + awsDataId);
            Case[] cases = [select id from Case where AWS_Data_Id__c =:awsDataId or id =:sfRecordId];
 
            if(!isNew){
                isClone = cases.size() == 0;
            }
            system.debug('isClone'+isClone + ' isNew'+isNew);
            if(isNew || isClone){
                System.debug('caseInfozhj = ' + caseInfo);
                if(!Test.isRunningTest()){
                    insert caseInfo;
                }
            }else{
                System.debug('into update');
                // String awsDataId = (String)caseInfo.get('AWS_Data_Id__c');
                // System.debug('awsDataId = ' + awsDataId);
                // Case[] cases = [select id from Case where AWS_Data_Id__c =:awsDataId];
                System.debug('cases ========================= ' + cases);
                System.debug('Cases[0].id = ' + cases[0].id);
                caseInfo.put('Id',cases[0].id);//For testing;
                if(!Test.isRunningTest()){
                    update caseInfo;
                }
            }
            rid=caseInfo.Id;
            PIHelper.saveTransLog(sobjectTypeValue,(String)caseInfo.get('AWS_Data_Id__c'),rid,transId,caseJson ,status,'');
            resp.recordId = caseInfo.Id;
            resp.message = '';
            resp.status = status;
            System.debug('resp from sfdx back-end' + 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,(String)caseInfo.get('AWS_Data_Id__c'),rid,transId, caseJson ,status,e.getMessage()+e.getStackTraceString());
            return resp;
            
        }catch(Exception e) {
            System.debug('into catch'+e.getMessage());
            Database.rollback(sp);
            status = 'fail';
            PIHelper.saveTransLog(sobjectTypeValue,(String)caseInfo.get('AWS_Data_Id__c'),rid,transId,caseJson,status,e.getMessage());
            resp.message = e.getMessage();            
            resp.status = status;
            return resp;
        }
    }
 
    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());
            }
        }
    }
}