Cui Zhi Feng
2024-09-13 59dd2b95dc1d8f011a1608fc4f6123eb7ca8b084
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
package com.mzl.flower.service.payment;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mzl.flower.base.interceptor.CodeDecorator;
import com.mzl.flower.component.SequenceNo;
import com.mzl.flower.config.exception.ValidationException;
import com.mzl.flower.config.security.SecurityUtils;
import com.mzl.flower.constant.Constants;
import com.mzl.flower.dto.request.payment.*;
import com.mzl.flower.dto.response.payment.OrderItemSalesNewDTO;
import com.mzl.flower.dto.response.payment.OrderItemSalesNewListDTO;
import com.mzl.flower.dto.response.payment.OrderStatusCountDTO;
import com.mzl.flower.dto.response.system.CodeValueDTO;
import com.mzl.flower.entity.payment.*;
import com.mzl.flower.entity.supplier.Station;
import com.mzl.flower.mapper.payment.*;
import com.mzl.flower.mapper.supplier.StationMapper;
import com.mzl.flower.service.BaseService;
import com.mzl.flower.service.system.CodeService;
import com.mzl.flower.utils.ExcelExportUtil;
import com.mzl.flower.utils.UUIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
@Slf4j
@Service
@Transactional
public class OrderItemSalesService extends BaseService {
 
    @Autowired
    private OrderItemSalesMapper orderItemSalesMapper;
 
    @Autowired
    private OrderMapper orderMapper;
 
    @Autowired
    private OrderItemMapper orderItemMapper;
 
    @Autowired
    private UserPaymentV3Service paymentV3Service;
 
    @Autowired
    private SequenceNo sequenceNo;
 
    @Autowired
    private StationMapper stationMapper;
 
    @Autowired
    private CodeService codeService;
 
    @Autowired
    private CodeDecorator codeDecorator;
 
    @Autowired
    private OrderItemCheckMapper orderItemCheckMapper;
 
    public String createSales(OrderItemSalesCreateDTO dto){
        Integer num = dto.getNum();
        if(num == null || num == 0){
            throw new ValidationException("申请数量不能为空");
        }
 
        OrderItem oi = orderItemMapper.selectById(dto.getOrderItemId());
        if(oi == null){
            throw new ValidationException("订单商品不存在");
        }
 
        OrderItemCheck c = orderItemCheckMapper.selectOne(new QueryWrapper<OrderItemCheck>()
                .eq("order_item_id", oi.getId())
                .eq("type", Constants.CHECK_TYPE.lack.name())
                .eq("audit_status", Constants.CHECK_AUDIT_STATUS.AGREED.name())
        );
        int totalNum = oi.getNum();
        if(c != null){//需要减去缺货的数量
            totalNum -= c.getNum();
        }
        if(num > totalNum){
            throw new ValidationException("申请数量不能超过总数");
        }
 
        //收货前可以申请售后,售后最多申请两次
        Order o = orderMapper.selectById(oi.getOrderId());
        String status = o.getStatus();
        if(!Constants.ORDER_STATUS.RECEIVE.name().equals(status)){
            throw new ValidationException("无法申请售后");
        }
 
        String userId = SecurityUtils.getUserId();
        int count = orderItemSalesMapper.selectCount(new QueryWrapper<OrderItemSales>()
                .eq("order_item_id", oi.getId())
                .eq("status", Constants.ORDER_SALES_STATUS.AGREED.name())
        );
        if(count >= 2){
            throw new ValidationException("售后申请超过限额");
        }
 
        String title = count > 0 ? "第二次售后" : "";
 
        count = orderItemSalesMapper.selectCount(new QueryWrapper<OrderItemSales>()
                .eq("order_item_id", oi.getId())
                .eq("status", Constants.ORDER_SALES_STATUS.PENDING.name())
        );
        if(count > 0){
            throw new ValidationException("有未处理售后,无法申请");
        }
 
        OrderItemSales s = new OrderItemSales();
        s.setId(UUIDGenerator.getUUID());
        s.setOrderId(oi.getOrderId());
        s.setOrderItemId(oi.getId());
        s.setSalesNo(getSalesNo());
        s.setNum(num);
        s.setTitle(title);
        s.setPictures(toJSONString(dto.getPictureList()));
        s.setVideos(toJSONString(dto.getVideoList()));
        s.setReason(dto.getReason());
        s.setStatus(Constants.ORDER_SALES_STATUS.PENDING.name());
        s.create(userId);
        s.setSalesType(dto.getSalesType());
        orderItemSalesMapper.insert(s);
 
        return s.getId();
    }
 
    private String getSalesNo(){
        String seq  = sequenceNo.getSeqNo(SequenceNo.ORDER_ITEM_SALES);
        return "SH" + format(LocalDateTime.now(), "yyyyMMdd") + seq;
    }
 
