From f2a7a8c774c78d3ec811a7bf06b84b9206314583 Mon Sep 17 00:00:00 2001 From: shahaibo <1023316923@qq.com> Date: Mon, 26 Aug 2024 16:36:44 +0800 Subject: [PATCH] TASK:mixi; --- .../common/tasks/MiTuExportScheduledTask.java | 5728 ++++++++--------- .../java/com/mixi/service/PythonService.java | 16 +- .../com/mixi/service/TAppProductService.java | 142 +- 3 files changed, 2935 insertions(+), 2951 deletions(-) diff --git a/src/main/java/com/mixi/common/tasks/MiTuExportScheduledTask.java b/src/main/java/com/mixi/common/tasks/MiTuExportScheduledTask.java index 1732eb1..ba6274a 100644 --- a/src/main/java/com/mixi/common/tasks/MiTuExportScheduledTask.java +++ b/src/main/java/com/mixi/common/tasks/MiTuExportScheduledTask.java @@ -1,1877 +1,1553 @@ -//package com.mixi.common.tasks; -// -//import com.alibaba.fastjson.JSON; -//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -//import com.mixi.common.tasks.mituExportEntity.*; -//import com.mixi.common.utils.CopyUtil; -//import com.mixi.common.utils.MinioUtil; -//import com.mixi.mapper.*; -//import com.mixi.mapper.entity.*; -//import com.mixi.model.dto.BatchUploadProductStoreStockDTO; -//import com.mixi.model.vo.TProductVO; -//import com.mixi.service.StoreService; -//import com.mixi.service.TProductService; -//import com.mixi.service.TProductStockService; -//import io.minio.errors.MinioException; -//import lombok.extern.slf4j.Slf4j; -//import org.apache.commons.compress.utils.IOUtils; -//import org.apache.poi.ss.usermodel.*; -//import org.apache.poi.ss.util.CellRangeAddress; -//import org.apache.poi.xssf.usermodel.XSSFWorkbook; -//import org.apache.commons.fileupload.FileItem; -//import org.apache.commons.fileupload.FileItemFactory; -//import org.apache.commons.fileupload.disk.DiskFileItemFactory; -//import org.springframework.context.annotation.Bean; -//import org.springframework.retry.annotation.Backoff; -//import org.springframework.retry.annotation.Retryable; -//import org.springframework.scheduling.annotation.Scheduled; -//import org.springframework.stereotype.Component; -//import org.springframework.util.CollectionUtils; -//import org.springframework.web.multipart.MultipartFile; -//import org.springframework.web.multipart.commons.CommonsMultipartFile; -// -//import javax.annotation.PostConstruct; -//import javax.annotation.Resource; -//import javax.imageio.ImageIO; -//import java.awt.*; -//import java.awt.image.BufferedImage; -//import java.io.*; -//import java.nio.file.Files; -//import java.nio.file.Paths; -//import java.sql.*; -//import java.time.*; -//import java.time.format.DateTimeFormatter; -//import java.time.temporal.TemporalAdjusters; -//import java.util.*; -//import java.util.Date; -//import java.util.List; -//import java.util.stream.Collectors; -// -//@Component -//@Slf4j -//public class MiTuExportScheduledTask { -// -// @Resource -// private MinioUtil minioUtil; -// -// static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; -// static final String DB_URL = "jdbc:sqlserver://118.142.0.178:1550;databaseName=Hayman_prod"; -// -// // 数据库凭据 -// static final String USER = "user01"; -// static final String PASS = "haySIS-0522"; -// -// @Resource -// private MiTuExportMapper miTuExportMapper; -// @Resource -// private MiTuProductMapper miTuProductMapper; -// @Resource -// private TProductMapper productMapper; -// -// @Resource -// private MiTuProductSellNumMapper miTuProductSellNumMapper; -// @PostConstruct -// public void executeWeeklyHeavyStockReport() { -//// customerPurchaseReport(); -//// NewJoinVIPReport(); -//// weeklySellThrReport(); -//// WeeklyHeavyStockReport(); -//// QuarterlyProductGroupingReport(); -//// customerTypeAnalysis(); -//// getBestSell(); -//// getData(); -//// runDailySalesIncentiveStatisticsForPast30Days(); -//// updateProductStock(); -// -// } -// -// @Resource -// private StoreService storeService; -// -// @Resource -// private TProductService productService; -// @Resource -// private TProductMapper tProductMapper; -// @Resource -// private TProductStockService tProductStockService; -// -// // 更新商品库存 -// private void updateProductStock() { -// log.info(String.valueOf(LocalDateTime.now())); -// -// // 根据当前已有店铺查询商品店铺库存 -// List miTuProductStock = new ArrayList<>(); -// List storeList = storeService.list(); -// HashMap storeMap = new HashMap<>(); -// for (TStore tStore : storeList) { -// storeMap.put(tStore.getName(), tStore.getId()); -// } -// List storeNameList = storeList.stream().map(TStore::getName).collect(Collectors.toList()); -// QueryWrapper qw = new QueryWrapper<>(); -// List productList = productMapper.selectList(qw); -// for (TProduct tProduct : productList) { -// QueryWrapper miTuProductQueryWrapper = new QueryWrapper<>(); -// miTuProductQueryWrapper.lambda().eq(MiTuProduct::getProductId, tProduct.getId()); -// List miTuProductList = miTuProductMapper.selectList(miTuProductQueryWrapper); -// if (!CollectionUtils.isEmpty(storeNameList)) { -// miTuProductStock = productService.getMiTuProductStock(miTuProductList.get(0).getPluCode(), miTuProductList.get(0).getColor()); -// miTuProductStock = miTuProductStock.stream().filter(o -> storeNameList.contains(o.getWhCode())).collect(Collectors.toList()); +package com.mixi.common.tasks; + +import com.alibaba.fastjson.JSON; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.mixi.common.tasks.mituExportEntity.*; +import com.mixi.common.utils.CopyUtil; +import com.mixi.common.utils.MinioUtil; +import com.mixi.mapper.*; +import com.mixi.mapper.entity.*; +import com.mixi.model.dto.BatchUploadProductStoreStockDTO; +import com.mixi.model.vo.TProductVO; +import com.mixi.service.StoreService; +import com.mixi.service.TProductService; +import com.mixi.service.TProductStockService; +import io.minio.errors.MinioException; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.compress.utils.IOUtils; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileItemFactory; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.Retryable; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.commons.CommonsMultipartFile; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.sql.*; +import java.time.*; +import java.time.format.DateTimeFormatter; +import java.time.temporal.TemporalAdjusters; +import java.util.*; +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; + +@Component +@Slf4j +public class MiTuExportScheduledTask { + + @Resource + private MinioUtil minioUtil; + + static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; + static final String DB_URL = "jdbc:sqlserver://118.142.0.178:1550;databaseName=Hayman_prod"; + + // 数据库凭据 + static final String USER = "user01"; + static final String PASS = "haySIS-0522"; + + @Resource + private MiTuExportMapper miTuExportMapper; + @Resource + private MiTuProductMapper miTuProductMapper; + @Resource + private TProductMapper productMapper; + + @Resource + private MiTuProductSellNumMapper miTuProductSellNumMapper; + @PostConstruct + public void executeWeeklyHeavyStockReport() { +// customerPurchaseReport(); +// NewJoinVIPReport(); +// weeklySellThrReport(); +// WeeklyHeavyStockReport(); +// QuarterlyProductGroupingReport(); +// customerTypeAnalysis(); +// getBestSell(); +// getData(); +// runDailySalesIncentiveStatisticsForPast30Days(); +// updateProductStock(); + + } + + @Resource + private StoreService storeService; + + @Resource + private TProductService productService; + @Resource + private TProductMapper tProductMapper; + @Resource + private TProductStockService tProductStockService; + + // 更新商品库存 + private void updateProductStock() { + log.info(String.valueOf(LocalDateTime.now())); + + // 根据当前已有店铺查询商品店铺库存 + List miTuProductStock = new ArrayList<>(); + List storeList = storeService.list(); + HashMap storeMap = new HashMap<>(); + for (TStore tStore : storeList) { + storeMap.put(tStore.getName(), tStore.getId()); + } + List storeNameList = storeList.stream().map(TStore::getName).collect(Collectors.toList()); + QueryWrapper qw = new QueryWrapper<>(); + List productList = productMapper.selectList(qw); + for (TProduct tProduct : productList) { + QueryWrapper miTuProductQueryWrapper = new QueryWrapper<>(); + miTuProductQueryWrapper.lambda().eq(MiTuProduct::getProductId, tProduct.getId()); + List miTuProductList = miTuProductMapper.selectList(miTuProductQueryWrapper); + if (!CollectionUtils.isEmpty(storeNameList)) { + miTuProductStock = productService.getMiTuProductStock(miTuProductList.get(0).getPluCode(), miTuProductList.get(0).getColor()); + miTuProductStock = miTuProductStock.stream().filter(o -> storeNameList.contains(o.getWhCode())).collect(Collectors.toList()); + } + int total = 0; + for (MiTuProductStock tuProductStock : miTuProductStock) { + total = total + tuProductStock.getNum(); + } + tProduct.setTotal(total); + tProductMapper.updateById(tProduct); +// List productStockList = new ArrayList<>(); + HashMap> map = new HashMap<>(); + QueryWrapper deleteQw = new QueryWrapper<>(); + deleteQw.lambda().eq(TProductStock::getProductId, tProduct.getId()); + tProductStockService.deleteByProductId(tProduct.getId()); + for (MiTuProductStock mituProductStock : miTuProductStock) { + if (map.containsKey(mituProductStock.getWhCode())) { + BatchUploadProductStoreStockDTO dto = new BatchUploadProductStoreStockDTO(); + dto.setSize(mituProductStock.getSize()); + dto.setNum(mituProductStock.getNum()); + map.get(mituProductStock.getWhCode()).add(dto); + }else { + List dtoList = new ArrayList<>(); + BatchUploadProductStoreStockDTO dto = new BatchUploadProductStoreStockDTO(); + dto.setSize(mituProductStock.getSize()); + dto.setNum(mituProductStock.getNum()); + dtoList.add(dto); + map.put(mituProductStock.getWhCode(), dtoList); + } + } + for (String whCode : map.keySet()) { + Long storeId = storeMap.get(whCode); + List batchUploadProductStoreStockDTOS = map.get(whCode); + String jsonString = com.alibaba.fastjson2.JSON.toJSONString(batchUploadProductStoreStockDTOS); + TProductStock tProductStock = TProductStock.builder() + .productId(tProduct.getId()) + .storeId(storeId) + .stockContent(jsonString) + .createDate(new Date()) + .build(); + tProductStockService.save(tProductStock); + } +// for (MiTuProduct miTuProduct : miTuProductList) { +// miTuProduct.setProductId(tProduct.getId()); +// miTuProductMapper.insert(miTuProduct); // } -// int total = 0; -// for (MiTuProductStock tuProductStock : miTuProductStock) { -// total = total + tuProductStock.getNum(); -// } -// tProduct.setTotal(total); -// tProductMapper.updateById(tProduct); -//// List productStockList = new ArrayList<>(); -// HashMap> map = new HashMap<>(); -// QueryWrapper deleteQw = new QueryWrapper<>(); -// deleteQw.lambda().eq(TProductStock::getProductId, tProduct.getId()); -// tProductStockService.deleteByProductId(tProduct.getId()); -// for (MiTuProductStock mituProductStock : miTuProductStock) { -// if (map.containsKey(mituProductStock.getWhCode())) { -// BatchUploadProductStoreStockDTO dto = new BatchUploadProductStoreStockDTO(); -// dto.setSize(mituProductStock.getSize()); -// dto.setNum(mituProductStock.getNum()); -// map.get(mituProductStock.getWhCode()).add(dto); -// }else { -// List dtoList = new ArrayList<>(); -// BatchUploadProductStoreStockDTO dto = new BatchUploadProductStoreStockDTO(); -// dto.setSize(mituProductStock.getSize()); -// dto.setNum(mituProductStock.getNum()); -// dtoList.add(dto); -// map.put(mituProductStock.getWhCode(), dtoList); -// } -// } -// for (String whCode : map.keySet()) { -// Long storeId = storeMap.get(whCode); -// List batchUploadProductStoreStockDTOS = map.get(whCode); -// String jsonString = com.alibaba.fastjson2.JSON.toJSONString(batchUploadProductStoreStockDTOS); -// TProductStock tProductStock = TProductStock.builder() -// .productId(tProduct.getId()) -// .storeId(storeId) -// .stockContent(jsonString) -// .createDate(new Date()) -// .build(); -// tProductStockService.save(tProductStock); -// } -//// for (MiTuProduct miTuProduct : miTuProductList) { -//// miTuProduct.setProductId(tProduct.getId()); -//// miTuProductMapper.insert(miTuProduct); -//// } -// } -// log.info(String.valueOf(LocalDateTime.now())); -// } -// -//// public static void main(String[] args) { -//// LocalDate today = LocalDate.now(); -//// for (int i = 0; i < 30; i++) { -//// // 将这一天的商品销售数量入库 -//// test(today); -//// System.out.println(today); -////// miTuProductSellNumEntry(today, productListAll); -//// today = today.minusDays(1); -//// } -//// } -//// public static void test(LocalDate today) { -//// today = today.minusDays(1); -//// } -// -// @Scheduled(cron = "0 0 1 * * ?") -// private void getBestSell() { -// QueryWrapper bestSellIsNotNull = new QueryWrapper<>(); -//// bestSellIsNotNull.lambda().isNotNull(TProduct::getBestSell); -// List productListAll = productMapper.selectList(bestSellIsNotNull); + } + log.info(String.valueOf(LocalDateTime.now())); + } + +// public static void main(String[] args) { // LocalDate today = LocalDate.now(); // for (int i = 0; i < 30; i++) { // // 将这一天的商品销售数量入库 -// miTuProductSellNumEntry(today, productListAll); +// test(today); +// System.out.println(today); +//// miTuProductSellNumEntry(today, productListAll); // today = today.minusDays(1); // } -//// for (TProduct tProduct : productList1) { -//// tProduct.setBestSell(null); -//// productMapper.updateById(tProduct); -//// } -//// Map> itemNameMap = getBestSellItemNameList(); -//// for (String s : itemNameMap.keySet()) { -//// if (s.equals("yesterdayItemNameList")) { -//// QueryWrapper qw = new QueryWrapper<>(); -//// qw.lambda().in(MiTuProduct::getItemName, itemNameMap.get(s)); -//// List miTuProductList = miTuProductMapper.selectList(qw); -//// if (!CollectionUtils.isEmpty(miTuProductList)) { -//// Set collect = miTuProductList.stream().map(MiTuProduct::getProductId).collect(Collectors.toSet()); -//// if (!CollectionUtils.isEmpty(collect)) { -//// QueryWrapper qwBestSell = new QueryWrapper<>(); -//// qwBestSell.lambda().in(TProduct::getId, new ArrayList<>(collect)); -//// List productList = productMapper.selectList(qwBestSell); -//// if (!CollectionUtils.isEmpty(productList)) { -//// for (TProduct tProduct : productList) { -//// tProduct.setBestSell("1"); -//// productMapper.updateById(tProduct); -//// } -//// } -//// } -//// } -//// } -//// if (s.equals("lastWeekItemNameList")) { -//// QueryWrapper qw = new QueryWrapper<>(); -//// qw.lambda().in(MiTuProduct::getItemName, itemNameMap.get(s)); -//// List miTuProductList = miTuProductMapper.selectList(qw); -//// if (!CollectionUtils.isEmpty(miTuProductList)) { -//// Set collect = miTuProductList.stream().map(MiTuProduct::getProductId).collect(Collectors.toSet()); -//// if (!CollectionUtils.isEmpty(collect)) { -//// QueryWrapper qwBestSell = new QueryWrapper<>(); -//// qwBestSell.lambda().in(TProduct::getId, new ArrayList<>(collect)); -//// List productList = productMapper.selectList(qwBestSell); -//// if (!CollectionUtils.isEmpty(productList)) { -//// for (TProduct tProduct : productList) { -//// if (StringUtils.isEmpty(tProduct.getBestSell())) { -//// tProduct.setBestSell("2"); -//// }else { -//// tProduct.setBestSell(tProduct.getBestSell() + ",2"); -//// } -//// productMapper.updateById(tProduct); -//// } -//// } -//// } -//// } -//// } -//// if (s.equals("lastMonthItemNameList")) { -//// QueryWrapper qw = new QueryWrapper<>(); -//// qw.lambda().in(MiTuProduct::getItemName, itemNameMap.get(s)); -//// List miTuProductList = miTuProductMapper.selectList(qw); -//// if (!CollectionUtils.isEmpty(miTuProductList)) { -//// Set collect = miTuProductList.stream().map(MiTuProduct::getProductId).collect(Collectors.toSet()); -//// if (!CollectionUtils.isEmpty(collect)) { -//// QueryWrapper qwBestSell = new QueryWrapper<>(); -//// qwBestSell.lambda().in(TProduct::getId, new ArrayList<>(collect)); -//// List productList = productMapper.selectList(qwBestSell); -//// if (!CollectionUtils.isEmpty(productList)) { -//// for (TProduct tProduct : productList) { -//// if (StringUtils.isEmpty(tProduct.getBestSell())) { -//// tProduct.setBestSell("3"); -//// }else { -//// tProduct.setBestSell(tProduct.getBestSell() + ",3"); -//// } -//// productMapper.updateById(tProduct); -//// } -//// } -//// } -//// } -//// } -//// } // } -// -// private void miTuProductSellNumEntry(LocalDate today, List productListAll) { -// String endDate = formatDate(today); -// String startDate = formatDate(today.minusDays(1)); -// for (TProduct product : productListAll) { -// String pictureName = product.getPictureName(); -// String[] split = pictureName.split("_"); -// String itemName = split[0]; -// String color = split[1]; -// MiTuProductSellNum miTuProductSellNum = getProductSellNum(itemName, color, startDate, endDate); -// miTuProductSellNum.setProductId(product.getId()); -// miTuProductSellNumMapper.insert(miTuProductSellNum); -// } +// public static void test(LocalDate today) { +// today = today.minusDays(1); // } -// -// private MiTuProductSellNum getProductSellNum(String itemName, String color, String startDate, String endDate) { -// Connection conn = null; -// Statement stmt = null; -// MiTuProductSellNum miTuProductSellNum = new MiTuProductSellNum(); -// try { -// // 注册 JDBC 驱动器 -// Class.forName(JDBC_DRIVER); -// -// // 打开一个连接 -// System.out.println("连接数据库..."); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// -// // 执行查询 -// System.out.println("创建声明..."); -// stmt = conn.createStatement(); -// String sql; -// sql = "SELECT SH_CODE, count(1) as num FROM v_MZG020B\n" + -// "WHERE TRX_DATE >= '" + startDate + "'\n" + -// "AND TRX_DATE < '" + endDate + "'\n" + -// "AND ITEM_NAME = '" + itemName + "'\n" + -// "AND COLOR = '" + color + "'\n" + -// "GROUP BY SH_CODE"; -// -// ResultSet rs = stmt.executeQuery(sql); -// // 处理结果集 -// while (rs.next()) { -// miTuProductSellNum.setSellNum(rs.getInt("num")); -// miTuProductSellNum.setSellDate(LocalDate.parse(startDate)); -// miTuProductSellNum.setShCode(rs.getString("SH_CODE")); -// } -// // 清理环境 -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException | ClassNotFoundException e) { -// // 处理异常 -// e.printStackTrace(); + + @Scheduled(cron = "0 0 1 * * ?") + private void getBestSell() { + QueryWrapper bestSellIsNotNull = new QueryWrapper<>(); +// bestSellIsNotNull.lambda().isNotNull(TProduct::getBestSell); + List productListAll = productMapper.selectList(bestSellIsNotNull); + LocalDate today = LocalDate.now(); + for (int i = 0; i < 30; i++) { + // 将这一天的商品销售数量入库 + miTuProductSellNumEntry(today, productListAll); + today = today.minusDays(1); + } +// for (TProduct tProduct : productList1) { +// tProduct.setBestSell(null); +// productMapper.updateById(tProduct); // } -// System.out.println("查询执行完成!"); -// return miTuProductSellNum; -// } -// -// // 格式化日期为字符串 -// private static String formatDate(LocalDate date) { -// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); -// return date.format(formatter); -// } -// private Map> getBestSellItemNameList() { -// Map> result = new HashMap<>(); -// // 获取当前日期 -// LocalDate currentDate = LocalDate.now(); -// // 格式化当前日期 -// String currentDateString = formatDate(currentDate); -// -// // 获取前一天日期 -// LocalDate yesterdayDate = currentDate.minusDays(1); -// // 格式化前一天日期 -// String yesterdayDateString = formatDate(yesterdayDate); -// -// // 获取前一周日期 -// LocalDate lastWeekDate = currentDate.minusWeeks(1); -// // 格式化前一周日期 -// String lastWeekDateString = formatDate(lastWeekDate); -// -// // 获取前一个月日期 -// LocalDate lastMonthDate = currentDate.minusMonths(1); -// // 格式化前一个月日期 -// String lastMonthDateString = formatDate(lastMonthDate); -// Connection conn = null; -// Statement stmt = null; -// try { -// // 注册 JDBC 驱动器 -// Class.forName(JDBC_DRIVER); -// -// // 打开一个连接 -// System.out.println("连接数据库..."); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// -// // 执行查询 -// System.out.println("创建声明..."); -// stmt = conn.createStatement(); -// String sql; -// sql = "SELECT TOP 20 ITEM_NAME FROM v_MZG020B\n" + -// " WHERE TRX_DATE >= '" + yesterdayDateString + "'\n" + -// " AND TRX_DATE < '" + currentDateString + "'\n" + -// " AND ITEM_NAME != 'Shopping Bag Fee'\n" + -// " GROUP BY ITEM_NAME\n" + -// " ORDER BY COUNT(1) DESC"; -// -// ResultSet rs = stmt.executeQuery(sql); -// // 处理结果集 -// List yesterdayItemNameList = new ArrayList<>(); -// while (rs.next()) { -// yesterdayItemNameList.add(rs.getString("ITEM_NAME")); -// } -// result.put("yesterdayItemNameList", yesterdayItemNameList); -// sql = "SELECT TOP 20 ITEM_NAME FROM v_MZG020B\n" + -// " WHERE TRX_DATE >= '" + lastWeekDateString + "'\n" + -// " AND TRX_DATE < '" + currentDateString + "'\n" + -// " AND ITEM_NAME != 'Shopping Bag Fee'\n" + -// " GROUP BY ITEM_NAME\n" + -// " ORDER BY COUNT(1) DESC"; -// -// rs = stmt.executeQuery(sql); -// // 处理结果集 -// List lastWeekItemNameList = new ArrayList<>(); -// while (rs.next()) { -// lastWeekItemNameList.add(rs.getString("ITEM_NAME")); -// } -// result.put("lastWeekItemNameList", lastWeekItemNameList); -// sql = "SELECT TOP 20 ITEM_NAME FROM v_MZG020B\n" + -// " WHERE TRX_DATE >= '" + lastMonthDateString + "'\n" + -// " AND TRX_DATE < '" + currentDateString + "'\n" + -// " AND ITEM_NAME != 'Shopping Bag Fee'\n" + -// " GROUP BY ITEM_NAME\n" + -// " ORDER BY COUNT(1) DESC"; -// -// rs = stmt.executeQuery(sql); -// // 处理结果集 -// List lastMonthItemNameList = new ArrayList<>(); -// while (rs.next()) { -// lastMonthItemNameList.add(rs.getString("ITEM_NAME")); -// } -// result.put("lastMonthItemNameList", lastMonthItemNameList); -// -// // 清理环境 -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException | ClassNotFoundException e) { -// // 处理异常 -// e.printStackTrace(); -// } -// System.out.println("查询执行完成!"); -// return result; -// } -// -// /** -// * Customer purchase report -// */ -// @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000)) -// @Scheduled(cron = "0 0 23 28-31 * ?") -// public void customerPurchaseReport() { -// final Calendar c = Calendar.getInstance(); -// // 如果是最后一天 则执行定时任务 -// if (c.get(Calendar.DATE) == c.getActualMaximum(Calendar.DATE)) { -// MiTuExport miTuExport = createMiTuExport("Customer purchase report", "month"); -// try { -// List transactionData = retrieveTransactionData(); -// List userMembers = transactionData.stream().map(TransactionData::getUserMember).collect(Collectors.toList()); -// List customerData = retrieveCustomerData(userMembers); -// updateCustomerDataWithTransactionData(customerData, transactionData); -// String filePath = miTuExport.getExportName()+".xlsx"; -// exportToExcelCustomerPurchaseReport(customerData, filePath); -// miTuExport.setUrl("mi-tu/export/" + filePath); -// miTuExport.setStatus(1); -// } catch (Exception e) { -// miTuExport.setStatus(0); -// e.printStackTrace(); -// } finally { -// miTuExportMapper.insert(miTuExport); -// System.out.println("接口执行完成!"); -// } -// }else { -// MiTuExport miTuExport = createMiTuExport("Customer purchase report", "month"); -// try { -// List transactionData = retrieveTransactionData(); -// List userMembers = transactionData.stream().map(TransactionData::getUserMember).collect(Collectors.toList()); -// List customerData = retrieveCustomerData(userMembers); -// updateCustomerDataWithTransactionData(customerData, transactionData); -// String filePath = miTuExport.getExportName()+".xlsx"; -// exportToExcelCustomerPurchaseReport(customerData, filePath); -// miTuExport.setUrl("mi-tu/export/" + filePath); -// miTuExport.setStatus(1); -// } catch (Exception e) { -// miTuExport.setStatus(0); -// e.printStackTrace(); -// } finally { -// miTuExportMapper.insert(miTuExport); -// System.out.println("接口执行完成!"); -// } -// } -// } -// -// private MiTuExport createMiTuExport(String fileName, String period) { -// LocalDateTime currentDateTime = LocalDateTime.now(); -// LocalDateTime startTime; -// LocalDateTime endTime; -// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); -// String exportName; -// -// switch (period) { -// case "week": -// startTime = currentDateTime.with(DayOfWeek.MONDAY).with(LocalTime.MIN); -// endTime = currentDateTime.with(DayOfWeek.SUNDAY).with(LocalTime.MAX); -// exportName = fileName + " week " + currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd")); -// break; -// case "month": -// startTime = currentDateTime.withDayOfMonth(1).with(LocalTime.MIN); -// endTime = currentDateTime.withDayOfMonth(currentDateTime.toLocalDate().lengthOfMonth()).with(LocalTime.MAX); -// exportName = fileName + " month " + currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd")); -// break; -// case "year": -// startTime = currentDateTime.withDayOfYear(1).with(LocalTime.MIN); -// endTime = currentDateTime.withDayOfYear(currentDateTime.toLocalDate().lengthOfYear()).with(LocalTime.MAX); -// exportName = fileName + " year " + currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd")); -// break; -// case "quarter": -// // 获取当前季度的第一个月和最后一个月 -// int currentQuarter = (currentDateTime.getMonthValue() - 1) / 3 + 1; -// int firstMonthOfQuarter = (currentQuarter - 1) * 3 + 1; -// int lastMonthOfQuarter = currentQuarter * 3; -// -// // 获取当前季度的起始时间和结束时间 -// startTime = currentDateTime.withMonth(firstMonthOfQuarter).withDayOfMonth(1).with(LocalTime.MIN); -// endTime = currentDateTime.withMonth(lastMonthOfQuarter).with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX); -// -// // 设置导出名称 -// exportName = fileName + " quarter " + currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd")); -// break; -// default: -// throw new IllegalArgumentException("Invalid period argument: " + period); -// } -// -// String startOfPeriod = startTime.format(formatter); -// String endOfPeriod = endTime.format(formatter); -// -// MiTuExport miTuExport = new MiTuExport(); -// miTuExport.setExportName(exportName); -// miTuExport.setSpan(period); -// miTuExport.setCreateTime(LocalDateTime.now()); -// miTuExport.setDataTime(startOfPeriod + " - " + endOfPeriod); -// return miTuExport; -// } -// -// -// private void updateCustomerDataWithTransactionData(List customerDataList, List transactionDataList) { -// for (TransactionData transactionDatum : transactionDataList) { -// for (CustomerData customerDatum : customerDataList) { -// if (customerDatum.getMbrCode().equals(transactionDatum.getUserMember())) { -// customerDatum.setThisMonth(transactionDatum.getThisMonth()); -// customerDatum.setMonth1(transactionDatum.getMonth1()); -// customerDatum.setMonth2(transactionDatum.getMonth2()); -// customerDatum.setMonth3(transactionDatum.getMonth3()); -// customerDatum.setMonth4(transactionDatum.getMonth4()); -// customerDatum.setMonth5(transactionDatum.getMonth5()); -// customerDatum.setMonth6(transactionDatum.getMonth6()); -// customerDatum.setMonth7(transactionDatum.getMonth7()); -// customerDatum.setMonth8(transactionDatum.getMonth8()); -// customerDatum.setMonth9(transactionDatum.getMonth9()); -// customerDatum.setMonth10(transactionDatum.getMonth10()); -// customerDatum.setMonth11(transactionDatum.getMonth11()); -// customerDatum.setMonth12(transactionDatum.getMonth12()); -// break; -// } -// } -// } -// } -// -// -// /** -// * New Join VIP report -// */ -// @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000)) -// @Scheduled(cron = "0 0 23 ? * 7") -// public void NewJoinVIPReport() { -// MiTuExport miTuExport = createMiTuExport("New join vip report", "week"); -// try { -// List transactionNewCustomerList = getTransactionNewCustomerList(); -// String filePath = miTuExport.getExportName()+".xlsx"; -// miTuExport.setUrl("mi-tu/export/" + filePath); -// exportNewJoinVIPReport(transactionNewCustomerList, filePath); -// miTuExport.setStatus(1); -// } catch (Exception e) { -// miTuExport.setStatus(0); -// e.printStackTrace(); -// } finally { -// miTuExportMapper.insert(miTuExport); -// System.out.println("接口执行完成!"); -// } -// } -// -// private void exportNewJoinVIPReport(List transactionNewCustomerList, String filePathName) throws IOException { -// String currentPath = Paths.get("").toAbsolutePath().toString(); -// File file = new File(currentPath + "/" + filePathName); -// // 如果文件不存在或者为空,则创建一个新的 Workbook -// Workbook workbook = new XSSFWorkbook(); -// -// // 创建一个新的 Sheet 或获取现有的 Sheet -// Sheet sheet = workbook.getSheet("Transaction New Customer"); -// if (sheet == null) { -// sheet = workbook.createSheet("Transaction New Customer"); -// } -// -// // 创建标题行 -// Row headerRow = sheet.getRow(0); -// if (headerRow == null) { -// headerRow = sheet.createRow(0); -// } -// -// // 写入标题行 -// headerRow.createCell(0).setCellValue("shCode"); -// headerRow.createCell(1).setCellValue("userMember"); -// headerRow.createCell(2).setCellValue("mbrName"); -// headerRow.createCell(3).setCellValue("mbrMobile"); -// headerRow.createCell(4).setCellValue("joinDate"); -// headerRow.createCell(5).setCellValue("salesAmt"); -// headerRow.createCell(6).setCellValue("vipGrade"); -// headerRow.createCell(7).setCellValue("salesmanName"); -// -// // 写入数据 -// int rowNum = sheet.getLastRowNum() + 1; -// for (TransactionNewCustomer transactionNewCustomer : transactionNewCustomerList) { -// Row row = sheet.createRow(rowNum++); -// -// row.createCell(0).setCellValue(transactionNewCustomer.getShCode()); -// row.createCell(1).setCellValue(transactionNewCustomer.getUserMember()); -// row.createCell(2).setCellValue(transactionNewCustomer.getMbrName()); -// row.createCell(3).setCellValue(transactionNewCustomer.getMbrMobile()); -// row.createCell(4).setCellValue(transactionNewCustomer.getJoinDate()); -// row.createCell(5).setCellValue(transactionNewCustomer.getSalesAmt()); -// row.createCell(6).setCellValue(transactionNewCustomer.getVipGrade()); -// row.createCell(7).setCellValue(transactionNewCustomer.getSalesmanName()); -// } -// -// // 将Workbook写入文件 -// try (FileOutputStream outputStream = new FileOutputStream(file)) { -// workbook.write(outputStream); -// } -// FileItem a = getMultipartFile(file, file.getName()); -// MultipartFile multipartFile = new CommonsMultipartFile(a); -// minioUtil.upload("mi-tu", "export", multipartFile); -// System.out.println("Excel file has been created successfully!"); -// } -// -// -// /** -// * Weekly Sell Through Report -// */ -// @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000)) -// @Scheduled(cron = "0 0 23 ? * 7") -// public void weeklySellThrReport() { -// MiTuExport miTuExport = createMiTuExport("Weekly sell thr report", "week"); -// try { -// List transactionSummaryList = getTransactionSummaryList(); -// String filePath = miTuExport.getExportName()+".xlsx"; -// miTuExport.setUrl("mi-tu/export/" + filePath); -// exportWeeklySellThrReport(transactionSummaryList, filePath); -// miTuExport.setStatus(1); -// } catch (Exception e) { -// miTuExport.setStatus(0); -// e.printStackTrace(); -// } finally { -// miTuExportMapper.insert(miTuExport); -// System.out.println("接口执行完成!"); -// } -// } -// -// private void exportWeeklySellThrReport(List transactionSummaryList, String filePathName) throws IOException { -// String currentPath = Paths.get("").toAbsolutePath().toString(); -// File file = new File(currentPath + "/" + filePathName); -// Workbook workbook = new XSSFWorkbook(); -// Sheet sheet = workbook.createSheet("Weekly Sell Through Report"); -// -// Row headerRow = sheet.createRow(0); -// String[] headers = {"PLU_CODE", "ToShopDate", "SalesDay", "CATEGORY", "SUB_CAT", "ItemName", -// "PriceOriginal", "ToRetailQty", "TotalSaleNum", "MAS_count", "MEL_count", -// "MPC_count", "MPS_count", "MTF_count", "MWP_count", "MYO_count", -// "LwSalesQty", "RetailOnHand", "SalesRate", "Product Image"}; -// for (int i = 0; i < headers.length; i++) { -// headerRow.createCell(i).setCellValue(headers[i]); -// } -// -// int rowNum = 1; -// int startRow = rowNum; -// String previousPluCode = ""; -// String imagePath = ""; -// -// for (TransactionSummary summary : transactionSummaryList) { -// if (!summary.getPLU_CODE().equals(previousPluCode)) { -// if (startRow < rowNum) { -// mergeCells(sheet, startRow, rowNum - 1); -// linkImageToCell(workbook, sheet, startRow, rowNum - 1, headers.length - 1, imagePath); -// } -// startRow = rowNum; -// previousPluCode = summary.getPLU_CODE(); -// imagePath = getImagePath(summary.getPLU_CODE()); -// } -// -// Row row = sheet.createRow(rowNum); -// row.createCell(0).setCellValue(summary.getPLU_CODE()); -// // 填充其他列的数据 -// row.createCell(1).setCellValue(summary.getToShopDate() != null ? summary.getToShopDate().toString() : ""); -// row.createCell(2).setCellValue(summary.getSalesDay()); -// row.createCell(3).setCellValue(summary.getCATEGORY()); -// row.createCell(4).setCellValue(summary.getSUB_CAT()); -// row.createCell(5).setCellValue(summary.getItemName()); -// row.createCell(6).setCellValue(summary.getPriceOriginal()); -// row.createCell(7).setCellValue(summary.getToRetailQty()); -// row.createCell(8).setCellValue(summary.getTotalSaleNum()); -// row.createCell(9).setCellValue(summary.getMAS_count()); -// row.createCell(10).setCellValue(summary.getMEL_count()); -// row.createCell(11).setCellValue(summary.getMPC_count()); -// row.createCell(12).setCellValue(summary.getMPS_count()); -// row.createCell(13).setCellValue(summary.getMTF_count()); -// row.createCell(14).setCellValue(summary.getMWP_count()); -// row.createCell(15).setCellValue(summary.getMYO_count()); -// row.createCell(16).setCellValue(summary.getLwSalesQty()); -// row.createCell(17).setCellValue(summary.getRetailOnHand()); -// row.createCell(18).setCellValue(summary.getSalesRate()); -// -// rowNum++; -// } -// -// // 处理最后一个PLU_CODE的数据 -// if (startRow < rowNum) { -// mergeCells(sheet, startRow, rowNum - 1); -// linkImageToCell(workbook, sheet, startRow, rowNum - 1, headers.length - 1, imagePath); -// } -// -// -// try (FileOutputStream outputStream = new FileOutputStream(file)) { -// workbook.write(outputStream); -// } -// -// FileItem a = getMultipartFile(file, file.getName()); -// MultipartFile multipartFile = new CommonsMultipartFile(a); -// minioUtil.upload("mi-tu", "export", multipartFile); -// } -// -// -// /** -// * WeeklyHeavyStockReport -// */ -// @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000)) -// @Scheduled(cron = "0 0 23 ? * 7") -// public void WeeklyHeavyStockReport() { -// MiTuExport miTuExport = createMiTuExport("Weekly heavy stock report", "week"); -// try { -// List weeklyHeavyStockList = getWeeklyHeavyStockList(); -// String filePath = miTuExport.getExportName()+".xlsx"; -// miTuExport.setUrl("mi-tu/export/" + filePath); -// exportWeeklyHeavyStock(weeklyHeavyStockList, filePath); -// miTuExport.setStatus(1); -// } catch (Exception e) { -// miTuExport.setStatus(0); -// e.printStackTrace(); -// } finally { -// miTuExportMapper.insert(miTuExport); -// System.out.println("接口执行完成!"); -// } -// } -// -// private void exportWeeklyHeavyStock(List weeklyHeavyStockList, String weeklyHeavyStockReportName) throws IOException { -// String currentPath = Paths.get("").toAbsolutePath().toString(); -// File file = new File(currentPath + "/" + weeklyHeavyStockReportName); -// Workbook workbook = new XSSFWorkbook(); -// Sheet sheet = workbook.createSheet("Weekly Heavy Stock Report"); -// -// Row headerRow = sheet.createRow(0); -// String[] headers = {"PLU_CODE", "item_name", "item_barcode", "cat", "sub_cat", "Col", "price_sales", -// "MAS", "MEL", "MPC", "MPS", "MTF", "MWP", "MYO", "MHZ", "MRT", "MBZ", "TLT", -// "subtotal", "G.TLT", "Product Image"}; -// for (int i = 0; i < headers.length; i++) { -// headerRow.createCell(i).setCellValue(headers[i]); -// } -// -// int rowNum = 1; -// int startRow = rowNum; -// String previousPluCode = ""; -// String imagePath = ""; -// -// for (WeeklyHeavyStock weeklyHeavyStock : weeklyHeavyStockList) { -// if (!weeklyHeavyStock.getPLU_CODE().equals(previousPluCode)) { -// if (startRow < rowNum - 1) { -// mergeCells(sheet, startRow, rowNum - 1); -// linkImageToCell(workbook, sheet, startRow, rowNum - 1, headers.length - 1, imagePath); -// } -// startRow = rowNum; -// previousPluCode = weeklyHeavyStock.getPLU_CODE(); -// imagePath = getImagePath(weeklyHeavyStock.getPLU_CODE()); -// } -// -// Row row = sheet.createRow(rowNum); -// row.createCell(0).setCellValue(weeklyHeavyStock.getPLU_CODE()); -// // 填充其他列的数据 -// row.createCell(1).setCellValue(weeklyHeavyStock.getItem_name()); -// row.createCell(2).setCellValue(weeklyHeavyStock.getItem_barcode()); -// row.createCell(3).setCellValue(weeklyHeavyStock.getCat()); -// row.createCell(4).setCellValue(weeklyHeavyStock.getSub_cat()); -// row.createCell(5).setCellValue(weeklyHeavyStock.getCol()); -// row.createCell(6).setCellValue(weeklyHeavyStock.getPrice_sales()); -// row.createCell(7).setCellValue(weeklyHeavyStock.getMAS()); -// row.createCell(8).setCellValue(weeklyHeavyStock.getMEL()); -// row.createCell(9).setCellValue(weeklyHeavyStock.getMPC()); -// row.createCell(10).setCellValue(weeklyHeavyStock.getMPS()); -// row.createCell(11).setCellValue(weeklyHeavyStock.getMTF()); -// row.createCell(12).setCellValue(weeklyHeavyStock.getMWP()); -// row.createCell(13).setCellValue(weeklyHeavyStock.getMYO()); -// row.createCell(14).setCellValue(weeklyHeavyStock.getMHZ()); -// row.createCell(15).setCellValue(weeklyHeavyStock.getMRT()); -// row.createCell(16).setCellValue(weeklyHeavyStock.getMBZ()); -// row.createCell(17).setCellValue(weeklyHeavyStock.getTLT()); -// row.createCell(18).setCellValue(weeklyHeavyStock.getSubtotal()); -// row.createCell(19).setCellValue(weeklyHeavyStock.getG_TLT()); -// -// rowNum++; -// } -// -// if (startRow < rowNum - 1 || previousPluCode != null) { -// mergeCells(sheet, startRow, rowNum - 1); -// linkImageToCell(workbook, sheet, startRow, rowNum - 1, headers.length - 1, imagePath); -// } -// -// try (FileOutputStream outputStream = new FileOutputStream(file)) { -// workbook.write(outputStream); -// } -// -// FileItem a = getMultipartFile(file, file.getName()); -// MultipartFile multipartFile = new CommonsMultipartFile(a); -// minioUtil.upload("mi-tu", "export", multipartFile); -// } -// -// -// -// /** -// * Quarterly Product Grouping Report -// */ -// @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000)) -// @Scheduled(cron = "#{@calculateLastDayOfQuarterCron}") -// public void QuarterlyProductGroupingReport() { -// MiTuExport miTuExport = createMiTuExport("Quarterly product grouping report", "quarter"); -// try { -// List QuarterlyProductGroupingList = getQuarterlyProductGroupingList(); -// String filePath = miTuExport.getExportName()+".xlsx"; -// miTuExport.setUrl("mi-tu/export/" + filePath); -// exportQuarterlyProductGrouping(QuarterlyProductGroupingList, filePath); -// miTuExport.setStatus(1); -// } catch (Exception e) { -// miTuExport.setStatus(0); -// e.printStackTrace(); -// } finally { -// miTuExportMapper.insert(miTuExport); -// System.out.println("接口执行完成!"); -// } -// } -// @Bean -// public String calculateLastDayOfQuarterCron() { -// // 获取当前日期 -// LocalDate currentDate = LocalDate.now(); -// -// // 计算下一个季度的最后一天 -// Month currentMonth = currentDate.getMonth(); -// Month nextQuarterStartMonth = currentMonth.plus(3 - currentMonth.getValue() % 3); -// LocalDate nextQuarterStartDate = LocalDate.of(currentDate.getYear(), nextQuarterStartMonth, 1); -// LocalDate lastDayOfNextQuarter = nextQuarterStartDate.with(TemporalAdjusters.lastDayOfMonth()); -// -// // 将日期转换成 Cron 表达式的格式 -// int year = lastDayOfNextQuarter.getYear(); -// int month = lastDayOfNextQuarter.getMonthValue(); -// int dayOfMonth = lastDayOfNextQuarter.getDayOfMonth(); -// return String.format("0 0 22 %d %d ?", dayOfMonth, month); -// } -// -// public void exportQuarterlyProductGrouping(List weeklyHeavyStockList, String weeklyHeavyStockReportName) throws IOException { -// String currentPath = Paths.get("").toAbsolutePath().toString(); -// File file = new File(currentPath + "/" + weeklyHeavyStockReportName); -// -// // 创建工作簿和工作表 -// Workbook workbook = new XSSFWorkbook(); -// Sheet sheet = workbook.createSheet("Quarterly Product Grouping Report"); -// -// // 添加报表头 -// Row titleRow = sheet.createRow(0); -// Cell titleCell = titleRow.createCell(0); -// titleCell.setCellValue("FW24 STOCK LIST"); -// sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 26)); // 合并标题单元格 -// -// // 添加“Stock on hand - shop”和“Stock on hand - back office” -// Row stockHeaderRow = sheet.createRow(1); -// -// Cell stockShopCell = stockHeaderRow.createCell(10); -// stockShopCell.setCellValue("Stock on hand - shop"); -// sheet.addMergedRegion(new CellRangeAddress(1, 1, 10, 16)); // 适当调整列的范围 -// -// Cell stockOfficeCell = stockHeaderRow.createCell(17); -// stockOfficeCell.setCellValue("Stock on hand - back office"); -// sheet.addMergedRegion(new CellRangeAddress(1, 1, 17, 19)); // 适当调整列的范围 -// -// // 创建标题行 -// Row headerRow = sheet.createRow(2); -// String[] headers = {"Image", "Plu Code", "Col", "Size", "Item Code", "Item Name", "Cat", "Sub_Cat", "RSP", -// "HK Sell-thru", "Shop total Sold", // 新增字段 -// "MAS Sold", "MEL Sold", "MPC Sold", "MPS Sold", "MTF Sold", "MWP Sold", "MYO Sold", -// "MAS", "MEL", "MPC", "MPS", "MTF", "MWP", "MYO", "MRT", "MBZ", "MHZ"}; -// -// for (int i = 0; i < headers.length; i++) { -// headerRow.createCell(i).setCellValue(headers[i]); -// } -// -//// // 自动调整除Image列外的其他列宽度 -//// for (int i = 1; i < headers.length; i++) { -//// sheet.autoSizeColumn(i); -//// } -// -// // 写入数据和插入图片 -// int rowNum = 3; // 数据从第四行开始 -// int startRow = rowNum; -// String previousPluCode = ""; -// String imagePath = ""; -// -// for (WeeklyHeavyStock weeklyHeavyStock : weeklyHeavyStockList) { -// if (!weeklyHeavyStock.getPLU_CODE().equals(previousPluCode)) { -// // 新的PLU_CODE,合并之前的单元格,并插入图片 -// if (startRow < rowNum - 1) { -// mergeCells(sheet, startRow, rowNum - 1); -// linkImageToCell(workbook, sheet, startRow, rowNum - 1, 0, imagePath); // 插入图片到合并单元格 -// } -// startRow = rowNum; -// previousPluCode = weeklyHeavyStock.getPLU_CODE(); -// imagePath = getImagePath(weeklyHeavyStock.getPLU_CODE()); -// } -// -// // 计算“Shop total Sold” -// int shopTotalSold = weeklyHeavyStock.getMASSOLD() + weeklyHeavyStock.getMELSOLD() + -// weeklyHeavyStock.getMPCSOLD() + weeklyHeavyStock.getMPSSOLD() + -// weeklyHeavyStock.getMTFSOLD() + weeklyHeavyStock.getMWPSOLD() + -// weeklyHeavyStock.getMYOSOLD(); -// -// // 计算“HK Sell-thru” -// int stockOnHand = weeklyHeavyStock.getMAS() + weeklyHeavyStock.getMEL() + -// weeklyHeavyStock.getMPC() + weeklyHeavyStock.getMPS() + -// weeklyHeavyStock.getMTF() + weeklyHeavyStock.getMWP() + -// weeklyHeavyStock.getMYO() + weeklyHeavyStock.getMRT() + -// weeklyHeavyStock.getMBZ() + weeklyHeavyStock.getMHZ(); -// -// String hkSellThru = stockOnHand > 0 ? String.format("%.0f%%", (double) shopTotalSold / stockOnHand * 100) : "0%"; -// -// Row row = sheet.createRow(rowNum); -// row.createCell(1).setCellValue(weeklyHeavyStock.getPLU_CODE()); -// row.createCell(2).setCellValue(weeklyHeavyStock.getCol()); -// row.createCell(3).setCellValue(weeklyHeavyStock.getSize()); -// row.createCell(4).setCellValue(weeklyHeavyStock.getItem_barcode()); -// row.createCell(5).setCellValue(weeklyHeavyStock.getItem_name()); -// row.createCell(6).setCellValue(weeklyHeavyStock.getCat()); -// row.createCell(7).setCellValue(weeklyHeavyStock.getSub_cat()); -// row.createCell(8).setCellValue(weeklyHeavyStock.getPrice_sales()); -// row.createCell(9).setCellValue(hkSellThru); // 填入计算的HK Sell-thru -// row.createCell(10).setCellValue(shopTotalSold); // 填入计算的Shop total Sold -// row.createCell(11).setCellValue(weeklyHeavyStock.getMASSOLD()); -// row.createCell(12).setCellValue(weeklyHeavyStock.getMELSOLD()); -// row.createCell(13).setCellValue(weeklyHeavyStock.getMPCSOLD()); -// row.createCell(14).setCellValue(weeklyHeavyStock.getMPSSOLD()); -// row.createCell(15).setCellValue(weeklyHeavyStock.getMTFSOLD()); -// row.createCell(16).setCellValue(weeklyHeavyStock.getMWPSOLD()); -// row.createCell(17).setCellValue(weeklyHeavyStock.getMYOSOLD()); -// row.createCell(18).setCellValue(weeklyHeavyStock.getMAS()); -// row.createCell(19).setCellValue(weeklyHeavyStock.getMEL()); -// row.createCell(20).setCellValue(weeklyHeavyStock.getMPC()); -// row.createCell(21).setCellValue(weeklyHeavyStock.getMPS()); -// row.createCell(22).setCellValue(weeklyHeavyStock.getMTF()); -// row.createCell(23).setCellValue(weeklyHeavyStock.getMWP()); -// row.createCell(24).setCellValue(weeklyHeavyStock.getMYO()); -// row.createCell(25).setCellValue(weeklyHeavyStock.getMRT()); -// row.createCell(26).setCellValue(weeklyHeavyStock.getMBZ()); -// row.createCell(27).setCellValue(weeklyHeavyStock.getMHZ()); -// -// rowNum++; -// } -// -// // 确保处理最后一个Plu Code -// if (startRow < rowNum - 1 || previousPluCode != null) { -// mergeCells(sheet, startRow, rowNum - 1); -// linkImageToCell(workbook, sheet, startRow, rowNum - 1, 0, imagePath); -// } -// -// // 将工作簿写入文件 -// try (FileOutputStream outputStream = new FileOutputStream(file)) { -// workbook.write(outputStream); -// } catch (IOException e) { -// e.printStackTrace(); -// } -// -// // 上传文件 -// FileItem a = getMultipartFile(file, file.getName()); -// MultipartFile multipartFile = new CommonsMultipartFile(a); -// minioUtil.upload("mi-tu", "export", multipartFile); -// -// System.out.println("Excel file has been created successfully!"); -// } -// -// private void mergeCells(Sheet sheet, int startRow, int endRow) { -// // 合并单元格 -// if (startRow < endRow) { -// for (int i = 1; i <= 1; i++) { // 只合并Plu Code列 -// sheet.addMergedRegion(new CellRangeAddress(startRow, endRow, i, i)); -// } -// } -// } -// -// private void linkImageToCell(Workbook workbook, Sheet sheet, int startRow, int endRow, int colNum, String imagePath) throws IOException { -// try (InputStream inputStream = minioUtil.download("mi-tu/26/BOTTOM/PANTS/MKTS27000_0CMY_copy.jpg")) { -// byte[] bytes = IOUtils.toByteArray(inputStream); -// int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG); -// -// CreationHelper helper = workbook.getCreationHelper(); -// Drawing drawing = sheet.createDrawingPatriarch(); -// ClientAnchor anchor = helper.createClientAnchor(); -// -// // 将图片设置为150x150像素的大小,并转换为EMU单位 -// int widthInEMU = 150 * 9525; -// int heightInEMU = 150 * 9525; -// -// // 设置图片的插入位置和大小,确保只覆盖Image列 -// anchor.setCol1(colNum); // 设置开始列为Image列 -// anchor.setRow1(startRow); // 设置开始行 -// anchor.setCol2(colNum); // 设置结束列为Image列,不应影响Plu Code列 -// anchor.setRow2(endRow + 1); // 设置结束行 -// -// // 设置图片的宽度和高度 -// anchor.setDx1(0); // 起始点x偏移量 -// anchor.setDy1(0); // 起始点y偏移量 -// anchor.setDx2(widthInEMU); // 结束点x偏移量,使得图片只占用Image列的空间 -// anchor.setDy2(heightInEMU); // 结束点y偏移量 -// -// Picture pict = drawing.createPicture(anchor, pictureIdx); -// -// // 设置Image列的宽度为150像素 -// sheet.setColumnWidth(colNum, 150 * 35); // 设置列宽,Excel列宽的单位为1/256个字符宽度 -// -//// // 自动调整除Image列外的其他列宽度 -//// for (int i = 1; i < sheet.getRow(2).getLastCellNum(); i++) { -//// sheet.autoSizeColumn(i); -//// } -// -// // 计算行数和每行的高度 -// int totalRows = endRow - startRow + 1; -// int rowHeight = (150 * 15) / totalRows; // 计算每行的高度,单位为1/20点 -// -// for (int i = startRow; i <= endRow; i++) { -// sheet.getRow(i).setHeight((short) rowHeight); // 设置每一行的行高 -// } -// } catch (MinioException e) { -// throw new RuntimeException(e); -// } -// } -// -// private String getImagePath(String pluCode) { -// // 假设图片路径与 PLU_CODE 相关,例如:return "path/to/images/" + pluCode + ".jpg"; -// return "C:\\Users\\10233\\Desktop\\2024 SS\\MKTS27000_0CMY.jpg"; // 示例路径 -// } -// -// private static List getQuarterlyProductGroupingList() { -// List QuarterlyProductGroupingList = new ArrayList<>(); -// Connection conn = null; -// Statement stmt = null; -// try { -// Class.forName(JDBC_DRIVER); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// stmt = conn.createStatement(); -// -// String sql = "WITH CountedData AS (\n" + -// " SELECT\n" + -// " WHCODE,\n" + -// " PLU_CODE,\n" + -// " item_name,\n" + -// " item_barcode,\n" + -// " cat,\n" + -// " sub_cat,\n" + -// " Col,\n" + -// " Size,\n" + -// " price_sales,\n" + -// " CASE WHEN WHCODE = 'MAS' THEN 1 ELSE 0 END AS MAS,\n" + -// " CASE WHEN WHCODE = 'MEL' THEN 1 ELSE 0 END AS MEL,\n" + -// " CASE WHEN WHCODE = 'MPC' THEN 1 ELSE 0 END AS MPC,\n" + -// " CASE WHEN WHCODE = 'MPS' THEN 1 ELSE 0 END AS MPS,\n" + -// " CASE WHEN WHCODE = 'MTF' THEN 1 ELSE 0 END AS MTF,\n" + -// " CASE WHEN WHCODE = 'MWP' THEN 1 ELSE 0 END AS MWP,\n" + -// " CASE WHEN WHCODE = 'MYO' THEN 1 ELSE 0 END AS MYO,\n" + -// " CASE WHEN WHCODE = 'MHZ' THEN 1 ELSE 0 END AS MHZ,\n" + -// " CASE WHEN WHCODE = 'MRT' THEN 1 ELSE 0 END AS MRT,\n" + -// " CASE WHEN WHCODE = 'MBZ' THEN 1 ELSE 0 END AS MBZ\n" + -// " FROM\n" + -// " (\n" + -// " SELECT\n" + -// " WHCODE,\n" + -// " PLU_CODE,\n" + -// " item_name,\n" + -// " item_code AS item_barcode,\n" + -// " CATEGORY AS cat,\n" + -// " SUB_CAT AS sub_cat,\n" + -// " COLOR AS Col,\n" + -// " SIZE AS SIZE,\n" + -// " price_original as price_sales\n" + -// " FROM\n" + -// " v_MZG003A \n" + -// " WHERE\n" + -// " PLU_CODE IN (SELECT TOP 3\n" + -// "PLU_CODE\n" + -// "FROM v_MZG020B\n" + -// "WHERE TRX_DATE >= '2024-03-04'\n" + -// "AND TRX_DATE <= '2024-03-10'\n" + -// "AND SH_CODE IN ('MAS', 'MEL', 'MPC', 'MPS', 'MTF', 'MWP', 'MYO')\n" + -// "GROUP BY PLU_CODE\n" + -// "ORDER BY count(1) desc)\n" + -// " AND item_active = 'Y' \n" + -// " AND WHCODE IN ('MAS', 'MEL', 'MPC', 'MPS', 'MTF', 'MWP', 'MYO', 'MHZ', 'MRT', 'MBZ')\n" + -// " ) AS v \n" + -// ") \n" + -// "SELECT\n" + -// " PLU_CODE,\n" + -// " item_name,\n" + -// " item_barcode,\n" + -// " cat,\n" + -// " sub_cat,\n" + -// " Col,\n" + -// " Size,\n" + -// " price_sales,\n" + -// " SUM(MAS) AS MAS,\n" + -// " SUM(MEL) AS MEL,\n" + -// " SUM(MPC) AS MPC,\n" + -// " SUM(MPS) AS MPS,\n" + -// " SUM(MTF) AS MTF,\n" + -// " SUM(MWP) AS MWP,\n" + -// " SUM(MYO) AS MYO,\n" + -// " SUM(MHZ) AS MHZ,\n" + -// " SUM(MRT) AS MRT,\n" + -// " SUM(MBZ) AS MBZ\n" + -// "FROM\n" + -// " CountedData \n" + -// "GROUP BY\n" + -// " PLU_CODE,\n" + -// " item_name,\n" + -// " item_barcode,\n" + -// " cat,\n" + -// " sub_cat,\n" + -// " Col,\n" + -// " Size,\n" + -// " price_sales"; -// -// ResultSet rs = stmt.executeQuery(sql); -// -// while (rs.next()) { -// WeeklyHeavyStock weeklyHeavyStock = new WeeklyHeavyStock(); -// weeklyHeavyStock.setPLU_CODE(rs.getString("PLU_CODE")); -// weeklyHeavyStock.setItem_name(rs.getString("item_name")); -// weeklyHeavyStock.setItem_barcode(rs.getString("item_barcode")); -// weeklyHeavyStock.setCat(rs.getString("cat")); -// weeklyHeavyStock.setSub_cat(rs.getString("sub_cat")); -// weeklyHeavyStock.setCol(rs.getString("Col")); -// weeklyHeavyStock.setSize(rs.getString("Size")); -// weeklyHeavyStock.setPrice_sales(rs.getDouble("price_sales")); -// weeklyHeavyStock.setMAS(rs.getInt("MAS")); -// weeklyHeavyStock.setMEL(rs.getInt("MEL")); -// weeklyHeavyStock.setMPC(rs.getInt("MPC")); -// weeklyHeavyStock.setMPS(rs.getInt("MPS")); -// weeklyHeavyStock.setMTF(rs.getInt("MTF")); -// weeklyHeavyStock.setMWP(rs.getInt("MWP")); -// weeklyHeavyStock.setMYO(rs.getInt("MYO")); -// weeklyHeavyStock.setMHZ(rs.getInt("MHZ")); -// weeklyHeavyStock.setMRT(rs.getInt("MRT")); -// weeklyHeavyStock.setMBZ(rs.getInt("MBZ")); -// QuarterlyProductGroupingList.add(weeklyHeavyStock); -// } -// sql = "SELECT\n" + -// "PLU_CODE,\n" + -// "ITEM_CODE,\n" + -// "SH_CODE\n" + -// "FROM\n" + -// "v_MZG020B\n" + -// "WHERE TRX_DATE >= '2024-03-04'\n" + -// "AND TRX_DATE <= '2024-03-10'\n" + -// "AND PLU_CODE IN (SELECT TOP 3\n" + -// "PLU_CODE\n" + -// "FROM v_MZG020B\n" + -// "WHERE TRX_DATE >= '2024-03-04'\n" + -// "AND TRX_DATE <= '2024-03-10'\n" + -// "AND SH_CODE IN ('MAS', 'MEL', 'MPC', 'MPS', 'MTF', 'MWP', 'MYO')\n" + -// "GROUP BY PLU_CODE\n" + -// "ORDER BY count(1) desc)"; -// -// rs = stmt.executeQuery(sql); -// -// List relationShCodeList = new ArrayList<>(); -// while (rs.next()) { -// WeeklyHeavyStock weeklyHeavyStock = new WeeklyHeavyStock(); -// weeklyHeavyStock.setPLU_CODE(rs.getString("PLU_CODE")); -// weeklyHeavyStock.setItem_barcode(rs.getString("ITEM_CODE")); -// weeklyHeavyStock.setSH_CODE(rs.getString("SH_CODE")); -// relationShCodeList.add(weeklyHeavyStock); -// } -// for (WeeklyHeavyStock relationShCode : relationShCodeList) { -// for (WeeklyHeavyStock quarterlyProductGrouping : QuarterlyProductGroupingList) { -// if (quarterlyProductGrouping.getItem_barcode().equals(relationShCode.getItem_barcode())) { -// if (relationShCode.getSH_CODE().equals("MPS ")) { -// quarterlyProductGrouping.setMASSOLD(quarterlyProductGrouping.getMASSOLD() + 1); -// } -// else if (relationShCode.getSH_CODE().equals("MEL ")) { -// quarterlyProductGrouping.setMELSOLD(quarterlyProductGrouping.getMELSOLD() + 1); -// } -// else if (relationShCode.getSH_CODE().equals("MPC ")) { -// quarterlyProductGrouping.setMPCSOLD(quarterlyProductGrouping.getMPCSOLD() + 1); -// } -// else if (relationShCode.getSH_CODE().equals("MPS ")) { -// quarterlyProductGrouping.setMPSSOLD(quarterlyProductGrouping.getMPSSOLD() + 1); -// } -// else if (relationShCode.getSH_CODE().equals("MTF ")) { -// quarterlyProductGrouping.setMTFSOLD(quarterlyProductGrouping.getMTFSOLD() + 1); -// } -// else if (relationShCode.getSH_CODE().equals("MWP ")) { -// quarterlyProductGrouping.setMWPSOLD(quarterlyProductGrouping.getMWPSOLD() + 1); -// } -// else if (relationShCode.getSH_CODE().equals("MYO ")) { -// quarterlyProductGrouping.setMYOSOLD(quarterlyProductGrouping.getMYOSOLD() + 1); +// Map> itemNameMap = getBestSellItemNameList(); +// for (String s : itemNameMap.keySet()) { +// if (s.equals("yesterdayItemNameList")) { +// QueryWrapper qw = new QueryWrapper<>(); +// qw.lambda().in(MiTuProduct::getItemName, itemNameMap.get(s)); +// List miTuProductList = miTuProductMapper.selectList(qw); +// if (!CollectionUtils.isEmpty(miTuProductList)) { +// Set collect = miTuProductList.stream().map(MiTuProduct::getProductId).collect(Collectors.toSet()); +// if (!CollectionUtils.isEmpty(collect)) { +// QueryWrapper qwBestSell = new QueryWrapper<>(); +// qwBestSell.lambda().in(TProduct::getId, new ArrayList<>(collect)); +// List productList = productMapper.selectList(qwBestSell); +// if (!CollectionUtils.isEmpty(productList)) { +// for (TProduct tProduct : productList) { +// tProduct.setBestSell("1"); +// productMapper.updateById(tProduct); +// } // } // } // } // } -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException | ClassNotFoundException se) { -// se.printStackTrace(); -// } finally { -// try { -// if (stmt != null) stmt.close(); -// } catch (SQLException ignored) {} -// try { -// if (conn != null) conn.close(); -// } catch (SQLException se) { -// se.printStackTrace(); -// } -// } -// System.out.println("Query execution completed!"); -// return QuarterlyProductGroupingList; -// } -// -// private static List getWeeklyHeavyStockList() { -// List weeklyHeavyStockList = new ArrayList<>(); -// Connection conn = null; -// Statement stmt = null; -// try { -// Class.forName(JDBC_DRIVER); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// stmt = conn.createStatement(); -// -// String sql = "WITH CountedData AS (\n" + -// " SELECT\n" + -// " WHCODE,\n" + -// " PLU_CODE,\n" + -// " item_name,\n" + -// " item_barcode,\n" + -// " cat,\n" + -// " sub_cat,\n" + -// " Col,\n" + -// " price_sales,\n" + -// " CASE WHEN WHCODE = 'MAS' THEN 1 ELSE 0 END AS MAS,\n" + -// " CASE WHEN WHCODE = 'MEL' THEN 1 ELSE 0 END AS MEL,\n" + -// " CASE WHEN WHCODE = 'MPC' THEN 1 ELSE 0 END AS MPC,\n" + -// " CASE WHEN WHCODE = 'MPS' THEN 1 ELSE 0 END AS MPS,\n" + -// " CASE WHEN WHCODE = 'MTF' THEN 1 ELSE 0 END AS MTF,\n" + -// " CASE WHEN WHCODE = 'MWP' THEN 1 ELSE 0 END AS MWP,\n" + -// " CASE WHEN WHCODE = 'MYO' THEN 1 ELSE 0 END AS MYO,\n" + -// " CASE WHEN WHCODE = 'MHZ' THEN 1 ELSE 0 END AS MHZ,\n" + -// " CASE WHEN WHCODE = 'MRT' THEN 1 ELSE 0 END AS MRT,\n" + -// " CASE WHEN WHCODE = 'MBZ' THEN 1 ELSE 0 END AS MBZ,\n" + -// " SUM(1) OVER (PARTITION BY PLU_CODE, Col) AS subtotal,\n" + -// " SUM(1) OVER (PARTITION BY PLU_CODE) AS \"G.TLT\"\n" + -// " FROM\n" + -// " (\n" + -// " SELECT\n" + -// " WHCODE,\n" + -// " PLU_CODE,\n" + -// " item_name,\n" + -// " item_code AS item_barcode,\n" + -// " CATEGORY AS cat,\n" + -// " SUB_CAT AS sub_cat,\n" + -// " COLOR AS Col,\n" + -// " SIZE AS SIZE,\n" + -// " price_original as price_sales\n" + -// " FROM\n" + -// " v_MZG003A \n" + -// " WHERE\n" + -// " PLU_CODE IN (\n" + -// " SELECT TOP 30 PLU_CODE \n" + -// " FROM v_MZG003A \n" + -// " WHERE item_active = 'Y' \n" + -// " GROUP BY PLU_CODE \n" + -// " ORDER BY COUNT ( 1 ) DESC\n" + -// " ) \n" + -// " AND item_active = 'Y' \n" + -// " AND WHCODE IN ('MAS', 'MEL', 'MPC', 'MPS', 'MTF', 'MWP', 'MYO', 'MHZ', 'MRT', 'MBZ')\n" + -// " ) AS v \n" + -// ") \n" + -// "SELECT\n" + -// " PLU_CODE,\n" + -// " item_name,\n" + -// " item_barcode,\n" + -// " cat,\n" + -// " sub_cat,\n" + -// " Col,\n" + -// " price_sales,\n" + -// " SUM(MAS) AS MAS,\n" + -// " SUM(MEL) AS MEL,\n" + -// " SUM(MPC) AS MPC,\n" + -// " SUM(MPS) AS MPS,\n" + -// " SUM(MTF) AS MTF,\n" + -// " SUM(MWP) AS MWP,\n" + -// " SUM(MYO) AS MYO,\n" + -// " SUM(MHZ) AS MHZ,\n" + -// " SUM(MRT) AS MRT,\n" + -// " SUM(MBZ) AS MBZ,\n" + -// " SUM(MAS + MEL + MPC + MPS + MTF + MWP + MYO + MHZ + MRT + MBZ) AS TLT,\n" + -// " subtotal,\n" + -// " \"G.TLT\"\n" + -// "FROM\n" + -// " CountedData \n" + -// "GROUP BY\n" + -// " PLU_CODE,\n" + -// " item_name,\n" + -// " item_barcode,\n" + -// " cat,\n" + -// " sub_cat,\n" + -// " Col,\n" + -// " price_sales,\n" + -// " subtotal,\n" + -// " \"G.TLT\"\n" + -// "ORDER BY \"G.TLT\" DESC, PLU_CODE ASC;\n"; -// -// ResultSet rs = stmt.executeQuery(sql); -// -// while (rs.next()) { -// WeeklyHeavyStock weeklyHeavyStock = new WeeklyHeavyStock(); -// weeklyHeavyStock.setPLU_CODE(rs.getString("PLU_CODE")); -// weeklyHeavyStock.setItem_name(rs.getString("item_name")); -// weeklyHeavyStock.setItem_barcode(rs.getString("item_barcode")); -// weeklyHeavyStock.setCat(rs.getString("cat")); -// weeklyHeavyStock.setSub_cat(rs.getString("sub_cat")); -// weeklyHeavyStock.setCol(rs.getString("Col")); -// weeklyHeavyStock.setPrice_sales(rs.getDouble("price_sales")); -// weeklyHeavyStock.setMAS(rs.getInt("MAS")); -// weeklyHeavyStock.setMEL(rs.getInt("MEL")); -// weeklyHeavyStock.setMPC(rs.getInt("MPC")); -// weeklyHeavyStock.setMPS(rs.getInt("MPS")); -// weeklyHeavyStock.setMTF(rs.getInt("MTF")); -// weeklyHeavyStock.setMWP(rs.getInt("MWP")); -// weeklyHeavyStock.setMYO(rs.getInt("MYO")); -// weeklyHeavyStock.setMHZ(rs.getInt("MHZ")); -// weeklyHeavyStock.setMRT(rs.getInt("MRT")); -// weeklyHeavyStock.setMBZ(rs.getInt("MBZ")); -// weeklyHeavyStock.setTLT(rs.getInt("TLT")); -// weeklyHeavyStock.setSubtotal(rs.getInt("subtotal")); -// weeklyHeavyStock.setG_TLT(rs.getInt("G.TLT")); -// weeklyHeavyStockList.add(weeklyHeavyStock); -// } -// -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException | ClassNotFoundException se) { -// se.printStackTrace(); -// } finally { -// try { -// if (stmt != null) stmt.close(); -// } catch (SQLException ignored) {} -// try { -// if (conn != null) conn.close(); -// } catch (SQLException se) { -// se.printStackTrace(); -// } -// } -// System.out.println("Query execution completed!"); -// return weeklyHeavyStockList; -// } -// -// private static List getTransactionSummaryList() { -// List transactionSummaryList = new ArrayList<>(); -// Connection conn = null; -// Statement stmt = null; -// try { -// // 注册 JDBC 驱动器 -// Class.forName(JDBC_DRIVER); -// -// // 打开一个连接 -// System.out.println("连接数据库..."); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// -// // 执行查询 -// System.out.println("创建声明..."); -// stmt = conn.createStatement(); -// String sql; -// -// // 获取当前日期 -// LocalDate currentDate = LocalDate.now(); -// -// // 获取当前星期的第一天(星期一)和最后一天(星期日) -// LocalDate firstDayOfWeek = currentDate.with(DayOfWeek.MONDAY); -// LocalDate lastDayOfWeek = currentDate.with(DayOfWeek.SUNDAY); -// -// // 格式化日期字符串 -// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); -// String firstDayOfWeekStr = formatter.format(firstDayOfWeek); -// String lastDayOfWeekStr = formatter.format(lastDayOfWeek); -// // 构建完整的 SQL 查询语句 -// sql = "SELECT TOP 30\n" + -// " PLU_CODE,\n" + -// " ITEM_NAME,\n" + -// " CATEGORY,\n" + -// " SUB_CAT,\n" + -// " PRICE_ORIGINAL,\n" + -// " COUNT(1) AS totalSaleNum,\n" + -// " SUM(CASE WHEN SH_CODE = 'MAS' THEN 1 ELSE 0 END) AS MAS,\n" + -// " SUM(CASE WHEN SH_CODE = 'MEL' THEN 1 ELSE 0 END) AS MEL,\n" + -// " SUM(CASE WHEN SH_CODE = 'MPC' THEN 1 ELSE 0 END) AS MPC,\n" + -// " SUM(CASE WHEN SH_CODE = 'MPS' THEN 1 ELSE 0 END) AS MPS,\n" + -// " SUM(CASE WHEN SH_CODE = 'MTF' THEN 1 ELSE 0 END) AS MTF,\n" + -// " SUM(CASE WHEN SH_CODE = 'MWP' THEN 1 ELSE 0 END) AS MWP,\n" + -// " SUM(CASE WHEN SH_CODE = 'MYO' THEN 1 ELSE 0 END) AS MYO\n" + -// "FROM\n" + -// " v_MZG020B\n" + -// "WHERE\n" + -// " TRX_DATE >= '" + firstDayOfWeekStr + "' \n" + -// " AND TRX_DATE <= '" + lastDayOfWeekStr + "' \n" + -// "GROUP BY\n" + -// " PLU_CODE, ITEM_NAME, CATEGORY, SUB_CAT, PRICE_ORIGINAL\n" + -// "ORDER BY \n" + -// " totalSaleNum DESC, PLU_CODE;"; -// ResultSet rs = stmt.executeQuery(sql); -// -// // 处理结果集 -// while (rs.next()) { -// TransactionSummary summary = new TransactionSummary(); -// summary.setPLU_CODE(rs.getString("PLU_CODE")); -// summary.setItemName(rs.getString("ITEM_NAME")); -// summary.setCATEGORY(rs.getString("CATEGORY")); -// summary.setSUB_CAT(rs.getString("SUB_CAT")); -// summary.setPriceOriginal(rs.getDouble("PRICE_ORIGINAL")); -// summary.setTotalSaleNum(rs.getInt("totalSaleNum")); -// summary.setMAS_count(rs.getInt("MAS")); -// summary.setMEL_count(rs.getInt("MEL")); -// summary.setMPC_count(rs.getInt("MPC")); -// summary.setMPS_count(rs.getInt("MPS")); -// summary.setMTF_count(rs.getInt("MTF")); -// summary.setMWP_count(rs.getInt("MWP")); -// summary.setMYO_count(rs.getInt("MYO")); -// transactionSummaryList.add(summary); -// } -// -// List pluCodeList = transactionSummaryList.stream().map(TransactionSummary::getPLU_CODE).collect(Collectors.toList()); -// StringBuilder inClause = new StringBuilder("("); -// for (String pluCode : pluCodeList) { -// inClause.append("'").append(pluCode).append("',"); -// } -// inClause.deleteCharAt(inClause.length() - 1); // 删除最后一个逗号 -// inClause.append(")"); -// -// // 构建完整的 SQL 查询语句 -// sql = "SELECT\n" + -// "PLU_CODE,\n" + -// "COUNT(1) AS retailOnHand\n" + -// "FROM v_MZG003A\n" + -// "WHERE PLU_CODE IN " + inClause.toString() + "\n" + -// "GROUP BY PLU_CODE;"; -// rs = stmt.executeQuery(sql); -// List retailOnHandList = new ArrayList<>(); -// while (rs.next()) { -// TransactionSummary summary = new TransactionSummary(); -// summary.setPLU_CODE(rs.getString("PLU_CODE")); -// summary.setRetailOnHand(rs.getInt("retailOnHand")); -// retailOnHandList.add(summary); -// } -// for (TransactionSummary transactionSummary : transactionSummaryList) { -// for (TransactionSummary summary : retailOnHandList) { -// if (transactionSummary.getPLU_CODE().equals(summary.getPLU_CODE())) { -// transactionSummary.setRetailOnHand(summary.getRetailOnHand()); -// break; +// if (s.equals("lastWeekItemNameList")) { +// QueryWrapper qw = new QueryWrapper<>(); +// qw.lambda().in(MiTuProduct::getItemName, itemNameMap.get(s)); +// List miTuProductList = miTuProductMapper.selectList(qw); +// if (!CollectionUtils.isEmpty(miTuProductList)) { +// Set collect = miTuProductList.stream().map(MiTuProduct::getProductId).collect(Collectors.toSet()); +// if (!CollectionUtils.isEmpty(collect)) { +// QueryWrapper qwBestSell = new QueryWrapper<>(); +// qwBestSell.lambda().in(TProduct::getId, new ArrayList<>(collect)); +// List productList = productMapper.selectList(qwBestSell); +// if (!CollectionUtils.isEmpty(productList)) { +// for (TProduct tProduct : productList) { +// if (StringUtils.isEmpty(tProduct.getBestSell())) { +// tProduct.setBestSell("2"); +// }else { +// tProduct.setBestSell(tProduct.getBestSell() + ",2"); +// } +// productMapper.updateById(tProduct); +// } +// } // } // } // } -// -// sql = "SELECT plu_code,toshopdate,lastwk_salesqty FROM v_MZG019C WHERE plu_code in" + inClause; -// rs = stmt.executeQuery(sql); -// List toShopDateList = new ArrayList<>(); -// while (rs.next()) { -// TransactionSummary summary = new TransactionSummary(); -// summary.setPLU_CODE(rs.getString("plu_code")); -// summary.setToShopDate(rs.getDate("toshopdate")); -// summary.setLwSalesQty(rs.getInt("lastwk_salesqty")); -// toShopDateList.add(summary); -// } -// -// for (TransactionSummary transactionSummary : transactionSummaryList) { -// for (TransactionSummary toShopDate : toShopDateList) { -// if (transactionSummary.getPLU_CODE().equals(toShopDate.getPLU_CODE())) { -// transactionSummary.setToShopDate(toShopDate.getToShopDate()); -// transactionSummary.setSalesDay(calculateDaysDifference(toShopDate.getToShopDate())); -// transactionSummary.setLwSalesQty(toShopDate.getLwSalesQty()); -// break; +// if (s.equals("lastMonthItemNameList")) { +// QueryWrapper qw = new QueryWrapper<>(); +// qw.lambda().in(MiTuProduct::getItemName, itemNameMap.get(s)); +// List miTuProductList = miTuProductMapper.selectList(qw); +// if (!CollectionUtils.isEmpty(miTuProductList)) { +// Set collect = miTuProductList.stream().map(MiTuProduct::getProductId).collect(Collectors.toSet()); +// if (!CollectionUtils.isEmpty(collect)) { +// QueryWrapper qwBestSell = new QueryWrapper<>(); +// qwBestSell.lambda().in(TProduct::getId, new ArrayList<>(collect)); +// List productList = productMapper.selectList(qwBestSell); +// if (!CollectionUtils.isEmpty(productList)) { +// for (TProduct tProduct : productList) { +// if (StringUtils.isEmpty(tProduct.getBestSell())) { +// tProduct.setBestSell("3"); +// }else { +// tProduct.setBestSell(tProduct.getBestSell() + ",3"); +// } +// productMapper.updateById(tProduct); +// } +// } // } // } // } -// -// for (TransactionSummary transactionSummary : transactionSummaryList) { -// int ttlSalesQty = transactionSummary.getTotalSaleNum(); -// int retailOnHand = transactionSummary.getRetailOnHand(); -// int toRetailQty = ttlSalesQty + retailOnHand; -// -// double result = (double) ttlSalesQty / toRetailQty; -// // 将结果四舍五入到两位小数 -// double roundedResult = Math.round(result * 100.0) / 100.0; -// // 将销售率转换为百分比形式 -// String salesRate = String.format("%.0f%%", roundedResult * 100); -// -// transactionSummary.setToRetailQty(toRetailQty); -// transactionSummary.setSalesRate(salesRate); -// } -// -// // 清理环境 -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException se) { -// // 处理 JDBC 错误 -// se.printStackTrace(); -// } catch (Exception e) { -// // 处理 Class.forName 错误 -// e.printStackTrace(); -// } finally { -// // 关闭资源 -// try { -// if (stmt != null) stmt.close(); -// } catch (SQLException se2) { -// } // 什么都不做 -// try { -// if (conn != null) conn.close(); -// } catch (SQLException se) { -// se.printStackTrace(); -// } // } -// System.out.println("查询执行完成!"); -// return transactionSummaryList; -// } -// -// public static int calculateDaysDifference(Date toShopDate) { -// // 获取当前时间的毫秒数 -// long currentTimeMillis = System.currentTimeMillis(); -// -// // 获取toShopDate的毫秒数 -// long toShopTimeMillis = toShopDate.getTime(); -// -// // 计算毫秒差,并转换为天数,并向上取整 -// int daysDifference = (int) Math.ceil((currentTimeMillis - toShopTimeMillis) / (1000.0 * 60 * 60 * 24)); -// -// return daysDifference; -// } -// -// private static List getCustomerData() { -// List customerDataList = new ArrayList<>(); -// Connection conn = null; -// Statement stmt = null; -// try { -// // 注册 JDBC 驱动器 -// Class.forName(JDBC_DRIVER); -// -// // 打开一个连接 -// System.out.println("连接数据库..."); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// -// // 执行查询 -// System.out.println("创建声明..."); -// stmt = conn.createStatement(); -// String sql; -//// // 构建 IN 子句的字符串,用于添加到 SQL 查询中 -//// StringBuilder inClause = new StringBuilder("("); -//// for (String code : collect) { -//// inClause.append("'").append(code).append("',"); -//// } -//// inClause.deleteCharAt(inClause.length() - 1); // 删除最后一个逗号 -//// inClause.append(")"); -// -// // 构建完整的 SQL 查询语句 -// sql = "SELECT * \n" + -// "FROM V_RW0095B\n" + -// "WHERE join_date >= DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()) - 1, 0)\n" + -// "AND mbr_group != 'NONMBR'\n" + -// "ORDER BY join_date DESC"; -// ResultSet rs = stmt.executeQuery(sql); -// -// -// // 处理结果集 -// while (rs.next()) { -// // 将每行数据转换为 CustomerData 对象并添加到列表中 -// CustomerData customer = new CustomerData(); -// customer.setMbrCode(rs.getString("mbr_code")); -// customer.setMbrName(rs.getString("mbr_name")); -// customer.setMbrMobile(rs.getString("mbr_mobile")); -// customer.setMbrGroup(rs.getString("mbr_group")); -// customer.setMbrStatus(rs.getString("mbr_status")); -// customer.setJoinDate(rs.getDate("join_date")); -// customer.setMbrIssue(rs.getString("mbr_issue")); -// customer.setBirthMonth(rs.getInt("birth_m")); -// customer.setMbrSex(rs.getString("mbr_sex")); -// customer.setOffBonus(rs.getDouble("off_bonus")); -// customer.setEffBonus(rs.getDouble("eff_bonus")); -// customer.setSumBonus(rs.getDouble("sum_bonus")); -// customerDataList.add(customer); -// + } + + private void miTuProductSellNumEntry(LocalDate today, List productListAll) { + String endDate = formatDate(today); + String startDate = formatDate(today.minusDays(1)); + for (TProduct product : productListAll) { + String pictureName = product.getPictureName(); + String[] split = pictureName.split("_"); + String itemName = split[0]; + String color = split[1]; + MiTuProductSellNum miTuProductSellNum = getProductSellNum(itemName, color, startDate, endDate); + miTuProductSellNum.setProductId(product.getId()); + miTuProductSellNumMapper.insert(miTuProductSellNum); + } + } + + private MiTuProductSellNum getProductSellNum(String itemName, String color, String startDate, String endDate) { + Connection conn = null; + Statement stmt = null; + MiTuProductSellNum miTuProductSellNum = new MiTuProductSellNum(); + try { + // 注册 JDBC 驱动器 + Class.forName(JDBC_DRIVER); + + // 打开一个连接 + System.out.println("连接数据库..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + + // 执行查询 + System.out.println("创建声明..."); + stmt = conn.createStatement(); + String sql; + sql = "SELECT SH_CODE, count(1) as num FROM v_MZG020B\n" + + "WHERE TRX_DATE >= '" + startDate + "'\n" + + "AND TRX_DATE < '" + endDate + "'\n" + + "AND ITEM_NAME = '" + itemName + "'\n" + + "AND COLOR = '" + color + "'\n" + + "GROUP BY SH_CODE"; + + ResultSet rs = stmt.executeQuery(sql); + // 处理结果集 + while (rs.next()) { + miTuProductSellNum.setSellNum(rs.getInt("num")); + miTuProductSellNum.setSellDate(LocalDate.parse(startDate)); + miTuProductSellNum.setShCode(rs.getString("SH_CODE")); + } + // 清理环境 + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException | ClassNotFoundException e) { + // 处理异常 + e.printStackTrace(); + } + System.out.println("查询执行完成!"); + return miTuProductSellNum; + } + + // 格式化日期为字符串 + private static String formatDate(LocalDate date) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + return date.format(formatter); + } + private Map> getBestSellItemNameList() { + Map> result = new HashMap<>(); + // 获取当前日期 + LocalDate currentDate = LocalDate.now(); + // 格式化当前日期 + String currentDateString = formatDate(currentDate); + + // 获取前一天日期 + LocalDate yesterdayDate = currentDate.minusDays(1); + // 格式化前一天日期 + String yesterdayDateString = formatDate(yesterdayDate); + + // 获取前一周日期 + LocalDate lastWeekDate = currentDate.minusWeeks(1); + // 格式化前一周日期 + String lastWeekDateString = formatDate(lastWeekDate); + + // 获取前一个月日期 + LocalDate lastMonthDate = currentDate.minusMonths(1); + // 格式化前一个月日期 + String lastMonthDateString = formatDate(lastMonthDate); + Connection conn = null; + Statement stmt = null; + try { + // 注册 JDBC 驱动器 + Class.forName(JDBC_DRIVER); + + // 打开一个连接 + System.out.println("连接数据库..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + + // 执行查询 + System.out.println("创建声明..."); + stmt = conn.createStatement(); + String sql; + sql = "SELECT TOP 20 ITEM_NAME FROM v_MZG020B\n" + + " WHERE TRX_DATE >= '" + yesterdayDateString + "'\n" + + " AND TRX_DATE < '" + currentDateString + "'\n" + + " AND ITEM_NAME != 'Shopping Bag Fee'\n" + + " GROUP BY ITEM_NAME\n" + + " ORDER BY COUNT(1) DESC"; + + ResultSet rs = stmt.executeQuery(sql); + // 处理结果集 + List yesterdayItemNameList = new ArrayList<>(); + while (rs.next()) { + yesterdayItemNameList.add(rs.getString("ITEM_NAME")); + } + result.put("yesterdayItemNameList", yesterdayItemNameList); + sql = "SELECT TOP 20 ITEM_NAME FROM v_MZG020B\n" + + " WHERE TRX_DATE >= '" + lastWeekDateString + "'\n" + + " AND TRX_DATE < '" + currentDateString + "'\n" + + " AND ITEM_NAME != 'Shopping Bag Fee'\n" + + " GROUP BY ITEM_NAME\n" + + " ORDER BY COUNT(1) DESC"; + + rs = stmt.executeQuery(sql); + // 处理结果集 + List lastWeekItemNameList = new ArrayList<>(); + while (rs.next()) { + lastWeekItemNameList.add(rs.getString("ITEM_NAME")); + } + result.put("lastWeekItemNameList", lastWeekItemNameList); + sql = "SELECT TOP 20 ITEM_NAME FROM v_MZG020B\n" + + " WHERE TRX_DATE >= '" + lastMonthDateString + "'\n" + + " AND TRX_DATE < '" + currentDateString + "'\n" + + " AND ITEM_NAME != 'Shopping Bag Fee'\n" + + " GROUP BY ITEM_NAME\n" + + " ORDER BY COUNT(1) DESC"; + + rs = stmt.executeQuery(sql); + // 处理结果集 + List lastMonthItemNameList = new ArrayList<>(); + while (rs.next()) { + lastMonthItemNameList.add(rs.getString("ITEM_NAME")); + } + result.put("lastMonthItemNameList", lastMonthItemNameList); + + // 清理环境 + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException | ClassNotFoundException e) { + // 处理异常 + e.printStackTrace(); + } + System.out.println("查询执行完成!"); + return result; + } + + /** + * Customer purchase report + */ + @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000)) + @Scheduled(cron = "0 0 23 28-31 * ?") + public void customerPurchaseReport() { + final Calendar c = Calendar.getInstance(); + // 如果是最后一天 则执行定时任务 + if (c.get(Calendar.DATE) == c.getActualMaximum(Calendar.DATE)) { + MiTuExport miTuExport = createMiTuExport("Customer purchase report", "month"); + try { + List transactionData = retrieveTransactionData(); + List userMembers = transactionData.stream().map(TransactionData::getUserMember).collect(Collectors.toList()); + List customerData = retrieveCustomerData(userMembers); + updateCustomerDataWithTransactionData(customerData, transactionData); + String filePath = miTuExport.getExportName()+".xlsx"; + exportToExcelCustomerPurchaseReport(customerData, filePath); + miTuExport.setUrl("mi-tu/export/" + filePath); + miTuExport.setStatus(1); + } catch (Exception e) { + miTuExport.setStatus(0); + e.printStackTrace(); + } finally { + miTuExportMapper.insert(miTuExport); + System.out.println("接口执行完成!"); + } + }else { + MiTuExport miTuExport = createMiTuExport("Customer purchase report", "month"); + try { + List transactionData = retrieveTransactionData(); + List userMembers = transactionData.stream().map(TransactionData::getUserMember).collect(Collectors.toList()); + List customerData = retrieveCustomerData(userMembers); + updateCustomerDataWithTransactionData(customerData, transactionData); + String filePath = miTuExport.getExportName()+".xlsx"; + exportToExcelCustomerPurchaseReport(customerData, filePath); + miTuExport.setUrl("mi-tu/export/" + filePath); + miTuExport.setStatus(1); + } catch (Exception e) { + miTuExport.setStatus(0); + e.printStackTrace(); + } finally { + miTuExportMapper.insert(miTuExport); + System.out.println("接口执行完成!"); + } + } + } + + private MiTuExport createMiTuExport(String fileName, String period) { + LocalDateTime currentDateTime = LocalDateTime.now(); + LocalDateTime startTime; + LocalDateTime endTime; + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + String exportName; + + switch (period) { + case "week": + startTime = currentDateTime.with(DayOfWeek.MONDAY).with(LocalTime.MIN); + endTime = currentDateTime.with(DayOfWeek.SUNDAY).with(LocalTime.MAX); + exportName = fileName + " week " + currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd")); + break; + case "month": + startTime = currentDateTime.withDayOfMonth(1).with(LocalTime.MIN); + endTime = currentDateTime.withDayOfMonth(currentDateTime.toLocalDate().lengthOfMonth()).with(LocalTime.MAX); + exportName = fileName + " month " + currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd")); + break; + case "year": + startTime = currentDateTime.withDayOfYear(1).with(LocalTime.MIN); + endTime = currentDateTime.withDayOfYear(currentDateTime.toLocalDate().lengthOfYear()).with(LocalTime.MAX); + exportName = fileName + " year " + currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd")); + break; + case "quarter": + // 获取当前季度的第一个月和最后一个月 + int currentQuarter = (currentDateTime.getMonthValue() - 1) / 3 + 1; + int firstMonthOfQuarter = (currentQuarter - 1) * 3 + 1; + int lastMonthOfQuarter = currentQuarter * 3; + + // 获取当前季度的起始时间和结束时间 + startTime = currentDateTime.withMonth(firstMonthOfQuarter).withDayOfMonth(1).with(LocalTime.MIN); + endTime = currentDateTime.withMonth(lastMonthOfQuarter).with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX); + + // 设置导出名称 + exportName = fileName + " quarter " + currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd")); + break; + default: + throw new IllegalArgumentException("Invalid period argument: " + period); + } + + String startOfPeriod = startTime.format(formatter); + String endOfPeriod = endTime.format(formatter); + + MiTuExport miTuExport = new MiTuExport(); + miTuExport.setExportName(exportName); + miTuExport.setSpan(period); + miTuExport.setCreateTime(LocalDateTime.now()); + miTuExport.setDataTime(startOfPeriod + " - " + endOfPeriod); + return miTuExport; + } + + + private void updateCustomerDataWithTransactionData(List customerDataList, List transactionDataList) { + for (TransactionData transactionDatum : transactionDataList) { + for (CustomerData customerDatum : customerDataList) { + if (customerDatum.getMbrCode().equals(transactionDatum.getUserMember())) { + customerDatum.setThisMonth(transactionDatum.getThisMonth()); + customerDatum.setMonth1(transactionDatum.getMonth1()); + customerDatum.setMonth2(transactionDatum.getMonth2()); + customerDatum.setMonth3(transactionDatum.getMonth3()); + customerDatum.setMonth4(transactionDatum.getMonth4()); + customerDatum.setMonth5(transactionDatum.getMonth5()); + customerDatum.setMonth6(transactionDatum.getMonth6()); + customerDatum.setMonth7(transactionDatum.getMonth7()); + customerDatum.setMonth8(transactionDatum.getMonth8()); + customerDatum.setMonth9(transactionDatum.getMonth9()); + customerDatum.setMonth10(transactionDatum.getMonth10()); + customerDatum.setMonth11(transactionDatum.getMonth11()); + customerDatum.setMonth12(transactionDatum.getMonth12()); + break; + } + } + } + } + + + /** + * New Join VIP report + */ + @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000)) + @Scheduled(cron = "0 0 23 ? * 7") + public void NewJoinVIPReport() { + MiTuExport miTuExport = createMiTuExport("New join vip report", "week"); + try { + List transactionNewCustomerList = getTransactionNewCustomerList(); + String filePath = miTuExport.getExportName()+".xlsx"; + miTuExport.setUrl("mi-tu/export/" + filePath); + exportNewJoinVIPReport(transactionNewCustomerList, filePath); + miTuExport.setStatus(1); + } catch (Exception e) { + miTuExport.setStatus(0); + e.printStackTrace(); + } finally { + miTuExportMapper.insert(miTuExport); + System.out.println("接口执行完成!"); + } + } + + private void exportNewJoinVIPReport(List transactionNewCustomerList, String filePathName) throws IOException { + String currentPath = Paths.get("").toAbsolutePath().toString(); + File file = new File(currentPath + "/" + filePathName); + // 如果文件不存在或者为空,则创建一个新的 Workbook + Workbook workbook = new XSSFWorkbook(); + + // 创建一个新的 Sheet 或获取现有的 Sheet + Sheet sheet = workbook.getSheet("Transaction New Customer"); + if (sheet == null) { + sheet = workbook.createSheet("Transaction New Customer"); + } + + // 创建标题行 + Row headerRow = sheet.getRow(0); + if (headerRow == null) { + headerRow = sheet.createRow(0); + } + + // 写入标题行 + headerRow.createCell(0).setCellValue("shCode"); + headerRow.createCell(1).setCellValue("userMember"); + headerRow.createCell(2).setCellValue("mbrName"); + headerRow.createCell(3).setCellValue("mbrMobile"); + headerRow.createCell(4).setCellValue("joinDate"); + headerRow.createCell(5).setCellValue("salesAmt"); + headerRow.createCell(6).setCellValue("vipGrade"); + headerRow.createCell(7).setCellValue("salesmanName"); + + // 写入数据 + int rowNum = sheet.getLastRowNum() + 1; + for (TransactionNewCustomer transactionNewCustomer : transactionNewCustomerList) { + Row row = sheet.createRow(rowNum++); + + row.createCell(0).setCellValue(transactionNewCustomer.getShCode()); + row.createCell(1).setCellValue(transactionNewCustomer.getUserMember()); + row.createCell(2).setCellValue(transactionNewCustomer.getMbrName()); + row.createCell(3).setCellValue(transactionNewCustomer.getMbrMobile()); + row.createCell(4).setCellValue(transactionNewCustomer.getJoinDate()); + row.createCell(5).setCellValue(transactionNewCustomer.getSalesAmt()); + row.createCell(6).setCellValue(transactionNewCustomer.getVipGrade()); + row.createCell(7).setCellValue(transactionNewCustomer.getSalesmanName()); + } + + // 将Workbook写入文件 + try (FileOutputStream outputStream = new FileOutputStream(file)) { + workbook.write(outputStream); + } + FileItem a = getMultipartFile(file, file.getName()); + MultipartFile multipartFile = new CommonsMultipartFile(a); + minioUtil.upload("mi-tu", "export", multipartFile); + System.out.println("Excel file has been created successfully!"); + } + + + /** + * Weekly Sell Through Report + */ + @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000)) + @Scheduled(cron = "0 0 23 ? * 7") + public void weeklySellThrReport() { + MiTuExport miTuExport = createMiTuExport("Weekly sell thr report", "week"); + try { + List transactionSummaryList = getTransactionSummaryList(); + String filePath = miTuExport.getExportName()+".xlsx"; + miTuExport.setUrl("mi-tu/export/" + filePath); + exportWeeklySellThrReport(transactionSummaryList, filePath); + miTuExport.setStatus(1); + } catch (Exception e) { + miTuExport.setStatus(0); + e.printStackTrace(); + } finally { + miTuExportMapper.insert(miTuExport); + System.out.println("接口执行完成!"); + } + } + + private void exportWeeklySellThrReport(List transactionSummaryList, String filePathName) throws IOException { + String currentPath = Paths.get("").toAbsolutePath().toString(); + File file = new File(currentPath + "/" + filePathName); + Workbook workbook = new XSSFWorkbook(); + Sheet sheet = workbook.createSheet("Weekly Sell Through Report"); + + Row headerRow = sheet.createRow(0); + String[] headers = {"PLU_CODE", "ToShopDate", "SalesDay", "CATEGORY", "SUB_CAT", "ItemName", + "PriceOriginal", "ToRetailQty", "TotalSaleNum", "MAS_count", "MEL_count", + "MPC_count", "MPS_count", "MTF_count", "MWP_count", "MYO_count", + "LwSalesQty", "RetailOnHand", "SalesRate", "Product Image"}; + for (int i = 0; i < headers.length; i++) { + headerRow.createCell(i).setCellValue(headers[i]); + } + + int rowNum = 1; + int startRow = rowNum; + String previousPluCode = ""; + String imagePath = ""; + + for (TransactionSummary summary : transactionSummaryList) { + if (!summary.getPLU_CODE().equals(previousPluCode)) { + if (startRow < rowNum) { + mergeCells(sheet, startRow, rowNum - 1); + linkImageToCell(workbook, sheet, startRow, rowNum - 1, headers.length - 1, imagePath); + } + startRow = rowNum; + previousPluCode = summary.getPLU_CODE(); + imagePath = getImagePath(summary.getPLU_CODE()); + } + + Row row = sheet.createRow(rowNum); + row.createCell(0).setCellValue(summary.getPLU_CODE()); + // 填充其他列的数据 + row.createCell(1).setCellValue(summary.getToShopDate() != null ? summary.getToShopDate().toString() : ""); + row.createCell(2).setCellValue(summary.getSalesDay()); + row.createCell(3).setCellValue(summary.getCATEGORY()); + row.createCell(4).setCellValue(summary.getSUB_CAT()); + row.createCell(5).setCellValue(summary.getItemName()); + row.createCell(6).setCellValue(summary.getPriceOriginal()); + row.createCell(7).setCellValue(summary.getToRetailQty()); + row.createCell(8).setCellValue(summary.getTotalSaleNum()); + row.createCell(9).setCellValue(summary.getMAS_count()); + row.createCell(10).setCellValue(summary.getMEL_count()); + row.createCell(11).setCellValue(summary.getMPC_count()); + row.createCell(12).setCellValue(summary.getMPS_count()); + row.createCell(13).setCellValue(summary.getMTF_count()); + row.createCell(14).setCellValue(summary.getMWP_count()); + row.createCell(15).setCellValue(summary.getMYO_count()); + row.createCell(16).setCellValue(summary.getLwSalesQty()); + row.createCell(17).setCellValue(summary.getRetailOnHand()); + row.createCell(18).setCellValue(summary.getSalesRate()); + + rowNum++; + } + + // 处理最后一个PLU_CODE的数据 + if (startRow < rowNum) { + mergeCells(sheet, startRow, rowNum - 1); + linkImageToCell(workbook, sheet, startRow, rowNum - 1, headers.length - 1, imagePath); + } + + + try (FileOutputStream outputStream = new FileOutputStream(file)) { + workbook.write(outputStream); + } + + FileItem a = getMultipartFile(file, file.getName()); + MultipartFile multipartFile = new CommonsMultipartFile(a); + minioUtil.upload("mi-tu", "export", multipartFile); + } + + + /** + * WeeklyHeavyStockReport + */ + @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000)) + @Scheduled(cron = "0 0 23 ? * 7") + public void WeeklyHeavyStockReport() { + MiTuExport miTuExport = createMiTuExport("Weekly heavy stock report", "week"); + try { + List weeklyHeavyStockList = getWeeklyHeavyStockList(); + String filePath = miTuExport.getExportName()+".xlsx"; + miTuExport.setUrl("mi-tu/export/" + filePath); + exportWeeklyHeavyStock(weeklyHeavyStockList, filePath); + miTuExport.setStatus(1); + } catch (Exception e) { + miTuExport.setStatus(0); + e.printStackTrace(); + } finally { + miTuExportMapper.insert(miTuExport); + System.out.println("接口执行完成!"); + } + } + + private void exportWeeklyHeavyStock(List weeklyHeavyStockList, String weeklyHeavyStockReportName) throws IOException { + String currentPath = Paths.get("").toAbsolutePath().toString(); + File file = new File(currentPath + "/" + weeklyHeavyStockReportName); + Workbook workbook = new XSSFWorkbook(); + Sheet sheet = workbook.createSheet("Weekly Heavy Stock Report"); + + Row headerRow = sheet.createRow(0); + String[] headers = {"PLU_CODE", "item_name", "item_barcode", "cat", "sub_cat", "Col", "price_sales", + "MAS", "MEL", "MPC", "MPS", "MTF", "MWP", "MYO", "MHZ", "MRT", "MBZ", "TLT", + "subtotal", "G.TLT", "Product Image"}; + for (int i = 0; i < headers.length; i++) { + headerRow.createCell(i).setCellValue(headers[i]); + } + + int rowNum = 1; + int startRow = rowNum; + String previousPluCode = ""; + String imagePath = ""; + + for (WeeklyHeavyStock weeklyHeavyStock : weeklyHeavyStockList) { + if (!weeklyHeavyStock.getPLU_CODE().equals(previousPluCode)) { + if (startRow < rowNum - 1) { + mergeCells(sheet, startRow, rowNum - 1); + linkImageToCell(workbook, sheet, startRow, rowNum - 1, headers.length - 1, imagePath); + } + startRow = rowNum; + previousPluCode = weeklyHeavyStock.getPLU_CODE(); + imagePath = getImagePath(weeklyHeavyStock.getPLU_CODE()); + } + + Row row = sheet.createRow(rowNum); + row.createCell(0).setCellValue(weeklyHeavyStock.getPLU_CODE()); + // 填充其他列的数据 + row.createCell(1).setCellValue(weeklyHeavyStock.getItem_name()); + row.createCell(2).setCellValue(weeklyHeavyStock.getItem_barcode()); + row.createCell(3).setCellValue(weeklyHeavyStock.getCat()); + row.createCell(4).setCellValue(weeklyHeavyStock.getSub_cat()); + row.createCell(5).setCellValue(weeklyHeavyStock.getCol()); + row.createCell(6).setCellValue(weeklyHeavyStock.getPrice_sales()); + row.createCell(7).setCellValue(weeklyHeavyStock.getMAS()); + row.createCell(8).setCellValue(weeklyHeavyStock.getMEL()); + row.createCell(9).setCellValue(weeklyHeavyStock.getMPC()); + row.createCell(10).setCellValue(weeklyHeavyStock.getMPS()); + row.createCell(11).setCellValue(weeklyHeavyStock.getMTF()); + row.createCell(12).setCellValue(weeklyHeavyStock.getMWP()); + row.createCell(13).setCellValue(weeklyHeavyStock.getMYO()); + row.createCell(14).setCellValue(weeklyHeavyStock.getMHZ()); + row.createCell(15).setCellValue(weeklyHeavyStock.getMRT()); + row.createCell(16).setCellValue(weeklyHeavyStock.getMBZ()); + row.createCell(17).setCellValue(weeklyHeavyStock.getTLT()); + row.createCell(18).setCellValue(weeklyHeavyStock.getSubtotal()); + row.createCell(19).setCellValue(weeklyHeavyStock.getG_TLT()); + + rowNum++; + } + + if (startRow < rowNum - 1 || previousPluCode != null) { + mergeCells(sheet, startRow, rowNum - 1); + linkImageToCell(workbook, sheet, startRow, rowNum - 1, headers.length - 1, imagePath); + } + + try (FileOutputStream outputStream = new FileOutputStream(file)) { + workbook.write(outputStream); + } + + FileItem a = getMultipartFile(file, file.getName()); + MultipartFile multipartFile = new CommonsMultipartFile(a); + minioUtil.upload("mi-tu", "export", multipartFile); + } + + + + /** + * Quarterly Product Grouping Report + */ + @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000)) + @Scheduled(cron = "#{@calculateLastDayOfQuarterCron}") + public void QuarterlyProductGroupingReport() { + MiTuExport miTuExport = createMiTuExport("Quarterly product grouping report", "quarter"); + try { + List QuarterlyProductGroupingList = getQuarterlyProductGroupingList(); + String filePath = miTuExport.getExportName()+".xlsx"; + miTuExport.setUrl("mi-tu/export/" + filePath); + exportQuarterlyProductGrouping(QuarterlyProductGroupingList, filePath); + miTuExport.setStatus(1); + } catch (Exception e) { + miTuExport.setStatus(0); + e.printStackTrace(); + } finally { + miTuExportMapper.insert(miTuExport); + System.out.println("接口执行完成!"); + } + } + @Bean + public String calculateLastDayOfQuarterCron() { + // 获取当前日期 + LocalDate currentDate = LocalDate.now(); + + // 计算下一个季度的最后一天 + Month currentMonth = currentDate.getMonth(); + Month nextQuarterStartMonth = currentMonth.plus(3 - currentMonth.getValue() % 3); + LocalDate nextQuarterStartDate = LocalDate.of(currentDate.getYear(), nextQuarterStartMonth, 1); + LocalDate lastDayOfNextQuarter = nextQuarterStartDate.with(TemporalAdjusters.lastDayOfMonth()); + + // 将日期转换成 Cron 表达式的格式 + int year = lastDayOfNextQuarter.getYear(); + int month = lastDayOfNextQuarter.getMonthValue(); + int dayOfMonth = lastDayOfNextQuarter.getDayOfMonth(); + return String.format("0 0 22 %d %d ?", dayOfMonth, month); + } + + public void exportQuarterlyProductGrouping(List weeklyHeavyStockList, String weeklyHeavyStockReportName) throws IOException { + String currentPath = Paths.get("").toAbsolutePath().toString(); + File file = new File(currentPath + "/" + weeklyHeavyStockReportName); + + // 创建工作簿和工作表 + Workbook workbook = new XSSFWorkbook(); + Sheet sheet = workbook.createSheet("Quarterly Product Grouping Report"); + + // 添加报表头 + Row titleRow = sheet.createRow(0); + Cell titleCell = titleRow.createCell(0); + titleCell.setCellValue("FW24 STOCK LIST"); + sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 26)); // 合并标题单元格 + + // 添加“Stock on hand - shop”和“Stock on hand - back office” + Row stockHeaderRow = sheet.createRow(1); + + Cell stockShopCell = stockHeaderRow.createCell(10); + stockShopCell.setCellValue("Stock on hand - shop"); + sheet.addMergedRegion(new CellRangeAddress(1, 1, 10, 16)); // 适当调整列的范围 + + Cell stockOfficeCell = stockHeaderRow.createCell(17); + stockOfficeCell.setCellValue("Stock on hand - back office"); + sheet.addMergedRegion(new CellRangeAddress(1, 1, 17, 19)); // 适当调整列的范围 + + // 创建标题行 + Row headerRow = sheet.createRow(2); + String[] headers = {"Image", "Plu Code", "Col", "Size", "Item Code", "Item Name", "Cat", "Sub_Cat", "RSP", + "HK Sell-thru", "Shop total Sold", // 新增字段 + "MAS Sold", "MEL Sold", "MPC Sold", "MPS Sold", "MTF Sold", "MWP Sold", "MYO Sold", + "MAS", "MEL", "MPC", "MPS", "MTF", "MWP", "MYO", "MRT", "MBZ", "MHZ"}; + + for (int i = 0; i < headers.length; i++) { + headerRow.createCell(i).setCellValue(headers[i]); + } + +// // 自动调整除Image列外的其他列宽度 +// for (int i = 1; i < headers.length; i++) { +// sheet.autoSizeColumn(i); +// } + + // 写入数据和插入图片 + int rowNum = 3; // 数据从第四行开始 + int startRow = rowNum; + String previousPluCode = ""; + String imagePath = ""; + + for (WeeklyHeavyStock weeklyHeavyStock : weeklyHeavyStockList) { + if (!weeklyHeavyStock.getPLU_CODE().equals(previousPluCode)) { + // 新的PLU_CODE,合并之前的单元格,并插入图片 + if (startRow < rowNum - 1) { + mergeCells(sheet, startRow, rowNum - 1); + linkImageToCell(workbook, sheet, startRow, rowNum - 1, 0, imagePath); // 插入图片到合并单元格 + } + startRow = rowNum; + previousPluCode = weeklyHeavyStock.getPLU_CODE(); + imagePath = getImagePath(weeklyHeavyStock.getPLU_CODE()); + } + + // 计算“Shop total Sold” + int shopTotalSold = weeklyHeavyStock.getMASSOLD() + weeklyHeavyStock.getMELSOLD() + + weeklyHeavyStock.getMPCSOLD() + weeklyHeavyStock.getMPSSOLD() + + weeklyHeavyStock.getMTFSOLD() + weeklyHeavyStock.getMWPSOLD() + + weeklyHeavyStock.getMYOSOLD(); + + // 计算“HK Sell-thru” + int stockOnHand = weeklyHeavyStock.getMAS() + weeklyHeavyStock.getMEL() + + weeklyHeavyStock.getMPC() + weeklyHeavyStock.getMPS() + + weeklyHeavyStock.getMTF() + weeklyHeavyStock.getMWP() + + weeklyHeavyStock.getMYO() + weeklyHeavyStock.getMRT() + + weeklyHeavyStock.getMBZ() + weeklyHeavyStock.getMHZ(); + + String hkSellThru = stockOnHand > 0 ? String.format("%.0f%%", (double) shopTotalSold / stockOnHand * 100) : "0%"; + + Row row = sheet.createRow(rowNum); + row.createCell(1).setCellValue(weeklyHeavyStock.getPLU_CODE()); + row.createCell(2).setCellValue(weeklyHeavyStock.getCol()); + row.createCell(3).setCellValue(weeklyHeavyStock.getSize()); + row.createCell(4).setCellValue(weeklyHeavyStock.getItem_barcode()); + row.createCell(5).setCellValue(weeklyHeavyStock.getItem_name()); + row.createCell(6).setCellValue(weeklyHeavyStock.getCat()); + row.createCell(7).setCellValue(weeklyHeavyStock.getSub_cat()); + row.createCell(8).setCellValue(weeklyHeavyStock.getPrice_sales()); + row.createCell(9).setCellValue(hkSellThru); // 填入计算的HK Sell-thru + row.createCell(10).setCellValue(shopTotalSold); // 填入计算的Shop total Sold + row.createCell(11).setCellValue(weeklyHeavyStock.getMASSOLD()); + row.createCell(12).setCellValue(weeklyHeavyStock.getMELSOLD()); + row.createCell(13).setCellValue(weeklyHeavyStock.getMPCSOLD()); + row.createCell(14).setCellValue(weeklyHeavyStock.getMPSSOLD()); + row.createCell(15).setCellValue(weeklyHeavyStock.getMTFSOLD()); + row.createCell(16).setCellValue(weeklyHeavyStock.getMWPSOLD()); + row.createCell(17).setCellValue(weeklyHeavyStock.getMYOSOLD()); + row.createCell(18).setCellValue(weeklyHeavyStock.getMAS()); + row.createCell(19).setCellValue(weeklyHeavyStock.getMEL()); + row.createCell(20).setCellValue(weeklyHeavyStock.getMPC()); + row.createCell(21).setCellValue(weeklyHeavyStock.getMPS()); + row.createCell(22).setCellValue(weeklyHeavyStock.getMTF()); + row.createCell(23).setCellValue(weeklyHeavyStock.getMWP()); + row.createCell(24).setCellValue(weeklyHeavyStock.getMYO()); + row.createCell(25).setCellValue(weeklyHeavyStock.getMRT()); + row.createCell(26).setCellValue(weeklyHeavyStock.getMBZ()); + row.createCell(27).setCellValue(weeklyHeavyStock.getMHZ()); + + rowNum++; + } + + // 确保处理最后一个Plu Code + if (startRow < rowNum - 1 || previousPluCode != null) { + mergeCells(sheet, startRow, rowNum - 1); + linkImageToCell(workbook, sheet, startRow, rowNum - 1, 0, imagePath); + } + + // 将工作簿写入文件 + try (FileOutputStream outputStream = new FileOutputStream(file)) { + workbook.write(outputStream); + } catch (IOException e) { + e.printStackTrace(); + } + + // 上传文件 + FileItem a = getMultipartFile(file, file.getName()); + MultipartFile multipartFile = new CommonsMultipartFile(a); + minioUtil.upload("mi-tu", "export", multipartFile); + + System.out.println("Excel file has been created successfully!"); + } + + private void mergeCells(Sheet sheet, int startRow, int endRow) { + // 合并单元格 + if (startRow < endRow) { + for (int i = 1; i <= 1; i++) { // 只合并Plu Code列 + sheet.addMergedRegion(new CellRangeAddress(startRow, endRow, i, i)); + } + } + } + + private void linkImageToCell(Workbook workbook, Sheet sheet, int startRow, int endRow, int colNum, String imagePath) throws IOException { + try (InputStream inputStream = minioUtil.download("mi-tu/26/BOTTOM/PANTS/MKTS27000_0CMY_copy.jpg")) { + byte[] bytes = IOUtils.toByteArray(inputStream); + int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG); + + CreationHelper helper = workbook.getCreationHelper(); + Drawing drawing = sheet.createDrawingPatriarch(); + ClientAnchor anchor = helper.createClientAnchor(); + + // 将图片设置为150x150像素的大小,并转换为EMU单位 + int widthInEMU = 150 * 9525; + int heightInEMU = 150 * 9525; + + // 设置图片的插入位置和大小,确保只覆盖Image列 + anchor.setCol1(colNum); // 设置开始列为Image列 + anchor.setRow1(startRow); // 设置开始行 + anchor.setCol2(colNum); // 设置结束列为Image列,不应影响Plu Code列 + anchor.setRow2(endRow + 1); // 设置结束行 + + // 设置图片的宽度和高度 + anchor.setDx1(0); // 起始点x偏移量 + anchor.setDy1(0); // 起始点y偏移量 + anchor.setDx2(widthInEMU); // 结束点x偏移量,使得图片只占用Image列的空间 + anchor.setDy2(heightInEMU); // 结束点y偏移量 + + Picture pict = drawing.createPicture(anchor, pictureIdx); + + // 设置Image列的宽度为150像素 + sheet.setColumnWidth(colNum, 150 * 35); // 设置列宽,Excel列宽的单位为1/256个字符宽度 + +// // 自动调整除Image列外的其他列宽度 +// for (int i = 1; i < sheet.getRow(2).getLastCellNum(); i++) { +// sheet.autoSizeColumn(i); // } -// -// // 清理环境 -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException se) { -// // 处理 JDBC 错误 -// se.printStackTrace(); -// } catch (Exception e) { -// // 处理 Class.forName 错误 -// e.printStackTrace(); -// } finally { -// // 关闭资源 -// try { -// if (stmt != null) stmt.close(); -// } catch (SQLException se2) { -// } // 什么都不做 -// try { -// if (conn != null) conn.close(); -// } catch (SQLException se) { -// se.printStackTrace(); -// } -// } -// System.out.println("查询执行完成!"); -// return customerDataList; -// } -// -// private static List getTransactionNewCustomerList() { -// List transactionNewCustomerList = new ArrayList<>(); -// Connection conn = null; -// Statement stmt = null; -// try { -// // 注册 JDBC 驱动器 -// Class.forName(JDBC_DRIVER); -// -// // 打开一个连接 -// System.out.println("连接数据库..."); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// -// // 执行查询 -// System.out.println("创建声明..."); -// stmt = conn.createStatement(); -// String sql; -// -// // 构建完整的 SQL 查询语句 -// sql = "SELECT * FROM v_MZG002b\n" + -// "WHERE join_date >= DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()) - 1, 0)\n" + -// "AND join_date <= DATEADD(DAY, -1, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0))\n" + -// "AND VIP_GRADE != 'WALK IN'\n" + -// "AND VIP_GRADE != 'OLD VIP-VIPP'\n" + -// "AND VIP_GRADE != 'OLD VIP-VIPC'\n" + -// "ORDER BY join_date DESC"; -// ResultSet rs = stmt.executeQuery(sql); -// -// -// // 处理结果集 -// while (rs.next()) { -// // 将每行数据转换为 TransactionNewCustomer 对象并添加到列表中 -// TransactionNewCustomer transactionNewCustomer = new TransactionNewCustomer(); -// transactionNewCustomer.setTrxNo(rs.getString("TRX_NO")); -// transactionNewCustomer.setShCode(rs.getString("SH_CODE")); -// transactionNewCustomer.setSalesmanName(rs.getString("SALEMAN_NAME")); -// transactionNewCustomer.setVipGrade(rs.getString("VIP_GRADE")); -// transactionNewCustomer.setSalesAmt(rs.getDouble("SALES_AMT")); -// transactionNewCustomer.setUserMember(rs.getString("USER_MEMBER")); -// transactionNewCustomer.setMbrName(rs.getString("MBR_NAME")); -// transactionNewCustomer.setMbrMobile(rs.getString("mbr_mobile")); -// transactionNewCustomer.setJoinDate(rs.getDate("join_date")); -// transactionNewCustomerList.add(transactionNewCustomer); -// } -// sql = "SELECT\n" + -// "aaa.TRX_NO,\n" + -// "sum(bbb.pay_bas_amt) as sumPayBasAmt\n" + -// "FROM\n" + -// "v_MZG002b aaa, V_MZG013 bbb\n" + -// "WHERE aaa.TRX_NO = bbb.trx_no\n" + -// "AND aaa.join_date >= DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()) - 1, 0)\n" + -// "AND aaa.join_date <= DATEADD(DAY, -1, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0))\n" + -// "AND aaa.VIP_GRADE != 'WALK IN'\n" + -// "AND aaa.VIP_GRADE != 'OLD VIP-VIPP'\n" + -// "AND aaa.VIP_GRADE != 'OLD VIP-VIPC'\n" + -// "AND bbb.pay_desc != 'Bonus'\n" + -// "AND bbb.pay_desc != 'mi-tu Cash Coupon'\n" + -// "GROUP BY aaa.TRX_NO"; -// ResultSet rs1 = stmt.executeQuery(sql); -// List transactionNewCustomerListSumPayBasAmt = new ArrayList<>(); -// while (rs1.next()) { -// TransactionNewCustomer transactionNewCustomer = new TransactionNewCustomer(); -// transactionNewCustomer.setTrxNo(rs1.getString("TRX_NO")); -// transactionNewCustomer.setSumPayBasAmt(rs1.getDouble("sumPayBasAmt")); -// transactionNewCustomerListSumPayBasAmt.add(transactionNewCustomer); -// } -// Iterator iterator = transactionNewCustomerList.iterator(); -// while (iterator.hasNext()) { -// TransactionNewCustomer transactionNewCustomer = iterator.next(); -// boolean exist = false; -// for (TransactionNewCustomer newCustomer : transactionNewCustomerListSumPayBasAmt) { -// if (newCustomer.getTrxNo().equals(transactionNewCustomer.getTrxNo())) { -// exist = true; -// break; -// } -// } -// if (!exist) { -// iterator.remove(); -// } -// } -// -// for (TransactionNewCustomer transactionNewCustomer : transactionNewCustomerListSumPayBasAmt) { -// for (TransactionNewCustomer newCustomer : transactionNewCustomerList) { -// if (newCustomer.getTrxNo().equals(transactionNewCustomer.getTrxNo())) { -// newCustomer.setSalesAmt(transactionNewCustomer.getSumPayBasAmt()); -// break; -// } -// } -// } -// -// // 清理环境 -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException se) { -// // 处理 JDBC 错误 -// se.printStackTrace(); -// } catch (Exception e) { -// // 处理 Class.forName 错误 -// e.printStackTrace(); -// } finally { -// // 关闭资源 -// try { -// if (stmt != null) stmt.close(); -// } catch (SQLException se2) { -// } // 什么都不做 -// try { -// if (conn != null) conn.close(); -// } catch (SQLException se) { -// se.printStackTrace(); -// } -// } -// System.out.println("查询执行完成!"); -// return transactionNewCustomerList; -// } -// -// public final static String MITU = "mi-tu"; -// -// public void exportToExcelCustomerPurchaseReport(List customerDataList, String fileName) throws IOException { -// String currentPath = Paths.get("").toAbsolutePath().toString(); -// File file = new File(currentPath + "/" + fileName); -// // 如果文件不存在或者为空,则创建一个新的 Workbook -// Workbook workbook = new XSSFWorkbook(); -// -// // 创建一个新的 Sheet 或获取现有的 Sheet -// Sheet sheet = workbook.getSheet("Customer Data"); -// if (sheet == null) { -// sheet = workbook.createSheet("Customer Data"); -// } -// -// // 创建标题行 -// Row headerRow = sheet.getRow(0); -// if (headerRow == null) { -// headerRow = sheet.createRow(0); -// } -// -// // 获取当前年月 -// YearMonth currentYearMonth = YearMonth.now(); -// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM"); -// String[] headers = new String[25]; -// headers[0] = "mbrCode"; -// headers[1] = "mbrName"; -// headers[2] = "mbrMobile"; -// headers[3] = "mbrGroup"; -// headers[4] = "mbrStatus"; -// headers[5] = "joinDate"; -// headers[6] = "mbrIssue"; -// headers[7] = "birthMonth"; -// headers[8] = "mbrSex"; -// headers[9] = "offBonus"; -// headers[10] = "effBonus"; -// headers[11] = "sumBonus"; -// headers[12] = "thisMonth"; -// -// // 添加过去十一个月的年月 -// for (int i = 0; i < 11; i++) { -// headers[13 + i] = currentYearMonth.minusMonths(i + 1).format(formatter); -// } -// for (int i = 0; i < headers.length; i++) { -// Cell cell = headerRow.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); -// cell.setCellValue(headers[i]); -// } -// -// // 写入数据 -// int rowNum = sheet.getLastRowNum() + 1; -// for (CustomerData customer : customerDataList) { -// Row row = sheet.createRow(rowNum++); -// -// row.createCell(0).setCellValue(customer.getMbrCode()); -// row.createCell(1).setCellValue(customer.getMbrName()); -// row.createCell(2).setCellValue(customer.getMbrMobile()); -// row.createCell(3).setCellValue(customer.getMbrGroup()); -// row.createCell(4).setCellValue(customer.getMbrStatus()); -// if (customer.getJoinDate() != null) { -// row.createCell(5).setCellValue(customer.getJoinDate().toString()); -// } -// row.createCell(6).setCellValue(customer.getMbrIssue()); -// row.createCell(7).setCellValue(customer.getBirthMonth()); -// row.createCell(8).setCellValue(customer.getMbrSex()); -// row.createCell(9).setCellValue(customer.getOffBonus()); -// row.createCell(10).setCellValue(customer.getEffBonus()); -// row.createCell(11).setCellValue(customer.getSumBonus()); -// row.createCell(12).setCellValue(customer.getThisMonth()); -// row.createCell(13).setCellValue(customer.getMonth1()); -// row.createCell(14).setCellValue(customer.getMonth2()); -// row.createCell(15).setCellValue(customer.getMonth3()); -// row.createCell(16).setCellValue(customer.getMonth4()); -// row.createCell(17).setCellValue(customer.getMonth5()); -// row.createCell(18).setCellValue(customer.getMonth6()); -// row.createCell(19).setCellValue(customer.getMonth7()); -// row.createCell(20).setCellValue(customer.getMonth8()); -// row.createCell(21).setCellValue(customer.getMonth9()); -// row.createCell(22).setCellValue(customer.getMonth10()); -// row.createCell(23).setCellValue(customer.getMonth11()); -// row.createCell(24).setCellValue(customer.getMonth12()); -// } -// -// // 将Workbook写入文件 -// try (FileOutputStream outputStream = new FileOutputStream(file)) { -// workbook.write(outputStream); -// } -// FileItem a = getMultipartFile(file, file.getName()); -// MultipartFile multipartFile = new CommonsMultipartFile(a); -// minioUtil.upload("mi-tu", "export", multipartFile); -// -// System.out.println("Excel file has been created successfully!"); -// } -// -// private File getProductFile(String fileName) { -// File file = new File("C:\\Users\\10233\\Desktop\\2024 SS NEW\\MKTS27000_0BLK.jpg"); -// return file; -// } -// -// private static FileItem getMultipartFile(File file, String fieldName) { -// // 使用 DiskFileItemFactory 创建一个 FileItemFactory -// FileItemFactory factory = new DiskFileItemFactory(16, null); -// -// // 使用 FileItemFactory 创建一个 FileItem 对象 -// String mimeType = getMimeType(file); -// FileItem item = factory.createItem(fieldName, mimeType, true, file.getName()); -// -// byte[] buffer = new byte[8192]; -// int bytesRead; -// -// try (FileInputStream fis = new FileInputStream(file); -// OutputStream os = item.getOutputStream()) { -// // 从文件中读取数据并写入 FileItem -// while ((bytesRead = fis.read(buffer)) != -1) { -// os.write(buffer, 0, bytesRead); -// } -// } catch (IOException e) { -// e.printStackTrace(); -// } -// -// return item; -// } -// -// private static String getMimeType(File file) { -// try { -// return Files.probeContentType(file.toPath()); -// } catch (IOException e) { -// e.printStackTrace(); -// return null; -// } -// } -// -// public static List retrieveCustomerData(List collect) { -// List customerDataList = new ArrayList<>(); -// Connection conn = null; -// Statement stmt = null; -// try { -// // 注册 JDBC 驱动器 -// Class.forName(JDBC_DRIVER); -// -// // 打开一个连接 -// System.out.println("连接数据库..."); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// -// // 执行查询 -// System.out.println("创建声明..."); -// stmt = conn.createStatement(); -// String sql; + + // 计算行数和每行的高度 + int totalRows = endRow - startRow + 1; + int rowHeight = (150 * 15) / totalRows; // 计算每行的高度,单位为1/20点 + + for (int i = startRow; i <= endRow; i++) { + sheet.getRow(i).setHeight((short) rowHeight); // 设置每一行的行高 + } + } catch (MinioException e) { + throw new RuntimeException(e); + } + } + + private String getImagePath(String pluCode) { + // 假设图片路径与 PLU_CODE 相关,例如:return "path/to/images/" + pluCode + ".jpg"; + return "C:\\Users\\10233\\Desktop\\2024 SS\\MKTS27000_0CMY.jpg"; // 示例路径 + } + + private static List getQuarterlyProductGroupingList() { + List QuarterlyProductGroupingList = new ArrayList<>(); + Connection conn = null; + Statement stmt = null; + try { + Class.forName(JDBC_DRIVER); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + stmt = conn.createStatement(); + + String sql = "WITH CountedData AS (\n" + + " SELECT\n" + + " WHCODE,\n" + + " PLU_CODE,\n" + + " item_name,\n" + + " item_barcode,\n" + + " cat,\n" + + " sub_cat,\n" + + " Col,\n" + + " Size,\n" + + " price_sales,\n" + + " CASE WHEN WHCODE = 'MAS' THEN 1 ELSE 0 END AS MAS,\n" + + " CASE WHEN WHCODE = 'MEL' THEN 1 ELSE 0 END AS MEL,\n" + + " CASE WHEN WHCODE = 'MPC' THEN 1 ELSE 0 END AS MPC,\n" + + " CASE WHEN WHCODE = 'MPS' THEN 1 ELSE 0 END AS MPS,\n" + + " CASE WHEN WHCODE = 'MTF' THEN 1 ELSE 0 END AS MTF,\n" + + " CASE WHEN WHCODE = 'MWP' THEN 1 ELSE 0 END AS MWP,\n" + + " CASE WHEN WHCODE = 'MYO' THEN 1 ELSE 0 END AS MYO,\n" + + " CASE WHEN WHCODE = 'MHZ' THEN 1 ELSE 0 END AS MHZ,\n" + + " CASE WHEN WHCODE = 'MRT' THEN 1 ELSE 0 END AS MRT,\n" + + " CASE WHEN WHCODE = 'MBZ' THEN 1 ELSE 0 END AS MBZ\n" + + " FROM\n" + + " (\n" + + " SELECT\n" + + " WHCODE,\n" + + " PLU_CODE,\n" + + " item_name,\n" + + " item_code AS item_barcode,\n" + + " CATEGORY AS cat,\n" + + " SUB_CAT AS sub_cat,\n" + + " COLOR AS Col,\n" + + " SIZE AS SIZE,\n" + + " price_original as price_sales\n" + + " FROM\n" + + " v_MZG003A \n" + + " WHERE\n" + + " PLU_CODE IN (SELECT TOP 3\n" + + "PLU_CODE\n" + + "FROM v_MZG020B\n" + + "WHERE TRX_DATE >= '2024-03-04'\n" + + "AND TRX_DATE <= '2024-03-10'\n" + + "AND SH_CODE IN ('MAS', 'MEL', 'MPC', 'MPS', 'MTF', 'MWP', 'MYO')\n" + + "GROUP BY PLU_CODE\n" + + "ORDER BY count(1) desc)\n" + + " AND item_active = 'Y' \n" + + " AND WHCODE IN ('MAS', 'MEL', 'MPC', 'MPS', 'MTF', 'MWP', 'MYO', 'MHZ', 'MRT', 'MBZ')\n" + + " ) AS v \n" + + ") \n" + + "SELECT\n" + + " PLU_CODE,\n" + + " item_name,\n" + + " item_barcode,\n" + + " cat,\n" + + " sub_cat,\n" + + " Col,\n" + + " Size,\n" + + " price_sales,\n" + + " SUM(MAS) AS MAS,\n" + + " SUM(MEL) AS MEL,\n" + + " SUM(MPC) AS MPC,\n" + + " SUM(MPS) AS MPS,\n" + + " SUM(MTF) AS MTF,\n" + + " SUM(MWP) AS MWP,\n" + + " SUM(MYO) AS MYO,\n" + + " SUM(MHZ) AS MHZ,\n" + + " SUM(MRT) AS MRT,\n" + + " SUM(MBZ) AS MBZ\n" + + "FROM\n" + + " CountedData \n" + + "GROUP BY\n" + + " PLU_CODE,\n" + + " item_name,\n" + + " item_barcode,\n" + + " cat,\n" + + " sub_cat,\n" + + " Col,\n" + + " Size,\n" + + " price_sales"; + + ResultSet rs = stmt.executeQuery(sql); + + while (rs.next()) { + WeeklyHeavyStock weeklyHeavyStock = new WeeklyHeavyStock(); + weeklyHeavyStock.setPLU_CODE(rs.getString("PLU_CODE")); + weeklyHeavyStock.setItem_name(rs.getString("item_name")); + weeklyHeavyStock.setItem_barcode(rs.getString("item_barcode")); + weeklyHeavyStock.setCat(rs.getString("cat")); + weeklyHeavyStock.setSub_cat(rs.getString("sub_cat")); + weeklyHeavyStock.setCol(rs.getString("Col")); + weeklyHeavyStock.setSize(rs.getString("Size")); + weeklyHeavyStock.setPrice_sales(rs.getDouble("price_sales")); + weeklyHeavyStock.setMAS(rs.getInt("MAS")); + weeklyHeavyStock.setMEL(rs.getInt("MEL")); + weeklyHeavyStock.setMPC(rs.getInt("MPC")); + weeklyHeavyStock.setMPS(rs.getInt("MPS")); + weeklyHeavyStock.setMTF(rs.getInt("MTF")); + weeklyHeavyStock.setMWP(rs.getInt("MWP")); + weeklyHeavyStock.setMYO(rs.getInt("MYO")); + weeklyHeavyStock.setMHZ(rs.getInt("MHZ")); + weeklyHeavyStock.setMRT(rs.getInt("MRT")); + weeklyHeavyStock.setMBZ(rs.getInt("MBZ")); + QuarterlyProductGroupingList.add(weeklyHeavyStock); + } + sql = "SELECT\n" + + "PLU_CODE,\n" + + "ITEM_CODE,\n" + + "SH_CODE\n" + + "FROM\n" + + "v_MZG020B\n" + + "WHERE TRX_DATE >= '2024-03-04'\n" + + "AND TRX_DATE <= '2024-03-10'\n" + + "AND PLU_CODE IN (SELECT TOP 3\n" + + "PLU_CODE\n" + + "FROM v_MZG020B\n" + + "WHERE TRX_DATE >= '2024-03-04'\n" + + "AND TRX_DATE <= '2024-03-10'\n" + + "AND SH_CODE IN ('MAS', 'MEL', 'MPC', 'MPS', 'MTF', 'MWP', 'MYO')\n" + + "GROUP BY PLU_CODE\n" + + "ORDER BY count(1) desc)"; + + rs = stmt.executeQuery(sql); + + List relationShCodeList = new ArrayList<>(); + while (rs.next()) { + WeeklyHeavyStock weeklyHeavyStock = new WeeklyHeavyStock(); + weeklyHeavyStock.setPLU_CODE(rs.getString("PLU_CODE")); + weeklyHeavyStock.setItem_barcode(rs.getString("ITEM_CODE")); + weeklyHeavyStock.setSH_CODE(rs.getString("SH_CODE")); + relationShCodeList.add(weeklyHeavyStock); + } + for (WeeklyHeavyStock relationShCode : relationShCodeList) { + for (WeeklyHeavyStock quarterlyProductGrouping : QuarterlyProductGroupingList) { + if (quarterlyProductGrouping.getItem_barcode().equals(relationShCode.getItem_barcode())) { + if (relationShCode.getSH_CODE().equals("MPS ")) { + quarterlyProductGrouping.setMASSOLD(quarterlyProductGrouping.getMASSOLD() + 1); + } + else if (relationShCode.getSH_CODE().equals("MEL ")) { + quarterlyProductGrouping.setMELSOLD(quarterlyProductGrouping.getMELSOLD() + 1); + } + else if (relationShCode.getSH_CODE().equals("MPC ")) { + quarterlyProductGrouping.setMPCSOLD(quarterlyProductGrouping.getMPCSOLD() + 1); + } + else if (relationShCode.getSH_CODE().equals("MPS ")) { + quarterlyProductGrouping.setMPSSOLD(quarterlyProductGrouping.getMPSSOLD() + 1); + } + else if (relationShCode.getSH_CODE().equals("MTF ")) { + quarterlyProductGrouping.setMTFSOLD(quarterlyProductGrouping.getMTFSOLD() + 1); + } + else if (relationShCode.getSH_CODE().equals("MWP ")) { + quarterlyProductGrouping.setMWPSOLD(quarterlyProductGrouping.getMWPSOLD() + 1); + } + else if (relationShCode.getSH_CODE().equals("MYO ")) { + quarterlyProductGrouping.setMYOSOLD(quarterlyProductGrouping.getMYOSOLD() + 1); + } + } + } + } + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException | ClassNotFoundException se) { + se.printStackTrace(); + } finally { + try { + if (stmt != null) stmt.close(); + } catch (SQLException ignored) {} + try { + if (conn != null) conn.close(); + } catch (SQLException se) { + se.printStackTrace(); + } + } + System.out.println("Query execution completed!"); + return QuarterlyProductGroupingList; + } + + private static List getWeeklyHeavyStockList() { + List weeklyHeavyStockList = new ArrayList<>(); + Connection conn = null; + Statement stmt = null; + try { + Class.forName(JDBC_DRIVER); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + stmt = conn.createStatement(); + + String sql = "WITH CountedData AS (\n" + + " SELECT\n" + + " WHCODE,\n" + + " PLU_CODE,\n" + + " item_name,\n" + + " item_barcode,\n" + + " cat,\n" + + " sub_cat,\n" + + " Col,\n" + + " price_sales,\n" + + " CASE WHEN WHCODE = 'MAS' THEN 1 ELSE 0 END AS MAS,\n" + + " CASE WHEN WHCODE = 'MEL' THEN 1 ELSE 0 END AS MEL,\n" + + " CASE WHEN WHCODE = 'MPC' THEN 1 ELSE 0 END AS MPC,\n" + + " CASE WHEN WHCODE = 'MPS' THEN 1 ELSE 0 END AS MPS,\n" + + " CASE WHEN WHCODE = 'MTF' THEN 1 ELSE 0 END AS MTF,\n" + + " CASE WHEN WHCODE = 'MWP' THEN 1 ELSE 0 END AS MWP,\n" + + " CASE WHEN WHCODE = 'MYO' THEN 1 ELSE 0 END AS MYO,\n" + + " CASE WHEN WHCODE = 'MHZ' THEN 1 ELSE 0 END AS MHZ,\n" + + " CASE WHEN WHCODE = 'MRT' THEN 1 ELSE 0 END AS MRT,\n" + + " CASE WHEN WHCODE = 'MBZ' THEN 1 ELSE 0 END AS MBZ,\n" + + " SUM(1) OVER (PARTITION BY PLU_CODE, Col) AS subtotal,\n" + + " SUM(1) OVER (PARTITION BY PLU_CODE) AS \"G.TLT\"\n" + + " FROM\n" + + " (\n" + + " SELECT\n" + + " WHCODE,\n" + + " PLU_CODE,\n" + + " item_name,\n" + + " item_code AS item_barcode,\n" + + " CATEGORY AS cat,\n" + + " SUB_CAT AS sub_cat,\n" + + " COLOR AS Col,\n" + + " SIZE AS SIZE,\n" + + " price_original as price_sales\n" + + " FROM\n" + + " v_MZG003A \n" + + " WHERE\n" + + " PLU_CODE IN (\n" + + " SELECT TOP 30 PLU_CODE \n" + + " FROM v_MZG003A \n" + + " WHERE item_active = 'Y' \n" + + " GROUP BY PLU_CODE \n" + + " ORDER BY COUNT ( 1 ) DESC\n" + + " ) \n" + + " AND item_active = 'Y' \n" + + " AND WHCODE IN ('MAS', 'MEL', 'MPC', 'MPS', 'MTF', 'MWP', 'MYO', 'MHZ', 'MRT', 'MBZ')\n" + + " ) AS v \n" + + ") \n" + + "SELECT\n" + + " PLU_CODE,\n" + + " item_name,\n" + + " item_barcode,\n" + + " cat,\n" + + " sub_cat,\n" + + " Col,\n" + + " price_sales,\n" + + " SUM(MAS) AS MAS,\n" + + " SUM(MEL) AS MEL,\n" + + " SUM(MPC) AS MPC,\n" + + " SUM(MPS) AS MPS,\n" + + " SUM(MTF) AS MTF,\n" + + " SUM(MWP) AS MWP,\n" + + " SUM(MYO) AS MYO,\n" + + " SUM(MHZ) AS MHZ,\n" + + " SUM(MRT) AS MRT,\n" + + " SUM(MBZ) AS MBZ,\n" + + " SUM(MAS + MEL + MPC + MPS + MTF + MWP + MYO + MHZ + MRT + MBZ) AS TLT,\n" + + " subtotal,\n" + + " \"G.TLT\"\n" + + "FROM\n" + + " CountedData \n" + + "GROUP BY\n" + + " PLU_CODE,\n" + + " item_name,\n" + + " item_barcode,\n" + + " cat,\n" + + " sub_cat,\n" + + " Col,\n" + + " price_sales,\n" + + " subtotal,\n" + + " \"G.TLT\"\n" + + "ORDER BY \"G.TLT\" DESC, PLU_CODE ASC;\n"; + + ResultSet rs = stmt.executeQuery(sql); + + while (rs.next()) { + WeeklyHeavyStock weeklyHeavyStock = new WeeklyHeavyStock(); + weeklyHeavyStock.setPLU_CODE(rs.getString("PLU_CODE")); + weeklyHeavyStock.setItem_name(rs.getString("item_name")); + weeklyHeavyStock.setItem_barcode(rs.getString("item_barcode")); + weeklyHeavyStock.setCat(rs.getString("cat")); + weeklyHeavyStock.setSub_cat(rs.getString("sub_cat")); + weeklyHeavyStock.setCol(rs.getString("Col")); + weeklyHeavyStock.setPrice_sales(rs.getDouble("price_sales")); + weeklyHeavyStock.setMAS(rs.getInt("MAS")); + weeklyHeavyStock.setMEL(rs.getInt("MEL")); + weeklyHeavyStock.setMPC(rs.getInt("MPC")); + weeklyHeavyStock.setMPS(rs.getInt("MPS")); + weeklyHeavyStock.setMTF(rs.getInt("MTF")); + weeklyHeavyStock.setMWP(rs.getInt("MWP")); + weeklyHeavyStock.setMYO(rs.getInt("MYO")); + weeklyHeavyStock.setMHZ(rs.getInt("MHZ")); + weeklyHeavyStock.setMRT(rs.getInt("MRT")); + weeklyHeavyStock.setMBZ(rs.getInt("MBZ")); + weeklyHeavyStock.setTLT(rs.getInt("TLT")); + weeklyHeavyStock.setSubtotal(rs.getInt("subtotal")); + weeklyHeavyStock.setG_TLT(rs.getInt("G.TLT")); + weeklyHeavyStockList.add(weeklyHeavyStock); + } + + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException | ClassNotFoundException se) { + se.printStackTrace(); + } finally { + try { + if (stmt != null) stmt.close(); + } catch (SQLException ignored) {} + try { + if (conn != null) conn.close(); + } catch (SQLException se) { + se.printStackTrace(); + } + } + System.out.println("Query execution completed!"); + return weeklyHeavyStockList; + } + + private static List getTransactionSummaryList() { + List transactionSummaryList = new ArrayList<>(); + Connection conn = null; + Statement stmt = null; + try { + // 注册 JDBC 驱动器 + Class.forName(JDBC_DRIVER); + + // 打开一个连接 + System.out.println("连接数据库..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + + // 执行查询 + System.out.println("创建声明..."); + stmt = conn.createStatement(); + String sql; + + // 获取当前日期 + LocalDate currentDate = LocalDate.now(); + + // 获取当前星期的第一天(星期一)和最后一天(星期日) + LocalDate firstDayOfWeek = currentDate.with(DayOfWeek.MONDAY); + LocalDate lastDayOfWeek = currentDate.with(DayOfWeek.SUNDAY); + + // 格式化日期字符串 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String firstDayOfWeekStr = formatter.format(firstDayOfWeek); + String lastDayOfWeekStr = formatter.format(lastDayOfWeek); + // 构建完整的 SQL 查询语句 + sql = "SELECT TOP 30\n" + + " PLU_CODE,\n" + + " ITEM_NAME,\n" + + " CATEGORY,\n" + + " SUB_CAT,\n" + + " PRICE_ORIGINAL,\n" + + " COUNT(1) AS totalSaleNum,\n" + + " SUM(CASE WHEN SH_CODE = 'MAS' THEN 1 ELSE 0 END) AS MAS,\n" + + " SUM(CASE WHEN SH_CODE = 'MEL' THEN 1 ELSE 0 END) AS MEL,\n" + + " SUM(CASE WHEN SH_CODE = 'MPC' THEN 1 ELSE 0 END) AS MPC,\n" + + " SUM(CASE WHEN SH_CODE = 'MPS' THEN 1 ELSE 0 END) AS MPS,\n" + + " SUM(CASE WHEN SH_CODE = 'MTF' THEN 1 ELSE 0 END) AS MTF,\n" + + " SUM(CASE WHEN SH_CODE = 'MWP' THEN 1 ELSE 0 END) AS MWP,\n" + + " SUM(CASE WHEN SH_CODE = 'MYO' THEN 1 ELSE 0 END) AS MYO\n" + + "FROM\n" + + " v_MZG020B\n" + + "WHERE\n" + + " TRX_DATE >= '" + firstDayOfWeekStr + "' \n" + + " AND TRX_DATE <= '" + lastDayOfWeekStr + "' \n" + + "GROUP BY\n" + + " PLU_CODE, ITEM_NAME, CATEGORY, SUB_CAT, PRICE_ORIGINAL\n" + + "ORDER BY \n" + + " totalSaleNum DESC, PLU_CODE;"; + ResultSet rs = stmt.executeQuery(sql); + + // 处理结果集 + while (rs.next()) { + TransactionSummary summary = new TransactionSummary(); + summary.setPLU_CODE(rs.getString("PLU_CODE")); + summary.setItemName(rs.getString("ITEM_NAME")); + summary.setCATEGORY(rs.getString("CATEGORY")); + summary.setSUB_CAT(rs.getString("SUB_CAT")); + summary.setPriceOriginal(rs.getDouble("PRICE_ORIGINAL")); + summary.setTotalSaleNum(rs.getInt("totalSaleNum")); + summary.setMAS_count(rs.getInt("MAS")); + summary.setMEL_count(rs.getInt("MEL")); + summary.setMPC_count(rs.getInt("MPC")); + summary.setMPS_count(rs.getInt("MPS")); + summary.setMTF_count(rs.getInt("MTF")); + summary.setMWP_count(rs.getInt("MWP")); + summary.setMYO_count(rs.getInt("MYO")); + transactionSummaryList.add(summary); + } + + List pluCodeList = transactionSummaryList.stream().map(TransactionSummary::getPLU_CODE).collect(Collectors.toList()); + StringBuilder inClause = new StringBuilder("("); + for (String pluCode : pluCodeList) { + inClause.append("'").append(pluCode).append("',"); + } + inClause.deleteCharAt(inClause.length() - 1); // 删除最后一个逗号 + inClause.append(")"); + + // 构建完整的 SQL 查询语句 + sql = "SELECT\n" + + "PLU_CODE,\n" + + "COUNT(1) AS retailOnHand\n" + + "FROM v_MZG003A\n" + + "WHERE PLU_CODE IN " + inClause.toString() + "\n" + + "GROUP BY PLU_CODE;"; + rs = stmt.executeQuery(sql); + List retailOnHandList = new ArrayList<>(); + while (rs.next()) { + TransactionSummary summary = new TransactionSummary(); + summary.setPLU_CODE(rs.getString("PLU_CODE")); + summary.setRetailOnHand(rs.getInt("retailOnHand")); + retailOnHandList.add(summary); + } + for (TransactionSummary transactionSummary : transactionSummaryList) { + for (TransactionSummary summary : retailOnHandList) { + if (transactionSummary.getPLU_CODE().equals(summary.getPLU_CODE())) { + transactionSummary.setRetailOnHand(summary.getRetailOnHand()); + break; + } + } + } + + sql = "SELECT plu_code,toshopdate,lastwk_salesqty FROM v_MZG019C WHERE plu_code in" + inClause; + rs = stmt.executeQuery(sql); + List toShopDateList = new ArrayList<>(); + while (rs.next()) { + TransactionSummary summary = new TransactionSummary(); + summary.setPLU_CODE(rs.getString("plu_code")); + summary.setToShopDate(rs.getDate("toshopdate")); + summary.setLwSalesQty(rs.getInt("lastwk_salesqty")); + toShopDateList.add(summary); + } + + for (TransactionSummary transactionSummary : transactionSummaryList) { + for (TransactionSummary toShopDate : toShopDateList) { + if (transactionSummary.getPLU_CODE().equals(toShopDate.getPLU_CODE())) { + transactionSummary.setToShopDate(toShopDate.getToShopDate()); + transactionSummary.setSalesDay(calculateDaysDifference(toShopDate.getToShopDate())); + transactionSummary.setLwSalesQty(toShopDate.getLwSalesQty()); + break; + } + } + } + + for (TransactionSummary transactionSummary : transactionSummaryList) { + int ttlSalesQty = transactionSummary.getTotalSaleNum(); + int retailOnHand = transactionSummary.getRetailOnHand(); + int toRetailQty = ttlSalesQty + retailOnHand; + + double result = (double) ttlSalesQty / toRetailQty; + // 将结果四舍五入到两位小数 + double roundedResult = Math.round(result * 100.0) / 100.0; + // 将销售率转换为百分比形式 + String salesRate = String.format("%.0f%%", roundedResult * 100); + + transactionSummary.setToRetailQty(toRetailQty); + transactionSummary.setSalesRate(salesRate); + } + + // 清理环境 + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException se) { + // 处理 JDBC 错误 + se.printStackTrace(); + } catch (Exception e) { + // 处理 Class.forName 错误 + e.printStackTrace(); + } finally { + // 关闭资源 + try { + if (stmt != null) stmt.close(); + } catch (SQLException se2) { + } // 什么都不做 + try { + if (conn != null) conn.close(); + } catch (SQLException se) { + se.printStackTrace(); + } + } + System.out.println("查询执行完成!"); + return transactionSummaryList; + } + + public static int calculateDaysDifference(Date toShopDate) { + // 获取当前时间的毫秒数 + long currentTimeMillis = System.currentTimeMillis(); + + // 获取toShopDate的毫秒数 + long toShopTimeMillis = toShopDate.getTime(); + + // 计算毫秒差,并转换为天数,并向上取整 + int daysDifference = (int) Math.ceil((currentTimeMillis - toShopTimeMillis) / (1000.0 * 60 * 60 * 24)); + + return daysDifference; + } + + private static List getCustomerData() { + List customerDataList = new ArrayList<>(); + Connection conn = null; + Statement stmt = null; + try { + // 注册 JDBC 驱动器 + Class.forName(JDBC_DRIVER); + + // 打开一个连接 + System.out.println("连接数据库..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + + // 执行查询 + System.out.println("创建声明..."); + stmt = conn.createStatement(); + String sql; // // 构建 IN 子句的字符串,用于添加到 SQL 查询中 // StringBuilder inClause = new StringBuilder("("); // for (String code : collect) { @@ -1879,1026 +1555,1350 @@ // } // inClause.deleteCharAt(inClause.length() - 1); // 删除最后一个逗号 // inClause.append(")"); -// -// // 构建完整的 SQL 查询语句 -// sql = "SELECT * FROM V_RW0095B WHERE mbr_code IN " + inClause.toString(); -// ResultSet rs = stmt.executeQuery(sql); -// -// -// // 处理结果集 -// while (rs.next()) { -// // 将每行数据转换为 CustomerData 对象并添加到列表中 -// CustomerData customer = new CustomerData(); -// customer.setMbrCode(rs.getString("mbr_code")); -// customer.setMbrName(rs.getString("mbr_name")); -// customer.setMbrMobile(rs.getString("mbr_mobile")); -// customer.setMbrGroup(rs.getString("mbr_group")); -// customer.setMbrStatus(rs.getString("mbr_status")); -// customer.setJoinDate(rs.getDate("join_date")); -// customer.setMbrIssue(rs.getString("mbr_issue")); -// customer.setBirthMonth(rs.getInt("birth_m")); -// customer.setMbrSex(rs.getString("mbr_sex")); -// customer.setOffBonus(rs.getDouble("off_bonus")); -// customer.setEffBonus(rs.getDouble("eff_bonus")); -// customer.setSumBonus(rs.getDouble("sum_bonus")); -// customerDataList.add(customer); -// -// } -// -// // 清理环境 -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException se) { -// // 处理 JDBC 错误 -// se.printStackTrace(); -// } catch (Exception e) { -// // 处理 Class.forName 错误 -// e.printStackTrace(); -// } finally { -// // 关闭资源 -// try { -// if (stmt != null) stmt.close(); -// } catch (SQLException se2) { -// } // 什么都不做 -// try { -// if (conn != null) conn.close(); -// } catch (SQLException se) { -// se.printStackTrace(); -// } -// } -// System.out.println("查询执行完成!"); -// return customerDataList; -// } -// -// public static List retrieveTransactionData() { -// List transactionDataList = new ArrayList<>(); -// Connection conn = null; -// Statement stmt = null; -// try { -// // 注册 JDBC 驱动器 -// Class.forName(JDBC_DRIVER); -// -// // 打开一个连接 -// System.out.println("连接数据库..."); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// -// // 执行查询 -// System.out.println("创建声明..."); -// stmt = conn.createStatement(); -// String sql; -// sql = "SELECT \n" + -// " user_member,\n" + -// " SUM(CASE WHEN trx_date >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) AND trx_date <= GETDATE() THEN pay_bas_amt ELSE 0 END) AS thisMonth,\n" + -// " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) THEN pay_bas_amt ELSE 0 END) AS month1,\n" + -// " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -2, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month2,\n" + -// " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -2, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month3,\n" + -// " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -4, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month4,\n" + -// " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -5, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -4, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month5,\n" + -// " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -6, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -5, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month6,\n" + -// " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -7, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -6, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month7,\n" + -// " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -8, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -7, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month8,\n" + -// " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -9, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -8, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month9,\n" + -// " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -10, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -9, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month10,\n" + -// " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -11, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -10, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month11,\n" + -// " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -12, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -11, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month12\n" + -// "FROM \n" + -// " V_MZG013\n" + -// "WHERE \n" + -// " trx_date >= DATEADD(MONTH, -12, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))\n" + -// " AND user_member IS NOT NULL\n" + -// " AND pay_desc != 'Bonus'\n" + -// " AND pay_desc != 'mi-tu Cash Coupon'\n" + -// "GROUP BY \n" + -// " user_member\n"; -// -// ResultSet rs = stmt.executeQuery(sql); -//// rs.setFetchSize(500); -// int a = 0; -// // 处理结果集 -// while (rs.next()) { -// a ++; -//// System.out.println(a); -// // 将每行数据转换为 TransactionData 对象并添加到列表中 -// TransactionData transaction = new TransactionData(); -// transaction.setUserMember(rs.getString("user_member")); -// -//// transaction.setMbrName(rs.getString("mbr_name")); -// transaction.setThisMonth(rs.getDouble("thisMonth")); -// transaction.setMonth1(rs.getDouble("month1")); -// transaction.setMonth2(rs.getDouble("month2")); -// transaction.setMonth3(rs.getDouble("month3")); -// transaction.setMonth4(rs.getDouble("month4")); -// transaction.setMonth5(rs.getDouble("month5")); -// transaction.setMonth6(rs.getDouble("month6")); -// transaction.setMonth7(rs.getDouble("month7")); -// transaction.setMonth8(rs.getDouble("month8")); -// transaction.setMonth9(rs.getDouble("month9")); -// transaction.setMonth10(rs.getDouble("month10")); -// transaction.setMonth11(rs.getDouble("month11")); -// transaction.setMonth12(rs.getDouble("month12")); -// -// transactionDataList.add(transaction); -// } -// -// // 清理环境 -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException | ClassNotFoundException e) { -// // 处理异常 -// e.printStackTrace(); -// } -// System.out.println("查询执行完成!"); -// return transactionDataList; -// } -// -// // 示例:导出数据到CSV文件 -// private static void exportToCSV(ResultSet resultSet, String filePath) throws SQLException, IOException { -// FileWriter writer = new FileWriter(filePath); -// -// while (resultSet.next()) { -// // 将结果写入CSV文件 -// // 这里需要根据实际情况将数据写入CSV文件 -// } -// -// writer.close(); -// } -// -// @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000)) -// @Scheduled(cron = "#{@calculateLastDayOfQuarterCron}") -// public void customerTypeAnalysis() { -// try { -// // 根据近三个月购买记录获取顾客member_code -// List memberCodeList = getMemberCode(); -// // 遍历每个顾客的类型 -// List miTuMemberList = getMemberType(memberCodeList); -// } catch (Exception e) { -// e.printStackTrace(); -// } finally { -// System.out.println("接口执行完成!"); -// } -// } -// -// @Resource -// private MiTuMemberMapper miTuMemberMapper; -// -// public Map varianceMap = new HashMap<>(); -// public Map mostFrequentColorMap = new HashMap<>(); -// public Map mostFrequentSizeMap = new HashMap<>(); -// public Map mostFrequentSubCatMap = new HashMap<>(); -// public Map mostFrequentCategoryMap = new HashMap<>(); -// public Map avePriceMap = new HashMap<>(); -// public Map priceVarianceMap = new HashMap<>(); -// -// private List getMemberType(List memberCodeList) { -// List miTuMemberList = new ArrayList<>(); -// for (String memberCode : memberCodeList) { -// if (memberCode == null) { -// continue; -// } -// String memberType = getMemberTypeByMemberCode(memberCode); -// MiTuMember member = getMember(memberCode); -// MiTuMember miTuMember = CopyUtil.copyObject(member, MiTuMember.class); -// miTuMember.setMbrCode(memberCode); -// miTuMember.setMemberType(memberType); -// miTuMember.setMostFrequentColor(mostFrequentColorMap.get(miTuMember.getMbrCode())); -// miTuMember.setMostFrequentSize(mostFrequentSizeMap.get(miTuMember.getMbrCode())); -// miTuMember.setMostFrequentSubCat(mostFrequentSubCatMap.get(miTuMember.getMbrCode())); -// miTuMember.setMostFrequentCategory(mostFrequentCategoryMap.get(miTuMember.getMbrCode())); -// miTuMember.setAvePrice(avePriceMap.get(miTuMember.getMbrCode())); -// miTuMember.setPriceVariance(priceVarianceMap.get(miTuMember.getMbrCode())); -// miTuMemberList.add(miTuMember); -// } -// // 计算顾客颜色方差的方差 -// // 计算所有顾客方差值的方差 -// double overallVariance = calculateOverallVariance(varianceMap); -// for (MiTuMember miTuMember : miTuMemberList) { -// if (miTuMember.getMemberType() == null) { -// if (varianceMap.get(miTuMember.getMbrCode()) < overallVariance) { -// miTuMember.setMemberType("Type D"); -// }else { -// miTuMember.setMemberType("Type S"); -// } -// } -// QueryWrapper qw = new QueryWrapper<>(); -// qw.lambda().eq(MiTuMember::getMbrCode, miTuMember.getMbrCode()); -// List miTuMembers = miTuMemberMapper.selectList(qw); -// if (CollectionUtils.isEmpty(miTuMembers)) { -// miTuMemberMapper.insert(miTuMember); -// }else { -// miTuMemberMapper.update(miTuMember, qw); -// } -// } -// return miTuMemberList; -// } -// -// private MiTuMember getMember(String memberCode) { -// MiTuMember member = new MiTuMember(); -// Connection conn = null; -// Statement stmt = null; -// try { -// // 注册 JDBC 驱动器 -// Class.forName(JDBC_DRIVER); -// -// // 打开一个连接 -// System.out.println("连接数据库..."); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// -// // 执行查询 -// System.out.println("创建声明..."); -// stmt = conn.createStatement(); -// String sql; -// sql = "SELECT * FROM V_RW0095B\n" + -// "WHERE mbr_code = '" + memberCode + "'"; -// -// ResultSet rs = stmt.executeQuery(sql); -// // 处理结果集 -// while (rs.next()) { -// member.setMbrCode(rs.getString("mbr_code")); -// member.setMbrName(rs.getString("mbr_name")); -// member.setMbrMobile(rs.getString("mbr_mobile")); -// member.setMbrGroup(rs.getString("mbr_group")); -// -// // Check if "mbr_status" is not NULL -// String mbrStatus = rs.getString("mbr_status"); -// if (mbrStatus != null) { -// member.setMbrStatus(mbrStatus.charAt(0)); -// } else { -// // Handle NULL value for "mbr_status" -// } -// -// // Check if "join_date" is not NULL -// member.setJoinDate(rs.getDate("join_date").toLocalDate()); -// member.setMbrIssue(rs.getString("mbr_issue")); -// member.setBirthMonth(rs.getInt("birth_m")); -// -// // Check if "mbr_sex" is not NULL -// String mbrSex = rs.getString("mbr_sex"); -// if (mbrSex != null) { -// member.setMbrSex(mbrSex.charAt(0)); -// } else { -// // Handle NULL value for "mbr_sex" -// } -// -// // Check if "off_bonus" is not NULL -// double offBonus = rs.getDouble("off_bonus"); -// if (!rs.wasNull()) { -// member.setOffBonus(offBonus); -// } else { -// // Handle NULL value for "off_bonus" -// } -// -// // Repeat similar checks for other fields... -// } -// -// // 清理环境 -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException | ClassNotFoundException e) { -// // 处理异常 -// e.printStackTrace(); -// } -// return member; -// } -// -// private double calculateOverallVariance(Map varianceMap) { -// // 计算平均值 -// double mean = varianceMap.values().stream().mapToDouble(Double::doubleValue).average().orElse(0.0); -// -// // 计算方差 -// double sumOfSquaredDifferences = varianceMap.values().stream() -// .mapToDouble(value -> Math.pow(value - mean, 2)) -// .sum(); -// -// return sumOfSquaredDifferences / varianceMap.size(); -// } -// -// private String getMemberTypeByMemberCode(String memberCode) { -// List transactionList = new ArrayList<>(); -// Connection conn = null; -// Statement stmt = null; -// try { -// // 注册 JDBC 驱动器 -// Class.forName(JDBC_DRIVER); -// -// // 打开一个连接 -// System.out.println("连接数据库..."); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// -// // 执行查询 -// System.out.println("创建声明..."); -// stmt = conn.createStatement(); -// String sql; -// String threeMonthsAgoDateAsString = getThreeMonthsAgoDateAsString(); -// sql = "SELECT\n" + -// "*\n" + -// "FROM v_MZG016A\n" + -// "WHERE TRX_DATE >= '" + threeMonthsAgoDateAsString +"'\n" + -// "AND member_code = '" + memberCode + "'"; -// -// ResultSet rs = stmt.executeQuery(sql); -// // 处理结果集 -// while (rs.next()) { -// Transaction transaction = new Transaction(); -// double itemDiscount = rs.getDouble("item_discount"); -// if (!rs.wasNull()) { -// transaction.setItemDiscount(itemDiscount); -// } -// double discountPer = rs.getDouble("discount_per"); -// if (!rs.wasNull()) { -// transaction.setDiscountPer(discountPer); -// } -// transaction.setYear(rs.getString("YEAR")); -// transaction.setSeason(rs.getString("SEASON")); -// -// transaction.setSize(rs.getString("SIZE")); -// transaction.setColor(rs.getString("COLOR")); -// transaction.setNetAmt(rs.getDouble("net_amt")); -// transaction.setSubCat(rs.getString("SUB_CAT")); -// transaction.setCategory(rs.getString("CATEGORY")); -// -// transactionList.add(transaction); -// } -// -// // 清理环境 -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException | ClassNotFoundException e) { -// // 处理异常 -// e.printStackTrace(); -// } -// -// return analysis(transactionList, memberCode); -// } -// -// private String analysis(List transactionList, String memberCode) { -// int discountNum = 0; -// int currentSeasonNum = 0; -// -// Map colorCountMap = new HashMap<>(); -// Map sizeCountMap = new HashMap<>(); -// Map subCatCountMap = new HashMap<>(); -// Map categoryCountMap = new HashMap<>(); -// int totalCount = transactionList.size(); -// double totalPrice = 0; -// -// // 统计每种颜色和尺寸的出现次数 -// for (Transaction transaction : transactionList) { -// String color = transaction.getColor(); -// colorCountMap.put(color, colorCountMap.getOrDefault(color, 0) + 1); -// -// totalPrice += transaction.getNetAmt(); -// -// String size = transaction.getSize(); -// sizeCountMap.put(size, sizeCountMap.getOrDefault(size, 0) + 1); -// -// String subCat = transaction.getSubCat(); -// subCatCountMap.put(subCat, subCatCountMap.getOrDefault(size, 0) + 1); -// -// String category = transaction.getCategory(); -// categoryCountMap.put(category, categoryCountMap.getOrDefault(size, 0) + 1); -// } -// -// if (totalCount > 0) { -// double avePrice = totalPrice / totalCount; -// avePriceMap.put(memberCode, avePrice); -// } -// -// // Step 1: 提取每笔交易的实际付款金额 -// List paymentList = transactionList.stream() -// .map(Transaction::getNetAmt) -// .collect(Collectors.toList()); -// -// // Step 2: 计算均值 -// double mean = paymentList.stream().mapToDouble(Double::doubleValue).average().orElse(0.0); -// -// // Step 3: 计算标准差 -// double priceVariance = paymentList.stream() -// .mapToDouble(payment -> Math.pow(payment - mean, 2)) -// .average().orElse(0.0); -// priceVarianceMap.put(memberCode, priceVariance); -// -// // 计算颜色的方差 -// double colorMean = (double) totalCount / colorCountMap.size(); -// double colorVarianceSum = 0; -// int maxColorCount = 0; -// for (Map.Entry entry : colorCountMap.entrySet()) { -// int count = entry.getValue(); -// colorVarianceSum += Math.pow(count - colorMean, 2); -// if (count > maxColorCount) { -// maxColorCount = count; -// } -// } -// double colorVariance = colorVarianceSum / colorCountMap.size(); -// -// // 计算尺寸的方差 -// double sizeMean = (double) totalCount / sizeCountMap.size(); -// double sizeVarianceSum = 0; -// int maxSizeCount = 0; -// for (Map.Entry entry : sizeCountMap.entrySet()) { -// int count = entry.getValue(); -// sizeVarianceSum += Math.pow(count - sizeMean, 2); -// if (count > maxSizeCount) { -// maxSizeCount = count; -// } -// } -// double sizeVariance = sizeVarianceSum / sizeCountMap.size(); -// -// // 计算SUBCAT的方差 -// double subCatMean = (double) totalCount / subCatCountMap.size(); -// double subCatVarianceSum = 0; -// int maxSubCatCount = 0; -// for (Map.Entry entry : subCatCountMap.entrySet()) { -// int count = entry.getValue(); -// subCatVarianceSum += Math.pow(count - subCatMean, 2); -// if (count > maxSubCatCount) { -// maxSubCatCount = count; -// } -// } -// double subCatVariance = subCatVarianceSum / subCatCountMap.size(); -// -// // 计算category的方差 -// double categoryMean = (double) totalCount / categoryCountMap.size(); -// double categoryVarianceSum = 0; -// int maxCategoryCount = 0; -// for (Map.Entry entry : categoryCountMap.entrySet()) { -// int count = entry.getValue(); -// categoryVarianceSum += Math.pow(count - categoryMean, 2); -// if (count > maxCategoryCount) { -// maxCategoryCount = count; -// } -// } -// double categoryVariance = categoryVarianceSum / categoryCountMap.size(); -// -// // 获取出现次数最多的颜色 -// int finalMaxColorCount = maxColorCount; -// List mostFrequentColors = colorCountMap.entrySet().stream() -// .filter(entry -> entry.getValue() == finalMaxColorCount) -// .map(Map.Entry::getKey) -// .collect(Collectors.toList()); -// String mostFrequentColor = String.join(",", mostFrequentColors); -// -// // 获取出现次数最多的尺寸 -// int finalMaxSizeCount = maxSizeCount; -// List mostFrequentSizes = sizeCountMap.entrySet().stream() -// .filter(entry -> entry.getValue() == finalMaxSizeCount) -// .map(Map.Entry::getKey) -// .collect(Collectors.toList()); -// String size = String.join(",", mostFrequentSizes); -// -// // 获取出现次数最多的SubCat -// int finalMaxSubCatCount = maxSubCatCount; -// List mostFrequentSubCats = subCatCountMap.entrySet().stream() -// .filter(entry -> entry.getValue() == finalMaxSubCatCount) -// .map(Map.Entry::getKey) -// .collect(Collectors.toList()); -// String subCat = String.join(",", mostFrequentSubCats); -// -// // 获取出现次数最多的category -// int finalMaxCategoryCount = maxCategoryCount; -// List mostFrequentCategory = categoryCountMap.entrySet().stream() -// .filter(entry -> entry.getValue() == finalMaxCategoryCount) -// .map(Map.Entry::getKey) -// .collect(Collectors.toList()); -// String category = String.join(",", mostFrequentCategory); -// -// // 统计折扣和当季商品数量 -// for (Transaction transaction : transactionList) { -// if ((transaction.getDiscountPer() != null && transaction.getDiscountPer() >= 20.0) || transaction.getSubCat().equals("TWIN SET")) { -// discountNum++; -// } -// if (transaction.getYear().equals("TE") && transaction.getSeason().equals("A")) { -// currentSeasonNum++; -// } -// } -// -// double variance = (colorVariance + sizeVariance + subCatVariance + categoryVariance) / 4; -// varianceMap.put(memberCode, variance); -//// varianceMap.put(memberCode, sizeVariance); -// mostFrequentColorMap.put(memberCode, mostFrequentColor); -// mostFrequentSizeMap.put(memberCode, size); -// mostFrequentSubCatMap.put(memberCode, subCat); -// mostFrequentCategoryMap.put(memberCode, category); -// -// if (discountNum >= transactionList.size() * 0.5) { -// return "Type C"; -// } -// if (currentSeasonNum >= transactionList.size() * 0.7) { -// return "Type i"; -// } -// return null; -// } -// -// private List getMemberCode() { -// List result = new ArrayList<>(); -// Connection conn = null; -// Statement stmt = null; -// try { -// // 注册 JDBC 驱动器 -// Class.forName(JDBC_DRIVER); -// -// // 打开一个连接 -// System.out.println("连接数据库..."); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// -// // 执行查询 -// System.out.println("创建声明..."); -// stmt = conn.createStatement(); -// String sql; -// String threeMonthsAgoDateAsString = getThreeMonthsAgoDateAsString(); -// sql = "SELECT\n" + -// "member_code\n" + -// "FROM v_MZG016A\n" + -// "WHERE TRX_DATE > '" + threeMonthsAgoDateAsString + "'\n" + -// "GROUP BY member_code"; -// -// ResultSet rs = stmt.executeQuery(sql); -// // 处理结果集 -// while (rs.next()) { -// result.add(rs.getString("member_code")); -// } -// -// // 清理环境 -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException | ClassNotFoundException e) { -// // 处理异常 -// e.printStackTrace(); -// } -// System.out.println("查询执行完成!"); -// return result; -// } -// -// public static String getThreeMonthsAgoDateAsString() { -// // 获取当前日期和时间 -// LocalDateTime currentDateTime = LocalDateTime.now(); -// -// // 计算三个月前的日期和时间 -// LocalDateTime threeMonthsAgoDateTime = currentDateTime.minusMonths(3); -// -// // 格式化日期和时间为字符串 -// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); -// String threeMonthsAgoDateTimeAsString = threeMonthsAgoDateTime.format(formatter); -// -// return threeMonthsAgoDateTimeAsString; -// } -// -// @Resource -// private TProductAttributeMapper productAttributeMapper; -// -// public void getData() { -//// QueryWrapper qw = new QueryWrapper<>(); -//// List productList = productMapper.selectList(qw); -//// Map map = new HashMap<>(); -//// for (TProduct tProduct : productList) { -//// Map aaa = new HashMap<>(); -//// QueryWrapper tProductAttributeQueryWrapper = new QueryWrapper<>(); -//// tProductAttributeQueryWrapper.eq("product_id", tProduct.getId()); -//// tProductAttributeQueryWrapper.eq("attribute_type", "Length"); -//// List tProductAttributes = productAttributeMapper.selectList(tProductAttributeQueryWrapper); -//// if (!CollectionUtils.isEmpty(tProductAttributes)) { -//// TProductAttribute tProductAttribute = tProductAttributes.get(0); -//// aaa.put("category", tProductAttribute.getAttributeItem()); -//// aaa.put("Length", tProductAttribute.getAttributeValue()); -//// } -//// map.put(tProduct.getPictureName(), aaa); -//// } -// List data = miTuProductMapper.getData(); + + // 构建完整的 SQL 查询语句 + sql = "SELECT * \n" + + "FROM V_RW0095B\n" + + "WHERE join_date >= DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()) - 1, 0)\n" + + "AND mbr_group != 'NONMBR'\n" + + "ORDER BY join_date DESC"; + ResultSet rs = stmt.executeQuery(sql); + + + // 处理结果集 + while (rs.next()) { + // 将每行数据转换为 CustomerData 对象并添加到列表中 + CustomerData customer = new CustomerData(); + customer.setMbrCode(rs.getString("mbr_code")); + customer.setMbrName(rs.getString("mbr_name")); + customer.setMbrMobile(rs.getString("mbr_mobile")); + customer.setMbrGroup(rs.getString("mbr_group")); + customer.setMbrStatus(rs.getString("mbr_status")); + customer.setJoinDate(rs.getDate("join_date")); + customer.setMbrIssue(rs.getString("mbr_issue")); + customer.setBirthMonth(rs.getInt("birth_m")); + customer.setMbrSex(rs.getString("mbr_sex")); + customer.setOffBonus(rs.getDouble("off_bonus")); + customer.setEffBonus(rs.getDouble("eff_bonus")); + customer.setSumBonus(rs.getDouble("sum_bonus")); + customerDataList.add(customer); + + } + + // 清理环境 + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException se) { + // 处理 JDBC 错误 + se.printStackTrace(); + } catch (Exception e) { + // 处理 Class.forName 错误 + e.printStackTrace(); + } finally { + // 关闭资源 + try { + if (stmt != null) stmt.close(); + } catch (SQLException se2) { + } // 什么都不做 + try { + if (conn != null) conn.close(); + } catch (SQLException se) { + se.printStackTrace(); + } + } + System.out.println("查询执行完成!"); + return customerDataList; + } + + private static List getTransactionNewCustomerList() { + List transactionNewCustomerList = new ArrayList<>(); + Connection conn = null; + Statement stmt = null; + try { + // 注册 JDBC 驱动器 + Class.forName(JDBC_DRIVER); + + // 打开一个连接 + System.out.println("连接数据库..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + + // 执行查询 + System.out.println("创建声明..."); + stmt = conn.createStatement(); + String sql; + + // 构建完整的 SQL 查询语句 + sql = "SELECT * FROM v_MZG002b\n" + + "WHERE join_date >= DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()) - 1, 0)\n" + + "AND join_date <= DATEADD(DAY, -1, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0))\n" + + "AND VIP_GRADE != 'WALK IN'\n" + + "AND VIP_GRADE != 'OLD VIP-VIPP'\n" + + "AND VIP_GRADE != 'OLD VIP-VIPC'\n" + + "ORDER BY join_date DESC"; + ResultSet rs = stmt.executeQuery(sql); + + + // 处理结果集 + while (rs.next()) { + // 将每行数据转换为 TransactionNewCustomer 对象并添加到列表中 + TransactionNewCustomer transactionNewCustomer = new TransactionNewCustomer(); + transactionNewCustomer.setTrxNo(rs.getString("TRX_NO")); + transactionNewCustomer.setShCode(rs.getString("SH_CODE")); + transactionNewCustomer.setSalesmanName(rs.getString("SALEMAN_NAME")); + transactionNewCustomer.setVipGrade(rs.getString("VIP_GRADE")); + transactionNewCustomer.setSalesAmt(rs.getDouble("SALES_AMT")); + transactionNewCustomer.setUserMember(rs.getString("USER_MEMBER")); + transactionNewCustomer.setMbrName(rs.getString("MBR_NAME")); + transactionNewCustomer.setMbrMobile(rs.getString("mbr_mobile")); + transactionNewCustomer.setJoinDate(rs.getDate("join_date")); + transactionNewCustomerList.add(transactionNewCustomer); + } + sql = "SELECT\n" + + "aaa.TRX_NO,\n" + + "sum(bbb.pay_bas_amt) as sumPayBasAmt\n" + + "FROM\n" + + "v_MZG002b aaa, V_MZG013 bbb\n" + + "WHERE aaa.TRX_NO = bbb.trx_no\n" + + "AND aaa.join_date >= DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()) - 1, 0)\n" + + "AND aaa.join_date <= DATEADD(DAY, -1, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0))\n" + + "AND aaa.VIP_GRADE != 'WALK IN'\n" + + "AND aaa.VIP_GRADE != 'OLD VIP-VIPP'\n" + + "AND aaa.VIP_GRADE != 'OLD VIP-VIPC'\n" + + "AND bbb.pay_desc != 'Bonus'\n" + + "AND bbb.pay_desc != 'mi-tu Cash Coupon'\n" + + "GROUP BY aaa.TRX_NO"; + ResultSet rs1 = stmt.executeQuery(sql); + List transactionNewCustomerListSumPayBasAmt = new ArrayList<>(); + while (rs1.next()) { + TransactionNewCustomer transactionNewCustomer = new TransactionNewCustomer(); + transactionNewCustomer.setTrxNo(rs1.getString("TRX_NO")); + transactionNewCustomer.setSumPayBasAmt(rs1.getDouble("sumPayBasAmt")); + transactionNewCustomerListSumPayBasAmt.add(transactionNewCustomer); + } + Iterator iterator = transactionNewCustomerList.iterator(); + while (iterator.hasNext()) { + TransactionNewCustomer transactionNewCustomer = iterator.next(); + boolean exist = false; + for (TransactionNewCustomer newCustomer : transactionNewCustomerListSumPayBasAmt) { + if (newCustomer.getTrxNo().equals(transactionNewCustomer.getTrxNo())) { + exist = true; + break; + } + } + if (!exist) { + iterator.remove(); + } + } + + for (TransactionNewCustomer transactionNewCustomer : transactionNewCustomerListSumPayBasAmt) { + for (TransactionNewCustomer newCustomer : transactionNewCustomerList) { + if (newCustomer.getTrxNo().equals(transactionNewCustomer.getTrxNo())) { + newCustomer.setSalesAmt(transactionNewCustomer.getSumPayBasAmt()); + break; + } + } + } + + // 清理环境 + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException se) { + // 处理 JDBC 错误 + se.printStackTrace(); + } catch (Exception e) { + // 处理 Class.forName 错误 + e.printStackTrace(); + } finally { + // 关闭资源 + try { + if (stmt != null) stmt.close(); + } catch (SQLException se2) { + } // 什么都不做 + try { + if (conn != null) conn.close(); + } catch (SQLException se) { + se.printStackTrace(); + } + } + System.out.println("查询执行完成!"); + return transactionNewCustomerList; + } + + public final static String MITU = "mi-tu"; + + public void exportToExcelCustomerPurchaseReport(List customerDataList, String fileName) throws IOException { + String currentPath = Paths.get("").toAbsolutePath().toString(); + File file = new File(currentPath + "/" + fileName); + // 如果文件不存在或者为空,则创建一个新的 Workbook + Workbook workbook = new XSSFWorkbook(); + + // 创建一个新的 Sheet 或获取现有的 Sheet + Sheet sheet = workbook.getSheet("Customer Data"); + if (sheet == null) { + sheet = workbook.createSheet("Customer Data"); + } + + // 创建标题行 + Row headerRow = sheet.getRow(0); + if (headerRow == null) { + headerRow = sheet.createRow(0); + } + + // 获取当前年月 + YearMonth currentYearMonth = YearMonth.now(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM"); + String[] headers = new String[25]; + headers[0] = "mbrCode"; + headers[1] = "mbrName"; + headers[2] = "mbrMobile"; + headers[3] = "mbrGroup"; + headers[4] = "mbrStatus"; + headers[5] = "joinDate"; + headers[6] = "mbrIssue"; + headers[7] = "birthMonth"; + headers[8] = "mbrSex"; + headers[9] = "offBonus"; + headers[10] = "effBonus"; + headers[11] = "sumBonus"; + headers[12] = "thisMonth"; + + // 添加过去十一个月的年月 + for (int i = 0; i < 11; i++) { + headers[13 + i] = currentYearMonth.minusMonths(i + 1).format(formatter); + } + for (int i = 0; i < headers.length; i++) { + Cell cell = headerRow.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); + cell.setCellValue(headers[i]); + } + + // 写入数据 + int rowNum = sheet.getLastRowNum() + 1; + for (CustomerData customer : customerDataList) { + Row row = sheet.createRow(rowNum++); + + row.createCell(0).setCellValue(customer.getMbrCode()); + row.createCell(1).setCellValue(customer.getMbrName()); + row.createCell(2).setCellValue(customer.getMbrMobile()); + row.createCell(3).setCellValue(customer.getMbrGroup()); + row.createCell(4).setCellValue(customer.getMbrStatus()); + if (customer.getJoinDate() != null) { + row.createCell(5).setCellValue(customer.getJoinDate().toString()); + } + row.createCell(6).setCellValue(customer.getMbrIssue()); + row.createCell(7).setCellValue(customer.getBirthMonth()); + row.createCell(8).setCellValue(customer.getMbrSex()); + row.createCell(9).setCellValue(customer.getOffBonus()); + row.createCell(10).setCellValue(customer.getEffBonus()); + row.createCell(11).setCellValue(customer.getSumBonus()); + row.createCell(12).setCellValue(customer.getThisMonth()); + row.createCell(13).setCellValue(customer.getMonth1()); + row.createCell(14).setCellValue(customer.getMonth2()); + row.createCell(15).setCellValue(customer.getMonth3()); + row.createCell(16).setCellValue(customer.getMonth4()); + row.createCell(17).setCellValue(customer.getMonth5()); + row.createCell(18).setCellValue(customer.getMonth6()); + row.createCell(19).setCellValue(customer.getMonth7()); + row.createCell(20).setCellValue(customer.getMonth8()); + row.createCell(21).setCellValue(customer.getMonth9()); + row.createCell(22).setCellValue(customer.getMonth10()); + row.createCell(23).setCellValue(customer.getMonth11()); + row.createCell(24).setCellValue(customer.getMonth12()); + } + + // 将Workbook写入文件 + try (FileOutputStream outputStream = new FileOutputStream(file)) { + workbook.write(outputStream); + } + FileItem a = getMultipartFile(file, file.getName()); + MultipartFile multipartFile = new CommonsMultipartFile(a); + minioUtil.upload("mi-tu", "export", multipartFile); + + System.out.println("Excel file has been created successfully!"); + } + + private File getProductFile(String fileName) { + File file = new File("C:\\Users\\10233\\Desktop\\2024 SS NEW\\MKTS27000_0BLK.jpg"); + return file; + } + + private static FileItem getMultipartFile(File file, String fieldName) { + // 使用 DiskFileItemFactory 创建一个 FileItemFactory + FileItemFactory factory = new DiskFileItemFactory(16, null); + + // 使用 FileItemFactory 创建一个 FileItem 对象 + String mimeType = getMimeType(file); + FileItem item = factory.createItem(fieldName, mimeType, true, file.getName()); + + byte[] buffer = new byte[8192]; + int bytesRead; + + try (FileInputStream fis = new FileInputStream(file); + OutputStream os = item.getOutputStream()) { + // 从文件中读取数据并写入 FileItem + while ((bytesRead = fis.read(buffer)) != -1) { + os.write(buffer, 0, bytesRead); + } + } catch (IOException e) { + e.printStackTrace(); + } + + return item; + } + + private static String getMimeType(File file) { + try { + return Files.probeContentType(file.toPath()); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + public static List retrieveCustomerData(List collect) { + List customerDataList = new ArrayList<>(); + Connection conn = null; + Statement stmt = null; + try { + // 注册 JDBC 驱动器 + Class.forName(JDBC_DRIVER); + + // 打开一个连接 + System.out.println("连接数据库..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + + // 执行查询 + System.out.println("创建声明..."); + stmt = conn.createStatement(); + String sql; + // 构建 IN 子句的字符串,用于添加到 SQL 查询中 + StringBuilder inClause = new StringBuilder("("); + for (String code : collect) { + inClause.append("'").append(code).append("',"); + } + inClause.deleteCharAt(inClause.length() - 1); // 删除最后一个逗号 + inClause.append(")"); + + // 构建完整的 SQL 查询语句 + sql = "SELECT * FROM V_RW0095B WHERE mbr_code IN " + inClause.toString(); + ResultSet rs = stmt.executeQuery(sql); + + + // 处理结果集 + while (rs.next()) { + // 将每行数据转换为 CustomerData 对象并添加到列表中 + CustomerData customer = new CustomerData(); + customer.setMbrCode(rs.getString("mbr_code")); + customer.setMbrName(rs.getString("mbr_name")); + customer.setMbrMobile(rs.getString("mbr_mobile")); + customer.setMbrGroup(rs.getString("mbr_group")); + customer.setMbrStatus(rs.getString("mbr_status")); + customer.setJoinDate(rs.getDate("join_date")); + customer.setMbrIssue(rs.getString("mbr_issue")); + customer.setBirthMonth(rs.getInt("birth_m")); + customer.setMbrSex(rs.getString("mbr_sex")); + customer.setOffBonus(rs.getDouble("off_bonus")); + customer.setEffBonus(rs.getDouble("eff_bonus")); + customer.setSumBonus(rs.getDouble("sum_bonus")); + customerDataList.add(customer); + + } + + // 清理环境 + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException se) { + // 处理 JDBC 错误 + se.printStackTrace(); + } catch (Exception e) { + // 处理 Class.forName 错误 + e.printStackTrace(); + } finally { + // 关闭资源 + try { + if (stmt != null) stmt.close(); + } catch (SQLException se2) { + } // 什么都不做 + try { + if (conn != null) conn.close(); + } catch (SQLException se) { + se.printStackTrace(); + } + } + System.out.println("查询执行完成!"); + return customerDataList; + } + + public static List retrieveTransactionData() { + List transactionDataList = new ArrayList<>(); + Connection conn = null; + Statement stmt = null; + try { + // 注册 JDBC 驱动器 + Class.forName(JDBC_DRIVER); + + // 打开一个连接 + System.out.println("连接数据库..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + + // 执行查询 + System.out.println("创建声明..."); + stmt = conn.createStatement(); + String sql; + sql = "SELECT \n" + + " user_member,\n" + + " SUM(CASE WHEN trx_date >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) AND trx_date <= GETDATE() THEN pay_bas_amt ELSE 0 END) AS thisMonth,\n" + + " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) THEN pay_bas_amt ELSE 0 END) AS month1,\n" + + " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -2, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month2,\n" + + " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -2, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month3,\n" + + " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -4, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month4,\n" + + " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -5, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -4, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month5,\n" + + " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -6, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -5, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month6,\n" + + " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -7, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -6, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month7,\n" + + " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -8, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -7, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month8,\n" + + " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -9, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -8, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month9,\n" + + " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -10, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -9, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month10,\n" + + " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -11, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -10, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month11,\n" + + " SUM(CASE WHEN trx_date >= DATEADD(MONTH, -12, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AND trx_date < DATEADD(MONTH, -11, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) THEN pay_bas_amt ELSE 0 END) AS month12\n" + + "FROM \n" + + " V_MZG013\n" + + "WHERE \n" + + " trx_date >= DATEADD(MONTH, -12, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))\n" + + " AND user_member IS NOT NULL\n" + + " AND pay_desc != 'Bonus'\n" + + " AND pay_desc != 'mi-tu Cash Coupon'\n" + + "GROUP BY \n" + + " user_member\n"; + + ResultSet rs = stmt.executeQuery(sql); +// rs.setFetchSize(500); + int a = 0; + // 处理结果集 + while (rs.next()) { + a ++; +// System.out.println(a); + // 将每行数据转换为 TransactionData 对象并添加到列表中 + TransactionData transaction = new TransactionData(); + transaction.setUserMember(rs.getString("user_member")); + +// transaction.setMbrName(rs.getString("mbr_name")); + transaction.setThisMonth(rs.getDouble("thisMonth")); + transaction.setMonth1(rs.getDouble("month1")); + transaction.setMonth2(rs.getDouble("month2")); + transaction.setMonth3(rs.getDouble("month3")); + transaction.setMonth4(rs.getDouble("month4")); + transaction.setMonth5(rs.getDouble("month5")); + transaction.setMonth6(rs.getDouble("month6")); + transaction.setMonth7(rs.getDouble("month7")); + transaction.setMonth8(rs.getDouble("month8")); + transaction.setMonth9(rs.getDouble("month9")); + transaction.setMonth10(rs.getDouble("month10")); + transaction.setMonth11(rs.getDouble("month11")); + transaction.setMonth12(rs.getDouble("month12")); + + transactionDataList.add(transaction); + } + + // 清理环境 + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException | ClassNotFoundException e) { + // 处理异常 + e.printStackTrace(); + } + System.out.println("查询执行完成!"); + return transactionDataList; + } + + // 示例:导出数据到CSV文件 + private static void exportToCSV(ResultSet resultSet, String filePath) throws SQLException, IOException { + FileWriter writer = new FileWriter(filePath); + + while (resultSet.next()) { + // 将结果写入CSV文件 + // 这里需要根据实际情况将数据写入CSV文件 + } + + writer.close(); + } + + @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000)) + @Scheduled(cron = "#{@calculateLastDayOfQuarterCron}") + public void customerTypeAnalysis() { + try { + // 根据近三个月购买记录获取顾客member_code + List memberCodeList = getMemberCode(); + // 遍历每个顾客的类型 + List miTuMemberList = getMemberType(memberCodeList); + } catch (Exception e) { + e.printStackTrace(); + } finally { + System.out.println("接口执行完成!"); + } + } + + @Resource + private MiTuMemberMapper miTuMemberMapper; + + public Map varianceMap = new HashMap<>(); + public Map mostFrequentColorMap = new HashMap<>(); + public Map mostFrequentSizeMap = new HashMap<>(); + public Map mostFrequentSubCatMap = new HashMap<>(); + public Map mostFrequentCategoryMap = new HashMap<>(); + public Map avePriceMap = new HashMap<>(); + public Map priceVarianceMap = new HashMap<>(); + + private List getMemberType(List memberCodeList) { + List miTuMemberList = new ArrayList<>(); + for (String memberCode : memberCodeList) { + if (memberCode == null) { + continue; + } + String memberType = getMemberTypeByMemberCode(memberCode); + MiTuMember member = getMember(memberCode); + MiTuMember miTuMember = CopyUtil.copyObject(member, MiTuMember.class); + miTuMember.setMbrCode(memberCode); + miTuMember.setMemberType(memberType); + miTuMember.setMostFrequentColor(mostFrequentColorMap.get(miTuMember.getMbrCode())); + miTuMember.setMostFrequentSize(mostFrequentSizeMap.get(miTuMember.getMbrCode())); + miTuMember.setMostFrequentSubCat(mostFrequentSubCatMap.get(miTuMember.getMbrCode())); + miTuMember.setMostFrequentCategory(mostFrequentCategoryMap.get(miTuMember.getMbrCode())); + miTuMember.setAvePrice(avePriceMap.get(miTuMember.getMbrCode())); + miTuMember.setPriceVariance(priceVarianceMap.get(miTuMember.getMbrCode())); + miTuMemberList.add(miTuMember); + } + // 计算顾客颜色方差的方差 + // 计算所有顾客方差值的方差 + double overallVariance = calculateOverallVariance(varianceMap); + for (MiTuMember miTuMember : miTuMemberList) { + if (miTuMember.getMemberType() == null) { + if (varianceMap.get(miTuMember.getMbrCode()) < overallVariance) { + miTuMember.setMemberType("Type D"); + }else { + miTuMember.setMemberType("Type S"); + } + } + QueryWrapper qw = new QueryWrapper<>(); + qw.lambda().eq(MiTuMember::getMbrCode, miTuMember.getMbrCode()); + List miTuMembers = miTuMemberMapper.selectList(qw); + if (CollectionUtils.isEmpty(miTuMembers)) { + miTuMemberMapper.insert(miTuMember); + }else { + miTuMemberMapper.update(miTuMember, qw); + } + } + return miTuMemberList; + } + + private MiTuMember getMember(String memberCode) { + MiTuMember member = new MiTuMember(); + Connection conn = null; + Statement stmt = null; + try { + // 注册 JDBC 驱动器 + Class.forName(JDBC_DRIVER); + + // 打开一个连接 + System.out.println("连接数据库..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + + // 执行查询 + System.out.println("创建声明..."); + stmt = conn.createStatement(); + String sql; + sql = "SELECT * FROM V_RW0095B\n" + + "WHERE mbr_code = '" + memberCode + "'"; + + ResultSet rs = stmt.executeQuery(sql); + // 处理结果集 + while (rs.next()) { + member.setMbrCode(rs.getString("mbr_code")); + member.setMbrName(rs.getString("mbr_name")); + member.setMbrMobile(rs.getString("mbr_mobile")); + member.setMbrGroup(rs.getString("mbr_group")); + + // Check if "mbr_status" is not NULL + String mbrStatus = rs.getString("mbr_status"); + if (mbrStatus != null) { + member.setMbrStatus(mbrStatus.charAt(0)); + } else { + // Handle NULL value for "mbr_status" + } + + // Check if "join_date" is not NULL + member.setJoinDate(rs.getDate("join_date").toLocalDate()); + member.setMbrIssue(rs.getString("mbr_issue")); + member.setBirthMonth(rs.getInt("birth_m")); + + // Check if "mbr_sex" is not NULL + String mbrSex = rs.getString("mbr_sex"); + if (mbrSex != null) { + member.setMbrSex(mbrSex.charAt(0)); + } else { + // Handle NULL value for "mbr_sex" + } + + // Check if "off_bonus" is not NULL + double offBonus = rs.getDouble("off_bonus"); + if (!rs.wasNull()) { + member.setOffBonus(offBonus); + } else { + // Handle NULL value for "off_bonus" + } + + // Repeat similar checks for other fields... + } + + // 清理环境 + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException | ClassNotFoundException e) { + // 处理异常 + e.printStackTrace(); + } + return member; + } + + private double calculateOverallVariance(Map varianceMap) { + // 计算平均值 + double mean = varianceMap.values().stream().mapToDouble(Double::doubleValue).average().orElse(0.0); + + // 计算方差 + double sumOfSquaredDifferences = varianceMap.values().stream() + .mapToDouble(value -> Math.pow(value - mean, 2)) + .sum(); + + return sumOfSquaredDifferences / varianceMap.size(); + } + + private String getMemberTypeByMemberCode(String memberCode) { + List transactionList = new ArrayList<>(); + Connection conn = null; + Statement stmt = null; + try { + // 注册 JDBC 驱动器 + Class.forName(JDBC_DRIVER); + + // 打开一个连接 + System.out.println("连接数据库..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + + // 执行查询 + System.out.println("创建声明..."); + stmt = conn.createStatement(); + String sql; + String threeMonthsAgoDateAsString = getThreeMonthsAgoDateAsString(); + sql = "SELECT\n" + + "*\n" + + "FROM v_MZG016A\n" + + "WHERE TRX_DATE >= '" + threeMonthsAgoDateAsString +"'\n" + + "AND member_code = '" + memberCode + "'"; + + ResultSet rs = stmt.executeQuery(sql); + // 处理结果集 + while (rs.next()) { + Transaction transaction = new Transaction(); + double itemDiscount = rs.getDouble("item_discount"); + if (!rs.wasNull()) { + transaction.setItemDiscount(itemDiscount); + } + double discountPer = rs.getDouble("discount_per"); + if (!rs.wasNull()) { + transaction.setDiscountPer(discountPer); + } + transaction.setYear(rs.getString("YEAR")); + transaction.setSeason(rs.getString("SEASON")); + + transaction.setSize(rs.getString("SIZE")); + transaction.setColor(rs.getString("COLOR")); + transaction.setNetAmt(rs.getDouble("net_amt")); + transaction.setSubCat(rs.getString("SUB_CAT")); + transaction.setCategory(rs.getString("CATEGORY")); + + transactionList.add(transaction); + } + + // 清理环境 + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException | ClassNotFoundException e) { + // 处理异常 + e.printStackTrace(); + } + + return analysis(transactionList, memberCode); + } + + private String analysis(List transactionList, String memberCode) { + int discountNum = 0; + int currentSeasonNum = 0; + + Map colorCountMap = new HashMap<>(); + Map sizeCountMap = new HashMap<>(); + Map subCatCountMap = new HashMap<>(); + Map categoryCountMap = new HashMap<>(); + int totalCount = transactionList.size(); + double totalPrice = 0; + + // 统计每种颜色和尺寸的出现次数 + for (Transaction transaction : transactionList) { + String color = transaction.getColor(); + colorCountMap.put(color, colorCountMap.getOrDefault(color, 0) + 1); + + totalPrice += transaction.getNetAmt(); + + String size = transaction.getSize(); + sizeCountMap.put(size, sizeCountMap.getOrDefault(size, 0) + 1); + + String subCat = transaction.getSubCat(); + subCatCountMap.put(subCat, subCatCountMap.getOrDefault(size, 0) + 1); + + String category = transaction.getCategory(); + categoryCountMap.put(category, categoryCountMap.getOrDefault(size, 0) + 1); + } + + if (totalCount > 0) { + double avePrice = totalPrice / totalCount; + avePriceMap.put(memberCode, avePrice); + } + + // Step 1: 提取每笔交易的实际付款金额 + List paymentList = transactionList.stream() + .map(Transaction::getNetAmt) + .collect(Collectors.toList()); + + // Step 2: 计算均值 + double mean = paymentList.stream().mapToDouble(Double::doubleValue).average().orElse(0.0); + + // Step 3: 计算标准差 + double priceVariance = paymentList.stream() + .mapToDouble(payment -> Math.pow(payment - mean, 2)) + .average().orElse(0.0); + priceVarianceMap.put(memberCode, priceVariance); + + // 计算颜色的方差 + double colorMean = (double) totalCount / colorCountMap.size(); + double colorVarianceSum = 0; + int maxColorCount = 0; + for (Map.Entry entry : colorCountMap.entrySet()) { + int count = entry.getValue(); + colorVarianceSum += Math.pow(count - colorMean, 2); + if (count > maxColorCount) { + maxColorCount = count; + } + } + double colorVariance = colorVarianceSum / colorCountMap.size(); + + // 计算尺寸的方差 + double sizeMean = (double) totalCount / sizeCountMap.size(); + double sizeVarianceSum = 0; + int maxSizeCount = 0; + for (Map.Entry entry : sizeCountMap.entrySet()) { + int count = entry.getValue(); + sizeVarianceSum += Math.pow(count - sizeMean, 2); + if (count > maxSizeCount) { + maxSizeCount = count; + } + } + double sizeVariance = sizeVarianceSum / sizeCountMap.size(); + + // 计算SUBCAT的方差 + double subCatMean = (double) totalCount / subCatCountMap.size(); + double subCatVarianceSum = 0; + int maxSubCatCount = 0; + for (Map.Entry entry : subCatCountMap.entrySet()) { + int count = entry.getValue(); + subCatVarianceSum += Math.pow(count - subCatMean, 2); + if (count > maxSubCatCount) { + maxSubCatCount = count; + } + } + double subCatVariance = subCatVarianceSum / subCatCountMap.size(); + + // 计算category的方差 + double categoryMean = (double) totalCount / categoryCountMap.size(); + double categoryVarianceSum = 0; + int maxCategoryCount = 0; + for (Map.Entry entry : categoryCountMap.entrySet()) { + int count = entry.getValue(); + categoryVarianceSum += Math.pow(count - categoryMean, 2); + if (count > maxCategoryCount) { + maxCategoryCount = count; + } + } + double categoryVariance = categoryVarianceSum / categoryCountMap.size(); + + // 获取出现次数最多的颜色 + int finalMaxColorCount = maxColorCount; + List mostFrequentColors = colorCountMap.entrySet().stream() + .filter(entry -> entry.getValue() == finalMaxColorCount) + .map(Map.Entry::getKey) + .collect(Collectors.toList()); + String mostFrequentColor = String.join(",", mostFrequentColors); + + // 获取出现次数最多的尺寸 + int finalMaxSizeCount = maxSizeCount; + List mostFrequentSizes = sizeCountMap.entrySet().stream() + .filter(entry -> entry.getValue() == finalMaxSizeCount) + .map(Map.Entry::getKey) + .collect(Collectors.toList()); + String size = String.join(",", mostFrequentSizes); + + // 获取出现次数最多的SubCat + int finalMaxSubCatCount = maxSubCatCount; + List mostFrequentSubCats = subCatCountMap.entrySet().stream() + .filter(entry -> entry.getValue() == finalMaxSubCatCount) + .map(Map.Entry::getKey) + .collect(Collectors.toList()); + String subCat = String.join(",", mostFrequentSubCats); + + // 获取出现次数最多的category + int finalMaxCategoryCount = maxCategoryCount; + List mostFrequentCategory = categoryCountMap.entrySet().stream() + .filter(entry -> entry.getValue() == finalMaxCategoryCount) + .map(Map.Entry::getKey) + .collect(Collectors.toList()); + String category = String.join(",", mostFrequentCategory); + + // 统计折扣和当季商品数量 + for (Transaction transaction : transactionList) { + if ((transaction.getDiscountPer() != null && transaction.getDiscountPer() >= 20.0) || transaction.getSubCat().equals("TWIN SET")) { + discountNum++; + } + if (transaction.getYear().equals("TE") && transaction.getSeason().equals("A")) { + currentSeasonNum++; + } + } + + double variance = (colorVariance + sizeVariance + subCatVariance + categoryVariance) / 4; + varianceMap.put(memberCode, variance); +// varianceMap.put(memberCode, sizeVariance); + mostFrequentColorMap.put(memberCode, mostFrequentColor); + mostFrequentSizeMap.put(memberCode, size); + mostFrequentSubCatMap.put(memberCode, subCat); + mostFrequentCategoryMap.put(memberCode, category); + + if (discountNum >= transactionList.size() * 0.5) { + return "Type C"; + } + if (currentSeasonNum >= transactionList.size() * 0.7) { + return "Type i"; + } + return null; + } + + private List getMemberCode() { + List result = new ArrayList<>(); + Connection conn = null; + Statement stmt = null; + try { + // 注册 JDBC 驱动器 + Class.forName(JDBC_DRIVER); + + // 打开一个连接 + System.out.println("连接数据库..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + + // 执行查询 + System.out.println("创建声明..."); + stmt = conn.createStatement(); + String sql; + String threeMonthsAgoDateAsString = getThreeMonthsAgoDateAsString(); + sql = "SELECT\n" + + "member_code\n" + + "FROM v_MZG016A\n" + + "WHERE TRX_DATE > '" + threeMonthsAgoDateAsString + "'\n" + + "GROUP BY member_code"; + + ResultSet rs = stmt.executeQuery(sql); + // 处理结果集 + while (rs.next()) { + result.add(rs.getString("member_code")); + } + + // 清理环境 + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException | ClassNotFoundException e) { + // 处理异常 + e.printStackTrace(); + } + System.out.println("查询执行完成!"); + return result; + } + + public static String getThreeMonthsAgoDateAsString() { + // 获取当前日期和时间 + LocalDateTime currentDateTime = LocalDateTime.now(); + + // 计算三个月前的日期和时间 + LocalDateTime threeMonthsAgoDateTime = currentDateTime.minusMonths(3); + + // 格式化日期和时间为字符串 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String threeMonthsAgoDateTimeAsString = threeMonthsAgoDateTime.format(formatter); + + return threeMonthsAgoDateTimeAsString; + } + + @Resource + private TProductAttributeMapper productAttributeMapper; + + public void getData() { +// QueryWrapper qw = new QueryWrapper<>(); +// List productList = productMapper.selectList(qw); // Map map = new HashMap<>(); -// for (TProductVO datum : data) { -// Map a = new HashMap<>(); -// a.put("category", datum.getItemGroup()); -// a.put("subCategory", datum.getSubGroup()); -// map.put(datum.getPictureName(), a); -// } -// System.out.println(JSON.toJSONString(map)); -// } -// -// @Resource -// private SalesRecordMapper salesRecordMapper; -// -// private void runDailySalesIncentiveStatisticsForPast30Days() { -// LocalDate today = LocalDate.now(); -// for (int i = 0; i < 30; i++) { -// dailySalesIncentiveStatistics(today); -// today = today.minusDays(1); // 日期向前移动一天 -// } -// } -// public void dailySalesIncentiveStatistics(LocalDate localDate) { -// // 获取前一日所有商品销售记录 -// -// // 全日最高個人生意額 (每日計) -// List saleRecordList = getSales(localDate); -// if (!CollectionUtils.isEmpty(saleRecordList)) { -// Transaction transaction = saleRecordList.get(0); -// SalesRecord salesRecord = new SalesRecord(); -// salesRecord.setSalesmanName(transaction.getSalesmanName()); -// salesRecord.setIncentiveNum(3); -// salesRecord.setTaskId(1); -// salesRecordMapper.insert(salesRecord); -// } -// -// // 全日最高個人銷售件數 (每日計) -// List saleRecordList1 = getSalesNumTop(localDate); -// if (!CollectionUtils.isEmpty(saleRecordList1)) { -// int i = 0; -// Transaction transaction = saleRecordList1.get(0); -// Integer totalNum = transaction.getTotalNum(); -// -// for (int i1 = 1; i1 < saleRecordList1.size(); i1++) { -// if (Objects.equals(saleRecordList1.get(i1).getTotalNum(), totalNum)) { -// i ++; -// } -// } -// -// for (int i1 = 0; i1 < i; i1++) { -// Transaction transaction1 = saleRecordList1.get(i1); -// -// SalesRecord salesRecord = new SalesRecord(); -// salesRecord.setSalesmanName(transaction1.getSalesmanName()); -// salesRecord.setIncentiveNum(3); -// salesRecord.setTaskId(2); -// salesRecordMapper.insert(salesRecord); +// for (TProduct tProduct : productList) { +// Map aaa = new HashMap<>(); +// QueryWrapper tProductAttributeQueryWrapper = new QueryWrapper<>(); +// tProductAttributeQueryWrapper.eq("product_id", tProduct.getId()); +// tProductAttributeQueryWrapper.eq("attribute_type", "Length"); +// List tProductAttributes = productAttributeMapper.selectList(tProductAttributeQueryWrapper); +// if (!CollectionUtils.isEmpty(tProductAttributes)) { +// TProductAttribute tProductAttribute = tProductAttributes.get(0); +// aaa.put("category", tProductAttribute.getAttributeItem()); +// aaa.put("Length", tProductAttribute.getAttributeValue()); // } +// map.put(tProduct.getPictureName(), aaa); // } -// -// List saleRecordList2 = getSalesByCategory(localDate); -// if (!CollectionUtils.isEmpty(saleRecordList2)) { -// for (Transaction transaction : saleRecordList2) { -// SalesRecord salesRecord = new SalesRecord(); -// salesRecord.setSalesmanName(transaction.getSalesmanName()); -// salesRecord.setIncentiveNum(transaction.getTotalNum()); -// salesRecord.setTaskId(3); -// salesRecordMapper.insert(salesRecord); -// } -// } -// -// List saleRecordList3 = getSalesByMultiSelling(localDate); -// if (!CollectionUtils.isEmpty(saleRecordList3)) { -// for (Transaction transaction : saleRecordList3) { -// SalesRecord salesRecord = new SalesRecord(); -// salesRecord.setSalesmanName(transaction.getSalesmanName()); -// salesRecord.setIncentiveNum(2); -// salesRecord.setTaskId(4); -// salesRecordMapper.insert(salesRecord); -// } -// } -// -// List saleRecordList4 = getSalesByPluCode(localDate); -// if (!CollectionUtils.isEmpty(saleRecordList4)) { -// for (Transaction transaction : saleRecordList4) { -// SalesRecord salesRecord = new SalesRecord(); -// salesRecord.setSalesmanName(transaction.getSalesmanName()); -// salesRecord.setIncentiveNum(2); -// salesRecord.setTaskId(5); -// salesRecordMapper.insert(salesRecord); -// } -// } -// -// -// -// -// -// } -// -// private List getSalesByPluCode(LocalDate localDate) { -// // 获取今日日期 -// LocalDate today = localDate; -// -// // 获取昨日日期 -// LocalDate yesterday = today.minusDays(1); -// -// // 格式化日期 -// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); -// String todayStr = today.format(formatter); -// String yesterdayStr = yesterday.format(formatter); -// List result = new ArrayList<>(); -// Connection conn = null; -// Statement stmt = null; -// try { -// // 注册 JDBC 驱动器 -// Class.forName(JDBC_DRIVER); -// -// // 打开一个连接 -// System.out.println("连接数据库..."); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// -// // 执行查询 -// System.out.println("创建声明..."); -// stmt = conn.createStatement(); -// String sql; -// sql = "SELECT\n" + -// "saleman_name\n" + -// "FROM v_MZG016A\n" + -// "WHERE trx_no IN \n" + -// "(SELECT trx_no\n" + -// " FROM V_MZG013\n" + -// "WHERE trx_date >= '" + yesterdayStr + "'\n" + -// "AND trx_date < '" + todayStr + "')\n" + -// "AND plu_code in ('MTDTEAN29367','MTDTEAN29350')"; -// -// ResultSet rs = stmt.executeQuery(sql); -// // 处理结果集 -// while (rs.next()) { -// Transaction transaction = new Transaction(); -// transaction.setSalesmanName(rs.getString("saleman_name")); -//// transaction.setTrxNo(rs.getString("trx_no")); -// result.add(transaction); -// } -// -// // 清理环境 -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException | ClassNotFoundException e) { -// // 处理异常 -// e.printStackTrace(); -// } -// System.out.println("查询执行完成!"); -// return result; -// } -// -// private List getSalesByMultiSelling(LocalDate localDate) { -// // 获取今日日期 -// LocalDate today = localDate; -// -// // 获取昨日日期 -// LocalDate yesterday = today.minusDays(1); -// -// // 格式化日期 -// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); -// String todayStr = today.format(formatter); -// String yesterdayStr = yesterday.format(formatter); -// List result = new ArrayList<>(); -// Connection conn = null; -// Statement stmt = null; -// try { -// // 注册 JDBC 驱动器 -// Class.forName(JDBC_DRIVER); -// -// // 打开一个连接 -// System.out.println("连接数据库..."); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// -// // 执行查询 -// System.out.println("创建声明..."); -// stmt = conn.createStatement(); -// String sql; -// sql = "SELECT\n" + -// "trx_no,\n" + -// "saleman_name\n" + -// "FROM v_MZG016A\n" + -// "WHERE trx_no IN \n" + -// "(SELECT\n" + -// " trx_no\n" + -// "FROM v_MZG016A\n" + -// "WHERE trx_no IN \n" + -// "(SELECT trx_no\n" + -// " FROM V_MZG013\n" + -// "WHERE trx_date >= '" + yesterdayStr + "'\n" + -// "AND trx_date < '" + todayStr + "')\n" + -// "GROUP BY trx_no\n" + -// "HAVING COUNT(*) >= 4)\n" + -// "GROUP BY trx_no, saleman_name"; -// -// ResultSet rs = stmt.executeQuery(sql); -// // 处理结果集 -// while (rs.next()) { -// Transaction transaction = new Transaction(); -// transaction.setSalesmanName(rs.getString("saleman_name")); + List data = miTuProductMapper.getData(); + Map map = new HashMap<>(); + for (TProductVO datum : data) { + Map a = new HashMap<>(); + a.put("category", datum.getItemGroup()); + a.put("subCategory", datum.getSubGroup()); + map.put(datum.getPictureName(), a); + } + System.out.println(JSON.toJSONString(map)); + } + + @Resource + private SalesRecordMapper salesRecordMapper; + + private void runDailySalesIncentiveStatisticsForPast30Days() { + LocalDate today = LocalDate.now(); + for (int i = 0; i < 1; i++) { + dailySalesIncentiveStatistics(today); + today = today.minusDays(1); // 日期向前移动一天 + } + } + public void dailySalesIncentiveStatistics(LocalDate localDate) { + // 获取前一日所有商品销售记录 + + // 全日最高個人生意額 (每日計) + List saleRecordList = getSales(localDate); + if (!CollectionUtils.isEmpty(saleRecordList)) { + Transaction transaction = saleRecordList.get(0); + SalesRecord salesRecord = new SalesRecord(); + salesRecord.setSalesmanName(transaction.getSalesmanName()); + salesRecord.setIncentiveNum(3); + salesRecord.setTaskId(1); + salesRecordMapper.insert(salesRecord); + } + + // 全日最高個人銷售件數 (每日計) + List saleRecordList1 = getSalesNumTop(localDate); + if (!CollectionUtils.isEmpty(saleRecordList1)) { + int i = 0; + Transaction transaction = saleRecordList1.get(0); + Integer totalNum = transaction.getTotalNum(); + + for (int i1 = 1; i1 < saleRecordList1.size(); i1++) { + if (Objects.equals(saleRecordList1.get(i1).getTotalNum(), totalNum)) { + i ++; + } + } + + for (int i1 = 0; i1 < i; i1++) { + Transaction transaction1 = saleRecordList1.get(i1); + + SalesRecord salesRecord = new SalesRecord(); + salesRecord.setSalesmanName(transaction1.getSalesmanName()); + salesRecord.setIncentiveNum(3); + salesRecord.setTaskId(2); + salesRecordMapper.insert(salesRecord); + } + } + + List saleRecordList2 = getSalesByCategory(localDate); + if (!CollectionUtils.isEmpty(saleRecordList2)) { + for (Transaction transaction : saleRecordList2) { + SalesRecord salesRecord = new SalesRecord(); + salesRecord.setSalesmanName(transaction.getSalesmanName()); + salesRecord.setIncentiveNum(transaction.getTotalNum()); + salesRecord.setTaskId(3); + salesRecordMapper.insert(salesRecord); + } + } + + List saleRecordList3 = getSalesByMultiSelling(localDate); + if (!CollectionUtils.isEmpty(saleRecordList3)) { + for (Transaction transaction : saleRecordList3) { + SalesRecord salesRecord = new SalesRecord(); + salesRecord.setSalesmanName(transaction.getSalesmanName()); + salesRecord.setIncentiveNum(2); + salesRecord.setTaskId(4); + salesRecordMapper.insert(salesRecord); + } + } + + List saleRecordList4 = getSalesByPluCode(localDate); + if (!CollectionUtils.isEmpty(saleRecordList4)) { + for (Transaction transaction : saleRecordList4) { + SalesRecord salesRecord = new SalesRecord(); + salesRecord.setSalesmanName(transaction.getSalesmanName()); + salesRecord.setIncentiveNum(2); + salesRecord.setTaskId(5); + salesRecordMapper.insert(salesRecord); + } + } + + + + + + } + + private List getSalesByPluCode(LocalDate localDate) { + // 获取今日日期 + LocalDate today = localDate; + + // 获取昨日日期 + LocalDate yesterday = today.minusDays(1); + + // 格式化日期 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String todayStr = today.format(formatter); + String yesterdayStr = yesterday.format(formatter); + List result = new ArrayList<>(); + Connection conn = null; + Statement stmt = null; + try { + // 注册 JDBC 驱动器 + Class.forName(JDBC_DRIVER); + + // 打开一个连接 + System.out.println("连接数据库..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + + // 执行查询 + System.out.println("创建声明..."); + stmt = conn.createStatement(); + String sql; + sql = "SELECT\n" + + "saleman_name\n" + + "FROM v_MZG016A\n" + + "WHERE trx_no IN \n" + + "(SELECT trx_no\n" + + " FROM V_MZG013\n" + + "WHERE trx_date >= '" + yesterdayStr + "'\n" + + "AND trx_date < '" + todayStr + "')\n" + + "AND plu_code in ('MTDTEAN29367','MTDTEAN29350')"; + + ResultSet rs = stmt.executeQuery(sql); + // 处理结果集 + while (rs.next()) { + Transaction transaction = new Transaction(); + transaction.setSalesmanName(rs.getString("saleman_name")); // transaction.setTrxNo(rs.getString("trx_no")); -// result.add(transaction); -// } + result.add(transaction); + } + + // 清理环境 + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException | ClassNotFoundException e) { + // 处理异常 + e.printStackTrace(); + } + System.out.println("查询执行完成!"); + return result; + } + + private List getSalesByMultiSelling(LocalDate localDate) { + // 获取今日日期 + LocalDate today = localDate; + + // 获取昨日日期 + LocalDate yesterday = today.minusDays(1); + + // 格式化日期 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String todayStr = today.format(formatter); + String yesterdayStr = yesterday.format(formatter); + List result = new ArrayList<>(); + Connection conn = null; + Statement stmt = null; + try { + // 注册 JDBC 驱动器 + Class.forName(JDBC_DRIVER); + + // 打开一个连接 + System.out.println("连接数据库..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + + // 执行查询 + System.out.println("创建声明..."); + stmt = conn.createStatement(); + String sql; + sql = "SELECT\n" + + "trx_no,\n" + + "saleman_name\n" + + "FROM v_MZG016A\n" + + "WHERE trx_no IN \n" + + "(SELECT\n" + + " trx_no\n" + + "FROM v_MZG016A\n" + + "WHERE trx_no IN \n" + + "(SELECT trx_no\n" + + " FROM V_MZG013\n" + + "WHERE trx_date >= '" + yesterdayStr + "'\n" + + "AND trx_date < '" + todayStr + "')\n" + + "GROUP BY trx_no\n" + + "HAVING COUNT(*) >= 4)\n" + + "GROUP BY trx_no, saleman_name"; + + ResultSet rs = stmt.executeQuery(sql); + // 处理结果集 + while (rs.next()) { + Transaction transaction = new Transaction(); + transaction.setSalesmanName(rs.getString("saleman_name")); + transaction.setTrxNo(rs.getString("trx_no")); + result.add(transaction); + } + + // 清理环境 + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException | ClassNotFoundException e) { + // 处理异常 + e.printStackTrace(); + } + System.out.println("查询执行完成!"); + return result; + } + + private List getSales(LocalDate date) { + // 获取昨日日期 + LocalDate yesterday = date.minusDays(1); + + // 格式化日期 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String todayStr = date.format(formatter); + String yesterdayStr = yesterday.format(formatter); + List result = new ArrayList<>(); + Connection conn = null; + Statement stmt = null; + try { + // 注册 JDBC 驱动器 + Class.forName(JDBC_DRIVER); + + // 打开一个连接 + System.out.println("连接数据库..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + + // 执行查询 + System.out.println("创建声明..."); + stmt = conn.createStatement(); + String sql = "SELECT\n" + + "saleman_name,\n" + + "SUM(net_amt) AS total_net_amt\n" + + "FROM v_MZG016A\n" + + "WHERE trx_no in (SELECT trx_no FROM V_MZG013\n" + + "WHERE trx_date >= '" + yesterdayStr + "'\n" + + "AND trx_date < '" + todayStr + "'\n" + + "and pay_desc != 'Bonus'\n" + + "AND pay_desc != 'mi-tu Cash Coupon')\n" + + "GROUP BY saleman_name\n" + + "ORDER BY total_net_amt desc"; + + ResultSet rs = stmt.executeQuery(sql); + // 处理结果集 + while (rs.next()) { + Transaction transaction = new Transaction(); + transaction.setSalesmanName(rs.getString("saleman_name")); + transaction.setNetAmt(rs.getDouble("total_net_amt")); + result.add(transaction); + } + + // 清理环境 + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException | ClassNotFoundException e) { + // 处理异常 + e.printStackTrace(); + } + System.out.println("查询执行完成!"); + return result; + } + + + private List getSalesNumTop(LocalDate localDate) { + // 获取今日日期 + LocalDate today = localDate; + + // 获取昨日日期 + LocalDate yesterday = today.minusDays(1); + + // 格式化日期 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String todayStr = today.format(formatter); + String yesterdayStr = yesterday.format(formatter); + List result = new ArrayList<>(); + Connection conn = null; + Statement stmt = null; + try { + // 注册 JDBC 驱动器 + Class.forName(JDBC_DRIVER); + + // 打开一个连接 + System.out.println("连接数据库..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + + // 执行查询 + System.out.println("创建声明..."); + stmt = conn.createStatement(); + String sql; + sql = "SELECT\n" + + "saleman_name,\n" + + "COUNT(*) AS total_count\n" + + "FROM v_MZG016A\n" + + "WHERE trx_no in (SELECT trx_no FROM V_MZG013\n" + + "WHERE trx_date >= '" + yesterdayStr + "'\n" + + "AND trx_date < '" + todayStr + "')\n" + + "AND CAT_DESC != 'GIFT'\n" + + "GROUP BY saleman_name\n" + + "ORDER BY total_count desc"; + + ResultSet rs = stmt.executeQuery(sql); + // 处理结果集 + while (rs.next()) { + Transaction transaction = new Transaction(); + transaction.setSalesmanName(rs.getString("saleman_name")); + transaction.setTotalNum(rs.getInt("total_count")); + result.add(transaction); + } + + // 清理环境 + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException | ClassNotFoundException e) { + // 处理异常 + e.printStackTrace(); + } + System.out.println("查询执行完成!"); + return result; + + } + + private List getSalesByCategory(LocalDate localDate) { + // 获取今日日期 + LocalDate today = localDate; + + // 获取昨日日期 + LocalDate yesterday = today.minusDays(1); + + // 格式化日期 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String todayStr = today.format(formatter); + String yesterdayStr = yesterday.format(formatter); + List result = new ArrayList<>(); + Connection conn = null; + Statement stmt = null; + try { + // 注册 JDBC 驱动器 + Class.forName(JDBC_DRIVER); + + // 打开一个连接 + System.out.println("连接数据库..."); + conn = DriverManager.getConnection(DB_URL, USER, PASS); + + // 执行查询 + System.out.println("创建声明..."); + stmt = conn.createStatement(); + String sql; + sql = "SELECT\n" + + "saleman_name,\n" + + "COUNT(*) AS total_count\n" + + "FROM v_MZG016A\n" + + "WHERE trx_no in (SELECT trx_no FROM V_MZG013\n" + + "WHERE trx_date >= '" + yesterdayStr + "'\n" + + "AND trx_date < '" + todayStr + "')\n" + + "AND YEAR = 'TE'\n" + + "AND SEASON = 'A'\n" + + "AND CATEGORY = 'ONE PIECE'\n" + + "GROUP BY saleman_name\n" + + "ORDER BY total_count desc"; + + ResultSet rs = stmt.executeQuery(sql); + // 处理结果集 + while (rs.next()) { + Transaction transaction = new Transaction(); + transaction.setSalesmanName(rs.getString("saleman_name")); + transaction.setTotalNum(rs.getInt("total_count")); + result.add(transaction); + } + + // 清理环境 + rs.close(); + stmt.close(); + conn.close(); + } catch (SQLException | ClassNotFoundException e) { + // 处理异常 + e.printStackTrace(); + } + System.out.println("查询执行完成!"); + return result; + + } + + /** + * 压缩图片 + * @param inputImagePath 原始图片路径 + * @param outputImagePath 压缩后图片保存路径 + * @param scaledWidth 压缩后图片的宽度 + * @param scaledHeight 压缩后图片的高度 + * @throws IOException + */ +// public static void compressImage(String inputImagePath, String outputImagePath, int scaledWidth, int scaledHeight) throws IOException { +// // 读取图片 +// BufferedImage inputImage = ImageIO.read(new File(inputImagePath)); // -// // 清理环境 -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException | ClassNotFoundException e) { -// // 处理异常 -// e.printStackTrace(); -// } -// System.out.println("查询执行完成!"); -// return result; +// // 创建输出图片 +// BufferedImage outputImage = new BufferedImage(scaledWidth, scaledHeight, inputImage.getType()); +// +// // 绘制缩放后的图片 +// Graphics2D g2d = outputImage.createGraphics(); +// g2d.drawImage(inputImage.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH), 0, 0, null); +// g2d.dispose(); +// +// // 保存到文件 +// ImageIO.write(outputImage, "jpg", new File(outputImagePath)); // } // -// private List getSales(LocalDate date) { -// // 获取昨日日期 -// LocalDate yesterday = date.minusDays(1); +// public static void main(String[] args) { +// String inputImagePath = "C:\\Users\\10233\\Desktop\\2024 SS\\MKTS27000_0CMY.jpg"; +// String outputImagePath = "C:\\Users\\10233\\Desktop\\2024 SS\\MKTS27000_0CMY_copy.jpg"; // -// // 格式化日期 -// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); -// String todayStr = date.format(formatter); -// String yesterdayStr = yesterday.format(formatter); -// List result = new ArrayList<>(); -// Connection conn = null; -// Statement stmt = null; // try { -// // 注册 JDBC 驱动器 -// Class.forName(JDBC_DRIVER); +// // 压缩图片到指定大小 +// int scaledWidth = 300; +// int scaledHeight = 300; +// compressImage(inputImagePath, outputImagePath, scaledWidth, scaledHeight); // -// // 打开一个连接 -// System.out.println("连接数据库..."); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// -// // 执行查询 -// System.out.println("创建声明..."); -// stmt = conn.createStatement(); -// String sql = "SELECT\n" + -// "saleman_name,\n" + -// "SUM(net_amt) AS total_net_amt\n" + -// "FROM v_MZG016A\n" + -// "WHERE trx_no in (SELECT trx_no FROM V_MZG013\n" + -// "WHERE trx_date >= '" + yesterdayStr + "'\n" + -// "AND trx_date < '" + todayStr + "'\n" + -// "and pay_desc != 'Bonus'\n" + -// "AND pay_desc != 'mi-tu Cash Coupon')\n" + -// "GROUP BY saleman_name\n" + -// "ORDER BY total_net_amt desc"; -// -// ResultSet rs = stmt.executeQuery(sql); -// // 处理结果集 -// while (rs.next()) { -// Transaction transaction = new Transaction(); -// transaction.setSalesmanName(rs.getString("saleman_name")); -// transaction.setNetAmt(rs.getDouble("total_net_amt")); -// result.add(transaction); -// } -// -// // 清理环境 -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException | ClassNotFoundException e) { -// // 处理异常 -// e.printStackTrace(); +// System.out.println("图片压缩完成。"); +// } catch (IOException ex) { +// System.out.println("图片压缩出错: " + ex.getMessage()); // } -// System.out.println("查询执行完成!"); -// return result; // } -// -// -// private List getSalesNumTop(LocalDate localDate) { -// // 获取今日日期 -// LocalDate today = localDate; -// -// // 获取昨日日期 -// LocalDate yesterday = today.minusDays(1); -// -// // 格式化日期 -// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); -// String todayStr = today.format(formatter); -// String yesterdayStr = yesterday.format(formatter); -// List result = new ArrayList<>(); -// Connection conn = null; -// Statement stmt = null; -// try { -// // 注册 JDBC 驱动器 -// Class.forName(JDBC_DRIVER); -// -// // 打开一个连接 -// System.out.println("连接数据库..."); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// -// // 执行查询 -// System.out.println("创建声明..."); -// stmt = conn.createStatement(); -// String sql; -// sql = "SELECT\n" + -// "saleman_name,\n" + -// "COUNT(*) AS total_count\n" + -// "FROM v_MZG016A\n" + -// "WHERE trx_no in (SELECT trx_no FROM V_MZG013\n" + -// "WHERE trx_date >= '" + yesterdayStr + "'\n" + -// "AND trx_date < '" + todayStr + "')\n" + -// "AND CAT_DESC != 'GIFT'\n" + -// "GROUP BY saleman_name\n" + -// "ORDER BY total_count desc"; -// -// ResultSet rs = stmt.executeQuery(sql); -// // 处理结果集 -// while (rs.next()) { -// Transaction transaction = new Transaction(); -// transaction.setSalesmanName(rs.getString("saleman_name")); -// transaction.setTotalNum(rs.getInt("total_count")); -// result.add(transaction); -// } -// -// // 清理环境 -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException | ClassNotFoundException e) { -// // 处理异常 -// e.printStackTrace(); -// } -// System.out.println("查询执行完成!"); -// return result; -// -// } -// -// private List getSalesByCategory(LocalDate localDate) { -// // 获取今日日期 -// LocalDate today = localDate; -// -// // 获取昨日日期 -// LocalDate yesterday = today.minusDays(1); -// -// // 格式化日期 -// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); -// String todayStr = today.format(formatter); -// String yesterdayStr = yesterday.format(formatter); -// List result = new ArrayList<>(); -// Connection conn = null; -// Statement stmt = null; -// try { -// // 注册 JDBC 驱动器 -// Class.forName(JDBC_DRIVER); -// -// // 打开一个连接 -// System.out.println("连接数据库..."); -// conn = DriverManager.getConnection(DB_URL, USER, PASS); -// -// // 执行查询 -// System.out.println("创建声明..."); -// stmt = conn.createStatement(); -// String sql; -// sql = "SELECT\n" + -// "saleman_name,\n" + -// "COUNT(*) AS total_count\n" + -// "FROM v_MZG016A\n" + -// "WHERE trx_no in (SELECT trx_no FROM V_MZG013\n" + -// "WHERE trx_date >= '" + yesterdayStr + "'\n" + -// "AND trx_date < '" + todayStr + "')\n" + -// "AND YEAR = 'TE'\n" + -// "AND SEASON = 'A'\n" + -// "AND CATEGORY = 'ONE PIECE'\n" + -// "GROUP BY saleman_name\n" + -// "ORDER BY total_count desc"; -// -// ResultSet rs = stmt.executeQuery(sql); -// // 处理结果集 -// while (rs.next()) { -// Transaction transaction = new Transaction(); -// transaction.setSalesmanName(rs.getString("saleman_name")); -// transaction.setTotalNum(rs.getInt("total_count")); -// result.add(transaction); -// } -// -// // 清理环境 -// rs.close(); -// stmt.close(); -// conn.close(); -// } catch (SQLException | ClassNotFoundException e) { -// // 处理异常 -// e.printStackTrace(); -// } -// System.out.println("查询执行完成!"); -// return result; -// -// } -// -// /** -// * 压缩图片 -// * @param inputImagePath 原始图片路径 -// * @param outputImagePath 压缩后图片保存路径 -// * @param scaledWidth 压缩后图片的宽度 -// * @param scaledHeight 压缩后图片的高度 -// * @throws IOException -// */ -//// public static void compressImage(String inputImagePath, String outputImagePath, int scaledWidth, int scaledHeight) throws IOException { -//// // 读取图片 -//// BufferedImage inputImage = ImageIO.read(new File(inputImagePath)); -//// -//// // 创建输出图片 -//// BufferedImage outputImage = new BufferedImage(scaledWidth, scaledHeight, inputImage.getType()); -//// -//// // 绘制缩放后的图片 -//// Graphics2D g2d = outputImage.createGraphics(); -//// g2d.drawImage(inputImage.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH), 0, 0, null); -//// g2d.dispose(); -//// -//// // 保存到文件 -//// ImageIO.write(outputImage, "jpg", new File(outputImagePath)); -//// } -//// -//// public static void main(String[] args) { -//// String inputImagePath = "C:\\Users\\10233\\Desktop\\2024 SS\\MKTS27000_0CMY.jpg"; -//// String outputImagePath = "C:\\Users\\10233\\Desktop\\2024 SS\\MKTS27000_0CMY_copy.jpg"; -//// -//// try { -//// // 压缩图片到指定大小 -//// int scaledWidth = 300; -//// int scaledHeight = 300; -//// compressImage(inputImagePath, outputImagePath, scaledWidth, scaledHeight); -//// -//// System.out.println("图片压缩完成。"); -//// } catch (IOException ex) { -//// System.out.println("图片压缩出错: " + ex.getMessage()); -//// } -//// } -//} +} diff --git a/src/main/java/com/mixi/service/PythonService.java b/src/main/java/com/mixi/service/PythonService.java index eab37a2..2b4e014 100644 --- a/src/main/java/com/mixi/service/PythonService.java +++ b/src/main/java/com/mixi/service/PythonService.java @@ -570,17 +570,17 @@ public class PythonService { public JSONObject getAIRecommend(AIRecommendDTO aiRecommendDTO) { //限流校验 - AccessLimitUtils.validate("similarityMatch", 20); +// AccessLimitUtils.validate("similarityMatch", 20); OkHttpClient client = new OkHttpClient().newBuilder() - .connectTimeout(30, TimeUnit.SECONDS) + .connectTimeout(300, TimeUnit.SECONDS) .pingInterval(5, TimeUnit.SECONDS)//websocket轮训间隔(单位:秒) .readTimeout(300, TimeUnit.SECONDS)//读取超时(单位:秒) .writeTimeout(300, TimeUnit.SECONDS)//写入超时(单位:秒) .build(); MediaType mediaType = MediaType.parse("application/json"); Map content = Maps.newHashMap(); - content.put("input_message", "recommend three outfits"); - content.put("user_id", "user456"); + content.put("input_message", "recommend four outfits"); + content.put("user_id", aiRecommendDTO.getUserId()); content.put("image_urls", ""); RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(content)); @@ -594,13 +594,13 @@ public class PythonService { Response response = null; String bodyStr = null; try { - log.info("获取python获取相似商品请求入参content###{}", JSON.toJSONString(content)); + log.info("获取python获取AI推荐请求入参content###{}", JSON.toJSONString(content)); response = client.newCall(request).execute(); bodyStr = response.body().string(); } catch (IOException ioException) { log.error("PythonService##similarityMatch异常###{}", ExceptionUtil.getThrowableList(ioException)); } - log.info("识获取python获取相似商品请求结果###{}", bodyStr.trim()); + log.info("识获取python获取AI推荐请求结果###{}", bodyStr.trim()); //去除限流 AccessLimitUtils.validateOut("similarityMatch"); if (Objects.isNull(response)) { @@ -613,8 +613,8 @@ public class PythonService { JSONObject parseObject = JSON.parseObject(bodyStr.trim()); return parseObject; } - log.info("获取python获取相似商品请求异常###{}", jsonObject); + log.info("获取python获取AI推荐请求异常###{}", jsonObject); //生成失败 - throw new BusinessException("SimilarityMatch exception."); + throw new BusinessException("AI recommendation exception."); } } diff --git a/src/main/java/com/mixi/service/TAppProductService.java b/src/main/java/com/mixi/service/TAppProductService.java index 1b536ea..c5ce67d 100644 --- a/src/main/java/com/mixi/service/TAppProductService.java +++ b/src/main/java/com/mixi/service/TAppProductService.java @@ -740,96 +740,80 @@ public class TAppProductService extends ServiceImpl { // private MinioUtil minioUtil; public List aiRecommend(AIRecommendDTO aiRecommendDTO) { + List result = new ArrayList<>(); // 创建推荐对象 OutfitRecommendation recommendation = new OutfitRecommendation(); // 调用ai推荐模型 -// JSONObject jsonObject = pythonService.getAIRecommend(aiRecommendDTO); -// -// // 检查jsonObject是否为null -// if (jsonObject == null) { -// throw new NullPointerException("The response from Python service is null"); -// } + JSONObject jsonObject = pythonService.getAIRecommend(aiRecommendDTO); + + // 检查jsonObject是否为null + if (jsonObject == null) { + throw new NullPointerException("The response from Python service is null"); + } // 从JSON对象中获取output字段 -// String output = jsonObject.getString("output"); - String output = "I have a great outfit recommendation for you! Here are the details:\n\n### Recommended Outfit:\n1. **Tailored Navy Blue Blazer**\n - **Description**: A single-breasted design with notched lapels and a slim fit. Features two front flap pockets and a single button closure. Made from a wool blend for a structured yet comfortable feel.\n - ![Navy Blue Blazer](fashion_items/mitu/MKTS27015_0CMY.jpg)\n\n2. **White Silk Blouse**\n - **Description**: A classic collar, button-down front, and long sleeves with buttoned cuffs. Slightly loose fit for a sophisticated and airy look.\n - ![White Silk Blouse](fashion_items/mitu/MKTS27018_0WHT.jpg)\n\n3. **High-Waisted Beige Trousers**\n - **Description**: Straight-leg trousers in a light beige color. Clean front with a concealed hook-and-bar closure, side pockets, and a slightly cropped length to show off the ankles.\n - ![Beige Trousers](fashion_items/mitu/MLSS27160_0BGE.jpg)\n\n### Reasons for Recommendation:\n- **Parisian Chic Theme**: Classic and versatile pieces that embody sophistication and elegance.\n- **Navy Blue Blazer**: Adds a touch of structure, perfect for various occasions.\n- **White Silk Blouse**: A timeless staple that pairs well with the blazer.\n- **High-Waisted Beige Trousers**: Neutral base that complements the navy and white, creating a balanced and polished ensemble.\n\nThis combination is ideal for general use and can be dressed up or down depending on the occasion. Enjoy your new look!"; + String output = jsonObject.getString("output"); +// String output = "Here are three outfit recommendations for you:\n" + +// "\n" + +// "1. **Garden Party or Brunch Look**:\n" + +// " - **Floral Dress**: A long floral dress with a gathered waist, featuring a wrap-style bodice and three-quarter sleeves. It's crafted from lightweight cotton with a multicolored botanical pattern, suitable for casual or semi-formal wear.\n" + +// " - **Denim Jacket**: A short denim jacket with a classic collar, button closures, and front pockets, crafted from blue denim. It adds a touch of casual chic, ideal for transitioning from day to evening.\n" + +// " - ![Floral Dress](fashion_items/mitu/images/MWSS27211_0LGN.jpg)\n" + +// " - ![Denim Jacket](fashion_items/mitu/images/MLSS27109_0DBL.jpg)\n" + +// "\n" + +// "2. **Casual Summer Day**:\n" + +// " - **Mid-Length Dress**: Featuring short sleeves and a shirt collar, crafted from lightweight blue fabric with white stripes and floral embroidery. It includes a belted waist and tiered skirt for a casual, summery style.\n" + +// " - **Tropical Top**: A sleeveless top with a round neckline and a tropical leaf print in green and beige on a white background, perfect for a sunny outing.\n" + +// " - ![Mid-Length Dress](fashion_items/mitu/images/MLSS27102_0BLU.jpg)\n" + +// " - ![Tropical Top](fashion_items/mitu/images/MLSS27156_0GRN.jpg)\n" + +// "\n" + +// "3. **Everyday Relaxed Look**:\n" + +// " - **White Blouse**: A long-sleeve blouse with a V-neckline and gathered cuffs, made from lightweight cotton. It offers a casual, airy style suitable for everyday wear.\n" + +// " - **Wide-Leg Pants**: Beige wide-leg pants with a striped waistband, crafted from a smooth fabric. They feature side pockets and a sleek, casual design.\n" + +// " - ![White Blouse](fashion_items/mitu/images/MKTS27002_0WHT.jpg)\n" + +// " - ![Wide-Leg Pants](fashion_items/mitu/images/MKTS27004_0BGE.jpg)\n" + +// "\n" + +// "These outfits are designed to provide comfort and style for various occasions. Enjoy your new looks!"; - List urls = extractBracketContents(output); - Map map = new HashMap<>(); - for (String url : urls) { - if (url.contains("/")) { - String[] split = url.split("/"); - String s = split[split.length - 1]; - if (s.contains(".")) { - String[] split1 = s.split("\\."); - String pictureName = split1[0]; - QueryWrapper qw = new QueryWrapper<>(); - qw.lambda().like(TProduct::getPictureName, pictureName); - List productList = productMapper.selectList(qw); - if (!CollectionUtils.isEmpty(productList)) { - String pictureUrl = productList.get(0).getPictureUrl(); - String presignedUrl = minioUtil.getPresignedUrl(pictureUrl, 24 * 60); - map.put(url, presignedUrl); - recommendation.addImageUrl(presignedUrl); + String[] parts = output.split("\\n\\n"); + + int length = parts.length; + String start = parts[0]; + String end = parts[length - 1]; + if (length >= 3) { + for (int i = 1; i < (length - 1); i++) { + OutfitRecommendation outfitRecommendation = new OutfitRecommendation(); + String part = parts[i]; + List urls = extractBracketContents(part); + Map map = new HashMap<>(); + for (String url : urls) { + if (url.contains("/")) { + String[] split = url.split("/"); + String s = split[split.length - 1]; + if (s.contains(".")) { + String[] split1 = s.split("\\."); + String pictureName = split1[0]; + QueryWrapper qw = new QueryWrapper<>(); + qw.lambda().like(TProduct::getPictureName, pictureName); + List productList = productMapper.selectList(qw); + if (!CollectionUtils.isEmpty(productList)) { + String pictureUrl = productList.get(0).getPictureUrl(); + String presignedUrl = minioUtil.getPresignedUrl(pictureUrl, 24 * 60); + map.put(url, presignedUrl); + outfitRecommendation.addImageUrl(presignedUrl); + } + } } } + for (String s : map.keySet()) { + part = part.replace(s, map.get(s)); + } + String recommendOutput = start + "\n\n" + part + "\n\n" + end; + outfitRecommendation.setMarkdownContent(recommendOutput); + result.add(outfitRecommendation); } } - - for (String s : map.keySet()) { - output = output.replace(s, map.get(s)); - } - - System.out.println(output); - -// // 解析output字符串 -// String[] parts = output.split("\n\n"); -// -// // 创建Markdown格式内容 -// StringBuilder markdownBuilder = new StringBuilder(); -// -// // 处理描述部分 -// if (parts.length > 1) { -// markdownBuilder.append("### Outfit Description:\n"); -// markdownBuilder.append(parts[1]).append("\n\n"); -// } -// -// // 处理推荐理由部分 -// markdownBuilder.append("### Reasons for Recommendation:\n"); -// StringBuilder reasonsBuilder = new StringBuilder(); -// for (int i = 2; i < parts.length; i++) { -// if (parts[i].contains("![") && parts[i].contains("](") && parts[i].contains(")")) { -// // 找到图像URL部分 -// try { -// String imageUrlPart = parts[i]; -// String imageUrl = imageUrlPart.substring(imageUrlPart.indexOf("](") + 2, imageUrlPart.indexOf(")")); -// recommendation.addImageUrl(imageUrl); -// -// // 添加到Markdown -// markdownBuilder.append(imageUrlPart).append("\n\n"); -// } catch (StringIndexOutOfBoundsException e) { -// // 捕获异常并继续处理剩余的部分 -// e.printStackTrace(); -// } -// } else { -// reasonsBuilder.append(parts[i]).append("\n\n"); -// } -// } -// recommendation.setReasons(reasonsBuilder.toString().trim()); -// -// // 将推荐理由添加到Markdown -// markdownBuilder.append(recommendation.getReasons()).append("\n\n"); - - // 设置Markdown内容 - recommendation.setMarkdownContent(output); -// recommendation.setMarkdownContent(output + output + output + output + output); -// System.out.println(markdownBuilder.toString().trim()); - List result = new ArrayList<>(); - result.add(recommendation); - result.add(recommendation); - result.add(recommendation); - result.add(recommendation); return result; }