Commit 085d8779 authored by wujipeng's avatar wujipeng
Browse files

账号导入导出优化

parent 1b41cf3f
......@@ -18,6 +18,45 @@ public class AccountImportRowDTO {
private String phoneNumber;
/**
* 以下字段仅用于学员花名册导入。教师和管理员仍使用原有的精简模板,
* 因此这些字段在非学员导入结果中保持为空,避免改变既有页面的数据口径。
*/
private String sex;
private String idCard;
private String userType1;
private String userType2;
private String companyName1;
private String companyCode1;
private String companyName2;
private String companyCode2;
private String highestEducation;
private String major;
private String socialSecurityYear;
private String workYear;
private String occupation;
@ApiModelProperty("所持前一等级证书的等级,不是当前培训班级等级")
private String certificateLevel;
private String certificateNo;
private String issueDate;
private String qualificationClause;
private String roleName;
private Integer roleId;
......
package com.platform.business.model.vo;
import lombok.Data;
/**
* 学员账户导出为正式职业技能认定花名册时使用的数据行。
*
* <p>该对象刻意与账户管理列表VO分离:列表页面只需要账户、班级和状态等摘要字段,
* 花名册则需要身份证、用工单位、学历及前一等级证书等申报资料。分离后不会因为导出
* 需求而扩大分页接口的响应体,也能明确区分“当前培训等级”和“前一证书等级”。</p>
*/
@Data
public class AccountStudentRosterVO {
private String id;
private String name;
private String sex;
private String idCard;
private String phoneNumber;
private String userType1;
private String userType2;
private String companyName1;
private String companyCode1;
private String companyName2;
private String companyCode2;
private String highestEducation;
private String major;
private String socialSecurityYear;
private String workYear;
private String occupation;
private String certificateLevel;
private String certificateNo;
private String issueDate;
private String qualificationClause;
private String remark;
}
......@@ -7,6 +7,7 @@ import com.platform.business.model.vo.AccountAdminStatisticsVO;
import com.platform.business.model.vo.AccountAttendanceVO;
import com.platform.business.model.vo.AccountLoginLogVO;
import com.platform.business.model.vo.AccountOptionVO;
import com.platform.business.model.vo.AccountStudentRosterVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
......@@ -21,6 +22,14 @@ public interface AccountAdminMapper {
@Param("broadRole") String broadRole,
@Param("sixMonthsAgo") Date sixMonthsAgo);
/**
* 使用与账户分页完全一致的筛选条件查询正式学员花名册字段,避免导出结果与页面不一致。
*/
List<AccountStudentRosterVO> selectStudentRosterRows(
@Param("query") AccountAdminQueryDTO query,
@Param("broadRole") String broadRole,
@Param("sixMonthsAgo") Date sixMonthsAgo);
AccountAdminDetailVO selectDetail(@Param("id") String id);
List<AccountAttendanceVO> selectAttendance(@Param("userId") String userId);
......
......@@ -83,6 +83,20 @@
`preview=true` 上传并展示逐行校验结果,用户确认后用同一文件以 `preview=false` 再次提交。
服务端只落库校验通过的行,单次最多500条、文件最大5MB。
### 学员正式花名册格式
`accountType=STUDENT` 时,模板和导出文件使用“花名册”工作表以及正式职业技能认定申报表
版式。前4行为固定抬头和两级表头,数据从第5行开始,共21列:序号、姓名、性别、身份证号、
联系电话、人员类别1/2、劳动关系单位名称及代码、实际用工单位名称及代码、最高学历、专业、
社保缴金年限、相关职业工作年限、前一等级证书的职业/等级/编号/日期、申报资质条款、备注。
- 模板预置48个空白学员行;仅预置序号的行不会被识别为待导入数据。
- 姓名和手机号必填,其他字段允许为空;填写身份证、性别和人员类别时会执行格式校验。
- 身份证、手机号、组织机构代码和证书编号按文本编号处理,兼容Excel科学计数法显示。
- 花名册“等级”属于“所持前一等级证书信息”;当前培训等级仍由`classId`对应班级决定。
- 导出少于48人时保留完整空白表格,超过48人时自动扩展并下移签字、备注区。
- 教师和管理员继续使用原有5列精简模板及账户清单格式。
## 数据库
发布前执行 `src/main/resources/sql/account_management.sql`。脚本新增账户状态、工号、结业/归档时间、
......
......@@ -88,6 +88,61 @@
order by coalesce(u.create_time, u.update_time, u.login_date) desc, u.id desc
</select>
<!--
正式花名册不复用AccountAdminListVO,防止身份证和单位等敏感字段被分页接口一并返回。
下方筛选条件必须与selectAccounts保持相同;学员导出由服务层固定传入STUDENT和“学生”。
-->
<select id="selectStudentRosterRows"
resultType="com.platform.business.model.vo.AccountStudentRosterVO">
select
u.id,
u.nick_name as name,
u.sex,
u.id_card as idCard,
u.phone_number as phoneNumber,
u.user_type1 as userType1,
u.user_type2 as userType2,
u.company_name1 as companyName1,
u.company_code1 as companyCode1,
u.company_name2 as companyName2,
u.company_code2 as companyCode2,
u.highest_education as highestEducation,
u.major,
u.social_security_year as socialSecurityYear,
u.work_year as workYear,
u.occupation,
u.level as certificateLevel,
u.cert_no as certificateNo,
u.issue_date as issueDate,
u.qualification_clause as qualificationClause,
u.remark
from user u
<include refid="accountJoins"/>
where exists (
select 1 from phone_role pr
where pr.phone = u.phone_number and pr.role_name = #{broadRole}
)
<if test="query.keyword != null and query.keyword != ''">
and (u.nick_name like concat('%', #{query.keyword}, '%')
or u.phone_number like concat('%', #{query.keyword}, '%')
or u.username like concat('%', #{query.keyword}, '%')
or u.employee_no like concat('%', #{query.keyword}, '%'))
</if>
<if test="query.classId != null">
and c.id = #{query.classId}
</if>
<if test="query.status != null and query.status != ''">
and <include refid="statusExpression"/> = #{query.status}
</if>
<if test="query.startDate != null">and c.start_date &gt;= #{query.startDate}</if>
<if test="query.endDate != null">and c.end_date &lt;= #{query.endDate}</if>
<if test="query.archiveOverSixMonths == true">
and <include refid="statusExpression"/> = 'GRADUATED'
and coalesce(u.graduation_time, c.end_date) &lt;= #{sixMonthsAgo}
</if>
order by coalesce(u.create_time, u.update_time, u.login_date) desc, u.id desc
</select>
<select id="selectDetail" resultType="com.platform.business.model.vo.AccountAdminDetailVO">
select
u.id,
......
......@@ -23,6 +23,8 @@ class AccountAdminMapperXmlTest {
configuration.getSqlFragments()).parse();
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.AccountAdminMapper.selectAccounts"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.AccountAdminMapper.selectStudentRosterRows"));
assertTrue(configuration.hasStatement(
"com.platform.business.mapper.AccountAdminMapper.selectDetail"));
assertTrue(configuration.hasStatement(
......
package com.platform.business.service.impl;
import com.platform.business.mapper.AccountAdminMapper;
import com.platform.business.mapper.ClassMapper;
import com.platform.business.model.dto.AccountAdminQueryDTO;
import com.platform.business.model.entity.ClassEntity;
import com.platform.business.model.entity.ClassStudentEntity;
import com.platform.business.model.entity.SysPhoneRoleEntity;
import com.platform.business.model.entity.UserEntity;
import com.platform.business.model.vo.AccountAdminDetailVO;
import com.platform.business.model.vo.AccountImportResultVO;
import com.platform.business.model.vo.AccountStudentRosterVO;
import com.platform.business.service.ClassStudentService;
import com.platform.business.service.SysPhoneRoleService;
import com.platform.business.service.SysRoleService;
import com.platform.business.service.SysUserAndRoleService;
import com.platform.business.service.UserService;
import com.platform.business.utils.PasswordUtil;
import com.platform.exception.BusinessException;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.util.ReflectionTestUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** 学员正式花名册模板、解析、持久化和导出的回归测试。 */
@ExtendWith(MockitoExtension.class)
class AccountAdminRosterExcelServiceTest {
@Mock
private AccountAdminMapper accountAdminMapper;
@Mock
private UserService userService;
@Mock
private SysPhoneRoleService phoneRoleService;
@Mock
private SysUserAndRoleService userRoleService;
@Mock
private SysRoleService roleService;
@Mock
private ClassStudentService classStudentService;
@Mock
private ClassMapper classMapper;
@Mock
private PasswordUtil passwordUtil;
private AccountAdminServiceImpl service;
@BeforeEach
void setUp() {
service = new AccountAdminServiceImpl();
ReflectionTestUtils.setField(service, "accountAdminMapper", accountAdminMapper);
ReflectionTestUtils.setField(service, "userService", userService);
ReflectionTestUtils.setField(service, "phoneRoleService", phoneRoleService);
ReflectionTestUtils.setField(service, "userRoleService", userRoleService);
ReflectionTestUtils.setField(service, "roleService", roleService);
ReflectionTestUtils.setField(service, "classStudentService", classStudentService);
ReflectionTestUtils.setField(service, "classMapper", classMapper);
ReflectionTestUtils.setField(service, "passwordUtil", passwordUtil);
}
@Test
void studentTemplateShouldMatchOfficialRosterStructureAndStyles() throws Exception {
byte[] bytes = downloadTemplate("STUDENT");
try (XSSFWorkbook workbook = new XSSFWorkbook(new ByteArrayInputStream(bytes))) {
Sheet sheet = workbook.getSheetAt(0);
assertEquals("花名册", sheet.getSheetName());
assertEquals("上海城投(集团)有限公司职业技能认定申报资质审核信息表",
sheet.getRow(0).getCell(0).getStringCellValue());
assertEquals("培养项目:污水处理工(污泥处理工)四级2025年1期",
sheet.getRow(1).getCell(11).getStringCellValue());
assertEquals("学员\n姓名", sheet.getRow(2).getCell(1).getStringCellValue());
assertEquals("职业(工种)", sheet.getRow(3).getCell(15).getStringCellValue());
assertTrue(hasMergedRegion(sheet, "A1:U1"));
assertTrue(hasMergedRegion(sheet, "F3:G3"));
assertTrue(hasMergedRegion(sheet, "P3:S3"));
assertTrue(hasMergedRegion(sheet, "A56:U56"));
assertEquals(4 * 256, sheet.getColumnWidth(0));
assertEquals(38.1f, sheet.getRow(0).getHeightInPoints(), 0.1f);
assertEquals(33f, sheet.getRow(4).getHeightInPoints(), 0.1f);
assertEquals(1d, sheet.getRow(4).getCell(0).getNumericCellValue());
assertEquals(48d, sheet.getRow(51).getCell(0).getNumericCellValue());
assertEquals("审核人签字:", sheet.getRow(54).getCell(0).getStringCellValue());
assertTrue(sheet.getRow(55).getCell(0).getStringCellValue().contains("2023版国标"));
Font titleFont = workbook.getFontAt(
sheet.getRow(0).getCell(0).getCellStyle().getFontIndex());
assertEquals("宋体", titleFont.getFontName());
assertEquals(28, titleFont.getFontHeightInPoints());
assertTrue(titleFont.getBold());
assertEquals(BorderStyle.THIN,
sheet.getRow(2).getCell(0).getCellStyle().getBorderTop());
assertEquals("@", sheet.getRow(4).getCell(3).getCellStyle().getDataFormatString());
}
}
@Test
void previewShouldParseAllTwentyOneColumnsAndNormalizeIdentifiers() throws Exception {
stubTargetClass();
MockMultipartFile file = rosterFile("1.3800138E10", false);
AccountImportResultVO result = service.importAccounts("STUDENT", 12, true, file, null);
assertEquals(1, result.getTotalCount());
assertEquals(1, result.getValidCount());
assertEquals(0, result.getInvalidCount());
assertEquals("13800138000", result.getRows().get(0).getPhoneNumber());
assertEquals("310101199001011234", result.getRows().get(0).getIdCard());
assertEquals("√", result.getRows().get(0).getUserType1());
assertEquals("上海城投污水处理有限公司", result.getRows().get(0).getCompanyName1());
assertEquals("五级", result.getRows().get(0).getCertificateLevel());
assertEquals("符合申报等级第1条", result.getRows().get(0).getQualificationClause());
}
@Test
void previewShouldRejectConflictingPersonCategoriesWithoutRejectingOptionalBlanks()
throws Exception {
stubTargetClass();
MockMultipartFile file = rosterFile("13800138000", true);
AccountImportResultVO result = service.importAccounts("STUDENT", 12, true, file, null);
assertEquals(0, result.getValidCount());
assertEquals(1, result.getInvalidCount());
assertTrue(result.getRows().get(0).getErrorMessage().contains("人员类别1和2不能同时勾选"));
}
@Test
void confirmedImportShouldPersistExtendedProfileAndKeepPreviousCertificateLevel()
throws Exception {
stubTargetClass();
when(passwordUtil.encodePassword(anyString())).thenReturn("encoded");
when(userService.save(any(UserEntity.class))).thenAnswer(invocation -> {
UserEntity user = invocation.getArgument(0);
user.setId("student-1");
return true;
});
when(phoneRoleService.count(any())).thenReturn(0L);
when(phoneRoleService.save(any(SysPhoneRoleEntity.class))).thenReturn(true);
when(classStudentService.remove(any())).thenReturn(true);
when(classStudentService.save(any(ClassStudentEntity.class))).thenReturn(true);
when(userRoleService.remove(any())).thenReturn(true);
AccountAdminDetailVO detail = new AccountAdminDetailVO();
detail.setId("student-1");
detail.setAccountType("STUDENT");
when(accountAdminMapper.selectDetail("student-1")).thenReturn(detail);
when(accountAdminMapper.selectAttendance("student-1")).thenReturn(Collections.emptyList());
when(accountAdminMapper.selectLoginLogs("student-1", 100)).thenReturn(Collections.emptyList());
AccountImportResultVO result = service.importAccounts(
"STUDENT", 12, false, rosterFile("13800138000", false), null);
assertEquals(1, result.getImportedCount());
ArgumentCaptor<UserEntity> userCaptor = ArgumentCaptor.forClass(UserEntity.class);
verify(userService).save(userCaptor.capture());
UserEntity saved = userCaptor.getValue();
assertEquals("310101199001011234", saved.getIdCard());
assertEquals("上海城投污水处理有限公司", saved.getCompanyName1());
assertEquals("91310115703235068A", saved.getCompanyCode1());
assertEquals("五级", saved.getLevel());
assertEquals("CERT-001", saved.getCertNo());
assertEquals("符合申报等级第1条", saved.getQualificationClause());
}
@Test
void studentExportShouldUseRosterQueryAndKeepMinimumFortyEightRows() throws Exception {
AccountStudentRosterVO roster = new AccountStudentRosterVO();
roster.setName("张三");
roster.setIdCard("310101199001011234");
roster.setPhoneNumber("13800138000");
roster.setCertificateLevel("五级");
roster.setCertificateNo("CERT-001");
when(accountAdminMapper.selectStudentRosterRows(any(AccountAdminQueryDTO.class),
anyString(), any(Date.class))).thenReturn(Collections.singletonList(roster));
AccountAdminQueryDTO query = new AccountAdminQueryDTO();
query.setAccountType("STUDENT");
MockHttpServletResponse response = new MockHttpServletResponse();
service.export(query, response);
try (XSSFWorkbook workbook = new XSSFWorkbook(
new ByteArrayInputStream(response.getContentAsByteArray()))) {
Sheet sheet = workbook.getSheet("花名册");
assertNotNull(sheet);
assertEquals("张三", sheet.getRow(4).getCell(1).getStringCellValue());
assertEquals(CellType.STRING, sheet.getRow(4).getCell(3).getCellType());
assertEquals("310101199001011234", sheet.getRow(4).getCell(3).getStringCellValue());
assertEquals("五级", sheet.getRow(4).getCell(16).getStringCellValue());
assertEquals("审核人签字:", sheet.getRow(54).getCell(0).getStringCellValue());
}
}
@Test
void studentExportShouldMoveSignatureAndNotesAfterMoreThanFortyEightRows() throws Exception {
List<AccountStudentRosterVO> rows = new ArrayList<>();
for (int i = 1; i <= 50; i++) {
AccountStudentRosterVO roster = new AccountStudentRosterVO();
roster.setName("学员" + i);
roster.setPhoneNumber(String.format("138%08d", i));
rows.add(roster);
}
when(accountAdminMapper.selectStudentRosterRows(any(AccountAdminQueryDTO.class),
anyString(), any(Date.class))).thenReturn(rows);
AccountAdminQueryDTO query = new AccountAdminQueryDTO();
query.setAccountType("STUDENT");
MockHttpServletResponse response = new MockHttpServletResponse();
service.export(query, response);
try (XSSFWorkbook workbook = new XSSFWorkbook(
new ByteArrayInputStream(response.getContentAsByteArray()))) {
Sheet sheet = workbook.getSheet("花名册");
assertEquals(50d, sheet.getRow(53).getCell(0).getNumericCellValue());
assertEquals("学员50", sheet.getRow(53).getCell(1).getStringCellValue());
// 50 条数据之后仍保留两行空白表格行,因此签字区从模板的第55行顺延到第57行。
assertEquals("审核人签字:", sheet.getRow(56).getCell(0).getStringCellValue());
assertTrue(sheet.getRow(57).getCell(0).getStringCellValue().contains("2023版国标"));
assertTrue(hasMergedRegion(sheet, "A58:U58"));
}
}
@Test
void studentImportShouldRejectMoreThanFiveHundredDataRows() throws Exception {
stubTargetClass();
MockMultipartFile file = rosterFileWithRows(501);
BusinessException exception = assertThrows(BusinessException.class,
() -> service.importAccounts("STUDENT", 12, true, file, null));
assertTrue(exception.getMessage().contains("500"));
}
@Test
void teacherTemplateShouldRemainTheOriginalFiveColumnFormat() throws Exception {
try (XSSFWorkbook workbook = new XSSFWorkbook(
new ByteArrayInputStream(downloadTemplate("TEACHER")))) {
Sheet sheet = workbook.getSheet("账户导入");
assertNotNull(sheet);
assertEquals("姓名", sheet.getRow(0).getCell(0).getStringCellValue());
assertEquals("工号", sheet.getRow(0).getCell(1).getStringCellValue());
assertEquals("手机号", sheet.getRow(0).getCell(2).getStringCellValue());
assertEquals("角色", sheet.getRow(0).getCell(3).getStringCellValue());
assertEquals("备注", sheet.getRow(0).getCell(4).getStringCellValue());
assertFalse(hasMergedRegion(sheet, "A1:U1"));
}
}
private byte[] downloadTemplate(String type) {
MockHttpServletResponse response = new MockHttpServletResponse();
service.downloadTemplate(type, response);
return response.getContentAsByteArray();
}
private void stubTargetClass() {
ClassEntity clazz = new ClassEntity();
clazz.setId(12);
clazz.setLevel("4");
when(classMapper.selectById(12)).thenReturn(clazz);
}
/**
* 基于服务真实下载的空模板构造合成数据,既验证模板可回读,也避免把参考文件中的
* 身份证和手机号等个人信息作为测试夹具提交到仓库。
*/
private MockMultipartFile rosterFile(String phone, boolean conflictingCategories)
throws Exception {
byte[] template = downloadTemplate("STUDENT");
try (XSSFWorkbook workbook = new XSSFWorkbook(new ByteArrayInputStream(template));
ByteArrayOutputStream output = new ByteArrayOutputStream()) {
Row row = workbook.getSheet("花名册").getRow(4);
String[] values = {
"张三", "男", "310101199001011234", phone, "√",
conflictingCategories ? "√" : "", "上海城投污水处理有限公司",
"91310115703235068A", "石洞口污水处理厂", "91310115703235068A",
"本科", "环境工程", "10.5", "6.5", "污水处理工", "五级",
"CERT-001", "2024-01-01", "符合申报等级第1条", "测试备注"
};
for (int i = 0; i < values.length; i++) {
row.getCell(i + 1).setCellValue(values[i]);
}
workbook.write(output);
return new MockMultipartFile("file", "花名册.xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
output.toByteArray());
}
}
/** 构造超过上限的合成花名册;移除页脚合并区后再将原页脚行复用为普通数据行。 */
private MockMultipartFile rosterFileWithRows(int rowCount) throws Exception {
byte[] template = downloadTemplate("STUDENT");
try (XSSFWorkbook workbook = new XSSFWorkbook(new ByteArrayInputStream(template));
ByteArrayOutputStream output = new ByteArrayOutputStream()) {
Sheet sheet = workbook.getSheet("花名册");
for (int i = sheet.getNumMergedRegions() - 1; i >= 0; i--) {
if (sheet.getMergedRegion(i).getFirstRow() >= 54) {
sheet.removeMergedRegion(i);
}
}
for (int i = 0; i < rowCount; i++) {
int rowIndex = i + 4;
Row row = sheet.getRow(rowIndex);
if (row == null) {
row = sheet.createRow(rowIndex);
}
row.createCell(0).setCellValue(i + 1);
row.createCell(1).setCellValue("学员" + (i + 1));
row.createCell(4).setCellValue(String.format("138%08d", i + 1));
}
workbook.write(output);
return new MockMultipartFile("file", "花名册-501条.xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
output.toByteArray());
}
}
private boolean hasMergedRegion(Sheet sheet, String reference) {
return sheet.getMergedRegions().stream()
.map(CellRangeAddress::formatAsString)
.anyMatch(reference::equals);
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment