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

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

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

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

+
+ 第 ${(rows?index + 1)?c} / ${pages?size?c} 页 + 门店:${store} + 事件:${event} + 月份:${month} + 客户数:${customerCount?c} + 平台:糕店客户管理系统 + 技术支持:夜雨 + 灰色列为休息日 +
+ + + + + <#list days as day> + class="closed">${day?c} + + + <#list rows as row> + + + <#list days as day> + class="closed"><#if !closed?seq_contains(day) && row.days?seq_contains(day)>√<#else>  + + <#else> + + + +
序号客户
${row.sequence?c}${row.name}
本月暂无登记记录
+ + + + diff --git a/src/test/java/com/imyeyu/api/modules/gao/service/GaoCustomerProfilePhotoTest.java b/src/test/java/com/imyeyu/api/modules/gao/service/GaoCustomerProfilePhotoTest.java new file mode 100644 index 0000000..177deef --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/gao/service/GaoCustomerProfilePhotoTest.java @@ -0,0 +1,38 @@ +package com.imyeyu.api.modules.gao.service; + +import com.imyeyu.api.modules.common.entity.Attachment; +import com.imyeyu.api.modules.common.service.AttachmentService; +import com.imyeyu.api.modules.common.service.implement.AttachmentServiceImplement; +import com.mongodb.client.gridfs.GridFSBucket; +import org.junit.jupiter.api.Test; +import org.springframework.data.mongodb.gridfs.GridFsTemplate; + +import java.util.List; +import java.util.NoSuchElementException; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +class GaoCustomerProfilePhotoTest { + @Test + void missingGridFsFileUsesPhotoPlaceholder() throws Exception { + var gridFs = mock(GridFsTemplate.class); + var bucket = mock(GridFSBucket.class); + var storage = new AttachmentServiceImplement(null, null, bucket, gridFs, null); + assertThrows(NoSuchElementException.class, () -> storage.getInputStreamByMongoId("missing")); + verifyNoInteractions(bucket); + + var attachments = mock(AttachmentService.class); + var photo = new Attachment(); + photo.setMongoId("missing"); + when(attachments.listByBizId(eq(Attachment.BizType.GAO_CUSTOMER), eq("customer"), any(String[].class))) + .thenReturn(List.of(photo)); + when(attachments.getInputStreamByMongoId("missing")) + .thenAnswer(invocation -> storage.getInputStreamByMongoId("missing")); + var service = new GaoCustomerProfileService(null, null, null, null, null, null, attachments, null, null, null, null, null); + var method = GaoCustomerProfileService.class.getDeclaredMethod("photo", String.class); + method.setAccessible(true); + assertEquals("", method.invoke(service, "customer")); + } +} diff --git a/src/test/java/com/imyeyu/api/modules/gao/service/GaoEventMonthExportTest.java b/src/test/java/com/imyeyu/api/modules/gao/service/GaoEventMonthExportTest.java new file mode 100644 index 0000000..84cf86f --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/gao/service/GaoEventMonthExportTest.java @@ -0,0 +1,105 @@ +package com.imyeyu.api.modules.gao.service; + +import com.imyeyu.api.modules.gao.entity.GaoEvent; +import com.imyeyu.api.modules.gao.entity.GaoStore; +import com.imyeyu.api.modules.gao.entity.GaoStoreBusinessDay; +import com.imyeyu.api.modules.gao.mapper.GaoEventMonthExportMapper; +import com.imyeyu.api.modules.gao.vo.event.GaoEventMonthRecord; +import freemarker.template.Configuration; +import org.apache.ibatis.builder.xml.XMLMapperBuilder; +import org.apache.ibatis.datasource.unpooled.UnpooledDataSource; +import org.apache.ibatis.mapping.Environment; +import org.apache.ibatis.session.SqlSessionFactoryBuilder; +import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.text.PDFTextStripper; +import org.junit.jupiter.api.Test; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class GaoEventMonthExportTest { + @Test + void queryIncludesRegistrationsOncePerCustomerAndDayWithinStoreAndEvent() throws Exception { + var ds = new UnpooledDataSource("org.h2.Driver", "jdbc:h2:mem:eventmonth;MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1", "sa", ""); + try (var c = ds.getConnection(); var s = c.createStatement()) { + s.execute("CREATE TABLE gao_customer(id VARCHAR, store_id VARCHAR, name VARCHAR, code VARCHAR)"); + s.execute("CREATE TABLE gao_event_record(customer_id VARCHAR, store_id VARCHAR, event_id VARCHAR, deleted_at BIGINT, registered_date_value INT, verification_status VARCHAR)"); + s.execute("INSERT INTO gao_customer VALUES ('c','s','客户','KH1')"); + s.execute("INSERT INTO gao_event_record VALUES ('c','s','e',NULL,20240204,'PENDING'),('c','s','e',NULL,20240204,'VERIFIED'),('c','s','e',NULL,20240229,'NOT_REQUIRED'),('c','s','other',NULL,20240205,'VERIFIED'),('c','other','e',NULL,20240206,'VERIFIED'),('c','s','e',1,20240207,'VERIFIED'),('c','s','e',NULL,20240301,'VERIFIED')"); + } + var config = new org.apache.ibatis.session.Configuration(new Environment("test", new JdbcTransactionFactory(), ds)); + String xml = "mapper/timi-server/gao/GaoEventMonthExportMapper.xml"; + try (var in = getClass().getClassLoader().getResourceAsStream(xml)) { + new XMLMapperBuilder(in, config, xml, config.getSqlFragments()).parse(); + } + try (var session = new SqlSessionFactoryBuilder().build(config).openSession()) { + var rows = session.getMapper(GaoEventMonthExportMapper.class).list("s", "e", 20240201, 20240229); + assertEquals(2, rows.size()); + assertEquals("客户", rows.getFirst().getCustomerName()); + assertEquals(20240204, rows.getFirst().getDateValue()); + assertEquals(20240229, rows.getLast().getDateValue()); + } + } + + @Test + void rendersLandscapeLeapMonthWithAllCustomersAndRepeatedHeaders() throws Exception { + String fontPath = System.getProperty("gao.customer-profile.font-path", "C:/Windows/Fonts/simsun.ttc"); + org.junit.jupiter.api.Assumptions.assumeTrue(Files.isRegularFile(Path.of(fontPath))); + var events = mock(GaoEventService.class); + var stores = mock(GaoStoreService.class); + var scope = mock(GaoStoreScopeService.class); + var businessDays = mock(GaoStoreBusinessDayService.class); + var mapper = mock(GaoEventMonthExportMapper.class); + var event = new GaoEvent(); event.setId("e"); event.setStoreId("s"); event.setName("到店登记"); + var store = new GaoStore(); store.setName("测试门店"); + when(events.get("e")).thenReturn(event); + when(stores.get("s")).thenReturn(store); + var rest = new GaoStoreBusinessDay(); rest.setStatus(GaoStoreBusinessDay.Status.CLOSED); rest.setDateValue(20240204); + when(businessDays.listByDateRange("s", 20240201, 20240229)).thenReturn(List.of(rest)); + var records = new ArrayList(); + for (int i = 0; i < 80; i++) { + var record = new GaoEventMonthRecord(); record.setCustomerId("c" + i); record.setCustomerName("客户" + i); record.setDateValue(20240205); records.add(record); + } + var repeat = new GaoEventMonthRecord(); repeat.setCustomerId("c0"); repeat.setCustomerName("客户0"); repeat.setDateValue(20240229); records.add(repeat); + var closedOnly = new GaoEventMonthRecord(); closedOnly.setCustomerId("closed"); closedOnly.setCustomerName("休息日客户"); closedOnly.setDateValue(20240204); records.add(closedOnly); + var longName = new GaoEventMonthRecord(); longName.setCustomerId("long"); longName.setCustomerName("长名字".repeat(10)); longName.setDateValue(20240205); records.add(longName); + when(mapper.list("s", "e", 20240201, 20240229)).thenReturn(records); + var cfg = new Configuration(Configuration.VERSION_2_3_33); cfg.setClassLoaderForTemplateLoading(getClass().getClassLoader(), "templates"); cfg.setDefaultEncoding("UTF-8"); + var service = new GaoEventMonthExportService(events, stores, scope, businessDays, mapper, cfg); + org.springframework.test.util.ReflectionTestUtils.setField(service, "fontPath", fontPath); + byte[] bytes = service.generate("e", "2024-02"); + if (System.getProperty("gao.event.month.preview") != null) Files.write(Path.of(System.getProperty("gao.event.month.preview")), bytes); + verify(scope).checkStoreId("s"); + try (var pdf = PDDocument.load(bytes)) { + assertTrue(pdf.getNumberOfPages() > 1); + for (var page : pdf.getPages()) assertTrue(page.getMediaBox().getWidth() > page.getMediaBox().getHeight()); + for (int page = 1; page <= pdf.getNumberOfPages(); page++) { + var stripper = new PDFTextStripper(); stripper.setStartPage(page); stripper.setEndPage(page); + String pageText = stripper.getText(pdf); + assertTrue(pageText.contains("2024-02") && pageText.contains("29"), "each page needs the month and date header"); + String normalizedPage = pageText.replaceAll("\\s+", ""); + assertTrue(normalizedPage.contains("第" + page + "/" + pdf.getNumberOfPages() + "页"), "page number must match the physical page"); + if (page == 1) { + assertTrue(pageText.contains("客户25"), "fill the first page with 26 customers"); + assertFalse(pageText.contains("客户26"), "the next customer starts the next page"); + } + } + String text = new PDFTextStripper().getText(pdf); + assertTrue(text.contains("客户79")); + assertFalse(text.contains("休息日客户")); + assertFalse(text.contains("KH0")); + assertTrue(text.contains("√")); + assertTrue(text.contains("2 月登记记录表")); + assertTrue(text.contains("29")); + assertTrue(text.contains("灰色列为休息日")); + assertTrue(text.split("客户", -1).length > 80); + } + assertThrows(Exception.class, () -> service.generate("e", "2024-13")); + } +} diff --git a/src/test/java/com/imyeyu/api/modules/gao/service/GaoReportOptionTest.java b/src/test/java/com/imyeyu/api/modules/gao/service/GaoReportOptionTest.java new file mode 100644 index 0000000..828db03 --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/gao/service/GaoReportOptionTest.java @@ -0,0 +1,46 @@ +package com.imyeyu.api.modules.gao.service; + +import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission; +import com.imyeyu.api.modules.gao.bean.GaoPermissionCode; +import com.imyeyu.api.modules.gao.controller.GaoReportOptionController; +import com.imyeyu.api.modules.gao.mapper.GaoReportOptionMapper; +import org.apache.ibatis.builder.xml.XMLMapperBuilder; +import org.apache.ibatis.datasource.unpooled.UnpooledDataSource; +import org.apache.ibatis.mapping.Environment; +import org.apache.ibatis.session.SqlSessionFactoryBuilder; +import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class GaoReportOptionTest { + @Test + void customerChoicesAreScopedAndUseProfilePermission() throws Exception { + var dataSource = new UnpooledDataSource("org.h2.Driver", "jdbc:h2:mem:reportoptions;MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1", "sa", ""); + try (var connection = dataSource.getConnection(); var statement = connection.createStatement()) { + statement.execute("CREATE TABLE gao_customer(id VARCHAR, store_id VARCHAR, name VARCHAR, code VARCHAR, telephone VARCHAR, deleted_at BIGINT)"); + statement.execute("INSERT INTO gao_customer VALUES ('a','s','张三','A001','1234',NULL),('b','s','李四','A002','5678',NULL),('c','other','张三','A003','1234',NULL),('d','s','张三','A004','1234',1)"); + } + var config = new org.apache.ibatis.session.Configuration(new Environment("test", new JdbcTransactionFactory(), dataSource)); + String xml = "mapper/timi-server/gao/GaoReportOptionMapper.xml"; + try (var in = getClass().getClassLoader().getResourceAsStream(xml)) { + new XMLMapperBuilder(in, config, xml, config.getSqlFragments()).parse(); + } + try (var session = new SqlSessionFactoryBuilder().build(config).openSession()) { + var mapper = session.getMapper(GaoReportOptionMapper.class); + var matches = mapper.customers("s", "1234", 0); + assertEquals(1, matches.size()); + assertEquals("a", matches.getFirst().getId()); + assertEquals("张三", matches.getFirst().getName()); + assertEquals(2, mapper.customers("s", "", 0).size()); + } + var method = GaoReportOptionController.class.getMethod("customers", String.class, String.class, int.class); + assertArrayEquals(new GaoPermissionCode[]{GaoPermissionCode.CUSTOMER_PROFILE_READ}, method.getAnnotation(RequireGaoPermission.class).value()); + var scope = mock(GaoStoreScopeService.class); + var mapper = mock(GaoReportOptionMapper.class); + when(scope.resolveStoreId("requested")).thenReturn("permitted"); + new GaoReportOptionController(mapper, scope).customers("requested", "张", 0); + verify(mapper).customers("permitted", "张", 0); + } +} From 7e7a9cf60cdaa16608b0b21015b4fb5229442a59 Mon Sep 17 00:00:00 2001 From: Timi Date: Tue, 24 Nov 2026 11:41:59 +0800 Subject: [PATCH 2/6] feat(gao-ai): add confirmed write operations - add prepare/commit/cancel MCP tools and pending operation state - enforce execution identity, permissions, exact confirmation and audit - support attachments and operation confirmation cards - rewrite Dify DSL for write routing and destructive confirmations --- src/ai/dsl/README.md | 82 + src/ai/dsl/main_agent.yml | 1330 ++++++++++++++++- .../com/imyeyu/api/config/RedisConfig.java | 20 + .../gao/ai/config/GaoAiProperties.java | 52 + .../controller/GaoAiOperationController.java | 171 +++ .../modules/gao/ai/entity/GaoAiAuditLog.java | 33 + .../modules/gao/ai/entity/GaoAiSession.java | 2 +- .../gao/ai/mcp/GaoAiMcpAuthentication.java | 32 +- .../gao/ai/mcp/GaoAiMcpCommitController.java | 252 ++++ .../gao/ai/mcp/GaoAiMcpController.java | 89 +- .../modules/gao/ai/mcp/GaoAiToolNames.java | 38 +- .../gao/ai/mcp/tool/FollowUpQueryTool.java | 96 ++ .../gao/ai/mcp/tool/FulfillmentQueryTool.java | 120 ++ .../gao/ai/mcp/tool/GaoAiWriteTool.java | 43 + .../gao/ai/mcp/tool/OperationCancelTool.java | 59 + .../gao/ai/mcp/tool/OperationCommitTool.java | 65 + .../gao/ai/mcp/tool/OperationPrepareTool.java | 85 ++ .../ai/operation/GaoAiAttachmentService.java | 49 + .../GaoAiAttachmentServiceImplement.java | 180 +++ .../ai/operation/GaoAiAttachmentToken.java | 40 + .../gao/ai/operation/GaoAiCommitResult.java | 65 + .../gao/ai/operation/GaoAiOperation.java | 66 + .../ai/operation/GaoAiOperationContext.java | 51 + .../operation/GaoAiOperationDefinition.java | 89 ++ .../ai/operation/GaoAiOperationException.java | 62 + .../ai/operation/GaoAiOperationHandler.java | 37 + .../ai/operation/GaoAiOperationRegistry.java | 181 +++ .../ai/operation/GaoAiOperationService.java | 70 + .../GaoAiOperationServiceImplement.java | 600 ++++++++ .../ai/operation/GaoAiOperationSupport.java | 834 +++++++++++ .../ai/operation/GaoAiPendingOperation.java | 154 ++ .../GaoAiPendingOperationService.java | 79 + ...GaoAiPendingOperationServiceImplement.java | 310 ++++ .../ai/operation/GaoAiPreparedOperation.java | 50 + .../gao/ai/operation/GaoAiToolAuthorizer.java | 62 + .../handler/CustomerOperationHandler.java | 419 ++++++ .../handler/OrderOperationHandler.java | 911 +++++++++++ .../handler/PackageOperationHandler.java | 188 +++ .../handler/PointOperationHandler.java | 243 +++ .../handler/StockOperationHandler.java | 136 ++ .../handler/StoreOperationHandler.java | 354 +++++ .../implement/GaoAiAuditServiceImplement.java | 14 +- .../implement/GaoAiChatServiceImplement.java | 80 +- .../GaoAiSessionServiceImplement.java | 28 +- .../gao/ai/vo/GaoAiAttachmentView.java | 28 + .../modules/gao/ai/vo/GaoAiChatRequest.java | 3 + .../ai/vo/GaoAiOperationCommitRequest.java | 23 + .../modules/gao/ai/vo/GaoAiToolResult.java | 72 + .../modules/gao/bean/GaoSystemSetting.java | 2 + .../context/ExecutionIdentityContext.java | 100 ++ .../implement/UserLoginServiceImplement.java | 16 + src/main/resources/application.yml | 18 + .../operation/GaoAiOperationRegistryTest.java | 61 + .../context/ExecutionIdentityContextTest.java | 49 + 54 files changed, 8223 insertions(+), 70 deletions(-) create mode 100644 src/ai/dsl/README.md create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/controller/GaoAiOperationController.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiMcpCommitController.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/FollowUpQueryTool.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/FulfillmentQueryTool.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/GaoAiWriteTool.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/OperationCancelTool.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/OperationCommitTool.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/OperationPrepareTool.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiAttachmentService.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiAttachmentServiceImplement.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiAttachmentToken.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiCommitResult.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperation.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationContext.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationDefinition.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationException.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationHandler.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationRegistry.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationService.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationServiceImplement.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationSupport.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPendingOperation.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPendingOperationService.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPendingOperationServiceImplement.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPreparedOperation.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiToolAuthorizer.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/CustomerOperationHandler.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/OrderOperationHandler.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/PackageOperationHandler.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/PointOperationHandler.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/StockOperationHandler.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/StoreOperationHandler.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiAttachmentView.java create mode 100644 src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiOperationCommitRequest.java create mode 100644 src/main/java/com/imyeyu/api/modules/user/context/ExecutionIdentityContext.java create mode 100644 src/test/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationRegistryTest.java create mode 100644 src/test/java/com/imyeyu/api/modules/user/context/ExecutionIdentityContextTest.java diff --git a/src/ai/dsl/README.md b/src/ai/dsl/README.md new file mode 100644 index 0000000..35d6fa3 --- /dev/null +++ b/src/ai/dsl/README.md @@ -0,0 +1,82 @@ +# GAO 门店智能助手 Dify DSL 配置说明 + +`main_agent.yml` 是 Advanced Chat 应用,支持: + +- 知识库规则回答 +- 实时业务查询 Agent +- 规则 + 实时数据混合分析 +- 带预览和人工确认的写操作 + +## 1. MCP Provider + +导入 DSL 后需要配置两个 MCP Provider。 + +| DSL 中的 Provider | 后端地址 | 服务密钥 | +|---|---|---| +| `gao-mcp-server-dev` | `http(s):///mcp/gao-ai` | 系统设置 `DIFY_MCP_SERVICE_KEY` | +| `gao-mcp-commit-dev` | `http(s):///mcp/gao-ai-commit` | 系统设置 `DIFY_MCP_COMMIT_SERVICE_KEY` | + +要求: + +1. `gao-mcp-server-dev` 只暴露查询工具和 `operation_prepare`。 +2. `gao-mcp-commit-dev` 只暴露 `operation_commit`、`operation_cancel`。 +3. **提交 Provider 不得绑定到任何 Agent 节点**,只允许 `main_agent.yml` 中的确定性工具节点调用。 +4. 如果 Dify 中的 Provider ID 与 DSL 不一致,请同时修改 DSL 中 `commit_tool`、`cancel_tool`、`prepare_tool` 的 `provider_id` 和 `provider_name`。 + +## 2. 写能力开关 + +后端默认关闭写能力: + +```yaml +gao: + ai: + write: + enabled: true + confirmation-ttl-seconds: 600 + result-ttl-seconds: 1800 + max-prepares-per-10-minutes: 10 + max-commits-per-10-minutes: 10 + order-max-sale-amount: 1000000 + order-max-discount-rate: 0.30 + point-adjust-max-abs: 10000 + stock-change-max-quantity: 1000 + attachment-max-count: 10 + attachment-max-size-mb: 10 + attachment-ttl-seconds: 86400 +``` + +## 3. 附件 + +Dify 内置文件上传保持关闭。前端流程: + +1. 调用 `POST /gao/ai/attachment/upload` 上传凭证,获得 `token`。 +2. 聊天请求携带 `attachmentTokenList`。 +3. 后端把附件 token 注入 Dify start 输入 `attachmentTokensJson`。 +4. `operation_prepare` 解析并校验附件,token 不进入模型提示词。 + +## 4. 确认流程 + +### 文本确认 + +1. 用户发起写操作。 +2. `operation_prepare` 返回 `PENDING_CONFIRMATION`、`previewText`、`requiredPhrase`。 +3. 下一轮聊天后端注入 `pendingOperationToken` 等 start 输入。 +4. `pending_gate` 判断是否存在待确认操作。 +5. `pending_action` 规则判断确认/取消。 +6. 确认时调用 `operation_commit`;取消时调用 `operation_cancel`。 + +### 卡片确认 + +1. 后端在 SSE 结束前推送 `operation_preview`。 +2. 卡片调用 `GET /gao/ai/operation/pending` 恢复状态。 +3. 确认调用 `POST /gao/ai/operation/commit`。 +4. 取消调用 `POST /gao/ai/operation/cancel`。 + +卡片使用公开 `operationId`,确认 token 不进入浏览器。 + +## 5. 安全边界 + +- 模型不可传 `storeId`、`operatorUserId`、`requestNo`、`confirmationToken`。 +- 提交工具只接受确认 token,不接受业务参数。 +- 破坏性和敏感操作必须精确短语,并重新校验权限、门店、价格、库存和状态。 +- 物理删除不在操作注册表中。 diff --git a/src/ai/dsl/main_agent.yml b/src/ai/dsl/main_agent.yml index 1ffab25..6f03c33 100644 --- a/src/ai/dsl/main_agent.yml +++ b/src/ai/dsl/main_agent.yml @@ -1,5 +1,5 @@ app: - description: 店长专用门店经营助手。按问题类型路由到知识库、GAO MCP Agent 或只读拒绝分支。 + description: 店长专用门店经营助手。支持知识查询、实时业务查询、混合分析,以及带预览和人工确认的写操作。 icon: 🏪 icon_background: '#E8F5E9' icon_type: emoji @@ -55,7 +55,7 @@ workflow: - local_file - remote_url number_limits: 3 - opening_statement: 你好,我是门店经营助手。可以查询今日经营、本月销售、库存预警、重点客户和积分套餐情况。 + opening_statement: 你好,我是门店经营助手。可以查询今日经营、客户、订单、库存和积分,也可以在你确认后办理客户、订单、收款、履约、库存等写操作。删除操作不受理。 retriever_resource: enabled: false sensitive_word_avoidance: @@ -245,14 +245,280 @@ workflow: iteration_id: null loop_id: null sourceType: start - targetType: question-classifier - id: start-classifier + targetType: if-else + id: start-pending source: start sourceHandle: source + target: pending_gate + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: if-else + targetType: code + id: pending-true + source: pending_gate + sourceHandle: 'true' + target: pending_action + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: if-else + targetType: question-classifier + id: pending-false + source: pending_gate + sourceHandle: 'false' target: classifier targetHandle: target type: custom zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: code + targetType: if-else + id: pending-action-confirm + source: pending_action + sourceHandle: source + target: confirm_gate + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: if-else + targetType: code + id: confirm-true + source: confirm_gate + sourceHandle: 'true' + target: pending_reason + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: if-else + targetType: if-else + id: confirm-false + source: confirm_gate + sourceHandle: 'false' + target: cancel_gate + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: if-else + targetType: tool + id: cancel-true + source: cancel_gate + sourceHandle: 'true' + target: cancel_tool + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: if-else + targetType: answer + id: cancel-false + source: cancel_gate + sourceHandle: 'false' + target: answer_pending_other + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: code + targetType: tool + id: pending-reason-commit + source: pending_reason + sourceHandle: source + target: commit_tool + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: tool + targetType: code + id: commit-parse + source: commit_tool + sourceHandle: source + target: commit_parse + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: code + targetType: answer + id: commit-answer + source: commit_parse + sourceHandle: source + target: answer_commit + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: tool + targetType: code + id: cancel-parse + source: cancel_tool + sourceHandle: source + target: cancel_parse + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: code + targetType: answer + id: cancel-answer + source: cancel_parse + sourceHandle: source + target: answer_cancel + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: question-classifier + targetType: llm + id: classifier-write + source: classifier + sourceHandle: write + target: write_planner + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: llm + targetType: code + id: write-plan-parse + source: write_planner + sourceHandle: source + target: parse_write_plan + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: code + targetType: if-else + id: plan-valid-gate + source: parse_write_plan + sourceHandle: source + target: plan_valid_gate + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: if-else + targetType: tool + id: plan-valid-true + source: plan_valid_gate + sourceHandle: 'true' + target: prepare_tool + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: if-else + targetType: answer + id: plan-valid-false + source: plan_valid_gate + sourceHandle: 'false' + target: answer_write_invalid + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: tool + targetType: code + id: prepare-parse + source: prepare_tool + sourceHandle: source + target: parse_prepare + targetHandle: target + type: custom + zIndex: 0 + - data: + isInIteration: false + isInLoop: false + iteration_id: null + loop_id: null + sourceType: code + targetType: answer + id: prepare-answer + source: parse_prepare + sourceHandle: source + target: answer_write + targetHandle: target + type: custom + zIndex: 0 nodes: - data: answer: '{{#hybrid_agent.text#}}' @@ -349,11 +615,14 @@ workflow: - id: hybrid label: CLASS 3 name: 混合问题:同时需要业务规则或指标口径,以及当前门店实时数据和经营分析 - - id: refuse + - id: write label: CLASS 4 - name: 拒绝:写操作、跨门店查询、无关闲聊、要求绕过权限或模型无法完成的请求 + name: 写操作:创建或修改客户、跟进、日记、事件、库存、订单、收款、履约、积分、套餐、积分兑换,以及允许的取消、拒绝、冲正、退款 + - id: refuse + label: CLASS 5 + name: 拒绝:物理删除、跨门店、越权、系统配置、无关闲聊、要求绕过权限或无法完成的请求 desc: 按问题的数据来源与权限属性路由,分类器不回答业务问题 - instruction: 只按类别定义分类。询问任何实时金额、数量、客户、订单、库存、积分、事件或门店经营结果时,必须归入“实时业务查询”或“混合问题”。 + instruction: 只按类别定义分类。询问制度、SOP、指标口径归入规则;询问当前门店实时数据归入实时查询;同时需要规则和实时数据归入混合;要求创建、修改、核销、收款、履约、库存变动、积分调整、退款、冲正或取消归入写操作;物理删除、跨门店、越权、系统配置和无关请求归入拒绝。 instructions: '' model: completion_params: @@ -386,9 +655,15 @@ workflow: agent_parameters: instruction: type: constant - value: "你是当前店长的门店混合查询 Agent。\n【知识库片段】\n {{#context#}}\n【/知识库片段】\n当前门店:{{#start.storeName#}};当前日期:{{#start.today#}}。\n\ - 先使用知识库结果解释规则和统计口径,再调用最少必要的 GAO 只读 MCP 工具获取实时数据;最多 3 次工具调用。\n不能调用写操作、不能跨店、不能编造数据。回答必须列出时间范围、统计口径、数据生成时间,并区分数据事实和经营建议。\n\ - 已提取参数:timePreset={{#params_hybrid.timePreset#}},startDate={{#params_hybrid.startDate#}},endDate={{#params_hybrid.endDate#}},customerKeyword={{#params_hybrid.customerKeyword#}},productKeyword={{#params_hybrid.productKeyword#}},topN={{#params_hybrid.topN#}}。\n" + value: | + 你是当前店长的门店混合查询 Agent。 + 【知识库片段】 + {{#context#}} + 【/知识库片段】 + 当前门店:{{#start.storeName#}};当前日期:{{#start.today#}}。 + 先使用知识库结果解释规则和统计口径,再调用最少必要的 GAO 只读 MCP 工具获取实时数据;最多 3 次工具调用。 + 不能调用写操作、不能跨店、不能编造数据。回答必须列出时间范围、统计口径、数据生成时间,并区分数据事实和经营建议。 + 已提取参数:timePreset={{#params_hybrid.timePreset#}},startDate={{#params_hybrid.startDate#}},endDate={{#params_hybrid.endDate#}},customerKeyword={{#params_hybrid.customerKeyword#}},productKeyword={{#params_hybrid.productKeyword#}},topN={{#params_hybrid.topN#}}。 model: type: constant value: @@ -726,6 +1001,70 @@ workflow: tool_label: metric_definition tool_name: metric_definition type: mcp + - enabled: true + extra: + description: 查询当前门店履约单,返回订单号、履约请求号、状态和履约时间 + parameters: + aiSessionId: + auto: 0 + value: + type: mixed + value: '{{#start.aiSessionId#}}' + cursor: + auto: 1 + value: null + filters: + auto: 1 + value: null + pageSize: + auto: 1 + value: null + query: + auto: 1 + value: null + timeRange: + auto: 1 + value: null + plugin_id: '' + provider_name: gao-mcp-server-dev + provider_show_name: GAO MCP 服务(开发) + settings: {} + tool_description: 查询当前门店履约单,返回订单号、履约请求号、状态和履约时间 + tool_label: fulfillment_query + tool_name: fulfillment_query + type: mcp + - enabled: true + extra: + description: 查询当前门店客户跟进提醒,返回提醒 ID、客户、内容、提醒时间和状态 + parameters: + aiSessionId: + auto: 0 + value: + type: mixed + value: '{{#start.aiSessionId#}}' + cursor: + auto: 1 + value: null + filters: + auto: 1 + value: null + pageSize: + auto: 1 + value: null + query: + auto: 1 + value: null + timeRange: + auto: 1 + value: null + plugin_id: '' + provider_name: gao-mcp-server-dev + provider_show_name: GAO MCP 服务(开发) + settings: {} + tool_description: 查询当前门店客户跟进提醒,返回提醒 ID、客户、内容、提醒时间和状态 + tool_label: follow_up_query + tool_name: follow_up_query + type: mcp agent_strategy_label: FunctionCalling agent_strategy_name: function_calling agent_strategy_provider_name: langgenius/agent/agent @@ -841,8 +1180,7 @@ workflow: zIndex: 0 - data: desc: 混合问题复用同一套参数,只额外取得规则与口径依据 - instruction: 从用户问题中提取查询条件。日期没有明确范围时,明细查询使用 TODAY,趋势或经营分析使用 MONTH_TO_DATE。不要提取、生成或修改门店 - ID。 + instruction: 从用户问题中提取查询条件。日期没有明确范围时,明细查询使用 TODAY,趋势或经营分析使用 MONTH_TO_DATE。不要提取、生成或修改门店 ID。 model: completion_params: temperature: 0 @@ -899,8 +1237,7 @@ workflow: zIndex: 0 - data: desc: 提取实时查询的通用筛选条件,空值表示使用 MCP 工具默认值 - instruction: 从用户问题中提取查询条件。日期没有明确范围时,明细查询使用 TODAY,趋势或经营分析使用 MONTH_TO_DATE。不要提取、生成或修改门店 - ID。 + instruction: 从用户问题中提取查询条件。日期没有明确范围时,明细查询使用 TODAY,趋势或经营分析使用 MONTH_TO_DATE。不要提取、生成或修改门店 ID。 model: completion_params: temperature: 0 @@ -967,19 +1304,13 @@ workflow: agent_parameters: instruction: type: constant - value: '你是当前店长的门店实时数据查询 Agent。 - + value: | + 你是当前店长的门店实时数据查询 Agent。 当前门店:{{#start.storeName#}};当前日期:{{#start.today#}}。 - 只能使用已绑定的 GAO 只读 MCP 工具;一次最多调用 5 个工具。 - 先根据问题和已提取参数选择最小必要工具。不能调用写操作,不得编造没有工具结果的数据。 - 回答必须包含时间范围、统计口径、数据生成时间;区分数据事实和经营建议。 - 已提取参数:timePreset={{#params_realtime.timePreset#}},startDate={{#params_realtime.startDate#}},endDate={{#params_realtime.endDate#}},customerKeyword={{#params_realtime.customerKeyword#}},productKeyword={{#params_realtime.productKeyword#}},orderNo={{#params_realtime.orderNo#}},eventKeyword={{#params_realtime.eventKeyword#}},topN={{#params_realtime.topN#}}。 - - ' model: type: constant value: @@ -1317,6 +1648,70 @@ workflow: tool_label: metric_definition tool_name: metric_definition type: mcp + - enabled: true + extra: + description: 查询当前门店履约单,返回订单号、履约请求号、状态和履约时间 + parameters: + aiSessionId: + auto: 0 + value: + type: mixed + value: '{{#start.aiSessionId#}}' + cursor: + auto: 1 + value: null + filters: + auto: 1 + value: null + pageSize: + auto: 1 + value: null + query: + auto: 1 + value: null + timeRange: + auto: 1 + value: null + plugin_id: '' + provider_name: gao-mcp-server-dev + provider_show_name: GAO MCP 服务(开发) + settings: {} + tool_description: 查询当前门店履约单,返回订单号、履约请求号、状态和履约时间 + tool_label: fulfillment_query + tool_name: fulfillment_query + type: mcp + - enabled: true + extra: + description: 查询当前门店客户跟进提醒,返回提醒 ID、客户、内容、提醒时间和状态 + parameters: + aiSessionId: + auto: 0 + value: + type: mixed + value: '{{#start.aiSessionId#}}' + cursor: + auto: 1 + value: null + filters: + auto: 1 + value: null + pageSize: + auto: 1 + value: null + query: + auto: 1 + value: null + timeRange: + auto: 1 + value: null + plugin_id: '' + provider_name: gao-mcp-server-dev + provider_show_name: GAO MCP 服务(开发) + settings: {} + tool_description: 查询当前门店客户跟进提醒,返回提醒 ID、客户、内容、提醒时间和状态 + tool_label: follow_up_query + tool_name: follow_up_query + type: mcp agent_strategy_label: FunctionCalling agent_strategy_name: function_calling agent_strategy_provider_name: langgenius/agent/agent @@ -1365,12 +1760,12 @@ workflow: prompt_template: - id: refuse-system role: system - text: 你是门店经营助手。仅支持当前店长所属门店的只读查询与经营分析。明确拒绝创建、修改、核销、退款、库存调整、积分调整、跨门店查询、绕过权限和无关请求;简短说明可支持的查询范围。 + text: 你是门店经营助手。仅支持当前店长所属门店的业务查询、经营分析,以及本工作流已开放的创建、修改、核销、收款、履约、库存变动、积分调整和允许的取消、拒绝、冲正、退款。明确拒绝物理删除、跨门店查询、越权、系统配置、绕过权限和无关请求;简短说明可支持范围。 - id: refuse-user role: user text: '{{#sys.query#}}' selected: false - title: 只读拒绝 + title: 拒绝说明 type: llm variables: [] vision: @@ -1412,9 +1807,18 @@ workflow: prompt_template: - id: rule-system role: system - text: "你是门店经营助手。\n\n【知识库片段】\n {{#context#}}\n【/知识库片段】\n\n仅依据知识库片段回答用户问题。\n\ - 如果片段只包含部分步骤,直接回答片段明确给出的步骤,不要因为信息不完整就说不知道。\n只有知识库片段完全没有相关内容时,才说明未找到对应规则。\n\ - 不得编造知识库没有提供的步骤或实时数据。\n当前日期:{{#start.today#}}" + text: |- + 你是门店经营助手。 + + 【知识库片段】 + {{#context#}} + 【/知识库片段】 + + 仅依据知识库片段回答用户问题。 + 如果片段只包含部分步骤,直接回答片段明确给出的步骤,不要因为信息不完整就说不知道。 + 只有知识库片段完全没有相关内容时,才说明未找到对应规则。 + 不得编造知识库没有提供的步骤或实时数据。 + 当前日期:{{#start.today#}} - id: rule-user role: user text: '{{#sys.query#}}' @@ -1439,7 +1843,7 @@ workflow: width: 242 zIndex: 0 - data: - desc: 后端传入已验证的会话上下文,aiSessionId 仅供 MCP 请求头注入,禁止进入模型上下文 + desc: 后端注入已验证的会话、待确认操作和附件凭证;门店、用户和 token 不进入模型提示词 selected: false title: 开始 type: start @@ -1462,6 +1866,42 @@ workflow: required: true type: text-input variable: today + - label: 待确认操作 Token + max_length: 128 + options: [] + required: false + type: text-input + variable: pendingOperationToken + - label: 待确认操作摘要 + max_length: 2000 + options: [] + required: false + type: paragraph + variable: pendingOperationSummary + - label: 待确认操作风险级别 + max_length: 32 + options: [] + required: false + type: text-input + variable: pendingOperationRisk + - label: 待确认操作精确短语 + max_length: 256 + options: [] + required: false + type: text-input + variable: pendingOperationRequiredPhrase + - label: 待确认操作过期时间 + max_length: 32 + options: [] + required: false + type: text-input + variable: pendingOperationExpiresAt + - label: 附件凭证 JSON + max_length: 4000 + options: [] + required: false + type: paragraph + variable: attachmentTokensJson height: 221 id: start position: @@ -1476,6 +1916,840 @@ workflow: type: custom width: 242 zIndex: 0 + - data: + conditions: + - comparison_operator: not empty + id: pending_gate-condition + value: '' + varType: string + variable_selector: + - start + - pendingOperationToken + desc: 存在待确认操作时,本轮只允许确认或取消,不再进入普通分类器 + logical_operator: and + selected: false + title: 待确认操作拦截 + type: if-else + height: 140 + id: pending_gate + position: + x: 360 + y: 130 + positionAbsolute: + x: 360 + y: 130 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 244 + zIndex: 0 + - data: + code: |2 + + import re + + def normalize(value): + return re.sub(r'[\s,。!?、;:,.!?;:\'"“”‘’]', '', value or '').lower() + + def main(query, required_phrase, risk): + q = normalize(query) + phrase = normalize(required_phrase) + if phrase and q == phrase: + return {"action": "CONFIRM"} + cancel_exact = {"取消", "放弃", "不要", "算了", "不用了", "停止", "不确认", "取消操作", "放弃操作"} + if q in cancel_exact: + return {"action": "CANCEL"} + if risk == "DESTRUCTIVE" or (risk == "SENSITIVE" and phrase): + return {"action": "OTHER"} + cancel_words = ["取消", "放弃", "不要", "算了", "不用了", "停止", "不确认"] + if any(word in q for word in cancel_words): + return {"action": "CANCEL"} + confirm_words = ["确认", "确定", "执行", "可以", "是的", "同意", "好", "办理"] + if any(word in q for word in confirm_words): + return {"action": "CONFIRM"} + return {"action": "OTHER"} + code_language: python3 + desc: 规则匹配确认/取消意图;破坏性和敏感操作只接受精确短语 + outputs: + action: + children: null + type: string + selected: false + title: 判断确认意图 + type: code + variables: + - value_selector: + - sys + - query + variable: query + - value_selector: + - start + - pendingOperationRequiredPhrase + variable: required_phrase + - value_selector: + - start + - pendingOperationRisk + variable: risk + height: 180 + id: pending_action + position: + x: 680 + y: 130 + positionAbsolute: + x: 680 + y: 130 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 320 + zIndex: 0 + - data: + conditions: + - comparison_operator: not empty + id: confirm_gate-condition + value: '' + varType: string + variable_selector: + - pending_action + - action + desc: 仅 action=CONFIRM 时进入提交 + logical_operator: and + selected: false + title: 是否确认 + type: if-else + height: 140 + id: confirm_gate + position: + x: 1000 + y: 130 + positionAbsolute: + x: 1000 + y: 130 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 244 + zIndex: 0 + - data: + code: |2 + + def main(query): + return {"reason": "用户文本确认:" + (query or "")} + code_language: python3 + desc: 文本确认路径把用户原话作为操作原因 + outputs: + reason: + children: null + type: string + selected: false + title: 生成文本确认原因 + type: code + variables: + - value_selector: + - sys + - query + variable: query + height: 180 + id: pending_reason + position: + x: 1320 + y: 40 + positionAbsolute: + x: 1320 + y: 40 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 320 + zIndex: 0 + - data: + desc: 调用独立提交 MCP,只允许传入 token,不接受业务参数 + provider_id: gao-mcp-commit-dev + provider_name: gao-mcp-commit-dev + provider_type: mcp + selected: false + title: 提交待确认操作 + tool_configurations: {} + tool_label: operation_commit + tool_name: operation_commit + tool_node_version: '2' + tool_parameters: + confirmationToken: + type: variable + value: + - start + - pendingOperationToken + confirmationPhrase: + type: variable + value: + - sys + - query + reason: + type: variable + value: + - pending_reason + - reason + aiSessionId: + type: variable + value: + - start + - aiSessionId + type: tool + height: 160 + id: commit_tool + position: + x: 1600 + y: 40 + positionAbsolute: + x: 1600 + y: 40 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 300 + zIndex: 0 + - data: + code: |2 + + import json + + def parse_payload(raw): + if isinstance(raw, dict): + return raw + text = str(raw or '').strip() + if not text: + return {} + try: + payload = json.loads(text) + if isinstance(payload, dict): + return payload + if isinstance(payload, list): + for item in payload: + if isinstance(item, dict): + if isinstance(item.get('json'), dict): + return item['json'] + if isinstance(item.get('text'), str): + try: + candidate = json.loads(item['text']) + if isinstance(candidate, dict): + return candidate + except Exception: + pass + except Exception: + pass + return {} + + def main(raw): + payload = parse_payload(raw) + status = str(payload.get('status') or 'FAILED') + if status == 'SUCCEEDED': + text = payload.get('resultText') or '操作已完成。' + if payload.get('entityNo'): + text += '\n业务单号:' + str(payload.get('entityNo')) + elif status == 'FAILED': + text = '未办理:' + str(payload.get('errorMessage') or '操作失败,请稍后重试。') + if payload.get('errorCode'): + text += '\n错误码:' + str(payload.get('errorCode')) + else: + text = str(payload.get('resultText') or payload.get('errorMessage') or '操作未完成。') + return {'answer_text': text, 'status': status} + code_language: python3 + desc: 只读取后端返回的结构化结果,不让模型改写金额和单号 + outputs: + answer_text: + children: null + type: string + status: + children: null + type: string + selected: false + title: 解析提交结果 + type: code + variables: + - value_selector: + - commit_tool + - text + variable: raw + height: 180 + id: commit_parse + position: + x: 1940 + y: 40 + positionAbsolute: + x: 1940 + y: 40 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 320 + zIndex: 0 + - data: + answer: '{{#commit_parse.answer_text#}}' + desc: '' + selected: false + title: 提交结果 + type: answer + variables: [] + height: 140 + id: answer_commit + position: + x: 2280 + y: 40 + positionAbsolute: + x: 2280 + y: 40 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 260 + zIndex: 0 + - data: + conditions: + - comparison_operator: not empty + id: cancel_gate-condition + value: '' + varType: string + variable_selector: + - pending_action + - action + desc: action=CANCEL 时进入取消 + logical_operator: and + selected: false + title: 是否取消 + type: if-else + height: 140 + id: cancel_gate + position: + x: 1000 + y: 330 + positionAbsolute: + x: 1000 + y: 330 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 244 + zIndex: 0 + - data: + desc: 调用独立提交 MCP 取消待确认操作 + provider_id: gao-mcp-commit-dev + provider_name: gao-mcp-commit-dev + provider_type: mcp + selected: false + title: 取消待确认操作 + tool_configurations: {} + tool_label: operation_cancel + tool_name: operation_cancel + tool_node_version: '2' + tool_parameters: + confirmationToken: + type: variable + value: + - start + - pendingOperationToken + aiSessionId: + type: variable + value: + - start + - aiSessionId + type: tool + height: 150 + id: cancel_tool + position: + x: 1320 + y: 330 + positionAbsolute: + x: 1320 + y: 330 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 300 + zIndex: 0 + - data: + code: |2 + + import json + + def main(raw): + payload = {} + if isinstance(raw, dict): + payload = raw + else: + try: + payload = json.loads(str(raw or '{}')) + except Exception: + payload = {} + if payload.get('status') == 'CANCELLED': + return {'answer_text': '已取消当前待确认操作。'} + return {'answer_text': str(payload.get('errorMessage') or '取消失败,请稍后重试。')} + code_language: python3 + desc: 只输出取消结果 + outputs: + answer_text: + children: null + type: string + selected: false + title: 解析取消结果 + type: code + variables: + - value_selector: + - cancel_tool + - text + variable: raw + height: 180 + id: cancel_parse + position: + x: 1660 + y: 330 + positionAbsolute: + x: 1660 + y: 330 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 320 + zIndex: 0 + - data: + answer: '{{#cancel_parse.answer_text#}}' + desc: '' + selected: false + title: 取消结果 + type: answer + variables: [] + height: 140 + id: answer_cancel + position: + x: 2000 + y: 330 + positionAbsolute: + x: 2000 + y: 330 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 260 + zIndex: 0 + - data: + answer: |- + 当前有待确认操作: + + {{#start.pendingOperationSummary#}} + + 请回复“确认”执行,或回复“取消”放弃。 + 破坏性或敏感操作必须回复完整短语:{{#start.pendingOperationRequiredPhrase#}} + desc: 其他回复不允许绕过确认 + selected: false + title: 待确认操作提示 + type: answer + variables: [] + height: 140 + id: answer_pending_other + position: + x: 1320 + y: 520 + positionAbsolute: + x: 1320 + y: 520 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 260 + zIndex: 0 + - data: + context: + enabled: false + variable_selector: [] + desc: 把自然语言请求转成写操作参数,不执行任何写操作 + model: + completion_params: + temperature: 0.1 + mode: chat + name: deepseek-flash + provider: langgenius/deepseek/deepseek + prompt_template: + - id: write-system + role: system + text: | + 你是门店写操作参数规划器。你的唯一任务是把店长本轮请求转换成写操作准备参数。 + + 只输出一个合法 JSON 对象,不要 Markdown,不要解释。格式: + {"operation":"操作代码","arguments":{},"missingFields":[]} + + 硬性规则: + 1. 只能使用下方操作目录中的 operation,不得创造操作。 + 2. 不得输出 storeId、operatorUserId、requestNo、confirmationToken、operationId、sourceSessionId。 + 3. 客户、订单、产品等尽量使用店长原话中的姓名、编码、单号、名称;缺少必填信息时放入 missingFields。 + 4. 一次只规划一个操作。复合请求拆成“先做哪一个”,只输出第一个。 + 5. 物理删除、跨门店、越权、系统配置、无关请求输出 {"operation":"REFUSE","arguments":{},"missingFields":[]}。 + 6. 金额单位是分;数量使用数字;时间使用毫秒时间戳或 yyyy-MM-dd HH:mm。 + 7. 订单明细使用 itemList 数组;履约明细使用 itemList 数组;不要输出请求号、门店、操作人。 + + 操作目录: + CUSTOMER_CREATE: name 必填;gender(男/女)、birthdate(yyyy-MM-dd)、telephone、address、remark、disease 可选。 + CUSTOMER_UPDATE: customerKeyword 或 customerId 必填;name、gender、birthdate、telephone、address、remark、disease 可选。 + FOLLOW_UP_CREATE: customerKeyword 或 customerId 必填;content 必填;remindAt 或 remindAtText 必填;responsibleUserName 可选,默认当前用户。 + FOLLOW_UP_UPDATE: reminderId 必填;content、remindAt 可选。 + FOLLOW_UP_COMPLETE: reminderId 必填。 + STORE_DIARY_CREATE: title、content 必填。 + STORE_DIARY_UPDATE: diaryId 必填;title、content 可选。 + EVENT_RECORD_CREATE: customerKeyword 或 customerId 必填;eventKeyword 或 eventId 必填;numberValue、pointValue、registeredAt、remark 可选。 + EVENT_RECORD_UPDATE: eventRecordId 必填;remark 可选。 + EVENT_RECORD_VERIFY: eventRecordId 必填。 + STOCK_MANUAL_IN / STOCK_MANUAL_OUT / STOCK_STOCKTAKE_GAIN / STOCK_STOCKTAKE_LOSS: skuKeyword 或 skuId 必填;unitKeyword 或 skuUnitId 可选;quantity 必填;remark 必填。 + SALES_ORDER_CREATE: customerKeyword 或 customerId 必填;itemList 必填,元素 {skuKeyword 或 skuId, unitKeyword 或 skuUnitId, quantity, unitPrice?, remark?};purchasedAt、remark 可选;unitPrice 只有明确改价时输出,并同时输出 overrideReason。 + SALES_ORDER_UPDATE: orderNo 或 salesOrderId 必填;remark 可选。 + SALES_ORDER_CANCEL: orderNo 或 salesOrderId 必填;reason 必填;fulfillmentRevokeList、fulfillmentReturnList、fundRevokeList、fundRefundList 可选;refund 元素 {amount, occurredAt?, remark?}。 + PAYMENT_RECEIVE / PAYMENT_RECEIVE_AND_VERIFY: orderNo 或 salesOrderId 必填;amount 必填;occurredAt、remark 可选。 + PAYMENT_VERIFY / PAYMENT_REJECT / PAYMENT_CANCEL: fundRequestNo 或 fundRecordId 必填;reject/cancel 还需要 reason。 + PAYMENT_REFUND: orderNo 或 salesOrderId 必填;amount、reason 必填;occurredAt、remark 可选。 + FUND_REVOKE: fundRequestNo 或 fundRecordId 必填;reason 必填;occurredAt、remark 可选。 + FULFILLMENT_CREATE / FULFILLMENT_CREATE_AND_VERIFY: orderNo 或 salesOrderId 必填;itemList 可用 fulfillAll=true 代替;remark、deliveredAt 可选。 + FULFILLMENT_VERIFY / FULFILLMENT_REJECT / FULFILLMENT_CANCEL: fulfillmentId,或 orderNo 加 fulfillmentRequestNo;reject/cancel 需要 reason。 + POINT_ADJUST: customerKeyword 或 customerId 必填;pointDelta 必填;remark 必填。 + POINT_REDEMPTION_CREATE: customerKeyword 或 customerId 必填;redeemKeyword 或 redeemSkuId 必填;quantity 必填;actualPointCost、remark 可选。 + CUSTOMER_PACKAGE_PURCHASE: customerKeyword 或 customerId 必填;packageKeyword 或 packageConfigId 必填;saleAmount、reason、itemList、purchasedAt、remark 可选。 + - id: write-user + role: user + text: |- + 当前门店:{{#start.storeName#}} + 当前日期:{{#start.today#}} + 店长请求:{{#sys.query#}} + selected: false + title: 写操作规划 + type: llm + variables: [] + vision: + enabled: false + height: 180 + id: write_planner + position: + x: 680 + y: 1050 + positionAbsolute: + x: 680 + y: 1050 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 320 + zIndex: 0 + - data: + code: |2 + + import json + import re + + ALLOWED = { + 'CUSTOMER_CREATE','CUSTOMER_UPDATE','FOLLOW_UP_CREATE','FOLLOW_UP_UPDATE','FOLLOW_UP_COMPLETE', + 'STORE_DIARY_CREATE','STORE_DIARY_UPDATE','EVENT_RECORD_CREATE','EVENT_RECORD_UPDATE','EVENT_RECORD_VERIFY', + 'STOCK_MANUAL_IN','STOCK_MANUAL_OUT','STOCK_STOCKTAKE_GAIN','STOCK_STOCKTAKE_LOSS', + 'SALES_ORDER_CREATE','SALES_ORDER_UPDATE','SALES_ORDER_CANCEL', + 'PAYMENT_RECEIVE','PAYMENT_RECEIVE_AND_VERIFY','PAYMENT_VERIFY','PAYMENT_REJECT','PAYMENT_CANCEL', + 'PAYMENT_REFUND','FUND_REVOKE','FULFILLMENT_CREATE','FULFILLMENT_CREATE_AND_VERIFY', + 'FULFILLMENT_VERIFY','FULFILLMENT_REJECT','FULFILLMENT_CANCEL','POINT_ADJUST', + 'POINT_REDEMPTION_CREATE','CUSTOMER_PACKAGE_PURCHASE', + } + + def parse_json(raw): + text = str(raw or '').strip() + text = re.sub(r'^```(?:json)?\s*', '', text, flags=re.I) + text = re.sub(r'\s*```$', '', text) + try: + return json.loads(text) + except Exception: + match = re.search(r'\{.*\}', text, re.S) + if match: + try: + return json.loads(match.group()) + except Exception: + pass + return {} + + def main(raw): + payload = parse_json(raw) + operation = str(payload.get('operation') or 'REFUSE').strip().upper() + arguments = payload.get('arguments') if isinstance(payload.get('arguments'), dict) else {} + missing = payload.get('missingFields') if isinstance(payload.get('missingFields'), list) else [] + if operation not in ALLOWED: + return {'operation': 'REFUSE', 'arguments_json': '{}', 'valid': False, + 'error_text': '该请求不在智能助手允许的写操作范围内。', + 'missing_fields_json': '[]'} + return {'operation': operation, + 'arguments_json': json.dumps(arguments, ensure_ascii=False), + 'valid': True, + 'error_text': '', + 'missing_fields_json': json.dumps(missing, ensure_ascii=False)} + code_language: python3 + desc: 校验操作白名单并序列化参数 + outputs: + operation: + children: null + type: string + arguments_json: + children: null + type: string + valid: + children: null + type: boolean + error_text: + children: null + type: string + missing_fields_json: + children: null + type: string + selected: false + title: 校验写操作计划 + type: code + variables: + - value_selector: + - write_planner + - text + variable: raw + height: 180 + id: parse_write_plan + position: + x: 1000 + y: 1050 + positionAbsolute: + x: 1000 + y: 1050 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 320 + zIndex: 0 + - data: + conditions: + - comparison_operator: is + id: plan-valid-condition + value: true + varType: boolean + variable_selector: + - parse_write_plan + - valid + desc: 无效计划直接拒绝,不调用准备工具 + logical_operator: and + selected: false + title: 写操作计划是否有效 + type: if-else + height: 140 + id: plan_valid_gate + position: + x: 1200 + y: 1200 + positionAbsolute: + x: 1200 + y: 1200 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 244 + zIndex: 0 + - data: + answer: '{{#parse_write_plan.error_text#}}' + desc: 无效或越权写操作直接拒绝 + selected: false + title: 写操作拒绝 + type: answer + variables: [] + height: 140 + id: answer_write_invalid + position: + x: 1200 + y: 1380 + positionAbsolute: + x: 1200 + y: 1380 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 260 + zIndex: 0 + - data: + desc: 调用 GAO MCP 准备写操作,只生成预览和确认 token + provider_id: gao-mcp-server-dev + provider_name: gao-mcp-server-dev + provider_type: mcp + selected: false + title: 准备写操作 + tool_configurations: {} + tool_label: operation_prepare + tool_name: operation_prepare + tool_node_version: '2' + tool_parameters: + operation: + type: variable + value: + - parse_write_plan + - operation + argumentsJson: + type: variable + value: + - parse_write_plan + - arguments_json + attachmentTokensJson: + type: variable + value: + - start + - attachmentTokensJson + aiSessionId: + type: variable + value: + - start + - aiSessionId + type: tool + height: 170 + id: prepare_tool + position: + x: 1360 + y: 1050 + positionAbsolute: + x: 1360 + y: 1050 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 320 + zIndex: 0 + - data: + code: |2 + + import json + + def parse_payload(raw): + if isinstance(raw, dict): + return raw + text = str(raw or '').strip() + if not text: + return {} + try: + payload = json.loads(text) + if isinstance(payload, dict): + return payload + if isinstance(payload, list): + for item in payload: + if not isinstance(item, dict): + continue + if isinstance(item.get('json'), dict): + return item['json'] + if isinstance(item.get('text'), str): + try: + candidate = json.loads(item['text']) + if isinstance(candidate, dict): + return candidate + except Exception: + pass + except Exception: + pass + return {} + + def main(raw): + payload = parse_payload(raw) + status = str(payload.get('status') or 'FAILED') + preview = payload.get('previewText') + error = payload.get('errorMessage') + if status == 'PENDING_CONFIRMATION': + text = str(preview or '操作已准备,等待确认。') + elif status == 'NEEDS_CLARIFICATION': + missing = payload.get('missingFields') or [] + text = '还缺少必要信息:' + ('、'.join([str(x) for x in missing]) if missing else str(error or '请补充信息。')) + elif status == 'CANDIDATES': + candidates = payload.get('candidates') or [] + lines = [] + for item in candidates: + if isinstance(item, dict): + lines.append('- ' + ' / '.join([str(v) for v in item.values() if v not in (None, '')])) + else: + lines.append('- ' + str(item)) + text = str(error or '匹配到多个结果,请补充更具体的信息。') + if lines: + text += '\n' + '\n'.join(lines[:8]) + elif status == 'ATTACHMENT_REQUIRED': + text = str(error or '该操作必须上传凭证照片,请先上传后重试。') + elif status == 'PERMISSION_DENIED': + text = str(error or '当前账号缺少办理该操作的权限。') + elif status == 'FEATURE_DISABLED': + text = str(error or '该操作暂未对智能助手开放。') + else: + text = str(error or preview or '操作准备失败,请稍后重试。') + return {'answer_text': text, 'status': status, 'operation_id': payload.get('operationId') or '', + 'error_code': payload.get('errorCode') or ''} + code_language: python3 + desc: 把后端预览、缺失字段、候选和错误转换成用户答复 + outputs: + answer_text: + children: null + type: string + status: + children: null + type: string + operation_id: + children: null + type: string + error_code: + children: null + type: string + selected: false + title: 解析准备结果 + type: code + variables: + - value_selector: + - prepare_tool + - text + variable: raw + height: 180 + id: parse_prepare + position: + x: 1720 + y: 1050 + positionAbsolute: + x: 1720 + y: 1050 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 320 + zIndex: 0 + - data: + answer: '{{#parse_prepare.answer_text#}}' + desc: 直接输出后端预览,不让模型改写金额、单号和状态 + selected: false + title: 写操作答复 + type: answer + variables: [] + height: 140 + id: answer_write + position: + x: 2080 + y: 1050 + positionAbsolute: + x: 2080 + y: 1050 + selected: false + sourcePosition: right + targetPosition: left + type: custom + width: 260 + zIndex: 0 viewport: x: -4.292682679471227 y: 3.141444007269058 diff --git a/src/main/java/com/imyeyu/api/config/RedisConfig.java b/src/main/java/com/imyeyu/api/config/RedisConfig.java index 186d77d..601de34 100644 --- a/src/main/java/com/imyeyu/api/config/RedisConfig.java +++ b/src/main/java/com/imyeyu/api/config/RedisConfig.java @@ -3,6 +3,8 @@ package com.imyeyu.api.config; import com.fasterxml.jackson.databind.ObjectMapper; import com.imyeyu.api.modules.common.entity.Multilingual; import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentToken; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation; import com.imyeyu.api.modules.gao.bean.GaoUserInviteCache; import com.imyeyu.spring.bean.RedisConfigParams; import com.imyeyu.spring.config.AbstractRedisConfig; @@ -187,4 +189,22 @@ public class RedisConfig extends AbstractRedisConfig { public Redis getGaoAiSessionRedisTemplate() { return getRedis(database, RedisSerializers.STRING, RedisSerializers.jacksonSerializer(jackson, GaoAiSession.class)); } + + /// @return AI 待确认操作,token 摘要/公开 ID: 待确认操作 + @Bean("redisGaoAiOperation") + public Redis getGaoAiOperationRedisTemplate() { + return getRedis(database, RedisSerializers.STRING, RedisSerializers.jacksonSerializer(jackson, GaoAiPendingOperation.class)); + } + + /// @return AI 待确认操作索引,用户+门店/来源会话: 公开操作 ID + @Bean("redisGaoAiOperationIndex") + public Redis getGaoAiOperationIndexRedisTemplate() { + return getRedis(database, RedisSerializers.STRING, RedisSerializers.STRING); + } + + /// @return AI 附件凭证,token 摘要: 附件凭证 + @Bean("redisGaoAiAttachment") + public Redis getGaoAiAttachmentRedisTemplate() { + return getRedis(database, RedisSerializers.STRING, RedisSerializers.jacksonSerializer(jackson, GaoAiAttachmentToken.class)); + } } diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/config/GaoAiProperties.java b/src/main/java/com/imyeyu/api/modules/gao/ai/config/GaoAiProperties.java index d184eca..4a2b6b9 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/ai/config/GaoAiProperties.java +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/config/GaoAiProperties.java @@ -29,4 +29,56 @@ public class GaoAiProperties { /// Dify 流式读取空闲超时,单位秒 @Value("${gao.ai.read-timeout-seconds:600}") private long readTimeoutSeconds; + + /// 是否启用智能体写能力 + @Value("${gao.ai.write.enabled:false}") + private boolean writeEnabled; + + /// 待确认操作有效期,单位秒 + @Value("${gao.ai.write.confirmation-ttl-seconds:600}") + private long confirmationTtlSeconds; + + /// 提交结果保留时间,单位秒 + @Value("${gao.ai.write.result-ttl-seconds:1800}") + private long resultTtlSeconds; + + /// 10 分钟内最大准备次数 + @Value("${gao.ai.write.max-prepares-per-10-minutes:10}") + private int maxPreparesPer10Minutes; + + /// 10 分钟内最大提交次数 + @Value("${gao.ai.write.max-commits-per-10-minutes:10}") + private int maxCommitsPer10Minutes; + + /// 单次 AI 会话最大工具调用次数 + @Value("${gao.ai.write.max-tool-calls-per-session:30}") + private int maxToolCallsPerSession; + + /// 单个订单最大成交金额,单位分 + @Value("${gao.ai.write.order-max-sale-amount:1000000}") + private long orderMaxSaleAmount; + + /// 订单/套餐最大折扣率,0.30 表示最多优惠 30% + @Value("${gao.ai.write.max-discount-rate:0.30}") + private double maxDiscountRate; + + /// 单次积分调整最大绝对值 + @Value("${gao.ai.write.point-adjust-max-abs:10000}") + private long pointAdjustMaxAbs; + + /// 单次库存变更最大数量 + @Value("${gao.ai.write.stock-change-max-quantity:1000}") + private long stockChangeMaxQuantity; + + /// 单次操作最大附件数 + @Value("${gao.ai.write.attachment-max-count:10}") + private int attachmentMaxCount; + + /// 单个附件最大大小,单位 MB + @Value("${gao.ai.write.attachment-max-size-mb:10}") + private long attachmentMaxSizeMb; + + /// 附件凭证有效期,单位秒 + @Value("${gao.ai.write.attachment-ttl-seconds:86400}") + private long attachmentTtlSeconds; } diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/controller/GaoAiOperationController.java b/src/main/java/com/imyeyu/api/modules/gao/ai/controller/GaoAiOperationController.java new file mode 100644 index 0000000..3ce10a5 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/controller/GaoAiOperationController.java @@ -0,0 +1,171 @@ +package com.imyeyu.api.modules.gao.ai.controller; + +import com.imyeyu.api.bean.ModuleCode; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentService; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationService; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperationService; +import com.imyeyu.api.modules.gao.ai.vo.GaoAiAttachmentView; +import com.imyeyu.api.modules.gao.ai.vo.GaoAiOperationCommitRequest; +import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult; +import com.imyeyu.api.modules.gao.bean.GaoRoleCode; +import com.imyeyu.api.modules.gao.service.GaoStoreScopeService; +import com.imyeyu.api.modules.user.entity.User; +import com.imyeyu.api.modules.user.service.RoleChecker; +import com.imyeyu.api.modules.user.service.UserLoginService; +import com.imyeyu.java.bean.timi.TimiException; +import com.imyeyu.spring.annotation.RequestRateLimit; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; + +/// GAO 智能体写操作卡片和附件接口 +/// +/// 浏览器只使用登录令牌,不接触确认 token。 +/// +/// @author Codex +/// @since 2026-11-23 +@RestController +@RequiredArgsConstructor +@RequestMapping("/gao/ai") +public class GaoAiOperationController { + + private final GaoAiOperationService operationService; + private final GaoAiPendingOperationService pendingService; + private final GaoAiAttachmentService attachmentService; + private final UserLoginService userLoginService; + private final RoleChecker roleChecker; + private final GaoStoreScopeService storeScopeService; + + /// 上传 AI 操作附件 + /// + /// @param files 文件列表 + /// @param storeId 门店 ID,全局管理员必填 + /// @return 附件凭证 + @RequestRateLimit + @PostMapping(value = "/attachment/upload", consumes = "multipart/form-data") + public List upload(@RequestParam("file") List files, + @RequestParam(required = false) String storeId) { + User user = requireAiUser(); + String resolvedStoreId = resolveStoreId(storeId); + try { + return attachmentService.upload(user.getId(), resolvedStoreId, files).stream() + .map(item -> new GaoAiAttachmentView(item.token(), item.name(), item.mimeType(), item.size(), item.expiresAt())) + .toList(); + } catch (GaoAiOperationException e) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage(), e); + } + } + + /// 查询当前待确认操作 + /// + /// @param conversationId Dify 会话 ID + /// @param storeId 门店 ID,全局管理员必填 + /// @return 待确认操作视图 + @RequestRateLimit + @GetMapping("/operation/pending") + public GaoAiToolResult pending(@RequestParam(required = false) String conversationId, + @RequestParam(required = false) String storeId) { + User user = requireAiUser(); + return operationService.pending(user.getId(), resolveStoreId(storeId), conversationId); + } + + /// 卡片确认提交 + /// + /// @param request 提交请求 + /// @return 提交结果 + @RequestRateLimit + @PostMapping("/operation/commit") + public GaoAiToolResult commit(@RequestBody GaoAiOperationCommitRequest request) { + User user = requireAiUser(); + if (request == null || request.getOperationId() == null || request.getOperationId().isBlank()) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "缺少操作 ID"); + } + try { + GaoAiPendingOperation pending = pendingService.requireByOperationId(request.getOperationId()); + if (!user.getId().equals(pending.getUserId())) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无权操作该待确认操作"); + } + storeScopeService.checkStoreId(pending.getStoreId()); + return operationService.commit(user.getId(), pending.getStoreId(), request.getConversationId(), + request.getOperationId(), request.getConfirmationPhrase(), request.getReason()); + } catch (GaoAiOperationException e) { + return failure(e); + } catch (TimiException e) { + return failure("STORE_SCOPE_DENIED", e.getMessage()); + } + } + + /// 卡片取消 + /// + /// @param request 取消请求 + /// @return 取消结果 + @RequestRateLimit + @PostMapping("/operation/cancel") + public GaoAiToolResult cancel(@RequestBody GaoAiOperationCommitRequest request) { + User user = requireAiUser(); + if (request == null || request.getOperationId() == null || request.getOperationId().isBlank()) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "缺少操作 ID"); + } + try { + GaoAiPendingOperation pending = pendingService.requireByOperationId(request.getOperationId()); + if (!user.getId().equals(pending.getUserId())) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无权操作该待确认操作"); + } + storeScopeService.checkStoreId(pending.getStoreId()); + return operationService.cancel(user.getId(), pending.getStoreId(), request.getOperationId()); + } catch (GaoAiOperationException e) { + return failure(e); + } catch (TimiException e) { + return failure("STORE_SCOPE_DENIED", e.getMessage()); + } + } + + private GaoAiToolResult failure(GaoAiOperationException exception) { + return failure(exception.getErrorCode(), exception.getMessage()); + } + + private GaoAiToolResult failure(String errorCode, String errorMessage) { + GaoAiToolResult result = new GaoAiToolResult(); + result.setStatus("FAILED"); + result.setErrorCode(errorCode); + result.setErrorMessage(errorMessage); + result.setRetryable(false); + return result; + } + + private User requireAiUser() { + User user = userLoginService.getLoginUser(); + if (user == null) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "登录已过期,请重新登录"); + } + if (!roleChecker.hasAny(ModuleCode.GAO, GaoRoleCode.STORE_MANAGER.name())) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "当前账号无权使用门店智能助手"); + } + return user; + } + + private String resolveStoreId(String requestedStoreId) { + try { + String storeId = storeScopeService.resolveStoreId(requestedStoreId); + if (storeId == null || storeId.isBlank()) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "当前账号没有可用的所属门店"); + } + return storeId; + } catch (ResponseStatusException e) { + throw e; + } catch (RuntimeException e) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "当前账号没有可用的所属门店", e); + } + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/entity/GaoAiAuditLog.java b/src/main/java/com/imyeyu/api/modules/gao/ai/entity/GaoAiAuditLog.java index b8abcb7..c484042 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/ai/entity/GaoAiAuditLog.java +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/entity/GaoAiAuditLog.java @@ -37,4 +37,37 @@ public class GaoAiAuditLog { /// 记录时间,单位毫秒 private long createdAt; + + /// 审计动作 + private String action; + + /// 写操作代码 + private String operation; + + /// 公开操作 ID + private String operationId; + + /// 幂等请求号 + private String requestNo; + + /// 确认 token 摘要 + private String confirmationTokenDigest; + + /// 风险级别 + private String riskLevel; + + /// 结果实体类型 + private String entityType; + + /// 结果实体 ID + private String entityId; + + /// 错误码 + private String errorCode; + + /// true 为幂等重放 + private boolean idempotentReplay; + + /// 原因摘要 + private String reasonDigest; } diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/entity/GaoAiSession.java b/src/main/java/com/imyeyu/api/modules/gao/ai/entity/GaoAiSession.java index 0584000..b46c82d 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/ai/entity/GaoAiSession.java +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/entity/GaoAiSession.java @@ -28,7 +28,7 @@ public class GaoAiSession { /// Dify 会话 ID,可为空 private String difyConversationId; - /// 允许调用的只读工具 + /// 允许调用的工具 private Set allowedTools = new LinkedHashSet<>(); /// 过期时间,单位毫秒 diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiMcpAuthentication.java b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiMcpAuthentication.java index 4982419..72f1bf9 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiMcpAuthentication.java +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiMcpAuthentication.java @@ -32,7 +32,20 @@ public class GaoAiMcpAuthentication { /// @param toolName 工具名称,可为空 /// @return 已认证会话 public GaoAiSession authenticate(String authorization, String headerSessionId, String argumentSessionId, String toolName) { - authenticateService(authorization); + return authenticate(authorization, headerSessionId, argumentSessionId, toolName, false); + } + + /// 校验 Dify 服务密钥和 AI 会话 + /// + /// @param authorization Authorization 请求头 + /// @param headerSessionId X-Timi-AI-Session 请求头 + /// @param argumentSessionId MCP 工具参数中的 AI 会话 ID + /// @param toolName 工具名称,可为空 + /// @param commit true 为提交 Provider + /// @return 已认证会话 + public GaoAiSession authenticate(String authorization, String headerSessionId, String argumentSessionId, + String toolName, boolean commit) { + authenticateService(authorization, commit); String sessionId = headerSessionId; if (isBlank(sessionId) && !isBlank(argumentSessionId)) { sessionId = argumentSessionId; @@ -50,9 +63,22 @@ public class GaoAiMcpAuthentication { /// /// @param authorization Authorization 请求头 public void authenticateService(String authorization) { - String key = settingService.getSystem(GaoSystemSetting.DIFY_MCP_SERVICE_KEY).asString(); + authenticateService(authorization, false); + } + + /// 只校验 Dify 服务间密钥 + /// + /// @param authorization Authorization 请求头 + /// @param commit true 为提交 Provider + public void authenticateService(String authorization, boolean commit) { + String key = commit + ? settingService.getSystem(GaoSystemSetting.DIFY_MCP_COMMIT_SERVICE_KEY).asString() + : settingService.getSystem(GaoSystemSetting.DIFY_MCP_SERVICE_KEY).asString(); + if (commit && (key == null || key.isEmpty())) { + throw new GaoAiSessionException("MCP 提交服务密钥未配置", 503); + } String actualKey = bearerValue(authorization); - if (key.isEmpty() || actualKey.isEmpty() || !constantTimeEquals(key, actualKey)) { + if (key == null || key.isEmpty() || actualKey.isEmpty() || !constantTimeEquals(key, actualKey)) { throw new GaoAiSessionException("MCP 服务认证失败", 401); } } diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiMcpCommitController.java b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiMcpCommitController.java new file mode 100644 index 0000000..510af03 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiMcpCommitController.java @@ -0,0 +1,252 @@ +package com.imyeyu.api.modules.gao.ai.mcp; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; +import com.imyeyu.api.modules.gao.ai.mcp.tool.GaoAiWriteTool; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException; +import com.imyeyu.api.modules.gao.ai.service.GaoAiSessionService; +import com.imyeyu.api.modules.gao.ai.service.GaoAiToolException; +import com.imyeyu.api.modules.gao.ai.service.implement.GaoAiSessionServiceImplement.GaoAiSessionException; +import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult; +import com.imyeyu.api.modules.user.context.ExecutionIdentityContext; +import com.imyeyu.spring.annotation.IgnoreGlobalReturn; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +/// GAO 智能体提交 MCP 接口 +/// +/// 使用独立服务密钥,只暴露提交和取消工具,不允许绑定到 Agent 节点。 +/// +/// @author Codex +/// @since 2026-11-23 +@Slf4j +@RestController +@RequestMapping("/mcp/gao-ai-commit") +public class GaoAiMcpCommitController { + + private final ObjectMapper jackson; + private final GaoAiMcpAuthentication authentication; + private final GaoAiSessionService sessionService; + private final Map toolMap; + + public GaoAiMcpCommitController(ObjectMapper jackson, GaoAiMcpAuthentication authentication, + GaoAiSessionService sessionService, List toolList) { + this.jackson = jackson; + this.authentication = authentication; + this.sessionService = sessionService; + this.toolMap = toolList.stream() + .filter(tool -> tool.provider() == GaoAiWriteTool.Provider.COMMIT) + .collect(Collectors.toUnmodifiableMap(GaoAiWriteTool::name, Function.identity())); + } + + /// 处理提交 MCP JSON-RPC 请求 + /// + /// @param authorization 提交服务密钥 + /// @param aiSessionId AI 会话头 + /// @param request JSON-RPC 请求 + /// @return JSON-RPC 响应 + @IgnoreGlobalReturn + @PostMapping + public ResponseEntity handle( + @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization, + @RequestHeader(value = "X-Timi-AI-Session", required = false) String aiSessionId, + @RequestBody JsonNode request) { + JsonNode id = request == null ? null : request.get("id"); + String method = text(request, "method"); + String toolName = text(request == null ? null : request.path("params"), "name"); + try { + if (request == null || !request.isObject()) { + return response(400, error(id, -32600, "MCP 请求格式无效")); + } + if (method == null) { + return response(400, error(id, -32600, "MCP 请求缺少 method")); + } + return switch (method) { + case "initialize" -> { + authentication.authenticateService(authorization, true); + yield response(200, success(id, initializeResult())); + } + case "notifications/initialized", "ping" -> { + authentication.authenticateService(authorization, true); + yield response(200, success(id, Map.of())); + } + case "tools/list" -> { + authentication.authenticateService(authorization, true); + yield response(200, success(id, toolsResult())); + } + case "tools/call" -> { + JsonNode params = request.path("params"); + String argumentSessionId = text(params.path("arguments"), "aiSessionId"); + GaoAiSession session = authentication.authenticate(authorization, aiSessionId, + argumentSessionId, text(params, "name"), true); + yield response(200, success(id, executeTool(session, params, aiSessionId))); + } + default -> response(400, error(id, -32601, "MCP 方法不支持")); + }; + } catch (GaoAiSessionException e) { + log.warn("GAO MCP 提交认证失败:method={}, toolName={}, status={}, reason={}", + method, toolName, e.getStatus(), e.getMessage()); + return response(e.getStatus(), error(id, -32001, e.getMessage())); + } catch (GaoAiToolException e) { + log.warn("GAO MCP 提交工具失败:method={}, toolName={}, status={}, reason={}", + method, toolName, e.getStatus(), e.getMessage()); + return response(e.getStatus(), error(id, -32602, e.getMessage())); + } catch (RuntimeException e) { + log.warn("GAO 智能体提交 MCP 请求失败", e); + return response(500, error(id, -32603, "智能体操作提交失败,请稍后重试")); + } + } + + private Object executeTool(GaoAiSession session, JsonNode params, String aiSessionId) { + if (params == null || !params.isObject()) { + throw new GaoAiToolException("工具参数格式无效", 400); + } + String toolName = text(params, "name"); + GaoAiWriteTool tool = toolMap.get(toolName); + if (tool == null) { + throw new GaoAiToolException("工具不存在或未启用", 403); + } + JsonNode arguments = params.has("arguments") ? params.get("arguments") : jackson.createObjectNode(); + if (arguments == null || !arguments.isObject()) { + throw new GaoAiToolException("工具参数格式无效", 400); + } + ObjectNode businessArguments = ((ObjectNode) arguments).deepCopy(); + businessArguments.remove("aiSessionId"); + if (containsField(businessArguments, "storeId")) { + throw new GaoAiToolException("工具请求不允许携带 storeId", 403); + } + try { + GaoAiToolResult result = ExecutionIdentityContext.runAs(session.getUserId(), "GAO_AI_MCP_COMMIT", + session.getSessionId(), () -> tool.execute(session, businessArguments)); + if (hasText(aiSessionId)) { + sessionService.increaseUsedCount(aiSessionId); + } + return mapResult(result); + } catch (GaoAiOperationException e) { + return mapFailure(e); + } + } + + private Map mapResult(GaoAiToolResult result) { + if (result == null) { + result = new GaoAiToolResult(); + result.setStatus("FAILED"); + result.setErrorCode("INTERNAL_ERROR"); + result.setErrorMessage("工具未返回结果"); + } + Map content = new LinkedHashMap<>(); + content.put("type", "text"); + content.put("text", writeJson(result)); + return Map.of("content", List.of(content), "structuredContent", result); + } + + private Map mapFailure(GaoAiOperationException exception) { + GaoAiToolResult result = new GaoAiToolResult(); + result.setStatus("FAILED"); + result.setErrorCode(exception.getErrorCode()); + result.setErrorMessage(exception.getMessage()); + result.setRetryable(exception.isRetryable()); + result.setCandidates(exception.getCandidates()); + result.setMissingFields(exception.getMissingFields()); + return mapResult(result); + } + + private Map initializeResult() { + Map result = new LinkedHashMap<>(); + result.put("protocolVersion", "2025-03-26"); + result.put("capabilities", Map.of("tools", Map.of("listChanged", false))); + result.put("serverInfo", Map.of("name", "TimiServerAPI-GAO-AI-COMMIT", "version", "1.0")); + return result; + } + + private Map toolsResult() { + List> tools = new ArrayList<>(); + for (GaoAiWriteTool tool : toolMap.values()) { + Map item = new LinkedHashMap<>(); + item.put("name", tool.name()); + item.put("description", tool.description()); + item.put("inputSchema", tool.inputSchema()); + tools.add(item); + } + return Map.of("tools", tools); + } + + private ResponseEntity response(int status, Object body) { + return ResponseEntity.status(status).body(body); + } + + private Map success(JsonNode id, Object result) { + Map response = new LinkedHashMap<>(); + response.put("jsonrpc", "2.0"); + response.put("id", id); + response.put("result", result); + return response; + } + + private Map error(JsonNode id, int code, String message) { + Map response = new LinkedHashMap<>(); + response.put("jsonrpc", "2.0"); + response.put("id", id); + response.put("error", Map.of("code", code, "message", message)); + return response; + } + + private String text(JsonNode node, String field) { + if (node == null || !node.hasNonNull(field)) { + return null; + } + String value = node.get(field).asText(); + return value == null || value.trim().isEmpty() ? null : value.trim(); + } + + private boolean hasText(String value) { + return value != null && !value.trim().isEmpty(); + } + + private boolean containsField(JsonNode node, String field) { + if (node == null) { + return false; + } + if (node.isObject()) { + if (node.has(field)) { + return true; + } + for (JsonNode child : node) { + if (containsField(child, field)) { + return true; + } + } + } + if (node.isArray()) { + for (JsonNode child : node) { + if (containsField(child, field)) { + return true; + } + } + } + return false; + } + + private String writeJson(Object value) { + try { + return jackson.writeValueAsString(value); + } catch (Exception e) { + throw new GaoAiToolException("工具结果序列化失败", 500); + } + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiMcpController.java b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiMcpController.java index e68a98f..f8b521c 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiMcpController.java +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiMcpController.java @@ -6,12 +6,15 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.imyeyu.api.modules.gao.ai.entity.GaoAiAuditLog; import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; import com.imyeyu.api.modules.gao.ai.mcp.tool.GaoAiTool; +import com.imyeyu.api.modules.gao.ai.mcp.tool.GaoAiWriteTool; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException; import com.imyeyu.api.modules.gao.ai.service.GaoAiAuditService; import com.imyeyu.api.modules.gao.ai.service.GaoAiSessionService; import com.imyeyu.api.modules.gao.ai.service.GaoAiToolException; import com.imyeyu.api.modules.gao.ai.service.implement.GaoAiSessionServiceImplement.GaoAiSessionException; import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest; import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult; +import com.imyeyu.api.modules.user.context.ExecutionIdentityContext; import com.imyeyu.spring.annotation.IgnoreGlobalReturn; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; @@ -30,7 +33,7 @@ import java.util.stream.Collectors; /// GAO 智能体 MCP Streamable HTTP 接口 /// -/// Dify 通过 Docker 内网访问本接口,业务查询只允许调用已注册的只读工具 +/// 主 Provider 暴露只读工具和写操作准备工具;提交工具使用独立 Provider。 /// /// @author Codex /// @since 2026-09-15 @@ -44,14 +47,19 @@ public class GaoAiMcpController { private final GaoAiSessionService sessionService; private final GaoAiAuditService auditService; private final Map toolMap; + private final Map writeToolMap; public GaoAiMcpController(ObjectMapper jackson, GaoAiMcpAuthentication authentication, - GaoAiSessionService sessionService, GaoAiAuditService auditService, List toolList) { + GaoAiSessionService sessionService, GaoAiAuditService auditService, List toolList, + List writeToolList) { this.jackson = jackson; this.authentication = authentication; this.sessionService = sessionService; this.auditService = auditService; this.toolMap = toolList.stream().collect(Collectors.toUnmodifiableMap(GaoAiTool::name, Function.identity())); + this.writeToolMap = writeToolList.stream() + .filter(tool -> tool.provider() == GaoAiWriteTool.Provider.MAIN) + .collect(Collectors.toUnmodifiableMap(GaoAiWriteTool::name, Function.identity())); } /// 处理 MCP JSON-RPC 请求 @@ -120,11 +128,7 @@ public class GaoAiMcpController { throw new GaoAiToolException("工具参数格式无效", 400); } String toolName = text(params, "name"); - GaoAiTool tool = toolMap.get(toolName); - if (tool == null) { - throw new GaoAiToolException("工具不存在或未启用", 403); - } - JsonNode arguments = params == null || !params.has("arguments") ? jackson.createObjectNode() : params.get("arguments"); + JsonNode arguments = params.has("arguments") ? params.get("arguments") : jackson.createObjectNode(); if (arguments == null || !arguments.isObject()) { throw new GaoAiToolException("工具参数格式无效", 400); } @@ -133,13 +137,45 @@ public class GaoAiMcpController { if (containsField(businessArguments, "storeId")) { throw new GaoAiToolException("工具请求不允许携带 storeId", 403); } + long startedAt = System.currentTimeMillis(); + GaoAiWriteTool writeTool = writeToolMap.get(toolName); + if (writeTool != null) { + try { + GaoAiToolResult result = ExecutionIdentityContext.runAs(session.getUserId(), "GAO_AI_MCP", + session.getSessionId(), () -> writeTool.execute(session, businessArguments)); + if (result == null) { + result = new GaoAiToolResult(); + result.setStatus("FAILED"); + result.setErrorCode("INTERNAL_ERROR"); + result.setErrorMessage("工具未返回结果"); + } + long duration = System.currentTimeMillis() - startedAt; + if (hasText(aiSessionId)) { + sessionService.increaseUsedCount(aiSessionId); + } + recordAudit(session, null, toolName, duration, "SUCCESS", 0L); + Map content = new LinkedHashMap<>(); + content.put("type", "text"); + content.put("text", writeJson(result)); + return Map.of("content", List.of(content), "structuredContent", result); + } catch (GaoAiOperationException e) { + recordAudit(session, null, toolName, System.currentTimeMillis() - startedAt, "ERROR", 0L); + return structuredFailure(e); + } catch (RuntimeException e) { + recordAudit(session, null, toolName, System.currentTimeMillis() - startedAt, "ERROR", 0L); + throw e; + } + } + GaoAiTool tool = toolMap.get(toolName); + if (tool == null) { + throw new GaoAiToolException("工具不存在或未启用", 403); + } GaoAiToolRequest request; try { request = jackson.treeToValue(businessArguments, GaoAiToolRequest.class); } catch (Exception e) { throw new GaoAiToolException("工具参数格式无效", 400); } - long startedAt = System.currentTimeMillis(); try { GaoAiToolResult result = tool.execute(session, request); long duration = System.currentTimeMillis() - startedAt; @@ -160,6 +196,20 @@ public class GaoAiMcpController { } } + private Map structuredFailure(GaoAiOperationException exception) { + GaoAiToolResult result = new GaoAiToolResult(); + result.setStatus("FAILED"); + result.setErrorCode(exception.getErrorCode()); + result.setErrorMessage(exception.getMessage()); + result.setRetryable(exception.isRetryable()); + result.setCandidates(exception.getCandidates()); + result.setMissingFields(exception.getMissingFields()); + Map content = new LinkedHashMap<>(); + content.put("type", "text"); + content.put("text", writeJson(result)); + return Map.of("content", List.of(content), "structuredContent", result); + } + private Map initializeResult() { Map result = new LinkedHashMap<>(); result.put("protocolVersion", "2025-03-26"); @@ -169,17 +219,24 @@ public class GaoAiMcpController { } private Map toolsResult() { - List> tools = toolMap.values().stream() - .map(tool -> { - Map item = new LinkedHashMap<>(); - item.put("name", tool.name()); - item.put("description", tool.description()); - item.put("inputSchema", tool.inputSchema()); - return item; - }).toList(); + List> tools = new java.util.ArrayList<>(); + for (GaoAiTool tool : toolMap.values()) { + tools.add(toolDescriptor(tool.name(), tool.description(), tool.inputSchema())); + } + for (GaoAiWriteTool tool : writeToolMap.values()) { + tools.add(toolDescriptor(tool.name(), tool.description(), tool.inputSchema())); + } return Map.of("tools", tools); } + private Map toolDescriptor(String name, String description, Map inputSchema) { + Map item = new LinkedHashMap<>(); + item.put("name", name); + item.put("description", description); + item.put("inputSchema", inputSchema); + return item; + } + private void recordAudit(GaoAiSession session, GaoAiToolRequest request, String toolName, long duration, String status, long resultCount) { GaoAiAuditLog audit = new GaoAiAuditLog(); diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiToolNames.java b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiToolNames.java index d6f94d8..2e570cb 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiToolNames.java +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/GaoAiToolNames.java @@ -4,7 +4,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -/// GAO 智能体只读工具名称 +/// GAO 智能体 MCP 工具名称 /// /// @author Codex /// @since 2026-09-15 @@ -20,6 +20,12 @@ public final class GaoAiToolNames { public static final String BUSINESS_REPORT = "business_report"; public static final String STORE_DIARY_QUERY = "store_diary_query"; public static final String METRIC_DEFINITION = "metric_definition"; + public static final String FULFILLMENT_QUERY = "fulfillment_query"; + public static final String FOLLOW_UP_QUERY = "follow_up_query"; + + public static final String OPERATION_PREPARE = "operation_prepare"; + public static final String OPERATION_COMMIT = "operation_commit"; + public static final String OPERATION_CANCEL = "operation_cancel"; public static final Set READ_ONLY_TOOLS = java.util.Collections.unmodifiableSet(new LinkedHashSet<>(List.of( STORE_OVERVIEW, @@ -31,16 +37,38 @@ public final class GaoAiToolNames { POINT_QUERY, BUSINESS_REPORT, STORE_DIARY_QUERY, - METRIC_DEFINITION + METRIC_DEFINITION, + FULFILLMENT_QUERY, + FOLLOW_UP_QUERY ))); + public static final Set PREPARE_TOOLS = java.util.Collections.unmodifiableSet( + new LinkedHashSet<>(List.of(OPERATION_PREPARE))); + + public static final Set COMMIT_TOOLS = java.util.Collections.unmodifiableSet( + new LinkedHashSet<>(List.of(OPERATION_COMMIT, OPERATION_CANCEL))); + private GaoAiToolNames() { } - /// 生成稳定的工具顺序 + /// 生成模型可见的查询和准备工具 /// /// @return 工具名称集合 - public static Set orderedReadOnlyTools() { - return new LinkedHashSet<>(READ_ONLY_TOOLS); + public static Set orderedModelTools() { + Set result = new LinkedHashSet<>(READ_ONLY_TOOLS); + result.addAll(PREPARE_TOOLS); + return result; + } + + /// 生成会话允许的全部工具 + /// + /// 主 MCP 只暴露查询和准备工具,提交 Provider 单独使用提交工具。 + /// + /// @return 工具名称集合 + public static Set orderedSessionTools() { + Set result = new LinkedHashSet<>(READ_ONLY_TOOLS); + result.addAll(PREPARE_TOOLS); + result.addAll(COMMIT_TOOLS); + return result; } } diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/FollowUpQueryTool.java b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/FollowUpQueryTool.java new file mode 100644 index 0000000..bed0f74 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/FollowUpQueryTool.java @@ -0,0 +1,96 @@ +package com.imyeyu.api.modules.gao.ai.mcp.tool; + +import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; +import com.imyeyu.api.modules.gao.ai.mcp.GaoAiToolNames; +import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest; +import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult; +import com.imyeyu.api.modules.gao.entity.GaoCustomer; +import com.imyeyu.api.modules.gao.entity.GaoCustomerFollowUpReminder; +import com.imyeyu.api.modules.gao.service.GaoCustomerFollowUpReminderService; +import com.imyeyu.api.modules.gao.service.GaoCustomerService; +import com.imyeyu.api.modules.gao.vo.customer.GaoCustomerFollowUpReminderPage; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// 客户跟进提醒查询工具 +/// +/// @author Codex +/// @since 2026-11-23 +@Component +@RequiredArgsConstructor +public class FollowUpQueryTool implements GaoAiTool { + + private static final ZoneId ZONE = ZoneId.systemDefault(); + private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + + private final GaoCustomerFollowUpReminderService followUpService; + private final GaoCustomerService customerService; + + @Override + public String name() { + return GaoAiToolNames.FOLLOW_UP_QUERY; + } + + @Override + public String description() { + return "查询当前门店客户跟进提醒,返回提醒 ID、客户、内容、提醒时间和状态"; + } + + @Override + public GaoAiToolResult execute(GaoAiSession session, GaoAiToolRequest request) { + GaoCustomerFollowUpReminderPage page = new GaoCustomerFollowUpReminderPage(); + page.setStoreId(session.getStoreId()); + page.setCustomerId(filter(request, "customerId")); + String status = filter(request, "status"); + if (status != null) { + try { + page.setStatus(GaoCustomerFollowUpReminder.Status.valueOf(status.trim().toUpperCase())); + } catch (RuntimeException e) { + throw new com.imyeyu.api.modules.gao.ai.service.GaoAiToolException("跟进状态无效", 400); + } + } + page.setSize(Math.max(1, Math.min(20, request.getPageSize() == null ? 10 : request.getPageSize()))); + var result = followUpService.pageByQuery(page); + List list = result == null || result.getList() == null ? List.of() : result.getList(); + Map customerMap = customerService.mapByIdList(list.stream() + .map(GaoCustomerFollowUpReminder::getCustomerId).distinct().toList()); + List details = list.stream().map(item -> { + GaoCustomer customer = customerMap.get(item.getCustomerId()); + Map detail = new LinkedHashMap<>(); + detail.put("reminderId", item.getId()); + detail.put("customerId", item.getCustomerId()); + detail.put("customerName", customer == null ? null : customer.getName()); + detail.put("content", item.getContent()); + detail.put("remindAt", dateTime(item.getRemindAt())); + detail.put("status", item.getStatus()); + return (Object) detail; + }).toList(); + GaoAiToolResult toolResult = new GaoAiToolResult(); + toolResult.getSummary().put("total", result == null ? 0L : result.getTotal()); + toolResult.getSummary().put("returnedCount", details.size()); + toolResult.setDetails(details); + toolResult.getSource().put("metric", "客户跟进提醒"); + toolResult.getSource().put("generatedAt", Instant.now().atZone(ZONE).toOffsetDateTime().toString()); + return toolResult; + } + + private String filter(GaoAiToolRequest request, String key) { + if (request == null || request.getFilters() == null) { + return null; + } + Object value = request.getFilters().get(key); + return value == null || value.toString().isBlank() ? null : value.toString().trim(); + } + + private String dateTime(Long millis) { + return millis == null ? null : LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZONE).format(DATE_TIME); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/FulfillmentQueryTool.java b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/FulfillmentQueryTool.java new file mode 100644 index 0000000..952a4fb --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/FulfillmentQueryTool.java @@ -0,0 +1,120 @@ +package com.imyeyu.api.modules.gao.ai.mcp.tool; + +import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; +import com.imyeyu.api.modules.gao.ai.mcp.GaoAiToolNames; +import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest; +import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult; +import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment; +import com.imyeyu.api.modules.gao.entity.GaoSalesOrder; +import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService; +import com.imyeyu.api.modules.gao.service.GaoSalesOrderService; +import com.imyeyu.api.modules.gao.vo.order.GaoOrderFulfillmentPage; +import com.imyeyu.api.modules.gao.vo.salesorder.GaoSalesOrderPage; +import com.imyeyu.spring.bean.PageResult; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// 履约查询工具 +/// +/// 返回订单号和履约请求号,供写操作按业务号定位履约单。 +/// +/// @author Codex +/// @since 2026-11-23 +@Component +@RequiredArgsConstructor +public class FulfillmentQueryTool implements GaoAiTool { + + private static final ZoneId ZONE = ZoneId.systemDefault(); + private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + + private final GaoOrderFulfillmentService fulfillmentService; + private final GaoSalesOrderService salesOrderService; + + @Override + public String name() { + return GaoAiToolNames.FULFILLMENT_QUERY; + } + + @Override + public String description() { + return "查询当前门店履约单,返回订单号、履约请求号、状态和履约时间"; + } + + @Override + public GaoAiToolResult execute(GaoAiSession session, GaoAiToolRequest request) { + GaoOrderFulfillmentPage page = new GaoOrderFulfillmentPage(); + page.setStoreId(session.getStoreId()); + page.setOrderAllowed(true); + page.setSalesOrderId(filter(request, "salesOrderId")); + page.setCustomerId(filter(request, "customerId")); + String orderNo = filter(request, "orderNo", "keyword"); + if (orderNo != null && page.getSalesOrderId() == null) { + GaoSalesOrderPage orderPage = new GaoSalesOrderPage(); + orderPage.setStoreId(session.getStoreId()); + orderPage.setKeyword(orderNo); + orderPage.setOrderAllowed(true); + orderPage.setSize(2); + PageResult orderResult = salesOrderService.pageByQuery(orderPage); + if (orderResult != null && orderResult.getList() != null && !orderResult.getList().isEmpty()) { + page.setSalesOrderId(orderResult.getList().getFirst().getId()); + } + } + String status = filter(request, "status"); + if (status != null) { + try { + page.setStatus(GaoOrderFulfillment.Status.valueOf(status.trim().toUpperCase())); + } catch (RuntimeException e) { + throw new com.imyeyu.api.modules.gao.ai.service.GaoAiToolException("履约状态无效", 400); + } + } + page.setSize(Math.max(1, Math.min(20, request.getPageSize() == null ? 10 : request.getPageSize()))); + PageResult result = fulfillmentService.pageByQuery(page); + List list = result == null || result.getList() == null ? List.of() : result.getList(); + Map orderMap = salesOrderService.mapByIdList(list.stream() + .map(GaoOrderFulfillment::getSalesOrderId).distinct().toList()); + List details = list.stream().map(item -> { + GaoSalesOrder order = orderMap.get(item.getSalesOrderId()); + Map detail = new LinkedHashMap<>(); + detail.put("fulfillmentId", item.getId()); + detail.put("orderNo", order == null ? null : order.getOrderNo()); + detail.put("salesOrderId", item.getSalesOrderId()); + detail.put("requestNo", item.getRequestNo()); + detail.put("status", item.getStatus()); + detail.put("deliveredAt", dateTime(item.getDeliveredAt())); + detail.put("remark", item.getRemark()); + return (Object) detail; + }).toList(); + GaoAiToolResult toolResult = new GaoAiToolResult(); + toolResult.getSummary().put("total", result == null ? 0L : result.getTotal()); + toolResult.getSummary().put("returnedCount", details.size()); + toolResult.setDetails(details); + toolResult.getSource().put("metric", "履约单、订单号和履约请求号"); + toolResult.getSource().put("generatedAt", Instant.now().atZone(ZONE).toOffsetDateTime().toString()); + return toolResult; + } + + private String filter(GaoAiToolRequest request, String... keys) { + if (request == null || request.getFilters() == null) { + return null; + } + for (String key : keys) { + Object value = request.getFilters().get(key); + if (value != null && !value.toString().isBlank()) { + return value.toString().trim(); + } + } + return null; + } + + private String dateTime(Long millis) { + return millis == null ? null : LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZONE).format(DATE_TIME); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/GaoAiWriteTool.java b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/GaoAiWriteTool.java new file mode 100644 index 0000000..a2cc6df --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/GaoAiWriteTool.java @@ -0,0 +1,43 @@ +package com.imyeyu.api.modules.gao.ai.mcp.tool; + +import com.fasterxml.jackson.databind.JsonNode; +import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; +import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult; + +import java.util.Map; + +/// GAO 智能体写工具 +/// +/// @author Codex +/// @since 2026-11-23 +public interface GaoAiWriteTool { + + /// 工具提供方 + enum Provider { + + /// 主 MCP,模型可见 + MAIN, + + /// 提交 MCP,只允许确定性工具节点调用 + COMMIT + } + + /// @return 工具名称 + String name(); + + /// @return 工具描述 + String description(); + + /// @return 工具提供方 + Provider provider(); + + /// @return MCP 输入参数结构 + Map inputSchema(); + + /// 执行工具 + /// + /// @param session 已认证会话 + /// @param arguments 已移除 aiSessionId 的业务参数 + /// @return 工具结果 + GaoAiToolResult execute(GaoAiSession session, JsonNode arguments); +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/OperationCancelTool.java b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/OperationCancelTool.java new file mode 100644 index 0000000..167a108 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/OperationCancelTool.java @@ -0,0 +1,59 @@ +package com.imyeyu.api.modules.gao.ai.mcp.tool; + +import com.fasterxml.jackson.databind.JsonNode; +import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; +import com.imyeyu.api.modules.gao.ai.mcp.GaoAiToolNames; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationService; +import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.util.LinkedHashMap; +import java.util.Map; + +/// GAO 智能体待确认操作取消工具 +/// +/// @author Codex +/// @since 2026-11-23 +@Component +@RequiredArgsConstructor +public class OperationCancelTool implements GaoAiWriteTool { + + private final GaoAiOperationService operationService; + + @Override + public String name() { + return GaoAiToolNames.OPERATION_CANCEL; + } + + @Override + public String description() { + return "取消一个待确认写操作。只接受 confirmationToken,不产生业务副作用。"; + } + + @Override + public Provider provider() { + return Provider.COMMIT; + } + + @Override + public Map inputSchema() { + Map properties = new LinkedHashMap<>(); + properties.put("confirmationToken", Map.of("type", "string", "description", "服务端签发的确认 token")); + properties.put("aiSessionId", Map.of("type", "string", "description", "AI 会话 ID")); + return Map.of("type", "object", "properties", properties, "additionalProperties", false); + } + + @Override + public GaoAiToolResult execute(GaoAiSession session, JsonNode arguments) { + return operationService.cancel(session, text(arguments, "confirmationToken")); + } + + private String text(JsonNode node, String field) { + if (node == null || !node.hasNonNull(field)) { + return null; + } + String value = node.get(field).asText(); + return value == null || value.isBlank() ? null : value.trim(); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/OperationCommitTool.java b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/OperationCommitTool.java new file mode 100644 index 0000000..6731eb4 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/OperationCommitTool.java @@ -0,0 +1,65 @@ +package com.imyeyu.api.modules.gao.ai.mcp.tool; + +import com.fasterxml.jackson.databind.JsonNode; +import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; +import com.imyeyu.api.modules.gao.ai.mcp.GaoAiToolNames; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationService; +import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.util.LinkedHashMap; +import java.util.Map; + +/// GAO 智能体待确认操作提交工具 +/// +/// 只能由 Dify 确定性工具节点调用,不接受任何业务参数。 +/// +/// @author Codex +/// @since 2026-11-23 +@Component +@RequiredArgsConstructor +public class OperationCommitTool implements GaoAiWriteTool { + + private final GaoAiOperationService operationService; + + @Override + public String name() { + return GaoAiToolNames.OPERATION_COMMIT; + } + + @Override + public String description() { + return "提交一个已准备的写操作。只接受服务端签发的 confirmationToken,不接受业务参数。"; + } + + @Override + public Provider provider() { + return Provider.COMMIT; + } + + @Override + public Map inputSchema() { + Map properties = new LinkedHashMap<>(); + properties.put("confirmationToken", Map.of("type", "string", "description", "服务端签发的确认 token")); + properties.put("confirmationPhrase", Map.of("type", "string", + "description", "破坏性或敏感操作要求的精确确认短语")); + properties.put("reason", Map.of("type", "string", "description", "破坏性或敏感操作的原因")); + properties.put("aiSessionId", Map.of("type", "string", "description", "AI 会话 ID")); + return Map.of("type", "object", "properties", properties, "additionalProperties", false); + } + + @Override + public GaoAiToolResult execute(GaoAiSession session, JsonNode arguments) { + return operationService.commit(session, text(arguments, "confirmationToken"), + text(arguments, "confirmationPhrase"), text(arguments, "reason")); + } + + private String text(JsonNode node, String field) { + if (node == null || !node.hasNonNull(field)) { + return null; + } + String value = node.get(field).asText(); + return value == null || value.isBlank() ? null : value.trim(); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/OperationPrepareTool.java b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/OperationPrepareTool.java new file mode 100644 index 0000000..35a1e1b --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/mcp/tool/OperationPrepareTool.java @@ -0,0 +1,85 @@ +package com.imyeyu.api.modules.gao.ai.mcp.tool; + +import com.fasterxml.jackson.databind.JsonNode; +import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; +import com.imyeyu.api.modules.gao.ai.mcp.GaoAiToolNames; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationRegistry; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationService; +import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.util.LinkedHashMap; +import java.util.Map; + +/// GAO 智能体写操作准备工具 +/// +/// 模型只负责填写业务参数,门店、操作人、请求号和确认 token 全部由后端生成。 +/// +/// @author Codex +/// @since 2026-11-23 +@Component +@RequiredArgsConstructor +public class OperationPrepareTool implements GaoAiWriteTool { + + private final GaoAiOperationRegistry registry; + private final GaoAiOperationService operationService; + + @Override + public String name() { + return GaoAiToolNames.OPERATION_PREPARE; + } + + @Override + public String description() { + return """ + 准备一个门店业务写操作,只生成预览和确认凭证,不写业务数据。 + 必须严格按操作目录传入 operation,并在 argumentsJson 中传入操作所需字段。 + 禁止传 storeId、operatorUserId、requestNo、confirmationToken、operationId。 + 操作目录: + """ + registry.catalog(); + } + + @Override + public Provider provider() { + return Provider.MAIN; + } + + @Override + public Map inputSchema() { + Map properties = new LinkedHashMap<>(); + properties.put("operation", Map.of("type", "string", "enum", registry.codes(), + "description", "写操作代码")); + properties.put("argumentsJson", Map.of("type", "string", + "description", "严格 JSON 对象字符串,字段由 operation 决定")); + properties.put("attachmentTokensJson", Map.of("type", "string", + "description", "附件凭证 JSON 数组,由工作流变量注入,模型不得生成")); + properties.put("aiSessionId", Map.of("type", "string", + "description", "由工作流变量注入的 AI 会话 ID,不允许由模型生成")); + return Map.of("type", "object", "properties", properties, "additionalProperties", false); + } + + @Override + public GaoAiToolResult execute(GaoAiSession session, JsonNode arguments) { + String operation = text(arguments, "operation"); + String argumentsJson = jsonText(arguments, "argumentsJson"); + String attachmentTokensJson = jsonText(arguments, "attachmentTokensJson"); + return operationService.prepare(session, operation, argumentsJson, attachmentTokensJson); + } + + private String text(JsonNode node, String field) { + if (node == null || !node.hasNonNull(field)) { + return null; + } + String value = node.get(field).asText(); + return value == null || value.isBlank() ? null : value.trim(); + } + + private String jsonText(JsonNode node, String field) { + if (node == null || !node.hasNonNull(field)) { + return null; + } + JsonNode value = node.get(field); + return value.isTextual() ? value.asText() : value.toString(); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiAttachmentService.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiAttachmentService.java new file mode 100644 index 0000000..656c25a --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiAttachmentService.java @@ -0,0 +1,49 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.imyeyu.api.modules.common.entity.Attachment; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/// GAO 智能体附件凭证服务 +/// +/// @author Codex +/// @since 2026-11-23 +public interface GaoAiAttachmentService { + + /// 上传并登记附件凭证 + /// + /// @param userId 用户 ID + /// @param storeId 门店 ID + /// @param files 文件列表 + /// @return 凭证和展示信息 + List upload(String userId, String storeId, List files); + + /// 解析并校验凭证 + /// + /// @param userId 用户 ID + /// @param storeId 门店 ID + /// @param tokens 凭证列表 + /// @return 附件凭证 + List resolve(String userId, String storeId, List tokens); + + /// 克隆为可提交给业务 Service 的临时附件 + /// + /// 每次 commit 都克隆,避免重试时临时文件已被业务消费。 + /// + /// @param userId 用户 ID + /// @param storeId 门店 ID + /// @param tokens 凭证列表 + /// @return 附件列表 + List cloneForCommit(String userId, String storeId, List tokens); + + /// 上传结果 + /// + /// @param token 凭证 + /// @param name 文件名 + /// @param mimeType MIME 类型 + /// @param size 文件大小 + /// @param expiresAt 过期时间 + record UploadedAttachment(String token, String name, String mimeType, Long size, long expiresAt) { + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiAttachmentServiceImplement.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiAttachmentServiceImplement.java new file mode 100644 index 0000000..e9dea7a --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiAttachmentServiceImplement.java @@ -0,0 +1,180 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.imyeyu.api.modules.common.entity.Attachment; +import com.imyeyu.api.modules.common.service.AttachmentService; +import com.imyeyu.api.modules.common.service.TempFileService; +import com.imyeyu.api.modules.common.vo.attach.TempFileResp; +import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties; +import com.imyeyu.spring.util.Redis; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; + +/// GAO 智能体附件凭证服务实现 +/// +/// @author Codex +/// @since 2026-11-23 +@Service +@RequiredArgsConstructor +public class GaoAiAttachmentServiceImplement implements GaoAiAttachmentService { + + private static final String KEY_PREFIX = "GAO:AI:ATTACH:"; + + private final GaoAiProperties properties; + private final TempFileService tempFileService; + private final AttachmentService attachmentService; + + @Qualifier("redisGaoAiAttachment") + private final Redis redis; + + private final SecureRandom secureRandom = new SecureRandom(); + + @Override + public List upload(String userId, String storeId, List files) { + if (userId == null || userId.isBlank() || storeId == null || storeId.isBlank()) { + throw new GaoAiOperationException("STORE_SCOPE_DENIED", "缺少用户或门店"); + } + if (files == null || files.isEmpty()) { + throw new GaoAiOperationException("ATTACHMENT_REQUIRED", "请先上传凭证照片"); + } + int maxCount = Math.max(1, properties.getAttachmentMaxCount()); + if (files.size() > maxCount) { + throw new GaoAiOperationException("VALIDATION_FAILED", "一次最多上传 %d 个附件".formatted(maxCount)); + } + long maxSize = Math.max(1L, properties.getAttachmentMaxSizeMb()) * 1024L * 1024L; + for (MultipartFile file : files) { + if (file == null || file.isEmpty()) { + throw new GaoAiOperationException("VALIDATION_FAILED", "附件不能为空"); + } + if (file.getSize() > maxSize) { + throw new GaoAiOperationException("VALIDATION_FAILED", "单个附件不能超过 %d MB".formatted(properties.getAttachmentMaxSizeMb())); + } + String contentType = file.getContentType(); + if (!allowedContentType(contentType)) { + throw new GaoAiOperationException("VALIDATION_FAILED", "仅支持图片或 PDF 凭证"); + } + } + long ttlMs = Math.max(60_000L, properties.getAttachmentTtlSeconds() * 1000L); + List tempFiles; + try { + tempFiles = tempFileService.create(files, ttlMs); + } catch (RuntimeException e) { + throw new GaoAiOperationException("ATTACHMENT_UPLOAD_FAILED", "附件上传失败,请检查文件大小和类型"); + } + List result = new ArrayList<>(); + for (int index = 0; index < tempFiles.size(); index++) { + TempFileResp tempFile = tempFiles.get(index); + Attachment attachment = attachmentService.get(tempFile.getId()); + if (attachment == null) { + throw new GaoAiOperationException("ATTACHMENT_INVALID", "附件上传失败"); + } + String mimeType = attachment.getMimeType(); + if (!allowedContentType(mimeType)) { + attachmentService.destroy(attachment.getId()); + throw new GaoAiOperationException("VALIDATION_FAILED", "附件内容类型不受支持"); + } + String token = newToken(); + GaoAiAttachmentToken tokenEntity = new GaoAiAttachmentToken(); + tokenEntity.setTokenHash(hash(token)); + tokenEntity.setTempFileId(tempFile.getId()); + tokenEntity.setUserId(userId); + tokenEntity.setStoreId(storeId); + tokenEntity.setName(attachment.getName()); + tokenEntity.setMimeType(mimeType); + tokenEntity.setSize(attachment.getSize()); + tokenEntity.setAttachType(mimeType != null && mimeType.startsWith("image") ? "PHOTO" : "OTHER"); + tokenEntity.setExpiresAt(System.currentTimeMillis() + ttlMs); + redis.set(key(tokenEntity.getTokenHash()), tokenEntity, ttlMs); + result.add(new UploadedAttachment(token, tokenEntity.getName(), tokenEntity.getMimeType(), + tokenEntity.getSize(), tokenEntity.getExpiresAt())); + } + return result; + } + + @Override + public List resolve(String userId, String storeId, List tokens) { + if (tokens == null || tokens.isEmpty()) { + return List.of(); + } + List result = new ArrayList<>(); + long now = System.currentTimeMillis(); + for (String token : tokens) { + if (token == null || token.isBlank()) { + continue; + } + GaoAiAttachmentToken entity = redis.get(key(hash(token.trim()))); + if (entity == null) { + throw new GaoAiOperationException("ATTACHMENT_INVALID", "附件凭证不存在或已过期,请重新上传"); + } + if (entity.getExpiresAt() <= now) { + redis.destroy(key(entity.getTokenHash())); + throw new GaoAiOperationException("ATTACHMENT_EXPIRED", "附件凭证已过期,请重新上传"); + } + if (!userId.equals(entity.getUserId()) || !storeId.equals(entity.getStoreId())) { + throw new GaoAiOperationException("ATTACHMENT_INVALID", "附件凭证不属于当前用户或门店"); + } + result.add(entity); + } + return result; + } + + @Override + public List cloneForCommit(String userId, String storeId, List tokens) { + List tokenList = resolve(userId, storeId, tokens); + List result = new ArrayList<>(); + for (GaoAiAttachmentToken token : tokenList) { + try { + Attachment clone = attachmentService.clone(token.getTempFileId()); + Attachment attachment = new Attachment(); + attachment.setTempFileId(clone.getId()); + attachment.setName(token.getName()); + attachment.setAttachType(token.getAttachType()); + attachment.setMetadata(clone.getMetadata()); + result.add(attachment); + } catch (RuntimeException e) { + throw new GaoAiOperationException("ATTACHMENT_INVALID", "附件已失效,请重新上传"); + } + } + return result; + } + + private String newToken() { + byte[] bytes = new byte[32]; + secureRandom.nextBytes(bytes); + return "att_" + Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private String key(String tokenHash) { + return KEY_PREFIX + tokenHash; + } + + private String hash(String value) { + try { + byte[] bytes = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); + StringBuilder result = new StringBuilder(bytes.length * 2); + for (byte item : bytes) { + result.append("%02x".formatted(item & 0xff)); + } + return result.toString(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("当前 JDK 不支持 SHA-256", e); + } + } + + private boolean allowedContentType(String contentType) { + if (contentType == null) { + return false; + } + String value = contentType.toLowerCase(); + return value.startsWith("image/") || "application/pdf".equals(value); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiAttachmentToken.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiAttachmentToken.java new file mode 100644 index 0000000..f72438c --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiAttachmentToken.java @@ -0,0 +1,40 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import lombok.Data; + +/// GAO 智能体附件凭证 +/// +/// 原始凭证只在浏览器和聊天请求中出现,Redis 只保存摘要。 +/// +/// @author Codex +/// @since 2026-11-23 +@Data +public class GaoAiAttachmentToken { + + /// 凭证摘要 + private String tokenHash; + + /// 临时文件 ID + private String tempFileId; + + /// 用户 ID + private String userId; + + /// 门店 ID + private String storeId; + + /// 文件名 + private String name; + + /// MIME 类型 + private String mimeType; + + /// 文件大小 + private Long size; + + /// 业务附件类型 + private String attachType = "PHOTO"; + + /// 过期时间 + private long expiresAt; +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiCommitResult.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiCommitResult.java new file mode 100644 index 0000000..d1a9c2a --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiCommitResult.java @@ -0,0 +1,65 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import lombok.Data; + +/// GAO 智能体写操作提交结果 +/// +/// @author Codex +/// @since 2026-11-23 +@Data +public class GaoAiCommitResult { + + /// 结果状态,成功固定为 SUCCEEDED + private String status; + + /// 操作代码 + private String operation; + + /// 结果实体类型 + private String entityType; + + /// 结果实体 ID + private String entityId; + + /// 结果实体业务单号 + private String entityNo; + + /// 给用户的结果文本 + private String resultText; + + /// true 为幂等重放 + private boolean idempotentReplay; + + /// 错误码 + private String errorCode; + + /// 错误消息 + private String errorMessage; + + /// 是否可重试 + private boolean retryable; + + /// 成功结果 + public static GaoAiCommitResult success(String operation, String entityType, String entityId, String entityNo, + String resultText) { + GaoAiCommitResult result = new GaoAiCommitResult(); + result.setStatus("SUCCEEDED"); + result.setOperation(operation); + result.setEntityType(entityType); + result.setEntityId(entityId); + result.setEntityNo(entityNo); + result.setResultText(resultText); + return result; + } + + /// 失败结果 + public static GaoAiCommitResult failure(String operation, String errorCode, String errorMessage, boolean retryable) { + GaoAiCommitResult result = new GaoAiCommitResult(); + result.setStatus("FAILED"); + result.setOperation(operation); + result.setErrorCode(errorCode); + result.setErrorMessage(errorMessage); + result.setRetryable(retryable); + return result; + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperation.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperation.java new file mode 100644 index 0000000..fad5b58 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperation.java @@ -0,0 +1,66 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import lombok.Getter; + +/// GAO 智能体写操作 +/// +/// 物理删除不在枚举中,静态检查可直接证明 AI 写能力不存在删除入口。 +/// +/// @author Codex +/// @since 2026-11-23 +@Getter +public enum GaoAiOperation { + + CUSTOMER_CREATE("客户创建", "CUSTOMER"), + CUSTOMER_UPDATE("客户资料修改", "CUSTOMER"), + + FOLLOW_UP_CREATE("客户跟进提醒创建", "CUSTOMER_FOLLOW_UP"), + FOLLOW_UP_UPDATE("客户跟进提醒修改", "CUSTOMER_FOLLOW_UP"), + FOLLOW_UP_COMPLETE("客户跟进提醒完成", "CUSTOMER_FOLLOW_UP"), + + STORE_DIARY_CREATE("门店日记创建", "STORE_DIARY"), + STORE_DIARY_UPDATE("门店日记修改", "STORE_DIARY"), + + EVENT_RECORD_CREATE("登记事件记录创建", "EVENT_RECORD"), + EVENT_RECORD_UPDATE("登记事件记录修改", "EVENT_RECORD"), + EVENT_RECORD_VERIFY("登记事件记录核销", "EVENT_RECORD"), + + STOCK_MANUAL_IN("库存手工入库", "PRODUCT_STOCK"), + STOCK_MANUAL_OUT("库存手工出库", "PRODUCT_STOCK"), + STOCK_STOCKTAKE_GAIN("库存盘盈", "PRODUCT_STOCK"), + STOCK_STOCKTAKE_LOSS("库存盘亏", "PRODUCT_STOCK"), + + SALES_ORDER_CREATE("销售订单创建", "SALES_ORDER"), + SALES_ORDER_UPDATE("销售订单备注和附件修改", "SALES_ORDER"), + SALES_ORDER_CANCEL("销售订单取消", "SALES_ORDER"), + + PAYMENT_RECEIVE("销售订单收款登记", "FUND_RECORD"), + PAYMENT_RECEIVE_AND_VERIFY("销售订单收款登记并核销", "FUND_RECORD"), + PAYMENT_VERIFY("销售订单收款核销", "FUND_RECORD"), + PAYMENT_REJECT("销售订单收款拒绝", "FUND_RECORD"), + PAYMENT_CANCEL("销售订单待核销收款撤销", "FUND_RECORD"), + PAYMENT_REFUND("销售订单退款", "FUND_RECORD"), + FUND_REVOKE("资金流水冲正", "FUND_RECORD"), + + FULFILLMENT_CREATE("履约创建", "ORDER_FULFILLMENT"), + FULFILLMENT_CREATE_AND_VERIFY("履约创建并核销", "ORDER_FULFILLMENT"), + FULFILLMENT_VERIFY("履约核销", "ORDER_FULFILLMENT"), + FULFILLMENT_REJECT("履约拒绝", "ORDER_FULFILLMENT"), + FULFILLMENT_CANCEL("待核销履约撤销", "ORDER_FULFILLMENT"), + + POINT_ADJUST("客户积分人工调整", "POINT_LEDGER"), + POINT_REDEMPTION_CREATE("积分兑换创建", "POINT_REDEMPTION"), + + CUSTOMER_PACKAGE_PURCHASE("客户套餐购买", "CUSTOMER_PACKAGE"); + + /// 操作标题 + private final String title; + + /// 结果实体类型 + private final String entityType; + + GaoAiOperation(String title, String entityType) { + this.title = title; + this.entityType = entityType; + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationContext.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationContext.java new file mode 100644 index 0000000..52b347c --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationContext.java @@ -0,0 +1,51 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; +import lombok.Getter; + +/// GAO 智能体写操作执行上下文 +/// +/// @author Codex +/// @since 2026-11-23 +@Getter +public final class GaoAiOperationContext { + + private final GaoAiSession session; + + private final String userId; + + private final String storeId; + + private final String conversationId; + + private final String requestId; + + private GaoAiOperationContext(GaoAiSession session, String userId, String storeId, String conversationId, String requestId) { + this.session = session; + this.userId = userId; + this.storeId = storeId; + this.conversationId = conversationId; + this.requestId = requestId; + } + + /// 从 AI 会话创建执行上下文 + /// + /// @param session AI 会话 + /// @param requestId 请求追踪 ID + /// @return 执行上下文 + public static GaoAiOperationContext of(GaoAiSession session, String requestId) { + return new GaoAiOperationContext(session, session.getUserId(), session.getStoreId(), + session.getDifyConversationId(), requestId); + } + + /// 从已认证用户创建执行上下文,用于 REST commit/cancel + /// + /// @param userId 用户 ID + /// @param storeId 门店 ID + /// @param conversationId Dify 会话 ID,可为空 + /// @param requestId 请求追踪 ID + /// @return 执行上下文 + public static GaoAiOperationContext of(String userId, String storeId, String conversationId, String requestId) { + return new GaoAiOperationContext(null, userId, storeId, conversationId, requestId); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationDefinition.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationDefinition.java new file mode 100644 index 0000000..dc08246 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationDefinition.java @@ -0,0 +1,89 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.imyeyu.api.modules.gao.bean.GaoPermissionCode; +import lombok.Getter; + +import java.util.List; + +/// GAO 智能体写操作定义 +/// +/// @author Codex +/// @since 2026-11-23 +@Getter +public class GaoAiOperationDefinition { + + /// 风险级别 + public enum RiskLevel { + + /// 普通创建/修改 + NORMAL, + + /// 影响金额、价格或不可逆状态 + SENSITIVE, + + /// 取消、拒绝、冲正、退款等逆向操作 + DESTRUCTIVE + } + + /// 附件策略 + public enum AttachmentPolicy { + + /// 不接收附件 + NONE, + + /// 可选附件 + OPTIONAL, + + /// 必须至少一张照片 + REQUIRED + } + + private final GaoAiOperation operation; + + private final RiskLevel riskLevel; + + private final AttachmentPolicy attachmentPolicy; + + private final List permissions; + + private final boolean reasonRequired; + + GaoAiOperationDefinition(GaoAiOperation operation, RiskLevel riskLevel, AttachmentPolicy attachmentPolicy, + List permissions, boolean reasonRequired) { + this.operation = operation; + this.riskLevel = riskLevel; + this.attachmentPolicy = attachmentPolicy; + this.permissions = List.copyOf(permissions); + this.reasonRequired = reasonRequired; + } + + /// @return 操作代码 + public String code() { + return operation.name(); + } + + /// @return 操作标题 + public String title() { + return operation.getTitle(); + } + + /// @return 结果实体类型 + public String entityType() { + return operation.getEntityType(); + } + + /// @return 是否破坏性操作 + public boolean destructive() { + return riskLevel == RiskLevel.DESTRUCTIVE; + } + + /// @return 是否敏感操作 + public boolean sensitive() { + return riskLevel == RiskLevel.SENSITIVE || destructive(); + } + + /// @return 是否必须精确确认短语 + public boolean exactPhraseRequired() { + return destructive(); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationException.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationException.java new file mode 100644 index 0000000..a50db6b --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationException.java @@ -0,0 +1,62 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import lombok.Getter; + +import java.util.List; + +/// GAO 智能体写操作异常 +/// +/// 业务错误通过错误码返回给 MCP/前端,不直接暴露内部异常。 +/// +/// @author Codex +/// @since 2026-11-23 +@Getter +public class GaoAiOperationException extends RuntimeException { + + private final String errorCode; + + private final boolean retryable; + + private final List candidates; + + private final List missingFields; + + public GaoAiOperationException(String errorCode, String message) { + this(errorCode, message, false, List.of(), List.of()); + } + + public GaoAiOperationException(String errorCode, String message, boolean retryable) { + this(errorCode, message, retryable, List.of(), List.of()); + } + + public GaoAiOperationException(String errorCode, String message, List candidates) { + this(errorCode, message, false, candidates, List.of()); + } + + public GaoAiOperationException(String errorCode, String message, boolean retryable, List candidates, + List missingFields) { + super(message); + this.errorCode = errorCode; + this.retryable = retryable; + this.candidates = candidates == null ? List.of() : candidates.stream().map(item -> (Object) item).toList(); + this.missingFields = missingFields == null ? List.of() : List.copyOf(missingFields); + } + + /// 缺少字段 + /// + /// @param message 提示 + /// @param missingFields 缺失字段 + /// @return 异常 + public static GaoAiOperationException clarification(String message, List missingFields) { + return new GaoAiOperationException("NEEDS_CLARIFICATION", message, false, List.of(), missingFields); + } + + /// 存在歧义 + /// + /// @param message 提示 + /// @param candidates 候选 + /// @return 异常 + public static GaoAiOperationException candidates(String message, List candidates) { + return new GaoAiOperationException("CANDIDATES", message, false, candidates, List.of()); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationHandler.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationHandler.java new file mode 100644 index 0000000..34813dc --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationHandler.java @@ -0,0 +1,37 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.fasterxml.jackson.databind.JsonNode; +import com.imyeyu.api.modules.common.entity.Attachment; + +import java.util.List; +import java.util.Set; + +/// GAO 智能体写操作处理器 +/// +/// @author Codex +/// @since 2026-11-23 +public interface GaoAiOperationHandler { + + /// @return 支持的操作 + Set supports(); + + /// 准备操作,只做解析、校验和预览,不写业务数据 + /// + /// @param context 执行上下文 + /// @param definition 操作定义 + /// @param arguments 参数 + /// @param attachments 已校验附件 + /// @return 准备结果 + GaoAiPreparedOperation prepare(GaoAiOperationContext context, GaoAiOperationDefinition definition, + JsonNode arguments, List attachments); + + /// 提交操作,业务参数只从待确认记录读取 + /// + /// @param context 执行上下文 + /// @param pending 待确认操作 + /// @param arguments 标准化参数 + /// @param attachments 已克隆的附件 + /// @return 提交结果 + GaoAiCommitResult commit(GaoAiOperationContext context, GaoAiPendingOperation pending, + JsonNode arguments, List attachments); +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationRegistry.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationRegistry.java new file mode 100644 index 0000000..9ad6d06 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationRegistry.java @@ -0,0 +1,181 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.AttachmentPolicy; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel; +import com.imyeyu.api.modules.gao.bean.GaoPermissionCode; +import org.springframework.stereotype.Component; + +import java.util.Arrays; +import java.util.Collections; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/// GAO 智能体写操作注册表 +/// +/// 所有写操作必须显式登记,未登记操作一律拒绝。 +/// 注册表中不存在任何物理删除操作。 +/// +/// @author Codex +/// @since 2026-11-23 +@Component +public class GaoAiOperationRegistry { + + private final Map definitions; + + public GaoAiOperationRegistry() { + Map map = new EnumMap<>(GaoAiOperation.class); + register(map, GaoAiOperation.CUSTOMER_CREATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.CUSTOMER_CREATE), false); + register(map, GaoAiOperation.CUSTOMER_UPDATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.CUSTOMER_UPDATE), false); + + register(map, GaoAiOperation.FOLLOW_UP_CREATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.CUSTOMER_FOLLOW_UP_REMINDER_CREATE), false); + register(map, GaoAiOperation.FOLLOW_UP_UPDATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.CUSTOMER_FOLLOW_UP_REMINDER_UPDATE), false); + register(map, GaoAiOperation.FOLLOW_UP_COMPLETE, RiskLevel.NORMAL, AttachmentPolicy.NONE, + List.of(GaoPermissionCode.CUSTOMER_FOLLOW_UP_REMINDER_COMPLETE), false); + + register(map, GaoAiOperation.STORE_DIARY_CREATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.STORE_DIARY_CREATE), false); + register(map, GaoAiOperation.STORE_DIARY_UPDATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.STORE_DIARY_UPDATE), false); + + register(map, GaoAiOperation.EVENT_RECORD_CREATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.EVENT_RECORD_CREATE), false); + register(map, GaoAiOperation.EVENT_RECORD_UPDATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.EVENT_RECORD_UPDATE), false); + register(map, GaoAiOperation.EVENT_RECORD_VERIFY, RiskLevel.SENSITIVE, AttachmentPolicy.NONE, + List.of(GaoPermissionCode.EVENT_RECORD_VERIFY), false); + + register(map, GaoAiOperation.STOCK_MANUAL_IN, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.PRODUCT_STOCK_CREATE), false); + register(map, GaoAiOperation.STOCK_MANUAL_OUT, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.PRODUCT_STOCK_CREATE), false); + register(map, GaoAiOperation.STOCK_STOCKTAKE_GAIN, RiskLevel.SENSITIVE, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.PRODUCT_STOCK_CREATE), false); + register(map, GaoAiOperation.STOCK_STOCKTAKE_LOSS, RiskLevel.SENSITIVE, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.PRODUCT_STOCK_CREATE), false); + + register(map, GaoAiOperation.SALES_ORDER_CREATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.SALES_ORDER_CREATE), false); + register(map, GaoAiOperation.SALES_ORDER_UPDATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.SALES_ORDER_UPDATE), false); + register(map, GaoAiOperation.SALES_ORDER_CANCEL, RiskLevel.DESTRUCTIVE, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.SALES_ORDER_CANCEL), true); + + register(map, GaoAiOperation.PAYMENT_RECEIVE, RiskLevel.NORMAL, AttachmentPolicy.REQUIRED, + List.of(GaoPermissionCode.FUND_RECEIVE_CREATE), false); + register(map, GaoAiOperation.PAYMENT_RECEIVE_AND_VERIFY, RiskLevel.SENSITIVE, AttachmentPolicy.REQUIRED, + List.of(GaoPermissionCode.FUND_RECEIVE_CREATE, GaoPermissionCode.FUND_RECEIVE_VERIFY), false); + register(map, GaoAiOperation.PAYMENT_VERIFY, RiskLevel.SENSITIVE, AttachmentPolicy.NONE, + List.of(GaoPermissionCode.FUND_RECEIVE_VERIFY), false); + register(map, GaoAiOperation.PAYMENT_REJECT, RiskLevel.DESTRUCTIVE, AttachmentPolicy.NONE, + List.of(GaoPermissionCode.FUND_RECEIVE_VERIFY), true); + register(map, GaoAiOperation.PAYMENT_CANCEL, RiskLevel.DESTRUCTIVE, AttachmentPolicy.NONE, + List.of(GaoPermissionCode.FUND_RECEIVE_CREATE), true); + register(map, GaoAiOperation.PAYMENT_REFUND, RiskLevel.DESTRUCTIVE, AttachmentPolicy.REQUIRED, + List.of(GaoPermissionCode.FUND_REFUND), true); + register(map, GaoAiOperation.FUND_REVOKE, RiskLevel.DESTRUCTIVE, AttachmentPolicy.REQUIRED, + List.of(GaoPermissionCode.FUND_REVOKE), true); + + register(map, GaoAiOperation.FULFILLMENT_CREATE, RiskLevel.NORMAL, AttachmentPolicy.REQUIRED, + List.of(GaoPermissionCode.ORDER_FULFILLMENT_CREATE), false); + register(map, GaoAiOperation.FULFILLMENT_CREATE_AND_VERIFY, RiskLevel.SENSITIVE, AttachmentPolicy.REQUIRED, + List.of(GaoPermissionCode.ORDER_FULFILLMENT_CREATE, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY), false); + register(map, GaoAiOperation.FULFILLMENT_VERIFY, RiskLevel.SENSITIVE, AttachmentPolicy.NONE, + List.of(GaoPermissionCode.ORDER_FULFILLMENT_VERIFY), false); + register(map, GaoAiOperation.FULFILLMENT_REJECT, RiskLevel.DESTRUCTIVE, AttachmentPolicy.NONE, + List.of(GaoPermissionCode.ORDER_FULFILLMENT_VERIFY), true); + register(map, GaoAiOperation.FULFILLMENT_CANCEL, RiskLevel.DESTRUCTIVE, AttachmentPolicy.NONE, + List.of(GaoPermissionCode.ORDER_FULFILLMENT_CREATE), true); + + register(map, GaoAiOperation.POINT_ADJUST, RiskLevel.SENSITIVE, AttachmentPolicy.NONE, + List.of(GaoPermissionCode.POINT_ADJUST), false); + register(map, GaoAiOperation.POINT_REDEMPTION_CREATE, RiskLevel.NORMAL, AttachmentPolicy.REQUIRED, + List.of(GaoPermissionCode.POINT_REDEMPTION_CREATE), false); + + register(map, GaoAiOperation.CUSTOMER_PACKAGE_PURCHASE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL, + List.of(GaoPermissionCode.CUSTOMER_PACKAGE_CREATE), false); + + this.definitions = Collections.unmodifiableMap(map); + } + + private void register(Map map, GaoAiOperation operation, + RiskLevel riskLevel, AttachmentPolicy attachmentPolicy, List permissions, + boolean reasonRequired) { + map.put(operation, new GaoAiOperationDefinition(operation, riskLevel, attachmentPolicy, permissions, reasonRequired)); + } + + /// 获取操作定义 + /// + /// @param operation 操作 + /// @return 操作定义 + public GaoAiOperationDefinition require(GaoAiOperation operation) { + GaoAiOperationDefinition definition = operation == null ? null : definitions.get(operation); + if (definition == null) { + throw new GaoAiOperationException("FEATURE_DISABLED", "该操作未对智能助手开放"); + } + return definition; + } + + /// 按代码解析操作 + /// + /// @param code 操作代码 + /// @return 操作定义 + public GaoAiOperationDefinition require(String code) { + if (code == null || code.isBlank()) { + throw new GaoAiOperationException("VALIDATION_FAILED", "缺少操作类型"); + } + try { + return require(GaoAiOperation.valueOf(code.trim().toUpperCase())); + } catch (IllegalArgumentException e) { + throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作类型"); + } + } + + /// @return 全部操作定义 + public List list() { + return List.copyOf(definitions.values()); + } + + /// @return 操作代码列表 + public List codes() { + return definitions.keySet().stream().map(Enum::name).toList(); + } + + /// 生成给模型和前端阅读的操作目录 + /// + /// @return 操作目录文本 + public String catalog() { + return definitions.values().stream() + .map(definition -> "- %s:%s;权限:%s;风险:%s".formatted( + definition.code(), + definition.title(), + definition.getPermissions().stream().map(GaoPermissionCode::getValue).collect(Collectors.joining(",")), + definition.getRiskLevel().name())) + .collect(Collectors.joining("\n")); + } + + /// 判断操作代码是否存在 + /// + /// @param code 操作代码 + /// @return true 为存在 + public boolean contains(String code) { + try { + return definitions.containsKey(GaoAiOperation.valueOf(code)); + } catch (RuntimeException e) { + return false; + } + } + + /// @return 静态检查用:确认没有任何删除操作代码 + public List destructiveOperationCodes() { + return Arrays.stream(GaoAiOperation.values()) + .filter(operation -> definitions.get(operation).destructive()) + .map(Enum::name) + .toList(); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationService.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationService.java new file mode 100644 index 0000000..8c6ca7c --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationService.java @@ -0,0 +1,70 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; +import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult; + +/// GAO 智能体写操作服务 +/// +/// @author Codex +/// @since 2026-11-23 +public interface GaoAiOperationService { + + /// 准备写操作 + /// + /// @param session AI 会话 + /// @param operation 操作代码 + /// @param argumentsJson 业务参数 JSON + /// @param attachmentTokensJson 附件凭证 JSON 数组 + /// @return 准备结果 + GaoAiToolResult prepare(GaoAiSession session, String operation, String argumentsJson, String attachmentTokensJson); + + /// 按确认 token 提交 + /// + /// @param session AI 会话 + /// @param token 确认 token + /// @param confirmationPhrase 确认短语 + /// @param reason 操作原因 + /// @return 提交结果 + GaoAiToolResult commit(GaoAiSession session, String token, String confirmationPhrase, String reason); + + /// 按公开操作 ID 提交,用于前端卡片 REST 接口 + /// + /// @param userId 用户 ID + /// @param storeId 门店 ID + /// @param conversationId Dify 会话 ID + /// @param operationId 公开操作 ID + /// @param confirmationPhrase 确认短语 + /// @param reason 操作原因 + /// @return 提交结果 + GaoAiToolResult commit(String userId, String storeId, String conversationId, String operationId, + String confirmationPhrase, String reason); + + /// 按确认 token 取消 + /// + /// @param session AI 会话 + /// @param token 确认 token + /// @return 取消结果 + GaoAiToolResult cancel(GaoAiSession session, String token); + + /// 按公开操作 ID 取消 + /// + /// @param userId 用户 ID + /// @param storeId 门店 ID + /// @param operationId 公开操作 ID + /// @return 取消结果 + GaoAiToolResult cancel(String userId, String storeId, String operationId); + + /// 查询当前活跃待确认操作 + /// + /// @param userId 用户 ID + /// @param storeId 门店 ID + /// @param conversationId Dify 会话 ID + /// @return 待确认操作视图 + GaoAiToolResult pending(String userId, String storeId, String conversationId); + + /// 绑定 Dify 会话 + /// + /// @param sourceSessionId 来源 AI 会话 ID + /// @param conversationId Dify 会话 ID + void bindConversation(String sourceSessionId, String conversationId); +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationServiceImplement.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationServiceImplement.java new file mode 100644 index 0000000..6d46363 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationServiceImplement.java @@ -0,0 +1,600 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties; +import com.imyeyu.api.modules.gao.ai.entity.GaoAiAuditLog; +import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel; +import com.imyeyu.api.modules.gao.ai.service.GaoAiAuditService; +import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult; +import com.imyeyu.api.modules.gao.service.GaoStoreScopeService; +import com.imyeyu.api.modules.user.context.ExecutionIdentityContext; +import com.imyeyu.java.bean.timi.TimiException; +import com.imyeyu.spring.util.Redis; +import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/// GAO 智能体写操作服务实现 +/// +/// @author Codex +/// @since 2026-11-23 +@Slf4j +@Service +@RequiredArgsConstructor +public class GaoAiOperationServiceImplement implements GaoAiOperationService { + + private static final String COMMIT_LOCK_PREFIX = "GAO:AI:OP:COMMIT:"; + + private final GaoAiProperties properties; + private final GaoAiOperationRegistry registry; + private final GaoAiToolAuthorizer authorizer; + private final GaoAiPendingOperationService pendingService; + private final GaoAiAttachmentService attachmentService; + private final GaoAiAuditService auditService; + private final GaoAiOperationSupport support; + private final GaoStoreScopeService storeScopeService; + private final ObjectMapper jackson; + private final List handlerList; + +// @Qualifier("redisLocker") + private Redis locker; + +// @Qualifier("redisRateLimit") + private Redis rateLimitRedis; + + private Map handlerMap; + + @PostConstruct + private void postConstruct() { + Map map = new EnumMap<>(GaoAiOperation.class); + for (GaoAiOperationHandler handler : handlerList) { + for (GaoAiOperation operation : handler.supports()) { + GaoAiOperationHandler previous = map.put(operation, handler); + if (previous != null) { + throw new IllegalStateException("重复注册 GAO AI 写操作处理器:" + operation); + } + } + } + for (GaoAiOperation operation : GaoAiOperation.values()) { + if (!map.containsKey(operation)) { + throw new IllegalStateException("GAO AI 写操作缺少处理器:" + operation); + } + } + this.handlerMap = Map.copyOf(map); + } + + @Override + public GaoAiToolResult prepare(GaoAiSession session, String operation, String argumentsJson, String attachmentTokensJson) { + long startedAt = System.currentTimeMillis(); + GaoAiOperationDefinition definition = null; + List tokens = List.of(); + try { + if (!properties.isWriteEnabled()) { + return failure("FEATURE_DISABLED", "FEATURE_DISABLED", "智能助手写能力暂未开放", false, startedAt, + List.of(), List.of()); + } + checkRate("PREPARE", session.getUserId(), properties.getMaxPreparesPer10Minutes()); + definition = registry.require(operation); + authorizer.check(session.getUserId(), definition); + try { + storeScopeService.checkStoreId(session.getStoreId()); + } catch (TimiException e) { + throw new GaoAiOperationException("STORE_SCOPE_DENIED", e.getMessage()); + } + if (argumentsJson != null && argumentsJson.length() > 20_000) { + throw new GaoAiOperationException("VALIDATION_FAILED", "操作参数过长"); + } + JsonNode arguments = support.object(argumentsJson); + rejectForbiddenFields(arguments, "$"); + tokens = parseTokens(attachmentTokensJson); + if (definition.getAttachmentPolicy() == GaoAiOperationDefinition.AttachmentPolicy.NONE) { + tokens = List.of(); + } + if (definition.getAttachmentPolicy() == GaoAiOperationDefinition.AttachmentPolicy.REQUIRED && tokens.isEmpty()) { + throw new GaoAiOperationException("ATTACHMENT_REQUIRED", "该操作必须上传凭证照片"); + } + List attachments = attachmentService.resolve(session.getUserId(), session.getStoreId(), tokens); + if (definition.getAttachmentPolicy() == GaoAiOperationDefinition.AttachmentPolicy.REQUIRED + && attachments.stream().noneMatch(item -> item.getMimeType() != null && item.getMimeType().startsWith("image/"))) { + throw new GaoAiOperationException("ATTACHMENT_REQUIRED", "该操作必须上传照片凭证"); + } + GaoAiOperationHandler handler = handler(definition.getOperation()); + GaoAiOperationContext context = GaoAiOperationContext.of(session, UUID.randomUUID().toString()); + GaoAiPreparedOperation prepared = handler.prepare(context, definition, arguments, attachments); + if (prepared == null || prepared.getPreviewText() == null) { + throw new GaoAiOperationException("INTERNAL_ERROR", "操作准备失败"); + } + if (prepared.getArgumentsJson() == null || prepared.getArgumentsJson().isBlank()) { + prepared.setArgumentsJson(arguments.toString()); + } + RiskLevel riskLevel = prepared.getRiskLevel(); + if (riskLevel == null || riskLevel.ordinal() < definition.getRiskLevel().ordinal()) { + riskLevel = definition.getRiskLevel(); + } + prepared.setRiskLevel(riskLevel); + if (prepared.getTitle() == null) { + prepared.setTitle(definition.title()); + } + if (prepared.getRequiredPhrase() == null && definition.exactPhraseRequired()) { + prepared.setRequiredPhrase("确认" + definition.title()); + } + if (prepared.getRiskLevel() == RiskLevel.DESTRUCTIVE) { + prepared.setReasonRequired(true); + } + String requestNo = support.requestNo(definition.getOperation()); + GaoAiPendingOperationService.Created created = pendingService.create(context, definition, requestNo, + prepared.getArgumentsJson(), tokens, prepared); + GaoAiPendingOperation pending = created.pending(); + recordAudit("GAO_AI_WRITE_PREPARE", "SUCCESS", session.getUserId(), session.getStoreId(), + session.getDifyConversationId(), pending.getOperation(), pending.getOperationId(), pending.getRequestNo(), + created.token(), pending.getRiskLevel(), null, null, false, null, startedAt); + // token 只由服务端下一轮注入,不返回给 Dify 工具输出,避免进入工作流日志和模型上下文 + return success(pending, null, false); + } catch (GaoAiOperationException e) { + recordAudit("GAO_AI_WRITE_PREPARE", "FAILED", session.getUserId(), session.getStoreId(), + session.getDifyConversationId(), definition == null ? operation : definition.code(), null, null, + null, definition == null ? null : definition.getRiskLevel().name(), e.getErrorCode(), null, false, + null, startedAt); + return failure(e.getErrorCode(), e.getErrorCode(), e.getMessage(), e.isRetryable(), startedAt, + e.getCandidates(), e.getMissingFields()); + } catch (TimiException e) { + recordAudit("GAO_AI_WRITE_PREPARE", "FAILED", session.getUserId(), session.getStoreId(), + session.getDifyConversationId(), definition == null ? operation : definition.code(), null, null, + null, definition == null ? null : definition.getRiskLevel().name(), "VALIDATION_FAILED", null, + false, null, startedAt); + return failure("VALIDATION_FAILED", "VALIDATION_FAILED", e.getMessage(), false, startedAt, List.of(), List.of()); + } catch (RuntimeException e) { + log.warn("GAO AI 写操作准备失败:operation={}, userId={}, storeId={}", operation, session.getUserId(), + session.getStoreId(), e); + recordAudit("GAO_AI_WRITE_PREPARE", "ERROR", session.getUserId(), session.getStoreId(), + session.getDifyConversationId(), definition == null ? operation : definition.code(), null, null, + null, definition == null ? null : definition.getRiskLevel().name(), "INTERNAL_ERROR", null, + false, null, startedAt); + return failure("INTERNAL_ERROR", "INTERNAL_ERROR", "操作准备失败,请稍后重试", false, startedAt, + List.of(), List.of()); + } + } + + @Override + public GaoAiToolResult commit(GaoAiSession session, String token, String confirmationPhrase, String reason) { + long startedAt = System.currentTimeMillis(); + GaoAiPendingOperation pending = null; + try { + pending = pendingService.requireByToken(token); + if (!pending.belongsTo(session.getUserId(), session.getStoreId())) { + throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "确认凭证无效"); + } + return commitInternal(pending, confirmationPhrase, reason, token, startedAt); + } catch (GaoAiOperationException e) { + recordAudit("GAO_AI_WRITE_COMMIT", "FAILED", session.getUserId(), session.getStoreId(), + session.getDifyConversationId(), pending == null ? null : pending.getOperation(), + pending == null ? null : pending.getOperationId(), pending == null ? null : pending.getRequestNo(), + token, pending == null ? null : pending.getRiskLevel(), e.getErrorCode(), null, false, reason, startedAt); + return failure("FAILED", e.getErrorCode(), e.getMessage(), e.isRetryable(), startedAt, List.of(), List.of()); + } catch (RuntimeException e) { + log.warn("GAO AI 写操作提交失败:token={}", token == null ? 0 : token.length(), e); + recordAudit("GAO_AI_WRITE_COMMIT", "ERROR", session.getUserId(), session.getStoreId(), + session.getDifyConversationId(), pending == null ? null : pending.getOperation(), + pending == null ? null : pending.getOperationId(), pending == null ? null : pending.getRequestNo(), + token, pending == null ? null : pending.getRiskLevel(), "INTERNAL_ERROR", null, false, reason, startedAt); + return failure("FAILED", "INTERNAL_ERROR", "操作提交失败,请稍后重试", false, startedAt, List.of(), List.of()); + } + } + + @Override + public GaoAiToolResult commit(String userId, String storeId, String conversationId, String operationId, + String confirmationPhrase, String reason) { + long startedAt = System.currentTimeMillis(); + GaoAiPendingOperation pending = null; + try { + pending = pendingService.requireByOperationId(operationId); + if (!pending.belongsTo(userId, storeId)) { + throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "操作不存在或已过期"); + } + return commitInternal(pending, confirmationPhrase, reason, null, startedAt); + } catch (GaoAiOperationException e) { + recordAudit("GAO_AI_WRITE_COMMIT", "FAILED", userId, storeId, conversationId, + pending == null ? null : pending.getOperation(), pending == null ? operationId : pending.getOperationId(), + pending == null ? null : pending.getRequestNo(), null, pending == null ? null : pending.getRiskLevel(), + e.getErrorCode(), null, false, reason, startedAt); + return failure("FAILED", e.getErrorCode(), e.getMessage(), e.isRetryable(), startedAt, List.of(), List.of()); + } catch (RuntimeException e) { + log.warn("GAO AI 卡片提交失败:operationId={}", operationId, e); + recordAudit("GAO_AI_WRITE_COMMIT", "ERROR", userId, storeId, conversationId, + pending == null ? null : pending.getOperation(), pending == null ? operationId : pending.getOperationId(), + pending == null ? null : pending.getRequestNo(), null, pending == null ? null : pending.getRiskLevel(), + "INTERNAL_ERROR", null, false, reason, startedAt); + return failure("FAILED", "INTERNAL_ERROR", "操作提交失败,请稍后重试", false, startedAt, List.of(), List.of()); + } + } + + private GaoAiToolResult commitInternal(GaoAiPendingOperation pending, String confirmationPhrase, String reason, + String token, long startedAt) { + if (pending.getStatus() == GaoAiPendingOperation.Status.SUCCEEDED) { + return replay(pending); + } + if (pending.getStatus() == GaoAiPendingOperation.Status.CANCELLED) { + throw new GaoAiOperationException("CONFIRMATION_CANCELLED", "该操作已取消"); + } + if (pending.getStatus() == GaoAiPendingOperation.Status.EXPIRED) { + throw new GaoAiOperationException("CONFIRMATION_EXPIRED", "该操作已过期"); + } + if (pending.getStatus() == GaoAiPendingOperation.Status.SUPERSEDED) { + throw new GaoAiOperationException("CONFIRMATION_SUPERSEDED", "该操作已被新的操作替代"); + } + if (pending.getStatus() == GaoAiPendingOperation.Status.COMMITTING) { + if (System.currentTimeMillis() - pending.getUpdatedAt() > 60_000L) { + pending.setStatus(GaoAiPendingOperation.Status.PENDING); + pendingService.save(pending); + } else { + throw new GaoAiOperationException("CONFIRMATION_IN_PROGRESS", "操作正在提交,请稍后查询结果", true); + } + } + if (pending.getStatus() == GaoAiPendingOperation.Status.FAILED) { + return failure("FAILED", pending.getLastErrorCode() == null ? "VALIDATION_FAILED" : pending.getLastErrorCode(), + pending.getLastErrorMessage() == null ? "操作提交失败" : pending.getLastErrorMessage(), false, + startedAt, List.of(), List.of()); + } + long now = System.currentTimeMillis(); + if (pending.getExpiresAt() <= now) { + pending.setStatus(GaoAiPendingOperation.Status.EXPIRED); + pendingService.save(pending); + throw new GaoAiOperationException("CONFIRMATION_EXPIRED", "确认已过期,请重新发起操作"); + } + checkRate("COMMIT", pending.getUserId(), properties.getMaxCommitsPer10Minutes()); + GaoAiOperationDefinition definition = registry.require(pending.getOperation()); + authorizer.check(pending.getUserId(), definition); + if (pending.getRequiredPhrase() != null && !pending.getRequiredPhrase().isBlank() + && !support.normalizePhrase(pending.getRequiredPhrase()).equals(support.normalizePhrase(confirmationPhrase))) { + throw new GaoAiOperationException("CONFIRMATION_PHRASE_MISMATCH", + "请按提示回复完整确认短语"); + } + if (pending.isReasonRequired() && (reason == null || reason.isBlank())) { + throw new GaoAiOperationException("REASON_REQUIRED", "该操作必须填写原因"); + } + String lockKey = COMMIT_LOCK_PREFIX + pending.getOperationId(); + if (!locker.lock(lockKey, 1, 30_000L)) { + throw new GaoAiOperationException("CONFIRMATION_IN_PROGRESS", "操作正在提交,请稍后查询结果", true); + } + try { + GaoAiPendingOperation current = pendingService.requireByOperationId(pending.getOperationId()); + if (current.getStatus() == GaoAiPendingOperation.Status.SUCCEEDED) { + return replay(current); + } + if (current.getStatus() == GaoAiPendingOperation.Status.COMMITTING) { + throw new GaoAiOperationException("CONFIRMATION_IN_PROGRESS", "操作正在提交,请稍后查询结果", true); + } + if (current.getStatus() == GaoAiPendingOperation.Status.FAILED) { + return failure("FAILED", current.getLastErrorCode() == null ? "VALIDATION_FAILED" + : current.getLastErrorCode(), current.getLastErrorMessage() == null ? "操作提交失败" + : current.getLastErrorMessage(), false, startedAt, List.of(), List.of()); + } + if (current.getStatus() == GaoAiPendingOperation.Status.CANCELLED) { + throw new GaoAiOperationException("CONFIRMATION_CANCELLED", "该操作已取消"); + } + if (current.getStatus() == GaoAiPendingOperation.Status.SUPERSEDED) { + throw new GaoAiOperationException("CONFIRMATION_SUPERSEDED", "该操作已被新的操作替代"); + } + if (!current.confirmable(System.currentTimeMillis())) { + throw new GaoAiOperationException("CONFIRMATION_EXPIRED", "确认已过期,请重新发起操作"); + } + current.setStatus(GaoAiPendingOperation.Status.COMMITTING); + current.setAttemptCount(current.getAttemptCount() + 1); + current.setCommitReason(reason); + pendingService.save(current); + GaoAiOperationContext context = GaoAiOperationContext.of(current.getUserId(), current.getStoreId(), + current.getConversationId(), current.getOperationId()); + JsonNode arguments = support.object(current.getArgumentsJson()); + List attachments = attachmentService.cloneForCommit( + current.getUserId(), current.getStoreId(), current.getAttachmentTokens()); + GaoAiOperationHandler handler = handler(definition.getOperation()); + GaoAiCommitResult result = ExecutionIdentityContext.runAs(current.getUserId(), "GAO_AI_OPERATION_COMMIT", + current.getOperationId(), () -> { + try { + storeScopeService.checkStoreId(current.getStoreId()); + } catch (TimiException e) { + throw new GaoAiOperationException("STORE_SCOPE_DENIED", e.getMessage()); + } + GaoAiCommitResult commitResult = handler.commit(context, current, arguments, attachments); + if (commitResult == null) { + throw new GaoAiOperationException("INTERNAL_ERROR", "业务操作未返回结果"); + } + return commitResult; + }); + current.setStatus(GaoAiPendingOperation.Status.SUCCEEDED); + current.setResultEntityId(result.getEntityId()); + current.setResultEntityNo(result.getEntityNo()); + current.setResultText(result.getResultText()); + current.setCommittedAt(System.currentTimeMillis()); + current.setLastErrorCode(null); + current.setLastErrorMessage(null); + pendingService.save(current); + recordAudit("GAO_AI_WRITE_COMMIT", "SUCCESS", current.getUserId(), current.getStoreId(), + current.getConversationId(), current.getOperation(), current.getOperationId(), current.getRequestNo(), + token, current.getRiskLevel(), null, result.getEntityType(), false, reason, startedAt); + GaoAiToolResult toolResult = success(current, null, false); + toolResult.setIdempotentReplay(false); + return toolResult; + } catch (GaoAiOperationException e) { + GaoAiPendingOperation current = safePending(pending); + if (current != null && !(current.getStatus() == GaoAiPendingOperation.Status.COMMITTING + && "CONFIRMATION_IN_PROGRESS".equals(e.getErrorCode()))) { + current.setLastErrorCode(e.getErrorCode()); + current.setLastErrorMessage(e.getMessage()); + boolean keepPending = e.isRetryable() + || "CONFIRMATION_PHRASE_MISMATCH".equals(e.getErrorCode()) + || "REASON_REQUIRED".equals(e.getErrorCode()); + current.setStatus(keepPending ? GaoAiPendingOperation.Status.PENDING + : GaoAiPendingOperation.Status.FAILED); + pendingService.save(current); + } + recordAudit("GAO_AI_WRITE_COMMIT", "FAILED", pending.getUserId(), pending.getStoreId(), + pending.getConversationId(), pending.getOperation(), pending.getOperationId(), pending.getRequestNo(), + token, pending.getRiskLevel(), e.getErrorCode(), null, false, reason, startedAt); + throw e; + } catch (TimiException e) { + GaoAiPendingOperation current = safePending(pending); + if (current != null) { + current.setStatus(GaoAiPendingOperation.Status.FAILED); + current.setLastErrorCode("VALIDATION_FAILED"); + current.setLastErrorMessage(e.getMessage()); + pendingService.save(current); + } + recordAudit("GAO_AI_WRITE_COMMIT", "FAILED", pending.getUserId(), pending.getStoreId(), + pending.getConversationId(), pending.getOperation(), pending.getOperationId(), pending.getRequestNo(), + token, pending.getRiskLevel(), "VALIDATION_FAILED", null, false, reason, startedAt); + return failure("FAILED", "VALIDATION_FAILED", e.getMessage(), false, startedAt, List.of(), List.of()); + } catch (RuntimeException e) { + log.warn("GAO AI 写操作提交异常:operationId={}", pending.getOperationId(), e); + GaoAiPendingOperation current = safePending(pending); + if (current != null) { + current.setStatus(GaoAiPendingOperation.Status.FAILED); + current.setLastErrorCode("INTERNAL_ERROR"); + current.setLastErrorMessage("操作提交失败,请稍后重试"); + pendingService.save(current); + } + recordAudit("GAO_AI_WRITE_COMMIT", "ERROR", pending.getUserId(), pending.getStoreId(), + pending.getConversationId(), pending.getOperation(), pending.getOperationId(), pending.getRequestNo(), + token, pending.getRiskLevel(), "INTERNAL_ERROR", null, false, reason, startedAt); + return failure("FAILED", "INTERNAL_ERROR", "操作提交失败,请稍后重试", false, startedAt, List.of(), List.of()); + } finally { + locker.releaseLock(lockKey); + } + } + + @Override + public GaoAiToolResult cancel(GaoAiSession session, String token) { + GaoAiPendingOperation pending = pendingService.requireByToken(token); + if (!pending.belongsTo(session.getUserId(), session.getStoreId())) { + throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "确认凭证无效"); + } + return cancelInternal(pending); + } + + @Override + public GaoAiToolResult cancel(String userId, String storeId, String operationId) { + GaoAiPendingOperation pending = pendingService.requireByOperationId(operationId); + if (!pending.belongsTo(userId, storeId)) { + throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "操作不存在或已过期"); + } + return cancelInternal(pending); + } + + private GaoAiToolResult cancelInternal(GaoAiPendingOperation pending) { + if (pending.getStatus() == GaoAiPendingOperation.Status.CANCELLED) { + return cancelled(pending); + } + if (pending.getStatus() == GaoAiPendingOperation.Status.SUCCEEDED) { + throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "操作已经成功,不能取消"); + } + if (pending.getStatus() == GaoAiPendingOperation.Status.COMMITTING) { + throw new GaoAiOperationException("CONFIRMATION_IN_PROGRESS", "操作正在提交,不能取消", true); + } + pending.setStatus(GaoAiPendingOperation.Status.CANCELLED); + pending.setCancelledAt(System.currentTimeMillis()); + pendingService.save(pending); + recordAudit("GAO_AI_WRITE_CANCEL", "SUCCESS", pending.getUserId(), pending.getStoreId(), + pending.getConversationId(), pending.getOperation(), pending.getOperationId(), pending.getRequestNo(), + null, pending.getRiskLevel(), null, null, false, null, System.currentTimeMillis()); + return cancelled(pending); + } + + @Override + public GaoAiToolResult pending(String userId, String storeId, String conversationId) { + GaoAiPendingOperation pending = pendingService.findActive(userId, storeId, conversationId); + if (pending == null) { + GaoAiToolResult result = new GaoAiToolResult(); + result.setStatus("NONE"); + return result; + } + return success(pending, null, false); + } + + @Override + public void bindConversation(String sourceSessionId, String conversationId) { + GaoAiPendingOperation pending = pendingService.findActiveBySourceSession(sourceSessionId); + if (pending != null) { + pendingService.bindConversation(pending, conversationId); + } + } + + private GaoAiOperationHandler handler(GaoAiOperation operation) { + GaoAiOperationHandler handler = handlerMap.get(operation); + if (handler == null) { + throw new GaoAiOperationException("FEATURE_DISABLED", "该操作处理器未启用"); + } + return handler; + } + + private GaoAiToolResult success(GaoAiPendingOperation pending, String token, boolean replay) { + GaoAiToolResult result = new GaoAiToolResult(); + result.setStatus(replay ? "SUCCEEDED" : "PENDING_CONFIRMATION"); + result.setOperation(pending.getOperation()); + result.setTitle(pending.getTitle()); + result.setOperationId(pending.getOperationId()); + result.setConfirmationToken(token); + result.setRiskLevel(pending.getRiskLevel()); + result.setRequiredPhrase(pending.getRequiredPhrase()); + result.setExpiresAt(pending.getExpiresAt()); + result.setDestructive(RiskLevel.DESTRUCTIVE.name().equals(pending.getRiskLevel())); + result.setReasonRequired(pending.isReasonRequired()); + result.setAttachmentCount(pending.getAttachmentTokens() == null ? 0 : pending.getAttachmentTokens().size()); + result.setPreview(pending.getPreview()); + result.setPreviewText(pending.getPreviewText()); + result.setImpactText(pending.getImpactText()); + result.setEntityType(pending.getEntityType()); + result.setEntityId(pending.getResultEntityId()); + result.setEntityNo(pending.getResultEntityNo()); + result.setResultText(pending.getResultText()); + result.setIdempotentReplay(replay); + return result; + } + + private GaoAiToolResult replay(GaoAiPendingOperation pending) { + GaoAiToolResult result = success(pending, null, true); + result.setStatus("SUCCEEDED"); + result.setIdempotentReplay(true); + return result; + } + + private GaoAiToolResult cancelled(GaoAiPendingOperation pending) { + GaoAiToolResult result = new GaoAiToolResult(); + result.setStatus("CANCELLED"); + result.setOperation(pending.getOperation()); + result.setOperationId(pending.getOperationId()); + result.setResultText("已取消待确认操作。"); + return result; + } + + private GaoAiToolResult failure(String status, String errorCode, String errorMessage, boolean retryable, + long startedAt, List candidates) { + return failure(status, errorCode, errorMessage, retryable, startedAt, candidates, List.of()); + } + + private GaoAiToolResult failure(String status, String errorCode, String errorMessage, boolean retryable, + long startedAt, List candidates, List missingFields) { + GaoAiToolResult result = new GaoAiToolResult(); + result.setStatus(status); + result.setErrorCode(errorCode); + result.setErrorMessage(errorMessage); + result.setRetryable(retryable); + result.setCandidates(candidates == null ? List.of() : new ArrayList<>(candidates)); + result.setMissingFields(missingFields == null ? List.of() : new ArrayList<>(missingFields)); + result.getSource().put("duration", Math.max(0L, System.currentTimeMillis() - startedAt)); + return result; + } + + private List parseTokens(String attachmentTokensJson) { + if (attachmentTokensJson == null || attachmentTokensJson.isBlank()) { + return List.of(); + } + try { + JsonNode node = jackson.readTree(attachmentTokensJson); + if (node == null || node.isNull()) { + return List.of(); + } + if (node.isArray()) { + List result = new ArrayList<>(); + for (JsonNode item : node) { + if (item != null && item.isTextual() && !item.asText().isBlank()) { + result.add(item.asText().trim()); + } + } + return result; + } + if (node.isTextual() && !node.asText().isBlank()) { + return List.of(node.asText().trim()); + } + } catch (Exception e) { + throw new GaoAiOperationException("VALIDATION_FAILED", "附件凭证格式无效"); + } + throw new GaoAiOperationException("VALIDATION_FAILED", "附件凭证格式无效"); + } + + private void rejectForbiddenFields(JsonNode node, String path) { + if (node == null) { + return; + } + if (node.isObject()) { + var fields = node.fields(); + while (fields.hasNext()) { + var entry = fields.next(); + String name = entry.getKey(); + if ("storeId".equals(name) || "operatorUserId".equals(name) || "userId".equals(name) + || "requestNo".equals(name) || "confirmationToken".equals(name) || "operationId".equals(name) + || "sourceSessionId".equals(name) || "requestId".equals(name)) { + throw new GaoAiOperationException("VALIDATION_FAILED", "参数不允许包含 " + name); + } + rejectForbiddenFields(entry.getValue(), path + "." + name); + } + } else if (node.isArray()) { + for (JsonNode item : node) { + rejectForbiddenFields(item, path + "[]"); + } + } + } + + private GaoAiPendingOperation safePending(GaoAiPendingOperation pending) { + try { + return pendingService.requireByOperationId(pending.getOperationId()); + } catch (RuntimeException e) { + return null; + } + } + + private void checkRate(String action, String userId, int limit) { + if (limit <= 0 || userId == null || userId.isBlank()) { + return; + } + long window = System.currentTimeMillis() / 600_000L; + String key = "GAO:AI:RATE:%s:%s:%d".formatted(action, userId, window); + String lockKey = key + ":LOCK"; + if (!locker.lock(lockKey, 1, 3_000L)) { + throw new GaoAiOperationException("RATE_LIMITED", "操作过于频繁,请稍后重试", true); + } + try { + Integer current = rateLimitRedis.get(key); + int next = current == null ? 1 : current + 1; + if (next > limit) { + throw new GaoAiOperationException("RATE_LIMITED", "操作过于频繁,请稍后重试", true); + } + rateLimitRedis.set(key, next, 600_000L); + } finally { + locker.releaseLock(lockKey); + } + } + + private void recordAudit(String action, String status, String userId, String storeId, String conversationId, + String operation, String operationId, String requestNo, String token, String riskLevel, String errorCode, + String entityType, boolean idempotentReplay, String reason, long startedAt) { + GaoAiAuditLog audit = new GaoAiAuditLog(); + audit.setAction(action); + audit.setUserId(userId); + audit.setStoreId(storeId); + audit.setConversationId(conversationId); + audit.setOperation(operation); + audit.setOperationId(operationId); + audit.setRequestNo(requestNo); + audit.setConfirmationTokenDigest(token == null ? null : auditService.digest(token)); + audit.setRiskLevel(riskLevel); + audit.setErrorCode(errorCode); + audit.setEntityType(entityType); + audit.setIdempotentReplay(idempotentReplay); + audit.setReasonDigest(reason == null ? null : auditService.digest(reason)); + audit.setToolName("operation"); + audit.setStatus(status); + audit.setDuration(Math.max(0L, System.currentTimeMillis() - startedAt)); + audit.setCreatedAt(System.currentTimeMillis()); + auditService.record(audit); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationSupport.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationSupport.java new file mode 100644 index 0000000..18442ac --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationSupport.java @@ -0,0 +1,834 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.imyeyu.api.modules.gao.entity.GaoCustomer; +import com.imyeyu.api.modules.gao.entity.GaoCustomerFollowUpReminder; +import com.imyeyu.api.modules.gao.entity.GaoEvent; +import com.imyeyu.api.modules.gao.entity.GaoEventRecord; +import com.imyeyu.api.modules.gao.entity.GaoFundRecord; +import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment; +import com.imyeyu.api.modules.gao.entity.GaoPackageConfig; +import com.imyeyu.api.modules.gao.entity.GaoPointRedeemSku; +import com.imyeyu.api.modules.gao.entity.GaoProduct; +import com.imyeyu.api.modules.gao.entity.GaoProductSku; +import com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit; +import com.imyeyu.api.modules.gao.entity.GaoSalesOrder; +import com.imyeyu.api.modules.gao.service.GaoCustomerFollowUpReminderService; +import com.imyeyu.api.modules.gao.service.GaoCustomerService; +import com.imyeyu.api.modules.gao.service.GaoEventRecordService; +import com.imyeyu.api.modules.gao.service.GaoEventService; +import com.imyeyu.api.modules.gao.service.GaoFundRecordService; +import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService; +import com.imyeyu.api.modules.gao.service.GaoPackageConfigService; +import com.imyeyu.api.modules.gao.service.GaoPointRedeemSkuService; +import com.imyeyu.api.modules.gao.service.GaoProductService; +import com.imyeyu.api.modules.gao.service.GaoProductSkuService; +import com.imyeyu.api.modules.gao.service.GaoSalesOrderService; +import com.imyeyu.api.modules.gao.vo.customer.GaoCustomerFollowUpReminderPage; +import com.imyeyu.api.modules.gao.vo.customer.GaoCustomerPage; +import com.imyeyu.api.modules.gao.vo.event.GaoEventRecordPage; +import com.imyeyu.api.modules.gao.vo.point.GaoPointRedeemSkuPage; +import com.imyeyu.api.modules.gao.vo.product.GaoProductPage; +import com.imyeyu.api.modules.gao.vo.product.GaoProductSkuUnitSelection; +import com.imyeyu.api.modules.gao.vo.salesorder.GaoSalesOrderPage; +import com.imyeyu.spring.bean.PageResult; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; + +/// GAO 智能体写操作公共支持 +/// +/// @author Codex +/// @since 2026-11-23 +@Service +@RequiredArgsConstructor +public class GaoAiOperationSupport { + + private static final ZoneId ZONE = ZoneId.systemDefault(); + private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + private static final DateTimeFormatter REQUEST_TIME = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); + + private final ObjectMapper jackson; + private final GaoCustomerService customerService; + private final GaoCustomerFollowUpReminderService followUpService; + private final GaoSalesOrderService salesOrderService; + private final GaoProductService productService; + private final GaoProductSkuService skuService; + private final GaoEventService eventService; + private final GaoEventRecordService eventRecordService; + private final GaoPackageConfigService packageConfigService; + private final GaoPointRedeemSkuService redeemSkuService; + private final GaoOrderFulfillmentService fulfillmentService; + private final GaoFundRecordService fundRecordService; + + /// 解析 JSON 对象 + /// + /// @param json JSON 文本 + /// @return JSON 对象 + public JsonNode object(String json) { + if (json == null || json.isBlank()) { + return jackson.createObjectNode(); + } + try { + JsonNode node = jackson.readTree(json); + if (node == null || !node.isObject()) { + throw new GaoAiOperationException("VALIDATION_FAILED", "操作参数必须是 JSON 对象"); + } + return node; + } catch (GaoAiOperationException e) { + throw e; + } catch (Exception e) { + throw new GaoAiOperationException("VALIDATION_FAILED", "操作参数 JSON 格式无效"); + } + } + + /// 复制为可修改对象 + /// + /// @param node 原参数 + /// @return 可修改对象 + public com.fasterxml.jackson.databind.node.ObjectNode normalizable(JsonNode node) { + if (node != null && node.isObject()) { + return ((com.fasterxml.jackson.databind.node.ObjectNode) node).deepCopy(); + } + return jackson.createObjectNode(); + } + + /// 第一个非空文本字段 + /// + /// @param node JSON 对象 + /// @param fields 字段名 + /// @return 文本,未找到返回 null + public String text(JsonNode node, String... fields) { + if (node == null) { + return null; + } + for (String field : fields) { + if (node.hasNonNull(field)) { + String value = node.get(field).asText(); + if (value != null && !value.isBlank()) { + return value.trim(); + } + } + } + return null; + } + + /// 必填文本 + /// + /// @param node JSON 对象 + /// @param label 展示名称 + /// @param fields 字段名 + /// @return 文本 + public String requiredText(JsonNode node, String label, String... fields) { + String value = text(node, fields); + if (value == null) { + throw GaoAiOperationException.clarification("请补充" + label, List.of(fields[0])); + } + return value; + } + + /// 可选长整型 + /// + /// @param node JSON 对象 + /// @param fields 字段名 + /// @return 长整型,未找到返回 null + public Long optionalLong(JsonNode node, String... fields) { + if (node == null) { + return null; + } + for (String field : fields) { + if (node.hasNonNull(field)) { + try { + return node.get(field).asLong(); + } catch (RuntimeException e) { + throw new GaoAiOperationException("VALIDATION_FAILED", field + " 必须是整数"); + } + } + } + return null; + } + + /// 必填长整型 + /// + /// @param node JSON 对象 + /// @param label 展示名称 + /// @param fields 字段名 + /// @return 长整型 + public long requiredLong(JsonNode node, String label, String... fields) { + Long value = optionalLong(node, fields); + if (value == null) { + throw GaoAiOperationException.clarification("请补充" + label, List.of(fields[0])); + } + return value; + } + + /// 可选小数 + /// + /// @param node JSON 对象 + /// @param fields 字段名 + /// @return 小数,未找到返回 null + public BigDecimal optionalDecimal(JsonNode node, String... fields) { + if (node == null) { + return null; + } + for (String field : fields) { + if (node.hasNonNull(field)) { + try { + return node.get(field).decimalValue(); + } catch (RuntimeException e) { + throw new GaoAiOperationException("VALIDATION_FAILED", field + " 必须是数字"); + } + } + } + return null; + } + + /// 必填小数 + /// + /// @param node JSON 对象 + /// @param label 展示名称 + /// @param fields 字段名 + /// @return 小数 + public BigDecimal requiredDecimal(JsonNode node, String label, String... fields) { + BigDecimal value = optionalDecimal(node, fields); + if (value == null) { + throw GaoAiOperationException.clarification("请补充" + label, List.of(fields[0])); + } + return value; + } + + /// 可选布尔 + /// + /// @param node JSON 对象 + /// @param fields 字段名 + /// @return 布尔,未找到返回 null + public Boolean optionalBoolean(JsonNode node, String... fields) { + if (node == null) { + return null; + } + for (String field : fields) { + if (node.hasNonNull(field)) { + return node.get(field).asBoolean(); + } + } + return null; + } + + /// 解析数组字段,支持数组或 JSON 字符串 + /// + /// @param node JSON 对象 + /// @param field 字段名 + /// @return 数组元素 + public List array(JsonNode node, String field) { + if (node == null || !node.hasNonNull(field)) { + return List.of(); + } + JsonNode value = node.get(field); + if (value.isArray()) { + List result = new ArrayList<>(); + value.forEach(result::add); + return result; + } + if (value.isTextual()) { + try { + JsonNode parsed = jackson.readTree(value.asText()); + if (parsed != null && parsed.isArray()) { + List result = new ArrayList<>(); + parsed.forEach(result::add); + return result; + } + } catch (Exception ignored) { + // 交由调用方返回字段错误 + } + } + throw new GaoAiOperationException("VALIDATION_FAILED", field + " 必须是数组"); + } + + /// 生成后端幂等请求号 + /// + /// @param operation 操作 + /// @return 请求号 + public String requestNo(GaoAiOperation operation) { + int random = ThreadLocalRandom.current().nextInt(0x1000000); + return "AI-%s-%s-%06x".formatted(operation.name(), LocalDateTime.now(ZONE).format(REQUEST_TIME), random); + } + + /// 金额格式化 + /// + /// @param cents 分 + /// @return 元文本 + public String money(Long cents) { + if (cents == null) { + return "0.00 元"; + } + return BigDecimal.valueOf(cents).movePointLeft(2).setScale(2, RoundingMode.HALF_UP).toPlainString() + " 元"; + } + + /// 时间格式化 + /// + /// @param millis 毫秒时间戳 + /// @return 时间文本 + public String dateTime(Long millis) { + if (millis == null) { + return "-"; + } + return LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZONE).format(DATE_TIME); + } + + /// 规范化确认短语 + /// + /// @param value 用户输入 + /// @return 规范化文本 + public String normalizePhrase(String value) { + if (value == null) { + return ""; + } + return value.replaceAll("[\\s,。!?、;:,.!?;:'\"“”‘’]", "").toLowerCase(Locale.ROOT); + } + + /// 手机号脱敏 + /// + /// @param phone 手机号 + /// @return 脱敏手机号 + public String maskPhone(String phone) { + if (phone == null || phone.length() < 7) { + return phone; + } + return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4); + } + + /// 客户摘要 + /// + /// @param customer 客户 + /// @return 摘要 + public Map customerBrief(GaoCustomer customer) { + Map result = new LinkedHashMap<>(); + result.put("id", customer.getId()); + result.put("name", customer.getName()); + result.put("code", customer.getCode()); + result.put("telephone", maskPhone(customer.getTelephone())); + return result; + } + + /// 订单摘要 + /// + /// @param order 订单 + /// @return 摘要 + public Map orderBrief(GaoSalesOrder order) { + Map result = new LinkedHashMap<>(); + result.put("id", order.getId()); + result.put("orderNo", order.getOrderNo()); + result.put("customerId", order.getCustomerId()); + result.put("saleAmount", money(order.getSaleAmount())); + result.put("paidAmount", money(order.getPaidAmount())); + result.put("pendingPaidAmount", money(order.getPendingPaidAmount())); + result.put("unpaidAmount", money(order.getUnpaidAmount())); + result.put("status", order.getStatus()); + result.put("paymentStatus", order.getPaymentStatus()); + result.put("refundStatus", order.getRefundStatus()); + return result; + } + + /// 解析客户 + /// + /// @param storeId 门店 ID + /// @param node 参数 + /// @return 客户 + public GaoCustomer customer(String storeId, JsonNode node) { + String value = text(node, "customerId", "customerKeyword", "customerName", "customerCode"); + if (value == null) { + throw GaoAiOperationException.clarification("请补充客户姓名或编码", List.of("customerKeyword")); + } + GaoCustomer customer = customerService.get(value); + if (customer != null) { + requireStore(storeId, customer.getStoreId(), "客户不属于当前门店"); + return customer; + } + customer = customerService.getByCode(storeId, value); + if (customer == null) { + customer = customerService.getByName(storeId, value); + } + if (customer != null) { + return customer; + } + GaoCustomerPage page = new GaoCustomerPage(); + page.setStoreId(storeId); + page.setKeyword(value); + page.setSize(5); + PageResult result = customerService.pageByQuery(page); + if (result != null && result.getList() != null && result.getList().size() == 1) { + return result.getList().getFirst(); + } + if (result != null && result.getList() != null && result.getList().size() > 1) { + throw GaoAiOperationException.candidates("匹配到多个客户,请选择客户编码", + result.getList().stream().map(this::customerBrief).toList()); + } + throw GaoAiOperationException.candidates("未找到客户,请确认姓名或编码", List.of()); + } + + /// 解析销售订单 + /// + /// @param storeId 门店 ID + /// @param node 参数 + /// @return 订单详情 + public GaoSalesOrder order(String storeId, JsonNode node) { + String value = text(node, "salesOrderId", "orderId", "orderNo", "orderKeyword"); + if (value == null) { + throw GaoAiOperationException.clarification("请补充订单号", List.of("orderNo")); + } + GaoSalesOrder order = salesOrderService.get(value); + if (order != null) { + requireStore(storeId, order.getStoreId(), "订单不属于当前门店"); + return salesOrderService.detail(order.getId()); + } + GaoSalesOrderPage page = new GaoSalesOrderPage(); + page.setStoreId(storeId); + page.setKeyword(value); + page.setOrderAllowed(true); + page.setSize(5); + PageResult result = salesOrderService.pageByQuery(page); + if (result != null && result.getList() != null && result.getList().size() == 1) { + return salesOrderService.detail(result.getList().getFirst().getId()); + } + if (result != null && result.getList() != null && result.getList().size() > 1) { + throw GaoAiOperationException.candidates("匹配到多个订单,请选择订单号", + result.getList().stream().map(this::orderBrief).toList()); + } + throw GaoAiOperationException.candidates("未找到订单,请确认订单号", List.of()); + } + + /// 解析 SKU 单位 + /// + /// @param storeId 门店 ID + /// @param node 参数 + /// @param purchase true 为采购/入库,false 为销售 + /// @return SKU 单位选项 + public GaoProductSkuUnitSelection skuUnit(String storeId, JsonNode node, boolean purchase) { + String skuId = text(node, "skuId"); + String unitId = text(node, "skuUnitId", "unitId"); + String unitKeyword = text(node, "unitKeyword", "unitName"); + if (skuId != null) { + GaoProductSku sku = skuService.get(skuId); + if (sku == null) { + throw new GaoAiOperationException("VALIDATION_FAILED", "SKU 不存在"); + } + requireStore(storeId, sku.getStoreId(), "SKU 不属于当前门店"); + GaoProduct product = productService.get(sku.getProductId()); + if (product == null || product.getStatus() != GaoProduct.Status.ACTIVE || sku.getStatus() != GaoProductSku.Status.ACTIVE) { + throw new GaoAiOperationException("VALIDATION_FAILED", "SKU 已停用"); + } + List units = skuService.listUnitBySkuId(skuId); + GaoProductSkuUnit unit = selectUnit(units, unitId, unitKeyword, purchase); + return new GaoProductSkuUnitSelection(product, sku, unit); + } + String keyword = requiredText(node, "skuKeyword", "productKeyword", "productName", "keyword"); + String unitText = unitKeyword; + GaoProductPage page = new GaoProductPage(); + page.setStoreId(storeId); + page.setKeyword(keyword); + page.setStatus(GaoProduct.Status.ACTIVE); + page.setSize(20); + List products = purchase + ? safeProductList(productService.pageByQuery(page)) + : productService.listSellable(page); + List candidates = new ArrayList<>(); + for (GaoProduct product : products) { + if (product == null || product.getStatus() != GaoProduct.Status.ACTIVE) { + continue; + } + for (GaoProductSku sku : product.getSkuList() == null ? List.of() : product.getSkuList()) { + if (sku == null || sku.getStatus() != GaoProductSku.Status.ACTIVE) { + continue; + } + for (GaoProductSkuUnit unit : sku.getUnitList() == null ? List.of() : sku.getUnitList()) { + if (!availableUnit(unit, purchase)) { + continue; + } + if ((contains(product.getName(), keyword) || matchesSku(sku, keyword)) + && matchesUnit(unit, unitText)) { + candidates.add(new GaoProductSkuUnitSelection(product, sku, unit)); + } + } + } + } + if (candidates.size() == 1) { + return candidates.getFirst(); + } + if (candidates.size() > 1) { + throw GaoAiOperationException.candidates("匹配到多个产品单位,请选择具体规格", + candidates.stream().map(this::skuBrief).toList()); + } + throw GaoAiOperationException.candidates("未找到可销售的产品单位,请确认产品名称", List.of()); + } + + /// 解析登记事件 + /// + /// @param storeId 门店 ID + /// @param node 参数 + /// @return 事件 + public GaoEvent event(String storeId, JsonNode node) { + String value = text(node, "eventId", "eventKeyword", "eventName"); + if (value == null) { + throw GaoAiOperationException.clarification("请补充登记事件名称", List.of("eventKeyword")); + } + List events = eventService.listValid(storeId); + List matches = events.stream() + .filter(event -> value.equals(event.getId()) || contains(event.getName(), value)) + .toList(); + if (matches.size() == 1) { + return matches.getFirst(); + } + if (matches.size() > 1) { + throw GaoAiOperationException.candidates("匹配到多个登记事件,请选择名称", + matches.stream().map(event -> brief("id", event.getId(), "name", event.getName())).toList()); + } + throw GaoAiOperationException.candidates("未找到登记事件,请确认名称", List.of()); + } + + /// 解析登记记录 + /// + /// @param storeId 门店 ID + /// @param node 参数 + /// @return 记录 + public GaoEventRecord eventRecord(String storeId, JsonNode node) { + String value = text(node, "eventRecordId", "recordId", "recordKeyword"); + if (value == null) { + throw GaoAiOperationException.clarification("请补充登记记录 ID", List.of("eventRecordId")); + } + GaoEventRecord record = eventRecordService.get(value); + if (record != null) { + requireStore(storeId, record.getStoreId(), "登记记录不属于当前门店"); + return record; + } + GaoEventRecordPage page = new GaoEventRecordPage(); + page.setStoreId(storeId); + page.setKeyword(value); + page.setSize(5); + PageResult result = eventRecordService.pageByRange(page); + if (result != null && result.getList() != null && result.getList().size() == 1) { + return result.getList().getFirst(); + } + if (result != null && result.getList() != null && result.getList().size() > 1) { + throw GaoAiOperationException.candidates("匹配到多条登记记录,请选择具体记录", + result.getList().stream().map(item -> brief("id", item.getId(), "customerId", item.getCustomerId(), + "registeredAt", dateTime(item.getRegisteredAt()))).toList()); + } + throw GaoAiOperationException.candidates("未找到登记记录", List.of()); + } + + /// 解析套餐配置 + /// + /// @param storeId 门店 ID + /// @param node 参数 + /// @return 套餐配置 + public GaoPackageConfig packageConfig(String storeId, JsonNode node) { + String value = text(node, "packageConfigId", "packageKeyword", "packageName"); + if (value == null) { + throw GaoAiOperationException.clarification("请补充套餐名称", List.of("packageKeyword")); + } + List configs = packageConfigService.listValid(storeId); + List matches = configs.stream() + .filter(config -> value.equals(config.getId()) || contains(config.getName(), value)) + .toList(); + if (matches.size() == 1) { + return matches.getFirst(); + } + if (matches.size() > 1) { + throw GaoAiOperationException.candidates("匹配到多个套餐,请选择套餐名称", + matches.stream().map(config -> brief("id", config.getId(), "name", config.getName(), + "standardAmount", money(config.getStandardAmount()))).toList()); + } + throw GaoAiOperationException.candidates("未找到可购买套餐", List.of()); + } + + /// 解析积分兑换 SKU + /// + /// @param storeId 门店 ID + /// @param node 参数 + /// @return 兑换配置 + public GaoPointRedeemSku redeemSku(String storeId, JsonNode node) { + String value = text(node, "redeemSkuId", "redeemKeyword", "productKeyword"); + if (value == null) { + throw GaoAiOperationException.clarification("请补充兑换产品名称", List.of("redeemKeyword")); + } + if (isIdLike(value)) { + try { + GaoPointRedeemSku detail = redeemSkuService.detail(storeId, value); + if (detail != null) { + return detail; + } + } catch (RuntimeException ignored) { + // 关键词不是 ID,继续按名称搜索 + } + } + GaoPointRedeemSkuPage page = new GaoPointRedeemSkuPage(); + page.setStoreId(storeId); + page.setKeyword(value); + page.setStatus(GaoPointRedeemSku.Status.ACTIVE); + page.setSize(5); + var result = redeemSkuService.pageByQuery(page); + if (result != null && result.getList() != null && result.getList().size() == 1) { + return result.getList().getFirst(); + } + if (result != null && result.getList() != null && result.getList().size() > 1) { + throw GaoAiOperationException.candidates("匹配到多个兑换产品,请选择具体产品", + result.getList().stream().map(item -> brief("id", item.getId(), "defaultPointCost", item.getDefaultPointCost())).toList()); + } + throw GaoAiOperationException.candidates("未找到可兑换产品", List.of()); + } + + /// 解析跟进提醒 + /// + /// @param storeId 门店 ID + /// @param node 参数 + /// @return 跟进提醒 + public GaoCustomerFollowUpReminder followUp(String storeId, JsonNode node) { + String value = text(node, "reminderId", "followUpId"); + if (value != null) { + GaoCustomerFollowUpReminder reminder = followUpService.get(value); + if (reminder == null) { + throw new GaoAiOperationException("VALIDATION_FAILED", "未找到跟进提醒"); + } + requireStore(storeId, reminder.getStoreId(), "跟进提醒不属于当前门店"); + return reminder; + } + GaoCustomer customer = customer(storeId, node); + GaoCustomerFollowUpReminderPage page = new GaoCustomerFollowUpReminderPage(); + page.setStoreId(storeId); + page.setCustomerId(customer.getId()); + page.setStatus(GaoCustomerFollowUpReminder.Status.PENDING); + page.setSize(5); + var result = followUpService.pageByQuery(page); + List list = result == null || result.getList() == null ? List.of() : result.getList(); + if (list.size() == 1) { + return list.getFirst(); + } + if (list.size() > 1) { + throw GaoAiOperationException.candidates("该客户有多条待完成跟进,请选择提醒 ID", + list.stream().map(item -> brief("reminderId", item.getId(), "content", item.getContent(), + "remindAt", dateTime(item.getRemindAt()))).toList()); + } + throw new GaoAiOperationException("VALIDATION_FAILED", "该客户没有待完成的跟进提醒"); + } + + /// 解析履约单 + /// + /// @param storeId 门店 ID + /// @param node 参数 + /// @return 履约单 + public GaoOrderFulfillment fulfillment(String storeId, JsonNode node) { + String id = text(node, "fulfillmentId", "fulfillmentNo"); + if (id != null) { + GaoOrderFulfillment fulfillment = fulfillmentService.detail(id); + if (fulfillment == null) { + throw new GaoAiOperationException("VALIDATION_FAILED", "未找到履约单"); + } + requireStore(storeId, fulfillment.getStoreId(), "履约单不属于当前门店"); + return fulfillment; + } + String requestNo = text(node, "fulfillmentRequestNo", "fulfillmentNo"); + String orderValue = text(node, "orderNo", "salesOrderId", "orderId"); + if (orderValue == null) { + throw GaoAiOperationException.clarification("请补充履约单 ID,或订单号加履约请求号", + List.of("fulfillmentId")); + } + GaoSalesOrder order = order(storeId, node); + List list = fulfillmentService.listBySalesOrderId(order.getId()); + String status = text(node, "status"); + List matches = list.stream() + .filter(item -> requestNo == null || requestNo.equals(item.getRequestNo())) + .filter(item -> status == null || status.equalsIgnoreCase(String.valueOf(item.getStatus()))) + .toList(); + if (matches.size() == 1) { + return matches.getFirst(); + } + if (matches.size() > 1) { + throw GaoAiOperationException.candidates("匹配到多张履约单,请选择请求号", + matches.stream().map(item -> brief("requestNo", item.getRequestNo(), + "status", item.getStatus().name(), "deliveredAt", dateTime(item.getDeliveredAt()))).toList()); + } + throw GaoAiOperationException.candidates("未找到履约单", list.stream() + .limit(10) + .map(item -> brief("requestNo", item.getRequestNo(), "status", item.getStatus().name(), + "deliveredAt", dateTime(item.getDeliveredAt()))) + .toList()); + } + + /// 解析资金流水 + /// + /// 支持内部 ID、业务请求号,或订单号加金额/操作类型定位,避免把内部 ID 暴露给模型。 + /// + /// @param storeId 门店 ID + /// @param node 参数 + /// @return 资金流水 + public GaoFundRecord fundRecord(String storeId, JsonNode node) { + String id = text(node, "fundRecordId", "fundId"); + if (id != null) { + GaoFundRecord record = fundRecordService.get(id); + if (record == null) { + throw new GaoAiOperationException("VALIDATION_FAILED", "未找到资金流水"); + } + requireStore(storeId, record.getStoreId(), "资金流水不属于当前门店"); + return record; + } + String requestNo = text(node, "fundRequestNo", "fundNo"); + if (requestNo != null) { + GaoFundRecord record = fundRecordService.getByRequestNo(storeId, requestNo); + if (record == null) { + throw new GaoAiOperationException("VALIDATION_FAILED", "未找到资金流水"); + } + return record; + } + String orderValue = text(node, "orderNo", "salesOrderId", "orderId"); + if (orderValue == null) { + throw GaoAiOperationException.clarification("请补充资金流水请求号或订单号", + List.of("fundRequestNo")); + } + GaoSalesOrder order = order(storeId, node); + Long amount = optionalLong(node, "amount"); + String operationType = text(node, "operationType", "fundOperationType"); + String status = text(node, "fundStatus", "status"); + List records = order.getFundRecordList() == null ? List.of() : order.getFundRecordList(); + List matches = records.stream() + .filter(item -> amount == null || amount.equals(item.getAmount())) + .filter(item -> operationType == null || operationType.equalsIgnoreCase(String.valueOf(item.getOperationType()))) + .filter(item -> status == null || status.equalsIgnoreCase(String.valueOf(item.getStatus()))) + .toList(); + if (matches.size() == 1) { + return matches.getFirst(); + } + if (matches.size() > 1) { + throw GaoAiOperationException.candidates("匹配到多笔资金流水,请选择请求号", + matches.stream().map(this::fundBrief).toList()); + } + throw GaoAiOperationException.candidates("未找到资金流水", records.stream().map(this::fundBrief).toList()); + } + + /// 校验门店一致 + /// + /// @param expected 期望门店 + /// @param actual 实际门店 + /// @param message 错误消息 + public void requireStore(String expected, String actual, String message) { + if (expected == null || !expected.equals(actual)) { + throw new GaoAiOperationException("STORE_SCOPE_DENIED", message); + } + } + + /// 计算行金额 + /// + /// @param unitPrice 单价,分 + /// @param quantity 数量 + /// @return 行金额,分 + public long lineAmount(long unitPrice, BigDecimal quantity) { + try { + return BigDecimal.valueOf(unitPrice).multiply(quantity).setScale(0, RoundingMode.UNNECESSARY).longValueExact(); + } catch (ArithmeticException e) { + throw new GaoAiOperationException("VALIDATION_FAILED", "数量与单价无法得到整数分金额"); + } + } + + /// 判断文本包含关系 + /// + /// @param source 源文本 + /// @param keyword 关键词 + /// @return true 为匹配 + public boolean contains(String source, String keyword) { + if (source == null || keyword == null) { + return false; + } + return source.toLowerCase(Locale.ROOT).contains(keyword.toLowerCase(Locale.ROOT)); + } + + private GaoProductSkuUnit selectUnit(List units, String unitId, String unitKeyword, boolean purchase) { + List available = units.stream().filter(unit -> availableUnit(unit, purchase)).toList(); + if (unitId != null) { + return available.stream().filter(unit -> unitId.equals(unit.getId())).findFirst() + .orElseThrow(() -> new GaoAiOperationException("VALIDATION_FAILED", "SKU 单位不存在或不可用")); + } + if (unitKeyword != null) { + List matches = available.stream().filter(unit -> contains(unit.getName(), unitKeyword)).toList(); + if (matches.size() == 1) { + return matches.getFirst(); + } + if (matches.size() > 1) { + throw GaoAiOperationException.candidates("匹配到多个单位,请选择单位", + matches.stream().map(unit -> brief("id", unit.getId(), "name", unit.getName())).toList()); + } + throw new GaoAiOperationException("VALIDATION_FAILED", "SKU 单位不存在或不可用"); + } + if (available.size() == 1) { + return available.getFirst(); + } + throw GaoAiOperationException.candidates("请选择 SKU 单位", + available.stream().map(unit -> brief("id", unit.getId(), "name", unit.getName(), + "salePrice", money(unit.getSalePrice()))).toList()); + } + + private boolean availableUnit(GaoProductSkuUnit unit, boolean purchase) { + return unit != null && (purchase ? Boolean.TRUE.equals(unit.getAllowPurchase()) : Boolean.TRUE.equals(unit.getAllowSale())); + } + + private boolean matchesSku(GaoProductSku sku, String keyword) { + return contains(sku.getName(), keyword) || contains(sku.getCode(), keyword) || contains(sku.getBarcode(), keyword); + } + + private boolean matchesUnit(GaoProductSkuUnit unit, String keyword) { + return keyword == null || contains(unit.getName(), keyword) || keyword.equals(unit.getId()); + } + + private boolean isIdLike(String value) { + return value != null && (value.matches("[0-9a-fA-F]{32}") || value.matches("[0-9a-fA-F-]{36}")); + } + + private List safeProductList(PageResult result) { + return result == null || result.getList() == null ? List.of() : result.getList(); + } + + private Map fundBrief(GaoFundRecord record) { + Map result = new LinkedHashMap<>(); + result.put("requestNo", record.getRequestNo()); + result.put("amount", money(record.getAmount())); + result.put("operationType", record.getOperationType()); + result.put("status", record.getStatus()); + result.put("occurredAt", dateTime(record.getOccurredAt())); + return result; + } + + private Map skuBrief(GaoProductSkuUnitSelection selection) { + Map result = new LinkedHashMap<>(); + result.put("productName", selection.getProduct().getName()); + result.put("skuId", selection.getSku().getId()); + result.put("skuName", selection.getSku().getName()); + result.put("skuCode", selection.getSku().getCode()); + result.put("unitId", selection.getUnit().getId()); + result.put("unitName", selection.getUnit().getName()); + result.put("salePrice", money(selection.getUnit().getSalePrice())); + return result; + } + + /// 构造允许 null 值的候选摘要 + /// + /// @param keyValues 键值对 + /// @return 有序 Map + public Map brief(Object... keyValues) { + Map result = new LinkedHashMap<>(); + for (int index = 0; index + 1 < keyValues.length; index += 2) { + result.put(String.valueOf(keyValues[index]), keyValues[index + 1]); + } + return result; + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPendingOperation.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPendingOperation.java new file mode 100644 index 0000000..90b6cdf --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPendingOperation.java @@ -0,0 +1,154 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// GAO 智能体待确认操作 +/// +/// 该对象只保存在服务端 Redis,`confirmationToken` 本身不落库, +/// 只保存其 SHA-256 摘要。 +/// +/// @author Codex +/// @since 2026-11-23 +@Data +public class GaoAiPendingOperation { + + /// 待确认操作状态 + public enum Status { + + /// 待确认 + PENDING, + + /// 提交中 + COMMITTING, + + /// 已成功 + SUCCEEDED, + + /// 最终失败 + FAILED, + + /// 已取消 + CANCELLED, + + /// 已过期 + EXPIRED, + + /// 已被新的待确认操作替代 + SUPERSEDED + } + + /// 公开操作 ID,前端卡片使用 + private String operationId; + + /// 确认 token 的 SHA-256 摘要 + private String tokenHash; + + /// 操作代码 + private String operation; + + /// 操作标题 + private String title; + + /// 风险级别 + private String riskLevel; + + /// 结果实体类型 + private String entityType; + + /// 用户 ID + private String userId; + + /// 门店 ID + private String storeId; + + /// Dify 会话 ID + private String conversationId; + + /// 产生该操作的 AI 会话 ID + private String sourceSessionId; + + /// 后端生成的幂等请求号 + private String requestNo; + + /// 标准化后的业务参数 JSON + private String argumentsJson; + + /// 附件 token 列表 + private List attachmentTokens = new ArrayList<>(); + + /// 预览结构 + private Map preview = new LinkedHashMap<>(); + + /// 预览文本 + private String previewText; + + /// 风险影响说明 + private String impactText; + + /// 精确确认短语 + private String requiredPhrase; + + /// 是否必须填写原因 + private boolean reasonRequired; + + /// 当前状态 + private Status status = Status.PENDING; + + /// 创建时间 + private long createdAt; + + /// 更新时间 + private long updatedAt; + + /// 过期时间 + private long expiresAt; + + /// 提交次数 + private int attemptCount; + + /// 提交原因 + private String commitReason; + + /// 最近一次错误码 + private String lastErrorCode; + + /// 最近一次错误消息 + private String lastErrorMessage; + + /// 成功结果实体 ID + private String resultEntityId; + + /// 成功结果实体单号 + private String resultEntityNo; + + /// 成功结果文本 + private String resultText; + + /// 成功时间 + private long committedAt; + + /// 取消时间 + private long cancelledAt; + + /// 判断是否仍可确认 + /// + /// @param now 当前时间 + /// @return true 为可确认 + public boolean confirmable(long now) { + return status == Status.PENDING && now < expiresAt; + } + + /// 判断是否属于指定用户和门店 + /// + /// @param userId 用户 ID + /// @param storeId 门店 ID + /// @return true 为匹配 + public boolean belongsTo(String userId, String storeId) { + return userId != null && userId.equals(this.userId) && storeId != null && storeId.equals(this.storeId); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPendingOperationService.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPendingOperationService.java new file mode 100644 index 0000000..a4d4481 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPendingOperationService.java @@ -0,0 +1,79 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import java.util.List; + +/// GAO 智能体待确认操作服务 +/// +/// @author Codex +/// @since 2026-11-23 +public interface GaoAiPendingOperationService { + + /// 创建待确认操作 + /// + /// @param context 执行上下文 + /// @param definition 操作定义 + /// @param requestNo 后端生成的幂等请求号 + /// @param argumentsJson 标准化业务参数 + /// @param attachmentTokens 附件凭证 + /// @param prepared 准备结果 + /// @return 待确认操作,包含原始 token 的创建结果 + Created create(GaoAiOperationContext context, GaoAiOperationDefinition definition, String requestNo, + String argumentsJson, List attachmentTokens, GaoAiPreparedOperation prepared); + + /// 查询用户和门店当前活跃的待确认操作 + /// + /// @param userId 用户 ID + /// @param storeId 门店 ID + /// @param conversationId Dify 会话 ID,可为空 + /// @return 待确认操作,无则为 null + GaoAiPendingOperation findActive(String userId, String storeId, String conversationId); + + /// 按来源 AI 会话查询待确认操作 + /// + /// @param sourceSessionId 来源 AI 会话 ID + /// @return 待确认操作,无则为 null + GaoAiPendingOperation findActiveBySourceSession(String sourceSessionId); + + /// 按确认 token 获取待确认操作 + /// + /// @param token 确认 token + /// @return 待确认操作 + GaoAiPendingOperation requireByToken(String token); + + /// 按公开操作 ID 获取待确认操作 + /// + /// @param operationId 公开操作 ID + /// @return 待确认操作 + GaoAiPendingOperation requireByOperationId(String operationId); + + /// 绑定 Dify 会话 ID + /// + /// @param pending 待确认操作 + /// @param conversationId Dify 会话 ID + void bindConversation(GaoAiPendingOperation pending, String conversationId); + + /// 为下一轮文本确认签发新的 token + /// + /// 只更新服务端摘要,旧 token 立即失效。 + /// + /// @param pending 待确认操作 + /// @return 新的原始 token + String issueToken(GaoAiPendingOperation pending); + + /// 保存待确认操作 + /// + /// @param pending 待确认操作 + void save(GaoAiPendingOperation pending); + + /// 清理当前活跃索引 + /// + /// @param pending 待确认操作 + void clearActive(GaoAiPendingOperation pending); + + /// 创建结果 + /// + /// @param pending 待确认操作 + /// @param token 原始确认 token,只在创建时返回一次 + record Created(GaoAiPendingOperation pending, String token) { + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPendingOperationServiceImplement.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPendingOperationServiceImplement.java new file mode 100644 index 0000000..b35d395 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPendingOperationServiceImplement.java @@ -0,0 +1,310 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel; +import com.imyeyu.spring.util.Redis; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Service; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Base64; +import java.util.List; + +/// GAO 智能体待确认操作服务实现 +/// +/// @author Codex +/// @since 2026-11-23 +@Service +@RequiredArgsConstructor +public class GaoAiPendingOperationServiceImplement implements GaoAiPendingOperationService { + + private static final String TOKEN_PREFIX = "GAO:AI:OP:TOKEN:"; + private static final String ID_PREFIX = "GAO:AI:OP:ID:"; + private static final String ACTIVE_PREFIX = "GAO:AI:OP:ACTIVE:"; + private static final String SESSION_PREFIX = "GAO:AI:OP:SESSION:"; + private static final String LOCK_PREFIX = "GAO:AI:OP:LOCK:"; + + private final GaoAiProperties properties; + +// @Qualifier("redisGaoAiOperation") + private Redis redis; + +// @Qualifier("redisGaoAiOperationIndex") + private Redis indexRedis; + +// @Qualifier("redisLocker") + private Redis locker; + + private final SecureRandom secureRandom = new SecureRandom(); + + @Override + public Created create(GaoAiOperationContext context, GaoAiOperationDefinition definition, String requestNo, + String argumentsJson, List attachmentTokens, GaoAiPreparedOperation prepared) { + String lockKey = LOCK_PREFIX + context.getUserId() + ":" + context.getStoreId(); + if (!locker.lock(lockKey, 1, 5_000L)) { + throw new GaoAiOperationException("CONFIRMATION_IN_PROGRESS", "操作正在处理,请稍后重试", true); + } + try { + supersedeActive(context.getUserId(), context.getStoreId()); + long now = System.currentTimeMillis(); + long ttlMs = Math.max(60_000L, properties.getConfirmationTtlSeconds() * 1000L); + String token = newToken(); + GaoAiPendingOperation pending = new GaoAiPendingOperation(); + pending.setOperationId(newOperationId()); + pending.setTokenHash(hash(token)); + pending.setOperation(definition.code()); + pending.setTitle(definition.title()); + RiskLevel riskLevel = prepared.getRiskLevel() == null ? definition.getRiskLevel() : prepared.getRiskLevel(); + pending.setRiskLevel(riskLevel.name()); + pending.setEntityType(definition.entityType()); + pending.setUserId(context.getUserId()); + pending.setStoreId(context.getStoreId()); + pending.setConversationId(blankToNull(context.getConversationId())); + pending.setSourceSessionId(context.getSession() == null ? null : context.getSession().getSessionId()); + pending.setRequestNo(requestNo); + pending.setArgumentsJson(argumentsJson); + pending.setAttachmentTokens(attachmentTokens == null ? List.of() : List.copyOf(attachmentTokens)); + pending.setPreview(prepared.getPreview()); + pending.setPreviewText(prepared.getPreviewText()); + pending.setImpactText(prepared.getImpactText()); + pending.setRequiredPhrase(prepared.getRequiredPhrase()); + pending.setReasonRequired(prepared.isReasonRequired() || definition.isReasonRequired()); + pending.setStatus(GaoAiPendingOperation.Status.PENDING); + pending.setCreatedAt(now); + pending.setUpdatedAt(now); + pending.setExpiresAt(now + ttlMs); + save(pending); + return new Created(pending, token); + } finally { + locker.releaseLock(lockKey); + } + } + + @Override + public GaoAiPendingOperation findActive(String userId, String storeId, String conversationId) { + if (isBlank(userId) || isBlank(storeId)) { + return null; + } + String operationId = indexRedis.get(activeKey(userId, storeId)); + if (isBlank(operationId)) { + return null; + } + GaoAiPendingOperation pending = redis.get(idKey(operationId)); + if (pending == null) { + indexRedis.destroy(activeKey(userId, storeId)); + return null; + } + if (!pending.belongsTo(userId, storeId)) { + indexRedis.destroy(activeKey(userId, storeId)); + return null; + } + if (pending.getStatus() == GaoAiPendingOperation.Status.PENDING && pending.getExpiresAt() <= System.currentTimeMillis()) { + pending.setStatus(GaoAiPendingOperation.Status.EXPIRED); + save(pending); + return null; + } + if (pending.getStatus() != GaoAiPendingOperation.Status.PENDING) { + clearActive(pending); + return null; + } + if (!isBlank(conversationId) && !isBlank(pending.getConversationId()) + && !conversationId.equals(pending.getConversationId())) { + return null; + } + return pending; + } + + @Override + public GaoAiPendingOperation findActiveBySourceSession(String sourceSessionId) { + if (isBlank(sourceSessionId)) { + return null; + } + String operationId = indexRedis.get(sessionKey(sourceSessionId)); + if (isBlank(operationId)) { + return null; + } + GaoAiPendingOperation pending = redis.get(idKey(operationId)); + if (pending == null || pending.getStatus() != GaoAiPendingOperation.Status.PENDING + || pending.getExpiresAt() <= System.currentTimeMillis()) { + indexRedis.destroy(sessionKey(sourceSessionId)); + return null; + } + return pending; + } + + @Override + public GaoAiPendingOperation requireByToken(String token) { + if (isBlank(token)) { + throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "缺少确认凭证"); + } + String tokenHash = hash(token.trim()); + GaoAiPendingOperation pending = redis.get(tokenKey(tokenHash)); + if (pending == null || !tokenHash.equals(pending.getTokenHash())) { + throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "确认凭证无效或已过期"); + } + return pending; + } + + @Override + public GaoAiPendingOperation requireByOperationId(String operationId) { + if (isBlank(operationId)) { + throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "缺少操作 ID"); + } + GaoAiPendingOperation pending = redis.get(idKey(operationId.trim())); + if (pending == null) { + throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "操作不存在或已过期"); + } + return pending; + } + + @Override + public void bindConversation(GaoAiPendingOperation pending, String conversationId) { + if (pending == null || isBlank(conversationId)) { + return; + } + if (isBlank(pending.getConversationId())) { + pending.setConversationId(conversationId.trim()); + pending.setUpdatedAt(System.currentTimeMillis()); + save(pending); + } + } + + @Override + public String issueToken(GaoAiPendingOperation pending) { + if (pending == null) { + throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "没有可确认的操作"); + } + String lockKey = LOCK_PREFIX + "TOKEN:" + pending.getOperationId(); + if (!locker.lock(lockKey, 1, 5_000L)) { + throw new GaoAiOperationException("CONFIRMATION_IN_PROGRESS", "操作正在处理,请稍后重试", true); + } + try { + GaoAiPendingOperation current = redis.get(idKey(pending.getOperationId())); + if (current == null || current.getStatus() != GaoAiPendingOperation.Status.PENDING) { + throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "没有可确认的操作"); + } + if (current.getExpiresAt() <= System.currentTimeMillis()) { + throw new GaoAiOperationException("CONFIRMATION_EXPIRED", "确认已过期,请重新发起操作"); + } + String token = newToken(); + current.setTokenHash(hash(token)); + current.setUpdatedAt(System.currentTimeMillis()); + save(current); + pending.setTokenHash(current.getTokenHash()); + pending.setUpdatedAt(current.getUpdatedAt()); + return token; + } finally { + locker.releaseLock(lockKey); + } + } + + @Override + public void save(GaoAiPendingOperation pending) { + if (pending == null || isBlank(pending.getOperationId())) { + return; + } + long now = System.currentTimeMillis(); + pending.setUpdatedAt(now); + long remain = Math.max(1_000L, pending.getExpiresAt() - now); + long ttlMs = remain + Math.max(0L, properties.getResultTtlSeconds() * 1000L); + redis.set(idKey(pending.getOperationId()), pending, ttlMs); + if (!isBlank(pending.getTokenHash())) { + redis.set(tokenKey(pending.getTokenHash()), pending, ttlMs); + } + if (pending.getStatus() == GaoAiPendingOperation.Status.PENDING) { + indexRedis.set(activeKey(pending.getUserId(), pending.getStoreId()), pending.getOperationId(), ttlMs); + if (!isBlank(pending.getSourceSessionId())) { + indexRedis.set(sessionKey(pending.getSourceSessionId()), pending.getOperationId(), ttlMs); + } + } else { + clearActive(pending); + } + } + + @Override + public void clearActive(GaoAiPendingOperation pending) { + if (pending == null) { + return; + } + if (!isBlank(pending.getUserId()) && !isBlank(pending.getStoreId())) { + indexRedis.destroy(activeKey(pending.getUserId(), pending.getStoreId())); + } + if (!isBlank(pending.getSourceSessionId())) { + indexRedis.destroy(sessionKey(pending.getSourceSessionId())); + } + } + + private void supersedeActive(String userId, String storeId) { + String operationId = indexRedis.get(activeKey(userId, storeId)); + if (isBlank(operationId)) { + return; + } + GaoAiPendingOperation old = redis.get(idKey(operationId)); + if (old == null) { + indexRedis.destroy(activeKey(userId, storeId)); + return; + } + if (old.getStatus() == GaoAiPendingOperation.Status.COMMITTING) { + throw new GaoAiOperationException("CONFIRMATION_IN_PROGRESS", "上一个操作正在提交,请稍后重试", true); + } + if (old.getStatus() == GaoAiPendingOperation.Status.PENDING) { + old.setStatus(GaoAiPendingOperation.Status.SUPERSEDED); + save(old); + } else { + clearActive(old); + } + } + + private String newToken() { + byte[] bytes = new byte[32]; + secureRandom.nextBytes(bytes); + return "op_" + Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private String newOperationId() { + byte[] bytes = new byte[18]; + secureRandom.nextBytes(bytes); + return "pub_" + Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private String hash(String value) { + try { + byte[] bytes = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); + StringBuilder result = new StringBuilder(bytes.length * 2); + for (byte item : bytes) { + result.append("%02x".formatted(item & 0xff)); + } + return result.toString(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("当前 JDK 不支持 SHA-256", e); + } + } + + private String tokenKey(String hash) { + return TOKEN_PREFIX + hash; + } + + private String idKey(String operationId) { + return ID_PREFIX + operationId; + } + + private String activeKey(String userId, String storeId) { + return ACTIVE_PREFIX + userId + ":" + storeId; + } + + private String sessionKey(String sessionId) { + return SESSION_PREFIX + sessionId; + } + + private String blankToNull(String value) { + return isBlank(value) ? null : value.trim(); + } + + private boolean isBlank(String value) { + return value == null || value.isBlank(); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPreparedOperation.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPreparedOperation.java new file mode 100644 index 0000000..63eabb0 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiPreparedOperation.java @@ -0,0 +1,50 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel; +import lombok.Data; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// GAO 智能体写操作准备结果 +/// +/// @author Codex +/// @since 2026-11-23 +@Data +public class GaoAiPreparedOperation { + + /// 标准 JSON 参数,commit 时直接读取,不再接受模型输入 + private String argumentsJson; + + /// 预览结构 + private Map preview = new LinkedHashMap<>(); + + /// 预览文本 + private String previewText; + + /// 风险影响说明 + private String impactText; + + /// 风险级别,默认取操作定义 + private RiskLevel riskLevel; + + /// 精确确认短语,破坏性/敏感操作为必填 + private String requiredPhrase; + + /// 是否必须填写原因 + private boolean reasonRequired; + + /// 警告 + private List warnings = new ArrayList<>(); + + /// 缺失字段 + private List missingFields = new ArrayList<>(); + + /// 候选列表,存在歧义时返回 + private List candidates = new ArrayList<>(); + + /// 实体标题,用于卡片 + private String title; +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiToolAuthorizer.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiToolAuthorizer.java new file mode 100644 index 0000000..5fad6a1 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiToolAuthorizer.java @@ -0,0 +1,62 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.imyeyu.api.modules.gao.bean.GaoPermissionCode; +import com.imyeyu.api.modules.user.service.PermissionChecker; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.Set; + +/// GAO 智能体写工具授权器 +/// +/// 权限实时按会话用户查询,prepare 和 commit 都会校验。 +/// +/// @author Codex +/// @since 2026-11-23 +@Service +@RequiredArgsConstructor +public class GaoAiToolAuthorizer { + + private final PermissionChecker permissionChecker; + + /// 校验操作定义要求的全部权限 + /// + /// @param userId 用户 ID + /// @param definition 操作定义 + public void check(String userId, GaoAiOperationDefinition definition) { + if (definition == null) { + throw new GaoAiOperationException("FEATURE_DISABLED", "该操作未开放"); + } + for (GaoPermissionCode code : definition.getPermissions()) { + checkCode(userId, code); + } + } + + /// 校验单个权限 + /// + /// @param userId 用户 ID + /// @param code 权限码 + public void checkCode(String userId, GaoPermissionCode code) { + if (!hasCode(userId, code)) { + throw new GaoAiOperationException("PERMISSION_DENIED", + "当前账号缺少权限:%s".formatted(code.getDefaultName())); + } + } + + /// 判断是否拥有权限 + /// + /// @param userId 用户 ID + /// @param code 权限码 + /// @return true 为拥有 + public boolean hasCode(String userId, GaoPermissionCode code) { + if (userId == null || userId.isBlank() || code == null) { + return false; + } + Set permissionCodes = permissionChecker.codeSet(userId); + return permissionCodes != null && permissionCodes.contains(buildKey(code)); + } + + private String buildKey(GaoPermissionCode code) { + return code.getModuleCode().name() + ":" + code.getValue(); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/CustomerOperationHandler.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/CustomerOperationHandler.java new file mode 100644 index 0000000..6b4fd15 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/CustomerOperationHandler.java @@ -0,0 +1,419 @@ +package com.imyeyu.api.modules.gao.ai.operation.handler; + +import com.fasterxml.jackson.databind.JsonNode; +import com.imyeyu.api.modules.common.entity.Attachment; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentToken; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiCommitResult; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationContext; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationHandler; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationSupport; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPreparedOperation; +import com.imyeyu.api.modules.gao.entity.GaoCustomer; +import com.imyeyu.api.modules.gao.entity.GaoCustomerFollowUpReminder; +import com.imyeyu.api.modules.gao.service.GaoCustomerFollowUpReminderService; +import com.imyeyu.api.modules.gao.service.GaoCustomerService; +import com.imyeyu.api.modules.user.bean.Gender; +import com.imyeyu.api.modules.user.entity.User; +import com.imyeyu.api.modules.user.service.UserService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// 客户与客户跟进写操作处理器 +/// +/// @author Codex +/// @since 2026-11-23 +@Component +@RequiredArgsConstructor +public class CustomerOperationHandler implements GaoAiOperationHandler { + + private static final ZoneId ZONE = ZoneId.systemDefault(); + private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + + private final GaoAiOperationSupport support; + private final GaoCustomerService customerService; + private final GaoCustomerFollowUpReminderService followUpService; + private final UserService userService; + + @Override + public Set supports() { + return Set.of(GaoAiOperation.CUSTOMER_CREATE, GaoAiOperation.CUSTOMER_UPDATE, + GaoAiOperation.FOLLOW_UP_CREATE, GaoAiOperation.FOLLOW_UP_UPDATE, GaoAiOperation.FOLLOW_UP_COMPLETE); + } + + @Override + public GaoAiPreparedOperation prepare(GaoAiOperationContext context, GaoAiOperationDefinition definition, + JsonNode arguments, List attachments) { + return switch (definition.getOperation()) { + case CUSTOMER_CREATE -> prepareCustomerCreate(arguments, attachments); + case CUSTOMER_UPDATE -> prepareCustomerUpdate(context, arguments, attachments); + case FOLLOW_UP_CREATE -> prepareFollowUpCreate(context, arguments, attachments); + case FOLLOW_UP_UPDATE -> prepareFollowUpUpdate(context, arguments, attachments); + case FOLLOW_UP_COMPLETE -> prepareFollowUpComplete(context, arguments); + default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作"); + }; + } + + @Override + public GaoAiCommitResult commit(GaoAiOperationContext context, GaoAiPendingOperation pending, + JsonNode arguments, List attachments) { + return switch (GaoAiOperation.valueOf(pending.getOperation())) { + case CUSTOMER_CREATE -> commitCustomerCreate(context, arguments, attachments); + case CUSTOMER_UPDATE -> commitCustomerUpdate(arguments, attachments); + case FOLLOW_UP_CREATE -> commitFollowUpCreate(arguments, attachments); + case FOLLOW_UP_UPDATE -> commitFollowUpUpdate(arguments, attachments); + case FOLLOW_UP_COMPLETE -> commitFollowUpComplete(arguments); + default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作"); + }; + } + + private GaoAiPreparedOperation prepareCustomerCreate(JsonNode arguments, List attachments) { + String name = support.requiredText(arguments, "客户姓名", "name", "customerName"); + com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments); + normalized.put("name", name); + Map preview = new LinkedHashMap<>(); + preview.put("name", name); + preview.put("gender", support.text(arguments, "gender")); + preview.put("birthdate", support.text(arguments, "birthdate")); + preview.put("telephone", support.maskPhone(support.text(arguments, "telephone"))); + preview.put("address", support.text(arguments, "address")); + preview.put("remark", support.text(arguments, "remark")); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("新建客户"); + result.setPreviewText(""" + ### 待确认:新建客户 + + 姓名:%s + 性别:%s + 出生日期:%s + 电话:%s + 地址:%s + 备注:%s + 凭证:%d 张 + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(name, blank(support.text(arguments, "gender")), blank(support.text(arguments, "birthdate")), + blank(support.maskPhone(support.text(arguments, "telephone"))), blank(support.text(arguments, "address")), + blank(support.text(arguments, "remark")), attachments.size())); + return result; + } + + private GaoAiPreparedOperation prepareCustomerUpdate(GaoAiOperationContext context, JsonNode arguments, + List attachments) { + GaoCustomer customer = support.customer(context.getStoreId(), arguments); + com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments); + normalized.put("customerId", customer.getId()); + Map preview = new LinkedHashMap<>(); + preview.put("customer", support.customerBrief(customer)); + preview.put("changes", changeSummary(arguments, "name", "gender", "birthdate", "telephone", "address", "remark", "disease")); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("修改客户资料"); + result.setPreviewText(""" + ### 待确认:修改客户资料 + + 客户:%s(%s) + 修改项:%s + 凭证:%d 张 + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(customer.getName(), blank(customer.getCode()), preview.get("changes"), attachments.size())); + return result; + } + + private GaoAiPreparedOperation prepareFollowUpCreate(GaoAiOperationContext context, JsonNode arguments, + List attachments) { + GaoCustomer customer = support.customer(context.getStoreId(), arguments); + User responsible = responsibleUser(context, arguments); + String content = support.requiredText(arguments, "跟进内容", "content", "remark"); + long remindAt = requiredRemindAt(arguments); + com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments); + normalized.put("customerId", customer.getId()); + normalized.put("responsibleUserId", responsible.getId()); + normalized.put("content", content); + normalized.put("remindAt", remindAt); + Map preview = new LinkedHashMap<>(); + preview.put("customer", support.customerBrief(customer)); + preview.put("responsibleUser", responsible.getName()); + preview.put("content", content); + preview.put("remindAt", support.dateTime(remindAt)); + preview.put("internalNotifyEnabled", support.optionalBoolean(arguments, "internalNotifyEnabled")); + preview.put("smsNotifyEnabled", support.optionalBoolean(arguments, "smsNotifyEnabled")); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("新建客户跟进提醒"); + result.setPreviewText(""" + ### 待确认:新建客户跟进提醒 + + 客户:%s(%s) + 负责人:%s + 内容:%s + 提醒时间:%s + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(customer.getName(), blank(customer.getCode()), responsible.getName(), content, + support.dateTime(remindAt))); + return result; + } + + private GaoAiPreparedOperation prepareFollowUpUpdate(GaoAiOperationContext context, JsonNode arguments, + List attachments) { + GaoCustomerFollowUpReminder reminder = support.followUp(context.getStoreId(), arguments); + com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments); + normalized.put("reminderId", reminder.getId()); + Long remindAt = support.optionalLong(arguments, "remindAt"); + if (remindAt == null && support.text(arguments, "remindAtText", "remindTime") != null) { + remindAt = requiredRemindAt(arguments); + normalized.put("remindAt", remindAt); + } + Map preview = new LinkedHashMap<>(); + preview.put("reminderId", reminder.getId()); + preview.put("customerId", reminder.getCustomerId()); + preview.put("content", support.text(arguments, "content", "remark") == null ? reminder.getContent() + : support.text(arguments, "content", "remark")); + preview.put("remindAt", support.dateTime(remindAt == null ? reminder.getRemindAt() : remindAt)); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("修改客户跟进提醒"); + result.setPreviewText(""" + ### 待确认:修改客户跟进提醒 + + 提醒 ID:%s + 客户 ID:%s + 内容:%s + 提醒时间:%s + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(reminder.getId(), reminder.getCustomerId(), preview.get("content"), preview.get("remindAt"))); + return result; + } + + private GaoAiPreparedOperation prepareFollowUpComplete(GaoAiOperationContext context, JsonNode arguments) { + GaoCustomerFollowUpReminder reminder = support.followUp(context.getStoreId(), arguments); + com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments); + normalized.put("reminderId", reminder.getId()); + Map preview = new LinkedHashMap<>(); + preview.put("reminderId", reminder.getId()); + preview.put("customerId", reminder.getCustomerId()); + preview.put("content", reminder.getContent()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("完成客户跟进提醒"); + result.setPreviewText(""" + ### 待确认:完成客户跟进提醒 + + 提醒 ID:%s + 客户 ID:%s + 内容:%s + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(reminder.getId(), reminder.getCustomerId(), reminder.getContent())); + return result; + } + + private GaoAiCommitResult commitCustomerCreate(GaoAiOperationContext context, JsonNode arguments, + List attachments) { + GaoCustomer customer = new GaoCustomer(); + customer.setName(support.requiredText(arguments, "name", "customerName")); + customer.setCode(support.text(arguments, "code")); + customer.setGender(gender(support.text(arguments, "gender"))); + customer.setBirthdate(birthdate(support.text(arguments, "birthdate"))); + customer.setTelephone(support.text(arguments, "telephone")); + customer.setAddress(support.text(arguments, "address")); + customer.setRemark(support.text(arguments, "remark")); + customer.setDisease(support.text(arguments, "disease")); + customer.setAttachmentList(attachments); + // storeId 只来自已认证会话,模型参数不包含门店 + customer.setStoreId(context.getStoreId()); + customerService.create(customer); + return GaoAiCommitResult.success(GaoAiOperation.CUSTOMER_CREATE.name(), "CUSTOMER", customer.getId(), + customer.getCode(), "已创建客户 %s。".formatted(customer.getName())); + } + + private GaoAiCommitResult commitCustomerUpdate(JsonNode arguments, List attachments) { + GaoCustomer existing = customerService.get(support.requiredText(arguments, "customerId", "id")); + if (existing == null) { + throw new GaoAiOperationException("STALE_PREVIEW", "客户已不存在,请重新发起"); + } + GaoCustomer customer = new GaoCustomer(); + customer.setId(existing.getId()); + customer.setStoreId(existing.getStoreId()); + customer.setName(defaultText(support.text(arguments, "name", "customerName"), existing.getName())); + customer.setCode(defaultText(support.text(arguments, "code"), existing.getCode())); + customer.setGender(support.text(arguments, "gender") == null ? existing.getGender() : gender(support.text(arguments, "gender"))); + customer.setBirthdate(support.text(arguments, "birthdate") == null ? existing.getBirthdate() : birthdate(support.text(arguments, "birthdate"))); + customer.setBirthdateCalendar(existing.getBirthdateCalendar()); + customer.setTelephone(defaultText(support.text(arguments, "telephone"), existing.getTelephone())); + customer.setAddress(defaultText(support.text(arguments, "address"), existing.getAddress())); + customer.setRemark(support.text(arguments, "remark")); + customer.setDisease(defaultText(support.text(arguments, "disease"), existing.getDisease())); + customer.setConditioningPart(existing.getConditioningPart()); + customer.setIntroducerCustomerId(existing.getIntroducerCustomerId()); + if (attachments.isEmpty()) { + customerService.update(customer); + } else { + customer.setAttachmentList(attachments); + customerService.updateWithAttachment(customer); + } + return GaoAiCommitResult.success(GaoAiOperation.CUSTOMER_UPDATE.name(), "CUSTOMER", customer.getId(), + customer.getCode(), "已更新客户 %s 的资料。".formatted(customer.getName())); + } + + private GaoAiCommitResult commitFollowUpCreate(JsonNode arguments, List attachments) { + GaoCustomer customer = customerService.get(support.requiredText(arguments, "customerId", "id")); + if (customer == null) { + throw new GaoAiOperationException("STALE_PREVIEW", "客户已不存在,请重新发起"); + } + GaoCustomerFollowUpReminder reminder = new GaoCustomerFollowUpReminder(); + reminder.setStoreId(customer.getStoreId()); + reminder.setCustomerId(customer.getId()); + reminder.setResponsibleUserId(support.requiredText(arguments, "responsibleUserId")); + reminder.setContent(support.requiredText(arguments, "content", "remark")); + reminder.setRemindAt(requiredRemindAt(arguments)); + reminder.setInternalNotifyEnabled(support.optionalBoolean(arguments, "internalNotifyEnabled")); + reminder.setSmsNotifyEnabled(support.optionalBoolean(arguments, "smsNotifyEnabled")); + reminder.setAttachmentList(attachments); + followUpService.create(reminder); + return GaoAiCommitResult.success(GaoAiOperation.FOLLOW_UP_CREATE.name(), "CUSTOMER_FOLLOW_UP", reminder.getId(), + null, "已创建客户跟进提醒,提醒时间 %s。".formatted(support.dateTime(reminder.getRemindAt()))); + } + + private GaoAiCommitResult commitFollowUpUpdate(JsonNode arguments, List attachments) { + GaoCustomerFollowUpReminder existing = followUpService.get(support.requiredText(arguments, "reminderId", "id")); + if (existing == null) { + throw new GaoAiOperationException("STALE_PREVIEW", "跟进提醒已不存在,请重新发起"); + } + GaoCustomerFollowUpReminder reminder = new GaoCustomerFollowUpReminder(); + reminder.setId(existing.getId()); + reminder.setStoreId(existing.getStoreId()); + reminder.setCustomerId(existing.getCustomerId()); + reminder.setResponsibleUserId(defaultText(support.text(arguments, "responsibleUserId"), existing.getResponsibleUserId())); + reminder.setContent(defaultText(support.text(arguments, "content", "remark"), existing.getContent())); + reminder.setRemindAt(support.optionalLong(arguments, "remindAt") == null ? existing.getRemindAt() + : support.optionalLong(arguments, "remindAt")); + reminder.setInternalNotifyEnabled(support.optionalBoolean(arguments, "internalNotifyEnabled") == null + ? existing.getInternalNotifyEnabled() : support.optionalBoolean(arguments, "internalNotifyEnabled")); + reminder.setSmsNotifyEnabled(support.optionalBoolean(arguments, "smsNotifyEnabled") == null + ? existing.getSmsNotifyEnabled() : support.optionalBoolean(arguments, "smsNotifyEnabled")); + reminder.setAttachmentList(attachments); + followUpService.update(reminder); + return GaoAiCommitResult.success(GaoAiOperation.FOLLOW_UP_UPDATE.name(), "CUSTOMER_FOLLOW_UP", reminder.getId(), + null, "已修改客户跟进提醒。"); + } + + private GaoAiCommitResult commitFollowUpComplete(JsonNode arguments) { + String reminderId = support.requiredText(arguments, "reminderId", "id"); + followUpService.complete(reminderId); + return GaoAiCommitResult.success(GaoAiOperation.FOLLOW_UP_COMPLETE.name(), "CUSTOMER_FOLLOW_UP", reminderId, + null, "已完成客户跟进提醒。"); + } + + private User responsibleUser(GaoAiOperationContext context, JsonNode arguments) { + String userId = support.text(arguments, "responsibleUserId"); + if (userId != null) { + User user = userService.get(userId); + if (user == null) { + throw new GaoAiOperationException("VALIDATION_FAILED", "负责人不存在"); + } + return user; + } + String name = support.text(arguments, "responsibleUserName", "responsibleUserKeyword"); + if (name != null) { + User user = userService.getByName(name); + if (user == null) { + throw GaoAiOperationException.candidates("未找到负责人,请确认姓名", List.of()); + } + return user; + } + User user = userService.get(context.getUserId()); + if (user == null) { + throw new GaoAiOperationException("VALIDATION_FAILED", "当前用户不存在"); + } + return user; + } + + private long requiredRemindAt(JsonNode arguments) { + Long value = support.optionalLong(arguments, "remindAt"); + if (value != null) { + return value; + } + String text = support.text(arguments, "remindAtText", "remindTime"); + if (text == null) { + throw GaoAiOperationException.clarification("请补充提醒时间", List.of("remindAt")); + } + try { + return LocalDateTime.parse(text, DATE_TIME).atZone(ZONE).toInstant().toEpochMilli(); + } catch (RuntimeException e) { + throw new GaoAiOperationException("VALIDATION_FAILED", "提醒时间格式应为 yyyy-MM-dd HH:mm"); + } + } + + private String changeSummary(JsonNode arguments, String... fields) { + Map changes = new LinkedHashMap<>(); + for (String field : fields) { + String value = support.text(arguments, field); + if (value != null) { + changes.put(field, "telephone".equals(field) ? support.maskPhone(value) : value); + } + } + return changes.isEmpty() ? "无" : changes.toString(); + } + + private Gender gender(String value) { + if (value == null) { + return null; + } + if ("男".equals(value) || "MALE".equalsIgnoreCase(value)) { + return Gender.MALE; + } + if ("女".equals(value) || "FEMALE".equalsIgnoreCase(value)) { + return Gender.FEMALE; + } + throw new GaoAiOperationException("VALIDATION_FAILED", "性别只能是男或女"); + } + + private LocalDate birthdate(String value) { + if (value == null) { + return null; + } + try { + return LocalDate.parse(value); + } catch (RuntimeException e) { + throw new GaoAiOperationException("VALIDATION_FAILED", "出生日期格式应为 yyyy-MM-dd"); + } + } + + private String defaultText(String value, String fallback) { + return value == null ? fallback : value; + } + + private String blank(String value) { + return value == null ? "-" : value; + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/OrderOperationHandler.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/OrderOperationHandler.java new file mode 100644 index 0000000..32de105 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/OrderOperationHandler.java @@ -0,0 +1,911 @@ +package com.imyeyu.api.modules.gao.ai.operation.handler; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.imyeyu.api.modules.common.entity.Attachment; +import com.imyeyu.api.modules.common.service.AttachmentService; +import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentToken; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiCommitResult; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationContext; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationHandler; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationSupport; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPreparedOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiToolAuthorizer; +import com.imyeyu.api.modules.gao.bean.GaoPermissionCode; +import com.imyeyu.api.modules.gao.entity.GaoCustomer; +import com.imyeyu.api.modules.gao.entity.GaoFundRecord; +import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment; +import com.imyeyu.api.modules.gao.entity.GaoSalesOrder; +import com.imyeyu.api.modules.gao.entity.GaoSalesOrderItem; +import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService; +import com.imyeyu.api.modules.gao.service.GaoOrderPaymentService; +import com.imyeyu.api.modules.gao.service.GaoSalesOrderService; +import com.imyeyu.api.modules.gao.vo.order.GaoDirectProductOrderCreateRequest; +import com.imyeyu.api.modules.gao.vo.order.GaoOrderFulfillmentActionRequest; +import com.imyeyu.api.modules.gao.vo.order.GaoOrderFulfillmentCreateRequest; +import com.imyeyu.api.modules.gao.vo.order.GaoOrderFulfillmentItemRequest; +import com.imyeyu.api.modules.gao.vo.order.GaoOrderFulfillmentReturnRequest; +import com.imyeyu.api.modules.gao.vo.order.GaoOrderFulfillmentRevokeRequest; +import com.imyeyu.api.modules.gao.vo.order.GaoOrderPaymentActionRequest; +import com.imyeyu.api.modules.gao.vo.order.GaoOrderPaymentReceiveRequest; +import com.imyeyu.api.modules.gao.vo.order.GaoOrderPaymentRefundRequest; +import com.imyeyu.api.modules.gao.vo.order.GaoOrderPaymentRevokeRequest; +import com.imyeyu.api.modules.gao.vo.salesorder.GaoSalesOrderCancelRequest; +import com.imyeyu.api.modules.gao.vo.salesorder.GaoSalesOrderItemRequest; +import com.imyeyu.api.modules.gao.vo.salesorder.GaoSalesOrderUpdateRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// 订单、收款与履约写操作处理器 +/// +/// @author Codex +/// @since 2026-11-23 +@Component +@RequiredArgsConstructor +public class OrderOperationHandler implements GaoAiOperationHandler { + + private final GaoAiOperationSupport support; + private final GaoAiProperties properties; + private final GaoAiToolAuthorizer authorizer; + private final GaoSalesOrderService salesOrderService; + private final GaoOrderPaymentService paymentService; + private final GaoOrderFulfillmentService fulfillmentService; + private final AttachmentService attachmentService; + + @Override + public Set supports() { + return Set.of(GaoAiOperation.SALES_ORDER_CREATE, GaoAiOperation.SALES_ORDER_UPDATE, + GaoAiOperation.SALES_ORDER_CANCEL, GaoAiOperation.PAYMENT_RECEIVE, + GaoAiOperation.PAYMENT_RECEIVE_AND_VERIFY, GaoAiOperation.PAYMENT_VERIFY, + GaoAiOperation.PAYMENT_REJECT, GaoAiOperation.PAYMENT_CANCEL, GaoAiOperation.PAYMENT_REFUND, + GaoAiOperation.FUND_REVOKE, GaoAiOperation.FULFILLMENT_CREATE, + GaoAiOperation.FULFILLMENT_CREATE_AND_VERIFY, GaoAiOperation.FULFILLMENT_VERIFY, + GaoAiOperation.FULFILLMENT_REJECT, GaoAiOperation.FULFILLMENT_CANCEL); + } + + @Override + public GaoAiPreparedOperation prepare(GaoAiOperationContext context, GaoAiOperationDefinition definition, + JsonNode arguments, List attachments) { + return switch (definition.getOperation()) { + case SALES_ORDER_CREATE -> prepareOrderCreate(context, definition, arguments, attachments); + case SALES_ORDER_UPDATE -> prepareOrderUpdate(context, arguments, attachments); + case SALES_ORDER_CANCEL -> prepareOrderCancel(context, definition, arguments, attachments); + case PAYMENT_RECEIVE, PAYMENT_RECEIVE_AND_VERIFY -> preparePaymentReceive(context, definition, arguments, attachments); + case PAYMENT_VERIFY -> preparePaymentVerify(context, arguments); + case PAYMENT_REJECT, PAYMENT_CANCEL -> preparePaymentAction(context, definition, arguments); + case PAYMENT_REFUND -> prepareRefund(context, definition, arguments, attachments); + case FUND_REVOKE -> prepareFundRevoke(context, definition, arguments, attachments); + case FULFILLMENT_CREATE, FULFILLMENT_CREATE_AND_VERIFY -> prepareFulfillmentCreate(context, definition, arguments, attachments); + case FULFILLMENT_VERIFY -> prepareFulfillmentAction(context, definition, arguments); + case FULFILLMENT_REJECT, FULFILLMENT_CANCEL -> prepareFulfillmentAction(context, definition, arguments); + default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作"); + }; + } + + @Override + public GaoAiCommitResult commit(GaoAiOperationContext context, GaoAiPendingOperation pending, + JsonNode arguments, List attachments) { + return switch (GaoAiOperation.valueOf(pending.getOperation())) { + case SALES_ORDER_CREATE -> commitOrderCreate(context, pending, arguments, attachments); + case SALES_ORDER_UPDATE -> commitOrderUpdate(arguments, attachments); + case SALES_ORDER_CANCEL -> commitOrderCancel(context, pending, arguments, attachments); + case PAYMENT_RECEIVE -> commitPaymentReceive(context, pending, arguments, attachments, false); + case PAYMENT_RECEIVE_AND_VERIFY -> commitPaymentReceive(context, pending, arguments, attachments, true); + case PAYMENT_VERIFY -> commitPaymentVerify(arguments); + case PAYMENT_REJECT -> commitPaymentAction(arguments, false); + case PAYMENT_CANCEL -> commitPaymentAction(arguments, true); + case PAYMENT_REFUND -> commitRefund(context, pending, arguments, attachments); + case FUND_REVOKE -> commitFundRevoke(context, pending, arguments, attachments); + case FULFILLMENT_CREATE -> commitFulfillmentCreate(context, pending, arguments, attachments, false); + case FULFILLMENT_CREATE_AND_VERIFY -> commitFulfillmentCreate(context, pending, arguments, attachments, true); + case FULFILLMENT_VERIFY -> commitFulfillmentVerify(arguments); + case FULFILLMENT_REJECT -> commitFulfillmentAction(arguments, false); + case FULFILLMENT_CANCEL -> commitFulfillmentAction(arguments, true); + default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作"); + }; + } + + private GaoAiPreparedOperation prepareOrderCreate(GaoAiOperationContext context, GaoAiOperationDefinition definition, + JsonNode arguments, List attachments) { + GaoCustomer customer = support.customer(context.getStoreId(), arguments); + List items = support.array(arguments, "itemList"); + if (items.isEmpty()) { + throw GaoAiOperationException.clarification("请补充订单产品明细", List.of("itemList")); + } + if (items.size() > 20) { + throw new GaoAiOperationException("VALIDATION_FAILED", "单笔订单最多 20 个明细"); + } + ObjectNode normalized = support.normalizable(arguments); + normalized.put("customerId", customer.getId()); + ArrayNode normalizedItems = normalized.putArray("itemList"); + List> previewItems = new ArrayList<>(); + long standardTotal = 0; + long saleTotal = 0; + boolean override = false; + String overrideReason = support.text(arguments, "overrideReason", "priceReason", "reason"); + for (int index = 0; index < items.size(); index++) { + JsonNode item = items.get(index); + var selection = support.skuUnit(context.getStoreId(), item, false); + BigDecimal quantity = support.requiredDecimal(item, "购买数量", "quantity"); + if (quantity.signum() <= 0) { + throw new GaoAiOperationException("VALIDATION_FAILED", "购买数量必须大于 0"); + } + Long standardPrice = selection.getUnit().getSalePrice(); + if (standardPrice == null) { + throw new GaoAiOperationException("VALIDATION_FAILED", "产品单位缺少建议售价"); + } + Long requestedPrice = support.optionalLong(item, "unitPrice"); + boolean lineOverride = requestedPrice != null && !requestedPrice.equals(standardPrice); + if (lineOverride && requestedPrice < 0) { + throw new GaoAiOperationException("VALIDATION_FAILED", "单价不能为负数"); + } + long lineStandard = support.lineAmount(standardPrice, quantity); + long lineSale = support.lineAmount(lineOverride ? requestedPrice : standardPrice, quantity); + if (lineOverride) { + override = true; + authorizer.checkCode(context.getUserId(), GaoPermissionCode.SALES_ORDER_PRICE_OVERRIDE); + validateDiscount(lineStandard, lineSale); + } + standardTotal = Math.addExact(standardTotal, lineStandard); + saleTotal = Math.addExact(saleTotal, lineSale); + ObjectNode normalizedItem = normalizedItems.addObject(); + normalizedItem.put("skuId", selection.getSku().getId()); + normalizedItem.put("skuUnitId", selection.getUnit().getId()); + normalizedItem.put("quantity", quantity.toPlainString()); + normalizedItem.put("sort", index); + if (lineOverride) { + normalizedItem.put("unitPrice", requestedPrice); + } + if (support.text(item, "remark") != null) { + normalizedItem.put("remark", support.text(item, "remark")); + } + Map preview = new LinkedHashMap<>(); + preview.put("productName", selection.getProduct().getName()); + preview.put("skuName", selection.getSku().getName()); + preview.put("skuCode", selection.getSku().getCode()); + preview.put("unitName", selection.getUnit().getName()); + preview.put("quantity", quantity.toPlainString()); + preview.put("standardUnitPrice", support.money(standardPrice)); + preview.put("unitPrice", support.money(lineOverride ? requestedPrice : standardPrice)); + preview.put("lineAmount", support.money(lineSale)); + previewItems.add(preview); + } + if (saleTotal > properties.getOrderMaxSaleAmount()) { + throw new GaoAiOperationException("VALIDATION_FAILED", "订单金额超过单笔上限"); + } + if (override) { + validateDiscount(standardTotal, saleTotal); + } + if (override && (overrideReason == null || overrideReason.isBlank())) { + throw GaoAiOperationException.clarification("改价必须填写原因", List.of("overrideReason")); + } + if (overrideReason != null) { + normalized.put("overrideReason", overrideReason); + } + if (support.text(arguments, "remark") != null) { + normalized.put("remark", support.text(arguments, "remark")); + } + + Map preview = new LinkedHashMap<>(); + preview.put("customer", support.customerBrief(customer)); + preview.put("items", previewItems); + preview.put("standardAmount", support.money(standardTotal)); + preview.put("saleAmount", support.money(saleTotal)); + preview.put("discount", discountText(standardTotal, saleTotal)); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("新建销售订单"); + if (override) { + result.setRiskLevel(RiskLevel.SENSITIVE); + result.setReasonRequired(true); + result.setRequiredPhrase("确认以 %s 创建订单".formatted(support.money(saleTotal))); + } + StringBuilder lines = new StringBuilder(); + for (Map item : previewItems) { + lines.append("- %s / %s × %s %s,单价 %s,小计 %s%n".formatted(item.get("productName"), + item.get("skuName"), item.get("quantity"), item.get("unitName"), item.get("unitPrice"), item.get("lineAmount"))); + } + result.setPreviewText(""" + ### 待确认:新建销售订单 + + 客户:%s(%s) + 明细: + %s + 合计:%s + 下单时间:%s + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(customer.getName(), blank(customer.getCode()), lines, support.money(saleTotal), + support.dateTime(support.optionalLong(arguments, "purchasedAt")))); + return result; + } + + private GaoAiPreparedOperation prepareOrderUpdate(GaoAiOperationContext context, JsonNode arguments, + List attachments) { + GaoSalesOrder order = support.order(context.getStoreId(), arguments); + ObjectNode normalized = support.normalizable(arguments); + normalized.put("salesOrderId", order.getId()); + Map preview = new LinkedHashMap<>(); + preview.put("order", support.orderBrief(order)); + preview.put("remark", support.text(arguments, "remark")); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("修改销售订单备注和附件"); + result.setPreviewText(""" + ### 待确认:修改销售订单 + + 订单:%s + 当前金额:%s + 新备注:%s + 新增附件:%d 个 + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(order.getOrderNo(), support.money(order.getSaleAmount()), + blank(support.text(arguments, "remark")), attachments.size())); + return result; + } + + private GaoAiPreparedOperation prepareOrderCancel(GaoAiOperationContext context, GaoAiOperationDefinition definition, + JsonNode arguments, List attachments) { + GaoSalesOrder order = support.order(context.getStoreId(), arguments); + String reason = support.requiredText(arguments, "取消原因", "reason"); + ObjectNode normalized = support.normalizable(arguments); + normalized.put("salesOrderId", order.getId()); + normalized.put("reason", reason); + List fulfillmentRevokeList = support.array(arguments, "fulfillmentRevokeList"); + List fulfillmentReturnList = support.array(arguments, "fulfillmentReturnList"); + List fundRevokeList = support.array(arguments, "fundRevokeList"); + List fundRefundList = support.array(arguments, "fundRefundList"); + boolean hasReversal = !fulfillmentRevokeList.isEmpty() || !fulfillmentReturnList.isEmpty() + || !fundRevokeList.isEmpty() || !fundRefundList.isEmpty(); + for (JsonNode item : fulfillmentRevokeList) { + support.requiredText(item, "履约单 ID", "fulfillmentId"); + } + for (JsonNode item : fulfillmentReturnList) { + support.requiredText(item, "履约单 ID", "fulfillmentId"); + } + for (JsonNode item : fundRevokeList) { + support.requiredText(item, "资金流水 ID", "fundRecordId"); + } + for (JsonNode item : fundRefundList) { + support.requiredText(item, "退款金额", "amount"); + } + if (!fulfillmentRevokeList.isEmpty()) { + authorizer.checkCode(context.getUserId(), GaoPermissionCode.ORDER_FULFILLMENT_REVOKE); + } + if (!fulfillmentReturnList.isEmpty()) { + authorizer.checkCode(context.getUserId(), GaoPermissionCode.ORDER_FULFILLMENT_RETURN); + } + if (!fundRevokeList.isEmpty()) { + authorizer.checkCode(context.getUserId(), GaoPermissionCode.FUND_REVOKE); + } + if (!fundRefundList.isEmpty()) { + authorizer.checkCode(context.getUserId(), GaoPermissionCode.FUND_REFUND); + } + if (hasReversal && !hasImage(attachments)) { + throw new GaoAiOperationException("ATTACHMENT_REQUIRED", "订单取消包含冲正、退货或退款时必须上传照片凭证"); + } + Map preview = new LinkedHashMap<>(); + preview.put("order", support.orderBrief(order)); + preview.put("reason", reason); + preview.put("fulfillmentRevokeCount", support.array(arguments, "fulfillmentRevokeList").size()); + preview.put("fulfillmentReturnCount", support.array(arguments, "fulfillmentReturnList").size()); + preview.put("fundRevokeCount", support.array(arguments, "fundRevokeList").size()); + preview.put("fundRefundCount", support.array(arguments, "fundRefundList").size()); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("取消销售订单"); + result.setRiskLevel(RiskLevel.DESTRUCTIVE); + result.setReasonRequired(true); + result.setRequiredPhrase("确认取消订单 %s".formatted(order.getOrderNo())); + result.setImpactText("订单将取消,关联的待核销收款、履约以及指定的冲正、退货、退款将同步处理。"); + result.setPreviewText(""" + ### 待确认:取消销售订单 + + 订单:%s + 客户:%s + 金额:%s + 取消原因:%s + 履约冲正:%d 单 + 履约退货:%d 单 + 资金冲正:%d 笔 + 退款:%d 笔 + + %s + + 请回复“确认取消订单 %s”执行,回复“取消”放弃。 + """.formatted(order.getOrderNo(), order.getCustomerId(), support.money(order.getSaleAmount()), reason, + preview.get("fulfillmentRevokeCount"), preview.get("fulfillmentReturnCount"), + preview.get("fundRevokeCount"), preview.get("fundRefundCount"), result.getImpactText(), order.getOrderNo())); + return result; + } + + private GaoAiPreparedOperation preparePaymentReceive(GaoAiOperationContext context, GaoAiOperationDefinition definition, + JsonNode arguments, List attachments) { + GaoSalesOrder order = support.order(context.getStoreId(), arguments); + long amount = support.requiredLong(arguments, "收款金额", "amount"); + if (amount <= 0) { + throw new GaoAiOperationException("VALIDATION_FAILED", "收款金额必须大于 0"); + } + ObjectNode normalized = support.normalizable(arguments); + normalized.put("salesOrderId", order.getId()); + normalized.put("amount", amount); + Map preview = new LinkedHashMap<>(); + preview.put("order", support.orderBrief(order)); + preview.put("amount", support.money(amount)); + preview.put("unpaidAmount", support.money(order.getUnpaidAmount())); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle(definition.title()); + result.setPreviewText(""" + ### 待确认:%s + + 订单:%s + 客户:%s + 收款金额:%s + 当前未收:%s + 凭证:%d 张 + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(definition.title(), order.getOrderNo(), order.getCustomerId(), support.money(amount), + support.money(order.getUnpaidAmount()), attachments.size())); + return result; + } + + private GaoAiPreparedOperation preparePaymentVerify(GaoAiOperationContext context, JsonNode arguments) { + GaoFundRecord record = support.fundRecord(context.getStoreId(), arguments); + ObjectNode normalized = support.normalizable(arguments); + normalized.put("fundRecordId", record.getId()); + Map preview = new LinkedHashMap<>(); + preview.put("fundRecordId", record.getId()); + preview.put("amount", support.money(record.getAmount())); + preview.put("customerId", record.getCustomerId()); + preview.put("bizId", record.getBizId()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("核销收款"); + result.setRiskLevel(RiskLevel.SENSITIVE); + result.setPreviewText(""" + ### 待确认:核销收款 + + 资金流水:%s + 金额:%s + 订单 ID:%s + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(record.getId(), support.money(record.getAmount()), record.getBizId())); + return result; + } + + private GaoAiPreparedOperation preparePaymentAction(GaoAiOperationContext context, GaoAiOperationDefinition definition, + JsonNode arguments) { + GaoFundRecord record = support.fundRecord(context.getStoreId(), arguments); + String reason = support.requiredText(arguments, "操作原因", "reason"); + ObjectNode normalized = support.normalizable(arguments); + normalized.put("fundRecordId", record.getId()); + normalized.put("reason", reason); + Map preview = new LinkedHashMap<>(); + preview.put("fundRecordId", record.getId()); + preview.put("amount", support.money(record.getAmount())); + preview.put("reason", reason); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle(definition.title()); + result.setRiskLevel(RiskLevel.DESTRUCTIVE); + result.setReasonRequired(true); + result.setRequiredPhrase("确认%s %s".formatted(definition.title(), support.money(record.getAmount()))); + result.setPreviewText(""" + ### 待确认:%s + + 资金流水:%s + 金额:%s + 原因:%s + + 请回复“确认%s %s”执行,回复“取消”放弃。 + """.formatted(definition.title(), record.getId(), support.money(record.getAmount()), reason, + definition.title(), support.money(record.getAmount()))); + return result; + } + + private GaoAiPreparedOperation prepareRefund(GaoAiOperationContext context, GaoAiOperationDefinition definition, + JsonNode arguments, List attachments) { + GaoSalesOrder order = support.order(context.getStoreId(), arguments); + long amount = support.requiredLong(arguments, "退款金额", "amount"); + if (amount <= 0) { + throw new GaoAiOperationException("VALIDATION_FAILED", "退款金额必须大于 0"); + } + String reason = support.requiredText(arguments, "退款原因", "reason"); + ObjectNode normalized = support.normalizable(arguments); + normalized.put("salesOrderId", order.getId()); + normalized.put("amount", amount); + normalized.put("reason", reason); + Map preview = new LinkedHashMap<>(); + preview.put("order", support.orderBrief(order)); + preview.put("amount", support.money(amount)); + preview.put("reason", reason); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("销售订单退款"); + result.setRiskLevel(RiskLevel.DESTRUCTIVE); + result.setReasonRequired(true); + result.setRequiredPhrase("确认退款 %s".formatted(support.money(amount))); + result.setImpactText("退款将形成资金流水,订单退款状态可能发生变化。"); + result.setPreviewText(""" + ### 待确认:销售订单退款 + + 订单:%s + 退款金额:%s + 原因:%s + 凭证:%d 张 + + 请回复“确认退款 %s”执行,回复“取消”放弃。 + """.formatted(order.getOrderNo(), support.money(amount), reason, attachments.size(), support.money(amount))); + return result; + } + + private GaoAiPreparedOperation prepareFundRevoke(GaoAiOperationContext context, GaoAiOperationDefinition definition, + JsonNode arguments, List attachments) { + GaoFundRecord record = support.fundRecord(context.getStoreId(), arguments); + String reason = support.requiredText(arguments, "冲正原因", "reason"); + ObjectNode normalized = support.normalizable(arguments); + normalized.put("fundRecordId", record.getId()); + normalized.put("reason", reason); + Map preview = new LinkedHashMap<>(); + preview.put("fundRecordId", record.getId()); + preview.put("amount", support.money(record.getAmount())); + preview.put("reason", reason); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("资金流水冲正"); + result.setRiskLevel(RiskLevel.DESTRUCTIVE); + result.setReasonRequired(true); + result.setRequiredPhrase("确认冲正资金流水 %s".formatted(support.money(record.getAmount()))); + result.setImpactText("原资金流水将失效,并生成反向冲正流水。"); + result.setPreviewText(""" + ### 待确认:资金流水冲正 + + 资金流水:%s + 金额:%s + 原因:%s + 凭证:%d 张 + + 请回复“确认冲正资金流水 %s”执行,回复“取消”放弃。 + """.formatted(record.getId(), support.money(record.getAmount()), reason, attachments.size(), + support.money(record.getAmount()))); + return result; + } + + private GaoAiPreparedOperation prepareFulfillmentCreate(GaoAiOperationContext context, + GaoAiOperationDefinition definition, JsonNode arguments, List attachments) { + GaoSalesOrder order = support.order(context.getStoreId(), arguments); + List items = fulfillmentItems(order, arguments); + if (items.isEmpty()) { + throw GaoAiOperationException.clarification("请补充履约明细", List.of("itemList")); + } + ObjectNode normalized = support.normalizable(arguments); + normalized.put("salesOrderId", order.getId()); + ArrayNode normalizedItems = normalized.putArray("itemList"); + List> previewItems = new ArrayList<>(); + Map itemMap = new LinkedHashMap<>(); + if (order.getItemList() != null) { + for (GaoSalesOrderItem item : order.getItemList()) { + itemMap.put(item.getId(), item); + } + } + for (JsonNode item : items) { + String sourceId = support.requiredText(item, "sourceOrderItemId", "orderItemId"); + String unitId = support.requiredText(item, "skuUnitId"); + BigDecimal quantity = support.requiredDecimal(item, "quantity"); + GaoSalesOrderItem source = itemMap.get(sourceId); + if (source == null) { + throw new GaoAiOperationException("VALIDATION_FAILED", "履约明细不属于当前订单"); + } + ObjectNode normalizedItem = normalizedItems.addObject(); + normalizedItem.put("sourceOrderItemId", sourceId); + normalizedItem.put("skuUnitId", unitId); + normalizedItem.put("quantity", quantity.toPlainString()); + Map previewItem = new LinkedHashMap<>(); + previewItem.put("productName", source.getProductNameSnapshot()); + previewItem.put("skuName", source.getSkuNameSnapshot()); + previewItem.put("quantity", quantity.toPlainString()); + previewItem.put("unitName", source.getUnitSnapshot()); + previewItems.add(previewItem); + } + Map preview = new LinkedHashMap<>(); + preview.put("order", support.orderBrief(order)); + preview.put("items", previewItems); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle(definition.title()); + result.setPreviewText(""" + ### 待确认:%s + + 订单:%s + 履约明细:%d 项 + 凭证:%d 张 + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(definition.title(), order.getOrderNo(), previewItems.size(), attachments.size())); + return result; + } + + private GaoAiPreparedOperation prepareFulfillmentAction(GaoAiOperationContext context, + GaoAiOperationDefinition definition, JsonNode arguments) { + GaoOrderFulfillment fulfillment = support.fulfillment(context.getStoreId(), arguments); + String reason = support.text(arguments, "reason"); + if (definition.getOperation() != GaoAiOperation.FULFILLMENT_VERIFY && (reason == null || reason.isBlank())) { + throw GaoAiOperationException.clarification("请补充操作原因", List.of("reason")); + } + ObjectNode normalized = support.normalizable(arguments); + normalized.put("fulfillmentId", fulfillment.getId()); + if (reason != null) { + normalized.put("reason", reason); + } + Map preview = new LinkedHashMap<>(); + preview.put("fulfillmentId", fulfillment.getId()); + preview.put("orderId", fulfillment.getSalesOrderId()); + preview.put("status", fulfillment.getStatus()); + preview.put("reason", reason); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle(definition.title()); + if (definition.destructive()) { + result.setRiskLevel(RiskLevel.DESTRUCTIVE); + result.setReasonRequired(true); + result.setRequiredPhrase("确认%s %s".formatted(definition.title(), fulfillment.getId())); + result.setImpactText("履约状态将发生变化,相关库存占用或核销记录会同步处理。"); + result.setPreviewText(""" + ### 待确认:%s + + 履约单:%s + 订单 ID:%s + 原因:%s + + 请回复“确认%s %s”执行,回复“取消”放弃。 + """.formatted(definition.title(), fulfillment.getId(), fulfillment.getSalesOrderId(), reason, + definition.title(), fulfillment.getId())); + } else { + result.setRiskLevel(RiskLevel.SENSITIVE); + result.setPreviewText(""" + ### 待确认:%s + + 履约单:%s + 订单 ID:%s + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(definition.title(), fulfillment.getId(), fulfillment.getSalesOrderId())); + } + return result; + } + + private GaoAiCommitResult commitOrderCreate(GaoAiOperationContext context, GaoAiPendingOperation pending, + JsonNode arguments, List attachments) { + GaoDirectProductOrderCreateRequest request = new GaoDirectProductOrderCreateRequest(); + request.setRequestNo(pending.getRequestNo()); + request.setStoreId(context.getStoreId()); + request.setCustomerId(support.requiredText(arguments, "customerId")); + request.setPurchasedAt(support.optionalLong(arguments, "purchasedAt")); + request.setRemark(support.text(arguments, "remark")); + request.setAttachmentList(attachments); + List itemList = new ArrayList<>(); + for (JsonNode item : support.array(arguments, "itemList")) { + GaoSalesOrderItemRequest requestItem = new GaoSalesOrderItemRequest(); + requestItem.setSkuId(support.requiredText(item, "skuId")); + requestItem.setSkuUnitId(support.requiredText(item, "skuUnitId")); + requestItem.setQuantity(support.requiredDecimal(item, "quantity")); + requestItem.setUnitPrice(support.optionalLong(item, "unitPrice")); + requestItem.setSort(support.optionalLong(item, "sort") == null ? itemList.size() + : support.optionalLong(item, "sort").intValue()); + requestItem.setRemark(support.text(item, "remark")); + itemList.add(requestItem); + } + request.setItemList(itemList); + GaoSalesOrder order = salesOrderService.createDirectProductOrder(request); + return GaoAiCommitResult.success(GaoAiOperation.SALES_ORDER_CREATE.name(), "SALES_ORDER", order.getId(), + order.getOrderNo(), "已创建销售订单 %s,金额 %s。".formatted(order.getOrderNo(), support.money(order.getSaleAmount()))); + } + + private GaoAiCommitResult commitOrderUpdate(JsonNode arguments, List attachments) { + String id = support.requiredText(arguments, "salesOrderId", "orderId"); + GaoSalesOrder existing = salesOrderService.detail(id); + GaoSalesOrderUpdateRequest request = new GaoSalesOrderUpdateRequest(); + request.setId(id); + request.setRemark(support.text(arguments, "remark")); + request.setAttachmentList(attachments.isEmpty() + ? attachmentService.listByBizId(Attachment.BizType.GAO_SALES_ORDER, existing.getId()) : attachments); + GaoSalesOrder order = salesOrderService.updateRemarkAndAttachments(request); + return GaoAiCommitResult.success(GaoAiOperation.SALES_ORDER_UPDATE.name(), "SALES_ORDER", order.getId(), + order.getOrderNo(), "已更新销售订单 %s。".formatted(order.getOrderNo())); + } + + private GaoAiCommitResult commitOrderCancel(GaoAiOperationContext context, GaoAiPendingOperation pending, + JsonNode arguments, List attachments) { + String orderId = support.requiredText(arguments, "salesOrderId", "orderId"); + String reason = support.requiredText(arguments, "reason"); + GaoSalesOrderCancelRequest request = new GaoSalesOrderCancelRequest(); + request.setSalesOrderId(orderId); + request.setReason(reason); + request.setRequestNo(pending.getRequestNo()); + request.setAttachmentList(attachments); + request.setFulfillmentRevokeList(fulfillmentRevokeList(arguments, reason, attachments)); + request.setFulfillmentReturnList(fulfillmentReturnList(arguments, reason, attachments)); + request.setFundRevokeList(fundRevokeList(arguments, reason, attachments)); + request.setFundRefundList(fundRefundList(orderId, arguments, reason, attachments)); + GaoSalesOrder order = salesOrderService.cancel(request); + return GaoAiCommitResult.success(GaoAiOperation.SALES_ORDER_CANCEL.name(), "SALES_ORDER", order.getId(), + order.getOrderNo(), "已取消销售订单 %s。".formatted(order.getOrderNo())); + } + + private GaoAiCommitResult commitPaymentReceive(GaoAiOperationContext context, GaoAiPendingOperation pending, + JsonNode arguments, List attachments, boolean verify) { + GaoOrderPaymentReceiveRequest request = new GaoOrderPaymentReceiveRequest(); + request.setSalesOrderId(support.requiredText(arguments, "salesOrderId", "orderId")); + request.setRequestNo(pending.getRequestNo()); + request.setAmount(support.requiredLong(arguments, "amount")); + request.setOccurredAt(support.optionalLong(arguments, "occurredAt")); + request.setAttachmentList(attachments); + request.setRemark(support.text(arguments, "remark")); + GaoFundRecord record = verify ? paymentService.receiveAndVerify(request) : paymentService.receive(request); + return GaoAiCommitResult.success(verify ? GaoAiOperation.PAYMENT_RECEIVE_AND_VERIFY.name() + : GaoAiOperation.PAYMENT_RECEIVE.name(), "FUND_RECORD", record.getId(), null, + "已登记收款 %s。".formatted(support.money(record.getAmount()))); + } + + private GaoAiCommitResult commitPaymentVerify(JsonNode arguments) { + String id = support.requiredText(arguments, "fundRecordId", "id"); + GaoFundRecord record = paymentService.verify(id); + return GaoAiCommitResult.success(GaoAiOperation.PAYMENT_VERIFY.name(), "FUND_RECORD", record.getId(), + null, "已核销收款 %s。".formatted(support.money(record.getAmount()))); + } + + private GaoAiCommitResult commitPaymentAction(JsonNode arguments, boolean cancel) { + GaoOrderPaymentActionRequest request = new GaoOrderPaymentActionRequest(); + request.setFundRecordId(support.requiredText(arguments, "fundRecordId", "id")); + request.setReason(support.requiredText(arguments, "reason")); + GaoFundRecord record = cancel ? paymentService.cancel(request) : paymentService.reject(request); + return GaoAiCommitResult.success(cancel ? GaoAiOperation.PAYMENT_CANCEL.name() + : GaoAiOperation.PAYMENT_REJECT.name(), "FUND_RECORD", record.getId(), null, + "已%s收款。".formatted(cancel ? "撤销" : "拒绝")); + } + + private GaoAiCommitResult commitRefund(GaoAiOperationContext context, GaoAiPendingOperation pending, + JsonNode arguments, List attachments) { + GaoOrderPaymentRefundRequest request = new GaoOrderPaymentRefundRequest(); + request.setSalesOrderId(support.requiredText(arguments, "salesOrderId", "orderId")); + request.setRequestNo(pending.getRequestNo()); + request.setAmount(support.requiredLong(arguments, "amount")); + request.setOccurredAt(support.optionalLong(arguments, "occurredAt")); + request.setReason(support.requiredText(arguments, "reason")); + request.setAttachmentList(attachments); + request.setRemark(support.text(arguments, "remark")); + GaoFundRecord record = paymentService.refund(request); + return GaoAiCommitResult.success(GaoAiOperation.PAYMENT_REFUND.name(), "FUND_RECORD", record.getId(), + null, "已登记退款 %s。".formatted(support.money(record.getAmount()))); + } + + private GaoAiCommitResult commitFundRevoke(GaoAiOperationContext context, GaoAiPendingOperation pending, + JsonNode arguments, List attachments) { + GaoOrderPaymentRevokeRequest request = new GaoOrderPaymentRevokeRequest(); + request.setFundRecordId(support.requiredText(arguments, "fundRecordId", "id")); + request.setRequestNo(pending.getRequestNo()); + request.setOccurredAt(support.optionalLong(arguments, "occurredAt")); + request.setReason(support.requiredText(arguments, "reason")); + request.setAttachmentList(attachments); + request.setRemark(support.text(arguments, "remark")); + GaoFundRecord record = paymentService.revoke(request); + return GaoAiCommitResult.success(GaoAiOperation.FUND_REVOKE.name(), "FUND_RECORD", record.getId(), + null, "已冲正资金流水 %s。".formatted(support.money(record.getAmount()))); + } + + private GaoAiCommitResult commitFulfillmentCreate(GaoAiOperationContext context, GaoAiPendingOperation pending, + JsonNode arguments, List attachments, boolean verify) { + GaoOrderFulfillmentCreateRequest request = new GaoOrderFulfillmentCreateRequest(); + request.setSalesOrderId(support.requiredText(arguments, "salesOrderId", "orderId")); + request.setRequestNo(pending.getRequestNo()); + request.setDeliveredAt(support.optionalLong(arguments, "deliveredAt")); + request.setRemark(support.text(arguments, "remark")); + request.setAttachmentList(attachments); + List itemList = new ArrayList<>(); + for (JsonNode item : support.array(arguments, "itemList")) { + GaoOrderFulfillmentItemRequest requestItem = new GaoOrderFulfillmentItemRequest(); + requestItem.setSourceOrderItemId(support.requiredText(item, "sourceOrderItemId")); + requestItem.setSkuUnitId(support.requiredText(item, "skuUnitId")); + requestItem.setQuantity(support.requiredDecimal(item, "quantity")); + itemList.add(requestItem); + } + request.setItemList(itemList); + GaoOrderFulfillment fulfillment = verify ? fulfillmentService.createAndVerify(request) + : fulfillmentService.create(request); + return GaoAiCommitResult.success(verify ? GaoAiOperation.FULFILLMENT_CREATE_AND_VERIFY.name() + : GaoAiOperation.FULFILLMENT_CREATE.name(), "ORDER_FULFILLMENT", fulfillment.getId(), null, + "已创建履约单,状态 %s。".formatted(fulfillment.getStatus())); + } + + private GaoAiCommitResult commitFulfillmentVerify(JsonNode arguments) { + GaoOrderFulfillmentActionRequest request = new GaoOrderFulfillmentActionRequest(); + request.setFulfillmentId(support.requiredText(arguments, "fulfillmentId", "id")); + GaoOrderFulfillment fulfillment = fulfillmentService.verify(request); + return GaoAiCommitResult.success(GaoAiOperation.FULFILLMENT_VERIFY.name(), "ORDER_FULFILLMENT", + fulfillment.getId(), null, "已核销履约单。"); + } + + private GaoAiCommitResult commitFulfillmentAction(JsonNode arguments, boolean cancel) { + GaoOrderFulfillmentActionRequest request = new GaoOrderFulfillmentActionRequest(); + request.setFulfillmentId(support.requiredText(arguments, "fulfillmentId", "id")); + request.setReason(support.requiredText(arguments, "reason")); + GaoOrderFulfillment fulfillment = cancel ? fulfillmentService.cancel(request) : fulfillmentService.reject(request); + return GaoAiCommitResult.success(cancel ? GaoAiOperation.FULFILLMENT_CANCEL.name() + : GaoAiOperation.FULFILLMENT_REJECT.name(), "ORDER_FULFILLMENT", fulfillment.getId(), null, + "已%s履约单。".formatted(cancel ? "撤销" : "拒绝")); + } + + private List fulfillmentItems(GaoSalesOrder order, JsonNode arguments) { + List items = support.array(arguments, "itemList"); + if (!items.isEmpty()) { + return items; + } + if (!Boolean.TRUE.equals(support.optionalBoolean(arguments, "fulfillAll"))) { + return List.of(); + } + List result = new ArrayList<>(); + for (GaoSalesOrderItem item : order.getItemList() == null ? List.of() : order.getItemList()) { + BigDecimal available = item.getAvailableBaseQuantity(); + if (available == null || available.signum() <= 0 || item.getBaseQuantityPerUnitSnapshot() == null + || item.getBaseQuantityPerUnitSnapshot().signum() <= 0) { + continue; + } + BigDecimal quantity = available.divide(item.getBaseQuantityPerUnitSnapshot(), 3, RoundingMode.DOWN); + if (quantity.signum() <= 0) { + continue; + } + ObjectNode node = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.objectNode(); + node.put("sourceOrderItemId", item.getId()); + node.put("skuUnitId", item.getSkuUnitId()); + node.put("quantity", quantity.toPlainString()); + result.add(node); + } + return result; + } + + private List fulfillmentRevokeList(JsonNode arguments, String defaultReason, + List attachments) { + List result = new ArrayList<>(); + int index = 0; + for (JsonNode item : support.array(arguments, "fulfillmentRevokeList")) { + GaoOrderFulfillmentRevokeRequest request = new GaoOrderFulfillmentRevokeRequest(); + request.setFulfillmentId(support.requiredText(item, "fulfillmentId")); + request.setRequestNo("%s-R%d".formatted(support.requestNo(GaoAiOperation.SALES_ORDER_CANCEL), index++)); + request.setDeliveredAt(support.optionalLong(item, "deliveredAt")); + request.setReason(defaultReason); + request.setReturnedToStore(support.optionalBoolean(item, "returnedToStore")); + request.setAttachmentList(attachments); + request.setRemark(support.text(item, "remark")); + result.add(request); + } + return result; + } + + private List fulfillmentReturnList(JsonNode arguments, String defaultReason, + List attachments) { + List result = new ArrayList<>(); + int index = 0; + for (JsonNode item : support.array(arguments, "fulfillmentReturnList")) { + GaoOrderFulfillmentReturnRequest request = new GaoOrderFulfillmentReturnRequest(); + request.setFulfillmentId(support.requiredText(item, "fulfillmentId")); + request.setRequestNo("%s-T%d".formatted(support.requestNo(GaoAiOperation.SALES_ORDER_CANCEL), index++)); + request.setReturnedAt(support.optionalLong(item, "returnedAt")); + request.setReason(defaultReason); + request.setReturnedToStore(support.optionalBoolean(item, "returnedToStore")); + request.setAttachmentList(attachments); + request.setRemark(support.text(item, "remark")); + result.add(request); + } + return result; + } + + private List fundRevokeList(JsonNode arguments, String defaultReason, + List attachments) { + List result = new ArrayList<>(); + int index = 0; + for (JsonNode item : support.array(arguments, "fundRevokeList")) { + GaoOrderPaymentRevokeRequest request = new GaoOrderPaymentRevokeRequest(); + request.setFundRecordId(support.requiredText(item, "fundRecordId")); + request.setRequestNo("%s-FR%d".formatted(support.requestNo(GaoAiOperation.SALES_ORDER_CANCEL), index++)); + request.setReason(defaultReason); + request.setOccurredAt(support.optionalLong(item, "occurredAt")); + request.setAttachmentList(attachments); + request.setRemark(support.text(item, "remark")); + result.add(request); + } + return result; + } + + private List fundRefundList(String salesOrderId, JsonNode arguments, + String defaultReason, List attachments) { + List result = new ArrayList<>(); + int index = 0; + for (JsonNode item : support.array(arguments, "fundRefundList")) { + GaoOrderPaymentRefundRequest request = new GaoOrderPaymentRefundRequest(); + request.setSalesOrderId(salesOrderId); + request.setRequestNo("%s-FD%d".formatted(support.requestNo(GaoAiOperation.SALES_ORDER_CANCEL), index++)); + request.setAmount(support.requiredLong(item, "amount")); + request.setOccurredAt(support.optionalLong(item, "occurredAt")); + request.setReason(defaultReason); + request.setAttachmentList(attachments); + request.setRemark(support.text(item, "remark")); + result.add(request); + } + return result; + } + + private void validateDiscount(long standardAmount, long saleAmount) { + if (standardAmount <= 0 || saleAmount >= standardAmount) { + return; + } + double discount = BigDecimal.valueOf(standardAmount - saleAmount) + .divide(BigDecimal.valueOf(standardAmount), 4, RoundingMode.HALF_UP).doubleValue(); + if (discount > properties.getMaxDiscountRate()) { + throw new GaoAiOperationException("VALIDATION_FAILED", "优惠幅度超过 %d%% 上限".formatted(Math.round(properties.getMaxDiscountRate() * 100))); + } + } + + private String discountText(long standardAmount, long saleAmount) { + if (standardAmount <= 0 || saleAmount >= standardAmount) { + return "无"; + } + double discount = BigDecimal.valueOf(standardAmount - saleAmount) + .divide(BigDecimal.valueOf(standardAmount), 4, RoundingMode.HALF_UP).doubleValue() * 100; + return "%.2f%%".formatted(discount); + } + + private boolean hasImage(List attachments) { + return attachments != null && attachments.stream() + .anyMatch(item -> item.getMimeType() != null && item.getMimeType().startsWith("image/")); + } + + private String blank(String value) { + return value == null ? "-" : value; + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/PackageOperationHandler.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/PackageOperationHandler.java new file mode 100644 index 0000000..999857e --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/PackageOperationHandler.java @@ -0,0 +1,188 @@ +package com.imyeyu.api.modules.gao.ai.operation.handler; + +import com.fasterxml.jackson.databind.JsonNode; +import com.imyeyu.api.modules.common.entity.Attachment; +import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentToken; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiCommitResult; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationContext; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationHandler; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationSupport; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPreparedOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiToolAuthorizer; +import com.imyeyu.api.modules.gao.bean.GaoPermissionCode; +import com.imyeyu.api.modules.gao.entity.GaoCustomer; +import com.imyeyu.api.modules.gao.entity.GaoCustomerPackage; +import com.imyeyu.api.modules.gao.entity.GaoPackageConfig; +import com.imyeyu.api.modules.gao.service.GaoCustomerPackageService; +import com.imyeyu.api.modules.gao.vo.customer.GaoCustomerPackagePurchaseItem; +import com.imyeyu.api.modules.gao.vo.customer.GaoCustomerPackagePurchaseRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// 客户套餐写操作处理器 +/// +/// @author Codex +/// @since 2026-11-23 +@Component +@RequiredArgsConstructor +public class PackageOperationHandler implements GaoAiOperationHandler { + + private final GaoAiOperationSupport support; + private final GaoAiProperties properties; + private final GaoAiToolAuthorizer authorizer; + private final GaoCustomerPackageService packageService; + + @Override + public Set supports() { + return Set.of(GaoAiOperation.CUSTOMER_PACKAGE_PURCHASE); + } + + @Override + public GaoAiPreparedOperation prepare(GaoAiOperationContext context, GaoAiOperationDefinition definition, + JsonNode arguments, List attachments) { + GaoCustomer customer = support.customer(context.getStoreId(), arguments); + GaoPackageConfig config = support.packageConfig(context.getStoreId(), arguments); + if (config.getStandardAmount() == null) { + throw new GaoAiOperationException("VALIDATION_FAILED", "套餐配置缺少标准价"); + } + Long saleAmount = support.optionalLong(arguments, "saleAmount", "amount"); + boolean override = saleAmount != null && !saleAmount.equals(config.getStandardAmount()); + if (override) { + authorizer.checkCode(context.getUserId(), GaoPermissionCode.CUSTOMER_PACKAGE_PRICE_OVERRIDE); + validateDiscount(config.getStandardAmount(), saleAmount); + String reason = support.requiredText(arguments, "改价原因", "reason"); + if (reason.isBlank()) { + throw new GaoAiOperationException("VALIDATION_FAILED", "改价必须填写原因"); + } + } + List itemList = itemList(arguments); + boolean gift = itemList.stream().anyMatch(item -> Boolean.TRUE.equals(item.getGifted())); + if (gift) { + authorizer.checkCode(context.getUserId(), GaoPermissionCode.CUSTOMER_PACKAGE_GIFT_CREATE); + } + long finalAmount = saleAmount == null ? config.getStandardAmount() : saleAmount; + if (finalAmount < 0) { + throw new GaoAiOperationException("VALIDATION_FAILED", "成交价不能为负数"); + } + com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments); + normalized.put("customerId", customer.getId()); + normalized.put("packageConfigId", config.getId()); + normalized.put("saleAmount", finalAmount); + if (arguments.hasNonNull("itemList")) { + normalized.set("itemList", arguments.get("itemList")); + } + + Map preview = new LinkedHashMap<>(); + preview.put("customer", support.customerBrief(customer)); + preview.put("packageName", config.getName()); + preview.put("standardAmount", support.money(config.getStandardAmount())); + preview.put("saleAmount", support.money(finalAmount)); + preview.put("discount", discountText(config.getStandardAmount(), finalAmount)); + preview.put("itemCount", itemList.size()); + preview.put("gift", gift); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("购买客户套餐"); + if (override || gift) { + result.setRiskLevel(RiskLevel.SENSITIVE); + result.setReasonRequired(override); + result.setRequiredPhrase("确认以 %s 购买套餐 %s".formatted(support.money(finalAmount), config.getName())); + } + result.setPreviewText(""" + ### 待确认:购买客户套餐 + + 客户:%s(%s) + 套餐:%s + 标准价:%s + 成交价:%s + 优惠:%s + 自定义明细:%d 项 + 赠送权益:%s + 凭证:%d 张 + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(customer.getName(), blank(customer.getCode()), config.getName(), + support.money(config.getStandardAmount()), support.money(finalAmount), + discountText(config.getStandardAmount(), finalAmount), itemList.size(), gift ? "是" : "否", + attachments.size())); + return result; + } + + @Override + public GaoAiCommitResult commit(GaoAiOperationContext context, GaoAiPendingOperation pending, + JsonNode arguments, List attachments) { + GaoCustomerPackagePurchaseRequest request = new GaoCustomerPackagePurchaseRequest(); + request.setRequestNo(pending.getRequestNo()); + request.setPackageConfigId(support.requiredText(arguments, "packageConfigId")); + request.setCustomerId(support.requiredText(arguments, "customerId")); + request.setSaleAmount(support.optionalLong(arguments, "saleAmount", "amount")); + request.setPurchasedAt(support.optionalLong(arguments, "purchasedAt")); + List purchaseItemList = itemList(arguments); + request.setItemList(purchaseItemList.isEmpty() ? null : purchaseItemList); + request.setAttachmentList(attachments); + request.setRemark(support.text(arguments, "remark")); + GaoCustomerPackage result = packageService.purchase(request); + return GaoAiCommitResult.success(GaoAiOperation.CUSTOMER_PACKAGE_PURCHASE.name(), "CUSTOMER_PACKAGE", + result.getId(), result.getSalesOrderId(), "已购买客户套餐「%s」。".formatted(result.getPackageNameSnapshot())); + } + + private List itemList(JsonNode arguments) { + List items = support.array(arguments, "itemList"); + List result = new ArrayList<>(); + for (JsonNode item : items) { + GaoCustomerPackagePurchaseItem purchaseItem = new GaoCustomerPackagePurchaseItem(); + purchaseItem.setSkuId(support.requiredText(item, "skuId")); + purchaseItem.setSkuUnitId(support.requiredText(item, "skuUnitId")); + purchaseItem.setGifted(support.optionalBoolean(item, "gifted")); + purchaseItem.setTotalQuantity(support.requiredDecimal(item, "totalQuantity", "quantity")); + purchaseItem.setRemark(support.text(item, "remark")); + result.add(purchaseItem); + } + return result; + } + + private void validateDiscount(Long standardAmount, Long saleAmount) { + if (standardAmount == null || standardAmount <= 0 || saleAmount == null) { + return; + } + if (saleAmount < 0) { + throw new GaoAiOperationException("VALIDATION_FAILED", "成交价不能为负数"); + } + double discount = BigDecimal.valueOf(standardAmount - saleAmount) + .divide(BigDecimal.valueOf(standardAmount), 4, java.math.RoundingMode.HALF_UP) + .doubleValue(); + if (discount > properties.getMaxDiscountRate()) { + throw new GaoAiOperationException("VALIDATION_FAILED", "优惠幅度超过 %d%% 上限".formatted(Math.round(properties.getMaxDiscountRate() * 100))); + } + } + + private String discountText(Long standardAmount, Long saleAmount) { + if (standardAmount == null || standardAmount <= 0 || saleAmount == null || standardAmount.equals(saleAmount)) { + return "无"; + } + double discount = BigDecimal.valueOf(standardAmount - saleAmount) + .divide(BigDecimal.valueOf(standardAmount), 4, java.math.RoundingMode.HALF_UP) + .doubleValue() * 100; + return "%.2f%%".formatted(discount); + } + + private String blank(String value) { + return value == null ? "-" : value; + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/PointOperationHandler.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/PointOperationHandler.java new file mode 100644 index 0000000..ab48066 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/PointOperationHandler.java @@ -0,0 +1,243 @@ +package com.imyeyu.api.modules.gao.ai.operation.handler; + +import com.fasterxml.jackson.databind.JsonNode; +import com.imyeyu.api.modules.common.entity.Attachment; +import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentToken; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiCommitResult; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationContext; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationHandler; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationSupport; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPreparedOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiToolAuthorizer; +import com.imyeyu.api.modules.gao.bean.GaoPermissionCode; +import com.imyeyu.api.modules.gao.entity.GaoCustomer; +import com.imyeyu.api.modules.gao.entity.GaoPointAccount; +import com.imyeyu.api.modules.gao.entity.GaoPointLedger; +import com.imyeyu.api.modules.gao.entity.GaoPointRedeemSku; +import com.imyeyu.api.modules.gao.entity.GaoPointRedemption; +import com.imyeyu.api.modules.gao.service.GaoPointAccountService; +import com.imyeyu.api.modules.gao.service.GaoPointLedgerService; +import com.imyeyu.api.modules.gao.service.GaoPointRedemptionService; +import com.imyeyu.api.modules.gao.vo.point.GaoPointAdjustRequest; +import com.imyeyu.api.modules.gao.vo.point.GaoPointRedemptionCreateRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.math.BigDecimal; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// 积分写操作处理器 +/// +/// @author Codex +/// @since 2026-11-23 +@Component +@RequiredArgsConstructor +public class PointOperationHandler implements GaoAiOperationHandler { + + private final GaoAiOperationSupport support; + private final GaoAiProperties properties; + private final GaoAiToolAuthorizer authorizer; + private final GaoPointAccountService pointAccountService; + private final GaoPointLedgerService pointLedgerService; + private final GaoPointRedemptionService redemptionService; + + @Override + public Set supports() { + return Set.of(GaoAiOperation.POINT_ADJUST, GaoAiOperation.POINT_REDEMPTION_CREATE); + } + + @Override + public GaoAiPreparedOperation prepare(GaoAiOperationContext context, GaoAiOperationDefinition definition, + JsonNode arguments, List attachments) { + return switch (definition.getOperation()) { + case POINT_ADJUST -> prepareAdjust(context, arguments); + case POINT_REDEMPTION_CREATE -> prepareRedemption(context, arguments, attachments); + default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作"); + }; + } + + @Override + public GaoAiCommitResult commit(GaoAiOperationContext context, GaoAiPendingOperation pending, + JsonNode arguments, List attachments) { + return switch (GaoAiOperation.valueOf(pending.getOperation())) { + case POINT_ADJUST -> commitAdjust(context, pending, arguments); + case POINT_REDEMPTION_CREATE -> commitRedemption(context, pending, arguments, attachments); + default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作"); + }; + } + + private GaoAiPreparedOperation prepareAdjust(GaoAiOperationContext context, JsonNode arguments) { + GaoCustomer customer = support.customer(context.getStoreId(), arguments); + long delta = support.requiredLong(arguments, "调整积分", "pointDelta", "points"); + if (delta == 0) { + throw new GaoAiOperationException("VALIDATION_FAILED", "调整积分不能为 0"); + } + if (Math.abs(delta) > properties.getPointAdjustMaxAbs()) { + throw new GaoAiOperationException("VALIDATION_FAILED", "单次积分调整不能超过 " + properties.getPointAdjustMaxAbs()); + } + String remark = support.requiredText(arguments, "调整原因", "remark", "reason"); + GaoPointAccount account = pointAccountService.getByCustomerId(context.getStoreId(), customer.getId()); + long balance = account == null ? 0L : account.getBalance(); + com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments); + normalized.put("customerId", customer.getId()); + normalized.put("pointDelta", delta); + normalized.put("remark", remark); + + Map preview = new LinkedHashMap<>(); + preview.put("customer", support.customerBrief(customer)); + preview.put("pointDelta", delta); + preview.put("balanceBefore", balance); + preview.put("balanceAfter", balance + delta); + preview.put("remark", remark); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("人工调整客户积分"); + result.setRiskLevel(RiskLevel.SENSITIVE); + result.setReasonRequired(true); + result.setRequiredPhrase("确认调整积分 %+d".formatted(delta)); + result.setPreviewText(""" + ### 待确认:人工调整积分 + + 客户:%s(%s) + 调整:%+d 积分 + 调整前:%d + 调整后:%d + 原因:%s + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(customer.getName(), blank(customer.getCode()), delta, balance, balance + delta, remark)); + return result; + } + + private GaoAiPreparedOperation prepareRedemption(GaoAiOperationContext context, JsonNode arguments, + List attachments) { + if (attachments.isEmpty()) { + throw new GaoAiOperationException("ATTACHMENT_REQUIRED", "积分兑换必须上传照片"); + } + GaoCustomer customer = support.customer(context.getStoreId(), arguments); + GaoPointRedeemSku redeemSku = support.redeemSku(context.getStoreId(), arguments); + BigDecimal quantity = support.requiredDecimal(arguments, "兑换数量", "quantity"); + if (quantity.signum() <= 0) { + throw new GaoAiOperationException("VALIDATION_FAILED", "兑换数量必须大于 0"); + } + if (quantity.stripTrailingZeros().scale() > 3) { + throw new GaoAiOperationException("VALIDATION_FAILED", "兑换数量最多保留三位小数"); + } + if (redeemSku.getDefaultPointCost() == null) { + throw new GaoAiOperationException("VALIDATION_FAILED", "兑换配置缺少默认积分"); + } + Long actualPointCost = support.optionalLong(arguments, "actualPointCost", "pointCost"); + boolean override = actualPointCost != null; + if (override) { + authorizer.checkCode(context.getUserId(), GaoPermissionCode.POINT_REDEMPTION_POINT_ADJUST); + if (actualPointCost <= 0) { + throw new GaoAiOperationException("VALIDATION_FAILED", "实际扣除积分必须大于 0"); + } + } + long defaultTotal; + try { + defaultTotal = BigDecimal.valueOf(redeemSku.getDefaultPointCost()).multiply(quantity) + .setScale(0, java.math.RoundingMode.UNNECESSARY).longValueExact(); + } catch (ArithmeticException e) { + throw new GaoAiOperationException("VALIDATION_FAILED", "兑换数量与默认积分无法得到整数积分"); + } + long finalTotal = override ? actualPointCost : defaultTotal; + GaoPointAccount account = pointAccountService.getByCustomerId(context.getStoreId(), customer.getId()); + long balance = account == null ? 0L : account.getBalance(); + if (balance < finalTotal) { + throw new GaoAiOperationException("VALIDATION_FAILED", "客户积分不足,当前 %d,需要 %d".formatted(balance, finalTotal)); + } + String remark = support.text(arguments, "remark"); + com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments); + normalized.put("customerId", customer.getId()); + normalized.put("redeemSkuId", redeemSku.getId()); + normalized.put("quantity", quantity.toPlainString()); + if (actualPointCost != null) { + normalized.put("actualPointCost", actualPointCost); + } + + Map preview = new LinkedHashMap<>(); + preview.put("customer", support.customerBrief(customer)); + preview.put("product", productName(redeemSku)); + preview.put("quantity", quantity.toPlainString()); + preview.put("defaultPointCost", defaultTotal); + preview.put("actualPointCost", finalTotal); + preview.put("balanceBefore", balance); + preview.put("balanceAfter", balance - finalTotal); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("客户积分兑换"); + result.setRiskLevel(override ? RiskLevel.SENSITIVE : RiskLevel.NORMAL); + if (override) { + result.setReasonRequired(true); + result.setRequiredPhrase("确认以 %d 积分兑换".formatted(finalTotal)); + } + result.setPreviewText(""" + ### 待确认:客户积分兑换 + + 客户:%s(%s) + 产品:%s + 数量:%s + 扣除积分:%d + 积分余额:%d → %d + 凭证:%d 张 + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(customer.getName(), blank(customer.getCode()), productName(redeemSku), + quantity.toPlainString(), finalTotal, balance, balance - finalTotal, attachments.size())); + return result; + } + + private GaoAiCommitResult commitAdjust(GaoAiOperationContext context, GaoAiPendingOperation pending, JsonNode arguments) { + GaoPointAdjustRequest request = new GaoPointAdjustRequest(); + request.setAdjustRequestId(pending.getRequestNo()); + request.setStoreId(context.getStoreId()); + request.setCustomerId(support.requiredText(arguments, "customerId")); + request.setPointDelta(support.requiredLong(arguments, "pointDelta")); + request.setRemark(support.requiredText(arguments, "remark", "reason")); + GaoPointLedger ledger = pointLedgerService.adjust(request, context.getUserId()); + return GaoAiCommitResult.success(GaoAiOperation.POINT_ADJUST.name(), "POINT_LEDGER", ledger.getId(), null, + "已调整客户积分 %+d,当前余额 %d。".formatted(ledger.getPointDelta(), ledger.getBalanceAfter())); + } + + private GaoAiCommitResult commitRedemption(GaoAiOperationContext context, GaoAiPendingOperation pending, + JsonNode arguments, List attachments) { + GaoPointRedemptionCreateRequest request = new GaoPointRedemptionCreateRequest(); + request.setRequestNo(pending.getRequestNo()); + request.setStoreId(context.getStoreId()); + request.setCustomerId(support.requiredText(arguments, "customerId")); + request.setRedeemSkuId(support.requiredText(arguments, "redeemSkuId")); + request.setQuantity(support.requiredDecimal(arguments, "quantity")); + request.setActualPointCost(support.optionalLong(arguments, "actualPointCost", "pointCost")); + request.setAttachmentList(attachments); + request.setRemark(support.text(arguments, "remark")); + GaoPointRedemption redemption = redemptionService.create(request); + return GaoAiCommitResult.success(GaoAiOperation.POINT_REDEMPTION_CREATE.name(), "POINT_REDEMPTION", + redemption.getId(), null, "已完成积分兑换,扣除 %d 积分。".formatted(redemption.getActualPointCost())); + } + + private String productName(GaoPointRedeemSku redeemSku) { + if (redeemSku.getSku() != null) { + return redeemSku.getSku().getName(); + } + return redeemSku.getSkuId(); + } + + private String blank(String value) { + return value == null ? "-" : value; + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/StockOperationHandler.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/StockOperationHandler.java new file mode 100644 index 0000000..aa463f8 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/StockOperationHandler.java @@ -0,0 +1,136 @@ +package com.imyeyu.api.modules.gao.ai.operation.handler; + +import com.fasterxml.jackson.databind.JsonNode; +import com.imyeyu.api.modules.common.entity.Attachment; +import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentToken; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiCommitResult; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationContext; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationHandler; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationSupport; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPreparedOperation; +import com.imyeyu.api.modules.gao.entity.GaoProductSku; +import com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit; +import com.imyeyu.api.modules.gao.entity.GaoProductStock; +import com.imyeyu.api.modules.gao.service.GaoProductStockService; +import com.imyeyu.api.modules.gao.vo.product.GaoProductSkuUnitSelection; +import com.imyeyu.api.modules.gao.vo.product.GaoProductStockChangeRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.math.BigDecimal; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// 库存写操作处理器 +/// +/// @author Codex +/// @since 2026-11-23 +@Component +@RequiredArgsConstructor +public class StockOperationHandler implements GaoAiOperationHandler { + + private final GaoAiOperationSupport support; + private final GaoAiProperties properties; + private final GaoProductStockService stockService; + + @Override + public Set supports() { + return Set.of(GaoAiOperation.STOCK_MANUAL_IN, GaoAiOperation.STOCK_MANUAL_OUT, + GaoAiOperation.STOCK_STOCKTAKE_GAIN, GaoAiOperation.STOCK_STOCKTAKE_LOSS); + } + + @Override + public GaoAiPreparedOperation prepare(GaoAiOperationContext context, GaoAiOperationDefinition definition, + JsonNode arguments, List attachments) { + boolean purchase = definition.getOperation() == GaoAiOperation.STOCK_MANUAL_IN + || definition.getOperation() == GaoAiOperation.STOCK_STOCKTAKE_GAIN; + GaoProductSkuUnitSelection selection = support.skuUnit(context.getStoreId(), arguments, purchase); + BigDecimal quantity = support.requiredDecimal(arguments, "数量", "quantity"); + if (quantity.signum() <= 0) { + throw new GaoAiOperationException("VALIDATION_FAILED", "数量必须大于 0"); + } + if (quantity.compareTo(BigDecimal.valueOf(properties.getStockChangeMaxQuantity())) > 0) { + throw new GaoAiOperationException("VALIDATION_FAILED", "单次库存变更数量不能超过 " + properties.getStockChangeMaxQuantity()); + } + GaoProductSku sku = selection.getSku(); + if (!Boolean.TRUE.equals(sku.getStockEnabled())) { + throw new GaoAiOperationException("VALIDATION_FAILED", "该 SKU 未启用库存管理"); + } + String remark = support.requiredText(arguments, "库存操作备注", "remark", "reason"); + GaoProductStock stock = stockService.detail(context.getStoreId(), sku.getId()); + com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments); + normalized.put("skuId", sku.getId()); + normalized.put("skuUnitId", selection.getUnit().getId()); + normalized.put("quantity", quantity.toPlainString()); + normalized.put("remark", remark); + + Map preview = new LinkedHashMap<>(); + preview.put("productName", selection.getProduct().getName()); + preview.put("skuName", sku.getName()); + preview.put("unitName", selection.getUnit().getName()); + preview.put("quantity", quantity.toPlainString()); + preview.put("onHandQuantity", stock == null ? "0" : stock.getOnHandQuantity().toPlainString()); + preview.put("remark", remark); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle(definition.title()); + result.setRiskLevel(definition.getRiskLevel()); + result.setPreviewText(""" + ### 待确认:%s + + 产品:%s / %s + 数量:%s %s + 当前库存:%s + 备注:%s + 凭证:%d 张 + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(definition.title(), selection.getProduct().getName(), blank(sku.getName()), + quantity.toPlainString(), selection.getUnit().getName(), preview.get("onHandQuantity"), remark, + attachments.size())); + if (definition.getRiskLevel() == RiskLevel.SENSITIVE) { + result.setRequiredPhrase("确认%s %s %s".formatted(definition.title(), quantity.toPlainString(), + selection.getUnit().getName())); + } + return result; + } + + @Override + public GaoAiCommitResult commit(GaoAiOperationContext context, GaoAiPendingOperation pending, + JsonNode arguments, List attachments) { + GaoAiOperation operation = GaoAiOperation.valueOf(pending.getOperation()); + GaoProductStockChangeRequest request = new GaoProductStockChangeRequest(); + request.setRequestNo(pending.getRequestNo()); + request.setStoreId(context.getStoreId()); + request.setSkuId(support.requiredText(arguments, "skuId")); + request.setSkuUnitId(support.requiredText(arguments, "skuUnitId")); + request.setQuantity(support.requiredDecimal(arguments, "quantity")); + request.setOccurredAt(support.optionalLong(arguments, "occurredAt")); + request.setRemark(support.requiredText(arguments, "remark", "reason")); + request.setAttachmentList(attachments); + GaoProductStock stock = switch (operation) { + case STOCK_MANUAL_IN -> stockService.manualIn(request); + case STOCK_MANUAL_OUT -> stockService.manualOut(request); + case STOCK_STOCKTAKE_GAIN -> stockService.stocktakeGain(request); + case STOCK_STOCKTAKE_LOSS -> stockService.stocktakeLoss(request); + default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作"); + }; + return GaoAiCommitResult.success(operation.name(), "PRODUCT_STOCK", stock.getSkuId(), null, + "已完成%s,当前库存 %s。".formatted(operation.getTitle(), stock.getOnHandQuantity().toPlainString())); + } + + private String blank(String value) { + return value == null ? "-" : value; + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/StoreOperationHandler.java b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/StoreOperationHandler.java new file mode 100644 index 0000000..64a68f6 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/operation/handler/StoreOperationHandler.java @@ -0,0 +1,354 @@ +package com.imyeyu.api.modules.gao.ai.operation.handler; + +import com.fasterxml.jackson.databind.JsonNode; +import com.imyeyu.api.modules.common.entity.Article; +import com.imyeyu.api.modules.common.entity.Attachment; +import com.imyeyu.api.modules.common.service.AttachmentService; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentToken; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiCommitResult; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationContext; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationHandler; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationSupport; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPreparedOperation; +import com.imyeyu.api.modules.gao.entity.GaoCustomer; +import com.imyeyu.api.modules.gao.entity.GaoEvent; +import com.imyeyu.api.modules.gao.entity.GaoEventRecord; +import com.imyeyu.api.modules.gao.service.GaoEventRecordService; +import com.imyeyu.api.modules.gao.service.GaoStoreDiaryService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// 门店日记与登记事件写操作处理器 +/// +/// @author Codex +/// @since 2026-11-23 +@Component +@RequiredArgsConstructor +public class StoreOperationHandler implements GaoAiOperationHandler { + + private final GaoAiOperationSupport support; + private final GaoStoreDiaryService diaryService; + private final GaoEventRecordService eventRecordService; + private final AttachmentService attachmentService; + + @Override + public Set supports() { + return Set.of(GaoAiOperation.STORE_DIARY_CREATE, GaoAiOperation.STORE_DIARY_UPDATE, + GaoAiOperation.EVENT_RECORD_CREATE, GaoAiOperation.EVENT_RECORD_UPDATE, GaoAiOperation.EVENT_RECORD_VERIFY); + } + + @Override + public GaoAiPreparedOperation prepare(GaoAiOperationContext context, GaoAiOperationDefinition definition, + JsonNode arguments, List attachments) { + return switch (definition.getOperation()) { + case STORE_DIARY_CREATE -> prepareDiaryCreate(arguments, attachments); + case STORE_DIARY_UPDATE -> prepareDiaryUpdate(context, arguments, attachments); + case EVENT_RECORD_CREATE -> prepareEventCreate(context, arguments, attachments); + case EVENT_RECORD_UPDATE -> prepareEventUpdate(context, arguments, attachments); + case EVENT_RECORD_VERIFY -> prepareEventVerify(context, arguments); + default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作"); + }; + } + + @Override + public GaoAiCommitResult commit(GaoAiOperationContext context, GaoAiPendingOperation pending, + JsonNode arguments, List attachments) { + return switch (GaoAiOperation.valueOf(pending.getOperation())) { + case STORE_DIARY_CREATE -> commitDiaryCreate(context, arguments, attachments); + case STORE_DIARY_UPDATE -> commitDiaryUpdate(context, arguments, attachments); + case EVENT_RECORD_CREATE -> commitEventCreate(context, arguments, attachments); + case EVENT_RECORD_UPDATE -> commitEventUpdate(arguments, attachments); + case EVENT_RECORD_VERIFY -> commitEventVerify(arguments); + default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作"); + }; + } + + private GaoAiPreparedOperation prepareDiaryCreate(JsonNode arguments, List attachments) { + String title = support.requiredText(arguments, "日记标题", "title"); + String content = support.requiredText(arguments, "日记内容", "content"); + Map preview = new LinkedHashMap<>(); + preview.put("title", title); + preview.put("content", content); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(arguments.toString()); + result.setPreview(preview); + result.setTitle("新建门店日记"); + result.setPreviewText(""" + ### 待确认:新建门店日记 + + 标题:%s + 内容:%s + 附件:%d 个 + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(title, content, attachments.size())); + return result; + } + + private GaoAiPreparedOperation prepareDiaryUpdate(GaoAiOperationContext context, JsonNode arguments, + List attachments) { + Article article = diary(context.getStoreId(), arguments); + com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments); + normalized.put("diaryId", article.getId()); + Map preview = new LinkedHashMap<>(); + preview.put("id", article.getId()); + preview.put("title", support.text(arguments, "title") == null ? article.getTitle() : support.text(arguments, "title")); + preview.put("content", support.text(arguments, "content") == null ? article.getContent() : support.text(arguments, "content")); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("修改门店日记"); + result.setPreviewText(""" + ### 待确认:修改门店日记 + + 标题:%s + 内容:%s + 新增附件:%d 个 + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(preview.get("title"), preview.get("content"), attachments.size())); + return result; + } + + private GaoAiPreparedOperation prepareEventCreate(GaoAiOperationContext context, JsonNode arguments, + List attachments) { + GaoCustomer customer = support.customer(context.getStoreId(), arguments); + GaoEvent event = support.event(context.getStoreId(), arguments); + verifyEventPhoto(event, attachments.size()); + Long numberValue = support.optionalLong(arguments, "numberValue"); + Long pointValue = support.optionalLong(arguments, "pointValue"); + long registeredAt = support.optionalLong(arguments, "registeredAt") == null + ? System.currentTimeMillis() : support.optionalLong(arguments, "registeredAt"); + com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments); + normalized.put("customerId", customer.getId()); + normalized.put("eventId", event.getId()); + normalized.put("registeredAt", registeredAt); + Map preview = new LinkedHashMap<>(); + preview.put("customer", support.customerBrief(customer)); + preview.put("event", event.getName()); + preview.put("numberValue", numberValue); + preview.put("pointValue", pointValue); + preview.put("registeredAt", support.dateTime(registeredAt)); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("新建登记事件记录"); + result.setPreviewText(""" + ### 待确认:登记事件 + + 客户:%s(%s) + 事件:%s + 数值:%s + 积分:%s + 登记时间:%s + 凭证:%d 张 + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(customer.getName(), blank(customer.getCode()), event.getName(), blank(numberValue), + blank(pointValue), support.dateTime(registeredAt), attachments.size())); + return result; + } + + private GaoAiPreparedOperation prepareEventUpdate(GaoAiOperationContext context, JsonNode arguments, + List attachments) { + GaoEventRecord record = support.eventRecord(context.getStoreId(), arguments); + com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments); + normalized.put("eventRecordId", record.getId()); + Map preview = new LinkedHashMap<>(); + preview.put("recordId", record.getId()); + preview.put("remark", support.text(arguments, "remark") == null ? record.getRemark() : support.text(arguments, "remark")); + preview.put("attachmentCount", attachments.size()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("修改登记事件记录"); + result.setPreviewText(""" + ### 待确认:修改登记记录 + + 记录 ID:%s + 备注:%s + 新增凭证:%d 张 + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(record.getId(), preview.get("remark"), attachments.size())); + return result; + } + + private GaoAiPreparedOperation prepareEventVerify(GaoAiOperationContext context, JsonNode arguments) { + GaoEventRecord record = support.eventRecord(context.getStoreId(), arguments); + com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments); + normalized.put("eventRecordId", record.getId()); + Map preview = new LinkedHashMap<>(); + preview.put("recordId", record.getId()); + preview.put("customerId", record.getCustomerId()); + preview.put("eventId", record.getEventId()); + + GaoAiPreparedOperation result = new GaoAiPreparedOperation(); + result.setArgumentsJson(normalized.toString()); + result.setPreview(preview); + result.setTitle("核销登记事件记录"); + result.setPreviewText(""" + ### 待确认:核销登记记录 + + 记录 ID:%s + 客户 ID:%s + 事件 ID:%s + + 请回复“确认”执行,回复“取消”放弃。 + """.formatted(record.getId(), record.getCustomerId(), record.getEventId())); + return result; + } + + private GaoAiCommitResult commitDiaryCreate(GaoAiOperationContext context, JsonNode arguments, List attachments) { + Article article = new Article(); + article.setBizId(context.getStoreId()); + article.setTitle(support.requiredText(arguments, "title")); + article.setContent(support.requiredText(arguments, "content")); + article.setDescription(support.text(arguments, "description")); + article.setContentType(contentType(support.text(arguments, "contentType"))); + article.setStatus(Article.Status.NORMAL); + article.setAttachmentList(attachments); + diaryService.create(article, context.getUserId()); + return GaoAiCommitResult.success(GaoAiOperation.STORE_DIARY_CREATE.name(), "STORE_DIARY", article.getId(), + null, "已创建门店日记「%s」。".formatted(article.getTitle())); + } + + private GaoAiCommitResult commitDiaryUpdate(GaoAiOperationContext context, JsonNode arguments, List attachments) { + String id = support.requiredText(arguments, "diaryId", "articleId", "id"); + Article existing = diaryService.get(id); + if (existing == null) { + throw new GaoAiOperationException("STALE_PREVIEW", "门店日记已不存在,请重新发起"); + } + Article article = new Article(); + article.setId(existing.getId()); + article.setTitle(defaultText(support.text(arguments, "title"), existing.getTitle())); + article.setDescription(defaultText(support.text(arguments, "description"), existing.getDescription())); + article.setContent(defaultText(support.text(arguments, "content"), existing.getContent())); + article.setContentType(support.text(arguments, "contentType") == null ? existing.getContentType() + : contentType(support.text(arguments, "contentType"))); + article.setStatus(existing.getStatus()); + article.setAttachmentList(attachments.isEmpty() ? existingAttachments(Attachment.BizType.ARTICLE, existing.getId()) : attachments); + diaryService.update(article, context.getUserId()); + return GaoAiCommitResult.success(GaoAiOperation.STORE_DIARY_UPDATE.name(), "STORE_DIARY", article.getId(), + null, "已更新门店日记「%s」。".formatted(article.getTitle())); + } + + private GaoAiCommitResult commitEventCreate(GaoAiOperationContext context, JsonNode arguments, List attachments) { + String customerId = support.requiredText(arguments, "customerId"); + GaoEvent event = support.event(context.getStoreId(), arguments); + verifyEventPhoto(event, attachments.size()); + GaoEventRecord record = new GaoEventRecord(); + record.setCustomerId(customerId); + record.setStoreId(event.getStoreId()); + record.setEventId(event.getId()); + record.setNumberValue(support.optionalLong(arguments, "numberValue")); + record.setPointValue(support.optionalLong(arguments, "pointValue")); + record.setRegisteredAt(support.optionalLong(arguments, "registeredAt")); + record.setRemark(support.text(arguments, "remark")); + record.setAttachmentList(attachments); + GaoEventRecord created = eventRecordService.createOne(record); + return GaoAiCommitResult.success(GaoAiOperation.EVENT_RECORD_CREATE.name(), "EVENT_RECORD", created.getId(), + null, "已登记事件「%s」。".formatted(event.getName())); + } + + private GaoAiCommitResult commitEventUpdate(JsonNode arguments, List attachments) { + String id = support.requiredText(arguments, "eventRecordId", "recordId", "id"); + GaoEventRecord existing = eventRecordService.get(id); + if (existing == null) { + throw new GaoAiOperationException("STALE_PREVIEW", "登记记录已不存在,请重新发起"); + } + GaoEventRecord record = new GaoEventRecord(); + record.setId(existing.getId()); + record.setStoreId(existing.getStoreId()); + record.setRemark(defaultText(support.text(arguments, "remark"), existing.getRemark())); + record.setAttachmentList(attachments.isEmpty() + ? existingAttachments(Attachment.BizType.GAO_EVENT_RECORD, existing.getId()) : attachments); + eventRecordService.update(record); + return GaoAiCommitResult.success(GaoAiOperation.EVENT_RECORD_UPDATE.name(), "EVENT_RECORD", record.getId(), + null, "已更新登记记录。"); + } + + private GaoAiCommitResult commitEventVerify(JsonNode arguments) { + String id = support.requiredText(arguments, "eventRecordId", "recordId", "id"); + eventRecordService.verify(id); + return GaoAiCommitResult.success(GaoAiOperation.EVENT_RECORD_VERIFY.name(), "EVENT_RECORD", id, + null, "已核销登记记录。"); + } + + private Article diary(String storeId, JsonNode arguments) { + String id = support.text(arguments, "diaryId", "articleId", "id"); + if (id != null) { + Article article = diaryService.get(id); + if (article == null) { + throw new GaoAiOperationException("VALIDATION_FAILED", "未找到门店日记"); + } + support.requireStore(storeId, article.getBizId(), "门店日记不属于当前门店"); + return article; + } + String keyword = support.text(arguments, "diaryKeyword", "title"); + if (keyword == null) { + throw GaoAiOperationException.clarification("请补充门店日记 ID 或标题", List.of("diaryId")); + } + com.imyeyu.api.modules.gao.vo.store.GaoStoreDiaryPage page = + new com.imyeyu.api.modules.gao.vo.store.GaoStoreDiaryPage(); + page.setStoreId(storeId); + page.setSize(20); + var result = diaryService.page(page); + List
matches = result == null || result.getList() == null ? List.of() + : result.getList().stream().filter(item -> support.contains(item.getTitle(), keyword)).toList(); + if (matches.size() == 1) { + return matches.getFirst(); + } + if (matches.size() > 1) { + throw GaoAiOperationException.candidates("匹配到多篇门店日记,请选择日记 ID", + matches.stream().map(item -> support.brief("diaryId", item.getId(), "title", item.getTitle(), + "createdAt", support.dateTime(item.getCreatedAt()))).toList()); + } + throw new GaoAiOperationException("VALIDATION_FAILED", "未找到匹配的门店日记"); + } + + private Article.ContentType contentType(String value) { + if (value == null) { + return Article.ContentType.MARKDOWN; + } + try { + return Article.ContentType.valueOf(value.trim().toUpperCase()); + } catch (RuntimeException e) { + return Article.ContentType.MARKDOWN; + } + } + + private void verifyEventPhoto(GaoEvent event, int attachmentCount) { + if (Boolean.TRUE.equals(event.getRequirePhoto()) && attachmentCount <= 0) { + throw new GaoAiOperationException("ATTACHMENT_REQUIRED", "该登记事件必须上传照片"); + } + } + + private List existingAttachments(Attachment.BizType bizType, String bizId) { + return attachmentService.listByBizId(bizType, bizId); + } + + private String defaultText(String value, String fallback) { + return value == null ? fallback : value; + } + + private String blank(Object value) { + return value == null ? "-" : value.toString(); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiAuditServiceImplement.java b/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiAuditServiceImplement.java index de1a665..3df1c34 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiAuditServiceImplement.java +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiAuditServiceImplement.java @@ -42,8 +42,20 @@ public class GaoAiAuditServiceImplement implements GaoAiAuditService { content.put("status", auditLog.getStatus()); content.put("resultCount", auditLog.getResultCount()); content.put("createdAt", auditLog.getCreatedAt()); + content.put("operation", auditLog.getOperation()); + content.put("operationId", auditLog.getOperationId()); + content.put("requestNo", auditLog.getRequestNo()); + content.put("confirmationTokenDigest", auditLog.getConfirmationTokenDigest()); + content.put("riskLevel", auditLog.getRiskLevel()); + content.put("entityType", auditLog.getEntityType()); + content.put("entityId", auditLog.getEntityId()); + content.put("errorCode", auditLog.getErrorCode()); + content.put("idempotentReplay", auditLog.isIdempotentReplay()); + content.put("reasonDigest", auditLog.getReasonDigest()); try { - Logger logger = new Logger(Logger.Module.GAO, auditLevel(auditLog.getStatus()), "GAO_AI_QUERY"); + String action = auditLog.getAction() == null || auditLog.getAction().isBlank() + ? "GAO_AI_QUERY" : auditLog.getAction(); + Logger logger = new Logger(Logger.Module.GAO, auditLevel(auditLog.getStatus()), action); logger.setUserId(auditLog.getUserId()); logger.setContent(jackson.writeValueAsString(content)); logger.setResult(auditLog.getStatus()); diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiChatServiceImplement.java b/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiChatServiceImplement.java index 38f22a4..109e7a6 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiChatServiceImplement.java +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiChatServiceImplement.java @@ -9,6 +9,8 @@ import com.imyeyu.api.modules.common.service.SettingService; import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties; import com.imyeyu.api.modules.gao.ai.entity.GaoAiAuditLog; import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation; +import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperationService; import com.imyeyu.api.modules.gao.ai.service.GaoAiAccessException; import com.imyeyu.api.modules.gao.ai.service.GaoAiAuditService; import com.imyeyu.api.modules.gao.ai.service.GaoAiChatService; @@ -45,6 +47,7 @@ import java.time.Duration; import java.time.LocalDate; import java.time.ZoneId; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; @@ -75,6 +78,7 @@ public class GaoAiChatServiceImplement implements GaoAiChatService { private final GaoStoreScopeService storeScopeService; private final GaoStoreService storeService; private final GaoAiSessionService sessionService; + private final GaoAiPendingOperationService pendingOperationService; private final GaoAiAuditService auditService; private final SettingService settingService; @@ -116,8 +120,13 @@ public class GaoAiChatServiceImplement implements GaoAiChatService { if (store == null || !store.isActivated()) { throw new GaoAiAccessException("当前账号没有可用的所属门店", 403); } + List attachmentTokens = request.getAttachmentTokenList() == null ? List.of() + : request.getAttachmentTokenList().stream().filter(item -> item != null && !item.isBlank()).map(String::trim).toList(); + if (attachmentTokens.size() > Math.max(1, properties.getAttachmentMaxCount())) { + throw new GaoAiAccessException("附件数量超过限制", 400); + } GaoAiSession session = sessionService.create(user.getId(), storeId, request.getConversationId()); - return stream(session, message); + return stream(session, message, attachmentTokens); } @Override @@ -164,7 +173,7 @@ public class GaoAiChatServiceImplement implements GaoAiChatService { sendDify(request, "删除历史会话"); } - private SseEmitter stream(GaoAiSession session, String message) { + private SseEmitter stream(GaoAiSession session, String message, List attachmentTokens) { long readTimeoutSeconds = positive(properties.getReadTimeoutSeconds(), 600L); long emitterTimeout = Math.min(Long.MAX_VALUE - 1L, readTimeoutSeconds * 1000L + 30_000L); SseEmitter emitter = new SseEmitter(emitterTimeout); @@ -190,7 +199,7 @@ public class GaoAiChatServiceImplement implements GaoAiChatService { emitter.onError(error -> cancel.run()); try { - HttpRequest httpRequest = buildRequest(session, message, readTimeoutSeconds); + HttpRequest httpRequest = buildRequest(session, message, attachmentTokens, readTimeoutSeconds); CompletableFuture> upstream = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofInputStream()); upstreamRef.set(upstream); if (finished.get()) { @@ -218,7 +227,8 @@ public class GaoAiChatServiceImplement implements GaoAiChatService { return emitter; } - private HttpRequest buildRequest(GaoAiSession session, String message, long readTimeoutSeconds) { + private HttpRequest buildRequest(GaoAiSession session, String message, List attachmentTokens, + long readTimeoutSeconds) { ObjectNode body = jackson.createObjectNode(); body.put("query", message); body.put("response_mode", "streaming"); @@ -232,6 +242,26 @@ public class GaoAiChatServiceImplement implements GaoAiChatService { GaoStore store = storeService.get(session.getStoreId()); inputs.put("storeName", store == null ? "当前门店" : store.getName()); inputs.put("today", LocalDate.now(ZONE).toString()); + inputs.put("pendingOperationToken", ""); + inputs.put("pendingOperationSummary", ""); + inputs.put("pendingOperationRisk", ""); + inputs.put("pendingOperationRequiredPhrase", ""); + inputs.put("pendingOperationExpiresAt", ""); + inputs.put("attachmentTokensJson", writeJson(attachmentTokens == null ? List.of() : attachmentTokens)); + GaoAiPendingOperation pending = pendingOperationService.findActive(session.getUserId(), session.getStoreId(), + session.getDifyConversationId()); + if (pending != null) { + try { + String token = pendingOperationService.issueToken(pending); + inputs.put("pendingOperationToken", token); + inputs.put("pendingOperationSummary", truncate(pending.getPreviewText(), 800)); + inputs.put("pendingOperationRisk", pending.getRiskLevel()); + inputs.put("pendingOperationRequiredPhrase", pending.getRequiredPhrase() == null ? "" : pending.getRequiredPhrase()); + inputs.put("pendingOperationExpiresAt", String.valueOf(pending.getExpiresAt())); + } catch (RuntimeException e) { + log.warn("GAO 智能体注入待确认操作失败:operationId={}", pending.getOperationId(), e); + } + } return newDifyRequest("/chat-messages") .timeout(Duration.ofSeconds(readTimeoutSeconds)) .header("X-Timi-AI-Session", session.getSessionId()) @@ -601,12 +631,43 @@ public class GaoAiChatServiceImplement implements GaoAiChatService { } } + private void emitOperationPreview(SseEmitter emitter, GaoAiSession session, AtomicBoolean finished) { + GaoAiPendingOperation pending; + try { + pending = pendingOperationService.findActiveBySourceSession(session.getSessionId()); + } catch (RuntimeException e) { + log.warn("GAO 智能体读取待确认操作失败:sessionId={}", session.getSessionId(), e); + return; + } + if (pending == null) { + return; + } + if (!isBlank(session.getDifyConversationId())) { + pendingOperationService.bindConversation(pending, session.getDifyConversationId()); + } + Map data = new LinkedHashMap<>(); + data.put("operationId", pending.getOperationId()); + data.put("operation", pending.getOperation()); + data.put("riskLevel", pending.getRiskLevel()); + data.put("title", pending.getTitle()); + data.put("preview", pending.getPreview()); + data.put("previewText", pending.getPreviewText()); + data.put("impactText", pending.getImpactText()); + data.put("requiredPhrase", pending.getRequiredPhrase()); + data.put("expiresAt", pending.getExpiresAt()); + data.put("reasonRequired", pending.isReasonRequired()); + data.put("allowedActions", List.of("CONFIRM", "CANCEL")); + data.put("attachmentCount", pending.getAttachmentTokens() == null ? 0 : pending.getAttachmentTokens().size()); + safeSend(emitter, SseEmitter.event().name("operation_preview").data(data), finished); + } + private void emitDone(SseEmitter emitter, GaoAiSession session, long startedAt, AtomicBoolean finished, AtomicReference> timeoutRef, AtomicBoolean auditRecorded, String message, AtomicReference status) { if (finished.get()) { return; } + emitOperationPreview(emitter, session, finished); Map data = new LinkedHashMap<>(); data.put("conversationId", session.getDifyConversationId()); data.put("duration", Math.max(0L, System.currentTimeMillis() - startedAt)); @@ -711,14 +772,21 @@ public class GaoAiChatServiceImplement implements GaoAiChatService { phase, session.getSessionId(), session.getUserId(), session.getStoreId(), error); } - private String writeJson(ObjectNode body) { + private String writeJson(Object value) { try { - return jackson.writeValueAsString(body); + return jackson.writeValueAsString(value); } catch (IOException e) { throw new IllegalStateException("无法生成 Dify 请求", e); } } + private String truncate(String value, int maxLength) { + if (value == null) { + return ""; + } + return value.length() <= maxLength ? value : value.substring(0, maxLength); + } + private String text(JsonNode node, String field, String fallback) { if (node != null && node.hasNonNull(field)) { String value = node.get(field).asText(); diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiSessionServiceImplement.java b/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiSessionServiceImplement.java index 74b7742..44f71d7 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiSessionServiceImplement.java +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/service/implement/GaoAiSessionServiceImplement.java @@ -40,7 +40,7 @@ public class GaoAiSessionServiceImplement implements GaoAiSessionService { session.setUserId(userId); session.setStoreId(storeId); session.setDifyConversationId(blankToNull(difyConversationId)); - session.setAllowedTools(GaoAiToolNames.orderedReadOnlyTools()); + session.setAllowedTools(GaoAiToolNames.orderedSessionTools()); session.setExpiresAt(System.currentTimeMillis() + ttlSeconds * 1000L); session.setUsedCount(0L); redis.set(key(session.getSessionId()), session, ttlSeconds * 1000L); @@ -49,6 +49,19 @@ public class GaoAiSessionServiceImplement implements GaoAiSessionService { @Override public GaoAiSession require(String sessionId) { + return require(sessionId, true); + } + + @Override + public GaoAiSession increaseUsedCount(String sessionId) { + GaoAiSession session = require(sessionId, false); + session.setUsedCount(session.getUsedCount() + 1L); + long remain = Math.max(1L, session.getExpiresAt() - System.currentTimeMillis()); + redis.set(key(session.getSessionId()), session, remain); + return session; + } + + private GaoAiSession require(String sessionId, boolean enforceLimit) { if (isBlank(sessionId)) { throw new GaoAiSessionException("缺少 AI 会话", 401); } @@ -57,15 +70,10 @@ public class GaoAiSessionServiceImplement implements GaoAiSessionService { redis.destroy(key(sessionId.trim())); throw new GaoAiSessionException("AI 会话不存在或已过期", 401); } - return session; - } - - @Override - public GaoAiSession increaseUsedCount(String sessionId) { - GaoAiSession session = require(sessionId); - session.setUsedCount(session.getUsedCount() + 1L); - long remain = Math.max(1L, session.getExpiresAt() - System.currentTimeMillis()); - redis.set(key(session.getSessionId()), session, remain); + if (enforceLimit && properties.getMaxToolCallsPerSession() > 0 + && session.getUsedCount() >= properties.getMaxToolCallsPerSession()) { + throw new GaoAiSessionException("AI 会话工具调用次数已达上限", 429); + } return session; } diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiAttachmentView.java b/src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiAttachmentView.java new file mode 100644 index 0000000..2083213 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiAttachmentView.java @@ -0,0 +1,28 @@ +package com.imyeyu.api.modules.gao.ai.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/// GAO 智能体附件凭证视图 +/// +/// @author Codex +/// @since 2026-11-23 +@Data +@AllArgsConstructor +public class GaoAiAttachmentView { + + /// 附件凭证 + private String token; + + /// 文件名 + private String name; + + /// MIME 类型 + private String mimeType; + + /// 文件大小 + private Long size; + + /// 过期时间 + private long expiresAt; +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiChatRequest.java b/src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiChatRequest.java index 60c8b78..bb55176 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiChatRequest.java +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiChatRequest.java @@ -17,4 +17,7 @@ public class GaoAiChatRequest { /// GLOBAL_MANAGER 兼任店长时使用当前选中门店 ID,可为空 private String storeId; + + /// AI 附件凭证列表,由前端上传附件后携带 + private java.util.List attachmentTokenList; } diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiOperationCommitRequest.java b/src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiOperationCommitRequest.java new file mode 100644 index 0000000..6e2465f --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiOperationCommitRequest.java @@ -0,0 +1,23 @@ +package com.imyeyu.api.modules.gao.ai.vo; + +import lombok.Data; + +/// GAO 智能体卡片提交请求 +/// +/// @author Codex +/// @since 2026-11-23 +@Data +public class GaoAiOperationCommitRequest { + + /// 公开操作 ID + private String operationId; + + /// 破坏性或敏感操作的精确确认短语 + private String confirmationPhrase; + + /// 操作原因 + private String reason; + + /// Dify 会话 ID,可为空 + private String conversationId; +} diff --git a/src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiToolResult.java b/src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiToolResult.java index 52ac6c4..de4b994 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiToolResult.java +++ b/src/main/java/com/imyeyu/api/modules/gao/ai/vo/GaoAiToolResult.java @@ -30,4 +30,76 @@ public class GaoAiToolResult { /// 来源和生成时间 private Map source = new LinkedHashMap<>(); + + /// 写操作状态 + private String status; + + /// 操作代码 + private String operation; + + /// 操作标题 + private String title; + + /// 公开操作 ID + private String operationId; + + /// 确认 token,只在 prepare 成功时返回 + private String confirmationToken; + + /// 风险级别 + private String riskLevel; + + /// 精确确认短语 + private String requiredPhrase; + + /// 待确认操作过期时间 + private Long expiresAt; + + /// 是否是破坏性操作 + private Boolean destructive; + + /// 是否必须填写原因 + private Boolean reasonRequired; + + /// 附件数量 + private Integer attachmentCount; + + /// 写操作预览 + private Map preview = new LinkedHashMap<>(); + + /// 预览文本 + private String previewText; + + /// 风险影响说明 + private String impactText; + + /// 缺失字段 + private List missingFields = new ArrayList<>(); + + /// 候选列表 + private List candidates = new ArrayList<>(); + + /// 错误码 + private String errorCode; + + /// 错误消息 + private String errorMessage; + + /// 是否可重试 + private Boolean retryable; + + /// 结果实体类型 + private String entityType; + + /// 结果实体 ID + private String entityId; + + /// 结果实体业务单号 + private String entityNo; + + /// 结果文本 + private String resultText; + + /// true 为幂等重放 + private Boolean idempotentReplay; } diff --git a/src/main/java/com/imyeyu/api/modules/gao/bean/GaoSystemSetting.java b/src/main/java/com/imyeyu/api/modules/gao/bean/GaoSystemSetting.java index 3a95d7c..56ae09b 100644 --- a/src/main/java/com/imyeyu/api/modules/gao/bean/GaoSystemSetting.java +++ b/src/main/java/com/imyeyu/api/modules/gao/bean/GaoSystemSetting.java @@ -19,6 +19,8 @@ public enum GaoSystemSetting implements SettingEnum { DIFY_MCP_SERVICE_KEY(null, Setting.ValueType.STRING), + DIFY_MCP_COMMIT_SERVICE_KEY(null, Setting.ValueType.STRING), + AI_AGENT_EXAMPLE(null, Setting.ValueType.JSON_LIST), AGREEMENT(null, Setting.ValueType.JSON_OBJECT); diff --git a/src/main/java/com/imyeyu/api/modules/user/context/ExecutionIdentityContext.java b/src/main/java/com/imyeyu/api/modules/user/context/ExecutionIdentityContext.java new file mode 100644 index 0000000..3c72a4f --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/user/context/ExecutionIdentityContext.java @@ -0,0 +1,100 @@ +package com.imyeyu.api.modules.user.context; + +import java.util.function.Supplier; + +/// 受控执行身份上下文 +/// +/// 只允许服务端受信入口(例如 GAO AI MCP 工具执行器)设置。 +/// 该上下文用于让既有业务 Service 在无用户登录令牌的服务间调用中, +/// 仍然按真实用户执行权限、门店范围和操作审计。 +/// +/// @author Codex +/// @since 2026-11-23 +public final class ExecutionIdentityContext { + + private static final ThreadLocal CURRENT = new ThreadLocal<>(); + + private ExecutionIdentityContext() { + } + + /// 以指定用户身份执行 + /// + /// @param userId 用户 ID + /// @param source 调用来源,例如 GAO_AI_MCP + /// @param requestId 请求追踪 ID + /// @param action 待执行逻辑 + /// @return 执行结果 + public static T runAs(String userId, String source, String requestId, Supplier action) { + if (userId == null || userId.isBlank()) { + throw new IllegalArgumentException("执行身份缺少用户"); + } + if (action == null) { + throw new IllegalArgumentException("执行身份缺少执行逻辑"); + } + Identity previous = CURRENT.get(); + if (previous != null && !previous.userId().equals(userId)) { + throw new IllegalStateException("不允许嵌套切换执行身份"); + } + Identity identity = new Identity(userId.trim(), blankToNull(source), blankToNull(requestId)); + CURRENT.set(identity); + try { + return action.get(); + } finally { + if (previous == null) { + CURRENT.remove(); + } else { + CURRENT.set(previous); + } + } + } + + /// 以指定用户身份执行无返回值逻辑 + /// + /// @param userId 用户 ID + /// @param source 调用来源 + /// @param requestId 请求追踪 ID + /// @param action 待执行逻辑 + public static void runAs(String userId, String source, String requestId, Runnable action) { + if (action == null) { + throw new IllegalArgumentException("执行身份缺少执行逻辑"); + } + runAs(userId, source, requestId, () -> { + action.run(); + return null; + }); + } + + /// 获取当前执行身份 + /// + /// @return 执行身份,未设置时返回 null + public static Identity current() { + return CURRENT.get(); + } + + /// 获取当前执行用户 ID + /// + /// @return 用户 ID,未设置时返回 null + public static String currentUserId() { + Identity identity = CURRENT.get(); + return identity == null ? null : identity.userId(); + } + + /// 清理当前线程执行身份 + /// + /// 仅供异常兜底和测试使用,正常路径由 runAs 的 finally 清理。 + public static void clear() { + CURRENT.remove(); + } + + private static String blankToNull(String value) { + return value == null || value.isBlank() ? null : value.trim(); + } + + /// 当前执行身份 + /// + /// @param userId 用户 ID + /// @param source 调用来源 + /// @param requestId 请求追踪 ID + public record Identity(String userId, String source, String requestId) { + } +} diff --git a/src/main/java/com/imyeyu/api/modules/user/service/implement/UserLoginServiceImplement.java b/src/main/java/com/imyeyu/api/modules/user/service/implement/UserLoginServiceImplement.java index b3150e4..2311529 100644 --- a/src/main/java/com/imyeyu/api/modules/user/service/implement/UserLoginServiceImplement.java +++ b/src/main/java/com/imyeyu/api/modules/user/service/implement/UserLoginServiceImplement.java @@ -9,6 +9,7 @@ import com.imyeyu.api.modules.common.service.SmsService; import com.imyeyu.api.modules.common.vo.SmsCaptchaVerifyRequest; import com.imyeyu.api.modules.user.bean.BootstrapData; import com.imyeyu.api.modules.user.bean.UserSetting; +import com.imyeyu.api.modules.user.context.ExecutionIdentityContext; import com.imyeyu.api.modules.user.entity.User; import com.imyeyu.api.modules.user.service.ApiKeyService; import com.imyeyu.api.modules.user.service.UserLoginService; @@ -115,6 +116,21 @@ public class UserLoginServiceImplement implements UserLoginService, TimiJava { return login(UUID.randomUUID().toString(), user.getId()); } + /// 获取当前登录用户 + /// + /// 服务间受信执行入口可通过 {@link ExecutionIdentityContext} 注入真实用户, + /// 其余场景仍按请求令牌解析。 + /// + /// @return 当前用户,未登录时返回 null + @Override + public User getLoginUser() { + String executionUserId = ExecutionIdentityContext.currentUserId(); + if (TimiJava.isNotEmpty(executionUserId)) { + return userService.get(executionUserId); + } + return getLoginUser(TimiSpring.getToken()); + } + @Override public User getLoginUser(String token) { if (TimiJava.isEmpty(token)) { diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index e3d801e..8411f44 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -30,3 +30,21 @@ spring: enable: true required: true default-encoding: UTF-8 + +# GAO 智能体写能力 +gao: + ai: + write: + enabled: false + confirmation-ttl-seconds: 600 + result-ttl-seconds: 1800 + max-prepares-per-10-minutes: 10 + max-commits-per-10-minutes: 10 + max-tool-calls-per-session: 30 + order-max-sale-amount: 1000000 + order-max-discount-rate: 0.30 + point-adjust-max-abs: 10000 + stock-change-max-quantity: 1000 + attachment-max-count: 10 + attachment-max-size-mb: 10 + attachment-ttl-seconds: 86400 diff --git a/src/test/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationRegistryTest.java b/src/test/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationRegistryTest.java new file mode 100644 index 0000000..2bee1bc --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/gao/ai/operation/GaoAiOperationRegistryTest.java @@ -0,0 +1,61 @@ +package com.imyeyu.api.modules.gao.ai.operation; + +import com.imyeyu.api.modules.gao.bean.GaoPermissionCode; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// 智能体写操作注册表静态约束测试 +/// +/// @author Codex +/// @since 2026-11-23 +class GaoAiOperationRegistryTest { + + @Test + void registryContainsNoPhysicalDeleteOperation() { + GaoAiOperationRegistry registry = new GaoAiOperationRegistry(); + for (GaoAiOperation operation : GaoAiOperation.values()) { + assertTrue(registry.require(operation) != null, operation.name()); + } + assertFalse(registry.codes().stream().anyMatch(code -> code.contains("DELETE"))); + assertTrue(registry.codes().contains("CUSTOMER_CREATE")); + assertTrue(registry.codes().contains("SALES_ORDER_CANCEL")); + assertTrue(registry.codes().contains("PAYMENT_REFUND")); + assertTrue(registry.codes().contains("FUND_REVOKE")); + } + + @Test + void destructiveOperationsAreExplicitAndRequireReason() { + GaoAiOperationRegistry registry = new GaoAiOperationRegistry(); + List destructive = registry.destructiveOperationCodes(); + assertTrue(destructive.contains("SALES_ORDER_CANCEL")); + assertTrue(destructive.contains("PAYMENT_REFUND")); + assertTrue(destructive.contains("FUND_REVOKE")); + assertTrue(destructive.contains("PAYMENT_REJECT")); + assertTrue(destructive.contains("FULFILLMENT_CANCEL")); + for (String code : destructive) { + GaoAiOperationDefinition definition = registry.require(code); + assertTrue(definition.isReasonRequired()); + assertTrue(definition.exactPhraseRequired()); + } + } + + @Test + void attachmentPoliciesMatchFinancialOperations() { + GaoAiOperationRegistry registry = new GaoAiOperationRegistry(); + assertEquals(GaoAiOperationDefinition.AttachmentPolicy.REQUIRED, + registry.require("PAYMENT_RECEIVE").getAttachmentPolicy()); + assertEquals(GaoAiOperationDefinition.AttachmentPolicy.REQUIRED, + registry.require("PAYMENT_REFUND").getAttachmentPolicy()); + assertEquals(GaoAiOperationDefinition.AttachmentPolicy.REQUIRED, + registry.require("FULFILLMENT_CREATE").getAttachmentPolicy()); + assertTrue(registry.require("PAYMENT_RECEIVE").getPermissions() + .contains(GaoPermissionCode.FUND_RECEIVE_CREATE)); + assertTrue(registry.require("SALES_ORDER_CANCEL").getPermissions() + .contains(GaoPermissionCode.SALES_ORDER_CANCEL)); + } +} diff --git a/src/test/java/com/imyeyu/api/modules/user/context/ExecutionIdentityContextTest.java b/src/test/java/com/imyeyu/api/modules/user/context/ExecutionIdentityContextTest.java new file mode 100644 index 0000000..89960a2 --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/user/context/ExecutionIdentityContextTest.java @@ -0,0 +1,49 @@ +package com.imyeyu.api.modules.user.context; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/// 受控执行身份上下文测试 +/// +/// @author Codex +/// @since 2026-11-23 +class ExecutionIdentityContextTest { + + @AfterEach + void cleanup() { + ExecutionIdentityContext.clear(); + } + + @Test + void runAsSetsAndClearsIdentity() { + assertNull(ExecutionIdentityContext.current()); + String result = ExecutionIdentityContext.runAs("user-1", "TEST", "request-1", () -> { + assertEquals("user-1", ExecutionIdentityContext.currentUserId()); + assertEquals("TEST", ExecutionIdentityContext.current().source()); + return "ok"; + }); + assertEquals("ok", result); + assertNull(ExecutionIdentityContext.current()); + } + + @Test + void nestedSameUserIsAllowed() { + ExecutionIdentityContext.runAs("user-1", "TEST", "request-1", () -> { + ExecutionIdentityContext.runAs("user-1", "TEST", "request-2", + () -> assertEquals("user-1", ExecutionIdentityContext.currentUserId())); + assertEquals("request-1", ExecutionIdentityContext.current().requestId()); + }); + } + + @Test + void nestedDifferentUserIsRejected() { + ExecutionIdentityContext.runAs("user-1", "TEST", "request-1", () -> assertThrows(IllegalStateException.class, + () -> ExecutionIdentityContext.runAs("user-2", "TEST", "request-2", () -> { + }))); + assertNull(ExecutionIdentityContext.current()); + } +} From 3b62f795deb497903b210fc64d13d4a97f0ccb41 Mon Sep 17 00:00:00 2001 From: Timi Date: Tue, 24 Nov 2026 15:36:17 +0800 Subject: [PATCH 3/6] feat(file): refactor file management module - add virtual path storage, granular permissions, trash and share features - secure upload, archive and transfer tasks; add folder size calculation - split controllers and add async task SSE progress events - add Flyway migrations and file module tests --- .../RequireCorePermissionInterceptor.java | 26 +- .../imyeyu/api/bean/CorePermissionCode.java | 5 + .../java/com/imyeyu/api/config/WebConfig.java | 3 - .../modules/system/audit/AuditOperation.java | 28 +- .../api/modules/system/bean/AccessKey.java | 19 - .../api/modules/system/bean/FileCategory.java | 96 ++++ .../modules/system/bean/FileSyncConfig.java | 50 -- .../api/modules/system/bean/FileType.java | 48 ++ .../api/modules/system/bean/ServerFile.java | 117 +++-- .../system/bean/SystemFileSetting.java | 37 +- .../api/modules/system/bean/TransferFile.java | 19 - .../controller/AsyncTaskController.java | 22 + .../controller/FileArchiveController.java | 109 ++++ .../controller/FileBinaryResponder.java | 53 ++ .../controller/FileContentController.java | 53 ++ .../system/controller/FileController.java | 467 +++--------------- .../controller/FileShareController.java | 91 ++++ .../controller/FileTrashController.java | 78 +++ .../controller/FileUploadController.java | 69 +++ .../api/modules/system/entity/FileShare.java | 63 +++ .../api/modules/system/entity/FileTrash.java | 40 ++ .../system/mapper/FileShareMapper.java | 43 ++ .../system/mapper/FileTrashMapper.java | 24 + .../system/service/AsyncTaskEventService.java | 221 +++++++++ .../system/service/FileContentService.java | 132 +++++ .../modules/system/service/FileService.java | 101 ++-- .../system/service/FileShareService.java | 184 +++++++ .../system/service/FileStorageService.java | 337 +++++++++++++ .../system/service/FileTrashService.java | 167 +++++++ .../system/service/FileUploadService.java | 265 ++++++++++ .../system/service/ThumbnailService.java | 100 ++++ .../service/implement/AbstractAsyncTask.java | 15 +- .../implement/AsyncTaskServiceImplement.java | 2 +- .../implement/FileServiceImplement.java | 415 +++++++--------- .../task/async/FileCalcSizeAsyncTask.java | 130 +++-- .../system/task/async/FileCopyAsyncTask.java | 73 ++- .../system/task/async/FileMoveAsyncTask.java | 80 ++- .../system/task/async/FileSyncTask.java | 150 ------ .../system/task/async/FileTarAsyncTask.java | 109 ++-- .../system/task/async/FileTaskSupport.java | 191 +++++++ .../system/task/async/FileUnTarAsyncTask.java | 188 ++++--- .../system/task/async/FileUnZipAsyncTask.java | 159 +++--- .../system/task/async/FileZipAsyncTask.java | 121 ++--- .../system/util/SystemAPIInterceptor.java | 64 --- .../api/modules/system/vo/ArchiveRequest.java | 9 + .../api/modules/system/vo/AsyncTaskEvent.java | 33 ++ .../modules/system/vo/FileListRequest.java | 9 + .../api/modules/system/vo/FileSizeResult.java | 23 + .../api/modules/system/vo/IdRequest.java | 7 + .../api/modules/system/vo/MkdirRequest.java | 6 + .../api/modules/system/vo/PathRequest.java | 6 + .../api/modules/system/vo/RenameRequest.java | 6 + .../api/modules/system/vo/SearchRequest.java | 6 + .../modules/system/vo/ShareCreateRequest.java | 6 + .../modules/system/vo/UnarchiveRequest.java | 6 + .../system/vo/UploadCompleteRequest.java | 6 + .../modules/system/vo/UploadInitRequest.java | 7 + .../timiserver/V93__create_file_trash.sql | 15 + .../timiserver/V94__create_file_share.sql | 24 + .../service/FileContentServiceTest.java | 94 ++++ .../service/FileServiceImplementTest.java | 102 ++++ .../system/service/FileShareServiceTest.java | 105 ++++ .../service/FileStorageServiceTest.java | 104 ++++ .../system/service/FileTestSupport.java | 61 +++ .../system/service/FileTrashServiceTest.java | 67 +++ .../system/service/FileUploadServiceTest.java | 113 +++++ .../task/async/FileArchiveTaskTest.java | 90 ++++ .../task/async/FileCalcSizeAsyncTaskTest.java | 65 +++ .../task/async/FileTaskSupportTest.java | 84 ++++ 69 files changed, 4380 insertions(+), 1438 deletions(-) delete mode 100644 src/main/java/com/imyeyu/api/modules/system/bean/AccessKey.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/bean/FileCategory.java delete mode 100644 src/main/java/com/imyeyu/api/modules/system/bean/FileSyncConfig.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/bean/FileType.java delete mode 100644 src/main/java/com/imyeyu/api/modules/system/bean/TransferFile.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/controller/FileArchiveController.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/controller/FileBinaryResponder.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/controller/FileContentController.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/controller/FileShareController.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/controller/FileTrashController.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/controller/FileUploadController.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/entity/FileShare.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/entity/FileTrash.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/mapper/FileShareMapper.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/mapper/FileTrashMapper.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/service/AsyncTaskEventService.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/service/FileContentService.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/service/FileShareService.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/service/FileStorageService.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/service/FileTrashService.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/service/FileUploadService.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/service/ThumbnailService.java delete mode 100644 src/main/java/com/imyeyu/api/modules/system/task/async/FileSyncTask.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/task/async/FileTaskSupport.java delete mode 100644 src/main/java/com/imyeyu/api/modules/system/util/SystemAPIInterceptor.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/vo/ArchiveRequest.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/vo/AsyncTaskEvent.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/vo/FileListRequest.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/vo/FileSizeResult.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/vo/IdRequest.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/vo/MkdirRequest.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/vo/PathRequest.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/vo/RenameRequest.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/vo/SearchRequest.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/vo/ShareCreateRequest.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/vo/UnarchiveRequest.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/vo/UploadCompleteRequest.java create mode 100644 src/main/java/com/imyeyu/api/modules/system/vo/UploadInitRequest.java create mode 100644 src/main/resources/db/migration/timiserver/V93__create_file_trash.sql create mode 100644 src/main/resources/db/migration/timiserver/V94__create_file_share.sql create mode 100644 src/test/java/com/imyeyu/api/modules/system/service/FileContentServiceTest.java create mode 100644 src/test/java/com/imyeyu/api/modules/system/service/FileServiceImplementTest.java create mode 100644 src/test/java/com/imyeyu/api/modules/system/service/FileShareServiceTest.java create mode 100644 src/test/java/com/imyeyu/api/modules/system/service/FileStorageServiceTest.java create mode 100644 src/test/java/com/imyeyu/api/modules/system/service/FileTestSupport.java create mode 100644 src/test/java/com/imyeyu/api/modules/system/service/FileTrashServiceTest.java create mode 100644 src/test/java/com/imyeyu/api/modules/system/service/FileUploadServiceTest.java create mode 100644 src/test/java/com/imyeyu/api/modules/system/task/async/FileArchiveTaskTest.java create mode 100644 src/test/java/com/imyeyu/api/modules/system/task/async/FileCalcSizeAsyncTaskTest.java create mode 100644 src/test/java/com/imyeyu/api/modules/system/task/async/FileTaskSupportTest.java diff --git a/src/main/java/com/imyeyu/api/annotation/RequireCorePermissionInterceptor.java b/src/main/java/com/imyeyu/api/annotation/RequireCorePermissionInterceptor.java index 3f6ecbd..5fc7245 100644 --- a/src/main/java/com/imyeyu/api/annotation/RequireCorePermissionInterceptor.java +++ b/src/main/java/com/imyeyu/api/annotation/RequireCorePermissionInterceptor.java @@ -5,6 +5,8 @@ import com.imyeyu.api.bean.CorePermissionCode; import com.imyeyu.api.bean.ModuleCode; import com.imyeyu.api.modules.user.service.PermissionChecker; import com.imyeyu.java.TimiJava; +import com.imyeyu.java.bean.timi.TimiException; +import com.imyeyu.spring.annotation.IgnoreGlobalReturn; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.lang.NonNull; @@ -12,6 +14,8 @@ import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; +import java.io.IOException; + /// /// CORE 权限注解处理器 /// @@ -32,14 +36,28 @@ public class RequireCorePermissionInterceptor implements HandlerInterceptor { return true; } RequireCorePermission annotation = handlerMethod.getMethodAnnotation(RequireCorePermission.class); + if (annotation == null) { + annotation = handlerMethod.getBeanType().getAnnotation(RequireCorePermission.class); + } if (annotation == null || TimiJava.isEmpty(annotation.value())) { return true; } String[] permissionCodeList = java.util.Arrays.stream(annotation.value()).map(CorePermissionCode::getValue).toArray(String[]::new); - if (annotation.mode() == PermissionMatchMode.ANY) { - permissionChecker.checkAny(ModuleCode.CORE, permissionCodeList); - } else { - permissionChecker.checkAll(ModuleCode.CORE, permissionCodeList); + try { + if (annotation.mode() == PermissionMatchMode.ANY) { + permissionChecker.checkAny(ModuleCode.CORE, permissionCodeList); + } else { + permissionChecker.checkAll(ModuleCode.CORE, permissionCodeList); + } + } catch (TimiException e) { + if (handlerMethod.hasMethodAnnotation(IgnoreGlobalReturn.class) && !resp.isCommitted()) { + try { + resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); + } catch (IOException ignored) { + } + return false; + } + throw e; } return true; } diff --git a/src/main/java/com/imyeyu/api/bean/CorePermissionCode.java b/src/main/java/com/imyeyu/api/bean/CorePermissionCode.java index 3a9b96c..aa9d559 100644 --- a/src/main/java/com/imyeyu/api/bean/CorePermissionCode.java +++ b/src/main/java/com/imyeyu/api/bean/CorePermissionCode.java @@ -69,6 +69,11 @@ public enum CorePermissionCode implements BuiltinPermissionCode { NOTIFY_DELETE("NOTIFY:DELETE", "通知删除", false, true), NOTIFY_CANCEL("NOTIFY:CANCEL", "通知取消", false, true), + FILE_READ("FILE:READ", "文件读取", false, true), + FILE_WRITE("FILE:WRITE", "文件写入", false, true), + FILE_DELETE("FILE:DELETE", "文件删除", false, true), + FILE_SHARE("FILE:SHARE", "文件分享", false, true), + USER_ROLE_CREATE("USER_ROLE:CREATE", "用户角色创建", true, true), USER_ROLE_READ("USER_ROLE:READ", "用户角色读取", true, true), USER_ROLE_DELETE("USER_ROLE:DELETE", "用户角色删除", true, true); diff --git a/src/main/java/com/imyeyu/api/config/WebConfig.java b/src/main/java/com/imyeyu/api/config/WebConfig.java index 14af09d..dc61027 100644 --- a/src/main/java/com/imyeyu/api/config/WebConfig.java +++ b/src/main/java/com/imyeyu/api/config/WebConfig.java @@ -11,7 +11,6 @@ import com.imyeyu.api.annotation.RequireCorePermissionInterceptor; import com.imyeyu.api.modules.app.annotation.RequireAppPermissionInterceptor; import com.imyeyu.api.modules.gao.annotation.RequireGaoPermissionInterceptor; import com.imyeyu.api.modules.journal.util.JournalAPIInterceptor; -import com.imyeyu.api.modules.system.util.SystemAPIInterceptor; import com.imyeyu.spring.annotation.RequestBodyValueArgumentResolver; import com.imyeyu.utils.Time; import lombok.RequiredArgsConstructor; @@ -38,7 +37,6 @@ import java.util.List; public class WebConfig implements WebMvcConfigurer { private final ObjectMapper jackson; - private final SystemAPIInterceptor systemAPIInterceptor; private final JournalAPIInterceptor journalAPIInterceptor; private final RequestRateLimitInterceptor requestRateLimitInterceptor; private final RequireGaoPermissionInterceptor requireGaoPermissionInterceptor; @@ -52,7 +50,6 @@ public class WebConfig implements WebMvcConfigurer { */ @Override public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(systemAPIInterceptor).addPathPatterns(SystemAPIInterceptor.PATH); registry.addInterceptor(journalAPIInterceptor).addPathPatterns(JournalAPIInterceptor.PATH); registry.addInterceptor(requireCorePermissionInterceptor).addPathPatterns("/**"); registry.addInterceptor(requireGaoPermissionInterceptor).addPathPatterns("/**"); diff --git a/src/main/java/com/imyeyu/api/modules/system/audit/AuditOperation.java b/src/main/java/com/imyeyu/api/modules/system/audit/AuditOperation.java index ffeba23..f7b7ac4 100644 --- a/src/main/java/com/imyeyu/api/modules/system/audit/AuditOperation.java +++ b/src/main/java/com/imyeyu/api/modules/system/audit/AuditOperation.java @@ -107,7 +107,33 @@ public enum AuditOperation { GAO_USER_DELETE(Logger.Module.GAO), GAO_STORE_DIARY_DELETE(Logger.Module.GAO), GAO_SALES_ORDER_PAYMENT_REJECT(Logger.Module.GAO), - GAO_SALES_ORDER_PAYMENT_CANCEL(Logger.Module.GAO); + GAO_SALES_ORDER_PAYMENT_CANCEL(Logger.Module.GAO), + /// 创建目录 + FILE_MKDIR(Logger.Module.SYSTEM), + + /// 重命名文件或目录 + FILE_RENAME(Logger.Module.SYSTEM), + + /// 上传文件(普通上传或分片上传完成) + FILE_UPLOAD(Logger.Module.SYSTEM), + + /// 移入回收站 + FILE_DELETE(Logger.Module.SYSTEM), + + /// 从回收站恢复 + FILE_RESTORE(Logger.Module.SYSTEM), + + /// 彻底删除回收站文件 + FILE_PURGE(Logger.Module.SYSTEM), + + /// 创建分享链接 + FILE_SHARE_CREATE(Logger.Module.SYSTEM), + + /// 撤销分享链接 + FILE_SHARE_REVOKE(Logger.Module.SYSTEM), + + /// 压缩、解压、复制、移动等归档操作 + FILE_ARCHIVE(Logger.Module.SYSTEM); final Logger.Module module; } diff --git a/src/main/java/com/imyeyu/api/modules/system/bean/AccessKey.java b/src/main/java/com/imyeyu/api/modules/system/bean/AccessKey.java deleted file mode 100644 index 4123bd7..0000000 --- a/src/main/java/com/imyeyu/api/modules/system/bean/AccessKey.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.imyeyu.api.modules.system.bean; - -import lombok.Data; - -/** - * 访问令牌 - * - * @author 夜雨 - * @since 2026-04-28 14:35 - */ -@Data -public class AccessKey { - - /** 值 */ - private String value; - - /** true 为高权限密钥 */ - private Boolean highAuthority; -} diff --git a/src/main/java/com/imyeyu/api/modules/system/bean/FileCategory.java b/src/main/java/com/imyeyu/api/modules/system/bean/FileCategory.java new file mode 100644 index 0000000..d6e60be --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/bean/FileCategory.java @@ -0,0 +1,96 @@ +package com.imyeyu.api.modules.system.bean; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +import java.util.Locale; + +/** + * 文件内容分类 + * + * @author 夜雨 + * @version 2026-11-24 + */ +public enum FileCategory { + + /// 目录 + DIRECTORY, + + /// 图片 + IMAGE, + + /// 视频 + VIDEO, + + /// 音频 + AUDIO, + + /// 纯文本 + TEXT, + + /// 代码/标记语言/配置 + CODE, + + /// 压缩包 + ARCHIVE, + + /// 文档,例如 PDF、Office 文件 + DOCUMENT, + + /// 未识别的其他类型 + OTHER; + + @JsonValue + public String getValue() { + return name().toLowerCase(Locale.ROOT); + } + + @JsonCreator + public static FileCategory of(String value) { + if (value != null) { + for (FileCategory category : values()) { + if (category.name().equalsIgnoreCase(value)) { + return category; + } + } + } + return OTHER; + } + + public static FileCategory of(String mimeType, String extension, boolean directory) { + if (directory) { + return DIRECTORY; + } + String mime = mimeType == null ? "" : mimeType; + if (mime.startsWith("image/")) { + return IMAGE; + } + if (mime.startsWith("video/")) { + return VIDEO; + } + if (mime.startsWith("audio/")) { + return AUDIO; + } + if (mime.startsWith("text/")) { + return TEXT; + } + if (mime.contains("json") || mime.contains("xml") || mime.contains("javascript")) { + return CODE; + } + if (mime.startsWith("application/zip") || mime.startsWith("application/x-tar") || mime.startsWith("application/gzip") + || mime.startsWith("application/x-7z") || mime.startsWith("application/vnd.rar")) { + return ARCHIVE; + } + if (mime.startsWith("application/pdf") || mime.contains("word") || mime.contains("excel") + || mime.contains("powerpoint") || mime.contains("officedocument")) { + return DOCUMENT; + } + String ext = extension == null ? "" : extension.toLowerCase(Locale.ROOT); + return switch (ext) { + case "zip", "tar", "gz", "tgz", "7z", "rar" -> ARCHIVE; + case "java", "js", "ts", "tsx", "jsx", "vue", "py", "go", "rs", "c", "cpp", "h", "cs", "sql", "sh", "bat", "ps1", "json", "xml", "yml", "yaml" -> CODE; + case "md", "txt", "log", "csv" -> TEXT; + default -> OTHER; + }; + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/bean/FileSyncConfig.java b/src/main/java/com/imyeyu/api/modules/system/bean/FileSyncConfig.java deleted file mode 100644 index 17de202..0000000 --- a/src/main/java/com/imyeyu/api/modules/system/bean/FileSyncConfig.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.imyeyu.api.modules.system.bean; - -import lombok.Data; - -import java.util.List; -import java.util.Map; - -/** - * 文件同步配置 - * - * @author 夜雨 - * @since 2024-12-09 14:14 - */ -@Data -public class FileSyncConfig { - - /** true 为启用同步功能 */ - private boolean enable; - - /** 轮询同步任务 cron 周期表达式,如果配置已启用但任务无效时自动创建 */ - private String cron; - - /** 同步任务列表 */ - private Map tasks; - - /** - * 同步任务 - * - * @author 夜雨 - * @since 2024-12-09 14:14 - */ - @Data - public static class Task { - - /** true 为启用此同步任务 */ - private boolean enable; - - /** true 为使用 MD5 校验,将会大幅增加扫描耗时 */ - private boolean useMD5Compare; - - /** 任务 cron 周期表达式 */ - private String cron; - - /** 同步来源文件路径 */ - private String source; - - /** 同步去向文件路径,不可位于 {@link #source} 内 */ - private List targets; - } -} diff --git a/src/main/java/com/imyeyu/api/modules/system/bean/FileType.java b/src/main/java/com/imyeyu/api/modules/system/bean/FileType.java new file mode 100644 index 0000000..e321ac3 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/bean/FileType.java @@ -0,0 +1,48 @@ +package com.imyeyu.api.modules.system.bean; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +import java.util.Locale; + +/** + * 文件系统条目类型 + * + * @author 夜雨 + * @version 2026-11-24 + */ +public enum FileType { + + /// 普通文件 + FILE, + + /// 目录 + DIRECTORY, + + /// 其他类型,例如符号链接、设备文件等 + OTHER; + + @JsonValue + public String getValue() { + return name().toLowerCase(Locale.ROOT); + } + + @JsonCreator + public static FileType of(String value) { + if (value != null) { + for (FileType type : values()) { + if (type.name().equalsIgnoreCase(value)) { + return type; + } + } + } + return OTHER; + } + + public static FileType of(boolean file, boolean directory) { + if (file) { + return FILE; + } + return directory ? DIRECTORY : OTHER; + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/bean/ServerFile.java b/src/main/java/com/imyeyu/api/modules/system/bean/ServerFile.java index 61b600b..6430aab 100644 --- a/src/main/java/com/imyeyu/api/modules/system/bean/ServerFile.java +++ b/src/main/java/com/imyeyu/api/modules/system/bean/ServerFile.java @@ -1,14 +1,16 @@ package com.imyeyu.api.modules.system.bean; -import com.imyeyu.api.TimiServerAPI; -import com.imyeyu.api.modules.common.service.SettingService; import lombok.Data; -import lombok.extern.slf4j.Slf4j; +import lombok.NoArgsConstructor; import org.apache.tika.Tika; -import java.io.File; import java.io.IOException; import java.io.Serializable; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; +import java.util.Locale; /** * 文件属性 @@ -17,16 +19,16 @@ import java.io.Serializable; * @version 2022-01-01 23:04 */ @Data -@Slf4j +@NoArgsConstructor public class ServerFile implements Serializable { - // ---------- 基本属性 ---------- + private static final Tika TIKA = new Tika(); /** 文件名 */ private String name; - /** 绝对路径(非文件系统绝对路径,仅基于配置路径) */ - private String absolutePath; + /** 基于 BASE_PATH 的虚拟路径 */ + private String path; /** MimeType */ private String mimeType; @@ -37,14 +39,30 @@ public class ServerFile implements Serializable { /** 修改时间 */ private Long modifiedAt; + /** 创建时间 */ + private Long createdAt; + + /** 扩展名(小写,不含点) */ + private String extension; + + /** 分类 */ + private FileCategory category; + + /** 文件类型 */ + private FileType type; + + /** true 为可执行 */ + private boolean executable; + + /** 文件 ETag(大小-修改时间) */ + private String etag; + /** true 为文件 */ private Boolean file; /** true 为文件夹 */ private Boolean directory; - // ---------- 权限 ---------- - /** true 为可读 */ private boolean canRead; @@ -57,48 +75,53 @@ public class ServerFile implements Serializable { /** true 为可预览 */ private boolean canPreview; - public ServerFile(File file) { - name = file.getName(); - absolutePath = file.getAbsolutePath().replaceAll("\\\\", "/"); - SettingService settingService = TimiServerAPI.applicationContext.getBean(SettingService.class); - absolutePath = absolutePath.substring(new File(settingService.getSystem(SystemFileSetting.BASE_PATH).asString()).getAbsolutePath().length()); - - modifiedAt = file.lastModified(); - this.file = file.isFile(); - directory = file.isDirectory(); - - canRead = file.canRead(); - canWrite = file.canWrite(); - isHidden = file.isHidden(); - - // 大小 - if (this.file) { - size = file.length(); + public ServerFile(Path base, Path path) { + Path absolute = path.toAbsolutePath().normalize(); + this.name = path.getFileName() == null ? "/" : path.getFileName().toString(); + String relative = base.toAbsolutePath().normalize().relativize(absolute).toString().replace('\\', '/'); + this.path = relative.isEmpty() ? "/" : "/" + relative; + this.file = Files.isRegularFile(absolute, LinkOption.NOFOLLOW_LINKS); + this.directory = Files.isDirectory(absolute, LinkOption.NOFOLLOW_LINKS); + this.type = FileType.of(Boolean.TRUE.equals(this.file), Boolean.TRUE.equals(this.directory)); + this.canRead = Files.isReadable(absolute); + this.canWrite = Files.isWritable(absolute); + this.executable = Files.isExecutable(absolute); + this.extension = extensionOf(this.name); + this.category = FileCategory.of(null, this.extension, Boolean.TRUE.equals(this.directory)); + try { + this.isHidden = Files.isHidden(absolute); + } catch (IOException e) { + this.isHidden = false; + } + if (Boolean.TRUE.equals(this.file)) { try { - mimeType = new Tika().detect(file); - - canPreview = switch (mimeType = new Tika().detect(file)) { - case "image/png", "image/jpeg", "video/mp4", "video/quicktime" -> true; - default -> false; - }; + this.size = Files.size(absolute); } catch (IOException e) { - throw new RuntimeException(e); + this.size = 0L; } + this.modifiedAt = absolute.toFile().lastModified(); + this.mimeType = TIKA.detect(this.name); + this.category = FileCategory.of(this.mimeType, this.extension, false); + this.etag = String.format("\"%x-%x\"", this.size, this.modifiedAt); + this.canPreview = switch (this.mimeType) { + case "image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp", + "video/mp4", "video/quicktime", "video/webm", + "application/pdf", "text/plain" -> true; + default -> false; + }; + } else { + this.size = 0L; + this.modifiedAt = absolute.toFile().lastModified(); + } + try { + this.createdAt = ((FileTime) Files.getAttribute(absolute, "creationTime", LinkOption.NOFOLLOW_LINKS)).toMillis(); + } catch (IOException | RuntimeException e) { + this.createdAt = this.modifiedAt; } } - /** @return true 为可读 */ - public boolean canRead() { - return canRead; - } - - /** @return true 为可写 */ - public boolean canWrite() { - return canWrite; - } - - /** @return true 为可预览 */ - public boolean canPreview() { - return false; + private static String extensionOf(String name) { + int dot = name.lastIndexOf('.'); + return dot > 0 && dot < name.length() - 1 ? name.substring(dot + 1).toLowerCase(Locale.ROOT) : ""; } } diff --git a/src/main/java/com/imyeyu/api/modules/system/bean/SystemFileSetting.java b/src/main/java/com/imyeyu/api/modules/system/bean/SystemFileSetting.java index 768ae41..7be6786 100644 --- a/src/main/java/com/imyeyu/api/modules/system/bean/SystemFileSetting.java +++ b/src/main/java/com/imyeyu/api/modules/system/bean/SystemFileSetting.java @@ -5,7 +5,7 @@ import com.imyeyu.api.modules.common.entity.Setting; import lombok.AllArgsConstructor; import lombok.Getter; -/// +/// 文件模块配置 /// /// @author 夜雨 /// @since 2026-09-08 17:08 @@ -13,9 +13,42 @@ import lombok.Getter; @AllArgsConstructor public enum SystemFileSetting implements SettingEnum { - BASE_PATH("data/file", Setting.ValueType.STRING); + /// 文件存储根目录,相对路径基于进程工作目录,也支持绝对路径 + BASE_PATH("data/file", Setting.ValueType.STRING), + /// 回收站目录,相对路径基于 BASE_PATH + TRASH_PATH(".trash", Setting.ValueType.STRING), + + /// 回收站文件保留天数,超期后由定时任务清理 + TRASH_RETENTION_DAYS("30", Setting.ValueType.INTEGER), + + /// 缩略图缓存目录,相对路径基于 BASE_PATH + THUMBNAIL_PATH(".cache/thumbnails", Setting.ValueType.STRING), + + /// 搜索接口最多返回的文件数量 + SEARCH_MAX_RESULTS("200", Setting.ValueType.INTEGER), + + /// 搜索接口最大遍历深度,避免深层目录耗时过长 + SEARCH_MAX_DEPTH("32", Setting.ValueType.INTEGER), + + /// 搜索接口超时时间,单位秒 + SEARCH_TIMEOUT_SECONDS("5", Setting.ValueType.INTEGER), + + /// 单个文件上传大小上限,单位字节,默认 4 GiB + UPLOAD_MAX_SIZE("4294967296", Setting.ValueType.BYTE_SIZE), + + /// 分片上传的单片大小,单位字节,默认 8 MiB + UPLOAD_CHUNK_SIZE("8388608", Setting.ValueType.BYTE_SIZE), + + /// 是否启用文件分享 + SHARE_ENABLED("true", Setting.ValueType.BOOLEAN), + + /// 分享链接默认有效期,单位天;创建时未指定过期时间则使用该值 + SHARE_DEFAULT_EXPIRE_DAYS("7", Setting.ValueType.INTEGER); + + /// 默认值 final String defaultValue; + /// 配置值类型 final Setting.ValueType valueType; } diff --git a/src/main/java/com/imyeyu/api/modules/system/bean/TransferFile.java b/src/main/java/com/imyeyu/api/modules/system/bean/TransferFile.java deleted file mode 100644 index c9b9014..0000000 --- a/src/main/java/com/imyeyu/api/modules/system/bean/TransferFile.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.imyeyu.api.modules.system.bean; - -import lombok.Data; -import org.springframework.web.multipart.MultipartFile; - -/** - * 上传文件对象 - * - * @author 夜雨 - * @version 2022-01-13 00:51 - */ -@Data -public class TransferFile { - - private Long length; - private String name, path; - - private MultipartFile file; -} diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/AsyncTaskController.java b/src/main/java/com/imyeyu/api/modules/system/controller/AsyncTaskController.java index d3c18e8..9ec8597 100644 --- a/src/main/java/com/imyeyu/api/modules/system/controller/AsyncTaskController.java +++ b/src/main/java/com/imyeyu/api/modules/system/controller/AsyncTaskController.java @@ -1,17 +1,22 @@ package com.imyeyu.api.modules.system.controller; +import com.imyeyu.api.modules.system.service.AsyncTaskEventService; import com.imyeyu.api.modules.system.service.AsyncTaskService; import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; import com.imyeyu.api.modules.system.task.async.DebugAsyncTask; import com.imyeyu.api.modules.system.vo.AsyncTaskView; +import com.imyeyu.api.modules.user.service.UserLoginService; import com.imyeyu.spring.annotation.AOPLog; +import com.imyeyu.spring.annotation.IgnoreGlobalReturn; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; 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 org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import java.util.List; @@ -28,6 +33,8 @@ import java.util.List; public class AsyncTaskController { private final AsyncTaskService service; + private final AsyncTaskEventService eventService; + private final UserLoginService userLoginService; @AOPLog @PostMapping("/debug") @@ -45,6 +52,21 @@ public class AsyncTaskController { return service.getAsyncTask(uuid); } + /** + * 订阅异步任务状态。 + * + *

适用于压缩、解压、复制、移动、文件夹大小统计等长耗时文件任务。 + * 任务结束后服务端会主动关闭连接;客户端断线后可以回退到 {@code /detail} 轮询。

+ * + * @param uuid 任务 ID + * @return SSE 事件流 + */ + @IgnoreGlobalReturn + @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public SseEmitter events(@RequestParam("uuid") String uuid) { + return eventService.subscribe(uuid, userLoginService.getRequireLoginUserId()); + } + @PostMapping("/list") public List list() { return service.listAllView(); diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/FileArchiveController.java b/src/main/java/com/imyeyu/api/modules/system/controller/FileArchiveController.java new file mode 100644 index 0000000..61d249a --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/controller/FileArchiveController.java @@ -0,0 +1,109 @@ +package com.imyeyu.api.modules.system.controller; + +import com.imyeyu.api.annotation.RequireCorePermission; +import com.imyeyu.api.bean.CorePermissionCode; +import com.imyeyu.api.modules.system.audit.AuditOperation; +import com.imyeyu.api.modules.system.audit.OperationAudit; +import com.imyeyu.api.modules.system.service.AsyncTaskService; +import com.imyeyu.api.modules.system.service.FileStorageService; +import com.imyeyu.api.modules.system.task.async.FileCopyAsyncTask; +import com.imyeyu.api.modules.system.task.async.FileMoveAsyncTask; +import com.imyeyu.api.modules.system.task.async.FileTarAsyncTask; +import com.imyeyu.api.modules.system.task.async.FileUnTarAsyncTask; +import com.imyeyu.api.modules.system.task.async.FileUnZipAsyncTask; +import com.imyeyu.api.modules.system.task.async.FileZipAsyncTask; +import com.imyeyu.api.modules.system.vo.ArchiveRequest; +import com.imyeyu.api.modules.system.vo.UnarchiveRequest; +import com.imyeyu.api.modules.user.service.PermissionChecker; +import com.imyeyu.api.modules.user.service.UserLoginService; +import com.imyeyu.spring.annotation.AOPLog; +import com.imyeyu.spring.annotation.RequestRateLimit; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * 文件压缩、复制、移动接口 + * + * @author 夜雨 + * @version 2026-11-24 + */ +@RestController +@RequiredArgsConstructor +@RequestMapping("/system/file") +public class FileArchiveController { + + private final FileStorageService storage; + private final AsyncTaskService asyncTaskService; + private final UserLoginService userLoginService; + private final PermissionChecker permissionChecker; + + @AOPLog + @OperationAudit(AuditOperation.FILE_ARCHIVE) + @RequestRateLimit + @RequireCorePermission({CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE}) + @PostMapping("/zip") + public String zip(@Valid @RequestBody ArchiveRequest request) { + FileZipAsyncTask task = new FileZipAsyncTask(request.list(), request.to(), storage, permissionChecker, userLoginService.getRequireLoginUserId()); + asyncTaskService.addAsyncTask(task); + return task.getId(); + } + + @AOPLog + @OperationAudit(AuditOperation.FILE_ARCHIVE) + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_WRITE) + @PostMapping("/unzip") + public String unzip(@Valid @RequestBody UnarchiveRequest request) { + FileUnZipAsyncTask task = new FileUnZipAsyncTask(request.file(), request.to(), storage, permissionChecker, userLoginService.getRequireLoginUserId()); + asyncTaskService.addAsyncTask(task); + return task.getId(); + } + + @AOPLog + @OperationAudit(AuditOperation.FILE_ARCHIVE) + @RequestRateLimit + @RequireCorePermission({CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE}) + @PostMapping("/tar") + public String tar(@Valid @RequestBody ArchiveRequest request) { + FileTarAsyncTask task = new FileTarAsyncTask(request.list(), request.to(), storage, permissionChecker, userLoginService.getRequireLoginUserId()); + asyncTaskService.addAsyncTask(task); + return task.getId(); + } + + @AOPLog + @OperationAudit(AuditOperation.FILE_ARCHIVE) + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_WRITE) + @PostMapping("/untar") + public String untar(@Valid @RequestBody UnarchiveRequest request) { + FileUnTarAsyncTask task = new FileUnTarAsyncTask(request.file(), request.to(), storage, permissionChecker, userLoginService.getRequireLoginUserId()); + asyncTaskService.addAsyncTask(task); + return task.getId(); + } + + @AOPLog + @OperationAudit(AuditOperation.FILE_ARCHIVE) + @RequestRateLimit + @RequireCorePermission({CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE, CorePermissionCode.FILE_DELETE}) + @PostMapping("/cut") + public String cut(@Valid @RequestBody ArchiveRequest request) { + FileMoveAsyncTask task = new FileMoveAsyncTask(request.list(), request.to(), storage, permissionChecker, userLoginService.getRequireLoginUserId()); + asyncTaskService.addAsyncTask(task); + return task.getId(); + } + + @AOPLog + @OperationAudit(AuditOperation.FILE_ARCHIVE) + @RequestRateLimit + @RequireCorePermission({CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE}) + @PostMapping("/copy") + public String copy(@Valid @RequestBody ArchiveRequest request) { + FileCopyAsyncTask task = new FileCopyAsyncTask(request.list(), request.to(), storage, permissionChecker, userLoginService.getRequireLoginUserId()); + asyncTaskService.addAsyncTask(task); + return task.getId(); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/FileBinaryResponder.java b/src/main/java/com/imyeyu/api/modules/system/controller/FileBinaryResponder.java new file mode 100644 index 0000000..1fbc4e1 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/controller/FileBinaryResponder.java @@ -0,0 +1,53 @@ +package com.imyeyu.api.modules.system.controller; + +import com.imyeyu.java.bean.timi.TimiCode; +import com.imyeyu.java.bean.timi.TimiException; +import jakarta.servlet.http.HttpServletResponse; + +import java.io.IOException; + +/** + * 文件二进制响应异常映射 + * + * @author 夜雨 + * @version 2026-11-24 + */ +final class FileBinaryResponder { + + private FileBinaryResponder() { + } + + static void serve(HttpServletResponse resp, BinaryAction action) { + try { + action.run(); + } catch (TimiException e) { + if (resp.isCommitted()) { + return; + } + int status = switch (e.getCode()) { + case PERMISSION_ERROR -> HttpServletResponse.SC_FORBIDDEN; + case RESULT_NULL -> HttpServletResponse.SC_NOT_FOUND; + case ARG_BAD, ARG_MISS, RESULT_BAD -> HttpServletResponse.SC_BAD_REQUEST; + default -> HttpServletResponse.SC_INTERNAL_SERVER_ERROR; + }; + try { + resp.sendError(status, e.getMessage()); + } catch (IOException ignored) { + } + } catch (Exception e) { + if (resp.isCommitted()) { + return; + } + try { + resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文件处理失败"); + } catch (IOException ignored) { + } + } + } + + @FunctionalInterface + interface BinaryAction { + + void run(); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/FileContentController.java b/src/main/java/com/imyeyu/api/modules/system/controller/FileContentController.java new file mode 100644 index 0000000..224f384 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/controller/FileContentController.java @@ -0,0 +1,53 @@ +package com.imyeyu.api.modules.system.controller; + +import com.imyeyu.api.annotation.RequireCorePermission; +import com.imyeyu.api.bean.CorePermissionCode; +import com.imyeyu.api.modules.system.service.FileContentService; +import com.imyeyu.spring.annotation.IgnoreGlobalReturn; +import com.imyeyu.spring.annotation.RequestRateLimit; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +/** + * 文件内容接口 + * + * @author 夜雨 + * @version 2026-11-24 + */ +@RestController +@RequiredArgsConstructor +@RequestMapping("/system/file") +public class FileContentController { + + private final FileContentService contentService; + + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_READ) + @IgnoreGlobalReturn + @GetMapping("/read/{*path}") + public void read(HttpServletRequest req, HttpServletResponse resp, @PathVariable("path") String path) { + FileBinaryResponder.serve(resp, () -> contentService.serve(req, resp, path, false)); + } + + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_READ) + @IgnoreGlobalReturn + @RequestMapping(value = "/download/{*path}", method = {RequestMethod.GET, RequestMethod.HEAD}) + public void download(HttpServletRequest req, HttpServletResponse resp, @PathVariable("path") String path) { + FileBinaryResponder.serve(resp, () -> contentService.serve(req, resp, path, true)); + } + + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_READ) + @IgnoreGlobalReturn + @GetMapping("/preview/{*path}") + public void preview(HttpServletRequest req, HttpServletResponse resp, @PathVariable("path") String path) { + FileBinaryResponder.serve(resp, () -> contentService.preview(req, resp, path)); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/FileController.java b/src/main/java/com/imyeyu/api/modules/system/controller/FileController.java index e6ccf8d..f496d26 100644 --- a/src/main/java/com/imyeyu/api/modules/system/controller/FileController.java +++ b/src/main/java/com/imyeyu/api/modules/system/controller/FileController.java @@ -1,453 +1,114 @@ package com.imyeyu.api.modules.system.controller; -import com.imyeyu.api.modules.common.service.SettingService; +import com.imyeyu.api.annotation.RequireCorePermission; +import com.imyeyu.api.bean.CorePermissionCode; import com.imyeyu.api.modules.system.bean.ServerFile; -import com.imyeyu.api.modules.system.bean.SystemFileSetting; -import com.imyeyu.api.modules.system.bean.TransferFile; import com.imyeyu.api.modules.system.service.AsyncTaskService; import com.imyeyu.api.modules.system.service.FileService; -import com.imyeyu.api.modules.system.task.async.FileCopyAsyncTask; -import com.imyeyu.api.modules.system.task.async.FileMoveAsyncTask; -import com.imyeyu.api.modules.system.task.async.FileTarAsyncTask; -import com.imyeyu.api.modules.system.task.async.FileUnTarAsyncTask; -import com.imyeyu.api.modules.system.task.async.FileUnZipAsyncTask; -import com.imyeyu.api.modules.system.task.async.FileZipAsyncTask; -import com.imyeyu.api.modules.system.util.ResourceHandler; -import com.imyeyu.api.modules.system.vo.ListFileToRequest; -import com.imyeyu.io.IO; -import com.imyeyu.java.TimiJava; -import com.imyeyu.java.bean.timi.TimiCode; -import com.imyeyu.java.bean.timi.TimiException; -import com.imyeyu.network.Network; -import com.imyeyu.spring.TimiSpring; +import com.imyeyu.api.modules.system.service.FileStorageService; +import com.imyeyu.api.modules.system.task.async.FileCalcSizeAsyncTask; +import com.imyeyu.api.modules.system.vo.MkdirRequest; +import com.imyeyu.api.modules.system.vo.PathRequest; +import com.imyeyu.api.modules.system.vo.RenameRequest; +import com.imyeyu.api.modules.system.vo.SearchRequest; +import com.imyeyu.api.modules.user.service.PermissionChecker; +import com.imyeyu.api.modules.user.service.UserLoginService; import com.imyeyu.spring.annotation.AOPLog; -import com.imyeyu.spring.annotation.IgnoreGlobalReturn; import com.imyeyu.spring.annotation.RequestRateLimit; -import com.imyeyu.spring.bean.RequestRange; -import com.imyeyu.utils.OS; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import lombok.Cleanup; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import net.coobird.thumbnailator.Thumbnails; -import org.apache.tika.Tika; -import org.jcodec.api.FrameGrab; -import org.jcodec.common.model.Picture; -import org.jcodec.scale.AWTUtil; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.RandomAccessFile; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; -import java.util.Map; /** - * 文件系统接口 + * 文件元数据接口 * * @author 夜雨 * @version 2022-01-01 20:00 */ -@Slf4j @RestController @RequiredArgsConstructor @RequestMapping("/system/file") -public class FileController implements TimiJava, OS.FileSystem { +public class FileController { - private final FileService service; - private final SettingService settingService; + private final FileService fileService; + private final FileStorageService storage; private final AsyncTaskService asyncTaskService; + private final UserLoginService userLoginService; + private final PermissionChecker permissionChecker; - private final ResourceHandler resourceHandler; - - /** - * 文件对象 - * - * @param req 请求 - * @param resp 返回 - * @return 元数据对象 - */ @AOPLog @RequestRateLimit - @GetMapping("/object/**") - public ServerFile object(HttpServletRequest req, HttpServletResponse resp) { - String path = req.getServletPath().substring("/system/file/object".length()); - if (TimiJava.isEmpty(path)) { - throw new TimiException(TimiCode.ARG_MISS, "TODO 缺少参数:object"); - } - ServerFile file = new ServerFile(new File(path)); - service.checkAccessPermission(file.getAbsolutePath()); - return file; + @RequireCorePermission(CorePermissionCode.FILE_READ) + @GetMapping("/object/{*path}") + public ServerFile object(@PathVariable("path") String path) { + return fileService.object(path); } - /** - * 深度搜索 - * - * @param params path: 基本路径, keyword: 关键字 - * @return 文件列表 - */ @AOPLog @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_READ) + @GetMapping("/list") + public List list(@RequestParam(defaultValue = "/") String path) { + return fileService.list(path); + } + + @AOPLog + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_READ) @PostMapping("/search") - public List search(@RequestBody Map params) { - if (TimiJava.isEmpty(params.get("path"))) { - throw new TimiException(TimiCode.ARG_MISS, "缺少参数:path"); - } - if (TimiJava.isEmpty(params.get("keyword"))) { - throw new TimiException(TimiCode.ARG_MISS, "缺少参数:keyword"); - } - return service.doFilter(service.search(params.get("path"), params.get("keyword"))); + public FileService.SearchResult search(@Valid @RequestBody SearchRequest request) { + return fileService.search(request.path(), request.keyword()); } - /** - * 文件是否存在 - * - * @param req 请求 - * @param resp 返回 - * @return true 为存在 - */ @AOPLog @RequestRateLimit - @GetMapping("/exist/**") - public boolean exist(HttpServletRequest req, HttpServletResponse resp) { - String path = req.getServletPath().substring("/system/file/exist".length()); - if (TimiJava.isEmpty(path)) { - throw new TimiException(TimiCode.ARG_MISS, "缺少参数:path"); - } - return service.canAccess(path) && service.isExist(path); + @RequireCorePermission(CorePermissionCode.FILE_READ) + @GetMapping("/exist") + public boolean exist(@RequestParam String path) { + return fileService.exists(path); } - /** - * 通用资源加载接口 - * - * @param req 请求 - * @param resp 返回 - */ - @AOPLog - @IgnoreGlobalReturn - @GetMapping("/read/**") - public void read(HttpServletRequest req, HttpServletResponse resp) { - try { - String path = req.getServletPath().substring("/system/file/read".length()); - path = settingService.getSystem(SystemFileSetting.BASE_PATH).asString() + path; - if (TimiJava.isEmpty(path)) { - resp.setStatus(HttpServletResponse.SC_NOT_FOUND); - return; - } - service.checkAccessPermission(path); - Path filePath = Paths.get(path); - if (!Files.exists(filePath)) { - log.warn("read a not exist file: {}", path); - resp.setStatus(HttpServletResponse.SC_NOT_FOUND); - return; - } - resp.setContentLengthLong(Files.size(filePath)); - String mimeType = new Tika().detect(filePath); - if (TimiJava.isNotEmpty(mimeType)) { - resp.setContentType(mimeType); - } - req.setAttribute(ResourceHandler.ATTR_TYPE, ResourceHandler.Type.FILE); - req.setAttribute(ResourceHandler.ATTR_VALUE, filePath); - resourceHandler.handleRequest(req, resp); - } catch (Exception e) { - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } - - /** - * 文件列表 - * - * @return 列表 - */ - @GetMapping("/list/**") - public List list(HttpServletRequest req) { - return service.doFilter(service.list(req.getServletPath().substring("/system/file/list".length()))); - } - - /** - * 预览接口 - * - * @param req 请求 - * @param resp 返回 - */ - @AOPLog - @IgnoreGlobalReturn - @GetMapping("/preview/**") - public void preview(HttpServletRequest req, HttpServletResponse resp) { - resp.setCharacterEncoding(StandardCharsets.UTF_8.toString()); - try { - String path = req.getServletPath().substring("/system/file/preview".length()); - if (TimiJava.isEmpty(path)) { - resp.setStatus(HttpServletResponse.SC_NOT_FOUND); - return; - } - File file = new File(settingService.getSystem(SystemFileSetting.BASE_PATH).asString() + path); - if (!file.exists()) { - log.warn("preview a not exist file: {}", path); - resp.setStatus(HttpServletResponse.SC_NOT_FOUND); - return; - } - service.checkAccessPermission(file.getAbsolutePath()); - String mimeType = new Tika().detect(file); - switch (mimeType) { - case "image/png", "image/bmp", "image/jpeg" -> { - if (TimiJava.isNotEmpty(mimeType)) { - resp.setContentType(mimeType); - } - Thumbnails.of(file).size(256, 256).toOutputStream(resp.getOutputStream()); - } - case "video/mp4", "video/quicktime" -> { - // 视频 - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Picture picture = FrameGrab.getFrameAtSec(file, 2); - BufferedImage bi = AWTUtil.toBufferedImage(picture); - ImageIO.write(bi, "png", baos); - Thumbnails.of(IO.toInputStream(baos)).size(256, 256).toOutputStream(resp.getOutputStream()); - } - default -> resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - } - } catch (Exception e) { - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } - - /** - * 创建文件夹 - * - * @param params path: 路径, name: 名称 - * @return true 为成功 - */ @AOPLog @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_READ) + @GetMapping("/hash") + public FileService.FileHash hash(@RequestParam String path) { + return fileService.hash(path); + } + + @AOPLog + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_READ) + @PostMapping("/size") + public String size(@Valid @RequestBody PathRequest request) { + FileCalcSizeAsyncTask task = new FileCalcSizeAsyncTask( + request.path(), storage, permissionChecker, userLoginService.getRequireLoginUserId() + ); + asyncTaskService.addAsyncTask(task); + return task.getId(); + } + + @AOPLog + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_WRITE) @PostMapping("/mkdir") - public String mkdir(@RequestBody Map params) { - if (TimiJava.isEmpty(params.get("path"))) { - throw new TimiException(TimiCode.ARG_MISS, "缺少参数:path"); - } - if (TimiJava.isEmpty(params.get("name"))) { - throw new TimiException(TimiCode.ARG_MISS, "缺少参数:name"); - } - return service.mkdir(params.get("path"), params.get("name")).getAbsolutePath(); + public ServerFile mkdir(@Valid @RequestBody MkdirRequest request) { + return fileService.mkdir(request.path(), request.name()); } - /** - * 重命名文件 - * - * @param params from: 原文件, to: 目标文件 - * @return true 为成功 - */ @AOPLog @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_WRITE) @PostMapping("/rename") - public boolean rename(@RequestBody Map params) { - if (TimiJava.isEmpty(params.get("from"))) { - throw new TimiException(TimiCode.ARG_MISS, "缺少参数:from"); - } - if (TimiJava.isEmpty(params.get("to"))) { - throw new TimiException(TimiCode.ARG_MISS, "缺少参数:to"); - } - return service.rename(params.get("from"), params.get("to")); - } - - /** - * 压缩 ZIP - * - * @param listFileToRequest 文件列表操作对象 - * @return 异步任务 UUID - */ - @AOPLog - @RequestRateLimit - @PostMapping("/zip") - public String zip(@RequestBody ListFileToRequest listFileToRequest) { - if (TimiJava.isEmpty(listFileToRequest.getList())) { - throw new TimiException(TimiCode.ARG_MISS, "缺少参数:list[]"); - } - if (TimiJava.isEmpty(listFileToRequest.getTo())) { - throw new TimiException(TimiCode.ARG_MISS, "缺少参数:to"); - } - // 异步任务 - FileZipAsyncTask task = new FileZipAsyncTask(listFileToRequest.getList(), listFileToRequest.getTo()); - asyncTaskService.addAsyncTask(task); - return task.getId(); - } - - /** - * 解压缩 ZIP - * - * @param params zipFile: 压缩文件, to: 解压到 - * @return 异步任务 UUID - */ - @AOPLog - @RequestRateLimit - @PostMapping("/unzip") - public String unzip(@RequestBody Map params) { - String zipFilePath = params.get("zipFile"); - if (TimiJava.isEmpty(zipFilePath)) { - throw new TimiException(TimiCode.ARG_MISS, "缺少参数:zipFile"); - } - File zipFile = new File(zipFilePath); - if (!zipFile.exists()) { - throw new TimiException(TimiCode.ARG_BAD, "文件不存在:" + zipFilePath); - } - if (TimiJava.isEmpty(params.get("to"))) { - throw new TimiException(TimiCode.ARG_MISS, "缺少参数:to"); - } - // 异步任务 - FileUnZipAsyncTask task = new FileUnZipAsyncTask(zipFile, params.get("to")); - asyncTaskService.addAsyncTask(task); - return task.getId(); - } - - /** - * 压缩 TAR - * - * @param listFileToRequest 文件列表操作对象 - * @return 异步任务 UUID - */ - @AOPLog - @RequestRateLimit - @PostMapping("/tar") - public String tar(@RequestBody ListFileToRequest listFileToRequest) { - FileTarAsyncTask task = new FileTarAsyncTask(listFileToRequest.getList(), listFileToRequest.getTo()); - asyncTaskService.addAsyncTask(task); - return task.getId(); - } - - /** - * 解压缩 TAR - * - * @param params tarFile: 压缩文件, to: 解压到 - * @return 异步任务 UUID - */ - @AOPLog - @RequestRateLimit - @PostMapping("/untar") - public String untar(@RequestBody Map params) { - // TODO 具名入参 - String tarFilePath = params.get("tarFile"); - if (TimiJava.isEmpty(tarFilePath)) { - throw new TimiException(TimiCode.ARG_MISS, "缺少参数:tarFile"); - } - File tarFile = new File(tarFilePath); - if (!tarFile.exists()) { - throw new TimiException(TimiCode.ARG_BAD, "文件不存在:" + tarFilePath); - } - if (TimiJava.isEmpty(params.get("to"))) { - throw new TimiException(TimiCode.ARG_MISS, "缺少参数:to"); - } - FileUnTarAsyncTask task = new FileUnTarAsyncTask(tarFile, params.get("to")); - asyncTaskService.addAsyncTask(task); - return task.getId(); - } - - /** - * 剪切 - * - * @param listFileToRequest 文件列表操作对象 - * @return 异步任务 UUID - */ - @AOPLog - @RequestRateLimit - @PostMapping("/cut") - public String cut(@RequestBody ListFileToRequest listFileToRequest) { - FileMoveAsyncTask task = new FileMoveAsyncTask(listFileToRequest.getList(), listFileToRequest.getTo()); - asyncTaskService.addAsyncTask(task); - return task.getId(); - } - - /** - * 复制 - * - * @param listFileToRequest 文件列表操作对象 - * @return 异步任务 UUID - */ - @AOPLog - @RequestRateLimit - @PostMapping("/copy") - public String copy(@RequestBody ListFileToRequest listFileToRequest) { - FileCopyAsyncTask task = new FileCopyAsyncTask(listFileToRequest.getList(), listFileToRequest.getTo()); - asyncTaskService.addAsyncTask(task); - return task.getId(); - } - - /** - * 上传文件 - * - * @param transferFile 文件传输对象 - */ - @AOPLog - @RequestRateLimit - @PostMapping("/upload") - public void upload(TransferFile transferFile) { - service.upload(transferFile); - } - - /** - * 下载文件 - * - * @param resp 返回对象 - */ - @AOPLog - @RequestRateLimit - @IgnoreGlobalReturn - @RequestMapping("/download/**") - public void download(HttpServletResponse resp) { - try { - String path = TimiSpring.cutURIStartAt("/system/file/download"); - File file = new File(settingService.getSystem(SystemFileSetting.BASE_PATH).asString() + path); - service.checkAccessPermission(file.getAbsolutePath()); - - String mimeType = new Tika().detect(file); - resp.setContentType(mimeType); - resp.setHeader("Content-Disposition", Network.getFileDownloadHeader(file.getName())); - resp.setHeader("Accept-Ranges", "bytes"); - - RequestRange range = TimiSpring.getRequestRange(file.length()); - if (range == null && resp.isCommitted()) { - return; - } - if (range == null) { - // 完整文件 - resp.setContentLengthLong(file.length()); - resp.setStatus(HttpServletResponse.SC_OK); - IO.toOutputStream(resp.getOutputStream(), file); - } else { - // 分片文件 - resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); - resp.setHeader("Content-Range", "bytes %s-%s/%s".formatted(range.getStart(), range.getEnd(), file.length())); - resp.setContentLengthLong(range.getLength()); - - @Cleanup - RandomAccessFile raf = new RandomAccessFile(file, "r"); - raf.seek(range.getStart()); - IO.toOutputStream(resp.getOutputStream(), raf, range.getStart(), range.getLength()); - } - } catch (Exception e) { - log.error("download error", e); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - } - - /** - * 销毁文件 - * - * @param list 服务器文件绝对路径列表 - */ - @AOPLog - @RequestRateLimit - @PostMapping("/destroy") - public void destroy(@RequestBody String[] list) { - service.destroy(list); + public ServerFile rename(@Valid @RequestBody RenameRequest request) { + return fileService.rename(request.from(), request.to()); } } diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/FileShareController.java b/src/main/java/com/imyeyu/api/modules/system/controller/FileShareController.java new file mode 100644 index 0000000..0033e77 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/controller/FileShareController.java @@ -0,0 +1,91 @@ +package com.imyeyu.api.modules.system.controller; + +import com.imyeyu.api.annotation.RequireCorePermission; +import com.imyeyu.api.bean.CorePermissionCode; +import com.imyeyu.api.modules.system.entity.FileShare; +import com.imyeyu.api.modules.system.entity.Logger; +import com.imyeyu.api.modules.system.service.FileContentService; +import com.imyeyu.api.modules.system.service.FileShareService; +import com.imyeyu.api.modules.system.service.LoggerService; +import com.imyeyu.api.modules.system.vo.ShareCreateRequest; +import com.imyeyu.api.modules.user.service.UserLoginService; +import com.imyeyu.spring.annotation.AOPLog; +import com.imyeyu.spring.annotation.IgnoreGlobalReturn; +import com.imyeyu.spring.annotation.RequestRateLimit; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * 文件分享接口 + * + * @author 夜雨 + * @version 2026-11-24 + */ +@RestController +@RequiredArgsConstructor +@RequestMapping("/system/file") +public class FileShareController { + + private final FileShareService shareService; + private final FileContentService contentService; + private final UserLoginService userLoginService; + private final LoggerService loggerService; + + @RequestRateLimit + @RequireCorePermission({CorePermissionCode.FILE_READ, CorePermissionCode.FILE_SHARE}) + @PostMapping("/share") + public FileShare share(@Valid @RequestBody ShareCreateRequest request) { + return shareService.create(request.path(), request.password(), request.expiresAt(), request.maxDownloads(), userLoginService.getRequireLoginUserId()); + } + + @AOPLog + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_SHARE) + @GetMapping("/share") + public List shares() { + return shareService.list(); + } + + @AOPLog + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_SHARE) + @DeleteMapping("/share/{id}") + public FileShare revokeShare(@PathVariable String id) { + return shareService.revoke(id); + } + + /// 公开分享下载,只校验令牌与密码,不要求登录权限。 + @RequestRateLimit + @IgnoreGlobalReturn + @RequestMapping(value = "/share/{token}/download", method = {RequestMethod.GET, RequestMethod.HEAD}) + public void downloadShare(@PathVariable String token, @RequestParam(required = false) String password, HttpServletRequest req, HttpServletResponse resp) { + FileBinaryResponder.serve(resp, () -> { + boolean consume = !"HEAD".equalsIgnoreCase(req.getMethod()); + FileShare share = shareService.open(token, password, consume); + contentService.serve(req, resp, share.getPath(), true); + loggerService.info(Logger.Module.SYSTEM, "FILE_SHARE_DOWNLOAD", + "shareId=" + share.getId() + ",path=" + share.getPath(), + "token=" + maskToken(token)); + }); + } + + private String maskToken(String token) { + if (token == null || token.length() < 8) { + return "***"; + } + return token.substring(0, 8) + "***"; + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/FileTrashController.java b/src/main/java/com/imyeyu/api/modules/system/controller/FileTrashController.java new file mode 100644 index 0000000..f2abb89 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/controller/FileTrashController.java @@ -0,0 +1,78 @@ +package com.imyeyu.api.modules.system.controller; + +import com.imyeyu.api.annotation.RequireCorePermission; +import com.imyeyu.api.bean.CorePermissionCode; +import com.imyeyu.api.modules.system.bean.ServerFile; +import com.imyeyu.api.modules.system.entity.FileTrash; +import com.imyeyu.api.modules.system.service.FileTrashService; +import com.imyeyu.api.modules.system.vo.FileListRequest; +import com.imyeyu.api.modules.system.vo.IdRequest; +import com.imyeyu.api.modules.user.service.UserLoginService; +import com.imyeyu.spring.annotation.AOPLog; +import com.imyeyu.spring.annotation.RequestRateLimit; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * 文件回收站接口 + * + * @author 夜雨 + * @version 2026-11-24 + */ +@RestController +@RequiredArgsConstructor +@RequestMapping("/system/file") +public class FileTrashController { + + private final FileTrashService trashService; + private final UserLoginService userLoginService; + + @AOPLog + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_DELETE) + @PostMapping("/delete") + public List delete(@Valid @RequestBody FileListRequest request) { + return trashService.trash(request.list(), userLoginService.getRequireLoginUserId()); + } + + @AOPLog + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_READ) + @GetMapping("/trash") + public List trash() { + return trashService.list(); + } + + @AOPLog + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_WRITE) + @PostMapping("/trash/restore") + public ServerFile restore(@Valid @RequestBody IdRequest request) { + return trashService.restore(request.id()); + } + + @AOPLog + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_DELETE) + @DeleteMapping("/trash/{id}") + public void purge(@PathVariable String id) { + trashService.purge(id); + } + + @AOPLog + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_DELETE) + @DeleteMapping("/trash") + public int emptyTrash() { + return trashService.empty(); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/FileUploadController.java b/src/main/java/com/imyeyu/api/modules/system/controller/FileUploadController.java new file mode 100644 index 0000000..66f64f8 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/controller/FileUploadController.java @@ -0,0 +1,69 @@ +package com.imyeyu.api.modules.system.controller; + +import com.imyeyu.api.annotation.RequireCorePermission; +import com.imyeyu.api.bean.CorePermissionCode; +import com.imyeyu.api.modules.system.bean.ServerFile; +import com.imyeyu.api.modules.system.service.FileUploadService; +import com.imyeyu.api.modules.system.vo.UploadCompleteRequest; +import com.imyeyu.api.modules.system.vo.UploadInitRequest; +import com.imyeyu.spring.annotation.AOPLog; +import com.imyeyu.spring.annotation.RequestRateLimit; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +/** + * 文件上传接口 + * + * @author 夜雨 + * @version 2026-11-24 + */ +@RestController +@RequiredArgsConstructor +@RequestMapping("/system/file") +public class FileUploadController { + + private final FileUploadService uploadService; + + @AOPLog + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_WRITE) + @PostMapping("/upload") + public ServerFile upload( + @RequestParam String path, + @RequestParam String name, + @RequestParam(defaultValue = "false") boolean overwrite, + @RequestPart("file") MultipartFile file + ) { + return uploadService.upload(path, name, file, overwrite); + } + + @AOPLog + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_WRITE) + @PostMapping("/upload/init") + public FileUploadService.UploadInit initUpload(@Valid @RequestBody UploadInitRequest request) { + return uploadService.init(request.path(), request.name(), request.size(), request.sha256()); + } + + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_WRITE) + @PostMapping("/upload/chunk") + public void uploadChunk(@RequestParam String uploadId, @RequestParam int index, @RequestPart("file") MultipartFile file) { + uploadService.chunk(uploadId, index, file); + } + + @AOPLog + @RequestRateLimit + @RequireCorePermission(CorePermissionCode.FILE_WRITE) + @PostMapping("/upload/complete") + public ServerFile completeUpload(@Valid @RequestBody UploadCompleteRequest request) { + return uploadService.complete(request.uploadId(), request.sha256()); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/entity/FileShare.java b/src/main/java/com/imyeyu/api/modules/system/entity/FileShare.java new file mode 100644 index 0000000..9a19677 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/entity/FileShare.java @@ -0,0 +1,63 @@ +package com.imyeyu.api.modules.system.entity; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.imyeyu.spring.annotation.Entity; +import com.imyeyu.spring.annotation.table.AutoUUID; +import com.imyeyu.spring.annotation.table.Id; +import lombok.Data; +import lombok.ToString; + +/// 文件分享 +@Data +@Entity +public class FileShare { + + @Id + @AutoUUID + private String id; + + /// 分享令牌 + @ToString.Exclude + private String token; + + /// 文件虚拟路径 + private String path; + + /// 文件名 + private String name; + + /// 创建人 + private String ownerUserId; + + /// 密码哈希(salt:hash) + @JsonIgnore + @ToString.Exclude + private String passwordHash; + + /// 分享时的文件 SHA-256 + private String fileHash; + + /// 分享时的文件大小 + private long fileSize; + + /// 分享时的文件修改时间(epoch millis) + private long fileModifiedAt; + + /// 过期时间(epoch millis) + private long expiresAt; + + /// 最大下载次数,0 表示不限 + private int maxDownloads; + + /// 已下载次数 + private int downloadCount; + + /// 最后访问时间 + private long lastAccessAt; + + /// 创建时间 + private long createdAt; + + /// 删除时间(epoch millis),0 表示未删除 + private long deletedAt; +} diff --git a/src/main/java/com/imyeyu/api/modules/system/entity/FileTrash.java b/src/main/java/com/imyeyu/api/modules/system/entity/FileTrash.java new file mode 100644 index 0000000..8d98fcf --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/entity/FileTrash.java @@ -0,0 +1,40 @@ +package com.imyeyu.api.modules.system.entity; + +import com.imyeyu.spring.annotation.Entity; +import com.imyeyu.spring.annotation.table.AutoUUID; +import com.imyeyu.spring.annotation.table.Id; +import lombok.Data; + +/// 回收站记录。文件被删除时移动到 `BASE_PATH/.trash/{trashName}`,记录原路径用于恢复。 +@Data +@Entity +public class FileTrash { + + @Id + @AutoUUID + protected String id; + + /// 删除前的虚拟路径 + protected String originalPath; + + /// 回收站中的目录名(UUID) + protected String trashName; + + /// 文件或文件夹名称 + protected String name; + + /// 文件大小时为字节数,文件夹为 0 + protected long size; + + /// 是否为文件夹 + protected boolean directory; + + /// 删除人用户 ID + protected String ownerUserId; + + /// 删除时间 + protected long deletedAt; + + /// 过期时间,超过后由定时任务彻底删除 + protected long expiresAt; +} diff --git a/src/main/java/com/imyeyu/api/modules/system/mapper/FileShareMapper.java b/src/main/java/com/imyeyu/api/modules/system/mapper/FileShareMapper.java new file mode 100644 index 0000000..d725bc2 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/mapper/FileShareMapper.java @@ -0,0 +1,43 @@ +package com.imyeyu.api.modules.system.mapper; + +import com.imyeyu.api.modules.system.entity.FileShare; +import com.imyeyu.spring.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +import java.util.List; + +public interface FileShareMapper extends BaseMapper { + + @Select("SELECT * FROM file_share WHERE id = #{id}") + FileShare selectRecord(@Param("id") String id); + + @Select("SELECT * FROM file_share WHERE token = #{token} AND deleted_at = 0") + FileShare selectActiveByToken(@Param("token") String token); + + @Select("SELECT * FROM file_share WHERE deleted_at = 0 ORDER BY created_at DESC") + List listAll(); + + @Select("SELECT COUNT(*) FROM file_share WHERE token = #{token}") + int countByToken(@Param("token") String token); + + @Update("UPDATE file_share SET deleted_at = #{now} WHERE id = #{id} AND deleted_at = 0") + int softDelete(@Param("id") String id, @Param("now") long now); + + @Update(""" + UPDATE file_share + SET file_hash = #{hash}, file_size = #{size}, file_modified_at = #{modifiedAt} + WHERE id = #{id} + """) + int updateFileMetadata(@Param("id") String id, @Param("hash") String hash, @Param("size") long size, @Param("modifiedAt") long modifiedAt); + + @Update(""" + UPDATE file_share + SET download_count = download_count + 1, last_access_at = #{now} + WHERE id = #{id} + AND deleted_at = 0 + AND (max_downloads = 0 OR download_count < max_downloads) + """) + int incrementDownload(@Param("id") String id, @Param("now") long now); +} diff --git a/src/main/java/com/imyeyu/api/modules/system/mapper/FileTrashMapper.java b/src/main/java/com/imyeyu/api/modules/system/mapper/FileTrashMapper.java new file mode 100644 index 0000000..b17721c --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/mapper/FileTrashMapper.java @@ -0,0 +1,24 @@ +package com.imyeyu.api.modules.system.mapper; + +import com.imyeyu.api.modules.system.entity.FileTrash; +import com.imyeyu.spring.mapper.BaseMapper; +import org.apache.ibatis.annotations.Delete; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +public interface FileTrashMapper extends BaseMapper { + + @Select("SELECT * FROM `file_trash` WHERE `expires_at` > #{now} ORDER BY `deleted_at` DESC") + List listActive(@Param("now") long now); + + @Select("SELECT * FROM `file_trash` WHERE `id` = #{id} AND `expires_at` > #{now}") + FileTrash selectActive(@Param("id") String id, @Param("now") long now); + + @Select("SELECT * FROM `file_trash` WHERE `expires_at` <= #{now}") + List listExpired(@Param("now") long now); + + @Delete("DELETE FROM `file_trash` WHERE `id` = #{id}") + int deleteRecord(@Param("id") String id); +} diff --git a/src/main/java/com/imyeyu/api/modules/system/service/AsyncTaskEventService.java b/src/main/java/com/imyeyu/api/modules/system/service/AsyncTaskEventService.java new file mode 100644 index 0000000..04fb03a --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/service/AsyncTaskEventService.java @@ -0,0 +1,221 @@ +package com.imyeyu.api.modules.system.service; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.imyeyu.api.modules.system.entity.AsyncTask; +import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; +import com.imyeyu.api.modules.system.vo.AsyncTaskEvent; +import com.imyeyu.java.bean.timi.TimiCode; +import com.imyeyu.java.bean.timi.TimiException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.stereotype.Service; +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; + +import java.io.IOException; +import java.time.Duration; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; + +/** + * 异步任务 SSE 推送。 + * + *

任务记录仍然是唯一状态源,SSE 只负责把状态变化、日志和最终结果推送给前端。 + * 连接断开或任务结束后会取消内部轮询,避免遗留定时任务。

+ * + * @author 夜雨 + * @version 2026-11-24 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class AsyncTaskEventService { + + private static final long CONNECTION_TIMEOUT = 30L * 60 * 1000; + private static final long POLL_INTERVAL = 500L; + private static final long HEARTBEAT_INTERVAL = 15L * 1000; + private static final int MESSAGE_LIMIT = 4096; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private final AsyncTaskService asyncTaskService; + private final TaskScheduler taskScheduler; + + /** + * 订阅异步任务事件。 + * + * @param taskId 任务 ID + * @param userId 当前登录用户 ID + * @return SSE 连接 + */ + public SseEmitter subscribe(String taskId, String userId) { + AbstractAsyncTask task = asyncTaskService.getAsyncTask(taskId); + checkOwner(task, userId); + + SseEmitter emitter = new SseEmitter(CONNECTION_TIMEOUT); + AtomicBoolean finished = new AtomicBoolean(); + AtomicReference> futureRef = new AtomicReference<>(); + AtomicReference lastPayload = new AtomicReference<>(); + AtomicLong lastHeartbeatAt = new AtomicLong(System.currentTimeMillis()); + + Runnable stopAction = () -> stop(emitter, finished, futureRef); + emitter.onCompletion(stopAction); + emitter.onTimeout(stopAction); + emitter.onError(error -> stopAction.run()); + + String payload = payload(task); + lastPayload.set(payload); + boolean terminal = terminal(task.getStatus()); + if (terminal) { + sendTerminal(emitter, task.getStatus(), payload, finished, futureRef); + return emitter; + } + if (!send(emitter, "snapshot", payload, finished, futureRef)) { + return emitter; + } + + ScheduledFuture future; + try { + future = taskScheduler.scheduleAtFixedRate( + () -> tick(taskId, emitter, finished, futureRef, lastPayload, lastHeartbeatAt), + Duration.ofMillis(POLL_INTERVAL) + ); + } catch (RuntimeException e) { + log.warn("订阅异步任务 SSE 失败,taskId={}", taskId, e); + sendError(emitter, "任务状态订阅失败", finished, futureRef); + return emitter; + } + futureRef.set(future); + if (finished.get()) { + future.cancel(false); + } + return emitter; + } + + private void tick(String taskId, SseEmitter emitter, AtomicBoolean finished, + AtomicReference> futureRef, AtomicReference lastPayload, + AtomicLong lastHeartbeatAt) { + if (finished.get()) { + return; + } + AbstractAsyncTask task; + try { + task = asyncTaskService.getAsyncTask(taskId); + } catch (TimiException e) { + sendError(emitter, "任务不存在或已结束", finished, futureRef); + return; + } catch (RuntimeException e) { + log.warn("读取异步任务状态失败,taskId={}", taskId, e); + sendError(emitter, "读取任务状态失败", finished, futureRef); + return; + } + + String payload = payload(task); + if (terminal(task.getStatus())) { + sendTerminal(emitter, task.getStatus(), payload, finished, futureRef); + return; + } + if (!payload.equals(lastPayload.getAndSet(payload))) { + if (!send(emitter, "progress", payload, finished, futureRef)) { + return; + } + lastHeartbeatAt.set(System.currentTimeMillis()); + return; + } + long now = System.currentTimeMillis(); + if (HEARTBEAT_INTERVAL <= now - lastHeartbeatAt.get()) { + lastHeartbeatAt.set(now); + send(emitter, "heartbeat", "{}", finished, futureRef); + } + } + + private void sendTerminal(SseEmitter emitter, AsyncTask.Status status, String payload, + AtomicBoolean finished, AtomicReference> futureRef) { + String event = status == AsyncTask.Status.SUCCESS ? "done" : "error"; + if (send(emitter, event, payload, finished, futureRef)) { + stop(emitter, finished, futureRef); + } + } + + private void sendError(SseEmitter emitter, String message, AtomicBoolean finished, + AtomicReference> futureRef) { + try { + String payload = MAPPER.writeValueAsString(java.util.Map.of("message", message)); + if (send(emitter, "error", payload, finished, futureRef)) { + stop(emitter, finished, futureRef); + } + } catch (JsonProcessingException e) { + stop(emitter, finished, futureRef); + } + } + + private boolean send(SseEmitter emitter, String event, String payload, AtomicBoolean finished, + AtomicReference> futureRef) { + if (finished.get()) { + return false; + } + try { + emitter.send(SseEmitter.event().name(event).data(payload)); + return true; + } catch (IOException | IllegalStateException e) { + log.debug("异步任务 SSE 发送失败", e); + stop(emitter, finished, futureRef); + return false; + } + } + + private void stop(SseEmitter emitter, AtomicBoolean finished, AtomicReference> futureRef) { + if (!finished.compareAndSet(false, true)) { + return; + } + ScheduledFuture future = futureRef.getAndSet(null); + if (future != null) { + future.cancel(false); + } + try { + emitter.complete(); + } catch (Exception e) { + log.debug("关闭异步任务 SSE 连接失败", e); + } + } + + private void checkOwner(AbstractAsyncTask task, String userId) { + String ownerUserId = task.getOwnerUserId(); + if (ownerUserId != null && !ownerUserId.equals(userId)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "无权访问该任务"); + } + } + + private String payload(AbstractAsyncTask task) { + String message = task.getMessage(); + if (message != null && MESSAGE_LIMIT < message.length()) { + message = message.substring(message.length() - MESSAGE_LIMIT); + } + AsyncTaskEvent event = new AsyncTaskEvent( + task.getId(), + task.getName(), + task.getType(), + task.getStatus(), + task.getProgress(), + message, + task.getResult(), + task.getCreatedAt(), + task.getStartAt(), + task.getCompletedAt() + ); + try { + return MAPPER.writeValueAsString(event); + } catch (JsonProcessingException e) { + throw new IllegalStateException("异步任务事件序列化失败", e); + } + } + + private boolean terminal(AsyncTask.Status status) { + return status == AsyncTask.Status.SUCCESS + || status == AsyncTask.Status.ERROR + || status == AsyncTask.Status.INTERRUPT + || status == AsyncTask.Status.DIED; + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/service/FileContentService.java b/src/main/java/com/imyeyu/api/modules/system/service/FileContentService.java new file mode 100644 index 0000000..3edcdb4 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/service/FileContentService.java @@ -0,0 +1,132 @@ +package com.imyeyu.api.modules.system.service; + +import com.imyeyu.api.modules.system.util.ResourceHandler; +import com.imyeyu.java.bean.timi.TimiCode; +import com.imyeyu.java.bean.timi.TimiException; +import com.imyeyu.network.Network; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.tika.Tika; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.util.Set; + +/// 文件内容服务:负责下载、读取、预览和 HTTP 缓存语义。 +@Slf4j +@Service +@RequiredArgsConstructor +public class FileContentService { + + private static final Tika TIKA = new Tika(); + private static final Set ATTACHMENT_TYPES = Set.of( + "text/html", "application/xhtml+xml", "image/svg+xml", + "application/javascript", "text/javascript", "application/x-javascript" + ); + + private final FileStorageService storage; + private final ThumbnailService thumbnailService; + private final ResourceHandler resourceHandler; + + public ContentInfo info(String virtualPath) { + Path file = storage.resolveExisting(virtualPath); + if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.ARG_BAD, "路径不是文件"); + } + try { + long size = Files.size(file); + long modifiedAt = Files.getLastModifiedTime(file).toMillis(); + String mimeType = TIKA.detect(file); + String etag = "\"%x-%x\"".formatted(size, modifiedAt); + return new ContentInfo(file, mimeType, size, modifiedAt, etag, + ATTACHMENT_TYPES.contains(mimeType)); + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "读取文件失败"); + } + } + + /// 输出原始文件,支持 GET/HEAD/Range/ETag。 + public void serve(HttpServletRequest req, HttpServletResponse resp, String virtualPath, boolean attachment) { + ContentInfo info = info(virtualPath); + resp.setHeader("ETag", info.etag()); + resp.setDateHeader("Last-Modified", info.modifiedAt()); + resp.setHeader("Cache-Control", "private, max-age=0, must-revalidate"); + if (notModified(req, info)) { + resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); + return; + } + resp.setContentType(info.mimeType()); + resp.setHeader("X-Content-Type-Options", "nosniff"); + if (attachment || info.attachment()) { + try { + resp.setHeader("Content-Disposition", Network.getFileDownloadHeader(info.path().getFileName().toString())); + } catch (java.io.UnsupportedEncodingException e) { + resp.setHeader("Content-Disposition", "attachment"); + } + } + req.setAttribute(ResourceHandler.ATTR_TYPE, ResourceHandler.Type.FILE); + req.setAttribute(ResourceHandler.ATTR_VALUE, info.path()); + try { + resourceHandler.handleRequest(req, resp); + } catch (Exception e) { + if (!resp.isCommitted()) { + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + } + + /// 输出预览图。图片/视频走缩略图缓存,PDF/文本直接内联。 + public void preview(HttpServletRequest req, HttpServletResponse resp, String virtualPath) { + ContentInfo info = info(virtualPath); + if (info.attachment()) { + throw new TimiException(TimiCode.ARG_BAD, "该文件类型不支持在线预览"); + } + resp.setHeader("ETag", info.etag()); + resp.setDateHeader("Last-Modified", info.modifiedAt()); + if (notModified(req, info)) { + resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); + return; + } + if (info.mimeType().startsWith("image/") || info.mimeType().startsWith("video/")) { + Path thumbnail = thumbnailService.thumbnail(info.path(), info.mimeType()); + try { + resp.setContentType("image/png"); + resp.setHeader("X-Content-Type-Options", "nosniff"); + resp.setHeader("Cache-Control", "private, max-age=86400"); + resp.setContentLengthLong(Files.size(thumbnail)); + Files.copy(thumbnail, resp.getOutputStream()); + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "生成预览失败"); + } + return; + } + if ("application/pdf".equals(info.mimeType()) || "text/plain".equals(info.mimeType())) { + resp.setContentType(info.mimeType()); + resp.setHeader("X-Content-Type-Options", "nosniff"); + resp.setHeader("Content-Disposition", "inline; filename*=UTF-8''" + + java.net.URLEncoder.encode(info.path().getFileName().toString(), java.nio.charset.StandardCharsets.UTF_8).replace("+", "%20")); + resp.setContentLengthLong(info.size()); + try { + Files.copy(info.path(), resp.getOutputStream()); + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "读取文件失败"); + } + return; + } + throw new TimiException(TimiCode.ARG_BAD, "该文件类型不支持预览"); + } + + private boolean notModified(HttpServletRequest req, ContentInfo info) { + String ifNoneMatch = req.getHeader("If-None-Match"); + return ifNoneMatch != null && ifNoneMatch.contains(info.etag()); + } + + public record ContentInfo(Path path, String mimeType, long size, long modifiedAt, String etag, + boolean attachment) { + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/service/FileService.java b/src/main/java/com/imyeyu/api/modules/system/service/FileService.java index 7a7cd36..5066306 100644 --- a/src/main/java/com/imyeyu/api/modules/system/service/FileService.java +++ b/src/main/java/com/imyeyu/api/modules/system/service/FileService.java @@ -1,114 +1,95 @@ package com.imyeyu.api.modules.system.service; -import com.imyeyu.java.bean.timi.TimiException; import com.imyeyu.api.modules.system.bean.ServerFile; -import com.imyeyu.api.modules.system.bean.TransferFile; -import java.io.File; import java.io.InputStream; import java.util.List; /** - * 文件服务 + * 文件元数据服务 * * @author 夜雨 * @version 2022-01-07 16:03 */ public interface FileService { - boolean canAccess(String absPath) throws TimiException; - - default boolean canAccess(File file) throws TimiException { - return canAccess(file.getAbsolutePath()); - } - - void checkAccessPermission(String absPath) throws TimiException; - - default void checkAccessPermission(File file) throws TimiException { - checkAccessPermission(file.getAbsolutePath()); - } - - List doFilter(List list) throws TimiException; + /** + * 文件对象 + * + * @param path 虚拟路径 + * @return 文件元数据 + */ + ServerFile object(String path); /** * 文件列表 * - * @param path 路径 + * @param path 虚拟路径 * @return 文件列表 - * @throws TimiException 服务异常 */ List list(String path); - /** - * 文件是否存在 - * - * @param path 路径 - * @return true 为存在 - * @throws TimiException 服务异常 - */ - boolean isExist(String path); - /** * 深度搜索 * * @param path 基本路径 * @param keyword 关键字 - * @return 文件列表 - * @throws TimiException 服务异常 + * @return 搜索结果 */ - List search(String path, String keyword); + SearchResult search(String path, String keyword); + + /** + * 文件是否存在 + * + * @param path 虚拟路径 + * @return true 为存在 + */ + boolean exists(String path); /** * 创建文件夹 * - * @param path 路径 - * @param name 名称 + * @param path 父路径 + * @param name 文件夹名称 * @return 文件夹 - * @throws TimiException 服务异常 */ - File mkdir(String path, String name); + ServerFile mkdir(String path, String name); /** - * 重命名,如果原文件不存在则修改失败 + * 重命名或移动文件 * - * @param from 原文件 - * @param to 目标文件 - * @return true 为成功 - * @throws TimiException 服务异常 + * @param from 原虚拟路径 + * @param to 目标虚拟路径 + * @return 目标文件 */ - boolean rename(String from, String to); + ServerFile rename(String from, String to); /** * 获取文件数据流 * - * @param path 绝对路径 + * @param path 虚拟路径 * @return 数据流 - * @throws TimiException 服务异常 */ - InputStream getInputStream(String path); + InputStream open(String path); /** - * 上传文件 + * 获取文件 SHA-256 * - * @param file 文件传输对象 - * @throws TimiException 服务异常 + * @param path 虚拟路径 + * @return 文件哈希信息 */ - void upload(TransferFile file); + FileHash hash(String path); /** - * 数据流写入到文件 + * 物理删除文件或文件夹 * - * @param file 文件 - * @param is 数据流 - * @throws TimiException 服务异常 + * @param paths 虚拟路径列表 */ - void toFile(File file, InputStream is); + void deletePermanently(String... paths); - /** - * 删除文件 - * - * @param list 列表 - * @throws TimiException 服务异常 - */ - void destroy(String... list); + record SearchResult(List items, boolean truncated, int scanned) { + } + + record FileHash(String path, long size, String sha256) { + } } diff --git a/src/main/java/com/imyeyu/api/modules/system/service/FileShareService.java b/src/main/java/com/imyeyu/api/modules/system/service/FileShareService.java new file mode 100644 index 0000000..c1ad029 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/service/FileShareService.java @@ -0,0 +1,184 @@ +package com.imyeyu.api.modules.system.service; + +import com.imyeyu.api.modules.system.audit.AuditOperation; +import com.imyeyu.api.modules.system.audit.OperationAudit; +import com.imyeyu.api.modules.system.entity.FileShare; +import com.imyeyu.api.modules.system.mapper.FileShareMapper; +import com.imyeyu.java.bean.timi.TimiCode; +import com.imyeyu.java.bean.timi.TimiException; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; + +/// 文件分享服务 +@Service +@RequiredArgsConstructor +public class FileShareService { + + private static final SecureRandom RANDOM = new SecureRandom(); + private static final long DAY_MILLIS = 86_400_000L; + + private final FileStorageService storage; + private final FileShareMapper mapper; + + @OperationAudit(AuditOperation.FILE_SHARE_CREATE) + public FileShare create(String path, String password, Long expiresAt, Integer maxDownloads, String ownerUserId) { + if (!storage.shareEnabled()) { + throw new TimiException(TimiCode.ARG_BAD, "文件分享未启用"); + } + Path file = storage.resolveExisting(path); + if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.ARG_BAD, "只能分享文件"); + } + long now = System.currentTimeMillis(); + long expire = expiresAt == null || expiresAt <= 0 + ? now + storage.shareDefaultExpireDays() * DAY_MILLIS + : expiresAt; + if (expire <= now) { + throw new TimiException(TimiCode.ARG_BAD, "过期时间必须晚于当前时间"); + } + FileShare share = new FileShare(); + share.setToken(nextToken()); + share.setPath(path); + share.setName(file.getFileName().toString()); + share.setOwnerUserId(ownerUserId); + share.setPasswordHash(password == null || password.isBlank() ? null : hashPassword(password)); + try { + share.setFileSize(Files.size(file)); + share.setFileModifiedAt(Files.getLastModifiedTime(file, LinkOption.NOFOLLOW_LINKS).toMillis()); + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "读取分享文件信息失败"); + } + share.setFileHash(storage.sha256(file)); + share.setExpiresAt(expire); + share.setMaxDownloads(maxDownloads == null ? 0 : Math.max(0, maxDownloads)); + share.setDownloadCount(0); + share.setLastAccessAt(0); + share.setCreatedAt(now); + share.setDeletedAt(0); + mapper.insert(share); + return share; + } + + public List list() { + return mapper.listAll(); + } + + @OperationAudit(AuditOperation.FILE_SHARE_REVOKE) + public FileShare revoke(String id) { + FileShare share = mapper.selectRecord(id); + if (share == null || share.getDeletedAt() > 0) { + throw new TimiException(TimiCode.RESULT_NULL, "分享不存在"); + } + long now = System.currentTimeMillis(); + mapper.softDelete(id, now); + share.setDeletedAt(now); + return share; + } + + /// 校验令牌、有效期、下载次数和密码,返回可下载的分享。 + public FileShare open(String token, String password) { + return open(token, password, true); + } + + /// 校验令牌、有效期、下载次数和密码,返回可下载的分享。 + /// + /// @param consume 是否消耗一次下载次数,HEAD 请求传 false + public FileShare open(String token, String password, boolean consume) { + FileShare share = mapper.selectActiveByToken(token); + if (share == null) { + throw new TimiException(TimiCode.RESULT_NULL, "分享不存在或已失效"); + } + long now = System.currentTimeMillis(); + if (share.getExpiresAt() <= now) { + throw new TimiException(TimiCode.RESULT_NULL, "分享已过期"); + } + if (share.getMaxDownloads() > 0 && share.getDownloadCount() >= share.getMaxDownloads()) { + throw new TimiException(TimiCode.RESULT_BAD, "分享下载次数已用完"); + } + if (share.getPasswordHash() != null && !verifyPassword(password, share.getPasswordHash())) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "分享密码错误"); + } + Path file = storage.resolveExisting(share.getPath()); + if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.RESULT_NULL, "分享文件不存在"); + } + try { + long size = Files.size(file); + long modifiedAt = Files.getLastModifiedTime(file, LinkOption.NOFOLLOW_LINKS).toMillis(); + if (share.getFileSize() != size || share.getFileModifiedAt() != modifiedAt) { + String hash = storage.sha256(file); + if (share.getFileHash() != null && !share.getFileHash().equals(hash)) { + mapper.softDelete(share.getId(), now); + throw new TimiException(TimiCode.RESULT_NULL, "分享文件已变化"); + } + mapper.updateFileMetadata(share.getId(), hash, size, modifiedAt); + share.setFileHash(hash); + share.setFileSize(size); + share.setFileModifiedAt(modifiedAt); + } + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "读取分享文件信息失败"); + } + if (consume && mapper.incrementDownload(share.getId(), now) == 0) { + throw new TimiException(TimiCode.RESULT_BAD, "分享下载次数已用完"); + } + return share; + } + + private String nextToken() { + for (int i = 0; i < 5; i++) { + String token = UUID.randomUUID().toString().replace("-", ""); + if (mapper.countByToken(token) == 0) { + return token; + } + } + throw new TimiException(TimiCode.ERROR, "生成分享令牌失败"); + } + + private static String hashPassword(String password) { + byte[] salt = new byte[16]; + RANDOM.nextBytes(salt); + byte[] digest = digest(salt, password); + return HexFormat.of().formatHex(salt) + ":" + HexFormat.of().formatHex(digest); + } + + private static boolean verifyPassword(String password, String stored) { + if (password == null) { + return false; + } + String[] parts = stored.split(":", 2); + if (parts.length != 2) { + return false; + } + try { + byte[] salt = HexFormat.of().parseHex(parts[0]); + byte[] expected = HexFormat.of().parseHex(parts[1]); + return MessageDigest.isEqual(expected, digest(salt, password)); + } catch (IllegalArgumentException e) { + return false; + } + } + + private static byte[] digest(byte[] salt, String password) { + try { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(salt); + md.update(password.getBytes(StandardCharsets.UTF_8)); + return md.digest(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/service/FileStorageService.java b/src/main/java/com/imyeyu/api/modules/system/service/FileStorageService.java new file mode 100644 index 0000000..c9f4e00 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/service/FileStorageService.java @@ -0,0 +1,337 @@ +package com.imyeyu.api.modules.system.service; + +import com.imyeyu.api.modules.common.entity.Setting; +import com.imyeyu.api.modules.common.service.SettingService; +import com.imyeyu.api.modules.system.bean.SystemFileSetting; +import com.imyeyu.java.bean.timi.TimiCode; +import com.imyeyu.java.bean.timi.TimiException; +import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.sql.init.dependency.DependsOnDatabaseInitialization; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Locale; +import java.util.Set; + +/// 文件存储路径解析器。 +/// +/// 所有对外接口只接受以 `/` 开头、相对 `BASE_PATH` 的虚拟路径。 +/// 该类是唯一允许把虚拟路径转换为真实路径的入口。 +@Slf4j +@Service +@RequiredArgsConstructor +@DependsOnDatabaseInitialization +public class FileStorageService { + + private static final Set WINDOWS_RESERVED_NAMES = Set.of( + "CON", "PRN", "AUX", "NUL", + "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", + "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" + ); + + private final SettingService settingService; + + private volatile Path basePath; + private volatile Path trashPath; + private volatile Path thumbnailPath; + + @PostConstruct + private void initialize() { + Path base = Path.of(value(SystemFileSetting.BASE_PATH)) + .toAbsolutePath().normalize(); + try { + Files.createDirectories(base); + basePath = base.toRealPath(); + trashPath = resolveDirectory(value(SystemFileSetting.TRASH_PATH), ".trash"); + thumbnailPath = resolveDirectory(value(SystemFileSetting.THUMBNAIL_PATH), ".cache/thumbnails"); + if (trashPath.equals(basePath) || thumbnailPath.equals(basePath) || trashPath.equals(thumbnailPath)) { + throw new IllegalStateException("回收站和缩略图目录必须是 BASE_PATH 下的独立目录"); + } + Files.createDirectories(trashPath); + Files.createDirectories(thumbnailPath); + log.info("file base path: {}", basePath); + } catch (IOException e) { + throw new IllegalStateException("无法初始化文件存储目录: " + base, e); + } + } + + /// 读取系统配置。启动阶段 InitBuiltinSetting 尚未执行时,数据库可能还没有新增配置记录, + /// 此时回退到枚举默认值,避免 FileStorageService 初始化直接失败。 + private Setting setting(SystemFileSetting key) { + Setting setting = settingService.getSystem(key); + if (setting != null) { + return setting; + } + Setting fallback = new Setting(); + fallback.setCode(key.name()); + fallback.setBizType(key.getBizType()); + fallback.setValue(key.getDefaultValue()); + fallback.setValueType(key.getValueType()); + return fallback; + } + + /// 读取配置值,空值时回退到枚举默认值。 + private String value(SystemFileSetting key) { + String value = setting(key).asString(); + return value == null || value.isBlank() ? key.getDefaultValue() : value; + } + + private Path resolveDirectory(String value, String fallback) throws IOException { + String path = value == null || value.isBlank() ? fallback : value; + Path directory = Path.of(path); + if (!directory.isAbsolute()) { + directory = basePath.resolve(path); + } + directory = directory.toAbsolutePath().normalize(); + if (!directory.startsWith(basePath)) { + throw new IllegalStateException("文件目录必须位于 BASE_PATH 内: " + directory); + } + ensureNoSymbolicLinks(basePath, directory); + Files.createDirectories(directory); + Path real = directory.toRealPath(); + if (!real.startsWith(basePath)) { + throw new IllegalStateException("文件目录必须位于 BASE_PATH 内: " + directory); + } + return real; + } + + public Path basePath() { + Path path = basePath; + if (path == null) { + throw new IllegalStateException("文件存储尚未初始化"); + } + return path; + } + + public Path trashPath() { + return trashPath; + } + + public Path thumbnailPath() { + return thumbnailPath; + } + + public long maxUploadSize() { + return setting(SystemFileSetting.UPLOAD_MAX_SIZE).asLong(); + } + + public long chunkSize() { + return setting(SystemFileSetting.UPLOAD_CHUNK_SIZE).asLong(); + } + + public int searchMaxResults() { + return setting(SystemFileSetting.SEARCH_MAX_RESULTS).asInteger(); + } + + public int searchMaxDepth() { + return setting(SystemFileSetting.SEARCH_MAX_DEPTH).asInteger(); + } + + public int searchTimeoutSeconds() { + return setting(SystemFileSetting.SEARCH_TIMEOUT_SECONDS).asInteger(); + } + + public int trashRetentionDays() { + return setting(SystemFileSetting.TRASH_RETENTION_DAYS).asInteger(); + } + + public boolean shareEnabled() { + return setting(SystemFileSetting.SHARE_ENABLED).asBoolean(); + } + + public int shareDefaultExpireDays() { + return setting(SystemFileSetting.SHARE_DEFAULT_EXPIRE_DAYS).asInteger(); + } + + /// 解析虚拟路径。路径必须位于 BASE_PATH 内,且不能经过符号链接。 + public Path resolve(String virtualPath) { + return resolve(virtualPath, false); + } + + /// 解析虚拟路径并要求目标存在。 + public Path resolveExisting(String virtualPath) { + return resolve(virtualPath, true); + } + + private Path resolve(String virtualPath, boolean mustExist) { + Path base = basePath(); + String value = virtualPath == null ? "" : virtualPath; + if (!value.equals(value.strip())) { + throw new TimiException(TimiCode.ARG_BAD, "路径首尾不能包含空白"); + } + if (value.indexOf('\0') >= 0 || value.indexOf('\\') >= 0) { + throw new TimiException(TimiCode.ARG_BAD, "路径不合法"); + } + if (!value.isEmpty() && !value.startsWith("/")) { + throw new TimiException(TimiCode.ARG_BAD, "路径必须以 / 开头"); + } + String relative = value.replaceFirst("^/+", ""); + Path target = base.resolve(relative).normalize(); + if (!target.startsWith(base)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "路径越界"); + } + if (isInternal(target)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "不能访问系统目录"); + } + ensureNoSymbolicLinks(base, target); + if (!mustExist) { + return target; + } + if (!Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.RESULT_NULL, "文件或路径不存在"); + } + try { + Path real = target.toRealPath(); + if (!real.startsWith(base)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "路径越界"); + } + return real; + } catch (IOException e) { + throw new TimiException(TimiCode.RESULT_NULL, "文件或路径不存在"); + } + } + + private void ensureNoSymbolicLinks(Path base, Path target) { + Path current = base; + Path relative = base.relativize(target); + for (Path part : relative) { + current = current.resolve(part); + if (Files.isSymbolicLink(current)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许访问符号链接"); + } + } + } + + /// 将真实路径转换为虚拟路径。 + public String virtualPath(Path path) { + Path absolute = path.toAbsolutePath().normalize(); + if (!absolute.startsWith(basePath())) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "路径越界"); + } + String relative = basePath().relativize(absolute).toString().replace('\\', '/'); + return relative.isEmpty() ? "/" : "/" + relative; + } + + /// 解析并校验单个文件名(不是完整路径)。 + public void validateFileName(String name) { + if (name == null || name.isBlank()) { + throw new TimiException(TimiCode.ARG_MISS, "缺少文件名称"); + } + if (name.length() > 255) { + throw new TimiException(TimiCode.ARG_BAD, "文件名称过长"); + } + if (".".equals(name) || "..".equals(name) || name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) { + throw new TimiException(TimiCode.ARG_BAD, "文件名称不合法"); + } + for (int i = 0; i < name.length(); i++) { + char c = name.charAt(i); + if (c < 0x20 || c == 0x7F || "<>:\"|?*".indexOf(c) >= 0) { + throw new TimiException(TimiCode.ARG_BAD, "文件名称不合法"); + } + } + if (name.endsWith(".") || name.endsWith(" ")) { + throw new TimiException(TimiCode.ARG_BAD, "文件名称不能以点或空格结尾"); + } + String baseName = name; + int dot = name.indexOf('.'); + if (dot >= 0) { + baseName = name.substring(0, dot); + } + if (WINDOWS_RESERVED_NAMES.contains(baseName.toUpperCase(Locale.ROOT))) { + throw new TimiException(TimiCode.ARG_BAD, "文件名称不合法"); + } + } + + /// 在父目录下拼接一个经过校验的文件名。 + public Path child(Path parent, String name) { + validateFileName(name); + Path child = parent.resolve(name).normalize(); + if (!child.startsWith(basePath())) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "路径越界"); + } + if (isInternal(child)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "不能访问系统目录"); + } + return child; + } + + public boolean isRoot(String virtualPath) { + return virtualPath == null || virtualPath.isBlank() || "/".equals(virtualPath); + } + + /// 是否为回收站或缩略图缓存等内部目录。 + public boolean isInternal(Path path) { + Path absolute = path.toAbsolutePath().normalize(); + if (absolute.startsWith(trashPath()) || absolute.startsWith(thumbnailPath())) { + return true; + } + Path cacheRoot = thumbnailPath().getParent(); + return cacheRoot != null && !cacheRoot.equals(basePath()) && absolute.startsWith(cacheRoot); + } + + public void move(Path source, Path target) throws IOException { + Files.createDirectories(target.getParent()); + try { + Files.move(source, target); + } catch (IOException e) { + copyRecursively(source, target); + deleteRecursively(source); + } + } + + private void copyRecursively(Path source, Path target) throws IOException { + if (Files.isSymbolicLink(source)) { + throw new IOException("不允许复制符号链接"); + } + if (Files.isDirectory(source, LinkOption.NOFOLLOW_LINKS)) { + Files.createDirectories(target); + try (var children = Files.newDirectoryStream(source)) { + for (Path child : children) { + copyRecursively(child, target.resolve(child.getFileName())); + } + } + } else { + Files.copy(source, target); + } + } + + public void deleteRecursively(Path path) throws IOException { + if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) { + return; + } + if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) { + try (var children = Files.newDirectoryStream(path)) { + for (Path child : children) { + deleteRecursively(child); + } + } + } + Files.deleteIfExists(path); + } + + /// 流式计算文件 SHA-256。 + public String sha256(Path file) { + try (InputStream input = Files.newInputStream(file)) { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] buffer = new byte[64 * 1024]; + int read; + while ((read = input.read(buffer)) >= 0) { + digest.update(buffer, 0, read); + } + return HexFormat.of().formatHex(digest.digest()); + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "计算文件哈希失败"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/service/FileTrashService.java b/src/main/java/com/imyeyu/api/modules/system/service/FileTrashService.java new file mode 100644 index 0000000..294d5d8 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/service/FileTrashService.java @@ -0,0 +1,167 @@ +package com.imyeyu.api.modules.system.service; + +import com.imyeyu.api.modules.system.audit.AuditOperation; +import com.imyeyu.api.modules.system.audit.OperationAudit; +import com.imyeyu.api.modules.system.bean.ServerFile; +import com.imyeyu.api.modules.system.entity.FileTrash; +import com.imyeyu.api.modules.system.mapper.FileTrashMapper; +import com.imyeyu.java.bean.timi.TimiCode; +import com.imyeyu.java.bean.timi.TimiException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/// 文件回收站。删除操作只移动文件并写入记录,恢复/彻底删除由本服务负责。 +@Slf4j +@Service +@RequiredArgsConstructor +public class FileTrashService { + + private final FileStorageService storage; + private final FileTrashMapper fileTrashMapper; + + /// 将文件移入回收站。 + @OperationAudit(AuditOperation.FILE_DELETE) + public List trash(List paths, String ownerUserId) { + if (paths == null || paths.isEmpty()) { + throw new TimiException(TimiCode.ARG_MISS, "缺少文件列表"); + } + long now = System.currentTimeMillis(); + long expiresAt = now + storage.trashRetentionDays() * 86_400_000L; + List result = new ArrayList<>(paths.size()); + for (String path : paths) { + if (storage.isRoot(path)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "不能删除根目录"); + } + Path source = storage.resolveExisting(path); + if (storage.isInternal(source)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "不能删除系统目录"); + } + String trashName = UUID.randomUUID().toString(); + Path item = storage.trashPath().resolve(trashName); + FileTrash record = new FileTrash(); + record.setOriginalPath(storage.virtualPath(source)); + record.setTrashName(trashName); + record.setName(source.getFileName().toString()); + record.setDirectory(Files.isDirectory(source, LinkOption.NOFOLLOW_LINKS)); + record.setSize(record.isDirectory() ? 0 : fileSize(source)); + record.setOwnerUserId(ownerUserId); + record.setDeletedAt(now); + record.setExpiresAt(expiresAt); + try { + storage.move(source, item); + fileTrashMapper.insert(record); + result.add(record); + } catch (IOException e) { + try { + if (Files.exists(item, LinkOption.NOFOLLOW_LINKS) && !Files.exists(source, LinkOption.NOFOLLOW_LINKS)) { + storage.move(item, source); + } + } catch (IOException ignored) { + log.warn("restore failed after trash error: {}", path, ignored); + } + throw new TimiException(TimiCode.ERROR, "删除失败:" + path); + } + } + return result; + } + + public List list() { + return fileTrashMapper.listActive(System.currentTimeMillis()); + } + + @OperationAudit(AuditOperation.FILE_RESTORE) + public ServerFile restore(String id) { + FileTrash record = requireActive(id); + Path item = storage.trashPath().resolve(record.getTrashName()); + if (!Files.exists(item, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.RESULT_NULL, "回收站文件不存在"); + } + String originalPath = record.getOriginalPath(); + int slash = originalPath.lastIndexOf('/'); + String parentPath = slash <= 0 ? "/" : originalPath.substring(0, slash); + String name = slash < 0 ? originalPath : originalPath.substring(slash + 1); + Path parent = storage.resolve(parentPath); + try { + Files.createDirectories(parent); + Path target = storage.child(parent, name); + if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.RESULT_BAD, "原位置已存在同名文件"); + } + storage.move(item, target); + fileTrashMapper.deleteRecord(id); + return new ServerFile(storage.basePath(), target); + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "恢复文件失败"); + } + } + + @OperationAudit(AuditOperation.FILE_PURGE) + public void purge(String id) { + FileTrash record = requireActive(id); + deleteItem(record); + fileTrashMapper.deleteRecord(id); + } + + @OperationAudit(AuditOperation.FILE_PURGE) + public int empty() { + List list = fileTrashMapper.listActive(System.currentTimeMillis()); + for (FileTrash record : list) { + try { + deleteItem(record); + fileTrashMapper.deleteRecord(record.getId()); + } catch (Exception e) { + log.warn("purge trash failed: {}", record.getId(), e); + } + } + return list.size(); + } + + /// 每天清理过期回收站。 + @Scheduled(cron = "0 30 3 * * ?") + public void cleanupExpired() { + List list = fileTrashMapper.listExpired(System.currentTimeMillis()); + for (FileTrash record : list) { + try { + deleteItem(record); + fileTrashMapper.deleteRecord(record.getId()); + } catch (Exception e) { + log.warn("cleanup trash failed: {}", record.getId(), e); + } + } + } + + private FileTrash requireActive(String id) { + FileTrash record = fileTrashMapper.selectActive(id, System.currentTimeMillis()); + if (record == null) { + throw new TimiException(TimiCode.RESULT_NULL, "回收站记录不存在"); + } + return record; + } + + private void deleteItem(FileTrash record) { + Path item = storage.trashPath().resolve(record.getTrashName()); + try { + storage.deleteRecursively(item); + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "彻底删除失败"); + } + } + + private long fileSize(Path path) { + try { + return Files.size(path); + } catch (IOException e) { + return 0; + } + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/service/FileUploadService.java b/src/main/java/com/imyeyu/api/modules/system/service/FileUploadService.java new file mode 100644 index 0000000..804f201 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/service/FileUploadService.java @@ -0,0 +1,265 @@ +package com.imyeyu.api.modules.system.service; + +import com.imyeyu.api.modules.system.audit.AuditOperation; +import com.imyeyu.api.modules.system.audit.OperationAudit; +import com.imyeyu.api.modules.system.bean.ServerFile; +import com.imyeyu.java.bean.timi.TimiCode; +import com.imyeyu.java.bean.timi.TimiException; +import lombok.RequiredArgsConstructor; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/// 文件上传服务,支持普通上传与分片上传。 +@Service +@RequiredArgsConstructor +public class FileUploadService { + + private static final long SESSION_TTL_MILLIS = 24 * 60 * 60 * 1000L; + + private final FileStorageService storage; + private final Map sessions = new ConcurrentHashMap<>(); + + @OperationAudit(AuditOperation.FILE_UPLOAD) + public ServerFile upload(String path, String name, MultipartFile file, boolean overwrite) { + if (file == null || file.isEmpty()) { + throw new TimiException(TimiCode.ARG_MISS, "缺少上传文件"); + } + if (storage.maxUploadSize() < file.getSize()) { + throw new TimiException(TimiCode.ARG_BAD, "文件超过大小限制"); + } + Path parent = requireDirectory(path); + Path target = storage.child(parent, name); + if (!overwrite && Files.exists(target)) { + throw new TimiException(TimiCode.RESULT_BAD, "目标文件已存在"); + } + Path temp = parent.resolve(".upload-" + UUID.randomUUID() + ".part"); + try { + try (InputStream input = file.getInputStream()) { + Files.copy(input, temp, StandardCopyOption.REPLACE_EXISTING); + } + move(temp, target, overwrite); + setPermissions(target); + return new ServerFile(storage.basePath(), target); + } catch (IOException e) { + deleteQuietly(temp); + throw new TimiException(TimiCode.ERROR, "上传文件失败"); + } + } + + public UploadInit init(String path, String name, long size, String sha256) { + if (size < 0 || storage.maxUploadSize() < size) { + throw new TimiException(TimiCode.ARG_BAD, "文件超过大小限制"); + } + Path parent = requireDirectory(path); + storage.validateFileName(name); + if (Files.exists(parent.resolve(name))) { + throw new TimiException(TimiCode.RESULT_BAD, "目标文件已存在"); + } + long chunkSize = storage.chunkSize(); + int totalChunks = (int) Math.max(1, (size + chunkSize - 1) / chunkSize); + String id = UUID.randomUUID().toString(); + UploadSession session = new UploadSession(id, path, name, size, chunkSize, totalChunks, sha256); + sessions.put(id, session); + try { + Files.createDirectories(session.directory); + } catch (IOException e) { + sessions.remove(id); + throw new TimiException(TimiCode.ERROR, "初始化上传失败"); + } + return new UploadInit(id, chunkSize, totalChunks); + } + + public void chunk(String uploadId, int index, MultipartFile file) { + UploadSession session = requireSession(uploadId); + if (index < 0 || session.totalChunks <= index) { + throw new TimiException(TimiCode.ARG_BAD, "分片序号不合法"); + } + if (file == null || file.isEmpty()) { + throw new TimiException(TimiCode.ARG_MISS, "缺少分片文件"); + } + if (session.chunkSize < file.getSize()) { + throw new TimiException(TimiCode.ARG_BAD, "分片大小超出限制"); + } + Path target = session.directory.resolve(index + ".part"); + try (InputStream input = file.getInputStream()) { + Files.copy(input, target, StandardCopyOption.REPLACE_EXISTING); + session.received.add(index); + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "写入分片失败"); + } + } + + @OperationAudit(AuditOperation.FILE_UPLOAD) + public ServerFile complete(String uploadId, String sha256) { + UploadSession session = requireSession(uploadId); + if (session.received.size() != session.totalChunks) { + throw new TimiException(TimiCode.RESULT_BAD, "分片不完整"); + } + Path parent = requireDirectory(session.path); + Path target = storage.child(parent, session.name); + if (Files.exists(target)) { + throw new TimiException(TimiCode.RESULT_BAD, "目标文件已存在"); + } + Path temp = parent.resolve(".upload-" + uploadId + ".part"); + try { + try (var output = Files.newOutputStream(temp, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { + for (int i = 0; i < session.totalChunks; i++) { + Path part = session.directory.resolve(i + ".part"); + if (!Files.isRegularFile(part)) { + throw new TimiException(TimiCode.RESULT_BAD, "分片不完整"); + } + Files.copy(part, output); + } + } + if (Files.size(temp) != session.size) { + throw new TimiException(TimiCode.ARG_BAD, "文件大小校验失败"); + } + String expected = sha256 != null && !sha256.isBlank() ? sha256 : session.sha256; + if (expected != null && !expected.isBlank() && !expected.equalsIgnoreCase(sha256(temp))) { + throw new TimiException(TimiCode.ARG_BAD, "文件校验失败"); + } + move(temp, target, false); + setPermissions(target); + sessions.remove(uploadId); + try { + storage.deleteRecursively(session.directory); + } catch (RuntimeException ignored) { + // 临时分片清理失败不影响上传结果。 + } + return new ServerFile(storage.basePath(), target); + } catch (IOException e) { + deleteQuietly(temp); + throw new TimiException(TimiCode.ERROR, "合并分片失败"); + } catch (RuntimeException e) { + deleteQuietly(temp); + throw e; + } + } + + /// 清理超过 24 小时未活动的分片上传会话。 + @Scheduled(cron = "0 0 * * * ?") + public void cleanupExpiredSessions() { + long now = System.currentTimeMillis(); + sessions.forEach((id, session) -> { + if (now - session.lastAccessAt < SESSION_TTL_MILLIS) { + return; + } + if (!sessions.remove(id, session)) { + return; + } + try { + storage.deleteRecursively(session.directory); + } catch (IOException | RuntimeException ignored) { + // 临时目录清理失败不影响后续会话。 + } + }); + } + + private Path requireDirectory(String path) { + Path directory = storage.resolveExisting(path); + if (!Files.isDirectory(directory)) { + throw new TimiException(TimiCode.ARG_BAD, "目标路径不是文件夹"); + } + return directory; + } + + private UploadSession requireSession(String id) { + UploadSession session = sessions.get(id); + if (session == null) { + throw new TimiException(TimiCode.RESULT_NULL, "上传任务不存在"); + } + session.lastAccessAt = System.currentTimeMillis(); + return session; + } + + private void move(Path source, Path target, boolean overwrite) throws IOException { + if (overwrite) { + try { + Files.move(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (java.nio.file.AtomicMoveNotSupportedException e) { + Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); + } + return; + } + try { + Files.move(source, target, StandardCopyOption.ATOMIC_MOVE); + } catch (java.nio.file.AtomicMoveNotSupportedException e) { + Files.move(source, target); + } + } + + private void setPermissions(Path path) { + try { + Files.setPosixFilePermissions(path, java.nio.file.attribute.PosixFilePermissions.fromString("rw-r--r--")); + } catch (UnsupportedOperationException | IOException ignored) { + // Windows 文件系统不支持 POSIX 权限,保留默认权限。 + } + } + + private String sha256(Path path) throws IOException { + try (InputStream input = Files.newInputStream(path)) { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] buffer = new byte[64 * 1024]; + int length; + while ((length = input.read(buffer)) >= 0) { + digest.update(buffer, 0, length); + } + StringBuilder result = new StringBuilder(); + for (byte b : digest.digest()) { + result.append(Character.forDigit((b >> 4) & 0xF, 16)); + result.append(Character.forDigit(b & 0xF, 16)); + } + return result.toString(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + private void deleteQuietly(Path path) { + try { + Files.deleteIfExists(path); + } catch (IOException ignored) { + } + } + + public record UploadInit(String uploadId, long chunkSize, int totalChunks) { + } + + private static final class UploadSession { + private final String id; + private final String path; + private final String name; + private final long size; + private final long chunkSize; + private final int totalChunks; + private final String sha256; + private final Path directory; + private final Set received = ConcurrentHashMap.newKeySet(); + private volatile long lastAccessAt = System.currentTimeMillis(); + + private UploadSession(String id, String path, String name, long size, long chunkSize, int totalChunks, String sha256) { + this.id = id; + this.path = path; + this.name = name; + this.size = size; + this.chunkSize = chunkSize; + this.totalChunks = totalChunks; + this.sha256 = sha256; + this.directory = Path.of(System.getProperty("java.io.tmpdir"), "timi-file-upload", id); + } + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/service/ThumbnailService.java b/src/main/java/com/imyeyu/api/modules/system/service/ThumbnailService.java new file mode 100644 index 0000000..c03e38b --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/service/ThumbnailService.java @@ -0,0 +1,100 @@ +package com.imyeyu.api.modules.system.service; + +import com.imyeyu.java.bean.timi.TimiCode; +import com.imyeyu.java.bean.timi.TimiException; +import lombok.RequiredArgsConstructor; +import net.coobird.thumbnailator.Thumbnails; +import org.jcodec.api.FrameGrab; +import org.jcodec.common.model.Picture; +import org.jcodec.scale.AWTUtil; +import org.springframework.stereotype.Service; + +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.stream.ImageInputStream; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Iterator; + +/// 缩略图缓存服务。 +@Service +@RequiredArgsConstructor +public class ThumbnailService { + + private static final int SIZE = 256; + private static final long MAX_PIXELS = 50_000_000L; + + private final FileStorageService storage; + + public Path thumbnail(Path source, String mimeType) { + try { + long modifiedAt = Files.getLastModifiedTime(source).toMillis(); + long size = Files.size(source); + String key = sha256(source.toAbsolutePath() + "|" + modifiedAt + "|" + size + "|" + SIZE); + Path target = storage.thumbnailPath().resolve(key + ".png"); + if (Files.isRegularFile(target)) { + return target; + } + Files.createDirectories(target.getParent()); + if (mimeType.startsWith("video/")) { + Picture picture; + try { + picture = FrameGrab.getFrameAtSec(source.toFile(), 0); + } catch (Exception e) { + picture = FrameGrab.getFrameAtSec(source.toFile(), 1); + } + BufferedImage image = AWTUtil.toBufferedImage(picture); + ImageIO.write(image, "png", target.toFile()); + } else { + validatePixelCount(source); + Thumbnails.of(source.toFile()).size(SIZE, SIZE).outputFormat("png").toFile(target.toFile()); + } + return target; + } catch (TimiException e) { + throw e; + } catch (Exception e) { + throw new TimiException(TimiCode.ERROR, "生成缩略图失败"); + } + } + + /// 在完整解码前检查图片像素数,避免超大图片耗尽内存。 + private void validatePixelCount(Path source) throws IOException { + try (ImageInputStream input = ImageIO.createImageInputStream(source.toFile())) { + if (input == null) { + throw new IOException("无法读取图片"); + } + Iterator readers = ImageIO.getImageReaders(input); + if (!readers.hasNext()) { + throw new IOException("不支持的图片格式"); + } + ImageReader reader = readers.next(); + try { + reader.setInput(input, true, true); + long pixels = (long) reader.getWidth(0) * reader.getHeight(0); + if (MAX_PIXELS < pixels) { + throw new TimiException(TimiCode.ARG_BAD, "图片像素过大"); + } + } finally { + reader.dispose(); + } + } + } + + private String sha256(String value) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + StringBuilder result = new StringBuilder(digest.length * 2); + for (byte b : digest) { + result.append(Character.forDigit((b >> 4) & 0xF, 16)); + result.append(Character.forDigit(b & 0xF, 16)); + } + return result.toString(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/service/implement/AbstractAsyncTask.java b/src/main/java/com/imyeyu/api/modules/system/service/implement/AbstractAsyncTask.java index a9632d0..deb53db 100644 --- a/src/main/java/com/imyeyu/api/modules/system/service/implement/AbstractAsyncTask.java +++ b/src/main/java/com/imyeyu/api/modules/system/service/implement/AbstractAsyncTask.java @@ -40,6 +40,9 @@ public abstract class AbstractAsyncTask extends AsyncTask { /** 日志缓冲 */ final StringBuilder logBuffer = new StringBuilder(); + /** 暂停/中断检查节流计数 */ + private int pauseCheckCount; + /// 任务持久化回调 private Consumer persistenceCallback = task -> { }; @@ -203,11 +206,19 @@ public abstract class AbstractAsyncTask extends AsyncTask { /** 在耗时任务中执行此方法可受 {@link #isPause()} 和 {@link #isInterrupt()} 控制暂停或中断 */ protected void pauseInterruptHandle() throws InterruptedException { - Thread.sleep(700); + // 每处理 64 项检查一次,避免每个文件固定休眠 700ms;暂停后恢复时立即重新检查。 + if (++pauseCheckCount % 64 != 0 && !isPause() && !isInterrupt()) { + return; + } if (isPause()) { // 暂停 synchronized (pauseLocker) { - pauseLocker.wait(); + while (isPause() && !isInterrupt()) { + pauseLocker.wait(); + } + } + if (isInterrupt()) { + throw TimiCode.ERROR_SERVICE_OFF.toException(); } setStatus(AsyncTask.Status.RUNNING); } diff --git a/src/main/java/com/imyeyu/api/modules/system/service/implement/AsyncTaskServiceImplement.java b/src/main/java/com/imyeyu/api/modules/system/service/implement/AsyncTaskServiceImplement.java index ac65d37..7a52959 100644 --- a/src/main/java/com/imyeyu/api/modules/system/service/implement/AsyncTaskServiceImplement.java +++ b/src/main/java/com/imyeyu/api/modules/system/service/implement/AsyncTaskServiceImplement.java @@ -144,7 +144,7 @@ public class AsyncTaskServiceImplement implements AsyncTaskService { task.setMessage(task.getLogContent()); return task; } - throw new TimiException(TimiCode.RESULT_NULL, "TODO not found task"); + throw new TimiException(TimiCode.RESULT_NULL, "任务不存在"); } @Override diff --git a/src/main/java/com/imyeyu/api/modules/system/service/implement/FileServiceImplement.java b/src/main/java/com/imyeyu/api/modules/system/service/implement/FileServiceImplement.java index 4eb16ac..70e96d8 100644 --- a/src/main/java/com/imyeyu/api/modules/system/service/implement/FileServiceImplement.java +++ b/src/main/java/com/imyeyu/api/modules/system/service/implement/FileServiceImplement.java @@ -1,266 +1,233 @@ package com.imyeyu.api.modules.system.service.implement; -import com.imyeyu.api.modules.common.service.SettingService; +import com.imyeyu.api.modules.system.audit.AuditOperation; +import com.imyeyu.api.modules.system.audit.OperationAudit; import com.imyeyu.api.modules.system.bean.ServerFile; -import com.imyeyu.api.modules.system.bean.SystemFileSetting; -import com.imyeyu.api.modules.system.bean.TransferFile; -import com.imyeyu.api.modules.system.service.AsyncTaskService; import com.imyeyu.api.modules.system.service.FileService; -import com.imyeyu.api.modules.system.util.SystemAPIInterceptor; -import com.imyeyu.io.IO; -import com.imyeyu.java.TimiJava; +import com.imyeyu.api.modules.system.service.FileStorageService; import com.imyeyu.java.bean.timi.TimiCode; import com.imyeyu.java.bean.timi.TimiException; -import com.imyeyu.utils.Decoder; -import com.imyeyu.utils.OS; -import jakarta.annotation.PostConstruct; -import lombok.Data; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.stereotype.Service; -import javax.naming.NoPermissionException; -import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.util.ArrayDeque; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; -import java.util.Deque; +import java.util.Comparator; import java.util.List; /** - * 文件服务,不可直接使用入参路径 + * 文件元数据服务实现 * * @author 夜雨 * @version 2022-01-07 16:05 */ -@Slf4j @Service @RequiredArgsConstructor -public class FileServiceImplement implements TimiJava, FileService { +public class FileServiceImplement implements FileService { - /** - * - * - * @author 夜雨 - * @since 2025-03-31 14:50 - */ - @Data - public static class FilterOption { + private static final Comparator FILE_COMPARATOR = (left, right) -> { + boolean leftDirectory = Files.isDirectory(left, LinkOption.NOFOLLOW_LINKS); + boolean rightDirectory = Files.isDirectory(right, LinkOption.NOFOLLOW_LINKS); + if (leftDirectory != rightDirectory) { + return leftDirectory ? -1 : 1; + } + return left.getFileName().toString().compareToIgnoreCase(right.getFileName().toString()); + }; - List allow; - - List exclude; - } - - private final SettingService settingService; - private final AsyncTaskService asyncTaskService; - - private final SystemAPIInterceptor interceptor; - private final ScheduledTaskRegistrar scheduledTaskRegistrar; - - private FilterOption option; - - @PostConstruct - private void fileSyncPostConstruct() { -// FileSyncConfig config = settingService.fromYaml(SettingKey.SYSTEM_FILE_SYNC, FileSyncConfig.class); -// if (config.isEnable()) { -// scheduledTaskRegistrar.scheduleCronTask(new CronTask(() -> { -// Map tasks = config.getTasks(); -// configTask: for (Map.Entry item : tasks.entrySet()) { -// if (item.getValue().isEnable()) { -// List runningTaskList = asyncTaskService.listAll(); -// for (int i = 0; i < runningTaskList.size(); i++) { -// AbstractAsyncTask runningTask = runningTaskList.get(i); -// if (runningTask.getType() == AsyncTask.Type.FILE_SYNC && runningTask.getName().equals(item.getKey())) { -// continue configTask; -// } -// } -// FileSyncTask task = new FileSyncTask(item.getKey(), item.getValue()); -// asyncTaskService.addAsyncTask(task); -// } -// } -// }, config.getCron())); -// } - } - - @PostConstruct - private void fileFilterPostConstruct() { -// option = settingService.fromYaml(SettingKey.SYSTEM_FILE_FILTER, FilterOption.class); - } + private final FileStorageService storage; @Override - public boolean canAccess(String path) { - if (interceptor.isHighAuthorityKey()) { - return true; - } - for (String allow : option.allow) { - if (!path.startsWith(allow)) { - return false; - } - } - for (String exclude : option.exclude) { - if (path.startsWith(exclude)) { - return false; - } - } - return true; - } - - @Override - public void checkAccessPermission(String path) { - if (canAccess(path)) { - return; - } - throw new TimiException(TimiCode.PERMISSION_ERROR, "TODO invalid permission"); - } - - @Override - public List doFilter(List list) { - list.removeIf(item -> !canAccess(item.getAbsolutePath())); - return list; + public ServerFile object(String path) { + Path file = storage.resolveExisting(path); + return new ServerFile(storage.basePath(), file); } @Override public List list(String path) { - File file = new File(getPath(path)); - if (file.exists()) { - List result = new ArrayList<>(); - - File[] files = file.listFiles(); - if (files != null) { - List list = new ArrayList<>(List.of(files)); - list.sort(OS.FileSystem.COMPARATOR_FILE_NAME); - for (int i = 0; i < list.size(); i++) { - result.add(new ServerFile(list.get(i))); - } - } - return result; - } else { - throw new TimiException(TimiCode.RESULT_NULL, "文件或路径不存在"); + Path directory = storage.resolveExisting(path); + if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.ARG_BAD, "路径不是文件夹"); } - } - - @Override - public boolean isExist(String path) { - return new File(getPath(path)).exists(); - } - - @Override - public List search(String path, String keyword) { - File file = new File(getPath(path)); - if (file.exists()) { - List result = new ArrayList<>(); - // 右进左出文件夹队列,非递归深度栈遍历 - Deque directoryQueue = new ArrayDeque<>(); - directoryQueue.addLast(file); - - deque: while (!directoryQueue.isEmpty()) { - File directory = directoryQueue.pollFirst(); - File[] files = directory.listFiles(); - if (files != null) { - for (int i = 0; i < files.length; i++) { - if (files[i].getName().contains(keyword)) { - result.add(new ServerFile(files[i])); - if (100 < result.size()) { - break deque; - } - } - if (files[i].isDirectory()) { - directoryQueue.addLast(files[i]); - } - } - } - } - return result; - } else { - throw new TimiException(TimiCode.RESULT_NULL, "文件或路径不存在"); - } - } - - @Override - public File mkdir(String path, String name) { - String uri = IO.fitPath(getPath(path)) + name; - try { - return IO.dir(uri); - } catch (NoPermissionException e) { - throw new TimiException(TimiCode.PERMISSION_ERROR, "权限错误"); - } - } - - @Override - public boolean rename(String from, String to) { - File source = new File(getPath(from)); - checkAccessPermission(source.getAbsolutePath()); - if (source.exists()) { - return source.renameTo(new File(getPath(to))); - } - return false; - } - - @Override - public InputStream getInputStream(String path) { - try { - return IO.getInputStream(getPath(path)); - } catch (FileNotFoundException e) { - throw new TimiException(TimiCode.RESULT_NULL, "找不到文件"); - } - } - - @Override - public void upload(TransferFile file) { - String path = getPath(Decoder.url(file.getPath())); - if (file.getName() == null) { - throw new TimiException(TimiCode.ARG_MISS, "缺少参数:name"); - } - String fileName = Decoder.url(file.getName()); - if (!OS.isValidFileName(path)) { - throw new TimiException(TimiCode.ARG_BAD, "路径名称不合法:" + path); - } - if (!OS.isValidFileName(fileName)) { - throw new TimiException(TimiCode.ARG_BAD, "文件名称不合法:" + fileName); - } - if (file.getLength() == file.getFile().getSize()) { - try { - toFile(new File(path + fileName), file.getFile().getInputStream()); - } catch (IOException e) { - log.error("get request input stream error", e); - throw new TimiException(TimiCode.ARG_BAD, "获取文件输入流失败"); - } - } else { - log.error("request submit request size: {}, receive request size: {}", file.getLength(), file.getFile().getSize()); - throw new TimiException(TimiCode.ERROR, "不完整上传文件,已忽略"); - } - } - - @Override - public void toFile(File file, InputStream is) { - try { - IO.toFile(file, is); + try (var children = Files.list(directory)) { + return children.filter(child -> !storage.isInternal(child)) + .filter(child -> !Files.isSymbolicLink(child)) + .sorted(FILE_COMPARATOR) + .map(child -> new ServerFile(storage.basePath(), child)) + .toList(); } catch (IOException e) { - throw new TimiException(TimiCode.ERROR); - } catch (NoPermissionException e) { - throw new TimiException(TimiCode.PERMISSION_ERROR); + throw new TimiException(TimiCode.ERROR, "读取文件夹失败"); } } @Override - public void destroy(String... list) { - for (int i = 0; i < list.length; i++) { - File file = new File(list[i]); - if (canAccess(file) && file.exists() && file.canWrite()) { - IO.destroy(file); + public SearchResult search(String path, String keyword) { + if (keyword == null || keyword.isBlank()) { + throw new TimiException(TimiCode.ARG_MISS, "缺少参数:keyword"); + } + Path start = storage.resolveExisting(path); + int maxResults = storage.searchMaxResults(); + int maxDepth = storage.searchMaxDepth(); + long deadline = System.nanoTime() + storage.searchTimeoutSeconds() * 1_000_000_000L; + List result = new ArrayList<>(); + int[] scanned = {0}; + boolean[] truncated = {false}; + try { + Files.walkFileTree(start, new SimpleFileVisitor<>() { + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { + if (Files.isSymbolicLink(dir)) { + return FileVisitResult.SKIP_SUBTREE; + } + if (storage.isInternal(dir)) { + return FileVisitResult.SKIP_SUBTREE; + } + if (start.relativize(dir).getNameCount() > maxDepth) { + truncated[0] = true; + return FileVisitResult.SKIP_SUBTREE; + } + return check(); + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { + scanned[0]++; + if (Files.isSymbolicLink(file)) { + return check(); + } + if (file.getFileName().toString().toLowerCase().contains(keyword.toLowerCase())) { + result.add(new ServerFile(storage.basePath(), file)); + } + return check(); + } + + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) { + return check(); + } + + private FileVisitResult check() { + if (maxResults <= result.size()) { + truncated[0] = true; + return FileVisitResult.TERMINATE; + } + if (deadline < System.nanoTime()) { + truncated[0] = true; + return FileVisitResult.TERMINATE; + } + return FileVisitResult.CONTINUE; + } + }); + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "搜索文件失败"); + } + return new SearchResult(List.copyOf(result), truncated[0], scanned[0]); + } + + @Override + public boolean exists(String path) { + try { + storage.resolveExisting(path); + return true; + } catch (TimiException e) { + if (e.getCode() == TimiCode.RESULT_NULL) { + return false; } + throw e; } } - private String getPath(String path) { - String basePath = settingService.getSystem(SystemFileSetting.BASE_PATH).asString(); - if (TimiJava.isEmpty(path)) { - return basePath; + @Override + @OperationAudit(AuditOperation.FILE_MKDIR) + public ServerFile mkdir(String path, String name) { + Path parent = storage.resolveExisting(path); + if (!Files.isDirectory(parent, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.ARG_BAD, "父路径不是文件夹"); + } + Path target = storage.child(parent, name); + try { + Files.createDirectory(target); + return new ServerFile(storage.basePath(), target); + } catch (java.nio.file.FileAlreadyExistsException e) { + throw new TimiException(TimiCode.RESULT_BAD, "文件夹已存在"); + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "创建文件夹失败"); + } + } + + @Override + @OperationAudit(AuditOperation.FILE_RENAME) + public ServerFile rename(String from, String to) { + Path source = storage.resolveExisting(from); + if (storage.isRoot(from)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "不能重命名根目录"); + } + Path target = storage.resolve(to); + if (target.startsWith(source)) { + throw new TimiException(TimiCode.ARG_BAD, "不能移动到自身内部"); + } + if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.RESULT_BAD, "目标文件已存在"); + } + if (!Files.isDirectory(target.getParent(), LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.ARG_BAD, "目标父路径不存在"); + } + try { + Files.move(source, target); + return new ServerFile(storage.basePath(), target); + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "重命名失败"); + } + } + + @Override + public InputStream open(String path) { + Path file = storage.resolveExisting(path); + if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.ARG_BAD, "路径不是文件"); + } + try { + return Files.newInputStream(file); + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "读取文件失败"); + } + } + + @Override + public FileHash hash(String path) { + Path file = storage.resolveExisting(path); + if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.ARG_BAD, "路径不是文件"); + } + try { + return new FileHash(storage.virtualPath(file), Files.size(file), storage.sha256(file)); + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "读取文件失败"); + } + } + + @Override + @OperationAudit(AuditOperation.FILE_PURGE) + public void deletePermanently(String... paths) { + if (paths == null || paths.length == 0) { + throw new TimiException(TimiCode.ARG_MISS, "缺少文件列表"); + } + for (String path : paths) { + if (storage.isRoot(path)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "不能删除根目录"); + } + Path file = storage.resolveExisting(path); + try { + storage.deleteRecursively(file); + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "删除失败:" + path); + } } - return basePath + path; } } diff --git a/src/main/java/com/imyeyu/api/modules/system/task/async/FileCalcSizeAsyncTask.java b/src/main/java/com/imyeyu/api/modules/system/task/async/FileCalcSizeAsyncTask.java index 69c82d7..8a7682d 100644 --- a/src/main/java/com/imyeyu/api/modules/system/task/async/FileCalcSizeAsyncTask.java +++ b/src/main/java/com/imyeyu/api/modules/system/task/async/FileCalcSizeAsyncTask.java @@ -1,54 +1,118 @@ package com.imyeyu.api.modules.system.task.async; import ch.qos.logback.classic.Level; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.imyeyu.api.bean.CorePermissionCode; import com.imyeyu.api.modules.system.entity.AsyncTask; +import com.imyeyu.api.modules.system.service.FileStorageService; import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; +import com.imyeyu.api.modules.system.vo.FileSizeResult; +import com.imyeyu.api.modules.user.service.PermissionChecker; +import com.imyeyu.java.bean.timi.TimiCode; +import com.imyeyu.java.bean.timi.TimiException; -import java.io.File; -import java.util.ArrayDeque; -import java.util.Deque; +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.concurrent.atomic.AtomicLong; /** - * 计算文件夹大小(无法计算进度) + * 统计文件夹大小。 + * + *

使用虚拟路径遍历,不跟随符号链接,并跳过回收站、缩略图等内部目录。 + * 由于目录总大小在遍历完成前无法预知,进度保持为不确定状态,结果通过任务 result 返回。

* * @author 夜雨 - * @version 2022-08-21 21:36 + * @version 2026-11-24 */ public class FileCalcSizeAsyncTask extends AbstractAsyncTask { - private final File file; + private static final ObjectMapper MAPPER = new ObjectMapper(); - public FileCalcSizeAsyncTask(File file) { - this.file = file; - type = AsyncTask.Type.FILE_CALC_SIZE; + private final String path; + private final FileStorageService storage; + private final PermissionChecker permissionChecker; + private final String ownerUserId; + + public FileCalcSizeAsyncTask(String path, FileStorageService storage, PermissionChecker permissionChecker, String ownerUserId) { + this.path = path; + this.storage = storage; + this.permissionChecker = permissionChecker; + this.ownerUserId = ownerUserId; + this.type = AsyncTask.Type.FILE_CALC_SIZE; + this.name = "计算文件夹大小 " + path; + } + + private void pause() { + try { + pauseInterruptHandle(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new TimiException(TimiCode.ERROR_SERVICE_OFF, "任务已中断"); + } } @Override - protected void run() throws InterruptedException { - long total = 0; + protected void run() throws Exception { + FileTaskSupport.require(permissionChecker, ownerUserId, CorePermissionCode.FILE_READ); - if (file != null && file.exists() && file.isDirectory()) { - // 左出右进,文件夹队列 - Deque deque = new ArrayDeque<>(); - deque.addLast(file); - - while (!deque.isEmpty()) { - File poll = deque.pollFirst(); - pauseInterruptHandle(); - - if (poll.isDirectory()) { - File[] files = poll.listFiles(); - if (files != null) { - for (int i = 0; i < files.length; i++) { - deque.addLast(files[i]); - } - } - } else { - total += poll.length(); - log(Level.INFO, String.valueOf(total)); - } - } + Path root = storage.resolveExisting(path); + if (!Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.ARG_BAD, "只能统计文件夹大小"); } - progress = 1; + + long startAt = System.currentTimeMillis(); + AtomicLong bytes = new AtomicLong(); + AtomicLong files = new AtomicLong(); + AtomicLong directories = new AtomicLong(); + AtomicLong failed = new AtomicLong(); + + Files.walkFileTree(root, new SimpleFileVisitor<>() { + + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + pause(); + if (!dir.equals(root) && storage.isInternal(dir)) { + return FileVisitResult.SKIP_SUBTREE; + } + directories.incrementAndGet(); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + pause(); + if (Files.isSymbolicLink(file)) { + return FileVisitResult.CONTINUE; + } + if (attrs.isRegularFile()) { + bytes.addAndGet(attrs.size()); + files.incrementAndGet(); + } + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFileFailed(Path file, IOException e) { + failed.incrementAndGet(); + log(Level.WARN, "跳过无法访问的文件:" + file + "," + e.getMessage()); + return FileVisitResult.CONTINUE; + } + }); + + FileSizeResult result = new FileSizeResult( + path, + bytes.get(), + files.get(), + directories.get(), + failed.get(), + System.currentTimeMillis() - startAt + ); + updateResult(MAPPER.writeValueAsString(result)); + log(Level.INFO, "文件夹大小统计完成:" + result); } } diff --git a/src/main/java/com/imyeyu/api/modules/system/task/async/FileCopyAsyncTask.java b/src/main/java/com/imyeyu/api/modules/system/task/async/FileCopyAsyncTask.java index 72b9596..e2dccd4 100644 --- a/src/main/java/com/imyeyu/api/modules/system/task/async/FileCopyAsyncTask.java +++ b/src/main/java/com/imyeyu/api/modules/system/task/async/FileCopyAsyncTask.java @@ -1,16 +1,18 @@ package com.imyeyu.api.modules.system.task.async; import ch.qos.logback.classic.Level; -import com.imyeyu.io.IO; +import com.imyeyu.api.bean.CorePermissionCode; import com.imyeyu.api.modules.system.entity.AsyncTask; +import com.imyeyu.api.modules.system.service.FileStorageService; import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; +import com.imyeyu.api.modules.user.service.PermissionChecker; +import com.imyeyu.java.bean.timi.TimiCode; +import com.imyeyu.java.bean.timi.TimiException; -import java.io.File; import java.nio.file.Files; -import java.nio.file.StandardCopyOption; -import java.util.HashMap; +import java.nio.file.LinkOption; +import java.nio.file.Path; import java.util.List; -import java.util.Map; /** * 文件复制 @@ -22,51 +24,48 @@ public class FileCopyAsyncTask extends AbstractAsyncTask { private final String to; private final List fromList; + private final FileStorageService storage; + private final PermissionChecker permissionChecker; - public FileCopyAsyncTask(List fromList, String to) { + public FileCopyAsyncTask(List fromList, String to, FileStorageService storage, PermissionChecker permissionChecker, String ownerUserId) { this.fromList = fromList; this.to = to; + this.storage = storage; + this.permissionChecker = permissionChecker; + this.ownerUserId = ownerUserId; type = AsyncTask.Type.FILE_COPY; } @Override protected void run() throws Exception { - // 准备文件 Map<文件, 深度路径>,深度路径含文件名 - Map fromList = new HashMap<>(); - File file; - for (int i = 0; i < this.fromList.size(); i++) { - pauseInterruptHandle(); - - file = new File(this.fromList.get(i)); - if (file.exists()) { - if (file.isFile()) { - fromList.put(file, file.getName()); - } else { - String basePath = file.getParentFile().getAbsolutePath(); - List files = IO.listFile(file); - for (int j = 0; j < files.size(); j++) { - fromList.put(files.get(j), files.get(j).getAbsolutePath().substring(basePath.length())); - } - } - } + FileTaskSupport.require(permissionChecker, ownerUserId, CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE); + Path destination = FileTaskSupport.targetDirectory(storage, to); + List sources = FileTaskSupport.sources(storage, fromList); + for (Path source : sources) { + FileTaskSupport.ensureNotNested(source, destination); } - // 复制文件 - int total = fromList.size(); - int i = 0; - for (Map.Entry item : fromList.entrySet()) { + List entries = FileTaskSupport.collect(sources, null); + int total = entries.size(); + int index = 0; + for (FileTaskSupport.Entry entry : entries) { pauseInterruptHandle(); - log(Level.INFO, item.getKey().getName()); - // 执行复制 - { - File toFile = new File(IO.fitPath(to) + item.getValue()); - IO.dir(toFile.getParent()); - Files.copy(item.getKey().toPath(), toFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + Path target = destination.resolve(entry.name()).normalize(); + if (!target.startsWith(destination)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "目标路径越界"); } - - // 更新进度 - progress = 1D * ++i / total; + log(Level.INFO, entry.name()); + if (entry.directory()) { + Files.createDirectories(target); + } else { + Files.createDirectories(target.getParent()); + if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.RESULT_BAD, "目标已存在:" + entry.name()); + } + Files.copy(entry.path(), target); + } + progress = 1D * ++index / total; } progress = 1; } diff --git a/src/main/java/com/imyeyu/api/modules/system/task/async/FileMoveAsyncTask.java b/src/main/java/com/imyeyu/api/modules/system/task/async/FileMoveAsyncTask.java index 51d7004..4d1b686 100644 --- a/src/main/java/com/imyeyu/api/modules/system/task/async/FileMoveAsyncTask.java +++ b/src/main/java/com/imyeyu/api/modules/system/task/async/FileMoveAsyncTask.java @@ -1,16 +1,18 @@ package com.imyeyu.api.modules.system.task.async; import ch.qos.logback.classic.Level; -import com.imyeyu.io.IO; +import com.imyeyu.api.bean.CorePermissionCode; +import com.imyeyu.api.modules.system.entity.AsyncTask; +import com.imyeyu.api.modules.system.service.FileStorageService; +import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; +import com.imyeyu.api.modules.user.service.PermissionChecker; import com.imyeyu.java.bean.timi.TimiCode; import com.imyeyu.java.bean.timi.TimiException; -import com.imyeyu.api.modules.system.entity.AsyncTask; -import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; -import java.io.File; -import java.util.HashMap; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; import java.util.List; -import java.util.Map; /** * 文件批量移动异步任务 @@ -22,64 +24,42 @@ public class FileMoveAsyncTask extends AbstractAsyncTask { private final String to; private final List fromList; + private final FileStorageService storage; + private final PermissionChecker permissionChecker; - public FileMoveAsyncTask(List fromList, String to) { + public FileMoveAsyncTask(List fromList, String to, FileStorageService storage, PermissionChecker permissionChecker, String ownerUserId) { this.fromList = fromList; this.to = to; + this.storage = storage; + this.permissionChecker = permissionChecker; + this.ownerUserId = ownerUserId; type = AsyncTask.Type.FILE_MOVE; } @Override protected void run() throws Exception { - // 准备文件 Map<文件, 深度路径>,深度路径含文件名 - Map fromList = new HashMap<>(); - File file; - for (int i = 0; i < this.fromList.size(); i++) { + FileTaskSupport.require(permissionChecker, ownerUserId, + CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE, CorePermissionCode.FILE_DELETE); + Path destination = FileTaskSupport.targetDirectory(storage, to); + List sources = FileTaskSupport.sources(storage, fromList); + int total = sources.size(); + int index = 0; + for (Path source : sources) { pauseInterruptHandle(); - file = new File(this.fromList.get(i)); - if (file.exists()) { - if (file.isFile()) { - fromList.put(file, file.getName()); - } else { - String basePath = file.getParentFile().getAbsolutePath(); - List files = IO.listFile(file); - for (int j = 0; j < files.size(); j++) { - fromList.put(files.get(j), files.get(j).getAbsolutePath().substring(basePath.length())); - } - } + FileTaskSupport.ensureNotNested(source, destination); + Path target = destination.resolve(source.getFileName()).normalize(); + if (target.equals(source)) { + throw new TimiException(TimiCode.ARG_BAD, "源路径与目标路径相同"); } - } - // 移动文件 - int total = fromList.size(); - int i = 0; - for (Map.Entry item : fromList.entrySet()) { - pauseInterruptHandle(); - - log(Level.INFO, item.getKey().getName()); - // 执行移动 - { - File toFile = new File(IO.fitPath(to) + item.getValue()); - IO.dir(toFile.getParent()); - if (!item.getKey().renameTo(toFile)) { - throw new TimiException(TimiCode.ERROR, "移动失败:" + item.getKey().getAbsolutePath() + " -> " + toFile.getAbsolutePath()); - } + if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.RESULT_BAD, "目标已存在:" + storage.virtualPath(target)); } - - // 更新进度 - progress = 1D * ++i / total; + log(Level.INFO, storage.virtualPath(source)); + storage.move(source, target); + progress = 1D * ++index / total; } progress = 1; - - // 删除已移动文件夹 - for (int j = 0; j < this.fromList.size(); j++) { - pauseInterruptHandle(); - - file = new File(this.fromList.get(j)); - if (file.exists()) { - IO.destroy(file); - } - } } } diff --git a/src/main/java/com/imyeyu/api/modules/system/task/async/FileSyncTask.java b/src/main/java/com/imyeyu/api/modules/system/task/async/FileSyncTask.java deleted file mode 100644 index 364c93d..0000000 --- a/src/main/java/com/imyeyu/api/modules/system/task/async/FileSyncTask.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.imyeyu.api.modules.system.task.async; - -import ch.qos.logback.classic.Level; -import com.imyeyu.io.IO; -import com.imyeyu.io.TreeFile; -import com.imyeyu.java.bean.timi.TimiCode; -import com.imyeyu.java.bean.timi.TimiException; -import com.imyeyu.api.modules.system.bean.FileSyncConfig; -import com.imyeyu.api.modules.system.entity.AsyncTask; -import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * 文件同步任务 - * - * @author 夜雨 - * @version 2024-06-16 08:36 - */ -public class FileSyncTask extends AbstractAsyncTask { - - private final FileSyncConfig.Task config; - - public FileSyncTask(String name, FileSyncConfig.Task config) { - this.config = config; - - super.name = name; - isPeriodical = true; - cron = config.getCron(); - type = AsyncTask.Type.FILE_SYNC; - - List targetList = config.getTargets(); - String sourceAbsPath = new File(config.getSource()).getAbsolutePath(); - for (int i = 0; i < targetList.size(); i++) { - File target = new File(targetList.get(i)); - if (target.getAbsolutePath().startsWith(sourceAbsPath)) { - throw new TimiException(TimiCode.ERROR, "invalid target:%s that is in source:%s".formatted(target.getAbsolutePath(), sourceAbsPath)); - } - } - } - - @Override - protected void run() throws Exception { - // 扫描 - setStatus(AsyncTask.Status.RUNNING); - log(Level.INFO, "building file tree"); - // Map<目标, 来源> - Map copyMap = new HashMap<>(); - List mkdirList = new ArrayList<>(); - List destoryList = new ArrayList<>(); - List targetList = config.getTargets(); - List targetTreeFileList = new ArrayList<>(); - for (int i = 0; i < targetList.size(); i++) { - targetTreeFileList.add(new TreeFile(targetList.get(i))); - } - { - log(Level.INFO, "scanning path:%s".formatted(new File(config.getSource()).getAbsolutePath())); - TreeFile sourceTreeFile = new TreeFile(config.getSource()); - sourceTreeFile.foreach((relPath, sourceFile) -> { - for (int i = 0; i < targetTreeFileList.size(); i++) { -// pauseInterruptHandle(); - - File targetFile = new File(IO.fitPath(targetTreeFileList.get(i).getAbsolutePath()) + relPath); - if (sourceFile.isFile()) { - if (!targetFile.exists() || targetFile.length() != sourceFile.length()) { - // 复制 - if (config.isUseMD5Compare() && !IO.md5(targetFile).equals(IO.md5(sourceFile))) { - copyMap.put(targetFile, sourceFile); - } else { - copyMap.put(targetFile, sourceFile); - } - } - } else { - if (!targetFile.exists()) { - // 新建文件夹 - mkdirList.add(targetFile); - } - } - } - }); - // 删除 - for (int i = 0; i < targetTreeFileList.size(); i++) { - TreeFile targetTreeFile = targetTreeFileList.get(i); - targetTreeFile.foreach((relPath, targetFile) -> { -// pauseInterruptHandle(); - - File sourceFile = new File(IO.fitPath(config.getSource()) + relPath); - if (!sourceFile.exists()) { - destoryList.add(targetFile); - } - }); - } - } - // 执行 - { - // 10% 进度用于操作创建文件夹和删除文件 - int easyActionTTL = mkdirList.size() + destoryList.size(); - int easyAction = 0; - for (int j = 0; j < mkdirList.size(); j++) { - pauseInterruptHandle(); - - log(Level.INFO, "making dir:%s".formatted(mkdirList.get(j).getAbsolutePath())); - IO.dir(mkdirList.get(j).getAbsolutePath()); - progress = 1D * ++easyAction / easyActionTTL * .1; - } - for (int j = 0; j < destoryList.size(); j++) { - pauseInterruptHandle(); - - log(Level.INFO, "destroying file:%s".formatted(destoryList.get(j).getAbsolutePath())); - IO.destroy(destoryList.get(j)); - progress = 1D * ++easyAction / easyActionTTL * .1; - } - progress = .1; - - // 复制文件 - long copySizeTTL = 0; - long copySize = 0; - List copyList = new ArrayList<>(copyMap.values()); - for (int i = 0; i < copyList.size(); i++) { - copySizeTTL += copyList.get(i).length(); - } - for (Map.Entry item : copyMap.entrySet()) { - pauseInterruptHandle(); - - log(Level.INFO, "copping file:%s to %s".formatted(item.getValue().getAbsolutePath(), item.getKey().getAbsolutePath())); - final long fileSize = item.getValue().length(); - final long finalCopySize = copySize; - final long finalCopySizeTTL = copySizeTTL; - IO.copy(item.getValue(), item.getKey().getParentFile().getAbsolutePath(), new IO.OnWriteCallback() { - - @Override - public boolean handler(long total, long now) { - progress = .1 + (1D * finalCopySize + total) / finalCopySizeTTL * .9; - return true; - } - }); - copySize += fileSize; - } - } - progress = 1; - log(Level.INFO, "synced"); - synchronized (this) { - wait(3000); - } - } -} diff --git a/src/main/java/com/imyeyu/api/modules/system/task/async/FileTarAsyncTask.java b/src/main/java/com/imyeyu/api/modules/system/task/async/FileTarAsyncTask.java index e772acf..4a8156c 100644 --- a/src/main/java/com/imyeyu/api/modules/system/task/async/FileTarAsyncTask.java +++ b/src/main/java/com/imyeyu/api/modules/system/task/async/FileTarAsyncTask.java @@ -1,23 +1,26 @@ package com.imyeyu.api.modules.system.task.async; import ch.qos.logback.classic.Level; -import com.imyeyu.io.IO; +import com.imyeyu.api.bean.CorePermissionCode; import com.imyeyu.api.modules.system.entity.AsyncTask; +import com.imyeyu.api.modules.system.service.FileStorageService; import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; +import com.imyeyu.api.modules.user.service.PermissionChecker; +import com.imyeyu.java.bean.timi.TimiCode; +import com.imyeyu.java.bean.timi.TimiException; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.util.HashMap; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; -import java.util.Map; +import java.util.Locale; /** * 压缩 TAR - * // TODO 可选是否压缩 * * @author 夜雨 * @version 2022-08-16 16:54 @@ -26,70 +29,66 @@ public class FileTarAsyncTask extends AbstractAsyncTask { private final String to; private final List fromList; + private final FileStorageService storage; + private final PermissionChecker permissionChecker; - public FileTarAsyncTask(List fromList, String to) { + public FileTarAsyncTask(List fromList, String to, FileStorageService storage, PermissionChecker permissionChecker, String ownerUserId) { this.fromList = fromList; this.to = to; + this.storage = storage; + this.permissionChecker = permissionChecker; + this.ownerUserId = ownerUserId; type = AsyncTask.Type.FILE_TAR; } @Override protected void run() throws Exception { - // 准备文件 Map<文件, 深度路径>,深度路径含文件名 - Map fromList = new HashMap<>(); - File file; - for (int i = 0; i < this.fromList.size(); i++) { - pauseInterruptHandle(); - - file = new File(this.fromList.get(i)); - if (file.exists()) { - if (file.isFile()) { - fromList.put(file, file.getName()); - } else { - String basePath = file.getParentFile().getAbsolutePath(); - List files = IO.listFile(file); - for (int j = 0; j < files.size(); j++) { - fromList.put(files.get(j), files.get(j).getAbsolutePath().substring(basePath.length())); - } - } - } + FileTaskSupport.require(permissionChecker, ownerUserId, CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE); + Path target = FileTaskSupport.targetFile(storage, to); + List sources = FileTaskSupport.sources(storage, fromList); + if (sources.stream().anyMatch(source -> source.equals(target))) { + throw new TimiException(TimiCode.ARG_BAD, "压缩目标不能是源文件"); } - - // 压缩文件 - int total = fromList.size(); - int i = 0; - - FileOutputStream fos = new FileOutputStream(to); - BufferedOutputStream bos = new BufferedOutputStream(fos); - GzipCompressorOutputStream gcos = new GzipCompressorOutputStream(bos); - TarArchiveOutputStream taos = new TarArchiveOutputStream(gcos); + if (sources.stream().anyMatch(source -> target.startsWith(source))) { + throw new TimiException(TimiCode.ARG_BAD, "压缩目标不能位于源目录内"); + } + FileTaskSupport.ensureParent(target); + List entries = FileTaskSupport.collect(sources, target); + Path temporary = FileTaskSupport.temporarySibling(target); try { + String lower = to.toLowerCase(Locale.ROOT); + boolean gzip = lower.endsWith(".gz") || lower.endsWith(".tgz"); + try (OutputStream fileOutput = new BufferedOutputStream(Files.newOutputStream(temporary), 64 * 1024); + OutputStream archiveOutput = gzip ? new GzipCompressorOutputStream(fileOutput) : fileOutput; + TarArchiveOutputStream tar = new TarArchiveOutputStream(archiveOutput)) { + tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX); + tar.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX); + int total = entries.size(); + int index = 0; + for (FileTaskSupport.Entry entry : entries) { + pauseInterruptHandle(); - TarArchiveEntry tarEntry; - for (Map.Entry item : fromList.entrySet()) { - pauseInterruptHandle(); - - log(Level.INFO, item.getKey().getName()); - // 执行压缩 - { - tarEntry = new TarArchiveEntry(item.getKey(), item.getValue()); - taos.putArchiveEntry(tarEntry); - taos.write(IO.toBytes(item.getKey())); - taos.closeArchiveEntry(); + log(Level.INFO, entry.name()); + if (entry.directory()) { + TarArchiveEntry tarEntry = new TarArchiveEntry(entry.name() + "/"); + tarEntry.setSize(0); + tar.putArchiveEntry(tarEntry); + } else { + TarArchiveEntry tarEntry = new TarArchiveEntry(entry.path().toFile(), entry.name()); + tarEntry.setSize(Files.size(entry.path())); + tar.putArchiveEntry(tarEntry); + Files.copy(entry.path(), tar); + } + tar.closeArchiveEntry(); + progress = 1D * ++index / total; } - - // 更新进度 - progress = 1D * ++i / total; } + FileTaskSupport.replace(temporary, target); progress = 1; - - } finally { - taos.finish(); - taos.close(); - gcos.close(); - bos.close(); - fos.close(); + } catch (Exception e) { + FileTaskSupport.deleteQuietly(temporary); + throw e; } } } diff --git a/src/main/java/com/imyeyu/api/modules/system/task/async/FileTaskSupport.java b/src/main/java/com/imyeyu/api/modules/system/task/async/FileTaskSupport.java new file mode 100644 index 0000000..bc95f78 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/task/async/FileTaskSupport.java @@ -0,0 +1,191 @@ +package com.imyeyu.api.modules.system.task.async; + +import com.imyeyu.api.bean.CorePermissionCode; +import com.imyeyu.api.bean.ModuleCode; +import com.imyeyu.api.modules.system.service.FileStorageService; +import com.imyeyu.api.modules.user.service.PermissionChecker; +import com.imyeyu.java.bean.timi.TimiCode; +import com.imyeyu.java.bean.timi.TimiException; + +import java.io.IOException; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/// 文件异步任务的公共路径、权限与归档辅助方法。 +final class FileTaskSupport { + + private FileTaskSupport() { + } + + /// 异步任务执行前按创建人复核权限,避免任务创建后权限被撤销仍继续执行。 + static void require(PermissionChecker permissionChecker, String userId, CorePermissionCode... codes) { + if (userId == null || userId.isBlank()) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "任务缺少创建人"); + } + Set codeSet = permissionChecker.codeSet(userId); + for (CorePermissionCode code : codes) { + if (!codeSet.contains(ModuleCode.CORE.name() + ":" + code.getValue())) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "权限不足:" + code.getValue()); + } + } + } + + /// 解析并去重源路径,父目录已包含时跳过其子路径。 + static List sources(FileStorageService storage, List virtualPaths) { + List resolved = new ArrayList<>(); + for (String virtualPath : virtualPaths) { + if (storage.isRoot(virtualPath)) { + throw new TimiException(TimiCode.ARG_BAD, "不能操作根目录"); + } + resolved.add(storage.resolveExisting(virtualPath)); + } + resolved.sort(Comparator.comparingInt(Path::getNameCount)); + List result = new ArrayList<>(); + for (Path path : resolved) { + boolean nested = result.stream().anyMatch(parent -> path.startsWith(parent) && !path.equals(parent)); + if (!nested) { + result.add(path); + } + } + return result; + } + + /// 解析并创建目标目录。 + static Path targetDirectory(FileStorageService storage, String virtualPath) throws IOException { + Path target = storage.resolve(virtualPath); + if (Files.exists(target, LinkOption.NOFOLLOW_LINKS) && !Files.isDirectory(target, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.ARG_BAD, "目标不是目录"); + } + Files.createDirectories(target); + return target; + } + + /// 解析目标文件,不创建目标本身或父目录。 + static Path targetFile(FileStorageService storage, String virtualPath) throws IOException { + Path target = storage.resolve(virtualPath); + if (Files.exists(target, LinkOption.NOFOLLOW_LINKS) && Files.isDirectory(target, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.ARG_BAD, "目标不是文件"); + } + if (target.getParent() == null) { + throw new TimiException(TimiCode.ARG_BAD, "目标路径不合法"); + } + return target; + } + + /// 创建目标文件的父目录。 + static void ensureParent(Path target) throws IOException { + Path parent = target.getParent(); + if (parent == null) { + throw new TimiException(TimiCode.ARG_BAD, "目标路径不合法"); + } + Files.createDirectories(parent); + } + + /// 防止把目录复制/移动到自身内部。 + static void ensureNotNested(Path source, Path destination) { + if (destination.equals(source) || destination.startsWith(source)) { + throw new TimiException(TimiCode.ARG_BAD, "目标不能位于源目录内"); + } + } + + /// 收集源文件与空目录,保留源名称作为归档/复制后的第一层路径。 + static List collect(List sources, Path exclude) throws IOException { + List entries = new ArrayList<>(); + Set names = new HashSet<>(); + for (Path source : sources) { + if (Files.isSymbolicLink(source)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许操作符号链接"); + } + String rootName = source.getFileName() == null ? "" : source.getFileName().toString(); + if (rootName.isEmpty()) { + throw new TimiException(TimiCode.ARG_BAD, "源路径不合法"); + } + if (Files.isDirectory(source, LinkOption.NOFOLLOW_LINKS)) { + Files.walkFileTree(source, new SimpleFileVisitor<>() { + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { + if (Files.isSymbolicLink(dir)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许归档符号链接"); + } + String relative = source.relativize(dir).toString().replace('\\', '/'); + String name = relative.isEmpty() ? rootName : rootName + "/" + relative; + add(entries, names, new Entry(dir, name, true)); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { + if (Files.isSymbolicLink(file)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许归档符号链接"); + } + String relative = source.relativize(file).toString().replace('\\', '/'); + add(entries, names, new Entry(file, rootName + "/" + relative, false)); + return FileVisitResult.CONTINUE; + } + }); + } else { + add(entries, names, new Entry(source, rootName, false)); + } + } + if (exclude != null) { + Path excluded = exclude.toAbsolutePath().normalize(); + entries.removeIf(entry -> entry.path().toAbsolutePath().normalize().equals(excluded)); + } + return entries; + } + + private static void add(List entries, Set names, Entry entry) { + if (!names.add(entry.name())) { + throw new TimiException(TimiCode.ARG_BAD, "源文件名称重复:" + entry.name()); + } + entries.add(entry); + } + + /// 防止解压时通过已存在的符号链接目录逃逸。 + static void ensureNoSymlink(Path root, Path target) { + Path current = root; + for (Path part : root.relativize(target)) { + current = current.resolve(part); + if (Files.isSymbolicLink(current)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许通过符号链接写入"); + } + } + } + + /// 在目标文件同目录创建临时文件,成功后原子替换目标。 + static Path temporarySibling(Path target) throws IOException { + return Files.createTempFile(target.getParent(), ".timi-archive-", ".part"); + } + + static void replace(Path temporary, Path target) throws IOException { + try { + Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (AtomicMoveNotSupportedException e) { + Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING); + } + } + + static void deleteQuietly(Path path) { + if (path == null) { + return; + } + try { + Files.deleteIfExists(path); + } catch (IOException ignored) { + } + } + + record Entry(Path path, String name, boolean directory) { + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/task/async/FileUnTarAsyncTask.java b/src/main/java/com/imyeyu/api/modules/system/task/async/FileUnTarAsyncTask.java index a6dd1bd..b0a5b62 100644 --- a/src/main/java/com/imyeyu/api/modules/system/task/async/FileUnTarAsyncTask.java +++ b/src/main/java/com/imyeyu/api/modules/system/task/async/FileUnTarAsyncTask.java @@ -1,17 +1,25 @@ package com.imyeyu.api.modules.system.task.async; import ch.qos.logback.classic.Level; -import com.imyeyu.io.IO; +import com.imyeyu.api.bean.CorePermissionCode; import com.imyeyu.api.modules.system.entity.AsyncTask; +import com.imyeyu.api.modules.system.service.FileStorageService; import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; -import org.apache.commons.compress.archivers.ArchiveEntry; +import com.imyeyu.api.modules.user.service.PermissionChecker; +import com.imyeyu.java.bean.timi.TimiCode; +import com.imyeyu.java.bean.timi.TimiException; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; -import java.io.File; -import java.io.FileInputStream; +import java.io.BufferedInputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; /** * 解压 TAR @@ -21,91 +29,119 @@ import java.io.IOException; */ public class FileUnTarAsyncTask extends AbstractAsyncTask { - private final File tarFile; - private final String unTarTo; + private static final int MAX_ENTRIES = 100_000; + private static final long MAX_RATIO = 1_000; + private static final long MIN_RATIO_SIZE = 10L * 1024 * 1024; - public FileUnTarAsyncTask(File tarFile, String unTarTo) { - this.tarFile = tarFile; - this.unTarTo = unTarTo; + private final String from; + private final String to; + private final FileStorageService storage; + private final PermissionChecker permissionChecker; + + public FileUnTarAsyncTask(String from, String to, FileStorageService storage, PermissionChecker permissionChecker, String ownerUserId) { + this.from = from; + this.to = to; + this.storage = storage; + this.permissionChecker = permissionChecker; + this.ownerUserId = ownerUserId; type = AsyncTask.Type.FILE_UNTAR; } @Override protected void run() throws Exception { - int total = getTotal(); - - // 解压 - FileInputStream fis = new FileInputStream(tarFile); - GzipCompressorInputStream gcis = null; - TarArchiveInputStream tais; - if (tarFile.getName().endsWith("gz")) { - gcis = new GzipCompressorInputStream(fis); - tais = new TarArchiveInputStream(gcis); - } else { - tais = new TarArchiveInputStream(fis); + FileTaskSupport.require(permissionChecker, ownerUserId, CorePermissionCode.FILE_WRITE); + Path tarPath = storage.resolveExisting(from); + if (!Files.isRegularFile(tarPath, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.ARG_BAD, "压缩文件不存在"); } - try { - TarArchiveEntry entry; + Path destination = FileTaskSupport.targetDirectory(storage, to); + long maxTotal = storage.maxUploadSize(); - int i = 0; - while ((entry = (TarArchiveEntry) tais.getNextEntry()) != null) { - pauseInterruptHandle(); - - String path = IO.fitPath(unTarTo) + entry.getName(); - - log(Level.INFO, path); - // 执行解压 - if (entry.isDirectory()) { - IO.dir(path); - } else { - IO.toFile(IO.file(path), tais); - // 更新进度(total 只包含文件) - progress = 1D * ++i / total; - } - } - progress = 1; - - } finally { - tais.close(); - if (gcis != null) { - gcis.close(); - } - fis.close(); - } - } - - private int getTotal() throws IOException, InterruptedException { int total = 0; - { - // 统计文件数量 - FileInputStream fis = new FileInputStream(tarFile); - GzipCompressorInputStream gcis = null; - TarArchiveInputStream tais; - if (tarFile.getName().endsWith("gz")) { - gcis = new GzipCompressorInputStream(fis); - tais = new TarArchiveInputStream(gcis); - } else { - tais = new TarArchiveInputStream(fis); - } - - try { - ArchiveEntry entry; - while ((entry = tais.getNextEntry()) != null) { - pauseInterruptHandle(); - - if (!entry.isDirectory()) { - ++total; + long declaredSize = 0; + try (TarArchiveInputStream tar = new TarArchiveInputStream(open(tarPath))) { + TarArchiveEntry entry; + int entryCount = 0; + while ((entry = tar.getNextTarEntry()) != null) { + if (++entryCount > MAX_ENTRIES) { + throw new TimiException(TimiCode.ARG_BAD, "压缩包条目过多"); + } + if (entry.isSymbolicLink() || entry.isLink()) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许解压链接文件"); + } + if (!entry.isDirectory()) { + ++total; + declaredSize += Math.max(0, entry.getSize()); + if (declaredSize > maxTotal) { + throw new TimiException(TimiCode.ARG_BAD, "解压后大小超过限制"); } } - } finally { - tais.close(); - if (gcis != null) { - gcis.close(); - } - fis.close(); } } - return total; + if (declaredSize > MIN_RATIO_SIZE && Files.size(tarPath) > 0 + && declaredSize / Files.size(tarPath) > MAX_RATIO) { + throw new TimiException(TimiCode.ARG_BAD, "压缩比异常"); + } + + long totalWritten = 0; + int index = 0; + try (TarArchiveInputStream tar = new TarArchiveInputStream(open(tarPath))) { + TarArchiveEntry entry; + while ((entry = tar.getNextTarEntry()) != null) { + pauseInterruptHandle(); + + if (entry.isSymbolicLink() || entry.isLink()) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许解压链接文件"); + } + Path target = target(destination, entry.getName()); + log(Level.INFO, entry.getName()); + if (entry.isDirectory()) { + Files.createDirectories(target); + } else { + Files.createDirectories(target.getParent()); + if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.RESULT_BAD, "目标已存在:" + entry.getName()); + } + try (OutputStream output = Files.newOutputStream(target, StandardOpenOption.CREATE_NEW)) { + byte[] buffer = new byte[64 * 1024]; + int length; + while ((length = tar.read(buffer)) != -1) { + totalWritten += length; + if (totalWritten > maxTotal) { + throw new TimiException(TimiCode.ARG_BAD, "解压后大小超过限制"); + } + output.write(buffer, 0, length); + } + } catch (Exception e) { + Files.deleteIfExists(target); + throw e; + } + progress = 1D * ++index / total; + } + } + } + progress = 1; + } + + private InputStream open(Path path) throws IOException { + BufferedInputStream input = new BufferedInputStream(Files.newInputStream(path)); + input.mark(2); + int first = input.read(); + int second = input.read(); + input.reset(); + return first == 0x1f && second == 0x8b ? new GzipCompressorInputStream(input) : input; + } + + private Path target(Path destination, String name) { + if (name == null || name.isBlank() || name.indexOf('\\') >= 0 || name.startsWith("/")) { + throw new TimiException(TimiCode.ARG_BAD, "压缩包路径不合法"); + } + Path target = destination.resolve(name).normalize(); + if (!target.startsWith(destination)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "压缩包路径越界"); + } + FileTaskSupport.ensureNoSymlink(destination, target); + return target; } } diff --git a/src/main/java/com/imyeyu/api/modules/system/task/async/FileUnZipAsyncTask.java b/src/main/java/com/imyeyu/api/modules/system/task/async/FileUnZipAsyncTask.java index fdee899..370e978 100644 --- a/src/main/java/com/imyeyu/api/modules/system/task/async/FileUnZipAsyncTask.java +++ b/src/main/java/com/imyeyu/api/modules/system/task/async/FileUnZipAsyncTask.java @@ -1,19 +1,24 @@ package com.imyeyu.api.modules.system.task.async; import ch.qos.logback.classic.Level; -import com.imyeyu.io.IO; -import com.imyeyu.java.TimiJava; +import com.imyeyu.api.bean.CorePermissionCode; import com.imyeyu.api.modules.system.entity.AsyncTask; +import com.imyeyu.api.modules.system.service.FileStorageService; import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; +import com.imyeyu.api.modules.user.service.PermissionChecker; +import com.imyeyu.java.bean.timi.TimiCode; +import com.imyeyu.java.bean.timi.TimiException; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipFile; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; import java.io.InputStream; -import java.util.Enumeration; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.Collections; +import java.util.List; /** * 解压缩 ZIP @@ -21,73 +26,105 @@ import java.util.zip.ZipFile; * @author 夜雨 * @version 2022-08-15 16:58 */ -public class FileUnZipAsyncTask extends AbstractAsyncTask implements TimiJava { +public class FileUnZipAsyncTask extends AbstractAsyncTask { - private final File zipFile; - private final String unZipTo; + private static final int MAX_ENTRIES = 100_000; + private static final long MAX_RATIO = 1_000; + private static final long MIN_RATIO_SIZE = 10L * 1024 * 1024; - public FileUnZipAsyncTask(File zipFile, String unZipTo) { - this.zipFile = zipFile; - this.unZipTo = unZipTo; + private final String from; + private final String to; + private final FileStorageService storage; + private final PermissionChecker permissionChecker; + + public FileUnZipAsyncTask(String from, String to, FileStorageService storage, PermissionChecker permissionChecker, String ownerUserId) { + this.from = from; + this.to = to; + this.storage = storage; + this.permissionChecker = permissionChecker; + this.ownerUserId = ownerUserId; type = AsyncTask.Type.FILE_UNZIP; } @Override - @SuppressWarnings("unchecked") protected void run() throws Exception { - ZipFile zip = new ZipFile(zipFile); - Enumeration entries = (Enumeration) zip.entries(); - - // 统计数量 - int total = 0; - - while (entries.hasMoreElements()) { - if (!entries.nextElement().isDirectory()) { - ++total; - } + FileTaskSupport.require(permissionChecker, ownerUserId, CorePermissionCode.FILE_WRITE); + Path zipPath = storage.resolveExisting(from); + if (!Files.isRegularFile(zipPath, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.ARG_BAD, "压缩文件不存在"); } + Path destination = FileTaskSupport.targetDirectory(storage, to); + long maxTotal = storage.maxUploadSize(); + long totalWritten = 0; - // 解压 - ZipEntry entry; - - InputStream is; - FileOutputStream fos; - BufferedInputStream bis; - BufferedOutputStream bos; - entries = (Enumeration) zip.entries(); - for (int i = 0; entries.hasMoreElements(); i++) { - pauseInterruptHandle(); - - entry = entries.nextElement(); - String path = IO.fitPath(unZipTo) + entry.getName(); - - log(Level.INFO, path); - // 执行解压 - { - File entryFile = IO.file(path); - is = zip.getInputStream(entry); - bis = new BufferedInputStream(is); - fos = new FileOutputStream(entryFile); - bos = new BufferedOutputStream(fos); - - int l; - byte[] buffer = new byte[4096]; - while ((l = bis.read(buffer)) != -1) { - bos.write(buffer, 0, l); + try (ZipFile zip = new ZipFile(zipPath.toFile())) { + List entries = Collections.list(zip.getEntries()); + if (entries.size() > MAX_ENTRIES) { + throw new TimiException(TimiCode.ARG_BAD, "压缩包条目过多"); + } + long declaredSize = 0; + for (ZipArchiveEntry entry : entries) { + if (entry.getSize() > 0) { + declaredSize += entry.getSize(); + if (declaredSize > maxTotal) { + throw new TimiException(TimiCode.ARG_BAD, "解压后大小超过限制"); + } + if (entry.getSize() > MIN_RATIO_SIZE && entry.getCompressedSize() > 0 + && entry.getSize() / entry.getCompressedSize() > MAX_RATIO) { + throw new TimiException(TimiCode.ARG_BAD, "压缩比异常"); + } } } - bos.flush(); - bos.close(); - fos.close(); - bis.close(); - is.close(); + int total = entries.size(); + int index = 0; + for (ZipArchiveEntry entry : entries) { + pauseInterruptHandle(); - progress = 1D * i / total; + if (entry.isUnixSymlink()) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "不允许解压符号链接"); + } + Path target = target(destination, entry.getName()); + log(Level.INFO, entry.getName()); + if (entry.isDirectory()) { + Files.createDirectories(target); + } else { + Files.createDirectories(target.getParent()); + if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { + throw new TimiException(TimiCode.RESULT_BAD, "目标已存在:" + entry.getName()); + } + try (InputStream input = zip.getInputStream(entry); + OutputStream output = Files.newOutputStream(target, StandardOpenOption.CREATE_NEW)) { + byte[] buffer = new byte[64 * 1024]; + int length; + while ((length = input.read(buffer)) != -1) { + totalWritten += length; + if (totalWritten > maxTotal) { + throw new TimiException(TimiCode.ARG_BAD, "解压后大小超过限制"); + } + output.write(buffer, 0, length); + } + } catch (Exception e) { + Files.deleteIfExists(target); + throw e; + } + } + progress = 1D * ++index / total; + } } - zip.close(); - progress = 1; } + + private Path target(Path destination, String name) { + if (name == null || name.isBlank() || name.indexOf('\\') >= 0 || name.startsWith("/")) { + throw new TimiException(TimiCode.ARG_BAD, "压缩包路径不合法"); + } + Path target = destination.resolve(name).normalize(); + if (!target.startsWith(destination)) { + throw new TimiException(TimiCode.PERMISSION_ERROR, "压缩包路径越界"); + } + FileTaskSupport.ensureNoSymlink(destination, target); + return target; + } } diff --git a/src/main/java/com/imyeyu/api/modules/system/task/async/FileZipAsyncTask.java b/src/main/java/com/imyeyu/api/modules/system/task/async/FileZipAsyncTask.java index 2216f34..292b6ed 100644 --- a/src/main/java/com/imyeyu/api/modules/system/task/async/FileZipAsyncTask.java +++ b/src/main/java/com/imyeyu/api/modules/system/task/async/FileZipAsyncTask.java @@ -1,19 +1,19 @@ package com.imyeyu.api.modules.system.task.async; import ch.qos.logback.classic.Level; -import com.imyeyu.io.IO; +import com.imyeyu.api.bean.CorePermissionCode; import com.imyeyu.api.modules.system.entity.AsyncTask; +import com.imyeyu.api.modules.system.service.FileStorageService; import com.imyeyu.api.modules.system.service.implement.AbstractAsyncTask; +import com.imyeyu.api.modules.user.service.PermissionChecker; +import com.imyeyu.java.bean.timi.TimiCode; +import com.imyeyu.java.bean.timi.TimiException; -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.util.HashMap; +import java.io.BufferedOutputStream; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; -import java.util.Map; -import java.util.zip.CRC32; -import java.util.zip.CheckedOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @@ -27,90 +27,57 @@ public class FileZipAsyncTask extends AbstractAsyncTask { private final String to; private final List fromList; + private final FileStorageService storage; + private final PermissionChecker permissionChecker; - public FileZipAsyncTask(List fromList, String to) { + public FileZipAsyncTask(List fromList, String to, FileStorageService storage, PermissionChecker permissionChecker, String ownerUserId) { this.fromList = fromList; this.to = to; + this.storage = storage; + this.permissionChecker = permissionChecker; + this.ownerUserId = ownerUserId; type = AsyncTask.Type.FILE_ZIP; } @Override protected void run() throws Exception { - // 准备文件 Map<文件, 深度路径>,深度路径含文件名 - Map fromList = new HashMap<>(); - File file; - for (int i = 0; i < this.fromList.size(); i++) { - pauseInterruptHandle(); - - file = new File(this.fromList.get(i)); - if (file.exists()) { - if (file.isFile()) { - fromList.put(file, file.getName()); - } else { - String basePath = file.getParentFile().getAbsolutePath(); - List files = IO.listFile(file); - for (int j = 0; j < files.size(); j++) { - fromList.put(files.get(j), files.get(j).getAbsolutePath().substring(basePath.length())); - } - } - } + FileTaskSupport.require(permissionChecker, ownerUserId, CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE); + Path target = FileTaskSupport.targetFile(storage, to); + List sources = FileTaskSupport.sources(storage, fromList); + if (sources.stream().anyMatch(source -> source.equals(target))) { + throw new TimiException(TimiCode.ARG_BAD, "压缩目标不能是源文件"); } - // 压缩文件 - int total = fromList.size(); - int i = 0; - - ZipOutputStream zos = null; - CheckedOutputStream cos = null; - FileOutputStream fos = null; + if (sources.stream().anyMatch(source -> target.startsWith(source))) { + throw new TimiException(TimiCode.ARG_BAD, "压缩目标不能位于源目录内"); + } + FileTaskSupport.ensureParent(target); + List entries = FileTaskSupport.collect(sources, target); + Path temporary = FileTaskSupport.temporarySibling(target); try { - File zipFile = IO.file(to); + try (ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(temporary), 64 * 1024))) { + int total = entries.size(); + int index = 0; + for (FileTaskSupport.Entry entry : entries) { + pauseInterruptHandle(); - fos = new FileOutputStream(zipFile); - cos = new CheckedOutputStream(fos, new CRC32()); - zos = new ZipOutputStream(cos); - - for (Map.Entry item : fromList.entrySet()) { - pauseInterruptHandle(); - - log(Level.INFO, item.getKey().getName()); - // 执行压缩 - { - ZipEntry entry = new ZipEntry(item.getValue()); - zos.putNextEntry(entry); - - FileInputStream fis = new FileInputStream(item.getKey()); - BufferedInputStream bis = new BufferedInputStream(fis); - - int l; - byte[] buffer = new byte[4096]; - while ((l = bis.read(buffer)) != -1) { - zos.write(buffer, 0, l); + log(Level.INFO, entry.name()); + ZipEntry zipEntry = new ZipEntry(entry.directory() ? entry.name() + "/" : entry.name()); + zip.putNextEntry(zipEntry); + if (!entry.directory()) { + try (InputStream input = Files.newInputStream(entry.path())) { + input.transferTo(zip); + } } - - bis.close(); - fis.close(); - zos.closeEntry(); + zip.closeEntry(); + progress = 1D * ++index / total; } - - // 更新进度 - progress = 1D * ++i / total; } + FileTaskSupport.replace(temporary, target); progress = 1; - - } finally { - if (zos != null) { - zos.flush(); - zos.close(); - } - if (cos != null) { - cos.flush(); - cos.close(); - } - if (fos != null) { - fos.flush(); - fos.close(); - } + } catch (Exception e) { + FileTaskSupport.deleteQuietly(temporary); + throw e; } } } diff --git a/src/main/java/com/imyeyu/api/modules/system/util/SystemAPIInterceptor.java b/src/main/java/com/imyeyu/api/modules/system/util/SystemAPIInterceptor.java deleted file mode 100644 index d04e1ad..0000000 --- a/src/main/java/com/imyeyu/api/modules/system/util/SystemAPIInterceptor.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.imyeyu.api.modules.system.util; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.imyeyu.api.modules.common.entity.Setting; -import com.imyeyu.api.modules.common.service.SettingService; -import com.imyeyu.api.modules.system.bean.AccessKey; -import com.imyeyu.java.bean.timi.TimiCode; -import com.imyeyu.java.bean.timi.TimiException; -import com.imyeyu.spring.TimiSpring; -import jakarta.annotation.PostConstruct; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.lang.NonNull; -import org.springframework.stereotype.Component; -import org.springframework.web.servlet.HandlerInterceptor; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @author 夜雨 - * @version 2023-11-23 17:09 - */ -@Slf4j -@Component -@RequiredArgsConstructor -public class SystemAPIInterceptor implements HandlerInterceptor { - - public static final String PATH = "/system/**"; - private static final String HIGH_AUTHORITY = "SYSTEM_API_HIGH_AUTHORITY_KEY"; - - private final ObjectMapper jackson; - private final SettingService settingService; - - private final Map keyMap = new HashMap<>(); - - @PostConstruct - private void postConstruct() throws JsonProcessingException { -// List list = jackson.readValue(settingService.getSystem(Setting.Module.System.API_KEY).asString(), new TypeReference<>() {}); -// for (AccessKey key : list) { -// keyMap.put(key.getValue(), key.getHighAuthority()); -// } - } - - public boolean preHandle(@NonNull HttpServletRequest req, @NonNull HttpServletResponse resp, @NonNull Object handler) { -// String key = TimiSpring.getKey(); -// if (keyMap.containsKey(key)) { -// TimiSpring.setRequestAttr(HIGH_AUTHORITY, keyMap.get(key)); -// return true; -// } -// throw new TimiException(TimiCode.PERMISSION_ERROR, "TODO invalid key"); - return true; - } - - public boolean isHighAuthorityKey() { -// return TimiSpring.getRequestAttr(HIGH_AUTHORITY, Boolean.class); - return true; - } -} diff --git a/src/main/java/com/imyeyu/api/modules/system/vo/ArchiveRequest.java b/src/main/java/com/imyeyu/api/modules/system/vo/ArchiveRequest.java new file mode 100644 index 0000000..ac8ad3d --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/vo/ArchiveRequest.java @@ -0,0 +1,9 @@ +package com.imyeyu.api.modules.system.vo; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotEmpty; + +import java.util.List; + +public record ArchiveRequest(@NotEmpty List<@NotBlank String> list, @NotBlank String to) { +} diff --git a/src/main/java/com/imyeyu/api/modules/system/vo/AsyncTaskEvent.java b/src/main/java/com/imyeyu/api/modules/system/vo/AsyncTaskEvent.java new file mode 100644 index 0000000..ec62a46 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/vo/AsyncTaskEvent.java @@ -0,0 +1,33 @@ +package com.imyeyu.api.modules.system.vo; + +import com.imyeyu.api.modules.system.entity.AsyncTask; + +/** + * 异步任务 SSE 事件快照。 + * + * @param id 任务 ID + * @param name 任务名称 + * @param type 任务类型 + * @param status 当前状态 + * @param progress 进度,-1 表示无法计算进度 + * @param message 最近日志 + * @param result 任务结果(通常为 JSON 字符串) + * @param createdAt 创建时间 + * @param startAt 开始时间 + * @param completedAt 完成时间 + * @author 夜雨 + * @version 2026-11-24 + */ +public record AsyncTaskEvent( + String id, + String name, + AsyncTask.Type type, + AsyncTask.Status status, + double progress, + String message, + String result, + long createdAt, + long startAt, + long completedAt +) { +} diff --git a/src/main/java/com/imyeyu/api/modules/system/vo/FileListRequest.java b/src/main/java/com/imyeyu/api/modules/system/vo/FileListRequest.java new file mode 100644 index 0000000..d071541 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/vo/FileListRequest.java @@ -0,0 +1,9 @@ +package com.imyeyu.api.modules.system.vo; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotEmpty; + +import java.util.List; + +public record FileListRequest(@NotEmpty List<@NotBlank String> list) { +} diff --git a/src/main/java/com/imyeyu/api/modules/system/vo/FileSizeResult.java b/src/main/java/com/imyeyu/api/modules/system/vo/FileSizeResult.java new file mode 100644 index 0000000..6f95576 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/vo/FileSizeResult.java @@ -0,0 +1,23 @@ +package com.imyeyu.api.modules.system.vo; + +/** + * 文件夹大小统计结果。 + * + * @param path 统计的虚拟路径 + * @param bytes 文件总字节数 + * @param files 文件数量 + * @param directories 目录数量(包含被统计的根目录) + * @param failed 无法访问而跳过的条目数量 + * @param durationMillis 统计耗时(毫秒) + * @author 夜雨 + * @version 2026-11-24 + */ +public record FileSizeResult( + String path, + long bytes, + long files, + long directories, + long failed, + long durationMillis +) { +} diff --git a/src/main/java/com/imyeyu/api/modules/system/vo/IdRequest.java b/src/main/java/com/imyeyu/api/modules/system/vo/IdRequest.java new file mode 100644 index 0000000..263ce1f --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/vo/IdRequest.java @@ -0,0 +1,7 @@ +package com.imyeyu.api.modules.system.vo; + +import jakarta.validation.constraints.NotBlank; + +/// 通用 ID 请求 +public record IdRequest(@NotBlank String id) { +} diff --git a/src/main/java/com/imyeyu/api/modules/system/vo/MkdirRequest.java b/src/main/java/com/imyeyu/api/modules/system/vo/MkdirRequest.java new file mode 100644 index 0000000..04c73a3 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/vo/MkdirRequest.java @@ -0,0 +1,6 @@ +package com.imyeyu.api.modules.system.vo; + +import jakarta.validation.constraints.NotBlank; + +public record MkdirRequest(@NotBlank String path, @NotBlank String name) { +} diff --git a/src/main/java/com/imyeyu/api/modules/system/vo/PathRequest.java b/src/main/java/com/imyeyu/api/modules/system/vo/PathRequest.java new file mode 100644 index 0000000..9b5457a --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/vo/PathRequest.java @@ -0,0 +1,6 @@ +package com.imyeyu.api.modules.system.vo; + +import jakarta.validation.constraints.NotBlank; + +public record PathRequest(@NotBlank String path) { +} diff --git a/src/main/java/com/imyeyu/api/modules/system/vo/RenameRequest.java b/src/main/java/com/imyeyu/api/modules/system/vo/RenameRequest.java new file mode 100644 index 0000000..ce3f2f0 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/vo/RenameRequest.java @@ -0,0 +1,6 @@ +package com.imyeyu.api.modules.system.vo; + +import jakarta.validation.constraints.NotBlank; + +public record RenameRequest(@NotBlank String from, @NotBlank String to) { +} diff --git a/src/main/java/com/imyeyu/api/modules/system/vo/SearchRequest.java b/src/main/java/com/imyeyu/api/modules/system/vo/SearchRequest.java new file mode 100644 index 0000000..eda44ae --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/vo/SearchRequest.java @@ -0,0 +1,6 @@ +package com.imyeyu.api.modules.system.vo; + +import jakarta.validation.constraints.NotBlank; + +public record SearchRequest(@NotBlank String path, @NotBlank String keyword) { +} diff --git a/src/main/java/com/imyeyu/api/modules/system/vo/ShareCreateRequest.java b/src/main/java/com/imyeyu/api/modules/system/vo/ShareCreateRequest.java new file mode 100644 index 0000000..d36651e --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/vo/ShareCreateRequest.java @@ -0,0 +1,6 @@ +package com.imyeyu.api.modules.system.vo; + +import jakarta.validation.constraints.NotBlank; + +public record ShareCreateRequest(@NotBlank String path, String password, Long expiresAt, Integer maxDownloads) { +} diff --git a/src/main/java/com/imyeyu/api/modules/system/vo/UnarchiveRequest.java b/src/main/java/com/imyeyu/api/modules/system/vo/UnarchiveRequest.java new file mode 100644 index 0000000..cc7d433 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/vo/UnarchiveRequest.java @@ -0,0 +1,6 @@ +package com.imyeyu.api.modules.system.vo; + +import jakarta.validation.constraints.NotBlank; + +public record UnarchiveRequest(@NotBlank String file, @NotBlank String to) { +} diff --git a/src/main/java/com/imyeyu/api/modules/system/vo/UploadCompleteRequest.java b/src/main/java/com/imyeyu/api/modules/system/vo/UploadCompleteRequest.java new file mode 100644 index 0000000..1e7b18c --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/vo/UploadCompleteRequest.java @@ -0,0 +1,6 @@ +package com.imyeyu.api.modules.system.vo; + +import jakarta.validation.constraints.NotBlank; + +public record UploadCompleteRequest(@NotBlank String uploadId, String sha256) { +} diff --git a/src/main/java/com/imyeyu/api/modules/system/vo/UploadInitRequest.java b/src/main/java/com/imyeyu/api/modules/system/vo/UploadInitRequest.java new file mode 100644 index 0000000..b8e0a2f --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/vo/UploadInitRequest.java @@ -0,0 +1,7 @@ +package com.imyeyu.api.modules.system.vo; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.PositiveOrZero; + +public record UploadInitRequest(@NotBlank String path, @NotBlank String name, @PositiveOrZero long size, String sha256) { +} diff --git a/src/main/resources/db/migration/timiserver/V93__create_file_trash.sql b/src/main/resources/db/migration/timiserver/V93__create_file_trash.sql new file mode 100644 index 0000000..b01bd0e --- /dev/null +++ b/src/main/resources/db/migration/timiserver/V93__create_file_trash.sql @@ -0,0 +1,15 @@ +CREATE TABLE `file_trash` +( + `id` VARCHAR(36) NOT NULL COMMENT '主键', + `original_path` VARCHAR(4096) NOT NULL COMMENT '删除前的虚拟路径', + `trash_name` VARCHAR(64) NOT NULL COMMENT '回收站目录名', + `name` VARCHAR(255) NOT NULL COMMENT '文件或文件夹名称', + `size` BIGINT NOT NULL DEFAULT 0 COMMENT '文件大小,文件夹为 0', + `directory` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否为文件夹', + `owner_user_id` VARCHAR(36) NULL COMMENT '删除人用户 ID', + `deleted_at` BIGINT NOT NULL COMMENT '删除时间', + `expires_at` BIGINT NOT NULL COMMENT '过期时间', + PRIMARY KEY (`id`), + KEY `idx_file_trash_expires_at` (`expires_at`), + KEY `idx_file_trash_deleted_at` (`deleted_at`) +) COMMENT = '文件回收站'; diff --git a/src/main/resources/db/migration/timiserver/V94__create_file_share.sql b/src/main/resources/db/migration/timiserver/V94__create_file_share.sql new file mode 100644 index 0000000..05d8052 --- /dev/null +++ b/src/main/resources/db/migration/timiserver/V94__create_file_share.sql @@ -0,0 +1,24 @@ +CREATE TABLE `file_share` +( + `id` varchar(36) NOT NULL COMMENT '主键', + `token` varchar(64) NOT NULL COMMENT '分享令牌', + `path` varchar(4096) NOT NULL COMMENT '文件虚拟路径', + `name` varchar(255) NOT NULL COMMENT '文件名', + `owner_user_id` varchar(36) NULL COMMENT '创建人', + `password_hash` varchar(255) NULL COMMENT '密码哈希', + `file_hash` varchar(64) NULL COMMENT '文件 SHA-256', + `file_size` bigint NOT NULL DEFAULT 0 COMMENT '分享时文件大小', + `file_modified_at` bigint NOT NULL DEFAULT 0 COMMENT '分享时文件修改时间', + `expires_at` bigint NOT NULL COMMENT '过期时间', + `max_downloads` int NOT NULL DEFAULT 0 COMMENT '最大下载次数,0 不限', + `download_count` int NOT NULL DEFAULT 0 COMMENT '已下载次数', + `last_access_at` bigint NOT NULL DEFAULT 0 COMMENT '最后访问时间', + `created_at` bigint NOT NULL COMMENT '创建时间', + `deleted_at` bigint NOT NULL DEFAULT 0 COMMENT '删除时间,0 未删除', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_file_share_token` (`token`), + KEY `idx_file_share_owner` (`owner_user_id`), + KEY `idx_file_share_expires` (`expires_at`), + KEY `idx_file_share_deleted` (`deleted_at`) +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 COMMENT = '文件分享'; diff --git a/src/test/java/com/imyeyu/api/modules/system/service/FileContentServiceTest.java b/src/test/java/com/imyeyu/api/modules/system/service/FileContentServiceTest.java new file mode 100644 index 0000000..25348b0 --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/system/service/FileContentServiceTest.java @@ -0,0 +1,94 @@ +package com.imyeyu.api.modules.system.service; + +import com.imyeyu.api.modules.system.util.ResourceHandler; +import com.imyeyu.java.bean.timi.TimiException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +/// 文件内容服务测试。 +class FileContentServiceTest { + + @TempDir + Path temp; + + private FileContentService service; + private ResourceHandler resourceHandler; + + @BeforeEach + void setUp() throws IOException { + FileStorageService storage = FileTestSupport.storage(temp, Map.of()); + resourceHandler = mock(ResourceHandler.class); + service = new FileContentService(storage, mock(ThumbnailService.class), resourceHandler); + } + + @Test + void detectsMimeTypeAndDangerousAttachment() throws IOException { + Files.writeString(temp.resolve("a.txt"), "hello", StandardCharsets.UTF_8); + Files.writeString(temp.resolve("a.html"), "", StandardCharsets.UTF_8); + + FileContentService.ContentInfo text = service.info("/a.txt"); + assertEquals("text/plain", text.mimeType()); + assertFalse(text.attachment()); + assertNotNull(text.etag()); + + FileContentService.ContentInfo html = service.info("/a.html"); + assertEquals("text/html", html.mimeType()); + assertTrue(html.attachment()); + } + + @Test + void rejectsDangerousPreview() throws IOException { + Files.writeString(temp.resolve("a.html"), "", StandardCharsets.UTF_8); + + assertThrows(TimiException.class, () -> service.preview(new MockHttpServletRequest(), + new MockHttpServletResponse(), "/a.html")); + } + + @Test + void servesNotModified() throws Exception { + Files.writeString(temp.resolve("a.txt"), "hello", StandardCharsets.UTF_8); + FileContentService.ContentInfo info = service.info("/a.txt"); + + MockHttpServletRequest req = new MockHttpServletRequest("GET", "/system/file/read/a.txt"); + req.addHeader("If-None-Match", info.etag()); + MockHttpServletResponse resp = new MockHttpServletResponse(); + + service.serve(req, resp, "/a.txt", false); + + assertEquals(304, resp.getStatus()); + verify(resourceHandler, org.mockito.Mockito.never()).handleRequest(req, resp); + } + + @Test + void servesWithCacheHeaders() throws Exception { + Files.writeString(temp.resolve("a.txt"), "hello", StandardCharsets.UTF_8); + + MockHttpServletRequest req = new MockHttpServletRequest("GET", "/system/file/read/a.txt"); + MockHttpServletResponse resp = new MockHttpServletResponse(); + + service.serve(req, resp, "/a.txt", false); + + assertEquals("text/plain", resp.getContentType()); + assertNotNull(resp.getHeader("ETag")); + assertEquals("nosniff", resp.getHeader("X-Content-Type-Options")); + assertEquals("private, max-age=0, must-revalidate", resp.getHeader("Cache-Control")); + verify(resourceHandler).handleRequest(req, resp); + } +} diff --git a/src/test/java/com/imyeyu/api/modules/system/service/FileServiceImplementTest.java b/src/test/java/com/imyeyu/api/modules/system/service/FileServiceImplementTest.java new file mode 100644 index 0000000..d0f6828 --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/system/service/FileServiceImplementTest.java @@ -0,0 +1,102 @@ +package com.imyeyu.api.modules.system.service; + +import com.imyeyu.api.modules.system.bean.ServerFile; +import com.imyeyu.api.modules.system.service.implement.FileServiceImplement; +import com.imyeyu.java.bean.timi.TimiException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// 文件元数据服务测试。 +class FileServiceImplementTest { + + @TempDir + Path temp; + + private FileStorageService storage; + private FileServiceImplement service; + + @BeforeEach + void setUp() throws IOException { + storage = FileTestSupport.storage(temp, Map.of( + "SEARCH_MAX_RESULTS", "200", + "SEARCH_MAX_DEPTH", "32", + "SEARCH_TIMEOUT_SECONDS", "5" + )); + service = new FileServiceImplement(storage); + } + + @Test + void listsDirectoriesFirstAndHidesInternalDirectories() throws IOException { + Files.createDirectories(temp.resolve("b")); + Files.writeString(temp.resolve("a.txt"), "a"); + Files.createDirectories(temp.resolve(".trash")); + + List list = service.list("/"); + assertEquals(2, list.size()); + assertTrue(Boolean.TRUE.equals(list.get(0).getDirectory())); + assertEquals("b", list.get(0).getName()); + assertEquals("a.txt", list.get(1).getName()); + assertFalse(list.stream().anyMatch(item -> ".trash".equals(item.getName()))); + } + + @Test + void createsAndRejectsDuplicateDirectory() { + ServerFile directory = service.mkdir("/", "new"); + assertTrue(Boolean.TRUE.equals(directory.getDirectory())); + assertEquals("/new", directory.getPath()); + assertThrows(TimiException.class, () -> service.mkdir("/", "new")); + assertThrows(TimiException.class, () -> service.mkdir("/", "../escape")); + } + + @Test + void renamesFileWithoutOverwrite() throws IOException { + Files.writeString(temp.resolve("a.txt"), "a"); + Files.writeString(temp.resolve("b.txt"), "b"); + + ServerFile renamed = service.rename("/a.txt", "/c.txt"); + assertEquals("/c.txt", renamed.getPath()); + assertTrue(Files.exists(temp.resolve("c.txt"))); + assertFalse(Files.exists(temp.resolve("a.txt"))); + assertThrows(TimiException.class, () -> service.rename("/c.txt", "/b.txt")); + assertThrows(TimiException.class, () -> service.rename("/", "/root")); + } + + @Test + void searchesByKeyword() throws IOException { + Files.writeString(temp.resolve("Report.txt"), "a"); + Files.createDirectories(temp.resolve("sub")); + Files.writeString(temp.resolve("sub/report-2026.txt"), "b"); + + FileService.SearchResult result = service.search("/", "report"); + assertEquals(2, result.items().size()); + assertFalse(result.truncated()); + assertTrue(result.scanned() >= 2); + } + + @Test + void opensOnlyRegularFilesAndDeletesRecursively() throws IOException { + Files.createDirectories(temp.resolve("dir/sub")); + Files.writeString(temp.resolve("dir/sub/a.txt"), "a"); + + assertThrows(TimiException.class, () -> service.open("/dir")); + try (var input = service.open("/dir/sub/a.txt")) { + assertEquals('a', input.read()); + } + + service.deletePermanently("/dir"); + assertFalse(Files.exists(temp.resolve("dir"))); + assertThrows(TimiException.class, () -> service.deletePermanently("/")); + } +} diff --git a/src/test/java/com/imyeyu/api/modules/system/service/FileShareServiceTest.java b/src/test/java/com/imyeyu/api/modules/system/service/FileShareServiceTest.java new file mode 100644 index 0000000..fcfe17b --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/system/service/FileShareServiceTest.java @@ -0,0 +1,105 @@ +package com.imyeyu.api.modules.system.service; + +import com.imyeyu.api.modules.system.entity.FileShare; +import com.imyeyu.api.modules.system.mapper.FileShareMapper; +import com.imyeyu.java.bean.timi.TimiException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/// 文件分享服务测试。 +class FileShareServiceTest { + + @TempDir + Path temp; + + private FileStorageService storage; + private FileShareMapper mapper; + private FileShareService service; + + @BeforeEach + void setUp() throws IOException { + storage = FileTestSupport.storage(temp, Map.of( + "SHARE_ENABLED", "true", + "SHARE_DEFAULT_EXPIRE_DAYS", "7" + )); + mapper = mock(FileShareMapper.class); + service = new FileShareService(storage, mapper); + when(mapper.countByToken(anyString())).thenReturn(0); + } + + @Test + void createsAndVerifiesPasswordProtectedShare() throws IOException { + Files.writeString(temp.resolve("a.txt"), "hello"); + FileShare share = service.create("/a.txt", "secret", null, 2, "user-1"); + assertNotNull(share.getToken()); + assertEquals(0L, share.getDeletedAt()); + assertNotNull(share.getPasswordHash()); + assertNotNull(share.getFileHash()); + + when(mapper.selectActiveByToken(share.getToken())).thenReturn(share); + when(mapper.incrementDownload(eq(share.getId()), anyLong())).thenReturn(1); + assertThrows(TimiException.class, () -> service.open(share.getToken(), "wrong")); + assertEquals(share, service.open(share.getToken(), "secret")); + } + + @Test + void rejectsExpiredAndExhaustedShare() throws IOException { + Files.writeString(temp.resolve("a.txt"), "hello"); + FileShare expired = service.create("/a.txt", null, null, 0, "user-1"); + expired.setExpiresAt(System.currentTimeMillis() - 1); + when(mapper.selectActiveByToken(expired.getToken())).thenReturn(expired); + assertThrows(TimiException.class, () -> service.open(expired.getToken(), null)); + + FileShare exhausted = service.create("/a.txt", null, null, 1, "user-1"); + exhausted.setDownloadCount(1); + when(mapper.selectActiveByToken(exhausted.getToken())).thenReturn(exhausted); + assertThrows(TimiException.class, () -> service.open(exhausted.getToken(), null)); + } + + @Test + void rejectsDirectoryShare() { + assertThrows(TimiException.class, () -> service.create("/", null, null, 0, "user-1")); + } + + @Test + void headDoesNotConsumeDownload() throws IOException { + Files.writeString(temp.resolve("a.txt"), "hello"); + FileShare share = service.create("/a.txt", "secret", null, 2, "user-1"); + when(mapper.selectActiveByToken(share.getToken())).thenReturn(share); + + service.open(share.getToken(), "secret", false); + + verify(mapper, never()).incrementDownload(anyString(), anyLong()); + } + + @Test + void rejectsAndInvalidatesChangedFile() throws IOException { + Path file = temp.resolve("a.txt"); + Files.writeString(file, "hello"); + FileShare share = service.create("/a.txt", null, null, 0, "user-1"); + Files.writeString(file, "world"); + Files.setLastModifiedTime(file, java.nio.file.attribute.FileTime.fromMillis(share.getFileModifiedAt() + 1000)); + when(mapper.selectActiveByToken(share.getToken())).thenReturn(share); + + assertThrows(TimiException.class, () -> service.open(share.getToken(), null)); + verify(mapper).softDelete(eq(share.getId()), anyLong()); + } +} diff --git a/src/test/java/com/imyeyu/api/modules/system/service/FileStorageServiceTest.java b/src/test/java/com/imyeyu/api/modules/system/service/FileStorageServiceTest.java new file mode 100644 index 0000000..fddacda --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/system/service/FileStorageServiceTest.java @@ -0,0 +1,104 @@ +package com.imyeyu.api.modules.system.service; + +import com.imyeyu.api.bean.SettingEnum; +import com.imyeyu.api.modules.common.entity.Setting; +import com.imyeyu.api.modules.common.service.SettingService; +import com.imyeyu.api.modules.system.bean.SystemFileSetting; +import com.imyeyu.java.bean.timi.TimiException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.test.util.ReflectionTestUtils; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.abort; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/// 文件存储路径安全测试。 +class FileStorageServiceTest { + + @TempDir + Path temp; + + private FileStorageService storage; + + @BeforeEach + void setUp() throws IOException { + storage = FileTestSupport.storage(temp, Map.of()); + } + + @Test + void initializesWithMissingOptionalSettings() throws Exception { + SettingService settingService = mock(SettingService.class); + when(settingService.getSystem(any())).thenAnswer(invocation -> { + SettingEnum key = invocation.getArgument(0); + if (key == SystemFileSetting.BASE_PATH) { + Setting base = new Setting(); + base.setValue(temp.toString()); + return base; + } + return null; + }); + + FileStorageService service = new FileStorageService(settingService); + ReflectionTestUtils.invokeMethod(service, "initialize"); + + assertEquals(temp.toRealPath(), service.basePath()); + assertTrue(Files.isDirectory(temp.resolve(".trash"))); + assertTrue(Files.isDirectory(temp.resolve(".cache/thumbnails"))); + } + + @Test + void resolvesVirtualPath() { + assertEquals(storage.basePath().resolve("a/b.txt"), storage.resolve("/a/b.txt")); + assertEquals("/a/b.txt", storage.virtualPath(storage.basePath().resolve("a/b.txt"))); + assertEquals("/", storage.virtualPath(storage.basePath())); + } + + @Test + void rejectsTraversalAndRelativePaths() { + assertThrows(TimiException.class, () -> storage.resolve("/../escape.txt")); + assertThrows(TimiException.class, () -> storage.resolve("a.txt")); + assertThrows(TimiException.class, () -> storage.resolve("/a\\b.txt")); + } + + @Test + void rejectsInternalDirectories() { + assertThrows(TimiException.class, () -> storage.resolve("/.trash/a.txt")); + assertThrows(TimiException.class, () -> storage.resolve("/.cache/thumbnails/a.png")); + } + + @Test + void validatesFileNames() { + storage.validateFileName("报告 2026.pdf"); + storage.validateFileName("a.txt"); + + assertThrows(TimiException.class, () -> storage.validateFileName("..")); + assertThrows(TimiException.class, () -> storage.validateFileName("a/b.txt")); + assertThrows(TimiException.class, () -> storage.validateFileName("CON.txt")); + assertThrows(TimiException.class, () -> storage.validateFileName("a:b.txt")); + assertThrows(TimiException.class, () -> storage.validateFileName("a.")); + } + + @Test + void rejectsSymbolicLinks() throws IOException { + Path outside = temp.resolve("outside"); + Files.createDirectories(outside); + Path link = temp.resolve("link"); + try { + Files.createSymbolicLink(link, outside); + } catch (IOException | UnsupportedOperationException e) { + abort("当前环境不支持符号链接"); + } + assertThrows(TimiException.class, () -> storage.resolve("/link/file.txt")); + } +} diff --git a/src/test/java/com/imyeyu/api/modules/system/service/FileTestSupport.java b/src/test/java/com/imyeyu/api/modules/system/service/FileTestSupport.java new file mode 100644 index 0000000..c8f112e --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/system/service/FileTestSupport.java @@ -0,0 +1,61 @@ +package com.imyeyu.api.modules.system.service; + +import com.imyeyu.api.bean.SettingEnum; +import com.imyeyu.api.modules.common.entity.Setting; +import com.imyeyu.api.modules.common.service.SettingService; +import org.springframework.test.util.ReflectionTestUtils; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/// 文件模块测试用存储环境。 +public final class FileTestSupport { + + private FileTestSupport() { + } + + public static FileStorageService storage(Path base, Map values) throws IOException { + Path realBase = base.toRealPath(); + Map settings = new HashMap<>(values); + settings.putIfAbsent("BASE_PATH", realBase.toString()); + settings.putIfAbsent("TRASH_PATH", ".trash"); + settings.putIfAbsent("THUMBNAIL_PATH", ".cache/thumbnails"); + settings.putIfAbsent("TRASH_RETENTION_DAYS", "30"); + settings.putIfAbsent("SEARCH_MAX_RESULTS", "200"); + settings.putIfAbsent("SEARCH_MAX_DEPTH", "32"); + settings.putIfAbsent("SEARCH_TIMEOUT_SECONDS", "5"); + settings.putIfAbsent("UPLOAD_MAX_SIZE", String.valueOf(1024L * 1024 * 1024)); + settings.putIfAbsent("UPLOAD_CHUNK_SIZE", String.valueOf(8L * 1024 * 1024)); + settings.putIfAbsent("SHARE_ENABLED", "true"); + settings.putIfAbsent("SHARE_DEFAULT_EXPIRE_DAYS", "7"); + + SettingService settingService = mock(SettingService.class); + when(settingService.getSystem(any())).thenAnswer(invocation -> { + SettingEnum key = invocation.getArgument(0); + String value = settings.get(key.name()); + if (value == null) { + return null; + } + Setting setting = new Setting(); + setting.setValue(value); + return setting; + }); + + FileStorageService storage = new FileStorageService(settingService); + ReflectionTestUtils.setField(storage, "basePath", realBase); + Path trash = realBase.resolve(".trash"); + Path thumbnail = realBase.resolve(".cache/thumbnails"); + Files.createDirectories(trash); + Files.createDirectories(thumbnail); + ReflectionTestUtils.setField(storage, "trashPath", trash); + ReflectionTestUtils.setField(storage, "thumbnailPath", thumbnail); + return storage; + } +} diff --git a/src/test/java/com/imyeyu/api/modules/system/service/FileTrashServiceTest.java b/src/test/java/com/imyeyu/api/modules/system/service/FileTrashServiceTest.java new file mode 100644 index 0000000..fc29ae7 --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/system/service/FileTrashServiceTest.java @@ -0,0 +1,67 @@ +package com.imyeyu.api.modules.system.service; + +import com.imyeyu.api.modules.system.entity.FileTrash; +import com.imyeyu.api.modules.system.mapper.FileTrashMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/// 回收站服务测试。 +class FileTrashServiceTest { + + @TempDir + Path temp; + + private FileStorageService storage; + private FileTrashMapper mapper; + private FileTrashService service; + + @BeforeEach + void setUp() throws IOException { + storage = FileTestSupport.storage(temp, Map.of("TRASH_RETENTION_DAYS", "30")); + mapper = mock(FileTrashMapper.class); + service = new FileTrashService(storage, mapper); + } + + @Test + void movesFileToTrashAndRestoresIt() throws IOException { + Files.writeString(temp.resolve("a.txt"), "hello"); + List records = service.trash(List.of("/a.txt"), "user-1"); + assertEquals(1, records.size()); + assertFalse(Files.exists(temp.resolve("a.txt"))); + + FileTrash record = records.getFirst(); + record.setId("trash-1"); + assertTrue(Files.exists(storage.trashPath().resolve(record.getTrashName()))); + when(mapper.selectActive(eq("trash-1"), anyLong())).thenReturn(record); + + var restored = service.restore("trash-1"); + assertEquals("/a.txt", restored.getPath()); + assertEquals("hello", Files.readString(temp.resolve("a.txt"))); + } + + @Test + void purgesTrashItem() throws IOException { + Files.writeString(temp.resolve("a.txt"), "hello"); + FileTrash record = service.trash(List.of("/a.txt"), "user-1").getFirst(); + record.setId("trash-2"); + when(mapper.selectActive(eq("trash-2"), anyLong())).thenReturn(record); + + service.purge("trash-2"); + assertFalse(Files.exists(storage.trashPath().resolve(record.getTrashName()))); + } +} diff --git a/src/test/java/com/imyeyu/api/modules/system/service/FileUploadServiceTest.java b/src/test/java/com/imyeyu/api/modules/system/service/FileUploadServiceTest.java new file mode 100644 index 0000000..9e00fa2 --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/system/service/FileUploadServiceTest.java @@ -0,0 +1,113 @@ +package com.imyeyu.api.modules.system.service; + +import com.imyeyu.api.modules.system.bean.ServerFile; +import com.imyeyu.java.bean.timi.TimiException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.util.ReflectionTestUtils; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/// 文件上传服务测试。 +class FileUploadServiceTest { + + @TempDir + Path temp; + + private FileUploadService service; + + @BeforeEach + void setUp() throws IOException { + FileStorageService storage = FileTestSupport.storage(temp, Map.of( + "UPLOAD_MAX_SIZE", "1048576", + "UPLOAD_CHUNK_SIZE", "4" + )); + service = new FileUploadService(storage); + } + + @Test + void uploadsAndRejectsDuplicate() { + MockMultipartFile file = new MockMultipartFile("file", "a.txt", "text/plain", + "hello".getBytes(StandardCharsets.UTF_8)); + ServerFile result = service.upload("/", "a.txt", file, false); + assertEquals("/a.txt", result.getPath()); + assertThrows(TimiException.class, () -> service.upload("/", "a.txt", file, false)); + + assertThrows(TimiException.class, () -> service.upload("/", "../escape.txt", file, false)); + } + + @Test + void completesChunkedUpload() throws IOException { + FileUploadService.UploadInit init = service.init("/", "b.txt", 10, null); + assertEquals(3, init.totalChunks()); + service.chunk(init.uploadId(), 0, chunk("0123")); + service.chunk(init.uploadId(), 1, chunk("4567")); + service.chunk(init.uploadId(), 2, chunk("89")); + + ServerFile result = service.complete(init.uploadId(), null); + assertEquals("/b.txt", result.getPath()); + assertEquals("0123456789", Files.readString(temp.resolve("b.txt"))); + } + + @Test + void rejectsWrongSizeAndCleansMergedTemp() throws IOException { + FileUploadService.UploadInit init = service.init("/", "short.txt", 7, null); + service.chunk(init.uploadId(), 0, chunk("0123")); + service.chunk(init.uploadId(), 1, chunk("45")); + + assertThrows(TimiException.class, () -> service.complete(init.uploadId(), null)); + assertEquals(0, uploadTempCount()); + } + + @Test + void rejectsChecksumAndCleansMergedTemp() throws IOException { + FileUploadService.UploadInit init = service.init("/", "checksum.txt", 4, "deadbeef"); + service.chunk(init.uploadId(), 0, chunk("0123")); + + assertThrows(TimiException.class, () -> service.complete(init.uploadId(), null)); + assertEquals(0, uploadTempCount()); + } + + @Test + void rejectsOversizedChunk() { + FileUploadService.UploadInit init = service.init("/", "chunk.txt", 4, null); + + assertThrows(TimiException.class, () -> service.chunk(init.uploadId(), 0, chunk("01234"))); + } + + @Test + @SuppressWarnings("unchecked") + void cleansExpiredSessions() throws IOException { + FileUploadService.UploadInit init = service.init("/", "c.txt", 4, null); + Map sessions = (Map) ReflectionTestUtils.getField(service, "sessions"); + Object session = sessions.get(init.uploadId()); + Path directory = (Path) ReflectionTestUtils.getField(session, "directory"); + ReflectionTestUtils.setField(session, "lastAccessAt", 0L); + + service.cleanupExpiredSessions(); + + assertFalse(sessions.containsKey(init.uploadId())); + assertFalse(Files.exists(directory)); + } + + private long uploadTempCount() throws IOException { + try (var files = Files.list(temp)) { + return files.filter(path -> path.getFileName().toString().startsWith(".upload-")).count(); + } + } + + private MockMultipartFile chunk(String value) { + return new MockMultipartFile("file", "chunk", "application/octet-stream", + value.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/src/test/java/com/imyeyu/api/modules/system/task/async/FileArchiveTaskTest.java b/src/test/java/com/imyeyu/api/modules/system/task/async/FileArchiveTaskTest.java new file mode 100644 index 0000000..dd42f15 --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/system/task/async/FileArchiveTaskTest.java @@ -0,0 +1,90 @@ +package com.imyeyu.api.modules.system.task.async; + +import com.imyeyu.api.modules.system.service.FileStorageService; +import com.imyeyu.api.modules.system.service.FileTestSupport; +import com.imyeyu.api.modules.user.service.PermissionChecker; +import com.imyeyu.java.bean.timi.TimiException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class FileArchiveTaskTest { + + @TempDir + Path temp; + + private FileStorageService storage; + private PermissionChecker permissionChecker; + + @BeforeEach + void setUp() throws Exception { + storage = FileTestSupport.storage(temp, java.util.Map.of()); + permissionChecker = mock(PermissionChecker.class); + when(permissionChecker.codeSet("user")).thenReturn(Set.of( + "CORE:FILE:READ", + "CORE:FILE:WRITE", + "CORE:FILE:DELETE" + )); + } + + @Test + void zipThenUnzipRoundTrip() throws Exception { + Files.createDirectories(temp.resolve("src/empty")); + Files.createDirectories(temp.resolve("src/sub")); + Files.writeString(temp.resolve("src/a.txt"), "hello"); + Files.writeString(temp.resolve("src/sub/b.txt"), "world"); + + new FileZipAsyncTask(List.of("/src"), "/src.zip", storage, permissionChecker, "user").run(); + + assertTrue(Files.isRegularFile(temp.resolve("src.zip"))); + assertTrue(Files.size(temp.resolve("src.zip")) > 0); + + new FileUnZipAsyncTask("/src.zip", "/out", storage, permissionChecker, "user").run(); + + assertEquals("hello", Files.readString(temp.resolve("out/src/a.txt"))); + assertEquals("world", Files.readString(temp.resolve("out/src/sub/b.txt"))); + assertTrue(Files.isDirectory(temp.resolve("out/src/empty"))); + } + + @Test + void zipRejectsTargetInsideSource() throws Exception { + Files.createDirectories(temp.resolve("src")); + Files.writeString(temp.resolve("src/a.txt"), "hello"); + + FileZipAsyncTask task = new FileZipAsyncTask(List.of("/src"), "/src/out.zip", storage, permissionChecker, "user"); + + assertThrows(TimiException.class, task::run); + assertFalse(Files.exists(temp.resolve("src/out.zip"))); + } + + @Test + void unzipRejectsTraversal() throws Exception { + Path zip = temp.resolve("bad.zip"); + try (OutputStream output = Files.newOutputStream(zip); + ZipOutputStream zipOutput = new ZipOutputStream(output)) { + zipOutput.putNextEntry(new ZipEntry("../evil.txt")); + zipOutput.write("evil".getBytes(java.nio.charset.StandardCharsets.UTF_8)); + zipOutput.closeEntry(); + } + + FileUnZipAsyncTask task = new FileUnZipAsyncTask("/bad.zip", "/out", storage, permissionChecker, "user"); + + assertThrows(TimiException.class, task::run); + assertFalse(Files.exists(temp.resolve("evil.txt"))); + } +} diff --git a/src/test/java/com/imyeyu/api/modules/system/task/async/FileCalcSizeAsyncTaskTest.java b/src/test/java/com/imyeyu/api/modules/system/task/async/FileCalcSizeAsyncTaskTest.java new file mode 100644 index 0000000..2f63a36 --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/system/task/async/FileCalcSizeAsyncTaskTest.java @@ -0,0 +1,65 @@ +package com.imyeyu.api.modules.system.task.async; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.imyeyu.api.modules.system.service.FileStorageService; +import com.imyeyu.api.modules.system.service.FileTestSupport; +import com.imyeyu.api.modules.user.service.PermissionChecker; +import com.imyeyu.java.bean.timi.TimiException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class FileCalcSizeAsyncTaskTest { + + @TempDir + Path temp; + + @Test + void countsFilesAndSkipsInternalDirectories() throws Exception { + Files.createDirectories(temp.resolve("data/sub")); + Files.writeString(temp.resolve("data/a.txt"), "abc"); + Files.writeString(temp.resolve("data/sub/b.txt"), "12345"); + Files.createDirectories(temp.resolve(".trash")); + Files.writeString(temp.resolve(".trash/ignored.txt"), "must not count"); + + FileStorageService storage = FileTestSupport.storage(temp, Map.of()); + PermissionChecker checker = mock(PermissionChecker.class); + when(checker.codeSet("user")).thenReturn(Set.of("CORE:FILE:READ")); + + FileCalcSizeAsyncTask task = new FileCalcSizeAsyncTask("/", storage, checker, "user"); + task.run(); + + JsonNode result = new ObjectMapper().readTree(task.getResult()); + assertEquals(8, result.get("bytes").asLong()); + assertEquals(2, result.get("files").asLong()); + assertTrue(result.get("directories").asLong() >= 3); + assertEquals(0, result.get("failed").asLong()); + } + + @Test + void rejectsFilesAndMissingPermission() throws Exception { + Files.writeString(temp.resolve("a.txt"), "abc"); + FileStorageService storage = FileTestSupport.storage(temp, Map.of()); + + PermissionChecker checker = mock(PermissionChecker.class); + when(checker.codeSet("user")).thenReturn(Set.of("CORE:FILE:READ")); + FileCalcSizeAsyncTask fileTask = new FileCalcSizeAsyncTask("/a.txt", storage, checker, "user"); + assertThrows(TimiException.class, fileTask::run); + + PermissionChecker noPermission = mock(PermissionChecker.class); + when(noPermission.codeSet("user")).thenReturn(Set.of()); + FileCalcSizeAsyncTask deniedTask = new FileCalcSizeAsyncTask("/", storage, noPermission, "user"); + assertThrows(TimiException.class, deniedTask::run); + } +} diff --git a/src/test/java/com/imyeyu/api/modules/system/task/async/FileTaskSupportTest.java b/src/test/java/com/imyeyu/api/modules/system/task/async/FileTaskSupportTest.java new file mode 100644 index 0000000..a530f57 --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/system/task/async/FileTaskSupportTest.java @@ -0,0 +1,84 @@ +package com.imyeyu.api.modules.system.task.async; + +import com.imyeyu.api.bean.CorePermissionCode; +import com.imyeyu.api.modules.system.service.FileStorageService; +import com.imyeyu.api.modules.system.service.FileTestSupport; +import com.imyeyu.api.modules.user.service.PermissionChecker; +import com.imyeyu.java.bean.timi.TimiException; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/// 异步任务公共辅助测试。 +class FileTaskSupportTest { + + @TempDir + Path temp; + + @Test + void collectsEmptyDirectories() throws IOException { + FileStorageService storage = FileTestSupport.storage(temp, Map.of()); + Files.createDirectories(temp.resolve("a/b")); + + List sources = FileTaskSupport.sources(storage, List.of("/a")); + List entries = FileTaskSupport.collect(sources, null); + + assertEquals(2, entries.size()); + assertTrue(entries.stream().anyMatch(entry -> entry.name().equals("a") && entry.directory())); + assertTrue(entries.stream().anyMatch(entry -> entry.name().equals("a/b") && entry.directory())); + } + + @Test + void rejectsNestedDestination() throws IOException { + FileStorageService storage = FileTestSupport.storage(temp, Map.of()); + Files.createDirectories(temp.resolve("a")); + + Path source = storage.resolveExisting("/a"); + Path destination = storage.resolve("/a/out"); + + assertThrows(TimiException.class, () -> FileTaskSupport.ensureNotNested(source, destination)); + } + + @Test + void requiresEveryPermission() { + PermissionChecker checker = mock(PermissionChecker.class); + when(checker.codeSet("u")).thenReturn(Set.of("CORE:FILE:READ")); + + assertDoesNotThrow(() -> FileTaskSupport.require(checker, "u", CorePermissionCode.FILE_READ)); + assertThrows(TimiException.class, () -> FileTaskSupport.require(checker, "u", + CorePermissionCode.FILE_READ, CorePermissionCode.FILE_WRITE)); + assertThrows(TimiException.class, () -> FileTaskSupport.require(checker, " ", CorePermissionCode.FILE_READ)); + } + + @Test + void rejectsSymlinkSources() throws IOException { + FileStorageService storage = FileTestSupport.storage(temp, Map.of()); + Path outside = temp.resolve("outside"); + Files.createDirectories(outside); + Files.createDirectories(temp.resolve("a")); + Path link = temp.resolve("a/link"); + try { + Files.createSymbolicLink(link, outside); + } catch (UnsupportedOperationException | IOException e) { + Assumptions.assumeTrue(false, "当前文件系统不支持符号链接"); + return; + } + + List sources = FileTaskSupport.sources(storage, List.of("/a")); + assertThrows(TimiException.class, () -> FileTaskSupport.collect(sources, null)); + } +} From dc5f62fd932ad3c1cc5991a017a2e61c65285a0d Mon Sep 17 00:00:00 2001 From: Timi Date: Wed, 25 Nov 2026 01:23:26 +0800 Subject: [PATCH 4/6] chore: remove serena project config --- .serena/.gitignore | 2 - .serena/memories/project_overview.md | 1 - .serena/memories/style_conventions.md | 1 - .serena/memories/suggested_commands.md | 1 - .serena/memories/task_completion.md | 1 - .serena/project.yml | 195 ------------------------- 6 files changed, 201 deletions(-) delete mode 100644 .serena/.gitignore delete mode 100644 .serena/memories/project_overview.md delete mode 100644 .serena/memories/style_conventions.md delete mode 100644 .serena/memories/suggested_commands.md delete mode 100644 .serena/memories/task_completion.md delete mode 100644 .serena/project.yml diff --git a/.serena/.gitignore b/.serena/.gitignore deleted file mode 100644 index 2e510af..0000000 --- a/.serena/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/cache -/project.local.yml diff --git a/.serena/memories/project_overview.md b/.serena/memories/project_overview.md deleted file mode 100644 index 63e6088..0000000 --- a/.serena/memories/project_overview.md +++ /dev/null @@ -1 +0,0 @@ -TimiServerAPI 是一个基于 Spring Boot 的高耦合业务后端服务,代码位于 src/main/java/com/imyeyu/api,下分多个业务模块,如 blog、common、gitea、forevermc、journal、minecraft、music、system 等。项目使用多数据源 MySQL(timiserver、gitea、forevermc)、MongoDB、Redis、MyBatis,并引入 Flyway 做数据库迁移。运行环境为 Windows,JDK 21。 \ No newline at end of file diff --git a/.serena/memories/style_conventions.md b/.serena/memories/style_conventions.md deleted file mode 100644 index 95cdb34..0000000 --- a/.serena/memories/style_conventions.md +++ /dev/null @@ -1 +0,0 @@ -项目约定:全部沟通、注释、文档使用中文;Java 使用 tab 缩进;注释要求符合 javadoc;优先使用官方 API,不随意引入外部依赖;字符串优先用 formatted(),长动态字符串用 StringBuilder;优先用代码级工具做精确修改;避免盲目通读大文件,先缩小目录和符号范围。 \ No newline at end of file diff --git a/.serena/memories/suggested_commands.md b/.serena/memories/suggested_commands.md deleted file mode 100644 index e062710..0000000 --- a/.serena/memories/suggested_commands.md +++ /dev/null @@ -1 +0,0 @@ -Windows / PowerShell 常用命令:`Get-ChildItem -Force` 查看目录,`rg --files` 列文件,`rg -n "PATTERN" PATH` 搜索文本,`mvn -q -DskipTests compile` 做基础编译验证,`git diff -- PATH` 查看改动。配置文件主要在 `src/main/resources`,Java 源码在 `src/main/java`。 \ No newline at end of file diff --git a/.serena/memories/task_completion.md b/.serena/memories/task_completion.md deleted file mode 100644 index eb628b9..0000000 --- a/.serena/memories/task_completion.md +++ /dev/null @@ -1 +0,0 @@ -完成任务后,优先做最小范围验证。Java 侧先尝试 `mvn -q -DskipTests compile`;如果失败,区分是本次改动导致还是项目已有编译问题。不要回滚用户已有改动,不要做破坏性 git 操作。多数据源场景要特别检查 `@Primary`、`@Qualifier` 和自动装配框架(如 Flyway)的绑定关系。 \ No newline at end of file diff --git a/.serena/project.yml b/.serena/project.yml deleted file mode 100644 index f50829f..0000000 --- a/.serena/project.yml +++ /dev/null @@ -1,195 +0,0 @@ -# the name by which the project can be referenced within Serena/when chatting with the LLM. -project_name: "TimiServerAPI" - -# the encoding used by text files in the project -# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings -encoding: "utf-8" - -# line ending convention to use when writing source files. -# Possible values: unset (use global setting), "lf", "crlf", or "native" (platform default) -# This does not affect Serena's own files (e.g. memories and configuration files), which always use native line endings. -line_ending: - -# The language backend to use for this project. -# If not set, the global setting from serena_config.yml is used. -# Valid values: LSP, JetBrains -# Note: the backend is fixed at startup. If a project with a different backend -# is activated post-init, an error will be returned. -language_backend: - -# whether to use project's .gitignore files to ignore files -ignore_all_files_in_gitignore: true - -# advanced configuration option allowing to configure language server-specific options. -# Maps the language key to the options. -# The settings are considered only if the project is trusted (see global configuration to define trusted projects). -# See https://oraios.github.io/serena/02-usage/050_configuration.html#language-server-specific-settings -ls_specific_settings: {} - -# list of additional paths to ignore in this project. -# Same syntax as gitignore, so you can use * and **. -# Important: quote patterns that start with `*`, otherwise YAML treats them as aliases. -# Example: -# ignored_paths: -# - "examples/**" -# - ".worktrees/**" -# - "**/bin/**" -# - "**/obj/**" -# Note: global ignored_paths from serena_config.yml are also applied additively. -ignored_paths: [] - -# whether the project is in read-only mode -# If set to true, all editing tools will be disabled and attempts to use them will result in an error -# Added on 2025-04-18 -read_only: false - -# list of tool names to exclude. -# This extends the existing exclusions (e.g. from the global configuration) -# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html -excluded_tools: [] - -# list of tools to include that would otherwise be disabled (particularly optional tools that are disabled by default). -# This extends the existing inclusions (e.g. from the global configuration). -# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html -included_optional_tools: [] - -# fixed set of tools to use as the base tool set (if non-empty), replacing Serena's default set of tools. -# This cannot be combined with non-empty excluded_tools or included_optional_tools. -# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html -fixed_tools: [] - -# list of mode names to that are always to be included in the set of active modes -# The full set of modes to be activated is base_modes + default_modes. -# If the setting is undefined, the base_modes from the global configuration (serena_config.yml) apply. -# Otherwise, this setting overrides the global configuration. -# Set this to [] to disable base modes for this project. -# Set this to a list of mode names to always include the respective modes for this project. -base_modes: - -# list of mode names that are to be activated by default, overriding the setting in the global configuration. -# The full set of modes to be activated is base_modes (from global config) + default_modes + added_modes. -# If the setting is undefined/empty, the default_modes from the global configuration (serena_config.yml) apply. -# Otherwise, this overrides the setting from the global configuration (serena_config.yml). -# Therefore, you can set this to [] if you do not want the default modes defined in the global config to apply -# for this project. -# This setting can, in turn, be overridden by CLI parameters (--mode). -# See https://oraios.github.io/serena/02-usage/050_configuration.html#modes -default_modes: - -# initial prompt for the project. It will always be given to the LLM upon activating the project -# (contrary to the memories, which are loaded on demand). -initial_prompt: "" - -# time budget (seconds) per tool call for the retrieval of additional symbol information -# such as docstrings or parameter information. -# This overrides the corresponding setting in the global configuration; see the documentation there. -# If null or missing, use the setting from the global configuration. -symbol_info_budget: - -# list of regex patterns which, when matched, mark a memory entry as read‑only. -# Extends the list from the global configuration, merging the two lists. -read_only_memory_patterns: [] - -# list of regex patterns for memories to completely ignore. -# Matching memories will not appear in list_memories or activate_project output -# and cannot be accessed via read_memory or write_memory. -# To access ignored memory files, use the read_file tool on the raw file path. -# Extends the list from the global configuration, merging the two lists. -# Example: ["_archive/.*", "_episodes/.*"] -ignored_memory_patterns: [] - -# list of language servers to start when using the LSP backend; choose from: -# ada al angular ansible astro -# bash bsl clojure cpp cpp_ccls -# crystal csharp csharp_omnisharp cue dart -# deno elixir elm erlang fortran -# fsharp gdscript gleam go groovy -# haskell haxe hlsl html java -# json julia julia_fatou kotlin latex -# lean4 lua lua_emmylua luau markdown -# matlab msl nextflow nix ocaml -# pascal perl php php_devsense php_phpactor -# php_phpantom powershell python python_basedpyright python_jedi -# python_pyrefly python_ty qml r rego -# ruby ruby_solargraph rust scala scss -# solidity svelte swift systemverilog terraform -# toml typescript typescript_tsgo typescript_vts vue -# vbnet wolfram yaml zig -# (This list may be outdated; generated with scripts/print_language_list.py; -# For the current list, see values of the LanguageServerId enum here: -# https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py) -# For some languages, there are several alternative language servers, e.g. csharp_omnisharp, ruby_solargraph.) -# Note: -# - For C, use cpp -# - For JavaScript, use typescript -# - For Angular projects, use angular (subsumes typescript+html; requires `npm install` in the project root) -# - For Astro projects, use astro (subsumes typescript/javascript for .astro projects; requires npm) -# - For Svelte projects, use svelte (subsumes typescript/javascript for .svelte projects; requires npm) -# - For Deno projects, use deno (serves the same .ts/.js files as typescript; requires the deno CLI on PATH) -# - For SCSS / Sass / plain CSS, use scss (some-sass-language-server handles all three) -# - For Free Pascal/Lazarus, use pascal -# - External Python adapters may add further registered IDs; install the adapter package first -# and then use its ID here, for example: example -# Special requirements: -# Some language servers require additional setup/installations. -# See here for details: https://oraios.github.io/serena/01-about/020_programming-languages.html#language-servers -# When using multiple language servers, the first language server that supports a given file will be used for that file. -# The first language server is the default language and the respective language server will be used as a fallback. -# Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored. -language_servers: -- java - -# list of mode names to be activated additionally for this project, e.g. ["query-projects"] -# The full set of modes to be activated is base_modes (from global config) + default_modes + added_modes. -# See https://oraios.github.io/serena/02-usage/050_configuration.html#modes -added_modes: - -# list of workspace folder paths (LSP backend only). -# These folders will be used to build up Serena's symbol index. -# Paths must be within the project root and should thus be relative to the project root. -# Furthermore, the paths should not be filtered by ignore settings. -# Default setting: The entire project root folder (".") is considered. -# In (large) monorepos, this can be used to index only subfolders of the project root, e.g. -# ls_workspace_folders: -# - "./subproject1" -# - "./subproject2" -ls_workspace_folders: -- . - -# list of additional workspace folder paths for cross-package reference support. -# Paths can be absolute or relative to the project root. -# Each folder is registered as an LSP workspace folder, enabling language servers to discover -# symbols and references across package boundaries, but these folders are not indexed by Serena, -# i.e. the respective symbols will not be found using Serena's symbol search tools. -# Example: -# additional_workspace_folders: -# - ../sibling-package -# - ../shared-lib -ls_additional_workspace_folders: [] - -# optional shell command to run before the language backend (LSP or JetBrains) is initialised. -# the command runs in the project root directory and is only executed if the project is trusted -# (see trusted_project_path_patterns in the global configuration). -# serena waits for the command to exit: a non-zero exit code is logged as an error but does not -# abort activation. a per-project timeout (activation_command_timeout, default 180s) is the safety -# backstop for non-terminating commands; on expiry the process is killed and activation continues. -# example: activation_command: "npx nx run-many -t build" -activation_command: - -# maximum time in seconds to wait for activation_command to complete before killing it (default 180s). -# must be a positive number. -activation_command_timeout: 180.0 - -# list of APIs (facades or facade methods, e.g. "lsp" or "lsp.get_diagnostics_for_symbol") to include in the REPL -# that would otherwise be disabled (particularly optional methods, which are disabled by default). -# This extends the existing inclusions (e.g. from the global configuration). -included_apis: [] - -# list of APIs (facades or facade methods, e.g. "lsp" or "lsp.find_symbol") to exclude from the REPL. -# This extends the existing exclusions (e.g. from the global configuration). -excluded_apis: [] - -# The interface through which the agent (LLM) accesses Serena's functionality (overrides the global setting). -# Valid values: tools, REPL (see the global configuration for details); leave empty to use the global setting. -# Note: the interface is fixed at startup. If a project is activated post-init, its setting is not applied. -agent_interface: From aefc0ad205ae2aa8b271738b2f976af58197f743 Mon Sep 17 00:00:00 2001 From: Timi Date: Wed, 25 Nov 2026 01:23:30 +0800 Subject: [PATCH 5/6] feat(openapi): integrate springdoc and API integration guide - add springdoc-openapi and expose /v3/api-docs, /v3/api-docs.yaml and Swagger UI - keep API docs responses unwrapped by replacing the global return handler - add Chinese @Tag/@Operation/@Parameter docs for file and async task controllers - add docs/api-integration.md and local export scripts for AI agent consumption - ignore local OpenAPI snapshots and force LF for shell scripts --- .gitattributes | 2 + .gitignore | 4 + docs/.gitkeep | 0 docs/api-integration.md | 271 ++++++++++++++++++ pom.xml | 5 + scripts/export-openapi.ps1 | 50 ++++ scripts/export-openapi.sh | 30 ++ .../com/imyeyu/api/config/OpenApiConfig.java | 96 +++++++ .../config/OpenApiGlobalReturnHandler.java | 28 ++ .../controller/AsyncTaskController.java | 35 ++- .../controller/FileArchiveController.java | 9 + .../controller/FileContentController.java | 22 +- .../system/controller/FileController.java | 28 +- .../controller/FileShareController.java | 21 +- .../controller/FileTrashController.java | 13 +- .../controller/FileUploadController.java | 20 +- src/main/resources/application.yml | 6 + 17 files changed, 623 insertions(+), 17 deletions(-) create mode 100644 .gitattributes create mode 100644 docs/.gitkeep create mode 100644 docs/api-integration.md create mode 100644 scripts/export-openapi.ps1 create mode 100644 scripts/export-openapi.sh create mode 100644 src/main/java/com/imyeyu/api/config/OpenApiConfig.java create mode 100644 src/main/java/com/imyeyu/api/config/OpenApiGlobalReturnHandler.java diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..90e7d87 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Shell 脚本使用 LF,避免 Windows 下 CRLF 导致执行失败 +*.sh text eol=lf diff --git a/.gitignore b/.gitignore index 5347943..d59dc5e 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,10 @@ /AGENTS.md /.workbuddy +# OpenAPI 本地导出(scripts/export-openapi.*) +/docs/openapi.local.yaml +/docs/openapi.local.json + multilingualField/ !.mvn/wrapper/maven-wrapper.jar !**/src/main/**/multilingualField/ diff --git a/docs/.gitkeep b/docs/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/docs/api-integration.md b/docs/api-integration.md new file mode 100644 index 0000000..a000af3 --- /dev/null +++ b/docs/api-integration.md @@ -0,0 +1,271 @@ +# TimiServerAPI 接口对接说明 + +> 接口的路径、方法、参数、请求体、响应体以 `docs/openapi.local.yaml` 为准。本文只补充 OpenAPI 无法完整表达的横切约定:统一响应包装、鉴权、错误码、分页、二进制响应与 SSE。 +> +> 本文不重复 OpenAPI 中的接口清单和字段说明。 + +- 服务版本:`1.0.79` +- OpenAPI 版本:`3.1.0` +- 默认本地地址:`http://localhost:18092`(无 context-path) +- OpenAPI JSON:`/v3/api-docs` +- OpenAPI YAML:`/v3/api-docs.yaml` +- Swagger UI:`/swagger-ui.html` + +--- + +## 1. 文档快照与覆盖范围 + +### 1.1 导出本地快照 + +仓库提供两个导出脚本,默认输出 `docs/openapi.local.yaml`: + +```powershell +# PowerShell +.\scripts\export-openapi.ps1 + +# 指定地址与文件名(.json 后缀会导出 JSON) +.\scripts\export-openapi.ps1 -BaseUrl http://192.168.1.10:18092 -OutFile docs\openapi.local.json +``` + +```bash +# Bash +bash scripts/export-openapi.sh + +bash scripts/export-openapi.sh http://192.168.1.10:18092 docs/openapi.local.json +``` + +`docs/openapi.local.*` 是本地快照,已在 `.gitignore` 中忽略,不应提交。需要给远程 AI Agent 使用时,优先发送该文件,而不是 `localhost` 地址。 + +### 1.2 覆盖范围说明 + +SpringDoc 会扫描项目中的全部 Controller,因此 OpenAPI 文件里会包含用户、标签、系统设置等模块的接口。本次只对文件模块与异步任务模块的 7 个 Controller 补充了完整的中文 `@Tag` / `@Operation` / `@Parameter` 描述;这些接口的路径、参数、请求体和响应结构均已包含在 OpenAPI 中。其他模块的接口属于 SpringDoc 自动生成的基础描述,业务语义可能不完整,复杂接口请结合源码或联调确认。 + +OpenAPI 中还声明了全局 `Token` 安全要求,但登录、注册等公开接口实际可能不需要登录。**是否需要鉴权以接口实际行为为准**;公开接口已在 OpenAPI 中按操作单独标记 `security`。 + +--- + +## 2. 基础约定 + +### 2.1 请求格式 + +- 普通接口:`Content-Type: application/json` +- 上传类接口:`multipart/form-data` +- 字符编码:UTF-8 +- 时间字段:除特别说明外,均为 **epoch 毫秒**(`long`) +- 大小字段:字节(`long`) + +### 2.2 鉴权 + +请求头优先使用: + +```http +Token: <登录令牌或 API Key> +``` + +服务端也兼容以下写法: + +```http +token: <登录令牌或 API Key> +``` + +以及 URL 参数: + +```text +?token=<登录令牌或 API Key> +``` + +> 生产环境建议只使用 `Token` 请求头。URL 参数容易进入访问日志、浏览器历史和 Referer。 +> +> 浏览器原生 `EventSource` 不能设置自定义请求头,SSE 场景才使用 `?token=`。 + +支持两种凭证: + +1. **登录令牌**:通过登录接口获取,具体接口见 OpenAPI。 +2. **API Key**:以 `tk_` 开头,格式为 `tk_<8位十六进制>_<32位十六进制>`。API Key 创建后只返回一次明文,不能用于管理 API Key 本身。 + +### 2.3 统一响应包装(TimiResponse) + +除二进制、SSE 等特殊接口外,所有 JSON 接口都会被统一包装为: + +```json +{ + "code": 20000, + "message": "可选,面向用户的提示", + "messageCode": "可选,国际化消息键", + "data": {} +} +``` + +字段说明: + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `code` | number | 业务代码,**不是 HTTP 状态码** | +| `message` | string | 提示信息,可能根据语言返回不同文案 | +| `messageCode` | string | 国际化消息键,可能不存在 | +| `data` | any | 业务数据;为 `null` 时通常被省略 | + +判断成功请使用: + +```ts +const success = response.code <= 30000; // 20000 成功,20001 表示成功但忽略请求 +``` + +不要只根据 HTTP 状态码判断业务结果。普通 JSON 接口即使业务失败,HTTP 状态通常仍是 `200`。 + +### 2.4 错误码 + +| code | 含义 | +| --- | --- | +| `20000` | 成功 | +| `20001` | 成功,忽略请求 | +| `40000` | 缺少参数 / 未登录 | +| `40001` | 参数不合法 | +| `40002` | 参数已过期 | +| `40100` | 无权限 | +| `40101` | 权限错误 | +| `40102` | 非法请求 / 请求过于频繁 | +| `40301` | 数据已存在 | +| `40400` | 数据不存在 | +| `40401` | 返回数据异常 | +| `40402` | 数据被禁用 | +| `40403` | 上游服务超时 | +| `50000` | 服务异常 | +| `50001` | 不支持的操作 | +| `50002` | 服务内部变量缺失 | +| `50003` | 服务已关闭 | +| `50300` | 服务繁忙 | + +### 2.5 多语言 + +可通过以下任一方式指定语言: + +```http +Accept-Language: zh-CN +``` + +```text +?lang=zh_CN +``` + +默认 `zh_CN`。 + +### 2.6 分页 + +分页接口的请求体通常是 `Page`: + +```json +{ + "index": 0, + "size": 16, + "equalsExample": {}, + "likesExample": {}, + "equalsLogic": "AND", + "likesLogic": "OR", + "orderMap": { + "created_at": "DESC" + } +} +``` + +- `index`:页码,**从 0 开始**,默认 `0` +- `size`:每页数量,默认 `16`;部分接口会限制最大值(例如 100) +- `equalsExample`:精确匹配示例 +- `likesExample`:模糊匹配示例 +- `equalsLogic`:精确条件连接方式,`AND` / `OR` +- `likesLogic`:模糊条件连接方式,`AND` / `OR` +- `orderMap`:排序字段与方向,字段通常使用数据库下划线命名 + +分页响应通常是 `PageResult`: + +```json +{ + "total": 128, + "pages": 8, + "list": [], + "empty": false, + "notEmpty": true +} +``` + +--- + +## 3. 特殊响应类型 + +### 3.1 二进制响应 + +部分接口直接返回二进制数据或字节流,不经过 `TimiResponse`: + +- 成功时直接返回字节流 +- 失败时使用标准 HTTP 状态码,例如 `400`、`403`、`404`、`500` +- 响应头可能包含 `Content-Type`、`Content-Length`、`Content-Disposition`、`ETag`、`Last-Modified`、`Accept-Ranges`、`Content-Range` +- 前端应使用 `blob` / `arrayBuffer`,不能按 JSON 解析 + +具体哪些接口属于二进制响应,以 OpenAPI 中定义的响应 `Content-Type` 为准。 + +### 3.2 SSE + +部分长任务接口使用 `text/event-stream`,不经过 `TimiResponse`。事件类型如下: + +| event | 说明 | +| --- | --- | +| `snapshot` | 连接建立后的当前任务快照 | +| `progress` | 状态或进度发生变化 | +| `heartbeat` | 心跳,约 15 秒一次 | +| `done` | 任务成功,随后服务端关闭连接 | +| `error` | 任务失败、被中断、死亡,或订阅异常,随后关闭连接 | + +说明: + +- 事件 `data` 是 JSON,字段和状态枚举以 OpenAPI 中对应的任务模型为准。 +- 任务结束后服务端主动关闭连接;断线后可回退到 OpenAPI 中的任务详情接口轮询。 +- 浏览器原生 `EventSource` 不能设置 `Token` 请求头,使用查询参数传递令牌。 + +```ts +const source = new EventSource(`${sseUrl}?token=${encodeURIComponent(token)}`); + +source.addEventListener("progress", (event) => { + const task = JSON.parse(event.data); + console.log(task.progress, task.status); +}); + +source.addEventListener("done", (event) => { + const task = JSON.parse(event.data); + source.close(); +}); +``` + +其中 `sseUrl` 从 OpenAPI 中对应的 SSE 接口获取。 + +--- + +## 4. AI Agent 对接建议 + +1. **优先使用导出的 OpenAPI 文件**,不要只给 `localhost` URL。远程 Agent 无法访问本机地址。 +2. 用 OpenAPI 生成 TypeScript 类型和请求客户端,再在客户端层统一补充 `TimiResponse` 包装。 +3. 不要假设 OpenAPI 的返回类型就是最终响应体;普通 JSON 接口需要取 `data`。 +4. 二进制接口单独处理:使用 `blob` / `arrayBuffer`,按 HTTP 状态判断成败。 +5. SSE 单独处理:使用 `EventSource` 或 fetch 流式读取,`Token` 放查询参数。 +6. 分页接口使用 `Page` / `PageResult`,`index` 从 0 开始。 +7. 业务错误优先看 `code`,不要只看 HTTP 状态。 +8. 接口路径、参数和字段结构以 OpenAPI 为准,不要根据本文猜测。 + +推荐给 AI Agent 的简要约束: + +```text +这是一个 Spring Boot 接口项目。接口路径、参数和响应结构以 OpenAPI 为准。 +普通 JSON 接口返回 TimiResponse 包装:{ code, message?, messageCode?, data? }, +code <= 30000 表示成功。鉴权使用 Token 请求头。 +二进制接口不包装,按 HTTP 状态判断;SSE 接口不包装,Token 放查询参数。 +分页请求使用 Page,index 从 0 开始。 +``` + +--- + +## 5. 已知限制 + +- OpenAPI 的响应 Schema 不包含 `TimiResponse` 包装。 +- 只有文件模块和异步任务模块的 7 个 Controller 有较完整的中文接口描述,其他模块为基础自动生成信息。 +- 二进制接口的响应体无法在 OpenAPI 中完整表达,需结合本文和实际响应头处理。 +- OpenAPI 全局声明了 `Token`,公开接口的实际鉴权行为以接口为准。 +- 当前没有提交固定的 `docs/openapi.yaml` 版本化文件;需要时使用导出脚本生成本地快照,或后续接入 CI 导出。 diff --git a/pom.xml b/pom.xml index 326a937..d39c771 100644 --- a/pom.xml +++ b/pom.xml @@ -195,6 +195,11 @@ timi-spring 0.0.20 + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 2.10.1 + org.springframework.boot spring-boot-starter-freemarker diff --git a/scripts/export-openapi.ps1 b/scripts/export-openapi.ps1 new file mode 100644 index 0000000..900eaeb --- /dev/null +++ b/scripts/export-openapi.ps1 @@ -0,0 +1,50 @@ +<# +.SYNOPSIS + 导出本地 OpenAPI 文档。 + +.DESCRIPTION + 从本地已启动的服务获取 /v3/api-docs.yaml(或 JSON),写入 docs 目录。 + 生成的文件已被 .gitignore 忽略,不会提交。 + +.PARAMETER BaseUrl + 服务地址,默认 http://localhost:18092。 + +.PARAMETER OutFile + 输出文件路径,默认 docs/openapi.local.yaml。 + 扩展名为 .json 时导出 JSON,否则导出 YAML。 + +.EXAMPLE + .\scripts\export-openapi.ps1 + +.EXAMPLE + .\scripts\export-openapi.ps1 -BaseUrl http://192.168.1.10:18092 -OutFile docs/openapi.local.json +#> +param( + [string]$BaseUrl = "http://localhost:18092", + [string]$OutFile +) + +$ErrorActionPreference = "Stop" + +if ([string]::IsNullOrWhiteSpace($OutFile)) { + $OutFile = Join-Path (Split-Path -Parent $PSScriptRoot) "docs\openapi.local.yaml" +} + +$BaseUrl = $BaseUrl.TrimEnd("/") +$OutFile = [System.IO.Path]::GetFullPath($OutFile) +$OutDir = Split-Path -Parent $OutFile + +if (-not (Test-Path -LiteralPath $OutDir)) { + New-Item -ItemType Directory -Path $OutDir -Force | Out-Null +} + +if ([System.IO.Path]::GetExtension($OutFile) -ieq ".json") { + $ApiPath = "/v3/api-docs" +} else { + $ApiPath = "/v3/api-docs.yaml" +} + +$Url = "$BaseUrl$ApiPath" +Write-Host "Fetching $Url" +Invoke-WebRequest -Uri $Url -OutFile $OutFile -UseBasicParsing +Write-Host "OpenAPI exported to $OutFile" diff --git a/scripts/export-openapi.sh b/scripts/export-openapi.sh new file mode 100644 index 0000000..595587d --- /dev/null +++ b/scripts/export-openapi.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# 导出本地 OpenAPI 文档。 +# +# 用法: +# scripts/export-openapi.sh [baseUrl] [outFile] +# +# 输出文件扩展名为 .json 时导出 JSON,否则导出 YAML。 +# 生成的文件已被 .gitignore 忽略,不会提交。 + +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +BASE_URL="${1:-http://localhost:18092}" +OUT_FILE="${2:-$ROOT_DIR/docs/openapi.local.yaml}" + +BASE_URL="${BASE_URL%/}" +mkdir -p "$(dirname "$OUT_FILE")" + +case "$OUT_FILE" in + *.json) + API_PATH="/v3/api-docs" + ;; + *) + API_PATH="/v3/api-docs.yaml" + ;; +esac + +echo "Fetching ${BASE_URL}${API_PATH}" +curl -fsS "${BASE_URL}${API_PATH}" -o "$OUT_FILE" +echo "OpenAPI exported to $OUT_FILE" diff --git a/src/main/java/com/imyeyu/api/config/OpenApiConfig.java b/src/main/java/com/imyeyu/api/config/OpenApiConfig.java new file mode 100644 index 0000000..7b49130 --- /dev/null +++ b/src/main/java/com/imyeyu/api/config/OpenApiConfig.java @@ -0,0 +1,96 @@ +package com.imyeyu.api.config; + +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.security.SecurityRequirement; +import io.swagger.v3.oas.models.security.SecurityScheme; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.ByteArrayHttpMessageConverter; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.List; + +/** + * OpenAPI 接口文档配置 + * + * @author 夜雨 + * @since 2026-11-24 + */ +@Configuration +public class OpenApiConfig { + + /** + * 移除 timi-spring 默认的全局返回处理器,由 {@link OpenApiGlobalReturnHandler} 替代。 + * + *

默认处理器会把所有响应包装为 TimiResponse,导致 SpringDoc 的接口描述无法被 Swagger UI 解析。

+ * + * @return Bean 定义注册后处理器 + */ + @Bean + public static BeanDefinitionRegistryPostProcessor openApiGlobalReturnHandlerReplacer() { + return new BeanDefinitionRegistryPostProcessor() { + + @Override + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) { + for (String beanName : registry.getBeanDefinitionNames()) { + BeanDefinition definition = registry.getBeanDefinition(beanName); + if ("globalReturnHandler".equals(beanName) + || "com.imyeyu.spring.util.GlobalReturnHandler".equals(definition.getBeanClassName())) { + registry.removeBeanDefinition(beanName); + } + } + } + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { + } + }; + } + + /** + * 接口文档信息与认证方式 + * + * @return OpenAPI 配置 + */ + @Bean + public OpenAPI timiServerOpenAPI() { + return new OpenAPI() + .info(new Info() + .title("TimiServerAPI") + .description("夜雨综合数据中心接口") + .version("1.0.79")) + .components(new Components() + .addSecuritySchemes("Token", new SecurityScheme() + .name("Token") + .type(SecurityScheme.Type.APIKEY) + .in(SecurityScheme.In.HEADER) + .description("登录令牌或 API Key,也可通过 URL 参数 token 传递"))) + .addSecurityItem(new SecurityRequirement().addList("Token")); + } + + /** + * 注册字节数组消息转换器,确保接口文档以原始 JSON 输出。 + * + *

项目的消息转换器配置仅注册了 Jackson 转换器,{@code byte[]} 会被序列化为 Base64 字符串, + * 导致 Swagger UI 无法解析接口文档。

+ * + * @return Web MVC 配置 + */ + @Bean + public WebMvcConfigurer openApiByteArrayMessageConverter() { + return new WebMvcConfigurer() { + + @Override + public void extendMessageConverters(List> converters) { + converters.add(0, new ByteArrayHttpMessageConverter()); + } + }; + } +} diff --git a/src/main/java/com/imyeyu/api/config/OpenApiGlobalReturnHandler.java b/src/main/java/com/imyeyu/api/config/OpenApiGlobalReturnHandler.java new file mode 100644 index 0000000..14235d4 --- /dev/null +++ b/src/main/java/com/imyeyu/api/config/OpenApiGlobalReturnHandler.java @@ -0,0 +1,28 @@ +package com.imyeyu.api.config; + +import com.imyeyu.spring.util.GlobalReturnHandler; +import org.springframework.core.MethodParameter; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.lang.NonNull; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +/** + * 全局返回处理器,跳过 SpringDoc 接口。 + * + *

接口文档响应需要保持原始 JSON 结构,不能包装为 TimiResponse。

+ * + * @author 夜雨 + * @since 2026-11-24 + */ +@RestControllerAdvice +public class OpenApiGlobalReturnHandler extends GlobalReturnHandler { + + @Override + public boolean supports(@NonNull MethodParameter returnType, @NonNull Class> converterType) { + Class containingClass = returnType.getContainingClass(); + if (containingClass != null && containingClass.getName().startsWith("org.springdoc.")) { + return false; + } + return super.supports(returnType, converterType); + } +} diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/AsyncTaskController.java b/src/main/java/com/imyeyu/api/modules/system/controller/AsyncTaskController.java index 9ec8597..4a65e09 100644 --- a/src/main/java/com/imyeyu/api/modules/system/controller/AsyncTaskController.java +++ b/src/main/java/com/imyeyu/api/modules/system/controller/AsyncTaskController.java @@ -8,6 +8,9 @@ import com.imyeyu.api.modules.system.vo.AsyncTaskView; import com.imyeyu.api.modules.user.service.UserLoginService; import com.imyeyu.spring.annotation.AOPLog; import com.imyeyu.spring.annotation.IgnoreGlobalReturn; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.MediaType; @@ -26,6 +29,7 @@ import java.util.List; * @author 夜雨 * @version 2022-08-13 19:38 */ +@Tag(name = "系统-异步任务", description = "异步任务查询、控制与进度订阅接口") @Slf4j @RestController @RequiredArgsConstructor @@ -36,9 +40,12 @@ public class AsyncTaskController { private final AsyncTaskEventService eventService; private final UserLoginService userLoginService; + @Operation(summary = "创建调试任务", description = "创建一个持续指定秒数的调试任务,返回任务 ID。") @AOPLog @PostMapping("/debug") - public String debug(@RequestParam("second") Integer second) { + public String debug( + @Parameter(description = "任务持续秒数,默认 60") + @RequestParam(value = "second", required = false) Integer second) { if (second == null) { second = 60; } @@ -47,8 +54,11 @@ public class AsyncTaskController { return task.getId(); } + @Operation(summary = "获取任务详情") @GetMapping("/detail") - public AbstractAsyncTask detail(@RequestParam ("uuid") String uuid) { + public AbstractAsyncTask detail( + @Parameter(description = "任务 ID", required = true) + @RequestParam("uuid") String uuid) { return service.getAsyncTask(uuid); } @@ -61,32 +71,45 @@ public class AsyncTaskController { * @param uuid 任务 ID * @return SSE 事件流 */ + @Operation(summary = "订阅任务事件", description = "以 SSE 推送任务状态与进度,任务结束后服务端主动关闭连接。") @IgnoreGlobalReturn @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE) - public SseEmitter events(@RequestParam("uuid") String uuid) { + public SseEmitter events( + @Parameter(description = "任务 ID", required = true) + @RequestParam("uuid") String uuid) { return eventService.subscribe(uuid, userLoginService.getRequireLoginUserId()); } + @Operation(summary = "获取任务列表") @PostMapping("/list") public List list() { return service.listAllView(); } + @Operation(summary = "启动任务") @AOPLog @PostMapping("/start") - public void start(@RequestParam ("uuid") String uuid) { + public void start( + @Parameter(description = "任务 ID", required = true) + @RequestParam("uuid") String uuid) { service.start(uuid); } + @Operation(summary = "暂停任务") @AOPLog @PostMapping("/pause") - public void pause(@RequestParam ("uuid") String uuid) { + public void pause( + @Parameter(description = "任务 ID", required = true) + @RequestParam("uuid") String uuid) { service.pause(uuid); } + @Operation(summary = "中断任务") @AOPLog @PostMapping("/interrupt") - public void interrupt(@RequestParam ("uuid") String uuid) { + public void interrupt( + @Parameter(description = "任务 ID", required = true) + @RequestParam("uuid") String uuid) { service.interrupt(uuid); } } diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/FileArchiveController.java b/src/main/java/com/imyeyu/api/modules/system/controller/FileArchiveController.java index 61d249a..b369b58 100644 --- a/src/main/java/com/imyeyu/api/modules/system/controller/FileArchiveController.java +++ b/src/main/java/com/imyeyu/api/modules/system/controller/FileArchiveController.java @@ -18,6 +18,8 @@ import com.imyeyu.api.modules.user.service.PermissionChecker; import com.imyeyu.api.modules.user.service.UserLoginService; import com.imyeyu.spring.annotation.AOPLog; import com.imyeyu.spring.annotation.RequestRateLimit; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.PostMapping; @@ -31,6 +33,7 @@ import org.springframework.web.bind.annotation.RestController; * @author 夜雨 * @version 2026-11-24 */ +@Tag(name = "系统-文件归档", description = "文件压缩、解压、复制与移动异步任务接口") @RestController @RequiredArgsConstructor @RequestMapping("/system/file") @@ -41,6 +44,7 @@ public class FileArchiveController { private final UserLoginService userLoginService; private final PermissionChecker permissionChecker; + @Operation(summary = "创建 ZIP 压缩任务", description = "将 list 中的文件或目录压缩到 to,返回异步任务 ID。") @AOPLog @OperationAudit(AuditOperation.FILE_ARCHIVE) @RequestRateLimit @@ -52,6 +56,7 @@ public class FileArchiveController { return task.getId(); } + @Operation(summary = "创建 ZIP 解压任务", description = "将 file 解压到 to,返回异步任务 ID。") @AOPLog @OperationAudit(AuditOperation.FILE_ARCHIVE) @RequestRateLimit @@ -63,6 +68,7 @@ public class FileArchiveController { return task.getId(); } + @Operation(summary = "创建 TAR 压缩任务", description = "将 list 中的文件或目录打包到 to,返回异步任务 ID。") @AOPLog @OperationAudit(AuditOperation.FILE_ARCHIVE) @RequestRateLimit @@ -74,6 +80,7 @@ public class FileArchiveController { return task.getId(); } + @Operation(summary = "创建 TAR 解压任务", description = "将 file 解压到 to,返回异步任务 ID。") @AOPLog @OperationAudit(AuditOperation.FILE_ARCHIVE) @RequestRateLimit @@ -85,6 +92,7 @@ public class FileArchiveController { return task.getId(); } + @Operation(summary = "创建移动任务", description = "将 list 中的文件或目录移动到 to,返回异步任务 ID。") @AOPLog @OperationAudit(AuditOperation.FILE_ARCHIVE) @RequestRateLimit @@ -96,6 +104,7 @@ public class FileArchiveController { return task.getId(); } + @Operation(summary = "创建复制任务", description = "将 list 中的文件或目录复制到 to,返回异步任务 ID。") @AOPLog @OperationAudit(AuditOperation.FILE_ARCHIVE) @RequestRateLimit diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/FileContentController.java b/src/main/java/com/imyeyu/api/modules/system/controller/FileContentController.java index 224f384..08f15f4 100644 --- a/src/main/java/com/imyeyu/api/modules/system/controller/FileContentController.java +++ b/src/main/java/com/imyeyu/api/modules/system/controller/FileContentController.java @@ -5,6 +5,9 @@ import com.imyeyu.api.bean.CorePermissionCode; import com.imyeyu.api.modules.system.service.FileContentService; import com.imyeyu.spring.annotation.IgnoreGlobalReturn; import com.imyeyu.spring.annotation.RequestRateLimit; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; @@ -20,6 +23,7 @@ import org.springframework.web.bind.annotation.RestController; * @author 夜雨 * @version 2026-11-24 */ +@Tag(name = "系统-文件内容", description = "文件内容读取、下载与预览接口") @RestController @RequiredArgsConstructor @RequestMapping("/system/file") @@ -27,27 +31,39 @@ public class FileContentController { private final FileContentService contentService; + @Operation(summary = "读取文件", description = "以内联方式输出文件内容,支持 Range 与条件请求。") @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_READ) @IgnoreGlobalReturn @GetMapping("/read/{*path}") - public void read(HttpServletRequest req, HttpServletResponse resp, @PathVariable("path") String path) { + public void read( + HttpServletRequest req, HttpServletResponse resp, + @Parameter(description = "文件虚拟路径,以 / 开头", required = true) + @PathVariable("path") String path) { FileBinaryResponder.serve(resp, () -> contentService.serve(req, resp, path, false)); } + @Operation(summary = "下载文件", description = "以附件方式输出文件内容,支持 Range 与 HEAD 请求。") @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_READ) @IgnoreGlobalReturn @RequestMapping(value = "/download/{*path}", method = {RequestMethod.GET, RequestMethod.HEAD}) - public void download(HttpServletRequest req, HttpServletResponse resp, @PathVariable("path") String path) { + public void download( + HttpServletRequest req, HttpServletResponse resp, + @Parameter(description = "文件虚拟路径,以 / 开头", required = true) + @PathVariable("path") String path) { FileBinaryResponder.serve(resp, () -> contentService.serve(req, resp, path, true)); } + @Operation(summary = "预览文件", description = "图片和视频返回 PNG 缩略图,PDF 与文本返回原始内容。") @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_READ) @IgnoreGlobalReturn @GetMapping("/preview/{*path}") - public void preview(HttpServletRequest req, HttpServletResponse resp, @PathVariable("path") String path) { + public void preview( + HttpServletRequest req, HttpServletResponse resp, + @Parameter(description = "文件虚拟路径,以 / 开头", required = true) + @PathVariable("path") String path) { FileBinaryResponder.serve(resp, () -> contentService.preview(req, resp, path)); } } diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/FileController.java b/src/main/java/com/imyeyu/api/modules/system/controller/FileController.java index f496d26..83320f2 100644 --- a/src/main/java/com/imyeyu/api/modules/system/controller/FileController.java +++ b/src/main/java/com/imyeyu/api/modules/system/controller/FileController.java @@ -15,6 +15,9 @@ import com.imyeyu.api.modules.user.service.PermissionChecker; import com.imyeyu.api.modules.user.service.UserLoginService; import com.imyeyu.spring.annotation.AOPLog; import com.imyeyu.spring.annotation.RequestRateLimit; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.GetMapping; @@ -33,6 +36,7 @@ import java.util.List; * @author 夜雨 * @version 2022-01-01 20:00 */ +@Tag(name = "系统-文件", description = "文件元数据、目录与检索接口") @RestController @RequiredArgsConstructor @RequestMapping("/system/file") @@ -44,22 +48,29 @@ public class FileController { private final UserLoginService userLoginService; private final PermissionChecker permissionChecker; + @Operation(summary = "获取文件属性", description = "返回指定路径的文件或目录属性。") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_READ) @GetMapping("/object/{*path}") - public ServerFile object(@PathVariable("path") String path) { + public ServerFile object( + @Parameter(description = "文件虚拟路径,以 / 开头", required = true) + @PathVariable("path") String path) { return fileService.object(path); } + @Operation(summary = "获取目录列表", description = "返回指定目录下的文件与子目录列表。") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_READ) @GetMapping("/list") - public List list(@RequestParam(defaultValue = "/") String path) { + public List list( + @Parameter(description = "目录虚拟路径,默认为根目录 /") + @RequestParam(defaultValue = "/") String path) { return fileService.list(path); } + @Operation(summary = "搜索文件", description = "在指定目录下按关键字搜索,返回匹配项、是否截断及扫描数量。") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_READ) @@ -68,22 +79,29 @@ public class FileController { return fileService.search(request.path(), request.keyword()); } + @Operation(summary = "判断路径是否存在") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_READ) @GetMapping("/exist") - public boolean exist(@RequestParam String path) { + public boolean exist( + @Parameter(description = "文件或目录虚拟路径", required = true) + @RequestParam String path) { return fileService.exists(path); } + @Operation(summary = "计算文件 SHA-256", description = "同步计算单个文件的 SHA-256,大文件请谨慎调用。") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_READ) @GetMapping("/hash") - public FileService.FileHash hash(@RequestParam String path) { + public FileService.FileHash hash( + @Parameter(description = "文件虚拟路径", required = true) + @RequestParam String path) { return fileService.hash(path); } + @Operation(summary = "统计目录大小", description = "创建异步任务统计目录大小,返回任务 ID,可通过异步任务接口订阅进度。") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_READ) @@ -96,6 +114,7 @@ public class FileController { return task.getId(); } + @Operation(summary = "创建目录") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_WRITE) @@ -104,6 +123,7 @@ public class FileController { return fileService.mkdir(request.path(), request.name()); } + @Operation(summary = "重命名或移动", description = "将文件或目录从 from 重命名或移动到 to。") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_WRITE) diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/FileShareController.java b/src/main/java/com/imyeyu/api/modules/system/controller/FileShareController.java index 0033e77..34771fa 100644 --- a/src/main/java/com/imyeyu/api/modules/system/controller/FileShareController.java +++ b/src/main/java/com/imyeyu/api/modules/system/controller/FileShareController.java @@ -12,6 +12,10 @@ import com.imyeyu.api.modules.user.service.UserLoginService; import com.imyeyu.spring.annotation.AOPLog; import com.imyeyu.spring.annotation.IgnoreGlobalReturn; import com.imyeyu.spring.annotation.RequestRateLimit; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.security.SecurityRequirements; +import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.validation.Valid; @@ -34,6 +38,7 @@ import java.util.List; * @author 夜雨 * @version 2026-11-24 */ +@Tag(name = "系统-文件分享", description = "文件分享创建、管理与公开下载接口") @RestController @RequiredArgsConstructor @RequestMapping("/system/file") @@ -44,6 +49,7 @@ public class FileShareController { private final UserLoginService userLoginService; private final LoggerService loggerService; + @Operation(summary = "创建文件分享", description = "对指定文件创建分享链接,可设置访问密码、过期时间与最大下载次数。") @RequestRateLimit @RequireCorePermission({CorePermissionCode.FILE_READ, CorePermissionCode.FILE_SHARE}) @PostMapping("/share") @@ -51,6 +57,7 @@ public class FileShareController { return shareService.create(request.path(), request.password(), request.expiresAt(), request.maxDownloads(), userLoginService.getRequireLoginUserId()); } + @Operation(summary = "获取分享列表") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_SHARE) @@ -59,19 +66,29 @@ public class FileShareController { return shareService.list(); } + @Operation(summary = "取消文件分享") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_SHARE) @DeleteMapping("/share/{id}") - public FileShare revokeShare(@PathVariable String id) { + public FileShare revokeShare( + @Parameter(description = "分享记录 ID", required = true) + @PathVariable String id) { return shareService.revoke(id); } /// 公开分享下载,只校验令牌与密码,不要求登录权限。 + @Operation(summary = "下载分享文件", description = "公开接口,仅校验分享令牌与访问密码,不要求登录。") + @SecurityRequirements @RequestRateLimit @IgnoreGlobalReturn @RequestMapping(value = "/share/{token}/download", method = {RequestMethod.GET, RequestMethod.HEAD}) - public void downloadShare(@PathVariable String token, @RequestParam(required = false) String password, HttpServletRequest req, HttpServletResponse resp) { + public void downloadShare( + @Parameter(description = "分享令牌", required = true) + @PathVariable String token, + @Parameter(description = "分享访问密码,未设置密码时省略") + @RequestParam(required = false) String password, + HttpServletRequest req, HttpServletResponse resp) { FileBinaryResponder.serve(resp, () -> { boolean consume = !"HEAD".equalsIgnoreCase(req.getMethod()); FileShare share = shareService.open(token, password, consume); diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/FileTrashController.java b/src/main/java/com/imyeyu/api/modules/system/controller/FileTrashController.java index f2abb89..c2f6f94 100644 --- a/src/main/java/com/imyeyu/api/modules/system/controller/FileTrashController.java +++ b/src/main/java/com/imyeyu/api/modules/system/controller/FileTrashController.java @@ -10,6 +10,9 @@ import com.imyeyu.api.modules.system.vo.IdRequest; import com.imyeyu.api.modules.user.service.UserLoginService; import com.imyeyu.spring.annotation.AOPLog; import com.imyeyu.spring.annotation.RequestRateLimit; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.DeleteMapping; @@ -28,6 +31,7 @@ import java.util.List; * @author 夜雨 * @version 2026-11-24 */ +@Tag(name = "系统-文件回收站", description = "文件删除、恢复与回收站清理接口") @RestController @RequiredArgsConstructor @RequestMapping("/system/file") @@ -36,6 +40,7 @@ public class FileTrashController { private final FileTrashService trashService; private final UserLoginService userLoginService; + @Operation(summary = "删除到回收站", description = "将 list 中的文件或目录移入回收站,返回删除记录。") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_DELETE) @@ -44,6 +49,7 @@ public class FileTrashController { return trashService.trash(request.list(), userLoginService.getRequireLoginUserId()); } + @Operation(summary = "获取回收站列表") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_READ) @@ -52,6 +58,7 @@ public class FileTrashController { return trashService.list(); } + @Operation(summary = "恢复回收站文件", description = "将回收站记录恢复到删除前的路径。") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_WRITE) @@ -60,14 +67,18 @@ public class FileTrashController { return trashService.restore(request.id()); } + @Operation(summary = "彻底删除回收站记录") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_DELETE) @DeleteMapping("/trash/{id}") - public void purge(@PathVariable String id) { + public void purge( + @Parameter(description = "回收站记录 ID", required = true) + @PathVariable String id) { trashService.purge(id); } + @Operation(summary = "清空回收站", description = "彻底删除回收站中的全部记录,返回清理数量。") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_DELETE) diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/FileUploadController.java b/src/main/java/com/imyeyu/api/modules/system/controller/FileUploadController.java index 66f64f8..fc56ecf 100644 --- a/src/main/java/com/imyeyu/api/modules/system/controller/FileUploadController.java +++ b/src/main/java/com/imyeyu/api/modules/system/controller/FileUploadController.java @@ -8,6 +8,9 @@ import com.imyeyu.api.modules.system.vo.UploadCompleteRequest; import com.imyeyu.api.modules.system.vo.UploadInitRequest; import com.imyeyu.spring.annotation.AOPLog; import com.imyeyu.spring.annotation.RequestRateLimit; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.PostMapping; @@ -24,6 +27,7 @@ import org.springframework.web.multipart.MultipartFile; * @author 夜雨 * @version 2026-11-24 */ +@Tag(name = "系统-文件上传", description = "文件直传与分片上传接口") @RestController @RequiredArgsConstructor @RequestMapping("/system/file") @@ -31,19 +35,25 @@ public class FileUploadController { private final FileUploadService uploadService; + @Operation(summary = "上传文件", description = "以 multipart/form-data 直接上传文件,overwrite 为 true 时覆盖同名文件。") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_WRITE) @PostMapping("/upload") public ServerFile upload( + @Parameter(description = "目标目录虚拟路径", required = true) @RequestParam String path, + @Parameter(description = "保存的文件名", required = true) @RequestParam String name, + @Parameter(description = "是否覆盖同名文件,默认 false") @RequestParam(defaultValue = "false") boolean overwrite, + @Parameter(description = "文件内容", required = true) @RequestPart("file") MultipartFile file ) { return uploadService.upload(path, name, file, overwrite); } + @Operation(summary = "初始化分片上传", description = "按文件大小与 SHA-256 创建上传会话,返回分片大小与分片数量。") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_WRITE) @@ -52,13 +62,21 @@ public class FileUploadController { return uploadService.init(request.path(), request.name(), request.size(), request.sha256()); } + @Operation(summary = "上传分片", description = "上传指定索引的分片,分片索引从 0 开始。") @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_WRITE) @PostMapping("/upload/chunk") - public void uploadChunk(@RequestParam String uploadId, @RequestParam int index, @RequestPart("file") MultipartFile file) { + public void uploadChunk( + @Parameter(description = "上传会话 ID", required = true) + @RequestParam String uploadId, + @Parameter(description = "分片索引,从 0 开始", required = true) + @RequestParam int index, + @Parameter(description = "分片内容", required = true) + @RequestPart("file") MultipartFile file) { uploadService.chunk(uploadId, index, file); } + @Operation(summary = "完成分片上传", description = "合并全部分片并校验 SHA-256,返回最终文件属性。") @AOPLog @RequestRateLimit @RequireCorePermission(CorePermissionCode.FILE_WRITE) diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 8411f44..73e4169 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -31,6 +31,12 @@ spring: required: true default-encoding: UTF-8 +# OpenAPI 接口文档 +springdoc: + swagger-ui: + tags-sorter: alpha + operations-sorter: method + # GAO 智能体写能力 gao: ai: From d4fc4274fd2919bf6f5a48f41a4b7a49ea339b29 Mon Sep 17 00:00:00 2001 From: Timi Date: Wed, 25 Nov 2026 01:25:46 +0800 Subject: [PATCH 6/6] v1.0.80 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d39c771..176f9d8 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ com.imyeyu.timiserverapi TimiServerAPI - 1.0.79 + 1.0.80 jar TimiServerAPI imyeyu.com API