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
global class StatisticsInstructedStaffBatch implements Database.Batchable<sObject>, Database.Stateful {
    public String query;
 
    public Date today = Date.today();
    public Date mon1stDate = Date.newInstance(today.year(), today.month(), 1);
    public Date monLastDate = mon1stDate.addMonths(1).addDays(-1);
    public Date lastMon1stDate = Date.newInstance(today.year(), today.month(), 1).addMonths(-1);
    public Date lastMonLastDate = mon1stDate.addDays(-1);
    public Integer month = today.month();
    public Boolean mon1stDateFlag = today == mon1stDate;
 
 
    global Integer totalCount = 0; // 总件数
    global Integer failedCount = 0;
    global List<String> emailMessages = new List<String>();
 
    global String sendMail;
    global String specifiedYearMonth;
    global Integer specifiedMonth;
    global StatisticsInstructedStaffBatch() {
       
    }
    //执行上个月的最后一次执行入口
    global StatisticsInstructedStaffBatch(Boolean mon1stDateFlag) {
        this.mon1stDateFlag = mon1stDateFlag;
    }
    //发送报表链接出现错误,重新发送入口
    global StatisticsInstructedStaffBatch(String sendMailFlag) {
        this.sendMail = sendMailFlag;
    }
 
    global StatisticsInstructedStaffBatch(String specifiedYearMonth,Boolean  specified_YearMonth) {
        this.specifiedYearMonth = specifiedYearMonth;
    }
 
    global Database.QueryLocator start(Database.BatchableContext bc) {
 
        String query =
            ' Select Id,Name,Instruct_report__r.ReportDate__c,Instruct_report__r.Status__c,ContactID__c ';
        query += ' from Instructed_staff__c ';
        query += ' where Instruct_report__r.Status__c = \'批准\'';
 
        if (mon1stDateFlag) {
            query += ' AND Instruct_report__r.ReportDate__c >= :lastMon1stDate';
            query += ' AND Instruct_report__r.ReportDate__c <= :lastMonLastDate';
        } else if (String.isNotBlank(specifiedYearMonth)) {
 
            Integer specifiedYear = Integer.valueOf(specifiedYearMonth.split(',')[0]);
            specifiedMonth = Integer.valueOf(specifiedYearMonth.split(',')[1]);
 
            Date startDate = Date.newInstance(specifiedYear, specifiedMonth, 1);
            Date endDate = startDate.addMonths(1).addDays(-1);
 
            query += ' AND Instruct_report__r.ReportDate__c >= :startDate';
            query += ' AND Instruct_report__r.ReportDate__c <= :endDate';
        } else {
            query += ' AND Instruct_report__r.ReportDate__c >= :mon1stDate';
            query += ' AND Instruct_report__r.ReportDate__c <= :monLastDate';
        }
        system.debug('query→→→Staff' + query);
        return Database.getQueryLocator(query);
    }
 
    global void execute(Database.BatchableContext BC, list<Instructed_staff__c> InstructedstaffList) {
        Savepoint sp = Database.setSavepoint();
        totalCount += InstructedstaffList.size();
        //totalCount += 1;
        
        Map<Id,Contact> updateContactMap = new Map<Id,Contact>();
        try {
            for (Instructed_staff__c staff : InstructedstaffList) {
                Contact contact = new Contact();
                contact.Id = staff.ContactID__c;
                if (String.isNotBlank(specifiedYearMonth)) {
                    contact = updateInstruct_CountN(specifiedMonth, mon1stDateFlag, contact, 1);
                } else {
                    system.debug('month--->'+month);
                    system.debug('mon1stDateFlag--->'+mon1stDateFlag);
                    system.debug('month--->'+month);
                    contact = updateInstruct_CountN(month, mon1stDateFlag, contact, 1);
                }
 
                updateContactMap.put((Id)staff.ContactID__c,contact);
            }
 
            if (updateContactMap.size() > 0) {
                system.debug('updateContactMap---->'+updateContactMap);
                update updateContactMap.values();
            }
        } catch (Exception e) {
            Database.rollback(sp);
            emailMessages.add(e.getMessage());
            System.debug(emailMessages);
            failedCount += InstructedstaffList.size();
            System.debug(failedCount);
        }
    }
 
    global void finish(Database.BatchableContext BC) {
        sendFieldEmail();
        Date today = Date.today();
        Boolean april_1Flag = today == Date.newInstance(today.year(), 4, 1);
 
        if (april_1Flag || 'sendMail'.equals(sendMail)) {
 
            if (!sendMail()) {
                system.debug('发送失败,请检查');
            }
        }
 
    }
    // 发送更新失败的消息
    private void sendFieldEmail() {
        PretechBatchEmailUtil be = new PretechBatchEmailUtil();
        //String[] toList = new String[] {UserInfo.getUserEmail()};
        String[] toList = new String[] {'xinhonglu@prec-tech.com'};
        String title = '客户人员带教数量赋值更新失败';
        String[] ccList = new String[] {};
        if (System.Test.isRunningTest()) {
            be.successMail('', 1);
        }
        if (emailMessages.size() > 0) {
            be.failedMail(toList, ccList, title,
                          String.join(this.emailMessages, '\n'),
                          totalCount, totalCount - failedCount, failedCount, '', false);
            be.send();
        }
    }
 
    global static Contact updateInstruct_CountN(Integer month, Boolean mon1stDateFlag, Contact contact, Integer SetNumber) {
 
        switch on month {
        when 1 {
            if (mon1stDateFlag) {
                    contact.Instruct_Count12__c = SetNumber;
                } else {
                    contact.Instruct_Count1__c = SetNumber;
                }
            }
            when 2 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count1__c = SetNumber;
                } else {
                    contact.Instruct_Count2__c = SetNumber;
                }
            }
            when 3 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count2__c = SetNumber;
                } else {
                    contact.Instruct_Count3__c = SetNumber;
                }
 
            }
            when 4 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count3__c = SetNumber;
                } else {
                    contact.Instruct_Count4__c = SetNumber;
                }
 
            }
            when 5 {
 
                if (mon1stDateFlag) {
                    contact.Instruct_Count4__c = SetNumber;
                } else {
                    contact.Instruct_Count5__c = SetNumber;
                }
            }
            when 6 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count5__c = SetNumber;
                } else {
                    contact.Instruct_Count6__c = SetNumber;
                }
 
            }
            when 7 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count6__c = SetNumber;
                } else {
                    contact.Instruct_Count7__c = SetNumber;
                }
            }
            when 8 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count7__c = SetNumber;
                } else {
                    contact.Instruct_Count8__c = SetNumber;
                }
            }
            when 9 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count8__c = SetNumber;
                } else {
                    contact.Instruct_Count9__c = SetNumber;
                }
            }
            when 10 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count9__c = SetNumber;
                } else {
                    contact.Instruct_Count10__c = SetNumber;
                }
            }
            when 11 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count10__c = SetNumber;
                } else {
                    contact.Instruct_Count11__c = SetNumber;
                }
            }
            when 12 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count11__c = SetNumber;
                } else {
                    contact.Instruct_Count12__c = SetNumber;
                }
            }
            when 13 {
                contact.Instruct_Count1__c  = SetNumber;
                contact.Instruct_Count2__c  = SetNumber;
                contact.Instruct_Count3__c  = SetNumber;
                contact.Instruct_Count4__c  = SetNumber;
                contact.Instruct_Count5__c  = SetNumber;
                contact.Instruct_Count6__c  = SetNumber;
                contact.Instruct_Count7__c  = SetNumber;
                contact.Instruct_Count8__c  = SetNumber;
                contact.Instruct_Count9__c  = SetNumber;
                contact.Instruct_Count10__c = SetNumber;
                contact.Instruct_Count11__c = SetNumber;
                contact.Instruct_Count12__c = SetNumber;
            }
        }
        system.debug('赋值之后的contact'+ contact);
        return contact;
    }
 
    public static boolean sendMail() {
 
        Boolean result = true;
        String title = '';
        String body = '';
        List<String> toMailList = new List<String>();
        List<String> ccMailList = new List<String>();
        List<String> statementIdList = new List<String>();
        Date today = Date.today();
        Integer NPnum = today.year() - 1 - 2004 + 137;
 
        //辛洪禄<xinhonglu@prec-tech.com>
        String  toMail = System.Label.toMail;
        ccMailList.add('xinhonglu@prec-tech.com');
        toMailList.add(toMail);
        
        //string query = 'select id , Email from user where id in (';
        //query += System.Label.contactPopulationReport.replaceall('\'', '\\\'') + ')';
        //List<user> toUserList = Database.Query(query);
 
        //for (user toUser : toUserList) {
        //    if (!String.isBlank(toUser.Email)) {
        //        toMailList.add(toUser.Email);
        //    }
        //}
 
        String NPnumP = NPnum + 'P';
        title = '您好,新的财年要开始了,请您将上一财年的客户人员的带教数相关的报表进行下载:';
        body += '以下报表为:' + NPnumP + '财年的客户人员带教相关报表,请在4月10日之前确认并下载。<br/>';
        body += '<br/>';
        for (String  nameAndId : System.Label.Statementlink.split(',')) {
            List<String> nameAndIdSplit = nameAndId.split(':');
            body += nameAndIdSplit[0] + ':报表链接:<a href="' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + nameAndIdSplit[1] + '">' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + nameAndIdSplit[1] + '</a><br/>';
        }
 
 
 
        List<Messaging.SingleEmailMessage> sendMails = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage messageNEW = new Messaging.SingleEmailMessage();
        messageNEW.subject = title;
        messageNEW.htmlBody = body;
        messageNEW.setCharset('UTF-8');
        messageNEW.toAddresses = toMailList;
        messageNEW.ccAddresses = ccMailList;
 
        sendMails.add(messageNEW);
        if (sendMails.size() > 0) {
            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);
                    result = false;
                }
            }
        }
 
        return result;
 
    }
}