From fd0bea6d4ad22f61b323ff5cf32e2b1104bb5492 Mon Sep 17 00:00:00 2001
From: 李金换 <lijinhuan@prec-tech.com>
Date: 星期四, 20 四月 2023 14:16:42 +0800
Subject: [PATCH] 失单报告增加限制

---
 force-app/main/default/classes/NFM206Rest.cls |  213 +++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 files changed, 204 insertions(+), 9 deletions(-)

diff --git a/force-app/main/default/classes/NFM206Rest.cls b/force-app/main/default/classes/NFM206Rest.cls
index 2845e21..25041b8 100644
--- a/force-app/main/default/classes/NFM206Rest.cls
+++ b/force-app/main/default/classes/NFM206Rest.cls
@@ -1,6 +1,6 @@
 @RestResource(urlMapping = '/NFM206/*')
 global with sharing class NFM206Rest {
-
+    
     global class GeDatas {
         public NFMUtil.Monitoring Monitoring;
         public NFM206Rest.GeData[] GeData;
@@ -20,8 +20,11 @@
         public String SPOApprovedQuote;                   //鍚堝悓瀹℃壒瀹屾垚鐨勬姤浠�
         //songxiaoqi ----------start
         public String IsTermination;                     //true浠h〃鍚堝悓缁堟
-
+        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
@@ -40,9 +43,26 @@
         }
 
         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) {
-            executefuture(rowData.Id);
+            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;
@@ -69,6 +89,9 @@
         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) {
@@ -76,7 +99,7 @@
         }
 
         Savepoint sp = Database.setSavepoint();
-        try {
+        try { // 20220916 ljh SWAG-CG2A7S 娉ㄩ噴 
             List<GeData> accordList = new List<GeData>();
             List<String> opportunity_NoList = new List<String>();
             //鍚堝悓蹇呭~瀛楁楠岃瘉
@@ -97,13 +120,16 @@
             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
+                                         Decided_Estimation__c,
                                          Estimation_Decision__c,
                                          Estimation_No__c,
                                          Competitor__c,
-                                         StageName
+                                         Sign_Contract_Electronically__c,
+                                         StageName,
+                                         CloseDate
                                          from Opportunity
                                          where Opportunity_No__c in : opportunity_NoList];
 
@@ -115,6 +141,7 @@
 
             for (GeData gda : accordList) {
                 Opportunity opportunityInfo = new Opportunity();
+
                 if (oppMap.containsKey(gda.Opportunity_No)) {
                     opportunityInfo = oppMap.get(gda.Opportunity_No);
                 } else {
@@ -129,7 +156,19 @@
                 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);
+                    // 鏀跺埌鏃ユ湡鏃惰嚜鍔╳in
+                    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 == '寮曞悎') {
@@ -142,6 +181,7 @@
                     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 鎾ら攢鍚堝悓鏃讹紝濡傛灉褰撳墠璇环绛夌骇涓篈1锛岄��鍥炲埌A start
                     if ('A1'.equals(opportunityInfo.Competitor__c)) {
@@ -173,6 +213,13 @@
                         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) {//闈炵數瀛愮鍚堝悓锛欼sEsign='0'
+                        opportunityInfo.Sign_Contract_Electronically__c = false;
+                    }
+                    // 2022-10-19 SWAG-CKB5S6 xxf end
                 }
                 //songxiaoqi ------start 2020/11/4 update 鐘舵��1鏄浠�
                 //浼犲叆true浠h〃鍚堝悓缁堟  StageName__c
@@ -185,6 +232,9 @@
                     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;
@@ -194,15 +244,67 @@
                     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) {
-                upsert opportunityUpsertList;
+                // 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';
-            rowData.retry_cnt__c = 0;
+            
+        // 20220916 ljh SWAG-CG2A7S 娉ㄩ噴 start
         } catch (Exception ex) {
             Database.rollback(sp);
             System.debug(Logginglevel.ERROR, 'NFM206_' + rowData.MessageGroupNumber__c + ':' + ex.getMessage());
@@ -219,6 +321,7 @@
                 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) {
@@ -229,4 +332,96 @@
         }
         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 = '鎮ㄥソ锛佸涓嬭浠疯嚜鍔╓IN澶辫触锛屽師鍥犲強閾炬帴瑙佽〃鏍硷細';
+        }
+        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);
+                }
+            }
+        }
+    }
 }
\ No newline at end of file

--
Gitblit v1.9.1