feat(gao): add customer profile and event month PDF exports

This commit is contained in:
Timi
2026-11-23 15:27:25 +08:00
parent badda20f32
commit 58310b1e33
25 changed files with 1732 additions and 1 deletions
@@ -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;
}