保誠-保戶業務員媒合平台
wayne
2022-01-26 6fa4bba623713c396432ba8b863846883d6a1906
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
package com.pollex.pam.service;
 
import com.pollex.pam.config.ApplicationProperties;
import com.pollex.pam.domain.Appointment;
import com.pollex.pam.domain.AppointmentCustomerView;
import com.pollex.pam.domain.Consultant;
import com.pollex.pam.domain.CustomerFavoriteConsultant;
import com.pollex.pam.domain.Satisfaction;
import com.pollex.pam.enums.ContactStatusEnum;
import com.pollex.pam.enums.LoginResult;
import com.pollex.pam.repository.ConsultantRepository;
import com.pollex.pam.repository.CustomerFavoriteConsultantRepository;
import com.pollex.pam.repository.SatisfactionRepository;
import com.pollex.pam.security.SecurityUtils;
import com.pollex.pam.service.dto.*;
import com.pollex.pam.service.mapper.AppointmentCustomerViewMapper;
import com.pollex.pam.service.mapper.ConsultantDTOMapper;
import com.pollex.pam.service.mapper.ConsultantMapper;
import com.pollex.pam.service.util.FileUtil;
import com.pollex.pam.web.rest.errors.ConsultantNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
 
import static com.pollex.pam.enums.ContactStatusEnum.*;
 
@Service
@Transactional
public class ConsultantService {
 
    private static final Logger log = LoggerFactory.getLogger(ConsultantService.class);
 
    @Autowired
    ConsultantRepository consultantRepository;
 
    @Autowired
    CustomerFavoriteConsultantRepository customerFavoriteConsultantRepository;
 
    @Autowired
    ConsultantMapper consultantMapper;
 
    @Autowired
    AppointmentService appointmentService;
 
    @Autowired
    LoginRecordService loginRecordService;
 
    @Autowired
    AppointmentCustomerViewMapper appointmentCustomerViewMapper;
 
    @Autowired
    SatisfactionService satisfactionService;
 
    @Autowired
    ConsultantDTOMapper consultantDTOMapper;
 
    @Autowired
    ApplicationProperties applicationProperty;
 
    @Autowired
    SendMsgService sendMsgService;
 
    @Autowired
    SpringTemplateEngine springTemplateEngine;
 
    @Autowired
    ApplicationProperties applicationProperties;
 
    @Autowired
    ConsultantService consultantService;
 
    @Autowired
    SatisfactionRepository satisfactionRepository;
 
    @Autowired
    PersonalNotificationService personalNotificationService;
 
    public List<CustomerFavoriteConsultantDTO> getMyConsultantList() {
        Long customerId = SecurityUtils.getCustomerDBId();
 
        return customerFavoriteConsultantRepository.findAllByCustomerId(customerId)
            .stream()
            .map(relation -> {
                Consultant consultant = relation.getConsultant();
                CustomerFavoriteConsultantDTO dto = consultantMapper.toCustomerFavoriteConsultantDto(consultant);
                dto.setCreateTime(relation.getCreatedDate());
                dto.setUpdateTime(relation.getCreatedDate());
                dto.setCustomerViewTime(relation.getViewTime());
 
                setInfoByAvailableAppointment(
                    dto,
                    appointmentService.findAvailableByAgentNoAndCustomerId(consultant.getAgentNo(), customerId)
                );
 
                setFavoriteConsultantUpdatedTime(relation, dto);
 
                return dto;
 
            }).collect(Collectors.toList());
    }
 
    public void setFavoriteConsultantUpdatedTime(CustomerFavoriteConsultant relation,
            CustomerFavoriteConsultantDTO dto) {
        Consultant consultant = relation.getConsultant();
        appointmentService.findLatestAppointmentByAgentNoAndCustomerId(consultant.getAgentNo(), relation.getCustomerId())
            .ifPresent(latestAppointment -> {
                dto.setUpdateTime(latestAppointment.getLastModifiedDate());
            });
 
        if(dto.getUpdateTime().isBefore(relation.getCreatedDate())) {
            dto.setUpdateTime(relation.getCreatedDate());
        }
    }
 
    private void setInfoByAvailableAppointment(CustomerFavoriteConsultantDTO customerFavoriteConsultantDTO, List<AppointmentCustomerView> appointmentList) {
        List<AppointmentCustomerView> appointments = appointmentList.stream()
            .sorted(Comparator.comparing(AppointmentCustomerView::getAppointmentDate).reversed())
            .collect(Collectors.toList());
 
        List<AppointmentCustomerViewDTO> appointmentCustomerViewDTOS = appointmentCustomerViewMapper.toAppointmentCustomerViewDTO(appointments);
        customerFavoriteConsultantDTO.setAppointments(appointmentCustomerViewDTOS);
 
        if (!appointments.isEmpty()) {
            AppointmentCustomerView latestAvailableAppointment = appointments.get(0);
            ContactStatusEnum latestStatus = latestAvailableAppointment.getCommunicateStatus();
            if(latestStatus != ContactStatusEnum.DONE && latestStatus != ContactStatusEnum.CLOSED)
                customerFavoriteConsultantDTO.setContactStatus(latestStatus);
            else
                customerFavoriteConsultantDTO.setContactStatus(PICKED);
        }else {
            customerFavoriteConsultantDTO.setContactStatus(PICKED);
        }
    }
 
    public List<ConsultantDTO> getRecommendConsultantList() {
        return consultantRepository.findAllByRecommendIsTrue()
            .stream()
            .map(consultantMapper::toDto)
            .collect(Collectors.toList());
    }
 
    public List<ConsultantDTO> strictQueryConsultant(StrictQueryConsultantParam param) {
        return consultantRepository.findAll(ConsultantQuerySpec.getStrictQuerySpec(param))
            .stream()
            .map(consultantMapper::toDto)
            .collect(Collectors.toList());
    }
 
    public List<ConsultantDTO> fastQueryConsultant(FastQueryConsultantParam param) {
        return consultantRepository.findAll(ConsultantQuerySpec.getFastQuerySpec(param))
            .stream()
            .map(consultantMapper::toDto)
            .collect(Collectors.toList());
    }
 
    public ConsultantDetailDTO getConsultantDetail(String agentNo) {
        Consultant consultant = consultantRepository.findOneByAgentNo(agentNo).orElseThrow(ConsultantNotFoundException::new);
        ConsultantDetailDTO consultantDetailDTO = consultantMapper.toDetailDto(consultant);
 
        loginRecordService.findLatestLoginRecord(agentNo, LoginResult.SUCCESS)
                .ifPresent(loginRecord -> consultantDetailDTO.setLatestLoginTime(loginRecord.getLoginDate()));
 
        return consultantDetailDTO;
    }
 
    @Transactional
    public void addConsultantToCustomList(AddConsultantParam param) {
        List<String> agentNoList = param.getAgentNoList();
        List<Consultant> consultants = consultantRepository.findAllByAgentNoIn(agentNoList);
        Long userId = SecurityUtils.getCustomerDBId();
 
        consultants.forEach(consultant -> {
            boolean isConsultantInList = customerFavoriteConsultantRepository.findOneByCustomerIdAndConsultant(userId, consultant).isPresent();
 
            if(!isConsultantInList) {
                CustomerFavoriteConsultant customerFavoriteConsultant = new CustomerFavoriteConsultant();
                customerFavoriteConsultant.setConsultant(consultant);
                customerFavoriteConsultant.setCustomerId(userId);
 
                customerFavoriteConsultantRepository.save(customerFavoriteConsultant);
            }
            else {
                log.info("The consultant is in customer favorite list! customId = {}, consultant AgentNo = {}", userId, consultant.getAgentNo());
            }
        });
 
    }
 
    public List<AppointmentCustomerViewDTO> getMyAppointment() {
        String agentNo = SecurityUtils.getAgentNo();
        return appointmentService.getConsultantAvailableAppointments(agentNo);
    }
 
    public void removeConsultantFromCustomList(String agentNo) {
        Long customId = SecurityUtils.getCustomerDBId();
        Consultant consultant = consultantRepository.findOneByAgentNo(agentNo).orElseThrow(ConsultantNotFoundException::new);
        CustomerFavoriteConsultant target = customerFavoriteConsultantRepository.findOneByCustomerIdAndConsultant(customId, consultant).orElse(null);
 
        if(target != null) {
            customerFavoriteConsultantRepository.delete(target);
        }
        else {
            log.info("this consultant is not in customer list! agentNo = {}, customId = {}", agentNo, customId);
        }
    }
 
