李金换
2023-04-21 cc7487a59bd4b0fa5bed1dd59f6d0565ace81b8b
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
@RestResource(urlMapping = '/NFM206/*')
global with sharing class NFM206Rest {
    
    global class GeDatas {
        public NFMUtil.Monitoring Monitoring;
        public NFM206Rest.GeData[] GeData;
    }
 
    global class GeData {
        public String NotesApprovedNo;                    // 合同申请决裁编码
        public String Assistant_Applied_Date;             // 助理:合同DB申请日(SPO的起草日期)
        public String Opportunity_No;                     // 询价编码
        public String OCM_Agent1_Price_DB;                // OCM-Agent1(合同DB)_元(SPO的合同金额)
        public String Contract_DB_SalesDept_complite_day; // 销售部:合同DB审批结束日
        public String Contract_DB_complite_day;           // 合同DB审批结束日
        public String Contract_DB_request_reason;         // 合同DB特价申请原因(SPO的合同特殊申请时的备注)
        public String ApprovedType;                       // User操作类型  3:撤回申请
        public String ContractType;                       // 业务申请类型 1:新建合同   2.更改合同   3.撤销合同
        public String Closing_Bid_Date;                   // 中标日期
        public String SPOApprovedQuote;                   //合同审批完成的报价
        //songxiaoqi ----------start
        public String IsTermination;                     //true代表合同终止
        public String SealDate;                          // 电子签日期
        //songxiaoqi-----------end
        // 2022-10-19 SWAG-CKB5S6 xxf start
        public String IsEsign;                           //是否电子签 1:电子签合同 0:非电子签合同
        // 2022-10-19 SWAG-CKB5S6 xxf end
    }
 
    @HttpPost
    global static void execute() {
        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();
        GeDatas ges = (GeDatas) JSON.deserializeStrict(strData, GeDatas.class);
 
        if (ges == null ) {
            return;
        }
 
        NFMUtil.Monitoring Monitoring = ges.Monitoring;
        if (Monitoring == null) {
            return;
        }
 
        BatchIF_Log__c rowData = NFMUtil.saveRowData(Monitoring, 'NFM206', ges.GeData);
        // 2022-10-15 SWAG-CG2A7S 同一合同多条询价自动win时的拆分处理 ssm start
        if (String.isBlank(rowData.Log__c) == false) {
            if (ges.GeData.size() > 1) {
                rowData.RowDataFlg__c = false;
                update rowData;
                Integer index = 1;
                String msg_num = Monitoring.MessageGroupNumber;
                for (NFM206Rest.GeData data : ges.GeData) {
                    NFM206Rest.GeData[] spGeData = new NFM206Rest.GeData[1];
                    spGeData[0] = data;
                    Monitoring.MessageGroupNumber = msg_num + '-' + index;
                    index ++;
                    BatchIF_Log__c spRowData = NFMUtil.saveRowData(Monitoring, 'NFM206', spGeData);
                    Database.executeBatch(new LogAutoSendBatch(spRowData.Id), 1);
                }
            } else {
                executefuture(rowData.Id);
            }
        }
        // 2022-10-15 SWAG-CG2A7S 同一合同多条询价自动win时的拆分处理 ssm start
 
        // JSONを戻す
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        res.statusCode = 200;
        //String jsonResponse = '{"status": "Success", "Message":'  + gedata + '}';
        String jsonResponse = '{"status": "Success", "Message":""}';
        res.responseBody = blob.valueOf(jsonResponse);
        return;
    }
 
    @future
    global static void executefuture(String rowData_Id) {
        main(rowData_Id);
    }
 
    global static void main(String rowData_Id) {
        Integer batch_retry_max_cnt = Integer.valueOf(System.Label.batch_retry_max_cnt);
        BatchIF_Log__c rowData      = [Select Id, Name, Log__c, ErrorLog__c, Log2__c, Log3__c, Log4__c, Log5__c, Log6__c, Log7__c, Log8__c, Log9__c, Log10__c, Log11__c, Log12__c, MessageGroupNumber__c, retry_cnt__c from BatchIF_Log__c where RowDataFlg__c = true and Id = :rowData_Id];
        String logstr               = rowData.MessageGroupNumber__c + ' start\n';
        BatchIF_Log__c iflog        = new BatchIF_Log__c();
        iflog.Type__c               = 'NFM206';
        iflog.MessageGroupNumber__c = rowData.MessageGroupNumber__c;
        iflog.Log__c                = logstr;
        iflog.ErrorLog__c           = '';
        insert iflog;
        // Integer  index = rowData.Log__c.indexOf('SealDate');
        // String SealDate = rowData.Log__c.subString(index+11,index+19);
        // system.debug('SealDate = '+ SealDate+'rowData.Log__c = ' +rowData.Log__c);
        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        List<GeData> geDataList = (List<GeData>) JSON.deserialize(rowDataStr, List<GeData>.class);
        if (geDataList == null || geDataList.size() == 0) {
            return;
        }
 
        Savepoint sp = Database.setSavepoint();
        try { // 20220916 ljh SWAG-CG2A7S 注释 
            List<GeData> accordList = new List<GeData>();
            List<String> opportunity_NoList = new List<String>();
            //合同必填字段验证
            for (GeData gda : geDataList) {
                if (String.isBlank(gda.Opportunity_No)) {
                    iflog.ErrorLog__c += 'Error! 询价编码不能为空。\n';
                    continue;
                }
 
                if (String.isBlank(gda.ApprovedType)) {
                    iflog.ErrorLog__c += 'Error! 合同申请类型不能为空 [ ' + gda.Opportunity_No + ' ]\n';
                    continue;
                }
                opportunity_NoList.add(gda.Opportunity_No);
                accordList.add(gda);
            }
 
            List<Opportunity> opportunityUpsertList = new List<Opportunity>();
            List<Opportunity> oppList = [Select Id ,
                                         Opportunity_No__c,
                                         SPOApprovedQuote__c, 
                                         Contract_DB_complite_day__c,
                                         SAP_Send_OK__c,
                                         Decided_Estimation__c,
                                         Estimation_Decision__c,
                                         Estimation_No__c,
                                         Competitor__c,
                                         Sign_Contract_Electronically__c,
                                         StageName,
                                         CloseDate
                                         from Opportunity
                                         where Opportunity_No__c in : opportunity_NoList];
 
            Map<String, Opportunity> oppMap = new Map<String, Opportunity>();
 
            for (Opportunity opp : oppList) {
                oppMap.put(opp.Opportunity_No__c, opp);
            }
 
            for (GeData gda : accordList) {
                Opportunity opportunityInfo = new Opportunity();
 
                if (oppMap.containsKey(gda.Opportunity_No)) {
                    opportunityInfo = oppMap.get(gda.Opportunity_No);
                } else {
                    iflog.ErrorLog__c += '询价编码不存在[ ' + gda.Opportunity_No + ' ]\n';
                    continue;
                }
                logstr += '询价编码:' + gda.Opportunity_No + ' 用户操作类型:' + gda.ApprovedType + ' 合同申请类型:' + gda.ContractType ;
 
                if (gda.ApprovedType == '3' && (gda.ContractType == '3' || gda.ContractType == '2')) {
                    continue;
                }
                opportunityInfo.IF_Submit__c = false;
                opportunityInfo.if_Interface_Lock__c = false;
                opportunityInfo.Contract_Authorize_Lock__c = false;
                // 2022-11-16 ssm 增加206接口判断,撤销合同时不设置电子签时间和自动win
                if (gda.ApprovedType != '3' && gda.ContractType != '3' && String.isNotBlank(gda.SealDate)) {
                    opportunityInfo.Agency_Contract_Date1__c = NFMUtil.parseStr2Date(gda.SealDate);
                    // 收到日期时自动win
                    opportunityInfo.SAP_Send_OK__c = true;
                    //20221208 you DB202212018969 给预测发货日赋值
                    Date SAP_Send_OKDay = Date.today();
                    if(SAP_Send_OKDay > opportunityInfo.CloseDate){
                      opportunityInfo.CloseDate = Date.today().addDays(1); 
                    }
                   
                }
                
                if (((gda.ContractType == '3' && gda.ApprovedType != '3') ||
                        (gda.ApprovedType == '3' && gda.ContractType == '1'))
                        && opportunityInfo.StageName == '引合') {
 
                    //新申请合同的撤销 或者最终取消合同时,清空合同信息
                    opportunityInfo.NotesApprovedNo__c                    = null;
                    opportunityInfo.Contract_DB_request_reason__c         = null;
                    opportunityInfo.Contract_DB_complite_day__c           = null;
                    opportunityInfo.Assistant_Applied_Date__c             = null;
                    opportunityInfo.Contract_DB_SalesDept_complite_day__c = null;
                    opportunityInfo.Contract_DB_Finalcomplite_day__c      = null;
                    opportunityInfo.SPOApprovedQuote__c                   = null;//add
                    opportunityInfo.Sign_Contract_Electronically__c       = false;
 
                    // 20211206 SWAG-C7P4XB 撤销合同时,如果当前询价等级为A1,退回到A start
                    if ('A1'.equals(opportunityInfo.Competitor__c)) {
                        opportunityInfo.Opportunity_stage__c = '确定了OLY参数';
                        opportunityInfo.Competitor__c = 'A';
                    }
                    // 20211206 SWAG-C7P4XB 撤销合同时,如果当前询价等级为A1,退回到A end
 
                    if (gda.ContractType == '3') {
                        opportunityInfo.Contract_Invalid_Date__c = NFMUtil.parseStr2Date(gda.Contract_DB_complite_day);
                    }
 
                } else if (gda.ContractType == '2' && gda.ApprovedType != '3') {
                    // 变更合同(未撤销)
                    opportunityInfo.Contract_DB_Finalcomplite_day__c = NFMUtil.parseStr2Date(gda.Contract_DB_complite_day);
                    opportunityInfo.Contract_Authorize_Lock__c = true;
 
                } else if (gda.ContractType == '1' && gda.ApprovedType != '3') {
                    // 新建合同(未撤销)
                    opportunityInfo.NotesApprovedNo__c = gda.NotesApprovedNo;
                    opportunityInfo.Contract_DB_request_reason__c = gda.Contract_DB_request_reason;
                    opportunityInfo.Contract_DB_complite_day__c = NFMUtil.parseStr2Date(gda.Contract_DB_complite_day);
                    opportunityInfo.Assistant_Applied_Date__c = NFMUtil.parseStr2Date(gda.Assistant_Applied_Date);
                    //opportunityInfo.Closing_Bid_Date__c  = NFMUtil.parseStr2Date(gda.Closing_Bid_Date); //SWAG-CCL6R7 2022-3-22 yjk 注释掉中标日逻辑
                    opportunityInfo.Contract_DB_SalesDept_complite_day__c = NFMUtil.parseStr2Date(gda.Contract_DB_SalesDept_complite_day);
                    opportunityInfo.Contract_Invalid_Date__c = null;
                    opportunityInfo.Contract_Authorize_Lock__c = true;
                    if (gda.Contract_DB_complite_day == null) {
                        opportunityInfo.if_Interface_Lock__c = true;
                    }
                    opportunityInfo.SPOApprovedQuote__c = gda.SPOApprovedQuote;//add
                    // 2022-10-19 SWAG-CKB5S6 xxf start
                    if(gda.IsEsign == '1'){//电子签合同:IsEsign='1'
                        opportunityInfo.Sign_Contract_Electronically__c = true;
                    }else if (gda.IsEsign == '0' || gda.IsEsign == null) {//非电子签合同:IsEsign='0'
                        opportunityInfo.Sign_Contract_Electronically__c = false;
                    }
                    // 2022-10-19 SWAG-CKB5S6 xxf end
                }
                //songxiaoqi ------start 2020/11/4 update 状态1是询价
                //传入true代表合同终止  StageName__c
 
                if (gda.IsTermination == 'true' && opportunityInfo.Estimation_Decision__c == true && gda.SPOApprovedQuote == opportunityInfo.Estimation_No__c && opportunityInfo.StageName == '引合') {
 
                    //决定报价deide
                    opportunityInfo.Estimation_Decision__c = false;
                    //清空确定备货确认日
                    opportunityInfo.Stock_Confrim_Date__c = null;
                    //取消win
                    opportunityInfo.SAP_Send_OK__c = false;
                    // 2022-05-30 取消win理由补充 ssm start
                    opportunityInfo.Reason_Cancel_WIN__c = System.Label.Opportunity_Cancel_WIN_ByAPI;
                    // 2022-05-30 取消win理由补充 ssm end
 
                    //撤销操作清空相关内容
                    opportunityInfo.NotesApprovedNo__c                    = null;
                    opportunityInfo.Contract_DB_request_reason__c         = null;
                    opportunityInfo.Contract_DB_complite_day__c           = null;
                    opportunityInfo.Assistant_Applied_Date__c             = null;
                    opportunityInfo.Contract_DB_SalesDept_complite_day__c = null;
                    opportunityInfo.Contract_DB_Finalcomplite_day__c      = null;
                    opportunityInfo.SPOApprovedQuote__c                   = null;
                    opportunityInfo.Sign_Contract_Electronically__c       = false;
                }
                //songxiaoqi -------end
 
                opportunityUpsertList.add(opportunityInfo);
            }
            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;// 20230419 ljh add
            if (opportunityUpsertList.size() > 0) {
                // 20220916 ljh SWAG-CG2A7S start
                // upsert opportunityUpsertList;
                // 20220916 ljh SWAG-CG2A7S start
                String logstrNew = '';
                Integer failedCount = 0;
                Integer failedCountEmail = 0;
                Map<String,String> errMap = new Map<String,String>();
                Map<String,String> errMapAll = new Map<String,String>();
                Database.SaveResult[] updateRepairResult = Database.update(opportunityUpsertList, false);
                for (Integer tIdx = 0; tIdx < updateRepairResult.size(); tIdx++) {
                    Database.SaveResult sr = updateRepairResult[tIdx];
                    System.debug('zheli:'+sr);
                    if (!sr.isSuccess()) {
                        failedCount += 1;
                        String errStr = '';
                        Database.Error emsg = sr.getErrors()[0];
                        errStr += '\n' + emsg.getMessage();
                        String eId = (String) opportunityUpsertList[tIdx].get('Id');
                        String SealDateStr = String.valueOf(opportunityUpsertList[tIdx].get('Agency_Contract_Date1__c'));
                        if ( String.isNotBlank(SealDateStr)  && !String.valueOf(emsg.getMessage()).contains('Future method cannot be called from a future or batch method')) {
                            failedCountEmail += 1;                            
                            errMap.put(eId,errStr);
                        }
                        errMapAll.put(eId,errStr);
                        logstr += '\n' + emsg.getMessage();
                        logstrNew = emsg.getMessage() + '\n' + emsg.getFields() + '\n' + logstrNew;
                    }
                }
                if(failedCount > 0){
                    Database.rollback(sp);
                    iflog.ErrorLog__c = logstrNew + '\n' + iflog.ErrorLog__c;
                    if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
                    if (rowData.retry_cnt__c < batch_retry_max_cnt) {
                        rowData.retry_cnt__c++;
                        LogAutoSendSchedule.assignOneMinute();
                    }
                    if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
                        rowData.ErrorLog__c =  logstrNew + rowData.ErrorLog__c + '错误次数已经超过自动收信设定的最大次数,请手动收信';
                    }
                    if(failedCountEmail > 0 && ((rowData.retry_cnt__c !=null && rowData.retry_cnt__c == batch_retry_max_cnt) || Test.isRunningTest())){
                        sendEmail(errMap,false);
                    }
                    if(failedCount > failedCountEmail && ((rowData.retry_cnt__c !=null && rowData.retry_cnt__c == batch_retry_max_cnt) || Test.isRunningTest())){
                        sendEmail(errMapAll,true);
                    }
                }else{
                    rowData.retry_cnt__c = 0;
                }
                // 20220916 ljh SWAG-CG2A7S end
            }
            logstr += '\nend';
            
        // 20220916 ljh SWAG-CG2A7S 注释 start
        } catch (Exception ex) {
            Database.rollback(sp);
            System.debug(Logginglevel.ERROR, 'NFM206_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
            System.debug(Logginglevel.ERROR, 'NFM206_' + rowData.MessageGroupNumber__c + ':' + ex.getStackTraceString());
            logstr += '\n' + ex.getMessage();
            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
 
            if (rowData.retry_cnt__c == null) rowData.retry_cnt__c = 0;
            if (rowData.retry_cnt__c < batch_retry_max_cnt) {
                rowData.retry_cnt__c++;
                LogAutoSendSchedule.assignOneMinute();
            }
            if (rowData.retry_cnt__c >= batch_retry_max_cnt) {
                rowData.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + rowData.ErrorLog__c + '错误次数已经超过自动收信设定的最大次数,请手动收信';
            }
        }
        // 20220916 ljh SWAG-CG2A7S 注释 end
        update rowData;
        iflog.Log__c = logstr;
        if (iflog.Log__c.length() > 131072) {
            iflog.Log__c = iflog.Log__c.subString(0, 131065) + ' ...';
        }
        if (iflog.ErrorLog__c.length() > 32768) {
            iflog.ErrorLog__c = iflog.ErrorLog__c.subString(0, 32760) + ' ...';
        }
        update iflog;
    }
 
    public static void sendEmail(Map<String,String> errMap,Boolean isAll){
        // 发送邮件内容
        List<Messaging.SingleEmailMessage> sendMails = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();   
 
        String  OCSM_province  = '';
        String title;
        if(isAll){
            title = '询价206更新报错 ';
        }else{
            title = '询价自动WIN失败 ';
        }
        String subject = title + ' 时间:' + Datetime.now().format();
        String htmlStr;
        if(isAll){
            htmlStr = '更新报错原因及链接见表格:';
        }else{
            htmlStr = '您好!如下询价自动WIN失败,原因及链接见表格:';
        }
        htmlStr += '<table border="1">';
        htmlStr += '<tr> <th>询价编码</th><th>失败原因</th><th>详细链接</th></tr>';
 
        for(Opportunity opp:[select Id,Name,Opportunity_No__c,OCM_man_province_no_dealer__c  from Opportunity where Id in:errMap.keySet()]){
            if(String.isBlank(OCSM_province)){
                OCSM_province = opp.OCM_man_province_no_dealer__c;
            }
            htmlStr += '<tr><td>'+opp.Opportunity_No__c+'</td><td>'+errMap.get(opp.Id)+'</td><td><a href="' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + opp.Id + '">点击链接</a>'+'</td></tr>';
        }
        htmlStr += '</table>';
        if(isAll){
            htmlStr += '<br/>请对应';
        }else{
            htmlStr += '<br/>请对应好后通知IT';
        }
        message.setSubject(subject);
        message.setHtmlBody(htmlStr);
        message.setCharset('UTF-8');
 
        if(isAll){
            String toEmail = System.Label.EmailAlert;
            if(toEmail.length() > 0){
                List<String> toMailsList = new List<String>();
                for(String email : toEmail.split(',')){
                    toMailsList.add(email);
                }
                if(toMailsList.size() > 0){
                    message.setToAddresses(toMailsList);
                } 
            }
        }else{
            // 收信人
            String toEmail = System.Label.CN_MEBG_BusinessSupport;
            if(toEmail.length() > 0){
                List<String> toMailsList = new List<String>();
                for(String email : toEmail.split(',')){
                    toMailsList.add(email);
                }
                if(toMailsList.size() > 0){
                    message.setToAddresses(toMailsList);
                } 
            }
            // CC
            Set<String> ccEmailSet = new Set<String>();
            String ccEmail = System.Label.EmailAlert;
            if(ccEmail.length() > 0){
                for(String email : ccEmail.split(',')){
                    ccEmailSet.add(email);
                }
            }
 
            if(!String.isBlank(OCSM_province)){
                List<OCM_Management_Province__c> ompList = [select Id,SalesManage__c,SalesManage__r.Email from OCM_Management_Province__c where name =:OCSM_province];
                if(ompList.size() > 0){
                    if (!String.isBlank(ompList[0].SalesManage__r.Email)) {
                        ccEmailSet.add(ompList[0].SalesManage__r.Email);
                    }
                }
            }
            message.setCcAddresses(new List<String>(ccEmailSet));
        }
        sendMails.add(message);
        if (sendMails.size() > 0) {
            //Messaging.sendEmail(allMails);
            Messaging.SendEmailResult[] results = Messaging.sendEmail(sendMails);
            for (Integer i = 0; i < results.size(); i++) {
                if (results[i].success == false) {
                    system.debug('=====send mail error:' + results[i].errors[0].message);
                }
            }
        }
    }
}