Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
邬吉朋
practical_train
Commits
9fc77652
Commit
9fc77652
authored
Aug 17, 2026
by
wujipeng
Browse files
管理员-题库管理-理论题库
parent
5fe1aba7
Changes
35
Hide whitespace changes
Inline
Side-by-side
practical-business/src/main/java/com/platform/business/service/BsFileService.java
View file @
9fc77652
...
...
@@ -13,6 +13,9 @@ public interface BsFileService extends IService<BsFileEntity> {
/** 将文件保存到磁盘并持久化文件元数据。 */
BsFileEntity
uploadFile
(
MultipartFile
file
)
;
/** 保存服务端生成的Excel等字节内容,并登记到统一文件表。 */
BsFileEntity
saveGeneratedFile
(
String
fileName
,
byte
[]
content
);
/** 以附件方式流式输出文件。 */
void
downloadFile
(
Integer
id
);
}
practical-business/src/main/java/com/platform/business/service/TheoreticalLibraryAdminService.java
0 → 100644
View file @
9fc77652
package
com.platform.business.service
;
import
com.platform.business.model.dto.TheoreticalLibraryBatchDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryBatchStatusDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryBatchTransferDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryNodeMoveDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryNodeSaveDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryQuestionQueryDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryQuestionSaveDTO
;
import
com.platform.business.model.entity.TheoreticalLibraryNodeEntity
;
import
com.platform.business.model.entity.UserEntity
;
import
com.platform.business.model.vo.TheoreticalLibraryNodeVO
;
import
com.platform.business.model.vo.TheoreticalLibraryQuestionVO
;
import
java.util.List
;
/** 管理员端理论题库完整业务接口。 */
public
interface
TheoreticalLibraryAdminService
{
List
<
TheoreticalLibraryNodeVO
>
tree
(
String
bankType
,
String
keyword
);
List
<
TheoreticalLibraryNodeEntity
>
flatNodes
(
String
bankType
);
TheoreticalLibraryNodeVO
createNode
(
TheoreticalLibraryNodeSaveDTO
body
,
UserEntity
admin
);
TheoreticalLibraryNodeVO
updateNode
(
String
id
,
TheoreticalLibraryNodeSaveDTO
body
);
Boolean
moveNode
(
String
id
,
TheoreticalLibraryNodeMoveDTO
body
);
Boolean
changeNodeStatus
(
String
id
,
Integer
status
);
Boolean
deleteNode
(
String
id
,
boolean
cascade
);
List
<
TheoreticalLibraryQuestionVO
>
page
(
TheoreticalLibraryQuestionQueryDTO
query
);
List
<
String
>
filteredIds
(
TheoreticalLibraryQuestionQueryDTO
query
);
TheoreticalLibraryQuestionVO
detail
(
String
id
);
TheoreticalLibraryQuestionVO
createQuestion
(
TheoreticalLibraryQuestionSaveDTO
body
,
UserEntity
admin
);
TheoreticalLibraryQuestionVO
updateQuestion
(
String
id
,
TheoreticalLibraryQuestionSaveDTO
body
);
TheoreticalLibraryQuestionVO
copyQuestion
(
String
id
,
UserEntity
admin
);
Boolean
deleteQuestion
(
String
id
);
Boolean
batchStatus
(
TheoreticalLibraryBatchStatusDTO
body
);
Boolean
batchTransfer
(
TheoreticalLibraryBatchTransferDTO
body
);
Boolean
batchDelete
(
TheoreticalLibraryBatchDTO
body
);
}
practical-business/src/main/java/com/platform/business/service/TheoreticalLibraryExcelService.java
0 → 100644
View file @
9fc77652
package
com.platform.business.service
;
import
com.platform.business.model.dto.TheoreticalLibraryExportDTO
;
import
com.platform.business.model.entity.UserEntity
;
import
com.platform.business.model.vo.TheoreticalLibraryImportResultVO
;
import
org.springframework.web.multipart.MultipartFile
;
import
javax.servlet.http.HttpServletResponse
;
/** 理论题库 Excel 模板、导入、导出和错误明细服务。 */
public
interface
TheoreticalLibraryExcelService
{
void
template
(
String
dataType
,
String
bankType
,
HttpServletResponse
response
);
TheoreticalLibraryImportResultVO
importData
(
String
dataType
,
String
bankType
,
String
mode
,
MultipartFile
file
,
UserEntity
admin
);
void
export
(
TheoreticalLibraryExportDTO
body
,
HttpServletResponse
response
);
void
downloadImportErrors
(
Integer
fileId
);
}
practical-business/src/main/java/com/platform/business/service/impl/BsFileServiceImpl.java
View file @
9fc77652
...
...
@@ -81,6 +81,49 @@ public class BsFileServiceImpl extends ServiceImpl<BsFileMapper, BsFileEntity> i
}
}
@Override
public
BsFileEntity
saveGeneratedFile
(
String
fileName
,
byte
[]
content
)
{
if
(
content
==
null
||
content
.
length
==
0
)
{
throw
new
BusinessException
(
"生成文件内容不能为空"
);
}
if
(
content
.
length
>
MAX_FILE_SIZE
)
{
throw
new
BusinessException
(
"生成文件不能超过500MB"
);
}
Path
target
=
null
;
try
{
Path
directory
=
Paths
.
get
(
uploadDirectory
).
toAbsolutePath
().
normalize
();
Files
.
createDirectories
(
directory
);
String
safeName
=
safeOriginalFilename
(
fileName
);
String
storedFilename
=
UUID
.
randomUUID
().
toString
().
replace
(
"-"
,
""
)
+
getExtension
(
safeName
);
target
=
directory
.
resolve
(
storedFilename
).
normalize
();
if
(!
target
.
startsWith
(
directory
))
{
throw
new
BusinessException
(
"文件保存路径非法"
);
}
Files
.
write
(
target
,
content
);
BsFileEntity
bsFile
=
BsFileEntity
.
builder
()
.
url
(
target
.
toString
())
.
fileName
(
safeName
)
.
delFlag
(
0
)
.
build
();
if
(!
save
(
bsFile
))
{
Files
.
deleteIfExists
(
target
);
throw
new
BusinessException
(
"文件信息保存失败"
);
}
return
bsFile
;
}
catch
(
IOException
e
)
{
if
(
target
!=
null
)
{
try
{
Files
.
deleteIfExists
(
target
);
}
catch
(
IOException
cleanupException
)
{
log
.
warn
(
"生成文件失败后清理临时文件失败:{}"
,
target
,
cleanupException
);
}
}
log
.
error
(
"生成文件保存失败"
,
e
);
throw
new
BusinessException
(
"生成文件保存失败"
);
}
}
@Override
public
void
downloadFile
(
Integer
id
)
{
// getById 会自动附带 del_flag=0 条件,已逻辑删除的文件不可下载。
...
...
practical-business/src/main/java/com/platform/business/service/impl/TheoreticalLibraryAdminServiceImpl.java
0 → 100644
View file @
9fc77652
package
com.platform.business.service.impl
;
import
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
;
import
com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper
;
import
com.fasterxml.jackson.core.JsonProcessingException
;
import
com.fasterxml.jackson.core.type.TypeReference
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
com.platform.business.constant.TheoreticalLibraryAdminConstants
;
import
com.platform.business.mapper.TheoreticalLibraryMapper
;
import
com.platform.business.mapper.TheoreticalLibraryNodeMapper
;
import
com.platform.business.model.dto.TheoreticalLibraryBatchDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryBatchStatusDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryBatchTransferDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryNodeMoveDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryNodeSaveDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryOptionDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryQuestionQueryDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryQuestionSaveDTO
;
import
com.platform.business.model.entity.TheoreticalLibraryEntity
;
import
com.platform.business.model.entity.TheoreticalLibraryNodeEntity
;
import
com.platform.business.model.entity.UserEntity
;
import
com.platform.business.model.vo.TheoreticalLibraryNodeCountVO
;
import
com.platform.business.model.vo.TheoreticalLibraryNodeVO
;
import
com.platform.business.model.vo.TheoreticalLibraryQuestionVO
;
import
com.platform.business.service.TheoreticalLibraryAdminService
;
import
com.platform.exception.BusinessException
;
import
org.springframework.beans.BeanUtils
;
import
org.springframework.stereotype.Service
;
import
org.springframework.transaction.annotation.Transactional
;
import
org.springframework.util.StringUtils
;
import
javax.annotation.Resource
;
import
java.time.LocalDateTime
;
import
java.time.format.DateTimeFormatter
;
import
java.util.ArrayList
;
import
java.util.Collections
;
import
java.util.Comparator
;
import
java.util.Date
;
import
java.util.HashMap
;
import
java.util.HashSet
;
import
java.util.LinkedHashMap
;
import
java.util.List
;
import
java.util.Locale
;
import
java.util.Map
;
import
java.util.Set
;
import
java.util.UUID
;
import
java.util.stream.Collectors
;
/**
* 管理员端理论题库实现。
*
* <p>新节点表是层级结构的唯一事实来源,题目仍写入旧 {@code theoretical_library}
* 表以兼容自动组卷和模拟练习。每次新增、编辑和转移都会从节点路径重新生成 scope、
* 一至四级名称等旧字段,杜绝新旧链路出现两套不一致的数据。</p>
*/
@Service
public
class
TheoreticalLibraryAdminServiceImpl
implements
TheoreticalLibraryAdminService
{
private
static
final
DateTimeFormatter
QUESTION_CODE_TIME
=
DateTimeFormatter
.
ofPattern
(
"yyyyMMddHHmmss"
);
@Resource
private
TheoreticalLibraryNodeMapper
nodeMapper
;
@Resource
private
TheoreticalLibraryMapper
libraryMapper
;
@Resource
private
ObjectMapper
objectMapper
;
@Override
@Transactional
(
readOnly
=
true
)
public
List
<
TheoreticalLibraryNodeVO
>
tree
(
String
bankType
,
String
keyword
)
{
String
normalizedBankType
=
TheoreticalLibraryAdminConstants
.
normalizeBankType
(
bankType
);
List
<
TheoreticalLibraryNodeEntity
>
nodes
=
flatNodes
(
normalizedBankType
);
if
(
nodes
.
isEmpty
())
{
return
Collections
.
emptyList
();
}
Map
<
String
,
Long
>
directCounts
=
new
HashMap
<>();
List
<
TheoreticalLibraryNodeCountVO
>
countRows
=
libraryMapper
.
selectQuestionCounts
(
normalizedBankType
);
if
(
countRows
!=
null
)
{
for
(
TheoreticalLibraryNodeCountVO
row
:
countRows
)
{
directCounts
.
put
(
row
.
getNodeId
(),
row
.
getQuestionCount
());
}
}
Map
<
String
,
TheoreticalLibraryNodeVO
>
voMap
=
new
LinkedHashMap
<>();
for
(
TheoreticalLibraryNodeEntity
node
:
nodes
)
{
TheoreticalLibraryNodeVO
vo
=
new
TheoreticalLibraryNodeVO
();
BeanUtils
.
copyProperties
(
node
,
vo
);
vo
.
setQuestionCount
(
directCounts
.
getOrDefault
(
node
.
getId
(),
0L
));
voMap
.
put
(
vo
.
getId
(),
vo
);
}
List
<
TheoreticalLibraryNodeVO
>
roots
=
new
ArrayList
<>();
for
(
TheoreticalLibraryNodeVO
vo
:
voMap
.
values
())
{
TheoreticalLibraryNodeVO
parent
=
voMap
.
get
(
vo
.
getParentId
());
if
(
parent
==
null
)
{
roots
.
add
(
vo
);
}
else
{
parent
.
getChildren
().
add
(
vo
);
}
}
for
(
TheoreticalLibraryNodeVO
root
:
roots
)
{
decorateTree
(
root
,
""
,
directCounts
);
}
String
normalizedKeyword
=
trimOptional
(
keyword
,
100
,
"节点搜索关键字"
);
if
(!
StringUtils
.
hasText
(
normalizedKeyword
))
{
return
roots
;
}
String
lowerKeyword
=
normalizedKeyword
.
toLowerCase
(
Locale
.
ROOT
);
return
roots
.
stream
()
.
map
(
root
->
filterTree
(
root
,
lowerKeyword
))
.
filter
(
item
->
item
!=
null
)
.
collect
(
Collectors
.
toList
());
}
@Override
@Transactional
(
readOnly
=
true
)
public
List
<
TheoreticalLibraryNodeEntity
>
flatNodes
(
String
bankType
)
{
String
normalizedBankType
=
TheoreticalLibraryAdminConstants
.
normalizeBankType
(
bankType
);
return
nodeMapper
.
selectList
(
new
LambdaQueryWrapper
<
TheoreticalLibraryNodeEntity
>()
.
eq
(
TheoreticalLibraryNodeEntity:
:
getBankType
,
normalizedBankType
)
.
orderByAsc
(
TheoreticalLibraryNodeEntity:
:
getSortNo
)
.
orderByAsc
(
TheoreticalLibraryNodeEntity:
:
getId
));
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
TheoreticalLibraryNodeVO
createNode
(
TheoreticalLibraryNodeSaveDTO
body
,
UserEntity
admin
)
{
if
(
body
==
null
)
{
throw
new
BusinessException
(
"节点信息不能为空"
);
}
String
bankType
=
TheoreticalLibraryAdminConstants
.
normalizeBankType
(
body
.
getBankType
());
String
parentId
=
normalizeParentId
(
body
.
getParentId
());
TheoreticalLibraryNodeEntity
parent
=
parent
(
parentId
);
if
(
parent
!=
null
&&
!
bankType
.
equals
(
parent
.
getBankType
()))
{
throw
new
BusinessException
(
"上级节点与当前题库类型不一致"
);
}
List
<
String
>
nodeTypes
=
TheoreticalLibraryAdminConstants
.
nodeTypes
(
bankType
);
int
level
=
parent
==
null
?
0
:
nodeTypes
.
indexOf
(
parent
.
getNodeType
())
+
1
;
if
(
level
<
0
||
level
>=
nodeTypes
.
size
())
{
throw
new
BusinessException
(
"末级节点不可继续新增下级"
);
}
TheoreticalLibraryNodeEntity
entity
=
new
TheoreticalLibraryNodeEntity
();
entity
.
setBankType
(
bankType
);
entity
.
setParentId
(
parentId
);
entity
.
setNodeType
(
nodeTypes
.
get
(
level
));
applyNodeFields
(
entity
,
body
,
null
);
entity
.
setCreateUserId
(
admin
==
null
?
null
:
admin
.
getId
());
entity
.
setCreateUserName
(
displayName
(
admin
));
ensureNodeCodeUnique
(
entity
,
null
);
if
(
nodeMapper
.
insert
(
entity
)
!=
1
)
{
throw
new
BusinessException
(
"节点新增失败,请重试"
);
}
return
findNodeVO
(
entity
.
getId
());
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
TheoreticalLibraryNodeVO
updateNode
(
String
id
,
TheoreticalLibraryNodeSaveDTO
body
)
{
TheoreticalLibraryNodeEntity
existing
=
requireNode
(
id
);
if
(
body
==
null
)
{
throw
new
BusinessException
(
"节点信息不能为空"
);
}
// 编辑接口不允许借请求体改变题库、父节点和节点类型,移动树结构需单独设计迁移操作。
applyNodeFields
(
existing
,
body
,
existing
.
getSortNo
());
ensureNodeCodeUnique
(
existing
,
existing
.
getId
());
if
(
nodeMapper
.
updateById
(
existing
)
!=
1
)
{
throw
new
BusinessException
(
"节点更新失败,请刷新后重试"
);
}
// 名称变化会影响旧 scope/章/节字段,必须同步整棵子树题目。
synchronizeQuestionsUnderNode
(
existing
.
getId
());
return
findNodeVO
(
existing
.
getId
());
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
Boolean
moveNode
(
String
id
,
TheoreticalLibraryNodeMoveDTO
body
)
{
TheoreticalLibraryNodeEntity
node
=
requireNode
(
id
);
String
direction
=
body
==
null
||
body
.
getDirection
()
==
null
?
""
:
body
.
getDirection
().
trim
().
toUpperCase
(
Locale
.
ROOT
);
if
(!
"UP"
.
equals
(
direction
)
&&
!
"DOWN"
.
equals
(
direction
))
{
throw
new
BusinessException
(
"移动方向仅支持UP或DOWN"
);
}
List
<
TheoreticalLibraryNodeEntity
>
siblings
=
nodeMapper
.
selectList
(
new
LambdaQueryWrapper
<
TheoreticalLibraryNodeEntity
>()
.
eq
(
TheoreticalLibraryNodeEntity:
:
getBankType
,
node
.
getBankType
())
.
eq
(
TheoreticalLibraryNodeEntity:
:
getParentId
,
node
.
getParentId
())
.
orderByAsc
(
TheoreticalLibraryNodeEntity:
:
getSortNo
)
.
orderByAsc
(
TheoreticalLibraryNodeEntity:
:
getId
));
int
index
=
-
1
;
for
(
int
i
=
0
;
i
<
siblings
.
size
();
i
++)
{
if
(
node
.
getId
().
equals
(
siblings
.
get
(
i
).
getId
()))
{
index
=
i
;
break
;
}
}
int
target
=
"UP"
.
equals
(
direction
)
?
index
-
1
:
index
+
1
;
if
(
index
<
0
||
target
<
0
||
target
>=
siblings
.
size
())
{
return
Boolean
.
TRUE
;
}
Collections
.
swap
(
siblings
,
index
,
target
);
for
(
int
i
=
0
;
i
<
siblings
.
size
();
i
++)
{
TheoreticalLibraryNodeEntity
sibling
=
siblings
.
get
(
i
);
sibling
.
setSortNo
((
i
+
1
)
*
10
);
nodeMapper
.
updateById
(
sibling
);
}
return
Boolean
.
TRUE
;
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
Boolean
changeNodeStatus
(
String
id
,
Integer
status
)
{
requireStatus
(
status
);
TheoreticalLibraryNodeEntity
node
=
requireNode
(
id
);
node
.
setStatus
(
status
);
if
(
nodeMapper
.
updateById
(
node
)
!=
1
)
{
throw
new
BusinessException
(
"节点状态更新失败"
);
}
return
Boolean
.
TRUE
;
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
Boolean
deleteNode
(
String
id
,
boolean
cascade
)
{
requireNode
(
id
);
if
(!
cascade
)
{
throw
new
BusinessException
(
"删除节点必须明确确认级联删除"
);
}
List
<
String
>
ids
=
descendantIds
(
id
,
true
);
libraryMapper
.
delete
(
new
LambdaQueryWrapper
<
TheoreticalLibraryEntity
>()
.
in
(
TheoreticalLibraryEntity:
:
getNodeId
,
ids
)
.
eq
(
TheoreticalLibraryEntity:
:
getIsProblem
,
true
));
if
(
nodeMapper
.
deleteBatchIds
(
ids
)
<
1
)
{
throw
new
BusinessException
(
"节点删除失败,请刷新后重试"
);
}
return
Boolean
.
TRUE
;
}
@Override
@Transactional
(
readOnly
=
true
)
public
List
<
TheoreticalLibraryQuestionVO
>
page
(
TheoreticalLibraryQuestionQueryDTO
query
)
{
TheoreticalLibraryQuestionQueryDTO
safeQuery
=
prepareQuery
(
query
);
List
<
TheoreticalLibraryQuestionVO
>
rows
=
libraryMapper
.
selectAdminQuestions
(
safeQuery
);
if
(
rows
==
null
)
{
return
Collections
.
emptyList
();
}
rows
.
forEach
(
this
::
decorateQuestion
);
return
rows
;
}
@Override
@Transactional
(
readOnly
=
true
)
public
List
<
String
>
filteredIds
(
TheoreticalLibraryQuestionQueryDTO
query
)
{
List
<
String
>
ids
=
libraryMapper
.
selectAdminQuestionIds
(
prepareQuery
(
query
));
if
(
ids
!=
null
&&
ids
.
size
()
>
TheoreticalLibraryAdminConstants
.
MAX_BATCH_SIZE
)
{
throw
new
BusinessException
(
"筛选结果超过5000条,请缩小范围后再全选"
);
}
return
ids
==
null
?
Collections
.
emptyList
()
:
ids
;
}
@Override
@Transactional
(
readOnly
=
true
)
public
TheoreticalLibraryQuestionVO
detail
(
String
id
)
{
TheoreticalLibraryEntity
entity
=
requireQuestion
(
id
,
false
);
TheoreticalLibraryQuestionVO
vo
=
new
TheoreticalLibraryQuestionVO
();
BeanUtils
.
copyProperties
(
entity
,
vo
);
decorateQuestion
(
vo
);
return
vo
;
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
TheoreticalLibraryQuestionVO
createQuestion
(
TheoreticalLibraryQuestionSaveDTO
body
,
UserEntity
admin
)
{
TheoreticalLibraryEntity
entity
=
prepareQuestion
(
body
,
null
);
entity
.
setCode
(
generateQuestionCode
());
entity
.
setCreateUserId
(
admin
==
null
?
null
:
admin
.
getId
());
entity
.
setCreateUserName
(
displayName
(
admin
));
if
(
libraryMapper
.
insert
(
entity
)
!=
1
)
{
throw
new
BusinessException
(
"试题新增失败,请重试"
);
}
return
detail
(
entity
.
getId
());
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
TheoreticalLibraryQuestionVO
updateQuestion
(
String
id
,
TheoreticalLibraryQuestionSaveDTO
body
)
{
TheoreticalLibraryEntity
existing
=
requireQuestion
(
id
,
true
);
TheoreticalLibraryEntity
prepared
=
prepareQuestion
(
body
,
existing
);
if
(
libraryMapper
.
updateById
(
prepared
)
!=
1
)
{
throw
new
BusinessException
(
"试题更新失败,请刷新后重试"
);
}
return
detail
(
prepared
.
getId
());
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
TheoreticalLibraryQuestionVO
copyQuestion
(
String
id
,
UserEntity
admin
)
{
TheoreticalLibraryEntity
source
=
requireQuestion
(
id
,
true
);
ensureEnabledTerminalNode
(
source
.
getNodeId
());
TheoreticalLibraryEntity
copy
=
new
TheoreticalLibraryEntity
();
BeanUtils
.
copyProperties
(
source
,
copy
,
"id"
,
"code"
,
"createTime"
,
"updateTime"
,
"createUserId"
,
"createUserName"
);
copy
.
setCode
(
generateQuestionCode
());
copy
.
setProblem
(
source
.
getProblem
()
+
"(副本)"
);
copy
.
setStatus
(
1
);
copy
.
setCreateUserId
(
admin
==
null
?
null
:
admin
.
getId
());
copy
.
setCreateUserName
(
displayName
(
admin
));
if
(
libraryMapper
.
insert
(
copy
)
!=
1
)
{
throw
new
BusinessException
(
"试题复制失败,请重试"
);
}
return
detail
(
copy
.
getId
());
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
Boolean
deleteQuestion
(
String
id
)
{
TheoreticalLibraryEntity
existing
=
requireQuestion
(
id
,
true
);
if
(
libraryMapper
.
deleteById
(
existing
.
getId
())
!=
1
)
{
throw
new
BusinessException
(
"试题删除失败,请刷新后重试"
);
}
return
Boolean
.
TRUE
;
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
Boolean
batchStatus
(
TheoreticalLibraryBatchStatusDTO
body
)
{
List
<
String
>
ids
=
requireBatchIds
(
body
==
null
?
null
:
body
.
getIds
());
requireStatus
(
body
.
getStatus
());
ensureQuestionsExist
(
ids
);
libraryMapper
.
update
(
null
,
new
LambdaUpdateWrapper
<
TheoreticalLibraryEntity
>()
.
in
(
TheoreticalLibraryEntity:
:
getId
,
ids
)
.
eq
(
TheoreticalLibraryEntity:
:
getIsProblem
,
true
)
.
set
(
TheoreticalLibraryEntity:
:
getStatus
,
body
.
getStatus
())
.
set
(
TheoreticalLibraryEntity:
:
getUpdateTime
,
new
Date
()));
return
Boolean
.
TRUE
;
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
Boolean
batchTransfer
(
TheoreticalLibraryBatchTransferDTO
body
)
{
List
<
String
>
ids
=
requireBatchIds
(
body
==
null
?
null
:
body
.
getIds
());
TheoreticalLibraryNodeEntity
target
=
ensureEnabledTerminalNode
(
body
==
null
?
null
:
body
.
getTargetNodeId
());
List
<
TheoreticalLibraryEntity
>
questions
=
lockQuestions
(
ids
);
for
(
TheoreticalLibraryEntity
question
:
questions
)
{
if
(!
target
.
getBankType
().
equals
(
question
.
getBankType
()))
{
throw
new
BusinessException
(
"试题不能跨职级题库和竞赛题库转移"
);
}
applyCompatibilityPath
(
question
,
target
);
libraryMapper
.
updateById
(
question
);
}
return
Boolean
.
TRUE
;
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
Boolean
batchDelete
(
TheoreticalLibraryBatchDTO
body
)
{
List
<
String
>
ids
=
requireBatchIds
(
body
==
null
?
null
:
body
.
getIds
());
ensureQuestionsExist
(
ids
);
if
(
libraryMapper
.
deleteBatchIds
(
ids
)
!=
ids
.
size
())
{
throw
new
BusinessException
(
"部分试题删除失败,操作已回滚"
);
}
return
Boolean
.
TRUE
;
}
/** 将节点转换为单节点响应;完整树由 tree 接口负责。 */
private
TheoreticalLibraryNodeVO
findNodeVO
(
String
id
)
{
TheoreticalLibraryNodeEntity
entity
=
requireNode
(
id
);
TheoreticalLibraryNodeVO
vo
=
new
TheoreticalLibraryNodeVO
();
BeanUtils
.
copyProperties
(
entity
,
vo
);
vo
.
setFullPath
(
path
(
entity
).
stream
().
map
(
TheoreticalLibraryNodeEntity:
:
getName
)
.
collect
(
Collectors
.
joining
(
" → "
)));
Long
directCount
=
libraryMapper
.
selectCount
(
new
LambdaQueryWrapper
<
TheoreticalLibraryEntity
>()
.
eq
(
TheoreticalLibraryEntity:
:
getNodeId
,
id
)
.
eq
(
TheoreticalLibraryEntity:
:
getIsProblem
,
true
));
vo
.
setQuestionCount
(
directCount
);
return
vo
;
}
/** 递归计算完整路径和子树题量。 */
private
long
decorateTree
(
TheoreticalLibraryNodeVO
node
,
String
parentPath
,
Map
<
String
,
Long
>
directCounts
)
{
String
currentPath
=
StringUtils
.
hasText
(
parentPath
)
?
parentPath
+
" → "
+
node
.
getName
()
:
node
.
getName
();
node
.
setFullPath
(
currentPath
);
node
.
getChildren
().
sort
(
Comparator
.
comparing
(
TheoreticalLibraryNodeVO:
:
getSortNo
,
Comparator
.
nullsLast
(
Integer:
:
compareTo
))
.
thenComparing
(
TheoreticalLibraryNodeVO:
:
getId
));
long
count
=
directCounts
.
getOrDefault
(
node
.
getId
(),
0L
);
for
(
TheoreticalLibraryNodeVO
child
:
node
.
getChildren
())
{
count
+=
decorateTree
(
child
,
currentPath
,
directCounts
);
}
node
.
setQuestionCount
(
count
);
return
count
;
}
/** 搜索树时保留匹配节点的完整祖先链,并复制节点防止破坏原树。 */
private
TheoreticalLibraryNodeVO
filterTree
(
TheoreticalLibraryNodeVO
source
,
String
keyword
)
{
List
<
TheoreticalLibraryNodeVO
>
matchedChildren
=
new
ArrayList
<>();
for
(
TheoreticalLibraryNodeVO
child
:
source
.
getChildren
())
{
TheoreticalLibraryNodeVO
matched
=
filterTree
(
child
,
keyword
);
if
(
matched
!=
null
)
{
matchedChildren
.
add
(
matched
);
}
}
boolean
selfMatched
=
source
.
getName
().
toLowerCase
(
Locale
.
ROOT
).
contains
(
keyword
)
||
source
.
getCode
().
toLowerCase
(
Locale
.
ROOT
).
contains
(
keyword
);
if
(!
selfMatched
&&
matchedChildren
.
isEmpty
())
{
return
null
;
}
TheoreticalLibraryNodeVO
copy
=
new
TheoreticalLibraryNodeVO
();
BeanUtils
.
copyProperties
(
source
,
copy
,
"children"
);
copy
.
setChildren
(
matchedChildren
);
return
copy
;
}
private
void
applyNodeFields
(
TheoreticalLibraryNodeEntity
entity
,
TheoreticalLibraryNodeSaveDTO
body
,
Integer
defaultSort
)
{
entity
.
setName
(
requireText
(
body
.
getName
(),
200
,
"节点名称"
));
entity
.
setCode
(
requireCode
(
body
.
getCode
()));
entity
.
setSortNo
(
body
.
getSortNo
()
==
null
?
(
defaultSort
==
null
?
10
:
defaultSort
)
:
Math
.
max
(
body
.
getSortNo
(),
0
));
entity
.
setStatus
(
body
.
getStatus
()
==
null
?
1
:
body
.
getStatus
());
requireStatus
(
entity
.
getStatus
());
entity
.
setRemark
(
trimOptional
(
body
.
getRemark
(),
500
,
"备注"
));
}
private
void
ensureNodeCodeUnique
(
TheoreticalLibraryNodeEntity
node
,
String
excludedId
)
{
LambdaQueryWrapper
<
TheoreticalLibraryNodeEntity
>
wrapper
=
new
LambdaQueryWrapper
<
TheoreticalLibraryNodeEntity
>()
.
eq
(
TheoreticalLibraryNodeEntity:
:
getBankType
,
node
.
getBankType
())
.
eq
(
TheoreticalLibraryNodeEntity:
:
getParentId
,
node
.
getParentId
())
.
eq
(
TheoreticalLibraryNodeEntity:
:
getCode
,
node
.
getCode
());
if
(
StringUtils
.
hasText
(
excludedId
))
{
wrapper
.
ne
(
TheoreticalLibraryNodeEntity:
:
getId
,
excludedId
);
}
if
(
nodeMapper
.
selectCount
(
wrapper
)
>
0
)
{
throw
new
BusinessException
(
"同一上级节点下编码已存在"
);
}
}
private
TheoreticalLibraryQuestionQueryDTO
prepareQuery
(
TheoreticalLibraryQuestionQueryDTO
query
)
{
TheoreticalLibraryQuestionQueryDTO
safe
=
query
==
null
?
new
TheoreticalLibraryQuestionQueryDTO
()
:
query
;
safe
.
setBankType
(
TheoreticalLibraryAdminConstants
.
normalizeBankType
(
safe
.
getBankType
()));
safe
.
setKeyword
(
trimOptional
(
safe
.
getKeyword
(),
200
,
"搜索关键字"
));
if
(
StringUtils
.
hasText
(
safe
.
getType
()))
{
safe
.
setType
(
TheoreticalLibraryAdminConstants
.
typeLabel
(
safe
.
getType
()));
}
if
(
safe
.
getStatus
()
!=
null
)
{
requireStatus
(
safe
.
getStatus
());
}
safe
.
setNodeIds
(
null
);
if
(
StringUtils
.
hasText
(
safe
.
getNodeId
()))
{
TheoreticalLibraryNodeEntity
selected
=
requireNode
(
safe
.
getNodeId
());
if
(!
safe
.
getBankType
().
equals
(
selected
.
getBankType
()))
{
throw
new
BusinessException
(
"筛选节点不属于当前题库"
);
}
safe
.
setNodeIds
(
descendantIds
(
selected
.
getId
(),
true
));
}
return
safe
;
}
private
TheoreticalLibraryEntity
prepareQuestion
(
TheoreticalLibraryQuestionSaveDTO
body
,
TheoreticalLibraryEntity
existing
)
{
if
(
body
==
null
)
{
throw
new
BusinessException
(
"试题信息不能为空"
);
}
TheoreticalLibraryNodeEntity
node
=
ensureEnabledTerminalNode
(
body
.
getNodeId
());
String
typeCode
=
TheoreticalLibraryAdminConstants
.
normalizeTypeCode
(
body
.
getType
());
String
difficulty
=
TheoreticalLibraryAdminConstants
.
normalizeDifficulty
(
body
.
getDifficulty
());
String
stem
=
requireText
(
body
.
getStem
(),
10000
,
"题干"
);
if
(
body
.
getScore
()
==
null
||
body
.
getScore
()
<=
0
||
body
.
getScore
()
>
1000
)
{
throw
new
BusinessException
(
"分值必须大于0且不超过1000"
);
}
int
status
=
body
.
getStatus
()
==
null
?
1
:
body
.
getStatus
();
requireStatus
(
status
);
TheoreticalLibraryEntity
entity
=
existing
==
null
?
new
TheoreticalLibraryEntity
()
:
existing
;
entity
.
setIsProblem
(
true
);
entity
.
setType
(
TheoreticalLibraryAdminConstants
.
typeLabel
(
typeCode
));
entity
.
setProblem
(
stem
);
entity
.
setScore
(
body
.
getScore
());
entity
.
setDifficulty
(
difficulty
);
entity
.
setStatus
(
status
);
entity
.
setParticipate
(!
Boolean
.
TRUE
.
equals
(
body
.
getNoExam
()));
entity
.
setAnalysis
(
trimOptional
(
body
.
getAnalysis
(),
10000
,
"解析"
));
entity
.
setKeywords
(
writeKeywords
(
body
.
getKeywords
()));
entity
.
setOptionA
(
null
);
entity
.
setOptionB
(
null
);
entity
.
setOptionC
(
null
);
entity
.
setOptionD
(
null
);
entity
.
setOptionE
(
null
);
entity
.
setAnswer
(
null
);
applyAnswer
(
entity
,
typeCode
,
body
);
applyCompatibilityPath
(
entity
,
node
);
return
entity
;
}
/**
* 按题型校验答案并写入旧 A-E 列。限制最多五个选项是为了保证随机组卷复制到
* theoretical_paper_detail 后仍能完整作答,而不是只在管理页面中看起来正确。
*/
private
void
applyAnswer
(
TheoreticalLibraryEntity
entity
,
String
typeCode
,
TheoreticalLibraryQuestionSaveDTO
body
)
{
if
(
"SINGLE"
.
equals
(
typeCode
)
||
"MULTI"
.
equals
(
typeCode
))
{
List
<
TheoreticalLibraryOptionDTO
>
options
=
body
.
getOptions
();
if
(
options
==
null
||
options
.
size
()
<
2
||
options
.
size
()
>
5
)
{
throw
new
BusinessException
(
"选择题必须包含2至5个选项"
);
}
String
[]
values
=
new
String
[
5
];
StringBuilder
answer
=
new
StringBuilder
();
int
correctCount
=
0
;
for
(
int
i
=
0
;
i
<
options
.
size
();
i
++)
{
TheoreticalLibraryOptionDTO
option
=
options
.
get
(
i
);
values
[
i
]
=
requireText
(
option
==
null
?
null
:
option
.
getText
(),
2000
,
"选项"
+
(
char
)
(
'A'
+
i
));
if
(
Boolean
.
TRUE
.
equals
(
option
.
getCorrect
()))
{
correctCount
++;
answer
.
append
((
char
)
(
'A'
+
i
));
}
}
if
(
"SINGLE"
.
equals
(
typeCode
)
&&
correctCount
!=
1
)
{
throw
new
BusinessException
(
"单选题必须有且仅有一个正确答案"
);
}
if
(
"MULTI"
.
equals
(
typeCode
)
&&
correctCount
<
2
)
{
throw
new
BusinessException
(
"多选题至少需要两个正确答案"
);
}
entity
.
setOptionA
(
values
[
0
]);
entity
.
setOptionB
(
values
[
1
]);
entity
.
setOptionC
(
values
[
2
]);
entity
.
setOptionD
(
values
[
3
]);
entity
.
setOptionE
(
values
[
4
]);
entity
.
setAnswer
(
answer
.
toString
());
return
;
}
String
answer
=
requireText
(
body
.
getAnswer
(),
10000
,
"标准答案"
);
if
(
"JUDGE"
.
equals
(
typeCode
))
{
if
(
"对"
.
equals
(
answer
)
||
"正确"
.
equals
(
answer
)
||
"√"
.
equals
(
answer
))
{
answer
=
"√"
;
}
else
if
(
"错"
.
equals
(
answer
)
||
"错误"
.
equals
(
answer
)
||
"×"
.
equals
(
answer
))
{
answer
=
"×"
;
}
else
{
throw
new
BusinessException
(
"判断题答案仅支持正确或错误"
);
}
}
entity
.
setAnswer
(
answer
);
}
/** 根据固定节点类型生成旧链路所需的 scope 和四级名称。 */
private
void
applyCompatibilityPath
(
TheoreticalLibraryEntity
question
,
TheoreticalLibraryNodeEntity
leaf
)
{
List
<
TheoreticalLibraryNodeEntity
>
path
=
path
(
leaf
);
if
(
TheoreticalLibraryAdminConstants
.
BANK_JOB
.
equals
(
leaf
.
getBankType
()))
{
if
(
path
.
size
()
!=
TheoreticalLibraryAdminConstants
.
JOB_NODE_TYPES
.
size
())
{
throw
new
BusinessException
(
"职级题库题目必须绑定到完整六级知识点"
);
}
question
.
setScope
(
path
.
get
(
0
).
getName
()
+
path
.
get
(
1
).
getName
());
question
.
setFirstLevelName
(
path
.
get
(
2
).
getName
());
question
.
setSecondLevelName
(
path
.
get
(
3
).
getName
());
question
.
setThirdLevelName
(
path
.
get
(
4
).
getName
());
question
.
setFourthLevelName
(
path
.
get
(
5
).
getName
());
question
.
setLev
(
parseLevel
(
path
.
get
(
1
).
getName
()));
}
else
{
if
(
path
.
size
()
!=
TheoreticalLibraryAdminConstants
.
COMP_NODE_TYPES
.
size
())
{
throw
new
BusinessException
(
"竞赛题库题目必须绑定到完整三级方向"
);
}
question
.
setScope
(
"技能竞赛"
);
question
.
setFirstLevelName
(
path
.
get
(
0
).
getName
());
question
.
setSecondLevelName
(
path
.
get
(
1
).
getName
());
question
.
setThirdLevelName
(
path
.
get
(
2
).
getName
());
question
.
setFourthLevelName
(
null
);
question
.
setLev
(
0
);
}
question
.
setBankType
(
leaf
.
getBankType
());
question
.
setNodeId
(
leaf
.
getId
());
}
private
void
decorateQuestion
(
TheoreticalLibraryQuestionVO
vo
)
{
vo
.
setStem
(
vo
.
getProblem
());
String
typeCode
=
TheoreticalLibraryAdminConstants
.
typeCodeFromDatabase
(
vo
.
getType
());
vo
.
setTypeCode
(
typeCode
);
vo
.
setTypeLabel
(
TheoreticalLibraryAdminConstants
.
typeLabel
(
typeCode
));
vo
.
setDifficultyLabel
(
TheoreticalLibraryAdminConstants
.
difficultyLabel
(
vo
.
getDifficulty
()));
vo
.
setNoExam
(!
Boolean
.
TRUE
.
equals
(
vo
.
getParticipate
()));
vo
.
setKeywordList
(
readKeywords
(
vo
.
getKeywords
()));
vo
.
setOptions
(
readOptions
(
vo
));
vo
.
setAnswerText
(
displayAnswer
(
vo
));
if
(
StringUtils
.
hasText
(
vo
.
getNodeId
()))
{
TheoreticalLibraryNodeEntity
leaf
=
nodeMapper
.
selectById
(
vo
.
getNodeId
());
if
(
leaf
!=
null
)
{
vo
.
setFullPath
(
path
(
leaf
).
stream
().
map
(
TheoreticalLibraryNodeEntity:
:
getName
)
.
collect
(
Collectors
.
joining
(
" → "
)));
}
}
}
private
List
<
TheoreticalLibraryOptionDTO
>
readOptions
(
TheoreticalLibraryEntity
entity
)
{
String
[]
values
=
{
entity
.
getOptionA
(),
entity
.
getOptionB
(),
entity
.
getOptionC
(),
entity
.
getOptionD
(),
entity
.
getOptionE
()};
Set
<
Character
>
correct
=
entity
.
getAnswer
()
==
null
?
Collections
.
emptySet
()
:
entity
.
getAnswer
().
chars
().
mapToObj
(
value
->
(
char
)
value
)
.
collect
(
Collectors
.
toSet
());
List
<
TheoreticalLibraryOptionDTO
>
options
=
new
ArrayList
<>();
for
(
int
i
=
0
;
i
<
values
.
length
;
i
++)
{
if
(!
StringUtils
.
hasText
(
values
[
i
]))
{
continue
;
}
TheoreticalLibraryOptionDTO
option
=
new
TheoreticalLibraryOptionDTO
();
option
.
setLabel
(
String
.
valueOf
((
char
)
(
'A'
+
i
)));
option
.
setText
(
values
[
i
]);
option
.
setCorrect
(
correct
.
contains
((
char
)
(
'A'
+
i
)));
options
.
add
(
option
);
}
return
options
;
}
private
String
displayAnswer
(
TheoreticalLibraryEntity
entity
)
{
if
(
entity
.
getAnswer
()
==
null
)
{
return
null
;
}
if
(
"√"
.
equals
(
entity
.
getAnswer
()))
{
return
"正确"
;
}
if
(
"×"
.
equals
(
entity
.
getAnswer
()))
{
return
"错误"
;
}
return
entity
.
getAnswer
();
}
private
TheoreticalLibraryNodeEntity
ensureEnabledTerminalNode
(
String
nodeId
)
{
TheoreticalLibraryNodeEntity
leaf
=
requireNode
(
nodeId
);
List
<
String
>
types
=
TheoreticalLibraryAdminConstants
.
nodeTypes
(
leaf
.
getBankType
());
if
(!
types
.
get
(
types
.
size
()
-
1
).
equals
(
leaf
.
getNodeType
()))
{
throw
new
BusinessException
(
"试题只能绑定到末级节点"
);
}
for
(
TheoreticalLibraryNodeEntity
node
:
path
(
leaf
))
{
if
(!
Integer
.
valueOf
(
1
).
equals
(
node
.
getStatus
()))
{
throw
new
BusinessException
(
"所属层级存在禁用节点,不能保存或转移试题"
);
}
}
return
leaf
;
}
private
List
<
TheoreticalLibraryNodeEntity
>
path
(
TheoreticalLibraryNodeEntity
leaf
)
{
List
<
TheoreticalLibraryNodeEntity
>
result
=
new
ArrayList
<>();
Set
<
String
>
visited
=
new
HashSet
<>();
TheoreticalLibraryNodeEntity
current
=
leaf
;
while
(
current
!=
null
)
{
if
(!
visited
.
add
(
current
.
getId
()))
{
throw
new
BusinessException
(
"题库层级存在循环引用,请先修复数据"
);
}
result
.
add
(
current
);
if
(
TheoreticalLibraryAdminConstants
.
ROOT_PARENT_ID
.
equals
(
current
.
getParentId
()))
{
break
;
}
current
=
nodeMapper
.
selectById
(
current
.
getParentId
());
if
(
current
==
null
)
{
throw
new
BusinessException
(
"题库层级链不完整,请先修复上级节点"
);
}
}
Collections
.
reverse
(
result
);
return
result
;
}
private
List
<
String
>
descendantIds
(
String
rootId
,
boolean
includeRoot
)
{
TheoreticalLibraryNodeEntity
root
=
requireNode
(
rootId
);
List
<
TheoreticalLibraryNodeEntity
>
all
=
flatNodes
(
root
.
getBankType
());
Map
<
String
,
List
<
String
>>
children
=
new
HashMap
<>();
for
(
TheoreticalLibraryNodeEntity
node
:
all
)
{
children
.
computeIfAbsent
(
node
.
getParentId
(),
key
->
new
ArrayList
<>()).
add
(
node
.
getId
());
}
List
<
String
>
result
=
new
ArrayList
<>();
collectDescendants
(
rootId
,
children
,
result
);
if
(!
includeRoot
)
{
result
.
remove
(
rootId
);
}
return
result
;
}
private
void
collectDescendants
(
String
id
,
Map
<
String
,
List
<
String
>>
children
,
List
<
String
>
result
)
{
if
(
result
.
contains
(
id
))
{
throw
new
BusinessException
(
"题库层级存在循环引用,请先修复数据"
);
}
result
.
add
(
id
);
for
(
String
child
:
children
.
getOrDefault
(
id
,
Collections
.
emptyList
()))
{
collectDescendants
(
child
,
children
,
result
);
}
}
private
void
synchronizeQuestionsUnderNode
(
String
nodeId
)
{
List
<
String
>
nodeIds
=
descendantIds
(
nodeId
,
true
);
List
<
TheoreticalLibraryEntity
>
questions
=
libraryMapper
.
selectList
(
new
LambdaQueryWrapper
<
TheoreticalLibraryEntity
>()
.
in
(
TheoreticalLibraryEntity:
:
getNodeId
,
nodeIds
)
.
eq
(
TheoreticalLibraryEntity:
:
getIsProblem
,
true
));
for
(
TheoreticalLibraryEntity
question
:
questions
)
{
TheoreticalLibraryNodeEntity
leaf
=
nodeMapper
.
selectById
(
question
.
getNodeId
());
if
(
leaf
!=
null
)
{
applyCompatibilityPath
(
question
,
leaf
);
libraryMapper
.
updateById
(
question
);
}
}
}
private
void
ensureQuestionsExist
(
List
<
String
>
ids
)
{
Long
count
=
libraryMapper
.
selectCount
(
new
LambdaQueryWrapper
<
TheoreticalLibraryEntity
>()
.
in
(
TheoreticalLibraryEntity:
:
getId
,
ids
)
.
eq
(
TheoreticalLibraryEntity:
:
getIsProblem
,
true
));
if
(
count
==
null
||
count
.
intValue
()
!=
ids
.
size
())
{
throw
new
BusinessException
(
"所选试题包含不存在或已删除的数据"
);
}
}
private
List
<
TheoreticalLibraryEntity
>
lockQuestions
(
List
<
String
>
ids
)
{
List
<
TheoreticalLibraryEntity
>
result
=
new
ArrayList
<>();
for
(
String
id
:
ids
)
{
TheoreticalLibraryEntity
entity
=
libraryMapper
.
selectQuestionForUpdate
(
id
);
if
(
entity
==
null
)
{
throw
new
BusinessException
(
"所选试题包含不存在或已删除的数据"
);
}
result
.
add
(
entity
);
}
return
result
;
}
private
TheoreticalLibraryEntity
requireQuestion
(
String
id
,
boolean
lock
)
{
String
normalizedId
=
requireText
(
id
,
64
,
"试题ID"
);
TheoreticalLibraryEntity
entity
=
lock
?
libraryMapper
.
selectQuestionForUpdate
(
normalizedId
)
:
libraryMapper
.
selectOne
(
new
LambdaQueryWrapper
<
TheoreticalLibraryEntity
>()
.
eq
(
TheoreticalLibraryEntity:
:
getId
,
normalizedId
)
.
eq
(
TheoreticalLibraryEntity:
:
getIsProblem
,
true
));
if
(
entity
==
null
)
{
throw
new
BusinessException
(
"试题不存在或已删除"
);
}
return
entity
;
}
private
TheoreticalLibraryNodeEntity
requireNode
(
String
id
)
{
String
normalizedId
=
requireText
(
id
,
64
,
"节点ID"
);
TheoreticalLibraryNodeEntity
node
=
nodeMapper
.
selectById
(
normalizedId
);
if
(
node
==
null
)
{
throw
new
BusinessException
(
"层级节点不存在或已删除"
);
}
return
node
;
}
private
TheoreticalLibraryNodeEntity
parent
(
String
parentId
)
{
return
TheoreticalLibraryAdminConstants
.
ROOT_PARENT_ID
.
equals
(
parentId
)
?
null
:
requireNode
(
parentId
);
}
private
String
normalizeParentId
(
String
parentId
)
{
return
StringUtils
.
hasText
(
parentId
)
?
parentId
.
trim
()
:
TheoreticalLibraryAdminConstants
.
ROOT_PARENT_ID
;
}
private
List
<
String
>
requireBatchIds
(
List
<
String
>
ids
)
{
if
(
ids
==
null
||
ids
.
isEmpty
())
{
throw
new
BusinessException
(
"请至少选择一道试题"
);
}
List
<
String
>
normalized
=
ids
.
stream
().
filter
(
StringUtils:
:
hasText
)
.
map
(
String:
:
trim
).
distinct
().
collect
(
Collectors
.
toList
());
if
(
normalized
.
size
()
!=
ids
.
size
())
{
throw
new
BusinessException
(
"试题ID不能为空或重复"
);
}
if
(
normalized
.
size
()
>
TheoreticalLibraryAdminConstants
.
MAX_BATCH_SIZE
)
{
throw
new
BusinessException
(
"单次批量操作不能超过5000道试题"
);
}
return
normalized
;
}
private
void
requireStatus
(
Integer
status
)
{
if
(
status
==
null
||
(
status
!=
0
&&
status
!=
1
))
{
throw
new
BusinessException
(
"状态仅支持0或1"
);
}
}
private
String
requireCode
(
String
code
)
{
String
value
=
requireText
(
code
,
64
,
"节点编码"
).
toUpperCase
(
Locale
.
ROOT
);
if
(!
value
.
matches
(
"[A-Z0-9][A-Z0-9_-]*"
))
{
throw
new
BusinessException
(
"节点编码仅支持英文字母、数字、下划线和短横线"
);
}
return
value
;
}
private
String
requireText
(
String
value
,
int
maxLength
,
String
field
)
{
if
(!
StringUtils
.
hasText
(
value
))
{
throw
new
BusinessException
(
field
+
"不能为空"
);
}
String
result
=
value
.
trim
();
if
(
result
.
length
()
>
maxLength
)
{
throw
new
BusinessException
(
field
+
"不能超过"
+
maxLength
+
"个字符"
);
}
return
result
;
}
private
String
trimOptional
(
String
value
,
int
maxLength
,
String
field
)
{
if
(!
StringUtils
.
hasText
(
value
))
{
return
null
;
}
String
result
=
value
.
trim
();
if
(
result
.
length
()
>
maxLength
)
{
throw
new
BusinessException
(
field
+
"不能超过"
+
maxLength
+
"个字符"
);
}
return
result
;
}
private
String
writeKeywords
(
List
<
String
>
keywords
)
{
List
<
String
>
normalized
=
keywords
==
null
?
Collections
.
emptyList
()
:
keywords
.
stream
().
filter
(
StringUtils:
:
hasText
).
map
(
String:
:
trim
).
distinct
()
.
limit
(
20
).
collect
(
Collectors
.
toList
());
try
{
return
objectMapper
.
writeValueAsString
(
normalized
);
}
catch
(
JsonProcessingException
e
)
{
throw
new
BusinessException
(
"关键词格式处理失败"
);
}
}
private
List
<
String
>
readKeywords
(
String
json
)
{
if
(!
StringUtils
.
hasText
(
json
))
{
return
Collections
.
emptyList
();
}
try
{
return
objectMapper
.
readValue
(
json
,
new
TypeReference
<
List
<
String
>>()
{
});
}
catch
(
Exception
ignored
)
{
// 兼容人工维护过的旧数据:非 JSON 时按英文或中文逗号拆分展示。
String
[]
values
=
json
.
split
(
"[,,]"
);
List
<
String
>
result
=
new
ArrayList
<>();
for
(
String
value
:
values
)
{
if
(
StringUtils
.
hasText
(
value
))
{
result
.
add
(
value
.
trim
());
}
}
return
result
;
}
}
private
int
parseLevel
(
String
levelName
)
{
String
[]
chinese
=
{
"一"
,
"二"
,
"三"
,
"四"
,
"五"
};
for
(
int
i
=
0
;
i
<
chinese
.
length
;
i
++)
{
if
(
levelName
.
contains
(
chinese
[
i
])
||
levelName
.
contains
(
String
.
valueOf
(
i
+
1
)))
{
return
i
+
1
;
}
}
return
0
;
}
private
String
generateQuestionCode
()
{
return
"Q"
+
QUESTION_CODE_TIME
.
format
(
LocalDateTime
.
now
())
+
UUID
.
randomUUID
().
toString
().
replace
(
"-"
,
""
).
substring
(
0
,
6
).
toUpperCase
();
}
private
String
displayName
(
UserEntity
user
)
{
if
(
user
==
null
)
{
return
"系统迁移"
;
}
if
(
StringUtils
.
hasText
(
user
.
getNickName
()))
{
return
user
.
getNickName
().
trim
();
}
if
(
StringUtils
.
hasText
(
user
.
getUsername
()))
{
return
user
.
getUsername
().
trim
();
}
if
(
StringUtils
.
hasText
(
user
.
getPhoneNumber
()))
{
return
user
.
getPhoneNumber
().
trim
();
}
return
user
.
getId
();
}
}
practical-business/src/main/java/com/platform/business/service/impl/TheoreticalLibraryExcelServiceImpl.java
0 → 100644
View file @
9fc77652
package
com.platform.business.service.impl
;
import
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
;
import
com.platform.business.constant.TheoreticalLibraryAdminConstants
;
import
com.platform.business.mapper.TheoreticalLibraryMapper
;
import
com.platform.business.model.dto.TheoreticalLibraryExportDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryNodeSaveDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryOptionDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryQuestionQueryDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryQuestionSaveDTO
;
import
com.platform.business.model.entity.BsFileEntity
;
import
com.platform.business.model.entity.TheoreticalLibraryEntity
;
import
com.platform.business.model.entity.TheoreticalLibraryNodeEntity
;
import
com.platform.business.model.entity.UserEntity
;
import
com.platform.business.model.vo.TheoreticalLibraryImportResultVO
;
import
com.platform.business.model.vo.TheoreticalLibraryQuestionVO
;
import
com.platform.business.service.BsFileService
;
import
com.platform.business.service.TheoreticalLibraryAdminService
;
import
com.platform.business.service.TheoreticalLibraryExcelService
;
import
com.platform.exception.BusinessException
;
import
org.apache.poi.ss.usermodel.Cell
;
import
org.apache.poi.ss.usermodel.CellStyle
;
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.usermodel.Workbook
;
import
org.apache.poi.xssf.usermodel.XSSFWorkbook
;
import
org.springframework.stereotype.Service
;
import
org.springframework.util.StringUtils
;
import
org.springframework.web.multipart.MultipartFile
;
import
javax.annotation.Resource
;
import
javax.servlet.http.HttpServletResponse
;
import
java.io.ByteArrayOutputStream
;
import
java.io.IOException
;
import
java.net.URLEncoder
;
import
java.nio.charset.StandardCharsets
;
import
java.util.ArrayList
;
import
java.util.Arrays
;
import
java.util.Collections
;
import
java.util.HashSet
;
import
java.util.List
;
import
java.util.Locale
;
import
java.util.Map
;
import
java.util.Set
;
import
java.util.stream.Collectors
;
/**
* 理论题库 Excel 实现。
*
* <p>导入采用“逐行校验、有效行提交、失败行生成错误文件”的页面口径。结构模板要求父节点
* 出现在子节点之前,这样一份文件既可以增量追加,也可以按完整编码路径确定覆盖目标。</p>
*/
@Service
public
class
TheoreticalLibraryExcelServiceImpl
implements
TheoreticalLibraryExcelService
{
private
static
final
List
<
String
>
STRUCTURE_HEADERS
=
Arrays
.
asList
(
"节点类型"
,
"父节点编码路径"
,
"名称"
,
"编码"
,
"排序号"
,
"状态"
,
"备注"
);
private
static
final
List
<
String
>
QUESTION_HEADERS
=
Arrays
.
asList
(
"题号"
,
"节点编码路径"
,
"题型"
,
"分值"
,
"难度"
,
"状态"
,
"不参与组卷"
,
"关键词"
,
"题干"
,
"选项A"
,
"选项B"
,
"选项C"
,
"选项D"
,
"选项E"
,
"答案"
,
"解析"
);
@Resource
private
TheoreticalLibraryAdminService
adminService
;
@Resource
private
TheoreticalLibraryMapper
libraryMapper
;
@Resource
private
BsFileService
bsFileService
;
@Override
public
void
template
(
String
dataType
,
String
bankType
,
HttpServletResponse
response
)
{
String
type
=
normalizeDataType
(
dataType
);
TheoreticalLibraryAdminConstants
.
normalizeBankType
(
bankType
);
List
<
String
>
headers
=
"STRUCTURE"
.
equals
(
type
)
?
STRUCTURE_HEADERS
:
QUESTION_HEADERS
;
try
(
Workbook
workbook
=
new
XSSFWorkbook
())
{
Sheet
sheet
=
workbook
.
createSheet
(
"导入模板"
);
writeHeader
(
sheet
,
headers
,
workbook
);
Row
example
=
sheet
.
createRow
(
1
);
if
(
"STRUCTURE"
.
equals
(
type
))
{
example
.
createCell
(
0
).
setCellValue
(
"CRAFT"
);
example
.
createCell
(
2
).
setCellValue
(
"污水"
);
example
.
createCell
(
3
).
setCellValue
(
"CRAFT-WATER"
);
example
.
createCell
(
4
).
setCellValue
(
10
);
example
.
createCell
(
5
).
setCellValue
(
"启用"
);
}
else
{
example
.
createCell
(
0
).
setCellValue
(
"Q-EXAMPLE-001"
);
example
.
createCell
(
1
).
setCellValue
(
"CRAFT-WATER/LEVEL-1/CH-01/SEC-01/TOPIC-01/POINT-01"
);
example
.
createCell
(
2
).
setCellValue
(
"SINGLE"
);
example
.
createCell
(
3
).
setCellValue
(
2
);
example
.
createCell
(
4
).
setCellValue
(
"MEDIUM"
);
example
.
createCell
(
5
).
setCellValue
(
"启用"
);
example
.
createCell
(
6
).
setCellValue
(
"否"
);
example
.
createCell
(
8
).
setCellValue
(
"示例题干"
);
example
.
createCell
(
9
).
setCellValue
(
"选项A"
);
example
.
createCell
(
10
).
setCellValue
(
"选项B"
);
example
.
createCell
(
14
).
setCellValue
(
"A"
);
}
autoWidth
(
sheet
,
headers
.
size
());
writeWorkbook
(
workbook
,
response
,
"理论题库-"
+
type
+
"-导入模板.xlsx"
);
}
catch
(
IOException
e
)
{
throw
new
BusinessException
(
"导入模板生成失败"
);
}
}
@Override
public
TheoreticalLibraryImportResultVO
importData
(
String
dataType
,
String
bankType
,
String
mode
,
MultipartFile
file
,
UserEntity
admin
)
{
String
type
=
normalizeDataType
(
dataType
);
String
normalizedBankType
=
TheoreticalLibraryAdminConstants
.
normalizeBankType
(
bankType
);
String
normalizedMode
=
normalizeMode
(
mode
);
validateImportFile
(
file
);
List
<
ImportError
>
errors
=
new
ArrayList
<>();
int
success
;
try
(
Workbook
workbook
=
new
XSSFWorkbook
(
file
.
getInputStream
()))
{
Sheet
sheet
=
workbook
.
getSheetAt
(
0
);
success
=
"STRUCTURE"
.
equals
(
type
)
?
importStructures
(
sheet
,
normalizedBankType
,
normalizedMode
,
admin
,
errors
)
:
importQuestions
(
sheet
,
normalizedBankType
,
normalizedMode
,
admin
,
errors
);
}
catch
(
IOException
e
)
{
throw
new
BusinessException
(
"Excel文件读取失败,请确认文件未损坏"
);
}
TheoreticalLibraryImportResultVO
result
=
new
TheoreticalLibraryImportResultVO
();
result
.
setSuccessCount
(
success
);
result
.
setFailureCount
(
errors
.
size
());
if
(!
errors
.
isEmpty
())
{
BsFileEntity
errorFile
=
bsFileService
.
saveGeneratedFile
(
"理论题库导入错误明细.xlsx"
,
createErrorWorkbook
(
errors
));
result
.
setErrorFileId
(
errorFile
.
getId
());
}
return
result
;
}
@Override
public
void
export
(
TheoreticalLibraryExportDTO
body
,
HttpServletResponse
response
)
{
if
(
body
==
null
)
{
throw
new
BusinessException
(
"导出配置不能为空"
);
}
String
type
=
normalizeDataType
(
body
.
getDataType
());
String
bankType
=
TheoreticalLibraryAdminConstants
.
normalizeBankType
(
body
.
getBankType
());
String
scope
=
body
.
getScope
()
==
null
?
"ALL"
:
body
.
getScope
().
trim
().
toUpperCase
(
Locale
.
ROOT
);
if
(!
"ALL"
.
equals
(
scope
)
&&
!
"FILTERED"
.
equals
(
scope
))
{
throw
new
BusinessException
(
"导出范围仅支持ALL或FILTERED"
);
}
try
(
Workbook
workbook
=
new
XSSFWorkbook
())
{
if
(
"STRUCTURE"
.
equals
(
type
))
{
exportStructures
(
workbook
,
bankType
,
scope
,
body
.
getQuery
());
}
else
{
exportQuestions
(
workbook
,
bankType
,
scope
,
body
.
getQuery
(),
!
Boolean
.
FALSE
.
equals
(
body
.
getIncludeAnswer
()));
}
writeWorkbook
(
workbook
,
response
,
"理论题库-"
+
type
+
"-导出.xlsx"
);
}
catch
(
IOException
e
)
{
throw
new
BusinessException
(
"题库导出失败"
);
}
}
@Override
public
void
downloadImportErrors
(
Integer
fileId
)
{
if
(
fileId
==
null
)
{
throw
new
BusinessException
(
"错误文件ID不能为空"
);
}
bsFileService
.
downloadFile
(
fileId
);
}
private
int
importStructures
(
Sheet
sheet
,
String
bankType
,
String
mode
,
UserEntity
admin
,
List
<
ImportError
>
errors
)
{
requireHeaders
(
sheet
,
STRUCTURE_HEADERS
);
int
success
=
0
;
for
(
int
rowIndex
=
1
;
rowIndex
<=
sheet
.
getLastRowNum
();
rowIndex
++)
{
Row
row
=
sheet
.
getRow
(
rowIndex
);
if
(
emptyRow
(
row
,
STRUCTURE_HEADERS
.
size
()))
{
continue
;
}
try
{
String
nodeType
=
cell
(
row
,
0
).
toUpperCase
(
Locale
.
ROOT
);
String
parentPath
=
cell
(
row
,
1
);
String
parentId
=
StringUtils
.
hasText
(
parentPath
)
?
resolveNodePath
(
bankType
,
parentPath
,
false
).
getId
()
:
TheoreticalLibraryAdminConstants
.
ROOT_PARENT_ID
;
int
level
=
StringUtils
.
hasText
(
parentPath
)
?
parentPath
.
split
(
"/"
).
length
:
0
;
List
<
String
>
expectedTypes
=
TheoreticalLibraryAdminConstants
.
nodeTypes
(
bankType
);
if
(
level
>=
expectedTypes
.
size
()
||
!
expectedTypes
.
get
(
level
).
equals
(
nodeType
))
{
throw
new
BusinessException
(
"节点类型与父节点层级不匹配"
);
}
String
code
=
cell
(
row
,
3
).
toUpperCase
(
Locale
.
ROOT
);
TheoreticalLibraryNodeEntity
existing
=
findChild
(
bankType
,
parentId
,
code
);
TheoreticalLibraryNodeSaveDTO
save
=
new
TheoreticalLibraryNodeSaveDTO
();
save
.
setBankType
(
bankType
);
save
.
setParentId
(
parentId
);
save
.
setName
(
cell
(
row
,
2
));
save
.
setCode
(
code
);
save
.
setSortNo
(
integerCell
(
row
,
4
,
10
));
save
.
setStatus
(
statusCell
(
row
,
5
));
save
.
setRemark
(
cell
(
row
,
6
));
if
(
existing
==
null
)
{
adminService
.
createNode
(
save
,
admin
);
}
else
if
(
"OVERWRITE"
.
equals
(
mode
))
{
adminService
.
updateNode
(
existing
.
getId
(),
save
);
}
else
{
throw
new
BusinessException
(
"同路径节点编码已存在"
);
}
success
++;
}
catch
(
Exception
e
)
{
errors
.
add
(
new
ImportError
(
rowIndex
+
1
,
message
(
e
),
rowText
(
row
,
STRUCTURE_HEADERS
.
size
())));
}
}
return
success
;
}
private
int
importQuestions
(
Sheet
sheet
,
String
bankType
,
String
mode
,
UserEntity
admin
,
List
<
ImportError
>
errors
)
{
requireHeaders
(
sheet
,
QUESTION_HEADERS
);
int
success
=
0
;
for
(
int
rowIndex
=
1
;
rowIndex
<=
sheet
.
getLastRowNum
();
rowIndex
++)
{
Row
row
=
sheet
.
getRow
(
rowIndex
);
if
(
emptyRow
(
row
,
QUESTION_HEADERS
.
size
()))
{
continue
;
}
try
{
String
questionCode
=
cell
(
row
,
0
).
toUpperCase
(
Locale
.
ROOT
);
if
(!
StringUtils
.
hasText
(
questionCode
))
{
throw
new
BusinessException
(
"题号不能为空"
);
}
TheoreticalLibraryNodeEntity
leaf
=
resolveNodePath
(
bankType
,
cell
(
row
,
1
),
true
);
TheoreticalLibraryQuestionSaveDTO
save
=
questionFromRow
(
row
,
leaf
.
getId
());
TheoreticalLibraryEntity
existing
=
libraryMapper
.
selectOne
(
new
LambdaQueryWrapper
<
TheoreticalLibraryEntity
>()
.
eq
(
TheoreticalLibraryEntity:
:
getBankType
,
bankType
)
.
eq
(
TheoreticalLibraryEntity:
:
getCode
,
questionCode
)
.
eq
(
TheoreticalLibraryEntity:
:
getIsProblem
,
true
));
if
(
existing
==
null
)
{
TheoreticalLibraryQuestionVO
created
=
adminService
.
createQuestion
(
save
,
admin
);
TheoreticalLibraryEntity
codeUpdate
=
new
TheoreticalLibraryEntity
();
codeUpdate
.
setId
(
created
.
getId
());
codeUpdate
.
setCode
(
questionCode
);
if
(
libraryMapper
.
updateById
(
codeUpdate
)
!=
1
)
{
// 创建和题号覆盖是两个独立服务调用;覆盖失败时立即补偿删除,避免脏题残留。
adminService
.
deleteQuestion
(
created
.
getId
());
throw
new
BusinessException
(
"导入题号保存失败"
);
}
}
else
if
(
"OVERWRITE"
.
equals
(
mode
))
{
adminService
.
updateQuestion
(
existing
.
getId
(),
save
);
}
else
{
throw
new
BusinessException
(
"题号已存在"
);
}
success
++;
}
catch
(
Exception
e
)
{
errors
.
add
(
new
ImportError
(
rowIndex
+
1
,
message
(
e
),
rowText
(
row
,
QUESTION_HEADERS
.
size
())));
}
}
return
success
;
}
private
TheoreticalLibraryQuestionSaveDTO
questionFromRow
(
Row
row
,
String
nodeId
)
{
TheoreticalLibraryQuestionSaveDTO
save
=
new
TheoreticalLibraryQuestionSaveDTO
();
save
.
setNodeId
(
nodeId
);
save
.
setType
(
cell
(
row
,
2
));
save
.
setScore
(
doubleCell
(
row
,
3
));
save
.
setDifficulty
(
cell
(
row
,
4
));
save
.
setStatus
(
statusCell
(
row
,
5
));
save
.
setNoExam
(
booleanCell
(
row
,
6
));
String
keywords
=
cell
(
row
,
7
);
save
.
setKeywords
(
StringUtils
.
hasText
(
keywords
)
?
Arrays
.
stream
(
keywords
.
split
(
"[,,]"
)).
map
(
String:
:
trim
)
.
filter
(
StringUtils:
:
hasText
).
collect
(
Collectors
.
toList
())
:
Collections
.
emptyList
());
save
.
setStem
(
cell
(
row
,
8
));
save
.
setAnalysis
(
cell
(
row
,
15
));
String
typeCode
=
TheoreticalLibraryAdminConstants
.
normalizeTypeCode
(
save
.
getType
());
if
(
"SINGLE"
.
equals
(
typeCode
)
||
"MULTI"
.
equals
(
typeCode
))
{
String
answer
=
cell
(
row
,
14
).
toUpperCase
(
Locale
.
ROOT
);
List
<
TheoreticalLibraryOptionDTO
>
options
=
new
ArrayList
<>();
for
(
int
i
=
0
;
i
<
5
;
i
++)
{
String
text
=
cell
(
row
,
9
+
i
);
if
(!
StringUtils
.
hasText
(
text
))
{
continue
;
}
TheoreticalLibraryOptionDTO
option
=
new
TheoreticalLibraryOptionDTO
();
option
.
setLabel
(
String
.
valueOf
((
char
)
(
'A'
+
i
)));
option
.
setText
(
text
);
option
.
setCorrect
(
answer
.
indexOf
((
char
)
(
'A'
+
i
))
>=
0
);
options
.
add
(
option
);
}
save
.
setOptions
(
options
);
}
else
{
save
.
setAnswer
(
cell
(
row
,
14
));
}
return
save
;
}
private
void
exportStructures
(
Workbook
workbook
,
String
bankType
,
String
scope
,
TheoreticalLibraryQuestionQueryDTO
query
)
{
Sheet
sheet
=
workbook
.
createSheet
(
"层级结构"
);
writeHeader
(
sheet
,
STRUCTURE_HEADERS
,
workbook
);
List
<
TheoreticalLibraryNodeEntity
>
nodes
=
adminService
.
flatNodes
(
bankType
);
Map
<
String
,
TheoreticalLibraryNodeEntity
>
map
=
nodes
.
stream
().
collect
(
Collectors
.
toMap
(
TheoreticalLibraryNodeEntity:
:
getId
,
value
->
value
));
if
(
"FILTERED"
.
equals
(
scope
)
&&
query
!=
null
&&
StringUtils
.
hasText
(
query
.
getNodeId
()))
{
Set
<
String
>
included
=
new
HashSet
<>();
included
.
add
(
query
.
getNodeId
());
boolean
changed
;
do
{
changed
=
false
;
for
(
TheoreticalLibraryNodeEntity
node
:
nodes
)
{
if
(
included
.
contains
(
node
.
getParentId
())
&&
included
.
add
(
node
.
getId
()))
{
changed
=
true
;
}
}
}
while
(
changed
);
nodes
=
nodes
.
stream
().
filter
(
node
->
included
.
contains
(
node
.
getId
()))
.
collect
(
Collectors
.
toList
());
}
int
rowIndex
=
1
;
for
(
TheoreticalLibraryNodeEntity
node
:
nodes
)
{
Row
row
=
sheet
.
createRow
(
rowIndex
++);
row
.
createCell
(
0
).
setCellValue
(
node
.
getNodeType
());
row
.
createCell
(
1
).
setCellValue
(
parentCodePath
(
node
,
map
));
row
.
createCell
(
2
).
setCellValue
(
node
.
getName
());
row
.
createCell
(
3
).
setCellValue
(
node
.
getCode
());
row
.
createCell
(
4
).
setCellValue
(
node
.
getSortNo
());
row
.
createCell
(
5
).
setCellValue
(
node
.
getStatus
()
==
1
?
"启用"
:
"禁用"
);
row
.
createCell
(
6
).
setCellValue
(
node
.
getRemark
()
==
null
?
""
:
node
.
getRemark
());
}
autoWidth
(
sheet
,
STRUCTURE_HEADERS
.
size
());
}
private
void
exportQuestions
(
Workbook
workbook
,
String
bankType
,
String
scope
,
TheoreticalLibraryQuestionQueryDTO
query
,
boolean
includeAnswer
)
{
Sheet
sheet
=
workbook
.
createSheet
(
"试题数据"
);
writeHeader
(
sheet
,
QUESTION_HEADERS
,
workbook
);
TheoreticalLibraryQuestionQueryDTO
safeQuery
=
"FILTERED"
.
equals
(
scope
)
&&
query
!=
null
?
query
:
new
TheoreticalLibraryQuestionQueryDTO
();
safeQuery
.
setBankType
(
bankType
);
List
<
TheoreticalLibraryQuestionVO
>
questions
=
adminService
.
page
(
safeQuery
);
Map
<
String
,
TheoreticalLibraryNodeEntity
>
nodes
=
adminService
.
flatNodes
(
bankType
).
stream
()
.
collect
(
Collectors
.
toMap
(
TheoreticalLibraryNodeEntity:
:
getId
,
value
->
value
));
int
rowIndex
=
1
;
for
(
TheoreticalLibraryQuestionVO
question
:
questions
)
{
Row
row
=
sheet
.
createRow
(
rowIndex
++);
row
.
createCell
(
0
).
setCellValue
(
question
.
getCode
());
row
.
createCell
(
1
).
setCellValue
(
nodeCodePath
(
question
.
getNodeId
(),
nodes
));
row
.
createCell
(
2
).
setCellValue
(
question
.
getTypeCode
());
row
.
createCell
(
3
).
setCellValue
(
question
.
getScore
()
==
null
?
0
:
question
.
getScore
());
row
.
createCell
(
4
).
setCellValue
(
question
.
getDifficulty
());
row
.
createCell
(
5
).
setCellValue
(
question
.
getStatus
()
!=
null
&&
question
.
getStatus
()
==
0
?
"禁用"
:
"启用"
);
row
.
createCell
(
6
).
setCellValue
(
Boolean
.
TRUE
.
equals
(
question
.
getNoExam
())
?
"是"
:
"否"
);
row
.
createCell
(
7
).
setCellValue
(
String
.
join
(
","
,
question
.
getKeywordList
()));
row
.
createCell
(
8
).
setCellValue
(
question
.
getProblem
());
String
[]
optionValues
=
{
question
.
getOptionA
(),
question
.
getOptionB
(),
question
.
getOptionC
(),
question
.
getOptionD
(),
question
.
getOptionE
()};
for
(
int
i
=
0
;
i
<
optionValues
.
length
;
i
++)
{
row
.
createCell
(
9
+
i
).
setCellValue
(
optionValues
[
i
]
==
null
?
""
:
optionValues
[
i
]);
}
row
.
createCell
(
14
).
setCellValue
(
includeAnswer
&&
question
.
getAnswer
()
!=
null
?
question
.
getAnswer
()
:
""
);
row
.
createCell
(
15
).
setCellValue
(
includeAnswer
&&
question
.
getAnalysis
()
!=
null
?
question
.
getAnalysis
()
:
""
);
}
autoWidth
(
sheet
,
QUESTION_HEADERS
.
size
());
}
private
TheoreticalLibraryNodeEntity
resolveNodePath
(
String
bankType
,
String
codePath
,
boolean
requireTerminal
)
{
if
(!
StringUtils
.
hasText
(
codePath
))
{
throw
new
BusinessException
(
"节点编码路径不能为空"
);
}
String
parentId
=
TheoreticalLibraryAdminConstants
.
ROOT_PARENT_ID
;
TheoreticalLibraryNodeEntity
current
=
null
;
for
(
String
code
:
codePath
.
trim
().
split
(
"/"
))
{
current
=
findChild
(
bankType
,
parentId
,
code
.
trim
().
toUpperCase
(
Locale
.
ROOT
));
if
(
current
==
null
)
{
throw
new
BusinessException
(
"节点编码路径不存在:"
+
codePath
);
}
parentId
=
current
.
getId
();
}
List
<
String
>
types
=
TheoreticalLibraryAdminConstants
.
nodeTypes
(
bankType
);
if
(
requireTerminal
&&
!
types
.
get
(
types
.
size
()
-
1
).
equals
(
current
.
getNodeType
()))
{
throw
new
BusinessException
(
"试题必须绑定到末级节点"
);
}
return
current
;
}
private
TheoreticalLibraryNodeEntity
findChild
(
String
bankType
,
String
parentId
,
String
code
)
{
return
adminService
.
flatNodes
(
bankType
).
stream
()
.
filter
(
node
->
parentId
.
equals
(
node
.
getParentId
())
&&
code
.
equalsIgnoreCase
(
node
.
getCode
()))
.
findFirst
().
orElse
(
null
);
}
private
String
parentCodePath
(
TheoreticalLibraryNodeEntity
node
,
Map
<
String
,
TheoreticalLibraryNodeEntity
>
map
)
{
return
TheoreticalLibraryAdminConstants
.
ROOT_PARENT_ID
.
equals
(
node
.
getParentId
())
?
""
:
nodeCodePath
(
node
.
getParentId
(),
map
);
}
private
String
nodeCodePath
(
String
nodeId
,
Map
<
String
,
TheoreticalLibraryNodeEntity
>
map
)
{
List
<
String
>
codes
=
new
ArrayList
<>();
Set
<
String
>
visited
=
new
HashSet
<>();
TheoreticalLibraryNodeEntity
current
=
map
.
get
(
nodeId
);
while
(
current
!=
null
&&
visited
.
add
(
current
.
getId
()))
{
codes
.
add
(
current
.
getCode
());
current
=
map
.
get
(
current
.
getParentId
());
}
Collections
.
reverse
(
codes
);
return
String
.
join
(
"/"
,
codes
);
}
private
void
validateImportFile
(
MultipartFile
file
)
{
if
(
file
==
null
||
file
.
isEmpty
())
{
throw
new
BusinessException
(
"导入文件不能为空"
);
}
if
(
file
.
getSize
()
>
TheoreticalLibraryAdminConstants
.
MAX_IMPORT_FILE_SIZE
)
{
throw
new
BusinessException
(
"导入文件不能超过10MB"
);
}
String
name
=
file
.
getOriginalFilename
();
if
(!
StringUtils
.
hasText
(
name
)
||
!
name
.
toLowerCase
(
Locale
.
ROOT
).
endsWith
(
".xlsx"
))
{
throw
new
BusinessException
(
"仅支持.xlsx格式文件"
);
}
}
private
void
requireHeaders
(
Sheet
sheet
,
List
<
String
>
expected
)
{
Row
header
=
sheet
.
getRow
(
0
);
if
(
header
==
null
)
{
throw
new
BusinessException
(
"Excel缺少表头"
);
}
for
(
int
i
=
0
;
i
<
expected
.
size
();
i
++)
{
if
(!
expected
.
get
(
i
).
equals
(
cell
(
header
,
i
)))
{
throw
new
BusinessException
(
"Excel表头不正确,第"
+
(
i
+
1
)
+
"列应为“"
+
expected
.
get
(
i
)
+
"”"
);
}
}
}
private
byte
[]
createErrorWorkbook
(
List
<
ImportError
>
errors
)
{
try
(
Workbook
workbook
=
new
XSSFWorkbook
();
ByteArrayOutputStream
output
=
new
ByteArrayOutputStream
())
{
Sheet
sheet
=
workbook
.
createSheet
(
"错误明细"
);
writeHeader
(
sheet
,
Arrays
.
asList
(
"Excel行号"
,
"错误原因"
,
"原始数据"
),
workbook
);
int
rowIndex
=
1
;
for
(
ImportError
error
:
errors
)
{
Row
row
=
sheet
.
createRow
(
rowIndex
++);
row
.
createCell
(
0
).
setCellValue
(
error
.
rowNumber
);
row
.
createCell
(
1
).
setCellValue
(
error
.
message
);
row
.
createCell
(
2
).
setCellValue
(
error
.
rawData
);
}
autoWidth
(
sheet
,
3
);
workbook
.
write
(
output
);
return
output
.
toByteArray
();
}
catch
(
IOException
e
)
{
throw
new
BusinessException
(
"错误明细生成失败"
);
}
}
private
void
writeHeader
(
Sheet
sheet
,
List
<
String
>
headers
,
Workbook
workbook
)
{
Font
font
=
workbook
.
createFont
();
font
.
setBold
(
true
);
CellStyle
style
=
workbook
.
createCellStyle
();
style
.
setFont
(
font
);
Row
row
=
sheet
.
createRow
(
0
);
for
(
int
i
=
0
;
i
<
headers
.
size
();
i
++)
{
Cell
cell
=
row
.
createCell
(
i
);
cell
.
setCellValue
(
headers
.
get
(
i
));
cell
.
setCellStyle
(
style
);
}
}
private
void
writeWorkbook
(
Workbook
workbook
,
HttpServletResponse
response
,
String
fileName
)
throws
IOException
{
response
.
setContentType
(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
);
String
encoded
=
URLEncoder
.
encode
(
fileName
,
StandardCharsets
.
UTF_8
.
name
())
.
replace
(
"+"
,
"%20"
);
response
.
setHeader
(
"Content-Disposition"
,
"attachment; filename*=UTF-8''"
+
encoded
);
workbook
.
write
(
response
.
getOutputStream
());
response
.
getOutputStream
().
flush
();
}
private
void
autoWidth
(
Sheet
sheet
,
int
columns
)
{
for
(
int
i
=
0
;
i
<
columns
;
i
++)
{
sheet
.
setColumnWidth
(
i
,
(
i
>=
8
?
50
:
24
)
*
256
);
}
}
private
String
normalizeDataType
(
String
dataType
)
{
String
value
=
dataType
==
null
?
""
:
dataType
.
trim
().
toUpperCase
(
Locale
.
ROOT
);
if
(!
"STRUCTURE"
.
equals
(
value
)
&&
!
"QUESTION"
.
equals
(
value
))
{
throw
new
BusinessException
(
"数据类型仅支持STRUCTURE或QUESTION"
);
}
return
value
;
}
private
String
normalizeMode
(
String
mode
)
{
String
value
=
mode
==
null
?
""
:
mode
.
trim
().
toUpperCase
(
Locale
.
ROOT
);
if
(!
"ADD"
.
equals
(
value
)
&&
!
"OVERWRITE"
.
equals
(
value
))
{
throw
new
BusinessException
(
"导入模式仅支持ADD或OVERWRITE"
);
}
return
value
;
}
private
String
cell
(
Row
row
,
int
index
)
{
if
(
row
==
null
||
row
.
getCell
(
index
)
==
null
)
{
return
""
;
}
Cell
cell
=
row
.
getCell
(
index
);
switch
(
cell
.
getCellType
())
{
case
NUMERIC:
double
number
=
cell
.
getNumericCellValue
();
return
number
==
Math
.
rint
(
number
)
?
String
.
valueOf
((
long
)
number
)
:
String
.
valueOf
(
number
);
case
BOOLEAN:
return
String
.
valueOf
(
cell
.
getBooleanCellValue
());
case
FORMULA:
return
cell
.
getCellFormula
();
default
:
return
cell
.
toString
().
trim
();
}
}
private
int
integerCell
(
Row
row
,
int
index
,
int
defaultValue
)
{
String
value
=
cell
(
row
,
index
);
return
StringUtils
.
hasText
(
value
)
?
Integer
.
parseInt
(
value
)
:
defaultValue
;
}
private
double
doubleCell
(
Row
row
,
int
index
)
{
String
value
=
cell
(
row
,
index
);
if
(!
StringUtils
.
hasText
(
value
))
{
throw
new
BusinessException
(
"分值不能为空"
);
}
return
Double
.
parseDouble
(
value
);
}
private
int
statusCell
(
Row
row
,
int
index
)
{
String
value
=
cell
(
row
,
index
);
return
"0"
.
equals
(
value
)
||
"禁用"
.
equals
(
value
)
?
0
:
1
;
}
private
boolean
booleanCell
(
Row
row
,
int
index
)
{
String
value
=
cell
(
row
,
index
);
return
"1"
.
equals
(
value
)
||
"是"
.
equalsIgnoreCase
(
value
)
||
"TRUE"
.
equalsIgnoreCase
(
value
);
}
private
boolean
emptyRow
(
Row
row
,
int
columns
)
{
if
(
row
==
null
)
{
return
true
;
}
for
(
int
i
=
0
;
i
<
columns
;
i
++)
{
if
(
StringUtils
.
hasText
(
cell
(
row
,
i
)))
{
return
false
;
}
}
return
true
;
}
private
String
rowText
(
Row
row
,
int
columns
)
{
List
<
String
>
values
=
new
ArrayList
<>();
for
(
int
i
=
0
;
i
<
columns
;
i
++)
{
values
.
add
(
cell
(
row
,
i
));
}
return
String
.
join
(
" | "
,
values
);
}
private
String
message
(
Exception
exception
)
{
return
StringUtils
.
hasText
(
exception
.
getMessage
())
?
exception
.
getMessage
()
:
"数据处理失败"
;
}
private
static
final
class
ImportError
{
private
final
int
rowNumber
;
private
final
String
message
;
private
final
String
rawData
;
private
ImportError
(
int
rowNumber
,
String
message
,
String
rawData
)
{
this
.
rowNumber
=
rowNumber
;
this
.
message
=
message
;
this
.
rawData
=
rawData
;
}
}
}
practical-business/src/main/java/com/platform/business/service/impl/TheoreticalLibraryServiceImpl.java
View file @
9fc77652
...
...
@@ -4,8 +4,10 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import
com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
;
import
com.google.common.collect.Lists
;
import
com.platform.business.mapper.TheoreticalLibraryMapper
;
import
com.platform.business.mapper.TheoreticalLibraryNodeMapper
;
import
com.platform.business.model.dto.TheoreticalLibraryDTO
;
import
com.platform.business.model.entity.TheoreticalLibraryEntity
;
import
com.platform.business.model.entity.TheoreticalLibraryNodeEntity
;
import
com.platform.business.model.entity.TheoreticalPaperDetailEntity
;
import
com.platform.business.model.entity.TheoreticalPracticeStudentSimulationDetailEntity
;
import
com.platform.business.model.vo.TheoreticalLibraryVO
;
...
...
@@ -25,7 +27,11 @@ import javax.servlet.http.HttpServletResponse;
import
java.io.IOException
;
import
java.net.URLEncoder
;
import
java.nio.charset.StandardCharsets
;
import
java.util.Date
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.Locale
;
import
java.util.Map
;
import
java.util.Objects
;
import
java.util.regex.Matcher
;
import
java.util.regex.Pattern
;
...
...
@@ -38,6 +44,9 @@ import java.util.regex.Pattern;
*/
@Service
public
class
TheoreticalLibraryServiceImpl
extends
ServiceImpl
<
TheoreticalLibraryMapper
,
TheoreticalLibraryEntity
>
implements
TheoreticalLibraryService
{
@javax
.
annotation
.
Resource
private
TheoreticalLibraryNodeMapper
theoreticalLibraryNodeMapper
;
@Override
public
void
removeDirtyData
()
{
baseMapper
.
removeDirtyData
();
...
...
@@ -280,6 +289,8 @@ public class TheoreticalLibraryServiceImpl extends ServiceImpl<TheoreticalLibrar
saveBatch
(
theoreticalLibraryList
);
//删除脏数据
removeDirtyData
();
// 旧竞赛模板仍由本入口导入;同步新节点和管理字段,保证新旧页面数据一致。
synchronizeImportedScope
(
scope
);
return
Result
.
success
(
"导入成功"
);
}
}
...
...
@@ -491,10 +502,118 @@ public class TheoreticalLibraryServiceImpl extends ServiceImpl<TheoreticalLibrar
saveBatch
(
theoreticalLibraryList
);
//删除脏数据
removeDirtyData
();
// 旧职级模板导入后补齐六级树及新字段,旧接口无需感知新表结构。
synchronizeImportedScope
(
scope
);
return
Result
.
success
(
"导入成功"
);
}
}
/**
* 将旧模板刚导入的题目投影到新版层级表。
*
* <p>方法只处理指定 scope,并使用“父节点+名称”缓存避免同一次导入反复查库。
* 节点编码采用稳定哈希,重复导入会复用原节点;题目仍保留旧层级名称供组卷查询。</p>
*/
private
void
synchronizeImportedScope
(
String
scope
)
{
List
<
TheoreticalLibraryEntity
>
questions
=
list
(
new
LambdaQueryWrapper
<
TheoreticalLibraryEntity
>()
.
eq
(
TheoreticalLibraryEntity:
:
getScope
,
scope
)
.
eq
(
TheoreticalLibraryEntity:
:
getIsProblem
,
true
));
Map
<
String
,
TheoreticalLibraryNodeEntity
>
cache
=
new
HashMap
<>();
boolean
competition
=
"技能竞赛"
.
equals
(
scope
);
for
(
TheoreticalLibraryEntity
question
:
questions
)
{
TheoreticalLibraryNodeEntity
leaf
;
if
(
competition
)
{
TheoreticalLibraryNodeEntity
competitionNode
=
ensureLegacyNode
(
cache
,
"COMP"
,
"0"
,
"COMPETITION"
,
fallback
(
question
.
getFirstLevelName
(),
"技能竞赛"
),
10
);
TheoreticalLibraryNodeEntity
category
=
ensureLegacyNode
(
cache
,
"COMP"
,
competitionNode
.
getId
(),
"CATEGORY"
,
fallback
(
question
.
getSecondLevelName
(),
"未分类"
),
10
);
leaf
=
ensureLegacyNode
(
cache
,
"COMP"
,
category
.
getId
(),
"DIRECTION"
,
fallback
(
question
.
getThirdLevelName
(),
"未分类方向"
),
10
);
question
.
setBankType
(
"COMP"
);
}
else
{
String
craftName
=
scope
!=
null
&&
(
scope
.
startsWith
(
"污水"
)
||
scope
.
startsWith
(
"污泥"
))
?
scope
.
substring
(
0
,
2
)
:
fallback
(
scope
,
"其他工艺"
);
String
levelName
=
scope
!=
null
&&
scope
.
length
()
>
craftName
.
length
()
?
scope
.
substring
(
craftName
.
length
())
:
"未分级"
;
TheoreticalLibraryNodeEntity
craft
=
ensureLegacyNode
(
cache
,
"JOB"
,
"0"
,
"CRAFT"
,
craftName
,
10
);
TheoreticalLibraryNodeEntity
level
=
ensureLegacyNode
(
cache
,
"JOB"
,
craft
.
getId
(),
"LEVEL"
,
levelName
,
10
);
TheoreticalLibraryNodeEntity
chapter
=
ensureLegacyNode
(
cache
,
"JOB"
,
level
.
getId
(),
"CHAPTER"
,
fallback
(
question
.
getFirstLevelName
(),
"未分类章"
),
10
);
TheoreticalLibraryNodeEntity
section
=
ensureLegacyNode
(
cache
,
"JOB"
,
chapter
.
getId
(),
"SECTION"
,
fallback
(
question
.
getSecondLevelName
(),
"未分类节"
),
10
);
TheoreticalLibraryNodeEntity
topic
=
ensureLegacyNode
(
cache
,
"JOB"
,
section
.
getId
(),
"TOPIC"
,
fallback
(
question
.
getThirdLevelName
(),
"未分类目"
),
10
);
leaf
=
ensureLegacyNode
(
cache
,
"JOB"
,
topic
.
getId
(),
"POINT"
,
fallback
(
question
.
getFourthLevelName
(),
"未分类知识点"
),
10
);
question
.
setBankType
(
"JOB"
);
}
question
.
setNodeId
(
leaf
.
getId
());
question
.
setStatus
(
1
);
question
.
setDifficulty
(
"MEDIUM"
);
question
.
setScore
(
defaultScore
(
question
.
getType
()));
question
.
setParticipate
(
question
.
getParticipate
()
==
null
||
question
.
getParticipate
());
question
.
setCreateUserName
(
"旧格式导入"
);
question
.
setCreateTime
(
question
.
getCreateTime
()
==
null
?
new
Date
()
:
question
.
getCreateTime
());
question
.
setUpdateTime
(
new
Date
());
updateById
(
question
);
}
}
/** 查找或创建旧数据回填节点,数据库唯一索引承担并发场景的最终保护。 */
private
TheoreticalLibraryNodeEntity
ensureLegacyNode
(
Map
<
String
,
TheoreticalLibraryNodeEntity
>
cache
,
String
bankType
,
String
parentId
,
String
nodeType
,
String
name
,
int
sortNo
)
{
String
cacheKey
=
bankType
+
'|'
+
parentId
+
'|'
+
name
;
TheoreticalLibraryNodeEntity
cached
=
cache
.
get
(
cacheKey
);
if
(
cached
!=
null
)
{
return
cached
;
}
TheoreticalLibraryNodeEntity
existing
=
theoreticalLibraryNodeMapper
.
selectOne
(
new
LambdaQueryWrapper
<
TheoreticalLibraryNodeEntity
>()
.
eq
(
TheoreticalLibraryNodeEntity:
:
getBankType
,
bankType
)
.
eq
(
TheoreticalLibraryNodeEntity:
:
getParentId
,
parentId
)
.
eq
(
TheoreticalLibraryNodeEntity:
:
getName
,
name
)
// 历史库可能曾人工创建同名不同编码节点;旧导入只需稳定复用其中一个。
.
orderByAsc
(
TheoreticalLibraryNodeEntity:
:
getSortNo
)
.
last
(
"LIMIT 1"
));
if
(
existing
==
null
)
{
existing
=
new
TheoreticalLibraryNodeEntity
();
existing
.
setBankType
(
bankType
);
existing
.
setParentId
(
parentId
);
existing
.
setNodeType
(
nodeType
);
existing
.
setName
(
name
);
existing
.
setCode
(
"LEGACY-"
+
Integer
.
toHexString
(
cacheKey
.
hashCode
())
.
toUpperCase
(
Locale
.
ROOT
));
existing
.
setSortNo
(
sortNo
);
existing
.
setStatus
(
1
);
existing
.
setCreateUserName
(
"旧格式导入"
);
theoreticalLibraryNodeMapper
.
insert
(
existing
);
}
cache
.
put
(
cacheKey
,
existing
);
return
existing
;
}
private
String
fallback
(
String
value
,
String
fallback
)
{
return
StringUtils
.
isNotBlank
(
value
)
?
value
.
trim
()
:
fallback
;
}
private
double
defaultScore
(
String
type
)
{
if
(
"判断题"
.
equals
(
type
))
{
return
1
D
;
}
if
(
"单选题"
.
equals
(
type
))
{
return
2
D
;
}
if
(
"多选题"
.
equals
(
type
))
{
return
3
D
;
}
return
5
D
;
}
private
String
multipleAnswer
(
String
column5
)
{
// 定义正则表达式匹配中文括号内的A-E字母组合
Pattern
pattern
=
Pattern
.
compile
(
"(([A-E]+))"
);
...
...
practical-business/src/main/resources/com/platform/business/mapper/TheoreticalLibraryMapper.xml
View file @
9fc77652
...
...
@@ -35,6 +35,23 @@
AND first_level_name = #{firstLevelName}
AND second_level_name = #{secondLevelName}
AND participate = true
AND COALESCE(status, 1) = 1
AND (node_id IS NULL OR EXISTS (
SELECT 1
FROM theoretical_library_node n0
LEFT JOIN theoretical_library_node n1 ON n1.id = n0.parent_id
LEFT JOIN theoretical_library_node n2 ON n2.id = n1.parent_id
LEFT JOIN theoretical_library_node n3 ON n3.id = n2.parent_id
LEFT JOIN theoretical_library_node n4 ON n4.id = n3.parent_id
LEFT JOIN theoretical_library_node n5 ON n5.id = n4.parent_id
WHERE n0.id = theoretical_library.node_id
AND n0.status = 1
AND COALESCE(n1.status, 1) = 1
AND COALESCE(n2.status, 1) = 1
AND COALESCE(n3.status, 1) = 1
AND COALESCE(n4.status, 1) = 1
AND COALESCE(n5.status, 1) = 1
))
ORDER BY RAND()
LIMIT #{count}
</select>
...
...
@@ -63,6 +80,19 @@
AND first_level_name = #{firstLevelName}
AND second_level_name = #{secondLevelName}
AND participate = true
AND COALESCE(status, 1) = 1
AND (node_id IS NULL OR EXISTS (
SELECT 1 FROM theoretical_library_node n0
LEFT JOIN theoretical_library_node n1 ON n1.id = n0.parent_id
LEFT JOIN theoretical_library_node n2 ON n2.id = n1.parent_id
LEFT JOIN theoretical_library_node n3 ON n3.id = n2.parent_id
LEFT JOIN theoretical_library_node n4 ON n4.id = n3.parent_id
LEFT JOIN theoretical_library_node n5 ON n5.id = n4.parent_id
WHERE n0.id = theoretical_library.node_id
AND n0.status = 1 AND COALESCE(n1.status, 1) = 1
AND COALESCE(n2.status, 1) = 1 AND COALESCE(n3.status, 1) = 1
AND COALESCE(n4.status, 1) = 1 AND COALESCE(n5.status, 1) = 1
))
ORDER BY RAND()
LIMIT #{count}
</select>
...
...
@@ -142,15 +172,104 @@
AND first_level_name = #{firstLevelName}
AND second_level_name = #{secondLevelName}
AND participate = true
AND COALESCE(status, 1) = 1
AND (node_id IS NULL OR EXISTS (
SELECT 1 FROM theoretical_library_node n0
LEFT JOIN theoretical_library_node n1 ON n1.id = n0.parent_id
LEFT JOIN theoretical_library_node n2 ON n2.id = n1.parent_id
LEFT JOIN theoretical_library_node n3 ON n3.id = n2.parent_id
LEFT JOIN theoretical_library_node n4 ON n4.id = n3.parent_id
LEFT JOIN theoretical_library_node n5 ON n5.id = n4.parent_id
WHERE n0.id = theoretical_library.node_id
AND n0.status = 1 AND COALESCE(n1.status, 1) = 1
AND COALESCE(n2.status, 1) = 1 AND COALESCE(n3.status, 1) = 1
AND COALESCE(n4.status, 1) = 1 AND COALESCE(n5.status, 1) = 1
))
ORDER BY RAND()
LIMIT #{count}
</select>
<!--
学员题库初始化仍需要旧的“章+节+两位序号”结构。新管理端不再维护旧伪层级行,
因此这里从固定六级节点反向投影为旧实体,保持调用方无需改动。
-->
<select
id=
"groupByChapter"
resultType=
"com.platform.business.model.entity.TheoreticalLibraryEntity"
>
SELECT CONCAT(craft.name, grade.name) AS scope,
chapter.name AS first_level_name,
section.name AS second_level_name,
CONCAT(
GREATEST(0, FLOOR(COALESCE(chapter.sort_no, 10) / 10) - 1),
GREATEST(1, FLOOR(COALESCE(section.sort_no, 10) / 10))
) AS sequence
FROM theoretical_library_node section
INNER JOIN theoretical_library_node chapter ON chapter.id = section.parent_id
INNER JOIN theoretical_library_node grade ON grade.id = chapter.parent_id
INNER JOIN theoretical_library_node craft ON craft.id = grade.parent_id
WHERE section.bank_type = 'JOB'
AND section.node_type = 'SECTION'
AND CONCAT(craft.name, grade.name) = #{level}
ORDER BY chapter.sort_no, section.sort_no
</select>
<sql
id=
"adminQuestionWhere"
>
WHERE q.is_problem = TRUE
<if
test=
"query.bankType != null and query.bankType != ''"
>
AND q.bank_type = #{query.bankType}
</if>
<if
test=
"query.nodeIds != null and query.nodeIds.size() > 0"
>
AND q.node_id IN
<foreach
collection=
"query.nodeIds"
item=
"nodeId"
open=
"("
separator=
","
close=
")"
>
#{nodeId}
</foreach>
</if>
<if
test=
"query.type != null and query.type != ''"
>
AND q.type = #{query.type}
</if>
<if
test=
"query.keyword != null and query.keyword != ''"
>
AND (q.problem LIKE CONCAT('%', #{query.keyword}, '%')
OR q.code LIKE CONCAT('%', #{query.keyword}, '%')
OR q.keywords LIKE CONCAT('%', #{query.keyword}, '%'))
</if>
<if
test=
"query.status != null"
>
AND COALESCE(q.status, 1) = #{query.status}
</if>
<if
test=
"query.createStart != null"
>
AND q.create_time
<![CDATA[>=]]>
#{query.createStart}
</if>
<if
test=
"query.createEnd != null"
>
AND q.create_time
<![CDATA[<]]>
DATE_ADD(#{query.createEnd}, INTERVAL 1 DAY)
</if>
</sql>
<select
id=
"selectAdminQuestions"
resultType=
"com.platform.business.model.vo.TheoreticalLibraryQuestionVO"
>
SELECT q.*
FROM theoretical_library q
<include
refid=
"adminQuestionWhere"
/>
ORDER BY q.create_time DESC, q.id DESC
</select>
<select
id=
"selectAdminQuestionIds"
resultType=
"java.lang.String"
>
SELECT q.id
FROM theoretical_library q
<include
refid=
"adminQuestionWhere"
/>
ORDER BY q.create_time DESC, q.id DESC
</select>
<select
id=
"selectQuestionCounts"
resultType=
"com.platform.business.model.vo.TheoreticalLibraryNodeCountVO"
>
SELECT node_id AS nodeId, COUNT(*) AS questionCount
FROM theoretical_library
WHERE is_problem = TRUE
AND bank_type = #{bankType}
AND node_id IS NOT NULL
GROUP BY node_id
</select>
<select
id=
"selectQuestionForUpdate"
resultType=
"com.platform.business.model.entity.TheoreticalLibraryEntity"
>
SELECT *
FROM theoretical_library
WHERE
sequence IS NOT NULL
AND
CHAR_LENGTH(sequence) = 2
and scope = #{level}
WHERE
id = #{id}
AND
is_problem = TRUE
FOR UPDATE
</select>
</mapper>
practical-business/src/main/resources/sql/theoretical_library_management.sql
0 → 100644
View file @
9fc77652
-- 管理员端“题库管理-理论题库”增量数据库脚本(MySQL 5.7+/8.0)。
--
-- 执行原则:
-- 1. 只扩展 theoretical_library,不删除历史题目和旧的 is_problem=false 层级行。
-- 2. 新建规范化节点表,并把历史题目回填到六级职级树或三级竞赛树。
-- 3. 所有 DDL 先检查 information_schema,可在开发、测试和生产重复执行。
-- 4. 沿用项目现状不建立外键;级联删除、层级约束和兼容字段同步由事务服务保证。
CREATE
TABLE
IF
NOT
EXISTS
theoretical_library_node
(
id
VARCHAR
(
64
)
NOT
NULL
COMMENT
'节点ID'
,
bank_type
VARCHAR
(
16
)
NOT
NULL
COMMENT
'JOB职级题库/COMP竞赛题库'
,
parent_id
VARCHAR
(
64
)
NOT
NULL
DEFAULT
'0'
COMMENT
'上级节点,0表示根'
,
node_type
VARCHAR
(
32
)
NOT
NULL
COMMENT
'CRAFT/LEVEL/CHAPTER/SECTION/TOPIC/POINT等'
,
name
VARCHAR
(
200
)
NOT
NULL
COMMENT
'节点名称'
,
code
VARCHAR
(
64
)
NOT
NULL
COMMENT
'同一父节点下唯一编码'
,
sort_no
INT
NOT
NULL
DEFAULT
10
COMMENT
'同级排序号'
,
status
TINYINT
NOT
NULL
DEFAULT
1
COMMENT
'1启用,0禁用'
,
remark
VARCHAR
(
500
)
NULL
COMMENT
'备注'
,
create_user_id
VARCHAR
(
64
)
NULL
COMMENT
'创建人用户ID'
,
create_user_name
VARCHAR
(
100
)
NULL
COMMENT
'创建人姓名快照'
,
create_time
DATETIME
NULL
COMMENT
'创建时间'
,
update_time
DATETIME
NULL
COMMENT
'最后更新时间'
,
PRIMARY
KEY
(
id
),
UNIQUE
KEY
uk_tl_node_parent_code
(
bank_type
,
parent_id
,
code
),
KEY
idx_tl_node_parent_sort
(
bank_type
,
parent_id
,
sort_no
,
id
),
KEY
idx_tl_node_name
(
bank_type
,
name
)
)
ENGINE
=
InnoDB
DEFAULT
CHARSET
=
utf8mb4
COMMENT
=
'理论题库层级节点'
;
DELIMITER
$$
DROP
PROCEDURE
IF
EXISTS
migrate_theoretical_library_management
$$
CREATE
PROCEDURE
migrate_theoretical_library_management
()
BEGIN
IF
NOT
EXISTS
(
SELECT
1
FROM
information_schema
.
columns
WHERE
table_schema
=
DATABASE
()
AND
table_name
=
'theoretical_library'
AND
column_name
=
'bank_type'
)
THEN
ALTER
TABLE
theoretical_library
ADD
COLUMN
bank_type
VARCHAR
(
16
)
NULL
COMMENT
'JOB职级题库/COMP竞赛题库'
AFTER
participate
;
END
IF
;
IF
NOT
EXISTS
(
SELECT
1
FROM
information_schema
.
columns
WHERE
table_schema
=
DATABASE
()
AND
table_name
=
'theoretical_library'
AND
column_name
=
'node_id'
)
THEN
ALTER
TABLE
theoretical_library
ADD
COLUMN
node_id
VARCHAR
(
64
)
NULL
COMMENT
'末级层级节点ID'
AFTER
bank_type
;
END
IF
;
IF
NOT
EXISTS
(
SELECT
1
FROM
information_schema
.
columns
WHERE
table_schema
=
DATABASE
()
AND
table_name
=
'theoretical_library'
AND
column_name
=
'score'
)
THEN
ALTER
TABLE
theoretical_library
ADD
COLUMN
score
DECIMAL
(
10
,
2
)
NULL
COMMENT
'题目默认分值'
AFTER
node_id
;
END
IF
;
IF
NOT
EXISTS
(
SELECT
1
FROM
information_schema
.
columns
WHERE
table_schema
=
DATABASE
()
AND
table_name
=
'theoretical_library'
AND
column_name
=
'difficulty'
)
THEN
ALTER
TABLE
theoretical_library
ADD
COLUMN
difficulty
VARCHAR
(
16
)
NULL
COMMENT
'EASY/MEDIUM/HARD'
AFTER
score
;
END
IF
;
IF
NOT
EXISTS
(
SELECT
1
FROM
information_schema
.
columns
WHERE
table_schema
=
DATABASE
()
AND
table_name
=
'theoretical_library'
AND
column_name
=
'status'
)
THEN
ALTER
TABLE
theoretical_library
ADD
COLUMN
status
TINYINT
NULL
COMMENT
'1启用,0禁用'
AFTER
difficulty
;
END
IF
;
IF
NOT
EXISTS
(
SELECT
1
FROM
information_schema
.
columns
WHERE
table_schema
=
DATABASE
()
AND
table_name
=
'theoretical_library'
AND
column_name
=
'keywords'
)
THEN
ALTER
TABLE
theoretical_library
ADD
COLUMN
keywords
TEXT
NULL
COMMENT
'关键词JSON数组'
AFTER
status
;
END
IF
;
IF
NOT
EXISTS
(
SELECT
1
FROM
information_schema
.
columns
WHERE
table_schema
=
DATABASE
()
AND
table_name
=
'theoretical_library'
AND
column_name
=
'analysis'
)
THEN
ALTER
TABLE
theoretical_library
ADD
COLUMN
analysis
TEXT
NULL
COMMENT
'题目解析'
AFTER
keywords
;
END
IF
;
IF
NOT
EXISTS
(
SELECT
1
FROM
information_schema
.
columns
WHERE
table_schema
=
DATABASE
()
AND
table_name
=
'theoretical_library'
AND
column_name
=
'create_user_id'
)
THEN
ALTER
TABLE
theoretical_library
ADD
COLUMN
create_user_id
VARCHAR
(
64
)
NULL
COMMENT
'创建人用户ID'
AFTER
analysis
;
END
IF
;
IF
NOT
EXISTS
(
SELECT
1
FROM
information_schema
.
columns
WHERE
table_schema
=
DATABASE
()
AND
table_name
=
'theoretical_library'
AND
column_name
=
'create_user_name'
)
THEN
ALTER
TABLE
theoretical_library
ADD
COLUMN
create_user_name
VARCHAR
(
100
)
NULL
COMMENT
'创建人姓名快照'
AFTER
create_user_id
;
END
IF
;
IF
NOT
EXISTS
(
SELECT
1
FROM
information_schema
.
columns
WHERE
table_schema
=
DATABASE
()
AND
table_name
=
'theoretical_library'
AND
column_name
=
'create_time'
)
THEN
ALTER
TABLE
theoretical_library
ADD
COLUMN
create_time
DATETIME
NULL
COMMENT
'创建时间'
AFTER
create_user_name
;
END
IF
;
IF
NOT
EXISTS
(
SELECT
1
FROM
information_schema
.
columns
WHERE
table_schema
=
DATABASE
()
AND
table_name
=
'theoretical_library'
AND
column_name
=
'update_time'
)
THEN
ALTER
TABLE
theoretical_library
ADD
COLUMN
update_time
DATETIME
NULL
COMMENT
'最后更新时间'
AFTER
create_time
;
END
IF
;
IF
NOT
EXISTS
(
SELECT
1
FROM
information_schema
.
statistics
WHERE
table_schema
=
DATABASE
()
AND
table_name
=
'theoretical_library'
AND
index_name
=
'idx_tl_admin_page'
)
THEN
ALTER
TABLE
theoretical_library
ADD
INDEX
idx_tl_admin_page
(
bank_type
,
node_id
,
status
,
create_time
,
id
);
END
IF
;
IF
NOT
EXISTS
(
SELECT
1
FROM
information_schema
.
statistics
WHERE
table_schema
=
DATABASE
()
AND
table_name
=
'theoretical_library'
AND
index_name
=
'idx_tl_bank_code'
)
THEN
ALTER
TABLE
theoretical_library
ADD
INDEX
idx_tl_bank_code
(
bank_type
,
code
);
END
IF
;
END
$$
CALL
migrate_theoretical_library_management
()
$$
DROP
PROCEDURE
IF
EXISTS
migrate_theoretical_library_management
$$
DELIMITER
;
-- 先统一历史管理字段。旧记录没有时间时以脚本执行时间作为可排序的迁移时间。
UPDATE
theoretical_library
SET
bank_type
=
COALESCE
(
bank_type
,
CASE
WHEN
scope
=
'技能竞赛'
THEN
'COMP'
ELSE
'JOB'
END
),
score
=
COALESCE
(
score
,
CASE
type
WHEN
'判断题'
THEN
1
.
00
WHEN
'单选题'
THEN
2
.
00
WHEN
'多选题'
THEN
3
.
00
ELSE
5
.
00
END
),
difficulty
=
COALESCE
(
NULLIF
(
difficulty
,
''
),
'MEDIUM'
),
status
=
COALESCE
(
status
,
1
),
participate
=
COALESCE
(
participate
,
TRUE
),
create_user_name
=
COALESCE
(
NULLIF
(
create_user_name
,
''
),
'历史数据迁移'
),
create_time
=
COALESCE
(
create_time
,
NOW
()),
update_time
=
COALESCE
(
update_time
,
create_time
,
NOW
())
WHERE
is_problem
=
TRUE
;
-- 临时表只保存题目路径。固定 ID 由完整路径 MD5 生成,脚本重复执行时会命中原节点。
DROP
TEMPORARY
TABLE
IF
EXISTS
tmp_tl_path
;
CREATE
TEMPORARY
TABLE
tmp_tl_path
AS
SELECT
id
AS
question_id
,
CASE
WHEN
scope
=
'技能竞赛'
THEN
'COMP'
ELSE
'JOB'
END
AS
bank_type
,
CASE
WHEN
scope
LIKE
'污水%'
OR
scope
LIKE
'污泥%'
THEN
LEFT
(
scope
,
2
)
WHEN
scope
=
'技能竞赛'
THEN
NULL
ELSE
COALESCE
(
NULLIF
(
TRIM
(
scope
),
''
),
'其他工艺'
)
END
AS
craft_name
,
CASE
WHEN
scope
LIKE
'污水%'
OR
scope
LIKE
'污泥%'
THEN
COALESCE
(
NULLIF
(
SUBSTRING
(
scope
,
3
),
''
),
'未分级'
)
WHEN
scope
=
'技能竞赛'
THEN
NULL
ELSE
'未分级'
END
AS
level_name
,
COALESCE
(
NULLIF
(
TRIM
(
first_level_name
),
''
),
CASE
WHEN
scope
=
'技能竞赛'
THEN
'技能竞赛'
ELSE
'未分类章'
END
)
AS
level1_name
,
COALESCE
(
NULLIF
(
TRIM
(
second_level_name
),
''
),
'未分类'
)
AS
level2_name
,
COALESCE
(
NULLIF
(
TRIM
(
third_level_name
),
''
),
CASE
WHEN
scope
=
'技能竞赛'
THEN
'未分类方向'
ELSE
'未分类目'
END
)
AS
level3_name
,
COALESCE
(
NULLIF
(
TRIM
(
fourth_level_name
),
''
),
'未分类知识点'
)
AS
level4_name
,
CAST
(
NULL
AS
CHAR
(
32
))
AS
craft_id
,
CAST
(
NULL
AS
CHAR
(
32
))
AS
level_id
,
CAST
(
NULL
AS
CHAR
(
32
))
AS
level1_id
,
CAST
(
NULL
AS
CHAR
(
32
))
AS
level2_id
,
CAST
(
NULL
AS
CHAR
(
32
))
AS
level3_id
,
CAST
(
NULL
AS
CHAR
(
32
))
AS
level4_id
FROM
theoretical_library
WHERE
is_problem
=
TRUE
;
UPDATE
tmp_tl_path
SET
craft_id
=
MD5
(
CONCAT
(
'JOB|CRAFT|'
,
craft_name
)),
level_id
=
MD5
(
CONCAT
(
'JOB|LEVEL|'
,
craft_name
,
'|'
,
level_name
)),
level1_id
=
MD5
(
CONCAT
(
bank_type
,
'|L1|'
,
COALESCE
(
craft_name
,
''
),
'|'
,
COALESCE
(
level_name
,
''
),
'|'
,
level1_name
)),
level2_id
=
MD5
(
CONCAT
(
bank_type
,
'|L2|'
,
COALESCE
(
craft_name
,
''
),
'|'
,
COALESCE
(
level_name
,
''
),
'|'
,
level1_name
,
'|'
,
level2_name
)),
level3_id
=
MD5
(
CONCAT
(
bank_type
,
'|L3|'
,
COALESCE
(
craft_name
,
''
),
'|'
,
COALESCE
(
level_name
,
''
),
'|'
,
level1_name
,
'|'
,
level2_name
,
'|'
,
level3_name
)),
level4_id
=
MD5
(
CONCAT
(
'JOB|L4|'
,
craft_name
,
'|'
,
level_name
,
'|'
,
level1_name
,
'|'
,
level2_name
,
'|'
,
level3_name
,
'|'
,
level4_name
));
-- 职级题库:工艺 → 职级 → 章 → 节 → 目 → 点。
INSERT
IGNORE
INTO
theoretical_library_node
(
id
,
bank_type
,
parent_id
,
node_type
,
name
,
code
,
sort_no
,
status
,
create_user_name
,
create_time
,
update_time
)
SELECT
DISTINCT
craft_id
,
'JOB'
,
'0'
,
'CRAFT'
,
craft_name
,
CONCAT
(
'LEGACY-'
,
UPPER
(
LEFT
(
craft_id
,
12
))),
10
,
1
,
'历史数据迁移'
,
NOW
(),
NOW
()
FROM
tmp_tl_path
WHERE
bank_type
=
'JOB'
;
INSERT
IGNORE
INTO
theoretical_library_node
(
id
,
bank_type
,
parent_id
,
node_type
,
name
,
code
,
sort_no
,
status
,
create_user_name
,
create_time
,
update_time
)
SELECT
DISTINCT
level_id
,
'JOB'
,
craft_id
,
'LEVEL'
,
level_name
,
CONCAT
(
'LEGACY-'
,
UPPER
(
LEFT
(
level_id
,
12
))),
10
,
1
,
'历史数据迁移'
,
NOW
(),
NOW
()
FROM
tmp_tl_path
WHERE
bank_type
=
'JOB'
;
INSERT
IGNORE
INTO
theoretical_library_node
(
id
,
bank_type
,
parent_id
,
node_type
,
name
,
code
,
sort_no
,
status
,
create_user_name
,
create_time
,
update_time
)
SELECT
DISTINCT
level1_id
,
'JOB'
,
level_id
,
'CHAPTER'
,
level1_name
,
CONCAT
(
'LEGACY-'
,
UPPER
(
LEFT
(
level1_id
,
12
))),
10
,
1
,
'历史数据迁移'
,
NOW
(),
NOW
()
FROM
tmp_tl_path
WHERE
bank_type
=
'JOB'
;
INSERT
IGNORE
INTO
theoretical_library_node
(
id
,
bank_type
,
parent_id
,
node_type
,
name
,
code
,
sort_no
,
status
,
create_user_name
,
create_time
,
update_time
)
SELECT
DISTINCT
level2_id
,
'JOB'
,
level1_id
,
'SECTION'
,
level2_name
,
CONCAT
(
'LEGACY-'
,
UPPER
(
LEFT
(
level2_id
,
12
))),
10
,
1
,
'历史数据迁移'
,
NOW
(),
NOW
()
FROM
tmp_tl_path
WHERE
bank_type
=
'JOB'
;
INSERT
IGNORE
INTO
theoretical_library_node
(
id
,
bank_type
,
parent_id
,
node_type
,
name
,
code
,
sort_no
,
status
,
create_user_name
,
create_time
,
update_time
)
SELECT
DISTINCT
level3_id
,
'JOB'
,
level2_id
,
'TOPIC'
,
level3_name
,
CONCAT
(
'LEGACY-'
,
UPPER
(
LEFT
(
level3_id
,
12
))),
10
,
1
,
'历史数据迁移'
,
NOW
(),
NOW
()
FROM
tmp_tl_path
WHERE
bank_type
=
'JOB'
;
INSERT
IGNORE
INTO
theoretical_library_node
(
id
,
bank_type
,
parent_id
,
node_type
,
name
,
code
,
sort_no
,
status
,
create_user_name
,
create_time
,
update_time
)
SELECT
DISTINCT
level4_id
,
'JOB'
,
level3_id
,
'POINT'
,
level4_name
,
CONCAT
(
'LEGACY-'
,
UPPER
(
LEFT
(
level4_id
,
12
))),
10
,
1
,
'历史数据迁移'
,
NOW
(),
NOW
()
FROM
tmp_tl_path
WHERE
bank_type
=
'JOB'
;
-- 竞赛题库:竞赛类型 → 题目分类 → 题目方向。
INSERT
IGNORE
INTO
theoretical_library_node
(
id
,
bank_type
,
parent_id
,
node_type
,
name
,
code
,
sort_no
,
status
,
create_user_name
,
create_time
,
update_time
)
SELECT
DISTINCT
level1_id
,
'COMP'
,
'0'
,
'COMPETITION'
,
level1_name
,
CONCAT
(
'LEGACY-'
,
UPPER
(
LEFT
(
level1_id
,
12
))),
10
,
1
,
'历史数据迁移'
,
NOW
(),
NOW
()
FROM
tmp_tl_path
WHERE
bank_type
=
'COMP'
;
INSERT
IGNORE
INTO
theoretical_library_node
(
id
,
bank_type
,
parent_id
,
node_type
,
name
,
code
,
sort_no
,
status
,
create_user_name
,
create_time
,
update_time
)
SELECT
DISTINCT
level2_id
,
'COMP'
,
level1_id
,
'CATEGORY'
,
level2_name
,
CONCAT
(
'LEGACY-'
,
UPPER
(
LEFT
(
level2_id
,
12
))),
10
,
1
,
'历史数据迁移'
,
NOW
(),
NOW
()
FROM
tmp_tl_path
WHERE
bank_type
=
'COMP'
;
INSERT
IGNORE
INTO
theoretical_library_node
(
id
,
bank_type
,
parent_id
,
node_type
,
name
,
code
,
sort_no
,
status
,
create_user_name
,
create_time
,
update_time
)
SELECT
DISTINCT
level3_id
,
'COMP'
,
level2_id
,
'DIRECTION'
,
level3_name
,
CONCAT
(
'LEGACY-'
,
UPPER
(
LEFT
(
level3_id
,
12
))),
10
,
1
,
'历史数据迁移'
,
NOW
(),
NOW
()
FROM
tmp_tl_path
WHERE
bank_type
=
'COMP'
;
UPDATE
theoretical_library
q
INNER
JOIN
tmp_tl_path
p
ON
p
.
question_id
=
q
.
id
SET
q
.
bank_type
=
p
.
bank_type
,
q
.
node_id
=
CASE
WHEN
p
.
bank_type
=
'COMP'
THEN
p
.
level3_id
ELSE
p
.
level4_id
END
,
q
.
update_time
=
COALESCE
(
q
.
update_time
,
NOW
());
DROP
TEMPORARY
TABLE
IF
EXISTS
tmp_tl_path
;
-- 只读核查:执行后若返回数据,应先修复再开放管理端页面。
SELECT
q
.
id
,
q
.
scope
,
q
.
code
,
q
.
problem
FROM
theoretical_library
q
LEFT
JOIN
theoretical_library_node
n
ON
n
.
id
=
q
.
node_id
WHERE
q
.
is_problem
=
TRUE
AND
(
q
.
bank_type
NOT
IN
(
'JOB'
,
'COMP'
)
OR
q
.
node_id
IS
NULL
OR
n
.
id
IS
NULL
);
SELECT
bank_type
,
parent_id
,
code
,
COUNT
(
*
)
AS
duplicate_count
FROM
theoretical_library_node
GROUP
BY
bank_type
,
parent_id
,
code
HAVING
COUNT
(
*
)
>
1
;
practical-business/src/main/resources/theoretical-library-admin-api.md
0 → 100644
View file @
9fc77652
# 管理员端理论题库管理接口
页面路径为“管理员 → 题库管理 → 理论题库”,接口统一使用
`/theoretical/library/admin`
前缀。所有请求必须携带
`Authorization`
,服务端从 JWT
解析用户并校验“管理员”角色。部署前先执行:
```
text
practical-business/src/main/resources/sql/theoretical_library_management.sql
```
职级题库
`JOB`
固定为“工艺→职级→章→节→目→点”,竞赛题库
`COMP`
固定为
“竞赛类型→题目分类→题目方向”。节点编码在同题库、同父节点下唯一。
## 1. 层级树与节点维护
-
`GET /nodes/tree?bankType=JOB&keyword=污水`
:返回嵌套树、完整路径及子树题量。
-
`POST /nodes`
:新增节点。根节点
`parentId`
传
`0`
或留空;
`nodeType`
由服务端根据父节点计算。
-
`PUT /nodes/{id}`
:编辑名称、编码、排序、状态和备注,不允许改变父节点或题库。
-
`PUT /nodes/{id}/move`
:请求体
`{"direction":"UP"}`
或
`DOWN`
。
-
`PUT /nodes/{id}/status`
:请求体
`{"status":0}`
或
`1`
。
-
`DELETE /nodes/{id}?cascade=true`
:彻底删除子树及关联试题;未显式传
`true`
会拒绝。
节点新增示例:
```
json
{
"bankType"
:
"JOB"
,
"parentId"
:
"0"
,
"name"
:
"污水"
,
"code"
:
"CRAFT-WATER"
,
"sortNo"
:
10
,
"status"
:
1
,
"remark"
:
"污水处理工艺"
}
```
## 2. 试题查询与维护
题型代码为
`SINGLE`
、
`MULTI`
、
`JUDGE`
、
`FILL`
、
`SHORT`
、
`CALC`
;难度代码为
`EASY`
、
`MEDIUM`
、
`HARD`
。
`POST /questions/page`
使用项目统一
`TableDataInfo`
:
```
json
{
"pageNum"
:
1
,
"pageSize"
:
10
,
"bankType"
:
"JOB"
,
"nodeId"
:
"末级或任意祖先节点ID"
,
"type"
:
"SINGLE"
,
"keyword"
:
"活性污泥"
,
"status"
:
1
,
"createStart"
:
"2026-08-01"
,
"createEnd"
:
"2026-08-31"
}
```
选择祖先节点时自动包含全部后代。列表和详情同时返回稳定代码、中文标签、完整层级路径、
结构化选项、
`answerText`
、关键词数组及
`noExam`
。
-
`POST /questions/filter-ids`
:同一筛选请求,返回页面“全选筛选结果”的 ID,最多 5000 条。
-
`GET /questions/{id}`
:预览和编辑回显。
-
`POST /questions`
、
`PUT /questions/{id}`
:新增或编辑。
-
`POST /questions/{id}/copy`
:复制为启用的新题,题干追加“(副本)”。
-
`DELETE /questions/{id}`
:彻底删除单题。
-
`PUT /questions/batch/status`
:
`{"ids":["1"],"status":0}`
。
-
`PUT /questions/batch/transfer`
:
`{"ids":["1"],"targetNodeId":"末级节点ID"}`
。
-
`POST /questions/batch/delete`
:
`{"ids":["1","2"]}`
。
新增单选题示例:
```
json
{
"nodeId"
:
"末级知识点ID"
,
"type"
:
"SINGLE"
,
"score"
:
2
,
"difficulty"
:
"MEDIUM"
,
"status"
:
1
,
"noExam"
:
false
,
"keywords"
:
[
"活性污泥"
,
"重点"
],
"stem"
:
"活性污泥法的核心处理单元是?"
,
"options"
:
[
{
"text"
:
"曝气池"
,
"correct"
:
true
},
{
"text"
:
"消毒池"
,
"correct"
:
false
}
],
"analysis"
:
"考查活性污泥法基本流程。"
}
```
选择题只允许 2–5 个选项;单选必须恰好一个正确答案,多选至少两个。判断、填空、简答、
计算题必须提交
`answer`
。
`noExam=true`
会保存为
`participate=false`
,不会参与随机组卷。
## 3. Excel 导入导出
-
`GET /templates/{STRUCTURE|QUESTION}?bankType=JOB`
:下载导入模板。
-
`POST /imports`
:
`multipart/form-data`
,字段为
`dataType`
、
`bankType`
、
`mode`
、
`file`
。
`mode`
支持
`ADD`
和
`OVERWRITE`
;仅允许 10MB 以内
`.xlsx`
。
-
导入返回
`successCount`
、
`failureCount`
、
`errorFileId`
;失败明细使用
`GET /imports/errors/{fileId}`
下载。
-
`POST /exports`
:导出层级或试题。
```
json
{
"dataType"
:
"QUESTION"
,
"bankType"
:
"JOB"
,
"scope"
:
"FILTERED"
,
"includeAnswer"
:
false
,
"query"
:
{
"bankType"
:
"JOB"
,
"nodeId"
:
"节点ID"
,
"type"
:
"SINGLE"
,
"keyword"
:
"污泥"
}
}
```
结构覆盖按“题库+父节点编码路径+编码”匹配;试题覆盖按“题库+题号”匹配。结构文件必须
先放父节点、后放子节点。无答案导出会同时隐藏标准答案和解析。
## 4. 旧接口兼容
原
`/theoretical/library`
分页、旧模板导入、编辑、删除和导出继续保留。旧格式导入完成后
服务端自动创建新节点并回填管理字段。随机组卷和模拟练习仍按原
`scope/章/节`
参数调用,
但只会抽取题目启用、允许组卷且所属节点整条祖先链均启用的数据。
practical-business/src/test/java/com/platform/business/controller/TheoreticalLibraryAdminControllerTest.java
0 → 100644
View file @
9fc77652
package
com.platform.business.controller
;
import
com.platform.business.model.dto.TheoreticalLibraryBatchDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryBatchStatusDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryBatchTransferDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryExportDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryNodeMoveDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryNodeSaveDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryQuestionQueryDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryQuestionSaveDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryStatusDTO
;
import
com.platform.business.model.entity.UserEntity
;
import
com.platform.business.model.vo.TheoreticalLibraryImportResultVO
;
import
com.platform.business.service.AuthenticatedUserService
;
import
com.platform.business.service.TheoreticalLibraryAdminService
;
import
com.platform.business.service.TheoreticalLibraryExcelService
;
import
com.platform.exception.BusinessException
;
import
org.junit.jupiter.api.BeforeEach
;
import
org.junit.jupiter.api.Test
;
import
org.junit.jupiter.api.extension.ExtendWith
;
import
org.mockito.Mock
;
import
org.mockito.junit.jupiter.MockitoExtension
;
import
org.springframework.mock.web.MockHttpServletRequest
;
import
org.springframework.mock.web.MockHttpServletResponse
;
import
org.springframework.mock.web.MockMultipartFile
;
import
org.springframework.test.util.ReflectionTestUtils
;
import
java.util.Collections
;
import
static
org
.
junit
.
jupiter
.
api
.
Assertions
.
assertEquals
;
import
static
org
.
junit
.
jupiter
.
api
.
Assertions
.
assertThrows
;
import
static
org
.
mockito
.
ArgumentMatchers
.
any
;
import
static
org
.
mockito
.
Mockito
.
doThrow
;
import
static
org
.
mockito
.
Mockito
.
times
;
import
static
org
.
mockito
.
Mockito
.
verify
;
import
static
org
.
mockito
.
Mockito
.
when
;
/** 管理员理论题库控制器的鉴权覆盖和分页边界测试。 */
@ExtendWith
(
MockitoExtension
.
class
)
class
TheoreticalLibraryAdminControllerTest
{
@Mock
private
TheoreticalLibraryAdminService
adminService
;
@Mock
private
TheoreticalLibraryExcelService
excelService
;
@Mock
private
AuthenticatedUserService
authenticatedUserService
;
private
TheoreticalLibraryAdminController
controller
;
private
MockHttpServletRequest
request
;
@BeforeEach
void
setUp
()
{
controller
=
new
TheoreticalLibraryAdminController
();
ReflectionTestUtils
.
setField
(
controller
,
"adminService"
,
adminService
);
ReflectionTestUtils
.
setField
(
controller
,
"excelService"
,
excelService
);
ReflectionTestUtils
.
setField
(
controller
,
"authenticatedUserService"
,
authenticatedUserService
);
request
=
new
MockHttpServletRequest
();
}
@Test
void
everyEndpointShouldRequireAdministrator
()
{
UserEntity
admin
=
new
UserEntity
();
admin
.
setId
(
"admin-1"
);
when
(
authenticatedUserService
.
current
(
request
)).
thenReturn
(
admin
);
when
(
adminService
.
tree
(
"JOB"
,
null
)).
thenReturn
(
Collections
.
emptyList
());
when
(
adminService
.
page
(
any
())).
thenReturn
(
Collections
.
emptyList
());
when
(
adminService
.
filteredIds
(
any
())).
thenReturn
(
Collections
.
emptyList
());
when
(
excelService
.
importData
(
any
(),
any
(),
any
(),
any
(),
any
()))
.
thenReturn
(
new
TheoreticalLibraryImportResultVO
());
MockHttpServletResponse
response
=
new
MockHttpServletResponse
();
MockMultipartFile
file
=
new
MockMultipartFile
(
"file"
,
"questions.xlsx"
,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
,
new
byte
[]{
1
});
controller
.
tree
(
"JOB"
,
null
,
request
);
controller
.
createNode
(
new
TheoreticalLibraryNodeSaveDTO
(),
request
);
controller
.
updateNode
(
"n1"
,
new
TheoreticalLibraryNodeSaveDTO
(),
request
);
controller
.
moveNode
(
"n1"
,
new
TheoreticalLibraryNodeMoveDTO
(),
request
);
controller
.
changeNodeStatus
(
"n1"
,
new
TheoreticalLibraryStatusDTO
(),
request
);
controller
.
deleteNode
(
"n1"
,
true
,
request
);
TheoreticalLibraryQuestionQueryDTO
query
=
new
TheoreticalLibraryQuestionQueryDTO
();
query
.
setBankType
(
"JOB"
);
controller
.
page
(
query
,
request
);
controller
.
filteredIds
(
query
,
request
);
controller
.
questionDetail
(
"q1"
,
request
);
controller
.
createQuestion
(
new
TheoreticalLibraryQuestionSaveDTO
(),
request
);
controller
.
updateQuestion
(
"q1"
,
new
TheoreticalLibraryQuestionSaveDTO
(),
request
);
controller
.
copyQuestion
(
"q1"
,
request
);
controller
.
deleteQuestion
(
"q1"
,
request
);
controller
.
batchStatus
(
new
TheoreticalLibraryBatchStatusDTO
(),
request
);
controller
.
batchTransfer
(
new
TheoreticalLibraryBatchTransferDTO
(),
request
);
controller
.
batchDelete
(
new
TheoreticalLibraryBatchDTO
(),
request
);
controller
.
template
(
"QUESTION"
,
"JOB"
,
request
,
response
);
controller
.
importData
(
"QUESTION"
,
"JOB"
,
"ADD"
,
file
,
request
);
controller
.
importErrors
(
1
,
request
);
controller
.
export
(
new
TheoreticalLibraryExportDTO
(),
request
,
response
);
verify
(
authenticatedUserService
,
times
(
20
)).
requireAdmin
(
admin
);
verify
(
adminService
).
createNode
(
any
(),
org
.
mockito
.
ArgumentMatchers
.
eq
(
admin
));
verify
(
adminService
).
createQuestion
(
any
(),
org
.
mockito
.
ArgumentMatchers
.
eq
(
admin
));
verify
(
adminService
).
copyQuestion
(
"q1"
,
admin
);
}
@Test
void
pageShouldNormalizeUnsafePagination
()
{
TheoreticalLibraryQuestionQueryDTO
query
=
new
TheoreticalLibraryQuestionQueryDTO
();
query
.
setPageNum
(
0
);
query
.
setPageSize
(
1000
);
controller
.
normalizePage
(
query
);
assertEquals
(
1
,
query
.
getPageNum
());
assertEquals
(
100
,
query
.
getPageSize
());
}
@Test
void
nonAdministratorShouldStopBeforeBusinessService
()
{
UserEntity
user
=
new
UserEntity
();
when
(
authenticatedUserService
.
current
(
request
)).
thenReturn
(
user
);
doThrow
(
new
BusinessException
(
"只有管理员可以访问管理端接口"
))
.
when
(
authenticatedUserService
).
requireAdmin
(
user
);
assertThrows
(
BusinessException
.
class
,
()
->
controller
.
questionDetail
(
"q1"
,
request
));
}
}
practical-business/src/test/java/com/platform/business/mapper/TheoreticalLibraryAdminMapperXmlTest.java
0 → 100644
View file @
9fc77652
package
com.platform.business.mapper
;
import
org.apache.ibatis.builder.xml.XMLMapperBuilder
;
import
org.apache.ibatis.io.Resources
;
import
org.apache.ibatis.session.Configuration
;
import
org.junit.jupiter.api.Test
;
import
java.io.InputStream
;
import
static
org
.
junit
.
jupiter
.
api
.
Assertions
.
assertTrue
;
/** 在应用启动前验证题库分页、全选、题量聚合和锁定 SQL 能被 MyBatis 完整解析。 */
class
TheoreticalLibraryAdminMapperXmlTest
{
@Test
void
mapperXmlShouldRegisterAdminStatements
()
throws
Exception
{
String
resource
=
"com/platform/business/mapper/TheoreticalLibraryMapper.xml"
;
Configuration
configuration
=
new
Configuration
();
try
(
InputStream
input
=
Resources
.
getResourceAsStream
(
resource
))
{
new
XMLMapperBuilder
(
input
,
configuration
,
resource
,
configuration
.
getSqlFragments
()).
parse
();
}
assertTrue
(
configuration
.
hasStatement
(
"com.platform.business.mapper.TheoreticalLibraryMapper.selectAdminQuestions"
));
assertTrue
(
configuration
.
hasStatement
(
"com.platform.business.mapper.TheoreticalLibraryMapper.selectAdminQuestionIds"
));
assertTrue
(
configuration
.
hasStatement
(
"com.platform.business.mapper.TheoreticalLibraryMapper.selectQuestionCounts"
));
assertTrue
(
configuration
.
hasStatement
(
"com.platform.business.mapper.TheoreticalLibraryMapper.selectQuestionForUpdate"
));
}
}
practical-business/src/test/java/com/platform/business/mapper/TheoreticalLibraryManagementSqlTest.java
0 → 100644
View file @
9fc77652
package
com.platform.business.mapper
;
import
org.junit.jupiter.api.Test
;
import
java.nio.charset.StandardCharsets
;
import
java.nio.file.Files
;
import
java.nio.file.Paths
;
import
static
org
.
junit
.
jupiter
.
api
.
Assertions
.
assertTrue
;
/** 增量脚本关键 DDL、历史回填和只读核查语句的静态完整性测试。 */
class
TheoreticalLibraryManagementSqlTest
{
@Test
void
migrationShouldBeIdempotentAndBackfillLegacyQuestions
()
throws
Exception
{
String
sql
=
new
String
(
Files
.
readAllBytes
(
Paths
.
get
(
"src/main/resources/sql/theoretical_library_management.sql"
)),
StandardCharsets
.
UTF_8
);
assertTrue
(
sql
.
contains
(
"CREATE TABLE IF NOT EXISTS theoretical_library_node"
));
assertTrue
(
sql
.
contains
(
"information_schema.columns"
));
assertTrue
(
sql
.
contains
(
"CREATE TEMPORARY TABLE tmp_tl_path"
));
assertTrue
(
sql
.
contains
(
"q.node_id = CASE WHEN p.bank_type = 'COMP'"
));
assertTrue
(
sql
.
contains
(
"HAVING COUNT(*) > 1"
));
}
}
practical-business/src/test/java/com/platform/business/service/impl/TheoreticalLibraryAdminServiceImplTest.java
0 → 100644
View file @
9fc77652
package
com.platform.business.service.impl
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
com.platform.business.mapper.TheoreticalLibraryMapper
;
import
com.platform.business.mapper.TheoreticalLibraryNodeMapper
;
import
com.platform.business.model.dto.TheoreticalLibraryOptionDTO
;
import
com.platform.business.model.dto.TheoreticalLibraryQuestionSaveDTO
;
import
com.platform.business.model.entity.TheoreticalLibraryNodeEntity
;
import
com.platform.business.model.vo.TheoreticalLibraryNodeCountVO
;
import
com.platform.business.model.vo.TheoreticalLibraryNodeVO
;
import
com.platform.exception.BusinessException
;
import
org.junit.jupiter.api.BeforeEach
;
import
org.junit.jupiter.api.Test
;
import
org.junit.jupiter.api.extension.ExtendWith
;
import
org.mockito.Mock
;
import
org.mockito.junit.jupiter.MockitoExtension
;
import
org.springframework.test.util.ReflectionTestUtils
;
import
java.util.Arrays
;
import
java.util.Collections
;
import
java.util.List
;
import
static
org
.
junit
.
jupiter
.
api
.
Assertions
.
assertEquals
;
import
static
org
.
junit
.
jupiter
.
api
.
Assertions
.
assertThrows
;
import
static
org
.
mockito
.
ArgumentMatchers
.
any
;
import
static
org
.
mockito
.
Mockito
.
never
;
import
static
org
.
mockito
.
Mockito
.
verify
;
import
static
org
.
mockito
.
Mockito
.
when
;
/** 管理员理论题库树聚合、级联保护和题型服务端校验测试。 */
@ExtendWith
(
MockitoExtension
.
class
)
class
TheoreticalLibraryAdminServiceImplTest
{
@Mock
private
TheoreticalLibraryNodeMapper
nodeMapper
;
@Mock
private
TheoreticalLibraryMapper
libraryMapper
;
private
TheoreticalLibraryAdminServiceImpl
service
;
@BeforeEach
void
setUp
()
{
service
=
new
TheoreticalLibraryAdminServiceImpl
();
ReflectionTestUtils
.
setField
(
service
,
"nodeMapper"
,
nodeMapper
);
ReflectionTestUtils
.
setField
(
service
,
"libraryMapper"
,
libraryMapper
);
ReflectionTestUtils
.
setField
(
service
,
"objectMapper"
,
new
ObjectMapper
());
}
@Test
void
treeSearchShouldKeepAncestorsAndAggregateQuestionCount
()
{
TheoreticalLibraryNodeEntity
craft
=
node
(
"craft"
,
"0"
,
"CRAFT"
,
"污水"
,
"C-WATER"
);
TheoreticalLibraryNodeEntity
level
=
node
(
"level"
,
"craft"
,
"LEVEL"
,
"一级"
,
"L-1"
);
when
(
nodeMapper
.
selectList
(
any
())).
thenReturn
(
Arrays
.
asList
(
craft
,
level
));
TheoreticalLibraryNodeCountVO
count
=
new
TheoreticalLibraryNodeCountVO
();
count
.
setNodeId
(
"level"
);
count
.
setQuestionCount
(
3L
);
when
(
libraryMapper
.
selectQuestionCounts
(
"JOB"
)).
thenReturn
(
Collections
.
singletonList
(
count
));
List
<
TheoreticalLibraryNodeVO
>
result
=
service
.
tree
(
"JOB"
,
"一级"
);
assertEquals
(
1
,
result
.
size
());
assertEquals
(
"污水"
,
result
.
get
(
0
).
getName
());
assertEquals
(
3L
,
result
.
get
(
0
).
getQuestionCount
());
assertEquals
(
"一级"
,
result
.
get
(
0
).
getChildren
().
get
(
0
).
getName
());
}
@Test
void
nodeDeleteShouldRequireExplicitCascadeConfirmation
()
{
when
(
nodeMapper
.
selectById
(
"node-1"
))
.
thenReturn
(
node
(
"node-1"
,
"0"
,
"CRAFT"
,
"污水"
,
"C-WATER"
));
assertThrows
(
BusinessException
.
class
,
()
->
service
.
deleteNode
(
"node-1"
,
false
));
verify
(
libraryMapper
,
never
()).
delete
(
any
());
}
@Test
void
singleChoiceShouldRejectMoreThanOneCorrectOptionBeforeInsert
()
{
List
<
TheoreticalLibraryNodeEntity
>
path
=
completeJobPath
();
for
(
TheoreticalLibraryNodeEntity
node
:
path
)
{
when
(
nodeMapper
.
selectById
(
node
.
getId
())).
thenReturn
(
node
);
}
TheoreticalLibraryQuestionSaveDTO
body
=
new
TheoreticalLibraryQuestionSaveDTO
();
body
.
setNodeId
(
"point"
);
body
.
setType
(
"SINGLE"
);
body
.
setScore
(
2
D
);
body
.
setDifficulty
(
"MEDIUM"
);
body
.
setStatus
(
1
);
body
.
setStem
(
"测试题干"
);
TheoreticalLibraryOptionDTO
optionA
=
option
(
"A"
,
true
);
TheoreticalLibraryOptionDTO
optionB
=
option
(
"B"
,
true
);
body
.
setOptions
(
Arrays
.
asList
(
optionA
,
optionB
));
assertThrows
(
BusinessException
.
class
,
()
->
service
.
createQuestion
(
body
,
null
));
verify
(
libraryMapper
,
never
()).
insert
(
any
());
}
private
List
<
TheoreticalLibraryNodeEntity
>
completeJobPath
()
{
return
Arrays
.
asList
(
node
(
"craft"
,
"0"
,
"CRAFT"
,
"污水"
,
"CRAFT-WATER"
),
node
(
"level"
,
"craft"
,
"LEVEL"
,
"一级"
,
"LEVEL-1"
),
node
(
"chapter"
,
"level"
,
"CHAPTER"
,
"第一章"
,
"CH-1"
),
node
(
"section"
,
"chapter"
,
"SECTION"
,
"第一节"
,
"SEC-1"
),
node
(
"topic"
,
"section"
,
"TOPIC"
,
"第一目"
,
"TOPIC-1"
),
node
(
"point"
,
"topic"
,
"POINT"
,
"知识点"
,
"POINT-1"
));
}
private
TheoreticalLibraryNodeEntity
node
(
String
id
,
String
parentId
,
String
type
,
String
name
,
String
code
)
{
TheoreticalLibraryNodeEntity
node
=
new
TheoreticalLibraryNodeEntity
();
node
.
setId
(
id
);
node
.
setParentId
(
parentId
);
node
.
setBankType
(
"JOB"
);
node
.
setNodeType
(
type
);
node
.
setName
(
name
);
node
.
setCode
(
code
);
node
.
setSortNo
(
10
);
node
.
setStatus
(
1
);
return
node
;
}
private
TheoreticalLibraryOptionDTO
option
(
String
text
,
boolean
correct
)
{
TheoreticalLibraryOptionDTO
option
=
new
TheoreticalLibraryOptionDTO
();
option
.
setText
(
text
);
option
.
setCorrect
(
correct
);
return
option
;
}
}
practical-business/src/test/java/com/platform/business/service/impl/TheoreticalLibraryExcelServiceImplTest.java
0 → 100644
View file @
9fc77652
package
com.platform.business.service.impl
;
import
com.platform.exception.BusinessException
;
import
org.junit.jupiter.api.Test
;
import
org.springframework.mock.web.MockMultipartFile
;
import
org.springframework.mock.web.MockHttpServletResponse
;
import
org.apache.poi.xssf.usermodel.XSSFWorkbook
;
import
java.io.ByteArrayInputStream
;
import
static
org
.
junit
.
jupiter
.
api
.
Assertions
.
assertEquals
;
import
static
org
.
junit
.
jupiter
.
api
.
Assertions
.
assertThrows
;
/** Excel 导入入口的格式和文件大小边界测试。 */
class
TheoreticalLibraryExcelServiceImplTest
{
@Test
void
questionTemplateShouldContainStableImportHeaders
()
throws
Exception
{
TheoreticalLibraryExcelServiceImpl
service
=
new
TheoreticalLibraryExcelServiceImpl
();
MockHttpServletResponse
response
=
new
MockHttpServletResponse
();
service
.
template
(
"QUESTION"
,
"JOB"
,
response
);
try
(
XSSFWorkbook
workbook
=
new
XSSFWorkbook
(
new
ByteArrayInputStream
(
response
.
getContentAsByteArray
())))
{
assertEquals
(
"题号"
,
workbook
.
getSheetAt
(
0
).
getRow
(
0
).
getCell
(
0
).
getStringCellValue
());
assertEquals
(
"节点编码路径"
,
workbook
.
getSheetAt
(
0
).
getRow
(
0
).
getCell
(
1
).
getStringCellValue
());
assertEquals
(
"答案"
,
workbook
.
getSheetAt
(
0
).
getRow
(
0
).
getCell
(
14
).
getStringCellValue
());
}
}
@Test
void
importShouldRejectLegacyXlsBeforeReadingWorkbook
()
{
TheoreticalLibraryExcelServiceImpl
service
=
new
TheoreticalLibraryExcelServiceImpl
();
MockMultipartFile
file
=
new
MockMultipartFile
(
"file"
,
"questions.xls"
,
"application/vnd.ms-excel"
,
new
byte
[]{
1
});
assertThrows
(
BusinessException
.
class
,
()
->
service
.
importData
(
"QUESTION"
,
"JOB"
,
"ADD"
,
file
,
null
));
}
@Test
void
importShouldRejectFileLargerThanTenMegabytes
()
{
TheoreticalLibraryExcelServiceImpl
service
=
new
TheoreticalLibraryExcelServiceImpl
();
MockMultipartFile
file
=
new
MockMultipartFile
(
"file"
,
"questions.xlsx"
,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
,
new
byte
[
10
*
1024
*
1024
+
1
]);
assertThrows
(
BusinessException
.
class
,
()
->
service
.
importData
(
"QUESTION"
,
"JOB"
,
"ADD"
,
file
,
null
));
}
}
Prev
1
2
Next
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment