中扬CRM客户关系管理系统
#
LSH
2023-12-01 7804e0f43c902645e29a5a7fccd2c741f86cd312
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
package com.zy.crm.manager.controller;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.core.common.DateUtils;
import com.core.exception.CoolException;
import com.zy.crm.common.model.SettleDto;
import com.zy.crm.common.service.OssService;
import com.zy.crm.manager.entity.*;
import com.zy.crm.manager.service.ContractSalesService;
import com.zy.crm.manager.service.ContractService;
import com.core.annotations.ManagerAuth;
import com.core.common.BaseRes;
import com.core.common.Cools;
import com.core.common.R;
import com.core.domain.KeyValueVo;
import com.zy.crm.common.web.BaseController;
import com.zy.crm.manager.service.ProcessPermissionsService;
import com.zy.crm.manager.utils.ChineseNumberUtils;
import com.zy.crm.manager.utils.WordUtils;
import com.zy.crm.system.entity.User;
import com.zy.crm.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
 
@RestController
public class ContractController extends BaseController {
 
    @Autowired
    private ContractService contractService;
    @Autowired
    private ContractSalesService contractSalesService;
    @Autowired
    private OssService ossService;
    @Autowired
    private UserService userService;
    @Autowired
    private ProcessPermissionsService processPermissionsService;
 
    @RequestMapping(value = "/contract/{id}/auth2")
    @ManagerAuth
    public R get(@PathVariable("id") String id) {
        Contract contract = contractService.selectById(String.valueOf(id));
        assert contract != null;
        JSONObject resultObj = JSON.parseObject(JSON.toJSONString(contract));
        // 步骤条相关
        resultObj.put("step", contract.getSettle() == 5 ? 0 : contract.getSettle() + 1);
        return R.ok().add(resultObj);
    }
 
    @RequestMapping(value = "/contract/list/auth")
    @ManagerAuth
    public R list(@RequestParam(defaultValue = "1")Integer curr,
                  @RequestParam(defaultValue = "10")Integer limit,
                  @RequestParam(required = false)String orderByField,
                  @RequestParam(required = false)String orderByType,
                  @RequestParam(required = false)String condition,
                  @RequestParam Map<String, Object> param){
        EntityWrapper<Contract> wrapper = new EntityWrapper<>();
        excludeTrash(param);
        convert(param, wrapper);
        allLike(Contract.class, param.keySet(), wrapper, condition);
        if (!Cools.isEmpty(orderByField)){wrapper.orderBy(humpToLine(orderByField), "asc".equals(orderByType));}
        return R.ok(contractService.selectPage(new Page<>(curr, limit), wrapper));
    }
 
    private <T> void convert(Map<String, Object> map, EntityWrapper<T> wrapper){
        boolean signUserId = false;
        boolean signDeptId = false;
        boolean signHostId = false;
        for (Map.Entry<String, Object> entry : map.entrySet()){
            if (entry.getKey().equals("dept_id")){
                signDeptId = true;
                if (String.valueOf(entry.getValue()).equals("19")){
                    signHostId = true;
                }
            }
        }
        for (Map.Entry<String, Object> entry : map.entrySet()){
            String val = String.valueOf(entry.getValue());
            if (val.contains(RANGE_TIME_LINK)){
                String[] dates = val.split(RANGE_TIME_LINK);
                wrapper.ge(entry.getKey(), DateUtils.convert(dates[0]));
                wrapper.le(entry.getKey(), DateUtils.convert(dates[1]));
            } else if (entry.getKey().equals("dept_id")){
                if (!val.equals("19")){
                    wrapper.eq(entry.getKey(), val);
                }
            } else if (entry.getKey().equals("user_id") && !signDeptId){
                signUserId = true;
                wrapper.eq(entry.getKey(), val);
            } else {
                wrapper.like(entry.getKey(), val);
            }
        }
        if (!signUserId && !signDeptId){
            if (getRole().getId()==1){
                wrapper.or().eq("host_id",getHostId());
            }else if (getRole().getId()==2){
                wrapper.eq("dept_id",getDeptId());
            }else {
                wrapper.eq("user_id", getUserId());
            }
        }
        if (signHostId){
            wrapper.or().eq("host_id",getHostId());
        }
    }
 
