init local code
This commit is contained in:
+10
@@ -0,0 +1,10 @@
|
||||
target/
|
||||
*.class
|
||||
*.log
|
||||
logs/
|
||||
.idea/
|
||||
*.iml
|
||||
.vscode/
|
||||
.DS_Store
|
||||
# 前端构建产物拷入目录(见 front README)
|
||||
src/main/resources/static/admin/
|
||||
@@ -0,0 +1,7 @@
|
||||
# CMS 后端镜像(对齐平台 sub-app 打包约定:fat jar + JRE8)
|
||||
FROM openjdk:8-jre-slim
|
||||
WORKDIR /app
|
||||
ENV TZ=Asia/Shanghai
|
||||
COPY target/cms.jar /app/cms.jar
|
||||
EXPOSE 8072
|
||||
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar /app/cms.jar"]
|
||||
@@ -0,0 +1,141 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.7.18</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
<groupId>com.yunhai</groupId>
|
||||
<artifactId>cms</artifactId>
|
||||
<version>0.1</version>
|
||||
<name>cms</name>
|
||||
<description>yh-platform 高校门户 CMS(管理端 API + Thymeleaf 门户 SSR)</description>
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.yunhai.platform</groupId>
|
||||
<artifactId>yh-platform-dependencies</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<!-- 门户 SSR(SEO/首屏刚需,方案 §3.1) -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
<!-- 模板内 LocalDateTime 格式化(#temporals) -->
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf.extras</groupId>
|
||||
<artifactId>thymeleaf-extras-java8time</artifactId>
|
||||
</dependency>
|
||||
<!-- 1-2 校规模本地缓存;上量切 Redis 仅改配置(方案 §4.1/§8.4) -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-cache</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.ben-manes.caffeine</groupId>
|
||||
<artifactId>caffeine</artifactId>
|
||||
</dependency>
|
||||
<!-- 参数校验(@Valid + 平台 GlobalExceptionHandler 统一包装) -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 基础平台全家桶(聚合 starter):CAS 认证 + 应用间签名 + 统一响应 + OpenAPI 客户端 +
|
||||
actuator 健康探活,一行带齐(同 UserHome/Notice 约定) -->
|
||||
<dependency>
|
||||
<groupId>com.yunhai.platform</groupId>
|
||||
<artifactId>yh-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<!-- CAS 客户端(UserHome 同款显式声明) -->
|
||||
<dependency>
|
||||
<groupId>org.jasig.cas.client</groupId>
|
||||
<artifactId>cas-client-core</artifactId>
|
||||
<version>3.5.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.36</version>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>8.0.33</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- 富文本正文入库前白名单清洗(方案 §8.5 内容安全);平台内无现成实现,自引入 -->
|
||||
<dependency>
|
||||
<groupId>org.jsoup</groupId>
|
||||
<artifactId>jsoup</artifactId>
|
||||
<version>1.17.2</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- 单测专用:验证方案 §12「缓存切 Redis 仅改配置」的演进承诺(生产仍为 Caffeine,零影响) -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>cms</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<!-- 本工程测试命名约定:纯单元 *Test + 集成 *IT(连本地 MySQL/Redis),统一由 surefire 执行 -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>**/*Test.java</include>
|
||||
<include>**/*IT.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>nexus-public</id>
|
||||
<name>bsch/nexus public</name>
|
||||
<url>http://nexus.yunhaixingtong.com/repository/maven-public/</url>
|
||||
<releases><enabled>true</enabled></releases>
|
||||
<snapshots><enabled>true</enabled></snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
</project>
|
||||
@@ -0,0 +1,122 @@
|
||||
-- ============================================================
|
||||
-- bsch_cms 本地种子数据(纯 SQL 版,2026-09-07 重写)
|
||||
-- 结构对齐 local-debug/build/day3-seed.cjs(同一份演示数据的 SQL 等价物):
|
||||
-- 1 站点 demo / 10 栏目(列表 7+单页 2+外链 1)/ 18 文章(13 发布含 3 置顶、3 草稿、2 下架)
|
||||
-- / 3 轮播(跳文章/栏目/外链各一)/ 6 友链(3 组)/ 8 附件(6 图 + 2 文档)
|
||||
-- 与 cjs 版的差异(有意):cjs 正文图走真实上传接口(PNG,uuid 文件名);
|
||||
-- 本 SQL 引用静态种子 SVG(front/mock/seed-assets.cjs 生成于 D:/bsch/cms/upload/seed/),
|
||||
-- art-1/art-2 在媒体/教学栏目复用(静态资产仅 6 张场景图)。
|
||||
-- 约定(B-1 / D3-8 / D6-1):
|
||||
-- * 上传地址一律相对路径 /cms/upload/... 入库,渲染期按访问域名补基准(禁绝对 URL)
|
||||
-- * 不配 public_base_url / domain(未配置=按请求派生,不写死 localhost)
|
||||
-- * 已废弃键 footer(死键)不出现;页脚= contact/copyright/beian
|
||||
-- 前置:cms_* 六表为空(Hibernate 自建表结构);种子账号 cmssuper/cmsschool(sch_id=990001)
|
||||
-- 清理:DELETE FROM cms_attachment; DELETE FROM cms_banner; DELETE FROM cms_link;
|
||||
-- DELETE FROM cms_article; DELETE FROM cms_category; DELETE FROM cms_site;
|
||||
-- 验证:2026-09-07 本地 MySQL 8.0.45 scratch 库(结构同 bsch_cms)整文件执行通过
|
||||
-- ============================================================
|
||||
|
||||
-- 1. 站点(config_json 五键与 day3-seed.cjs 一致;logo 相对路径)
|
||||
INSERT INTO cms_site (id, code, parent_site_id, sch_id, sch_name, name, theme, config_json, status, create_by, create_time) VALUES
|
||||
(1, 'demo', 0, 990001, '云海大学', '云海大学门户网站', 'default',
|
||||
'{"logo": "/cms/upload/seed/logo-univ.svg", "contact": "地址:云海市学府路 1 号 · 电话:010-88888888", "copyright": "云海大学 版权所有 © 2026(演示数据)", "beian": "京ICP备00000000号-1 · 京公网安备110000000000号", "seo_description": "云海大学门户网站演示站点(day3 验收演示数据)"}',
|
||||
1, 'cmssuper', NOW());
|
||||
|
||||
-- 2. 栏目(三种类型各就位:列表 7(含 2 父)/ 单页 2 / 外链 1;排序与 cjs 相同)
|
||||
INSERT INTO cms_category (id, site_id, parent_id, name, type, link_url, content, sort_no, seo_title, status, create_by, create_time) VALUES
|
||||
(1, 1, 0, '学校概况', 2, NULL, '<h2>学校简介</h2><p>云海大学创建于 1958 年,是一所以工为主、多学科协调发展的综合性大学。(演示数据)</p>', 1, NULL, 1, 'cmssuper', NOW()),
|
||||
(2, 1, 0, '新闻中心', 1, NULL, NULL, 2, NULL, 1, 'cmssuper', NOW()),
|
||||
(3, 1, 2, '通知公告', 1, NULL, NULL, 1, NULL, 1, 'cmssuper', NOW()),
|
||||
(4, 1, 2, '校园动态', 1, NULL, NULL, 2, NULL, 1, 'cmssuper', NOW()),
|
||||
(5, 1, 2, '媒体报道', 1, NULL, NULL, 3, NULL, 1, 'cmssuper', NOW()),
|
||||
(6, 1, 0, '教学科研', 1, NULL, NULL, 3, NULL, 1, 'cmssuper', NOW()),
|
||||
(7, 1, 6, '教学动态', 1, NULL, NULL, 1, NULL, 1, 'cmssuper', NOW()),
|
||||
(8, 1, 6, '科研成果', 1, NULL, NULL, 2, NULL, 1, 'cmssuper', NOW()),
|
||||
(9, 1, 0, '招生网', 3, 'https://zs.example.edu.cn', NULL, 4, NULL, 1, 'cmssuper', NOW()),
|
||||
(10, 1, 0, '联系我们', 2, NULL, '<p>地址:云海市学府路 1 号</p><p>邮编:100000</p><p>电话:010-88888888</p>', 5, NULL, 1, 'cmssuper', NOW());
|
||||
|
||||
-- 3. 文章(5 个叶子列表栏目 × 3~4 篇;状态组合与 day3-seed.cjs 逐篇一致:
|
||||
-- 发布 13(含置顶 3)/ 草稿 3 / 下架 2;发布后下架者保留 publish_time)
|
||||
-- 图文篇配图/art-N.svg、封面/cover-*.svg 均相对路径(B-1)
|
||||
INSERT INTO cms_article (id, site_id, category_id, title, summary, content, cover_image, author_account, author_name, source, status, topmost, publish_time, view_count, create_by, create_time) VALUES
|
||||
(1, 1, 3, '关于 2026 年秋季学期开学注册安排的通知', '现将 2026 年秋季学期开学注册有关事项通知如下。',
|
||||
'<p>关于 2026 年秋季学期开学注册安排的通知——演示数据正文。本篇配图为种子静态资源。</p><p>各单位、全体同学:2026 年秋季学期开学注册定于 9 月 6 日至 7 日进行,请按各学院通知分批办理。</p><p><img src="/cms/upload/seed/art-1.svg" alt="演示配图" style="max-width:100%"/></p><p>第二段正文,验证排版与图片渲染。</p>',
|
||||
NULL, 'cmssuper', '张老师', '', 1, 1, NOW() - INTERVAL 1 DAY, 1411, 'cmssuper', NOW() - INTERVAL 1 DAY),
|
||||
(2, 1, 3, '图书馆国庆节期间开放时间调整公告', NULL,
|
||||
'<p>图书馆开放时间调整——演示数据正文。本篇配图为种子静态资源。</p><p>国庆节期间(10 月 1 日至 7 日)图书馆开放时间调整为 9:00-16:00,10 月 8 日起恢复正常。</p><p><img src="/cms/upload/seed/art-2.svg" alt="演示配图" style="max-width:100%"/></p><p>第二段正文,验证排版与图片渲染。</p>',
|
||||
NULL, 'cmssuper', '张老师', '', 1, 0, NOW() - INTERVAL 3 DAY, 499, 'cmssuper', NOW() - INTERVAL 2 DAY),
|
||||
(3, 1, 3, '校园网络升级维护通知(草稿)', NULL,
|
||||
'<p>校园网络升级维护通知(草稿)——演示数据正文。</p>',
|
||||
NULL, 'cmssuper', '张老师', '', 0, 0, NULL, 680, 'cmssuper', NOW() - INTERVAL 1 DAY),
|
||||
(4, 1, 3, '关于开展 2026 级新生入学教育系列活动的通知', NULL,
|
||||
'<p>关于开展 2026 级新生入学教育系列活动的通知——演示数据正文。本篇配图为种子静态资源。</p><p><img src="/cms/upload/seed/art-3.svg" alt="演示配图" style="max-width:100%"/></p><p>第二段正文,验证排版与图片渲染。</p>',
|
||||
NULL, 'cmssuper', '张老师', '', 1, 0, NOW() - INTERVAL 6 DAY, 1899, 'cmssuper', NOW() - INTERVAL 2 DAY),
|
||||
(5, 1, 4, '我校成功举办第 38 届田径运动会', '为期三天的校运会圆满落幕,16 个学院代表队参赛。',
|
||||
'<p>我校成功举办第 38 届田径运动会——演示数据正文。本篇配图为种子静态资源。</p><p>为期三天的校运会圆满落幕,16 个学院代表队、1200 余名运动员参赛,打破校纪录 3 项。</p><p><img src="/cms/upload/seed/art-4.svg" alt="演示配图" style="max-width:100%"/></p><p>第二段正文,验证排版与图片渲染。</p>',
|
||||
'/cms/upload/seed/cover-运动会.svg', 'cmssuper', '张老师', '', 1, 1, NOW() - INTERVAL 2 DAY, 134, 'cmssuper', NOW() - INTERVAL 5 DAY),
|
||||
(6, 1, 4, '2026 年迎新晚会精彩回顾', NULL,
|
||||
'<p>2026 年迎新晚会精彩回顾——演示数据正文。本篇配图为种子静态资源。</p><p><img src="/cms/upload/seed/art-5.svg" alt="演示配图" style="max-width:100%"/></p><p>第二段正文,验证排版与图片渲染。</p>',
|
||||
'/cms/upload/seed/cover-迎新晚会.svg', 'cmssuper', '张老师', '', 1, 0, NOW() - INTERVAL 5 DAY, 1497, 'cmssuper', NOW() - INTERVAL 5 DAY),
|
||||
(7, 1, 4, '大学生创新创业大赛校内选拔赛落幕', NULL,
|
||||
'<p>大学生创新创业大赛校内选拔赛落幕——演示数据正文。本篇配图为种子静态资源。</p><p><img src="/cms/upload/seed/art-6.svg" alt="演示配图" style="max-width:100%"/></p><p>第二段正文,验证排版与图片渲染。</p>',
|
||||
'/cms/upload/seed/cover-创新创业.svg', 'cmssuper', '张老师', '', 1, 0, NOW() - INTERVAL 9 DAY, 299, 'cmssuper', NOW() - INTERVAL 7 DAY),
|
||||
(8, 1, 4, '2025 年优秀学生表彰大会报道(已下架)', NULL,
|
||||
'<p>2025 年优秀学生表彰大会报道(已下架)——演示数据正文。</p>',
|
||||
NULL, 'cmssuper', '张老师', '', 2, 0, NOW() - INTERVAL 40 DAY, 1123, 'cmssuper', NOW() - INTERVAL 40 DAY),
|
||||
(9, 1, 5, '《云海日报》:云海大学深耕产教融合一线观察', NULL,
|
||||
'<p>《云海日报》:云海大学深耕产教融合一线观察——演示数据正文。本篇配图为种子静态资源(art-1 复用)。</p><p><img src="/cms/upload/seed/art-1.svg" alt="演示配图" style="max-width:100%"/></p><p>第二段正文,验证排版与图片渲染。</p>',
|
||||
NULL, 'cmssuper', '张老师', '云海日报', 1, 0, NOW() - INTERVAL 4 DAY, 566, 'cmssuper', NOW() - INTERVAL 6 DAY),
|
||||
(10, 1, 5, '市电视台专访我校智能制造实验室', NULL,
|
||||
'<p>市电视台专访我校智能制造实验室——演示数据正文。</p>',
|
||||
NULL, 'cmssuper', '张老师', '云海电视台', 1, 0, NOW() - INTERVAL 12 DAY, 331, 'cmssuper', NOW() - INTERVAL 9 DAY),
|
||||
(11, 1, 5, '志愿服务月活动启动(草稿)', NULL,
|
||||
'<p>志愿服务月活动启动(草稿)——演示数据正文。</p>',
|
||||
NULL, 'cmssuper', '张老师', '', 0, 0, NULL, 108, 'cmssuper', NOW() - INTERVAL 8 DAY),
|
||||
(12, 1, 7, '我校 12 门课程获评省级一流本科课程', NULL,
|
||||
'<p>我校 12 门课程获评省级一流本科课程——演示数据正文。本篇配图为种子静态资源(art-2 复用)。</p><p><img src="/cms/upload/seed/art-2.svg" alt="演示配图" style="max-width:100%"/></p><p>第二段正文,验证排版与图片渲染。</p>',
|
||||
NULL, 'cmssuper', '张老师', '', 1, 0, NOW() - INTERVAL 7 DAY, 208, 'cmssuper', NOW() - INTERVAL 11 DAY),
|
||||
(13, 1, 7, '关于组织申报 2027 年教改项目的预通知', NULL,
|
||||
'<p>关于组织申报 2027 年教改项目的预通知——演示数据正文。</p>',
|
||||
NULL, 'cmssuper', '张老师', '', 1, 0, NOW() - INTERVAL 15 DAY, 97, 'cmssuper', NOW() - INTERVAL 13 DAY),
|
||||
(14, 1, 7, '人工智能赋能课堂教学改革研讨会举行', NULL,
|
||||
'<p>人工智能赋能课堂教学改革研讨会举行——演示数据正文。</p>',
|
||||
NULL, 'cmssuper', '张老师', '', 1, 0, NOW() - INTERVAL 10 DAY, 156, 'cmssuper', NOW() - INTERVAL 10 DAY),
|
||||
(15, 1, 8, '材料学院团队在《Nature》子刊发表最新成果', '该研究首次揭示了新型钙钛矿材料的界面稳定性机制。',
|
||||
'<p>材料学院团队在《Nature》子刊发表最新成果——演示数据正文。</p><p>该研究首次揭示了新型钙钛矿材料的界面稳定性机制,为下一代光伏器件提供理论基础。</p>',
|
||||
NULL, 'cmssuper', '张老师', '', 1, 1, NOW() - INTERVAL 2 DAY, 1730, 'cmssuper', NOW() - INTERVAL 14 DAY),
|
||||
(16, 1, 8, '我校获国家重点研发计划项目立项 3 项', NULL,
|
||||
'<p>我校获国家重点研发计划项目立项 3 项——演示数据正文。</p>',
|
||||
NULL, 'cmssuper', '张老师', '', 1, 0, NOW() - INTERVAL 18 DAY, 145, 'cmssuper', NOW() - INTERVAL 16 DAY),
|
||||
(17, 1, 8, '大模型教育应用白皮书编制启动(草稿)', NULL,
|
||||
'<p>大模型教育应用白皮书编制启动(草稿)——演示数据正文。</p>',
|
||||
NULL, 'cmssuper', '张老师', '', 0, 0, NULL, 12, 'cmssuper', NOW() - INTERVAL 3 DAY),
|
||||
(18, 1, 8, '校企合作联合实验室签约(已下架)', NULL,
|
||||
'<p>校企合作联合实验室签约(已下架)——演示数据正文。</p>',
|
||||
NULL, 'cmssuper', '张老师', '', 2, 0, NOW() - INTERVAL 30 DAY, 87, 'cmssuper', NOW() - INTERVAL 30 DAY);
|
||||
|
||||
-- 4. 轮播(3 张:跳栏目 / 跳文章 / 跳外链;第 2 张目标=迎新晚会(cjs 版 publishedIds[4] 的等价行))
|
||||
INSERT INTO cms_banner (id, site_id, position, title, image_url, link_type, link_value, sort_no, status, create_by, create_time) VALUES
|
||||
(1, 1, 'home', '笃学慎思 明辨笃行', '/cms/upload/seed/banner-1.svg', 2, '2', 1, 1, 'cmssuper', NOW()),
|
||||
(2, 1, 'home', '第 38 届田径运动会', '/cms/upload/seed/banner-2.svg', 1, '6', 2, 1, 'cmssuper', NOW()),
|
||||
(3, 1, 'home', '2026 年招生咨询', '/cms/upload/seed/banner-3.svg', 3, 'https://zs.example.edu.cn', 3, 1, 'cmssuper', NOW());
|
||||
|
||||
-- 5. 友情链接(3 组 × 2 条;logo 相对路径)
|
||||
INSERT INTO cms_link (id, site_id, group_name, name, logo_url, link_url, sort_no, status, create_by, create_time) VALUES
|
||||
(1, 1, '上级部门', '教育部', '/cms/upload/seed/logo-1.svg', 'http://www.moe.gov.cn', 1, 1, 'cmssuper', NOW()),
|
||||
(2, 1, '上级部门', '省教育厅', '/cms/upload/seed/logo-2.svg', 'http://jyt.example.cn', 2, 1, 'cmssuper', NOW()),
|
||||
(3, 1, '兄弟院校', '云海理工大学', '/cms/upload/seed/logo-3.svg', 'https://www.yhlg.edu.cn', 3, 1, 'cmssuper', NOW()),
|
||||
(4, 1, '兄弟院校', '云海师范大学', '/cms/upload/seed/logo-4.svg', 'https://www.yhsf.edu.cn', 4, 1, 'cmssuper', NOW()),
|
||||
(5, 1, '常用服务', '教务系统', '/cms/upload/seed/logo-6.svg', 'https://jw.yunhai-demo.edu.cn', 5, 1, 'cmssuper', NOW()),
|
||||
(6, 1, '常用服务', '图书馆', '/cms/upload/seed/logo-7.svg', 'https://lib.yunhai-demo.edu.cn', 6, 1, 'cmssuper', NOW());
|
||||
|
||||
-- 6. 附件(对应 cjs 版 8 张真实上传的等价行:6 张种子图(不绑文章=孤儿,演示孤儿清理)
|
||||
-- + 2 个 PDF(绑定文章 1/5,演示文档附件);web_url 一律相对路径(B-1))
|
||||
INSERT INTO cms_attachment (id, site_id, article_id, file_name, file_path, web_url, file_size, mime_type, create_by, create_time) VALUES
|
||||
(1, 1, NULL, 'scene-1.svg', 'seed/art-1.svg', '/cms/upload/seed/art-1.svg', 2100, 'image/svg+xml', 'cmssuper', NOW() - INTERVAL 1 DAY),
|
||||
(2, 1, NULL, 'scene-2.svg', 'seed/art-2.svg', '/cms/upload/seed/art-2.svg', 2100, 'image/svg+xml', 'cmssuper', NOW() - INTERVAL 2 DAY),
|
||||
(3, 1, NULL, 'scene-3.svg', 'seed/art-3.svg', '/cms/upload/seed/art-3.svg', 2100, 'image/svg+xml', 'cmssuper', NOW() - INTERVAL 6 DAY),
|
||||
(4, 1, NULL, 'scene-4.svg', 'seed/art-4.svg', '/cms/upload/seed/art-4.svg', 2100, 'image/svg+xml', 'cmssuper', NOW() - INTERVAL 2 DAY),
|
||||
(5, 1, NULL, 'scene-5.svg', 'seed/art-5.svg', '/cms/upload/seed/art-5.svg', 2100, 'image/svg+xml', 'cmssuper', NOW() - INTERVAL 5 DAY),
|
||||
(6, 1, NULL, 'scene-6.svg', 'seed/art-6.svg', '/cms/upload/seed/art-6.svg', 2100, 'image/svg+xml', 'cmssuper', NOW() - INTERVAL 9 DAY),
|
||||
(7, 1, 1, '2026秋季学期校历.pdf', 'seed/2026校历.pdf', '/cms/upload/seed/2026校历.pdf', 620, 'application/pdf', 'cmssuper', NOW() - INTERVAL 1 DAY),
|
||||
(8, 1, 5, '运动会秩序册.pdf', 'seed/运动会秩序册.pdf', '/cms/upload/seed/运动会秩序册.pdf', 630, 'application/pdf', 'cmssuper', NOW() - INTERVAL 5 DAY);
|
||||
@@ -0,0 +1,61 @@
|
||||
-- ============================================================
|
||||
-- 视觉精修边界状态种子(2026-09-06,docs/decisions.md 决策 D0-2)
|
||||
-- 目的:edge 站覆盖 空列表/无封面/超长标题/单轮播/无友链/富文本详情 等边界;
|
||||
-- demo 站补全页脚三键 + 院系子站(header 专业院系下拉);下架手工测试轮播"213"。
|
||||
-- 清理(恢复原状):
|
||||
-- UPDATE cms_banner SET status=1 WHERE id=5;
|
||||
-- UPDATE cms_site SET config_json=JSON_REMOVE(config_json,'$.contact','$.copyright','$.beian') WHERE code='demo';
|
||||
-- DELETE FROM cms_site WHERE code IN ('edge','jdx','xxgc');
|
||||
-- DELETE FROM cms_category WHERE site_id IN (SELECT id FROM cms_site WHERE code='edge') OR id IN (61,62,63);
|
||||
-- DELETE FROM cms_article WHERE site_id IN (SELECT id FROM cms_site WHERE code='edge');
|
||||
-- DELETE FROM cms_banner WHERE title='边界站唯一轮播';
|
||||
-- (注:site 删除需先删子表行,上面顺序已按依赖排列;jdx/xxgc 的栏目/文章见 61,62,63)
|
||||
-- ============================================================
|
||||
|
||||
-- 1) demo:页脚三键补全(模板读 contact/copyright/beian)+ 下架测试轮播
|
||||
UPDATE cms_site SET config_json = JSON_SET(config_json,
|
||||
'$.contact', '地址:云海市学府路 1 号 · 电话:010-88888888',
|
||||
'$.copyright', '云海大学 版权所有',
|
||||
'$.beian', '京ICP备00000000号-1 · 京公网安备110000000000号')
|
||||
WHERE code = 'demo';
|
||||
UPDATE cms_banner SET status = 0 WHERE id = 5;
|
||||
|
||||
-- 2) 院系子站(demo 的子站:header 出"专业院系"下拉;不配 public_base_url=按请求派生)
|
||||
INSERT INTO cms_site (id, code, parent_site_id, sch_id, sch_name, name, theme, config_json, status, create_by, create_time) VALUES
|
||||
(6, 'jdx', 1, 990001, '云海大学', '机电学院', 'default', '{"copyright": "机电学院"}', 1, 'cmssuper', NOW()),
|
||||
(7, 'xxgc', 1, 990001, '云海大学', '信息工程学院', 'default', '{"copyright": "信息工程学院"}', 1, 'cmssuper', NOW());
|
||||
INSERT INTO cms_category (id, site_id, parent_id, name, type, link_url, content, sort_no, status, create_by, create_time) VALUES
|
||||
(61, 6, 0, '学院概况', 2, NULL, '<p>机电学院(视觉精修种子)。</p>', 1, 1, 'cmssuper', NOW()),
|
||||
(62, 6, 0, '学院新闻', 1, NULL, NULL, 2, 1, 'cmssuper', NOW()),
|
||||
(63, 7, 0, '学院概况', 2, NULL, '<p>信息工程学院(视觉精修种子)。</p>', 1, 1, 'cmssuper', NOW());
|
||||
|
||||
-- 3) edge 边界站:单轮播 / 空列表栏目 / 图文栏目(无封面+超长标题+富文本) / 单页(富+空)
|
||||
INSERT INTO cms_site (id, code, parent_site_id, sch_id, sch_name, name, theme, config_json, status, create_by, create_time) VALUES
|
||||
(5, 'edge', 0, 990001, '云海大学', '边界状态演示站', 'default',
|
||||
'{"logo": "/cms/upload/seed/logo-univ.svg", "contact": "边界站 · 视觉回归用", "copyright": "边界状态演示站", "beian": "无备案(演示数据)", "seo_description": "门户视觉边界状态演示站"}',
|
||||
1, 'cmssuper', NOW());
|
||||
INSERT INTO cms_category (id, site_id, parent_id, name, type, link_url, content, sort_no, status, create_by, create_time) VALUES
|
||||
(51, 5, 0, '通知公告', 1, NULL, NULL, 1, 1, 'cmssuper', NOW()),
|
||||
(52, 5, 0, '图文快讯', 1, NULL, NULL, 2, 1, 'cmssuper', NOW()),
|
||||
(53, 5, 0, '学校简介', 2, NULL,
|
||||
'<h2>学校概况</h2><p>边界状态演示站用于验证门户在极端内容形态下的视觉稳定性。本页包含标题、段落、图片、表格、列表、引用等全部正文元素。</p><figure><img src="/cms/upload/seed/art-2.svg" alt="校园示意图"><figcaption>校园示意图(640×360 演示图)</figcaption></figure><h3>基本数据</h3><table><thead><tr><th>指标</th><th>数值</th><th>备注</th></tr></thead><tbody><tr><td>占地面积</td><td>3000 亩</td><td>含新校区</td></tr><tr><td>全日制在校生</td><td>32000 人</td><td>本科生 26000</td></tr><tr><td>专任教师</td><td>1800 人</td><td>含院士 12 名</td></tr></tbody></table><ul><li>国家级一流本科专业建设点 42 个</li><li>省部级科研平台 28 个</li><li>国际合作院校 120 余所</li></ul><blockquote>笃学慎思,明辨笃行——演示校训。</blockquote><p>以上内容均为本地演示数据,用于视觉回归测试。</p>',
|
||||
3, 1, 'cmssuper', NOW()),
|
||||
(54, 5, 0, '空白单页', 2, NULL, '', 4, 1, 'cmssuper', NOW());
|
||||
|
||||
INSERT INTO cms_banner (site_id, position, title, image_url, link_type, link_value, status, sort_no, create_by, create_time) VALUES
|
||||
(5, 'home', '边界站唯一轮播', '/cms/upload/seed/banner-2.svg', 1, NULL, 1, 1, 'cmssuper', NOW());
|
||||
|
||||
-- 超长标题(约 74 字)
|
||||
INSERT INTO cms_article (site_id, category_id, title, summary, content, cover_image, author_account, author_name, source, status, topmost, publish_time, view_count, create_by, create_time) VALUES
|
||||
(5, 52, '关于举办2026年云海大学"数智赋能高等教育高质量发展"系列学术论坛暨第三届校级教育教学成果奖申报动员培训会的通知公告', '超长标题边界样例——验证单行省略、列表行高与详情页标题换行的稳定性。',
|
||||
'<p>超长标题边界样例正文。本篇用于验证:首页区块/列表页的单行省略、轮播与区块布局稳定性、详情页 H1 长标题换行与行高。</p><p><img src="/cms/upload/seed/art-3.svg" alt="配图"></p>',
|
||||
'/cms/upload/seed/cover-运动会.svg', 'cmssuper', '边界测试', '', 1, 1, NOW() - INTERVAL 1 DAY, 42, 'cmssuper', NOW() - INTERVAL 1 DAY),
|
||||
-- 无封面文章
|
||||
(5, 52, '这篇边界文章没有封面图——验证无封面样式的占位设计', '无封面边界样例:列表不得出现破图或空洞。',
|
||||
'<p>无封面边界样例正文。列表与首页若展示封面,无封面文章必须呈现精心设计的占位形态而非空白或破图。</p><p><img src="/cms/upload/seed/art-4.svg" alt="配图"></p>',
|
||||
NULL, 'cmssuper', '边界测试', '', 1, 0, NOW() - INTERVAL 2 DAY, 7, 'cmssuper', NOW() - INTERVAL 2 DAY),
|
||||
-- 普通文章(有摘要)
|
||||
(5, 52, '边界站常规文章样例', '常规形态对照样例。',
|
||||
'<p>常规形态正文,作为边界样式的对照。</p>',
|
||||
'/cms/upload/seed/cover-创新创业.svg', 'cmssuper', '边界测试', '边界站', 1, 0, NOW() - INTERVAL 3 DAY, 3, 'cmssuper', NOW() - INTERVAL 3 DAY);
|
||||
-- edge 站不插入任何 cms_link → 友链整段隐藏边界
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.yunhai.cms;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
/**
|
||||
* 云海平台高校门户 CMS。
|
||||
*
|
||||
* <p>一个服务两副面孔(方案 §3.1):
|
||||
* <ul>
|
||||
* <li>{@code /cms/admin} —— Vue 管理端 SPA(静态资源,编辑人员经 CAS SSO 登录,数据走 {@code /api/*})</li>
|
||||
* <li>{@code /cms/portal/{siteCode}/**} —— Thymeleaf SSR 门户(匿名可访问,SEO 刚需)</li>
|
||||
* </ul>
|
||||
* CAS 只拦 {@code /api/*}(yh.sso.url-pattern),门户必须匿名,勿改配置(方案 §7.1)。
|
||||
*/
|
||||
@EnableCaching
|
||||
@EnableScheduling
|
||||
@SpringBootApplication
|
||||
public class CmsApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CmsApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.yunhai.cms.common;
|
||||
|
||||
import com.yunhai.cms.entity.BaseEntity;
|
||||
import com.yunhai.platform.auth.LoginUser;
|
||||
import com.yunhai.platform.auth.UserContextHolder;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.persistence.PrePersist;
|
||||
import javax.persistence.PreUpdate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 审计字段自动填充(Notice NoticeAuditListener 同款模式)。
|
||||
* 账号取 ThreadLocal 中的 CAS 会话用户;门户匿名渲染、定时任务等无会话场景为 null。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class CmsAuditListener {
|
||||
|
||||
@PrePersist
|
||||
public void prePersist(BaseEntity entity) {
|
||||
String account = currentAccount();
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
entity.setCreateBy(account);
|
||||
entity.setCreateTime(now);
|
||||
entity.setUpdateBy(account);
|
||||
entity.setUpdateTime(now);
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
public void preUpdate(BaseEntity entity) {
|
||||
entity.setUpdateBy(currentAccount());
|
||||
entity.setUpdateTime(LocalDateTime.now());
|
||||
}
|
||||
|
||||
private String currentAccount() {
|
||||
LoginUser user = UserContextHolder.get();
|
||||
return user == null ? null : user.getLoginName();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.yunhai.cms.config;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import com.github.benmanes.caffeine.cache.Expiry;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.CachingConfigurer;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.cache.caffeine.CaffeineCache;
|
||||
import org.springframework.cache.interceptor.CacheErrorHandler;
|
||||
import org.springframework.cache.support.SimpleCacheManager;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.lang.NonNull;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
/**
|
||||
* Caffeine 本地缓存装配(方案 §8.4 工程约束)。
|
||||
*
|
||||
* <ul>
|
||||
* <li>TTL 随机抖动 ±60s 防雪崩:自定义 {@link JitterExpiry} 按条目随机;</li>
|
||||
* <li>null 哨兵 30s 防穿透(爬虫扫随机 ID):写入值为 Spring NullValue 标记时短 TTL;</li>
|
||||
* <li>CacheErrorHandler:缓存异常按 miss 降级 + error 日志(dirty data risk, TTL 自愈)。</li>
|
||||
* </ul>
|
||||
* 切 Redis 时仅替换本配置与 spring.cache.type(方案 §1.2/§12);
|
||||
* yml 中 spring.cache.caffeine.spec 供默认管理器/演进期使用,本管理器按 CacheNames 显式装配。
|
||||
*/
|
||||
@Configuration
|
||||
@EnableCaching
|
||||
public class CacheConfig implements CachingConfigurer {
|
||||
|
||||
/** 抖动幅度:±60s */
|
||||
private static final Duration JITTER = Duration.ofSeconds(60);
|
||||
/** null 哨兵 TTL */
|
||||
private static final Duration NULL_TTL = Duration.ofSeconds(30);
|
||||
/** 抖动后 TTL 下限,避免抖出负数/过短 */
|
||||
private static final Duration MIN_TTL = Duration.ofSeconds(30);
|
||||
|
||||
private final LoggingCacheErrorHandler errorHandler;
|
||||
|
||||
public CacheConfig(LoggingCacheErrorHandler errorHandler) {
|
||||
this.errorHandler = errorHandler;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Override
|
||||
public CacheManager cacheManager() {
|
||||
SimpleCacheManager manager = new SimpleCacheManager();
|
||||
manager.setCaches(Arrays.asList(
|
||||
new CaffeineCache(CacheNames.SITE, caffeine(Duration.ofMinutes(30)).build()),
|
||||
new CaffeineCache(CacheNames.ARTICLE, caffeine(Duration.ofMinutes(5)).build()),
|
||||
new CaffeineCache(CacheNames.LIST, caffeine(Duration.ofMinutes(5)).build())));
|
||||
return manager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CacheErrorHandler errorHandler() {
|
||||
return errorHandler;
|
||||
}
|
||||
|
||||
private Caffeine<Object, Object> caffeine(Duration baseTtl) {
|
||||
return Caffeine.newBuilder()
|
||||
.maximumSize(10_000)
|
||||
.expireAfter(new JitterExpiry(baseTtl));
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 TTL 基准 + 随机抖动的过期策略;null 哨兵固定 30s。
|
||||
*/
|
||||
static class JitterExpiry implements Expiry<Object, Object> {
|
||||
|
||||
private final Duration baseTtl;
|
||||
|
||||
JitterExpiry(Duration baseTtl) {
|
||||
this.baseTtl = baseTtl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long expireAfterCreate(@NonNull Object key, Object value, long currentTime) {
|
||||
if (isNullValue(value)) {
|
||||
return NULL_TTL.toNanos();
|
||||
}
|
||||
long jitterMillis = ThreadLocalRandom.current()
|
||||
.nextLong(-JITTER.toMillis(), JITTER.toMillis());
|
||||
Duration jittered = baseTtl.plusMillis(jitterMillis);
|
||||
if (jittered.compareTo(MIN_TTL) < 0) {
|
||||
jittered = MIN_TTL;
|
||||
}
|
||||
return jittered.toNanos();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long expireAfterUpdate(@NonNull Object key, Object value, long currentTime,
|
||||
long currentDuration) {
|
||||
return currentDuration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long expireAfterRead(@NonNull Object key, Object value, long currentTime,
|
||||
long currentDuration) {
|
||||
return currentDuration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spring 把 null 包成 NullValue 单例存入 Caffeine(Caffeine 本身不收 null)。
|
||||
* 用类名判断避免对 Spring 内部类硬编译依赖。
|
||||
*/
|
||||
private boolean isNullValue(Object value) {
|
||||
return value == null
|
||||
|| "org.springframework.cache.support.NullValue".equals(value.getClass().getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.yunhai.cms.config;
|
||||
|
||||
/**
|
||||
* 缓存名常量(方案 §8.4)。
|
||||
* <p>javadoc 即失效契约:CacheNames 与失效事件的对应关系集中在此,禁止散落魔法串。
|
||||
* <ul>
|
||||
* <li>{@link #SITE}:siteCode → 站点+栏目树+轮播+友链快照,TTL 30min±60s;
|
||||
* 失效事件 = 站点/栏目/轮播/友链 变更(SiteContentChangedEvent)</li>
|
||||
* <li>{@link #ARTICLE}:articleId → 详情,TTL 5min±60s;articleId 不存在时缓存 null 哨兵 30s 防穿透;
|
||||
* 失效事件 = 文章发布/修改/下架(ArticleChangedEvent / ArticlePublishedEvent)</li>
|
||||
* <li>{@link #LIST}:siteId:categoryId:page → 列表页数据,TTL 5min±60s(null 哨兵同上);
|
||||
* 失效事件 = 该站点文章发布/下架/修改</li>
|
||||
* </ul>
|
||||
*/
|
||||
public final class CacheNames {
|
||||
|
||||
/** 门户站点快照(首页数据源) */
|
||||
public static final String SITE = "cms:site";
|
||||
/** 门户文章详情 */
|
||||
public static final String ARTICLE = "cms:article";
|
||||
/** 门户栏目列表页 */
|
||||
public static final String LIST = "cms:list";
|
||||
|
||||
private CacheNames() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.yunhai.cms.config;
|
||||
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* CMS 权限判定(对齐 UserBase GroupAuthzService#isSuperAdmin 与 UserTypeEnum 平台约定)。
|
||||
*
|
||||
* <p>超管规则:{@code BoaUser.type == 1}(UserTypeEnum.SUPER_ADMIN,系统种子账号),
|
||||
* 或 {@code BoaUser.id == 100000}(基石超级管理员账号,同 UserBase 内部判定)。
|
||||
* type 随认证链路经 BoaUserLoader 从 UserBase 换出,无需任何注入配置。
|
||||
* 学校管理员(type=2,持 ADMIN 角色)与学校领导不特判,统一走
|
||||
* {@code currentRole.schId → site.schId} 校级规则(方案 §7.2 规则②)。</p>
|
||||
*/
|
||||
@Component
|
||||
public class CmsAuthProperties {
|
||||
|
||||
/** UserBase 基石超级管理员账号 id(DicUtil.SUPER_ADMIN_ID,平台约定常量) */
|
||||
private static final int PLATFORM_ROOT_USER_ID = 100000;
|
||||
|
||||
public boolean isSuperAdmin(BoaUser user) {
|
||||
if (user == null) {
|
||||
return false;
|
||||
}
|
||||
if (user.getType() != null && user.getType() == 1) {
|
||||
return true;
|
||||
}
|
||||
return user.getId() != null && user.getId() == PLATFORM_ROOT_USER_ID;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.yunhai.cms.config;
|
||||
|
||||
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
|
||||
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
|
||||
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/**
|
||||
* LocalDateTime 统一按 yyyy-MM-dd HH:mm:ss 序列化/反序列化
|
||||
* (yml 的 spring.jackson.date-format 不作用于 JSR310,需显式定制;UserHome JacksonConfig 同意图)。
|
||||
*/
|
||||
@Configuration
|
||||
public class JacksonConfig {
|
||||
|
||||
private static final DateTimeFormatter DATE_TIME =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
@Bean
|
||||
public Jackson2ObjectMapperBuilderCustomizer localDateTimeCustomizer() {
|
||||
return builder -> builder
|
||||
.serializers(new LocalDateTimeSerializer(DATE_TIME))
|
||||
.deserializers(new LocalDateTimeDeserializer(DATE_TIME));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.yunhai.cms.config;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.interceptor.CacheErrorHandler;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 缓存异常降级(方案 §8.4):get 异常按 miss 返回 null,put/evict/clear 异常吞掉;
|
||||
* 脏数据风险靠 TTL 自愈,只留 error 日志定位。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class LoggingCacheErrorHandler implements CacheErrorHandler {
|
||||
|
||||
@Override
|
||||
public void handleCacheGetError(@NonNull RuntimeException ex, @NonNull Cache cache,
|
||||
@NonNull Object key) {
|
||||
log.error("cache get error, treat as miss, cache={}, key={}", cache.getName(), key, ex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleCachePutError(@NonNull RuntimeException ex, @NonNull Cache cache,
|
||||
@NonNull Object key, @Nullable Object value) {
|
||||
log.error("cache dirty data risk, TTL自愈, cache={}, key={}", cache.getName(), key, ex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleCacheEvictError(@NonNull RuntimeException ex, @NonNull Cache cache,
|
||||
@NonNull Object key) {
|
||||
log.error("cache dirty data risk, TTL自愈, cache={}, key={}", cache.getName(), key, ex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleCacheClearError(@NonNull RuntimeException ex, @NonNull Cache cache) {
|
||||
log.error("cache dirty data risk, TTL自愈, cache={}", cache.getName(), ex);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.yunhai.cms.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.filter.ForwardedHeaderFilter;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* Web 静态资源装配。
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code /upload/**} → FILE_PATH 本地磁盘(正文图片/轮播图/友链 Logo,双 key 约定方案 §7.3);</li>
|
||||
* <li>{@code /admin/**} → 管理端 SPA(front 构建产物拷入 classpath:/static/admin/,
|
||||
* hash 路由 + 相对 base,天然支持子路径部署);</li>
|
||||
* <li>根路径与 /admin 跳管理端入口。</li>
|
||||
* </ul>
|
||||
* 门户主题资产不在此处:按站点皮肤包解析,见 PortalAssetController。
|
||||
*/
|
||||
@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Value("${FILE_PATH:./upload/}")
|
||||
private String filePath;
|
||||
|
||||
/**
|
||||
* X-Forwarded-Proto/Host/Port 头处理(B-2):反代(Caddy/nginx)形态下
|
||||
* request.getScheme()/getServerName()/getServerPort() 修正为对外值,
|
||||
* 使 public_base_url/base-origin 均未配置时的请求派生 URL 不携带内网 scheme/端口。
|
||||
* 仅应在可信反代之后部署(直连暴露时该头可伪造,只影响派生形态展示,不影响数据)。
|
||||
*/
|
||||
@Bean
|
||||
public ForwardedHeaderFilter forwardedHeaderFilter() {
|
||||
return new ForwardedHeaderFilter();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
String root = filePath.endsWith("/") || filePath.endsWith("\\") ? filePath : filePath + "/";
|
||||
registry.addResourceHandler("/upload/**")
|
||||
.addResourceLocations("file:" + new File(root).getAbsolutePath().replace('\\', '/') + "/");
|
||||
registry.addResourceHandler("/admin/**")
|
||||
.addResourceLocations("classpath:/static/admin/");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addViewControllers(ViewControllerRegistry registry) {
|
||||
registry.addRedirectViewController("/", "/admin/index.html");
|
||||
registry.addRedirectViewController("/admin", "/admin/index.html");
|
||||
registry.addRedirectViewController("/admin/", "/admin/index.html");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.yunhai.cms.controller.api;
|
||||
|
||||
import com.yunhai.platform.apistd.ApiResponse;
|
||||
import com.yunhai.platform.utils.exception.ErrorCode;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.convert.ConversionFailedException;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
|
||||
/**
|
||||
* 管理端参数级异常翻译(体检 H-1/H-4 根因修复)。
|
||||
*
|
||||
* <p>平台 GlobalExceptionHandler 只兜 @Valid 校验/BizException/全局 Exception,
|
||||
* 三类 Spring MVC 参数绑定异常(缺参/类型不匹配/请求体不可读)落入兜底分支被
|
||||
* 报成 code=6 "内部服务错误"。本 advice 以更高优先级把它们翻译回 code=2 参数错误,
|
||||
* 前端可提示、日志不再噪音;真正的业务/系统异常不受影响(仍走平台处理器,堆栈完整)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
@RestControllerAdvice(basePackages = "com.yunhai.cms.controller.api")
|
||||
public class ApiParamExceptionHandler {
|
||||
|
||||
@ExceptionHandler(MissingServletRequestParameterException.class)
|
||||
public ApiResponse<Object> missingParam(MissingServletRequestParameterException e) {
|
||||
log.warn("管理端缺必填参数: {}", e.getParameterName());
|
||||
return ApiResponse.fail(ErrorCode.PARAM_ERROR, "缺少必填参数:" + e.getParameterName());
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
||||
public ApiResponse<Object> typeMismatch(MethodArgumentTypeMismatchException e) {
|
||||
String expected = e.getRequiredType() == null ? "" : "(应为 " + e.getRequiredType().getSimpleName() + ")";
|
||||
log.warn("管理端参数类型不匹配: {}={}", e.getName(), e.getValue());
|
||||
return ApiResponse.fail(ErrorCode.PARAM_ERROR, "参数格式不正确:" + e.getName() + expected);
|
||||
}
|
||||
|
||||
/** JSON 解析失败:编码/语法/时间格式(jackson date-format yyyy-MM-dd HH:mm:ss) */
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ApiResponse<Object> unreadable(HttpMessageNotReadableException e) {
|
||||
Throwable cause = e.getCause() == null ? e : e.getCause();
|
||||
String hint = cause.getMessage() == null ? "" : ": " + firstLine(cause.getMessage());
|
||||
log.warn("管理端请求体不可读 {}", firstLine(hint));
|
||||
return ApiResponse.fail(ErrorCode.PARAM_ERROR,
|
||||
"请求体格式错误(JSON/UTF-8/时间格式,时间需 yyyy-MM-dd HH:mm:ss)");
|
||||
}
|
||||
|
||||
private static String firstLine(String s) {
|
||||
int i = s.indexOf('\n');
|
||||
String line = i < 0 ? s : s.substring(0, i);
|
||||
return line.length() > 120 ? line.substring(0, 120) : line;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.yunhai.cms.controller.api;
|
||||
|
||||
import com.yunhai.cms.model.dto.ArticleSaveRequest;
|
||||
import com.yunhai.cms.model.dto.DeleteRequest;
|
||||
import com.yunhai.cms.model.query.ArticlePageQuery;
|
||||
import com.yunhai.cms.model.vo.ArticleEditVo;
|
||||
import com.yunhai.cms.service.impl.ArticleService;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
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.validation.Valid;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 文章管理(方案 §9.2):分页/保存(jsoup 清洗)/发布/下架/置顶/删除。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/article")
|
||||
@RequiredArgsConstructor
|
||||
public class ArticleController {
|
||||
|
||||
private final ArticleService articleService;
|
||||
|
||||
@GetMapping("/page")
|
||||
public Map<String, Object> page(BoaUser authUserWithDept, ArticlePageQuery query) {
|
||||
return articleService.page(authUserWithDept, query);
|
||||
}
|
||||
|
||||
/** 编辑回显(正文/扩展列) */
|
||||
@GetMapping("/get")
|
||||
public ArticleEditVo get(BoaUser authUserWithDept,
|
||||
@RequestParam("siteId") Integer siteId,
|
||||
@RequestParam("id") Integer id) {
|
||||
return articleService.getEdit(authUserWithDept, siteId, id);
|
||||
}
|
||||
|
||||
/** 保存草稿(content 先过 jsoup 白名单) */
|
||||
@PostMapping("/save")
|
||||
public Integer save(BoaUser authUserWithDept, @Valid @RequestBody ArticleSaveRequest request) {
|
||||
return articleService.save(authUserWithDept, request);
|
||||
}
|
||||
|
||||
/** 发布(publish_time 为未来时间即定时发布;作者自动从 CAS 会话填充) */
|
||||
@PostMapping("/publish/{id}")
|
||||
public void publish(BoaUser authUserWithDept,
|
||||
@PathVariable("id") Integer id,
|
||||
@RequestParam("siteId") Integer siteId) {
|
||||
articleService.publish(authUserWithDept, siteId, id);
|
||||
}
|
||||
|
||||
@PostMapping("/offline/{id}")
|
||||
public void offline(BoaUser authUserWithDept,
|
||||
@PathVariable("id") Integer id,
|
||||
@RequestParam("siteId") Integer siteId) {
|
||||
articleService.offline(authUserWithDept, siteId, id);
|
||||
}
|
||||
|
||||
@PostMapping("/topmost/{id}")
|
||||
public void topmost(BoaUser authUserWithDept,
|
||||
@PathVariable("id") Integer id,
|
||||
@RequestParam("siteId") Integer siteId,
|
||||
@RequestParam("enable") boolean enable) {
|
||||
articleService.topmost(authUserWithDept, siteId, id, enable);
|
||||
}
|
||||
|
||||
/** 删除(附件转孤儿,附件管理页清理) */
|
||||
@PostMapping("/delete")
|
||||
public void delete(BoaUser authUserWithDept, @Valid @RequestBody DeleteRequest request) {
|
||||
articleService.delete(authUserWithDept, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.yunhai.cms.controller.api;
|
||||
|
||||
import com.yunhai.cms.model.dto.DeleteRequest;
|
||||
import com.yunhai.cms.model.vo.AttachmentVo;
|
||||
import com.yunhai.cms.service.impl.AttachmentService;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
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 javax.validation.Valid;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 附件管理(方案 §9.2):编辑器图片/附件/轮播图/友链 Logo 复用同一上传接口。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/attachment")
|
||||
@RequiredArgsConstructor
|
||||
public class AttachmentController {
|
||||
|
||||
private final AttachmentService attachmentService;
|
||||
|
||||
/** 上传(multipart:file 必填;articleId 可空) */
|
||||
@PostMapping("/upload")
|
||||
public AttachmentVo upload(BoaUser authUserWithDept,
|
||||
@RequestParam("siteId") Integer siteId,
|
||||
@RequestParam(value = "articleId", required = false) Integer articleId,
|
||||
@RequestParam("file") MultipartFile file) {
|
||||
return attachmentService.upload(authUserWithDept, siteId, articleId, file);
|
||||
}
|
||||
|
||||
/** 附件列表(orphanOnly=true 仅孤儿) */
|
||||
@GetMapping("/page")
|
||||
public Map<String, Object> page(BoaUser authUserWithDept,
|
||||
@RequestParam("siteId") Integer siteId,
|
||||
@RequestParam(value = "orphanOnly", required = false,
|
||||
defaultValue = "false") boolean orphanOnly,
|
||||
@RequestParam(value = "page", required = false,
|
||||
defaultValue = "1") Integer page,
|
||||
@RequestParam(value = "pageSize", required = false,
|
||||
defaultValue = "10") Integer pageSize) {
|
||||
return attachmentService.page(authUserWithDept, siteId, orphanOnly, page, pageSize);
|
||||
}
|
||||
|
||||
/** 删除附件记录(物理文件运维定期清理) */
|
||||
@PostMapping("/delete")
|
||||
public void delete(BoaUser authUserWithDept, @Valid @RequestBody DeleteRequest request) {
|
||||
attachmentService.delete(authUserWithDept, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.yunhai.cms.controller.api;
|
||||
|
||||
import com.yunhai.cms.config.CmsAuthProperties;
|
||||
import com.yunhai.cms.model.vo.AuthUserVo;
|
||||
import com.yunhai.cms.model.vo.SiteVo;
|
||||
import com.yunhai.cms.service.impl.SiteService;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 管理端登录态(CAS 会话用户镜像,方案 §7.2)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/auth")
|
||||
@RequiredArgsConstructor
|
||||
public class AuthController {
|
||||
|
||||
private final SiteService siteService;
|
||||
private final CmsAuthProperties authProperties;
|
||||
|
||||
@GetMapping("/user")
|
||||
public AuthUserVo user(BoaUser authUserWithDept) {
|
||||
boolean superAdmin = authProperties.isSuperAdmin(authUserWithDept);
|
||||
List<SiteVo> sites = siteService.listFor(authUserWithDept);
|
||||
return AuthUserVo.of(authUserWithDept, superAdmin, sites);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.yunhai.cms.controller.api;
|
||||
|
||||
import com.yunhai.cms.model.dto.BannerSaveRequest;
|
||||
import com.yunhai.cms.model.dto.DeleteRequest;
|
||||
import com.yunhai.cms.model.vo.BannerVo;
|
||||
import com.yunhai.cms.service.impl.BannerService;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
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 javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 轮播/推荐位管理(方案 §9.2)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/banner")
|
||||
@RequiredArgsConstructor
|
||||
public class BannerController {
|
||||
|
||||
private final BannerService bannerService;
|
||||
|
||||
@GetMapping("/list")
|
||||
public List<BannerVo> list(BoaUser authUserWithDept,
|
||||
@RequestParam("siteId") Integer siteId,
|
||||
@RequestParam(value = "position", required = false) String position) {
|
||||
return bannerService.list(authUserWithDept, siteId, position);
|
||||
}
|
||||
|
||||
/** 保存(校验 link_type/link_value 匹配且属本站) */
|
||||
@PostMapping("/save")
|
||||
public BannerVo save(BoaUser authUserWithDept, @Valid @RequestBody BannerSaveRequest request) {
|
||||
return bannerService.save(authUserWithDept, request);
|
||||
}
|
||||
|
||||
@PostMapping("/delete")
|
||||
public void delete(BoaUser authUserWithDept, @Valid @RequestBody DeleteRequest request) {
|
||||
bannerService.delete(authUserWithDept, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.yunhai.cms.controller.api;
|
||||
|
||||
import com.yunhai.cms.service.impl.CmsUserCenterService;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 平台代理域接口(Notice BaseApiController 同款契约):GetUserInfo / GetUserMod。
|
||||
* 返回裸对象,由平台 ApiResponseAdvice 自动包装为 {code, msg, data}。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/base")
|
||||
@RequiredArgsConstructor
|
||||
public class BaseApiController {
|
||||
|
||||
private final CmsUserCenterService userCenterService;
|
||||
|
||||
/**
|
||||
* 获取当前登录用户信息(CAS 会话注入;前端 layout 取姓名/头像)。
|
||||
*/
|
||||
@GetMapping("GetUserInfo")
|
||||
public BoaUser getUserInfo(BoaUser authUserWithDept) {
|
||||
return authUserWithDept;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户已授权的模块列表(左侧菜单树)。
|
||||
*/
|
||||
@GetMapping("GetUserMod")
|
||||
public List<Map<String, Object>> getUserMod(BoaUser authUserWithDept) {
|
||||
Integer schId = authUserWithDept.getCurrentRole() != null
|
||||
? authUserWithDept.getCurrentRole().getSchId() : null;
|
||||
return userCenterService.getUserModuleTree(authUserWithDept.getId(), schId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.yunhai.cms.controller.api;
|
||||
|
||||
import com.yunhai.cms.model.dto.CategorySaveRequest;
|
||||
import com.yunhai.cms.model.dto.CategorySortRequest;
|
||||
import com.yunhai.cms.model.dto.DeleteRequest;
|
||||
import com.yunhai.cms.model.vo.CategoryTreeNode;
|
||||
import com.yunhai.cms.service.impl.CategoryService;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
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 java.util.List;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
/**
|
||||
* 栏目管理(方案 §9.2)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/category")
|
||||
@RequiredArgsConstructor
|
||||
public class CategoryController {
|
||||
|
||||
private final CategoryService categoryService;
|
||||
|
||||
@GetMapping("/tree")
|
||||
public List<CategoryTreeNode> tree(BoaUser authUserWithDept,
|
||||
@RequestParam("siteId") Integer siteId) {
|
||||
return categoryService.tree(authUserWithDept, siteId);
|
||||
}
|
||||
|
||||
@PostMapping("/save")
|
||||
public CategoryTreeNode save(BoaUser authUserWithDept,
|
||||
@Valid @RequestBody CategorySaveRequest request) {
|
||||
return categoryService.save(authUserWithDept, request);
|
||||
}
|
||||
|
||||
@PostMapping("/delete")
|
||||
public void delete(BoaUser authUserWithDept, @Valid @RequestBody DeleteRequest request) {
|
||||
categoryService.delete(authUserWithDept, request);
|
||||
}
|
||||
|
||||
/** 子栏目排序(UserBase SortChildren 同语义:按传入顺序落库 sortNo=1..n) */
|
||||
@PostMapping("/sort")
|
||||
public void sort(BoaUser authUserWithDept, @Valid @RequestBody CategorySortRequest request) {
|
||||
categoryService.sort(authUserWithDept, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.yunhai.cms.controller.api;
|
||||
|
||||
import com.yunhai.cms.model.dto.DeleteRequest;
|
||||
import com.yunhai.cms.model.dto.LinkSaveRequest;
|
||||
import com.yunhai.cms.model.vo.LinkVo;
|
||||
import com.yunhai.cms.service.impl.LinkService;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
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 javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 友情链接管理(方案 §9.2)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/link")
|
||||
@RequiredArgsConstructor
|
||||
public class LinkController {
|
||||
|
||||
private final LinkService linkService;
|
||||
|
||||
@GetMapping("/list")
|
||||
public List<LinkVo> list(BoaUser authUserWithDept, @RequestParam("siteId") Integer siteId) {
|
||||
return linkService.list(authUserWithDept, siteId);
|
||||
}
|
||||
|
||||
@PostMapping("/save")
|
||||
public LinkVo save(BoaUser authUserWithDept, @Valid @RequestBody LinkSaveRequest request) {
|
||||
return linkService.save(authUserWithDept, request);
|
||||
}
|
||||
|
||||
@PostMapping("/delete")
|
||||
public void delete(BoaUser authUserWithDept, @Valid @RequestBody DeleteRequest request) {
|
||||
linkService.delete(authUserWithDept, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.yunhai.cms.controller.api;
|
||||
|
||||
import com.yunhai.cms.model.vo.SchoolVo;
|
||||
import com.yunhai.cms.service.impl.SchoolService;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 学校工作台(docs/09 §3.3):一级页面=学校列表,二级 /sch/{code}/** 为学校专属管理壳。
|
||||
* 权限语义与 /api/site/list 一致;写操作仍走 /api/site/save(添加学校=初始化主站)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/school")
|
||||
@RequiredArgsConstructor
|
||||
public class SchoolController {
|
||||
|
||||
private final SchoolService schoolService;
|
||||
|
||||
/** 学校工作台列表(超管=全部顶层站点;校级=本校;无角色=空) */
|
||||
@GetMapping("/list")
|
||||
public List<SchoolVo> list(BoaUser authUserWithDept) {
|
||||
return schoolService.listFor(authUserWithDept);
|
||||
}
|
||||
|
||||
/** UserBase 学校选项(添加学校绑定用,仅超管;平台不可达降级空数组) */
|
||||
@GetMapping("/options")
|
||||
public List<SchoolVo.Option> options(BoaUser authUserWithDept) {
|
||||
return schoolService.schoolOptions(authUserWithDept);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.yunhai.cms.controller.api;
|
||||
|
||||
import com.yunhai.cms.model.dto.SiteSaveRequest;
|
||||
import com.yunhai.cms.model.vo.SiteVo;
|
||||
import com.yunhai.cms.service.impl.SiteService;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
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.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
/**
|
||||
* 站点管理(超管,方案 §9.1/§9.2)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/site")
|
||||
@RequiredArgsConstructor
|
||||
public class SiteController {
|
||||
|
||||
private final SiteService siteService;
|
||||
|
||||
/** 站点列表(超管=全部;校级=本校站点) */
|
||||
@GetMapping("/list")
|
||||
public List<SiteVo> list(BoaUser authUserWithDept) {
|
||||
return siteService.listFor(authUserWithDept);
|
||||
}
|
||||
|
||||
/** 站点保存(仅超管) */
|
||||
@PostMapping("/save")
|
||||
public SiteVo save(BoaUser authUserWithDept, @Valid @RequestBody SiteSaveRequest request) {
|
||||
return siteService.save(authUserWithDept, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.yunhai.cms.controller.api;
|
||||
|
||||
import com.yunhai.cms.service.impl.ThemeService;
|
||||
import com.yunhai.cms.theme.ThemeRegistry;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.MediaTypeFactory;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
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.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 主题管理接口(方案 §5.2,路径对齐 /api/{domain} 约定):
|
||||
* /api/theme/list 主题列表;/api/theme/{name}/asset/** 主题资产代理
|
||||
* (screenshot 与预览资产共用,防穿越同 PortalAssetController,name 先过 Registry 白名单)。
|
||||
* 走 /api/* CAS 鉴权(现状边界)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/theme")
|
||||
@RequiredArgsConstructor
|
||||
public class ThemeController {
|
||||
|
||||
private static final Duration ASSET_CACHE = Duration.ofHours(1);
|
||||
|
||||
private final ThemeService themeService;
|
||||
private final ThemeRegistry themeRegistry;
|
||||
|
||||
@GetMapping("/list")
|
||||
public List<com.yunhai.cms.model.vo.ThemeVo> list() {
|
||||
return themeService.list();
|
||||
}
|
||||
|
||||
@GetMapping("/{name}/asset/**")
|
||||
public ResponseEntity<Resource> asset(@PathVariable("name") String name,
|
||||
HttpServletRequest request) {
|
||||
if (!themeRegistry.contains(name)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
String path = extractRelativePath(request, name);
|
||||
if (path == null || path.isEmpty() || path.contains("..")) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
Resource resource = new ClassPathResource("templates/themes/" + name + "/assets/" + path);
|
||||
if (!resource.exists()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
MediaType mediaType = MediaTypeFactory.getMediaType(path)
|
||||
.orElse(MediaType.APPLICATION_OCTET_STREAM);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(mediaType)
|
||||
.cacheControl(CacheControl.maxAge(ASSET_CACHE).cachePublic())
|
||||
.body(resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从请求 URI 截取 /asset/ 之后的相对路径(同 PortalAssetController:
|
||||
* 直接解析 URL-decode 后的 URI,兼容两种路径匹配器语义)。
|
||||
*/
|
||||
private String extractRelativePath(HttpServletRequest request, String name) {
|
||||
String uri = request.getRequestURI();
|
||||
String prefix = request.getContextPath() + "/api/theme/" + name + "/asset/";
|
||||
int index = uri.indexOf(prefix);
|
||||
if (index < 0) {
|
||||
return null;
|
||||
}
|
||||
String relative = uri.substring(index + prefix.length());
|
||||
try {
|
||||
relative = java.net.URLDecoder.decode(relative, "UTF-8");
|
||||
} catch (java.io.UnsupportedEncodingException e) {
|
||||
return null;
|
||||
}
|
||||
return relative.replace('\\', '/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.yunhai.cms.controller.api;
|
||||
|
||||
import com.yunhai.cms.model.portal.PortalSiteSnapshot;
|
||||
import com.yunhai.cms.service.impl.PortalQueryService;
|
||||
import com.yunhai.cms.service.impl.SiteService;
|
||||
import com.yunhai.cms.service.impl.ThemeService;
|
||||
import com.yunhai.cms.theme.ThemeInfo;
|
||||
import com.yunhai.cms.theme.ThemeVarsCss;
|
||||
import com.yunhai.cms.controller.portal.PortalPageRenderer;
|
||||
import com.yunhai.cms.utils.PortalUrlHelper;
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import com.yunhai.platform.utils.exception.ErrorCode;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 主题预览(方案 §5.5):管理端鉴权的代理渲染接口,iframe 同源加载。
|
||||
* 预览渲染用站点快照的浅拷贝覆盖 theme/themeParams,资产 URL 切换到管理端代理
|
||||
* (防预览资产串包,R1);不在匿名门户 URL 开任何覆盖参数。
|
||||
* B-6:page 白名单(P1 仅 home,非法值明确报错);内容源站点过可管理校验(requireManageable)。
|
||||
*/
|
||||
@Controller
|
||||
@RequestMapping("/api/theme")
|
||||
@RequiredArgsConstructor
|
||||
public class ThemePreviewController {
|
||||
|
||||
private final ThemeService themeService;
|
||||
private final PortalQueryService portalQueryService;
|
||||
private final PortalPageRenderer pageRenderer;
|
||||
private final SiteService siteService;
|
||||
|
||||
/** 预览首页(page 参数 P1 仅支持 home):no-store 防止进缓存/CDN(方案 §10 风险表) */
|
||||
@GetMapping("/preview")
|
||||
public String preview(@RequestParam("siteCode") String siteCode,
|
||||
@RequestParam("theme") String theme,
|
||||
@RequestParam(value = "page", required = false, defaultValue = "home") String page,
|
||||
BoaUser authUserWithDept,
|
||||
HttpServletRequest request, HttpServletResponse response, Model model) {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
// B-6①:page 白名单——非法值明确报错,不静默当 home 渲染(接口语义误导)
|
||||
if (!"home".equals(page)) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "不支持的预览页面:" + page + "(当前仅支持 home)");
|
||||
}
|
||||
ThemeInfo info = themeService.requireRegistered(theme);
|
||||
PortalSiteSnapshot site = portalQueryService.siteSnapshot(siteCode);
|
||||
if (site == null) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR,
|
||||
"内容源站点不存在或已停用:" + siteCode);
|
||||
}
|
||||
// B-6②:预览渲染的是内容源站点数据快照,与管理端同权限级(requireManageable)
|
||||
if (authUserWithDept == null) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "未登录或会话失效,无法预览");
|
||||
}
|
||||
siteService.requireManageable(authUserWithDept, site.getId());
|
||||
PortalSiteSnapshot previewSite = site.shallowCopy();
|
||||
previewSite.setTheme(theme);
|
||||
Map<String, String> params = themeService.extractPreviewParams(info, request.getParameterMap());
|
||||
previewSite.setThemeParams(params);
|
||||
previewSite.setThemeVarsCss(ThemeVarsCss.build(info, params));
|
||||
return pageRenderer.renderHome(previewSite, PortalUrlHelper.forPreview(request, siteCode, theme), model);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.yunhai.cms.controller.portal;
|
||||
|
||||
import com.yunhai.cms.service.impl.PortalQueryService;
|
||||
import com.yunhai.cms.model.portal.PortalSiteSnapshot;
|
||||
import com.yunhai.cms.theme.ThemeRegistry;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.MediaTypeFactory;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
* 门户主题资产(方案 §8.2/§8.6):/portal/{siteCode}/assets/{theme}/** 解析到
|
||||
* classpath:/templates/themes/{theme}/assets/**。URL 由 PortalUrlHelper 以
|
||||
* public_base_url 为基准生成并携带主题段(B-3),学校域名形态同样命中本控制器。
|
||||
*
|
||||
* <p>主题段取自 URL 而非站点当前皮肤:换肤后 URL 即变,浏览器/CDN 对旧 URL 的
|
||||
* max-age 缓存天然失效;旧 URL 本身仍可服务(URL 与内容一一对应,缓存语义安全)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
public class PortalAssetController {
|
||||
|
||||
private static final Duration ASSET_CACHE = Duration.ofHours(1);
|
||||
|
||||
private final PortalQueryService portalQueryService;
|
||||
private final ThemeRegistry themeRegistry;
|
||||
|
||||
@GetMapping("/portal/{siteCode}/assets/{theme}/**")
|
||||
public ResponseEntity<Resource> asset(@PathVariable("siteCode") String siteCode,
|
||||
@PathVariable("theme") String theme,
|
||||
HttpServletRequest request) {
|
||||
// 主题段必须已注册(兼防路径注入:未注册名一律 404)
|
||||
if (!themeRegistry.contains(theme)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
PortalSiteSnapshot site = portalQueryService.siteSnapshot(siteCode);
|
||||
if (site == null) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
String path = extractRelativePath(request, siteCode, theme);
|
||||
if (path == null || path.isEmpty() || path.contains("..")) {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
Resource resource = new ClassPathResource(
|
||||
"templates/themes/" + theme + "/assets/" + path);
|
||||
if (!resource.exists()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
MediaType mediaType = MediaTypeFactory.getMediaType(path)
|
||||
.orElse(MediaType.APPLICATION_OCTET_STREAM);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(mediaType)
|
||||
.cacheControl(CacheControl.maxAge(ASSET_CACHE).cachePublic())
|
||||
.body(resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从请求 URI 截取 /assets/{theme}/ 之后的相对路径。
|
||||
* 直接解析 URI(URL-decode 后),兼容 AntPathMatcher 与 PathPatternParser 两种匹配器语义。
|
||||
*/
|
||||
private String extractRelativePath(HttpServletRequest request, String siteCode, String theme) {
|
||||
String uri = request.getRequestURI();
|
||||
String prefix = request.getContextPath() + "/portal/" + siteCode + "/assets/" + theme + "/";
|
||||
int index = uri.indexOf(prefix);
|
||||
if (index < 0) {
|
||||
return null;
|
||||
}
|
||||
String relative = uri.substring(index + prefix.length());
|
||||
try {
|
||||
relative = java.net.URLDecoder.decode(relative, "UTF-8");
|
||||
} catch (java.io.UnsupportedEncodingException e) {
|
||||
return null;
|
||||
}
|
||||
return relative.replace('\\', '/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
package com.yunhai.cms.controller.portal;
|
||||
|
||||
import com.yunhai.cms.entity.CmsArticle;
|
||||
import com.yunhai.cms.enums.ArticleStatusEnum;
|
||||
import com.yunhai.cms.enums.CategoryTypeEnum;
|
||||
import com.yunhai.cms.enums.LinkTypeEnum;
|
||||
import com.yunhai.cms.model.portal.PortalBanner;
|
||||
import com.yunhai.cms.model.portal.PortalCategory;
|
||||
import com.yunhai.cms.model.portal.PortalListData;
|
||||
import com.yunhai.cms.model.portal.PortalSiteSnapshot;
|
||||
import com.yunhai.cms.repository.CmsArticleRepository;
|
||||
import com.yunhai.cms.service.impl.PortalQueryService;
|
||||
import com.yunhai.cms.service.impl.ViewCounterService;
|
||||
import com.yunhai.cms.utils.PortalUrlHelper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 门户 SSR(方案 §8,匿名可访问——CAS url-pattern 只配 /api/*,勿改)。
|
||||
* 站点身份来自路径不依赖 Host(方案 §8.6);所有链接经 PortalUrlHelper 按
|
||||
* public_base_url 生成,base 域子路径与学校独立域名两种暴露形态共用渲染。
|
||||
*/
|
||||
@Slf4j
|
||||
@Controller
|
||||
@RequiredArgsConstructor
|
||||
public class PortalController {
|
||||
|
||||
/** 首页每个一级栏目取 N 条 */
|
||||
private static final int HOME_BLOCK_SIZE = 8;
|
||||
/** 首页置顶区取 N 条 */
|
||||
private static final int HOME_TOP_SIZE = 6;
|
||||
|
||||
private final PortalQueryService portalQueryService;
|
||||
private final CmsArticleRepository articleRepository;
|
||||
private final ViewCounterService viewCounterService;
|
||||
private final PortalPageRenderer pageRenderer;
|
||||
|
||||
@Value("${cms.portal.detail-max-age:300}")
|
||||
private int detailMaxAge;
|
||||
|
||||
/** base 域对外基地址(C-6:public_base_url 未配置时的规范派生基准;空=按请求派生) */
|
||||
@Value("${cms.portal.base-origin:}")
|
||||
private String baseOrigin;
|
||||
|
||||
/** 首页:站点配置 + home 轮播位 + 各一级栏目 top N + 置顶文章 + 友链分组(装配在 PortalPageRenderer,方案 §5.5) */
|
||||
@GetMapping("/portal/{siteCode}/")
|
||||
public String home(@PathVariable("siteCode") String siteCode, HttpServletRequest request,
|
||||
HttpServletResponse response, Model model) throws Exception {
|
||||
PortalSiteSnapshot site = requireSite(siteCode, response);
|
||||
if (site == null) {
|
||||
return null;
|
||||
}
|
||||
return pageRenderer.renderHome(site, buildUrl(site, request), model);
|
||||
}
|
||||
|
||||
/** 栏目页(列表/单页);外链栏目 302(方案 §8.1) */
|
||||
@GetMapping("/portal/{siteCode}/c/{categoryId}")
|
||||
public String category(@PathVariable("siteCode") String siteCode,
|
||||
@PathVariable("categoryId") Integer categoryId,
|
||||
@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
|
||||
HttpServletRequest request, HttpServletResponse response,
|
||||
Model model) throws Exception {
|
||||
PortalSiteSnapshot site = requireSite(siteCode, response);
|
||||
if (site == null) {
|
||||
return null;
|
||||
}
|
||||
PortalCategory category = findCategory(site, categoryId);
|
||||
if (category == null) {
|
||||
response.sendError(HttpServletResponse.SC_NOT_FOUND);
|
||||
return null;
|
||||
}
|
||||
if (category.getType() != null && category.getType() == CategoryTypeEnum.LINK.getCode()) {
|
||||
PortalUrlHelper fallback = buildUrl(site, request);
|
||||
response.sendRedirect(category.getLinkUrl() == null ? fallback.home() : category.getLinkUrl());
|
||||
return null;
|
||||
}
|
||||
PortalUrlHelper url = buildUrl(site, request);
|
||||
model.addAttribute("url", url);
|
||||
model.addAttribute("site", site);
|
||||
model.addAttribute("themeParams", site.getThemeParams());
|
||||
model.addAttribute("themeVarsCss", site.getThemeVarsCss());
|
||||
model.addAttribute("themeBase", "themes/" + site.getTheme());
|
||||
model.addAttribute("navCategories", site.getCategories());
|
||||
model.addAttribute("currentCategoryId", categoryId);
|
||||
model.addAttribute("category", category);
|
||||
model.addAttribute("pageTitle", seoTitle(category, site));
|
||||
model.addAttribute("seoDescription", category.getSeoDescription());
|
||||
model.addAttribute("canonical", url.category(categoryId));
|
||||
|
||||
if (category.getType() != null && category.getType() == CategoryTypeEnum.SINGLE.getCode()) {
|
||||
// 单页正文上传地址渲染期补基准(B-1):拷贝后重写,不污染快照缓存体
|
||||
model.addAttribute("category", category.withContent(
|
||||
url.rewriteUploadUrls(category.getContent())));
|
||||
return "themes/" + site.getTheme() + "/single";
|
||||
}
|
||||
PortalListData listData = portalQueryService.categoryPage(categoryId, page, 10);
|
||||
if (listData == null) {
|
||||
response.sendError(HttpServletResponse.SC_NOT_FOUND);
|
||||
return null;
|
||||
}
|
||||
model.addAttribute("listData", listData);
|
||||
model.addAttribute("searchMode", false);
|
||||
return "themes/" + site.getTheme() + "/list";
|
||||
}
|
||||
|
||||
/** 文章详情:正文 th:utext + 上下篇 + 浏览量异步累加 + Cache-Control(方案 §8.3) */
|
||||
@GetMapping("/portal/{siteCode}/a/{articleId}")
|
||||
public String article(@PathVariable("siteCode") String siteCode,
|
||||
@PathVariable("articleId") Integer articleId,
|
||||
HttpServletRequest request, HttpServletResponse response,
|
||||
Model model) throws Exception {
|
||||
PortalSiteSnapshot site = requireSite(siteCode, response);
|
||||
if (site == null) {
|
||||
return null;
|
||||
}
|
||||
com.yunhai.cms.model.portal.PortalArticleDetail detail =
|
||||
portalQueryService.articleDetail(articleId);
|
||||
if (detail == null || !detail.getSiteId().equals(site.getId())) {
|
||||
response.sendError(HttpServletResponse.SC_NOT_FOUND);
|
||||
return null;
|
||||
}
|
||||
viewCounterService.increment(articleId);
|
||||
|
||||
PortalUrlHelper url = buildUrl(site, request);
|
||||
model.addAttribute("url", url);
|
||||
model.addAttribute("site", site);
|
||||
model.addAttribute("themeParams", site.getThemeParams());
|
||||
model.addAttribute("themeVarsCss", site.getThemeVarsCss());
|
||||
model.addAttribute("themeBase", "themes/" + site.getTheme());
|
||||
model.addAttribute("navCategories", site.getCategories());
|
||||
model.addAttribute("currentCategoryId", detail.getCategoryId());
|
||||
// 面包屑栏目名(视觉精修 D2-2):按栏目树查名,查不到(栏目已删)退"正文"
|
||||
PortalCategory detailCategory = findCategory(site, detail.getCategoryId());
|
||||
model.addAttribute("currentCategoryName", detailCategory == null ? "正文" : detailCategory.getName());
|
||||
// 正文上传地址渲染期补基准(B-1):详情来自 cms:article 缓存(快照跨两种暴露形态共享),
|
||||
// 拷贝后重写,避免把某一形态的绝对 URL 写回缓存
|
||||
model.addAttribute("article", detail.withContent(
|
||||
url.rewriteUploadUrls(detail.getContent())));
|
||||
// og:image(C-7):文章封面(无封面则不输出该标签)
|
||||
model.addAttribute("ogImage", url.upload(detail.getCoverImage()));
|
||||
model.addAttribute("pageTitle", detail.getTitle() + " - " + site.getName());
|
||||
model.addAttribute("seoDescription", detail.getSummary());
|
||||
model.addAttribute("canonical", url.article(articleId));
|
||||
model.addAttribute("prevArticle", prevArticle(site.getId(), articleId, detail.getPublishTime()));
|
||||
model.addAttribute("nextArticle", nextArticle(site.getId(), articleId, detail.getPublishTime()));
|
||||
response.setHeader("Cache-Control", "max-age=" + detailMaxAge);
|
||||
return "themes/" + site.getTheme() + "/detail";
|
||||
}
|
||||
|
||||
/** 站内搜索:title/summary LIKE(实时查询不缓存) */
|
||||
@GetMapping("/portal/{siteCode}/search")
|
||||
public String search(@PathVariable("siteCode") String siteCode,
|
||||
@RequestParam(value = "q", required = false, defaultValue = "") String q,
|
||||
@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
|
||||
HttpServletRequest request, HttpServletResponse response,
|
||||
Model model) throws Exception {
|
||||
PortalSiteSnapshot site = requireSite(siteCode, response);
|
||||
if (site == null) {
|
||||
return null;
|
||||
}
|
||||
PortalUrlHelper url = buildUrl(site, request);
|
||||
model.addAttribute("url", url);
|
||||
model.addAttribute("site", site);
|
||||
model.addAttribute("themeParams", site.getThemeParams());
|
||||
model.addAttribute("themeVarsCss", site.getThemeVarsCss());
|
||||
model.addAttribute("themeBase", "themes/" + site.getTheme());
|
||||
model.addAttribute("navCategories", site.getCategories());
|
||||
model.addAttribute("q", q);
|
||||
model.addAttribute("pageTitle", "搜索:" + q + " - " + site.getName());
|
||||
model.addAttribute("seoDescription", null);
|
||||
model.addAttribute("canonical", url.search(q, page));
|
||||
model.addAttribute("searchMode", true);
|
||||
if (q.trim().isEmpty()) {
|
||||
model.addAttribute("listData", emptyList(page));
|
||||
return "themes/" + site.getTheme() + "/list";
|
||||
}
|
||||
org.springframework.data.domain.Page<PortalListData.Item> result =
|
||||
portalQueryService.search(site.getId(), q, page, 10);
|
||||
PortalListData listData = new PortalListData();
|
||||
listData.setSiteId(site.getId());
|
||||
listData.setItems(result.getContent());
|
||||
listData.setTotal(result.getTotalElements());
|
||||
listData.setPage(page);
|
||||
listData.setPageSize(10);
|
||||
listData.setTotalPages(result.getTotalPages());
|
||||
model.addAttribute("listData", listData);
|
||||
return "themes/" + site.getTheme() + "/list";
|
||||
}
|
||||
|
||||
// ===== 内部装配 =====
|
||||
|
||||
private PortalSiteSnapshot requireSite(String siteCode, HttpServletResponse response) throws Exception {
|
||||
PortalSiteSnapshot site = portalQueryService.siteSnapshot(siteCode);
|
||||
if (site == null) {
|
||||
response.sendError(HttpServletResponse.SC_NOT_FOUND);
|
||||
return null;
|
||||
}
|
||||
return site;
|
||||
}
|
||||
|
||||
/**
|
||||
* URL 生成器基准三级决策(方案 §8.6):
|
||||
* ① 站点 public_base_url(绑学校域名);
|
||||
* ② 平台 cms.portal.base-origin(未绑域时的 base 域规范形态,C-6);
|
||||
* ③ 当前请求派生(本地/预览形态,反代下经 ForwardedHeaderFilter 修正 scheme/port,B-2)。
|
||||
* theme 随 helper 走,使资产 URL 含主题段(B-3)。
|
||||
*/
|
||||
private PortalUrlHelper buildUrl(PortalSiteSnapshot site, HttpServletRequest request) {
|
||||
if (site.getPublicBaseUrl() != null) {
|
||||
return new PortalUrlHelper(site.getPublicBaseUrl(), site.getCode(), site.getTheme(), baseOrigin);
|
||||
}
|
||||
if (baseOrigin != null && !baseOrigin.trim().isEmpty()) {
|
||||
return PortalUrlHelper.fromBaseOrigin(baseOrigin, site.getCode(), site.getTheme());
|
||||
}
|
||||
return PortalUrlHelper.fromRequest(request, site.getCode(), site.getTheme());
|
||||
}
|
||||
|
||||
/** 全树递归查找栏目(管理端允许 3 级以上栏目,门户不得因层级深而 404,bug D-1) */
|
||||
private PortalCategory findCategory(PortalSiteSnapshot site, Integer categoryId) {
|
||||
for (PortalCategory root : site.getCategories()) {
|
||||
PortalCategory hit = findCategoryDeep(root, categoryId);
|
||||
if (hit != null) {
|
||||
return hit;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private PortalCategory findCategoryDeep(PortalCategory node, Integer categoryId) {
|
||||
if (node.getId().equals(categoryId)) {
|
||||
return node;
|
||||
}
|
||||
for (PortalCategory child : node.getChildren()) {
|
||||
PortalCategory hit = findCategoryDeep(child, categoryId);
|
||||
if (hit != null) {
|
||||
return hit;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
private PortalListData.Item toItem(CmsArticle a) {
|
||||
PortalListData.Item item = new PortalListData.Item();
|
||||
item.setId(a.getId());
|
||||
item.setTitle(a.getTitle());
|
||||
item.setSummary(a.getSummary());
|
||||
item.setCoverImage(a.getCoverImage());
|
||||
item.setPublishTime(a.getPublishTime());
|
||||
item.setTopmost(a.getTopmost());
|
||||
return item;
|
||||
}
|
||||
|
||||
private PortalListData.Item prevArticle(Integer siteId, Integer articleId, LocalDateTime publishTime) {
|
||||
LocalDateTime pt = publishTime == null ? LocalDateTime.now() : publishTime;
|
||||
List<CmsArticle> list = articleRepository.findPrevPublished(siteId,
|
||||
ArticleStatusEnum.PUBLISHED.getCode(), pt, articleId, PageRequest.of(0, 1));
|
||||
return list.isEmpty() ? null : toItem(list.get(0));
|
||||
}
|
||||
|
||||
private PortalListData.Item nextArticle(Integer siteId, Integer articleId, LocalDateTime publishTime) {
|
||||
LocalDateTime pt = publishTime == null ? LocalDateTime.MIN : publishTime;
|
||||
List<CmsArticle> list = articleRepository.findNextPublished(siteId,
|
||||
ArticleStatusEnum.PUBLISHED.getCode(), pt, articleId, PageRequest.of(0, 1));
|
||||
return list.isEmpty() ? null : toItem(list.get(0));
|
||||
}
|
||||
|
||||
private PortalListData emptyList(Integer page) {
|
||||
PortalListData data = new PortalListData();
|
||||
data.setPage(page == null ? 1 : page);
|
||||
return data;
|
||||
}
|
||||
|
||||
private String seoTitle(PortalCategory category, PortalSiteSnapshot site) {
|
||||
String title = category.getSeoTitle() == null || category.getSeoTitle().isEmpty()
|
||||
? category.getName() : category.getSeoTitle();
|
||||
return title + " - " + site.getName();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.yunhai.cms.controller.portal;
|
||||
|
||||
import com.yunhai.cms.entity.CmsSite;
|
||||
import com.yunhai.cms.repository.CmsSiteRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 门户根路径(/cms/portal/):跳转首个启用的顶层校站点(院系子站不作默认入口,《院系子站方案》)。
|
||||
* 容器健康探活打此路径(docker-compose healthcheck),返回 302 即视为存活。
|
||||
*/
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class PortalIndexController {
|
||||
|
||||
private final CmsSiteRepository siteRepository;
|
||||
|
||||
@GetMapping({"/portal", "/portal/"})
|
||||
public void index(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
// B-5:显式按 id 升序,多顶层站时 302 目标确定(healthcheck 与用户首跳不漂移)
|
||||
List<CmsSite> sites = siteRepository.findByStatusOrderByIdAsc(1);
|
||||
if (sites.isEmpty()) {
|
||||
response.sendError(HttpServletResponse.SC_NOT_FOUND, "暂无启用站点");
|
||||
return;
|
||||
}
|
||||
CmsSite target = sites.stream()
|
||||
.filter(s -> s.getParentSiteId() == null || s.getParentSiteId() == 0)
|
||||
.findFirst()
|
||||
.orElse(sites.get(0));
|
||||
response.sendRedirect(request.getContextPath() + "/portal/" + target.getCode() + "/");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.yunhai.cms.controller.portal;
|
||||
|
||||
import com.yunhai.cms.enums.CategoryTypeEnum;
|
||||
import com.yunhai.cms.enums.LinkTypeEnum;
|
||||
import com.yunhai.cms.model.portal.PortalBanner;
|
||||
import com.yunhai.cms.model.portal.PortalCategory;
|
||||
import com.yunhai.cms.model.portal.PortalListData;
|
||||
import com.yunhai.cms.model.portal.PortalSiteSnapshot;
|
||||
import com.yunhai.cms.repository.CmsArticleRepository;
|
||||
import com.yunhai.cms.utils.PortalUrlHelper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.ui.Model;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 门户页面装配组件(方案 §5.5,P1 抽取重构):PortalController 与主题预览接口共用,
|
||||
* 由 PortalSsrIT 全绿守护既有行为。首页数据装配(轮播时间窗/置顶/栏目区块)在此收口。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PortalPageRenderer {
|
||||
|
||||
/** 首页每个一级栏目取 N 条 */
|
||||
private static final int HOME_BLOCK_SIZE = 8;
|
||||
/** 首页置顶区取 N 条 */
|
||||
private static final int HOME_TOP_SIZE = 6;
|
||||
|
||||
private final CmsArticleRepository articleRepository;
|
||||
|
||||
/** 首页装配 + 视图名(方案 §4.3 契约:themeParams/themeVarsCss 顶层属性在此统一挂载) */
|
||||
public String renderHome(PortalSiteSnapshot site, PortalUrlHelper url, Model model) {
|
||||
model.addAttribute("url", url);
|
||||
model.addAttribute("site", site);
|
||||
model.addAttribute("themeParams", site.getThemeParams());
|
||||
model.addAttribute("themeVarsCss", site.getThemeVarsCss());
|
||||
model.addAttribute("themeBase", "themes/" + site.getTheme());
|
||||
model.addAttribute("navCategories", site.getCategories());
|
||||
List<Map<String, Object>> banners = activeBanners(site, "home", url);
|
||||
model.addAttribute("banners", banners);
|
||||
model.addAttribute("topArticles", topArticles(site.getId()));
|
||||
model.addAttribute("focusArticles", focusArticles(site.getId()));
|
||||
model.addAttribute("categoryBlocks", categoryBlocks(site.getId(), site.getCategories(), url));
|
||||
model.addAttribute("pageTitle", site.getName());
|
||||
model.addAttribute("seoDescription", site.getConfig() == null ? null
|
||||
: site.getConfig().get("seo_description"));
|
||||
model.addAttribute("canonical", url.home());
|
||||
// og:image(C-7):轮播首图(已补基准)优先,退站点 Logo
|
||||
Object firstBanner = banners.isEmpty() ? null : banners.get(0).get("imageUrl");
|
||||
Object logo = site.getConfig() == null ? null : site.getConfig().get("logo");
|
||||
model.addAttribute("ogImage", firstBanner != null ? firstBanner : url.upload(
|
||||
logo == null ? null : logo.toString()));
|
||||
return "themes/" + site.getTheme() + "/home";
|
||||
}
|
||||
|
||||
// ===== 内部装配(自 PortalController 原样迁移)=====
|
||||
|
||||
/** 启用中且在时间窗内的指定位轮播,并解析为完整跳转 URL */
|
||||
private List<Map<String, Object>> activeBanners(PortalSiteSnapshot site, String position,
|
||||
PortalUrlHelper url) {
|
||||
List<Map<String, Object>> result = new ArrayList<>();
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
for (PortalBanner b : site.getBanners()) {
|
||||
if (!position.equals(b.getPosition())) {
|
||||
continue;
|
||||
}
|
||||
if (b.getStartTime() != null && now.isBefore(b.getStartTime())) {
|
||||
continue; // 定时上线未到
|
||||
}
|
||||
if (b.getEndTime() != null && !now.isBefore(b.getEndTime())) {
|
||||
continue; // 已过下线时间
|
||||
}
|
||||
Map<String, Object> item = new HashMap<>();
|
||||
item.put("id", b.getId());
|
||||
item.put("title", b.getTitle());
|
||||
// 上传图渲染期补基准(B-1):入库相对地址 → 当前基准完整 URL
|
||||
item.put("imageUrl", url.upload(b.getImageUrl()));
|
||||
item.put("linkUrl", resolveBannerLink(b, url));
|
||||
result.add(item);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String resolveBannerLink(PortalBanner b, PortalUrlHelper url) {
|
||||
LinkTypeEnum type = LinkTypeEnum.byCode(b.getLinkType());
|
||||
if (type == LinkTypeEnum.ARTICLE) {
|
||||
return url.article(b.getLinkValue());
|
||||
}
|
||||
if (type == LinkTypeEnum.CATEGORY) {
|
||||
return url.category(b.getLinkValue());
|
||||
}
|
||||
return b.getLinkValue();
|
||||
}
|
||||
|
||||
/** 首页置顶文章区:数据库精确取 N 条(置顶优先 + 发布时间倒序) */
|
||||
private List<PortalListData.Item> topArticles(Integer siteId) {
|
||||
List<com.yunhai.cms.entity.CmsArticle> articles = articleRepository.findBySiteIdAndStatus(
|
||||
siteId, com.yunhai.cms.enums.ArticleStatusEnum.PUBLISHED.getCode(),
|
||||
PageRequest.of(0, HOME_TOP_SIZE,
|
||||
Sort.by(Sort.Order.desc("topmost"), Sort.Order.desc("publishTime"))));
|
||||
List<PortalListData.Item> items = new ArrayList<>();
|
||||
for (com.yunhai.cms.entity.CmsArticle a : articles) {
|
||||
items.add(toItem(a));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* 首页"图片新闻"卡(视觉精修 D2-1):有封面的已发布文章取 3 条(发布时间倒序)。
|
||||
* 无封面文章不进此卡(无封面边界由列表页文字行呈现,不造占位图)。
|
||||
*/
|
||||
private List<PortalListData.Item> focusArticles(Integer siteId) {
|
||||
List<com.yunhai.cms.entity.CmsArticle> articles = articleRepository.findBySiteIdAndStatus(
|
||||
siteId, com.yunhai.cms.enums.ArticleStatusEnum.PUBLISHED.getCode(),
|
||||
PageRequest.of(0, 30, Sort.by(Sort.Order.desc("publishTime"))));
|
||||
List<PortalListData.Item> items = new ArrayList<>();
|
||||
for (com.yunhai.cms.entity.CmsArticle a : articles) {
|
||||
if (a.getCoverImage() == null || a.getCoverImage().trim().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
items.add(toItem(a));
|
||||
if (items.size() >= 3) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* 首页一级栏目区块:每栏目精确取 top N(列表型栏目才出区块)。
|
||||
* D1-2:区块聚合列表型子孙栏目文章(文章通常挂叶子栏目,父栏目区块必须显示汇总)。
|
||||
*/
|
||||
private List<Map<String, Object>> categoryBlocks(Integer siteId, List<PortalCategory> categories,
|
||||
PortalUrlHelper url) {
|
||||
List<Map<String, Object>> blocks = new ArrayList<>();
|
||||
for (PortalCategory category : categories) {
|
||||
if (category.getType() == null || category.getType() != CategoryTypeEnum.LIST.getCode()) {
|
||||
continue;
|
||||
}
|
||||
List<Integer> categoryIds = new ArrayList<>();
|
||||
collectListDescendantIds(category, categoryIds);
|
||||
List<com.yunhai.cms.entity.CmsArticle> articles = articleRepository
|
||||
.findBySiteIdAndCategoryIdInAndStatus(siteId, categoryIds,
|
||||
com.yunhai.cms.enums.ArticleStatusEnum.PUBLISHED.getCode(),
|
||||
PageRequest.of(0, HOME_BLOCK_SIZE,
|
||||
Sort.by(Sort.Order.desc("topmost"), Sort.Order.desc("publishTime"))))
|
||||
.getContent();
|
||||
List<PortalListData.Item> items = new ArrayList<>();
|
||||
for (com.yunhai.cms.entity.CmsArticle a : articles) {
|
||||
items.add(toItem(a));
|
||||
}
|
||||
Map<String, Object> block = new HashMap<>();
|
||||
block.put("category", category);
|
||||
block.put("items", items);
|
||||
block.put("moreUrl", url.category(category.getId()));
|
||||
blocks.add(block);
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
/** 快照栏目树深度优先收集列表型子孙 id(含自身;单页/外链子孙不入列也不下钻) */
|
||||
private void collectListDescendantIds(PortalCategory category, List<Integer> ids) {
|
||||
ids.add(category.getId());
|
||||
for (PortalCategory child : category.getChildren()) {
|
||||
if (child.getType() != null && child.getType() == CategoryTypeEnum.LIST.getCode()) {
|
||||
collectListDescendantIds(child, ids);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private PortalListData.Item toItem(com.yunhai.cms.entity.CmsArticle a) {
|
||||
PortalListData.Item item = new PortalListData.Item();
|
||||
item.setId(a.getId());
|
||||
item.setTitle(a.getTitle());
|
||||
item.setSummary(a.getSummary());
|
||||
item.setCoverImage(a.getCoverImage());
|
||||
item.setPublishTime(a.getPublishTime());
|
||||
item.setTopmost(a.getTopmost());
|
||||
return item;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.yunhai.cms.controller.portal;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* 门户 HTML 路由异常落地为错误页(体检 H-1/H-2 根因修复)。
|
||||
*
|
||||
* <p>门户控制器抛异常原本落到平台 JSON 兜底(匿名访客看到裸 {"code":6,...})。
|
||||
* 本 advice 将参数类异常转 sendError(400)、其余转 sendError(500),
|
||||
* 经 Boot 错误页机制渲染 templates/error/ 下的皮肤化错误页;
|
||||
* 响应已提交(模板渲染中途失败)时只记日志不再改写响应。
|
||||
*/
|
||||
@Slf4j
|
||||
@ControllerAdvice(assignableTypes = {PortalController.class, PortalIndexController.class,
|
||||
PortalAssetController.class})
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class PortalWebExceptionHandler {
|
||||
|
||||
@ExceptionHandler({MethodArgumentTypeMismatchException.class,
|
||||
MissingServletRequestParameterException.class})
|
||||
public void badRequest(Exception e, HttpServletResponse response) throws Exception {
|
||||
if (response.isCommitted()) {
|
||||
log.warn("门户参数异常但响应已提交: {}", e.getMessage());
|
||||
return;
|
||||
}
|
||||
log.warn("门户参数异常: {}", e.getMessage());
|
||||
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public void serverError(Exception e, HttpServletResponse response) throws Exception {
|
||||
if (response.isCommitted()) {
|
||||
log.warn("门户渲染异常且响应已提交: {}", e.getMessage());
|
||||
return;
|
||||
}
|
||||
log.error("门户渲染异常", e);
|
||||
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.yunhai.cms.entity;
|
||||
|
||||
import com.yunhai.cms.common.CmsAuditListener;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.EntityListeners;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.MappedSuperclass;
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 所有实体的公共基类:自增主键 + 创建人/时间 + 更新人/时间(由 CmsAuditListener 自动填充)。
|
||||
* 操作日志独立表为演进项(方案 §2),MVP 靠本审计四字段追溯。
|
||||
*/
|
||||
@MappedSuperclass
|
||||
@Getter
|
||||
@Setter
|
||||
@EntityListeners(CmsAuditListener.class)
|
||||
public abstract class BaseEntity implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Integer id;
|
||||
|
||||
@Column(name = "create_by", updatable = false)
|
||||
private String createBy;
|
||||
|
||||
@Column(name = "create_time", updatable = false)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@Column(name = "update_by")
|
||||
private String updateBy;
|
||||
|
||||
@Column(name = "update_time")
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.yunhai.cms.entity;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Index;
|
||||
import javax.persistence.Table;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* CMS 文章(方案 §5.1 表3)。
|
||||
* 审核状态机为演进项(触发后加 audit_status 列);ext_json 保留键:
|
||||
* {@code wechat}(推送回执,本期不写)、{@code albums}(图集演进)。
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@Entity
|
||||
@Table(name = "cms_article", indexes = {
|
||||
@Index(name = "idx_art_list", columnList = "site_id, category_id, status, publish_time"),
|
||||
@Index(name = "idx_art_site_top", columnList = "site_id, status, topmost")})
|
||||
public class CmsArticle extends BaseEntity {
|
||||
|
||||
/** 所属站点(隔离/查询维度;文章不冗余 sch_id,权限经 site 一跳映射) */
|
||||
@Column(name = "site_id", nullable = false)
|
||||
private Integer siteId;
|
||||
|
||||
/** 所属栏目(逻辑外键 → cms_category.id) */
|
||||
@Column(name = "category_id", nullable = false)
|
||||
private Integer categoryId;
|
||||
|
||||
/** 标题 */
|
||||
@Column(name = "title", nullable = false, length = 200)
|
||||
private String title;
|
||||
|
||||
/** 摘要(列表/SEO 用,空=截取正文) */
|
||||
@Column(name = "summary", length = 500)
|
||||
private String summary;
|
||||
|
||||
/** 正文 HTML(wangEditor 产出,保存时 jsoup 白名单清洗,方案 §8.5) */
|
||||
@Column(name = "content", columnDefinition = "LONGTEXT")
|
||||
private String content;
|
||||
|
||||
/** 封面图 URL */
|
||||
@Column(name = "cover_image", length = 500)
|
||||
private String coverImage;
|
||||
|
||||
/** 作者账号(发布时从 BoaUser 填充) */
|
||||
@Column(name = "author_account", length = 64)
|
||||
private String authorAccount;
|
||||
|
||||
/** 作者姓名(冗余展示) */
|
||||
@Column(name = "author_name", length = 64)
|
||||
private String authorName;
|
||||
|
||||
/** 来源(转载出处) */
|
||||
@Column(name = "source", length = 128)
|
||||
private String source;
|
||||
|
||||
/** 状态:0=草稿 1=已发布 2=已下架(见 ArticleStatusEnum) */
|
||||
@Column(name = "status", nullable = false)
|
||||
private Integer status = 0;
|
||||
|
||||
/** 置顶:0/1 */
|
||||
@Column(name = "topmost", nullable = false)
|
||||
private Integer topmost = 0;
|
||||
|
||||
/** 发布时间(空=保存即发布;未来=定时发布) */
|
||||
@Column(name = "publish_time")
|
||||
private LocalDateTime publishTime;
|
||||
|
||||
/** 下架时间(可选,@Scheduled 每分钟扫描到期记录) */
|
||||
@Column(name = "offline_time")
|
||||
private LocalDateTime offlineTime;
|
||||
|
||||
/** 浏览量(MVP 异步累加,量大后改缓存聚合) */
|
||||
@Column(name = "view_count", nullable = false)
|
||||
private Integer viewCount = 0;
|
||||
|
||||
/** 扩展字段 JSON(wechat/albums 预留,免 DDL 演进) */
|
||||
@Column(name = "ext_json", columnDefinition = "JSON")
|
||||
private String extJson;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.yunhai.cms.entity;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Index;
|
||||
import javax.persistence.Table;
|
||||
|
||||
/**
|
||||
* CMS 附件(正文图片 + 文档附件 + 轮播图/友链 Logo 复用同一上传链路,方案 §7.3)。
|
||||
* 文章删除时附件记录保留、article_id 置空成"孤儿",由附件管理页清理。
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@Entity
|
||||
@Table(name = "cms_attachment", indexes = {
|
||||
@Index(name = "idx_att_article", columnList = "article_id"),
|
||||
@Index(name = "idx_att_site", columnList = "site_id")})
|
||||
public class CmsAttachment extends BaseEntity {
|
||||
|
||||
/** 所属站点 */
|
||||
@Column(name = "site_id", nullable = false)
|
||||
private Integer siteId;
|
||||
|
||||
/** 关联文章(编辑器图片保存时回填) */
|
||||
@Column(name = "article_id")
|
||||
private Integer articleId;
|
||||
|
||||
/** 原始文件名 */
|
||||
@Column(name = "file_name", nullable = false, length = 255)
|
||||
private String fileName;
|
||||
|
||||
/** 存储路径(相对 FILE_PATH) */
|
||||
@Column(name = "file_path", nullable = false, length = 500)
|
||||
private String filePath;
|
||||
|
||||
/** Web 访问 URL */
|
||||
@Column(name = "web_url", nullable = false, length = 500)
|
||||
private String webUrl;
|
||||
|
||||
/** 字节数 */
|
||||
@Column(name = "file_size")
|
||||
private Long fileSize;
|
||||
|
||||
/** MIME 类型 */
|
||||
@Column(name = "mime_type", length = 128)
|
||||
private String mimeType;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.yunhai.cms.entity;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Index;
|
||||
import javax.persistence.Table;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* CMS 轮播/推荐位(首页 banner、图片新闻位等,方案 §5.1 表5)。
|
||||
* 定时上下线靠门户渲染时过滤 start/end(无需调度任务改状态)。
|
||||
* 广告投放统计不做(方案 §2)。
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@Entity
|
||||
@Table(name = "cms_banner", indexes = @Index(name = "idx_banner", columnList = "site_id, position, status, sort_no"))
|
||||
public class CmsBanner extends BaseEntity {
|
||||
|
||||
/** 所属站点 */
|
||||
@Column(name = "site_id", nullable = false)
|
||||
private Integer siteId;
|
||||
|
||||
/** 展示位标识(home=首页轮播;皮肤包约定其他位) */
|
||||
@Column(name = "position", nullable = false, length = 32)
|
||||
private String position = "home";
|
||||
|
||||
/** 标题(alt 文案/无图兜底) */
|
||||
@Column(name = "title", nullable = false, length = 200)
|
||||
private String title;
|
||||
|
||||
/** 图片 URL(上传至 FILE_PATH) */
|
||||
@Column(name = "image_url", nullable = false, length = 500)
|
||||
private String imageUrl;
|
||||
|
||||
/** 跳转类型:1=文章 2=栏目 3=外链(见 LinkTypeEnum) */
|
||||
@Column(name = "link_type", nullable = false)
|
||||
private Integer linkType = 1;
|
||||
|
||||
/** 跳转目标(文章ID/栏目ID/URL,按 link_type 解释) */
|
||||
@Column(name = "link_value", length = 500)
|
||||
private String linkValue;
|
||||
|
||||
/** 同级排序(升序) */
|
||||
@Column(name = "sort_no", nullable = false)
|
||||
private Integer sortNo = 0;
|
||||
|
||||
/** 上线时间(空=立即;未来=定时上线) */
|
||||
@Column(name = "start_time")
|
||||
private LocalDateTime startTime;
|
||||
|
||||
/** 下线时间(可选,门户渲染时过滤) */
|
||||
@Column(name = "end_time")
|
||||
private LocalDateTime endTime;
|
||||
|
||||
/** 状态:0=停用 1=启用 */
|
||||
@Column(name = "status", nullable = false)
|
||||
private Integer status = 1;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.yunhai.cms.entity;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Index;
|
||||
import javax.persistence.Table;
|
||||
|
||||
/**
|
||||
* CMS 栏目(站点内树形,方案 §5.1 表2)。
|
||||
* 旧 CMS3.0 的"频道"层收敛为本表 type(列表/单页/外链),覆盖原频道全部用法。
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@Entity
|
||||
@Table(name = "cms_category", indexes = @Index(name = "idx_cat_tree", columnList = "site_id, parent_id, sort_no"))
|
||||
public class CmsCategory extends BaseEntity {
|
||||
|
||||
/** 所属站点(逻辑外键 → cms_site.id) */
|
||||
@Column(name = "site_id", nullable = false)
|
||||
private Integer siteId;
|
||||
|
||||
/** 父栏目ID(0=根) */
|
||||
@Column(name = "parent_id", nullable = false)
|
||||
private Integer parentId = 0;
|
||||
|
||||
/** 栏目名称 */
|
||||
@Column(name = "name", nullable = false, length = 64)
|
||||
private String name;
|
||||
|
||||
/** 栏目类型:1=文章列表 2=单页 3=外链(见 CategoryTypeEnum) */
|
||||
@Column(name = "type", nullable = false)
|
||||
private Integer type = 1;
|
||||
|
||||
/** 外链地址(type=3 必填) */
|
||||
@Column(name = "link_url", length = 500)
|
||||
private String linkUrl;
|
||||
|
||||
/** 栏目模板覆盖(空=按 type 取默认,预留能力,方案 §8.2) */
|
||||
@Column(name = "template", length = 64)
|
||||
private String template;
|
||||
|
||||
/**
|
||||
* 单页栏目内容(type=2 时门户直接渲染;经 jsoup 白名单清洗入库)。
|
||||
* 注:方案 §8.1 要求单页直接渲染 content,但 §5.1 DDL 漏列,此处补齐(ddl-auto=update 自动加列)。
|
||||
*/
|
||||
@Column(name = "content", columnDefinition = "LONGTEXT")
|
||||
private String content;
|
||||
|
||||
/** 同级排序(升序) */
|
||||
@Column(name = "sort_no", nullable = false)
|
||||
private Integer sortNo = 0;
|
||||
|
||||
/** SEO 标题(空=用栏目名) */
|
||||
@Column(name = "seo_title", length = 200)
|
||||
private String seoTitle;
|
||||
|
||||
/** SEO 描述 */
|
||||
@Column(name = "seo_description", length = 500)
|
||||
private String seoDescription;
|
||||
|
||||
/** 状态:0=隐藏 1=显示 */
|
||||
@Column(name = "status", nullable = false)
|
||||
private Integer status = 1;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.yunhai.cms.entity;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Index;
|
||||
import javax.persistence.Table;
|
||||
|
||||
/**
|
||||
* CMS 友情链接(页脚/首页分组成员,方案 §5.1 表6)。
|
||||
* 分组即旧 linkCategory:上级部门/兄弟院校/合作单位…,group_name 字符串直接分组。
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@Entity
|
||||
@Table(name = "cms_link", indexes = @Index(name = "idx_link", columnList = "site_id, group_name, sort_no"))
|
||||
public class CmsLink extends BaseEntity {
|
||||
|
||||
/** 所属站点 */
|
||||
@Column(name = "site_id", nullable = false)
|
||||
private Integer siteId;
|
||||
|
||||
/** 分组(上级部门/兄弟院校/合作单位…) */
|
||||
@Column(name = "group_name", nullable = false, length = 64)
|
||||
private String groupName = "default";
|
||||
|
||||
/** 链接名称 */
|
||||
@Column(name = "name", nullable = false, length = 128)
|
||||
private String name;
|
||||
|
||||
/** Logo URL(可选,文字链可空) */
|
||||
@Column(name = "logo_url", length = 500)
|
||||
private String logoUrl;
|
||||
|
||||
/** 链接地址 */
|
||||
@Column(name = "link_url", nullable = false, length = 500)
|
||||
private String linkUrl;
|
||||
|
||||
/** 组内排序(升序) */
|
||||
@Column(name = "sort_no", nullable = false)
|
||||
private Integer sortNo = 0;
|
||||
|
||||
/** 状态:0=隐藏 1=显示 */
|
||||
@Column(name = "status", nullable = false)
|
||||
private Integer status = 1;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.yunhai.cms.entity;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Index;
|
||||
import javax.persistence.Table;
|
||||
import javax.persistence.UniqueConstraint;
|
||||
|
||||
/**
|
||||
* CMS 站点(多租户根,方案 §5.1 表1)。
|
||||
*
|
||||
* <p>站点层级(《院系子站方案》):{@code parent_site_id}=0 为顶层校站点(一校一主站),
|
||||
* >0 为该院系子站(挂主站 id,层级固定两层)。
|
||||
*
|
||||
* <p>config_json 保留键(方案 §8.6):{@code domain}(学校绑定域名台账)、
|
||||
* {@code public_base_url}(对外基地址,默认派生自 base 域,绑学校域名后覆盖)、
|
||||
* {@code colleges_label}(门户"专业院系"下拉文案,默认"专业院系")、
|
||||
* {@code wechat}(公众号配置节点,本期不写,见微信平台对接方案)。
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@Entity
|
||||
@Table(name = "cms_site",
|
||||
uniqueConstraints = @UniqueConstraint(name = "uk_site_code", columnNames = "code"),
|
||||
indexes = @Index(name = "idx_site_sch", columnList = "sch_id"))
|
||||
public class CmsSite extends BaseEntity {
|
||||
|
||||
/** 站点编码,URL 路径用(/portal/{code}) */
|
||||
@Column(name = "code", nullable = false, length = 64)
|
||||
private String code;
|
||||
|
||||
/** 上级站点ID(0=顶层校站点;院系子站挂主站 id,层级固定两层) */
|
||||
@Column(name = "parent_site_id", nullable = false)
|
||||
private Integer parentSiteId = 0;
|
||||
|
||||
/** 学校ID(逻辑外键 → UserBase sys_group.id) */
|
||||
@Column(name = "sch_id")
|
||||
private Integer schId;
|
||||
|
||||
/** 学校名称(冗余展示) */
|
||||
@Column(name = "sch_name", length = 128)
|
||||
private String schName;
|
||||
|
||||
/** 站点名称 */
|
||||
@Column(name = "name", nullable = false, length = 128)
|
||||
private String name;
|
||||
|
||||
/** 皮肤包名(classpath:/templates/themes/{theme}/) */
|
||||
@Column(name = "theme", length = 64)
|
||||
private String theme = "default";
|
||||
|
||||
/** 站点配置 JSON(logo/联系方式/页脚/domain/public_base_url) */
|
||||
@Column(name = "config_json", columnDefinition = "JSON")
|
||||
private String configJson;
|
||||
|
||||
/** 状态:0=停用 1=启用 */
|
||||
@Column(name = "status", nullable = false)
|
||||
private Integer status = 1;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.yunhai.cms.enums;
|
||||
|
||||
/**
|
||||
* 文章状态:MVP 草稿→发布 两态 + 已下架;审核状态机为演进项(方案 §2/§5.2)。
|
||||
*/
|
||||
public enum ArticleStatusEnum {
|
||||
|
||||
/** 草稿(publish_time 为未来时间时即"定时发布"待触发) */
|
||||
DRAFT(0),
|
||||
/** 已发布 */
|
||||
PUBLISHED(1),
|
||||
/** 已下架 */
|
||||
OFFLINE(2);
|
||||
|
||||
private final int code;
|
||||
|
||||
ArticleStatusEnum(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public static ArticleStatusEnum byCode(Integer code) {
|
||||
if (code == null) {
|
||||
return DRAFT;
|
||||
}
|
||||
for (ArticleStatusEnum e : values()) {
|
||||
if (e.code == code) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
return DRAFT;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.yunhai.cms.enums;
|
||||
|
||||
/**
|
||||
* 栏目类型(旧 CMS3.0"频道"层收敛而来,方案 §2/§5.2):
|
||||
* 文章列表 / 单页 / 外链 三类覆盖原频道全部用法。
|
||||
*/
|
||||
public enum CategoryTypeEnum {
|
||||
|
||||
/** 文章列表 */
|
||||
LIST(1),
|
||||
/** 单页(直接渲染 content) */
|
||||
SINGLE(2),
|
||||
/** 外链(门户 302 跳转) */
|
||||
LINK(3);
|
||||
|
||||
private final int code;
|
||||
|
||||
CategoryTypeEnum(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public static CategoryTypeEnum byCode(Integer code) {
|
||||
if (code == null) {
|
||||
return LIST;
|
||||
}
|
||||
for (CategoryTypeEnum e : values()) {
|
||||
if (e.code == code) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
return LIST;
|
||||
}
|
||||
|
||||
/** 严格解析:未知/空返回 null(用户输入校验用;渲染期脏数据仍走 byCode 宽松回退) */
|
||||
public static CategoryTypeEnum ofCode(Integer code) {
|
||||
if (code == null) {
|
||||
return null;
|
||||
}
|
||||
for (CategoryTypeEnum e : values()) {
|
||||
if (e.code == code) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.yunhai.cms.enums;
|
||||
|
||||
/**
|
||||
* 跳转类型(轮播 link_type 等通用;方案 §5.1 表5)。
|
||||
* 计划中的 LinkTypeEnum/BannerLinkTypeEnum 语义重合,合并为本枚举。
|
||||
*/
|
||||
public enum LinkTypeEnum {
|
||||
|
||||
/** 文章(link_value=文章ID,门户渲染为 /portal/{code}/a/{id}) */
|
||||
ARTICLE(1),
|
||||
/** 栏目(link_value=栏目ID,渲染为 /portal/{code}/c/{id}) */
|
||||
CATEGORY(2),
|
||||
/** 外链(link_value=完整 URL) */
|
||||
EXTERNAL(3);
|
||||
|
||||
private final int code;
|
||||
|
||||
LinkTypeEnum(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public static LinkTypeEnum byCode(Integer code) {
|
||||
if (code == null) {
|
||||
return ARTICLE;
|
||||
}
|
||||
for (LinkTypeEnum e : values()) {
|
||||
if (e.code == code) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
return ARTICLE;
|
||||
}
|
||||
|
||||
/** 严格解析:未知/空返回 null(用户输入校验用;渲染期脏数据仍走 byCode 宽松回退) */
|
||||
public static LinkTypeEnum ofCode(Integer code) {
|
||||
if (code == null) {
|
||||
return null;
|
||||
}
|
||||
for (LinkTypeEnum e : values()) {
|
||||
if (e.code == code) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.yunhai.cms.event;
|
||||
|
||||
/**
|
||||
* 文章内容变更事件(保存修改/下架/删除)。事务提交后触发缓存失效(方案 §8.4)。
|
||||
*/
|
||||
public class ArticleChangedEvent {
|
||||
|
||||
private final Integer articleId;
|
||||
private final Integer siteId;
|
||||
|
||||
public ArticleChangedEvent(Integer articleId, Integer siteId) {
|
||||
this.articleId = articleId;
|
||||
this.siteId = siteId;
|
||||
}
|
||||
|
||||
public Integer getArticleId() {
|
||||
return articleId;
|
||||
}
|
||||
|
||||
public Integer getSiteId() {
|
||||
return siteId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.yunhai.cms.event;
|
||||
|
||||
/**
|
||||
* 文章发布事件(方案 §7.4 微信预留挂点):事务提交后由 AFTER_COMMIT 监听器消费。
|
||||
* 本期监听方 = 缓存失效 + WeChatPushService(Noop 实现,零外联);
|
||||
* 启用《微信平台对接方案》时仅替换 Noop 实现,零表结构变更。
|
||||
*/
|
||||
public class ArticlePublishedEvent {
|
||||
|
||||
private final Integer articleId;
|
||||
private final Integer siteId;
|
||||
private final String title;
|
||||
|
||||
public ArticlePublishedEvent(Integer articleId, Integer siteId, String title) {
|
||||
this.articleId = articleId;
|
||||
this.siteId = siteId;
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public Integer getArticleId() {
|
||||
return articleId;
|
||||
}
|
||||
|
||||
public Integer getSiteId() {
|
||||
return siteId;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.yunhai.cms.event;
|
||||
|
||||
/**
|
||||
* 站点内容/结构变更事件:站点本身、栏目树、轮播、友链 任一变更即发,
|
||||
* 门户站点快照缓存(cms:site)整体失效 + 列表缓存清除(方案 §8.4)。
|
||||
*/
|
||||
public class SiteContentChangedEvent {
|
||||
|
||||
private final Integer siteId;
|
||||
|
||||
/** 变更来源说明(日志用):site/category/banner/link */
|
||||
private final String scope;
|
||||
|
||||
public SiteContentChangedEvent(Integer siteId, String scope) {
|
||||
this.siteId = siteId;
|
||||
this.scope = scope;
|
||||
}
|
||||
|
||||
public Integer getSiteId() {
|
||||
return siteId;
|
||||
}
|
||||
|
||||
public String getScope() {
|
||||
return scope;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.yunhai.cms.event.listener;
|
||||
|
||||
import com.yunhai.cms.config.CacheNames;
|
||||
import com.yunhai.cms.event.ArticleChangedEvent;
|
||||
import com.yunhai.cms.event.ArticlePublishedEvent;
|
||||
import com.yunhai.cms.event.SiteContentChangedEvent;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.event.TransactionPhase;
|
||||
import org.springframework.transaction.event.TransactionalEventListener;
|
||||
|
||||
/**
|
||||
* 门户缓存失效监听(方案 §8.4):全部 AFTER_COMMIT(fallbackExecution=true 兼容
|
||||
* 定时任务等无事务路径),失效失败仅记日志,靠 TTL 自愈。
|
||||
*
|
||||
* <p>cms:list / cms:site 的 key 含分页与站点维度,MVP 直接整缓存 clear:
|
||||
* 单实例 Caffeine、站点 ≤20,clear 成本可忽略;精确 evict 留给 Redis 演进。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PortalCacheEvictListener {
|
||||
|
||||
private final CacheManager cacheManager;
|
||||
|
||||
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
|
||||
public void onArticlePublished(ArticlePublishedEvent event) {
|
||||
evictArticle(event.getArticleId());
|
||||
clear(CacheNames.LIST);
|
||||
}
|
||||
|
||||
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
|
||||
public void onArticleChanged(ArticleChangedEvent event) {
|
||||
evictArticle(event.getArticleId());
|
||||
clear(CacheNames.LIST);
|
||||
}
|
||||
|
||||
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
|
||||
public void onSiteContentChanged(SiteContentChangedEvent event) {
|
||||
clear(CacheNames.SITE);
|
||||
clear(CacheNames.LIST);
|
||||
}
|
||||
|
||||
private void evictArticle(Integer articleId) {
|
||||
Cache cache = cacheManager.getCache(CacheNames.ARTICLE);
|
||||
if (cache != null && articleId != null) {
|
||||
cache.evict(articleId);
|
||||
}
|
||||
}
|
||||
|
||||
private void clear(String cacheName) {
|
||||
Cache cache = cacheManager.getCache(cacheName);
|
||||
if (cache != null) {
|
||||
cache.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.yunhai.cms.event.listener;
|
||||
|
||||
import com.yunhai.cms.event.ArticlePublishedEvent;
|
||||
import com.yunhai.cms.service.WeChatPushService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.event.TransactionPhase;
|
||||
import org.springframework.transaction.event.TransactionalEventListener;
|
||||
|
||||
/**
|
||||
* 文章发布 → 微信推送挂点(方案 §7.4 后端层预留)。
|
||||
* 事务提交后才触发,保证推送方读到的数据已落库;推送失败不影响业务事务。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class WeChatPushListener {
|
||||
|
||||
private final WeChatPushService weChatPushService;
|
||||
|
||||
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
|
||||
public void onArticlePublished(ArticlePublishedEvent event) {
|
||||
weChatPushService.onArticlePublished(event);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.yunhai.cms.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 文章保存(草稿,content 先过 jsoup 白名单,方案 §9.2)。
|
||||
* 发布语义见 ArticleService.publish:publishTime 为未来时间即"定时发布"。
|
||||
*/
|
||||
@Data
|
||||
public class ArticleSaveRequest {
|
||||
|
||||
/** 修改时必填 */
|
||||
private Integer id;
|
||||
|
||||
@NotNull(message = "siteId 不得为空")
|
||||
private Integer siteId;
|
||||
|
||||
@NotNull(message = "所属栏目不得为空")
|
||||
private Integer categoryId;
|
||||
|
||||
@NotBlank(message = "标题不得为空")
|
||||
@Size(max = 200, message = "标题过长")
|
||||
private String title;
|
||||
|
||||
/** 摘要(空=服务端截取正文) */
|
||||
@Size(max = 500, message = "摘要过长")
|
||||
private String summary;
|
||||
|
||||
/** 正文 HTML(服务端 jsoup 清洗后入库) */
|
||||
private String content;
|
||||
|
||||
@Size(max = 500)
|
||||
private String coverImage;
|
||||
|
||||
/** 作者姓名(展示用;账号发布时自动从 BoaUser 填充) */
|
||||
@Size(max = 64)
|
||||
private String authorName;
|
||||
|
||||
@Size(max = 128)
|
||||
private String source;
|
||||
|
||||
/** 置顶:0/1 */
|
||||
private Integer topmost = 0;
|
||||
|
||||
/** 定时发布时间(空=不指定,发布动作时取当前时间) */
|
||||
private LocalDateTime publishTime;
|
||||
|
||||
/** 定时下架时间(可空) */
|
||||
private LocalDateTime offlineTime;
|
||||
|
||||
/**
|
||||
* 同步到公众号开关(微信预留入口,本期恒禁用,方案 §7.4)。
|
||||
* 仅作占位字段,后端不消费;启用后写 ext_json.wechat。
|
||||
*/
|
||||
private Boolean syncWechat = false;
|
||||
|
||||
/** 本次编辑上传的附件 id 列表(保存时回填 article_id 归属,方案 §5.1 表4) */
|
||||
private java.util.List<Integer> attachmentIds;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.yunhai.cms.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 轮播保存(校验 link_type/link_value,方案 §9.2)。
|
||||
*/
|
||||
@Data
|
||||
public class BannerSaveRequest {
|
||||
|
||||
/** 修改时必填 */
|
||||
private Integer id;
|
||||
|
||||
@NotNull(message = "siteId 不得为空")
|
||||
private Integer siteId;
|
||||
|
||||
/** 展示位(home=首页轮播) */
|
||||
@Size(max = 32)
|
||||
private String position = "home";
|
||||
|
||||
@NotBlank(message = "标题不得为空")
|
||||
@Size(max = 200, message = "标题过长")
|
||||
private String title;
|
||||
|
||||
@NotBlank(message = "图片不得为空")
|
||||
@Size(max = 500)
|
||||
private String imageUrl;
|
||||
|
||||
/** 1=文章 2=栏目 3=外链 */
|
||||
@NotNull(message = "跳转类型不得为空")
|
||||
private Integer linkType;
|
||||
|
||||
/** 跳转目标:文章ID/栏目ID/URL(服务端按类型校验必填与存在性) */
|
||||
@Size(max = 500, message = "跳转目标过长")
|
||||
private String linkValue;
|
||||
|
||||
private Integer sortNo = 0;
|
||||
|
||||
/** 上线时间(空=立即) */
|
||||
private LocalDateTime startTime;
|
||||
|
||||
/** 下线时间(可空) */
|
||||
private LocalDateTime endTime;
|
||||
|
||||
/** 0=停用 1=启用 */
|
||||
private Integer status = 1;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.yunhai.cms.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
/**
|
||||
* 栏目保存(新增 id 空 / 修改 id 必填,方案 §9.2)。
|
||||
*/
|
||||
@Data
|
||||
public class CategorySaveRequest {
|
||||
|
||||
/** 修改时必填 */
|
||||
private Integer id;
|
||||
|
||||
@NotNull(message = "siteId 不得为空")
|
||||
private Integer siteId;
|
||||
|
||||
/** 父栏目ID(0=根) */
|
||||
@NotNull(message = "父栏目不得为空")
|
||||
private Integer parentId;
|
||||
|
||||
@NotBlank(message = "栏目名称不得为空")
|
||||
@Size(max = 64, message = "栏目名称过长")
|
||||
private String name;
|
||||
|
||||
/** 1=文章列表 2=单页 3=外链 */
|
||||
@NotNull(message = "栏目类型不得为空")
|
||||
private Integer type;
|
||||
|
||||
/** 外链地址(type=3 必填,服务端校验) */
|
||||
@Size(max = 500, message = "外链地址过长")
|
||||
private String linkUrl;
|
||||
|
||||
/** 栏目模板覆盖(预留能力) */
|
||||
@Size(max = 64)
|
||||
private String template;
|
||||
|
||||
/** 单页栏目内容(type=2 有效,服务端 jsoup 清洗后入库) */
|
||||
private String content;
|
||||
|
||||
private Integer sortNo = 0;
|
||||
|
||||
@Size(max = 200)
|
||||
private String seoTitle;
|
||||
|
||||
@Size(max = 500)
|
||||
private String seoDescription;
|
||||
|
||||
/** 0=隐藏 1=显示 */
|
||||
private Integer status = 1;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.yunhai.cms.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 子栏目排序入参(UserBase SysGroupSortRequest 同语义:ids 顺序即 sortNo 1..n)。
|
||||
*/
|
||||
@Data
|
||||
public class CategorySortRequest {
|
||||
|
||||
/** 站点 ID(权限校验用) */
|
||||
@NotNull(message = "站点ID不能为空")
|
||||
private Integer siteId;
|
||||
|
||||
/** 父栏目 ID(0=根栏目下的排序) */
|
||||
@NotNull(message = "父栏目ID不能为空")
|
||||
private Integer parentId;
|
||||
|
||||
/** 期望的、parentId 直接子栏目有序 ID 列表(按传入顺序生效) */
|
||||
@NotNull(message = "子栏目ID列表不能为空")
|
||||
private List<Integer> ids;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.yunhai.cms.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
/**
|
||||
* 通用删除入参:id + siteId(siteId 用于站点归属权限校验,避免越权 id 枚举)。
|
||||
*/
|
||||
@Data
|
||||
public class DeleteRequest {
|
||||
|
||||
@NotNull(message = "id 不得为空")
|
||||
private Integer id;
|
||||
|
||||
@NotNull(message = "siteId 不得为空")
|
||||
private Integer siteId;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.yunhai.cms.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
/**
|
||||
* 友链保存(方案 §9.2)。
|
||||
*/
|
||||
@Data
|
||||
public class LinkSaveRequest {
|
||||
|
||||
/** 修改时必填 */
|
||||
private Integer id;
|
||||
|
||||
@NotNull(message = "siteId 不得为空")
|
||||
private Integer siteId;
|
||||
|
||||
/** 分组(上级部门/兄弟院校/合作单位…,空=default) */
|
||||
@Size(max = 64, message = "分组名过长")
|
||||
private String groupName = "default";
|
||||
|
||||
@NotBlank(message = "链接名称不得为空")
|
||||
@Size(max = 128, message = "链接名称过长")
|
||||
private String name;
|
||||
|
||||
/** Logo(可空,文字链) */
|
||||
@Size(max = 500)
|
||||
private String logoUrl;
|
||||
|
||||
@NotBlank(message = "链接地址不得为空")
|
||||
@Size(max = 500, message = "链接地址过长")
|
||||
private String linkUrl;
|
||||
|
||||
private Integer sortNo = 0;
|
||||
|
||||
/** 0=隐藏 1=显示 */
|
||||
private Integer status = 1;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.yunhai.cms.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Pattern;
|
||||
import javax.validation.constraints.Size;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 站点保存(仅超管可见,方案 §9.1/§7.2)。
|
||||
* MVP 1-2 校:初始化脚本建站即可,本接口为超管后台兜底入口。
|
||||
*/
|
||||
@Data
|
||||
public class SiteSaveRequest {
|
||||
|
||||
/** 修改时必填 */
|
||||
private Integer id;
|
||||
|
||||
@NotBlank(message = "站点编码不得为空")
|
||||
@Pattern(regexp = "^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$", message = "编码仅限小写字母/数字/短横线")
|
||||
private String code;
|
||||
|
||||
/** 上级站点ID(空或 0=顶层校站点;院系子站挂主站 id,《院系子站方案》) */
|
||||
private Integer parentSiteId;
|
||||
|
||||
private Integer schId;
|
||||
|
||||
@Size(max = 128)
|
||||
private String schName;
|
||||
|
||||
@NotBlank(message = "站点名称不得为空")
|
||||
@Size(max = 128, message = "站点名称过长")
|
||||
private String name;
|
||||
|
||||
/** 皮肤包名(空=default) */
|
||||
@Size(max = 64)
|
||||
private String theme;
|
||||
|
||||
/**
|
||||
* 站点配置 JSON(logo/联系方式/页脚;保留键 domain/public_base_url/wechat,方案 §8.6)。
|
||||
* 服务端做 JSON 合法性校验。
|
||||
*/
|
||||
private String configJson;
|
||||
|
||||
/**
|
||||
* 主题微调参数(方案 §5.3):仅接收所选主题 theme.json 声明过的 key;
|
||||
* 服务端校验后合并进 config_json.theme_params(保留其余键),非法 key/值服务端丢弃。
|
||||
*/
|
||||
private Map<String, String> themeParams;
|
||||
|
||||
/** 0=停用 1=启用 */
|
||||
private Integer status = 1;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.yunhai.cms.model.portal;
|
||||
|
||||
import com.yunhai.cms.entity.CmsArticle;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 门户文章详情(cms:article 缓存体;已发布文章才缓存,null 哨兵 30s 防穿透)。
|
||||
*/
|
||||
@Data
|
||||
public class PortalArticleDetail {
|
||||
|
||||
private Integer id;
|
||||
|
||||
private Integer siteId;
|
||||
|
||||
private Integer categoryId;
|
||||
|
||||
private String title;
|
||||
|
||||
/** 正文(入库前已 jsoup 清洗,模板 th:utext 输出) */
|
||||
private String content;
|
||||
|
||||
private String summary;
|
||||
|
||||
private String coverImage;
|
||||
|
||||
private String authorName;
|
||||
|
||||
private String source;
|
||||
|
||||
private LocalDateTime publishTime;
|
||||
|
||||
private Integer viewCount;
|
||||
|
||||
public static PortalArticleDetail of(CmsArticle a) {
|
||||
PortalArticleDetail detail = new PortalArticleDetail();
|
||||
detail.setId(a.getId());
|
||||
detail.setSiteId(a.getSiteId());
|
||||
detail.setCategoryId(a.getCategoryId());
|
||||
detail.setTitle(a.getTitle());
|
||||
detail.setContent(a.getContent());
|
||||
detail.setSummary(a.getSummary());
|
||||
detail.setCoverImage(a.getCoverImage());
|
||||
detail.setAuthorName(a.getAuthorName());
|
||||
detail.setSource(a.getSource());
|
||||
detail.setPublishTime(a.getPublishTime());
|
||||
detail.setViewCount(a.getViewCount());
|
||||
return detail;
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染副本(B-1):本对象是 cms:article 缓存体(两种暴露形态共享),
|
||||
* 正文上传地址需按当前请求基准重写,故拷贝后替换 content,不回写缓存。
|
||||
*/
|
||||
public PortalArticleDetail withContent(String content) {
|
||||
PortalArticleDetail copy = new PortalArticleDetail();
|
||||
copy.id = id;
|
||||
copy.siteId = siteId;
|
||||
copy.categoryId = categoryId;
|
||||
copy.title = title;
|
||||
copy.content = content;
|
||||
copy.summary = summary;
|
||||
copy.coverImage = coverImage;
|
||||
copy.authorName = authorName;
|
||||
copy.source = source;
|
||||
copy.publishTime = publishTime;
|
||||
copy.viewCount = viewCount;
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.yunhai.cms.model.portal;
|
||||
|
||||
import com.yunhai.cms.entity.CmsBanner;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 门户轮播项(启用态;定时上下线由渲染方按时间窗过滤)。
|
||||
*/
|
||||
@Data
|
||||
public class PortalBanner {
|
||||
|
||||
private Integer id;
|
||||
|
||||
/** 展示位(home=首页轮播) */
|
||||
private String position;
|
||||
|
||||
private String title;
|
||||
|
||||
private String imageUrl;
|
||||
|
||||
/** 1=文章 2=栏目 3=外链 */
|
||||
private Integer linkType;
|
||||
|
||||
/** 跳转目标原值(文章ID/栏目ID/URL),渲染时解析为完整 URL */
|
||||
private String linkValue;
|
||||
|
||||
private Integer sortNo;
|
||||
|
||||
/** 上线时间(渲染方过滤) */
|
||||
private LocalDateTime startTime;
|
||||
|
||||
/** 下线时间(渲染方过滤) */
|
||||
private LocalDateTime endTime;
|
||||
|
||||
public static PortalBanner of(CmsBanner b) {
|
||||
PortalBanner item = new PortalBanner();
|
||||
item.setId(b.getId());
|
||||
item.setPosition(b.getPosition());
|
||||
item.setTitle(b.getTitle());
|
||||
item.setImageUrl(b.getImageUrl());
|
||||
item.setLinkType(b.getLinkType());
|
||||
item.setLinkValue(b.getLinkValue());
|
||||
item.setSortNo(b.getSortNo());
|
||||
item.setStartTime(b.getStartTime());
|
||||
item.setEndTime(b.getEndTime());
|
||||
return item;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.yunhai.cms.model.portal;
|
||||
|
||||
import com.yunhai.cms.entity.CmsCategory;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 门户栏目节点(仅启用项;单页栏目带 content)。
|
||||
*/
|
||||
@Data
|
||||
public class PortalCategory {
|
||||
|
||||
private Integer id;
|
||||
|
||||
private Integer parentId;
|
||||
|
||||
private String name;
|
||||
|
||||
/** 1=文章列表 2=单页 3=外链 */
|
||||
private Integer type;
|
||||
|
||||
private String linkUrl;
|
||||
|
||||
private String template;
|
||||
|
||||
private String seoTitle;
|
||||
|
||||
private String seoDescription;
|
||||
|
||||
/** 单页内容(type=2,已清洗 HTML) */
|
||||
private String content;
|
||||
|
||||
private List<PortalCategory> children = new ArrayList<>();
|
||||
|
||||
public static PortalCategory of(CmsCategory c) {
|
||||
PortalCategory node = new PortalCategory();
|
||||
node.setId(c.getId());
|
||||
node.setParentId(c.getParentId());
|
||||
node.setName(c.getName());
|
||||
node.setType(c.getType());
|
||||
node.setLinkUrl(c.getLinkUrl());
|
||||
node.setTemplate(c.getTemplate());
|
||||
node.setSeoTitle(c.getSeoTitle());
|
||||
node.setSeoDescription(c.getSeoDescription());
|
||||
node.setContent(c.getContent());
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染副本(B-1):本对象挂在 cms:site 快照缓存上,
|
||||
* 单页正文上传地址按当前请求基准重写需在拷贝上进行,不回写缓存。
|
||||
*/
|
||||
public PortalCategory withContent(String content) {
|
||||
PortalCategory copy = new PortalCategory();
|
||||
copy.id = id;
|
||||
copy.parentId = parentId;
|
||||
copy.name = name;
|
||||
copy.type = type;
|
||||
copy.linkUrl = linkUrl;
|
||||
copy.template = template;
|
||||
copy.seoTitle = seoTitle;
|
||||
copy.seoDescription = seoDescription;
|
||||
copy.content = content;
|
||||
copy.children = children;
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.yunhai.cms.model.portal;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 门户友链分组(页脚/首页区块渲染,方案 §8.1:不设独立路由)。
|
||||
*/
|
||||
@Data
|
||||
public class PortalLinkGroup {
|
||||
|
||||
private String groupName;
|
||||
|
||||
private List<PortalLink> links = new ArrayList<>();
|
||||
|
||||
@Data
|
||||
public static class PortalLink {
|
||||
|
||||
private String name;
|
||||
|
||||
private String logoUrl;
|
||||
|
||||
private String linkUrl;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.yunhai.cms.model.portal;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 门户列表页数据(cms:list 缓存体,key=categoryId:page)。
|
||||
*/
|
||||
@Data
|
||||
public class PortalListData {
|
||||
|
||||
private Integer categoryId;
|
||||
|
||||
private Integer siteId;
|
||||
|
||||
private List<Item> items = new ArrayList<>();
|
||||
|
||||
private long total;
|
||||
|
||||
private int page;
|
||||
|
||||
private int pageSize;
|
||||
|
||||
private int totalPages;
|
||||
|
||||
@Data
|
||||
public static class Item {
|
||||
|
||||
private Integer id;
|
||||
|
||||
private String title;
|
||||
|
||||
private String summary;
|
||||
|
||||
private String coverImage;
|
||||
|
||||
private LocalDateTime publishTime;
|
||||
|
||||
private Integer topmost;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.yunhai.cms.model.portal;
|
||||
|
||||
import com.yunhai.cms.entity.CmsSite;
|
||||
import com.yunhai.cms.utils.ExtJsonUtils;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 院系子站精简态(门户"专业院系"下拉数据源,《院系子站方案》)。
|
||||
* 链接不进快照:由渲染方经 {@link com.yunhai.cms.utils.PortalUrlHelper#siteHome}
|
||||
* 生成(该站 public_base_url 优先,未配置按当前请求基准派生,方案 §8.6 前置约定2)。
|
||||
*/
|
||||
@Data
|
||||
public class PortalSiteBrief {
|
||||
|
||||
private Integer id;
|
||||
|
||||
private String code;
|
||||
|
||||
private String name;
|
||||
|
||||
/** 站点 logo(config_json.logo,下拉项可选展示) */
|
||||
private String logoUrl;
|
||||
|
||||
/** 对外基地址(config_json.public_base_url,未配置时渲染方按当前请求派生) */
|
||||
private String publicBaseUrl;
|
||||
|
||||
public static PortalSiteBrief of(CmsSite site) {
|
||||
PortalSiteBrief brief = new PortalSiteBrief();
|
||||
brief.setId(site.getId());
|
||||
brief.setCode(site.getCode());
|
||||
brief.setName(site.getName());
|
||||
Map<String, Object> config = ExtJsonUtils.parse(site.getConfigJson());
|
||||
brief.setLogoUrl(ExtJsonUtils.getString(config, "logo"));
|
||||
brief.setPublicBaseUrl(ExtJsonUtils.getString(config, "public_base_url"));
|
||||
return brief;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.yunhai.cms.model.portal;
|
||||
|
||||
import com.yunhai.cms.entity.CmsSite;
|
||||
import com.yunhai.cms.utils.ExtJsonUtils;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 门户站点快照(cms:site 缓存体,方案 §8.4):
|
||||
* 站点配置 + 栏目树 + 轮播位 + 友链分组 + 同校院系子站。文章数据不进快照(cms:list / cms:article 独立缓存)。
|
||||
*/
|
||||
@Data
|
||||
public class PortalSiteSnapshot {
|
||||
|
||||
private Integer id;
|
||||
|
||||
private String code;
|
||||
|
||||
/** 上级站点ID(0=顶层校站点,《院系子站方案》) */
|
||||
private Integer parentSiteId;
|
||||
|
||||
private String name;
|
||||
|
||||
private String schName;
|
||||
|
||||
/** 皮肤包名(缺省/default 回退已在装配时处理) */
|
||||
private String theme;
|
||||
|
||||
/** 站点配置(logo/contact/footer 等,模板经 config['key'] 取用) */
|
||||
private Map<String, Object> config;
|
||||
|
||||
/** 站点绑定域名(config_json.domain,台账用) */
|
||||
private String domain;
|
||||
|
||||
/** 对外基地址(config_json.public_base_url,未配置时渲染方按请求派生) */
|
||||
private String publicBaseUrl;
|
||||
|
||||
/** 启用栏目树(status=1,已组树) */
|
||||
private List<PortalCategory> categories = new ArrayList<>();
|
||||
|
||||
/** 启用轮播(status=1 全部位,时间窗过滤在渲染方) */
|
||||
private List<PortalBanner> banners = new ArrayList<>();
|
||||
|
||||
/** 启用友链分组 */
|
||||
private List<PortalLinkGroup> linkGroups = new ArrayList<>();
|
||||
|
||||
/** 同校院系子站("专业院系"下拉数据源;顶层站无子站/子站的兄弟站集合,空则模板不渲染) */
|
||||
private List<PortalSiteBrief> colleges = new ArrayList<>();
|
||||
|
||||
/** 微调参数(仅所选主题 theme.json 声明过的 key 且值合法,方案 §5.3) */
|
||||
private Map<String, String> themeParams = new LinkedHashMap<>();
|
||||
|
||||
/** 服务端预构建的 :root{...} CSS 变量覆盖串(无有效参数时为空串,方案 §5.3) */
|
||||
private String themeVarsCss = "";
|
||||
|
||||
public static PortalSiteSnapshot of(CmsSite site) {
|
||||
PortalSiteSnapshot snapshot = new PortalSiteSnapshot();
|
||||
snapshot.setId(site.getId());
|
||||
snapshot.setCode(site.getCode());
|
||||
snapshot.setParentSiteId(site.getParentSiteId() == null ? 0 : site.getParentSiteId());
|
||||
snapshot.setName(site.getName());
|
||||
snapshot.setSchName(site.getSchName());
|
||||
snapshot.setTheme(site.getTheme() == null || site.getTheme().isEmpty()
|
||||
? com.yunhai.cms.theme.ThemeRegistry.DEFAULT_THEME : site.getTheme());
|
||||
Map<String, Object> config = ExtJsonUtils.parse(site.getConfigJson());
|
||||
snapshot.setConfig(config);
|
||||
snapshot.setDomain(ExtJsonUtils.getString(config, "domain"));
|
||||
snapshot.setPublicBaseUrl(ExtJsonUtils.getString(config, "public_base_url"));
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* 预览用浅拷贝(方案 §5.5):集合字段共享只读引用;覆盖 theme/themeParams/themeVarsCss
|
||||
* 的操作由预览方在拷贝上进行,不影响缓存中的原快照。
|
||||
*/
|
||||
public PortalSiteSnapshot shallowCopy() {
|
||||
PortalSiteSnapshot copy = new PortalSiteSnapshot();
|
||||
copy.setId(id);
|
||||
copy.setCode(code);
|
||||
copy.setParentSiteId(parentSiteId);
|
||||
copy.setName(name);
|
||||
copy.setSchName(schName);
|
||||
copy.setTheme(theme);
|
||||
copy.setConfig(config);
|
||||
copy.setDomain(domain);
|
||||
copy.setPublicBaseUrl(publicBaseUrl);
|
||||
copy.setCategories(categories);
|
||||
copy.setBanners(banners);
|
||||
copy.setLinkGroups(linkGroups);
|
||||
copy.setColleges(colleges);
|
||||
copy.setThemeParams(themeParams);
|
||||
copy.setThemeVarsCss(themeVarsCss);
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.yunhai.cms.model.query;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 文章分页查询(方案 §9.2:siteId/categoryId/status/关键字)。
|
||||
*/
|
||||
@Data
|
||||
public class ArticlePageQuery {
|
||||
|
||||
private Integer siteId;
|
||||
|
||||
/** 栏目 id(可空;支持多选时前端传逗号分隔,MVP 单选/空=全部) */
|
||||
private List<Integer> categoryIds;
|
||||
|
||||
/** 状态:空=全部,0=草稿 1=已发布 2=已下架 */
|
||||
private Integer status;
|
||||
|
||||
/** 标题关键字 */
|
||||
private String keyword;
|
||||
|
||||
/** 页码,1 起 */
|
||||
private Integer page = 1;
|
||||
|
||||
/** 页长 */
|
||||
private Integer pageSize = 10;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.yunhai.cms.model.vo;
|
||||
|
||||
import com.yunhai.cms.entity.CmsArticle;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 文章编辑回显 VO(含正文与扩展列)。
|
||||
*/
|
||||
@Data
|
||||
public class ArticleEditVo {
|
||||
|
||||
private Integer id;
|
||||
|
||||
private Integer siteId;
|
||||
|
||||
private Integer categoryId;
|
||||
|
||||
private String title;
|
||||
|
||||
private String summary;
|
||||
|
||||
/** 正文 HTML(已清洗入库内容原样回显) */
|
||||
private String content;
|
||||
|
||||
private String coverImage;
|
||||
|
||||
private String authorName;
|
||||
|
||||
private String source;
|
||||
|
||||
private Integer status;
|
||||
|
||||
private Integer topmost;
|
||||
|
||||
private LocalDateTime publishTime;
|
||||
|
||||
private LocalDateTime offlineTime;
|
||||
|
||||
/** 扩展列 JSON 原文(wechat/albums 预留键) */
|
||||
private String extJson;
|
||||
|
||||
public static ArticleEditVo of(CmsArticle a) {
|
||||
ArticleEditVo vo = new ArticleEditVo();
|
||||
vo.setId(a.getId());
|
||||
vo.setSiteId(a.getSiteId());
|
||||
vo.setCategoryId(a.getCategoryId());
|
||||
vo.setTitle(a.getTitle());
|
||||
vo.setSummary(a.getSummary());
|
||||
vo.setContent(a.getContent());
|
||||
vo.setCoverImage(a.getCoverImage());
|
||||
vo.setAuthorName(a.getAuthorName());
|
||||
vo.setSource(a.getSource());
|
||||
vo.setStatus(a.getStatus());
|
||||
vo.setTopmost(a.getTopmost());
|
||||
vo.setPublishTime(a.getPublishTime());
|
||||
vo.setOfflineTime(a.getOfflineTime());
|
||||
vo.setExtJson(a.getExtJson());
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.yunhai.cms.model.vo;
|
||||
|
||||
import com.yunhai.cms.entity.CmsArticle;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 文章分页行(列表页,方案 §9.1 文章列表)。
|
||||
*/
|
||||
@Data
|
||||
public class ArticlePageItem {
|
||||
|
||||
private Integer id;
|
||||
|
||||
private Integer siteId;
|
||||
|
||||
private Integer categoryId;
|
||||
|
||||
private String categoryName;
|
||||
|
||||
private String title;
|
||||
|
||||
private String summary;
|
||||
|
||||
private String coverImage;
|
||||
|
||||
/** 0=草稿 1=已发布 2=已下架 */
|
||||
private Integer status;
|
||||
|
||||
private Integer topmost;
|
||||
|
||||
/** 发布时间(草稿且未来时间为"定时发布") */
|
||||
private LocalDateTime publishTime;
|
||||
|
||||
private LocalDateTime offlineTime;
|
||||
|
||||
private Integer viewCount;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
|
||||
private String createBy;
|
||||
|
||||
public static ArticlePageItem of(CmsArticle a, String categoryName) {
|
||||
ArticlePageItem item = new ArticlePageItem();
|
||||
item.setId(a.getId());
|
||||
item.setSiteId(a.getSiteId());
|
||||
item.setCategoryId(a.getCategoryId());
|
||||
item.setCategoryName(categoryName);
|
||||
item.setTitle(a.getTitle());
|
||||
item.setSummary(a.getSummary());
|
||||
item.setCoverImage(a.getCoverImage());
|
||||
item.setStatus(a.getStatus());
|
||||
item.setTopmost(a.getTopmost());
|
||||
item.setPublishTime(a.getPublishTime());
|
||||
item.setOfflineTime(a.getOfflineTime());
|
||||
item.setViewCount(a.getViewCount());
|
||||
item.setCreateTime(a.getCreateTime());
|
||||
item.setCreateBy(a.getCreateBy());
|
||||
return item;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.yunhai.cms.model.vo;
|
||||
|
||||
import com.yunhai.cms.entity.CmsAttachment;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 附件 VO(上传返回 + 附件管理列表)。
|
||||
*/
|
||||
@Data
|
||||
public class AttachmentVo {
|
||||
|
||||
private Integer id;
|
||||
|
||||
private Integer siteId;
|
||||
|
||||
private Integer articleId;
|
||||
|
||||
private String fileName;
|
||||
|
||||
/** Web 访问 URL(编辑器/封面/轮播直接引用) */
|
||||
private String url;
|
||||
|
||||
private Long fileSize;
|
||||
|
||||
private String mimeType;
|
||||
|
||||
private String createTime;
|
||||
|
||||
/** 是否孤儿(文章已删除/未关联) */
|
||||
private boolean orphan;
|
||||
|
||||
public static AttachmentVo of(CmsAttachment a) {
|
||||
AttachmentVo vo = new AttachmentVo();
|
||||
vo.setId(a.getId());
|
||||
vo.setSiteId(a.getSiteId());
|
||||
vo.setArticleId(a.getArticleId());
|
||||
vo.setFileName(a.getFileName());
|
||||
vo.setUrl(a.getWebUrl());
|
||||
vo.setFileSize(a.getFileSize());
|
||||
vo.setMimeType(a.getMimeType());
|
||||
vo.setCreateTime(a.getCreateTime() == null ? null : a.getCreateTime().toString());
|
||||
vo.setOrphan(a.getArticleId() == null);
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.yunhai.cms.model.vo;
|
||||
|
||||
import com.yunhai.platform.utils.model.BoaRoleInfo;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 管理端登录态:CAS 会话用户 + 可管理站点 + 是否超管(方案 §7.2 权限规则的客户端镜像)。
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
public class AuthUserVo {
|
||||
|
||||
/** 登录账号 */
|
||||
private String account;
|
||||
|
||||
/** 姓名 */
|
||||
private String name;
|
||||
|
||||
/** 当前角色(roleId/roleName/schId/schName) */
|
||||
private BoaRoleInfo currentRole;
|
||||
|
||||
/** 是否平台超管(BoaUser.type == 1,平台约定) */
|
||||
private boolean superAdmin;
|
||||
|
||||
/** 可管理的站点(超管=全部;校级=本校站点) */
|
||||
private List<SiteVo> sites;
|
||||
|
||||
/** 角色集合(前端判断用) */
|
||||
private List<Integer> roleIds;
|
||||
|
||||
public static AuthUserVo of(BoaUser user, boolean superAdmin, List<SiteVo> sites) {
|
||||
return AuthUserVo.builder()
|
||||
.account(user.getAccount())
|
||||
.name(user.getName())
|
||||
.currentRole(user.getCurrentRole())
|
||||
.superAdmin(superAdmin)
|
||||
.sites(sites)
|
||||
.roleIds(user.getRoleIds())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.yunhai.cms.model.vo;
|
||||
|
||||
import com.yunhai.cms.entity.CmsBanner;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 轮播 VO。
|
||||
*/
|
||||
@Data
|
||||
public class BannerVo {
|
||||
|
||||
private Integer id;
|
||||
|
||||
private Integer siteId;
|
||||
|
||||
private String position;
|
||||
|
||||
private String title;
|
||||
|
||||
private String imageUrl;
|
||||
|
||||
/** 1=文章 2=栏目 3=外链 */
|
||||
private Integer linkType;
|
||||
|
||||
private String linkValue;
|
||||
|
||||
private Integer sortNo;
|
||||
|
||||
private LocalDateTime startTime;
|
||||
|
||||
private LocalDateTime endTime;
|
||||
|
||||
private Integer status;
|
||||
|
||||
public static BannerVo of(CmsBanner b) {
|
||||
BannerVo vo = new BannerVo();
|
||||
vo.setId(b.getId());
|
||||
vo.setSiteId(b.getSiteId());
|
||||
vo.setPosition(b.getPosition());
|
||||
vo.setTitle(b.getTitle());
|
||||
vo.setImageUrl(b.getImageUrl());
|
||||
vo.setLinkType(b.getLinkType());
|
||||
vo.setLinkValue(b.getLinkValue());
|
||||
vo.setSortNo(b.getSortNo());
|
||||
vo.setStartTime(b.getStartTime());
|
||||
vo.setEndTime(b.getEndTime());
|
||||
vo.setStatus(b.getStatus());
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.yunhai.cms.model.vo;
|
||||
|
||||
import com.yunhai.cms.entity.CmsCategory;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 栏目树节点(管理端树控件与门户导航共用结构)。
|
||||
*/
|
||||
@Data
|
||||
public class CategoryTreeNode {
|
||||
|
||||
private Integer id;
|
||||
|
||||
private Integer parentId;
|
||||
|
||||
private Integer siteId;
|
||||
|
||||
private String name;
|
||||
|
||||
/** 1=文章列表 2=单页 3=外链 */
|
||||
private Integer type;
|
||||
|
||||
private String linkUrl;
|
||||
|
||||
private String template;
|
||||
|
||||
/** 单页栏目内容(type=2 时编辑/渲染用) */
|
||||
private String content;
|
||||
|
||||
private Integer sortNo;
|
||||
|
||||
private String seoTitle;
|
||||
|
||||
private String seoDescription;
|
||||
|
||||
/** 0=隐藏 1=显示 */
|
||||
private Integer status;
|
||||
|
||||
private List<CategoryTreeNode> children = new ArrayList<>();
|
||||
|
||||
public static CategoryTreeNode of(CmsCategory c) {
|
||||
CategoryTreeNode node = new CategoryTreeNode();
|
||||
node.setId(c.getId());
|
||||
node.setParentId(c.getParentId());
|
||||
node.setSiteId(c.getSiteId());
|
||||
node.setName(c.getName());
|
||||
node.setType(c.getType());
|
||||
node.setLinkUrl(c.getLinkUrl());
|
||||
node.setTemplate(c.getTemplate());
|
||||
node.setContent(c.getContent());
|
||||
node.setSortNo(c.getSortNo());
|
||||
node.setSeoTitle(c.getSeoTitle());
|
||||
node.setSeoDescription(c.getSeoDescription());
|
||||
node.setStatus(c.getStatus());
|
||||
return node;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.yunhai.cms.model.vo;
|
||||
|
||||
import com.yunhai.cms.entity.CmsLink;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 友链 VO。
|
||||
*/
|
||||
@Data
|
||||
public class LinkVo {
|
||||
|
||||
private Integer id;
|
||||
|
||||
private Integer siteId;
|
||||
|
||||
private String groupName;
|
||||
|
||||
private String name;
|
||||
|
||||
private String logoUrl;
|
||||
|
||||
private String linkUrl;
|
||||
|
||||
private Integer sortNo;
|
||||
|
||||
private Integer status;
|
||||
|
||||
public static LinkVo of(CmsLink l) {
|
||||
LinkVo vo = new LinkVo();
|
||||
vo.setId(l.getId());
|
||||
vo.setSiteId(l.getSiteId());
|
||||
vo.setGroupName(l.getGroupName());
|
||||
vo.setName(l.getName());
|
||||
vo.setLogoUrl(l.getLogoUrl());
|
||||
vo.setLinkUrl(l.getLinkUrl());
|
||||
vo.setSortNo(l.getSortNo());
|
||||
vo.setStatus(l.getStatus());
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.yunhai.cms.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 学校工作台聚合 VO(docs/09 §3.3,D6-4):CMS 不设学校表,
|
||||
* 学校卡片 = 顶层站点(主站),院系子站经 parentSiteId 归属,schId/schName 冗余展示。
|
||||
*/
|
||||
@Data
|
||||
public class SchoolVo {
|
||||
|
||||
/** 学校 ID(UserBase sys_group.id,主站冗余字段) */
|
||||
private Integer schId;
|
||||
|
||||
private String schName;
|
||||
|
||||
/** 主站(顶层站点) */
|
||||
private Integer mainSiteId;
|
||||
/** 主站编码(学校上下文 URL 段 /sch/{code}) */
|
||||
private String mainSiteCode;
|
||||
private String mainSiteName;
|
||||
private String theme;
|
||||
|
||||
/** 该主站下站点总数(含主站自身) */
|
||||
private Integer siteCount;
|
||||
|
||||
/** 该校全部站点文章总数(管理端规模口径,含未发布) */
|
||||
private Long articleCount;
|
||||
|
||||
/** 主站状态:1 启用 / 0 停用 */
|
||||
private Integer status;
|
||||
|
||||
/** UserBase 学校选项(「添加学校」选择器用) */
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class Option {
|
||||
private Integer id;
|
||||
private String name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.yunhai.cms.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 站点 VO。
|
||||
*/
|
||||
@Data
|
||||
public class SiteVo {
|
||||
|
||||
private Integer id;
|
||||
|
||||
private String code;
|
||||
|
||||
/** 上级站点ID(0=顶层校站点,《院系子站方案》) */
|
||||
private Integer parentSiteId;
|
||||
|
||||
/** 上级站点名称(列表展示用,服务端装配) */
|
||||
private String parentName;
|
||||
|
||||
private Integer schId;
|
||||
|
||||
private String schName;
|
||||
|
||||
private String name;
|
||||
|
||||
private String theme;
|
||||
|
||||
/** 站点配置 JSON 原文(domain/public_base_url/logo 等) */
|
||||
private String configJson;
|
||||
|
||||
/** 0=停用 1=启用 */
|
||||
private Integer status;
|
||||
|
||||
private String createTime;
|
||||
|
||||
public static SiteVo of(com.yunhai.cms.entity.CmsSite site) {
|
||||
SiteVo vo = new SiteVo();
|
||||
vo.setId(site.getId());
|
||||
vo.setCode(site.getCode());
|
||||
vo.setParentSiteId(site.getParentSiteId() == null ? 0 : site.getParentSiteId());
|
||||
vo.setSchId(site.getSchId());
|
||||
vo.setSchName(site.getSchName());
|
||||
vo.setName(site.getName());
|
||||
vo.setTheme(site.getTheme());
|
||||
vo.setConfigJson(site.getConfigJson());
|
||||
vo.setStatus(site.getStatus());
|
||||
vo.setCreateTime(site.getCreateTime() == null ? null : site.getCreateTime().toString());
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.yunhai.cms.model.vo;
|
||||
|
||||
import com.yunhai.cms.theme.ThemeInfo;
|
||||
import com.yunhai.cms.theme.ThemeParam;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 主题包 VO(管理端主题列表,方案 §5.2)。
|
||||
*/
|
||||
@Data
|
||||
public class ThemeVo {
|
||||
|
||||
private String name;
|
||||
|
||||
private String title;
|
||||
|
||||
private String description;
|
||||
|
||||
private String version;
|
||||
|
||||
private String author;
|
||||
|
||||
private String bannerSize;
|
||||
|
||||
/** 预览图 URL(管理端资产代理 /api/theme/{name}/asset/screenshot.png,方案 §5.2) */
|
||||
private String screenshotUrl;
|
||||
|
||||
/** 可调参数 schema(管理端表单按此动态生成,方案 §6.3) */
|
||||
private List<ThemeParamVo> params;
|
||||
|
||||
@Data
|
||||
public static class ThemeParamVo {
|
||||
|
||||
private String key;
|
||||
|
||||
private String cssVar;
|
||||
|
||||
private String label;
|
||||
|
||||
private String type;
|
||||
|
||||
private String defaultValue;
|
||||
|
||||
private List<ThemeParam.Option> options;
|
||||
|
||||
public static ThemeParamVo of(ThemeParam p) {
|
||||
ThemeParamVo vo = new ThemeParamVo();
|
||||
vo.setKey(p.getKey());
|
||||
vo.setCssVar(p.getCssVar());
|
||||
vo.setLabel(p.getLabel());
|
||||
vo.setType(p.getType());
|
||||
vo.setDefaultValue(p.getDefaultValue());
|
||||
vo.setOptions(p.getOptions());
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
|
||||
public static ThemeVo of(ThemeInfo info) {
|
||||
ThemeVo vo = new ThemeVo();
|
||||
vo.setName(info.getName());
|
||||
vo.setTitle(info.getTitle());
|
||||
vo.setDescription(info.getDescription());
|
||||
vo.setVersion(info.getVersion());
|
||||
vo.setAuthor(info.getAuthor());
|
||||
vo.setBannerSize(info.getBannerSize());
|
||||
vo.setScreenshotUrl("/api/theme/" + info.getName() + "/asset/screenshot.png");
|
||||
vo.setParams(new java.util.ArrayList<>());
|
||||
for (ThemeParam p : info.getParams()) {
|
||||
vo.getParams().add(ThemeParamVo.of(p));
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.yunhai.cms.repository;
|
||||
|
||||
import com.yunhai.cms.entity.CmsArticle;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface CmsArticleRepository extends JpaRepository<CmsArticle, Integer>,
|
||||
JpaSpecificationExecutor<CmsArticle> {
|
||||
|
||||
Optional<CmsArticle> findByIdAndSiteId(Integer id, Integer siteId);
|
||||
|
||||
long countByCategoryId(Integer categoryId);
|
||||
|
||||
/** 学校工作台规模计数(docs/09 §3.3,管理端口径含未发布) */
|
||||
long countBySiteId(Integer siteId);
|
||||
|
||||
/** 栏目列表页:已发布,发布时间倒序(置顶由 Specification/排序组合处理) */
|
||||
Page<CmsArticle> findBySiteIdAndCategoryIdAndStatus(Integer siteId, Integer categoryId,
|
||||
Integer status, Pageable pageable);
|
||||
|
||||
/** 栏目聚合查询(D1-2/D1-3):父栏目区块/列表页聚合列表型子孙栏目的文章 */
|
||||
Page<CmsArticle> findBySiteIdAndCategoryIdInAndStatus(Integer siteId, Collection<Integer> categoryIds,
|
||||
Integer status, Pageable pageable);
|
||||
|
||||
/** 门户:首页按站点取已发布(置顶优先),条数由 Pageable 控制 */
|
||||
List<CmsArticle> findBySiteIdAndStatus(Integer siteId, Integer status, Pageable pageable);
|
||||
|
||||
/**
|
||||
* 详情页上下篇:publish_time 相同(如同秒批量导入)时以 id 决胜,
|
||||
* 约定列表排序 = publish_time desc, id desc,上一篇文章是该序中的后继。
|
||||
*/
|
||||
@Query("select a from CmsArticle a where a.siteId = :siteId and a.status = :status"
|
||||
+ " and (a.publishTime < :pt or (a.publishTime = :pt and a.id < :id))"
|
||||
+ " order by a.publishTime desc, a.id desc")
|
||||
List<CmsArticle> findPrevPublished(@Param("siteId") Integer siteId, @Param("status") Integer status,
|
||||
@Param("pt") LocalDateTime pt, @Param("id") Integer id,
|
||||
Pageable pageable);
|
||||
|
||||
@Query("select a from CmsArticle a where a.siteId = :siteId and a.status = :status"
|
||||
+ " and (a.publishTime > :pt or (a.publishTime = :pt and a.id > :id))"
|
||||
+ " order by a.publishTime asc, a.id asc")
|
||||
List<CmsArticle> findNextPublished(@Param("siteId") Integer siteId, @Param("status") Integer status,
|
||||
@Param("pt") LocalDateTime pt, @Param("id") Integer id,
|
||||
Pageable pageable);
|
||||
|
||||
/** 站内搜索(title/summary LIKE,MVP 不上 ES,方案 §2) */
|
||||
Page<CmsArticle> findBySiteIdAndStatusAndTitleContainingOrSiteIdAndStatusAndSummaryContaining(
|
||||
Integer siteId, Integer status, String title, Integer siteId2, Integer status2, String summary,
|
||||
Pageable pageable);
|
||||
|
||||
/** 定时发布扫描:草稿且发布时间已到 */
|
||||
List<CmsArticle> findByStatusAndPublishTimeNotNullAndPublishTimeLessThanEqual(Integer status,
|
||||
LocalDateTime now);
|
||||
|
||||
/** 定时下架扫描:已发布且下架时间已到 */
|
||||
List<CmsArticle> findByStatusAndOfflineTimeNotNullAndOfflineTimeLessThanEqual(Integer status,
|
||||
LocalDateTime now);
|
||||
|
||||
/** 浏览量异步累加(fire-and-forget,失败忽略,方案 §5.2) */
|
||||
@Modifying
|
||||
@Query("update CmsArticle a set a.viewCount = a.viewCount + 1 where a.id = :id")
|
||||
int incrementViewCount(@Param("id") Integer id);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.yunhai.cms.repository;
|
||||
|
||||
import com.yunhai.cms.entity.CmsAttachment;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface CmsAttachmentRepository extends JpaRepository<CmsAttachment, Integer> {
|
||||
|
||||
Page<CmsAttachment> findBySiteId(Integer siteId, Pageable pageable);
|
||||
|
||||
List<CmsAttachment> findByArticleId(Integer articleId);
|
||||
|
||||
/** 编辑器图片上传时先按路径去重绑定,避免重复行 */
|
||||
long countBySiteIdAndFilePath(Integer siteId, String filePath);
|
||||
|
||||
/** 孤儿附件(文章已删除:article_id is null) */
|
||||
Page<CmsAttachment> findBySiteIdAndArticleIdIsNull(Integer siteId, Pageable pageable);
|
||||
|
||||
long countBySiteIdAndArticleIdIsNull(Integer siteId);
|
||||
|
||||
@Modifying
|
||||
@Query("update CmsAttachment a set a.articleId = :articleId where a.id in :ids")
|
||||
int bindArticle(@Param("articleId") Integer articleId, @Param("ids") List<Integer> ids);
|
||||
|
||||
/** 文章删除:附件转孤儿 */
|
||||
@Modifying
|
||||
@Query("update CmsAttachment a set a.articleId = null where a.articleId = :articleId")
|
||||
int unbindArticle(@Param("articleId") Integer articleId);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.yunhai.cms.repository;
|
||||
|
||||
import com.yunhai.cms.entity.CmsBanner;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface CmsBannerRepository extends JpaRepository<CmsBanner, Integer> {
|
||||
|
||||
/** 管理端:展示位全量(含停用,按排序) */
|
||||
List<CmsBanner> findBySiteIdAndPositionOrderBySortNoAscIdAsc(Integer siteId, String position);
|
||||
|
||||
List<CmsBanner> findBySiteIdOrderByPositionAscSortNoAscIdAsc(Integer siteId);
|
||||
|
||||
/** 引用完整性(删除拦截用):指定跳转类型下是否存在指向目标 id 的轮播(跨站也拦,link_value 全局比对) */
|
||||
boolean existsByLinkTypeAndLinkValue(Integer linkType, String linkValue);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.yunhai.cms.repository;
|
||||
|
||||
import com.yunhai.cms.entity.CmsCategory;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface CmsCategoryRepository extends JpaRepository<CmsCategory, Integer> {
|
||||
|
||||
/** 栏目树数据源(内存组树,站点数 ≤20 栏目量级小) */
|
||||
List<CmsCategory> findBySiteIdOrderBySortNoAscIdAsc(Integer siteId);
|
||||
|
||||
long countBySiteId(Integer siteId);
|
||||
|
||||
long countByParentId(Integer parentId);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.yunhai.cms.repository;
|
||||
|
||||
import com.yunhai.cms.entity.CmsLink;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface CmsLinkRepository extends JpaRepository<CmsLink, Integer> {
|
||||
|
||||
List<CmsLink> findBySiteIdOrderByGroupNameAscSortNoAscIdAsc(Integer siteId);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.yunhai.cms.repository;
|
||||
|
||||
import com.yunhai.cms.entity.CmsSite;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface CmsSiteRepository extends JpaRepository<CmsSite, Integer> {
|
||||
|
||||
Optional<CmsSite> findByCode(String code);
|
||||
|
||||
/** 启用站点(B-5:显式按 id 升序,/portal 默认入口跳转目标确定) */
|
||||
List<CmsSite> findByStatusOrderByIdAsc(Integer status);
|
||||
|
||||
/** 本校可管理的站点(非超管按 currentRole.schId 过滤) */
|
||||
List<CmsSite> findBySchId(Integer schId);
|
||||
|
||||
/** 指定主站下的启用院系子站(门户"专业院系"下拉数据源,《院系子站方案》) */
|
||||
List<CmsSite> findByParentSiteIdAndStatusOrderByIdAsc(Integer parentSiteId, Integer status);
|
||||
|
||||
/** 是否存在院系子站(站点改挂上级前的守卫) */
|
||||
boolean existsByParentSiteId(Integer parentSiteId);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.yunhai.cms.service;
|
||||
|
||||
import com.yunhai.cms.event.ArticlePublishedEvent;
|
||||
|
||||
/**
|
||||
* 微信图文推送服务接口(方案 §7.4 预留入口)。
|
||||
*
|
||||
* <p>本期 {@link com.yunhai.cms.service.impl.NoopWeChatPushService} 空实现:
|
||||
* 事件照常发布,Noop 直接返回,零微信外联/零微信配置键/零新增依赖。
|
||||
* 启用时按《微信平台对接方案.md》提供真实实现(公众号配置经 projman 注入)。
|
||||
*/
|
||||
public interface WeChatPushService {
|
||||
|
||||
/**
|
||||
* 文章发布后回调(AFTER_COMMIT)。
|
||||
*
|
||||
* @param event 发布事件(articleId/siteId/title)
|
||||
* @return 是否已推送(Noop 恒 false)
|
||||
*/
|
||||
boolean onArticlePublished(ArticlePublishedEvent event);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.yunhai.cms.service.impl;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 定时发布/下架触发器(方案 §13 风险表:MVP 用 @Scheduled 每分钟扫到期记录,无重调度器)。
|
||||
* 扫描语义在 {@link ArticleScheduleWorker}(D5-5 拆分:触发与逻辑分离,IT 直接调 Worker
|
||||
* 消除自动调度与手动调用的并发竞态)。cms.schedule.auto-enabled=false 可关自动触发
|
||||
* (仅集成测试用,生产默认开)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(value = "cms.schedule.auto-enabled", havingValue = "true", matchIfMissing = true)
|
||||
public class ArticleScheduleTask {
|
||||
|
||||
private final ArticleScheduleWorker worker;
|
||||
|
||||
/** 定时发布:草稿且发布时间已到 */
|
||||
@Scheduled(initialDelay = 30_000, fixedDelay = 60_000)
|
||||
public void publishDue() {
|
||||
worker.publishDue();
|
||||
}
|
||||
|
||||
/** 定时下架:已发布且下架时间已到 */
|
||||
@Scheduled(initialDelay = 45_000, fixedDelay = 60_000)
|
||||
public void offlineDue() {
|
||||
worker.offlineDue();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.yunhai.cms.service.impl;
|
||||
|
||||
import com.yunhai.cms.entity.CmsArticle;
|
||||
import com.yunhai.cms.enums.ArticleStatusEnum;
|
||||
import com.yunhai.cms.event.ArticleChangedEvent;
|
||||
import com.yunhai.cms.event.ArticlePublishedEvent;
|
||||
import com.yunhai.cms.repository.CmsArticleRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 定时发布/下架扫描逻辑(方案 §13 风险表:MVP 每分钟扫到期记录,无重调度器)。
|
||||
* 从 ArticleScheduleTask 拆出纯逻辑体(D5-5):@Scheduled 触发器与扫描语义分离,
|
||||
* 集成测试直接调 Worker 消除"上下文自动调度与测试手动调用并发处理同一记录"的竞态
|
||||
* (表现为事件数翻倍断言失败)。每条记录独立事务;到期即发对应事件
|
||||
* (缓存失效 + 微信挂点照常生效)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ArticleScheduleWorker {
|
||||
|
||||
private final CmsArticleRepository articleRepository;
|
||||
private final TransactionTemplate transactionTemplate;
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
|
||||
/** 定时发布:草稿且发布时间已到 */
|
||||
public void publishDue() {
|
||||
List<CmsArticle> dueList =
|
||||
articleRepository.findByStatusAndPublishTimeNotNullAndPublishTimeLessThanEqual(
|
||||
ArticleStatusEnum.DRAFT.getCode(), LocalDateTime.now());
|
||||
for (CmsArticle due : dueList) {
|
||||
transactionTemplate.executeWithoutResult(status -> {
|
||||
CmsArticle article = articleRepository.findById(due.getId()).orElse(null);
|
||||
if (article == null || article.getStatus() != ArticleStatusEnum.DRAFT.getCode()) {
|
||||
return;
|
||||
}
|
||||
article.setStatus(ArticleStatusEnum.PUBLISHED.getCode());
|
||||
articleRepository.save(article);
|
||||
eventPublisher.publishEvent(new ArticlePublishedEvent(article.getId(),
|
||||
article.getSiteId(), article.getTitle()));
|
||||
log.info("定时发布文章 articleId={} siteId={}", article.getId(), article.getSiteId());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** 定时下架:已发布且下架时间已到 */
|
||||
public void offlineDue() {
|
||||
List<CmsArticle> dueList =
|
||||
articleRepository.findByStatusAndOfflineTimeNotNullAndOfflineTimeLessThanEqual(
|
||||
ArticleStatusEnum.PUBLISHED.getCode(), LocalDateTime.now());
|
||||
for (CmsArticle due : dueList) {
|
||||
transactionTemplate.executeWithoutResult(status -> {
|
||||
CmsArticle article = articleRepository.findById(due.getId()).orElse(null);
|
||||
if (article == null || article.getStatus() != ArticleStatusEnum.PUBLISHED.getCode()) {
|
||||
return;
|
||||
}
|
||||
article.setStatus(ArticleStatusEnum.OFFLINE.getCode());
|
||||
articleRepository.save(article);
|
||||
eventPublisher.publishEvent(new ArticleChangedEvent(article.getId(), article.getSiteId()));
|
||||
log.info("定时下架文章 articleId={} siteId={}", article.getId(), article.getSiteId());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
package com.yunhai.cms.service.impl;
|
||||
|
||||
import com.yunhai.cms.entity.CmsArticle;
|
||||
import com.yunhai.cms.entity.CmsCategory;
|
||||
import com.yunhai.cms.entity.CmsSite;
|
||||
import com.yunhai.cms.enums.ArticleStatusEnum;
|
||||
import com.yunhai.cms.event.ArticleChangedEvent;
|
||||
import com.yunhai.cms.event.ArticlePublishedEvent;
|
||||
import com.yunhai.cms.model.dto.ArticleSaveRequest;
|
||||
import com.yunhai.cms.model.dto.DeleteRequest;
|
||||
import com.yunhai.cms.model.query.ArticlePageQuery;
|
||||
import com.yunhai.cms.model.vo.ArticleEditVo;
|
||||
import com.yunhai.cms.model.vo.ArticlePageItem;
|
||||
import com.yunhai.cms.repository.CmsArticleRepository;
|
||||
import com.yunhai.cms.repository.CmsAttachmentRepository;
|
||||
import com.yunhai.cms.repository.CmsCategoryRepository;
|
||||
import com.yunhai.cms.utils.HtmlSanitizer;
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import com.yunhai.platform.utils.exception.ErrorCode;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.persistence.criteria.Predicate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 文章管理(方案 §9.1/§9.2):草稿/发布/下架/置顶/定时发布下架 + jsoup 保存时清洗。
|
||||
* 发布动作发布 {@link ArticlePublishedEvent}(AFTER_COMMIT:缓存失效 + 微信 Noop 挂点)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ArticleService {
|
||||
|
||||
private final CmsArticleRepository articleRepository;
|
||||
private final CmsCategoryRepository categoryRepository;
|
||||
private final CmsAttachmentRepository attachmentRepository;
|
||||
private final com.yunhai.cms.repository.CmsBannerRepository bannerRepository;
|
||||
private final SiteService siteService;
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
|
||||
/** 文章分页(管理端,全状态可见);pageSize 上限 100 防全表拖库(体检 H-6) */
|
||||
public Map<String, Object> page(BoaUser user, ArticlePageQuery query) {
|
||||
siteService.requireManageable(user, query.getSiteId());
|
||||
int pageIndex = query.getPage() == null || query.getPage() < 1 ? 0 : query.getPage() - 1;
|
||||
int pageSize = query.getPageSize() == null || query.getPageSize() < 1 ? 10 : query.getPageSize();
|
||||
pageSize = Math.min(pageSize, 100);
|
||||
Pageable pageable = PageRequest.of(pageIndex, pageSize,
|
||||
Sort.by(Sort.Order.desc("topmost"), Sort.Order.desc("createTime")));
|
||||
|
||||
Specification<CmsArticle> spec = (root, cq, cb) -> {
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
predicates.add(cb.equal(root.get("siteId"), query.getSiteId()));
|
||||
if (query.getCategoryIds() != null && !query.getCategoryIds().isEmpty()) {
|
||||
predicates.add(root.get("categoryId").in(query.getCategoryIds()));
|
||||
}
|
||||
if (query.getStatus() != null) {
|
||||
predicates.add(cb.equal(root.get("status"), query.getStatus()));
|
||||
}
|
||||
if (StringUtils.hasText(query.getKeyword())) {
|
||||
predicates.add(cb.like(root.get("title"), "%" + query.getKeyword().trim() + "%"));
|
||||
}
|
||||
return cb.and(predicates.toArray(new Predicate[0]));
|
||||
};
|
||||
|
||||
Map<Integer, String> categoryNames = categoryNameMap(query.getSiteId());
|
||||
Page<CmsArticle> page = articleRepository.findAll(spec, pageable);
|
||||
List<ArticlePageItem> items = new ArrayList<>();
|
||||
for (CmsArticle article : page.getContent()) {
|
||||
items.add(ArticlePageItem.of(article, categoryNames.get(article.getCategoryId())));
|
||||
}
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("total", page.getTotalElements());
|
||||
result.put("list", items);
|
||||
return result;
|
||||
}
|
||||
|
||||
private Map<Integer, String> categoryNameMap(Integer siteId) {
|
||||
Map<Integer, String> names = new HashMap<>();
|
||||
for (CmsCategory c : categoryRepository.findBySiteIdOrderBySortNoAscIdAsc(siteId)) {
|
||||
names.put(c.getId(), c.getName());
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/** 编辑回显 */
|
||||
public ArticleEditVo getEdit(BoaUser user, Integer siteId, Integer id) {
|
||||
siteService.requireManageable(user, siteId);
|
||||
CmsArticle article = articleRepository.findByIdAndSiteId(id, siteId)
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "文章不存在"));
|
||||
return ArticleEditVo.of(article);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存(草稿)。content 过 jsoup 白名单;摘要空则截取正文;
|
||||
* 请求携带 attachmentIds 时回填编辑器图片归属。已发布文章被修改后发变更事件保持门户新鲜。
|
||||
*/
|
||||
@Transactional
|
||||
public Integer save(BoaUser user, ArticleSaveRequest req) {
|
||||
CmsSite site = siteService.requireManageable(user, req.getSiteId());
|
||||
CmsCategory category = categoryRepository.findById(req.getCategoryId())
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "所属栏目不存在"));
|
||||
if (!category.getSiteId().equals(site.getId())) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "栏目不属于该站点");
|
||||
}
|
||||
|
||||
CmsArticle article;
|
||||
if (req.getId() == null) {
|
||||
article = new CmsArticle();
|
||||
article.setSiteId(site.getId());
|
||||
article.setStatus(ArticleStatusEnum.DRAFT.getCode());
|
||||
} else {
|
||||
article = articleRepository.findByIdAndSiteId(req.getId(), site.getId())
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "文章不存在"));
|
||||
}
|
||||
validateTimeWindow(req.getPublishTime(), req.getOfflineTime());
|
||||
article.setCategoryId(category.getId());
|
||||
article.setTitle(req.getTitle());
|
||||
article.setContent(HtmlSanitizer.clean(req.getContent()));
|
||||
String summary = req.getSummary();
|
||||
if (!StringUtils.hasText(summary)) {
|
||||
summary = HtmlSanitizer.toText(article.getContent(), 120);
|
||||
}
|
||||
article.setSummary(summary);
|
||||
article.setCoverImage(req.getCoverImage());
|
||||
article.setAuthorName(req.getAuthorName());
|
||||
article.setSource(req.getSource());
|
||||
article.setTopmost(req.getTopmost() == null ? 0 : req.getTopmost());
|
||||
article.setPublishTime(req.getPublishTime());
|
||||
article.setOfflineTime(req.getOfflineTime());
|
||||
article = articleRepository.save(article);
|
||||
|
||||
if (req.getAttachmentIds() != null && !req.getAttachmentIds().isEmpty()) {
|
||||
attachmentRepository.bindArticle(article.getId(), req.getAttachmentIds());
|
||||
}
|
||||
eventPublisher.publishEvent(new ArticleChangedEvent(article.getId(), site.getId()));
|
||||
return article.getId();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布:填发布时间与作者。publishTime 为空或已过 → 立即发布;
|
||||
* 未来时间 → 保持草稿(定时发布,@Scheduled 扫描触发)。
|
||||
*/
|
||||
@Transactional
|
||||
public void publish(BoaUser user, Integer siteId, Integer id) {
|
||||
CmsSite site = siteService.requireManageable(user, siteId);
|
||||
CmsArticle article = requireArticle(site.getId(), id);
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime effective = article.getPublishTime() != null && article.getPublishTime().isAfter(now)
|
||||
? article.getPublishTime() : now;
|
||||
// 重新发布即开启新生命周期:过期的定时下架时间若不清掉,发布后会被调度器立刻下架
|
||||
// (旧数据/边界操作产生的矛盾态在此自愈,save 入口已拦截新产生的矛盾时间窗)
|
||||
if (article.getOfflineTime() != null && !article.getOfflineTime().isAfter(effective)) {
|
||||
article.setOfflineTime(null);
|
||||
}
|
||||
article.setPublishTime(effective);
|
||||
if (!StringUtils.hasText(article.getAuthorAccount()) && user != null) {
|
||||
article.setAuthorAccount(user.getAccount());
|
||||
if (!StringUtils.hasText(article.getAuthorName())) {
|
||||
article.setAuthorName(user.getName());
|
||||
}
|
||||
}
|
||||
if (effective.isAfter(now)) {
|
||||
article.setStatus(ArticleStatusEnum.DRAFT.getCode());
|
||||
articleRepository.save(article);
|
||||
eventPublisher.publishEvent(new ArticleChangedEvent(article.getId(), site.getId()));
|
||||
} else {
|
||||
article.setStatus(ArticleStatusEnum.PUBLISHED.getCode());
|
||||
articleRepository.save(article);
|
||||
eventPublisher.publishEvent(new ArticlePublishedEvent(article.getId(), site.getId(), article.getTitle()));
|
||||
}
|
||||
}
|
||||
|
||||
/** 下架 */
|
||||
@Transactional
|
||||
public void offline(BoaUser user, Integer siteId, Integer id) {
|
||||
CmsSite site = siteService.requireManageable(user, siteId);
|
||||
CmsArticle article = requireArticle(site.getId(), id);
|
||||
article.setStatus(ArticleStatusEnum.OFFLINE.getCode());
|
||||
articleRepository.save(article);
|
||||
eventPublisher.publishEvent(new ArticleChangedEvent(article.getId(), site.getId()));
|
||||
}
|
||||
|
||||
/** 置顶开关 */
|
||||
@Transactional
|
||||
public void topmost(BoaUser user, Integer siteId, Integer id, boolean enable) {
|
||||
CmsSite site = siteService.requireManageable(user, siteId);
|
||||
CmsArticle article = requireArticle(site.getId(), id);
|
||||
article.setTopmost(enable ? 1 : 0);
|
||||
articleRepository.save(article);
|
||||
eventPublisher.publishEvent(new ArticleChangedEvent(article.getId(), site.getId()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除:附件转孤儿(article_id 置空,由附件管理页清理,方案 §9.1 附件管理)。
|
||||
* 轮播仍引用该文章时拦截删除(引用完整性统一规则:被引用即拦,与栏目删除一致)。
|
||||
*/
|
||||
@Transactional
|
||||
public void delete(BoaUser user, DeleteRequest req) {
|
||||
CmsSite site = siteService.requireManageable(user, req.getSiteId());
|
||||
CmsArticle article = requireArticle(site.getId(), req.getId());
|
||||
if (bannerRepository.existsByLinkTypeAndLinkValue(
|
||||
com.yunhai.cms.enums.LinkTypeEnum.ARTICLE.getCode(), String.valueOf(article.getId()))) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR,
|
||||
"存在轮播图跳转到该文章,请先在轮播管理中删除或修改对应轮播");
|
||||
}
|
||||
attachmentRepository.unbindArticle(article.getId());
|
||||
articleRepository.delete(article);
|
||||
eventPublisher.publishEvent(new ArticleChangedEvent(article.getId(), site.getId()));
|
||||
}
|
||||
|
||||
/** 定时时间窗校验:offlineTime 必须晚于 publishTime(否则调度器会发布后立刻下架,状态机自相矛盾) */
|
||||
private void validateTimeWindow(LocalDateTime publishTime, LocalDateTime offlineTime) {
|
||||
if (publishTime != null && offlineTime != null && !offlineTime.isAfter(publishTime)) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "定时下架时间必须晚于发布时间");
|
||||
}
|
||||
}
|
||||
|
||||
private CmsArticle requireArticle(Integer siteId, Integer id) {
|
||||
return articleRepository.findByIdAndSiteId(id, siteId)
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "文章不存在"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package com.yunhai.cms.service.impl;
|
||||
|
||||
import com.yunhai.cms.entity.CmsAttachment;
|
||||
import com.yunhai.cms.entity.CmsSite;
|
||||
import com.yunhai.cms.model.dto.DeleteRequest;
|
||||
import com.yunhai.cms.model.vo.AttachmentVo;
|
||||
import com.yunhai.cms.repository.CmsAttachmentRepository;
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import com.yunhai.platform.utils.exception.ErrorCode;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 附件上传/管理(方案 §7.3):FILE_PATH + FILE_WEB_PATH 双 key 约定。
|
||||
* 存储 {FILE_PATH}/cms/{siteCode}/{yyyyMM}/{uuid32}.{ext};类型白名单 + 重命名存储,
|
||||
* 禁止可执行后缀(方案 §8.5);图片类叠加 Content-Type + 魔数双校验(A-3)。
|
||||
* 轮播图/友链 Logo 走同一接口。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AttachmentService {
|
||||
|
||||
private static final DateTimeFormatter MONTH_DIR = DateTimeFormatter.ofPattern("yyyyMM");
|
||||
|
||||
/** 上传白名单(图片/文档/压缩包/音视频);svg 因可携带脚本不入白名单(XSS) */
|
||||
private static final List<String> ALLOWED_EXTS = Arrays.asList(
|
||||
"jpg", "jpeg", "png", "gif", "webp", "bmp", "ico",
|
||||
"pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "md",
|
||||
"zip", "rar", "7z", "mp4", "mp3", "wav");
|
||||
|
||||
/** 图片类扩展名:在白名单之上叠加 Content-Type + 魔数双校验,防伪装后缀(A-3) */
|
||||
private static final List<String> IMAGE_EXTS = Arrays.asList(
|
||||
"jpg", "jpeg", "png", "gif", "webp", "bmp", "ico");
|
||||
|
||||
private final CmsAttachmentRepository attachmentRepository;
|
||||
private final SiteService siteService;
|
||||
|
||||
@Value("${FILE_PATH:./upload/}")
|
||||
private String filePath;
|
||||
|
||||
/** 只接受相对路径(/cms/upload/)或公网可达绝对地址;绝对内网地址(localhost:8072 等)入库即断图(B-1/C-5) */
|
||||
@Value("${FILE_WEB_PATH:/cms/upload/}")
|
||||
private String fileWebPath;
|
||||
|
||||
/** 上传(编辑器图片/附件/轮播图/Logo 复用);articleId 可空 */
|
||||
@Transactional
|
||||
public AttachmentVo upload(BoaUser user, Integer siteId, Integer articleId, MultipartFile file) {
|
||||
CmsSite site = siteService.requireManageable(user, siteId);
|
||||
if (file == null || file.isEmpty()) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "上传文件不能为空");
|
||||
}
|
||||
String originalName = file.getOriginalFilename() == null ? "file" : file.getOriginalFilename();
|
||||
String ext = extOf(originalName);
|
||||
if (!ALLOWED_EXTS.contains(ext)) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "不支持的文件类型:" + ext);
|
||||
}
|
||||
if (IMAGE_EXTS.contains(ext)) {
|
||||
requireRealImage(file, ext);
|
||||
}
|
||||
|
||||
String relativeDir = "cms/" + site.getCode() + "/" + MONTH_DIR.format(LocalDateTime.now());
|
||||
String storedName = UUID.randomUUID().toString().replace("-", "") + "." + ext;
|
||||
File dir = new File(filePath, relativeDir);
|
||||
if (!dir.exists() && !dir.mkdirs()) {
|
||||
throw new BizException(ErrorCode.INTERNAL_SERVER_ERROR, "上传目录创建失败");
|
||||
}
|
||||
try {
|
||||
file.transferTo(new File(dir, storedName));
|
||||
} catch (IOException e) {
|
||||
log.error("附件保存失败 siteId={}", siteId, e);
|
||||
throw new BizException(ErrorCode.INTERNAL_SERVER_ERROR, "文件保存失败");
|
||||
}
|
||||
|
||||
String relativePath = relativeDir + "/" + storedName;
|
||||
String webUrl = joinUrl(fileWebPath, relativePath);
|
||||
|
||||
CmsAttachment attachment = new CmsAttachment();
|
||||
attachment.setSiteId(site.getId());
|
||||
attachment.setArticleId(articleId);
|
||||
attachment.setFileName(originalName);
|
||||
attachment.setFilePath(relativePath);
|
||||
attachment.setWebUrl(webUrl);
|
||||
attachment.setFileSize(file.getSize());
|
||||
attachment.setMimeType(file.getContentType());
|
||||
attachment = attachmentRepository.save(attachment);
|
||||
return AttachmentVo.of(attachment);
|
||||
}
|
||||
|
||||
/** 附件列表(orphanOnly=true 时仅孤儿,附件管理页清理用) */
|
||||
public Map<String, Object> page(BoaUser user, Integer siteId, boolean orphanOnly,
|
||||
Integer page, Integer pageSize) {
|
||||
siteService.requireManageable(user, siteId);
|
||||
int pageIndex = page == null || page < 1 ? 0 : page - 1;
|
||||
int size = pageSize == null || pageSize < 1 ? 10 : pageSize;
|
||||
Page<CmsAttachment> result = orphanOnly
|
||||
? attachmentRepository.findBySiteIdAndArticleIdIsNull(siteId,
|
||||
PageRequest.of(pageIndex, size, Sort.by(Sort.Direction.DESC, "createTime")))
|
||||
: attachmentRepository.findBySiteId(siteId,
|
||||
PageRequest.of(pageIndex, size, Sort.by(Sort.Direction.DESC, "createTime")));
|
||||
List<AttachmentVo> list = new ArrayList<>();
|
||||
for (CmsAttachment a : result.getContent()) {
|
||||
list.add(AttachmentVo.of(a));
|
||||
}
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("total", result.getTotalElements());
|
||||
map.put("list", list);
|
||||
map.put("orphanCount", attachmentRepository.countBySiteIdAndArticleIdIsNull(siteId));
|
||||
return map;
|
||||
}
|
||||
|
||||
/** 删除附件记录(不删物理文件,运维定期清理磁盘,避免误删被引用文件) */
|
||||
@Transactional
|
||||
public void delete(BoaUser user, DeleteRequest req) {
|
||||
siteService.requireManageable(user, req.getSiteId());
|
||||
CmsAttachment attachment = attachmentRepository.findById(req.getId())
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "附件不存在"));
|
||||
if (!attachment.getSiteId().equals(req.getSiteId())) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "无权删除该附件");
|
||||
}
|
||||
attachmentRepository.delete(attachment);
|
||||
}
|
||||
|
||||
/**
|
||||
* 图片类双校验(A-3):Content-Type 必须 image/*,且内容必须真实可解。
|
||||
* 防 .exe 改名 .jpg 之类伪装后缀入库后经门户以图片身份对外分发。
|
||||
*/
|
||||
private void requireRealImage(MultipartFile file, String ext) {
|
||||
String contentType = file.getContentType();
|
||||
if (contentType == null || !contentType.toLowerCase(Locale.ROOT).startsWith("image/")) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "图片文件类型非法(Content-Type=" + contentType + ")");
|
||||
}
|
||||
if (!isDecodableImage(file, ext)) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "文件内容不是有效图片(疑似伪装后缀):" + file.getOriginalFilename());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 魔数校验:jpg/jpeg/png/gif/bmp 用 ImageIO 真实解码(可读才算图片);
|
||||
* webp/ico JDK8 无内置 reader,退化为魔数头校验(RIFF....WEBP / 00 00 01 00)。
|
||||
*/
|
||||
private boolean isDecodableImage(MultipartFile file, String ext) {
|
||||
if ("webp".equals(ext) || "ico".equals(ext)) {
|
||||
byte[] head = readHead(file, 12);
|
||||
if (head.length < 4) {
|
||||
return false;
|
||||
}
|
||||
if ("webp".equals(ext)) {
|
||||
return head.length >= 12
|
||||
&& head[0] == 'R' && head[1] == 'I' && head[2] == 'F' && head[3] == 'F'
|
||||
&& head[8] == 'W' && head[9] == 'E' && head[10] == 'B' && head[11] == 'P';
|
||||
}
|
||||
return head[0] == 0 && head[1] == 0 && head[2] == 1 && head[3] == 0;
|
||||
}
|
||||
try (InputStream in = file.getInputStream()) {
|
||||
return ImageIO.read(in) != null;
|
||||
} catch (IOException e) {
|
||||
log.warn("图片魔数校验读取失败:{}", file.getOriginalFilename());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] readHead(MultipartFile file, int length) {
|
||||
byte[] head = new byte[length];
|
||||
try (InputStream in = file.getInputStream()) {
|
||||
int read = 0;
|
||||
while (read < length) {
|
||||
int n = in.read(head, read, length - read);
|
||||
if (n < 0) {
|
||||
break;
|
||||
}
|
||||
read += n;
|
||||
}
|
||||
return Arrays.copyOf(head, read);
|
||||
} catch (IOException e) {
|
||||
return new byte[0];
|
||||
}
|
||||
}
|
||||
|
||||
private String extOf(String name) {
|
||||
int dot = name.lastIndexOf('.');
|
||||
if (dot < 0 || dot == name.length() - 1) {
|
||||
return "";
|
||||
}
|
||||
return name.substring(dot + 1).toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private String joinUrl(String base, String relative) {
|
||||
if (!StringUtils.hasText(base)) {
|
||||
return "/" + relative;
|
||||
}
|
||||
return base.endsWith("/") ? base + relative : base + "/" + relative;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package com.yunhai.cms.service.impl;
|
||||
|
||||
import com.yunhai.cms.entity.CmsBanner;
|
||||
import com.yunhai.cms.entity.CmsSite;
|
||||
import com.yunhai.cms.enums.LinkTypeEnum;
|
||||
import com.yunhai.cms.event.SiteContentChangedEvent;
|
||||
import com.yunhai.cms.model.dto.BannerSaveRequest;
|
||||
import com.yunhai.cms.model.dto.DeleteRequest;
|
||||
import com.yunhai.cms.model.vo.BannerVo;
|
||||
import com.yunhai.cms.repository.CmsArticleRepository;
|
||||
import com.yunhai.cms.repository.CmsBannerRepository;
|
||||
import com.yunhai.cms.repository.CmsCategoryRepository;
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import com.yunhai.platform.utils.exception.ErrorCode;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 轮播/推荐位管理(方案 §9.1 轮播管理)。保存时校验 link_type/link_value 匹配。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class BannerService {
|
||||
|
||||
private final CmsBannerRepository bannerRepository;
|
||||
private final CmsArticleRepository articleRepository;
|
||||
private final CmsCategoryRepository categoryRepository;
|
||||
private final SiteService siteService;
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
|
||||
public List<BannerVo> list(BoaUser user, Integer siteId, String position) {
|
||||
siteService.requireManageable(user, siteId);
|
||||
List<CmsBanner> banners = StringUtils.hasText(position)
|
||||
? bannerRepository.findBySiteIdAndPositionOrderBySortNoAscIdAsc(siteId, position)
|
||||
: bannerRepository.findBySiteIdOrderByPositionAscSortNoAscIdAsc(siteId);
|
||||
List<BannerVo> result = new ArrayList<>();
|
||||
for (CmsBanner b : banners) {
|
||||
result.add(BannerVo.of(b));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BannerVo save(BoaUser user, BannerSaveRequest req) {
|
||||
CmsSite site = siteService.requireManageable(user, req.getSiteId());
|
||||
LinkTypeEnum linkType = LinkTypeEnum.ofCode(req.getLinkType());
|
||||
if (linkType == null) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "跳转类型非法:" + req.getLinkType() + "(仅 1=文章 2=栏目 3=外链)");
|
||||
}
|
||||
validateLink(site.getId(), linkType, req.getLinkValue());
|
||||
|
||||
CmsBanner banner;
|
||||
if (req.getId() == null) {
|
||||
banner = new CmsBanner();
|
||||
banner.setSiteId(site.getId());
|
||||
} else {
|
||||
banner = bannerRepository.findById(req.getId())
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "轮播不存在"));
|
||||
if (!banner.getSiteId().equals(site.getId())) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "无权修改该轮播");
|
||||
}
|
||||
}
|
||||
banner.setPosition(StringUtils.hasText(req.getPosition()) ? req.getPosition() : "home");
|
||||
banner.setTitle(req.getTitle());
|
||||
banner.setImageUrl(req.getImageUrl());
|
||||
banner.setLinkType(linkType.getCode());
|
||||
banner.setLinkValue(req.getLinkValue());
|
||||
banner.setSortNo(req.getSortNo() == null ? 0 : req.getSortNo());
|
||||
banner.setStartTime(req.getStartTime());
|
||||
banner.setEndTime(req.getEndTime());
|
||||
if (banner.getStartTime() != null && banner.getEndTime() != null
|
||||
&& banner.getEndTime().isBefore(banner.getStartTime())) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "下线时间不能早于上线时间");
|
||||
}
|
||||
banner.setStatus(req.getStatus() == null ? 1 : req.getStatus());
|
||||
banner = bannerRepository.save(banner);
|
||||
eventPublisher.publishEvent(new SiteContentChangedEvent(site.getId(), "banner"));
|
||||
return BannerVo.of(banner);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void delete(BoaUser user, DeleteRequest req) {
|
||||
CmsSite site = siteService.requireManageable(user, req.getSiteId());
|
||||
CmsBanner banner = bannerRepository.findById(req.getId())
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "轮播不存在"));
|
||||
if (!banner.getSiteId().equals(site.getId())) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "无权删除该轮播");
|
||||
}
|
||||
bannerRepository.delete(banner);
|
||||
eventPublisher.publishEvent(new SiteContentChangedEvent(site.getId(), "banner"));
|
||||
}
|
||||
|
||||
/**
|
||||
* link_type/link_value 匹配校验:1=文章 2=栏目(须存在且属于本站,禁止跨站引用)
|
||||
* 3=外链(必须 http/https 开头)。
|
||||
*/
|
||||
private void validateLink(Integer siteId, LinkTypeEnum linkType, String linkValue) {
|
||||
if (linkType == LinkTypeEnum.EXTERNAL) {
|
||||
if (!StringUtils.hasText(linkValue)
|
||||
|| !(linkValue.startsWith("http://") || linkValue.startsWith("https://"))) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "外链地址必须以 http(s):// 开头");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!StringUtils.hasText(linkValue)) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "跳转目标不能为空");
|
||||
}
|
||||
Integer targetId;
|
||||
try {
|
||||
targetId = Integer.valueOf(linkValue.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "跳转目标必须是数字 ID");
|
||||
}
|
||||
if (linkType == LinkTypeEnum.ARTICLE) {
|
||||
articleRepository.findByIdAndSiteId(targetId, siteId)
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "跳转文章不存在"));
|
||||
} else if (linkType == LinkTypeEnum.CATEGORY) {
|
||||
categoryRepository.findById(targetId)
|
||||
.filter(c -> c.getSiteId().equals(siteId))
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "跳转栏目不存在"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package com.yunhai.cms.service.impl;
|
||||
|
||||
import com.yunhai.cms.entity.CmsCategory;
|
||||
import com.yunhai.cms.entity.CmsSite;
|
||||
import com.yunhai.cms.enums.CategoryTypeEnum;
|
||||
import com.yunhai.cms.event.SiteContentChangedEvent;
|
||||
import com.yunhai.cms.model.dto.CategorySaveRequest;
|
||||
import com.yunhai.cms.model.dto.CategorySortRequest;
|
||||
import com.yunhai.cms.model.dto.DeleteRequest;
|
||||
import com.yunhai.cms.model.vo.CategoryTreeNode;
|
||||
import com.yunhai.cms.repository.CmsArticleRepository;
|
||||
import com.yunhai.cms.repository.CmsCategoryRepository;
|
||||
import com.yunhai.cms.utils.HtmlSanitizer;
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import com.yunhai.platform.utils.exception.ErrorCode;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 栏目树管理(方案 §9.1 栏目管理)。删除校验空栏目(无子栏目且无文章)。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class CategoryService {
|
||||
|
||||
private final CmsCategoryRepository categoryRepository;
|
||||
private final CmsArticleRepository articleRepository;
|
||||
private final com.yunhai.cms.repository.CmsBannerRepository bannerRepository;
|
||||
private final SiteService siteService;
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
|
||||
/** 栏目树(管理端全量含隐藏;门户侧由 PortalQueryService 另行过滤) */
|
||||
public List<CategoryTreeNode> tree(BoaUser user, Integer siteId) {
|
||||
siteService.requireManageable(user, siteId);
|
||||
List<CmsCategory> all = categoryRepository.findBySiteIdOrderBySortNoAscIdAsc(siteId);
|
||||
Map<Integer, CategoryTreeNode> nodeMap = new HashMap<>();
|
||||
for (CmsCategory c : all) {
|
||||
nodeMap.put(c.getId(), CategoryTreeNode.of(c));
|
||||
}
|
||||
List<CategoryTreeNode> roots = new ArrayList<>();
|
||||
for (CmsCategory c : all) {
|
||||
CategoryTreeNode node = nodeMap.get(c.getId());
|
||||
CategoryTreeNode parent = c.getParentId() == null ? null : nodeMap.get(c.getParentId());
|
||||
if (parent == null) {
|
||||
roots.add(node);
|
||||
} else {
|
||||
parent.getChildren().add(node);
|
||||
}
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public CategoryTreeNode save(BoaUser user, CategorySaveRequest req) {
|
||||
CmsSite site = siteService.requireManageable(user, req.getSiteId());
|
||||
CategoryTypeEnum type = CategoryTypeEnum.ofCode(req.getType());
|
||||
if (type == null) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "栏目类型非法:" + req.getType() + "(仅 1=列表 2=单页 3=外链)");
|
||||
}
|
||||
if (type == CategoryTypeEnum.LINK && !StringUtils.hasText(req.getLinkUrl())) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "外链栏目必须填写外链地址");
|
||||
}
|
||||
CmsCategory category;
|
||||
if (req.getId() == null) {
|
||||
category = new CmsCategory();
|
||||
category.setSiteId(site.getId());
|
||||
} else {
|
||||
category = categoryRepository.findById(req.getId())
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "栏目不存在"));
|
||||
if (!category.getSiteId().equals(site.getId())) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "无权修改该栏目");
|
||||
}
|
||||
}
|
||||
validateParent(category, req);
|
||||
category.setParentId(req.getParentId() == null ? 0 : req.getParentId());
|
||||
category.setName(req.getName());
|
||||
category.setType(type.getCode());
|
||||
category.setLinkUrl(req.getLinkUrl());
|
||||
category.setTemplate(req.getTemplate());
|
||||
category.setContent(HtmlSanitizer.clean(req.getContent()));
|
||||
category.setSortNo(req.getSortNo() == null ? 0 : req.getSortNo());
|
||||
category.setSeoTitle(req.getSeoTitle());
|
||||
category.setSeoDescription(req.getSeoDescription());
|
||||
category.setStatus(req.getStatus() == null ? 1 : req.getStatus());
|
||||
category = categoryRepository.save(category);
|
||||
eventPublisher.publishEvent(new SiteContentChangedEvent(site.getId(), "category"));
|
||||
return CategoryTreeNode.of(category);
|
||||
}
|
||||
|
||||
private void validateParent(CmsCategory category, CategorySaveRequest req) {
|
||||
Integer parentId = req.getParentId() == null ? 0 : req.getParentId();
|
||||
if (parentId == 0) {
|
||||
return;
|
||||
}
|
||||
if (category.getId() != null && parentId.equals(category.getId())) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "父栏目不能是自身");
|
||||
}
|
||||
CmsCategory parent = categoryRepository.findById(parentId)
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "父栏目不存在"));
|
||||
if (!parent.getSiteId().equals(req.getSiteId())) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "父栏目不属于该站点");
|
||||
}
|
||||
if (category.getId() != null && parent.getParentId() != null
|
||||
&& parent.getParentId().equals(category.getId())) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "不支持把子栏目设为父栏目(成环)");
|
||||
}
|
||||
}
|
||||
|
||||
/** 删除(校验空栏目 + 轮播引用,统一"被引用即拦"规则) */
|
||||
@Transactional
|
||||
public void delete(BoaUser user, DeleteRequest req) {
|
||||
CmsSite site = siteService.requireManageable(user, req.getSiteId());
|
||||
CmsCategory category = categoryRepository.findById(req.getId())
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "栏目不存在"));
|
||||
if (!category.getSiteId().equals(site.getId())) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "无权删除该栏目");
|
||||
}
|
||||
if (categoryRepository.countByParentId(category.getId()) > 0) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "存在子栏目,请先删除子栏目");
|
||||
}
|
||||
if (articleRepository.countByCategoryId(category.getId()) > 0) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "栏目下存在文章,请先处理文章");
|
||||
}
|
||||
if (bannerRepository.existsByLinkTypeAndLinkValue(
|
||||
com.yunhai.cms.enums.LinkTypeEnum.CATEGORY.getCode(), String.valueOf(category.getId()))) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR,
|
||||
"存在轮播图跳转到该栏目,请先在轮播管理中删除或修改对应轮播");
|
||||
}
|
||||
categoryRepository.delete(category);
|
||||
eventPublisher.publishEvent(new SiteContentChangedEvent(site.getId(), "category"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 子栏目排序(UserBase SortChildren 同语义):ids 顺序即 sortNo 1..n。
|
||||
*/
|
||||
@Transactional
|
||||
public void sort(BoaUser user, CategorySortRequest req) {
|
||||
CmsSite site = siteService.requireManageable(user, req.getSiteId());
|
||||
List<Integer> ids = req.getIds();
|
||||
if (ids.isEmpty()) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "子栏目ID列表不能为空");
|
||||
}
|
||||
if (ids.stream().distinct().count() != ids.size()) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "子栏目ID列表存在重复");
|
||||
}
|
||||
List<CmsCategory> children = categoryRepository.findBySiteIdOrderBySortNoAscIdAsc(site.getId()).stream()
|
||||
.filter(c -> c.getParentId() != null && c.getParentId().equals(req.getParentId()))
|
||||
.collect(Collectors.toList());
|
||||
Map<Integer, CmsCategory> childMap = children.stream()
|
||||
.collect(Collectors.toMap(CmsCategory::getId, c -> c, (a, b) -> a));
|
||||
for (Integer id : ids) {
|
||||
if (!childMap.containsKey(id)) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "ids 中存在不属于该栏目的直接子栏目");
|
||||
}
|
||||
}
|
||||
// 按传入顺序落库排序(1 起)
|
||||
for (int i = 0; i < ids.size(); i++) {
|
||||
childMap.get(ids.get(i)).setSortNo(i + 1);
|
||||
}
|
||||
categoryRepository.saveAll(children);
|
||||
eventPublisher.publishEvent(new SiteContentChangedEvent(site.getId(), "category"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.yunhai.cms.service.impl;
|
||||
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import com.yunhai.platform.openapi.client.YschBaseOpenApi;
|
||||
import com.yunhai.platform.utils.exception.ErrorCode;
|
||||
import com.yunhai.platform.utils.model.BoaModule;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 用户中心代理(Notice UserCenterService 同款逻辑平移):
|
||||
* 模块菜单树来自基础平台 SDK(YschBaseOpenApi.getUserModule),扁平转树对齐前端 layout 契约。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class CmsUserCenterService {
|
||||
|
||||
/**
|
||||
* 当前用户已授权模块树(左侧菜单)。
|
||||
*/
|
||||
public List<Map<String, Object>> getUserModuleTree(Integer userId, Integer schId) {
|
||||
if (userId == null) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "用户ID不得为空");
|
||||
}
|
||||
List<BoaModule> modules;
|
||||
try {
|
||||
modules = YschBaseOpenApi.getUserModule(userId, schId);
|
||||
} catch (Exception e) {
|
||||
// 平台不可达时菜单降级为空(登录/站点能力不受影响),避免整页不可用
|
||||
log.warn("[cms] 获取用户模块失败, schId={}: {}", schId, e.getMessage());
|
||||
return Collections.emptyList();
|
||||
}
|
||||
if (modules == null || modules.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return buildModuleTree(modules);
|
||||
}
|
||||
|
||||
/**
|
||||
* 扁平 BoaModule → 树结构(modId/page/children),对齐前端 layout 期望。
|
||||
* 顶层取 parentId=0 或父节点不在列表中的节点,保持 SDK 返回顺序。
|
||||
*/
|
||||
private List<Map<String, Object>> buildModuleTree(List<BoaModule> modules) {
|
||||
Map<Integer, BoaModule> moduleMap = modules.stream()
|
||||
.collect(Collectors.toMap(BoaModule::getId, m -> m, (a, b) -> a));
|
||||
|
||||
Map<Integer, Map<String, Object>> nodeMap = new LinkedHashMap<>();
|
||||
for (BoaModule m : modules) {
|
||||
Map<String, Object> node = new LinkedHashMap<>();
|
||||
node.put("id", m.getId());
|
||||
node.put("modId", m.getId());
|
||||
node.put("name", m.getName());
|
||||
node.put("parentId", m.getParentId() != null ? m.getParentId() : 0);
|
||||
node.put("page", m.getPath() != null ? m.getPath() : "");
|
||||
node.put("level", m.getLevel() != null ? m.getLevel() : 0);
|
||||
node.put("icon", m.getIcon() != null ? m.getIcon() : "");
|
||||
node.put("orderNumber", m.getSortNo() != null ? m.getSortNo() : 0);
|
||||
node.put("usable", true);
|
||||
node.put("children", new ArrayList<>());
|
||||
nodeMap.put(m.getId(), node);
|
||||
}
|
||||
|
||||
List<Map<String, Object>> roots = new ArrayList<>();
|
||||
for (BoaModule m : modules) {
|
||||
Map<String, Object> node = nodeMap.get(m.getId());
|
||||
int parentId = m.getParentId() != null ? m.getParentId() : 0;
|
||||
if (parentId == 0 || !moduleMap.containsKey(parentId)) {
|
||||
roots.add(node);
|
||||
} else {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> children = (List<Map<String, Object>>) nodeMap.get(parentId).get("children");
|
||||
children.add(node);
|
||||
}
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.yunhai.cms.service.impl;
|
||||
|
||||
import com.yunhai.cms.entity.CmsLink;
|
||||
import com.yunhai.cms.entity.CmsSite;
|
||||
import com.yunhai.cms.event.SiteContentChangedEvent;
|
||||
import com.yunhai.cms.model.dto.DeleteRequest;
|
||||
import com.yunhai.cms.model.dto.LinkSaveRequest;
|
||||
import com.yunhai.cms.model.vo.LinkVo;
|
||||
import com.yunhai.cms.repository.CmsLinkRepository;
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import com.yunhai.platform.utils.exception.ErrorCode;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 友情链接管理(方案 §9.1 友情链接管理)。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class LinkService {
|
||||
|
||||
private final CmsLinkRepository linkRepository;
|
||||
private final SiteService siteService;
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
|
||||
public List<LinkVo> list(BoaUser user, Integer siteId) {
|
||||
siteService.requireManageable(user, siteId);
|
||||
List<CmsLink> links = linkRepository.findBySiteIdOrderByGroupNameAscSortNoAscIdAsc(siteId);
|
||||
List<LinkVo> result = new ArrayList<>();
|
||||
for (CmsLink l : links) {
|
||||
result.add(LinkVo.of(l));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public LinkVo save(BoaUser user, LinkSaveRequest req) {
|
||||
CmsSite site = siteService.requireManageable(user, req.getSiteId());
|
||||
if (!StringUtils.hasText(req.getLinkUrl())
|
||||
|| !(req.getLinkUrl().startsWith("http://") || req.getLinkUrl().startsWith("https://")
|
||||
|| req.getLinkUrl().startsWith("/"))) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "链接地址必须以 http(s):// 或 / 开头");
|
||||
}
|
||||
CmsLink link;
|
||||
if (req.getId() == null) {
|
||||
link = new CmsLink();
|
||||
link.setSiteId(site.getId());
|
||||
} else {
|
||||
link = linkRepository.findById(req.getId())
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "友链不存在"));
|
||||
if (!link.getSiteId().equals(site.getId())) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "无权修改该友链");
|
||||
}
|
||||
}
|
||||
link.setGroupName(StringUtils.hasText(req.getGroupName()) ? req.getGroupName() : "default");
|
||||
link.setName(req.getName());
|
||||
link.setLogoUrl(req.getLogoUrl());
|
||||
link.setLinkUrl(req.getLinkUrl());
|
||||
link.setSortNo(req.getSortNo() == null ? 0 : req.getSortNo());
|
||||
link.setStatus(req.getStatus() == null ? 1 : req.getStatus());
|
||||
link = linkRepository.save(link);
|
||||
eventPublisher.publishEvent(new SiteContentChangedEvent(site.getId(), "link"));
|
||||
return LinkVo.of(link);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void delete(BoaUser user, DeleteRequest req) {
|
||||
CmsSite site = siteService.requireManageable(user, req.getSiteId());
|
||||
CmsLink link = linkRepository.findById(req.getId())
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "友链不存在"));
|
||||
if (!link.getSiteId().equals(site.getId())) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "无权删除该友链");
|
||||
}
|
||||
linkRepository.delete(link);
|
||||
eventPublisher.publishEvent(new SiteContentChangedEvent(site.getId(), "link"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.yunhai.cms.service.impl;
|
||||
|
||||
import com.yunhai.cms.event.ArticlePublishedEvent;
|
||||
import com.yunhai.cms.service.WeChatPushService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* 微信推送空实现(方案 §7.4):仅日志留痕,不产生任何外联请求。
|
||||
* 真实实现启用前,管理端"同步到公众号"开关保持灰显。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class NoopWeChatPushService implements WeChatPushService {
|
||||
|
||||
@Override
|
||||
public boolean onArticlePublished(ArticlePublishedEvent event) {
|
||||
log.debug("微信推送未启用,忽略文章发布事件:articleId={}, title={}(规划见《微信平台对接方案.md》)",
|
||||
event.getArticleId(), event.getTitle());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package com.yunhai.cms.service.impl;
|
||||
|
||||
import com.yunhai.cms.config.CacheNames;
|
||||
import com.yunhai.cms.entity.CmsArticle;
|
||||
import com.yunhai.cms.entity.CmsBanner;
|
||||
import com.yunhai.cms.entity.CmsCategory;
|
||||
import com.yunhai.cms.entity.CmsLink;
|
||||
import com.yunhai.cms.entity.CmsSite;
|
||||
import com.yunhai.cms.enums.ArticleStatusEnum;
|
||||
import com.yunhai.cms.model.portal.PortalArticleDetail;
|
||||
import com.yunhai.cms.model.portal.PortalBanner;
|
||||
import com.yunhai.cms.model.portal.PortalCategory;
|
||||
import com.yunhai.cms.model.portal.PortalLinkGroup;
|
||||
import com.yunhai.cms.model.portal.PortalListData;
|
||||
import com.yunhai.cms.model.portal.PortalSiteBrief;
|
||||
import com.yunhai.cms.model.portal.PortalSiteSnapshot;
|
||||
import com.yunhai.cms.repository.CmsArticleRepository;
|
||||
import com.yunhai.cms.repository.CmsBannerRepository;
|
||||
import com.yunhai.cms.repository.CmsCategoryRepository;
|
||||
import com.yunhai.cms.repository.CmsLinkRepository;
|
||||
import com.yunhai.cms.repository.CmsSiteRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 门户只读查询(缓存入口,方案 §8.4)。
|
||||
* 缓存体为不可变 POJO 快照;失效由 AFTER_COMMIT 事件监听(PortalCacheEvictListener)。
|
||||
* 皮肤包不存在时回退 default,避免缺模板 500。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class PortalQueryService {
|
||||
|
||||
private final CmsSiteRepository siteRepository;
|
||||
private final CmsCategoryRepository categoryRepository;
|
||||
private final CmsArticleRepository articleRepository;
|
||||
private final CmsBannerRepository bannerRepository;
|
||||
private final CmsLinkRepository linkRepository;
|
||||
private final com.yunhai.cms.theme.ThemeRegistry themeRegistry;
|
||||
|
||||
/** 站点快照(siteCode → 站点+栏目树+轮播+友链);站点不存在/停用缓存 null 哨兵 */
|
||||
@Cacheable(cacheNames = CacheNames.SITE, key = "#siteCode")
|
||||
public PortalSiteSnapshot siteSnapshot(String siteCode) {
|
||||
CmsSite site = siteRepository.findByCode(siteCode).orElse(null);
|
||||
if (site == null || site.getStatus() == null || site.getStatus() != 1) {
|
||||
return null;
|
||||
}
|
||||
PortalSiteSnapshot snapshot = PortalSiteSnapshot.of(site);
|
||||
snapshot.setTheme(resolveTheme(snapshot.getTheme()));
|
||||
// 微调参数注入(方案 §5.3):按已解析主题 schema 过滤,回退主题与参数过滤天然一致
|
||||
com.yunhai.cms.theme.ThemeInfo themeInfo = themeRegistry.get(snapshot.getTheme());
|
||||
java.util.Map<String, String> themeParams =
|
||||
themeInfo.filterValidValues(rawParamsMap(snapshot));
|
||||
snapshot.setThemeParams(themeParams);
|
||||
snapshot.setThemeVarsCss(com.yunhai.cms.theme.ThemeVarsCss.build(themeInfo, themeParams));
|
||||
|
||||
// 栏目树(仅启用):一次查询复用两遍(建节点 + 组树),省一次 DB 往返
|
||||
List<CmsCategory> categories = categoryRepository.findBySiteIdOrderBySortNoAscIdAsc(site.getId());
|
||||
Map<Integer, PortalCategory> nodeMap = new HashMap<>();
|
||||
List<PortalCategory> roots = new ArrayList<>();
|
||||
for (CmsCategory c : categories) {
|
||||
if (c.getStatus() == null || c.getStatus() != 1) {
|
||||
continue;
|
||||
}
|
||||
PortalCategory node = PortalCategory.of(c);
|
||||
nodeMap.put(node.getId(), node);
|
||||
}
|
||||
for (CmsCategory c : categories) {
|
||||
PortalCategory node = nodeMap.get(c.getId());
|
||||
if (node == null) {
|
||||
continue;
|
||||
}
|
||||
PortalCategory parent = c.getParentId() == null ? null : nodeMap.get(c.getParentId());
|
||||
if (parent == null) {
|
||||
roots.add(node);
|
||||
} else {
|
||||
parent.getChildren().add(node);
|
||||
}
|
||||
}
|
||||
snapshot.setCategories(roots);
|
||||
|
||||
// 轮播(仅启用;时间窗过滤留给渲染)
|
||||
List<PortalBanner> banners = new ArrayList<>();
|
||||
for (CmsBanner b : bannerRepository.findBySiteIdOrderByPositionAscSortNoAscIdAsc(site.getId())) {
|
||||
if (b.getStatus() != null && b.getStatus() == 1) {
|
||||
banners.add(PortalBanner.of(b));
|
||||
}
|
||||
}
|
||||
snapshot.setBanners(banners);
|
||||
|
||||
// 友链分组(仅启用)
|
||||
Map<String, PortalLinkGroup> groupMap = new HashMap<>();
|
||||
List<PortalLinkGroup> groups = new ArrayList<>();
|
||||
for (CmsLink l : linkRepository.findBySiteIdOrderByGroupNameAscSortNoAscIdAsc(site.getId())) {
|
||||
if (l.getStatus() == null || l.getStatus() != 1) {
|
||||
continue;
|
||||
}
|
||||
PortalLinkGroup group = groupMap.computeIfAbsent(l.getGroupName(), k -> {
|
||||
PortalLinkGroup g = new PortalLinkGroup();
|
||||
g.setGroupName(k);
|
||||
groups.add(g);
|
||||
return g;
|
||||
});
|
||||
PortalLinkGroup.PortalLink link = new PortalLinkGroup.PortalLink();
|
||||
link.setName(l.getName());
|
||||
link.setLogoUrl(l.getLogoUrl());
|
||||
link.setLinkUrl(l.getLinkUrl());
|
||||
group.getLinks().add(link);
|
||||
}
|
||||
snapshot.setLinkGroups(groups);
|
||||
|
||||
// 同校院系子站("专业院系"下拉,《院系子站方案》):顶层站取其子站,
|
||||
// 院系子站取兄弟站(含自身,对齐真实高校门户);跨校防御过滤
|
||||
Integer anchorId = snapshot.getParentSiteId() == 0 ? site.getId() : snapshot.getParentSiteId();
|
||||
List<PortalSiteBrief> colleges = new ArrayList<>();
|
||||
for (CmsSite child : siteRepository.findByParentSiteIdAndStatusOrderByIdAsc(anchorId, 1)) {
|
||||
if (site.getSchId() != null && !site.getSchId().equals(child.getSchId())) {
|
||||
continue;
|
||||
}
|
||||
colleges.add(PortalSiteBrief.of(child));
|
||||
}
|
||||
snapshot.setColleges(colleges);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/** 文章详情(已发布才可读;不存在/未发布缓存 null 哨兵 30s 防穿透) */
|
||||
@Cacheable(cacheNames = CacheNames.ARTICLE, key = "#articleId")
|
||||
public PortalArticleDetail articleDetail(Integer articleId) {
|
||||
CmsArticle article = articleRepository.findById(articleId).orElse(null);
|
||||
if (article == null || article.getStatus() == null
|
||||
|| article.getStatus() != ArticleStatusEnum.PUBLISHED.getCode()) {
|
||||
return null;
|
||||
}
|
||||
return PortalArticleDetail.of(article);
|
||||
}
|
||||
|
||||
/**
|
||||
* 栏目分页(已发布,置顶优先 + 发布时间倒序;key=categoryId:page)。
|
||||
* D1-3:父栏目聚合其列表型子孙栏目的文章(高校惯例:文章挂叶子栏目,父栏目页展示汇总)。
|
||||
*/
|
||||
@Cacheable(cacheNames = CacheNames.LIST, key = "#categoryId + ':' + #page")
|
||||
public PortalListData categoryPage(Integer categoryId, Integer page, Integer pageSize) {
|
||||
CmsCategory category = categoryRepository.findById(categoryId).orElse(null);
|
||||
if (category == null) {
|
||||
return null;
|
||||
}
|
||||
int pageIndex = page == null || page < 1 ? 0 : page - 1;
|
||||
Pageable pageable = PageRequest.of(pageIndex, pageSize == null || pageSize < 1 ? 10 : pageSize,
|
||||
Sort.by(Sort.Order.desc("topmost"), Sort.Order.desc("publishTime")));
|
||||
Page<CmsArticle> result = articleRepository.findBySiteIdAndCategoryIdInAndStatus(
|
||||
category.getSiteId(), listCategoryIdsAggregatingChildren(category),
|
||||
ArticleStatusEnum.PUBLISHED.getCode(), pageable);
|
||||
|
||||
PortalListData data = new PortalListData();
|
||||
data.setCategoryId(categoryId);
|
||||
data.setSiteId(category.getSiteId());
|
||||
data.setTotal(result.getTotalElements());
|
||||
data.setPage(pageIndex + 1);
|
||||
data.setPageSize(pageable.getPageSize());
|
||||
data.setTotalPages(result.getTotalPages());
|
||||
for (CmsArticle a : result.getContent()) {
|
||||
PortalListData.Item item = new PortalListData.Item();
|
||||
item.setId(a.getId());
|
||||
item.setTitle(a.getTitle());
|
||||
item.setSummary(a.getSummary());
|
||||
item.setCoverImage(a.getCoverImage());
|
||||
item.setPublishTime(a.getPublishTime());
|
||||
item.setTopmost(a.getTopmost());
|
||||
data.getItems().add(item);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 栏目自身 + 其列表型子孙栏目 id 集(D1-3 聚合用)。
|
||||
* 一次性载入站点栏目(量级小),从目标栏目 BFS;单页/外链型子孙不纳入
|
||||
* (其文章不属于列表语义,且外链栏目无文章)。
|
||||
*/
|
||||
private List<Integer> listCategoryIdsAggregatingChildren(CmsCategory category) {
|
||||
List<Integer> ids = new ArrayList<>();
|
||||
ids.add(category.getId());
|
||||
Map<Integer, List<CmsCategory>> childrenMap = new HashMap<>();
|
||||
for (CmsCategory c : categoryRepository.findBySiteIdOrderBySortNoAscIdAsc(category.getSiteId())) {
|
||||
if (c.getParentId() != null) {
|
||||
childrenMap.computeIfAbsent(c.getParentId(), k -> new ArrayList<>()).add(c);
|
||||
}
|
||||
}
|
||||
java.util.ArrayDeque<Integer> queue = new java.util.ArrayDeque<>(ids);
|
||||
while (!queue.isEmpty()) {
|
||||
Integer current = queue.poll();
|
||||
for (CmsCategory child : childrenMap.getOrDefault(current, java.util.Collections.emptyList())) {
|
||||
if (child.getType() != null
|
||||
&& child.getType() == com.yunhai.cms.enums.CategoryTypeEnum.LIST.getCode()) {
|
||||
ids.add(child.getId());
|
||||
queue.add(child.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/** 站内搜索(title/summary LIKE,实时不缓存,MVP 不上 ES,方案 §2) */
|
||||
public Page<PortalListData.Item> search(Integer siteId, String keyword, Integer page, Integer pageSize) {
|
||||
int pageIndex = page == null || page < 1 ? 0 : page - 1;
|
||||
Pageable pageable = PageRequest.of(pageIndex, pageSize == null || pageSize < 1 ? 10 : pageSize,
|
||||
Sort.by(Sort.Order.desc("publishTime")));
|
||||
// Containing 自带 %包裹与转义,勿手动再加 %(否则字面 % 参与匹配导致恒不命中)
|
||||
String like = keyword == null ? "" : keyword.trim();
|
||||
Page<CmsArticle> result = articleRepository
|
||||
.findBySiteIdAndStatusAndTitleContainingOrSiteIdAndStatusAndSummaryContaining(
|
||||
siteId, ArticleStatusEnum.PUBLISHED.getCode(), like,
|
||||
siteId, ArticleStatusEnum.PUBLISHED.getCode(), like, pageable);
|
||||
return result.map(a -> {
|
||||
PortalListData.Item item = new PortalListData.Item();
|
||||
item.setId(a.getId());
|
||||
item.setTitle(a.getTitle());
|
||||
item.setSummary(a.getSummary());
|
||||
item.setCoverImage(a.getCoverImage());
|
||||
item.setPublishTime(a.getPublishTime());
|
||||
item.setTopmost(a.getTopmost());
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
/** 皮肤包存在性检查:委托 ThemeRegistry(theme.json + 4 模板齐全校验,方案 §5.1 重构,缺省回退 default) */
|
||||
private String resolveTheme(String theme) {
|
||||
if (themeRegistry.contains(theme)) {
|
||||
return theme;
|
||||
}
|
||||
log.warn("皮肤包 {} 未注册,回退 default", theme);
|
||||
return com.yunhai.cms.theme.ThemeRegistry.DEFAULT_THEME;
|
||||
}
|
||||
|
||||
/** config_json.theme_params 原始值(非对象形态按无参数处理) */
|
||||
private Map<?, ?> rawParamsMap(PortalSiteSnapshot snapshot) {
|
||||
Object raw = snapshot.getConfig() == null ? null : snapshot.getConfig().get("theme_params");
|
||||
return raw instanceof Map ? (Map<?, ?>) raw : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.yunhai.cms.service.impl;
|
||||
|
||||
import com.yunhai.cms.model.vo.SchoolVo;
|
||||
import com.yunhai.cms.model.vo.SiteVo;
|
||||
import com.yunhai.cms.repository.CmsArticleRepository;
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import com.yunhai.platform.openapi.client.YschBaseOpenApi;
|
||||
import com.yunhai.platform.utils.exception.ErrorCode;
|
||||
import com.yunhai.platform.utils.model.BoaGroup;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 学校工作台(docs/09 §3.3,方案A 双层壳):
|
||||
* ① listFor —— 学校卡片 = 顶层站点(主站),院系子站经 parentSiteId 归属;
|
||||
* 权限语义与 {@link SiteService#listFor} 完全一致(超管全部 / 校级本校 / 无角色空)。
|
||||
* ② schoolOptions —— 「添加学校」选择器:代理 UserBase oapi getGroupTree 过滤 type=2(学校组),
|
||||
* 只绑定不跨系统写(D6-4);平台不可达降级空数组(CmsUserCenterService 同款)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class SchoolService {
|
||||
|
||||
/** UserBase GroupTypeEnum.SCHOOL_GROUP:学校组节点类型 */
|
||||
private static final int GROUP_TYPE_SCHOOL = 2;
|
||||
|
||||
private final SiteService siteService;
|
||||
private final CmsArticleRepository articleRepository;
|
||||
|
||||
/** 学校工作台列表:当前用户可见的顶层站点逐站聚合成学校卡片 */
|
||||
public List<SchoolVo> listFor(BoaUser user) {
|
||||
List<SiteVo> sites = siteService.listFor(user);
|
||||
List<SchoolVo> result = new ArrayList<>();
|
||||
for (SiteVo top : sites) {
|
||||
if (top.getParentSiteId() != null && top.getParentSiteId() > 0) {
|
||||
continue;
|
||||
}
|
||||
SchoolVo vo = new SchoolVo();
|
||||
vo.setSchId(top.getSchId());
|
||||
vo.setSchName(top.getSchName());
|
||||
vo.setMainSiteId(top.getId());
|
||||
vo.setMainSiteCode(top.getCode());
|
||||
vo.setMainSiteName(top.getName());
|
||||
vo.setTheme(top.getTheme());
|
||||
vo.setStatus(top.getStatus());
|
||||
// 院系子站按 parentSiteId 归属(同权限范围内统计)
|
||||
long articleCount = 0;
|
||||
int siteCount = 1;
|
||||
for (SiteVo s : sites) {
|
||||
if (s.getParentSiteId() != null && top.getId().equals(s.getParentSiteId())) {
|
||||
siteCount++;
|
||||
}
|
||||
}
|
||||
for (SiteVo s : sites) {
|
||||
boolean own = s.getId().equals(top.getId());
|
||||
boolean child = s.getParentSiteId() != null && top.getId().equals(s.getParentSiteId());
|
||||
if (own || child) {
|
||||
articleCount += articleRepository.countBySiteId(s.getId());
|
||||
}
|
||||
}
|
||||
vo.setSiteCount(siteCount);
|
||||
vo.setArticleCount(articleCount);
|
||||
result.add(vo);
|
||||
}
|
||||
result.sort((a, b) -> Integer.compare(a.getMainSiteId(), b.getMainSiteId()));
|
||||
return result;
|
||||
}
|
||||
|
||||
/** UserBase 学校选项(仅超管;添加学校=绑定已有学校,不新建) */
|
||||
public List<SchoolVo.Option> schoolOptions(BoaUser user) {
|
||||
siteService.requireSuperAdmin(user);
|
||||
BoaGroup root;
|
||||
try {
|
||||
root = YschBaseOpenApi.getGroupTree();
|
||||
} catch (Exception e) {
|
||||
log.warn("[cms] 获取 UserBase 学校组树失败,学校选项降级为空: {}", e.getMessage());
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<SchoolVo.Option> options = new ArrayList<>();
|
||||
collectSchools(root, options);
|
||||
return options;
|
||||
}
|
||||
|
||||
private void collectSchools(BoaGroup node, List<SchoolVo.Option> out) {
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
if (node.getType() != null && node.getType() == GROUP_TYPE_SCHOOL) {
|
||||
out.add(new SchoolVo.Option(node.getId(), node.getName()));
|
||||
}
|
||||
if (node.getChildren() != null) {
|
||||
for (BoaGroup child : node.getChildren()) {
|
||||
collectSchools(child, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 工作台卡片挂载的站点摘要(供校名下拉/快速切换;权限复用 listFor) */
|
||||
public Map<Integer, List<SiteVo>> sitesGroupedByMain(BoaUser user) {
|
||||
List<SiteVo> sites = siteService.listFor(user);
|
||||
Map<Integer, List<SiteVo>> grouped = new LinkedHashMap<>();
|
||||
for (SiteVo s : sites) {
|
||||
Integer mainId = (s.getParentSiteId() == null || s.getParentSiteId() <= 0)
|
||||
? s.getId() : s.getParentSiteId();
|
||||
grouped.computeIfAbsent(mainId, k -> new ArrayList<>()).add(s);
|
||||
}
|
||||
return grouped;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package com.yunhai.cms.service.impl;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.yunhai.cms.config.CmsAuthProperties;
|
||||
import com.yunhai.cms.entity.CmsSite;
|
||||
import com.yunhai.cms.event.SiteContentChangedEvent;
|
||||
import com.yunhai.cms.model.dto.SiteSaveRequest;
|
||||
import com.yunhai.cms.model.vo.SiteVo;
|
||||
import com.yunhai.cms.repository.CmsSiteRepository;
|
||||
import com.yunhai.cms.utils.ExtJsonUtils;
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import com.yunhai.platform.utils.exception.ErrorCode;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 站点与校级权限(方案 §7.2):
|
||||
* ① 平台超管(BoaUser.type==1)→ 所有站点;② 学校角色(currentRole.schId)→ 仅本校站点(site.sch_id 匹配)。
|
||||
* 所有管理端写操作入口先过 {@link #requireManageable}。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class SiteService {
|
||||
|
||||
private final CmsSiteRepository siteRepository;
|
||||
private final CmsAuthProperties authProperties;
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
private final com.yunhai.cms.theme.ThemeRegistry themeRegistry;
|
||||
|
||||
/** config_json 已知键约束(与前端 utils/siteConfigForm.ts 保持一致,docs/09 §0 键清单) */
|
||||
private static final ObjectMapper CONFIG_MAPPER = new ObjectMapper();
|
||||
private static final Pattern HOST_PATTERN = Pattern.compile(
|
||||
"^(\\*\\.)?[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)+$");
|
||||
private static final Pattern URL_PATTERN = Pattern.compile("^https?://\\S+$");
|
||||
private static final Pattern ASSET_PATTERN = Pattern.compile("^(/.+|https?://\\S+)$");
|
||||
private static final Pattern CONFIG_KEY_PATTERN = Pattern.compile("^[A-Za-z_][A-Za-z0-9_]*$");
|
||||
private static final Set<String> RESERVED_CONFIG_KEYS =
|
||||
java.util.Collections.unmodifiableSet(new java.util.HashSet<>(java.util.Arrays.asList("theme_params")));
|
||||
private static final int CONFIG_VALUE_MAX_LEN = 500;
|
||||
|
||||
/** 当前用户可管理的站点列表(含上级站点名回填,展示"主站/院系子站"层级) */
|
||||
public List<SiteVo> listFor(BoaUser user) {
|
||||
List<CmsSite> sites = authProperties.isSuperAdmin(user)
|
||||
? siteRepository.findAll()
|
||||
: (user.getCurrentRole() == null || user.getCurrentRole().getSchId() == null
|
||||
? java.util.Collections.emptyList()
|
||||
: siteRepository.findBySchId(user.getCurrentRole().getSchId()));
|
||||
Map<Integer, String> nameById = new java.util.HashMap<>();
|
||||
for (CmsSite site : sites) {
|
||||
nameById.put(site.getId(), site.getName());
|
||||
}
|
||||
List<SiteVo> result = new ArrayList<>();
|
||||
for (CmsSite site : sites) {
|
||||
SiteVo vo = SiteVo.of(site);
|
||||
if (vo.getParentSiteId() != null && vo.getParentSiteId() > 0) {
|
||||
vo.setParentName(nameById.get(vo.getParentSiteId()));
|
||||
}
|
||||
result.add(vo);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 校验可管理权限并返回站点;越权抛 FORBIDDEN */
|
||||
public CmsSite requireManageable(BoaUser user, Integer siteId) {
|
||||
CmsSite site = siteRepository.findById(siteId == null ? -1 : siteId)
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "站点不存在"));
|
||||
if (!canManage(user, site)) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "无权管理该站点");
|
||||
}
|
||||
return site;
|
||||
}
|
||||
|
||||
public boolean canManage(BoaUser user, CmsSite site) {
|
||||
if (authProperties.isSuperAdmin(user)) {
|
||||
return true;
|
||||
}
|
||||
Integer schId = user.getCurrentRole() == null ? null : user.getCurrentRole().getSchId();
|
||||
return schId != null && site.getSchId() != null && schId.equals(site.getSchId());
|
||||
}
|
||||
|
||||
public void requireSuperAdmin(BoaUser user) {
|
||||
if (!authProperties.isSuperAdmin(user)) {
|
||||
throw new BizException(ErrorCode.FORBIDDEN, "仅平台超管可执行该操作");
|
||||
}
|
||||
}
|
||||
|
||||
public CmsSite getByCode(String code) {
|
||||
return siteRepository.findByCode(code).orElse(null);
|
||||
}
|
||||
|
||||
public String configValue(CmsSite site, String key) {
|
||||
Map<String, Object> config = ExtJsonUtils.parse(site.getConfigJson());
|
||||
return ExtJsonUtils.getString(config, key);
|
||||
}
|
||||
|
||||
/** 站点保存(仅超管;MVP 1-2 校以初始化脚本为主,本接口为后台兜底) */
|
||||
@Transactional
|
||||
public SiteVo save(BoaUser user, SiteSaveRequest req) {
|
||||
requireSuperAdmin(user);
|
||||
CmsSite site;
|
||||
if (req.getId() == null) {
|
||||
if (siteRepository.findByCode(req.getCode()).isPresent()) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "站点编码已存在");
|
||||
}
|
||||
site = new CmsSite();
|
||||
site.setCode(req.getCode());
|
||||
} else {
|
||||
site = siteRepository.findById(req.getId())
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "站点不存在"));
|
||||
}
|
||||
validateParent(req, site);
|
||||
// B-8:顶层站 schId 必填——canManage 按 currentRole.schId ↔ site.schId 匹配,
|
||||
// 顶层站空 schId 建成即"校级角色不可见/不可管"(院系子站已在 validateParent 继承主站 schId,不受影响)
|
||||
if ((site.getParentSiteId() == null || site.getParentSiteId() == 0) && req.getSchId() == null) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "顶层站点必须指定学校ID(schId),否则校级角色无法管理");
|
||||
}
|
||||
site.setSchId(req.getSchId());
|
||||
site.setSchName(req.getSchName());
|
||||
site.setName(req.getName());
|
||||
String resolvedTheme = StringUtils.hasText(req.getTheme())
|
||||
? req.getTheme() : com.yunhai.cms.theme.ThemeRegistry.DEFAULT_THEME;
|
||||
if (!themeRegistry.contains(resolvedTheme)) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "皮肤包未注册:" + resolvedTheme);
|
||||
}
|
||||
site.setTheme(resolvedTheme);
|
||||
validateConfigJson(req.getConfigJson());
|
||||
site.setConfigJson(mergeThemeParams(req, resolvedTheme));
|
||||
site.setStatus(req.getStatus() == null ? 1 : req.getStatus());
|
||||
site = siteRepository.save(site);
|
||||
eventPublisher.publishEvent(new SiteContentChangedEvent(site.getId(), "site"));
|
||||
return SiteVo.of(site);
|
||||
}
|
||||
|
||||
/**
|
||||
* themeParams 服务端合并(方案 §5.3,对应评审 R6):仅替换 config_json.theme_params 键,
|
||||
* 保留 logo/contact/domain 等其余键;未声明 key 与非法值按所选主题 schema 丢弃(不回传错误)。
|
||||
* SPA 不再手拼 configJson 中的该节点。
|
||||
*/
|
||||
private String mergeThemeParams(SiteSaveRequest req, String theme) {
|
||||
if (req.getThemeParams() == null) {
|
||||
return req.getConfigJson();
|
||||
}
|
||||
Map<String, Object> config = new java.util.LinkedHashMap<>(ExtJsonUtils.parse(req.getConfigJson()));
|
||||
Map<String, String> filtered = themeRegistry.get(theme).filterValidValues(req.getThemeParams());
|
||||
if (filtered.isEmpty()) {
|
||||
config.remove("theme_params");
|
||||
} else {
|
||||
config.put("theme_params", filtered);
|
||||
}
|
||||
try {
|
||||
return new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(config);
|
||||
} catch (Exception e) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "站点配置序列化失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 院系子站层级校验(《院系子站方案》):上级必须存在、必须为顶层站(层级固定两层)、
|
||||
* 与子站同校;子站缺省继承主站的学校信息;已挂子站的顶层站禁止改挂为子站(防锚点悬空)。
|
||||
*/
|
||||
private void validateParent(SiteSaveRequest req, CmsSite site) {
|
||||
Integer parentSiteId = req.getParentSiteId() == null ? 0 : req.getParentSiteId();
|
||||
if (parentSiteId <= 0) {
|
||||
site.setParentSiteId(0);
|
||||
return;
|
||||
}
|
||||
if (site.getId() != null && site.getId().equals(parentSiteId)) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "上级站点不能是自身");
|
||||
}
|
||||
CmsSite parent = siteRepository.findById(parentSiteId)
|
||||
.orElseThrow(() -> new BizException(ErrorCode.PARAM_ERROR, "上级站点不存在"));
|
||||
if (parent.getParentSiteId() != null && parent.getParentSiteId() > 0) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "院系子站下不允许再挂子站");
|
||||
}
|
||||
if (req.getSchId() == null) {
|
||||
req.setSchId(parent.getSchId());
|
||||
req.setSchName(parent.getSchName());
|
||||
} else if (parent.getSchId() != null && !req.getSchId().equals(parent.getSchId())) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "院系子站与主站不属于同一学校");
|
||||
}
|
||||
boolean wasTopLevel = site.getId() == null || site.getParentSiteId() == null
|
||||
|| site.getParentSiteId() == 0;
|
||||
if (wasTopLevel && site.getId() != null && siteRepository.existsByParentSiteId(site.getId())) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "该站点下已有院系子站,不能改为院系子站");
|
||||
}
|
||||
site.setParentSiteId(parentSiteId);
|
||||
}
|
||||
|
||||
/**
|
||||
* config_json 校验(docs/09 §3.1,替代旧「空 Map 且长度>2」判定):
|
||||
* ① 必须是 JSON 对象(修复 A-09:带空白空对象误判);② 键名仅字母/数字/下划线;
|
||||
* ③ 已知键按类型校验(domain 域名 / public_base_url 完整 URL / logo、favicon 资产路径)。
|
||||
* 系统托管键 theme_params 直通;非字符串值(wechat 等预留对象)不校验原样放行——
|
||||
* 只拦新脏数据,不做严格 schema 拒绝未知键(D6-2)。
|
||||
*/
|
||||
private void validateConfigJson(String configJson) {
|
||||
if (!StringUtils.hasText(configJson)) {
|
||||
return;
|
||||
}
|
||||
JsonNode node;
|
||||
try {
|
||||
node = CONFIG_MAPPER.readTree(configJson);
|
||||
} catch (Exception e) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "站点配置不是合法的 JSON");
|
||||
}
|
||||
if (!node.isObject()) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "站点配置必须是 JSON 对象");
|
||||
}
|
||||
node.fields().forEachRemaining(entry -> {
|
||||
String key = entry.getKey();
|
||||
if (RESERVED_CONFIG_KEYS.contains(key)) {
|
||||
return;
|
||||
}
|
||||
if (!CONFIG_KEY_PATTERN.matcher(key).matches()) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR,
|
||||
"站点配置键名不合法:" + key + "(仅限字母/数字/下划线,且以字母或下划线开头)");
|
||||
}
|
||||
JsonNode value = entry.getValue();
|
||||
if (!value.isTextual()) {
|
||||
return;
|
||||
}
|
||||
String text = value.asText();
|
||||
if (!StringUtils.hasText(text)) {
|
||||
return;
|
||||
}
|
||||
if (text.length() > CONFIG_VALUE_MAX_LEN) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR, "站点配置值过长:" + key + "(上限 500 字)");
|
||||
}
|
||||
switch (key) {
|
||||
case "domain":
|
||||
if (!HOST_PATTERN.matcher(text).matches()) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR,
|
||||
"绑定域名格式不正确:" + text + "(示例 www.xxx.edu.cn,不带协议)");
|
||||
}
|
||||
break;
|
||||
case "public_base_url":
|
||||
if (!URL_PATTERN.matcher(text).matches()) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR,
|
||||
"对外基地址必须是完整的 http(s):// 地址:" + text);
|
||||
}
|
||||
break;
|
||||
case "logo":
|
||||
case "favicon":
|
||||
if (!ASSET_PATTERN.matcher(text).matches()) {
|
||||
throw new BizException(ErrorCode.PARAM_ERROR,
|
||||
key + " 必须是站点上传路径(/ 开头)或 http(s) 地址");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.yunhai.cms.service.impl;
|
||||
|
||||
import com.yunhai.cms.model.vo.ThemeVo;
|
||||
import com.yunhai.cms.theme.ThemeInfo;
|
||||
import com.yunhai.cms.theme.ThemeRegistry;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 主题管理(方案 §5.1/§5.2):主题列表(含参数 schema)供管理端卡片选择与
|
||||
* 参数表单动态生成;screenshot 与预览资产经 /api/theme/{name}/asset/** 代理。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ThemeService {
|
||||
|
||||
private final ThemeRegistry themeRegistry;
|
||||
|
||||
/** 可用主题(default 优先,其余按名称排序),管理端建站向导与站点编辑共用 */
|
||||
public List<ThemeVo> list() {
|
||||
List<ThemeVo> result = new ArrayList<>();
|
||||
for (ThemeInfo info : themeRegistry.list()) {
|
||||
result.add(ThemeVo.of(info));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 未注册主题返回 null(白名单判断用) */
|
||||
public ThemeInfo get(String name) {
|
||||
return themeRegistry.get(name);
|
||||
}
|
||||
|
||||
/** 未注册主题抛 PARAM_ERROR(预览接口明确 400 语义,不静默回退,方案 §5.5/T27) */
|
||||
public ThemeInfo requireRegistered(String name) {
|
||||
ThemeInfo info = themeRegistry.get(name);
|
||||
if (info == null) {
|
||||
throw new com.yunhai.platform.apistd.BizException(
|
||||
com.yunhai.platform.utils.exception.ErrorCode.PARAM_ERROR, "皮肤包未注册:" + name);
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取预览 p_* 前缀参数并按主题 schema 过滤(方案 §5.5):
|
||||
* key 为 theme.json 声明过的,# 由前端 URLSearchParams 自动编码为 %23(容器已解码)。
|
||||
*/
|
||||
public java.util.Map<String, String> extractPreviewParams(ThemeInfo info,
|
||||
java.util.Map<String, String[]> parameterMap) {
|
||||
java.util.Map<String, Object> raw = new java.util.LinkedHashMap<>();
|
||||
if (parameterMap != null) {
|
||||
for (java.util.Map.Entry<String, String[]> e : parameterMap.entrySet()) {
|
||||
if (e.getKey().startsWith("p_") && e.getValue() != null && e.getValue().length > 0) {
|
||||
raw.put(e.getKey().substring(2), e.getValue()[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return info.filterValidValues(raw);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.yunhai.cms.service.impl;
|
||||
|
||||
import com.yunhai.cms.repository.CmsArticleRepository;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 浏览量异步累加(方案 §5.2):详情渲染 fire-and-forget UPDATE,失败忽略;
|
||||
* 量大后改缓存批量聚合。单线程队列足够 1-2 校门户流量。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class ViewCounterService {
|
||||
|
||||
private final CmsArticleRepository articleRepository;
|
||||
private final TransactionTemplate transactionTemplate;
|
||||
private final ExecutorService executor = Executors.newSingleThreadExecutor(r -> {
|
||||
Thread thread = new Thread(r, "cms-view-counter");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
|
||||
public ViewCounterService(CmsArticleRepository articleRepository,
|
||||
TransactionTemplate transactionTemplate) {
|
||||
this.articleRepository = articleRepository;
|
||||
this.transactionTemplate = transactionTemplate;
|
||||
}
|
||||
|
||||
public void increment(Integer articleId) {
|
||||
if (articleId == null) {
|
||||
return;
|
||||
}
|
||||
executor.execute(() -> {
|
||||
try {
|
||||
transactionTemplate.executeWithoutResult(
|
||||
status -> articleRepository.incrementViewCount(articleId));
|
||||
} catch (Exception e) {
|
||||
log.debug("浏览量累加失败 articleId={}(忽略)", articleId, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void shutdown() {
|
||||
executor.shutdown();
|
||||
try {
|
||||
executor.awaitTermination(3, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.yunhai.cms.theme;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 主题包元数据(theme.json 解析结果,方案 §4.2)。
|
||||
* 仅含包声明信息;注册与校验在 {@link ThemeRegistry}。
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class ThemeInfo {
|
||||
|
||||
private Integer specVersion;
|
||||
|
||||
private String name;
|
||||
|
||||
private String title;
|
||||
|
||||
private String version;
|
||||
|
||||
private String author;
|
||||
|
||||
private String description;
|
||||
|
||||
/** 预览图相对包路径(缺省 assets/screenshot.png,方案 §4.1/§5.2) */
|
||||
private String screenshot;
|
||||
|
||||
/** 轮播图设计尺寸约定(D2 决策点),如 1920x560 */
|
||||
private String bannerSize;
|
||||
|
||||
private List<ThemeParam> params = new ArrayList<>();
|
||||
|
||||
public String screenshotPath() {
|
||||
return screenshot == null || screenshot.isEmpty() ? "assets/screenshot.png" : screenshot;
|
||||
}
|
||||
|
||||
public ThemeParam param(String key) {
|
||||
for (ThemeParam p : params) {
|
||||
if (p.getKey() != null && p.getKey().equals(key)) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 schema 过滤 + 校验原始参数(方案 §5.3 合并语义):
|
||||
* 未声明 key 丢弃、非法值丢弃;返回仅含合法声明的有序 Map。
|
||||
*/
|
||||
public Map<String, String> filterValidValues(Map<?, ?> raw) {
|
||||
Map<String, String> result = new LinkedHashMap<>();
|
||||
if (raw == null) {
|
||||
return result;
|
||||
}
|
||||
for (Map.Entry<?, ?> entry : raw.entrySet()) {
|
||||
Object rawKey = entry.getKey();
|
||||
Object rawValue = entry.getValue();
|
||||
if (rawKey == null || rawValue == null) {
|
||||
continue;
|
||||
}
|
||||
ThemeParam schema = param(rawKey.toString());
|
||||
String value = rawValue.toString();
|
||||
if (schema != null && schema.isValidValue(value)) {
|
||||
result.put(schema.getKey(), value);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.yunhai.cms.theme;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 主题包可调参数声明(theme.json params[],方案 §4.2)。
|
||||
* 类型与取值约束:color 色值正则 / image 仅 /cms/upload/** / select 枚举 / text 短文本。
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class ThemeParam {
|
||||
|
||||
public static final String TYPE_COLOR = "color";
|
||||
public static final String TYPE_IMAGE = "image";
|
||||
public static final String TYPE_SELECT = "select";
|
||||
public static final String TYPE_TEXT = "text";
|
||||
|
||||
/** color 合法值:#RGB/#RRGGBB/#RRGGBBAA(方案 §4.2,防 CSS 上下文注入) */
|
||||
public static final Pattern COLOR_PATTERN = Pattern.compile("^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$");
|
||||
|
||||
/** param key 约束(方案 §4.1) */
|
||||
public static final Pattern KEY_PATTERN = Pattern.compile("^[a-zA-Z][a-zA-Z0-9_]{0,31}$");
|
||||
|
||||
private String key;
|
||||
|
||||
/** 聚合进 :root{} 的 CSS 变量名(仅 color 类型允许,方案 §4.1/§9) */
|
||||
private String cssVar;
|
||||
|
||||
private String label;
|
||||
|
||||
private String type;
|
||||
|
||||
@JsonProperty("default")
|
||||
private String defaultValue;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@Data
|
||||
public static class Option {
|
||||
private String value;
|
||||
private String label;
|
||||
}
|
||||
|
||||
private List<Option> options;
|
||||
|
||||
/** 值是否合法(按参数类型;null/空一律不合法,方案 §5.3) */
|
||||
public boolean isValidValue(String value) {
|
||||
if (value == null || value.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
switch (type == null ? "" : type) {
|
||||
case TYPE_COLOR:
|
||||
return COLOR_PATTERN.matcher(value).matches();
|
||||
case TYPE_IMAGE:
|
||||
// B-7:与应用真实可达路径对齐——附件 webUrl 相对形态为 /cms/upload/**(含 context-path),
|
||||
// 旧约定 /upload/** 在 context-path=/cms 部署下渲染必 404
|
||||
return value.startsWith("/cms/upload/");
|
||||
case TYPE_SELECT:
|
||||
return options != null && options.stream().anyMatch(o -> value.equals(o.getValue()));
|
||||
case TYPE_TEXT:
|
||||
return value.length() <= 256;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 是否聚合为 CSS 变量(仅 color 且声明了 cssVar,方案 §4.2) */
|
||||
public boolean isCssVarParam() {
|
||||
return cssVar != null && !cssVar.isEmpty() && TYPE_COLOR.equals(type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package com.yunhai.cms.theme;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 主题注册表(方案 §5.1):启动时按 SCAN_PATTERN 扫描各主题包的 theme.json,
|
||||
* 按包规范(§4.1)校验,坏包剔除 + log.warn;default 缺失或非法 → 启动失败(fail-fast)。
|
||||
* 运行时不支持热加载,皮肤包随版本发布(zip 上传是 P3 项)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class ThemeRegistry {
|
||||
|
||||
public static final String DEFAULT_THEME = "default";
|
||||
|
||||
/** 包名与目录名约束(方案 §4.1) */
|
||||
private static final Pattern NAME_PATTERN = Pattern.compile("^[a-z][a-z0-9-]{1,30}[a-z0-9]$");
|
||||
|
||||
/** 必备页面模板(方案 §4.1,收紧 R12:缺任一即整包剔除) */
|
||||
private static final List<String> REQUIRED_TEMPLATES =
|
||||
Arrays.asList("home.html", "list.html", "detail.html", "single.html");
|
||||
|
||||
private static final String SCAN_PATTERN = "classpath*:templates/themes/*/theme.json";
|
||||
|
||||
/** 未知字段忽略、已知字段兼容(方案 §4.2 specVersion 演进策略) */
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper()
|
||||
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
private final Map<String, ThemeInfo> themes = new LinkedHashMap<>();
|
||||
|
||||
@PostConstruct
|
||||
public void load() {
|
||||
themes.clear();
|
||||
Map<String, ThemeInfo> loaded = new LinkedHashMap<>();
|
||||
int rejected = 0;
|
||||
for (Resource resource : scanResources()) {
|
||||
String dirName = dirNameOf(resource);
|
||||
try {
|
||||
ThemeInfo info = MAPPER.readValue(resource.getInputStream(), ThemeInfo.class);
|
||||
validate(info, dirName);
|
||||
loaded.put(info.getName(), info);
|
||||
} catch (Exception e) {
|
||||
rejected++;
|
||||
log.warn("主题包 {} 注册失败被剔除:{}", dirName, e.getMessage());
|
||||
}
|
||||
}
|
||||
List<ThemeInfo> sorted = new ArrayList<>(loaded.values());
|
||||
sorted.sort(Comparator.comparing(info -> DEFAULT_THEME.equals(info.getName())
|
||||
? "" : info.getName()));
|
||||
for (ThemeInfo info : sorted) {
|
||||
themes.put(info.getName(), info);
|
||||
}
|
||||
verifyDefaultPresent();
|
||||
log.info("主题注册表加载完成:可用 {} {},剔除 {} 个坏包", themes.size(), themes.keySet(), rejected);
|
||||
}
|
||||
|
||||
/** default 包缺失或非法时抛 IllegalStateException 阻止启动(方案 §5.1 fail-fast) */
|
||||
public void verifyDefaultPresent() {
|
||||
if (!themes.containsKey(DEFAULT_THEME)) {
|
||||
throw new IllegalStateException("默认主题包 default 缺失或非法,拒绝启动(方案 §5.1)");
|
||||
}
|
||||
}
|
||||
|
||||
/** 可用主题(default 优先,其余按名称排序) */
|
||||
public List<ThemeInfo> list() {
|
||||
return new ArrayList<>(themes.values());
|
||||
}
|
||||
|
||||
public boolean contains(String name) {
|
||||
return name != null && themes.containsKey(name);
|
||||
}
|
||||
|
||||
public ThemeInfo get(String name) {
|
||||
return name == null ? null : themes.get(name);
|
||||
}
|
||||
|
||||
// ===== 包规范校验(方案 §4.1)=====
|
||||
|
||||
private void validate(ThemeInfo info, String dirName) {
|
||||
if (info == null) {
|
||||
throw new IllegalArgumentException("清单为空");
|
||||
}
|
||||
if (info.getSpecVersion() == null || info.getSpecVersion() != 1) {
|
||||
throw new IllegalArgumentException("specVersion 必须为 1");
|
||||
}
|
||||
if (info.getName() == null || !NAME_PATTERN.matcher(info.getName()).matches()) {
|
||||
throw new IllegalArgumentException("name 缺失或不符合命名规范:" + info.getName());
|
||||
}
|
||||
if (!info.getName().equals(dirName)) {
|
||||
throw new IllegalArgumentException("name 与目录名不一致:" + dirName + " != " + info.getName());
|
||||
}
|
||||
for (String template : REQUIRED_TEMPLATES) {
|
||||
if (!new ClassPathResource("templates/themes/" + dirName + "/" + template).exists()) {
|
||||
throw new IllegalArgumentException("缺必备模板 " + template);
|
||||
}
|
||||
}
|
||||
// fragments/ 目录存在性以 head.html 片段代替(jar 内目录项不可靠)
|
||||
if (!new ClassPathResource("templates/themes/" + dirName + "/fragments/head.html").exists()) {
|
||||
throw new IllegalArgumentException("缺 fragments/head.html 公共片段");
|
||||
}
|
||||
validateParams(info);
|
||||
String shot = "templates/themes/" + dirName + "/" + info.screenshotPath();
|
||||
if (!new ClassPathResource(shot).exists()) {
|
||||
throw new IllegalArgumentException("声明的 screenshot 不存在:" + info.screenshotPath());
|
||||
}
|
||||
}
|
||||
|
||||
private void validateParams(ThemeInfo info) {
|
||||
List<String> seen = new ArrayList<>();
|
||||
for (ThemeParam p : info.getParams()) {
|
||||
if (p.getKey() == null || !ThemeParam.KEY_PATTERN.matcher(p.getKey()).matches()) {
|
||||
throw new IllegalArgumentException("param key 非法:" + p.getKey());
|
||||
}
|
||||
if (seen.contains(p.getKey())) {
|
||||
throw new IllegalArgumentException("param key 重复:" + p.getKey());
|
||||
}
|
||||
seen.add(p.getKey());
|
||||
String type = p.getType();
|
||||
boolean knownType = ThemeParam.TYPE_COLOR.equals(type) || ThemeParam.TYPE_IMAGE.equals(type)
|
||||
|| ThemeParam.TYPE_SELECT.equals(type) || ThemeParam.TYPE_TEXT.equals(type);
|
||||
if (!knownType) {
|
||||
throw new IllegalArgumentException("param " + p.getKey() + " 类型非法:" + type);
|
||||
}
|
||||
if (p.getCssVar() != null && !p.getCssVar().isEmpty() && !ThemeParam.TYPE_COLOR.equals(type)) {
|
||||
throw new IllegalArgumentException("cssVar 仅允许 color 类型参数:" + p.getKey());
|
||||
}
|
||||
if (ThemeParam.TYPE_SELECT.equals(type)
|
||||
&& (p.getOptions() == null || p.getOptions().isEmpty())) {
|
||||
throw new IllegalArgumentException("select 参数缺 options:" + p.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 资源定位 =====
|
||||
|
||||
private List<Resource> scanResources() {
|
||||
try {
|
||||
Resource[] resources = new PathMatchingResourcePatternResolver().getResources(SCAN_PATTERN);
|
||||
return Arrays.asList(resources);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("主题包扫描失败:" + SCAN_PATTERN, e);
|
||||
}
|
||||
}
|
||||
|
||||
/** 从 theme.json 资源 URL 截取所属包目录名 */
|
||||
private String dirNameOf(Resource resource) {
|
||||
try {
|
||||
String url = resource.getURL().toString().replace('\\', '/');
|
||||
int root = url.indexOf("templates/themes/");
|
||||
if (root < 0) {
|
||||
return url;
|
||||
}
|
||||
String rest = url.substring(root + "templates/themes/".length());
|
||||
return rest.contains("/") ? rest.substring(0, rest.indexOf('/')) : rest;
|
||||
} catch (IOException e) {
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.yunhai.cms.theme;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* themeVarsCss 构建器(方案 §5.3,对应评审 R4):
|
||||
* 服务端预构建 :root{...} 覆盖串,只拼通过 color 正则校验的声明值——
|
||||
* 模板仅做 th:utext 输出,安全性由"服务端只拼校验过的值"保证(可单测)。
|
||||
*/
|
||||
public final class ThemeVarsCss {
|
||||
|
||||
private ThemeVarsCss() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 按主题 schema 将参数值聚合为 CSS 变量声明串,形如
|
||||
* {@code :root{--primary:#b01a2e;--bg:#f7f5f2;}};无有效声明返回空串。
|
||||
* 输入应为已按 schema 过滤的合法值({@link ThemeInfo#filterValidValues})。
|
||||
*/
|
||||
public static String build(ThemeInfo theme, Map<String, String> params) {
|
||||
if (theme == null || params == null || params.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder sb = new StringBuilder(":root{");
|
||||
for (ThemeParam p : theme.getParams()) {
|
||||
if (!p.isCssVarParam()) {
|
||||
continue;
|
||||
}
|
||||
String value = params.get(p.getKey());
|
||||
// 双重校验(方案 §9 注入面):入口已过滤,此处仍只拼通过 color 正则的值
|
||||
if (value == null || !p.isValidValue(value)) {
|
||||
continue;
|
||||
}
|
||||
sb.append(p.getCssVar()).append(':').append(value).append(';');
|
||||
}
|
||||
return sb.length() == 6 ? "" : sb.append('}').toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.yunhai.cms.utils;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* JSON 扩展列(cms_site.config_json / cms_article.ext_json)解析工具。
|
||||
* 解析失败按空 Map 处理(扩展列不允许影响主流程)。
|
||||
* 保留键见方案 §5.2:site 侧 domain/public_base_url/wechat;article 侧 wechat/albums。
|
||||
*/
|
||||
public final class ExtJsonUtils {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private ExtJsonUtils() {
|
||||
}
|
||||
|
||||
public static Map<String, Object> parse(String json) {
|
||||
if (json == null || json.trim().isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
try {
|
||||
Map<String, Object> map = MAPPER.readValue(json, new TypeReference<LinkedHashMap<String, Object>>() { });
|
||||
return map == null ? Collections.emptyMap() : map;
|
||||
} catch (Exception e) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
}
|
||||
|
||||
public static String getString(Map<String, Object> map, String key) {
|
||||
Object value = map == null ? null : map.get(key);
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.yunhai.cms.utils;
|
||||
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.safety.Safelist;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 富文本白名单清洗(方案 §8.5 内容安全):wangEditor 产出的正文 HTML 入库前执行。
|
||||
*
|
||||
* <p>策略:jsoup Safelist.relaxed() 为基础,补 figure/figcaption(编辑器图片段落)、
|
||||
* 全局受限 style(仅排版类属性白名单),a/img 协议收紧;script/iframe/on* 一律剥除。
|
||||
* 列表页等纯文本字段由 Thymeleaf th:text 转义输出,th:utext 仅限本工具清洗过的内容。
|
||||
*/
|
||||
public final class HtmlSanitizer {
|
||||
|
||||
/** 允许保留的内联样式属性(排版用途),其余 style 值丢弃 */
|
||||
private static final Pattern SAFE_STYLE =
|
||||
Pattern.compile("^(\\s*(text-align|color|background-color|font-size|font-weight"
|
||||
+ "|line-height|width|height|max-width|float|margin|padding)\\s*:\\s*[^;()]+;?)*\\s*$",
|
||||
Pattern.CASE_INSENSITIVE);
|
||||
|
||||
private static final Safelist WHITELIST = Safelist.relaxed()
|
||||
.addTags("figure", "figcaption", "span")
|
||||
.addAttributes(":all", "style")
|
||||
.addAttributes("img", "style", "alt", "width", "height")
|
||||
.addProtocols("a", "href", "http", "https", "mailto", "ftp", "#")
|
||||
.addProtocols("img", "src", "http", "https", "data")
|
||||
// 相对链接保留(day3 验收 B-9 根因修复):上传地址约定相对路径入库(B-1,
|
||||
// FILE_WEB_PATH=/cms/upload/**),编辑器贴图的 img src 即相对 URL;jsoup 默认
|
||||
// preserveRelativeLinks=false 时相对 src/href 无法解析协议 → 整个属性被剥除,
|
||||
// 保存后贴图全部断图。开启后相对 URL 原样放行(不参与协议校验),
|
||||
// 绝对 URL 仍受上方协议白名单约束。
|
||||
.preserveRelativeLinks(true);
|
||||
|
||||
private HtmlSanitizer() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 清洗富文本;空入参原样返回。
|
||||
*
|
||||
* <p>baseUri 用占位 https 域(B-9 根因修复配套):jsoup 对带协议白名单的属性先做
|
||||
* absUrl 解析再校验协议,空 baseUri 下相对 URL 解析必失败 → 属性整体剥除(编辑器
|
||||
* 贴图保存后断图)。给占位 base 后相对 URL 解析为 https 形态通过校验,再由
|
||||
* preserveRelativeLinks(true) 回写原始相对值——绝对 URL 的协议白名单约束不变。
|
||||
*/
|
||||
public static String clean(String html) {
|
||||
if (html == null || html.isEmpty()) {
|
||||
return html;
|
||||
}
|
||||
String cleaned = Jsoup.clean(html, "https://sanitizer.base.invalid/", WHITELIST);
|
||||
return stripUnsafeStyle(cleaned);
|
||||
}
|
||||
|
||||
/**
|
||||
* 纯文本提取(摘要兜底、搜索片段用):去标签 + 折叠空白。
|
||||
*/
|
||||
public static String toText(String html, int maxLength) {
|
||||
if (html == null || html.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
String text = Jsoup.parse(html).text().replaceAll("\\s+", " ").trim();
|
||||
if (maxLength > 0 && text.length() > maxLength) {
|
||||
return text.substring(0, maxLength);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* jsoup 原生不支持按值过滤属性,二次遍历按 SAFE_STYLE 白名单过滤 style:
|
||||
* 不匹配白名单的 style 整个属性丢弃(A-07 修复——原先只删含 url()/expression 的,
|
||||
* 与类注释"其余 style 值丢弃"不符);jsoup 清洗阶段已保证 style 值不含引号逃逸。
|
||||
*/
|
||||
private static String stripUnsafeStyle(String html) {
|
||||
org.jsoup.nodes.Document doc = org.jsoup.Jsoup.parseBodyFragment(html);
|
||||
for (org.jsoup.nodes.Element el : doc.select("[style]")) {
|
||||
String style = el.attr("style");
|
||||
if (style == null || !SAFE_STYLE.matcher(style).matches()) {
|
||||
el.removeAttr("style");
|
||||
}
|
||||
}
|
||||
return doc.body().html();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package com.yunhai.cms.utils;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 门户 URL 生成器(方案 §8.6 前置约定2):所有链接、主题资产、canonical 统一经此生成,
|
||||
* 禁止模板硬编码绝对地址——base 域子路径与学校独立域名两种暴露形态共用同一套渲染。
|
||||
*
|
||||
* <p>基准 = 站点 config_json.public_base_url(绑学校域名后为学校域),
|
||||
* 未配置时从当前请求派生(预览/平台内跳转形态)。
|
||||
*/
|
||||
public class PortalUrlHelper {
|
||||
|
||||
/** 正文/单页内容里出现的上传资源地址:可选历史绝对前缀 + 相对路径(B-1 渲染期统一补基准) */
|
||||
private static final Pattern UPLOAD_URL_IN_CONTENT =
|
||||
Pattern.compile("(?:https?://[^/\\s\"']+)?((?:/cms)?/upload/[^\\s\"']+)");
|
||||
|
||||
/** 不带尾斜杠的门户基地址,形如 {scheme}://{host}{context}/portal/{siteCode} 或 https://www.xxx.edu.cn */
|
||||
private final String baseUrl;
|
||||
|
||||
private final String siteCode;
|
||||
|
||||
/** 当前皮肤包名:进入资产 URL(B-3,换肤即换 URL 使浏览器/CDN 缓存天然失效) */
|
||||
private final String theme;
|
||||
|
||||
/**
|
||||
* base 域对外基地址(cms.portal.base-origin,含 context-path,如 https://base.yunhaixingtong.com/cms)。
|
||||
* C-6:站点未配 public_base_url 时的规范派生基准;B-4:siteHome 无段形态退化目标。空 = 未配置。
|
||||
*/
|
||||
private final String baseOrigin;
|
||||
|
||||
/** 预览模式资产前缀(非 null 时 asset() 改走管理端代理,方案 §5.5 防资产串包) */
|
||||
private final String assetProxyPrefix;
|
||||
|
||||
public PortalUrlHelper(String baseUrl, String siteCode, String theme) {
|
||||
this(baseUrl, siteCode, theme, null, null);
|
||||
}
|
||||
|
||||
public PortalUrlHelper(String baseUrl, String siteCode, String theme, String baseOrigin) {
|
||||
this(baseUrl, siteCode, theme, baseOrigin, null);
|
||||
}
|
||||
|
||||
private PortalUrlHelper(String baseUrl, String siteCode, String theme, String baseOrigin,
|
||||
String assetProxyPrefix) {
|
||||
this.baseUrl = trimTail(baseUrl);
|
||||
this.siteCode = siteCode;
|
||||
this.theme = theme;
|
||||
this.baseOrigin = trimTail(baseOrigin);
|
||||
this.assetProxyPrefix = assetProxyPrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* 预览模式工厂(方案 §5.5):资产 URL 指向管理端主题资产代理 /api/theme/{theme}/asset/**,
|
||||
* 其余站内链接仍指向真实门户(点击回真实门户是已接受的预览局限)。
|
||||
*/
|
||||
public static PortalUrlHelper forPreview(HttpServletRequest request, String siteCode, String theme) {
|
||||
PortalUrlHelper base = fromRequest(request, siteCode, theme);
|
||||
// 显式走 5 参构造:第 4 参是 base-origin,代理前缀必须落第 5 参(避免误绑 4 参重载)
|
||||
return new PortalUrlHelper(base.baseUrl, siteCode, theme, null, "/api/theme/" + theme + "/asset/");
|
||||
}
|
||||
|
||||
/**
|
||||
* 从当前请求派生门户基地址(public_base_url / base-origin 均未配置时的兜底;
|
||||
* 反代形态经 ForwardedHeaderFilter 修正后的 scheme/host/port 已反映在请求上,B-2)。
|
||||
*/
|
||||
public static PortalUrlHelper fromRequest(HttpServletRequest request, String siteCode, String theme) {
|
||||
String scheme = request.getScheme();
|
||||
String host = request.getServerName();
|
||||
int port = request.getServerPort();
|
||||
String context = request.getContextPath();
|
||||
StringBuilder sb = new StringBuilder(scheme).append("://").append(host);
|
||||
boolean defaultPort = "http".equals(scheme) && port == 80 || "https".equals(scheme) && port == 443;
|
||||
if (!defaultPort) {
|
||||
sb.append(':').append(port);
|
||||
}
|
||||
sb.append(context).append("/portal/").append(siteCode);
|
||||
return new PortalUrlHelper(sb.toString(), siteCode, theme);
|
||||
}
|
||||
|
||||
/**
|
||||
* base 域规范形态工厂(C-6):站点未配 public_base_url 且平台配了 cms.portal.base-origin 时,
|
||||
* 以 base 域规范路径为基准(base-origin + /portal/{siteCode}),不随访问 host 漂移——
|
||||
* 方案 §8.6「默认派生 https://base.yunhaixingtong.com/cms/portal/{code}」的落地。
|
||||
*/
|
||||
public static PortalUrlHelper fromBaseOrigin(String baseOrigin, String siteCode, String theme) {
|
||||
return new PortalUrlHelper(trimTail(baseOrigin) + "/portal/" + siteCode, siteCode, theme, baseOrigin);
|
||||
}
|
||||
|
||||
/** 首页 */
|
||||
public String home() {
|
||||
return baseUrl + "/";
|
||||
}
|
||||
|
||||
/**
|
||||
* 其他站点首页("专业院系"下拉用,《院系子站方案》):目标站配置了 public_base_url 时以它为准;
|
||||
* 否则把当前基准里的站点段替换为目标站点(base 域子路径形态);
|
||||
* 学校域形态(当前基准无 /portal/ 段)时退化为 base 域规范路径(B-4,base-origin 未配置才回 "/")。
|
||||
*/
|
||||
public String siteHome(String targetCode, String targetPublicBaseUrl) {
|
||||
if (targetPublicBaseUrl != null && !targetPublicBaseUrl.trim().isEmpty()) {
|
||||
return trimTail(targetPublicBaseUrl) + "/";
|
||||
}
|
||||
int idx = baseUrl.lastIndexOf("/portal/");
|
||||
if (idx >= 0) {
|
||||
return baseUrl.substring(0, idx + "/portal/".length()) + targetCode + "/";
|
||||
}
|
||||
if (baseOrigin != null && !baseOrigin.isEmpty()) {
|
||||
return baseOrigin + "/portal/" + targetCode + "/";
|
||||
}
|
||||
return "/";
|
||||
}
|
||||
|
||||
/** 栏目列表/单页(type=3 外链不在此渲染,直接取 linkUrl) */
|
||||
public String category(Object categoryId) {
|
||||
return baseUrl + "/c/" + categoryId;
|
||||
}
|
||||
|
||||
/** 文章详情 */
|
||||
public String article(Object articleId) {
|
||||
return baseUrl + "/a/" + articleId;
|
||||
}
|
||||
|
||||
/** 站内搜索 */
|
||||
public String search(String q, Integer page) {
|
||||
String url = baseUrl + "/search?q=" + urlEncode(q == null ? "" : q);
|
||||
return page != null && page > 1 ? url + "&page=" + page : url;
|
||||
}
|
||||
|
||||
/**
|
||||
* 主题资产(css/图片):常规经 PortalAssetController 按站点皮肤解析;预览模式走管理端代理。
|
||||
* URL 含主题段(B-3):换肤即换 URL,浏览器/CDN 的 max-age 缓存天然失效。
|
||||
*/
|
||||
public String asset(String path) {
|
||||
if (assetProxyPrefix != null) {
|
||||
return assetProxyPrefix + trimLead(path);
|
||||
}
|
||||
String themeSeg = theme == null || theme.isEmpty() ? "default" : theme;
|
||||
return baseUrl + "/assets/" + themeSeg + "/" + trimLead(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传资源地址补基准(B-1):入库的 webUrl 一律为相对路径(FILE_WEB_PATH 相对形态),
|
||||
* 渲染时按当前基准补 origin 成完整 URL——base 域/学校域/任意外部域访问不断图。
|
||||
* 已是完整 http(s) 地址(外链图片等)原样返回;空值原样返回。
|
||||
*/
|
||||
public String upload(String storedUrl) {
|
||||
if (storedUrl == null || storedUrl.trim().isEmpty()) {
|
||||
return storedUrl;
|
||||
}
|
||||
String s = storedUrl.trim();
|
||||
if (s.startsWith("http://") || s.startsWith("https://")) {
|
||||
return s;
|
||||
}
|
||||
return originOf(baseUrl) + (s.startsWith("/") ? s : "/" + s);
|
||||
}
|
||||
|
||||
/**
|
||||
* 富文本内容后处理(B-1):把正文里历史绝对前缀(http://localhost:8072 等)
|
||||
* 与相对形态的上传地址统一重写为当前基准下的完整 URL。外链图片不受影响。
|
||||
*/
|
||||
public String rewriteUploadUrls(String html) {
|
||||
if (html == null || html.isEmpty()) {
|
||||
return html;
|
||||
}
|
||||
Matcher matcher = UPLOAD_URL_IN_CONTENT.matcher(html);
|
||||
StringBuffer sb = new StringBuffer(html.length());
|
||||
while (matcher.find()) {
|
||||
matcher.appendReplacement(sb, Matcher.quoteReplacement(upload(matcher.group(1))));
|
||||
}
|
||||
matcher.appendTail(sb);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public String getSiteCode() {
|
||||
return siteCode;
|
||||
}
|
||||
|
||||
public String getBaseUrl() {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
/** 从基地址截取 scheme://host[:port](去掉 /portal 段及任何路径),upload() 补基准用 */
|
||||
private static String originOf(String baseUrl) {
|
||||
if (baseUrl == null) {
|
||||
return "";
|
||||
}
|
||||
int schemeEnd = baseUrl.indexOf("://");
|
||||
if (schemeEnd < 0) {
|
||||
return "";
|
||||
}
|
||||
int pathStart = baseUrl.indexOf('/', schemeEnd + 3);
|
||||
return pathStart < 0 ? baseUrl : baseUrl.substring(0, pathStart);
|
||||
}
|
||||
|
||||
private static String trimTail(String url) {
|
||||
String s = url == null ? "" : url.trim();
|
||||
while (s.endsWith("/")) {
|
||||
s = s.substring(0, s.length() - 1);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
private static String trimLead(String path) {
|
||||
String s = path == null ? "" : path;
|
||||
while (s.startsWith("/")) {
|
||||
s = s.substring(1);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
private static String urlEncode(String value) {
|
||||
try {
|
||||
return java.net.URLEncoder.encode(value, "UTF-8");
|
||||
} catch (java.io.UnsupportedEncodingException e) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
server:
|
||||
port: 8072
|
||||
servlet:
|
||||
context-path: /cms
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: cms
|
||||
datasource:
|
||||
url: jdbc:mysql://localhost:3306/bsch_cms?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
|
||||
username: root
|
||||
password: 123456
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: update
|
||||
show-sql: false
|
||||
open-in-view: false
|
||||
properties:
|
||||
hibernate:
|
||||
jdbc:
|
||||
time_zone: Asia/Shanghai
|
||||
jackson:
|
||||
# 管理端 JSON 时间格式(前端 DatePicker 对齐 yyyy-MM-dd HH:mm:ss)
|
||||
date-format: yyyy-MM-dd HH:mm:ss
|
||||
time-zone: Asia/Shanghai
|
||||
# ===== 门户 SSR =====
|
||||
thymeleaf:
|
||||
cache: false # 本地改模板热生效;生产注入覆盖为 true(方案 §6.2)
|
||||
prefix: classpath:/templates/
|
||||
suffix: .html
|
||||
encoding: UTF-8
|
||||
servlet:
|
||||
multipart:
|
||||
max-file-size: 100MB
|
||||
max-request-size: 100MB
|
||||
# 1-2 校规模:Caffeine 本地缓存(对齐缓存决策「单实例部署」结论)
|
||||
cache:
|
||||
type: caffeine
|
||||
caffeine:
|
||||
spec: maximumSize=10000,expireAfterWrite=5m
|
||||
|
||||
# ===== 基础平台 yh 配置(UserHome 同款三件套)=====
|
||||
yh:
|
||||
auth:
|
||||
enabled: true
|
||||
sso:
|
||||
server-url-prefix: http://sso.yunhaixingtong.com
|
||||
# 本地 dev 必须指向前端 dev server(8073):CAS 验票回跳走 vite 代理,
|
||||
# 配合前端代理的 cookiePathRewrite 才能让 JSESSIONID(path=/cms) 进入 /api 请求;
|
||||
# 指回 8072 会导致 8073 页面会话死循环。生产由 projman 注入覆盖,不受此值影响。
|
||||
client-host-url: http://localhost:8073
|
||||
allow-headers: all
|
||||
allow-origins: all
|
||||
# ⚠️ 只拦管理端 API;门户 /portal/** 必须匿名可访问(SEO/首屏刚需),勿放进 pattern
|
||||
url-pattern: /api/*
|
||||
mobi-api-pattern: /mobiapi/*
|
||||
app-auth:
|
||||
enabled: true
|
||||
# UserBase 注册后分配(进白名单),与 yh.open 保持一致;生产由 projman 注入
|
||||
app-key: 100005
|
||||
app-secret: 2c7885de594742cc840b8762910b2d2e
|
||||
open:
|
||||
enabled: true
|
||||
base-host: http://base.yunhaixingtong.com
|
||||
base-path: /userbase
|
||||
app-key: 100005
|
||||
app-secret: 2c7885de594742cc840b8762910b2d2e
|
||||
|
||||
# ===== CMS 专属配置 =====
|
||||
cms:
|
||||
# 超管判定:BoaUser.type == 1(UserBase sys_user.type=1 平台约定,无注入配置);
|
||||
# 校级权限按 currentRole.schId → site.sch_id 校验(方案 §7.2)
|
||||
portal:
|
||||
# 详情页浏览器缓存(秒),配合后端 5 分钟数据缓存(方案 §8.3)
|
||||
detail-max-age: 300
|
||||
# base 域对外基地址(C-6,方案 §8.6「未配 public_base_url 默认派生 base 域规范路径」的固化配置):
|
||||
# 含 context-path,如 https://base.yunhaixingtong.com/cms;生产由 projman 注入。
|
||||
# 为空(本地开发默认)时按当前请求派生(反代下经 ForwardedHeaderFilter 修正 scheme/port,B-2)。
|
||||
base-origin: ""
|
||||
|
||||
logging:
|
||||
level:
|
||||
com.yunhai.cms: debug
|
||||
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
exposure:
|
||||
include: health
|
||||
endpoint:
|
||||
health:
|
||||
show-details: never
|
||||
|
||||
# 文件上传(同 UserHome 双 key 约定,方案 §7.3)
|
||||
# FILE_WEB_PATH 只接受相对路径(默认 /cms/upload/,含 context-path)或公网可达绝对地址;
|
||||
# 禁止填 localhost/内网绝对地址——webUrl 入库后非本机访问全部断图(B-1/C-5)。
|
||||
# 门户渲染侧由 PortalUrlHelper.upload() 按访问基准补全为完整 URL。
|
||||
FILE_PATH: D:/bsch/cms/upload/
|
||||
FILE_WEB_PATH: /cms/upload/
|
||||
@@ -0,0 +1,149 @@
|
||||
-- ============================================================
|
||||
-- bsch_cms 初始化脚本
|
||||
-- 约定:JPA ddl-auto=update 自动建表;本脚本用于生产显式初始化/评审参考
|
||||
-- 多租户:site 表挂 sch_id(逻辑外键 → UserBase sys_group.id),文章只挂 site_id,
|
||||
-- 编辑权限经 currentRole.schId → site.sch_id 映射校验
|
||||
-- ============================================================
|
||||
|
||||
-- 1. 站点表(多租户根;一校一主站 + N 院系子站,见《院系子站方案.md》)
|
||||
CREATE TABLE IF NOT EXISTS `cms_site` (
|
||||
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`code` VARCHAR(64) NOT NULL COMMENT '站点编码,URL 路径用(/portal/{code})',
|
||||
`parent_site_id` INT NOT NULL DEFAULT 0 COMMENT '上级站点ID(0=顶层校站点;院系子站挂主站 id,层级固定两层)',
|
||||
`sch_id` INT NULL COMMENT '学校ID(逻辑外键 → UserBase sys_group.id)',
|
||||
`sch_name` VARCHAR(128) NULL COMMENT '学校名称(冗余展示)',
|
||||
`name` VARCHAR(128) NOT NULL COMMENT '站点名称',
|
||||
`theme` VARCHAR(64) NULL DEFAULT 'default' COMMENT '皮肤包名(classpath:/templates/themes/{theme}/)',
|
||||
`config_json` JSON NULL COMMENT '站点配置(logo/联系方式/页脚等;预留 wechat 节点)',
|
||||
`status` TINYINT NOT NULL DEFAULT 1 COMMENT '状态:0=停用 1=启用',
|
||||
`create_by` VARCHAR(64) NULL COMMENT '创建人账号',
|
||||
`create_time` DATETIME NULL,
|
||||
`update_by` VARCHAR(64) NULL,
|
||||
`update_time` DATETIME NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_site_code` (`code`),
|
||||
KEY `idx_site_sch` (`sch_id`),
|
||||
KEY `idx_site_parent` (`parent_site_id`)
|
||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = 'CMS 站点(一校一主站 + N 院系子站)';
|
||||
|
||||
-- 2. 栏目表(站点内树形)
|
||||
CREATE TABLE IF NOT EXISTS `cms_category` (
|
||||
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`site_id` INT NOT NULL COMMENT '所属站点(逻辑外键 → cms_site.id)',
|
||||
`parent_id` INT NOT NULL DEFAULT 0 COMMENT '父栏目ID(0=根)',
|
||||
`name` VARCHAR(64) NOT NULL COMMENT '栏目名称',
|
||||
`type` TINYINT NOT NULL DEFAULT 1 COMMENT '栏目类型:1=文章列表 2=单页 3=外链',
|
||||
`link_url` VARCHAR(500) NULL COMMENT '外链地址(type=3 必填)',
|
||||
`template` VARCHAR(64) NULL COMMENT '栏目模板覆盖(空=按 type 取默认)',
|
||||
`content` LONGTEXT NULL COMMENT '单页栏目内容(type=2 时门户直接渲染;方案 §8.1 要求,§5.1 原稿漏列此处补齐)',
|
||||
`sort_no` INT NOT NULL DEFAULT 0 COMMENT '同级排序(升序)',
|
||||
`seo_title` VARCHAR(200) NULL COMMENT 'SEO 标题(空=用栏目名)',
|
||||
`seo_description` VARCHAR(500) NULL COMMENT 'SEO 描述',
|
||||
`status` TINYINT NOT NULL DEFAULT 1 COMMENT '0=隐藏 1=显示',
|
||||
`create_by` VARCHAR(64) NULL,
|
||||
`create_time` DATETIME NULL,
|
||||
`update_by` VARCHAR(64) NULL,
|
||||
`update_time` DATETIME NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_cat_tree` (`site_id`, `parent_id`, `sort_no`)
|
||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = 'CMS 栏目(树形)';
|
||||
|
||||
-- 3. 文章表
|
||||
CREATE TABLE IF NOT EXISTS `cms_article` (
|
||||
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`site_id` INT NOT NULL COMMENT '所属站点(隔离/查询维度)',
|
||||
`category_id` INT NOT NULL COMMENT '所属栏目(逻辑外键 → cms_category.id)',
|
||||
`title` VARCHAR(200) NOT NULL COMMENT '标题',
|
||||
`summary` VARCHAR(500) NULL COMMENT '摘要(列表/SEO 用,空=截取正文)',
|
||||
`content` LONGTEXT NULL COMMENT '正文 HTML(wangEditor 产出,保存时 jsoup 白名单清洗)',
|
||||
`cover_image` VARCHAR(500) NULL COMMENT '封面图 URL',
|
||||
`author_account` VARCHAR(64) NULL COMMENT '作者账号(发布时从 BoaUser 填充)',
|
||||
`author_name` VARCHAR(64) NULL COMMENT '作者姓名(冗余展示)',
|
||||
`source` VARCHAR(128) NULL COMMENT '来源(转载出处)',
|
||||
`status` TINYINT NOT NULL DEFAULT 0 COMMENT '状态:0=草稿 1=已发布 2=已下架',
|
||||
`topmost` TINYINT NOT NULL DEFAULT 0 COMMENT '置顶:0/1',
|
||||
`publish_time` DATETIME NULL COMMENT '发布时间(空=保存即发布;未来=定时发布)',
|
||||
`offline_time` DATETIME NULL COMMENT '下架时间(可选)',
|
||||
`view_count` INT NOT NULL DEFAULT 0 COMMENT '浏览量(MVP 异步累加)',
|
||||
`ext_json` JSON NULL COMMENT '扩展字段(保留键:wechat=推送回执预留、albums=图集演进)',
|
||||
`create_by` VARCHAR(64) NULL,
|
||||
`create_time` DATETIME NULL,
|
||||
`update_by` VARCHAR(64) NULL,
|
||||
`update_time` DATETIME NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_art_list` (`site_id`, `category_id`, `status`, `publish_time`),
|
||||
KEY `idx_art_site_top` (`site_id`, `status`, `topmost`)
|
||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = 'CMS 文章';
|
||||
|
||||
-- 4. 附件表(正文图片 + 文档附件)
|
||||
CREATE TABLE IF NOT EXISTS `cms_attachment` (
|
||||
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`site_id` INT NOT NULL COMMENT '所属站点',
|
||||
`article_id` INT NULL COMMENT '关联文章(编辑器图片保存时回填)',
|
||||
`file_name` VARCHAR(255) NOT NULL COMMENT '原始文件名',
|
||||
`file_path` VARCHAR(500) NOT NULL COMMENT '存储路径(相对 FILE_PATH)',
|
||||
`web_url` VARCHAR(500) NOT NULL COMMENT 'Web 访问 URL',
|
||||
`file_size` BIGINT NULL COMMENT '字节数',
|
||||
`mime_type` VARCHAR(128) NULL COMMENT 'MIME 类型',
|
||||
`create_by` VARCHAR(64) NULL,
|
||||
`create_time` DATETIME NULL,
|
||||
`update_by` VARCHAR(64) NULL,
|
||||
`update_time` DATETIME NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_att_article` (`article_id`),
|
||||
KEY `idx_att_site` (`site_id`)
|
||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = 'CMS 附件';
|
||||
|
||||
-- 5. 轮播/推荐位表(首页 banner、图片新闻位等)
|
||||
CREATE TABLE IF NOT EXISTS `cms_banner` (
|
||||
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`site_id` INT NOT NULL COMMENT '所属站点',
|
||||
`position` VARCHAR(32) NOT NULL DEFAULT 'home' COMMENT '展示位标识(home=首页轮播;皮肤包约定其他位)',
|
||||
`title` VARCHAR(200) NOT NULL COMMENT '标题(alt 文案/无图兜底)',
|
||||
`image_url` VARCHAR(500) NOT NULL COMMENT '图片 URL(上传至 FILE_PATH)',
|
||||
`link_type` TINYINT NOT NULL DEFAULT 1 COMMENT '跳转类型:1=文章 2=栏目 3=外链',
|
||||
`link_value` VARCHAR(500) NULL COMMENT '跳转目标(文章ID/栏目ID/URL,按 link_type 解释)',
|
||||
`sort_no` INT NOT NULL DEFAULT 0 COMMENT '同级排序(升序)',
|
||||
`start_time` DATETIME NULL COMMENT '上线时间(空=立即;未来=定时上线)',
|
||||
`end_time` DATETIME NULL COMMENT '下线时间(可选,门户渲染时过滤)',
|
||||
`status` TINYINT NOT NULL DEFAULT 1 COMMENT '状态:0=停用 1=启用',
|
||||
`create_by` VARCHAR(64) NULL,
|
||||
`create_time` DATETIME NULL,
|
||||
`update_by` VARCHAR(64) NULL,
|
||||
`update_time` DATETIME NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_banner` (`site_id`, `position`, `status`, `sort_no`)
|
||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = 'CMS 轮播/推荐位';
|
||||
|
||||
-- 6. 友情链接表(页脚/首页分组成员)
|
||||
CREATE TABLE IF NOT EXISTS `cms_link` (
|
||||
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`site_id` INT NOT NULL COMMENT '所属站点',
|
||||
`group_name` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '分组(上级部门/兄弟院校/合作单位…)',
|
||||
`name` VARCHAR(128) NOT NULL COMMENT '链接名称',
|
||||
`logo_url` VARCHAR(500) NULL COMMENT 'Logo URL(可选,文字链可空)',
|
||||
`link_url` VARCHAR(500) NOT NULL COMMENT '链接地址',
|
||||
`sort_no` INT NOT NULL DEFAULT 0 COMMENT '组内排序(升序)',
|
||||
`status` TINYINT NOT NULL DEFAULT 1 COMMENT '0=隐藏 1=显示',
|
||||
`create_by` VARCHAR(64) NULL,
|
||||
`create_time` DATETIME NULL,
|
||||
`update_by` VARCHAR(64) NULL,
|
||||
`update_time` DATETIME NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_link` (`site_id`, `group_name`, `sort_no`)
|
||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = 'CMS 友情链接';
|
||||
|
||||
-- ============================================================
|
||||
-- 示例数据(联调首屏用,按需执行)
|
||||
-- ============================================================
|
||||
-- INSERT INTO cms_site (code, sch_id, sch_name, name, theme)
|
||||
-- VALUES ('demo', 1, 'XX学校', 'XX学校门户网站', 'default');
|
||||
--
|
||||
-- INSERT INTO cms_category (site_id, parent_id, name, type, sort_no)
|
||||
-- VALUES (1, 0, '新闻中心', 1, 1), (1, 0, '通知公告', 1, 2), (1, 0, '学校简介', 2, 3);
|
||||
--
|
||||
-- INSERT INTO cms_banner (site_id, position, title, image_url, link_type, sort_no)
|
||||
-- VALUES (1, 'home', '欢迎访问XX学校', '/upload/cms/demo/202609/example.jpg', 3, 1);
|
||||
--
|
||||
-- INSERT INTO cms_link (site_id, group_name, name, link_url, sort_no)
|
||||
-- VALUES (1, '上级部门', '教育部', 'http://www.moe.gov.cn', 1);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user