    public void cancelSales(String id){
        OrderItemSales s = orderItemSalesMapper.selectById(id);
        String userId = SecurityUtils.getUserId();
        if(!userId.equals(s.getCreateBy())){
            throw new ValidationException("无权操作");
        }
 
        String status = s.getStatus();
        if(!Constants.SALES_STATUS.PENDING.name().equals(status)){
            throw new ValidationException("已处理完成不用取消");
        }
 
        s.setStatus(Constants.SALES_STATUS.CANCEL.name());
        s.update(userId);
        orderItemSalesMapper.updateById(s);
    }
 
    public List<OrderStatusCountDTO> getSalesStatusCount(OrderItemSalesQueryDTO dto) {
        dto.setOrderStartDate(parseLocalDateTime(dto.getOrderStartDateStr()));
        dto.setOrderEndDate(parseLocalDateTime(dto.getOrderEndDateStr()));
        dto.setSalesStartDate(parseLocalDateTime(dto.getSalesStartDateStr()));
        dto.setSalesEndDate(parseLocalDateTime(dto.getSalesEndDateStr()));
 
        List<CodeValueDTO> ls = codeService.searchValue("ORDER_SALES_STATUS");
        List<OrderStatusCountDTO> ll = orderItemSalesMapper.getSalesStatusCount(dto);
        Map<String, Integer> llMap = new HashMap<>();
        if (ll != null && ll.size() > 0) {
            for (OrderStatusCountDTO c : ll) {
                llMap.put(c.getValue(), c.getOrderCount());
            }
        }
 
        List<OrderStatusCountDTO> rr = new ArrayList<>();
        for (CodeValueDTO c : ls) {
            OrderStatusCountDTO r = new OrderStatusCountDTO();
            r.setValue(c.getValue());
            r.setLabel(c.getLabel());
            Integer count = llMap.get(r.getValue());
            r.setOrderCount(count == null ? 0 : count);
 
            rr.add(r);
        }
 
        return rr;
    }
 
    public Page<OrderItemSalesNewListDTO> selectSalesList(Page page, OrderItemSalesQueryDTO dto){
        dto.setOrderStartDate(parseLocalDateTime(dto.getOrderStartDateStr(), true));
        dto.setOrderEndDate(parseLocalDateTime(dto.getOrderEndDateStr(), false));
        dto.setSalesStartDate(parseLocalDateTime(dto.getSalesStartDateStr(), true));
        dto.setSalesEndDate(parseLocalDateTime(dto.getSalesEndDateStr(), false));
 
        List<OrderItemSalesNewListDTO> ls = orderItemSalesMapper.selectItemSalesList(page, dto);
 
        page.setRecords(ls);
        return page;
    }
 
