\"fix: use explicit labels and native text order_by to enforce strict warning logic\"
This commit is contained in:
@ -313,32 +313,37 @@ class MaterialBaseService:
|
||||
enable_warning_sort = has_warning_permission and filters.get('enableWarningSort', False)
|
||||
|
||||
if enable_warning_sort:
|
||||
print("====== [DEBUG] 成功进入预警智能排序逻辑 ======")
|
||||
from sqlalchemy import text
|
||||
|
||||
# 状态层级:红(2) > 黄(1) > 常规(0)
|
||||
print("====== [DEBUG] 执行虚拟列强排模式 ======")
|
||||
|
||||
# 1. 建立虚拟列标签 (显式暴露出计算结果)
|
||||
warning_level = case([
|
||||
(and_(MaterialWarningSetting.is_enabled.is_(True), total_inv <= MaterialWarningSetting.red_threshold), 2),
|
||||
(and_(MaterialWarningSetting.is_enabled.is_(True), total_inv <= MaterialWarningSetting.yellow_threshold), 1)
|
||||
], else_=0)
|
||||
], else_=0).label('sort_level')
|
||||
|
||||
# 红色组内部:缺口越大越靠前 (red_threshold - total_inv) DESC
|
||||
# 红色组内部:缺口越大越靠前 DESC
|
||||
red_shortage = case([
|
||||
(and_(MaterialWarningSetting.is_enabled.is_(True), total_inv <= MaterialWarningSetting.red_threshold),
|
||||
MaterialWarningSetting.red_threshold - total_inv)
|
||||
], else_=0)
|
||||
], else_=0).label('sort_red')
|
||||
|
||||
# 黄色组内部:距离红线越近越靠前 (total_inv - red_threshold) ASC
|
||||
# 黄色组内部:距离红线越近越靠前 ASC
|
||||
yellow_distance = case([
|
||||
(and_(MaterialWarningSetting.is_enabled.is_(True), total_inv > MaterialWarningSetting.red_threshold, total_inv <= MaterialWarningSetting.yellow_threshold),
|
||||
total_inv - MaterialWarningSetting.red_threshold)
|
||||
], else_=999999)
|
||||
], else_=999999).label('sort_yellow')
|
||||
|
||||
# 清除默认排序,应用严谨的四级排序
|
||||
query = query.order_by(
|
||||
desc(warning_level),
|
||||
desc(red_shortage),
|
||||
asc(yellow_distance),
|
||||
desc(MaterialBase.id)
|
||||
# 2. 将虚拟列加入查询 (使其成为真实可引用的字段)
|
||||
query = query.add_columns(warning_level, red_shortage, yellow_distance)
|
||||
|
||||
# 3. 清除任何杂乱排序,使用原生 text 强行指引数据库按虚拟列名排序
|
||||
query = query.order_by(None).order_by(
|
||||
text("sort_level DESC"),
|
||||
text("sort_red DESC"),
|
||||
text("sort_yellow ASC"),
|
||||
MaterialBase.id.desc()
|
||||
)
|
||||
elif order_by_column:
|
||||
# 字段映射
|
||||
|
||||
Reference in New Issue
Block a user