liuyn
2024-03-11 a87f1c3df03078814ee97ad0c8ac200a232419e9
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
/**
 * FSE日报
 */
@RestResource(urlMapping = '/NFM608/*')
global with sharing class NFM608Rest {
    public static final String LOG_TYPE = 'NFM608';
    global class GeData {
        public String mngCd; //工程师管理编码
        public String departmentCd; //科室编码
        public String applicantId; //报修人ID
        public String synchroDate; //同步日期
        public String replyID; //活动草稿ID
        public String visitInfo; //任务类型
        public String visitStartDate; //开始时间
        public String visitEndDate; //结束时间
        public String replyResult; //应对结果
        public String visitDistinction; //拜访区分
        public String visitPurpose; //拜访目的
        public String activityDifferentiation; //活动区分
    }
    @HttpPost
    global static void doPost() {
        // 取得接口传输内容
        String strData = RestContext.request.requestBody.toString();
        
        GeData ged = (GeData) JSON.deserializeStrict(strData, GeData.class);
 
        if (ged == null) {
            return;
        }
 
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = LOG_TYPE;
        iflog.ErrorLog__c = '';
        iflog.Log__c = 'callout start\n';
 
        BatchIF_Log__c rowData = NFMUtil.makeRowData(iflog, LOG_TYPE, ged);
        insert rowData;
        if (String.isBlank(rowData.Log__c) == false) {
            executefuture(rowData.Id);
        }
 
        // JSONを戻す
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        res.statusCode = 200;
        String jsonResponse = '{"status": "Success", "Message":"成功"}';
        res.responseBody = Blob.valueOf(jsonResponse);
        return;
 
    }
    @future(callout = true)
    global static void executefuture(String rowData_Id) {
        main(rowData_Id);
    }
    global static void main(String rowData_Id) {
       
        Map<String, String> transferMap = new Map<String, String>();
        List<BatchIF_Transfer__c> transferList = [select Table__c,
                                  Column__c,
                                  External_value__c,
                                  Internal_value__c
                                  from BatchIF_Transfer__c
                                  where Dropped_Flag__c = false
                                          and (Table__c = 'Event__c')
                                          ];
        for (BatchIF_Transfer__c t : transferList) {
            transferMap.put(t.Column__c + t.External_value__c, t.Internal_value__c);
        }
 
        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.Name + ' start\n';//MessageGroupNumber__c
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = LOG_TYPE;
        iflog.MessageGroupNumber__c = rowData.Name;//rowData.MessageGroupNumber__c;
        iflog.Log__c = logstr;
        iflog.ErrorLog__c = '';
        insert iflog;
        String rowDataStr = NFMUtil.getRowDataStr(rowData);
        GeData ged = (GeData) JSON.deserialize(rowDataStr, GeData.class);
        if (ged == null) {
            return;
        }
        Savepoint sp = Database.setSavepoint();
        try {
            rowData.retry_cnt__c = 0; //必加
            // 必填字段验证 Start
            String dataComplete = verify(ged);
            // 必填字段验证 End
            if (!String.isBlank(dataComplete)) {
                logstr += dataComplete;
            } else {
 
 
                String mngCd = ged.mngCd;
                // 获取社内用户Id
                Id userId = getUserId(mngCd); 
                if (userId == null) {
                    logstr += '社内用户 [ ' + mngCd + ' ],不存在或未启用或已离职,此条数据跳过不执行!\n';
                    return;
                }
                // 获取日报
                Daily_Report__c drc = getDaily_Report(ged, userId);
 
                // 获取科室
                Account departmentAccount = getdepartmentAccount(ged.departmentCd);
                if (departmentAccount == null) {
                    // 20230109 ljh start
                    // logstr += '客户 [ ' + ged.departmentCd + ' ] 不存在或已无效,此条数据跳过不执行\n';
                    logstr += '[ '+ged.replyID+' ]'+'客户 [ ' + ged.departmentCd + ' ] 不存在或已无效,此条数据跳过不执行\n';
                    // 20230109 ljh end
                    return;
                }
 
                String strType = getVisitType(ged.visitDistinction);
                if (String.isBlank(strType)) {
                    // 20230109 ljh start
                    // logstr += '拜访区分 [ ' + ged.visitDistinction + ' ]无效,此条数据跳过不执行 \n';
                    logstr += '[ '+ged.replyID+' ]'+'拜访区分 [ ' + ged.visitDistinction + ' ]无效,此条数据跳过不执行 \n';
                    // 20230109 ljh end
                    return;
                }
                //日报审批通过之后,不能在创建报告一览
                if(null!=drc){
                    // 20230109 ljh start
                    // if(drc.Status__c=='承認'){
                    if(drc.Status__c=='承認' || drc.Status__c=='申請中'){
                        // logstr += '日报状态 [' + drc.Status__c +' ],此条数据跳过不执行 \n';
                        logstr += '[ '+ged.replyID+' ]'+'日报状态 [' + drc.Status__c +' ],此条数据跳过不执行 \n';
                    // 20230109 ljh end
                        return;
                    }
                }
                Datetime startdate1 = NFMUtil.parseStr2DateTime(ged.visitStartDate);
                Datetime enddate1 = NFMUtil.parseStr2DateTime(ged.visitEndDate);
                Long timeDif = enddate1.getTime() - startdate1.getTime(); 
                Integer ts = Integer.valueOf((enddate1.getTime() - startdate1.getTime()) / 1000 / 3600 /24);
                system.debug( startdate1.getTime()+'==='+enddate1.getTime()+'==='+startdate1+'==='+enddate1+'==='+ts);
                if(ts > 14){
                    // 20230109 ljh start
                    // logstr += '事件的持续时间不能超过 14 天,此条数据跳过不执行 \n';
                    logstr += '[ '+ged.replyID+' ]'+'事件的持续时间不能超过 14 天,此条数据跳过不执行 \n';
                    // 20230109 ljh start
                   return;
                }
                
                // 查找访问对象
                String contactId = null;
                if (String.isNotBlank(ged.applicantId)) {
                    contactId = getContact(ged.applicantId,departmentAccount.Id);
                    if (String.isBlank(contactId)) {
                        logstr += '访问对象 [ ' + ged.applicantId + ' ] 不存在或不在 客户 [ '+departmentAccount.Name+'('+ged.departmentCd+')下 ],数据正常保存,特此记录\n';
                    }    
                }
 
                Event__c report = new Event__c();//报告一览
                report.ServicePlatformCode__c = ged.replyID;//AWS活动编码
                report.Account_ID__c = departmentAccount.Id;//科室
                report.whatid__c = departmentAccount.Id;
                // report.VisitType__c = ged.visitInfo;//任务类型
                report.Visitor1_ID__c = contactId; //訪問者1
                report.StartDateTime__c = NFMUtil.parseStr2DateTime(ged.visitStartDate);//开始时间
                report.ActivityDate__c = NFMUtil.parseDateTimeStr2Date(ged.visitStartDate);//活动日期
                report.EndDateTime__c = NFMUtil.parseStr2DateTime(ged.visitEndDate);//结束时间
                report.Description__c = ged.replyResult;//结果
 
                report.Location__c = departmentAccount.Name; //位置
 
                report.Activity_Type2__c = strType;//拜访区分
                //report.Activity_PurposeEscFSE__c  = ged.visitPurpose;//拜访目的
                //report.Activity_PurposeFSE__c  = ged.visitPurpose;//拜访目的
                //report.Purpose_TypeFSE__c  = ged.activityDifferentiation;//活动区分
                report.Activity_PurposeFSE__c  = NFMUtil.getMapValue(transferMap, 'Activity_PurposeFSE__c', string.valueof(ged.visitPurpose), iflog);
                report.Purpose_TypeFSE__c  = NFMUtil.getMapValue(transferMap, 'Purpose_TypeFSE__c', string.valueof(ged.activityDifferentiation), iflog);
                
                //20231114 zzm 小程序的数据添加主题 start
                if(String.isNotBlank(ged.visitPurpose) && String.isNotBlank(report.Location__c)){
                    report.Subject__c = ged.visitPurpose+'(' +report.Location__c +')';  
                } else if(String.isNotBlank(report.Location__c)){
                    report.Subject__c = report.Location__c;
                } else {
                    report.Subject__c = ged.visitPurpose;
                }
                //20231114 zzm 小程序的数据添加主题 end
                
 
                report.Daily_Report__c = drc.Id;//日报
                report.IsFromApplet__c = true;//20221226 ljh DB202212307127 是否小程序来源
                insert report;
                logstr +=  '报告一览 [ '+ged.replyID+' ] 保存成功!\n';
            }
           // rowData.retry_cnt__c = 0; //必加
            
        } catch (Exception ex) {
            // エラーが発生した場合
            Database.rollback(sp);
            logstr += '\n' + ex.getMessage();
            iflog.ErrorLog__c = ex.getMessage() + '\n' + ex.getStackTraceString() + '\n' + iflog.ErrorLog__c;
 
            // 异常重发
            rowData = NFMUtil.LogAutoSend(rowData, ex, null);
            update iflog;
        } 
        finally {
            update rowData;
            iflog.Log__c = logstr;
            update iflog;
        }
 
 
    }
    // 查找 访问科室
    private static Account getdepartmentAccount(String departmentCd) {
        Account acc = [select Id, Name from Account where Management_Code__c =: departmentCd];
        return acc;
 
    }
 
    // 查找 对应科室下的拜访对象
    public static String getContact(String applicantId,String departmentAccountId) {
        String contactId = null;
        List < Contact > contactList = [SELECT Id FROM Contact WHERE CManageCode__c =: applicantId AND AccountId =:departmentAccountId];
        if (contactList.size() > 0) {
            contactId = contactList[0].Id;
        }
        return contactId;
    }
    // 获取日报,不存在 创建
    private static Daily_Report__c getDaily_Report(GeData ged, Id userId) {
        Daily_Report__c result = new Daily_Report__c();
        // 获取 活动日期
        Date visitStartDate = null;
        if (ged.visitStartDate.length() >= 8) {
            visitStartDate = NFMUtil.parseStr2Date(ged.visitStartDate.subString(0, 8));
        }
 
 
        List < Daily_Report__c > drcs = [select Id, Reporter__r.Employee_No__c,Status__c from Daily_Report__c where Reported_Date__c =: visitStartDate and Reporter__r.Employee_No__c =: ged.mngCd];
        if (drcs.size() > 0) {
            result = drcs[0];
        } else {
            // 创建日报
            result = createDR(userId, visitStartDate);
            insert result;
        }
        return result;
    }
 
 
    // 获取有效的社内用户
    private static Id getUserId(String mngCd) {
        Id userId = null;
        User user = [SELECT Id, Employee_No__c, Contact.CManageCode__c
            FROM User
            WHERE IsActive = true AND Stay_or_not__c = '在职'
            AND Employee_No__c =: mngCd
        ];
        userId = user != null ? user.Id : null;
        return userId;
    }
    // 日报字段赋值
    private static Daily_Report__c createDR(id userId, Date reportDate) {
 
        Daily_Report__c report = new Daily_Report__c();
        report.Reporter__c = userId;
        report.Status__c = '作成中';
        report.Daily_Report_Data_Type__c = '通常';
        report.Reported_Date__c = reportDate;
        report.Working_Time_From__c =
            Datetime.newInstance(reportDate.year(),
                reportDate.month(),
                reportDate.day(), 8, 45, 0);
        report.Working_Time_To__c =
            Datetime.newInstance(reportDate.year(),
                reportDate.month(),
                reportDate.day(),
                17, 30, 0);
        report.OwnerId = userId;
        return report;
    }
    
    private static String getVisitType(String visitDistinction) {
        String result = null;
        Map < String, String > VisitTypeMap = new Map < String, String > ();
        VisitTypeMap.put('公司工作', '社内活動');
        VisitTypeMap.put('用户拜访', '病院');
        VisitTypeMap.put('经销商支持', '販売店');
        VisitTypeMap.put('学术会议', '社外イベント');
        VisitTypeMap.put('移动', '移動');
        VisitTypeMap.put('休假', '休暇');
        result = VisitTypeMap.get(visitDistinction);
        return result;
    }
    // 字段验证
    private static String verify(GeData ged) {
        String result = '';
        String replyID = '';
        if (ged.mngCd == null) {
            result += 'DataError: 工程师管理编码 [ mngCd ] is null!\n';
        }
        if (String.isBlank(ged.replyID)) {
            result += 'DataError: 活动草稿ID [ replyID ] is null!\n';
        } else {
            replyID = '活动草稿ID [ ' + ged.replyID + ' ]\n';
        }
 
        if (ged.departmentCd == null) {
            result += 'DataError: 科室编码 [ departmentCd ] is null!\n';
        }
        if (ged.synchroDate == null) {
            result += 'DataError: 同步日期 [ synchroDate ] is null!\n';
        }
        if (String.isBlank(ged.visitDistinction)) {
            result += 'DataError: 拜访区分 [ visitDistinction ] is null!\n';
        }
        if (String.isBlank(ged.visitStartDate)) {
            result += 'DataError: 开始时间  [ visitStartDate ] is null!\n';
        }
 
        if (String.isBlank(ged.visitEndDate)) {
            result += 'DataError: 结束时间  [ visitEndDate ] is null!\n';
        }
        if (String.isNotBlank(replyID) && String.isNotBlank(result)) {
            result = replyID + result;
        }
        return result;
    }
}