Skip to content
项目
群组
代码片段
帮助
当前项目
正在载入...
登录 / 注册
切换导航面板
S
studyweb
项目
项目
详情
活动
周期分析
仓库
仓库
文件
提交
分支
标签
贡献者
图表
比较
统计图
议题
0
议题
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
CI / CD
CI / CD
流水线
作业
日程
统计图
Wiki
Wiki
代码片段
代码片段
成员
成员
折叠边栏
关闭边栏
活动
图像
聊天
创建新问题
作业
提交
问题看板
Open sidebar
project
studyweb
Commits
58c1d2b9
提交
58c1d2b9
authored
7月 17, 2026
作者:
caifuming
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
ljy_完善项目模块
上级
2f089360
显示空白字符变更
内嵌
并排
正在显示
26 个修改的文件
包含
1847 行增加
和
204 行删除
+1847
-204
README.md
ai-service/README.md
+0
-0
auth.py
ai-service/app/ai_calling/auth.py
+7
-4
ai_chat.py
ai-service/app/api/ai_chat.py
+12
-3
health.py
ai-service/app/api/health.py
+22
-0
project.py
ai-service/app/api/project.py
+237
-16
main.py
ai-service/app/main.py
+3
-2
project_catalog.py
ai-service/app/project_catalog.py
+115
-0
project_recommend_response.schema.json
...app/prompt/schemas/project_recommend_response.schema.json
+31
-0
project_recommend_v1.yaml
ai-service/app/prompt/templates/project_recommend_v1.yaml
+20
-0
test_ai_calling.py
ai-service/tests/test_ai_calling.py
+295
-0
test_project_endpoints.py
ai-service/tests/test_project_endpoints.py
+156
-0
ProjectFileController.java
...orm/backend/project/controller/ProjectFileController.java
+40
-1
ProjectAiClientService.java
...tform/backend/project/service/ProjectAiClientService.java
+14
-4
ProjectFileService.java
.../platform/backend/project/service/ProjectFileService.java
+34
-3
ProjectPermissionService.java
...orm/backend/project/service/ProjectPermissionService.java
+16
-0
ProjectService.java
.../com/platform/backend/project/service/ProjectService.java
+2
-4
MinioStorageService.java
...platform/backend/project/storage/MinioStorageService.java
+37
-0
ProjectFileServiceTest.java
...tform/backend/project/service/ProjectFileServiceTest.java
+30
-6
package.json
frontend/package.json
+5
-3
pnpm-lock.yaml
frontend/pnpm-lock.yaml
+246
-0
App.tsx
frontend/src/App.tsx
+8
-6
ProjectPage.tsx
frontend/src/pages/ProjectPage.tsx
+240
-18
permissionApi.ts
frontend/src/services/permissionApi.ts
+1
-0
useAuthStore.ts
frontend/src/stores/useAuthStore.ts
+19
-101
import_data.py
milvus-lab/scripts/import_data.py
+45
-0
start.sh
scripts/start.sh
+212
-33
没有找到文件。
ai-service/README.md
浏览文件 @
58c1d2b9
ai-service/app/ai_calling/auth.py
浏览文件 @
58c1d2b9
...
...
@@ -3,19 +3,22 @@ from __future__ import annotations
import
os
import
secrets
from
typing
import
Annotated
from
fastapi
import
H
TTPException
,
Request
,
status
from
fastapi
import
H
eader
,
HTTPException
,
status
def
_get_expected_internal_token
()
->
str
:
return
os
.
getenv
(
"AI_INTERNAL_TOKEN"
,
"dev-internal-token"
)
def
require_internal_token
(
request
:
Request
,
async
def
require_internal_token
(
x_internal_token
:
Annotated
[
str
|
None
,
Header
(
alias
=
"X-Internal-Token"
),
]
=
None
,
)
->
None
:
expected_token
=
_get_expected_internal_token
()
x_internal_token
=
request
.
headers
.
get
(
"X-Internal-Token"
)
if
not
x_internal_token
or
not
secrets
.
compare_digest
(
x_internal_token
,
expected_token
):
raise
HTTPException
(
status_code
=
status
.
HTTP_401_UNAUTHORIZED
,
...
...
ai-service/app/api/ai_chat.py
浏览文件 @
58c1d2b9
"""AI chat API routes."""
from
fastapi
import
APIRouter
,
Depends
from
fastapi.responses
import
JSONResponse
from
app.ai_calling.auth
import
require_internal_token
from
app.ai_calling.schemas
import
AIChatRequest
,
AIChatResponse
,
AIHealthResponse
...
...
@@ -15,8 +16,16 @@ async def chat(req: AIChatRequest) -> AIChatResponse:
return
await
service
.
chat
(
req
)
@router.get
(
"/health"
,
response_model
=
AIHealthResponse
,
dependencies
=
[
Depends
(
require_internal_token
)])
async
def
ai_health
()
->
AIHealthResponse
:
@router.get
(
"/health"
,
response_model
=
AIHealthResponse
,
dependencies
=
[
Depends
(
require_internal_token
)],
responses
=
{
503
:
{
"model"
:
AIHealthResponse
}},
)
async
def
ai_health
():
"""Return AI-calling specific health status without changing legacy health output."""
service
=
get_ai_service
()
return
service
.
get_health_status
()
health
=
service
.
get_health_status
()
if
health
.
unhealthy
:
return
JSONResponse
(
status_code
=
503
,
content
=
health
.
model_dump
())
return
health
ai-service/app/api/health.py
浏览文件 @
58c1d2b9
"""健康检查路由。"""
from
fastapi
import
APIRouter
from
fastapi.responses
import
JSONResponse
from
app.ai_calling.service
import
get_ai_service
router
=
APIRouter
()
...
...
@@ -7,3 +10,22 @@ router = APIRouter()
@router.get
(
""
)
async
def
health
()
->
dict
:
return
{
"status"
:
"ok"
,
"service"
:
"ai-service"
,
"version"
:
"1.0.0"
}
@router.get
(
"/readiness"
,
responses
=
{
503
:
{
"description"
:
"AI calling layer is unhealthy."
}},
)
async
def
readiness
():
"""Return 503 when the AI calling layer has crossed its failure threshold."""
ai_health
=
get_ai_service
()
.
get_health_status
()
payload
=
{
"status"
:
"unhealthy"
if
ai_health
.
unhealthy
else
"ok"
,
"service"
:
"ai-service"
,
"checks"
:
{
"ai_calling"
:
ai_health
.
status
,
},
}
if
ai_health
.
unhealthy
:
return
JSONResponse
(
status_code
=
503
,
content
=
payload
)
return
payload
ai-service/app/api/project.py
浏览文件 @
58c1d2b9
"""Project-module AI business endpoints."""
from
__future__
import
annotations
import
json
import
time
from
typing
import
Any
from
pydantic
import
AliasChoices
,
BaseModel
,
Field
from
fastapi
import
APIRouter
,
HTTPException
from
fastapi
import
APIRouter
,
Depends
,
HTTPException
from
app.ai_calling.auth
import
require_internal_token
from
app.ai_calling.schemas
import
AIChatRequest
from
app.ai_calling.service
import
get_ai_service
from
app.project_catalog
import
find_github_knowledge
,
load_github_candidates
from
app.vector_store
import
VectorIndexService
router
=
APIRouter
()
router
=
APIRouter
(
dependencies
=
[
Depends
(
require_internal_token
)]
)
vector_index
=
VectorIndexService
()
...
...
@@ -169,7 +174,31 @@ async def score_difficulty(req: DifficultyScoreRequest) -> DifficultyScoreRespon
@router.post
(
"/knowledge/extract"
,
response_model
=
KnowledgeExtractResponse
)
async
def
extract_knowledge
(
req
:
KnowledgeExtractRequest
)
->
KnowledgeExtractResponse
:
"""Return deterministic MVP knowledge points for project-module integration."""
"""Extract knowledge from collected GitHub data, AI, or deterministic fallback."""
if
req
.
project_type
==
"github"
:
record
=
find_github_knowledge
(
req
.
source_code_url
,
req
.
project_name
)
local_points
=
_knowledge_points_from_record
(
record
,
req
)
if
local_points
:
return
KnowledgeExtractResponse
(
success
=
True
,
data
=
KnowledgeExtractData
(
knowledge_points
=
local_points
),
)
ai_points
=
await
_extract_knowledge_with_ai
(
req
)
if
ai_points
:
return
KnowledgeExtractResponse
(
success
=
True
,
data
=
KnowledgeExtractData
(
knowledge_points
=
ai_points
),
)
return
KnowledgeExtractResponse
(
success
=
True
,
data
=
KnowledgeExtractData
(
knowledge_points
=
_rule_knowledge_points
(
req
)),
)
def
_rule_knowledge_points
(
req
:
KnowledgeExtractRequest
)
->
list
[
KnowledgePointData
]:
"""Preserve the existing deterministic response as the final fallback."""
points
:
list
[
KnowledgePointData
]
=
[
KnowledgePointData
(
name
=
"项目需求理解"
,
...
...
@@ -215,32 +244,33 @@ async def extract_knowledge(req: KnowledgeExtractRequest) -> KnowledgeExtractRes
if
len
(
points
)
==
1
:
points
.
extend
(
_fallback_points
(
req
))
return
KnowledgeExtractResponse
(
success
=
True
,
data
=
KnowledgeExtractData
(
knowledge_points
=
points
),
)
return
points
@router.post
(
"/recommend"
,
response_model
=
RecommendResponse
)
async
def
recommend_projects
(
req
:
RecommendRequest
)
->
RecommendResponse
:
"""R
eturn deterministic MVP recommendations for project-module integration
."""
"""R
ank supplied candidates or the local GitHub catalog, then enhance reasons with AI
."""
started
=
time
.
perf_counter
()
seed_tags
=
_clean_values
(
req
.
seed_project
.
tags
+
req
.
seed_project
.
tech_stack
)
scored
:
list
[
tuple
[
float
,
RecommendItem
]]
=
[]
vector_rank
=
_vector_rank
(
req
)
for
candidate
in
req
.
candidates
:
if
candidate
.
project_id
in
set
(
req
.
exclude_ids
):
candidates
=
list
(
req
.
candidates
)
if
not
candidates
and
req
.
project_type
==
"github"
:
candidates
=
[
RecommendCandidate
(
**
item
)
for
item
in
load_github_candidates
()]
excluded_ids
=
set
(
req
.
exclude_ids
)
for
candidate
in
candidates
:
if
candidate
.
project_id
in
excluded_ids
:
continue
candidate_tags
=
_clean_values
(
candidate
.
tags
+
candidate
.
tech_stack
)
shared
=
[
tag
for
tag
in
candidate_tags
if
tag
in
seed_tags
]
[:
4
]
shared
=
_shared_values
(
seed_tags
,
candidate_tags
)
[:
4
]
overlap
=
len
(
shared
)
difficulty_bonus
=
_difficulty_similarity
(
req
.
seed_project
.
difficulty_level
,
candidate
.
difficulty_level
)
stars_bonus
=
min
((
candidate
.
stars
or
0
)
/
5000.0
,
0.15
)
vector_bonus
=
vector_rank
.
get
(
candidate
.
project_id
,
0.0
)
# 推荐主链路:优先使用向量召回得分增强排序;没有向量结果时仍按标签/难度兜底。
score
=
min
(
0.99
,
0.30
+
overlap
*
0.16
+
difficulty_bonus
*
0.30
+
stars_bonus
+
vector_bonus
*
0.22
)
reason_parts
=
[]
reason_parts
:
list
[
str
]
=
[]
if
vector_bonus
>
0
:
reason_parts
.
append
(
"向量语义相似度较高"
)
if
shared
:
...
...
@@ -258,18 +288,18 @@ async def recommend_projects(req: RecommendRequest) -> RecommendResponse:
difficulty_level
=
candidate
.
difficulty_level
,
tech_stack
=
candidate
.
tech_stack
,
match_score
=
round
(
score
,
4
),
match_reason
=
f
"与种子项目“{req.seed_project.name}”匹配:{','.join(reason_parts)}。"
,
match_reason
=
_build_rule_reason
(
req
.
seed_project
.
name
,
candidate
,
reason_parts
)
,
stars
=
candidate
.
stars
,
)
scored
.
append
((
score
,
item
))
recommendations
=
[
item
for
_
,
item
in
sorted
(
scored
,
key
=
lambda
pair
:
pair
[
0
],
reverse
=
True
)[:
max
(
req
.
limit
,
1
)]]
ai_enhanced
=
await
_enhance_recommendation_reasons
(
req
,
recommendations
)
total_time
=
int
((
time
.
perf_counter
()
-
started
)
*
1000
)
source
=
"vector"
if
vector_rank
else
"ai"
return
RecommendResponse
(
success
=
True
,
data
=
RecommendData
(
source
=
source
,
source
=
"ai"
if
ai_enhanced
else
"fallback"
,
total_time
=
total_time
,
recommendations
=
recommendations
,
),
...
...
@@ -317,6 +347,197 @@ def _clean_values(values: list[str] | None) -> list[str]:
return
cleaned
def
_shared_values
(
left
:
list
[
str
],
right
:
list
[
str
])
->
list
[
str
]:
left_keys
=
{
value
.
casefold
()
for
value
in
left
}
return
[
value
for
value
in
right
if
value
.
casefold
()
in
left_keys
]
def
_build_rule_reason
(
seed_project_name
:
str
,
candidate
:
RecommendCandidate
,
reason_parts
:
list
[
str
],
)
->
str
:
match_detail
=
"、"
.
join
(
reason_parts
)
if
reason_parts
else
"项目主题与训练方向接近"
difficulty
=
candidate
.
difficulty_level
or
"待评估"
reason
=
(
f
"候选项目“{candidate.project_name}”与种子项目“{seed_project_name}”存在匹配,主要依据是"
f
"{match_detail}。候选项目难度为{difficulty},可用于继续练习相关技术并比较工程实现差异;"
"建议结合 README、核心目录和实际运行结果确认学习成本。"
)
return
reason
[:
200
]
async
def
_enhance_recommendation_reasons
(
req
:
RecommendRequest
,
recommendations
:
list
[
RecommendItem
],
)
->
bool
:
if
not
recommendations
:
return
False
request
=
AIChatRequest
(
task
=
"project_recommend"
,
prompt_name
=
"project_recommend_v1"
,
variables
=
{
"seed_project_json"
:
json
.
dumps
(
req
.
seed_project
.
model_dump
(),
ensure_ascii
=
False
),
"candidates_json"
:
json
.
dumps
(
[
{
"project_id"
:
item
.
project_id
,
"project_name"
:
item
.
project_name
,
"description"
:
item
.
description
,
"difficulty_level"
:
item
.
difficulty_level
,
"tech_stack"
:
item
.
tech_stack
,
"base_match_score"
:
item
.
match_score
,
}
for
item
in
recommendations
],
ensure_ascii
=
False
,
),
},
response_format
=
"json"
,
temperature
=
0.2
,
timeout_seconds
=
6.0
,
)
try
:
response
=
await
get_ai_service
()
.
chat
(
request
)
except
Exception
:
return
False
if
not
response
.
success
or
not
isinstance
(
response
.
data
.
structured
,
dict
):
return
False
raw_items
=
response
.
data
.
structured
.
get
(
"recommendations"
)
if
not
isinstance
(
raw_items
,
list
):
return
False
reasons
:
dict
[
int
,
str
]
=
{}
for
item
in
raw_items
:
if
not
isinstance
(
item
,
dict
):
continue
project_id
=
item
.
get
(
"project_id"
)
reason
=
str
(
item
.
get
(
"match_reason"
)
or
""
)
.
strip
()
if
isinstance
(
project_id
,
int
)
and
50
<=
len
(
reason
)
<=
200
:
reasons
[
project_id
]
=
reason
changed
=
0
for
recommendation
in
recommendations
:
reason
=
reasons
.
get
(
recommendation
.
project_id
)
if
reason
:
recommendation
.
match_reason
=
reason
changed
+=
1
return
changed
==
len
(
recommendations
)
async
def
_extract_knowledge_with_ai
(
req
:
KnowledgeExtractRequest
)
->
list
[
KnowledgePointData
]:
project_content
=
(
req
.
project_content
or
""
)
.
strip
()
if
not
project_content
:
project_content
=
"
\n
"
.
join
(
value
for
value
in
[
f
"Source code: {req.source_code_url}"
if
req
.
source_code_url
else
""
,
f
"Requirement document: {req.requirement_doc_url}"
if
req
.
requirement_doc_url
else
""
,
f
"Tech stack: {', '.join(_clean_values(req.tech_stack))}"
if
req
.
tech_stack
else
""
,
f
"Tags: {', '.join(_clean_values(req.knowledge_tags or req.tags))}"
if
(
req
.
knowledge_tags
or
req
.
tags
)
else
""
,
]
if
value
)
if
not
project_content
:
return
[]
request
=
AIChatRequest
(
task
=
"knowledge_extract"
,
prompt_name
=
"knowledge_extract_v1"
,
variables
=
{
"project_name"
:
req
.
project_name
or
f
"project-{req.project_id}"
,
"project_content"
:
project_content
[:
12000
],
},
response_format
=
"json"
,
temperature
=
0.1
,
timeout_seconds
=
6.0
,
)
try
:
response
=
await
get_ai_service
()
.
chat
(
request
)
except
Exception
:
return
[]
# The mock provider verifies the calling layer; rule/local results remain more useful for business output.
if
not
response
.
success
or
response
.
provider
==
"mock"
or
not
isinstance
(
response
.
data
.
structured
,
dict
):
return
[]
raw_points
=
response
.
data
.
structured
.
get
(
"knowledge_points"
)
if
not
isinstance
(
raw_points
,
list
):
return
[]
points
:
list
[
KnowledgePointData
]
=
[]
for
item
in
raw_points
:
if
not
isinstance
(
item
,
dict
):
continue
name
=
str
(
item
.
get
(
"name"
)
or
""
)
.
strip
()
description
=
str
(
item
.
get
(
"description"
)
or
""
)
.
strip
()
if
not
name
or
not
description
:
continue
try
:
estimated_minutes
=
max
(
int
(
item
.
get
(
"estimated_minutes"
)
or
60
),
1
)
except
(
TypeError
,
ValueError
):
estimated_minutes
=
60
points
.
append
(
KnowledgePointData
(
name
=
name
,
description
=
description
,
category
=
"skill"
,
difficulty
=
_map_ai_difficulty
(
str
(
item
.
get
(
"difficulty"
)
or
""
)),
estimated_hours
=
round
(
estimated_minutes
/
60.0
,
2
),
material_url
=
req
.
source_code_url
or
req
.
requirement_doc_url
,
prerequisites
=
_clean_values
(
item
.
get
(
"prerequisites"
)),
)
)
return
points
def
_knowledge_points_from_record
(
record
:
dict
[
str
,
Any
]
|
None
,
req
:
KnowledgeExtractRequest
,
)
->
list
[
KnowledgePointData
]:
if
not
record
:
return
[]
raw_points
=
record
.
get
(
"knowledge_points"
)
if
not
isinstance
(
raw_points
,
list
):
return
[]
points
:
list
[
KnowledgePointData
]
=
[]
previous_name
:
str
|
None
=
None
for
item
in
raw_points
:
if
not
isinstance
(
item
,
dict
):
continue
name
=
str
(
item
.
get
(
"name"
)
or
""
)
.
strip
()
description
=
str
(
item
.
get
(
"description"
)
or
""
)
.
strip
()
if
not
name
or
not
description
:
continue
prerequisites
=
[
previous_name
]
if
previous_name
else
[]
points
.
append
(
KnowledgePointData
(
name
=
name
,
description
=
description
,
category
=
str
(
item
.
get
(
"category"
)
or
"skill"
),
difficulty
=
_knowledge_difficulty
(
req
.
difficulty_level
),
estimated_hours
=
3.0
if
str
(
item
.
get
(
"importance"
)
or
""
)
==
"高"
else
2.0
,
material_url
=
str
(
record
.
get
(
"repo_url"
)
or
req
.
source_code_url
or
""
)
or
None
,
prerequisites
=
prerequisites
,
)
)
previous_name
=
name
return
points
def
_map_ai_difficulty
(
value
:
str
)
->
str
:
return
{
"beginner"
:
"easy"
,
"intermediate"
:
"medium"
,
"advanced"
:
"hard"
,
"easy"
:
"easy"
,
"medium"
:
"medium"
,
"hard"
:
"hard"
,
}
.
get
(
value
.
casefold
(),
"medium"
)
def
_knowledge_difficulty
(
level
:
str
|
None
)
->
str
:
return
{
"L1"
:
"easy"
,
...
...
ai-service/app/main.py
浏览文件 @
58c1d2b9
...
...
@@ -16,11 +16,12 @@ app.add_middleware(
allow_headers
=
[
"*"
],
)
from
app.api
import
ai
,
health
,
knowledge
# noqa: E402
from
app.api
import
ai
_chat
,
health
,
knowledge
,
project
# noqa: E402
app
.
include_router
(
health
.
router
,
prefix
=
"/api/health"
,
tags
=
[
"health"
])
app
.
include_router
(
knowledge
.
router
,
prefix
=
"/api/knowledge"
,
tags
=
[
"knowledge"
])
app
.
include_router
(
ai
.
router
,
prefix
=
"/api/v1/ai"
,
tags
=
[
"ai"
])
app
.
include_router
(
ai_chat
.
router
,
prefix
=
"/api/v1/ai"
,
tags
=
[
"ai"
])
app
.
include_router
(
project
.
router
,
prefix
=
"/ai"
,
tags
=
[
"project-ai"
])
if
__name__
==
"__main__"
:
...
...
ai-service/app/project_catalog.py
0 → 100644
浏览文件 @
58c1d2b9
"""Read-only access to locally collected GitHub repository knowledge."""
from
__future__
import
annotations
import
hashlib
import
json
from
pathlib
import
Path
from
typing
import
Any
PROJECT_ROOT
=
Path
(
__file__
)
.
resolve
()
.
parents
[
2
]
GITHUB_DATA_DIR
=
PROJECT_ROOT
/
"shared"
/
"data"
/
"github_repos"
KNOWLEDGE_OUTPUTS_DIR
=
GITHUB_DATA_DIR
/
"knowledge_outputs"
NORMALIZED_DIR
=
GITHUB_DATA_DIR
/
"normalized"
def
load_github_candidates
()
->
list
[
dict
[
str
,
Any
]]:
"""Convert collected knowledge records into recommendation candidates."""
candidates
:
list
[
dict
[
str
,
Any
]]
=
[]
for
path
in
_json_files
(
KNOWLEDGE_OUTPUTS_DIR
):
knowledge
=
_load_json
(
path
)
if
not
knowledge
:
continue
normalized
=
_load_json
(
NORMALIZED_DIR
/
path
.
name
)
or
{}
repo_url
=
str
(
knowledge
.
get
(
"repo_url"
)
or
normalized
.
get
(
"repo_url"
)
or
""
)
.
strip
()
repo_name
=
str
(
knowledge
.
get
(
"repo_name"
)
or
normalized
.
get
(
"repo_name"
)
or
path
.
stem
)
.
strip
()
if
not
repo_url
or
not
repo_name
:
continue
tags
=
_clean_strings
(
knowledge
.
get
(
"tags"
))
primary_language
=
str
(
normalized
.
get
(
"primary_language"
)
or
""
)
.
strip
()
tech_stack
=
_clean_strings
([
primary_language
,
*
tags
[:
5
]])
candidates
.
append
(
{
"project_id"
:
stable_project_id
(
repo_url
),
"project_name"
:
repo_name
,
"project_type"
:
"github"
,
"description"
:
str
(
knowledge
.
get
(
"summary"
)
or
""
)
.
strip
()
or
None
,
"difficulty_level"
:
"L3"
,
"tech_stack"
:
tech_stack
,
"tags"
:
tags
,
"stars"
:
_optional_int
(
normalized
.
get
(
"stars"
)),
"github_url"
:
repo_url
,
}
)
return
candidates
def
find_github_knowledge
(
source_code_url
:
str
|
None
,
project_name
:
str
|
None
,
)
->
dict
[
str
,
Any
]
|
None
:
"""Find a collected knowledge record by GitHub URL, then by repository name."""
normalized_url
=
_normalize_repo_url
(
source_code_url
)
normalized_name
=
(
project_name
or
""
)
.
strip
()
.
casefold
()
name_match
:
dict
[
str
,
Any
]
|
None
=
None
for
path
in
_json_files
(
KNOWLEDGE_OUTPUTS_DIR
):
record
=
_load_json
(
path
)
if
not
record
:
continue
repo_url
=
_normalize_repo_url
(
str
(
record
.
get
(
"repo_url"
)
or
""
))
if
normalized_url
and
repo_url
==
normalized_url
:
return
record
repo_name
=
str
(
record
.
get
(
"repo_name"
)
or
""
)
.
strip
()
.
casefold
()
if
normalized_name
and
repo_name
==
normalized_name
:
name_match
=
record
return
name_match
def
stable_project_id
(
repo_url
:
str
)
->
int
:
"""Build a stable positive ID for standalone local-catalog responses."""
digest
=
hashlib
.
sha256
(
_normalize_repo_url
(
repo_url
)
.
encode
(
"utf-8"
))
.
digest
()
return
int
.
from_bytes
(
digest
[:
8
],
"big"
)
%
2
_000_000_000
+
1
def
_json_files
(
directory
:
Path
)
->
list
[
Path
]:
if
not
directory
.
is_dir
():
return
[]
return
sorted
(
path
for
path
in
directory
.
glob
(
"*.json"
)
if
path
.
is_file
())
def
_load_json
(
path
:
Path
)
->
dict
[
str
,
Any
]
|
None
:
try
:
payload
=
json
.
loads
(
path
.
read_text
(
encoding
=
"utf-8"
))
except
(
OSError
,
json
.
JSONDecodeError
):
return
None
return
payload
if
isinstance
(
payload
,
dict
)
else
None
def
_normalize_repo_url
(
value
:
str
|
None
)
->
str
:
url
=
(
value
or
""
)
.
strip
()
.
rstrip
(
"/"
)
if
url
.
endswith
(
".git"
):
url
=
url
[:
-
4
]
return
url
.
casefold
()
def
_clean_strings
(
values
:
Any
)
->
list
[
str
]:
if
not
isinstance
(
values
,
list
):
return
[]
cleaned
:
list
[
str
]
=
[]
seen
:
set
[
str
]
=
set
()
for
value
in
values
:
item
=
str
(
value
or
""
)
.
strip
()
key
=
item
.
casefold
()
if
item
and
key
not
in
seen
:
seen
.
add
(
key
)
cleaned
.
append
(
item
)
return
cleaned
def
_optional_int
(
value
:
Any
)
->
int
|
None
:
try
:
return
int
(
value
)
if
value
is
not
None
else
None
except
(
TypeError
,
ValueError
):
return
None
ai-service/app/prompt/schemas/project_recommend_response.schema.json
0 → 100644
浏览文件 @
58c1d2b9
{
"$schema"
:
"https://json-schema.org/draft/2020-12/schema"
,
"type"
:
"object"
,
"additionalProperties"
:
false
,
"required"
:
[
"recommendations"
],
"properties"
:
{
"recommendations"
:
{
"type"
:
"array"
,
"items"
:
{
"type"
:
"object"
,
"additionalProperties"
:
false
,
"required"
:
[
"project_id"
,
"match_reason"
],
"properties"
:
{
"project_id"
:
{
"type"
:
"integer"
},
"match_reason"
:
{
"type"
:
"string"
,
"minLength"
:
50
,
"maxLength"
:
200
}
}
}
}
}
}
ai-service/app/prompt/templates/project_recommend_v1.yaml
0 → 100644
浏览文件 @
58c1d2b9
name
:
project_recommend_v1
version
:
v1
response_schema
:
project_recommend_response.schema.json
required_variables
:
-
seed_project_json
-
candidates_json
system
:
|
You generate recommendation reasons for an intern training platform.
Return strict JSON only. Do not add candidates or change project IDs.
Each match_reason must be 50 to 200 Chinese characters and must explain
concrete overlap, learning value, and one practical review suggestion.
user
:
|
Seed project JSON:
{seed_project_json}
<CANDIDATES_JSON>
{candidates_json}
</CANDIDATES_JSON>
Return one match_reason for every candidate project_id.
ai-service/tests/test_ai_calling.py
0 → 100644
浏览文件 @
58c1d2b9
from
__future__
import
annotations
import
asyncio
import
os
import
unittest
from
unittest.mock
import
patch
import
httpx
from
app.ai_calling.call_log
import
CallLogger
from
app.ai_calling.errors
import
MODEL_UNAVAILABLE
,
AIServiceError
from
app.ai_calling.health
import
AIServiceHealthTracker
from
app.ai_calling.limiter
import
InMemoryRateLimiter
from
app.ai_calling.schemas
import
AIChatRequest
from
app.ai_calling.service
import
AISettings
,
AICallingService
,
get_ai_service
from
app.llm.base
import
LLMProvider
,
ProviderRequest
,
ProviderResult
from
app.main
import
app
from
app.prompt.loader
import
PromptLoader
class
SequenceProvider
(
LLMProvider
):
name
=
"sequence"
def
__init__
(
self
,
outcomes
:
list
[
ProviderResult
|
AIServiceError
])
->
None
:
self
.
outcomes
=
outcomes
self
.
calls
=
0
async
def
chat
(
self
,
request
:
ProviderRequest
)
->
ProviderResult
:
outcome
=
self
.
outcomes
[
min
(
self
.
calls
,
len
(
self
.
outcomes
)
-
1
)]
self
.
calls
+=
1
if
isinstance
(
outcome
,
AIServiceError
):
raise
outcome
return
outcome
class
SlowProvider
(
LLMProvider
):
name
=
"slow"
async
def
chat
(
self
,
request
:
ProviderRequest
)
->
ProviderResult
:
await
asyncio
.
sleep
(
0.05
)
return
ProviderResult
(
content
=
"late"
)
class
StaticProviderFactory
:
def
__init__
(
self
,
provider
:
LLMProvider
)
->
None
:
self
.
provider
=
provider
def
create
(
self
,
provider_name
:
str
)
->
LLMProvider
:
return
self
.
provider
class
CapturingCallLogger
(
CallLogger
):
def
__init__
(
self
)
->
None
:
self
.
events
:
list
[
dict
]
=
[]
def
log
(
self
,
payload
:
dict
)
->
None
:
self
.
events
.
append
(
payload
)
def
build_settings
(
*
,
timeout
:
float
=
0.05
,
retries
:
int
=
0
)
->
AISettings
:
return
AISettings
(
default_provider
=
"test"
,
default_model
=
"test-model"
,
fallback_provider
=
None
,
fallback_model
=
None
,
request_timeout_seconds
=
timeout
,
max_retries
=
retries
,
rate_limit_rps
=
10
,
failure_threshold
=
2
,
openai_api_key
=
None
,
openai_base_url
=
"https://api.openai.com/v1"
,
openai_organization
=
None
,
tongyi_api_key
=
None
,
tongyi_base_url
=
None
,
wenxin_api_key
=
None
,
wenxin_base_url
=
None
,
)
def
build_request
(
*
,
timeout
:
float
=
0.05
)
->
AIChatRequest
:
return
AIChatRequest
(
prompt_name
=
"recommend_v1"
,
variables
=
{
"project_name"
:
"demo"
,
"project_context"
:
"Python API"
,
},
timeout_seconds
=
timeout
,
)
class
AICallingServiceTests
(
unittest
.
IsolatedAsyncioTestCase
):
async
def
test_retryable_failure_is_retried
(
self
)
->
None
:
provider
=
SequenceProvider
(
[
AIServiceError
(
MODEL_UNAVAILABLE
,
"temporary"
,
retryable
=
True
),
ProviderResult
(
content
=
"ok"
),
]
)
call_logger
=
CapturingCallLogger
()
service
=
AICallingService
(
settings
=
build_settings
(
retries
=
1
),
prompt_loader
=
PromptLoader
(),
provider_factory
=
StaticProviderFactory
(
provider
),
limiter
=
InMemoryRateLimiter
(
max_requests
=
10
),
health_tracker
=
AIServiceHealthTracker
(
failure_threshold
=
2
),
call_logger
=
call_logger
,
)
response
=
await
service
.
chat
(
build_request
())
self
.
assertTrue
(
response
.
success
)
self
.
assertEqual
(
provider
.
calls
,
2
)
self
.
assertEqual
(
len
(
call_logger
.
events
),
1
)
self
.
assertTrue
(
call_logger
.
events
[
0
][
"success"
])
async
def
test_timeout_returns_fallback_without_raising
(
self
)
->
None
:
service
=
AICallingService
(
settings
=
build_settings
(
timeout
=
0.01
),
prompt_loader
=
PromptLoader
(),
provider_factory
=
StaticProviderFactory
(
SlowProvider
()),
limiter
=
InMemoryRateLimiter
(
max_requests
=
10
),
health_tracker
=
AIServiceHealthTracker
(
failure_threshold
=
2
),
call_logger
=
CapturingCallLogger
(),
)
response
=
await
service
.
chat
(
build_request
(
timeout
=
0.02
))
self
.
assertFalse
(
response
.
success
)
self
.
assertTrue
(
response
.
fallback
)
self
.
assertIsNotNone
(
response
.
error
)
async
def
test_invalid_structured_output_returns_fallback
(
self
)
->
None
:
provider
=
SequenceProvider
(
[
ProviderResult
(
content
=
'{"unexpected": true}'
,
structured
=
{
"unexpected"
:
True
},
)
]
)
service
=
AICallingService
(
settings
=
build_settings
(),
prompt_loader
=
PromptLoader
(),
provider_factory
=
StaticProviderFactory
(
provider
),
limiter
=
InMemoryRateLimiter
(
max_requests
=
10
),
health_tracker
=
AIServiceHealthTracker
(
failure_threshold
=
2
),
call_logger
=
CapturingCallLogger
(),
)
request
=
AIChatRequest
(
prompt_name
=
"knowledge_extract_v1"
,
variables
=
{
"project_name"
:
"demo"
,
"project_content"
:
"Python API"
,
},
response_format
=
"json"
,
)
response
=
await
service
.
chat
(
request
)
self
.
assertFalse
(
response
.
success
)
self
.
assertTrue
(
response
.
fallback
)
self
.
assertEqual
(
response
.
error
.
code
,
"MODEL_INVALID_RESPONSE"
)
class
AIEndpointTests
(
unittest
.
IsolatedAsyncioTestCase
):
async
def
asyncTearDown
(
self
)
->
None
:
get_ai_service
.
cache_clear
()
async
def
test_internal_token_protects_chat_and_project_routes
(
self
)
->
None
:
with
patch
.
dict
(
os
.
environ
,
{
"AI_INTERNAL_TOKEN"
:
"test-token"
,
"AI_DEFAULT_PROVIDER"
:
"mock"
,
"AI_DEFAULT_MODEL"
:
"mock-model"
,
},
clear
=
False
,
):
get_ai_service
.
cache_clear
()
transport
=
httpx
.
ASGITransport
(
app
=
app
)
async
with
httpx
.
AsyncClient
(
transport
=
transport
,
base_url
=
"http://test"
)
as
client
:
chat_payload
=
{
"prompt_name"
:
"recommend_v1"
,
"variables"
:
{
"project_name"
:
"demo"
,
"project_context"
:
"Python API"
,
},
}
unauthorized_chat
=
await
client
.
post
(
"/api/v1/ai/chat"
,
json
=
chat_payload
)
authorized_chat
=
await
client
.
post
(
"/api/v1/ai/chat"
,
json
=
chat_payload
,
headers
=
{
"X-Internal-Token"
:
"test-token"
},
)
unauthorized_project
=
await
client
.
post
(
"/ai/difficulty/score"
,
json
=
{
"project_id"
:
1
},
)
authorized_project
=
await
client
.
post
(
"/ai/difficulty/score"
,
json
=
{
"project_id"
:
1
},
headers
=
{
"X-Internal-Token"
:
"test-token"
},
)
self
.
assertEqual
(
unauthorized_chat
.
status_code
,
401
)
self
.
assertEqual
(
authorized_chat
.
status_code
,
200
)
self
.
assertTrue
(
authorized_chat
.
json
()[
"success"
])
self
.
assertEqual
(
unauthorized_project
.
status_code
,
401
)
self
.
assertEqual
(
authorized_project
.
status_code
,
200
)
async
def
test_primary_failure_uses_configured_fallback_provider
(
self
)
->
None
:
with
patch
.
dict
(
os
.
environ
,
{
"AI_INTERNAL_TOKEN"
:
"test-token"
,
"AI_DEFAULT_PROVIDER"
:
"unsupported"
,
"AI_DEFAULT_MODEL"
:
"test-model"
,
"AI_FALLBACK_PROVIDER"
:
"mock"
,
"AI_FALLBACK_MODEL"
:
"mock-model"
,
"AI_RATE_LIMIT_RPS"
:
"10"
,
},
clear
=
False
,
):
get_ai_service
.
cache_clear
()
transport
=
httpx
.
ASGITransport
(
app
=
app
)
async
with
httpx
.
AsyncClient
(
transport
=
transport
,
base_url
=
"http://test"
)
as
client
:
response
=
await
client
.
post
(
"/api/v1/ai/chat"
,
headers
=
{
"X-Internal-Token"
:
"test-token"
},
json
=
{
"prompt_name"
:
"recommend_v1"
,
"variables"
:
{
"project_name"
:
"demo"
,
"project_context"
:
"Python API"
,
},
},
)
self
.
assertEqual
(
response
.
status_code
,
200
)
self
.
assertTrue
(
response
.
json
()[
"success"
])
self
.
assertTrue
(
response
.
json
()[
"fallback"
])
self
.
assertEqual
(
response
.
json
()[
"provider"
],
"mock"
)
async
def
test_unhealthy_status_returns_503_but_liveness_stays_200
(
self
)
->
None
:
with
patch
.
dict
(
os
.
environ
,
{
"AI_INTERNAL_TOKEN"
:
"test-token"
,
"AI_DEFAULT_PROVIDER"
:
"unsupported"
,
"AI_DEFAULT_MODEL"
:
"test-model"
,
"AI_FALLBACK_PROVIDER"
:
""
,
"AI_FALLBACK_MODEL"
:
""
,
"AI_FAILURE_THRESHOLD"
:
"2"
,
"AI_RATE_LIMIT_RPS"
:
"10"
,
},
clear
=
False
,
):
get_ai_service
.
cache_clear
()
transport
=
httpx
.
ASGITransport
(
app
=
app
)
async
with
httpx
.
AsyncClient
(
transport
=
transport
,
base_url
=
"http://test"
)
as
client
:
payload
=
{
"prompt_name"
:
"recommend_v1"
,
"variables"
:
{
"project_name"
:
"demo"
,
"project_context"
:
"Python API"
,
},
}
for
_
in
range
(
2
):
failure
=
await
client
.
post
(
"/api/v1/ai/chat"
,
headers
=
{
"X-Internal-Token"
:
"test-token"
},
json
=
payload
,
)
self
.
assertEqual
(
failure
.
status_code
,
200
)
self
.
assertFalse
(
failure
.
json
()[
"success"
])
self
.
assertTrue
(
failure
.
json
()[
"fallback"
])
ai_health
=
await
client
.
get
(
"/api/v1/ai/health"
,
headers
=
{
"X-Internal-Token"
:
"test-token"
},
)
readiness
=
await
client
.
get
(
"/api/health/readiness"
)
liveness
=
await
client
.
get
(
"/api/health"
)
self
.
assertEqual
(
ai_health
.
status_code
,
503
)
self
.
assertTrue
(
ai_health
.
json
()[
"unhealthy"
])
self
.
assertEqual
(
readiness
.
status_code
,
503
)
self
.
assertEqual
(
readiness
.
json
()[
"checks"
][
"ai_calling"
],
"unhealthy"
)
self
.
assertEqual
(
liveness
.
status_code
,
200
)
self
.
assertEqual
(
liveness
.
json
()[
"status"
],
"ok"
)
if
__name__
==
"__main__"
:
unittest
.
main
()
ai-service/tests/test_project_endpoints.py
0 → 100644
浏览文件 @
58c1d2b9
from
__future__
import
annotations
import
asyncio
import
os
import
unittest
from
app.ai_calling.service
import
get_ai_service
from
app.api.project
import
(
KnowledgeExtractRequest
,
RecommendCandidate
,
RecommendRequest
,
RecommendSeedProject
,
extract_knowledge
,
recommend_projects
,
)
from
app.project_catalog
import
find_github_knowledge
,
load_github_candidates
class
ProjectEndpointTests
(
unittest
.
TestCase
):
def
setUp
(
self
)
->
None
:
self
.
previous_provider
=
os
.
environ
.
get
(
"AI_DEFAULT_PROVIDER"
)
self
.
previous_model
=
os
.
environ
.
get
(
"AI_DEFAULT_MODEL"
)
os
.
environ
[
"AI_DEFAULT_PROVIDER"
]
=
"mock"
os
.
environ
[
"AI_DEFAULT_MODEL"
]
=
"mock-model"
get_ai_service
.
cache_clear
()
def
tearDown
(
self
)
->
None
:
if
self
.
previous_provider
is
None
:
os
.
environ
.
pop
(
"AI_DEFAULT_PROVIDER"
,
None
)
else
:
os
.
environ
[
"AI_DEFAULT_PROVIDER"
]
=
self
.
previous_provider
if
self
.
previous_model
is
None
:
os
.
environ
.
pop
(
"AI_DEFAULT_MODEL"
,
None
)
else
:
os
.
environ
[
"AI_DEFAULT_MODEL"
]
=
self
.
previous_model
get_ai_service
.
cache_clear
()
def
test_local_catalog_is_available
(
self
)
->
None
:
candidates
=
load_github_candidates
()
self
.
assertGreaterEqual
(
len
(
candidates
),
10
)
self
.
assertIsNotNone
(
find_github_knowledge
(
"https://github.com/langchain-ai/langchain"
,
None
))
def
test_recommend_uses_local_catalog_when_candidates_are_missing
(
self
)
->
None
:
request
=
RecommendRequest
(
project_type
=
"github"
,
seed_project
=
RecommendSeedProject
(
id
=
1
,
name
=
"RAG 学习项目"
,
difficulty_level
=
"L3"
,
tech_stack
=
[
"Python"
],
tags
=
[
"RAG"
,
"LLM"
],
),
limit
=
3
,
)
response
=
asyncio
.
run
(
recommend_projects
(
request
))
self
.
assertTrue
(
response
.
success
)
self
.
assertEqual
(
response
.
data
.
source
,
"ai"
)
self
.
assertEqual
(
len
(
response
.
data
.
recommendations
),
3
)
self
.
assertTrue
(
all
(
0
<=
item
.
match_score
<=
1
for
item
in
response
.
data
.
recommendations
))
self
.
assertTrue
(
all
(
50
<=
len
(
item
.
match_reason
)
<=
200
for
item
in
response
.
data
.
recommendations
))
def
test_recommend_preserves_supplied_candidate_contract
(
self
)
->
None
:
request
=
RecommendRequest
(
project_type
=
"github"
,
seed_project
=
RecommendSeedProject
(
id
=
1
,
name
=
"FastAPI 服务"
,
difficulty_level
=
"L3"
,
tech_stack
=
[
"Python"
,
"FastAPI"
],
tags
=
[
"API"
],
),
candidates
=
[
RecommendCandidate
(
project_id
=
99
,
project_name
=
"fastapi"
,
project_type
=
"github"
,
difficulty_level
=
"L3"
,
tech_stack
=
[
"Python"
,
"FastAPI"
],
tags
=
[
"API"
],
github_url
=
"https://github.com/fastapi/fastapi"
,
)
],
)
response
=
asyncio
.
run
(
recommend_projects
(
request
))
self
.
assertEqual
(
response
.
data
.
recommendations
[
0
]
.
project_id
,
99
)
self
.
assertEqual
(
response
.
data
.
recommendations
[
0
]
.
github_url
,
"https://github.com/fastapi/fastapi"
)
def
test_recommend_falls_back_when_provider_is_unavailable
(
self
)
->
None
:
os
.
environ
[
"AI_DEFAULT_PROVIDER"
]
=
"unavailable-provider"
get_ai_service
.
cache_clear
()
request
=
RecommendRequest
(
project_type
=
"github"
,
seed_project
=
RecommendSeedProject
(
id
=
1
,
name
=
"FastAPI 服务"
,
difficulty_level
=
"L3"
,
tech_stack
=
[
"Python"
,
"FastAPI"
],
tags
=
[
"API"
],
),
candidates
=
[
RecommendCandidate
(
project_id
=
99
,
project_name
=
"fastapi"
,
project_type
=
"github"
,
difficulty_level
=
"L3"
,
tech_stack
=
[
"Python"
,
"FastAPI"
],
tags
=
[
"API"
],
github_url
=
"https://github.com/fastapi/fastapi"
,
)
],
)
response
=
asyncio
.
run
(
recommend_projects
(
request
))
self
.
assertTrue
(
response
.
success
)
self
.
assertEqual
(
response
.
data
.
source
,
"fallback"
)
self
.
assertEqual
(
len
(
response
.
data
.
recommendations
),
1
)
self
.
assertGreaterEqual
(
len
(
response
.
data
.
recommendations
[
0
]
.
match_reason
),
50
)
def
test_knowledge_extract_uses_collected_github_record
(
self
)
->
None
:
request
=
KnowledgeExtractRequest
(
project_id
=
1
,
project_type
=
"github"
,
project_name
=
"langchain"
,
difficulty_level
=
"L3"
,
source_code_url
=
"https://github.com/langchain-ai/langchain"
,
)
response
=
asyncio
.
run
(
extract_knowledge
(
request
))
self
.
assertTrue
(
response
.
success
)
self
.
assertGreater
(
len
(
response
.
data
.
knowledge_points
),
1
)
self
.
assertNotEqual
(
response
.
data
.
knowledge_points
[
0
]
.
name
,
"项目需求理解"
)
self
.
assertEqual
(
response
.
data
.
knowledge_points
[
0
]
.
material_url
,
"https://github.com/langchain-ai/langchain"
,
)
def
test_knowledge_extract_keeps_rule_fallback_for_mock_provider
(
self
)
->
None
:
request
=
KnowledgeExtractRequest
(
project_id
=
2
,
project_type
=
"internal"
,
project_name
=
"内部 API 项目"
,
difficulty_level
=
"L2"
,
tech_stack
=
[
"FastAPI"
],
project_content
=
"Build an internal REST API with FastAPI."
,
)
response
=
asyncio
.
run
(
extract_knowledge
(
request
))
names
=
[
item
.
name
for
item
in
response
.
data
.
knowledge_points
]
self
.
assertIn
(
"项目需求理解"
,
names
)
self
.
assertIn
(
"FastAPI 实践"
,
names
)
if
__name__
==
"__main__"
:
unittest
.
main
()
backend/apps/backend-app/src/main/java/com/platform/backend/project/controller/ProjectFileController.java
浏览文件 @
58c1d2b9
...
...
@@ -6,10 +6,18 @@ import com.platform.backend.project.dto.FileDtos;
import
com.platform.backend.project.service.ProjectPermissionService
;
import
com.platform.backend.project.service.ProjectFileService
;
import
lombok.RequiredArgsConstructor
;
import
org.springframework.http.ContentDisposition
;
import
org.springframework.http.HttpHeaders
;
import
org.springframework.http.MediaType
;
import
org.springframework.http.ResponseEntity
;
import
org.springframework.security.core.Authentication
;
import
org.springframework.web.bind.annotation.*
;
import
org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody
;
import
org.springframework.web.multipart.MultipartFile
;
import
java.nio.charset.StandardCharsets
;
import
java.util.Set
;
@RestController
@RequestMapping
(
"/api/v1/files"
)
@RequiredArgsConstructor
...
...
@@ -25,7 +33,7 @@ public class ProjectFileController {
@RequestParam
(
"file_type"
)
String
fileType
,
Authentication
authentication
)
{
accessService
.
require
Role
(
authentication
,
"ADMIN
"
);
accessService
.
require
Permission
(
authentication
,
"file:upload
"
);
User
user
=
accessService
.
currentUser
(
authentication
);
return
ApiResponse
.
success
(
fileService
.
upload
(
file
,
projectId
,
projectType
,
fileType
,
user
));
}
...
...
@@ -38,4 +46,35 @@ public class ProjectFileController {
User
user
=
accessService
.
currentUser
(
authentication
);
return
ApiResponse
.
success
(
fileService
.
downloadUrl
(
fileId
,
user
));
}
/**
* 通过后端代理返回文件内容,使远程浏览器不需要直接访问 MinIO 的 localhost 地址。
*/
@GetMapping
(
"/{fileId}/content"
)
public
ResponseEntity
<
StreamingResponseBody
>
content
(
@PathVariable
Long
fileId
,
@RequestParam
(
defaultValue
=
"attachment"
)
String
disposition
,
Authentication
authentication
)
{
if
(!
Set
.
of
(
"inline"
,
"attachment"
).
contains
(
disposition
))
{
throw
new
IllegalArgumentException
(
"disposition 仅支持 inline 或 attachment"
);
}
User
user
=
accessService
.
currentUser
(
authentication
);
ProjectFileService
.
FileContent
content
=
fileService
.
prepareContent
(
fileId
,
user
);
ContentDisposition
contentDisposition
=
ContentDisposition
.
builder
(
disposition
)
.
filename
(
content
.
fileName
(),
StandardCharsets
.
UTF_8
)
.
build
();
MediaType
mediaType
;
try
{
mediaType
=
MediaType
.
parseMediaType
(
content
.
contentType
());
}
catch
(
IllegalArgumentException
ignored
)
{
mediaType
=
MediaType
.
APPLICATION_OCTET_STREAM
;
}
StreamingResponseBody
body
=
outputStream
->
fileService
.
writeContent
(
content
,
outputStream
);
return
ResponseEntity
.
ok
()
.
contentType
(
mediaType
)
.
contentLength
(
content
.
contentLength
())
.
header
(
HttpHeaders
.
CONTENT_DISPOSITION
,
contentDisposition
.
toString
())
.
body
(
body
);
}
}
backend/apps/backend-app/src/main/java/com/platform/backend/project/service/ProjectAiClientService.java
浏览文件 @
58c1d2b9
...
...
@@ -207,6 +207,8 @@ public class ProjectAiClientService {
AiRecommendRequest
request
=
new
AiRecommendRequest
();
request
.
setProjectType
(
projectType
);
request
.
setLimit
(
limit
==
null
?
5
:
limit
);
// ai-service 的推荐接口要求数组字段必须是 list,显式传空数组避免 null 触发 422。
request
.
setExcludeIds
(
List
.
of
());
request
.
setSeedProject
(
toSeedProject
(
seedProject
));
request
.
setCandidates
(
candidates
.
stream
().
map
(
this
::
toCandidate
).
toList
());
response
=
runProtected
(
"recommend"
,
()
->
aiWebClient
.
post
()
...
...
@@ -581,8 +583,8 @@ public class ProjectAiClientService {
seed
.
setId
(
project
.
getId
());
seed
.
setName
(
project
.
getName
());
seed
.
setDifficultyLevel
(
project
.
getDifficultyLevel
());
seed
.
setTechStack
(
project
.
getTechStack
(
));
seed
.
setTags
(
project
.
getKnowledgeTags
(
));
seed
.
setTechStack
(
nonNullList
(
project
.
getTechStack
()
));
seed
.
setTags
(
nonNullList
(
project
.
getKnowledgeTags
()
));
return
seed
;
}
...
...
@@ -593,13 +595,21 @@ public class ProjectAiClientService {
aiCandidate
.
setProjectType
(
candidate
.
getProjectType
());
aiCandidate
.
setDescription
(
candidate
.
getDescription
());
aiCandidate
.
setDifficultyLevel
(
candidate
.
getDifficultyLevel
());
aiCandidate
.
setTechStack
(
candidate
.
getTechStack
(
));
aiCandidate
.
setTags
(
candidate
.
getTags
(
));
aiCandidate
.
setTechStack
(
nonNullList
(
candidate
.
getTechStack
()
));
aiCandidate
.
setTags
(
nonNullList
(
candidate
.
getTags
()
));
aiCandidate
.
setStars
(
candidate
.
getStars
());
aiCandidate
.
setGithubUrl
(
candidate
.
getGithubUrl
());
return
aiCandidate
;
}
/**
* 推荐接口对数组字段做了严格校验,这里统一把 null 归一为 [],
* 避免后端内部请求因为空集合语义不一致而返回 422。
*/
private
List
<
String
>
nonNullList
(
List
<
String
>
values
)
{
return
values
==
null
?
List
.
of
()
:
values
;
}
private
RecommendationDtos
.
RecommendationItem
toRecommendationItem
(
AiRecommendItem
item
)
{
RecommendationDtos
.
RecommendationItem
result
=
new
RecommendationDtos
.
RecommendationItem
();
result
.
setProjectId
(
item
.
getProjectId
());
...
...
backend/apps/backend-app/src/main/java/com/platform/backend/project/service/ProjectFileService.java
浏览文件 @
58c1d2b9
...
...
@@ -12,6 +12,8 @@ import org.springframework.stereotype.Service;
import
org.springframework.transaction.annotation.Transactional
;
import
org.springframework.web.multipart.MultipartFile
;
import
java.io.OutputStream
;
@Service
@RequiredArgsConstructor
public
class
ProjectFileService
{
...
...
@@ -54,13 +56,42 @@ public class ProjectFileService {
public
FileDtos
.
DownloadUrlResponse
downloadUrl
(
Long
fileId
,
User
user
)
{
ProjectAttachment
attachment
=
attachmentRepository
.
findById
(
fileId
)
.
orElseThrow
(()
->
new
ProjectBusinessException
(
"文件不存在"
));
// 仅在项目模块内按真实 role_code 判断,避免被 User.getRole() 的旧兼容实现误导。
if
(!
permissionService
.
hasRole
(
user
,
"ADMIN"
)
&&
!
user
.
getId
().
equals
(
attachment
.
getUploadedBy
()))
{
throw
new
ProjectBusinessException
(
"仅文件所有者或 ADMIN 可获取"
);
if
(!
permissionService
.
hasPermission
(
user
,
"file:download"
))
{
throw
new
ProjectBusinessException
(
"无文件下载权限"
);
}
FileDtos
.
DownloadUrlResponse
response
=
new
FileDtos
.
DownloadUrlResponse
();
response
.
setUrl
(
minioStorageService
.
signedUrl
(
attachment
.
getFileUrl
()));
response
.
setExpiresMinutes
(
30
);
return
response
;
}
/**
* 为前端预览和下载准备文件流信息。鉴权规则与既有下载接口完全一致。
*/
public
FileContent
prepareContent
(
Long
fileId
,
User
user
)
{
ProjectAttachment
attachment
=
attachmentRepository
.
findById
(
fileId
)
.
orElseThrow
(()
->
new
ProjectBusinessException
(
"文件不存在"
));
if
(!
permissionService
.
hasPermission
(
user
,
"file:download"
))
{
throw
new
ProjectBusinessException
(
"无文件下载权限"
);
}
MinioStorageService
.
ObjectMetadata
metadata
=
minioStorageService
.
objectMetadata
(
attachment
.
getFileUrl
());
return
new
FileContent
(
attachment
.
getFileName
(),
attachment
.
getFileUrl
(),
metadata
.
contentType
(),
metadata
.
contentLength
()
);
}
public
void
writeContent
(
FileContent
content
,
OutputStream
outputStream
)
{
minioStorageService
.
writeObjectTo
(
content
.
objectName
(),
outputStream
);
}
public
record
FileContent
(
String
fileName
,
String
objectName
,
String
contentType
,
long
contentLength
)
{
}
}
backend/apps/backend-app/src/main/java/com/platform/backend/project/service/ProjectPermissionService.java
浏览文件 @
58c1d2b9
...
...
@@ -5,6 +5,7 @@ import com.platform.backend.entity.User;
import
com.platform.backend.project.common.ProjectBusinessException
;
import
com.platform.backend.repository.RoleRepository
;
import
com.platform.backend.repository.UserRepository
;
import
com.platform.backend.security.PermissionService
;
import
lombok.RequiredArgsConstructor
;
import
org.springframework.security.core.Authentication
;
import
org.springframework.stereotype.Service
;
...
...
@@ -14,6 +15,7 @@ import org.springframework.stereotype.Service;
public
class
ProjectPermissionService
{
private
final
UserRepository
userRepository
;
private
final
RoleRepository
roleRepository
;
private
final
PermissionService
permissionService
;
public
User
currentUser
(
Authentication
authentication
)
{
if
(
authentication
==
null
||
authentication
.
getName
()
==
null
)
{
...
...
@@ -50,6 +52,20 @@ public class ProjectPermissionService {
return
false
;
}
/**
* 文件等可配置能力必须按真实权限码判断,不能仅根据预置角色名称写死。
*/
public
boolean
hasPermission
(
User
user
,
String
permissionCode
)
{
return
user
.
getId
()
!=
null
&&
permissionService
.
hasPermission
(
user
.
getId
(),
permissionCode
);
}
public
void
requirePermission
(
Authentication
authentication
,
String
permissionCode
)
{
User
user
=
currentUser
(
authentication
);
if
(!
hasPermission
(
user
,
permissionCode
))
{
throw
new
ProjectBusinessException
(
"无权限操作"
);
}
}
private
String
resolveRoleCode
(
User
user
)
{
Long
roleId
=
user
.
getRoleId
();
if
(
roleId
==
null
)
{
...
...
backend/apps/backend-app/src/main/java/com/platform/backend/project/service/ProjectService.java
浏览文件 @
58c1d2b9
...
...
@@ -552,13 +552,11 @@ public class ProjectService {
if
(
objectName
==
null
||
objectName
.
isBlank
())
{
return
objectName
;
}
// 详情接口只对
上传者或管理员
回填签名 URL,避免绕过下载接口的权限判断。
// 详情接口只对
拥有文件下载权限的用户
回填签名 URL,避免绕过下载接口的权限判断。
if
(
user
==
null
)
{
return
null
;
}
boolean
isOwner
=
user
.
getId
()
!=
null
&&
user
.
getId
().
equals
(
attachment
.
getUploadedBy
());
boolean
isAdmin
=
permissionService
.
hasRole
(
user
,
"ADMIN"
);
if
(!
isOwner
&&
!
isAdmin
)
{
if
(!
permissionService
.
hasPermission
(
user
,
"file:download"
))
{
return
null
;
}
try
{
...
...
backend/apps/backend-app/src/main/java/com/platform/backend/project/storage/MinioStorageService.java
浏览文件 @
58c1d2b9
...
...
@@ -8,6 +8,7 @@ import org.springframework.beans.factory.annotation.Value;
import
org.springframework.stereotype.Service
;
import
org.springframework.web.multipart.MultipartFile
;
import
java.io.OutputStream
;
import
java.util.Set
;
import
java.util.UUID
;
import
java.util.concurrent.TimeUnit
;
...
...
@@ -62,6 +63,39 @@ public class MinioStorageService {
}
}
/**
* 读取对象元数据,供后端文件流接口设置正确的响应类型和长度。
*/
public
ObjectMetadata
objectMetadata
(
String
objectName
)
{
try
{
StatObjectResponse
stat
=
minioClient
.
statObject
(
StatObjectArgs
.
builder
()
.
bucket
(
bucket
)
.
object
(
objectName
)
.
build
());
String
contentType
=
stat
.
contentType
();
if
(
contentType
==
null
||
contentType
.
isBlank
())
{
contentType
=
"application/octet-stream"
;
}
return
new
ObjectMetadata
(
contentType
,
stat
.
size
());
}
catch
(
Exception
e
)
{
throw
new
ProjectBusinessException
(
"文件元数据读取失败:"
+
e
.
getMessage
());
}
}
/**
* 由后端将 MinIO 对象写入 HTTP 响应,避免浏览器直接访问远程服务器的 localhost MinIO 地址。
*/
public
void
writeObjectTo
(
String
objectName
,
OutputStream
outputStream
)
{
try
(
GetObjectResponse
objectStream
=
minioClient
.
getObject
(
GetObjectArgs
.
builder
()
.
bucket
(
bucket
)
.
object
(
objectName
)
.
build
()))
{
objectStream
.
transferTo
(
outputStream
);
}
catch
(
Exception
e
)
{
throw
new
ProjectBusinessException
(
"文件读取失败:"
+
e
.
getMessage
());
}
}
private
void
ensureBucket
()
{
try
{
boolean
exists
=
minioClient
.
bucketExists
(
BucketExistsArgs
.
builder
().
bucket
(
bucket
).
build
());
...
...
@@ -89,4 +123,7 @@ public class MinioStorageService {
throw
new
ProjectBusinessException
(
"仅支持 PDF/Word/Excel/压缩包"
);
}
}
public
record
ObjectMetadata
(
String
contentType
,
long
contentLength
)
{
}
}
backend/apps/backend-app/src/test/java/com/platform/backend/project/service/ProjectFileServiceTest.java
浏览文件 @
58c1d2b9
...
...
@@ -43,7 +43,7 @@ class ProjectFileServiceTest {
}
@Test
void
downloadUrlAllows
AdminEvenWhenLegacyUserRoleFieldIsNotAdminText
()
{
void
downloadUrlAllows
UsersWithConfiguredFileDownloadPermission
()
{
User
user
=
new
User
();
user
.
setId
(
100L
);
user
.
setRoleId
(
1L
);
...
...
@@ -54,18 +54,18 @@ class ProjectFileServiceTest {
attachment
.
setUploadedBy
(
200L
);
when
(
attachmentRepository
.
findById
(
20L
)).
thenReturn
(
Optional
.
of
(
attachment
));
when
(
permissionService
.
has
Role
(
user
,
"ADMIN
"
)).
thenReturn
(
true
);
when
(
permissionService
.
has
Permission
(
user
,
"file:download
"
)).
thenReturn
(
true
);
when
(
minioStorageService
.
signedUrl
(
"project/github/readme.pdf"
)).
thenReturn
(
"https://signed.example/file"
);
FileDtos
.
DownloadUrlResponse
response
=
projectFileService
.
downloadUrl
(
20L
,
user
);
assertEquals
(
"https://signed.example/file"
,
response
.
getUrl
());
assertEquals
(
30
,
response
.
getExpiresMinutes
());
verify
(
permissionService
).
has
Role
(
user
,
"ADMIN
"
);
verify
(
permissionService
).
has
Permission
(
user
,
"file:download
"
);
}
@Test
void
downloadUrlRejects
NonOwnerNonAdmi
n
()
{
void
downloadUrlRejects
UsersWithoutConfiguredFileDownloadPermissio
n
()
{
User
user
=
new
User
();
user
.
setId
(
100L
);
...
...
@@ -75,13 +75,37 @@ class ProjectFileServiceTest {
attachment
.
setUploadedBy
(
200L
);
when
(
attachmentRepository
.
findById
(
21L
)).
thenReturn
(
Optional
.
of
(
attachment
));
when
(
permissionService
.
has
Role
(
user
,
"ADMIN
"
)).
thenReturn
(
false
);
when
(
permissionService
.
has
Permission
(
user
,
"file:download
"
)).
thenReturn
(
false
);
ProjectBusinessException
exception
=
assertThrows
(
ProjectBusinessException
.
class
,
()
->
projectFileService
.
downloadUrl
(
21L
,
user
)
);
assertEquals
(
"仅文件所有者或 ADMIN 可获取"
,
exception
.
getMessage
());
assertEquals
(
"无文件下载权限"
,
exception
.
getMessage
());
}
@Test
void
prepareContentUsesTheSameConfiguredPermissionAsDownloadUrl
()
{
User
user
=
new
User
();
user
.
setId
(
100L
);
ProjectAttachment
attachment
=
new
ProjectAttachment
();
attachment
.
setId
(
22L
);
attachment
.
setFileName
(
"guide.pdf"
);
attachment
.
setFileUrl
(
"projects/1/internal/guide.pdf"
);
attachment
.
setUploadedBy
(
100L
);
when
(
attachmentRepository
.
findById
(
22L
)).
thenReturn
(
Optional
.
of
(
attachment
));
when
(
permissionService
.
hasPermission
(
user
,
"file:download"
)).
thenReturn
(
true
);
when
(
minioStorageService
.
objectMetadata
(
"projects/1/internal/guide.pdf"
))
.
thenReturn
(
new
MinioStorageService
.
ObjectMetadata
(
"application/pdf"
,
128L
));
ProjectFileService
.
FileContent
content
=
projectFileService
.
prepareContent
(
22L
,
user
);
assertEquals
(
"guide.pdf"
,
content
.
fileName
());
assertEquals
(
"application/pdf"
,
content
.
contentType
());
assertEquals
(
128L
,
content
.
contentLength
());
verify
(
permissionService
).
hasPermission
(
user
,
"file:download"
);
}
}
frontend/package.json
浏览文件 @
58c1d2b9
...
...
@@ -10,12 +10,14 @@
"lint"
:
"eslint src --ext ts,tsx"
},
"dependencies"
:
{
"@ant-design/icons"
:
"^5.5.1"
,
"antd"
:
"^5.21.2"
,
"axios"
:
"^1.7.7"
,
"mammoth"
:
"^1.12.0"
,
"react"
:
"^18.3.1"
,
"react-dom"
:
"^18.3.1"
,
"react-router-dom"
:
"^6.26.2"
,
"antd"
:
"^5.21.2"
,
"@ant-design/icons"
:
"^5.5.1"
,
"axios"
:
"^1.7.7"
,
"xlsx"
:
"^0.18.5"
,
"zustand"
:
"^4.5.5"
},
"devDependencies"
:
{
...
...
frontend/pnpm-lock.yaml
浏览文件 @
58c1d2b9
...
...
@@ -17,6 +17,9 @@ importers:
axios
:
specifier
:
^1.7.7
version
:
1.18.1
mammoth
:
specifier
:
^1.12.0
version
:
1.12.0
react
:
specifier
:
^18.3.1
version
:
18.3.1
...
...
@@ -26,6 +29,9 @@ importers:
react-router-dom
:
specifier
:
^6.26.2
version
:
6.30.4(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
xlsx
:
specifier
:
^0.18.5
version
:
0.18.5
zustand
:
specifier
:
^4.5.5
version
:
4.5.7(@types/react@18.3.31)(react@18.3.1)
...
...
@@ -561,6 +567,14 @@ packages:
peerDependencies
:
vite
:
^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0
'
@xmldom/xmldom@0.8.13'
:
resolution
:
{
integrity
:
sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==
}
engines
:
{
node
:
'
>=10.0.0'
}
adler-32@1.3.1
:
resolution
:
{
integrity
:
sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==
}
engines
:
{
node
:
'
>=0.8'
}
agent-base@6.0.2
:
resolution
:
{
integrity
:
sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==
}
engines
:
{
node
:
'
>=
6.0.0'
}
...
...
@@ -571,17 +585,26 @@ packages:
react
:
'
>=16.9.0'
react-dom
:
'
>=16.9.0'
argparse@1.0.10
:
resolution
:
{
integrity
:
sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==
}
asynckit@0.4.0
:
resolution
:
{
integrity
:
sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==
}
axios@1.18.1
:
resolution
:
{
integrity
:
sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==
}
base64-js@1.5.1
:
resolution
:
{
integrity
:
sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==
}
baseline-browser-mapping@2.10.43
:
resolution
:
{
integrity
:
sha512-AjYpR78kDWAY3Efj+cDTFH9t9SCoL7OoTp1BOb0mQV7S+6CiLwnWM3FyxhJtdPufDFKzmCSFoUncKjWgJEZTCQ==
}
engines
:
{
node
:
'
>=6.0.0'
}
hasBin
:
true
bluebird@3.4.7
:
resolution
:
{
integrity
:
sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA==
}
browserslist@4.28.6
:
resolution
:
{
integrity
:
sha512-FQBYNK15VMslhLHpA7+n+n1GOlF1kId2xcCg7/j95f24AOF6VDYMNH4mFxF7KuaTdv627faazpOAjFzMrfJOUw==
}
engines
:
{
node
:
^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7
}
...
...
@@ -594,9 +617,17 @@ packages:
caniuse-lite@1.0.30001805
:
resolution
:
{
integrity
:
sha512-52noaS3DubycKSXaU30TwPGIp+POyQSUVa5jBEq3vkRkY0kjyb3LQgvhU6WGyCcyXqVLWO0Cw0Q6BSdD0kUfVA==
}
cfb@1.2.2
:
resolution
:
{
integrity
:
sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==
}
engines
:
{
node
:
'
>=0.8'
}
classnames@2.5.1
:
resolution
:
{
integrity
:
sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==
}
codepage@1.15.0
:
resolution
:
{
integrity
:
sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==
}
engines
:
{
node
:
'
>=0.8'
}
combined-stream@1.0.8
:
resolution
:
{
integrity
:
sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==
}
engines
:
{
node
:
'
>=
0.8'
}
...
...
@@ -610,6 +641,14 @@ packages:
copy-to-clipboard@3.3.3
:
resolution
:
{
integrity
:
sha512-2KV8NhB5JqC3ky0r9PMCAZKbUHSwtEo4CwCs0KXgruG43gX5PMqDEBbVU4OUzw2MuAWUfsuFmWvEKG5QRfSnJA==
}
core-util-is@1.0.3
:
resolution
:
{
integrity
:
sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==
}
crc-32@1.2.2
:
resolution
:
{
integrity
:
sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==
}
engines
:
{
node
:
'
>=0.8'
}
hasBin
:
true
csstype@3.2.3
:
resolution
:
{
integrity
:
sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==
}
...
...
@@ -629,6 +668,12 @@ packages:
resolution
:
{
integrity
:
sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==
}
engines
:
{
node
:
'
>=0.4.0'
}
dingbat-to-unicode@1.0.1
:
resolution
:
{
integrity
:
sha512-98l0sW87ZT58pU4i61wa2OHwxbiYSbuxsCBozaVnYX2iCnr3bLM3fIes1/ej7h1YdOKuKt/MLs706TVnALA65w==
}
duck@0.1.12
:
resolution
:
{
integrity
:
sha512-wkctla1O6VfP89gQ+J/yDesM0S7B7XLXjKGzXxMDVFg7uEn706niAtyYovKbyq1oT9YwDcly721/iUWoc8MVRg==
}
dunder-proto@1.0.1
:
resolution
:
{
integrity
:
sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==
}
engines
:
{
node
:
'
>=
0.4'
}
...
...
@@ -674,6 +719,10 @@ packages:
resolution
:
{
integrity
:
sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==
}
engines
:
{
node
:
'
>=
6'
}
frac@1.1.2
:
resolution
:
{
integrity
:
sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==
}
engines
:
{
node
:
'
>=0.8'
}
fsevents@2.3.3
:
resolution
:
{
integrity
:
sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==
}
engines
:
{
node
:
^8.16.0 || ^10.6.0 || >=11.0.0
}
...
...
@@ -714,6 +763,15 @@ packages:
resolution
:
{
integrity
:
sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==
}
engines
:
{
node
:
'
>=
6'
}
immediate@3.0.6
:
resolution
:
{
integrity
:
sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==
}
inherits@2.0.4
:
resolution
:
{
integrity
:
sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==
}
isarray@1.0.0
:
resolution
:
{
integrity
:
sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==
}
js-tokens@4.0.0
:
resolution
:
{
integrity
:
sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==
}
...
...
@@ -730,13 +788,27 @@ packages:
engines
:
{
node
:
'
>=6'
}
hasBin
:
true
jszip@3.10.1
:
resolution
:
{
integrity
:
sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==
}
lie@3.3.0
:
resolution
:
{
integrity
:
sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==
}
loose-envify@1.4.0
:
resolution
:
{
integrity
:
sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==
}
hasBin
:
true
lop@0.4.2
:
resolution
:
{
integrity
:
sha512-RefILVDQ4DKoRZsJ4Pj22TxE3omDO47yFpkIBoDKzkqPRISs5U1cnAdg/5583YPkWPaLIYHOKRMQSvjFsO26cw==
}
lru-cache@5.1.1
:
resolution
:
{
integrity
:
sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==
}
mammoth@1.12.0
:
resolution
:
{
integrity
:
sha512-cwnK1RIcRdDMi2HRx2EXGYlxqIEh0Oo3bLhorgnsVJi2UkbX1+jKxuBNR9PC5+JaX7EkmJxFPmo6mjLpqShI2w==
}
engines
:
{
node
:
'
>=12.0.0'
}
hasBin
:
true
math-intrinsics@1.1.0
:
resolution
:
{
integrity
:
sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==
}
engines
:
{
node
:
'
>=
0.4'
}
...
...
@@ -761,6 +833,16 @@ packages:
resolution
:
{
integrity
:
sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==
}
engines
:
{
node
:
'
>=18'
}
option@0.2.4
:
resolution
:
{
integrity
:
sha512-pkEqbDyl8ou5cpq+VsnQbe/WlEy5qS7xPzMS1U55OCG9KPvwFD46zDbxQIj3egJSFc3D+XhYOPUzz49zQAVy7A==
}
pako@1.0.11
:
resolution
:
{
integrity
:
sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==
}
path-is-absolute@1.0.1
:
resolution
:
{
integrity
:
sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==
}
engines
:
{
node
:
'
>=0.10.0'
}
picocolors@1.1.1
:
resolution
:
{
integrity
:
sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==
}
...
...
@@ -768,6 +850,9 @@ packages:
resolution
:
{
integrity
:
sha512-Mz8SaolMd8nB+G13WkORcxQKHZ/NE4xXevtkJHVuG+guo9/wYKlIMTKAqGdEmYOXR2ijPjTYNHssizdaVSUNdQ==
}
engines
:
{
node
:
^10 || ^12 || >=14
}
process-nextick-args@2.0.1
:
resolution
:
{
integrity
:
sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==
}
proxy-from-env@2.1.0
:
resolution
:
{
integrity
:
sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==
}
engines
:
{
node
:
'
>=10'
}
...
...
@@ -1029,6 +1114,9 @@ packages:
resolution
:
{
integrity
:
sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==
}
engines
:
{
node
:
'
>=0.10.0'
}
readable-stream@2.3.8
:
resolution
:
{
integrity
:
sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==
}
resize-observer-polyfill@1.5.1
:
resolution
:
{
integrity
:
sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg==
}
...
...
@@ -1037,6 +1125,9 @@ packages:
engines
:
{
node
:
'
>=18.0.0'
,
npm
:
'
>=8.0.0'
}
hasBin
:
true
safe-buffer@5.1.2
:
resolution
:
{
integrity
:
sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==
}
scheduler@0.23.2
:
resolution
:
{
integrity
:
sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==
}
...
...
@@ -1047,13 +1138,26 @@ packages:
resolution
:
{
integrity
:
sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==
}
hasBin
:
true
setimmediate@1.0.5
:
resolution
:
{
integrity
:
sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==
}
source-map-js@1.2.1
:
resolution
:
{
integrity
:
sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==
}
engines
:
{
node
:
'
>=0.10.0'
}
sprintf-js@1.0.3
:
resolution
:
{
integrity
:
sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==
}
ssf@0.11.2
:
resolution
:
{
integrity
:
sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==
}
engines
:
{
node
:
'
>=0.8'
}
string-convert@0.2.1
:
resolution
:
{
integrity
:
sha512-u/1tdPl4yQnPBjnVrmdLo9gtuLvELKsAoRapekWggdiQNvvvum+jYF329d84NAa660KQw7pB2n36KrIKVoXa3A==
}
string_decoder@1.1.1
:
resolution
:
{
integrity
:
sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==
}
stylis@4.4.0
:
resolution
:
{
integrity
:
sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA==
}
...
...
@@ -1069,6 +1173,9 @@ packages:
engines
:
{
node
:
'
>=14.17'
}
hasBin
:
true
underscore@1.13.8
:
resolution
:
{
integrity
:
sha512-DXtD3ZtEQzc7M8m4cXotyHR+FAS18C64asBYY5vqZexfYryNNnDc02W4hKg3rdQuqOYas1jkseX0+nZXjTXnvQ==
}
update-browserslist-db@1.2.3
:
resolution
:
{
integrity
:
sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==
}
hasBin
:
true
...
...
@@ -1080,6 +1187,9 @@ packages:
peerDependencies
:
react
:
^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
util-deprecate@1.0.2
:
resolution
:
{
integrity
:
sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==
}
vite@5.4.21
:
resolution
:
{
integrity
:
sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==
}
engines
:
{
node
:
^18.0.0 || >=20.0.0
}
...
...
@@ -1111,6 +1221,23 @@ packages:
terser
:
optional
:
true
wmf@1.0.2
:
resolution
:
{
integrity
:
sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==
}
engines
:
{
node
:
'
>=0.8'
}
word@0.3.0
:
resolution
:
{
integrity
:
sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==
}
engines
:
{
node
:
'
>=0.8'
}
xlsx@0.18.5
:
resolution
:
{
integrity
:
sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==
}
engines
:
{
node
:
'
>=0.8'
}
hasBin
:
true
xmlbuilder@10.1.1
:
resolution
:
{
integrity
:
sha512-OyzrcFLL/nb6fMGHbiRDuPup9ljBycsdCypwuyg5AAHvyWzGfChJpCXMG88AGTIMFhGZ9RccFN1e6lhg3hkwKg==
}
engines
:
{
node
:
'
>=4.0'
}
yallist@3.1.1
:
resolution
:
{
integrity
:
sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==
}
...
...
@@ -1578,6 +1705,10 @@ snapshots:
transitivePeerDependencies
:
-
supports-color
'
@xmldom/xmldom@0.8.13'
:
{}
adler-32@1.3.1
:
{}
agent-base@6.0.2
:
dependencies
:
debug
:
4.4.3
...
...
@@ -1642,6 +1773,10 @@ snapshots:
-
luxon
-
moment
argparse@1.0.10
:
dependencies
:
sprintf-js
:
1.0.3
asynckit@0.4.0
:
{}
axios@1.18.1
:
...
...
@@ -1654,8 +1789,12 @@ snapshots:
-
debug
-
supports-color
base64-js@1.5.1
:
{}
baseline-browser-mapping@2.10.43
:
{}
bluebird@3.4.7
:
{}
browserslist@4.28.6
:
dependencies
:
baseline-browser-mapping
:
2.10.43
...
...
@@ -1671,8 +1810,15 @@ snapshots:
caniuse-lite@1.0.30001805
:
{}
cfb@1.2.2
:
dependencies
:
adler-32
:
1.3.1
crc-32
:
1.2.2
classnames@2.5.1
:
{}
codepage@1.15.0
:
{}
combined-stream@1.0.8
:
dependencies
:
delayed-stream
:
1.0.0
...
...
@@ -1685,6 +1831,10 @@ snapshots:
dependencies
:
toggle-selection
:
1.0.6
core-util-is@1.0.3
:
{}
crc-32@1.2.2
:
{}
csstype@3.2.3
:
{}
dayjs@1.11.21
:
{}
...
...
@@ -1695,6 +1845,12 @@ snapshots:
delayed-stream@1.0.0
:
{}
dingbat-to-unicode@1.0.1
:
{}
duck@0.1.12
:
dependencies
:
underscore
:
1.13.8
dunder-proto@1.0.1
:
dependencies
:
call-bind-apply-helpers
:
1.0.2
...
...
@@ -1756,6 +1912,8 @@ snapshots:
hasown
:
2.0.4
mime-types
:
2.1.35
frac@1.1.2
:
{}
fsevents@2.3.3
:
optional
:
true
...
...
@@ -1800,6 +1958,12 @@ snapshots:
transitivePeerDependencies
:
-
supports-color
immediate@3.0.6
:
{}
inherits@2.0.4
:
{}
isarray@1.0.0
:
{}
js-tokens@4.0.0
:
{}
jsesc@3.1.0
:
{}
...
...
@@ -1810,14 +1974,44 @@ snapshots:
json5@2.2.3
:
{}
jszip@3.10.1
:
dependencies
:
lie
:
3.3.0
pako
:
1.0.11
readable-stream
:
2.3.8
setimmediate
:
1.0.5
lie@3.3.0
:
dependencies
:
immediate
:
3.0.6
loose-envify@1.4.0
:
dependencies
:
js-tokens
:
4.0.0
lop@0.4.2
:
dependencies
:
duck
:
0.1.12
option
:
0.2.4
underscore
:
1.13.8
lru-cache@5.1.1
:
dependencies
:
yallist
:
3.1.1
mammoth@1.12.0
:
dependencies
:
'
@xmldom/xmldom'
:
0.8.13
argparse
:
1.0.10
base64-js
:
1.5.1
bluebird
:
3.4.7
dingbat-to-unicode
:
1.0.1
jszip
:
3.10.1
lop
:
0.4.2
path-is-absolute
:
1.0.1
underscore
:
1.13.8
xmlbuilder
:
10.1.1
math-intrinsics@1.1.0
:
{}
mime-db@1.52.0
:
{}
...
...
@@ -1832,6 +2026,12 @@ snapshots:
node-releases@2.0.51
:
{}
option@0.2.4
:
{}
pako@1.0.11
:
{}
path-is-absolute@1.0.1
:
{}
picocolors@1.1.1
:
{}
postcss@8.5.19
:
...
...
@@ -1840,6 +2040,8 @@ snapshots:
picocolors
:
1.1.1
source-map-js
:
1.2.1
process-nextick-args@2.0.1
:
{}
proxy-from-env@2.1.0
:
{}
rc-cascader@3.34.0(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
:
...
...
@@ -2187,6 +2389,16 @@ snapshots:
dependencies
:
loose-envify
:
1.4.0
readable-stream@2.3.8
:
dependencies
:
core-util-is
:
1.0.3
inherits
:
2.0.4
isarray
:
1.0.0
process-nextick-args
:
2.0.1
safe-buffer
:
5.1.2
string_decoder
:
1.1.1
util-deprecate
:
1.0.2
resize-observer-polyfill@1.5.1
:
{}
rollup@4.62.2
:
...
...
@@ -2220,6 +2432,8 @@ snapshots:
'
@rollup/rollup-win32-x64-msvc'
:
4.62.2
fsevents
:
2.3.3
safe-buffer@5.1.2
:
{}
scheduler@0.23.2
:
dependencies
:
loose-envify
:
1.4.0
...
...
@@ -2230,10 +2444,22 @@ snapshots:
semver@6.3.1
:
{}
setimmediate@1.0.5
:
{}
source-map-js@1.2.1
:
{}
sprintf-js@1.0.3
:
{}
ssf@0.11.2
:
dependencies
:
frac
:
1.1.2
string-convert@0.2.1
:
{}
string_decoder@1.1.1
:
dependencies
:
safe-buffer
:
5.1.2
stylis@4.4.0
:
{}
throttle-debounce@5.0.2
:
{}
...
...
@@ -2242,6 +2468,8 @@ snapshots:
typescript@5.9.3
:
{}
underscore@1.13.8
:
{}
update-browserslist-db@1.2.3(browserslist@4.28.6)
:
dependencies
:
browserslist
:
4.28.6
...
...
@@ -2252,6 +2480,8 @@ snapshots:
dependencies
:
react
:
18.3.1
util-deprecate@1.0.2
:
{}
vite@5.4.21
:
dependencies
:
esbuild
:
0.21.5
...
...
@@ -2260,6 +2490,22 @@ snapshots:
optionalDependencies
:
fsevents
:
2.3.3
wmf@1.0.2
:
{}
word@0.3.0
:
{}
xlsx@0.18.5
:
dependencies
:
adler-32
:
1.3.1
cfb
:
1.2.2
codepage
:
1.15.0
crc-32
:
1.2.2
ssf
:
0.11.2
wmf
:
1.0.2
word
:
0.3.0
xmlbuilder@10.1.1
:
{}
yallist@3.1.1
:
{}
zustand@4.5.7(@types/react@18.3.31)(react@18.3.1)
:
...
...
frontend/src/App.tsx
浏览文件 @
58c1d2b9
...
...
@@ -70,14 +70,16 @@ const PublicRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const
MainLayout
:
React
.
FC
=
()
=>
{
const
[
collapsed
,
setCollapsed
]
=
useState
(
false
);
const
[
selectedKey
,
setSelectedKey
]
=
useState
(
'/dashboard'
);
const
{
user
,
logout
,
isLoading
,
loadPermissions
,
permissions
}
=
useAuthStore
();
const
{
user
,
logout
,
isLoading
,
loadPermissions
}
=
useAuthStore
();
const
location
=
useLocation
();
const
navigate
=
useNavigate
();
//
加载权限
//
每次应用加载都读取后端真实权限,避免持久化的旧权限掩盖管理员的新分配。
useEffect
(()
=>
{
loadPermissions
();
},
[]);
if
(
user
)
{
void
loadPermissions
(
true
);
}
},
[
user
?.
id
,
loadPermissions
]);
// 根据用户角色过滤菜单
const
visibleMenus
=
useMemo
(()
=>
{
...
...
@@ -183,8 +185,8 @@ const MainLayout: React.FC = () => {
navigate
(
e
.
key
);
};
// 等待
权限加载完成
if
(
isLoading
||
permissions
.
length
===
0
)
{
// 等待
登录加载完成(用于登录后的首次加载)
if
(
isLoading
)
{
return
(
<
div
style=
{
{
display
:
'flex'
,
justifyContent
:
'center'
,
alignItems
:
'center'
,
height
:
'100vh'
}
}
>
<
Spin
size=
"large"
tip=
"加载中..."
/>
...
...
frontend/src/pages/ProjectPage.tsx
浏览文件 @
58c1d2b9
...
...
@@ -13,6 +13,7 @@ import {
Row
,
Select
,
Space
,
Spin
,
Statistic
,
Table
,
Tag
,
...
...
@@ -36,6 +37,8 @@ import {
}
from
'@ant-design/icons'
;
import
axios
from
'axios'
;
import
{
useEffect
,
useState
}
from
'react'
;
import
{
PERMISSION_CODES
,
ROLE_CODES
}
from
'../services/permissionApi'
;
import
{
useAuthStore
}
from
'../stores/useAuthStore'
;
const
{
TextArea
}
=
Input
;
...
...
@@ -93,6 +96,24 @@ type AttachmentItem = {
fileType
:
string
;
};
type
SpreadsheetPreviewSheet
=
{
name
:
string
;
rows
:
string
[][];
truncated
:
boolean
;
};
type
AttachmentPreview
=
|
{
kind
:
'document'
;
fileName
:
string
;
content
:
string
;
}
|
{
kind
:
'spreadsheet'
;
fileName
:
string
;
sheets
:
SpreadsheetPreviewSheet
[];
};
type
ProjectFilters
=
{
page
:
number
;
size
:
number
;
...
...
@@ -354,6 +375,7 @@ const sleep = (ms: number) => new Promise((resolve) => {
export
default
function
ProjectPage
()
{
const
[
messageApi
,
contextHolder
]
=
message
.
useMessage
();
const
{
user
,
permissions
}
=
useAuthStore
();
const
[
loading
,
setLoading
]
=
useState
(
false
);
const
[
projects
,
setProjects
]
=
useState
<
ProjectItem
[]
>
([]);
const
[
total
,
setTotal
]
=
useState
(
0
);
...
...
@@ -385,6 +407,10 @@ export default function ProjectPage() {
const
[
projectModalOpen
,
setProjectModalOpen
]
=
useState
(
false
);
const
[
tagModalOpen
,
setTagModalOpen
]
=
useState
(
false
);
const
[
scorecardModalOpen
,
setScorecardModalOpen
]
=
useState
(
false
);
const
[
attachmentPreviewOpen
,
setAttachmentPreviewOpen
]
=
useState
(
false
);
const
[
attachmentPreviewLoading
,
setAttachmentPreviewLoading
]
=
useState
(
false
);
const
[
attachmentPreview
,
setAttachmentPreview
]
=
useState
<
AttachmentPreview
|
null
>
(
null
);
const
[
selectedPreviewSheet
,
setSelectedPreviewSheet
]
=
useState
(
''
);
const
[
editingProject
,
setEditingProject
]
=
useState
<
ProjectDetail
|
null
>
(
null
);
const
[
editingTag
,
setEditingTag
]
=
useState
<
TagItem
|
null
>
(
null
);
const
[
editingScorecard
,
setEditingScorecard
]
=
useState
<
ScorecardItem
|
null
>
(
null
);
...
...
@@ -394,6 +420,11 @@ export default function ProjectPage() {
const
[
calibrateForm
]
=
Form
.
useForm
();
const
[
knowledgeForm
]
=
Form
.
useForm
<
KnowledgeFormValues
>
();
const
canUploadFile
=
permissions
.
includes
(
PERMISSION_CODES
.
FILE_UPLOAD
);
const
canDownloadFile
=
permissions
.
includes
(
PERMISSION_CODES
.
FILE_DOWNLOAD
);
// 文件预览是项目模块的 P2 管理能力,当前只对 ADMIN 提供入口。
const
canPreviewFile
=
user
?.
roles
?.
includes
(
ROLE_CODES
.
ADMIN
)
??
false
;
useEffect
(()
=>
{
void
Promise
.
all
([
loadProjects
(),
loadTags
(),
loadScorecard
(
1
)]);
},
[]);
...
...
@@ -817,14 +848,141 @@ export default function ProjectPage() {
}
}
;
// 资料预览和下载都走签名链接接口,避免直接依赖详情里临时 URL 的实现细节。
const openAttachment = async (attachment: AttachmentItem) =
>
{
// 文件内容经后端代理读取,远程浏览器无需访问服务器侧的 localhost MinIO 地址。
const fetchAttachmentBlob = async (
attachment: AttachmentItem,
disposition: 'inline' | 'attachment' = 'attachment',
) =
>
{
try
{
const
data
=
await
request
<
{
url
:
string
}
>
(
api
.
get
(
`/files/${attachment.id}/download-url`
));
window
.
open
(
data
.
url
,
'_blank'
,
'noopener,noreferrer'
);
const
response
=
await
api
.
get
(
`/files/${attachment.id}/content`
,
{
params
:
{
disposition
},
responseType
:
'blob'
,
});
return
response
.
data
as
Blob
;
}
catch
(
error
)
{
messageApi
.
error
(
error
instanceof
Error
?
error
.
message
:
'文件链接生成失败'
);
return
null
;
}
}
;
const downloadAttachment = async (attachment: AttachmentItem) =
>
{
const
blob
=
await
fetchAttachmentBlob
(
attachment
);
if
(
!
blob
)
return
;
const
objectUrl
=
URL
.
createObjectURL
(
blob
);
const
link
=
document
.
createElement
(
'a'
);
link
.
href
=
objectUrl
;
link
.
download
=
attachment
.
fileName
;
document
.
body
.
appendChild
(
link
);
link
.
click
();
link
.
remove
();
URL
.
revokeObjectURL
(
objectUrl
);
}
;
const closeAttachmentPreview = () =
>
{
setAttachmentPreviewOpen
(
false
);
setAttachmentPreview
(
null
);
setSelectedPreviewSheet
(
''
);
}
;
const openPreviewModal = () =
>
{
setAttachmentPreview
(
null
);
setAttachmentPreviewLoading
(
true
);
setAttachmentPreviewOpen
(
true
);
}
;
const openDocumentPreview = async (attachment: AttachmentItem) =
>
{
openPreviewModal
();
const
blob
=
await
fetchAttachmentBlob
(
attachment
,
'inline'
);
if
(
!
blob
)
{
closeAttachmentPreview
();
return
;
}
try
{
// 只提取 DOCX 纯文本而不直接插入 HTML,避免上传文档内容成为页面脚本注入入口。
const
mammoth
=
await
import
(
'mammoth'
);
const
result
=
await
mammoth
.
extractRawText
({
arrayBuffer
:
await
blob
.
arrayBuffer
()
});
setAttachmentPreview
({
kind
:
'document'
,
fileName
:
attachment
.
fileName
,
content
:
result
.
value
.
trim
()
||
'该文档不包含可提取的正文文本。'
,
});
}
catch
(
error
)
{
closeAttachmentPreview
();
messageApi
.
error
(
error
instanceof
Error
?
error
.
message
:
'DOCX 文件解析失败'
);
}
finally
{
setAttachmentPreviewLoading
(
false
);
}
}
;
const openSpreadsheetPreview = async (attachment: AttachmentItem) =
>
{
openPreviewModal
();
const
blob
=
await
fetchAttachmentBlob
(
attachment
,
'inline'
);
if
(
!
blob
)
{
closeAttachmentPreview
();
return
;
}
try
{
const
xlsxModule
=
await
import
(
'xlsx'
);
// xlsx 在不同构建环境中可能是默认导出或命名导出,这里统一为同一个调用对象。
const
XLSX
=
(
'default'
in
xlsxModule
?
xlsxModule
.
default
:
xlsxModule
)
as
typeof
xlsxModule
;
const
workbook
=
XLSX
.
read
(
await
blob
.
arrayBuffer
(),
{
type
:
'array'
});
const
sheets
=
workbook
.
SheetNames
.
map
((
name
)
=>
{
const
worksheet
=
workbook
.
Sheets
[
name
];
const
rawRows
=
XLSX
.
utils
.
sheet_to_json
<
unknown
[]
>
(
worksheet
,
{
header
:
1
,
defval
:
''
,
raw
:
false
,
});
const
truncated
=
rawRows
.
length
>
200
||
rawRows
.
some
((
row
)
=>
row
.
length
>
30
);
return
{
name
,
// 预览只渲染前 200 行、30 列,避免大表格阻塞项目详情页。
rows
:
rawRows
.
slice
(
0
,
200
).
map
((
row
)
=>
row
.
slice
(
0
,
30
).
map
((
cell
)
=>
String
(
cell
??
''
))),
truncated
,
};
});
if
(
sheets
.
length
===
0
)
{
throw
new
Error
(
'Excel 文件不包含可预览的工作表'
);
}
setAttachmentPreview
({
kind
:
'spreadsheet'
,
fileName
:
attachment
.
fileName
,
sheets
});
setSelectedPreviewSheet
(
sheets
[
0
].
name
);
}
catch
(
error
)
{
closeAttachmentPreview
();
messageApi
.
error
(
error
instanceof
Error
?
error
.
message
:
'Excel 文件解析失败'
);
}
finally
{
setAttachmentPreviewLoading
(
false
);
}
}
;
const previewAttachment = async (attachment: AttachmentItem) =
>
{
const
extension
=
attachment
.
fileName
.
split
(
'.'
).
pop
()?.
toLowerCase
();
if
(
extension
===
'docx'
)
{
await
openDocumentPreview
(
attachment
);
return
;
}
if
(
extension
===
'xls'
||
extension
===
'xlsx'
)
{
await
openSpreadsheetPreview
(
attachment
);
return
;
}
if
(
extension
===
'pdf'
)
{
// 先在用户点击时创建窗口,避免异步请求完成后被浏览器当作弹窗拦截。
const
previewWindow
=
window
.
open
(
''
,
'_blank'
);
if
(
!
previewWindow
)
{
messageApi
.
error
(
'浏览器拦截了预览窗口,请允许当前站点打开弹窗后重试'
);
return
;
}
const
blob
=
await
fetchAttachmentBlob
(
attachment
,
'inline'
);
if
(
!
blob
)
{
previewWindow
.
close
();
return
;
}
const
objectUrl
=
URL
.
createObjectURL
(
blob
);
previewWindow
.
location
.
href
=
objectUrl
;
previewWindow
.
addEventListener
(
'beforeunload'
,
()
=>
URL
.
revokeObjectURL
(
objectUrl
),
{
once
:
true
});
return
;
}
messageApi
.
info
(
'旧版 DOC 和压缩包暂不支持在线预览,已开始下载'
);
await
downloadAttachment
(
attachment
);
}
;
const columns: ColumnsType
<
ProjectItem
>
= [
...
...
@@ -887,6 +1045,33 @@ export default function ProjectPage() {
.filter((item) =
>
item.id !== editingKnowledgePoint?.id)
.map((item) =
>
(
{
label
:
item
.
name
,
value
:
item
.
id
}
));
const previewSheet = attachmentPreview?.kind === 'spreadsheet'
? attachmentPreview.sheets.find((sheet) =
>
sheet.name === selectedPreviewSheet)
|| attachmentPreview.sheets[0]
: undefined;
const previewTableColumns: ColumnsType
<
{
key
:
string
;
cells
:
string
[]
}
>
= (previewSheet?.rows[0] || [])
.map((title, index) =
>
(
{
title
:
title
||
`第 ${index + 1} 列`
,
width
:
160
,
render
:
(
_
,
row
)
=>
row
.
cells
[
index
]
||
'-'
,
}
));
const previewTableRows = (previewSheet?.rows.slice(1) || [])
.map((cells, index) =
>
(
{
key
:
String
(
index
),
cells
}
));
const attachmentColumns: ColumnsType
<
AttachmentItem
>
= [
{
title
:
'文件'
,
dataIndex
:
'fileName'
}
,
{
title
:
'类型'
,
dataIndex
:
'fileType'
,
width
:
120
}
,
...(canPreviewFile || canDownloadFile ? [
{
title
:
'操作'
,
width
:
180
,
render
:
(
_
:
unknown
,
record
:
AttachmentItem
)
=>
(
<
Space
>
{
canPreviewFile
&&
<
Button
size=
"small"
onClick=
{
()
=>
void
previewAttachment
(
record
)
}
>
预览
</
Button
>
}
{
canDownloadFile
&&
<
Button
size=
"small"
onClick=
{
()
=>
void
downloadAttachment
(
record
)
}
>
下载
</
Button
>
}
</
Space
>
),
}
] : []),
];
return (
<
Space
direction=
"vertical"
size=
{
16
}
style=
{
{
width
:
'100%'
}
}
>
{
contextHolder
}
...
...
@@ -1270,6 +1455,53 @@ export default function ProjectPage() {
/>
</
Modal
>
<
Modal
title=
{
attachmentPreview
?
`预览:${attachmentPreview.fileName}`
:
'文件预览'
}
open=
{
attachmentPreviewOpen
}
onCancel=
{
closeAttachmentPreview
}
footer=
{
<
Button
onClick=
{
closeAttachmentPreview
}
>
关闭
</
Button
>
}
width=
{
1000
}
destroyOnClose
>
{
attachmentPreviewLoading
&&
(
<
Space
direction=
"vertical"
align=
"center"
style=
{
{
display
:
'flex'
,
minHeight
:
260
,
justifyContent
:
'center'
}
}
>
<
Spin
/>
<
Typography
.
Text
type=
"secondary"
>
正在解析文件,请稍候...
</
Typography
.
Text
>
</
Space
>
)
}
{
!
attachmentPreviewLoading
&&
attachmentPreview
?.
kind
===
'document'
&&
(
<
Typography
.
Paragraph
style=
{
{
whiteSpace
:
'pre-wrap'
,
maxHeight
:
'65vh'
,
overflowY
:
'auto'
,
marginBottom
:
0
}
}
>
{
attachmentPreview
.
content
}
</
Typography
.
Paragraph
>
)
}
{
!
attachmentPreviewLoading
&&
attachmentPreview
?.
kind
===
'spreadsheet'
&&
previewSheet
&&
(
<
Space
direction=
"vertical"
size=
{
12
}
style=
{
{
width
:
'100%'
}
}
>
<
Select
value=
{
previewSheet
.
name
}
options=
{
attachmentPreview
.
sheets
.
map
((
sheet
)
=>
({
label
:
sheet
.
name
,
value
:
sheet
.
name
}))
}
style=
{
{
width
:
240
}
}
onChange=
{
setSelectedPreviewSheet
}
/>
{
previewSheet
.
truncated
&&
(
<
Typography
.
Text
type=
"secondary"
>
预览仅显示当前工作表前 200 行、30 列,完整内容请下载查看。
</
Typography
.
Text
>
)
}
{
previewTableColumns
.
length
>
0
?
(
<
Table
bordered
size=
"small"
rowKey=
"key"
pagination=
{
false
}
columns=
{
previewTableColumns
}
dataSource=
{
previewTableRows
}
scroll=
{
{
x
:
'max-content'
,
y
:
480
}
}
/>
)
:
(
<
Typography
.
Text
type=
"secondary"
>
该工作表没有可预览的数据。
</
Typography
.
Text
>
)
}
</
Space
>
)
}
</
Modal
>
<
Drawer
title=
{
detail
?.
name
}
width=
{
860
}
...
...
@@ -1283,6 +1515,7 @@ export default function ProjectPage() {
setRecommendationHistory
([]);
setKnowledgeModalOpen
(
false
);
setEditingKnowledgePoint
(
null
);
closeAttachmentPreview
();
calibrateForm
.
resetFields
();
knowledgeForm
.
resetFields
();
}
}
...
...
@@ -1322,28 +1555,17 @@ export default function ProjectPage() {
{
detail
.
githubUrl
?
<
a
href=
{
detail
.
githubUrl
}
target=
"_blank"
rel=
"noreferrer"
>
{
detail
.
githubUrl
}
</
a
>
:
'-'
}
</
Descriptions
.
Item
>
</
Descriptions
>
{
canUploadFile
&&
(
<
Upload
customRequest=
{
uploadFile
}
showUploadList=
{
false
}
>
<
Button
icon=
{
<
CloudUploadOutlined
/>
}
>
上传资料
</
Button
>
</
Upload
>
)
}
<
Table
size=
"small"
rowKey=
"id"
pagination=
{
false
}
dataSource=
{
detail
.
attachments
||
[]
}
columns=
{
[
{
title
:
'文件'
,
dataIndex
:
'fileName'
},
{
title
:
'类型'
,
dataIndex
:
'fileType'
,
width
:
120
},
{
title
:
'操作'
,
width
:
180
,
render
:
(
_
,
record
:
AttachmentItem
)
=>
(
<
Space
>
<
Button
size=
"small"
onClick=
{
()
=>
void
openAttachment
(
record
)
}
>
预览
</
Button
>
<
Button
size=
"small"
onClick=
{
()
=>
void
openAttachment
(
record
)
}
>
下载
</
Button
>
</
Space
>
),
},
]
}
columns=
{
attachmentColumns
}
/>
</
Space
>
),
...
...
frontend/src/services/permissionApi.ts
浏览文件 @
58c1d2b9
...
...
@@ -21,6 +21,7 @@ export interface User {
status
:
number
;
createdAt
:
string
;
roles
?:
string
[];
permissions
?:
string
[];
}
// 角色类型
...
...
frontend/src/stores/useAuthStore.ts
浏览文件 @
58c1d2b9
import
{
create
}
from
'zustand'
;
import
{
persist
}
from
'zustand/middleware'
;
import
{
login
as
loginApi
,
logout
as
logoutApi
,
phoneLogin
as
phoneLoginApi
,
LoginResponse
}
from
'../services/authApi'
;
import
{
userApi
,
menuApi
,
PERMISSION_CODES
,
User
}
from
'../services/permissionApi'
;
import
{
userApi
,
menuApi
}
from
'../services/permissionApi'
;
interface
AuthState
{
user
:
LoginResponse
[
'user'
]
|
null
;
...
...
@@ -11,6 +11,7 @@ interface AuthState {
refreshToken
:
string
|
null
;
isAuthenticated
:
boolean
;
isLoading
:
boolean
;
permissionsLoading
:
boolean
;
// Actions
setAuth
:
(
data
:
LoginResponse
)
=>
void
;
...
...
@@ -18,7 +19,7 @@ interface AuthState {
phoneLogin
:
(
phone
:
string
,
smsCode
:
string
)
=>
Promise
<
void
>
;
logout
:
()
=>
Promise
<
void
>
;
clearAuth
:
()
=>
void
;
loadPermissions
:
()
=>
Promise
<
void
>
;
loadPermissions
:
(
force
?:
boolean
)
=>
Promise
<
void
>
;
loadMenus
:
()
=>
Promise
<
void
>
;
}
...
...
@@ -32,6 +33,7 @@ export const useAuthStore = create<AuthState>()(
refreshToken
:
null
,
isAuthenticated
:
false
,
isLoading
:
false
,
permissionsLoading
:
false
,
setAuth
:
(
data
:
LoginResponse
)
=>
{
localStorage
.
setItem
(
'accessToken'
,
data
.
accessToken
);
...
...
@@ -41,6 +43,7 @@ export const useAuthStore = create<AuthState>()(
accessToken
:
data
.
accessToken
,
refreshToken
:
data
.
refreshToken
,
isAuthenticated
:
true
,
permissions
:
[],
});
},
...
...
@@ -89,21 +92,27 @@ export const useAuthStore = create<AuthState>()(
accessToken
:
null
,
refreshToken
:
null
,
isAuthenticated
:
false
,
permissionsLoading
:
false
,
});
},
// 加载用户权限
loadPermissions
:
async
()
=>
{
loadPermissions
:
async
(
force
=
false
)
=>
{
const
currentState
=
get
();
// 防止重复加载
if
(
currentState
.
permissionsLoading
||
(
!
force
&&
currentState
.
permissions
.
length
>
0
))
{
return
;
}
set
({
permissionsLoading
:
true
});
try
{
// 获取
用户详情,包含权限信息
// 获取
后端按角色实际配置计算出的权限,支持管理员动态调整角色权限。
const
userDetail
=
await
userApi
.
getCurrentUser
();
// 根据用户角色预设默认权限
const
roles
=
userDetail
.
roles
||
[];
const
defaultPermissions
=
getDefaultPermissionsByRoles
(
roles
);
set
({
permissions
:
defaultPermissions
});
set
({
permissions
:
userDetail
.
permissions
||
[],
permissionsLoading
:
false
});
}
catch
(
error
)
{
console
.
error
(
'加载权限失败:'
,
error
);
set
({
permissions
:
[]
});
// 即使加载失败,也设置 permissionsLoading 为 false,避免无限等待
set
({
permissions
:
[],
permissionsLoading
:
false
});
}
},
...
...
@@ -127,99 +136,8 @@ export const useAuthStore = create<AuthState>()(
accessToken
:
state
.
accessToken
,
refreshToken
:
state
.
refreshToken
,
isAuthenticated
:
state
.
isAuthenticated
,
// 注意:permissionsLoading 不需要持久化,因为它只在运行时使用
}),
}
)
);
// 根据用户角色获取默认权限
function
getDefaultPermissionsByRoles
(
roles
:
string
[]):
string
[]
{
const
allPermissions
:
string
[]
=
[];
const
roleSet
=
new
Set
(
roles
);
// ADMIN 拥有所有权限
if
(
roleSet
.
has
(
'ADMIN'
))
{
return
Object
.
values
(
PERMISSION_CODES
);
}
// 公共权限 - 所有人都有的权限
const
publicPermissions
=
[
PERMISSION_CODES
.
PROJECT_VIEW
,
PERMISSION_CODES
.
PROJECT_SIMPLE_LIST
,
PERMISSION_CODES
.
TAG_VIEW
,
PERMISSION_CODES
.
RECOMMEND_VIEW
,
PERMISSION_CODES
.
KNOWLEDGE_VIEW
,
PERMISSION_CODES
.
DEFENSE_VIEW
,
PERMISSION_CODES
.
PROFILE_VIEW
,
PERMISSION_CODES
.
DEFECT_VIEW
,
PERMISSION_CODES
.
ADVANCED_VIEW
,
PERMISSION_CODES
.
ROLE_VIEW
,
];
allPermissions
.
push
(...
publicPermissions
);
// 主管权限
if
(
roleSet
.
has
(
'SUPERVISOR'
))
{
const
supervisorPermissions
=
[
PERMISSION_CODES
.
DIFFICULTY_VIEW
,
PERMISSION_CODES
.
DIFFICULTY_CALIBRATE
,
PERMISSION_CODES
.
DIFFICULTY_AI_SCORE_VIEW
,
PERMISSION_CODES
.
TRAINING_VIEW_ALL
,
PERMISSION_CODES
.
TRAINING_VIEW_DETAIL
,
PERMISSION_CODES
.
PREVIEW_VIEW_PROGRESS
,
PERMISSION_CODES
.
DEFENSE_AUDIT
,
PERMISSION_CODES
.
DEFENSE_PENDING_LIST
,
PERMISSION_CODES
.
HISTORY_VIEW_ALL
,
PERMISSION_CODES
.
CONTAINER_MANAGE
,
PERMISSION_CODES
.
USER_VIEW_LIST
,
PERMISSION_CODES
.
USER_VIEW_DETAIL
,
PERMISSION_CODES
.
MENTOR_DASHBOARD
,
];
allPermissions
.
push
(...
supervisorPermissions
);
}
// 导师权限
if
(
roleSet
.
has
(
'MENTOR'
))
{
const
mentorPermissions
=
[
PERMISSION_CODES
.
DIFFICULTY_VIEW
,
PERMISSION_CODES
.
TRAINING_VIEW_ASSIGNED
,
PERMISSION_CODES
.
TRAINING_VIEW_DETAIL
,
PERMISSION_CODES
.
PREVIEW_VIEW_PROGRESS
,
PERMISSION_CODES
.
DEFENSE_REVIEW
,
PERMISSION_CODES
.
DEFENSE_PENDING_LIST
,
PERMISSION_CODES
.
HISTORY_VIEW_DEPARTMENT
,
PERMISSION_CODES
.
DEFECT_ADD
,
PERMISSION_CODES
.
USER_VIEW_DETAIL
,
PERMISSION_CODES
.
MENTOR_DASHBOARD
,
];
allPermissions
.
push
(...
mentorPermissions
);
}
// 学员权限
if
(
roleSet
.
has
(
'STUDENT'
))
{
const
studentPermissions
=
[
PERMISSION_CODES
.
RECOMMEND_REQUEST
,
PERMISSION_CODES
.
RECOMMEND_CHOOSE
,
PERMISSION_CODES
.
RECOMMEND_IGNORE
,
PERMISSION_CODES
.
TRAINING_CREATE
,
PERMISSION_CODES
.
TRAINING_VIEW_OWN
,
PERMISSION_CODES
.
TRAINING_UPDATE
,
PERMISSION_CODES
.
TRAINING_DELETE
,
PERMISSION_CODES
.
TRAINING_VIEW_DETAIL
,
PERMISSION_CODES
.
PREVIEW_VIEW_KNOWLEDGE
,
PERMISSION_CODES
.
PREVIEW_SUBMIT
,
PERMISSION_CODES
.
PREVIEW_TAK_QUIZ
,
PERMISSION_CODES
.
PRACTICE_SUBMIT_ARTIFACT
,
PERMISSION_CODES
.
PRACTICE_WRITE_REPORT
,
PERMISSION_CODES
.
PRACTICE_SUBMIT_REPORT
,
PERMISSION_CODES
.
DEFENSE_APPLY
,
PERMISSION_CODES
.
HISTORY_VIEW_OWN
,
PERMISSION_CODES
.
CONTAINER_USE
,
PERMISSION_CODES
.
ADVANCED_ACCEPT
,
PERMISSION_CODES
.
ADVANCED_REJECT
,
];
allPermissions
.
push
(...
studentPermissions
);
}
// 去重
return
[...
new
Set
(
allPermissions
)];
}
milvus-lab/scripts/import_data.py
0 → 100644
浏览文件 @
58c1d2b9
import
numpy
as
np
from
pymilvus
import
MilvusClient
client
=
MilvusClient
(
uri
=
'http://localhost:19530'
)
COLLECTION
=
'demo_vector_db'
DIM
=
1536
N
=
1000
# Drop & create with GPU 6 index
client
.
drop_collection
(
COLLECTION
)
client
.
create_collection
(
COLLECTION
,
dimension
=
DIM
,
primary_field
=
'id'
,
vector_field
=
'vector'
,
index_params
=
{
'index_type'
:
'GPU_IVF_FLAT'
,
'metric_type'
:
'L2'
,
'params'
:
{
'nlist'
:
128
,
'gpu_id'
:
6
}
}
)
# Insert 1000 random vectors
np
.
random
.
seed
(
42
)
data
=
[{
'id'
:
i
,
'vector'
:
np
.
random
.
rand
(
DIM
)
.
astype
(
np
.
float32
)
.
tolist
()}
for
i
in
range
(
N
)]
client
.
insert
(
COLLECTION
,
data
=
data
)
client
.
flush
(
COLLECTION
)
# Verify
stats
=
client
.
get_collection_stats
(
COLLECTION
)
print
(
f
"集合: {COLLECTION}"
)
print
(
f
"维度: {DIM}"
)
print
(
f
"向量数量: {stats.get('row_count', '?')}"
)
print
(
f
"索引: GPU_IVF_FLAT (GPU 6)"
)
# Quick search
import
time
results
=
client
.
search
(
COLLECTION
,
data
=
[
np
.
random
.
rand
(
DIM
)
.
astype
(
np
.
float32
)
.
tolist
()],
limit
=
5
,
search_params
=
{
'nprobe'
:
16
}
)
print
(
f
"检索验证: 返回 {len(results[0])} 条结果, 示例 id={[r['id'] for r in results[0]]}"
)
scripts/start.sh
浏览文件 @
58c1d2b9
...
...
@@ -6,11 +6,16 @@
# - frontend : Vite dev server,端口 7080
# - ai-service : FastAPI,端口 7083
#
# 前置依赖(Docker 容器,已设置成自愈式检测):
# - studyweb-mysql : MySQL 8.0,宿主端口 5688(容器 3306)
# - studyweb-redis : Redis 7,宿主端口 16379(容器 6379)
#
# 用法:
# ./scripts/start.sh # 默认启动所有服务
# ./scripts/start.sh start # 启动所有服务
# ./scripts/start.sh restart # 重启所有服务
# ./scripts/start.sh stop # 停止所有服务
# ./scripts/start.sh status # 查看依赖与服务状态
# =============================================================================
set
-e
...
...
@@ -27,15 +32,28 @@ BACKEND_LOG="${PROJECT_ROOT}/logs/backend-app.log"
FRONTEND_LOG
=
"
${
PROJECT_ROOT
}
/logs/frontend.log"
AISERVICE_LOG
=
"
${
PROJECT_ROOT
}
/logs/ai-service.log"
# ---------- 超时配置(秒)----------
MAX_STARTUP_TIME
=
60
mkdir
-p
"
${
PROJECT_ROOT
}
/logs"
# ---------- 颜色 ----------
RED
=
'\033[0;31m'
GREEN
=
'\033[0;32m'
YELLOW
=
'\033[1;33m'
NC
=
'\033[0m'
ok
()
{
echo
-e
"
${
GREEN
}
[✓]
${
NC
}
$*
"
;
}
warn
()
{
echo
-e
"
${
YELLOW
}
[!]
${
NC
}
$*
"
;
}
err
()
{
echo
-e
"
${
RED
}
[✗]
${
NC
}
$*
"
;
}
# ---------- conda 环境激活 ----------
CONDA_SH
=
"/datacore/home/admin2/miniconda3/etc/profile.d/conda.sh"
if
[
-f
"
${
CONDA_SH
}
"
]
;
then
# shellcheck disable=SC1090
source
"
${
CONDA_SH
}
"
conda activate studyweb
else
e
cho
"错误:
找不到 conda.sh(
${
CONDA_SH
}
),请确认 conda 安装路径"
e
rr
"
找不到 conda.sh(
${
CONDA_SH
}
),请确认 conda 安装路径"
exit
1
fi
...
...
@@ -44,35 +62,125 @@ is_running() {
pgrep
-f
"
$1
"
&>/dev/null
}
# ---------- 端口占用工具 ----------
port_in_use
()
{
local
port
=
"
$1
"
if
command
-v
ss &>/dev/null
;
then
ss
-tln
"sport = :
${
port
}
"
2>/dev/null |
tail
-n
+2 |
grep
-q
LISTEN
else
lsof
-iTCP
:
"
${
port
}
"
-sTCP
:LISTEN &>/dev/null
fi
}
free_port
()
{
local
port
=
"
$1
"
local
pids
if
command
-v
fuser &>/dev/null
;
then
pids
=
$(
fuser
"
${
port
}
/tcp"
2>/dev/null
||
true
)
[
-n
"
${
pids
}
"
]
&&
kill
-9
${
pids
}
2>/dev/null
||
true
fi
if
command
-v
lsof &>/dev/null
;
then
pids
=
$(
lsof
-iTCP
:
"
${
port
}
"
-sTCP
:LISTEN
-t
2>/dev/null
||
true
)
[
-n
"
${
pids
}
"
]
&&
kill
-9
${
pids
}
2>/dev/null
||
true
fi
}
# ---------- 依赖健康检查:Docker 容器 ----------
ensure_container
()
{
local
name
=
"
$1
"
local
label
=
"
$2
"
if
!
command
-v
docker &>/dev/null
;
then
err
"docker 命令不可用,跳过
${
label
}
自愈"
return
1
fi
local
state
state
=
$(
docker inspect
-f
'{{.State.Running}}'
"
${
name
}
"
2>/dev/null
||
echo
"missing"
)
case
"
${
state
}
"
in
true
)
ok
"
${
label
}
(
${
name
}
) 已在运行"
;;
false
)
warn
"
${
label
}
(
${
name
}
) 已停止,尝试启动..."
docker start
"
${
name
}
"
>
/dev/null
ok
"
${
label
}
已启动"
;;
missing
)
err
"容器
${
name
}
不存在,请先创建(docker run / docker-compose up)"
exit
1
;;
*
)
err
"无法读取
${
name
}
状态:
${
state
}
"
exit
1
;;
esac
}
wait_for_tcp
()
{
local
host
=
"
$1
"
port
=
"
$2
"
label
=
"
$3
"
timeout
=
"
${
4
:-
30
}
"
for
i
in
$(
seq
1
"
${
timeout
}
"
)
;
do
if
(
echo
>
/dev/tcp/
"
${
host
}
"
/
"
${
port
}
"
)
2>/dev/null
;
then
ok
"
${
label
}
${
host
}
:
${
port
}
已就绪 (
${
i
}
s)"
return
0
fi
sleep
1
done
err
"
${
label
}
${
host
}
:
${
port
}
在
${
timeout
}
s 内未就绪"
return
1
}
check_dependencies
()
{
echo
">>> 检查依赖容器..."
ensure_container
"studyweb-mysql"
"MySQL"
ensure_container
"studyweb-redis"
"Redis"
echo
">>> 等待依赖端口就绪..."
wait_for_tcp localhost 5688
"MySQL"
30
wait_for_tcp localhost 16379
"Redis"
10
}
# ---------- 超时检测 ----------
check_timeout
()
{
local
start_time
=
$1
local
service_name
=
$2
local
elapsed
=
$((
$(
date
+%s
)
-
start_time
))
if
[
${
elapsed
}
-gt
${
MAX_STARTUP_TIME
}
]
;
then
err
"
${
service_name
}
启动超时(已超过 60 s)"
return
1
fi
return
0
}
# ---------- 停止服务 ----------
do_stop
()
{
echo
">>> 停止所有服务..."
# 1.
先尝试
优雅终止
# 1. 优雅终止
pkill
-f
"mvn.*spring-boot:run"
2>/dev/null
||
true
pkill
-f
"com.platform.backend.BackendApplication"
2>/dev/null
||
true
pkill
-f
"vite.*7080"
2>/dev/null
||
true
pkill
-f
"uvicorn.*7083"
2>/dev/null
||
true
# 2. 等待进程退出
sleep
2
# 3. 强制杀死仍未退出的进程
# 2. 强制杀进程
pkill
-9
-f
"mvn.*spring-boot:run"
2>/dev/null
||
true
pkill
-9
-f
"com.platform.backend"
2>/dev/null
||
true
pkill
-9
-f
"node.*vite"
2>/dev/null
||
true
pkill
-9
-f
"uvicorn.*7083"
2>/dev/null
||
true
#
4. 杀掉占用端口的进程
f
user
-k
7087/tcp 2>/dev/null
||
true
f
user
-k
7080/tcp 2>/dev/null
||
true
f
user
-k
7083/tcp 2>/dev/null
||
true
#
3. 端口兜底
f
ree_port 7087
f
ree_port 7080
f
ree_port 7083
sleep
1
#
5
. 验证端口已释放
#
4
. 验证端口已释放
for
port
in
7087 7080 7083
;
do
if
lsof
-i
:
${
port
}
&>/dev/null
;
then
echo
" 警告: 端口
${
port
}
仍被占用,尝试强制清理..."
lsof
-i
:
${
port
}
-t
| xargs
-r
kill
-9
2>/dev/null
||
true
if
port_in_use
"
${
port
}
"
;
then
warn
"端口
${
port
}
仍被占用"
else
ok
"端口
${
port
}
已释放"
fi
done
...
...
@@ -81,34 +189,77 @@ do_stop() {
# ---------- 启动服务 ----------
do_start
()
{
local
start_time
=
$(
date
+%s
)
echo
">>> 启动所有服务..."
check_dependencies
# 检查整体超时
if
!
check_timeout
${
start_time
}
"整体启动"
;
then
err
"启动过程已超过 60 s,强制退出"
exit
1
fi
# 0. 端口预检查
for
port
in
7087 7080 7083
;
do
if
port_in_use
"
${
port
}
"
;
then
warn
"端口
${
port
}
已被占用,先清理..."
free_port
"
${
port
}
"
sleep
1
fi
done
# 1. backend-app
if
is_running
"mvn.*spring-boot:run"
;
then
echo
"[backend-app] 已运行,跳过
"
if
is_running
"mvn.*spring-boot:run"
||
port_in_use 7087
;
then
warn
"[backend-app] 已在运行,跳过启动
"
else
echo
"[backend-app] 启动中(端口 7087)..."
cd
"
${
BACKEND_DIR
}
"
nohup
mvn spring-boot:run
\
-Dspring-boot
.run.jvmArguments
=
"-Xms256m -Xmx512m"
\
>
"
${
BACKEND_LOG
}
"
2>&1 &
echo
"[backend-app] pid=
$!
,日志 ->
${
BACKEND_LOG
}
"
# 等待 Spring Boot 启动
echo
" 等待 backend-app 启动(最多 120s)..."
for
i
in
$(
seq
1 60
)
;
do
local
backend_pid
=
$!
echo
"[backend-app] pid=
${
backend_pid
}
,日志 ->
${
BACKEND_LOG
}
"
echo
" 等待 backend-app 启动(最多 60 s)..."
ready
=
0
for
i
in
$(
seq
1 180
)
;
do
sleep
2
if
curl
-sf
http://localhost:7087/actuator/health &>/dev/null
||
\
curl
-sf
http://localhost:7087/ &>/dev/null
;
then
echo
" backend-app 已就绪"
# 检查超时
if
!
check_timeout
${
start_time
}
"backend-app"
;
then
err
"backend-app 启动超时,强制退出"
kill
-9
${
backend_pid
}
2>/dev/null
||
true
exit
1
fi
# 真实登录探测,更可靠
if
curl
-sf
-o
/dev/null
-X
POST http://localhost:7087/api/v1/auth/login
\
-H
"Content-Type: application/json"
\
-d
'{"username":"admin","password":"admin123"}'
;
then
ok
"backend-app 已就绪(登录成功,约
$((
i
*
2
))
s)"
ready
=
1
break
fi
echo
" 等待中... (
$((
i
*
2
))
s)"
# 180s 仍未就绪,再做一次错误检测
if
[
$((
i
%
15
))
-eq
0
]
;
then
if
grep
-q
"APPLICATION FAILED TO START
\|
Caused by:
\|
BUILD FAILURE
\|
COMPILATION ERROR"
"
${
BACKEND_LOG
}
"
2>/dev/null
;
then
err
"backend-app 启动失败,请查看日志:tail -50
${
BACKEND_LOG
}
"
tail
-30
"
${
BACKEND_LOG
}
"
||
true
exit
1
fi
local
elapsed
=
$((
$(
date
+%s
)
-
start_time
))
echo
" 等待中... (
${
elapsed
}
s)"
fi
done
if
[
"
${
ready
}
"
-ne
1
]
;
then
err
"backend-app 在 60 s内未就绪,请查看
${
BACKEND_LOG
}
"
tail
-50
"
${
BACKEND_LOG
}
"
||
true
exit
1
fi
fi
# 2. ai-service
if
is_running
"uvicorn.*7083"
;
then
echo
"[ai-service] 已运行,跳过
"
if
is_running
"uvicorn.*7083"
||
port_in_use 7083
;
then
warn
"[ai-service] 已在运行,跳过启动
"
else
echo
"[ai-service] 启动中(端口 7083)..."
cd
"
${
AISERVICE_DIR
}
"
...
...
@@ -119,15 +270,15 @@ do_start() {
echo
"[ai-service] pid=
$!
,日志 ->
${
AISERVICE_LOG
}
"
sleep
2
if
curl
-sf
http://localhost:7083/api/health &>/dev/null
;
then
echo
"[ai-service]
已就绪"
ok
"ai-service
已就绪"
else
echo
"[ai-service]
启动中,health 接口可能稍后可用"
warn
"ai-service
启动中,health 接口可能稍后可用"
fi
fi
# 3. frontend
if
is_running
"vite.*7080"
;
then
echo
"[frontend] 已运行,跳过
"
if
is_running
"vite.*7080"
||
port_in_use 7080
;
then
warn
"[frontend] 已在运行,跳过启动
"
else
echo
"[frontend] 启动中(端口 7080)..."
cd
"
${
FRONTEND_DIR
}
"
...
...
@@ -136,24 +287,48 @@ do_start() {
echo
"[frontend] pid=
$!
,日志 ->
${
FRONTEND_LOG
}
"
sleep
3
if
curl
-sf
http://localhost:7080/ &>/dev/null
;
then
echo
"[frontend]
已就绪"
ok
"frontend
已就绪"
else
echo
"[frontend]
启动中,页面可能稍后可用"
warn
"frontend
启动中,页面可能稍后可用"
fi
fi
local
total_elapsed
=
$((
$(
date
+%s
)
-
start_time
))
echo
""
echo
"==========================================="
echo
" 服务已全部启动"
echo
" 服务已全部启动
(耗时
${
total_elapsed
}
s)
"
echo
" backend-app : http://localhost:7087"
echo
" ai-service : http://localhost:7083"
echo
" frontend : http://localhost:7080"
echo
"==========================================="
}
# ---------- 状态查询 ----------
do_status
()
{
echo
">>> 服务状态"
for
entry
in
"backend-app:7087"
"ai-service:7083"
"frontend:7080"
;
do
name
=
"
${
entry
%%
:
*
}
"
port
=
"
${
entry
##*
:
}
"
if
port_in_use
"
${
port
}
"
;
then
ok
"
${
name
}
(
${
port
}
) 监听中"
else
warn
"
${
name
}
(
${
port
}
) 未监听"
fi
done
echo
""
echo
">>> 容器状态"
for
c
in
studyweb-mysql studyweb-redis
;
do
state
=
$(
docker inspect
-f
'{{.State.Running}}'
"
${
c
}
"
2>/dev/null
||
echo
"missing"
)
case
"
${
state
}
"
in
true
)
ok
"
${
c
}
运行中"
;;
false
)
warn
"
${
c
}
已停止"
;;
*
)
err
"
${
c
}
缺失"
;;
esac
done
}
# ---------- 主逻辑 ----------
ACTION
=
"
${
1
:-
start
}
"
case
"
${
ACTION
}
"
in
start|restart
)
do_stop
...
...
@@ -163,11 +338,15 @@ case "${ACTION}" in
stop
)
do_stop
;;
status
)
do_status
;;
*
)
echo
"用法:
$0
[start|restart|stop]"
echo
"用法:
$0
[start|restart|stop
|status
]"
echo
" start — 启动所有服务(默认)"
echo
" restart — 重启所有服务"
echo
" stop — 停止所有服务"
echo
" status — 查看依赖与服务状态"
exit
1
;;
esac
编写
预览
Markdown
格式
0%
重试
或
添加新文件
添加附件
取消
您添加了
0
人
到此讨论。请谨慎行事。
请先完成此评论的编辑!
取消
请
注册
或者
登录
后发表评论