    @RequestMapping(value = "/contract/add/auth")
    @ManagerAuth(memo = "添加合同")
    public R add(Contract contract) {
        Date now = new Date();
        contract.setUserId(getUserId());
        //创建人员部门
        contract.setDeptId(getDeptId());
        contract.setCreateTime(now);
 
        contract.setSettle(1);
 
        User manager = new User();
        try{
            manager = userService.getDeptManager(getHostId(), getUser().getDeptId());        // 获取部门领导
        }catch (Exception e){
            manager = getUser();
        }
        contract.setDirector(manager.getId());
        List<String> initNames = new ArrayList<>();
        initNames.add("创建合同模板");
        initNames.add("提交合同");
        initNames.add("部门经理审核");
        ProcessPermissions processPermissions = processPermissionsService.selectOne(new EntityWrapper<ProcessPermissions>().eq("process_memo", 7).eq("process",  "3-1" ));//7:合同管理
        User president = userService.selectById(processPermissions.getUserId());
        initNames.add("总经办"+president.getNickname()+"审核");
        initNames.add("业务员确认");
        contract.setSettleMsg(JSON.toJSONString(SettleDto.initContract(manager,getUser(),president,initNames,4)));
 
        contract.setUpdateTime(now);
        contract.setUpdateBy(getUserId());
        contractService.insert(contract);
        return R.ok();
    }
 
    @RequestMapping(value = "/contract/update/auth")
    @ManagerAuth(memo = "更新合同")
    public R update(Contract contract){
        if (Cools.isEmpty(contract) || null==contract.getId()){
            return R.error();
        }
        contract.setUpdateBy(getUserId());
        contract.setUpdateTime(new Date());
        contractService.updateById(contract);
        return R.ok();
    }
 
    @RequestMapping(value = "/contract/delete/auth")
    @ManagerAuth(memo = "删除合同")
    public R delete(@RequestParam(value="ids[]") Long[] ids){
         for (Long id : ids){
            contractService.deleteById(id);
        }
        return R.ok();
    }
 