    public void exportSalesList(HttpServletResponse response, OrderItemSalesQueryDTO dto){
        dto.setOrderStartDate(parseLocalDateTime(dto.getOrderStartDateStr(), true));
        dto.setOrderEndDate(parseLocalDateTime(dto.getOrderEndDateStr(), false));
        dto.setSalesStartDate(parseLocalDateTime(dto.getSalesStartDateStr(), true));
        dto.setSalesEndDate(parseLocalDateTime(dto.getSalesEndDateStr(), false));
 
        List<OrderItemSalesNewListDTO> ls = orderItemSalesMapper.selectItemSalesList(null, dto);
        codeDecorator.decorate(ls);
 
        String[] rowsName = new String[]{"集货站", "商品名称", "商品单位", "商品颜色", "商品等级"
                , "商品分类", "收货人", "收货人手机号码", "收货地址", "商品数量", "供应商名称", "商品售价"
                , "总金额", "订单号", "售后单号", "标题", "申请数量", "理由", "实际退款", "审核结果"
                , "申请时间", "平台回复"};
        List<Object[]> dataList = new ArrayList<>();
 
        for (OrderItemSalesNewListDTO d : ls) {
            Object[] objs = new Object[rowsName.length];
            int a = 0;
            objs[a++] = d.getStationName();
            objs[a++] = d.getFlowerName();
            objs[a++] = d.getFlowerUnit();
            objs[a++] = d.getFlowerColor();
            objs[a++] = d.getFlowerLevelStr();
            objs[a++] = d.getFlowerCategory();
            objs[a++] = d.getCustomer();
            objs[a++] = d.getCustomerTel();
            objs[a++] = d.getCustomerAddress();
            objs[a++] = d.getFlowerNum();
            objs[a++] = d.getSupplierName();
            objs[a++] = d.getPrice();
            objs[a++] = d.getTotal();
            objs[a++] = d.getOrderNo();
            objs[a++] = d.getSalesNo();
            objs[a++] = d.getTitle();
            objs[a++] = d.getNum();
            objs[a++] = d.getReason();
            objs[a++] = d.getTotalFee();
            objs[a++] = d.getStatusStr();
            objs[a++] = format(d.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
            objs[a++] = d.getRemarks();
 
            dataList.add(objs);
        }
 
        ExcelExportUtil excelExportUtil = new ExcelExportUtil("售后申请列表", rowsName, dataList, response);
        try {
            response.addHeader("filename", URLEncoder.encode("售后申请列表.xls", "UTF-8"));
            response.addHeader("Access-Control-Expose-Headers", "filename");
            excelExportUtil.export();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
 
    public OrderItemSalesNewDTO getSalesInfo(String id){
        OrderItemSalesNewDTO rr = new OrderItemSalesNewDTO();
        OrderItemSales sl = orderItemSalesMapper.selectById(id);
        if(sl == null){
            throw new ValidationException("售后单不存在");
        }
 
        BeanUtils.copyProperties(sl, rr);
        rr.setPictureList(parseArray(sl.getPictures(), String.class));
        rr.setVideoList(parseArray(sl.getVideos(), String.class));
 
        Order o = orderMapper.selectById(sl.getOrderId());
        rr.setOrderNo(o.getOrderNo());
        rr.setCustomer(o.getCustomer());
        rr.setCustomerTel(o.getCustomerTel());
        rr.setCustomerProvince(o.getCustomerProvince());
        rr.setCustomerCity(o.getCustomerCity());
        rr.setCustomerRegion(o.getCustomerRegion());
        rr.setCustomerAddress(o.getCustomerAddress());
        rr.setOrderTime(o.getCreateTime());
 
        OrderItem oi = orderItemMapper.selectById(sl.getOrderItemId());
        rr.setFlowerName(oi.getFlowerName());
        rr.setFlowerUnit(oi.getFlowerUnit());
        rr.setFlowerColor(oi.getFlowerColor());
        rr.setFlowerCover(oi.getFlowerCover());
        rr.setFlowerLevel(oi.getFlowerLevel());
        rr.setFlowerCategory(oi.getFlowerCategory());
        rr.setFlowerNum(oi.getNum());
        rr.setSupplierName(oi.getSupplierName());
        rr.setPrice(oi.getPrice());
        rr.setTotal(oi.getTotal());
        rr.setSupplierPrice(oi.getSupplierPrice());
        rr.setMarkupPartner(oi.getMarkupPartner());
 
        Long stationId = oi.getStationId();
        if(stationId != null) {
            Station s = stationMapper.selectById(oi.getStationId());
            rr.setStationName(s.getName());
        }
 
        return rr;
    }
 
    public OrderItem doAudit(OrderItemSalesAuditDTO dto, String status){
        OrderItemSales sl = orderItemSalesMapper.selectById(dto.getId());
        if(sl == null){
            throw new ValidationException("售后单不存在");
        }
        if(!Constants.ORDER_SALES_STATUS.PENDING.name().equals(sl.getStatus())){
            throw new ValidationException("不可操作");
        }
 
        OrderItem oi = orderItemMapper.selectById(sl.getOrderItemId());
        if(oi == null){
            throw new ValidationException("订单商品不存在");
        }
 
        BigDecimal feeSupplier = getAmount(dto.getFeeSupplier());
        BigDecimal feePartner = getAmount(dto.getFeePartner());
        BigDecimal feePlatform = getAmount(dto.getFeePlatform());
        BigDecimal feePlatformPack = getAmount(dto.getFeePlatformPack());
        BigDecimal feePlatformCheck = getAmount(dto.getFeePlatformCheck());
        BigDecimal feePlatformTransport = getAmount(dto.getFeePlatformTransport());
 
        BigDecimal totalFee = feeSupplier.add(feePartner).add(feePlatform).add(feePlatformPack)
                .add(feePlatformCheck).add(feePlatformTransport);
 
        BigDecimal st = oi.getPrice().multiply(new BigDecimal(sl.getNum()));//申请售后的花的金额
        if(totalFee.doubleValue() > st.doubleValue()){
            throw new ValidationException("退款金额不能大于商品申请数量的售价");
        }
 
        List<OrderItemSales> ls = orderItemSalesMapper.selectList(new QueryWrapper<OrderItemSales>()
                .eq("order_item_id", oi.getId())
                .eq("status", Constants.ORDER_SALES_STATUS.AGREED.name())
        );
        BigDecimal preFee = new BigDecimal(0);
        if(ls != null && ls.size() > 0){
            for(OrderItemSales s : ls){
                preFee = preFee.add(s.getTotalFee());
            }
        }
        preFee = preFee.add(totalFee);
        if(preFee.doubleValue() > oi.getTotal().doubleValue()){
            throw new ValidationException("退款总金额不能大于商品总价");
        }
 
        sl.setRemarks(dto.getRemarks());
        sl.setFeeSupplier(feeSupplier);
        sl.setFeePartner(feePartner);
        sl.setFeePlatform(feePlatform);
        sl.setFeePlatformPack(feePlatformPack);
        sl.setFeePlatformCheck(feePlatformCheck);
        sl.setFeePlatformTransport(feePlatformTransport);
        sl.setTotalFee(totalFee);
        sl.setStatus(status);
        sl.setAuditTime(LocalDateTime.now());
        sl.update(SecurityUtils.getUserId());
 
        if(Constants.ORDER_SALES_STATUS.AGREED.name().equals(sl.getStatus())){
            if(totalFee.doubleValue() > 0) {
                Order o = orderMapper.selectById(sl.getOrderId());
                String refundId = paymentV3Service.refundOrderSub(o, totalFee);
                sl.setRefundId(refundId);
            }
        }
 
        orderItemSalesMapper.updateById(sl);
 
        return oi;
    }
}