Compare commits

...
Author SHA1 Message Date
zlwuandCursor f9aa16ef31 feat(oa): 评论@人员优先展示同部门用户
OA 评论选人列表改为请求 users/options 时按当前登录用户部门优先排序,Web 与移动 OA 共用后端稳定排序,便于先选到同部门同事。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 14:24:21 +08:00
cykj 7751cc0f4a Merge pull request 'fix(qc): 样本接收废弃同步该样本状态为已作废 (#129)' (#130)
fix(qc): 样本接收废弃同步该样本状态为已作废 (#129)
2026-11-19 05:19:04 +00:00
zlwuandCursor 0346bc0b1d fix(qc): 样本接收废弃同步该样本状态为已作废
单条接收结论为废弃时仅将该样本置 yzf;改回接收且协议仍有效时清空作废状态;全部废弃仍自动作废协议。补充历史回刷 SQL(#129)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 13:14:10 +08:00
cykj 76ddb81818 Merge pull request 'fix(protocol): 协议作废/属地废弃同步样本状态为已作废 (#127)' (#128)
fix(protocol): 协议作废/属地废弃同步样本状态为已作废 (#127)
2026-11-19 04:33:48 +00:00
zlwuandCursor 3f16a8ab3e fix(protocol): 协议作废/属地废弃同步样本状态为已作废
协议变为 yzf 或 sdfq 时,除样本接收废弃联动外,将下属有效样本 sample_status 置为 yzf 并写入 void_date;补充历史回刷 SQL 与单测(#127)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 12:31:57 +08:00
cykj 14e733faf0 Merge pull request 'feat(oa): 收款账户组件支持图标编辑与删除 (#110)' (#126) from codex/issue-110-receive-account-edit-07c5b0874c18 into V2.0
feat(oa): 收款账户组件支持图标编辑与删除 (#110)

Merge pull request #126
2026-11-19 04:05:04 +00:00
zlwuandCursor aac72e1fd9 feat(oa): 收款账户组件支持图标编辑与删除 (#110)
在 Web 与移动 OA 表单收款账户选择器中,对可见账户增加行尾编辑/删除图标;
复用现有新增表单做编辑,删除二次确认后软删并从已选移除。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 12:04:08 +08:00
cykj f0a6abe538 fix(oa): 同意/拒绝/打回前自动发送评论草稿 (#125)
fix(oa): 同意/拒绝/打回前自动发送评论草稿 (#125)

关联 #118。
2026-11-19 03:56:42 +00:00
zlwuandCursor a69dcc5bca fix(oa): 同意/拒绝/打回前自动发送评论草稿
审批动作前冲刷评论区未发送内容,减少先点发送再审批的一步操作。
关联 #118。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 11:55:53 +08:00
cykj 0929164bf5 fix(qc): 去掉入库质检对象两列跨度导致的空白间距 (#124)
Refs #122
2026-11-19 03:27:55 +00:00
22 changed files with 1336 additions and 198 deletions

No files matched your search

+15 -2
View File
@@ -29,6 +29,7 @@ from app.crud import user as user_svc
from app.crud.collection_protocol import _lookup_attachment_by_url
from app.models.models import BizAttachment, SysDept, SysRole, SysUser, SysMenu, SysPost
from app.services.permission_administration import validate_tenant_references
from app.services.user_select_options import prioritize_caller_dept_options
from app.services.web_auth_roles import (
_map_role_name_to_web,
list_user_ids_with_effective_role_name,
@@ -77,12 +78,15 @@ async def list_roles_for_select(
@router.get("/users/options")
async def list_users_for_select(
roleName: Optional[str] = Query(None, alias="roleName"),
prioritizeCallerDept: bool = Query(False, alias="prioritizeCallerDept"),
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
"""返回用户下拉选项(label=昵称,value=用户ID),供流程设计器审批人选择使用。
"""返回用户下拉选项(label=昵称,value=用户ID,deptId=部门ID)。
供流程设计器审批人选择、OA 评论 @ 人员等使用。
可选 roleName:按有效角色(直接绑定 ∪ 职位继承)精确过滤。
可选 prioritizeCallerDept:当前登录用户同部门人员排在前面(组内仍按创建时间倒序)。
"""
tenant_no = _user.get("tenant_no", "")
q = db.query(SysUser).filter(SysUser.del_flag == 0, SysUser.status == "1")
@@ -97,7 +101,16 @@ async def list_users_for_select(
return success_response([])
q = q.filter(SysUser.id.in_(matched_ids))
rows = q.order_by(SysUser.create_time.desc()).distinct().all()
out = [{"label": (r.nick_name or r.user_no or ""), "value": r.id} for r in rows]
out = [
{
"label": (r.nick_name or r.user_no or ""),
"value": r.id,
"deptId": (r.dept_id or ""),
}
for r in rows
]
if prioritizeCallerDept:
out = prioritize_caller_dept_options(out, _user.get("region_id") or "")
return success_response(out)
+1 -1
View File
@@ -2677,7 +2677,7 @@ def update_collection_protocol(
next_status = protocol_status.strip()
assert_protocol_status_transition(obj.protocol_status or "", next_status, kind="protocol")
obj.protocol_status = next_status
if next_status == "yzf" and from_status != "yzf":
if next_status in ("yzf", "sdfq") and from_status not in ("yzf", "sdfq"):
voided_now = True
if next_status == "yzf" and void_time is not None:
if void_type is None or not str(void_type).strip():
+2 -1
View File
@@ -1702,7 +1702,8 @@ def change_status(
)
db.add(obj)
if ns == "yzf" and (current or "").strip() != "yzf":
from_status = (current or "").strip()
if ns in ("yzf", "sdfq") and from_status not in ("yzf", "sdfq"):
from app.services.protocol_reception_discard_sync import after_protocol_voided
after_protocol_voided(
+8 -10
View File
@@ -1045,12 +1045,11 @@ def create_sample_reception(
user_id=user_id,
create_dept_id=create_dept_id or "",
)
if conclusion == "bj":
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
after_sample_reception_saved(
db, reception=obj, tenant_no=tenant_no, user_id=user_id
)
after_sample_reception_saved(
db, reception=obj, tenant_no=tenant_no, user_id=user_id
)
db.commit()
db.refresh(obj)
return obj
@@ -1169,12 +1168,11 @@ def update_sample_reception(
)
check_result_svc.sync_legacy_columns_from_results(db, rec, saved_rows)
db.add(rec)
if conclusion == "bj":
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
from app.services.protocol_reception_discard_sync import after_sample_reception_saved
after_sample_reception_saved(
db, reception=rec, tenant_no=tenant_no, user_id=user_id
)
after_sample_reception_saved(
db, reception=rec, tenant_no=tenant_no, user_id=user_id
)
db.commit()
db.refresh(rec)
return rec
@@ -1,16 +1,21 @@
"""市场协议作废 ↔ 质检样本接收废弃双向联动。
"""市场协议无效态 ↔ 样本接收废弃 / 样本状态作废联动。
规则(细胞存储 / 科研捐赠):
1. 协议变为已作废(yzf)时,协议下全部样本接收结论自动为废弃(bj)。
2. 协议下全部有效样本均已废弃/拒收(bj)时,协议自动已作废,作废类型为「实验室废弃」。
1. 单条样本接收结论为废弃(bj)时:仅该样本 `sample_status` 置为已作废(yzf)并写 `void_date`;
协议状态保持不变。接收结论改回接收(js)且协议仍有效时:若该样本为 yzf,则清空状态与 void_date。
2. 协议变为已作废(yzf)或属地废弃(sdfq)时:
- 协议下全部样本接收结论自动为废弃(bj);
- 协议下全部有效样本 `sample_status` 置为已作废(yzf),并写入 `void_date`。
3. 协议下全部有效样本均已废弃/拒收(bj)时,协议自动已作废,作废类型为「实验室废弃」。
"""
from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from typing import List, Optional, Union
from sqlalchemy.orm import Session
from app.core.protocol_status_display import INACTIVE_PROTOCOL_STATUSES
from app.core.utils import generate_uuid
from app.models.models import (
BizCollectionProtocol,
@@ -23,11 +28,24 @@ from app.models.research_donation import BizResearchDonation, BizResearchDonatio
LAB_VOID_TYPE_CODE = "sysfq"
LAB_VOID_TYPE_LABEL = "实验室废弃"
VOID_TYPE_DICT = "xyzflx"
SAMPLE_VOID_STATUS = "yzf"
_AUTO_DISCARD_REMARK = "协议作废自动废弃"
_AUTO_VOID_DESC = "全部样本接收废弃/拒收,系统自动作废"
def _void_date_yyyymmdd(
*,
void_time: Optional[datetime] = None,
void_date: Optional[str] = None,
) -> str:
raw = (void_date or "").strip()
if len(raw) == 8 and raw.isdigit():
return raw
ts = void_time or datetime.now()
return ts.strftime("%Y%m%d")
def ensure_lab_void_type(db: Session, *, tenant_no: str) -> str:
"""确保租户字典 xyzflx 存在「实验室废弃」,返回 dict_value。"""
tenant = (tenant_no or "").strip()
@@ -204,7 +222,7 @@ def discard_receptions_for_voided_protocol(
tenant_no: str,
user_id: Optional[str] = None,
) -> int:
"""协议已作废后,将其下样本接收全部置为废弃。返回处理样本数。"""
"""协议无效后,将其下样本接收全部置为废弃。返回处理样本数。"""
src = (source or "").strip()
pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip()
@@ -242,6 +260,75 @@ def discard_receptions_for_voided_protocol(
return len(samples)
def void_samples_for_inactive_protocol(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
user_id: Optional[str] = None,
void_time: Optional[datetime] = None,
void_date: Optional[str] = None,
) -> int:
"""协议无效后,将其下有效样本状态一律置为已作废并写入 void_date。返回处理样本数。"""
src = (source or "").strip()
pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip()
if src not in ("cell_storage", "research_donation") or not pid or not tenant:
return 0
date_s = _void_date_yyyymmdd(void_time=void_time, void_date=void_date)
now = datetime.now()
if src == "cell_storage":
samples: List[Union[BizProtocolSample, BizResearchDonationSample]] = list(
_list_cell_samples(db, protocol_id=pid, tenant_no=tenant)
)
else:
samples = list(_list_donation_samples(db, donation_id=pid, tenant_no=tenant))
for sample in samples:
sample.sample_status = SAMPLE_VOID_STATUS
sample.void_date = date_s
sample.update_by = user_id
sample.update_time = now
db.add(sample)
db.flush()
return len(samples)
def _resolve_protocol_void_time(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
) -> Optional[datetime]:
src = (source or "").strip()
pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip()
if src == "cell_storage":
obj = (
db.query(BizCollectionProtocol)
.filter(
BizCollectionProtocol.id == pid,
BizCollectionProtocol.tenant_no == tenant,
BizCollectionProtocol.del_flag == 0,
)
.first()
)
return obj.void_time if obj else None
obj = (
db.query(BizResearchDonation)
.filter(
BizResearchDonation.id == pid,
BizResearchDonation.tenant_no == tenant,
BizResearchDonation.del_flag == 0,
)
.first()
)
return obj.void_time if obj else None
def _all_samples_discarded(
db: Session,
*,
@@ -299,7 +386,7 @@ def maybe_void_protocol_when_all_samples_discarded(
if not obj:
return False
status = (obj.protocol_status or "").strip()
if status in ("yzf", "sdfq"):
if status in INACTIVE_PROTOCOL_STATUSES:
return False
from app.core.protocol_status_display import assert_protocol_status_transition
from app.crud.collection_protocol import update_collection_protocol
@@ -319,7 +406,8 @@ def maybe_void_protocol_when_all_samples_discarded(
void_desc=_AUTO_VOID_DESC,
void_type=void_type,
commit=False,
sync_reception_discard=False,
# 接收已全部废弃;仍需同步样本状态为已作废
sync_reception_discard=True,
)
return True
@@ -335,7 +423,7 @@ def maybe_void_protocol_when_all_samples_discarded(
if not obj:
return False
status = (obj.donation_status or "").strip()
if status in ("yzf", "sdfq"):
if status in INACTIVE_PROTOCOL_STATUSES:
return False
# 捐赠 change_status 默认 commit;此处内联等价逻辑避免提前提交。
@@ -374,6 +462,168 @@ def maybe_void_protocol_when_all_samples_discarded(
)
db.add(obj)
db.flush()
# 接收已全部废弃;仍需同步样本状态为已作废
after_protocol_voided(
db,
source="research_donation",
protocol_id=pid,
tenant_no=tenant,
user_id=user_id,
)
return True
def _find_sample_for_reception(
db: Session,
*,
reception: BizSampleReception,
tenant_no: str,
) -> tuple[str, Optional[Union[BizProtocolSample, BizResearchDonationSample]]]:
source = (reception.reception_source or "cell_storage").strip() or "cell_storage"
tenant = (tenant_no or "").strip()
code = (reception.sample_code or "").strip()
if source == "cell_storage":
sid = (reception.protocol_sample_id or "").strip()
if sid:
obj = (
db.query(BizProtocolSample)
.filter(
BizProtocolSample.id == sid,
BizProtocolSample.tenant_no == tenant,
BizProtocolSample.del_flag == 0,
)
.first()
)
if obj:
return source, obj
pid = (reception.collection_protocol_id or "").strip()
if code and pid:
return source, (
db.query(BizProtocolSample)
.filter(
BizProtocolSample.collection_protocol_id == pid,
BizProtocolSample.sample_code == code,
BizProtocolSample.tenant_no == tenant,
BizProtocolSample.del_flag == 0,
)
.first()
)
return source, None
sid = (reception.donation_sample_id or "").strip()
if sid:
obj = (
db.query(BizResearchDonationSample)
.filter(
BizResearchDonationSample.id == sid,
BizResearchDonationSample.tenant_no == tenant,
BizResearchDonationSample.del_flag == 0,
)
.first()
)
if obj:
return source, obj
pid = (reception.research_donation_id or "").strip()
if code and pid:
return source, (
db.query(BizResearchDonationSample)
.filter(
BizResearchDonationSample.research_donation_id == pid,
BizResearchDonationSample.sample_code == code,
BizResearchDonationSample.tenant_no == tenant,
BizResearchDonationSample.del_flag == 0,
)
.first()
)
return source, None
def _protocol_is_inactive(
db: Session,
*,
source: str,
protocol_id: str,
tenant_no: str,
) -> bool:
src = (source or "").strip()
pid = (protocol_id or "").strip()
tenant = (tenant_no or "").strip()
if not pid or not tenant:
return False
if src == "cell_storage":
obj = (
db.query(BizCollectionProtocol)
.filter(
BizCollectionProtocol.id == pid,
BizCollectionProtocol.tenant_no == tenant,
BizCollectionProtocol.del_flag == 0,
)
.first()
)
status = (obj.protocol_status or "").strip() if obj else ""
else:
obj = (
db.query(BizResearchDonation)
.filter(
BizResearchDonation.id == pid,
BizResearchDonation.tenant_no == tenant,
BizResearchDonation.del_flag == 0,
)
.first()
)
status = (obj.donation_status or "").strip() if obj else ""
return status in INACTIVE_PROTOCOL_STATUSES
def void_sample_for_discarded_reception(
db: Session,
*,
reception: BizSampleReception,
tenant_no: str,
user_id: Optional[str] = None,
) -> bool:
"""单条接收废弃:仅将该样本置为已作废。"""
_source, sample = _find_sample_for_reception(db, reception=reception, tenant_no=tenant_no)
if not sample:
return False
now = datetime.now()
sample.sample_status = SAMPLE_VOID_STATUS
sample.void_date = _void_date_yyyymmdd(void_time=reception.reception_time or now)
sample.update_by = user_id
sample.update_time = now
db.add(sample)
db.flush()
return True
def clear_sample_void_for_accepted_reception(
db: Session,
*,
reception: BizSampleReception,
tenant_no: str,
user_id: Optional[str] = None,
) -> bool:
"""接收改回接收:协议仍有效且样本为 yzf 时,清空样本作废状态。"""
source, sample = _find_sample_for_reception(db, reception=reception, tenant_no=tenant_no)
if not sample:
return False
if (sample.sample_status or "").strip() != SAMPLE_VOID_STATUS:
return False
if source == "cell_storage":
protocol_id = (reception.collection_protocol_id or "").strip()
else:
protocol_id = (reception.research_donation_id or "").strip()
if _protocol_is_inactive(
db, source=source, protocol_id=protocol_id, tenant_no=tenant_no
):
return False
now = datetime.now()
sample.sample_status = None
sample.void_date = None
sample.update_by = user_id
sample.update_time = now
db.add(sample)
db.flush()
return True
@@ -384,23 +634,32 @@ def after_sample_reception_saved(
tenant_no: str,
user_id: Optional[str] = None,
) -> None:
"""样本接收保存后:若结论为废弃,尝试自动作废所属协议。"""
if (reception.accept_conclusion or "").strip() != "bj":
return
"""样本接收保存后:同步该样本状态;若全部废弃则尝试自动作废协议。"""
conclusion = (reception.accept_conclusion or "").strip()
source = (reception.reception_source or "cell_storage").strip() or "cell_storage"
if source == "cell_storage":
protocol_id = (reception.collection_protocol_id or "").strip()
else:
protocol_id = (reception.research_donation_id or "").strip()
if not protocol_id:
if conclusion == "bj":
void_sample_for_discarded_reception(
db, reception=reception, tenant_no=tenant_no, user_id=user_id
)
if protocol_id:
maybe_void_protocol_when_all_samples_discarded(
db,
source=source,
protocol_id=protocol_id,
tenant_no=tenant_no,
user_id=user_id,
)
return
maybe_void_protocol_when_all_samples_discarded(
db,
source=source,
protocol_id=protocol_id,
tenant_no=tenant_no,
user_id=user_id,
)
if conclusion == "js":
clear_sample_void_for_accepted_reception(
db, reception=reception, tenant_no=tenant_no, user_id=user_id
)
def after_protocol_voided(
@@ -411,7 +670,7 @@ def after_protocol_voided(
tenant_no: str,
user_id: Optional[str] = None,
) -> None:
"""协议作废后:同步废弃其下全部样本接收。"""
"""协议作废/属地废弃后:同步废弃样本接收,并将样本状态置为已作废。"""
discard_receptions_for_voided_protocol(
db,
source=source,
@@ -419,3 +678,13 @@ def after_protocol_voided(
tenant_no=tenant_no,
user_id=user_id,
)
void_samples_for_inactive_protocol(
db,
source=source,
protocol_id=protocol_id,
tenant_no=tenant_no,
user_id=user_id,
void_time=_resolve_protocol_void_time(
db, source=source, protocol_id=protocol_id, tenant_no=tenant_no
),
)
@@ -0,0 +1,19 @@
"""用户下拉选项:同部门优先排序等轻量辅助。"""
from __future__ import annotations
from typing import Any, Dict, List, Sequence
def prioritize_caller_dept_options(
options: Sequence[Dict[str, Any]],
caller_dept_id: str,
) -> List[Dict[str, Any]]:
"""稳定排序:当前登录用户同部门在前,其余保持原相对顺序。"""
items = list(options)
dept = (caller_dept_id or "").strip()
if not dept or not items:
return items
return sorted(
items,
key=lambda item: 0 if str(item.get("deptId") or "").strip() == dept else 1,
)
@@ -23,6 +23,7 @@ from app.models.research_donation import (
)
from app.services.protocol_reception_discard_sync import (
LAB_VOID_TYPE_CODE,
SAMPLE_VOID_STATUS,
after_protocol_voided,
after_sample_reception_saved,
ensure_lab_void_type,
@@ -77,6 +78,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="p1",
protocol_no="CP-1",
protocol_status="sxz",
void_time=now,
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
@@ -89,6 +91,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="s1",
collection_protocol_id="p1",
sample_code="ZK001",
sample_status="yrk",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
@@ -101,6 +104,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="s2",
collection_protocol_id="p1",
sample_code="ZK002",
sample_status="jcz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
@@ -152,6 +156,16 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
self.assertEqual(by_code["ZK001"], "bj")
self.assertEqual(by_code["ZK002"], "bj")
samples = (
db.query(BizProtocolSample)
.filter(BizProtocolSample.collection_protocol_id == "p1")
.all()
)
self.assertEqual(len(samples), 2)
for s in samples:
self.assertEqual(s.sample_status, SAMPLE_VOID_STATUS)
self.assertEqual(s.void_date, "20261105")
def test_all_samples_discarded_auto_voids_protocol_with_lab_type(self):
db = _session()
now = _now()
@@ -172,6 +186,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="s3",
collection_protocol_id="p2",
sample_code="ZK003",
sample_status="ycj",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
@@ -212,6 +227,9 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
self.assertEqual(proto.protocol_status, "yzf")
self.assertEqual(proto.void_type, LAB_VOID_TYPE_CODE)
self.assertIn("全部样本接收", proto.void_desc or "")
sample = db.query(BizProtocolSample).filter(BizProtocolSample.id == "s3").one()
self.assertEqual(sample.sample_status, SAMPLE_VOID_STATUS)
self.assertTrue((sample.void_date or "").strip())
def test_partial_discard_does_not_void_protocol(self):
db = _session()
@@ -282,6 +300,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="d1",
donation_no="RD-1",
donation_status="sxz",
void_time=now,
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
@@ -294,6 +313,7 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
id="ds1",
research_donation_id="d1",
sample_code="RD001",
sample_status="yrk",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
@@ -322,6 +342,199 @@ class TestProtocolReceptionDiscardSync(unittest.TestCase):
)
self.assertEqual(rec.accept_conclusion, "bj")
self.assertEqual(rec.research_donation_id, "d1")
sample = (
db.query(BizResearchDonationSample)
.filter(BizResearchDonationSample.id == "ds1")
.one()
)
self.assertEqual(sample.sample_status, SAMPLE_VOID_STATUS)
self.assertEqual(sample.void_date, "20261105")
def test_sdfq_also_voids_sample_status(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p-sdfq",
protocol_no="CP-SDFQ",
protocol_status="sdfq",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProtocolSample(
id="s-sdfq",
collection_protocol_id="p-sdfq",
sample_code="ZKSDFQ",
sample_status="ycj",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.commit()
after_protocol_voided(
db,
source="cell_storage",
protocol_id="p-sdfq",
tenant_no="tenant-a",
user_id="u1",
)
db.commit()
sample = db.query(BizProtocolSample).filter(BizProtocolSample.id == "s-sdfq").one()
self.assertEqual(sample.sample_status, SAMPLE_VOID_STATUS)
self.assertTrue((sample.void_date or "").strip())
rec = (
db.query(BizSampleReception)
.filter(BizSampleReception.sample_code == "ZKSDFQ")
.one()
)
self.assertEqual(rec.accept_conclusion, "bj")
def test_single_reception_discard_voids_only_that_sample(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p-multi",
protocol_no="CP-MULTI",
protocol_status="sxz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
for sid, code, status in (
("sa", "ZKA", "ycj"),
("sb", "ZKB", "ycj"),
("sc", "ZKC", "ycj"),
):
db.add(
BizProtocolSample(
id=sid,
collection_protocol_id="p-multi",
sample_code=code,
sample_status=status,
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
rec_a = BizSampleReception(
id="ra",
protocol_sample_id="sa",
collection_protocol_id="p-multi",
reception_time=now,
accept_conclusion="bj",
reception_source="cell_storage",
sample_code="ZKA",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
check_packaging=0,
check_sealing=0,
check_no_damage=0,
check_no_leakage=0,
check_color=0,
check_tying_rope=0,
check_no_stratification=0,
)
db.add(rec_a)
db.commit()
after_sample_reception_saved(
db, reception=rec_a, tenant_no="tenant-a", user_id="u1"
)
db.commit()
proto = db.query(BizCollectionProtocol).filter(BizCollectionProtocol.id == "p-multi").one()
self.assertEqual(proto.protocol_status, "sxz")
by_id = {
s.id: s
for s in db.query(BizProtocolSample)
.filter(BizProtocolSample.collection_protocol_id == "p-multi")
.all()
}
self.assertEqual(by_id["sa"].sample_status, SAMPLE_VOID_STATUS)
self.assertEqual(by_id["sa"].void_date, "20261105")
self.assertEqual(by_id["sb"].sample_status, "ycj")
self.assertEqual(by_id["sc"].sample_status, "ycj")
def test_reception_accept_clears_sample_void_when_protocol_active(self):
db = _session()
now = _now()
db.add(
BizCollectionProtocol(
id="p-clear",
protocol_no="CP-CLEAR",
protocol_status="sxz",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
db.add(
BizProtocolSample(
id="s-clear",
collection_protocol_id="p-clear",
sample_code="ZKCLR",
sample_status=SAMPLE_VOID_STATUS,
void_date="20261101",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
)
)
rec = BizSampleReception(
id="r-clear",
protocol_sample_id="s-clear",
collection_protocol_id="p-clear",
reception_time=now,
accept_conclusion="js",
reception_source="cell_storage",
sample_code="ZKCLR",
tenant_no="tenant-a",
create_dept_id="",
create_time=now,
update_time=now,
del_flag=0,
check_packaging=0,
check_sealing=0,
check_no_damage=0,
check_no_leakage=0,
check_color=0,
check_tying_rope=0,
check_no_stratification=0,
)
db.add(rec)
db.commit()
after_sample_reception_saved(
db, reception=rec, tenant_no="tenant-a", user_id="u1"
)
db.commit()
sample = db.query(BizProtocolSample).filter(BizProtocolSample.id == "s-clear").one()
self.assertFalse((sample.sample_status or "").strip())
self.assertFalse((sample.void_date or "").strip())
if __name__ == "__main__":
+27
View File
@@ -0,0 +1,27 @@
"""用户下拉选项:同部门优先排序。"""
from app.services.user_select_options import prioritize_caller_dept_options
def test_prioritize_caller_dept_keeps_relative_order():
options = [
{"label": "外1", "value": "a", "deptId": "d2"},
{"label": "同1", "value": "b", "deptId": "d1"},
{"label": "外2", "value": "c", "deptId": "d3"},
{"label": "同2", "value": "d", "deptId": "d1"},
{"label": "无部门", "value": "e", "deptId": ""},
]
out = prioritize_caller_dept_options(options, "d1")
assert [x["value"] for x in out] == ["b", "d", "a", "c", "e"]
def test_prioritize_caller_dept_noop_without_caller_dept():
options = [
{"label": "a", "value": "a", "deptId": "d1"},
{"label": "b", "value": "b", "deptId": "d2"},
]
assert prioritize_caller_dept_options(options, "") == options
assert prioritize_caller_dept_options(options, " ") == options
def test_prioritize_caller_dept_empty_list():
assert prioritize_caller_dept_options([], "d1") == []
@@ -0,0 +1,54 @@
-- Issue #127:已作废 / 属地废弃协议下样本状态回刷为已作废
-- 细胞存储 + 科研捐赠;可重复执行。
-- 规则:协议 status 为 yzf/sdfq 且样本未删除时,sample_status 置 yzf,
-- void_date 为空时按协议 void_time / update_time 补齐 YYYYMMDD。
-- 细胞存储协议样本
UPDATE biz_protocol_sample s
INNER JOIN biz_collection_protocol p
ON p.id = s.collection_protocol_id
AND p.tenant_no = s.tenant_no
AND p.del_flag = 0
SET
s.sample_status = 'yzf',
s.void_date = CASE
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
WHEN p.void_time IS NOT NULL THEN DATE_FORMAT(p.void_time, '%Y%m%d')
WHEN p.update_time IS NOT NULL THEN DATE_FORMAT(p.update_time, '%Y%m%d')
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
END,
s.update_time = NOW()
WHERE s.del_flag = 0
AND p.protocol_status IN ('yzf', 'sdfq')
AND (
s.sample_status IS NULL
OR TRIM(s.sample_status) = ''
OR s.sample_status <> 'yzf'
OR s.void_date IS NULL
OR TRIM(s.void_date) = ''
);
-- 科研捐赠样本
UPDATE biz_research_donation_sample s
INNER JOIN biz_research_donation d
ON d.id = s.research_donation_id
AND d.tenant_no = s.tenant_no
AND d.del_flag = 0
SET
s.sample_status = 'yzf',
s.void_date = CASE
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
WHEN d.void_time IS NOT NULL THEN DATE_FORMAT(d.void_time, '%Y%m%d')
WHEN d.update_time IS NOT NULL THEN DATE_FORMAT(d.update_time, '%Y%m%d')
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
END,
s.update_time = NOW()
WHERE s.del_flag = 0
AND d.donation_status IN ('yzf', 'sdfq')
AND (
s.sample_status IS NULL
OR TRIM(s.sample_status) = ''
OR s.sample_status <> 'yzf'
OR s.void_date IS NULL
OR TRIM(s.void_date) = ''
);
@@ -0,0 +1,67 @@
-- Issue #129:样本接收结论已为废弃(bj)、但样本状态尚未作废的历史回刷
-- 细胞存储 / 科研捐赠;可重复执行。
-- 仅处理协议仍有效(非 yzf/sdfq)的样本行;已作废协议样本由 #127 回刷脚本覆盖。
-- 细胞存储
UPDATE biz_protocol_sample s
INNER JOIN biz_sample_reception r
ON r.tenant_no = s.tenant_no
AND r.del_flag = 0
AND r.reception_source = 'cell_storage'
AND r.accept_conclusion = 'bj'
AND r.sample_code = s.sample_code
AND r.collection_protocol_id = s.collection_protocol_id
INNER JOIN biz_collection_protocol p
ON p.id = s.collection_protocol_id
AND p.tenant_no = s.tenant_no
AND p.del_flag = 0
SET
s.sample_status = 'yzf',
s.void_date = CASE
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
WHEN r.reception_time IS NOT NULL THEN DATE_FORMAT(r.reception_time, '%Y%m%d')
WHEN s.update_time IS NOT NULL THEN DATE_FORMAT(s.update_time, '%Y%m%d')
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
END,
s.update_time = NOW()
WHERE s.del_flag = 0
AND p.protocol_status NOT IN ('yzf', 'sdfq')
AND (
s.sample_status IS NULL
OR TRIM(s.sample_status) = ''
OR s.sample_status <> 'yzf'
OR s.void_date IS NULL
OR TRIM(s.void_date) = ''
);
-- 科研捐赠
UPDATE biz_research_donation_sample s
INNER JOIN biz_sample_reception r
ON r.tenant_no = s.tenant_no
AND r.del_flag = 0
AND r.reception_source = 'research_donation'
AND r.accept_conclusion = 'bj'
AND r.sample_code = s.sample_code
AND r.research_donation_id = s.research_donation_id
INNER JOIN biz_research_donation d
ON d.id = s.research_donation_id
AND d.tenant_no = s.tenant_no
AND d.del_flag = 0
SET
s.sample_status = 'yzf',
s.void_date = CASE
WHEN s.void_date IS NOT NULL AND TRIM(s.void_date) <> '' THEN s.void_date
WHEN r.reception_time IS NOT NULL THEN DATE_FORMAT(r.reception_time, '%Y%m%d')
WHEN s.update_time IS NOT NULL THEN DATE_FORMAT(s.update_time, '%Y%m%d')
ELSE DATE_FORMAT(NOW(), '%Y%m%d')
END,
s.update_time = NOW()
WHERE s.del_flag = 0
AND d.donation_status NOT IN ('yzf', 'sdfq')
AND (
s.sample_status IS NULL
OR TRIM(s.sample_status) = ''
OR s.sample_status <> 'yzf'
OR s.void_date IS NULL
OR TRIM(s.void_date) = ''
);
+11
View File
@@ -25,6 +25,17 @@ export function fetchCreateReceiveAccount(data) {
return post('/web/admin/oa-approval/receive-accounts', data)
}
export function fetchUpdateReceiveAccount(id, data) {
return put(`/web/admin/oa-approval/receive-accounts/${id}`, data)
}
export function fetchDeleteReceiveAccount(id) {
return request({
url: `/web/admin/oa-approval/receive-accounts/${id}`,
method: 'DELETE'
})
}
export function fetchRelatedCandidates(params) {
return get('/web/admin/oa-approval/related-candidates', params)
}
@@ -150,6 +150,7 @@ import {
uploadAttachment
} from '../../api/oa.js'
import OaCommentFileCards from './OaCommentFileCards.vue'
import { hasOaCommentDraft } from '../oa-comment-draft.js'
import { attachmentFullUrl } from '../../utils/attachment.js'
import { isHarmonyWechat } from '../../utils/harmony-file-picker.js'
import HarmonyFileSource from '../../components/HarmonyFileSource.vue'
@@ -215,7 +216,8 @@ async function ensureUserCache() {
if (userCachePromise) return userCachePromise
userCachePromise = (async () => {
try {
const res = await fetchUserOptions()
// 同部门优先:由后端按当前登录用户部门排序
const res = await fetchUserOptions({ prioritizeCallerDept: true })
const list = Array.isArray(res) ? res : res?.list || []
const next = []
const seen = new Set()
@@ -516,12 +518,25 @@ function confirmMention() {
mentionVisible.value = false
}
async function onSend() {
const content = draft.value.trim()
if (!content && !mentionUsers.value.length && !picked.value.length) {
showToast('请填写评论、@人员或添加附件')
return
function draftPending() {
return hasOaCommentDraft({
content: draft.value,
mentionCount: mentionUsers.value.length,
attachmentCount: picked.value.length
})
}
/**
* 审批动作前冲刷未发送草稿:无草稿直接成功;有草稿则等同点击「发送」。
* @returns {Promise<boolean>} false 表示发送失败或忙碌,调用方应中止审批动作
*/
async function flushDraft(opts = {}) {
if (!draftPending()) return true
if (sending.value || uploading.value) {
showToast(uploading.value ? '附件上传中,请稍后再试' : '评论发送中,请稍后再试')
return false
}
const content = draft.value.trim()
sending.value = true
try {
await fetchCreateOaComment(props.instanceId, {
@@ -533,15 +548,27 @@ async function onSend() {
picked.value = []
mentionUsers.value = []
closeAtSuggest()
showToast('已发送')
if (!opts.quiet) showToast('已发送')
emit('refresh')
return true
} catch (e) {
showToast(e?.message || '发送失败')
return false
} finally {
sending.value = false
}
}
async function onSend() {
if (!draftPending()) {
showToast('请填写评论、@人员或添加附件')
return
}
await flushDraft()
}
defineExpose({ flushDraft, draftPending })
onMounted(() => {
void ensureUserCache()
})
@@ -52,6 +52,24 @@
<div class="oa-sheet-row__title">{{ a.label }}</div>
<div v-if="a.sub" class="oa-sheet-row__meta">{{ a.sub }}</div>
</div>
<div class="oa-sheet-row__actions" @click.stop>
<button
type="button"
class="oa-sheet-row__icon is-edit"
aria-label="编辑"
@click="openEdit(a.id)"
>
<van-icon name="edit" />
</button>
<button
type="button"
class="oa-sheet-row__icon is-delete"
aria-label="删除"
@click="confirmDelete(a.id)"
>
<van-icon name="delete-o" />
</button>
</div>
</div>
</van-checkbox-group>
<van-empty v-if="!loading && !filtered.length" description="暂无本人的收款账户" />
@@ -63,17 +81,17 @@
</div>
</van-popup>
<van-popup v-model:show="createVisible" position="bottom" round>
<van-popup v-model:show="formVisible" position="bottom" round>
<div class="oa-recv__sheet oa-recv__sheet--create">
<div class="oa-recv__hd">
<span @click="createVisible = false">取消</span>
<strong>新增收款账户</strong>
<span @click="formVisible = false">取消</span>
<strong>{{ formTitle }}</strong>
<span
class="oa-recv__ok"
:class="{ 'is-busy': createLoading }"
@click="submitCreate"
:class="{ 'is-busy': formLoading }"
@click="submitForm"
>
{{ createLoading ? '提交中' : '确定' }}
{{ formLoading ? '提交中' : '确定' }}
</span>
</div>
<div class="oa-recv__form">
@@ -87,45 +105,45 @@
<label class="oa-recv-field">
<span class="oa-recv-field__label">户名<b>*</b></span>
<span class="oa-recv-field__box">
<input v-model="createForm.accountName" maxlength="128" placeholder="请输入户名" />
<input v-model="formModel.accountName" maxlength="128" placeholder="请输入户名" />
</span>
</label>
<label class="oa-recv-field">
<span class="oa-recv-field__label">账号<b>*</b></span>
<span class="oa-recv-field__box">
<input v-model="createForm.accountNo" maxlength="128" placeholder="请输入账号" />
<input v-model="formModel.accountNo" maxlength="128" placeholder="请输入账号" />
</span>
</label>
<template v-if="createForm.accountType !== 'alipay'">
<template v-if="formModel.accountType !== 'alipay'">
<label class="oa-recv-field">
<span class="oa-recv-field__label">银行<b>*</b></span>
<span class="oa-recv-field__box">
<input v-model="createForm.bankName" maxlength="128" placeholder="如:中国工商银行" />
<input v-model="formModel.bankName" maxlength="128" placeholder="如:中国工商银行" />
</span>
</label>
<label class="oa-recv-field">
<span class="oa-recv-field__label">银行所在省<b>*</b></span>
<span class="oa-recv-field__box">
<input v-model="createForm.bankProvince" maxlength="64" placeholder="如:安徽省" />
<input v-model="formModel.bankProvince" maxlength="64" placeholder="如:安徽省" />
</span>
</label>
<label class="oa-recv-field">
<span class="oa-recv-field__label">银行所在市<b>*</b></span>
<span class="oa-recv-field__box">
<input v-model="createForm.bankCity" maxlength="64" placeholder="如:合肥市" />
<input v-model="formModel.bankCity" maxlength="64" placeholder="如:合肥市" />
</span>
</label>
<label class="oa-recv-field">
<span class="oa-recv-field__label">银行支行<b>*</b></span>
<span class="oa-recv-field__box">
<input v-model="createForm.bankBranch" maxlength="256" placeholder="请输入开户支行全称" />
<input v-model="formModel.bankBranch" maxlength="256" placeholder="请输入开户支行全称" />
</span>
</label>
</template>
<label class="oa-recv-field">
<span class="oa-recv-field__label">备注</span>
<span class="oa-recv-field__box oa-recv-field__box--area">
<textarea v-model="createForm.remark" maxlength="512" rows="2" placeholder="选填" />
<textarea v-model="formModel.remark" maxlength="512" rows="2" placeholder="选填" />
</span>
</label>
</div>
@@ -135,7 +153,7 @@
<van-popup v-model:show="typePickerVisible" position="bottom" round>
<van-picker
:columns="accountTypeColumns"
:model-value="[createForm.accountType]"
:model-value="[formModel.accountType]"
@confirm="onTypeConfirm"
@cancel="typePickerVisible = false"
/>
@@ -145,8 +163,13 @@
<script setup>
import { computed, onMounted, ref } from 'vue'
import { showToast } from 'vant'
import { fetchCreateReceiveAccount, fetchReceiveAccountOptions } from '../../api/oa.js'
import { showConfirmDialog, showToast } from 'vant'
import {
fetchCreateReceiveAccount,
fetchDeleteReceiveAccount,
fetchReceiveAccountOptions,
fetchUpdateReceiveAccount
} from '../../api/oa.js'
import {
ACCOUNT_TYPE_LABEL,
formatReceiveAccountLine,
@@ -170,17 +193,19 @@ const keyword = ref('')
const pendingIds = ref([])
const snapshotMap = ref(new Map())
const accountOptions = ref([])
const createVisible = ref(false)
const createLoading = ref(false)
const formVisible = ref(false)
const formLoading = ref(false)
const formMode = ref('create')
const editingId = ref('')
const typePickerVisible = ref(false)
const accountTypeColumns = [
{ text: '支付宝', value: 'alipay' },
{ text: '个人银行卡', value: 'personal' },
{ text: '对公银行账户', value: 'corporate' }
]
const createForm = ref(emptyCreateForm())
const formModel = ref(emptyForm())
function emptyCreateForm() {
function emptyForm() {
return {
accountType: 'alipay',
accountName: '',
@@ -193,8 +218,12 @@ function emptyCreateForm() {
}
}
const formTitle = computed(() =>
formMode.value === 'edit' ? '编辑收款账户' : '新增收款账户'
)
const accountTypeLabel = computed(
() => ACCOUNT_TYPE_LABEL[createForm.value.accountType] || ''
() => ACCOUNT_TYPE_LABEL[formModel.value.accountType] || ''
)
const normalized = computed(() => normalizeReceiveAccountModelValue(props.modelValue))
@@ -260,26 +289,78 @@ function optionFromSnap(snap) {
}
}
function upsertLocalSnap(snap) {
if (!snap.id) return
const map = new Map(snapshotMap.value)
map.set(snap.id, snap)
snapshotMap.value = map
const opt = optionFromSnap(snap)
const idx = accountOptions.value.findIndex((x) => x.id === snap.id)
if (idx >= 0) {
const next = [...accountOptions.value]
next[idx] = opt
accountOptions.value = next
} else {
accountOptions.value = [...accountOptions.value, opt]
}
}
function fillFormFromSnap(snap) {
const form = {
accountType: snap.accountType || 'alipay',
accountName: snap.accountName || '',
accountNo: snap.accountNo || '',
bankName: snap.bankName || '',
bankProvince: snap.bankProvince || '',
bankCity: snap.bankCity || '',
bankBranch: snap.bankBranch || '',
remark: snap.remark || ''
}
if (form.accountType === 'alipay') {
form.bankName = ''
form.bankProvince = ''
form.bankCity = ''
form.bankBranch = ''
}
formModel.value = form
}
function openCreate() {
createForm.value = emptyCreateForm()
formMode.value = 'create'
editingId.value = ''
formModel.value = emptyForm()
typePickerVisible.value = false
createVisible.value = true
formVisible.value = true
}
function openEdit(id) {
const tid = String(id || '').trim()
const snap = snapshotMap.value.get(tid)
if (!snap) {
showToast('账户不存在或已删除')
return
}
formMode.value = 'edit'
editingId.value = tid
fillFormFromSnap(snap)
typePickerVisible.value = false
formVisible.value = true
}
function onTypeConfirm({ selectedOptions }) {
const next = selectedOptions?.[0]?.value || 'alipay'
const form = { ...createForm.value, accountType: next }
const form = { ...formModel.value, accountType: next }
if (next === 'alipay') {
form.bankName = ''
form.bankProvince = ''
form.bankCity = ''
form.bankBranch = ''
}
createForm.value = form
formModel.value = form
typePickerVisible.value = false
}
function validateCreate(form) {
function validateForm(form) {
if (!form.accountName.trim()) return '请输入户名'
if (!form.accountNo.trim()) return '请输入账号'
if (form.accountType !== 'alipay') {
@@ -291,14 +372,7 @@ function validateCreate(form) {
return ''
}
async function submitCreate() {
if (createLoading.value) return
const form = createForm.value
const invalid = validateCreate(form)
if (invalid) {
showToast(invalid)
return
}
function buildPayload(form) {
const payload = {
accountType: form.accountType,
accountName: form.accountName.trim(),
@@ -316,36 +390,80 @@ async function submitCreate() {
payload.bankCity = form.bankCity.trim()
payload.bankBranch = form.bankBranch.trim()
}
createLoading.value = true
return payload
}
async function submitForm() {
if (formLoading.value) return
const form = formModel.value
const invalid = validateForm(form)
if (invalid) {
showToast(invalid)
return
}
const payload = buildPayload(form)
formLoading.value = true
try {
const created = await fetchCreateReceiveAccount(payload)
const snap = snapshotFromRow(created)
const row =
formMode.value === 'edit' && editingId.value
? await fetchUpdateReceiveAccount(editingId.value, payload)
: await fetchCreateReceiveAccount(payload)
const snap = snapshotFromRow(row)
if (!snap.id) {
showToast('创建成功但未返回账户 ID')
showToast(formMode.value === 'edit' ? '更新成功但未返回账户 ID' : '创建成功但未返回账户 ID')
return
}
await loadOptions()
if (!snapshotMap.value.has(snap.id)) {
const map = new Map(snapshotMap.value)
map.set(snap.id, snap)
snapshotMap.value = map
if (!accountOptions.value.some((x) => x.id === snap.id)) {
accountOptions.value = [...accountOptions.value, optionFromSnap(snap)]
upsertLocalSnap(snap)
if (formMode.value === 'edit') {
const selected = normalized.value.map((x) => x.id)
if (selected.includes(snap.id)) {
emitItems(selected.map((id) => snapshotMap.value.get(id)).filter(Boolean))
}
showToast('更新成功')
} else {
const selected = new Set(normalized.value.map((x) => x.id))
selected.add(snap.id)
emitItems([...selected].map((id) => snapshotMap.value.get(id)).filter(Boolean))
if (!pendingIds.value.includes(snap.id)) {
pendingIds.value = [...pendingIds.value, snap.id]
}
keyword.value = ''
showToast('创建成功')
}
const selected = new Set(normalized.value.map((x) => x.id))
selected.add(snap.id)
emitItems([...selected].map((id) => snapshotMap.value.get(id)).filter(Boolean))
if (!pendingIds.value.includes(snap.id)) {
pendingIds.value = [...pendingIds.value, snap.id]
}
keyword.value = ''
createVisible.value = false
showToast('创建成功')
formVisible.value = false
} catch (e) {
showToast(e?.message || '新增收款账户失败')
showToast(e?.message || (formMode.value === 'edit' ? '编辑收款账户失败' : '新增收款账户失败'))
} finally {
createLoading.value = false
formLoading.value = false
}
}
async function confirmDelete(id) {
const tid = String(id || '').trim()
const snap = snapshotMap.value.get(tid)
const name = snap?.accountName || tid
try {
await showConfirmDialog({
title: '删除收款账户',
message: `确定删除收款账户「${name}」吗?删除后不可再选;已提交单据中的账户快照仍保留。`
})
} catch {
return
}
try {
await fetchDeleteReceiveAccount(tid)
await loadOptions()
const nextSelected = normalized.value
.map((x) => x.id)
.filter((x) => x !== tid)
.map((x) => snapshotMap.value.get(x))
.filter(Boolean)
emitItems(nextSelected)
pendingIds.value = pendingIds.value.filter((x) => x !== tid)
showToast('删除成功')
} catch (e) {
showToast(e?.message || '删除收款账户失败')
}
}
@@ -411,6 +529,39 @@ onMounted(() => {
line-height: 1.5;
}
.oa-sheet-row__actions {
display: inline-flex;
flex: none;
gap: 6px;
align-items: center;
margin-left: 4px;
}
.oa-sheet-row__icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
margin: 0;
padding: 0;
border: 0;
border-radius: 8px;
background: transparent;
font-size: 18px;
cursor: pointer;
}
.oa-sheet-row__icon.is-edit {
background: #ecfdf5;
color: var(--brand-green-dark, #16a34a);
}
.oa-sheet-row__icon.is-delete {
background: #fef2f2;
color: #dc2626;
}
.oa-recv__add {
display: flex;
gap: 6px;
+7
View File
@@ -0,0 +1,7 @@
/** 评论区是否有未发送草稿(文字 / @ / 附件) */
export function hasOaCommentDraft(input = {}) {
const content = String(input.content || '').trim()
const mentionCount = Number(input.mentionCount || 0)
const attachmentCount = Number(input.attachmentCount || 0)
return !!(content || mentionCount > 0 || attachmentCount > 0)
}
@@ -0,0 +1,14 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { hasOaCommentDraft } from './oa-comment-draft.js'
test('empty draft is false', () => {
assert.equal(hasOaCommentDraft({}), false)
assert.equal(hasOaCommentDraft({ content: ' ', mentionCount: 0, attachmentCount: 0 }), false)
})
test('text / mention / attachment counts as draft', () => {
assert.equal(hasOaCommentDraft({ content: '@test' }), true)
assert.equal(hasOaCommentDraft({ mentionCount: 1 }), true)
assert.equal(hasOaCommentDraft({ attachmentCount: 2 }), true)
})
+11 -1
View File
@@ -29,6 +29,7 @@
@refresh="reloadDetail"
/>
<OaCommentComposer
ref="commentComposerRef"
:instance-id="instanceId"
:instance-status="detail?.status || ''"
@refresh="reloadDetail"
@@ -238,6 +239,7 @@ const currentUserId = ref('')
const currentUserName = ref('')
const autoPrinted = ref(false)
const commentComposerRef = ref(null)
const commentVisible = ref(false)
const commentKind = ref('approve') // approve | reject | return
const commentText = ref('')
@@ -492,8 +494,16 @@ function goCopyRestart() {
})
}
function openComment(kind) {
/** 同意/拒绝/打回前先发送评论区未提交草稿 */
async function flushPendingComment() {
const flush = commentComposerRef.value?.flushDraft
if (!flush) return true
return await flush()
}
async function openComment(kind) {
if (!myPendingTask.value) return
if (!(await flushPendingComment())) return
commentKind.value = kind
commentText.value = defaultComment(kind)
commentVisible.value = true
+6 -3
View File
@@ -22,9 +22,12 @@ export function fetchGetRoleList() {
})
}
/** 流程设计器:用户下拉选项(label=昵称,value=用户ID) */
export function fetchUserOptions(params?: { roleName?: string }) {
return request.get<Array<{ label: string; value: string }>>({
/** 用户下拉选项(label=昵称,value=用户ID;可选 deptId / prioritizeCallerDept) */
export function fetchUserOptions(params?: {
roleName?: string
prioritizeCallerDept?: boolean
}) {
return request.get<Array<{ label: string; value: string; deptId?: string }>>({
url: '/web/admin/users/options',
params
})
@@ -192,6 +192,7 @@
} from '@/api/oaApproval'
import OaCommentFileCards from '@/components/oa-approval/OaCommentFileCards.vue'
import { attachmentFullUrl } from '@/composables/useAttachmentActions'
import { hasOaCommentDraft } from '@/utils/oa-comment-draft'
import { isOaUploadImageFile, isOaUploadVideoFile } from '@/utils/oa-upload-file-type'
defineOptions({ name: 'OaCommentPanel' })
@@ -254,7 +255,8 @@
if (userCachePromise) return userCachePromise
userCachePromise = (async () => {
try {
const res = await fetchUserOptions()
// 同部门优先:由后端按当前登录用户部门排序
const res = await fetchUserOptions({ prioritizeCallerDept: true })
const list = Array.isArray(res) ? res : []
const next: MentionUser[] = []
const seen = new Set<string>()
@@ -546,12 +548,25 @@
}
}
async function onSend() {
const content = draft.value.trim()
if (!content && !mentionUsers.value.length && !picked.value.length) {
ElMessage.warning('请填写评论、@人员或添加附件')
return
function draftPending() {
return hasOaCommentDraft({
content: draft.value,
mentionCount: mentionUsers.value.length,
attachmentCount: picked.value.length
})
}
/**
* 审批动作前冲刷未发送草稿:无草稿直接成功;有草稿则等同点击「发送」。
* @returns false 表示发送失败或忙碌,调用方应中止审批动作
*/
async function flushDraft(opts?: { quiet?: boolean }): Promise<boolean> {
if (!draftPending()) return true
if (sending.value || uploading.value) {
ElMessage.warning(uploading.value ? '附件上传中,请稍后再试' : '评论发送中,请稍后再试')
return false
}
const content = draft.value.trim()
sending.value = true
try {
await fetchCreateOaComment(props.instanceId, {
@@ -565,15 +580,27 @@
picked.value = []
mentionUsers.value = []
closeAtSuggest()
ElMessage.success('已发送')
if (!opts?.quiet) ElMessage.success('已发送')
emit('refresh')
return true
} catch (e: any) {
ElMessage.error(e?.message || '发送失败')
return false
} finally {
sending.value = false
}
}
async function onSend() {
if (!draftPending()) {
ElMessage.warning('请填写评论、@人员或添加附件')
return
}
await flushDraft()
}
defineExpose({ flushDraft, draftPending })
onMounted(() => {
void ensureUserCache()
})
@@ -40,17 +40,39 @@
class="oa-receive-account-select__search"
/>
<div class="oa-receive-account-select__list">
<label
<div
v-for="a in filteredOptions"
:key="a.id"
class="oa-receive-account-select__row"
>
<el-checkbox
:model-value="pendingIds.includes(a.id)"
@change="(v: boolean | string | number) => onNarrowCheck(a.id, !!v)"
/>
<span class="oa-receive-account-select__row-label">{{ a.label }}</span>
</label>
<label class="oa-receive-account-select__row-main">
<el-checkbox
:model-value="pendingIds.includes(a.id)"
@change="(v: boolean | string | number) => onNarrowCheck(a.id, !!v)"
/>
<span class="oa-receive-account-select__row-label">{{ a.label }}</span>
</label>
<div class="oa-receive-account-select__row-actions">
<button
type="button"
class="oa-receive-account-select__icon-btn is-edit"
title="编辑"
aria-label="编辑"
@click="openEditDialog(a.id)"
>
<el-icon><Edit /></el-icon>
</button>
<button
type="button"
class="oa-receive-account-select__icon-btn is-delete"
title="删除"
aria-label="删除"
@click="confirmDelete(a.id)"
>
<el-icon><Delete /></el-icon>
</button>
</div>
</div>
<div v-if="!filteredOptions.length" class="oa-receive-account-select__empty">
暂无本人的收款账户
</div>
@@ -92,7 +114,31 @@
:key="a.id"
:label="a.label"
:value="a.id"
/>
>
<div class="oa-receive-account-select__option">
<span class="oa-receive-account-select__option-label">{{ a.label }}</span>
<span class="oa-receive-account-select__option-actions" @mousedown.prevent @click.stop>
<button
type="button"
class="oa-receive-account-select__icon-btn is-edit"
title="编辑"
aria-label="编辑"
@click="openEditDialog(a.id)"
>
<el-icon><Edit /></el-icon>
</button>
<button
type="button"
class="oa-receive-account-select__icon-btn is-delete"
title="删除"
aria-label="删除"
@click="confirmDelete(a.id)"
>
<el-icon><Delete /></el-icon>
</button>
</span>
</div>
</el-option>
<template #empty>
<div class="oa-receive-account-select__empty">
{{ accountOptions.length === 0 ? '暂无本人的收款账户' : '无匹配数据' }}
@@ -120,8 +166,8 @@
</template>
<el-dialog
v-model="createVisible"
title="新增收款账户"
v-model="formVisible"
:title="formTitle"
width="720px"
class="dialog-form-layout"
align-center
@@ -131,9 +177,9 @@
:close-on-click-modal="false"
>
<el-form
ref="createFormRef"
:model="createForm"
:rules="createRules"
ref="formRef"
:model="formModel"
:rules="formRules"
label-position="top"
scroll-to-error
:scroll-into-view-options="{ behavior: 'smooth', block: 'center' }"
@@ -141,9 +187,9 @@
<div class="form-grid-2">
<el-form-item label="账户类型" prop="accountType" class="form-col-span-2">
<el-select
v-model="createForm.accountType"
v-model="formModel.accountType"
placeholder="请选择"
@change="onCreateTypeChange"
@change="onFormTypeChange"
>
<el-option
v-for="(label, value) in ACCOUNT_TYPE_LABEL"
@@ -154,22 +200,22 @@
</el-select>
</el-form-item>
<el-form-item label="户名" prop="accountName">
<el-input v-model="createForm.accountName" placeholder="请输入户名" maxlength="128" />
<el-input v-model="formModel.accountName" placeholder="请输入户名" maxlength="128" />
</el-form-item>
<el-form-item label="账号" prop="accountNo">
<el-input v-model="createForm.accountNo" placeholder="请输入账号" maxlength="128" />
<el-input v-model="formModel.accountNo" placeholder="请输入账号" maxlength="128" />
</el-form-item>
<template v-if="createForm.accountType !== 'alipay'">
<template v-if="formModel.accountType !== 'alipay'">
<el-form-item label="银行" prop="bankName">
<el-input
v-model="createForm.bankName"
v-model="formModel.bankName"
placeholder="如:中国工商银行"
maxlength="128"
/>
</el-form-item>
<el-form-item label="银行所在省" prop="bankProvince">
<el-input
v-model="createForm.bankProvince"
v-model="formModel.bankProvince"
placeholder="如:安徽省"
maxlength="64"
clearable
@@ -177,7 +223,7 @@
</el-form-item>
<el-form-item label="银行所在市" prop="bankCity">
<el-input
v-model="createForm.bankCity"
v-model="formModel.bankCity"
placeholder="如:合肥市"
maxlength="64"
clearable
@@ -185,7 +231,7 @@
</el-form-item>
<el-form-item label="银行支行" prop="bankBranch" class="form-col-span-2">
<el-input
v-model="createForm.bankBranch"
v-model="formModel.bankBranch"
placeholder="请输入开户支行全称"
maxlength="256"
/>
@@ -193,7 +239,7 @@
</template>
<el-form-item label="备注" class="form-col-span-2">
<el-input
v-model="createForm.remark"
v-model="formModel.remark"
type="textarea"
:rows="2"
placeholder="选填"
@@ -203,15 +249,15 @@
</div>
</el-form>
<template #footer>
<el-button class="btn-ghost" @click="createVisible = false">
<el-button class="btn-ghost" @click="formVisible = false">
<el-icon><Close /></el-icon>
取消
</el-button>
<el-button
class="btn-main"
type="primary"
:loading="createLoading"
@click="submitCreate"
:loading="formLoading"
@click="submitForm"
>
<el-icon><Check /></el-icon>
确定
@@ -223,11 +269,13 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { Check, Close, Plus } from '@element-plus/icons-vue'
import { Check, Close, Delete, Edit, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
fetchCreateOaReceiveAccount,
fetchOaReceiveAccountOptions
fetchDeleteOaReceiveAccount,
fetchOaReceiveAccountOptions,
fetchUpdateOaReceiveAccount
} from '@/api/oaApproval'
import {
ACCOUNT_TYPE_LABEL,
@@ -253,6 +301,7 @@
}>()
type AccountOpt = { id: string; label: string }
type FormMode = 'create' | 'edit'
const snapshotMap = ref(new Map<string, ReceiveAccountSnapshot>())
const accountOptions = ref<AccountOpt[]>([])
@@ -263,10 +312,12 @@
const selectRef = ref<{ blur?: () => void } | null>(null)
let mql: MediaQueryList | null = null
const createVisible = ref(false)
const createLoading = ref(false)
const createFormRef = ref()
const createForm = reactive({
const formVisible = ref(false)
const formLoading = ref(false)
const formMode = ref<FormMode>('create')
const editingId = ref('')
const formRef = ref()
const formModel = reactive({
accountType: 'alipay' as ReceiveAccountType,
accountName: '',
accountNo: '',
@@ -277,8 +328,12 @@
remark: ''
})
const formTitle = computed(() =>
formMode.value === 'edit' ? '编辑收款账户' : '新增收款账户'
)
const requireWhenBank = (_rule: any, value: string, callback: (e?: Error) => void) => {
if (createForm.accountType === 'alipay') {
if (formModel.accountType === 'alipay') {
callback()
return
}
@@ -289,7 +344,7 @@
callback()
}
const createRules = computed(() => ({
const formRules = computed(() => ({
accountType: [{ required: true, message: '请选择账户类型', trigger: 'change' }],
accountName: [{ required: true, message: '请输入户名', trigger: 'blur' }],
accountNo: [{ required: true, message: '请输入账号', trigger: 'blur' }],
@@ -358,90 +413,161 @@
drawerVisible.value = false
}
function clearCreateBankFields() {
createForm.bankName = ''
createForm.bankProvince = ''
createForm.bankCity = ''
createForm.bankBranch = ''
function clearBankFields() {
formModel.bankName = ''
formModel.bankProvince = ''
formModel.bankCity = ''
formModel.bankBranch = ''
}
function resetCreateForm() {
createForm.accountType = 'alipay'
createForm.accountName = ''
createForm.accountNo = ''
clearCreateBankFields()
createForm.remark = ''
function resetFormModel() {
formModel.accountType = 'alipay'
formModel.accountName = ''
formModel.accountNo = ''
clearBankFields()
formModel.remark = ''
}
function onCreateTypeChange() {
if (createForm.accountType === 'alipay') clearCreateBankFields()
createFormRef.value?.clearValidate?.()
function fillFormFromSnap(snap: ReceiveAccountSnapshot) {
formModel.accountType = snap.accountType
formModel.accountName = snap.accountName
formModel.accountNo = snap.accountNo
formModel.bankName = snap.bankName
formModel.bankProvince = snap.bankProvince
formModel.bankCity = snap.bankCity
formModel.bankBranch = snap.bankBranch
formModel.remark = snap.remark
if (formModel.accountType === 'alipay') clearBankFields()
}
function onFormTypeChange() {
if (formModel.accountType === 'alipay') clearBankFields()
formRef.value?.clearValidate?.()
}
function buildPayload() {
const payload: Record<string, unknown> = {
accountType: formModel.accountType,
accountName: formModel.accountName.trim(),
accountNo: formModel.accountNo.trim(),
remark: formModel.remark?.trim() || undefined
}
if (formModel.accountType === 'alipay') {
payload.bankName = ''
payload.bankProvince = ''
payload.bankCity = ''
payload.bankBranch = ''
} else {
payload.bankName = formModel.bankName.trim()
payload.bankProvince = formModel.bankProvince.trim()
payload.bankCity = formModel.bankCity.trim()
payload.bankBranch = formModel.bankBranch.trim()
}
return payload
}
function upsertLocalSnap(snap: ReceiveAccountSnapshot) {
if (!snap.id) return
const map = new Map(snapshotMap.value)
map.set(snap.id, snap)
snapshotMap.value = map
const label = optionLabelFromRow(snap)
const idx = accountOptions.value.findIndex((x) => x.id === snap.id)
if (idx >= 0) {
const next = [...accountOptions.value]
next[idx] = { id: snap.id, label }
accountOptions.value = next
} else {
accountOptions.value = [...accountOptions.value, { id: snap.id, label }]
}
}
function openCreateDialog() {
selectRef.value?.blur?.()
resetCreateForm()
createVisible.value = true
nextTick(() => createFormRef.value?.clearValidate?.())
formMode.value = 'create'
editingId.value = ''
resetFormModel()
formVisible.value = true
nextTick(() => formRef.value?.clearValidate?.())
}
async function submitCreate() {
function openEditDialog(id: string) {
const tid = String(id || '').trim()
const snap = snapshotMap.value.get(tid)
if (!snap) {
ElMessage.error('账户不存在或已删除')
return
}
selectRef.value?.blur?.()
formMode.value = 'edit'
editingId.value = tid
fillFormFromSnap(snap)
formVisible.value = true
nextTick(() => formRef.value?.clearValidate?.())
}
async function submitForm() {
try {
await createFormRef.value?.validate?.()
await formRef.value?.validate?.()
} catch {
ElMessageBox.alert('请完善必填项后再提交', '提示', { type: 'warning' })
return
}
createLoading.value = true
formLoading.value = true
try {
const payload: Record<string, unknown> = {
accountType: createForm.accountType,
accountName: createForm.accountName.trim(),
accountNo: createForm.accountNo.trim(),
remark: createForm.remark?.trim() || undefined
}
if (createForm.accountType === 'alipay') {
payload.bankName = ''
payload.bankProvince = ''
payload.bankCity = ''
payload.bankBranch = ''
const payload = buildPayload()
let row: any
if (formMode.value === 'edit' && editingId.value) {
row = await fetchUpdateOaReceiveAccount(editingId.value, payload)
} else {
payload.bankName = createForm.bankName.trim()
payload.bankProvince = createForm.bankProvince.trim()
payload.bankCity = createForm.bankCity.trim()
payload.bankBranch = createForm.bankBranch.trim()
row = await fetchCreateOaReceiveAccount(payload)
}
const created = await fetchCreateOaReceiveAccount(payload)
const snap = snapshotFromRow(created)
const snap = snapshotFromRow(row)
if (!snap.id) {
ElMessage.error('创建成功但未返回账户 ID')
ElMessage.error(formMode.value === 'edit' ? '更新成功但未返回账户 ID' : '创建成功但未返回账户 ID')
return
}
await loadOptions()
// 确保新账户在 map 中(options 可能短暂未刷新)
if (!snapshotMap.value.has(snap.id)) {
const map = new Map(snapshotMap.value)
map.set(snap.id, snap)
snapshotMap.value = map
if (!accountOptions.value.some((x) => x.id === snap.id)) {
accountOptions.value = [
...accountOptions.value,
{ id: snap.id, label: optionLabelFromRow(snap) }
]
upsertLocalSnap(snap)
if (formMode.value === 'edit') {
if (selectModel.value.includes(snap.id)) {
emitFromIds(selectModel.value)
}
} else {
const nextIds = [...selectModel.value]
if (!nextIds.includes(snap.id)) nextIds.push(snap.id)
emitFromIds(nextIds)
if (drawerVisible.value && !pendingIds.value.includes(snap.id)) {
pendingIds.value = [...pendingIds.value, snap.id]
}
}
const nextIds = [...selectModel.value]
if (!nextIds.includes(snap.id)) nextIds.push(snap.id)
emitFromIds(nextIds)
if (drawerVisible.value && !pendingIds.value.includes(snap.id)) {
pendingIds.value = [...pendingIds.value, snap.id]
}
createVisible.value = false
formVisible.value = false
} finally {
createLoading.value = false
formLoading.value = false
}
}
async function confirmDelete(id: string) {
const tid = String(id || '').trim()
const snap = snapshotMap.value.get(tid)
const name = snap?.accountName || tid
try {
await ElMessageBox.confirm(
`确定删除收款账户「${name}」吗?删除后不可再选;已提交单据中的账户快照仍保留。`,
'删除收款账户',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
} catch {
return
}
selectRef.value?.blur?.()
await fetchDeleteOaReceiveAccount(tid)
await loadOptions()
const nextSelected = selectModel.value.filter((x) => x !== tid)
emitFromIds(nextSelected)
pendingIds.value = pendingIds.value.filter((x) => x !== tid)
}
async function loadOptions() {
try {
const res = await fetchOaReceiveAccountOptions()
@@ -512,6 +638,53 @@
min-height: 40px;
}
.oa-receive-account-select__option {
display: flex;
gap: 8px;
align-items: center;
justify-content: space-between;
width: 100%;
min-width: 0;
}
.oa-receive-account-select__option-label {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.oa-receive-account-select__option-actions,
.oa-receive-account-select__row-actions {
display: inline-flex;
flex-shrink: 0;
gap: 4px;
align-items: center;
}
.oa-receive-account-select__icon-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
border: 0;
border-radius: 6px;
cursor: pointer;
}
.oa-receive-account-select__icon-btn.is-edit {
background: var(--mint-primary-bg, #ecfdf5);
color: var(--mint-primary-dark, #059669);
}
.oa-receive-account-select__icon-btn.is-delete {
background: #fef2f2;
color: #dc2626;
}
.oa-receive-account-select__add-footer {
padding: 4px 8px 8px;
border-top: 1px solid var(--mint-border, #d9e8e2);
@@ -597,6 +770,14 @@
align-items: center;
min-height: 44px;
padding: 6px 4px;
}
.oa-receive-account-select__row-main {
display: flex;
flex: 1;
gap: 8px;
align-items: center;
min-width: 0;
cursor: pointer;
}
@@ -630,5 +811,10 @@
.oa-receive-account-select__trigger {
min-height: 44px;
}
.oa-receive-account-select__icon-btn {
width: 36px;
height: 36px;
}
}
</style>
@@ -0,0 +1,16 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { hasOaCommentDraft } from './oa-comment-draft.ts'
describe('hasOaCommentDraft', () => {
it('treats blank content without mentions/files as empty', () => {
assert.equal(hasOaCommentDraft({}), false)
assert.equal(hasOaCommentDraft({ content: ' ', mentionCount: 0, attachmentCount: 0 }), false)
})
it('detects text, mentions and attachments', () => {
assert.equal(hasOaCommentDraft({ content: '@test' }), true)
assert.equal(hasOaCommentDraft({ mentionCount: 1 }), true)
assert.equal(hasOaCommentDraft({ attachmentCount: 2 }), true)
})
})
+12
View File
@@ -0,0 +1,12 @@
/** 评论区是否有未发送草稿(文字 / @ / 附件) */
export function hasOaCommentDraft(input: {
content?: string | null
mentionCount?: number
attachmentCount?: number
}): boolean {
return !!(
String(input.content || '').trim() ||
(input.mentionCount || 0) > 0 ||
(input.attachmentCount || 0) > 0
)
}
@@ -99,6 +99,7 @@
/>
<OaCommentPanel
v-if="detail?.id"
ref="commentPanelRef"
:instance-id="detail.id"
:instance-status="detail.status || ''"
@refresh="load"
@@ -236,6 +237,9 @@
const userStore = useUserStore()
const loading = ref(false)
const acting = ref(false)
const commentPanelRef = ref<{ flushDraft?: (opts?: { quiet?: boolean }) => Promise<boolean> } | null>(
null
)
const detail = ref<any>(null)
const viewFormData = ref<Record<string, any>>({})
const viewRule = ref<any[]>([])
@@ -392,9 +396,17 @@
}
}
/** 同意/拒绝/打回前先发送评论区未提交草稿 */
async function flushPendingComment(): Promise<boolean> {
const flush = commentPanelRef.value?.flushDraft
if (!flush) return true
return await flush()
}
async function act(kind: 'approve' | 'reject') {
const task = myPendingTask.value
if (!task) return
if (!(await flushPendingComment())) return
let comment = ''
try {
const res = await ElMessageBox.prompt(
@@ -436,6 +448,7 @@
async function doReturn() {
const task = myPendingTask.value
if (!task) return
if (!(await flushPendingComment())) return
let comment = ''
try {
const res = await ElMessageBox.prompt('请填写打回意见(必填)', '打回', {