This commit is contained in:
van
2026-10-08 00:01:07 +08:00
parent bdb9a5e099
commit 8b7d097f23
4 changed files with 551 additions and 0 deletions
@@ -5,6 +5,7 @@ import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
@@ -16,6 +17,7 @@ import com.ruoyi.jarvis.domain.GroupRebateExcelUpload;
import com.ruoyi.jarvis.domain.OrderRows; import com.ruoyi.jarvis.domain.OrderRows;
import com.ruoyi.jarvis.service.IGroupRebateExcelUploadService; import com.ruoyi.jarvis.service.IGroupRebateExcelUploadService;
import com.ruoyi.jarvis.service.impl.GroupRebateExcelImportService; import com.ruoyi.jarvis.service.impl.GroupRebateExcelImportService;
import com.ruoyi.jarvis.service.impl.RebateSheetConvertService;
import com.ruoyi.jarvis.service.IOrderRowsService; import com.ruoyi.jarvis.service.IOrderRowsService;
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONObject;
@@ -67,6 +69,7 @@ public class JDOrderListController extends BaseController
private final IOrderRowsService orderRowsService; private final IOrderRowsService orderRowsService;
private final IInstructionService instructionService; private final IInstructionService instructionService;
private final GroupRebateExcelImportService groupRebateExcelImportService; private final GroupRebateExcelImportService groupRebateExcelImportService;
private final RebateSheetConvertService rebateSheetConvertService;
private final IGroupRebateExcelUploadService groupRebateExcelUploadService; private final IGroupRebateExcelUploadService groupRebateExcelUploadService;
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
@@ -77,6 +80,7 @@ public class JDOrderListController extends BaseController
IOrderRowsService orderRowsService, IOrderRowsService orderRowsService,
IInstructionService instructionService, IInstructionService instructionService,
GroupRebateExcelImportService groupRebateExcelImportService, GroupRebateExcelImportService groupRebateExcelImportService,
RebateSheetConvertService rebateSheetConvertService,
IGroupRebateExcelUploadService groupRebateExcelUploadService, IGroupRebateExcelUploadService groupRebateExcelUploadService,
ObjectMapper objectMapper, ObjectMapper objectMapper,
ISysConfigService sysConfigService, ISysConfigService sysConfigService,
@@ -86,6 +90,7 @@ public class JDOrderListController extends BaseController
this.orderRowsService = orderRowsService; this.orderRowsService = orderRowsService;
this.instructionService = instructionService; this.instructionService = instructionService;
this.groupRebateExcelImportService = groupRebateExcelImportService; this.groupRebateExcelImportService = groupRebateExcelImportService;
this.rebateSheetConvertService = rebateSheetConvertService;
this.groupRebateExcelUploadService = groupRebateExcelUploadService; this.groupRebateExcelUploadService = groupRebateExcelUploadService;
this.objectMapper = objectMapper; this.objectMapper = objectMapper;
this.sysConfigService = sysConfigService; this.sysConfigService = sysConfigService;
@@ -261,6 +266,49 @@ public class JDOrderListController extends BaseController
} }
} }
/**
* 上传旧返现表,按订单号匹配系统订单,下载新表头 Excel。
* 旧表头:日期、单号、型号、总共返现。
* 新表头:日期、订单编号、型号、数量、成本价、实付价、后返金额。
*/
@Log(title = "返现表转换新表头", businessType = BusinessType.EXPORT)
@PostMapping("/convertRebateExcel")
public void convertRebateExcel(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException {
if (file == null || file.isEmpty()) {
writeJson(response, AjaxResult.error("请选择文件"));
return;
}
String name = file.getOriginalFilename();
if (name != null) {
String lower = name.toLowerCase(Locale.ROOT);
if (!lower.endsWith(".xls") && !lower.endsWith(".xlsx")) {
writeJson(response, AjaxResult.error("请上传 xls 或 xlsx 文件"));
return;
}
}
try {
RebateSheetConvertService.Result result = rebateSheetConvertService.convert(file.getInputStream());
if (result.getErrorMessage() != null) {
writeJson(response, AjaxResult.error(result.getErrorMessage()));
return;
}
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
FileUtils.setAttachmentResponseHeader(response, result.getFilename());
String summary = String.format(Locale.ROOT, "共%d行,已匹配%d,未找到订单%d,单号为空%d",
result.getTotalRows(), result.getMatched(), result.getUnmatched(), result.getBlankOrder());
response.setHeader("x-convert-summary", FileUtils.percentEncode(summary));
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename,x-convert-summary");
response.getOutputStream().write(result.getContent());
} catch (Exception e) {
writeJson(response, AjaxResult.error("转换失败: " + e.getMessage()));
}
}
private void writeJson(HttpServletResponse response, AjaxResult body) throws IOException {
response.setContentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8");
response.getWriter().write(JSON.toJSONString(body));
}
/** /**
* 后返表上传记录(分页) * 后返表上传记录(分页)
*/ */
@@ -80,6 +80,11 @@ public interface OrderRowsMapper
*/ */
public OrderRows selectOrderRowsByOrderId(String orderId); public OrderRows selectOrderRowsByOrderId(String orderId);
/**
* 按京东订单号批量取 SKU 数量。同一订单多行时按修改时间倒序,调用方取第一条。
*/
List<OrderRows> selectSkuNumByOrderIds(@Param("orderIds") List<String> orderIds);
/** /**
* 根据礼金Key查询订单列表 * 根据礼金Key查询订单列表
* *
@@ -0,0 +1,488 @@
package com.ruoyi.jarvis.service.impl;
import com.ruoyi.jarvis.domain.JDOrder;
import com.ruoyi.jarvis.domain.OrderRows;
import com.ruoyi.jarvis.mapper.JDOrderMapper;
import com.ruoyi.jarvis.mapper.OrderRowsMapper;
import com.ruoyi.jarvis.util.QuickRecordModelShopOptionUtil;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 把旧返现表(日期、单号、型号、总共返现)转成新表头,并用订单号回填数量、成本价、实付价、后返金额。
*/
@Service
public class RebateSheetConvertService {
private static final DataFormatter DATA_FORMATTER = new DataFormatter();
private static final String[] OUT_HEADERS = {
"日期", "订单编号", "型号", "数量", "成本价", "实付价", "后返金额", "匹配结果"
};
private static final int CHUNK = 400;
@Resource
private JDOrderMapper jdOrderMapper;
@Resource
private OrderRowsMapper orderRowsMapper;
public Result convert(InputStream in) throws Exception {
Result result = new Result();
try (Workbook workbook = WorkbookFactory.create(in)) {
if (workbook.getNumberOfSheets() <= 0) {
result.errorMessage = "Excel 里没有工作表";
return result;
}
Sheet sheet = workbook.getSheetAt(0);
int headerIndex = findHeaderRowIndex(sheet);
if (headerIndex < 0) {
result.errorMessage = "未找到表头。旧表需包含「单号」和「总共返现」;新表需包含「订单编号」。";
return result;
}
HeaderMap header = buildHeaderMap(sheet.getRow(headerIndex));
if (header.orderCol < 0) {
result.errorMessage = "未识别订单号列(「单号」或「订单编号」)";
return result;
}
List<SourceRow> rows = readRows(sheet, headerIndex, header);
if (rows.isEmpty()) {
result.errorMessage = "表头下没有数据行";
return result;
}
Map<String, JDOrder> orders = loadOrders(rows);
Map<String, Integer> skuNums = loadSkuNums(orders);
result.totalRows = rows.size();
result.content = writeWorkbook(rows, orders, skuNums, result);
result.filename = "返现表-新表头.xlsx";
return result;
}
}
private byte[] writeWorkbook(List<SourceRow> rows, Map<String, JDOrder> orders,
Map<String, Integer> skuNums, Result result) throws Exception {
try (XSSFWorkbook out = new XSSFWorkbook(); ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
Sheet sheet = out.createSheet("返现表");
CellStyle headerStyle = headerStyle(out);
CellStyle moneyStyle = moneyStyle(out);
CellStyle textStyle = textStyle(out);
Row headerRow = sheet.createRow(0);
for (int i = 0; i < OUT_HEADERS.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(OUT_HEADERS[i]);
cell.setCellStyle(headerStyle);
}
int excelRow = 1;
for (SourceRow src : rows) {
Row row = sheet.createRow(excelRow++);
JDOrder order = src.orderNo.isEmpty() ? null : orders.get(src.orderNo);
boolean matched = order != null;
if (src.orderNo.isEmpty()) {
result.blankOrder++;
} else if (matched) {
result.matched++;
} else {
result.unmatched++;
}
String orderNo = matched && order.getOrderId() != null && !order.getOrderId().trim().isEmpty()
? order.getOrderId().trim() : src.orderNo;
String model = src.model;
if ((model == null || model.isEmpty()) && matched) {
model = QuickRecordModelShopOptionUtil.fullModelNumber(order);
}
BigDecimal rebate = src.sheetRebate;
if (rebate == null && matched && order.getRebateAmount() != null) {
rebate = BigDecimal.valueOf(order.getRebateAmount());
}
BigDecimal pay = matched && order.getPaymentAmount() != null
? BigDecimal.valueOf(order.getPaymentAmount()) : null;
BigDecimal cost = null;
if (pay != null) {
BigDecimal reb = rebate != null ? rebate : BigDecimal.ZERO;
BigDecimal extra = order.getExtraCost() != null
? BigDecimal.valueOf(order.getExtraCost()) : BigDecimal.ZERO;
cost = pay.subtract(reb).add(extra);
}
Integer qty = null;
if (matched) {
Integer sku = skuNums.get(src.orderNo);
qty = (sku != null && sku > 0) ? sku : 1;
}
writeText(row, 0, src.dateText, textStyle);
writeText(row, 1, orderNo, textStyle);
writeText(row, 2, model, textStyle);
if (qty != null) {
Cell qtyCell = row.createCell(3);
qtyCell.setCellValue(qty);
}
writeMoney(row, 4, cost, moneyStyle);
writeMoney(row, 5, pay, moneyStyle);
if (rebate != null) {
writeMoney(row, 6, rebate, moneyStyle);
} else {
writeText(row, 6, src.sheetRebateRaw, textStyle);
}
String status;
if (src.orderNo.isEmpty()) {
status = "单号为空";
} else if (matched) {
status = "已匹配";
} else {
status = "未找到订单";
}
writeText(row, 7, status, textStyle);
}
int[] widths = {14, 22, 28, 10, 14, 14, 14, 16};
for (int i = 0; i < widths.length; i++) {
sheet.setColumnWidth(i, widths[i] * 256);
}
sheet.createFreezePane(0, 1);
out.write(bos);
return bos.toByteArray();
}
}
private Map<String, JDOrder> loadOrders(List<SourceRow> rows) {
Set<String> ids = new LinkedHashSet<>();
for (SourceRow row : rows) {
if (!row.orderNo.isEmpty()) {
ids.add(row.orderNo);
}
}
Map<String, JDOrder> map = new HashMap<>();
if (ids.isEmpty()) {
return map;
}
List<String> all = new ArrayList<>(ids);
for (int i = 0; i < all.size(); i += CHUNK) {
List<String> chunk = all.subList(i, Math.min(i + CHUNK, all.size()));
List<JDOrder> found = jdOrderMapper.selectLatestJDOrdersByOrderIds(chunk);
if (found == null) {
continue;
}
for (JDOrder order : found) {
if (order == null || order.getOrderId() == null) {
continue;
}
map.putIfAbsent(normalizeOrderNo(order.getOrderId()), order);
}
}
return map;
}
private Map<String, Integer> loadSkuNums(Map<String, JDOrder> orders) {
Set<String> ids = new LinkedHashSet<>();
for (String orderNo : orders.keySet()) {
if (orderNo.matches("\\d+")) {
ids.add(orderNo);
}
}
Map<String, Integer> map = new HashMap<>();
if (ids.isEmpty()) {
return map;
}
List<String> all = new ArrayList<>(ids);
for (int i = 0; i < all.size(); i += CHUNK) {
List<String> chunk = all.subList(i, Math.min(i + CHUNK, all.size()));
List<OrderRows> found = orderRowsMapper.selectSkuNumByOrderIds(chunk);
if (found == null) {
continue;
}
for (OrderRows row : found) {
if (row == null || row.getOrderId() == null) {
continue;
}
map.putIfAbsent(String.valueOf(row.getOrderId()), row.getSkuNum());
}
}
return map;
}
private static List<SourceRow> readRows(Sheet sheet, int headerIndex, HeaderMap header) {
List<SourceRow> rows = new ArrayList<>();
for (int i = headerIndex + 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
SourceRow src = new SourceRow();
src.dateText = cellText(row, header.dateCol);
src.orderNo = normalizeOrderNo(cellText(row, header.orderCol));
src.model = cellText(row, header.modelCol);
String rebateText = firstNonEmpty(cellText(row, header.totalRebateCol), cellText(row, header.rebateCol));
src.sheetRebateRaw = rebateText;
src.sheetRebate = parseMoney(rebateText);
if (src.dateText.isEmpty() && src.orderNo.isEmpty() && src.model.isEmpty() && rebateText.isEmpty()) {
continue;
}
rows.add(src);
}
return rows;
}
private static int findHeaderRowIndex(Sheet sheet) {
int maxScan = Math.min(15, sheet.getLastRowNum() + 1);
for (int i = 0; i < maxScan; i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
boolean hasOrder = false;
boolean hasMarker = false;
for (int c = 0; c <= row.getLastCellNum() && c < 64; c++) {
String h = normalizeHeader(cellText(row, c));
if (h.isEmpty()) {
continue;
}
if (isOrderHeader(h)) {
hasOrder = true;
}
if ("日期".equals(h) || "型号".equals(h) || h.contains("总共返现") || h.contains("后返金额")) {
hasMarker = true;
}
}
if (hasOrder && hasMarker) {
return i;
}
}
return -1;
}
private static HeaderMap buildHeaderMap(Row headerRow) {
HeaderMap hm = new HeaderMap();
for (int c = 0; c <= headerRow.getLastCellNum() && c < 128; c++) {
String raw = normalizeHeader(cellText(headerRow, c));
if (raw.isEmpty()) {
continue;
}
if (hm.orderCol < 0 && isOrderHeader(raw)) {
hm.orderCol = c;
}
if (hm.dateCol < 0 && "日期".equals(raw)) {
hm.dateCol = c;
}
if (hm.modelCol < 0 && "型号".equals(raw)) {
hm.modelCol = c;
}
if (hm.totalRebateCol < 0 && raw.contains("总共返现")) {
hm.totalRebateCol = c;
}
if (hm.rebateCol < 0 && raw.contains("后返金额")) {
hm.rebateCol = c;
}
}
return hm;
}
private static boolean isOrderHeader(String h) {
if (h.contains("第三方")) {
return false;
}
if ("单号".equals(h) || h.startsWith("单号")) {
return true;
}
return h.contains("订单号") || h.contains("订单编号");
}
private static String normalizeHeader(String s) {
if (s == null) {
return "";
}
return s.replace('\n', ' ').replace('\r', ' ').replace(" ", "").trim();
}
private static String cellText(Row row, int col) {
if (row == null || col < 0) {
return "";
}
Cell cell = row.getCell(col);
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case STRING:
return cell.getStringCellValue() == null ? "" : cell.getStringCellValue().trim();
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
return DATA_FORMATTER.formatCellValue(cell).trim();
}
double d = cell.getNumericCellValue();
if (d == Math.floor(d) && Math.abs(d) < 1e16) {
return String.valueOf((long) d);
}
return DATA_FORMATTER.formatCellValue(cell).trim();
case BOOLEAN:
return Boolean.toString(cell.getBooleanCellValue());
case FORMULA:
try {
return DATA_FORMATTER.formatCellValue(cell).trim();
} catch (Exception e) {
return "";
}
default:
String formatted = DATA_FORMATTER.formatCellValue(cell);
return formatted == null ? "" : formatted.trim();
}
}
private static String normalizeOrderNo(String raw) {
if (raw == null) {
return "";
}
String t = raw.trim().replace(" ", "").replace("\u00A0", "");
if (t.endsWith(".0") && t.matches("\\d+\\.0")) {
t = t.substring(0, t.length() - 2);
}
return t;
}
private static BigDecimal parseMoney(String raw) {
if (raw == null) {
return null;
}
String t = raw.trim().replace(",", "").replace(",", "").replace("¥", "").replace("¥", "");
if (t.isEmpty() || "-".equals(t) || "—".equals(t)) {
return null;
}
try {
return new BigDecimal(t);
} catch (NumberFormatException e) {
return null;
}
}
private static String firstNonEmpty(String a, String b) {
if (a != null && !a.isEmpty()) {
return a;
}
return b == null ? "" : b;
}
private static void writeText(Row row, int col, String value, CellStyle style) {
Cell cell = row.createCell(col);
cell.setCellValue(value == null ? "" : value);
cell.setCellStyle(style);
}
private static void writeMoney(Row row, int col, BigDecimal value, CellStyle style) {
Cell cell = row.createCell(col);
if (value == null) {
cell.setCellValue("");
return;
}
cell.setCellValue(value.setScale(2, RoundingMode.HALF_UP).doubleValue());
cell.setCellStyle(style);
}
private static CellStyle headerStyle(Workbook wb) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setBold(true);
style.setFont(font);
style.setAlignment(HorizontalAlignment.CENTER);
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setBorderBottom(BorderStyle.THIN);
return style;
}
private static CellStyle moneyStyle(Workbook wb) {
CellStyle style = wb.createCellStyle();
style.setDataFormat(wb.createDataFormat().getFormat("0.00"));
return style;
}
private static CellStyle textStyle(Workbook wb) {
CellStyle style = wb.createCellStyle();
style.setDataFormat(wb.createDataFormat().getFormat("@"));
return style;
}
private static class HeaderMap {
int dateCol = -1;
int orderCol = -1;
int modelCol = -1;
int totalRebateCol = -1;
int rebateCol = -1;
}
private static class SourceRow {
String dateText = "";
String orderNo = "";
String model = "";
String sheetRebateRaw = "";
BigDecimal sheetRebate;
}
public static class Result {
private byte[] content;
private String filename;
private String errorMessage;
private int totalRows;
private int matched;
private int unmatched;
private int blankOrder;
public byte[] getContent() {
return content;
}
public String getFilename() {
return filename;
}
public String getErrorMessage() {
return errorMessage;
}
public int getTotalRows() {
return totalRows;
}
public int getMatched() {
return matched;
}
public int getUnmatched() {
return unmatched;
}
public int getBlankOrder() {
return blankOrder;
}
}
}
@@ -398,6 +398,16 @@
where order_id = #{orderId} where order_id = #{orderId}
</select> </select>
<select id="selectSkuNumByOrderIds" resultMap="OrderRowsResult">
select order_id, sku_num, modify_time
from order_rows
where order_id in
<foreach collection="orderIds" item="oid" open="(" separator="," close=")">
#{oid}
</foreach>
order by modify_time desc
</select>
<select id="selectOrderRowsByOrderNo" parameterType="String" resultMap="OrderRowsResult"> <select id="selectOrderRowsByOrderNo" parameterType="String" resultMap="OrderRowsResult">
<include refid="selectOrderRowsVo"/> <include refid="selectOrderRowsVo"/>
where order_id = #{orderNo} or parent_id = #{orderNo} where order_id = #{orderNo} or parent_id = #{orderNo}