    @RequestMapping(value = "/contract/generate/auth")
    @ManagerAuth(memo = "生成合同")
    public ResponseEntity<InputStreamResource> generate(@RequestParam Integer id,
                                                        @RequestParam String contractTemplate){
        try {
            /////////////////////////生成合同数据/////////////////////////
            Contract contract = contractService.selectById(id);
            if (contract == null) {
                return null;
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("{{serial}}", contract.getSerial());
            map.put("{{customer}}", contract.getCustomer());
            map.put("{{address}}", contract.getAddress());
            map.put("{{company}}", contract.getCompany());
            map.put("{{companyAddress}}", contract.getCompanyAddress());
            map.put("{{taxNum}}", contract.getTaxNum());
            map.put("{{bank}}", contract.getBank());
            map.put("{{bankNum}}", contract.getBankNum());
            map.put("{{city}}", contract.getCity());
            map.put("{{shippingAddress}}", contract.getShippingAddress());
            map.put("{{shippingName}}", contract.getShippingName());
            map.put("{{shippingPhone}}", contract.getShippingPhone());
            map.put("{{email}}", contract.getEmail());
            map.put("{{boss}}", contract.getBoss());
            map.put("{{priceChinese}}", ChineseNumberUtils.numberToChinese(contract.getPrice()));
            map.put("{{priceSci}}", WordUtils.formatNumberForAccounting(contract.getPrice()));
 
            SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
            map.put("{{now}}", format.format(new Date()));
            /////////////////////////生成合同数据/////////////////////////
 
            /////////////////////////生成Tab表格数据/////////////////////////
            List<ContractSales> contractSales = contractSalesService.selectByContractId(contract.getId());
            List<List<String>> tabParam = new ArrayList<>();
            ArrayList<String> tabTitle = new ArrayList<>();
            tabTitle.add("序号");
            tabTitle.add("品名");
            tabTitle.add("数量");
            tabTitle.add("单位");
            tabTitle.add("单价(元)");
            tabTitle.add("合计(元)");
            tabTitle.add("备注");
            tabParam.add(tabTitle);
            int idx = 1;//tab序号
            double totalPrice = 0D;
            for (ContractSales contractSale : contractSales) {
                ArrayList<String> list = new ArrayList<>();
                list.add(String.valueOf(idx));
                list.add(contractSale.getName());
                list.add(String.valueOf(contractSale.getNum()));
                list.add(contractSale.getUnit());
                list.add(WordUtils.formatNumberForAccounting(contractSale.getUnitPrice()));
                list.add(WordUtils.formatNumberForAccounting(contractSale.getTotalPrice()));
                list.add(contractSale.getMemo());
                tabParam.add(list);
                totalPrice += contractSale.getTotalPrice();
                idx++;//序号+1
            }
 
            //tab最后合计栏
            ArrayList<String> tabFooter = new ArrayList<>();
            tabFooter.add("合计(大写金额):" + ChineseNumberUtils.numberToChinese(totalPrice));
            tabFooter.add("");//合并单元格
            tabFooter.add("");//合并单元格
            tabFooter.add("");//合并单元格
            tabFooter.add("合计:" + WordUtils.formatNumberForAccounting(totalPrice));
            tabFooter.add("");//合并单元格
            tabFooter.add("");//合并单元格
            tabParam.add(tabFooter);
            /////////////////////////生成Tab表格数据/////////////////////////
 
            String fileName = this.getClass().getClassLoader().getResource("contractTemplate/" + contractTemplate + ".docx").getPath();//获取文件路径
 
//            String outPdfPath = fileName.split("\\.")[0]+".pdf";
            ResponseEntity<InputStreamResource> generate = WordUtils.generate(fileName, map, tabParam);
//            WordUtils.documents4jWordToPdf(fileName,outPdfPath);
            return generate;
        } catch (Exception e) {
            return null;
        }
    }
 
    @RequestMapping(value = "/contract/upload/auth")
    @ManagerAuth(memo = "上传合同")
    public R upload(@RequestParam("id") Integer id,
                         @RequestParam("file") MultipartFile[] files) throws IOException {
        Contract contract = contractService.selectById(id);
        if (contract == null) {
            return R.error();
        }
 
        MultipartFile file = files[0];
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String path =  ClassUtils.getDefaultClassLoader().getResource("contractTemplate/upload").getPath();
        //文件后缀名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //上传文件名
        String filename = format.format(new Date()) + "_" + file.getOriginalFilename();
        //最终文件路径
        String filepath = path + "/" + filename;
        //OSS文件存储路径
        String ossPath = "contract/" + filename;
 
        //服务器端保存的文件对象
        File serverFile = new File(filepath);
        if(!serverFile.exists()) {
            try {
                //创建文件
                serverFile.createNewFile();
                //将上传的文件写入到服务器端文件内
                file.transferTo(serverFile);
 
                //上传至OSS
                ossService.uploadFile(ossPath, serverFile);
                contract.setFilepath(ossPath);
                contractService.updateById(contract);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.ok();
    }
 
    @RequestMapping(value = "/contract/download/auth")
    @ManagerAuth(memo = "下载合同")
    public R download(@RequestParam("id") Integer id) {
        Contract contract = contractService.selectById(id);
        if (contract == null) {
            return R.error();
        }
        if (Cools.isEmpty(contract.getFilepath())) {
            return R.error();
        }
 
        String download = ossService.download(contract.getFilepath());//获取OSS临时下载URL
        return R.ok().add(download);
    }
 
    @RequestMapping(value = "/contract/export/auth")
    @ManagerAuth
    public R export(@RequestBody JSONObject param){
        EntityWrapper<Contract> wrapper = new EntityWrapper<>();
        List<String> fields = JSONObject.parseArray(param.getJSONArray("fields").toJSONString(), String.class);
        Map<String, Object> map = excludeTrash(param.getJSONObject("contract"));
        convert(map, wrapper);
        List<Contract> list = contractService.selectList(wrapper);
        return R.ok(exportSupport(list, fields));
    }
 
    @RequestMapping(value = "/contractQuery/auth")
    @ManagerAuth
    public R query(String condition) {
        EntityWrapper<Contract> wrapper = new EntityWrapper<>();
        wrapper.like("id", condition);
        Page<Contract> page = contractService.selectPage(new Page<>(0, 10), wrapper);
        List<Map<String, Object>> result = new ArrayList<>();
        for (Contract contract : page.getRecords()){
            Map<String, Object> map = new HashMap<>();
            map.put("id", contract.getId());
            map.put("value", contract.getId());
            result.add(map);
        }
        return R.ok(result);
    }
 
    @RequestMapping(value = "/contract/check/column/auth")
    @ManagerAuth
    public R query(@RequestBody JSONObject param) {
        Wrapper<Contract> wrapper = new EntityWrapper<Contract>().eq(humpToLine(String.valueOf(param.get("key"))), param.get("val"));
        if (null != contractService.selectOne(wrapper)){
            return R.parse(BaseRes.REPEAT).add(getComment(Contract.class, String.valueOf(param.get("key"))));
        }
        return R.ok();
    }
 
    @RequestMapping("/contract/all/get/kv")
    @ManagerAuth
    public R getDataKV(@RequestParam(required = false) String condition) {
        List<KeyValueVo> vos = new ArrayList<>();
        Wrapper<Contract> wrapper = new EntityWrapper<Contract>().andNew().like("id", condition).orderBy("create_time", false);
        contractService.selectPage(new Page<>(1, 30), wrapper).getRecords().forEach(item -> vos.add(new KeyValueVo(String.valueOf(item.getId()), item.getId())));
        return R.ok().add(vos);
    }
 
    @PostMapping(value = "/contract/approval/auth")
    @ManagerAuth
    public R approvalBusinessTrip(@RequestParam Long contractId,
                                  @RequestParam(required = false) Long plannerId){
        Contract contract = contractService.selectById(contractId);
        assert contract != null;
        Date now = new Date();
        switch (contract.getSettle()) {
            case 0:
                if (Cools.isEmpty(getUser())) {
                    return R.error("抱歉,您没有提交的权限");
                }
                if (!getUserId().equals(getUser().getId())) {
                    return R.error("抱歉,您没有提交的权限");
                }
                // 修改 settle 步骤数据
                List<SettleDto> list1 = JSON.parseArray(contract.getSettleMsg(), SettleDto.class);
                for (SettleDto dto : list1) {
                    switch (dto.getStep()) {
                        case 0:
                            dto.setCurr(Boolean.FALSE);
                            break;
                        case 1:
                            dto.setCurr(Boolean.TRUE);
                            dto.setMsg(getUser().getNickname() + "提交完成");
                            dto.setTime(DateUtils.convert(now));
                            break;
                        case 2:
                            contract.setDirector(dto.getUserId());
                            break;
                        default:
                            break;
                    }
                }
                contract.setSettleMsg(JSON.toJSONString(list1));
                // 修改规划单状态
                contract.setSettle(1);
                contract.setUpdateTime(now);
 
                if (!contractService.updateById(contract)) {
                    throw new CoolException("提交失败,请联系管理员");
                }
                break;
            case 1:
                // 本部门经理审核
                User manager = userService.selectById(contract.getDirector());
 
                if (manager.getId().equals(getUserId())) {
 
                    // 修改 settle 步骤数据
                    List<SettleDto> list = JSON.parseArray(contract.getSettleMsg(), SettleDto.class);
                    for (SettleDto dto : list) {
                        switch (dto.getStep()) {
                            case 1:
                                dto.setCurr(Boolean.FALSE);
                                break;
                            case 2:
                                dto.setCurr(Boolean.TRUE);
                                dto.setMsg("部门经理" + manager.getNickname() + "审批通过");
                                dto.setTime(DateUtils.convert(now));
                                break;
                            case 3:
                                contract.setDirector(dto.getUserId());
                                break;
                            default:
                                break;
                        }
                    }
                    contract.setSettleMsg(JSON.toJSONString(list));
 
                    // 修改规划单状态
                    contract.setSettle(2);  // 申请通过
                    contract.setUpdateTime(now);
                    if (!contractService.updateById(contract)) {
                        throw new CoolException("审核失败,请联系管理员");
                    }
                } else {
                    return R.error("抱歉,您没有审核的权限!!!");
                }
                break;
            case 2:
                User planLeader = userService.selectById(contract.getDirector());
 
                if (planLeader.getId().equals(getUserId())) {
 
                    // 修改 settle 步骤数据
                    List<SettleDto> list = JSON.parseArray(contract.getSettleMsg(), SettleDto.class);
                    for (SettleDto dto : list) {
                        switch (dto.getStep()) {
                            case 2:
                                dto.setCurr(Boolean.FALSE);
                                break;
                            case 3:
                                dto.setCurr(Boolean.TRUE);
                                dto.setMsg("总裁办" + planLeader.getNickname() + "审批通过");
                                dto.setTime(DateUtils.convert(now));
                                break;
                            case 4:
                                contract.setDirector(dto.getUserId());
                                break;
                            default:
                                break;
                        }
                    }
                    contract.setSettleMsg(JSON.toJSONString(list));
 
                    // 修改规划单状态
                    contract.setSettle(3);  // 申请通过
                    contract.setUpdateTime(now);
                    if (!contractService.updateById(contract)) {
                        throw new CoolException("审核失败,请联系管理员");
                    }
                } else {
                    return R.error("抱歉,您没有审核的权限!!!");
                }
                break;
            case 3:
                // 业务员
                User salesman0 = userService.selectById(contract.getUserId());
                if (!getUserId().equals(salesman0.getId())) {
                    return R.error("抱歉,您无需确认!!!");
                }
                // 修改 settle 步骤数据
                List<SettleDto> list2 = JSON.parseArray(contract.getSettleMsg(), SettleDto.class);
                for (SettleDto dto : list2) {
                    switch (dto.getStep()) {
                        case 3:
                            dto.setCurr(Boolean.TRUE);
                            break;
                        case 4:
                            dto.setCurr(Boolean.TRUE);
                            dto.setMsg("业务员" + salesman0.getNickname() + "以确认");
                            dto.setTime(DateUtils.convert(new Date()));
                            break;
                        default:
                            break;
                    }
                }
                contract.setSettleMsg(JSON.toJSONString(list2));
                // 修改规划单状态
                contract.setSettle(4);  // 审批通过
                contract.setUpdateTime(new Date());
 
                if (!contractService.updateById(contract)) {
                    throw new CoolException("确认失败,请联系管理员");
                }
                break;
            default:
                return R.error();
        }
        return R.ok("审批成功");
    }
 
}