From 58310b1e33c27395fe20cc1817495704e1c312e5 Mon Sep 17 00:00:00 2001 From: Timi Date: Mon, 23 Nov 2026 15:27:25 +0800 Subject: [PATCH] feat(gao): add customer profile and event month PDF exports --- README.md | 10 +- pom.xml | 11 + .../implement/AttachmentServiceImplement.java | 3 + .../modules/gao/bean/GaoPermissionCode.java | 2 + .../GaoCustomerProfileController.java | 43 ++ .../GaoEventMonthExportController.java | 38 ++ .../controller/GaoReportOptionController.java | 44 ++ .../gao/mapper/GaoCustomerProfileMapper.java | 46 ++ .../gao/mapper/GaoEventMonthExportMapper.java | 10 + .../gao/mapper/GaoReportOptionMapper.java | 9 + .../service/GaoCustomerProfileService.java | 426 ++++++++++++++++++ .../service/GaoEventMonthExportService.java | 140 ++++++ .../GaoCustomerServiceImplement.java | 1 + .../api/modules/gao/util/GaoBodyArea.java | 47 ++ .../gao/util/GaoProfileNumberFormatter.java | 36 ++ .../gao/vo/event/GaoEventMonthRecord.java | 11 + .../gao/vo/report/GaoReportOption.java | 11 + .../gao/GaoCustomerProfileMapper.xml | 117 +++++ .../gao/GaoEventMonthExportMapper.xml | 13 + .../timi-server/gao/GaoReportOptionMapper.xml | 10 + .../templates/GaoCustomerProfile.ftl | 396 ++++++++++++++++ .../templates/GaoEventMonthExport.ftl | 120 +++++ .../service/GaoCustomerProfilePhotoTest.java | 38 ++ .../gao/service/GaoEventMonthExportTest.java | 105 +++++ .../gao/service/GaoReportOptionTest.java | 46 ++ 25 files changed, 1732 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/imyeyu/api/modules/gao/controller/GaoCustomerProfileController.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/controller/GaoEventMonthExportController.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/controller/GaoReportOptionController.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/mapper/GaoCustomerProfileMapper.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/mapper/GaoEventMonthExportMapper.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/mapper/GaoReportOptionMapper.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/service/GaoCustomerProfileService.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/service/GaoEventMonthExportService.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/util/GaoBodyArea.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/util/GaoProfileNumberFormatter.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/vo/event/GaoEventMonthRecord.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/vo/report/GaoReportOption.java create mode 100644 src/main/resources/mapper/timi-server/gao/GaoCustomerProfileMapper.xml create mode 100644 src/main/resources/mapper/timi-server/gao/GaoEventMonthExportMapper.xml create mode 100644 src/main/resources/mapper/timi-server/gao/GaoReportOptionMapper.xml create mode 100644 src/main/resources/templates/GaoCustomerProfile.ftl create mode 100644 src/main/resources/templates/GaoEventMonthExport.ftl create mode 100644 src/test/java/com/imyeyu/api/modules/gao/service/GaoCustomerProfilePhotoTest.java create mode 100644 src/test/java/com/imyeyu/api/modules/gao/service/GaoEventMonthExportTest.java create mode 100644 src/test/java/com/imyeyu/api/modules/gao/service/GaoReportOptionTest.java diff --git a/README.md b/README.md index 039fb67..3b95c55 100644 --- a/README.md +++ b/README.md @@ -4,4 +4,12 @@ 技术栈:SpringBoot MariaDB MyBatis Redis -[timijava](https://github.com/imyeyu/timijava) \ No newline at end of file +[timijava](https://github.com/imyeyu/timijava) + +### GAO 客户画像 PDF + +`POST /gao/customer/profile/pdf?id={客户ID}` 返回 `application/pdf`,响应按浏览器内预览处理。调用者需要独立的 `CUSTOMER_PROFILE:READ` 权限,且客户必须在其门店数据范围内;画像读取不再要求分别持有订单、积分或回收物权限。默认不将该权限授予店长或门店管理角色,需要在角色管理中显式授权。 + +统计限定客户所属门店。事件包含已核销及无需核销的记录,排除待核销记录,并沿用既有事件查询对历史消费事件的排除规则;上月和本月按服务端时区的自然月计算。订单排除取消单,金额由分换算为元,净收款为已付款减退款。积分月份按流水发生时间统计获得和消费;回收物按品种和单位分别展示,账户流水中的获得、使用及人工调整与回收支付的当前核销状态分别统计。数量、积分和金额均按每四位分组。 + +PDF 使用 `templates/GaoCustomerProfile.ftl`,单页展示最多 6 种事件、6 项产品、4 种回收物和 3 条跟进提醒;多出的数据不影响总体汇总。长文本会截断,页面空间不足时会缩小字号;若仍无法排入一页,接口返回错误,不生成多页文件。使用首张 `PHOTO` 附件并按比例转为灰度;无图片或图片格式无法解码时使用占位。字体使用服务器上合法安装的宋体 SimSun,默认路径为 `C:/Windows/Fonts/simsun.ttc`。非 Windows 环境或使用其他路径时,设置 `gao.customer-profile.font-path` 指向包含 SimSun 的 TTC 文件;服务不会自动替换字体,字体缺失时接口返回错误。项目不分发该字体文件。 diff --git a/pom.xml b/pom.xml index b026699..326a937 100644 --- a/pom.xml +++ b/pom.xml @@ -180,6 +180,11 @@ + + com.openhtmltopdf + openhtmltopdf-pdfbox + 1.0.10 + org.apache.groovy groovy @@ -246,6 +251,12 @@ + + com.h2database + h2 + 2.3.232 + test + org.mariadb.jdbc mariadb-java-client diff --git a/src/main/java/com/imyeyu/api/modules/common/service/implement/AttachmentServiceImplement.java b/src/main/java/com/imyeyu/api/modules/common/service/implement/AttachmentServiceImplement.java index 590cc02..fbf37c1 100644 --- a/src/main/java/com/imyeyu/api/modules/common/service/implement/AttachmentServiceImplement.java +++ b/src/main/java/com/imyeyu/api/modules/common/service/implement/AttachmentServiceImplement.java @@ -244,6 +244,9 @@ public class AttachmentServiceImplement extends AbstractEntityService customers(@RequestParam(required = false) String storeId, + @RequestParam(defaultValue = "") String keyword, @RequestParam(defaultValue = "0") int offset) { + return mapper.customers(resolveStore(storeId), keyword, checkedOffset(offset)); + } + + private String resolveStore(String storeId) { + String resolved = scope.resolveStoreId(storeId); + TimiException.required(resolved, "请选择门店"); + return resolved; + } + + private int checkedOffset(int offset) { + TimiException.requiredTrue(offset >= 0 && offset <= 1000000, "分页范围无效"); + return offset; + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/mapper/GaoCustomerProfileMapper.java b/src/main/java/com/imyeyu/api/modules/gao/mapper/GaoCustomerProfileMapper.java new file mode 100644 index 0000000..7286a16 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/mapper/GaoCustomerProfileMapper.java @@ -0,0 +1,46 @@ +package com.imyeyu.api.modules.gao.mapper; + +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/// 客户画像的门店内聚合查询。时间区间均为左闭右开。 +public interface GaoCustomerProfileMapper { + List> events( + @Param("store") String store, + @Param("customer") String customer, + @Param("lastStart") long lastStart, + @Param("monthStart") long monthStart, + @Param("end") long end); + + Map orders(@Param("store") String store, @Param("customer") String customer); + + List> products( + @Param("store") String store, @Param("customer") String customer); + + Map points( + @Param("store") String store, + @Param("customer") String customer, + @Param("lastStart") long lastStart, + @Param("monthStart") long monthStart, + @Param("end") long end); + + List> reminders( + @Param("store") String store, @Param("customer") String customer); + + Map redemptions( + @Param("store") String store, @Param("customer") String customer); + + List> recycleTotals( + @Param("store") String store, @Param("customer") String customer); + + List> recyclePayments( + @Param("store") String store, @Param("customer") String customer); + + long recycleExchanges(@Param("store") String store, @Param("customer") String customer); + long productCount(@Param("store") String store, @Param("customer") String customer); + long reminderCount(@Param("store") String store, @Param("customer") String customer); + Map latestOrder(@Param("store") String store, @Param("customer") String customer); + List> latestEvents(@Param("store") String store, @Param("customer") String customer, @Param("end") long end); +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/mapper/GaoEventMonthExportMapper.java b/src/main/java/com/imyeyu/api/modules/gao/mapper/GaoEventMonthExportMapper.java new file mode 100644 index 0000000..ca139e2 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/mapper/GaoEventMonthExportMapper.java @@ -0,0 +1,10 @@ +package com.imyeyu.api.modules.gao.mapper; + +import com.imyeyu.api.modules.gao.vo.event.GaoEventMonthRecord; +import org.apache.ibatis.annotations.Param; +import java.util.List; + +public interface GaoEventMonthExportMapper { + List list(@Param("store") String store, @Param("event") String event, + @Param("begin") int begin, @Param("end") int end); +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/mapper/GaoReportOptionMapper.java b/src/main/java/com/imyeyu/api/modules/gao/mapper/GaoReportOptionMapper.java new file mode 100644 index 0000000..f2f3c4f --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/mapper/GaoReportOptionMapper.java @@ -0,0 +1,9 @@ +package com.imyeyu.api.modules.gao.mapper; + +import com.imyeyu.api.modules.gao.vo.report.GaoReportOption; +import org.apache.ibatis.annotations.Param; +import java.util.List; + +public interface GaoReportOptionMapper { + List customers(@Param("store") String store, @Param("keyword") String keyword, @Param("offset") int offset); +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/service/GaoCustomerProfileService.java b/src/main/java/com/imyeyu/api/modules/gao/service/GaoCustomerProfileService.java new file mode 100644 index 0000000..aca8574 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/service/GaoCustomerProfileService.java @@ -0,0 +1,426 @@ +package com.imyeyu.api.modules.gao.service; + +import com.imyeyu.api.config.dbsource.TimiServerDBConfig; +import com.imyeyu.api.modules.common.entity.Attachment; +import com.imyeyu.api.modules.common.entity.TagApply; +import com.imyeyu.api.modules.common.service.AttachmentService; +import com.imyeyu.api.modules.common.service.TagService; +import com.imyeyu.api.modules.gao.entity.GaoCustomer; +import com.imyeyu.api.modules.gao.entity.GaoPointAccount; +import com.imyeyu.api.modules.gao.entity.GaoStore; +import com.imyeyu.api.modules.gao.mapper.GaoCustomerProfileMapper; +import com.imyeyu.api.modules.gao.mapper.GaoRecycleAccountMapper; +import com.imyeyu.api.modules.gao.util.GaoProfileNumberFormatter; +import com.imyeyu.api.modules.gao.util.GaoBodyArea; +import com.imyeyu.api.modules.gao.util.LunarDate; +import com.imyeyu.api.modules.user.service.UserLoginService; +import com.imyeyu.api.modules.user.service.UserService; +import com.imyeyu.api.util.MultilingualFieldBinder; +import com.imyeyu.java.bean.timi.TimiException; +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import com.openhtmltopdf.pdfboxout.PDFontSupplier; +import com.openhtmltopdf.outputdevice.helper.BaseRendererBuilder; +import org.apache.fontbox.ttf.TrueTypeCollection; +import org.springframework.beans.factory.annotation.Value; + +import freemarker.template.Configuration; +import freemarker.template.utility.DeepUnwrap; + +import lombok.RequiredArgsConstructor; + +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDPageContentStream; +import org.apache.pdfbox.pdmodel.font.PDType0Font; +import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState; +import org.apache.pdfbox.util.Matrix; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +@Service +@RequiredArgsConstructor +public class GaoCustomerProfileService { + private final GaoCustomerService customers; + private final GaoStoreService stores; + private final GaoStoreScopeService scope; + private final GaoPointAccountService points; + private final GaoRecycleAccountMapper recycle; + private final GaoCustomerProfileMapper mapper; + private final AttachmentService attachments; + private final TagService tags; + private final MultilingualFieldBinder multilingual; + private final UserService users; + private final UserLoginService login; + private final Configuration freemarker; + + @Value("${gao.customer-profile.font-path:C:/Windows/Fonts/simsun.ttc}") + private String fontPath = "C:/Windows/Fonts/simsun.ttc"; + private static final ZoneId ZONE = ZoneId.systemDefault(); + private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + + @Transactional(value = TimiServerDBConfig.ROLLBACKER, readOnly = true) + public byte[] generate(String id) throws Exception { + GaoCustomer c = customers.get(id); + TimiException.required(c, "客户不存在"); + scope.checkStoreId(c.getStoreId()); + String storeId = c.getStoreId(); + GaoStore store = stores.get(storeId); + long now = System.currentTimeMillis(); + LocalDate today = Instant.ofEpochMilli(now).atZone(ZONE).toLocalDate(); + long month = today.withDayOfMonth(1).atStartOfDay(ZONE).toInstant().toEpochMilli(); + long last = + today.withDayOfMonth(1) + .minusMonths(1) + .atStartOfDay(ZONE) + .toInstant() + .toEpochMilli(); + Map model = new HashMap<>(); + model.put("store", store == null ? "门店" : store.getName()); + model.put("generated", now); + model.put("operator", displayName(login.getRequireLoginUser())); + model.put("name", c.getName()); + model.put("code", c.getCode()); + model.put("gender", gender(c)); + model.put("age", c.getAge()); + model.put("birthdate", formatBirthday(c.getBirthdate(), c.getBirthdateCalendar())); + model.put("telephone", c.getTelephone()); + model.put("created", c.getCreatedAt()); + model.put("address", c.getAddress()); + model.put("disease", c.getDisease()); + model.put("conditioning", GaoBodyArea.format(c.getConditioningPart())); + model.put("remark", c.getRemark()); + model.put("invited", c.getInvitedCount()); + var creator = c.getCreatorUserId() == null ? null : users.get(c.getCreatorUserId()); + model.put("creator", displayName(creator)); + var tagList = tags.listByBizType(TagApply.BizType.GAO_CUSTOMER, id); + multilingual.bind(tagList); + model.put("tags", tagList == null ? List.of() : tagList.stream() + .filter(t -> storeId.equals(t.getOwnerId())) + .map(t -> t.getName() != null ? t.getName() : t.getZhCN()) + .filter(Objects::nonNull).toList()); + GaoCustomer introducer = c.getIntroducerCustomerId() == null + ? null : customers.get(c.getIntroducerCustomerId()); + model.put("introducer", introducer == null || !storeId.equals(introducer.getStoreId()) + ? null : introducer.getName()); + model.put("photo", photo(c.getId())); + // SQL 负责数据范围与聚合;模板负责展示格式、列表裁剪和文案。 + var events = mapper.events(storeId, id, last, month, now + 1); + long total = 0, previous = 0, current = 0; + Long firstEvent = null, lastEvent = null; + for (var event : events) { + Long first = number(event, "firstAt"), latest = number(event, "lastAt"); + if (first != null && (firstEvent == null || first < firstEvent)) firstEvent = first; + if (latest != null && (lastEvent == null || latest > lastEvent)) lastEvent = latest; + total += longValue(event, "total"); + previous += longValue(event, "lastMonth"); + current += longValue(event, "thisMonth"); + } + model.put("events", canonicalRows(events)); + model.put("recentEvents", canonicalRows(mapper.latestEvents(storeId, id, now + 1))); + model.put("eventTotal", total); + model.put("eventMonth", current); + model.put("eventPrevious", previous); + model.put("eventFirst", firstEvent); + model.put("eventLast", lastEvent); + model.put("monthStart", today.withDayOfMonth(1).toString()); + model.put("lastStart", today.minusMonths(1).withDayOfMonth(1).toString()); + model.put("lastEnd", today.withDayOfMonth(1).minusDays(1).toString()); + + model.put("order", canonical(mapper.orders(storeId, id))); + model.put("products", canonicalRows(mapper.products(storeId, id))); + model.put("productCount", mapper.productCount(storeId, id)); + model.put("latestOrder", canonical(mapper.latestOrder(storeId, id))); + GaoPointAccount account = points.getByCustomerId(storeId, id); + model.put("pointAccount", account == null ? Map.of() : account); + model.put("pointStats", canonical(mapper.points(storeId, id, last, month, now + 1))); + model.put("redemptions", canonical(mapper.redemptions(storeId, id))); + + var totals = mapper.recycleTotals(storeId, id); + var payments = mapper.recyclePayments(storeId, id); + var accounts = recycle.listAccounts(storeId, id); + var recycles = new ArrayList>(); + for (var item : accounts) { + var totalsForItem = totals.stream() + .filter(x -> Objects.equals(get(x, "itemId"), item.getRecycleItemId())) + .findFirst().orElse(Map.of()); + var paymentsForItem = payments.stream() + .filter(x -> Objects.equals(get(x, "itemId"), item.getRecycleItemId())) + .findFirst().orElse(Map.of()); + Map row = new HashMap<>(); + row.put("account", item); + row.put("totals", canonical(totalsForItem)); + row.put("payments", canonical(paymentsForItem)); + recycles.add(row); + } + model.put("recycles", recycles); + model.put("recycleExchanges", mapper.recycleExchanges(storeId, id)); + model.put("reminders", canonicalRows(mapper.reminders(storeId, id))); + model.put("reminderCount", mapper.reminderCount(storeId, id)); + model.put("fmtNumber", (freemarker.template.TemplateMethodModelEx) args -> + GaoProfileNumberFormatter.format(new BigDecimal(unwrap(args, 0).toString()))); + model.put("fmtMoney", (freemarker.template.TemplateMethodModelEx) args -> + "¥ " + GaoProfileNumberFormatter.format(new BigDecimal(unwrap(args, 0).toString()).movePointLeft(2).setScale(2))); + model.put("fmtDay", (freemarker.template.TemplateMethodModelEx) args -> + date(((Number) unwrap(args, 0)).longValue(), false)); + model.put("fmtTime", (freemarker.template.TemplateMethodModelEx) args -> + date(((Number) unwrap(args, 0)).longValue(), true)); + model.put("fmtText", (freemarker.template.TemplateMethodModelEx) args -> + cut(unwrap(args, 0), ((Number) unwrap(args, 1)).intValue())); + String html = + FreeMarkerTemplateUtils.processTemplateIntoString( + freemarker.getTemplate("GaoCustomerProfile.ftl"), model); + if (!java.nio.file.Files.isRegularFile(java.nio.file.Path.of(fontPath))) { + throw new IllegalStateException("未找到 SimSun 字体文件,请设置 gao.customer-profile.font-path"); + } + ByteArrayOutputStream raw = null; + for (int attempt = 0; attempt < 3; attempt++) { + String layout = attempt == 0 ? html : html + .replace("font-size: 8pt", attempt == 1 ? "font-size: 7pt" : "font-size: 6pt") + .replace("line-height:9pt", attempt == 1 ? "line-height:8pt" : "line-height:7pt") + .replace("line-height: 9pt", attempt == 1 ? "line-height: 8pt" : "line-height: 7pt") + .replace("padding:0.72mm", attempt == 1 ? "padding:0.4mm" : "padding:0.2mm") + .replace("padding: 0.72mm", attempt == 1 ? "padding: 0.4mm" : "padding: 0.2mm"); + raw = new ByteArrayOutputStream(); + try (TrueTypeCollection collection = new TrueTypeCollection(new java.io.File(fontPath)); + PDDocument document = new PDDocument()) { + var trueType = collection.getFontByName("SimSun"); + if (trueType == null) throw new IOException("指定字体文件不包含 SimSun: " + fontPath); + var pdfFont = PDType0Font.load(document, trueType, true); + PdfRendererBuilder builder = new PdfRendererBuilder(); + builder.usePDDocument(document); + builder.useFont(new PDFontSupplier(pdfFont), "ProfileFont", 400, BaseRendererBuilder.FontStyle.NORMAL, true); + builder.useFont(new PDFontSupplier(pdfFont), "ProfileFont", 700, BaseRendererBuilder.FontStyle.NORMAL, true); + builder.withHtmlContent(layout, null); + builder.toStream(raw); + builder.run(); + } + try (PDDocument check = PDDocument.load(raw.toByteArray())) { + if (check.getNumberOfPages() == 1) break; + } + } + + try (PDDocument pdf = PDDocument.load(raw.toByteArray()); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + TrueTypeCollection collection = new TrueTypeCollection(new java.io.File(fontPath))) { +// if (pdf.getNumberOfPages() != 1) throw new IllegalStateException("客户画像超过一页,请检查模板布局"); + var trueType = collection.getFontByName("SimSun"); + if (trueType == null) throw new IOException("指定字体文件不包含 SimSun: " + fontPath); + PDType0Font f = PDType0Font.load(pdf, trueType, true); + PDExtendedGraphicsState state = new PDExtendedGraphicsState(); + state.setNonStrokingAlphaConstant(0.10f); + try (PDPageContentStream canvas = + new PDPageContentStream( + pdf, + pdf.getPage(0), + PDPageContentStream.AppendMode.APPEND, + true, + true)) { + canvas.saveGraphicsState(); + canvas.setGraphicsStateParameters(state); + canvas.beginText(); + String firstLine = supported(f, cut(store == null ? "门店" : store.getName(), 200) + + " " + cut(displayName(login.getRequireLoginUser()), 200)); + String secondLine = supported(f, date(now, true)); + float fontSize = Math.min(24f, 460f * 1000f / Math.max(f.getStringWidth(firstLine), f.getStringWidth(secondLine))); + double angle = Math.toRadians(35); + double cosine = Math.cos(angle); + double sine = Math.sin(angle); + float leading = fontSize + 8; + float firstWidth = f.getStringWidth(firstLine) * fontSize / 1000f; + float secondWidth = f.getStringWidth(secondLine) * fontSize / 1000f; + float centerY = (f.getFontDescriptor().getAscent() + f.getFontDescriptor().getDescent()) * fontSize / 2000f - leading / 2; + var page = pdf.getPage(0).getCropBox(); + double centerX = page.getLowerLeftX() + page.getWidth() / 2; + double centerPageY = page.getLowerLeftY() + page.getHeight() / 2; + canvas.setFont(f, fontSize); + canvas.setTextMatrix(Matrix.getRotateInstance(angle, + (float) (centerX - cosine * firstWidth / 2 + sine * centerY), + (float) (centerPageY - sine * firstWidth / 2 - cosine * centerY))); + canvas.showText(firstLine); + canvas.setTextMatrix(Matrix.getRotateInstance(angle, + (float) (centerX - cosine * secondWidth / 2 + sine * (centerY + leading)), + (float) (centerPageY - sine * secondWidth / 2 - cosine * (centerY + leading)))); + canvas.showText(secondLine); + canvas.endText(); + canvas.restoreGraphicsState(); + } + pdf.save(out); + return out.toByteArray(); + } + } + + /// 首张 PHOTO 等比缩放到固定画框;不存在或无法解码时使用占位。 + private String photo(String id) throws IOException { + var list = attachments.listByBizId(Attachment.BizType.GAO_CUSTOMER, id, "PHOTO"); + if (list == null || list.isEmpty()) return ""; + Attachment photo = list.stream() + .min(java.util.Comparator.comparing(Attachment::getCreatedAt, java.util.Comparator.nullsLast(java.util.Comparator.naturalOrder())) + .thenComparing(Attachment::getId, java.util.Comparator.nullsLast(java.util.Comparator.naturalOrder()))) + .orElseThrow(); + InputStream photoInput; + try { + photoInput = attachments.getInputStreamByMongoId(photo.getMongoId()); + } catch (java.util.NoSuchElementException ex) { + return ""; + } + try (InputStream input = photoInput; + javax.imageio.stream.ImageInputStream imageInput = + new javax.imageio.stream.MemoryCacheImageInputStream(input)) { + if (imageInput == null) return ""; + var readers = javax.imageio.ImageIO.getImageReaders(imageInput); + if (!readers.hasNext()) return ""; + var reader = readers.next(); + try { + reader.setInput(imageInput, true, true); + int width = reader.getWidth(0), height = reader.getHeight(0); + if (width <= 0 || height <= 0) return ""; + int sample = Math.max(1, (int) Math.ceil(Math.max(width, height) / 1024.0)); + var params = reader.getDefaultReadParam(); + params.setSourceSubsampling(sample, sample, 0, 0); + var image = reader.read(0, params); + if (image == null) return ""; + var frame = + new java.awt.image.BufferedImage( + 240, 312, java.awt.image.BufferedImage.TYPE_BYTE_GRAY); + var graphics = frame.createGraphics(); + try { + graphics.setColor(java.awt.Color.WHITE); + graphics.fillRect(0, 0, 240, 312); + graphics.setRenderingHint( + java.awt.RenderingHints.KEY_INTERPOLATION, + java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR); + double scale = Math.min(240.0 / image.getWidth(), 312.0 / image.getHeight()); + int w = Math.max(1, (int) Math.round(image.getWidth() * scale)); + int h = Math.max(1, (int) Math.round(image.getHeight() * scale)); + graphics.drawImage(image, (240 - w) / 2, (312 - h) / 2, w, h, null); + } finally { + graphics.dispose(); + } + try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { + javax.imageio.ImageIO.write(frame, "png", output); + return "data:image/png;base64," + + Base64.getEncoder().encodeToString(output.toByteArray()); + } + } finally { + reader.dispose(); + } + } catch (javax.imageio.IIOException ex) { + return ""; + } + } + + private static String supported(PDType0Font font, String s) { + StringBuilder result = new StringBuilder(); + s.codePoints() + .forEach( + cp -> { + String ch = new String(Character.toChars(cp)); + try { + font.encode(ch); + result.append(ch); + } catch (IllegalArgumentException | IOException ex) { + result.append(" "); + } + }); + return result.toString(); + } + + private static String cut(Object value, int max) { + if (value == null) return "—"; + String text = value.toString().replaceAll("[\\r\\n]+", " "); + StringBuilder safe = new StringBuilder(); + text.codePoints() + .filter( + cp -> + cp == 9 + || cp == 10 + || cp == 13 + || (cp >= 32 && cp <= 0xD7FF) + || (cp >= 0xE000 && cp <= 0xFFFD) + || (cp >= 0x10000 && cp <= 0x10FFFF)) + .forEach(safe::appendCodePoint); + int length = safe.codePointCount(0, safe.length()); + return length > max + ? safe.substring(0, safe.offsetByCodePoints(0, max - 1)) + "…" + : safe.toString(); + } + + private static Object get(Map m, String key) { + if (m == null) return null; + for (var e : m.entrySet()) if (e.getKey().equalsIgnoreCase(key)) return e.getValue(); + return null; + } + + private static Long number(Map m, String key) { + Object n = get(m, key); + return n instanceof Number ? ((Number) n).longValue() : null; + } + + private static long longValue(Map m, String key) { + Long n = number(m, key); + return n == null ? 0 : n; + } + + private static Map canonical(Map source) { + Map result = new HashMap<>(); + if (source != null) source.forEach((key, value) -> result.put(key.toLowerCase(java.util.Locale.ROOT), value)); + return result; + } + + private static List> canonicalRows(List> rows) { + return rows == null ? List.of() : rows.stream().map(GaoCustomerProfileService::canonical).toList(); + } + + private static Object unwrap(List args, int index) throws freemarker.template.TemplateModelException { + return DeepUnwrap.unwrap((freemarker.template.TemplateModel) args.get(index)); + } + + /// 客户出生日期统一以公历保存;按客户登记历法展示,保留农历闰月。 + static String formatBirthday(LocalDate birthdate, GaoCustomer.BirthdateCalendar calendar) { + if (birthdate == null) return "—"; + if (calendar == GaoCustomer.BirthdateCalendar.LUNAR) { + var lunar = LunarDate.toLunar(birthdate); + return "农历 " + lunar.getYear() + "年" + lunar.getMonthInChinese() + "月" + + lunar.getDayInChinese() + "(公历 " + birthdate + ")"; + } + return calendar == GaoCustomer.BirthdateCalendar.SOLAR + ? "公历 " + birthdate : birthdate + "(历法未知)"; + } + + + private static String displayName(com.imyeyu.api.modules.user.entity.User user) { + return user == null ? null : user.getNick() != null ? user.getNick() : user.getName(); + } + + private static String gender(GaoCustomer c) { + return c.getGender() == null + ? "—" + : switch (c.getGender().name()) { + case "MALE" -> "男"; + case "FEMALE" -> "女"; + default -> "未知"; + }; + } + + private static String date(Long millis, boolean time) { + return millis == null + ? "—" + : (time ? TIME : DATE).format(Instant.ofEpochMilli(millis).atZone(ZONE)); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/service/GaoEventMonthExportService.java b/src/main/java/com/imyeyu/api/modules/gao/service/GaoEventMonthExportService.java new file mode 100644 index 0000000..7878b0f --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/service/GaoEventMonthExportService.java @@ -0,0 +1,140 @@ +package com.imyeyu.api.modules.gao.service; + +import com.imyeyu.api.config.dbsource.TimiServerDBConfig; +import com.imyeyu.api.modules.gao.entity.GaoStoreBusinessDay; +import com.imyeyu.api.modules.gao.mapper.GaoEventMonthExportMapper; +import com.imyeyu.java.bean.timi.TimiException; +import com.openhtmltopdf.outputdevice.helper.BaseRendererBuilder; +import com.openhtmltopdf.pdfboxout.PDFontSupplier; +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import freemarker.template.Configuration; +import lombok.RequiredArgsConstructor; +import org.apache.fontbox.ttf.TrueTypeCollection; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.font.PDType0Font; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.time.YearMonth; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.IntStream; + +@Service +@RequiredArgsConstructor +public class GaoEventMonthExportService { + private final GaoEventService events; + private final GaoStoreService stores; + private final GaoStoreScopeService scope; + private final GaoStoreBusinessDayService businessDays; + private final GaoEventMonthExportMapper mapper; + private final Configuration freemarker; + + @Value("${gao.customer-profile.font-path:C:/Windows/Fonts/simsun.ttc}") + private String fontPath = "C:/Windows/Fonts/simsun.ttc"; + + @Transactional(value = TimiServerDBConfig.ROLLBACKER, readOnly = true) + public byte[] generate(String eventId, String month) throws Exception { + TimiException.required(eventId, "事件 ID 不能为空"); + TimiException.requiredTrue(month != null && month.matches("[0-9]{4}-(0[1-9]|1[0-2])"), "年月格式应为 yyyy-MM"); + YearMonth yearMonth; + try { + yearMonth = YearMonth.parse(month); + } catch (DateTimeParseException ex) { + throw new IllegalArgumentException("年月格式应为 yyyy-MM", ex); + } + var event = events.get(eventId); + TimiException.required(event, "事件不存在"); + String storeId = event.getStoreId(); + scope.checkStoreId(storeId); + var store = stores.get(storeId); + int monthValue = yearMonth.getYear() * 10000 + yearMonth.getMonthValue() * 100; + int first = monthValue + 1, last = monthValue + yearMonth.lengthOfMonth(); + Set closed = new LinkedHashSet<>(); + for (var day : businessDays.listByDateRange(storeId, first, last)) { + if (day.getStatus() == GaoStoreBusinessDay.Status.CLOSED && day.getDateValue() != null) { + closed.add(day.getDateValue() % 100); + } + } + Map> grouped = new LinkedHashMap<>(); + for (var item : mapper.list(storeId, eventId, first, last)) { + if (item.getCustomerId() == null || item.getDateValue() == null || closed.contains(item.getDateValue() % 100)) continue; + var row = grouped.computeIfAbsent(item.getCustomerId(), key -> { + Map result = new LinkedHashMap<>(); + result.put("name", safe(item.getCustomerName(), "已删除客户", 30)); + result.put("days", new LinkedHashSet()); + return result; + }); + @SuppressWarnings("unchecked") Set days = (Set) row.get("days"); + days.add(item.getDateValue() % 100); + } + List> rows = new ArrayList<>(); + for (var row : grouped.values()) { + row.put("days", new ArrayList<>((Set) row.get("days"))); + row.put("sequence", rows.size() + 1); + rows.add(row); + } + List>> pages = new ArrayList<>(); + List> pageRows = new ArrayList<>(); + int pageUnits = 0; + for (var row : rows) { + String name = (String) row.get("name"); + int units = Math.max(1, (name.codePointCount(0, name.length()) + 9) / 10); + if (!pageRows.isEmpty() && pageUnits + units > 26) { + pages.add(pageRows); + pageRows = new ArrayList<>(); + pageUnits = 0; + } + pageRows.add(row); + pageUnits += units; + } + if (!pageRows.isEmpty()) pages.add(pageRows); + if (pages.isEmpty()) pages.add(List.of()); + Map model = Map.of( + "store", safe(store == null ? null : store.getName(), "门店"), + "event", safe(event.getName(), "未命名事件"), "month", month, + "days", IntStream.rangeClosed(1, yearMonth.lengthOfMonth()).boxed().toList(), + "closed", new ArrayList<>(closed), "pages", pages, "customerCount", rows.size(), "monthNumber", yearMonth.getMonthValue()); + String html = FreeMarkerTemplateUtils.processTemplateIntoString(freemarker.getTemplate("GaoEventMonthExport.ftl"), model); + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); + TrueTypeCollection collection = new TrueTypeCollection(new java.io.File(fontPath)); + PDDocument document = new PDDocument()) { + var trueType = collection.getFontByName("SimSun"); + if (trueType == null) throw new IOException("指定字体文件不包含 SimSun: " + fontPath); + var font = PDType0Font.load(document, trueType, true); + var builder = new PdfRendererBuilder(); + builder.usePDDocument(document); + builder.useFont(new PDFontSupplier(font), "ProfileFont", 400, BaseRendererBuilder.FontStyle.NORMAL, true); + builder.useFont(new PDFontSupplier(font), "ProfileFont", 700, BaseRendererBuilder.FontStyle.NORMAL, true); + builder.withHtmlContent(html, null); + builder.toStream(out); + builder.run(); + return out.toByteArray(); + } + } + + private static String safe(String value, String fallback) { + return safe(value, fallback, 100); + } + + private static String safe(String value, String fallback, int max) { + if (value == null || value.isBlank()) return fallback; + StringBuilder result = new StringBuilder(); + value.codePoints().filter(cp -> (cp >= 32 && cp <= 0xD7FF) || (cp >= 0xE000 && cp <= 0xFFFD) + || (cp >= 0x10000 && cp <= 0x10FFFF)).limit(max + 1L).forEach(result::appendCodePoint); + if (result.codePointCount(0, result.length()) > max) { + result.setLength(result.offsetByCodePoints(0, max - 1)); + result.append("…"); + } + return result.toString(); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/service/implement/GaoCustomerServiceImplement.java b/src/main/java/com/imyeyu/api/modules/gao/service/implement/GaoCustomerServiceImplement.java index a3659e8..ca5ae78 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/service/implement/GaoCustomerServiceImplement.java +++ b/src/main/java/com/imyeyu/api/modules/gao/service/implement/GaoCustomerServiceImplement.java @@ -167,6 +167,7 @@ public class GaoCustomerServiceImplement extends AbstractEntityService LABELS = Map.ofEntries( + Map.entry("head", "头部"), Map.entry("neck", "颈部"), + Map.entry("left-shoulder", "右肩"), Map.entry("right-shoulder", "左肩"), + Map.entry("left-upper-arm", "右上臂"), Map.entry("right-upper-arm", "左上臂"), + Map.entry("left-forearm", "右前臂"), Map.entry("right-forearm", "左前臂"), + Map.entry("left-hand", "右手"), Map.entry("right-hand", "左手"), + Map.entry("left-chest", "右胸"), Map.entry("right-chest", "左胸"), + Map.entry("left-abdomen", "右腹"), Map.entry("right-abdomen", "左腹"), + Map.entry("left-waist", "右腰"), Map.entry("right-waist", "左腰"), + Map.entry("left-thigh", "右大腿"), Map.entry("right-thigh", "左大腿"), + Map.entry("left-knee", "右膝"), Map.entry("right-knee", "左膝"), + Map.entry("left-calf", "右小腿"), Map.entry("right-calf", "左小腿"), + Map.entry("left-foot", "右脚"), Map.entry("right-foot", "左脚") + ); + + private GaoBodyArea() { + } + + /// 空列表显示未选择;未知代码保留原值,与前端行为一致。 + public static String format(JsonNode value) { + if (value == null || value.isNull()) return "未选择"; + JsonNode codes = value.isObject() ? value.path("selectedCodeList") : value; + if (codes.isTextual()) { + String code = codes.asText().trim(); + return code.isEmpty() ? "未选择" : LABELS.getOrDefault(code, code); + } + if (!codes.isArray()) return "未选择"; + List labels = new ArrayList<>(); + for (JsonNode codeNode : codes) { + if (!codeNode.isTextual()) continue; + String code = codeNode.asText().trim(); + if (!code.isEmpty()) labels.add(LABELS.getOrDefault(code, code)); + } + return labels.isEmpty() ? "未选择" : String.join("、", labels); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/util/GaoProfileNumberFormatter.java b/src/main/java/com/imyeyu/api/modules/gao/util/GaoProfileNumberFormatter.java new file mode 100644 index 0000000..c97688d --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/util/GaoProfileNumberFormatter.java @@ -0,0 +1,36 @@ +package com.imyeyu.api.modules.gao.util; + +import java.math.BigDecimal; + +/// 客户画像数值按万位分组,不改变小数精度。 +public final class GaoProfileNumberFormatter { + + private GaoProfileNumberFormatter() {} + + public static String format(BigDecimal value) { + if (value == null) { + return "—"; + } + String plain = value.toPlainString(); + int decimal = plain.indexOf('.'); + String integer = decimal < 0 ? plain : plain.substring(0, decimal); + String fraction = decimal < 0 ? "" : plain.substring(decimal); + boolean negative = integer.startsWith("-"); + String digits = negative ? integer.substring(1) : integer; + StringBuilder result = new StringBuilder(digits.length() + digits.length() / 4 + 1); + if (negative) { + result.append('-'); + } + for (int i = 0; i < digits.length(); i++) { + if (i > 0 && (digits.length() - i) % 4 == 0) { + result.append(','); + } + result.append(digits.charAt(i)); + } + return result.append(fraction).toString(); + } + + public static String format(Long value) { + return format(value == null ? null : BigDecimal.valueOf(value)); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/vo/event/GaoEventMonthRecord.java b/src/main/java/com/imyeyu/api/modules/gao/vo/event/GaoEventMonthRecord.java new file mode 100644 index 0000000..e1ea814 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/vo/event/GaoEventMonthRecord.java @@ -0,0 +1,11 @@ +package com.imyeyu.api.modules.gao.vo.event; + +import lombok.Data; + +/// 月登记表的一名客户在某一天的登记记录。 +@Data +public class GaoEventMonthRecord { + private String customerId; + private String customerName; + private Integer dateValue; +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/vo/report/GaoReportOption.java b/src/main/java/com/imyeyu/api/modules/gao/vo/report/GaoReportOption.java new file mode 100644 index 0000000..617bdba --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/vo/report/GaoReportOption.java @@ -0,0 +1,11 @@ +package com.imyeyu.api.modules.gao.vo.report; + +import lombok.Data; + +/// 报表配置时使用的最小选择项。 +@Data +public class GaoReportOption { + private String id; + private String name; + private String code; +} diff --git a/src/main/resources/mapper/timi-server/gao/GaoCustomerProfileMapper.xml b/src/main/resources/mapper/timi-server/gao/GaoCustomerProfileMapper.xml new file mode 100644 index 0000000..1c819af --- /dev/null +++ b/src/main/resources/mapper/timi-server/gao/GaoCustomerProfileMapper.xml @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/mapper/timi-server/gao/GaoEventMonthExportMapper.xml b/src/main/resources/mapper/timi-server/gao/GaoEventMonthExportMapper.xml new file mode 100644 index 0000000..ec60b83 --- /dev/null +++ b/src/main/resources/mapper/timi-server/gao/GaoEventMonthExportMapper.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/src/main/resources/mapper/timi-server/gao/GaoReportOptionMapper.xml b/src/main/resources/mapper/timi-server/gao/GaoReportOptionMapper.xml new file mode 100644 index 0000000..15d529a --- /dev/null +++ b/src/main/resources/mapper/timi-server/gao/GaoReportOptionMapper.xml @@ -0,0 +1,10 @@ + + + + + diff --git a/src/main/resources/templates/GaoCustomerProfile.ftl b/src/main/resources/templates/GaoCustomerProfile.ftl new file mode 100644 index 0000000..8b2af7e --- /dev/null +++ b/src/main/resources/templates/GaoCustomerProfile.ftl @@ -0,0 +1,396 @@ +<#ftl output_format="HTML" auto_esc=true> +<#function n value=0><#return fmtNumber(value)> +<#function money value=0><#return fmtMoney(value)> +<#function day value=0><#if value == 0><#return ""><#else><#return fmtDay(value)> +<#function time value=0><#if value == 0><#return ""><#else><#return fmtTime(value)> +<#function label value max=36><#return fmtText(value, max)> +<#assign productTypes={"DIRECT_PRODUCT":"商品", "PACKAGE_ENTITLEMENT":"套餐权益", "RECYCLE_ENTITLEMENT":"回收兑换"}> +<#assign orderStatuses={"ACTIVE":"进行中", "FULFILLED":"已履约"}> +<#assign paymentStatuses={"UNPAID":"未付款", "PARTIALLY_PAID":"部分付款", "PAID":"已付清"}> +<#assign reminderStatuses={"PENDING":"待完成", "COMPLETED":"已完成"}> + + + + + + + +

客户画像档案(内部资料)

+ + + + + + + + + +
${label(store!"", 90)}CUSTOMER PROFILE / 客户经营档案
糕店客户管理系统 / 技术支持:夜雨档案编号:${label(code!"", 24)}
+
客户资料及统计仅限当前门店,数据截至档案生成时。
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <#list 0..5 as i> + <#if i lt events?size><#assign e=events[i]> + + + + <#else> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <#macro productCells index><#if index lt products?size><#local p=products[index]> + <#local productName=label(p.name!"", 36)> + <#if (p.skucount!0) gt 1> + <#local sku=p.specsummary!""> + <#if !sku?has_content><#local sku=p.skuname!""> + <#if !sku?has_content || sku == productName><#local sku=p.skucode!""> + <#if sku?has_content><#local productName=productName + "(" + sku + ")"> + + + + <#else> + + + + <#list 0..4 as i> + <@productCells index=i*2/><@productCells index=i*2+1/> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <#list 0..3 as i> + <#if i lt recycles?size><#assign r=recycles[i]> + + + + + + + <#else> + + + + + + + + + + + + + + + + + +
一、客户基本资料
客户姓名${label(name!"", 12)}客户编号${label(code!"", 24)}性别${gender}<#if photo?has_content><#else>客户照片
PHOTO +
暂无照片
出生日期${birthdate}年龄<#if age??>${n(age)}<#else>
所属门店${label(store!"", 90)}联系电话${label(telephone!"", 24)}
建档人${label(creator!"", 12)}介绍人${label(introducer!"", 12)}邀请客户<#if invited??>${n(invited)}<#else> 人
客户标签<#if tags?has_content><#assign tagText=tags[0..*8]?join("、")><#if tags?size gt 8><#assign tagText=tagText + "…">${label(tagText, 70)}<#else>建档日期${day(created!0)}
联系地址${label(address!"", 45)}
健康情况${label(disease!"", 160)}
调理部位${label(conditioning!"", 160)}
客户备注${label(remark!"", 70)}
二、客户登记事件统计(已核验及无需核验)
累计次数${n(eventTotal)} 次事件种类${n(events?size)} 种首次登记${day(eventFirst!0)}最近登记${day(eventLast!0)}
本月登记${n(eventMonth)} 次上月登记${n(eventPrevious)} 次
登记事件累计上个月本月
${label(e.name!"", 24)}${n(e.total!0)} 次${n(e.lastmonth!0)} 次${n(e.thismonth!0)} 次    
最近登记<#if recentEvents?has_content><#list recentEvents as e>${day(e.registeredat!0)}(${label(e.name!"", 13)})<#sep>,<#else><#if events?size gt 6> | 另有 ${n(events?size - 6)} 种事件未列出
三、订单及产品统计(排除已取消订单)
有效订单${n(order.count!0)} 笔销售金额${money(order.sale!0)}已付款${money(order.paid!0)}待付款${money(order.unpaid!0)}
退款金额${money(order.refunded!0)}净收款${money((order.paid!0) - (order.refunded!0))}首次购买${day(order.firstat!0)}最近购买${day(order.lastat!0)}
产品订单${n(order.directcount!0)} 笔 / 成交 ${money(order.directsale!0)}套餐订单${n(order.packagecount!0)} 笔 / 成交 ${money(order.packagesale!0)}
回收订单${n(order.recyclecount!0)} 笔最近订单<#if latestOrder?has_content>${label(latestOrder.orderno!"")}<#else>
产品(按数量排序)单位数量产品(续)单位数量
${label(productName, 24)}${label(p.unit!"", 8)}${n(p.quantity!0)}   
<#if productCount gt 10>仅列前 10 项,另有 ${n(productCount - 10)} 项未列出<#else>产品按购买数量排序 + ;净收款 = 已付款 - 退款。订单状态:进行中 ${n(order.active!0)} / 已履约 ${n(order.fulfilled!0)}
四、积分统计
当前余额${n(pointAccount.balance!0)}累计获得${n(pointAccount.totalEarned!0)}累计消费${n(pointAccount.totalConsumed!0)}累计撤销${n(pointAccount.totalRevoked!0)}
累计调整${n(pointAccount.totalAdjusted!0)}积分兑换${n(redemptions.count!0)} 次 / 消耗 ${n(redemptions.spent!0)} / + 退回 ${n(redemptions.returned!0)}
本月积分获得 ${n(pointStats.thisearned!0)} / 消费 ${n(pointStats.thisconsumed!0)}上月积分获得 ${n(pointStats.lastearned!0)} / 消费 ${n(pointStats.lastconsumed!0)}
主要来源事件 ${n(pointStats.eventearned!0)} / 订单 ${n(pointStats.orderearned!0)}最近变动${day(pointStats.lastat!0)}
五、回收物统计(各品种分别统计)
品种及单位当前余额已预留获得 冲回核销 退回累计调整最近变动
${label(r.account.recycleName!"", 8)}(${label(r.account.recycleUnit!"", 4)})${n(r.account.balance!0)}${n(r.account.reserved!0)}${n(r.totals.earned!0)} / ${n(r.totals.revoked!0)}${n(r.totals.used!0)} / ${n(r.totals.returned!0)}${n(r.totals.adjusted!0)}${day(r.account.updatedAt!0)}       
兑换情况兑换 ${n(recycleExchanges)} + 次;不同品种分别统计<#if recycles?size gt 4>;另有 ${n(recycles?size - 4)} 个品种未列出<#list recycles as r><#if r?index lt 4> | ${label(r.account.recycleName!"", 8)}:已核 ${n(r.payments.verified!0)} / 待核 ${n(r.payments.pending!0)}
隐私与保密提示
本档案包含客户个人资料、联系方式及健康相关信息,仅供授权人员在业务范围内使用。请妥善保管,勿向无关人员传播。打印或下载后请按门店保密要求处理,丢弃前请彻底销毁。
本页为统计摘要,部分明细可能因版面限制省略;统计结果以系统实际记录及业务口径为准。 +
+ + + + + +
制单人:${label(operator!"", 12)}  所属门店:${label(store!"", 90)}生成时间:${time(generated)}
+ + diff --git a/src/main/resources/templates/GaoEventMonthExport.ftl b/src/main/resources/templates/GaoEventMonthExport.ftl new file mode 100644 index 0000000..c77fb7c --- /dev/null +++ b/src/main/resources/templates/GaoEventMonthExport.ftl @@ -0,0 +1,120 @@ +<#ftl output_format="HTML" auto_esc=true> + + + + + + + +<#list pages as rows> + class="page-break"> +

${monthNumber?c} 月登记记录表

+
+ 第 ${(rows?index + 1)?c} / ${pages?size?c} 页 + 门店:${store} + 事件:${event} + 月份:${month} + 客户数:${customerCount?c} + 平台:糕店客户管理系统 + 技术支持:夜雨 + 灰色列为休息日 +
+ + + + + <#list days as day> + class="closed">${day?c} + + + <#list rows as row> + + + <#list days as day> + class="closed"><#if !closed?seq_contains(day) && row.days?seq_contains(day)>√<#else>  + + <#else> + + + +
序号客户
${row.sequence?c}${row.name}
本月暂无登记记录
+ + + + diff --git a/src/test/java/com/imyeyu/api/modules/gao/service/GaoCustomerProfilePhotoTest.java b/src/test/java/com/imyeyu/api/modules/gao/service/GaoCustomerProfilePhotoTest.java new file mode 100644 index 0000000..177deef --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/gao/service/GaoCustomerProfilePhotoTest.java @@ -0,0 +1,38 @@ +package com.imyeyu.api.modules.gao.service; + +import com.imyeyu.api.modules.common.entity.Attachment; +import com.imyeyu.api.modules.common.service.AttachmentService; +import com.imyeyu.api.modules.common.service.implement.AttachmentServiceImplement; +import com.mongodb.client.gridfs.GridFSBucket; +import org.junit.jupiter.api.Test; +import org.springframework.data.mongodb.gridfs.GridFsTemplate; + +import java.util.List; +import java.util.NoSuchElementException; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +class GaoCustomerProfilePhotoTest { + @Test + void missingGridFsFileUsesPhotoPlaceholder() throws Exception { + var gridFs = mock(GridFsTemplate.class); + var bucket = mock(GridFSBucket.class); + var storage = new AttachmentServiceImplement(null, null, bucket, gridFs, null); + assertThrows(NoSuchElementException.class, () -> storage.getInputStreamByMongoId("missing")); + verifyNoInteractions(bucket); + + var attachments = mock(AttachmentService.class); + var photo = new Attachment(); + photo.setMongoId("missing"); + when(attachments.listByBizId(eq(Attachment.BizType.GAO_CUSTOMER), eq("customer"), any(String[].class))) + .thenReturn(List.of(photo)); + when(attachments.getInputStreamByMongoId("missing")) + .thenAnswer(invocation -> storage.getInputStreamByMongoId("missing")); + var service = new GaoCustomerProfileService(null, null, null, null, null, null, attachments, null, null, null, null, null); + var method = GaoCustomerProfileService.class.getDeclaredMethod("photo", String.class); + method.setAccessible(true); + assertEquals("", method.invoke(service, "customer")); + } +} diff --git a/src/test/java/com/imyeyu/api/modules/gao/service/GaoEventMonthExportTest.java b/src/test/java/com/imyeyu/api/modules/gao/service/GaoEventMonthExportTest.java new file mode 100644 index 0000000..84cf86f --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/gao/service/GaoEventMonthExportTest.java @@ -0,0 +1,105 @@ +package com.imyeyu.api.modules.gao.service; + +import com.imyeyu.api.modules.gao.entity.GaoEvent; +import com.imyeyu.api.modules.gao.entity.GaoStore; +import com.imyeyu.api.modules.gao.entity.GaoStoreBusinessDay; +import com.imyeyu.api.modules.gao.mapper.GaoEventMonthExportMapper; +import com.imyeyu.api.modules.gao.vo.event.GaoEventMonthRecord; +import freemarker.template.Configuration; +import org.apache.ibatis.builder.xml.XMLMapperBuilder; +import org.apache.ibatis.datasource.unpooled.UnpooledDataSource; +import org.apache.ibatis.mapping.Environment; +import org.apache.ibatis.session.SqlSessionFactoryBuilder; +import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.text.PDFTextStripper; +import org.junit.jupiter.api.Test; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class GaoEventMonthExportTest { + @Test + void queryIncludesRegistrationsOncePerCustomerAndDayWithinStoreAndEvent() throws Exception { + var ds = new UnpooledDataSource("org.h2.Driver", "jdbc:h2:mem:eventmonth;MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1", "sa", ""); + try (var c = ds.getConnection(); var s = c.createStatement()) { + s.execute("CREATE TABLE gao_customer(id VARCHAR, store_id VARCHAR, name VARCHAR, code VARCHAR)"); + s.execute("CREATE TABLE gao_event_record(customer_id VARCHAR, store_id VARCHAR, event_id VARCHAR, deleted_at BIGINT, registered_date_value INT, verification_status VARCHAR)"); + s.execute("INSERT INTO gao_customer VALUES ('c','s','客户','KH1')"); + s.execute("INSERT INTO gao_event_record VALUES ('c','s','e',NULL,20240204,'PENDING'),('c','s','e',NULL,20240204,'VERIFIED'),('c','s','e',NULL,20240229,'NOT_REQUIRED'),('c','s','other',NULL,20240205,'VERIFIED'),('c','other','e',NULL,20240206,'VERIFIED'),('c','s','e',1,20240207,'VERIFIED'),('c','s','e',NULL,20240301,'VERIFIED')"); + } + var config = new org.apache.ibatis.session.Configuration(new Environment("test", new JdbcTransactionFactory(), ds)); + String xml = "mapper/timi-server/gao/GaoEventMonthExportMapper.xml"; + try (var in = getClass().getClassLoader().getResourceAsStream(xml)) { + new XMLMapperBuilder(in, config, xml, config.getSqlFragments()).parse(); + } + try (var session = new SqlSessionFactoryBuilder().build(config).openSession()) { + var rows = session.getMapper(GaoEventMonthExportMapper.class).list("s", "e", 20240201, 20240229); + assertEquals(2, rows.size()); + assertEquals("客户", rows.getFirst().getCustomerName()); + assertEquals(20240204, rows.getFirst().getDateValue()); + assertEquals(20240229, rows.getLast().getDateValue()); + } + } + + @Test + void rendersLandscapeLeapMonthWithAllCustomersAndRepeatedHeaders() throws Exception { + String fontPath = System.getProperty("gao.customer-profile.font-path", "C:/Windows/Fonts/simsun.ttc"); + org.junit.jupiter.api.Assumptions.assumeTrue(Files.isRegularFile(Path.of(fontPath))); + var events = mock(GaoEventService.class); + var stores = mock(GaoStoreService.class); + var scope = mock(GaoStoreScopeService.class); + var businessDays = mock(GaoStoreBusinessDayService.class); + var mapper = mock(GaoEventMonthExportMapper.class); + var event = new GaoEvent(); event.setId("e"); event.setStoreId("s"); event.setName("到店登记"); + var store = new GaoStore(); store.setName("测试门店"); + when(events.get("e")).thenReturn(event); + when(stores.get("s")).thenReturn(store); + var rest = new GaoStoreBusinessDay(); rest.setStatus(GaoStoreBusinessDay.Status.CLOSED); rest.setDateValue(20240204); + when(businessDays.listByDateRange("s", 20240201, 20240229)).thenReturn(List.of(rest)); + var records = new ArrayList(); + for (int i = 0; i < 80; i++) { + var record = new GaoEventMonthRecord(); record.setCustomerId("c" + i); record.setCustomerName("客户" + i); record.setDateValue(20240205); records.add(record); + } + var repeat = new GaoEventMonthRecord(); repeat.setCustomerId("c0"); repeat.setCustomerName("客户0"); repeat.setDateValue(20240229); records.add(repeat); + var closedOnly = new GaoEventMonthRecord(); closedOnly.setCustomerId("closed"); closedOnly.setCustomerName("休息日客户"); closedOnly.setDateValue(20240204); records.add(closedOnly); + var longName = new GaoEventMonthRecord(); longName.setCustomerId("long"); longName.setCustomerName("长名字".repeat(10)); longName.setDateValue(20240205); records.add(longName); + when(mapper.list("s", "e", 20240201, 20240229)).thenReturn(records); + var cfg = new Configuration(Configuration.VERSION_2_3_33); cfg.setClassLoaderForTemplateLoading(getClass().getClassLoader(), "templates"); cfg.setDefaultEncoding("UTF-8"); + var service = new GaoEventMonthExportService(events, stores, scope, businessDays, mapper, cfg); + org.springframework.test.util.ReflectionTestUtils.setField(service, "fontPath", fontPath); + byte[] bytes = service.generate("e", "2024-02"); + if (System.getProperty("gao.event.month.preview") != null) Files.write(Path.of(System.getProperty("gao.event.month.preview")), bytes); + verify(scope).checkStoreId("s"); + try (var pdf = PDDocument.load(bytes)) { + assertTrue(pdf.getNumberOfPages() > 1); + for (var page : pdf.getPages()) assertTrue(page.getMediaBox().getWidth() > page.getMediaBox().getHeight()); + for (int page = 1; page <= pdf.getNumberOfPages(); page++) { + var stripper = new PDFTextStripper(); stripper.setStartPage(page); stripper.setEndPage(page); + String pageText = stripper.getText(pdf); + assertTrue(pageText.contains("2024-02") && pageText.contains("29"), "each page needs the month and date header"); + String normalizedPage = pageText.replaceAll("\\s+", ""); + assertTrue(normalizedPage.contains("第" + page + "/" + pdf.getNumberOfPages() + "页"), "page number must match the physical page"); + if (page == 1) { + assertTrue(pageText.contains("客户25"), "fill the first page with 26 customers"); + assertFalse(pageText.contains("客户26"), "the next customer starts the next page"); + } + } + String text = new PDFTextStripper().getText(pdf); + assertTrue(text.contains("客户79")); + assertFalse(text.contains("休息日客户")); + assertFalse(text.contains("KH0")); + assertTrue(text.contains("√")); + assertTrue(text.contains("2 月登记记录表")); + assertTrue(text.contains("29")); + assertTrue(text.contains("灰色列为休息日")); + assertTrue(text.split("客户", -1).length > 80); + } + assertThrows(Exception.class, () -> service.generate("e", "2024-13")); + } +} diff --git a/src/test/java/com/imyeyu/api/modules/gao/service/GaoReportOptionTest.java b/src/test/java/com/imyeyu/api/modules/gao/service/GaoReportOptionTest.java new file mode 100644 index 0000000..828db03 --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/gao/service/GaoReportOptionTest.java @@ -0,0 +1,46 @@ +package com.imyeyu.api.modules.gao.service; + +import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission; +import com.imyeyu.api.modules.gao.bean.GaoPermissionCode; +import com.imyeyu.api.modules.gao.controller.GaoReportOptionController; +import com.imyeyu.api.modules.gao.mapper.GaoReportOptionMapper; +import org.apache.ibatis.builder.xml.XMLMapperBuilder; +import org.apache.ibatis.datasource.unpooled.UnpooledDataSource; +import org.apache.ibatis.mapping.Environment; +import org.apache.ibatis.session.SqlSessionFactoryBuilder; +import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class GaoReportOptionTest { + @Test + void customerChoicesAreScopedAndUseProfilePermission() throws Exception { + var dataSource = new UnpooledDataSource("org.h2.Driver", "jdbc:h2:mem:reportoptions;MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1", "sa", ""); + try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { + statement.execute("CREATE TABLE gao_customer(id VARCHAR, store_id VARCHAR, name VARCHAR, code VARCHAR, telephone VARCHAR, deleted_at BIGINT)"); + statement.execute("INSERT INTO gao_customer VALUES ('a','s','张三','A001','1234',NULL),('b','s','李四','A002','5678',NULL),('c','other','张三','A003','1234',NULL),('d','s','张三','A004','1234',1)"); + } + var config = new org.apache.ibatis.session.Configuration(new Environment("test", new JdbcTransactionFactory(), dataSource)); + String xml = "mapper/timi-server/gao/GaoReportOptionMapper.xml"; + try (var in = getClass().getClassLoader().getResourceAsStream(xml)) { + new XMLMapperBuilder(in, config, xml, config.getSqlFragments()).parse(); + } + try (var session = new SqlSessionFactoryBuilder().build(config).openSession()) { + var mapper = session.getMapper(GaoReportOptionMapper.class); + var matches = mapper.customers("s", "1234", 0); + assertEquals(1, matches.size()); + assertEquals("a", matches.getFirst().getId()); + assertEquals("张三", matches.getFirst().getName()); + assertEquals(2, mapper.customers("s", "", 0).size()); + } + var method = GaoReportOptionController.class.getMethod("customers", String.class, String.class, int.class); + assertArrayEquals(new GaoPermissionCode[]{GaoPermissionCode.CUSTOMER_PROFILE_READ}, method.getAnnotation(RequireGaoPermission.class).value()); + var scope = mock(GaoStoreScopeService.class); + var mapper = mock(GaoReportOptionMapper.class); + when(scope.resolveStoreId("requested")).thenReturn("permitted"); + new GaoReportOptionController(mapper, scope).customers("requested", "张", 0); + verify(mapper).customers("permitted", "张", 0); + } +}