    public void recordAllAppointmentsView() {
        String agentNo = SecurityUtils.getAgentNo();
        appointmentService.recordAllAppointmentsView(agentNo);
    }
 
    public void recordMyConsultantListView() {
        Long customerId = SecurityUtils.getCustomerDBId();
        List<CustomerFavoriteConsultant> notViewRelation = customerFavoriteConsultantRepository
            .findAllByCustomerId(customerId)
            .stream()
            .filter(relation -> Objects.isNull(relation.getViewTime()))
            .collect(Collectors.toList());
 
        notViewRelation.forEach(relation -> {
            relation.setViewTime(Instant.now());
        });
 
        customerFavoriteConsultantRepository.saveAll(notViewRelation);
    }
 
    public Consultant findByAgentNo(String agentNo) {
        return consultantRepository.findOneByAgentNo(agentNo).get();
    }
 
    public Consultant editConsultant(ConsultantEditDTO editDTO) {
        Consultant consultant = consultantRepository.findOneByAgentNo(editDTO.getAgentNo())
                .orElseThrow(ConsultantNotFoundException::new);
        consultantDTOMapper.copyToConsultant(editDTO, consultant);
        FileUtil.base64ToFile(editDTO.getPhotoBase64(), editDTO.getPhotoFileName(), applicationProperty.getFileFolderPath());
        consultantRepository.save(consultant);
        personalNotificationService.createEditConsultantToConsultant(consultant);
        return consultant;
    }
 
    public InputStream getAvatarImage(String agentNo) {
        Consultant consultant = consultantRepository.findOneByAgentNo(agentNo)
                .orElseThrow(ConsultantNotFoundException::new);
        File file = new File(consultant.getPhotoPath());
        try {
            InputStream in = new FileInputStream(file);
            return in;
        } catch (FileNotFoundException e) {
            log.error("agent photo not found , agentNo:"+agentNo,e);
            return null;
        }
    }
 
    public void sendSatisfactionToClient(Appointment appointment) {
        String subject = "滿意度填寫通知";
 
        if(StringUtils.hasText(appointment.getEmail())) {
            String content = genSendSatisfactionEmailContent(appointment);
            sendMsgService.sendMsgByEmail(appointment.getEmail(), subject, content, true);
 
        }if(StringUtils.hasText(appointment.getPhone())) {
            String content = genSendSatisfactionSMSContent(appointment);
            sendMsgService.sendMsgBySMS(appointment.getPhone(), content);
        }
 
        personalNotificationService.createSendSatisfactionToClientToCustomer(appointment);
    }
 
    private String genSendSatisfactionSMSContent(Appointment appointment) {
        String agentNo = appointment.getAgentNo();
        Consultant consultant = consultantService.findByAgentNo(agentNo);
        String contsultantName = consultant.getName();
        String content = contsultantName+"顧問請您填寫保誠媒合平台的滿意度評比"+getSendSatisfactionToClientUrl(appointment.getId());
        return content;
    }
 
    private String genSendSatisfactionEmailContent(Appointment appointment) {
        String agentNo = appointment.getAgentNo();
        Consultant consultant = consultantService.findByAgentNo(agentNo);
        Context context = new Context();
        context.setVariable("consultantName", consultant.getName());
        context.setVariable("appointmentUrl", getSendSatisfactionToClientUrl(appointment.getId()));
        String content = springTemplateEngine.process("mail/writeSatisfactionNotice", context);
        return content;
    }
 
    public String getSendSatisfactionToClientUrl(Long appointmentId) {
        return applicationProperties.getFrontEndDomain() + "/?appointmentId=" + appointmentId;
    }
 
    public void setConsultantAvgScore(Satisfaction satisfaction) {
        float avgScore = getAgentAvgScore(satisfaction.getAgentNo());
        Consultant consultant = consultantRepository.findOneByAgentNo(satisfaction.getAgentNo())
                .get();
        consultant.setAvgScore(avgScore);
        consultantRepository.save(consultant);
    }
 
    public float getAgentAvgScore(String agentNo) {
        Float avgScore = satisfactionRepository.getAgentScoreAvg(agentNo);
        if(avgScore==null)return 0;
        BigDecimal bigDecimal = new BigDecimal(avgScore);
        return avgScore = bigDecimal.setScale(1,BigDecimal.ROUND_HALF_UP).floatValue();
    }
}