Compare commits

...
11 Commits
Author SHA1 Message Date
ops 70cfc3d62e fix(ci): 构建容器名唯一化 + npm 走国内镜像源(避免并发互踩 exit 137) 2026-10-21 06:24:26 +00:00
ops e7fc38e3a7 ci: apk 源统一走 aliyun(规避 dl-cdn 时段性被拦卡 60s) 2026-10-21 01:36:57 +00:00
wanghu e93149b534 附件
build / build-push (push) Successful in 52s
2026-09-21 17:25:25 +08:00
wanghu e15e272111 附件
build / build-push (push) Failing after 1m23s
2026-09-21 17:00:23 +08:00
wanghu 2d186a1ca9 附件
build / build-push (push) Failing after 59s
2026-09-21 16:52:57 +08:00
wanghu 69e628fc28 统计时间修改
build / build-push (push) Successful in 54s
2026-09-20 16:37:21 +08:00
wanghu 246462d7b0 宿舍逻辑修改
build / build-push (push) Successful in 57s
2026-09-20 15:11:08 +08:00
wanghu 40bc49a46e 宿舍逻辑修改
build / build-push (push) Successful in 54s
2026-09-20 14:13:42 +08:00
wanghu c70d3e68c2 空格
build / build-push (push) Successful in 34s
2026-09-20 11:46:00 +08:00
wanghu 743f7fec43 修改userid
build / build-push (push) Successful in 1m27s
2026-09-20 10:56:41 +08:00
wanghu 6433ccea2d sys_dict 添加学校id 有关也业务逻辑也许补上 2026-09-20 10:15:37 +08:00
15 changed files with 291 additions and 234 deletions
+18 -9
View File
@@ -25,7 +25,10 @@ jobs:
options: --network infra-infra-net
steps:
- name: 安装 git / curl(alpine)
run: apk add --no-cache git curl
run: |
# 统一走 aliyun 源:dl-cdn 时段性被拦会卡满 60s×2(2026-10-20 事故)
sed -i 's#dl-cdn.alpinelinux.org#mirrors.aliyun.com#g' /etc/apk/repositories
apk add --no-cache git curl
# 内网 Gitea 无法访问 GitHub 拉 actions/checkout,手动 clone 本仓库
- name: 拉取源码(内网无 GitHub,手动 clone 本仓库)
@@ -55,18 +58,24 @@ jobs:
- name: 构建 jar(maven 容器,复用宿主 m2 缓存)
run: |
set -e
docker rm -f mavenbuild 2>/dev/null || true
docker run -d --name mavenbuild \
# 构建容器名必须全局唯一:runner 挂的是宿主 docker.sock,容器名在整个 daemon 上共享
# 命名空间。固定名会在多仓/多条 workflow 并发时互相 docker rm -f 掉对方正在构建的
# 容器,表现为无编译报错的 exit 137(SIGKILL,2026-10-21 实测复现)。
# GITHUB_RUN_ID 实例级唯一,再拼时间戳兜底。
BUILD_CONTAINER="mavenbuild-${GITHUB_RUN_ID:-0}-$(date +%s)"
echo "BUILD_CONTAINER=${BUILD_CONTAINER}"
docker rm -f "$BUILD_CONTAINER" 2>/dev/null || true
docker run -d --name "$BUILD_CONTAINER" \
--network infra-infra-net \
-v /opt/docker/projman-m2:/root/.m2 \
-w /build maven:3.6.3-jdk-8 sleep 3600
docker cp "${PWD}/." mavenbuild:/build/
docker exec mavenbuild sh -c "printf '%s' '<settings><profiles><profile><id>nexus-repo</id><repositories><repository><id>nexus-internal</id><url>http://nexus:8081/repository/maven-public/</url><releases><enabled>true</enabled></releases><snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots></repository></repositories></profile></profiles><activeProfiles><activeProfile>nexus-repo</activeProfile></activeProfiles></settings>' > /root/.m2/settings.xml"
docker exec mavenbuild sh -c 'cd /build && mvn -B -DskipTests clean package'
docker exec mavenbuild sh -c 'cd /build/target && cp *.jar app.jar'
docker cp "${PWD}/." "$BUILD_CONTAINER":/build/
docker exec "$BUILD_CONTAINER" sh -c "printf '%s' '<settings><profiles><profile><id>nexus-repo</id><repositories><repository><id>nexus-internal</id><url>http://nexus:8081/repository/maven-public/</url><releases><enabled>true</enabled></releases><snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots></repository></repositories></profile></profiles><activeProfiles><activeProfile>nexus-repo</activeProfile></activeProfiles></settings>' > /root/.m2/settings.xml"
docker exec "$BUILD_CONTAINER" sh -c 'cd /build && mvn -B -DskipTests clean package'
docker exec "$BUILD_CONTAINER" sh -c 'cd /build/target && cp *.jar app.jar'
mkdir -p "${PWD}/target"
docker cp mavenbuild:/build/target/app.jar "${PWD}/target/app.jar"
docker rm -f mavenbuild
docker cp "$BUILD_CONTAINER":/build/target/app.jar "${PWD}/target/app.jar"
docker rm -f "$BUILD_CONTAINER"
- name: 构建并推送镜像
run: |
@@ -1,8 +1,7 @@
package com.yunhai.dormnotice.common.listener;
import com.yunhai.dormnotice.entity.BaseEntity;
import com.yunhai.platform.auth.LoginUser;
import com.yunhai.platform.auth.UserContextHolder;
import com.yunhai.dormnotice.utils.UserContext;
import org.springframework.stereotype.Component;
import javax.persistence.PrePersist;
@@ -10,9 +9,10 @@ import javax.persistence.PreUpdate;
import java.time.LocalDateTime;
/**
* JPA 审计监听器:在实体持久化/更新前自动填充创建人/更新人(平台当前登录人)与时间戳。
* 对应 {@link BaseEntity} 的 createBy / updateBy / createTime / updateTime 字段。
* 当前登录人取自基础平台 {@link UserContextHolder}。
* JPA 审计监听器:实体持久化/更新前自动填充创建人/更新人与时间戳。
* <p>决策 D4:{@code create_by / update_by} 存**当前登录用户 ID**(数字 id),不再存登录账号。
* id 取自 {@link UserContext#getUserId()}(由 ControllerUserContextAspect 在请求线程填充);
* 无登录上下文(启动种子/系统任务)时为 null,保持原值。</p>
*/
@Component
public class NoticeAuditListener {
@@ -22,26 +22,26 @@ public class NoticeAuditListener {
LocalDateTime now = LocalDateTime.now();
entity.setCreateTime(now);
entity.setUpdateTime(now);
String account = currentAccount();
if (account != null) {
Integer uid = currentUserId();
if (uid != null) {
if (entity.getCreateBy() == null) {
entity.setCreateBy(account);
entity.setCreateBy(uid);
}
entity.setUpdateBy(account);
entity.setUpdateBy(uid);
}
}
@PreUpdate
public void preUpdate(BaseEntity entity) {
entity.setUpdateTime(LocalDateTime.now());
String account = currentAccount();
if (account != null) {
entity.setUpdateBy(account);
Integer uid = currentUserId();
if (uid != null) {
entity.setUpdateBy(uid);
}
}
private String currentAccount() {
LoginUser user = UserContextHolder.get();
return user == null ? null : user.getLoginName();
/** 当前登录用户 ID(数字);无上下文返回 null。 */
private Integer currentUserId() {
return UserContext.getUserId();
}
}
@@ -1,70 +0,0 @@
package com.yunhai.dormnotice.config;
import com.yunhai.dormnotice.entity.SysDict;
import com.yunhai.dormnotice.repository.SysDictRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 字典自举种子:启动时若 sys_dict 缺 dept / noticeType 则补入默认口径(幂等,仅在为空时插)。
* <p>解决「发布部门/通知类型下拉为空」——不依赖 DBA 手动跑 dormnotice_init.sql。
* 生产可用 {@code dormnotice.seed-dict=false} 关闭。</p>
*/
@Component
public class DictSeedRunner implements ApplicationRunner {
private static final Logger log = LoggerFactory.getLogger(DictSeedRunner.class);
private static final String[][] DEPTS = {
{"D001", "校办"}, {"D002", "德育处"}, {"D003", "生活管理科"}, {"D004", "教务处"},
{"D005", "后勤保障部"}, {"D006", "校医务室"}, {"D007", "武术训练部"}, {"D008", "安全管理办公室"},
};
private static final String[][] NOTICE_TYPES = {
{"T001", "作息调整"}, {"T002", "宿舍调整"}, {"T003", "卫生检查"}, {"T004", "违规通报"},
{"T005", "停水停电"}, {"T006", "安全排查"}, {"T007", "留宿申请"}, {"T008", "家长探视"},
{"T009", "夜间查寝"}, {"T010", "物品清退"}, {"T011", "疫情防控"}, {"T012", "假期安排"}, {"T013", "其他"},
};
@Autowired
private SysDictRepository sysDictRepository;
@Value("${dormnotice.seed-dict:true}")
private boolean enabled;
@Override
@Transactional
public void run(ApplicationArguments args) {
if (!enabled) {
return;
}
seed("dept", DEPTS);
seed("noticeType", NOTICE_TYPES);
}
private void seed(String type, String[][] items) {
List<SysDict> existing = sysDictRepository.findByDictTypeOrderBySortOrderAsc(type);
if (!existing.isEmpty()) {
log.info("[DictSeed] 字典 {} 已有 {} 条,跳过种子", type, existing.size());
return;
}
int order = 1;
for (String[] it : items) {
SysDict d = new SysDict();
d.setDictType(type);
d.setDictKey(it[0]);
d.setDictValue(it[1]);
d.setSortOrder(order++);
d.setEnableFlag(1);
sysDictRepository.save(d);
}
log.info("[DictSeed] 字典 {} 已种入 {} 条", type, items.length);
}
}
@@ -42,26 +42,31 @@ public class ReadBackfillRunner implements ApplicationRunner {
if (!enabled) {
return;
}
List<Receipt> acted = receiptRepository.findByStatusIn(java.util.Arrays.asList("confirmed", "filled"));
int added = 0;
for (Receipt r : acted) {
if (r.getNoticeId() == null || r.getStudentId() == null) {
continue;
try {
List<Receipt> acted = receiptRepository.findByStatusIn(java.util.Arrays.asList("confirmed", "filled"));
int added = 0;
for (Receipt r : acted) {
if (r.getNoticeId() == null || r.getStudentId() == null) {
continue;
}
if (readRepository.existsByNoticeIdAndStudentId(r.getNoticeId(), r.getStudentId())) {
continue;
}
DormNoticeRead rd = new DormNoticeRead();
rd.setNoticeId(r.getNoticeId());
rd.setStudentId(r.getStudentId());
rd.setRoomId(r.getRoomId());
rd.setReadAt(r.getSubmittedAt() != null ? r.getSubmittedAt() : LocalDateTime.now());
rd.setSchId(r.getSchId());
readRepository.save(rd);
added++;
}
if (readRepository.existsByNoticeIdAndStudentId(r.getNoticeId(), r.getStudentId())) {
continue;
if (added > 0) {
log.info("[ReadBackfill] 依据已确认/已填报回执回填阅读记录 {} 条", added);
}
DormNoticeRead rd = new DormNoticeRead();
rd.setNoticeId(r.getNoticeId());
rd.setStudentId(r.getStudentId());
rd.setRoomId(r.getRoomId());
rd.setReadAt(r.getSubmittedAt() != null ? r.getSubmittedAt() : LocalDateTime.now());
rd.setSchId(r.getSchId());
readRepository.save(rd);
added++;
}
if (added > 0) {
log.info("[ReadBackfill] 依据已确认/已填报回执回填阅读记录 {} 条", added);
} catch (Exception e) {
// 回填失败不得阻断启动(如列类型未迁移等)
log.warn("[ReadBackfill] 阅读记录回填跳过:{}", e.getMessage());
}
}
}
@@ -106,14 +106,6 @@ public class DormController {
dormService.setMonitor(roomId, studentId);
}
/** 从 bschclass 学籍导入全校学生到待安排池(幂等),返回新增人数。 */
@PostMapping("ImportStudents")
public Map<String, Object> importStudents() {
Map<String, Object> r = new java.util.LinkedHashMap<>();
r.put("added", dormService.importStudentsFromBschclass());
return r;
}
private static Map<String, Object> toObj(Map<String, String> src) {
return src.entrySet().stream().collect(java.util.stream.Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
@@ -24,10 +24,10 @@ public abstract class BaseEntity implements Serializable {
private Integer id;
/**
* 创建人登录账号
* 创建人用户ID(数字;决策 D4,不存登录账号)
*/
@Column(name = "create_by", updatable = false)
private String createBy;
private Integer createBy;
/**
* 创建时间
@@ -36,10 +36,10 @@ public abstract class BaseEntity implements Serializable {
private LocalDateTime createTime;
/**
* 更新人登录账号
* 更新人用户ID(数字;决策 D4,不存登录账号)
*/
@Column(name = "update_by")
private String updateBy;
private Integer updateBy;
/**
* 更新时间
@@ -9,7 +9,7 @@ import javax.persistence.Entity;
import javax.persistence.Table;
/**
* 系统字典(发文部门等)。对应原 .NET Common_DeptDic 表。
* 系统字典(发文部门 / 通知类型)。按学校隔离(sch_id),对应原 .NET Common_DeptDic 表。
*/
@NoArgsConstructor
@Data
@@ -18,7 +18,7 @@ import javax.persistence.Table;
@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = false)
public class SysDict extends BaseEntity {
/** 字典类型(如 "dept"=发文部门) */
/** 字典类型("dept"=发文部门 / "noticeType"=通知类型) */
@Column(name = "dict_type", length = 50)
private String dictType;
@@ -37,4 +37,8 @@ public class SysDict extends BaseEntity {
/** 是否启用:0 禁用 / 1 启用(原 Enable) */
@Column(name = "enable_flag")
private Integer enableFlag = 1;
/** 学校ID(多租户隔离;发布/查询按当前学校过滤) */
@Column(name = "sch_id")
private Integer schId;
}
@@ -12,4 +12,11 @@ public interface SysDictRepository extends JpaRepository<SysDict, Integer> {
/** 按类型+key 取单条字典(发文部门名称解析用) */
Optional<SysDict> findByDictTypeAndDictKey(String dictType, String dictKey);
/** 学校隔离:按 schId + 类型 查询(schId 传 null 命中 sch_id IS NULL) */
List<SysDict> findBySchIdAndDictTypeOrderBySortOrderAsc(Integer schId, String dictType);
List<SysDict> findBySchIdAndDictTypeAndEnableFlagOrderBySortOrderAsc(Integer schId, String dictType, Integer enableFlag);
Optional<SysDict> findBySchIdAndDictTypeAndDictKey(Integer schId, String dictType, String dictKey);
}
@@ -40,7 +40,4 @@ public interface IDormService {
/** 楼栋→楼层→房间树(ztree,供发布选房间;对应 base/GetDormTree)。 */
List<Map<String, Object>> dormTree();
/** 从 bschclass 学籍导入全校学生到「待安排池」(roomId=0),幂等;返回新增人数。 */
int importStudentsFromBschclass();
}
@@ -1,8 +1,8 @@
package com.yunhai.dormnotice.service;
import com.yunhai.dormnotice.entity.UpFile;
import com.yunhai.dormnotice.model.notice.UpFileVo;
import com.yunhai.dormnotice.model.notice.UpFileResultVo;
import com.yunhai.dormnotice.model.notice.UpFileVo;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
@@ -83,7 +83,11 @@ public interface IFileService {
void downloadZipByTopic(String topicType, Integer topicId, String zipName, HttpServletResponse response);
/**
* 按附件ID集合打包下载为 ZIP(通知 AllFileDown 用:通知存的是 fileIds 逗号串)。
* 按附件记录ID列表打包下载为 ZIP。
*
* @param fileIds 附件记录ID列表
* @param zipName 压缩包显示名(自动追加 .zip)
* @param response HTTP 响应
*/
void downloadZipByIds(List<Integer> fileIds, String zipName, HttpServletResponse response);
@@ -3,6 +3,7 @@ package com.yunhai.dormnotice.service.impl;
import com.yunhai.dormnotice.entity.SysDict;
import com.yunhai.dormnotice.repository.SysDictRepository;
import com.yunhai.dormnotice.service.IDictService;
import com.yunhai.dormnotice.utils.UserContext;
import com.yunhai.platform.apistd.BizException;
import com.yunhai.platform.utils.exception.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
@@ -19,7 +20,8 @@ import java.util.stream.Collectors;
/**
* 系统字典服务(宿舍通知版)。type 维度:dept 发布部门 / noticeType 通知类型。
* dict_key 存 CodeID(D001/T001…),dict_value 存展示名(Name)。
* <p>按学校隔离(sys_dict.sch_id):读写均限当前 {@link UserContext#getSchId()};
* 某校首次访问某类型且为空时,惰性种入默认口径(部门 8 / 类型 13),各校独立可增删改。</p>
*/
@Service
public class DictService implements IDictService {
@@ -27,9 +29,24 @@ public class DictService implements IDictService {
private static final String DEPT = "dept";
private static final String NOTICE_TYPE = "noticeType";
/** 默认种子(首次访问按学校惰性写入) */
private static final String[][] DEPT_SEED = {
{"D001", "校办"}, {"D002", "德育处"}, {"D003", "生活管理科"}, {"D004", "教务处"},
{"D005", "后勤保障部"}, {"D006", "校医务室"}, {"D007", "武术训练部"}, {"D008", "安全管理办公室"},
};
private static final String[][] NOTICE_TYPE_SEED = {
{"T001", "作息调整"}, {"T002", "宿舍调整"}, {"T003", "卫生检查"}, {"T004", "违规通报"},
{"T005", "停水停电"}, {"T006", "安全排查"}, {"T007", "留宿申请"}, {"T008", "家长探视"},
{"T009", "夜间查寝"}, {"T010", "物品清退"}, {"T011", "疫情防控"}, {"T012", "假期安排"}, {"T013", "其他"},
};
@Autowired
private SysDictRepository sysDictRepository;
private Integer currentSchId() {
return UserContext.getSchId();
}
private String normalizeType(String type) {
if (!StringUtils.hasText(type)) {
return NOTICE_TYPE;
@@ -41,12 +58,34 @@ public class DictService implements IDictService {
return DEPT.equals(type) ? "D" : "T";
}
/** 首次访问某校某类型且为空时,种入默认口径(幂等,按 schId)。 */
@Transactional
public void ensureSeeded(Integer schId, String type) {
if (!sysDictRepository.findBySchIdAndDictTypeOrderBySortOrderAsc(schId, type).isEmpty()) {
return;
}
String[][] seed = DEPT.equals(type) ? DEPT_SEED : NOTICE_TYPE_SEED;
int order = 1;
for (String[] it : seed) {
SysDict d = new SysDict();
d.setDictType(type);
d.setDictKey(it[0]);
d.setDictValue(it[1]);
d.setSortOrder(order++);
d.setEnableFlag(1);
d.setSchId(schId);
sysDictRepository.save(d);
}
}
// ============================ List(下拉) ============================
@Override
public List<Map<String, Object>> list(String type) {
String t = normalizeType(type);
List<SysDict> items = sysDictRepository.findByDictTypeAndEnableFlagOrderBySortOrderAsc(t, 1);
Integer schId = currentSchId();
ensureSeeded(schId, t);
List<SysDict> items = sysDictRepository.findBySchIdAndDictTypeAndEnableFlagOrderBySortOrderAsc(schId, t, 1);
List<Map<String, Object>> out = new ArrayList<>();
for (SysDict d : items) {
Map<String, Object> m = new LinkedHashMap<>();
@@ -62,7 +101,9 @@ public class DictService implements IDictService {
@Override
public List<Map<String, Object>> manageList(String type) {
String t = normalizeType(type);
return sysDictRepository.findByDictTypeOrderBySortOrderAsc(t).stream().map(d -> {
Integer schId = currentSchId();
ensureSeeded(schId, t);
return sysDictRepository.findBySchIdAndDictTypeOrderBySortOrderAsc(schId, t).stream().map(d -> {
Map<String, Object> m = new LinkedHashMap<>();
m.put("SerID", d.getId());
m.put("CodeID", d.getDictKey());
@@ -82,7 +123,9 @@ public class DictService implements IDictService {
}
String trimmed = name.trim();
String t = normalizeType(type);
List<SysDict> existing = sysDictRepository.findByDictTypeOrderBySortOrderAsc(t);
Integer schId = currentSchId();
ensureSeeded(schId, t);
List<SysDict> existing = sysDictRepository.findBySchIdAndDictTypeOrderBySortOrderAsc(schId, t);
boolean dup = existing.stream().anyMatch(d -> trimmed.equals(d.getDictValue()));
if (dup) {
throw new BizException(ErrorCode.FORBIDDEN, NOTICE_TYPE.equals(t) ? "该通知类型已存在" : "已存在该分类,请重新填写!");
@@ -93,6 +136,7 @@ public class DictService implements IDictService {
dict.setDictValue(trimmed);
dict.setSortOrder(maxSort + 1);
dict.setEnableFlag(1);
dict.setSchId(schId);
dict.setDictKey(codePrefix(t) + "000"); // 占位,save 后按 id 生成 CodeID
SysDict saved = sysDictRepository.save(dict);
saved.setDictKey(codePrefix(t) + String.format("%03d", saved.getId()));
@@ -109,9 +153,10 @@ public class DictService implements IDictService {
}
SysDict dict = sysDictRepository.findById(serId)
.orElseThrow(() -> new BizException(ErrorCode.FORBIDDEN, "字典记录不存在"));
assertSameSchool(dict);
if (StringUtils.hasText(name)) {
String t = normalizeType(type);
boolean dup = sysDictRepository.findByDictTypeOrderBySortOrderAsc(t).stream()
boolean dup = sysDictRepository.findBySchIdAndDictTypeOrderBySortOrderAsc(currentSchId(), t).stream()
.anyMatch(d -> !d.getId().equals(serId) && name.trim().equals(d.getDictValue()));
if (dup) {
throw new BizException(ErrorCode.FORBIDDEN, "已存在该分类,请重新填写!");
@@ -131,7 +176,7 @@ public class DictService implements IDictService {
public void delete(Integer serId, String type) {
SysDict dict = sysDictRepository.findById(serId)
.orElseThrow(() -> new BizException(ErrorCode.FORBIDDEN, "字典记录不存在"));
// 通知引用校验在 NoticeService 侧按 deptId/noticeType 命中判定;此处直接删字典项。
assertSameSchool(dict);
sysDictRepository.delete(dict);
}
@@ -149,8 +194,10 @@ public class DictService implements IDictService {
for (int id : idArr) {
final int order = index--;
sysDictRepository.findById(id).ifPresent(d -> {
d.setSortOrder(order);
sysDictRepository.save(d);
if (sameSchool(d)) {
d.setSortOrder(order);
sysDictRepository.save(d);
}
});
}
}
@@ -169,7 +216,27 @@ public class DictService implements IDictService {
if (!StringUtils.hasText(deptId)) {
return null;
}
return sysDictRepository.findByDictTypeAndDictKey(DEPT, deptId.trim())
Integer schId = currentSchId();
String name = sysDictRepository.findBySchIdAndDictTypeAndDictKey(schId, DEPT, deptId.trim())
.map(SysDict::getDictValue).orElse(null);
if (name == null) {
name = sysDictRepository.findByDictTypeAndDictKey(DEPT, deptId.trim())
.map(SysDict::getDictValue).orElse(null);
}
return name;
}
// ============================ 租户守卫 ============================
private boolean sameSchool(SysDict d) {
Integer cur = currentSchId();
// 无学校上下文(系统/脚本)放行;否则要求同校(历史 sch_id 为 null 的行也放行,避免锁死)
return cur == null || d.getSchId() == null || cur.equals(d.getSchId());
}
private void assertSameSchool(SysDict d) {
if (!sameSchool(d)) {
throw new BizException(ErrorCode.FORBIDDEN, "无权操作其他学校的字典");
}
}
}
@@ -108,34 +108,68 @@ public class DormService implements IDormService {
@Override
public List<Map<String, Object>> pendingStudents(String keyword, String gender) {
// 待安排池:dorm_student 中 roomId=0/null。池空时惰性从 bschclass 学籍导入一次,
// 让「安排入住」有数据源;导入失败(平台不可达等)不影响页面,返回空池。
List<DormStudent> raw = studentRepository.findByRoomIdOrderByIdAsc(0);
if (raw.isEmpty()) {
try {
int n = importStudentsFromBschclass();
if (n > 0) {
raw = studentRepository.findByRoomIdOrderByIdAsc(0);
}
} catch (Exception e) {
log.warn("[pendingStudents] 从 bschclass 导入学生失败,返回空池: {}", e.getMessage());
// 实时在册 − 已在住:从 bschclass 拉最新全校在册学生,排除已安排进房间(roomId>0)的;
// 已在池(roomId=0)或从未入库的在册生都会出现在此名单。平台不可达时回退到已保存的待安排池。
List<DormStudent> all = studentRepository.findAll();
Set<Integer> housedIds = new HashSet<>();
Map<Integer, DormStudent> savedById = new HashMap<>();
for (DormStudent d : all) {
if (d.getStudentId() == null) {
continue;
}
savedById.put(d.getStudentId(), d);
if (nz(d.getRoomId()) > 0) {
housedIds.add(d.getStudentId());
}
}
List<DormStudent> pool = raw.stream()
.filter(s -> !StringUtils.hasText(gender) || gender.equals(s.getGender()))
.filter(s -> !StringUtils.hasText(keyword)
|| (s.getStudentName() + s.getClassName() + s.getGuardianName()).contains(keyword))
.collect(Collectors.toList());
String kw = keyword == null ? "" : keyword.trim();
List<Map<String, Object>> out = new ArrayList<>();
for (DormStudent s : pool) {
Roster roster = fetchRoster();
if (roster != null) {
for (SchStudentDto s : roster.students) {
if (s.getStuId() == null || housedIds.contains(s.getStuId())) {
continue; // 排除已在住
}
DormStudent saved = savedById.get(s.getStuId());
String g = saved != null ? saved.getGender() : null;
if (StringUtils.hasText(gender) && !gender.equals(g)) {
continue;
}
String cn = roster.classNames.get(s.getClassId());
if (!kw.isEmpty() && !(String.valueOf(s.getStuName()) + cn + (saved != null ? saved.getGuardianName() : "")).contains(kw)) {
continue;
}
Map<String, Object> m = new LinkedHashMap<>();
m.put("studentId", s.getStuId());
m.put("studentName", s.getStuName());
m.put("gender", g);
m.put("className", cn);
m.put("guardianName", saved != null ? saved.getGuardianName() : null);
m.put("guardianPhone", saved != null ? saved.getGuardianPhone() : null);
m.put("sourceDesc", saved != null && saved.getSourceDesc() != null ? saved.getSourceDesc() : "学籍在册未分配床位");
out.add(m);
}
return out;
}
// 平台不可达:回退到已保存的待安排池(roomId=0)
for (DormStudent d : all) {
if (nz(d.getRoomId()) != 0) {
continue;
}
if (StringUtils.hasText(gender) && !gender.equals(d.getGender())) {
continue;
}
if (!kw.isEmpty() && !(String.valueOf(d.getStudentName()) + d.getClassName() + d.getGuardianName()).contains(kw)) {
continue;
}
Map<String, Object> m = new LinkedHashMap<>();
m.put("studentId", s.getStudentId());
m.put("studentName", s.getStudentName());
m.put("gender", s.getGender());
m.put("className", s.getClassName());
m.put("guardianName", s.getGuardianName());
m.put("guardianPhone", s.getGuardianPhone());
m.put("sourceDesc", s.getSourceDesc());
m.put("studentId", d.getStudentId());
m.put("studentName", d.getStudentName());
m.put("gender", d.getGender());
m.put("className", d.getClassName());
m.put("guardianName", d.getGuardianName());
m.put("guardianPhone", d.getGuardianPhone());
m.put("sourceDesc", d.getSourceDesc());
out.add(m);
}
return out;
@@ -317,9 +351,31 @@ public class DormService implements IDormService {
public void assignStudent(Integer roomId, List<Integer> studentIds) {
DormRoom room = roomRepository.findByRoomId(roomId)
.orElseThrow(() -> new BizException(ErrorCode.FORBIDDEN, "房间不存在"));
// 预取在册名单:待安排名单可能含从未入库的在册生,安排时按 roster 补建 dorm_student
Roster roster = fetchRoster();
Map<Integer, SchStudentDto> rosterById = new HashMap<>();
if (roster != null) {
for (SchStudentDto s : roster.students) {
if (s.getStuId() != null) {
rosterById.put(s.getStuId(), s);
}
}
}
for (Integer sid : studentIds) {
DormStudent s = studentRepository.findByStudentId(sid)
.orElseThrow(() -> new BizException(ErrorCode.FORBIDDEN, "学生不存在:" + sid));
DormStudent s = studentRepository.findByStudentId(sid).orElse(null);
if (s == null) {
SchStudentDto dto = rosterById.get(sid);
if (dto == null) {
throw new BizException(ErrorCode.FORBIDDEN, "学生不存在或不在册:" + sid);
}
s = new DormStudent();
s.setStudentId(sid);
s.setStudentName(dto.getStuName());
s.setClassName(roster.classNames.get(dto.getClassId()));
s.setRoomId(0);
s.setIsMonitor(false);
s.setSchId(UserContext.getSchId());
}
if (nz(s.getRoomId()) != 0) {
throw new BizException(ErrorCode.FORBIDDEN, s.getStudentName() + " 已安排床位");
}
@@ -378,54 +434,41 @@ public class DormService implements IDormService {
}
}
// ============================ bschclass 学籍导入 ============================
// ============================ bschclass 学籍(在册名单) ============================
@Override
@Transactional
public int importStudentsFromBschclass() {
private static final class Roster {
final List<SchStudentDto> students;
final Map<Integer, String> classNames;
Roster(List<SchStudentDto> students, Map<Integer, String> classNames) {
this.students = students;
this.classNames = classNames;
}
}
/** 拉取本校在册学生 + 班级名映射;无学校上下文/失败/空返回 null(调用方按空处理)。 */
private Roster fetchRoster() {
Integer schId = UserContext.getSchId();
if (schId == null) {
throw new BizException(ErrorCode.PARAM_ERROR, "未获取到学校上下文,无法导入学生");
return null;
}
SchInfoDto info = classService.getSchFirst(schId);
if (info == null || !StringUtils.hasText(info.getSchSerId())) {
log.warn("[importStudents] schId={} 未取到 bschclass SchSerId", schId);
return 0;
log.warn("[dorm] schId={} 未取到 bschclass SchSerId", schId);
return null;
}
String schSerId = info.getSchSerId();
List<SchStudentDto> stus = classService.getSchStuList(schSerId);
List<SchStudentDto> stus = classService.getSchStuList(info.getSchSerId());
if (stus == null || stus.isEmpty()) {
return 0;
return null;
}
Map<Integer, String> classNames = new HashMap<>();
try {
for (SchClassDto c : classService.getSchClassList(schSerId)) {
for (SchClassDto c : classService.getSchClassList(info.getSchSerId())) {
classNames.put(c.getClassId(), c.getClassName());
}
} catch (Exception e) {
log.warn("[importStudents] 取班级名单失败(班级名留空): {}", e.getMessage());
log.warn("[dorm] 取班级名单失败(班级名留空): {}", e.getMessage());
}
int added = 0;
for (SchStudentDto s : stus) {
if (s.getStuId() == null) {
continue;
}
if (studentRepository.findByStudentId(s.getStuId()).isPresent()) {
continue; // 已存在(在住或已在池)跳过,幂等
}
DormStudent d = new DormStudent();
d.setStudentId(s.getStuId());
d.setStudentName(s.getStuName());
d.setClassName(classNames.get(s.getClassId()));
d.setRoomId(0);
d.setIsMonitor(false);
d.setSourceDesc("学籍在册未分配床位");
d.setSchId(schId);
studentRepository.save(d);
added++;
}
log.info("[importStudents] schId={} schSerId={} 学籍 {} 人,新导入待安排 {} 人", schId, schSerId, stus.size(), added);
return added;
return new Roster(stus, classNames);
}
// ============================ 辅助 ============================
@@ -1,8 +1,8 @@
package com.yunhai.dormnotice.service.impl;
import com.yunhai.dormnotice.entity.UpFile;
import com.yunhai.dormnotice.model.notice.UpFileVo;
import com.yunhai.dormnotice.model.notice.UpFileResultVo;
import com.yunhai.dormnotice.model.notice.UpFileVo;
import com.yunhai.dormnotice.repository.UpFileRepository;
import com.yunhai.dormnotice.service.IFileService;
import com.yunhai.platform.apistd.BizException;
@@ -18,7 +18,6 @@ import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLConnection;
@@ -26,15 +25,7 @@ import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.ArrayList;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -43,7 +34,7 @@ import java.util.zip.ZipOutputStream;
* 文件上传/下载/删除业务实现。
* <p>
* 存储路径规则:{uploadPath}/{appType}/{yyyyMMdd}/{uuid}.{ext}
* 与 C# UpLoadFile.FileSave 逻辑等价,但去除分片上传和 Office 转 PDF(后续按需补充)。
* UpLoadFile.FileSave 逻辑等价,但去除分片上传和 Office 转 PDF(后续按需补充)。
*/
@Service
public class FileService implements IFileService {
@@ -53,11 +44,9 @@ public class FileService implements IFileService {
@Autowired
private UpFileRepository upFileRepository;
@Value("${file.upload-path}")
@Value("${FILE_PATH}")
private String uploadPath;
private static final String DEFAULT_APP_TYPE = "dormnotice";
// ============================ 上传 ============================
@Override
@@ -77,13 +66,10 @@ public class FileService implements IFileService {
ext = originalName.substring(dotIdx + 1).toLowerCase();
}
// 构造存储子路径:{appType}/{yyyyMMdd}/{uuid}.{ext}
String dateDir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
String savedName = UUID.randomUUID().toString().replace("-", "") + (ext.isEmpty() ? "" : "." + ext);
String relativePath = (appType == null ? DEFAULT_APP_TYPE : appType) + "/" + dateDir + "/" + savedName;
// 物理写入
Path fullPath = Paths.get(uploadPath, relativePath);
Path fullPath = Paths.get(uploadPath, savedName);
try {
Files.createDirectories(fullPath.getParent());
file.transferTo(fullPath.toFile());
@@ -94,10 +80,10 @@ public class FileService implements IFileService {
// 入库
UpFile entity = new UpFile();
entity.setTopicType(appType == null ? DEFAULT_APP_TYPE : appType);
entity.setTopicType(appType);
entity.setTopicId(topicId);
entity.setFileTrueName(originalName);
entity.setFileName(relativePath);
entity.setFileName(savedName);
entity.setFileSize((int) file.getSize());
entity.setFileType(ext);
upFileRepository.save(entity);
@@ -125,8 +111,7 @@ public class FileService implements IFileService {
@Override
public List<UpFileVo> listByTopic(String appType, Integer topicId) {
String type = appType == null ? DEFAULT_APP_TYPE : appType;
return upFileRepository.findByTopicTypeAndTopicId(type, topicId).stream()
return upFileRepository.findByTopicTypeAndTopicId(appType, topicId).stream()
.map(this::toVo)
.collect(Collectors.toList());
}
@@ -279,17 +264,17 @@ public class FileService implements IFileService {
@Override
public void downloadZipByTopic(String topicType, Integer topicId, String zipName,
HttpServletResponse response) {
String type = topicType == null ? DEFAULT_APP_TYPE : topicType;
List<UpFile> files = upFileRepository.findByTopicTypeAndTopicId(type, topicId);
List<UpFile> files = upFileRepository.findByTopicTypeAndTopicId(topicType, topicId);
downloadZip(files, zipName, response);
}
// ============================ 按附件ID列表打包下载 ============================
@Override
public void downloadZipByIds(List<Integer> fileIds, String zipName, HttpServletResponse response) {
if (fileIds == null || fileIds.isEmpty()) {
throw new BizException(ErrorCode.PARAM_ERROR, "无附件可下载");
}
List<UpFile> files = upFileRepository.findAllById(fileIds);
List<UpFile> files = fileIds == null || fileIds.isEmpty()
? Collections.emptyList()
: upFileRepository.findAllById(fileIds);
downloadZip(files, zipName, response);
}
@@ -302,9 +287,8 @@ public class FileService implements IFileService {
if (files == null || files.length == 0) {
return results;
}
String type = appType != null ? appType : DEFAULT_APP_TYPE;
for (MultipartFile file : files) {
results.add(upload(file, type, null));
results.add(upload(file, appType, null));
}
return results;
}
@@ -15,6 +15,7 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
@@ -409,7 +410,7 @@ public class NoticeService implements INoticeService {
@Override
public Map<String, Object> statis(String startTime, String endTime) {
List<Notice> list = noticeRepository.findAll();
LocalDateTime st = parseDt(startTime), et = parseDt(endTime);
LocalDateTime st = parseDt(startTime), et = parseDateEnd(endTime);
if (st != null) list = list.stream().filter(n -> !nz(n.getCreateTime()).isBefore(st)).collect(Collectors.toList());
if (et != null) list = list.stream().filter(n -> !nz(n.getCreateTime()).isAfter(et)).collect(Collectors.toList());
@@ -910,7 +911,8 @@ public class NoticeService implements INoticeService {
m.put("receiveText", receiveText(n));
m.put("roomCount", targetRooms(n).size());
m.put("bedCount", allowCount(n));
m.put("progress", "draft".equals(n.getNoticeStatus()) ? null : progress(n.getId(), n));
// 仅通知类(none)不产生回执行,progress 置空,前端据此显示「仅通知 · 无需回执」而不是 0/0
m.put("progress", "draft".equals(n.getNoticeStatus()) || "none".equals(n.getReceiptMode()) ? null : progress(n.getId(), n));
m.put("createBy", n.getCreateBy());
m.put("createTime", fmt(n.getCreateTime()));
m.put("updateBy", n.getUpdateBy());
@@ -942,7 +944,7 @@ public class NoticeService implements INoticeService {
m.put("needSupervisor", nz(n.getNeedSupervisor()));
m.put("noticeStatus", n.getNoticeStatus());
m.put("noticeStatusDesc", DormEnums.statusDesc(n.getNoticeStatus()));
m.put("progress", "draft".equals(n.getNoticeStatus()) ? null : progress(n.getId(), n));
m.put("progress", "draft".equals(n.getNoticeStatus()) || "none".equals(n.getReceiptMode()) ? null : progress(n.getId(), n));
m.put("ChaoSend", fileItems(n.getFileIds()));
m.put("tlist", "ALL".equalsIgnoreCase(str(n.getReceiveList()).trim()) ? "all" : new ArrayList<>(targetRoomIds(n)));
m.put("receiveType", "room");
@@ -1108,7 +1110,7 @@ public class NoticeService implements INoticeService {
if (StringUtils.hasText(ns) && !"all".equals(ns)) {
out = out.stream().filter(n -> ns.equals(n.getNoticeStatus())).collect(Collectors.toList());
}
LocalDateTime st = parseDt(q.get("startTime")), et = parseDt(q.get("endTime"));
LocalDateTime st = parseDt(q.get("startTime")), et = parseDateEnd(q.get("endTime"));
if (st != null) out = out.stream().filter(n -> !nz(n.getEffectiveTime() == null ? n.getCreateTime() : n.getEffectiveTime()).isBefore(st)).collect(Collectors.toList());
if (et != null) out = out.stream().filter(n -> !nz(n.getEffectiveTime() == null ? n.getCreateTime() : n.getEffectiveTime()).isAfter(et)).collect(Collectors.toList());
int rt = intg(q.get("readType"), 0);
@@ -1194,6 +1196,18 @@ public class NoticeService implements INoticeService {
}
}
/**
* 解析查询区间的结束时间:纯日期(yyyy-MM-dd)时取当天末尾 23:59:59.999999999,使区间包含当天
*/
private LocalDateTime parseDateEnd(Object o) {
LocalDateTime t = parseDt(o);
if (t == null || o == null) {
return t;
}
String s = String.valueOf(o).trim();
return s.length() == 10 ? t.toLocalDate().atTime(LocalTime.MAX) : t;
}
private Map<String, Object> parseFill(Object o) {
if (o == null) {
return null;
@@ -22,6 +22,7 @@ import java.util.stream.Collectors;
* GetGroupUser 空桩改为显式报错(未接入用户中心对应开放接口时提示,而非静默返回空列表)。
* 跨仓调用统一收敛到 {@link YschBaseOpenApi} 门面,Controller 不再直接静态调用。</p>
*/
@Service
public class UserCenterService implements IUserCenterService {