v1.0.80 #92

Merged
timi merged 6 commits from dev into master 2026-11-24 17:26:46 +00:00
25 changed files with 1732 additions and 1 deletions
Showing only changes of commit 58310b1e33 - Show all commits
+9 -1
View File
@@ -4,4 +4,12 @@
技术栈:SpringBoot MariaDB MyBatis Redis
[timijava](https://github.com/imyeyu/timijava)
[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 文件;服务不会自动替换字体,字体缺失时接口返回错误。项目不分发该字体文件。
+11
View File
@@ -180,6 +180,11 @@
</repositories>
<dependencies>
<dependency>
<groupId>com.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-pdfbox</artifactId>
<version>1.0.10</version>
</dependency>
<dependency>
<groupId>org.apache.groovy</groupId>
<artifactId>groovy</artifactId>
@@ -246,6 +251,12 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.3.232</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
@@ -244,6 +244,9 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
@Override
public InputStream getInputStreamByMongoId(String mongoId) {
GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(mongoId)));
if (gridFSFile == null) {
throw new java.util.NoSuchElementException("GridFS file not found: " + mongoId);
}
return gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
}
@@ -31,6 +31,8 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
CUSTOMER_READ("CUSTOMER:READ", "客户读取", false, false),
CUSTOMER_PROFILE_READ("CUSTOMER_PROFILE:READ", "客户画像读取", false, false),
CUSTOMER_UPDATE("CUSTOMER:UPDATE", "客户修改", false, false),
CUSTOMER_DELETE("CUSTOMER:DELETE", "客户删除", false, false),
@@ -0,0 +1,43 @@
package com.imyeyu.api.modules.gao.controller;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.service.GaoCustomerProfileService;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import com.imyeyu.spring.annotation.RequestRateLimit;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/customer/profile")
public class GaoCustomerProfileController {
private final GaoCustomerProfileService service;
@AOPLog
@IgnoreGlobalReturn
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_PROFILE_READ)
@PostMapping(value = "/pdf", produces = MediaType.APPLICATION_PDF_VALUE)
public void pdf(@RequestParam String id, HttpServletResponse response) throws Exception {
byte[] pdf = service.generate(id);
response.setContentType(MediaType.APPLICATION_PDF_VALUE);
response.setHeader(
HttpHeaders.CONTENT_DISPOSITION,
ContentDisposition.inline().filename("customer-profile.pdf").build().toString());
response.setHeader(HttpHeaders.CACHE_CONTROL, "private, no-store");
response.setContentLength(pdf.length);
response.getOutputStream().write(pdf);
}
}
@@ -0,0 +1,38 @@
package com.imyeyu.api.modules.gao.controller;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.service.GaoEventMonthExportService;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import com.imyeyu.spring.annotation.RequestRateLimit;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/event/record")
public class GaoEventMonthExportController {
private final GaoEventMonthExportService service;
@AOPLog
@IgnoreGlobalReturn
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.EVENT_RECORD_READ)
@PostMapping(value = "/month/pdf", produces = MediaType.APPLICATION_PDF_VALUE)
public void export(@RequestParam String eventId, @RequestParam String month, HttpServletResponse response) throws Exception {
byte[] pdf = service.generate(eventId, month);
response.setContentType(MediaType.APPLICATION_PDF_VALUE);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment().filename("event-month.pdf").build().toString());
response.setHeader(HttpHeaders.CACHE_CONTROL, "private, no-store");
response.setContentLength(pdf.length);
response.getOutputStream().write(pdf);
}
}
@@ -0,0 +1,44 @@
package com.imyeyu.api.modules.gao.controller;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.mapper.GaoReportOptionMapper;
import com.imyeyu.api.modules.gao.service.GaoStoreScopeService;
import com.imyeyu.api.modules.gao.vo.report.GaoReportOption;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/report/options")
public class GaoReportOptionController {
private final GaoReportOptionMapper mapper;
private final GaoStoreScopeService scope;
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_PROFILE_READ)
@PostMapping("/customers")
public List<GaoReportOption> 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;
}
}
@@ -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<Map<String, Object>> events(
@Param("store") String store,
@Param("customer") String customer,
@Param("lastStart") long lastStart,
@Param("monthStart") long monthStart,
@Param("end") long end);
Map<String, Object> orders(@Param("store") String store, @Param("customer") String customer);
List<Map<String, Object>> products(
@Param("store") String store, @Param("customer") String customer);
Map<String, Object> points(
@Param("store") String store,
@Param("customer") String customer,
@Param("lastStart") long lastStart,
@Param("monthStart") long monthStart,
@Param("end") long end);
List<Map<String, Object>> reminders(
@Param("store") String store, @Param("customer") String customer);
Map<String, Object> redemptions(
@Param("store") String store, @Param("customer") String customer);
List<Map<String, Object>> recycleTotals(
@Param("store") String store, @Param("customer") String customer);
List<Map<String, Object>> 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<String, Object> latestOrder(@Param("store") String store, @Param("customer") String customer);
List<Map<String, Object>> latestEvents(@Param("store") String store, @Param("customer") String customer, @Param("end") long end);
}
@@ -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<GaoEventMonthRecord> list(@Param("store") String store, @Param("event") String event,
@Param("begin") int begin, @Param("end") int end);
}
@@ -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<GaoReportOption> customers(@Param("store") String store, @Param("keyword") String keyword, @Param("offset") int offset);
}
@@ -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<String, Object> 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<Map<String, Object>>();
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<String, Object> 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<String, Object> 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<String, Object> m, String key) {
Object n = get(m, key);
return n instanceof Number ? ((Number) n).longValue() : null;
}
private static long longValue(Map<String, Object> m, String key) {
Long n = number(m, key);
return n == null ? 0 : n;
}
private static Map<String, Object> canonical(Map<String, Object> source) {
Map<String, Object> result = new HashMap<>();
if (source != null) source.forEach((key, value) -> result.put(key.toLowerCase(java.util.Locale.ROOT), value));
return result;
}
private static List<Map<String, Object>> canonicalRows(List<Map<String, Object>> 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));
}
}
@@ -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<Integer> 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<String, Map<String, Object>> 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<String, Object> result = new LinkedHashMap<>();
result.put("name", safe(item.getCustomerName(), "已删除客户", 30));
result.put("days", new LinkedHashSet<Integer>());
return result;
});
@SuppressWarnings("unchecked") Set<Integer> days = (Set<Integer>) row.get("days");
days.add(item.getDateValue() % 100);
}
List<Map<String, Object>> 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<List<Map<String, Object>>> pages = new ArrayList<>();
List<Map<String, Object>> 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<String, Object> 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();
}
}
@@ -167,6 +167,7 @@ public class GaoCustomerServiceImplement extends AbstractEntityService<GaoCustom
fillPinyin(dbCustomer);
dbCustomer.setGender(customer.getGender());
dbCustomer.setAge(customer.getAge());
dbCustomer.setBirthdate(customer.getBirthdate());
dbCustomer.setBirthdateCalendar(customer.getBirthdateCalendar());
if (TimiJava.isNotEmpty(customer.getBirthdate())) {
dbCustomer.setAge(ChronoUnit.YEARS.between(customer.getBirthdate(), LocalDate.now()));
@@ -0,0 +1,47 @@
package com.imyeyu.api.modules.gao.util;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/// 客户调理部位代码与前端 bodyArea.ts 保持一致。
public final class GaoBodyArea {
private static final Map<String, String> 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<String> 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);
}
}
@@ -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));
}
}
@@ -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;
}
@@ -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;
}
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.imyeyu.api.modules.gao.mapper.GaoCustomerProfileMapper">
<select id="events" resultType="map">
SELECT COALESCE(e.name, '已删除事件') AS name, COUNT(*) AS total, MIN(r.registered_at) AS firstAt, MAX(r.registered_at) AS lastAt,
SUM(CASE WHEN r.registered_at &gt;= #{lastStart} AND r.registered_at &lt; #{monthStart} THEN 1 ELSE 0 END) AS lastMonth,
SUM(CASE WHEN r.registered_at &gt;= #{monthStart} AND r.registered_at &lt; #{end} THEN 1 ELSE 0 END) AS thisMonth
FROM gao_event_record r LEFT JOIN gao_event e ON e.id = r.event_id AND e.store_id = r.store_id
WHERE r.store_id = #{store} AND r.customer_id = #{customer} AND r.deleted_at IS NULL
AND r.verification_status IN ('VERIFIED', 'NOT_REQUIRED') AND r.registered_at &lt; #{end}
AND (e.id IS NULL OR e.deleted_at IS NOT NULL OR e.biz_type IS NULL OR e.biz_type &lt;&gt; 'LEGACY_CONSUMPTION')
GROUP BY r.event_id, e.name ORDER BY total DESC, name ASC
</select>
<select id="orders" resultType="map">
SELECT COUNT(*) AS count,
SUM(CASE WHEN status='ACTIVE' THEN 1 ELSE 0 END) AS active,
SUM(CASE WHEN status='FULFILLED' THEN 1 ELSE 0 END) AS fulfilled,
SUM(CASE WHEN order_type='DIRECT_PRODUCT' THEN 1 ELSE 0 END) AS directCount,
SUM(CASE WHEN order_type='PACKAGE' THEN 1 ELSE 0 END) AS packageCount,
SUM(CASE WHEN order_type='RECYCLE' THEN 1 ELSE 0 END) AS recycleCount,
COALESCE(SUM(CASE WHEN order_type='DIRECT_PRODUCT' THEN sale_amount ELSE 0 END),0) AS directSale,
COALESCE(SUM(CASE WHEN order_type='PACKAGE' THEN sale_amount ELSE 0 END),0) AS packageSale,
COALESCE(SUM(CASE WHEN order_type IN ('DIRECT_PRODUCT','PACKAGE') THEN sale_amount ELSE 0 END),0) AS sale,
COALESCE(SUM(CASE WHEN order_type IN ('DIRECT_PRODUCT','PACKAGE') THEN paid_amount ELSE 0 END),0) AS paid,
COALESCE(SUM(CASE WHEN order_type IN ('DIRECT_PRODUCT','PACKAGE') THEN refunded_amount ELSE 0 END),0) AS refunded,
COALESCE(SUM(CASE WHEN order_type IN ('DIRECT_PRODUCT','PACKAGE') THEN GREATEST(sale_amount-paid_amount,0) ELSE 0 END),0) AS unpaid,
MIN(purchased_at) AS firstAt, MAX(purchased_at) AS lastAt
FROM gao_sales_order WHERE store_id=#{store} AND customer_id=#{customer}
AND deleted_at IS NULL AND status &lt;&gt; 'CANCELLED'
</select>
<select id="products" resultType="map">
SELECT i.product_name_snapshot AS name, i.item_type AS type, i.unit_snapshot AS unit,
MAX(i.sku_name_snapshot) AS skuName, MAX(i.spec_summary_snapshot) AS specSummary,
MAX(i.sku_code_snapshot) AS skuCode,
(SELECT COUNT(*) FROM gao_product_sku k WHERE k.product_id=i.product_id_snapshot
AND k.store_id=#{store} AND k.deleted_at IS NULL) AS skuCount,
SUM(i.quantity) AS quantity
FROM gao_sales_order_item i JOIN gao_sales_order o ON o.id=i.sales_order_id
WHERE o.store_id=#{store} AND o.customer_id=#{customer} AND o.deleted_at IS NULL
AND o.status &lt;&gt; 'CANCELLED' AND i.deleted_at IS NULL
GROUP BY i.product_id_snapshot, i.product_name_snapshot, i.item_type, i.unit_snapshot, i.sku_id
ORDER BY quantity DESC, name ASC LIMIT 10
</select>
<select id="points" resultType="map">
SELECT MAX(occurred_at) AS lastAt,
COALESCE(SUM(CASE WHEN change_type='EARN' AND trigger_source_type='EVENT_RECORD' THEN point_delta ELSE 0 END),0) AS eventEarned,
COALESCE(SUM(CASE WHEN change_type='EARN' AND trigger_source_type='SALES_ORDER_PAID' THEN point_delta ELSE 0 END),0) AS orderEarned,
COALESCE(SUM(CASE WHEN occurred_at &gt;= #{monthStart} AND occurred_at &lt; #{end} AND change_type='EARN' THEN point_delta ELSE 0 END),0) AS thisEarned,
COALESCE(SUM(CASE WHEN occurred_at &gt;= #{monthStart} AND occurred_at &lt; #{end} AND change_type='CONSUME' THEN -point_delta ELSE 0 END),0) AS thisConsumed,
COALESCE(SUM(CASE WHEN occurred_at &gt;= #{lastStart} AND occurred_at &lt; #{monthStart} AND change_type='EARN' THEN point_delta ELSE 0 END),0) AS lastEarned,
COALESCE(SUM(CASE WHEN occurred_at &gt;= #{lastStart} AND occurred_at &lt; #{monthStart} AND change_type='CONSUME' THEN -point_delta ELSE 0 END),0) AS lastConsumed
FROM gao_point_ledger WHERE store_id=#{store} AND customer_id=#{customer} AND deleted_at IS NULL
AND occurred_at &lt; #{end}
</select>
<select id="reminders" resultType="map">
SELECT r.remind_at AS remindAt, r.completed_at AS completedAt, r.content AS content, r.status AS status,
u.nick AS responsible
FROM gao_customer_follow_up_reminder r LEFT JOIN `user` u ON u.id=r.responsible_user_id
WHERE r.store_id=#{store} AND r.customer_id=#{customer} AND r.deleted_at IS NULL
ORDER BY CASE WHEN r.status='PENDING' THEN 0 ELSE 1 END,
CASE WHEN r.status='PENDING' THEN r.remind_at END ASC,
CASE WHEN r.status='COMPLETED' THEN r.completed_at END DESC, r.id ASC LIMIT 5
</select>
<select id="redemptions" resultType="map">
SELECT COUNT(*) AS count, COALESCE(SUM(actual_point_cost),0) AS spent,
COALESCE(SUM(returned_point_cost),0) AS returned
FROM gao_point_redemption WHERE store_id=#{store} AND customer_id=#{customer} AND deleted_at IS NULL
</select>
<select id="recycleTotals" resultType="map">
SELECT recycle_item_id AS itemId,
COALESCE(SUM(CASE WHEN biz_type='FULFILLMENT_YIELD' THEN balance_delta ELSE 0 END),0) AS earned,
COALESCE(SUM(CASE WHEN biz_type='FULFILLMENT_REVOKE' THEN -balance_delta ELSE 0 END),0) AS revoked,
COALESCE(SUM(CASE WHEN biz_type='PAYMENT_VERIFY' THEN -balance_delta ELSE 0 END),0) AS used,
COALESCE(SUM(CASE WHEN biz_type='PAYMENT_REVOKE' THEN balance_delta ELSE 0 END),0) AS returned,
COALESCE(SUM(CASE WHEN biz_type IN ('MANUAL','ADJUST') THEN balance_delta ELSE 0 END),0) AS adjusted
FROM gao_recycle_ledger WHERE store_id=#{store} AND customer_id=#{customer}
GROUP BY recycle_item_id
</select>
<select id="recyclePayments" resultType="map">
SELECT recycle_item_id AS itemId,
COALESCE(SUM(CASE WHEN status='PENDING' THEN quantity ELSE 0 END),0) AS pending,
COALESCE(SUM(CASE WHEN status='VERIFIED' THEN quantity ELSE 0 END),0) AS verified
FROM gao_recycle_payment WHERE store_id=#{store} AND customer_id=#{customer} AND deleted_at IS NULL
GROUP BY recycle_item_id
</select>
<select id="recycleExchanges" resultType="long">
SELECT COUNT(*) FROM gao_recycle_exchange WHERE store_id=#{store} AND customer_id=#{customer}
AND deleted_at IS NULL AND status &lt;&gt; 'CANCELLED'
</select>
<select id="productCount" resultType="long">
SELECT COUNT(*) FROM (
SELECT i.product_id_snapshot, i.product_name_snapshot, i.item_type, i.unit_snapshot
FROM gao_sales_order_item i JOIN gao_sales_order o ON o.id=i.sales_order_id
WHERE o.store_id=#{store} AND o.customer_id=#{customer} AND o.deleted_at IS NULL
AND o.status &lt;&gt; 'CANCELLED' AND i.deleted_at IS NULL
GROUP BY i.product_id_snapshot, i.product_name_snapshot, i.item_type, i.unit_snapshot, i.sku_id
) products
</select>
<select id="reminderCount" resultType="long">
SELECT COUNT(*) FROM gao_customer_follow_up_reminder
WHERE store_id=#{store} AND customer_id=#{customer} AND deleted_at IS NULL
</select>
<select id="latestOrder" resultType="map">
SELECT order_no AS orderNo, status, payment_status AS paymentStatus, purchased_at AS purchasedAt
FROM gao_sales_order WHERE store_id=#{store} AND customer_id=#{customer}
AND deleted_at IS NULL AND status &lt;&gt; 'CANCELLED'
ORDER BY purchased_at DESC, created_at DESC, id DESC LIMIT 1
</select>
<select id="latestEvents" resultType="map">
SELECT COALESCE(e.name, '已删除事件') AS name, r.registered_at AS registeredAt
FROM gao_event_record r LEFT JOIN gao_event e ON e.id = r.event_id AND e.store_id = r.store_id
WHERE r.store_id = #{store} AND r.customer_id = #{customer} AND r.deleted_at IS NULL
AND r.verification_status IN ('VERIFIED', 'NOT_REQUIRED') AND r.registered_at &lt; #{end}
AND (e.id IS NULL OR e.deleted_at IS NOT NULL OR e.biz_type IS NULL OR e.biz_type &lt;&gt; 'LEGACY_CONSUMPTION')
ORDER BY r.registered_at DESC, r.event_id ASC LIMIT 3
</select>
</mapper>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.imyeyu.api.modules.gao.mapper.GaoEventMonthExportMapper">
<select id="list" resultType="com.imyeyu.api.modules.gao.vo.event.GaoEventMonthRecord">
SELECT DISTINCT r.customer_id AS customerId, c.name AS customerName,
r.registered_date_value AS dateValue
FROM gao_event_record r
LEFT JOIN gao_customer c ON c.id = r.customer_id AND c.store_id = r.store_id
WHERE r.store_id = #{store} AND r.event_id = #{event} AND r.deleted_at IS NULL
AND r.registered_date_value &gt;= #{begin} AND r.registered_date_value &lt;= #{end}
ORDER BY customerName, customerId, dateValue
</select>
</mapper>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.imyeyu.api.modules.gao.mapper.GaoReportOptionMapper">
<select id="customers" resultType="com.imyeyu.api.modules.gao.vo.report.GaoReportOption">
SELECT id, name, code FROM gao_customer
WHERE store_id = #{store} AND deleted_at IS NULL
<if test="keyword != null and keyword != ''">AND (name LIKE CONCAT('%', #{keyword}, '%') OR code LIKE CONCAT('%', #{keyword}, '%') OR telephone LIKE CONCAT('%', #{keyword}, '%'))</if>
ORDER BY name, id LIMIT #{offset}, 21
</select>
</mapper>
@@ -0,0 +1,396 @@
<#ftl output_format="HTML" auto_esc=true>
<#function n value=0><#return fmtNumber(value)></#function>
<#function money value=0><#return fmtMoney(value)></#function>
<#function day value=0><#if value == 0><#return ""><#else><#return fmtDay(value)></#if></#function>
<#function time value=0><#if value == 0><#return ""><#else><#return fmtTime(value)></#if></#function>
<#function label value max=36><#return fmtText(value, max)></#function>
<#assign productTypes={"DIRECT_PRODUCT":"商品", "PACKAGE_ENTITLEMENT":"套餐权益", "RECYCLE_ENTITLEMENT":"回收兑换"}>
<#assign orderStatuses={"ACTIVE":"进行中", "FULFILLED":"已履约"}>
<#assign paymentStatuses={"UNPAID":"未付款", "PARTIALLY_PAID":"部分付款", "PAID":"已付清"}>
<#assign reminderStatuses={"PENDING":"待完成", "COMPLETED":"已完成"}>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
<style>
@page {
size: A4;
margin: 9mm;
}
body {
margin: 0;
padding: 3mm 2mm;
font-family: ProfileFont;
font-size: 11.5pt;
line-height: 12pt;
color: #111;
}
h3 {
text-align: center;
line-height: 24pt;
letter-spacing: 2px;
margin: 0 0 2mm;
text-decoration: underline;
}
table {
border-collapse: collapse;
width: 100%;
table-layout: fixed;
}
.header {
margin-bottom: .5mm;
}
.header td {
border: 0;
font-size: 12pt;
font-weight: bold;
line-height: 12pt;
vertical-align: bottom;
}
.sheet td, .sheet th {
border: 0.5pt solid #555;
vertical-align: middle;
line-height: 1;
word-wrap: break-word;
font-weight: normal;
}
.sheet th {
position: relative;
z-index: 0;
background: #f1f1f1;
text-align: center;
font-weight: bold;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
.sheet th::before {
content: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAD0lEQVR4nGN4gAMwDC0JAKSXqAHu0VR/AAAAAElFTkSuQmCC");
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
.sheet th.section::before {
content: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAD0lEQVR4nGN4gQMwDC0JAPy1rgFMdZn6AAAAAElFTkSuQmCC");
}
.sheet .section {
text-align: left;
letter-spacing: 1px;
background: #eee;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
.extended {
height: 7mm;
}
.center {
text-align: center;
}
.right {
text-align: right;
}
.photo {
text-align: center;
color: #555;
}
.photo img {
width: 20mm;
height: 26mm;
}
.small {
font-size: 11.5pt;
line-height: 12pt;
}
.foot {
border: 0;
margin-top: 2mm;
font-size: 11.5pt;
line-height: 12pt;
}
.foot td {
border: 0;
}
</style>
</head>
<body>
<h3>客户画像档案(内部资料)</h3>
<table class="header">
<tr>
<td colspan="4"><span class="brand">${label(store!"", 90)}</span></td>
<td colspan="4" class="right">CUSTOMER PROFILE / 客户经营档案</td>
</tr>
<tr>
<td colspan="4">糕店客户管理系统 / 技术支持:夜雨</td>
<td colspan="4" class="right">档案编号:${label(code!"", 24)}</td>
</tr>
</table>
<div class="intro">客户资料及统计仅限当前门店,数据截至档案生成时。</div>
<table class="sheet">
<colgroup>
<col style="width:11%"/>
<col style="width:14%"/>
<col style="width:11%"/>
<col style="width:14%"/>
<col style="width:11%"/>
<col style="width:14%"/>
<col style="width:11%"/>
<col style="width:14%"/>
</colgroup>
<tr>
<th colspan="8" class="section">一、客户基本资料</th>
</tr>
<tr>
<td class="center">客户姓名</td>
<td>${label(name!"", 12)}</td>
<td class="center">客户编号</td>
<td>${label(code!"", 24)}</td>
<td class="center">性别</td>
<td>${gender}</td>
<td colspan="2" rowspan="6" class="photo"><#if photo?has_content><img src="${photo}"/><#else>客户照片<br/>PHOTO
<br/>暂无照片</#if></td>
</tr>
<tr>
<td class="center">出生日期</td>
<td colspan="3">${birthdate}</td>
<td class="center">年龄</td>
<td><#if age??>${n(age)}<#else></#if></td>
</tr>
<tr>
<td class="center">所属门店</td>
<td colspan="2">${label(store!"", 90)}</td>
<td class="center">联系电话</td>
<td colspan="2">${label(telephone!"", 24)}</td>
</tr>
<tr>
<td class="center">建档人</td>
<td>${label(creator!"", 12)}</td>
<td class="center">介绍人</td>
<td>${label(introducer!"", 12)}</td>
<td class="center">邀请客户</td>
<td><#if invited??>${n(invited)}<#else></#if> 人</td>
</tr>
<tr>
<td class="center">客户标签</td>
<td colspan="3"><#if tags?has_content><#assign tagText=tags[0..*8]?join("、")><#if tags?size gt 8><#assign tagText=tagText + "…"></#if>${label(tagText, 70)}<#else></#if></td>
<td class="center">建档日期</td>
<td>${day(created!0)}</td>
</tr>
<tr>
<td class="center">联系地址</td>
<td colspan="5">${label(address!"", 45)}</td>
</tr>
<tr>
<td class="center">健康情况</td>
<td colspan="7" class="extended">${label(disease!"", 160)}</td>
</tr>
<tr>
<td class="center">调理部位</td>
<td colspan="7" class="extended">${label(conditioning!"", 160)}</td>
</tr>
<tr>
<td class="center">客户备注</td>
<td colspan="7">${label(remark!"", 70)}</td>
</tr>
<tr>
<th colspan="8" class="section">二、客户登记事件统计(已核验及无需核验)</th>
</tr>
<tr>
<td class="center">累计次数</td>
<td class="center">${n(eventTotal)} 次</td>
<td class="center">事件种类</td>
<td class="center">${n(events?size)} 种</td>
<td class="center">首次登记</td>
<td>${day(eventFirst!0)}</td>
<td class="center">最近登记</td>
<td>${day(eventLast!0)}</td>
</tr>
<tr>
<td class="center">本月登记</td>
<td class="center" colspan="3">${n(eventMonth)} 次</td>
<td class="center">上月登记</td>
<td class="center" colspan="3">${n(eventPrevious)} 次</td>
</tr>
<tr>
<th colspan="2">登记事件</th>
<th colspan="2">累计</th>
<th colspan="2">上个月</th>
<th colspan="2">本月</th>
</tr>
<#list 0..5 as i>
<tr><#if i lt events?size><#assign e=events[i]>
<td colspan="2">${label(e.name!"", 24)}</td>
<td colspan="2" class="center">${n(e.total!0)} 次</td>
<td colspan="2" class="center">${n(e.lastmonth!0)} 次</td>
<td colspan="2" class="center">${n(e.thismonth!0)} 次</td><#else>
<td colspan="2">&#160;</td>
<td colspan="2">&#160;</td>
<td colspan="2">&#160;</td>
<td colspan="2">&#160;</td></#if></tr></#list>
<tr>
<td class="center">最近登记</td>
<td colspan="7"><#if recentEvents?has_content><#list recentEvents as e>${day(e.registeredat!0)}(${label(e.name!"", 13)})<#sep>,</#list><#else></#if><#if events?size gt 6> | 另有 ${n(events?size - 6)} 种事件未列出</#if></td>
</tr>
<tr>
<th colspan="8" class="section">三、订单及产品统计(排除已取消订单)</th>
</tr>
<tr>
<td class="center">有效订单</td>
<td class="center">${n(order.count!0)} 笔</td>
<td class="center">销售金额</td>
<td class="right">${money(order.sale!0)}</td>
<td class="center">已付款</td>
<td class="right">${money(order.paid!0)}</td>
<td class="center">待付款</td>
<td class="right">${money(order.unpaid!0)}</td>
</tr>
<tr>
<td class="center">退款金额</td>
<td class="right">${money(order.refunded!0)}</td>
<td class="center">净收款</td>
<td class="right">${money((order.paid!0) - (order.refunded!0))}</td>
<td class="center">首次购买</td>
<td>${day(order.firstat!0)}</td>
<td class="center">最近购买</td>
<td>${day(order.lastat!0)}</td>
</tr>
<tr>
<td class="center">产品订单</td>
<td colspan="3">${n(order.directcount!0)} 笔 / 成交 ${money(order.directsale!0)}</td>
<td class="center">套餐订单</td>
<td colspan="3">${n(order.packagecount!0)} 笔 / 成交 ${money(order.packagesale!0)}</td>
</tr>
<tr>
<td class="center">回收订单</td>
<td colspan="3">${n(order.recyclecount!0)} 笔</td>
<td class="center">最近订单</td>
<td colspan="3"><#if latestOrder?has_content>${label(latestOrder.orderno!"")}<#else></#if></td>
</tr>
<tr>
<th colspan="2">产品(按数量排序)</th>
<th>单位</th>
<th>数量</th>
<th colspan="2">产品(续)</th>
<th>单位</th>
<th>数量</th>
</tr>
<#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>
<#if !sku?has_content || sku == productName><#local sku=p.skucode!""></#if>
<#if sku?has_content><#local productName=productName + "(" + sku + ")"></#if>
</#if>
<td colspan="2">${label(productName, 24)}</td>
<td class="center">${label(p.unit!"", 8)}</td>
<td class="center">${n(p.quantity!0)}</td><#else>
<td colspan="2">&#160;</td>
<td>&#160;</td>
<td>&#160;</td></#if></#macro>
<#list 0..4 as i>
<tr><@productCells index=i*2/><@productCells index=i*2+1/></tr></#list>
<tr>
<td colspan="8"><#if productCount gt 10>仅列前 10 项,另有 ${n(productCount - 10)} 项未列出<#else>产品按购买数量排序</#if>
;净收款 = 已付款 - 退款。订单状态:进行中 ${n(order.active!0)} / 已履约 ${n(order.fulfilled!0)}</td>
</tr>
<tr>
<th colspan="8" class="section">四、积分统计</th>
</tr>
<tr>
<td class="center">当前余额</td>
<td class="center">${n(pointAccount.balance!0)}</td>
<td class="center">累计获得</td>
<td class="center">${n(pointAccount.totalEarned!0)}</td>
<td class="center">累计消费</td>
<td class="center">${n(pointAccount.totalConsumed!0)}</td>
<td class="center">累计撤销</td>
<td class="center">${n(pointAccount.totalRevoked!0)}</td>
</tr>
<tr>
<td class="center">累计调整</td>
<td class="center">${n(pointAccount.totalAdjusted!0)}</td>
<td class="center">积分兑换</td>
<td colspan="5">${n(redemptions.count!0)} 次 / 消耗 ${n(redemptions.spent!0)} /
退回 ${n(redemptions.returned!0)}</td>
</tr>
<tr>
<td class="center">本月积分</td>
<td colspan="3">获得 ${n(pointStats.thisearned!0)} / 消费 ${n(pointStats.thisconsumed!0)}</td>
<td class="center">上月积分</td>
<td colspan="3">获得 ${n(pointStats.lastearned!0)} / 消费 ${n(pointStats.lastconsumed!0)}</td>
</tr>
<tr>
<td class="center">主要来源</td>
<td colspan="3">事件 ${n(pointStats.eventearned!0)} / 订单 ${n(pointStats.orderearned!0)}</td>
<td class="center">最近变动</td>
<td colspan="3">${day(pointStats.lastat!0)}</td>
</tr>
<tr>
<th colspan="8" class="section">五、回收物统计(各品种分别统计)</th>
</tr>
<tr>
<th colspan="2">品种及单位</th>
<th>当前余额</th>
<th>已预留</th>
<th>获得 冲回</th>
<th>核销 退回</th>
<th>累计调整</th>
<th>最近变动</th>
</tr>
<#list 0..3 as i>
<tr><#if i lt recycles?size><#assign r=recycles[i]>
<td colspan="2">${label(r.account.recycleName!"", 8)}(${label(r.account.recycleUnit!"", 4)})</td>
<td class="center">${n(r.account.balance!0)}</td>
<td class="center">${n(r.account.reserved!0)}</td>
<td class="center">${n(r.totals.earned!0)} / ${n(r.totals.revoked!0)}</td>
<td class="center">${n(r.totals.used!0)} / ${n(r.totals.returned!0)}</td>
<td class="center">${n(r.totals.adjusted!0)}</td>
<td>${day(r.account.updatedAt!0)}</td><#else>
<td colspan="2">&#160;</td>
<td>&#160;</td>
<td>&#160;</td>
<td>&#160;</td>
<td>&#160;</td>
<td>&#160;</td>
<td>&#160;</td></#if></tr></#list>
<tr>
<td class="center">兑换情况</td>
<td colspan="7">兑换 ${n(recycleExchanges)}
次;不同品种分别统计<#if recycles?size gt 4>;另有 ${n(recycles?size - 4)} 个品种未列出</#if><#list recycles as r><#if r?index lt 4> | ${label(r.account.recycleName!"", 8)}:已核 ${n(r.payments.verified!0)} / 待核 ${n(r.payments.pending!0)}</#if></#list></td>
</tr>
<tr>
<th colspan="8" class="section">隐私与保密提示</th>
</tr>
<tr>
<td colspan="8" class="small">本档案包含客户个人资料、联系方式及健康相关信息,仅供授权人员在业务范围内使用。请妥善保管,勿向无关人员传播。打印或下载后请按门店保密要求处理,丢弃前请彻底销毁。<br/>本页为统计摘要,部分明细可能因版面限制省略;统计结果以系统实际记录及业务口径为准。
</td>
</tr>
</table>
<table class="foot">
<tr>
<td colspan="4">制单人:${label(operator!"", 12)}  所属门店:${label(store!"", 90)}</td>
<td colspan="4" class="right">生成时间:${time(generated)}</td>
</tr>
</table>
</body>
</html>
@@ -0,0 +1,120 @@
<#ftl output_format="HTML" auto_esc=true>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
<style>
@page {
size: A4 landscape;
margin: 9mm;
}
body {
font-family: ProfileFont;
font-size: 10pt;
color: #111;
}
h1 {
font-size: 19pt;
text-align: center;
margin: 0 0 3mm;
}
.info {
gap: 2.5cm;
margin: 0 0 3mm;
display: flex;
}
.page-number {
float: right;
}
.page-break {
page-break-before: always;
}
table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
}
thead {
display: table-header-group;
}
tr {
page-break-inside: avoid;
}
th, td {
border: .5pt solid #555;
height: 7.5mm;
padding: 1.2mm 0;
text-align: center;
vertical-align: middle;
}
th {
background: #f4f4f4;
}
.name {
width: 30mm;
text-align: left;
padding-left: 1mm;
word-wrap: break-word;
}
.number {
width: 10mm;
}
.closed {
background: #e5e5e5;
}
.small {
font-size: 8pt;
}
</style>
</head>
<body>
<#list pages as rows>
<div<#if rows?index gt 0> class="page-break"</#if>>
<h1>${monthNumber?c} 月登记记录表</h1>
<div class="info">
<span class="page-number">第 ${(rows?index + 1)?c} / ${pages?size?c} 页</span>
<span>门店:${store}</span>
<span>事件:${event}</span>
<span>月份:${month}</span>
<span>客户数:${customerCount?c}</span>
<span>平台:糕店客户管理系统</span>
<span>技术支持:夜雨</span>
<span>灰色列为休息日</span>
</div>
<table>
<thead>
<tr>
<th class="number">序号</th>
<th class="name">客户</th><#list days as day>
<th<#if closed?seq_contains(day)> class="closed"</#if>>${day?c}</th></#list></tr>
</thead>
<tbody>
<#list rows as row>
<tr>
<td>${row.sequence?c}</td>
<td class="name">${row.name}</td><#list days as day>
<td<#if closed?seq_contains(day)> class="closed"</#if>><#if !closed?seq_contains(day) && row.days?seq_contains(day)>√<#else>&#160;</#if></td></#list>
</tr>
<#else>
<tr>
<td colspan="${(days?size + 2)?c}">本月暂无登记记录</td></tr></#list>
</tbody>
</table>
</div>
</#list>
</body>
</html>
@@ -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"));
}
}
@@ -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<GaoEventMonthRecord>();
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"));
}
}
@@ -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);
}
}