feat(ui): 工作台界面全部替换为element plus

This commit is contained in:
sophie committed 2026-10-29 09:38:38 +08:00
1 parent 26d213c05b
commit d5f988a16c
38 files changed
+4240 -2826

No files matched your search

@@ -5,6 +5,7 @@ backend/app/services/voucher_check/notification.py
依赖:wecom_notify、notify_config_service、ScheduleTask.notify_user_ids_json、engine_persistence。 依赖:wecom_notify、notify_config_service、ScheduleTask.notify_user_ids_json、engine_persistence。
逻辑:缺件按文件类型接收人拆成每人一封,正文只含该人负责且本批缺失的类型; 逻辑:缺件按文件类型接收人拆成每人一封,正文只含该人负责且本批缺失的类型;
卡片标题为「销售开票附件缺件提醒」,不写业务方代号和批次号; 卡片标题为「销售开票附件缺件提醒」,不写业务方代号和批次号;
卡片发出后紧跟本批检核结果 Excel,收件人不用进详情才知道缺哪张票;
排程「启用通知」为总开关;技术失败仍走排程通知人;domain_notification_managed 避免通用排程重复通知。 排程「启用通知」为总开关;技术失败仍走排程通知人;domain_notification_managed 避免通用排程重复通知。
""" """
@@ -59,7 +60,7 @@ def _missing_textcard(period_month: str, items: list[dict[str, Any]]) -> tuple[s
_friendly_period_label(period_month), _friendly_period_label(period_month),
"销售开票附件已检核,你负责的类型还有缺件:", "销售开票附件已检核,你负责的类型还有缺件:",
*[_missing_type_line(item) for item in items], *[_missing_type_line(item) for item in items],
"请尽快补齐。完整清单见详情里的 Excel。", "请尽快补齐。缺件明细见下一条 Excel。",
] ]
) )
return "销售开票附件缺件提醒", body return "销售开票附件缺件提醒", body
@@ -113,6 +114,36 @@ def _persist_skip(
return send_status return send_status
def _send_excel_file(wecom_userid: str, media_id: str) -> bool:
"""
把已上传的检核结果 Excel 发给一个收件人。
核心逻辑:企微文件消息与 textcard 是两条消息,失败只记日志,不回滚已发出的卡片。
Returns:
企业微信 errcode 为 0 时为 True。
"""
from app.services.integrations.wecom.notify import send_wecom_file_message
try:
data = send_wecom_file_message(wecom_userid, media_id)
except Exception as exc:
current_app.logger.warning(
"[voucher-check] excel file failed user=%s err=%s",
wecom_userid,
exc,
)
return False
if data.get("errcode") == 0:
return True
current_app.logger.warning(
"[voucher-check] excel file failed user=%s errcode=%s errmsg=%s",
wecom_userid,
data.get("errcode"),
data.get("errmsg"),
)
return False
def send_batch_missing_summary( def send_batch_missing_summary(
*, *,
task: ScheduleTask, task: ScheduleTask,
@@ -122,11 +153,17 @@ def send_batch_missing_summary(
period_month: str, period_month: str,
stats: dict[str, Any], stats: dict[str, Any],
excel_filename: str | None, excel_filename: str | None,
excel_bytes: bytes | None = None,
enabled: bool, enabled: bool,
) -> str: ) -> str:
""" """
按文件类型接收人发送缺件 textcard。 按文件类型接收人发送缺件 textcard,并附上本批检核结果 Excel。
核心逻辑:每人一封,只列出该人负责且本批缺失的类型;标题写明销售开票附件,不写业务方代号和批次号。无缺件或无人可发则写审计不发空消息。 核心逻辑:每人一封,只列出该人负责且本批缺失的类型;标题写明销售开票附件,不写业务方代号和批次号。
Excel 全批共用一份,上传一次后随卡片发给每个收件人。附件失败不挡住卡片,原因写入审计。
无缺件或无人可发则写审计不发空消息。
Args:
excel_bytes: 与排程落库同一份检核结果。为空时只发卡片。
Returns: Returns:
send_status:sent / skipped_no_missing / skipped_no_recipients / skipped_disabled / failed send_status:sent / skipped_no_missing / skipped_no_recipients / skipped_disabled / failed
@@ -213,9 +250,20 @@ def send_batch_missing_summary(
_build_jump_url, _build_jump_url,
_create_audit, _create_audit,
send_wecom_textcard_message, send_wecom_textcard_message,
upload_wecom_temp_media,
) )
media_id = None
file_note = None
if excel_bytes and excel_filename:
try:
media_id = upload_wecom_temp_media(excel_bytes, excel_filename)
except Exception as exc:
file_note = "Excel 附件上传失败"
current_app.logger.warning("[voucher-check] excel upload failed: %s", exc)
ok_any = False ok_any = False
file_failed = False
sent_ids: list[int] = [] sent_ids: list[int] = []
for user in users: for user in users:
items = plan["user_rules"].get(int(user.id)) or [] items = plan["user_rules"].get(int(user.id)) or []
@@ -234,6 +282,8 @@ def send_batch_missing_summary(
audit.status = "sent" audit.status = "sent"
ok_any = True ok_any = True
sent_ids.append(int(user.id)) sent_ids.append(int(user.id))
if media_id and not _send_excel_file(user.wecom_userid, media_id):
file_failed = True
else: else:
audit.error_code = str(data.get("errcode")) audit.error_code = str(data.get("errcode"))
audit.error_message = str(data.get("errmsg", "unknown"))[:255] audit.error_message = str(data.get("errmsg", "unknown"))[:255]
@@ -244,11 +294,16 @@ def send_batch_missing_summary(
exc, exc,
) )
skip_reason = None if file_failed and not file_note:
file_note = "部分 Excel 附件发送失败"
reasons: list[str] = []
if not ok_any: if not ok_any:
skip_reason = "企业微信发送失败" reasons.append("企业微信发送失败")
elif plan["unmapped_codes"]: elif plan["unmapped_codes"]:
skip_reason = "部分文件类型未配置接收人" reasons.append("部分文件类型未配置接收人")
if file_note:
reasons.append(file_note)
skip_reason = ";".join(reasons) or None
persist_notification( persist_notification(
run_id=engine_run_id, run_id=engine_run_id,
excel_filename=excel_filename, excel_filename=excel_filename,
+18 -3
View File
@@ -4,7 +4,7 @@ backend/app/services/voucher_check/runner.py
用途:销售一期周批次编排(上月清单、目录扫描、按票归档、缺件聚合、Excel、企微汇总)。 用途:销售一期周批次编排(上月清单、目录扫描、按票归档、缺件聚合、Excel、企微汇总)。
依赖:profile_loader、adapters、dms_client、aggregator、engine_persistence、excel_rows、notification。 依赖:profile_loader、adapters、dms_client、aggregator、engine_persistence、excel_rows、notification。
逻辑:不调用 erp_po_print.fetch / oa_sales_release.fetch;PO PDF 由 accounting-voucher-po-print(周二 05:00)、销货放行单由 accounting-voucher-oa-sales-release(周二 05:30)提前写入类型目录。 逻辑:不调用 erp_po_print.fetch / oa_sales_release.fetch;PO PDF 由 accounting-voucher-po-print(周二 05:00)、销货放行单由 accounting-voucher-oa-sales-release(周二 05:30)提前写入类型目录。
命中文件复制到所有归档,同名跳过仍记 archived。 命中文件复制到所有归档,同名跳过仍记 archived。缺件通知附带与排程落库相同的检核结果 Excel。
""" """
from __future__ import annotations from __future__ import annotations
@@ -28,7 +28,11 @@ from app.services.voucher_check.engine_persistence import (
persist_engine_results, persist_engine_results,
) )
from app.services.voucher_check.erp_repository import previous_period_bounds from app.services.voucher_check.erp_repository import previous_period_bounds
from app.services.voucher_check.excel_rows import to_excel_invoice_row from app.services.voucher_check.excel_rows import (
VOUCHER_CHECK_HEADER_LABELS,
VOUCHER_CHECK_HEADER_ORDER,
to_excel_invoice_row,
)
from app.services.voucher_check.notification import send_batch_missing_summary, send_failure_alert from app.services.voucher_check.notification import send_batch_missing_summary, send_failure_alert
from app.services.voucher_check.profile_loader import ensure_published_profile, load_profile_definition from app.services.voucher_check.profile_loader import ensure_published_profile, load_profile_definition
from app.services.voucher_check.profiles.sales import required_file_rules from app.services.voucher_check.profiles.sales import required_file_rules
@@ -369,8 +373,18 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
to_excel_invoice_row(item, period=period, executed_at=executed_at) to_excel_invoice_row(item, period=period, executed_at=executed_at)
for item in stats["excel_rows"] for item in stats["excel_rows"]
] ]
from app.services.schedule.excel_service import export_schedule_result_excel
# [STEP 4] 按文件类型接收人拆成每人一封缺件通知 # 与排程落库用同一导出,保证企微附件和事后下载是同一张表。
excel_bytes, _, _ = export_schedule_result_excel(
run_no=run.run_no,
summary={"period": period},
details=details,
header_order=list(VOUCHER_CHECK_HEADER_ORDER),
header_labels=VOUCHER_CHECK_HEADER_LABELS,
)
# [STEP 4] 按文件类型接收人拆成每人一封缺件通知,并附上本批 Excel
notify_status = send_batch_missing_summary( notify_status = send_batch_missing_summary(
task=task, task=task,
schedule_run=run, schedule_run=run,
@@ -379,6 +393,7 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
period_month=period, period_month=period,
stats=stats, stats=stats,
excel_filename=excel_filename, excel_filename=excel_filename,
excel_bytes=excel_bytes,
enabled=config.notify_missing_enabled, enabled=config.notify_missing_enabled,
) )
step_logs.append( step_logs.append(
@@ -3,7 +3,7 @@ backend/tests/voucher_check/test_notify_config.py
用途:按文件类型配置缺件接收人,以及把缺件类型拆成每人一封。 用途:按文件类型配置缺件接收人,以及把缺件类型拆成每人一封。
依赖:pytest、Flask client、notify_config_service、notification.send_batch_missing_summary。 依赖:pytest、Flask client、notify_config_service、notification.send_batch_missing_summary。
逻辑:GET/PUT 仅 is_platform_admin;未知规则码丢弃;发送时每人只看到自己负责且本批缺失的类型。 逻辑:GET/PUT 仅 is_platform_admin;未知规则码丢弃;发送时每人只看到自己负责且本批缺失的类型,并收到同一份 Excel。
""" """
from __future__ import annotations from __future__ import annotations
@@ -179,14 +179,26 @@ def test_notify_config_rejects_non_admin_headers(app, client, user_headers):
def test_send_batch_splits_one_card_per_user(app, monkeypatch): def test_send_batch_splits_one_card_per_user(app, monkeypatch):
"""缺件通知按人拆信,正文只含该人负责的缺失类型。""" """缺件通知按人拆信,正文只含该人负责的缺失类型,并给每人附上同一份 Excel。"""
sent: list[tuple[str, str, str]] = [] sent: list[tuple[str, str, str]] = []
uploaded: list[tuple[bytes, str]] = []
files: list[tuple[str, str]] = []
def _fake_send(wecom_userid, title, description, jump_url): def _fake_send(wecom_userid, title, description, jump_url):
sent.append((wecom_userid, title, description)) sent.append((wecom_userid, title, description))
return {"errcode": 0} return {"errcode": 0}
def _fake_upload(data, filename):
uploaded.append((data, filename))
return "media-vc-1"
def _fake_file(wecom_userid, media_id):
files.append((wecom_userid, media_id))
return {"errcode": 0}
monkeypatch.setattr("app.services.integrations.wecom.notify.send_wecom_textcard_message", _fake_send) monkeypatch.setattr("app.services.integrations.wecom.notify.send_wecom_textcard_message", _fake_send)
monkeypatch.setattr("app.services.integrations.wecom.notify.upload_wecom_temp_media", _fake_upload)
monkeypatch.setattr("app.services.integrations.wecom.notify.send_wecom_file_message", _fake_file)
monkeypatch.setattr( monkeypatch.setattr(
"app.services.integrations.wecom.notify._create_audit", "app.services.integrations.wecom.notify._create_audit",
lambda *args, **kwargs: SimpleNamespace( lambda *args, **kwargs: SimpleNamespace(
@@ -279,6 +291,7 @@ def test_send_batch_splits_one_card_per_user(app, monkeypatch):
}, },
}, },
excel_filename="voucher_check_sales_2026-08.xlsx", excel_filename="voucher_check_sales_2026-08.xlsx",
excel_bytes=b"voucher-xlsx",
enabled=True, enabled=True,
) )
assert status == "sent" assert status == "sent"
@@ -306,3 +319,7 @@ def test_send_batch_splits_one_card_per_user(app, monkeypatch):
assert "发票:缺" not in po_body assert "发票:缺" not in po_body
assert "提单" in bl_body assert "提单" in bl_body
assert "PO订单:缺" not in bl_body assert "PO订单:缺" not in bl_body
# 关键断言:同一份 Excel 只上传一次,两个收件人都收到文件消息。
assert uploaded == [(b"voucher-xlsx", "voucher_check_sales_2026-08.xlsx")]
assert files == [("wx-po-recv", "media-vc-1"), ("wx-bl-recv", "media-vc-1")]
assert "下一条 Excel" in po_body
@@ -244,7 +244,7 @@ flowchart TD
| -------- | ------------------------------------------------------------------------------------------------------- | | -------- | ------------------------------------------------------------------------------------------------------- |
| 触发 | 本批存在必检文件缺件 | | 触发 | 本批存在必检文件缺件 |
| 聚合 | 审计仍是一个检核批次一条;企微按接收人拆信,不在正文逐票展开缺失明细 | | 聚合 | 审计仍是一个检核批次一条;企微按接收人拆信,不在正文逐票展开缺失明细 |
| 内容 | 标题为「销售开票附件缺件提醒」。正文为中文年月、该人负责且本批缺失的文件类型(缺多少份、涉及多少张发票),并提示到详情 Excel 补齐。不写业务方代号和批次号 | | 内容 | 标题为「销售开票附件缺件提醒」。正文为中文年月、该人负责且本批缺失的文件类型(缺多少份、涉及多少张发票),并提示下一条消息是本批 Excel。不写业务方代号和批次号。卡片发出后另发本批检核结果 Excel 文件 |
| 明细查看 | 全部缺件 `invoice`、缺失文件列表和处理状态以 Excel 与执行记录为准 | | 明细查看 | 全部缺件 `invoice`、缺失文件列表和处理状态以 Excel 与执行记录为准 |
| 接收人 | 平台管理员在 Chat「通知配置」按文件类型从系统用户多选。未配置任何接收人时不发送空通知,并在发送记录标记未发送原因 | | 接收人 | 平台管理员在 Chat「通知配置」按文件类型从系统用户多选。未配置任何接收人时不发送空通知,并在发送记录标记未发送原因 |
| 技术失败 | 不作为缺件通知;按排程通知人单独告警 | | 技术失败 | 不作为缺件通知;按排程通知人单独告警 |
@@ -268,7 +268,7 @@ flowchart TD
1. 每周二任务仅处理上一个自然月,支持跨年期间计算和增量跳过。 1. 每周二任务仅处理上一个自然月,支持跨年期间计算和增量跳过。
2. 同一 `invoice` 缺少多个文件时,Excel 的“缺件文件总数”正确累计,“缺件 invoice 数”只计一次。 2. 同一 `invoice` 缺少多个文件时,Excel 的“缺件文件总数”正确累计,“缺件 invoice 数”只计一次。
3. Excel 报告顶部可按资料所属期间选择年月,并单独展示执行时间;每个 `invoice` 一行,直接展示各必检文件为“有 / 缺件 / 未检核”和总体状态;全部必检文件均为“有”时状态为“完整”。 3. Excel 报告顶部可按资料所属期间选择年月,并单独展示执行时间;每个 `invoice` 一行,直接展示各必检文件为“有 / 缺件 / 未检核”和总体状态;全部必检文件均为“有”时状态为“完整”。
4. 企业微信按文件类型接收人拆成每人一封,正文只含该人负责的缺件类型,并提供本批 Excel 下载入口;完整 `invoice` 明细不在消息正文展开。审计仍是每批一条。 4. 企业微信按文件类型接收人拆成每人一封,正文只含该人负责的缺件类型;卡片之后发送本批 Excel 文件。完整 `invoice` 明细不在消息正文展开。审计仍是每批一条。
5. OA 关联字段不完整记录被直接丢弃,不进入异常、缺件、打印或归档结果。 5. OA 关联字段不完整记录被直接丢弃,不进入异常、缺件、打印或归档结果。
6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、按文件类型选人界面已确认;ERP PO 取数:发票 HXJM、采购单 TGHX,关联 `TRIM(oma99)=TRIM(pmm99)` 已接线(独立抓取,见技术设计 §3.4);OA 销货放行单取数已接线(E10 `ft_xqqgsq` + OpenAPI,独立排程周二 05:30),凭据只进环境变量。 6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、按文件类型选人界面已确认;ERP PO 取数:发票 HXJM、采购单 TGHX,关联 `TRIM(oma99)=TRIM(pmm99)` 已接线(独立抓取,见技术设计 §3.4);OA 销货放行单取数已接线(E10 `ft_xqqgsq` + OpenAPI,独立排程周二 05:30),凭据只进环境变量。
7. 归档复制采用「同名跳过」:目标目录已有同名文件不覆盖、不报缺件。文档库自动加上的「(重命名)」改回原名,同一目录多出来的该后缀副本删除。 7. 归档复制采用「同名跳过」:目标目录已有同名文件不覆盖、不报缺件。文档库自动加上的「(重命名)」改回原名,同一目录多出来的该后缀副本删除。
@@ -318,7 +318,7 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成
### 6.2 通知聚合 ### 6.2 通知聚合
缺件通知按文件类型接收人拆信:同一人管多类时合并为一封,正文只含该人负责且本批缺失的类型。审计仍以 `run_id` 聚合为一条 `voucher_check_notifications`。接收人由 Chat「通知配置」(仅平台管理员)维护,存在 `voucher_check_notify_configs`,不写进 Profile。未配置则不发送并记录原因。排程「启用通知」与 `notify_missing_enabled` 为总开关;排程选人只用于技术失败告警,不混入缺件通知。 缺件通知按文件类型接收人拆信:同一人管多类时合并为一封,正文只含该人负责且本批缺失的类型,卡片之后再发本批检核结果 Excel。审计仍以 `run_id` 聚合为一条 `voucher_check_notifications`。接收人由 Chat「通知配置」(仅平台管理员)维护,存在 `voucher_check_notify_configs`,不写进 Profile。未配置则不发送并记录原因。排程「启用通知」与 `notify_missing_enabled` 为总开关;排程选人只用于技术失败告警,不混入缺件通知。
### 6.3 检核任务列表 ### 6.3 检核任务列表
@@ -1,12 +1,12 @@
<script setup lang="ts"> <script setup lang="ts">
/** /**
* features/kb/components/KbJobQueuePanel.vue * features/kb/components/KbJobQueuePanel.vue
* 知识库任务队列展示面板。 * 用途:知识库任务队列展示面板。
* 依赖:kb.api 的 KbJob 类型、Vue I18n、lucide-vue-next 图标。 * 依赖:kb.api 的 KbJob 类型、Vue I18n、Element Plus 按钮与标签。样式由引用它的页面引入。
* 逻辑:只负责渲染任务列表和触发执行事件;任务执行、反馈和刷新由父级 KbAdminPanel 处理。 * 逻辑:只负责渲染任务列表和触发执行事件;任务执行、反馈和刷新由父级处理。
*/ */
import { VideoPlay } from '@element-plus/icons-vue';
import { Play } from 'lucide-vue-next'; import { ElButton, ElTag } from 'element-plus';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import type { KbJob } from '../api/kb.api'; import type { KbJob } from '../api/kb.api';
@@ -21,15 +21,33 @@ const emit = defineEmits<{
const { t } = useI18n(); const { t } = useI18n();
/** 判断任务是否允许手动执行,避免模板里重复硬编码任务类型条件。 */ /**
* 判断任务是否允许手动执行,避免模板里重复硬编码任务类型条件。
* @param job - 队列中的一条任务
* @returns 清洗或同步且尚未成功时为 true
*/
const canRunJob = (job: KbJob): boolean => ['clean', 'sync_dify'].includes(job.job_type) && job.status !== 'success'; const canRunJob = (job: KbJob): boolean => ['clean', 'sync_dify'].includes(job.job_type) && job.status !== 'success';
/**
* 把任务状态映射成 Element 标签类型。
* 核心逻辑:成功为绿,失败为危险,排队或执行中为警告,其余为信息。
* @param status - 任务状态原文
* @returns ElTag 的 type
*/
function jobTagType(status: string): 'success' | 'warning' | 'danger' | 'info' {
const normalized = String(status || '').toLowerCase();
if (['success', 'synced', 'cleaned'].includes(normalized)) return 'success';
if (['failed', 'error'].includes(normalized)) return 'danger';
if (['running', 'processing', 'queued'].includes(normalized)) return 'warning';
return 'info';
}
</script> </script>
<template> <template>
<section class="kb-admin-section"> <section class="kb-admin-section">
<div class="mb-4 flex items-center justify-between"> <div class="mb-4 flex items-center justify-between">
<h3 class="section-title">{{ t('kbAdmin.jobsTitle') }}</h3> <h3 class="section-title">{{ t('kbAdmin.jobsTitle') }}</h3>
<span class="text-xs text-muted">/api/kb/jobs</span> <span>/api/kb/jobs</span>
</div> </div>
<div v-if="jobs.length === 0" class="kb-admin-empty"> <div v-if="jobs.length === 0" class="kb-admin-empty">
{{ t('kbAdmin.jobsEmpty') }} {{ t('kbAdmin.jobsEmpty') }}
@@ -38,25 +56,24 @@ const canRunJob = (job: KbJob): boolean => ['clean', 'sync_dify'].includes(job.j
<div v-for="job in jobs" :key="job.id" class="kb-admin-card"> <div v-for="job in jobs" :key="job.id" class="kb-admin-card">
<div class="flex items-start justify-between gap-3"> <div class="flex items-start justify-between gap-3">
<div class="min-w-0"> <div class="min-w-0">
<div class="font-semibold text-primary">{{ job.job_type }}</div> <div>{{ job.job_type }}</div>
<div class="mt-1 text-sm text-muted">{{ job.created_at || '--' }}</div> <div class="mt-1">{{ job.created_at || '--' }}</div>
<div class="mt-2 text-sm text-muted">{{ job.message || t('kbAdmin.noJobMessage') }}</div> <div class="mt-2">{{ job.message || t('kbAdmin.noJobMessage') }}</div>
<div class="mt-2 text-xs text-muted"> <div class="mt-2">
{{ t('kbAdmin.jobMeta', { docId: job.document_id ?? '--', versionId: job.document_version_id ?? '--', progress: job.progress ?? 0 }) }} {{ t('kbAdmin.jobMeta', { docId: job.document_id ?? '--', versionId: job.document_version_id ?? '--', progress: job.progress ?? 0 }) }}
</div> </div>
</div> </div>
<span class="kb-admin-badge">{{ job.status }}</span> <ElTag effect="light" :type="jobTagType(job.status)">{{ job.status }}</ElTag>
</div> </div>
<div v-if="canRunJob(job)" class="mt-3 flex justify-end"> <div v-if="canRunJob(job)" class="mt-3 flex justify-end">
<button <ElButton
type="button" :icon="VideoPlay"
class="inline-flex items-center gap-1 rounded-xl border border-brand-200 px-3 py-2 text-xs font-medium text-brand-700 transition-colors hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60" :loading="runningJobId === job.id"
:disabled="runningJobId === job.id" :disabled="runningJobId === job.id"
@click="emit('run-job', job)" @click="emit('run-job', job)"
> >
<Play class="h-3.5 w-3.5" />
{{ runningJobId === job.id ? t('kbAdmin.running') : t('kbAdmin.runJob') }} {{ runningJobId === job.id ? t('kbAdmin.running') : t('kbAdmin.runJob') }}
</button> </ElButton>
</div> </div>
</div> </div>
</div> </div>
File diff suppressed because it is too large. Load diff
@@ -1,12 +1,13 @@
/** /**
* features/kb/composables/kb-workspace/kb-workspace.state.ts * features/kb/composables/kb-workspace/kb-workspace.state.ts
* 用途:作业面共享响应式状态;各子 composable 通过同一 state 读写,避免重复 ref。 * 用途:作业面共享响应式状态;各子 composable 通过同一 state 读写,避免重复 ref。
* 依赖:vue-router、vue-i18n、auth、kb.api 类型、kb-workspace.types。 * 依赖:vue-router、vue-i18n、Element Plus ElMessageBox、auth、kb.api 类型、kb-workspace.types。
* 逻辑:createKbWorkspaceState 产出全部 ref;含公共确认弹窗(删除/上传路径等)辅助方法。 * 逻辑:createKbWorkspaceState 产出全部 ref;删除与路径确认走 ElMessageBox.confirm,取消时不执行回调。
*/ */
import { computed, ref } from 'vue'; import { computed, ref } from 'vue';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { ElMessageBox } from 'element-plus';
import { getStoredAuthUser, isPlatformAdminUser } from '@/shared/utils/auth'; import { getStoredAuthUser, isPlatformAdminUser } from '@/shared/utils/auth';
import type { import type {
KbDocumentItem, KbDocumentItem,
@@ -55,12 +56,6 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
const showFailureModal = ref(false); const showFailureModal = ref(false);
const showPathUploadModal = ref(false); const showPathUploadModal = ref(false);
const showPathUploadHistoryModal = ref(false); const showPathUploadHistoryModal = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
const deleteConfirmTitle = ref('');
const deleteConfirmText = ref('');
const deleteConfirmTone = ref<'danger' | 'primary'>('danger');
let pendingDeleteAction: (() => Promise<void> | void) | null = null;
const showPathUploadDetails = ref(false); const showPathUploadDetails = ref(false);
const fileInputRef = ref<HTMLInputElement | null>(null); const fileInputRef = ref<HTMLInputElement | null>(null);
const pathUploadInputRef = ref<HTMLInputElement | null>(null); const pathUploadInputRef = ref<HTMLInputElement | null>(null);
@@ -118,14 +113,15 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
}); });
/** /**
* 打开公共确认弹窗(删除 / 上传路径等场景复用)。 * 弹出 Element 确认框,确认后再执行删除或写入路径清单。
* 核心逻辑:ElMessageBox.confirm 在取消或关闭时 reject,catch 后直接返回,不调用 onConfirm。
* @param message - 正文 * @param message - 正文
* @param onConfirm - 确认回调 * @param onConfirm - 用户确认后的回调
* @param options.title - 标题;空则用删除默认文案 * @param options.title - 标题;空则用删除默认文案
* @param options.confirmText - 确认按钮文案 * @param options.confirmText - 确认按钮文案
* @param options.confirmTone - danger 删除 / primary 非破坏性确认 * @param options.confirmTone - danger 删除 / primary 非破坏性确认
*/ */
const openDeleteConfirmDialog = ( const openDeleteConfirmDialog = async (
message: string, message: string,
onConfirm: () => Promise<void> | void, onConfirm: () => Promise<void> | void,
options?: { options?: {
@@ -134,33 +130,29 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
confirmTone?: 'danger' | 'primary'; confirmTone?: 'danger' | 'primary';
}, },
) => { ) => {
deleteConfirmMessage.value = message; const tone = options?.confirmTone || 'danger';
deleteConfirmTitle.value = options?.title || '';
deleteConfirmText.value = options?.confirmText || '';
deleteConfirmTone.value = options?.confirmTone || 'danger';
pendingDeleteAction = onConfirm;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirmDialog = () => {
showDeleteConfirmDialog.value = false;
deleteConfirmMessage.value = '';
deleteConfirmTitle.value = '';
deleteConfirmText.value = '';
deleteConfirmTone.value = 'danger';
pendingDeleteAction = null;
};
const handleDeleteConfirm = async () => {
if (!pendingDeleteAction) return;
try { try {
await pendingDeleteAction(); await ElMessageBox.confirm(
message,
options?.title || t('common.deleteDialog.defaultTitle'),
{
type: tone === 'primary' ? 'info' : 'warning',
confirmButtonText: options?.confirmText || t('common.deleteDialog.confirm'),
cancelButtonText: t('common.deleteDialog.cancel'),
confirmButtonType: tone === 'primary' ? 'primary' : 'danger',
closeOnClickModal: false,
},
);
} catch {
return;
}
try {
await onConfirm();
} catch (err) { } catch (err) {
console.error('[deleteConfirm]', err); console.error('[deleteConfirm]', err);
feedback.value = String(err) || t('kbWorkspace.msg.operationFailed'); feedback.value = String(err) || t('kbWorkspace.msg.operationFailed');
feedbackType.value = 'error'; feedbackType.value = 'error';
} }
closeDeleteConfirmDialog();
}; };
return { return {
@@ -190,11 +182,6 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
showFailureModal, showFailureModal,
showPathUploadModal, showPathUploadModal,
showPathUploadHistoryModal, showPathUploadHistoryModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
deleteConfirmTitle,
deleteConfirmText,
deleteConfirmTone,
showPathUploadDetails, showPathUploadDetails,
fileInputRef, fileInputRef,
pathUploadInputRef, pathUploadInputRef,
@@ -228,8 +215,6 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
sourceInfoVersions, sourceInfoVersions,
pathUploadTask, pathUploadTask,
openDeleteConfirmDialog, openDeleteConfirmDialog,
closeDeleteConfirmDialog,
handleDeleteConfirm,
}; };
} }
@@ -1,7 +1,7 @@
/** /**
* features/kb/composables/kb-workspace/useKbWorkspacePathUpload.ts * features/kb/composables/kb-workspace/useKbWorkspacePathUpload.ts
* 用途:路径上传编排——选目录、分批 job、轮询进度与历史批次操作。 * 用途:路径上传编排——选目录、分批 job、轮询进度与历史批次操作。
* 依赖:kb.api、kb-path-upload.utils、DeleteConfirmDialog(经 state.openDeleteConfirmDialog)。 * 依赖:kb.api、kb-path-upload.utils、state.openDeleteConfirmDialog(ElMessageBox.confirm)。
* 逻辑:优先 showDirectoryPicker 避免浏览器原生目录确认;回退 webkitdirectory;确认后写入待上传清单。 * 逻辑:优先 showDirectoryPicker 避免浏览器原生目录确认;回退 webkitdirectory;确认后写入待上传清单。
*/ */
import type { KbJob } from '../../api/kb.api'; import type { KbJob } from '../../api/kb.api';
@@ -231,7 +231,7 @@ export function useKbWorkspacePathUpload(
/** /**
* 打开目录选择器;优先 showDirectoryPicker(无 Windows 原生上传确认), * 打开目录选择器;优先 showDirectoryPicker(无 Windows 原生上传确认),
* 不支持时回退隐藏 input[webkitdirectory]。 * 不支持时回退隐藏 input[webkitdirectory]。
* 选完后用公共 DeleteConfirmDialog 二次确认再写入清单。 * 选完后调用 openDeleteConfirmDialog,由 Element 确认框确认后再写入清单;取消则不写入。
*/ */
const triggerPathUploadSelection = async () => { const triggerPathUploadSelection = async () => {
const picker = (window as Window & { const picker = (window as Window & {
@@ -277,7 +277,7 @@ export function useKbWorkspacePathUpload(
/** /**
* 旧版 input[webkitdirectory] 回退:浏览器会先弹原生确认,再进入本回调。 * 旧版 input[webkitdirectory] 回退:浏览器会先弹原生确认,再进入本回调。
* 仍用公共确认弹窗二次确认后写入清单。 * 仍调用 openDeleteConfirmDialog,由 Element 确认框确认后写入清单;取消则不写入。
*/ */
const handlePathFilesSelected = (event: Event) => { const handlePathFilesSelected = (event: Event) => {
const input = event.target as HTMLInputElement; const input = event.target as HTMLInputElement;
+382 -287
View File
@@ -1,12 +1,35 @@
<script setup lang="ts"> <script setup lang="ts">
/** /**
* features/kb/views/KbWorkspaceView.vue * features/kb/views/KbWorkspaceView.vue
* 知识库作业面视图壳:模板与弹窗布局,业务逻辑见 useKbWorkspace。 * 用途:知识库作业面视图壳。分组概览、文档列表、路径上传进度与筛选。
* 依赖:Element Plus、useKbWorkspace、KbWorkspaceOverlays。样式只在本页入口引入。
* 逻辑:业务仍走 useKbWorkspace。按钮、输入、筛选、表格、分页换成 Element;隐藏文件框保留。
* 本页没有 PDF/canvas 绘制。Markdown 与源文件操作在 KbWorkspaceOverlays。
*/ */
import { ArrowLeft, BookOpen, ChevronDown, ChevronUp, FileText, Info, RefreshCw, Search, Settings, SquareCheck, Trash2, Upload } from 'lucide-vue-next'; import { ArrowDown, ArrowLeft, ArrowUp, Delete, Document, InfoFilled, Reading, Refresh, Search, Select, Setting, Upload } from '@element-plus/icons-vue';
import PaginationBar from '@/shared/components/PaginationBar.vue'; import {
ElAlert,
ElButton,
ElCheckbox,
ElIcon,
ElInput,
ElLoading,
ElPagination,
ElRadioButton,
ElRadioGroup,
ElTable,
ElTableColumn,
ElTag,
ElText,
ElTooltip,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/shared/styles/element-theme.css';
import KbWorkspaceOverlays from '../components/KbWorkspaceOverlays.vue'; import KbWorkspaceOverlays from '../components/KbWorkspaceOverlays.vue';
import { useKbWorkspace } from '../composables/useKbWorkspace'; import { useKbWorkspace } from '../composables/useKbWorkspace';
import type { KbDocumentItem } from '../api/kb.api';
import type { PathUploadTaskItem } from '../types/kb-workspace.types';
const props = defineProps<{ const props = defineProps<{
embedded?: boolean; embedded?: boolean;
@@ -14,6 +37,40 @@ const props = defineProps<{
/** 作业面状态与操作:模板统一通过 kb.xxx 访问,含 fileInputRef / pathUploadInputRef */ /** 作业面状态与操作:模板统一通过 kb.xxx 访问,含 fileInputRef / pathUploadInputRef */
const kb = useKbWorkspace({ embedded: props.embedded }); const kb = useKbWorkspace({ embedded: props.embedded });
const vLoading = ElLoading.directive;
/**
* 把现有状态色映射成 Element 标签类型。
* 核心逻辑:绿为成功、琥珀为警告、玫红为危险,其余为信息。不改工作流判定。
* @param className - getStatusBadgeClass 或路径项展示态返回的样式类
* @returns ElTag 的 type
*/
function statusTagType(className: string): 'success' | 'warning' | 'danger' | 'info' {
if (className.includes('emerald')) return 'success';
if (className.includes('amber')) return 'warning';
if (className.includes('rose')) return 'danger';
return 'info';
}
/**
* 按当前打开的文档给出表格行类名。
* 核心逻辑:渲染时读取 selectedId,选中行跟着详情开关更新。
* @param selectedId - 当前文档 id,没有打开详情时为 null
* @returns Element 表格 row-class-name 回调
*/
function documentRowClass(selectedId: number | null) {
return ({ row }: { row: KbDocumentItem }) => (selectedId === row.id ? 'kb-doc-row--current' : '');
}
/**
* 点击分组摘要。只有失败数大于 0 的格子才打开对应失败列表。
* @param item - 摘要格,含是否可点以及失败阶段
*/
function openFailureSummary(item: { clickable: boolean; failureType?: 'upload' | 'clean' | 'sync' }) {
if (item.clickable && item.failureType) {
kb.openFailureModal(item.failureType);
}
}
</script> </script>
<template> <template>
@@ -21,72 +78,70 @@ const kb = useKbWorkspace({ embedded: props.embedded });
<div :class="!kb.embedded ? 'mx-auto max-w-7xl page-shell-mobile py-6' : ''"> <div :class="!kb.embedded ? 'mx-auto max-w-7xl page-shell-mobile py-6' : ''">
<div class="card mb-6 flex flex-col gap-4 p-6 md:flex-row md:items-center md:justify-between"> <div class="card mb-6 flex flex-col gap-4 p-6 md:flex-row md:items-center md:justify-between">
<div class="flex items-start gap-4"> <div class="flex items-start gap-4">
<button <ElButton
v-if="!kb.embedded || (kb.embedded && kb.viewMode === 'group_detail')" v-if="!kb.embedded || (kb.embedded && kb.viewMode === 'group_detail')"
@click="kb.embedded ? kb.backToGroupOverview() : kb.router.push('/workspace')" :icon="ArrowLeft"
class="kb-ws-icon-btn"
:title="kb.embedded ? kb.t('kbWorkspace.actions.backToOverview') : kb.t('kbWorkspace.actions.backToWorkspace')" :title="kb.embedded ? kb.t('kbWorkspace.actions.backToOverview') : kb.t('kbWorkspace.actions.backToWorkspace')"
> :aria-label="kb.embedded ? kb.t('kbWorkspace.actions.backToOverview') : kb.t('kbWorkspace.actions.backToWorkspace')"
<ArrowLeft class="h-5 w-5" /> @click="kb.embedded ? kb.backToGroupOverview() : kb.router.push('/workspace')"
</button> />
<div> <div>
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
<div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-brand-50 text-brand-600"> <div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-brand-50 text-brand-600">
<BookOpen class="h-6 w-6" /> <ElIcon :size="24"><Reading /></ElIcon>
</div> </div>
<div> <div>
<h1 class="text-2xl font-bold text-primary"> <h1 class="section-title">
{{ kb.viewMode === 'group_overview' ? kb.t('kbWorkspace.header.groupOverviewTitle') : kb.t('kbWorkspace.header.workspaceTitle') }} {{ kb.viewMode === 'group_overview' ? kb.t('kbWorkspace.header.groupOverviewTitle') : kb.t('kbWorkspace.header.workspaceTitle') }}
</h1> </h1>
<p class="mt-1 text-sm text-muted"> <p class="section-desc">
{{ kb.viewMode === 'group_overview' ? kb.t('kbWorkspace.header.groupOverviewSubtitle') : kb.t('kbWorkspace.header.workspaceSubtitle') }} {{ kb.viewMode === 'group_overview' ? kb.t('kbWorkspace.header.groupOverviewSubtitle') : kb.t('kbWorkspace.header.workspaceSubtitle') }}
</p> </p>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div class="flex flex-wrap items-center gap-3"> <div class="kb-toolbar">
<button <ElButton
v-if="kb.viewMode === 'group_overview'" v-if="kb.viewMode === 'group_overview'"
type="button" type="primary"
:icon="Setting"
@click="kb.router.push('/admin/knowledge-base')" @click="kb.router.push('/admin/knowledge-base')"
class="btn-primary"
> >
<Settings class="h-4 w-4" />
{{ kb.t('kbWorkspace.actions.manageGroups') }} {{ kb.t('kbWorkspace.actions.manageGroups') }}
</button> </ElButton>
</div> </div>
</div> </div>
<template v-if="kb.viewMode === 'group_overview'"> <template v-if="kb.viewMode === 'group_overview'">
<section class="kb-ws-section"> <section class="kb-ws-section">
<div class="mb-4 flex items-center"> <div class="mb-4 flex items-center">
<h2 class="text-lg font-semibold text-primary">{{ kb.t('kbWorkspace.overview.title') }}</h2> <h2 class="section-title">{{ kb.t('kbWorkspace.overview.title') }}</h2>
</div> </div>
<div v-if="kb.isLoading" class="py-10 text-center text-sm text-muted">{{ kb.t('kbWorkspace.overview.loadingGroups') }}</div> <div v-if="kb.isLoading" class="py-10 text-center">{{ kb.t('kbWorkspace.overview.loadingGroups') }}</div>
<div v-else-if="kb.groups.length === 0" class="kb-ws-empty py-10 text-center text-sm text-muted"> <div v-else-if="kb.groups.length === 0" class="kb-ws-empty py-10 text-center">
{{ kb.t('kbWorkspace.overview.emptyGroups') }} {{ kb.t('kbWorkspace.overview.emptyGroups') }}
</div> </div>
<div v-else class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4"> <div v-else class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4">
<div <div
v-for="group in kb.groups" v-for="group in kb.groups"
:key="group.id" :key="group.id"
@click="kb.openGroupDetail(group.id)"
class="kb-ws-card--interactive !min-h-[150px]" class="kb-ws-card--interactive !min-h-[150px]"
@click="kb.openGroupDetail(group.id)"
> >
<div class="w-full text-left"> <div class="w-full text-left">
<div class="flex items-start justify-between gap-3"> <div class="flex items-start justify-between gap-3">
<div class="min-w-0"> <div class="min-w-0">
<div class="text-xl font-bold leading-tight text-primary break-words">{{ group.name }}</div> <div class="section-title break-words">{{ group.name }}</div>
<div class="mt-1 line-clamp-2 text-sm text-muted" :title="group.description || kb.t('kbWorkspace.overview.noDescription')"> <div class="section-desc line-clamp-2" :title="group.description || kb.t('kbWorkspace.overview.noDescription')">
{{ group.description || kb.t('kbWorkspace.overview.noDescription') }} {{ group.description || kb.t('kbWorkspace.overview.noDescription') }}
</div> </div>
</div> </div>
<div class="rounded-full bg-surface-soft px-2.5 py-1 text-xs font-medium text-secondary whitespace-nowrap"> <ElTag effect="light">
{{ kb.t('kbWorkspace.overview.documentCount', { count: group.document_count ?? 0 }) }} {{ kb.t('kbWorkspace.overview.documentCount', { count: group.document_count ?? 0 }) }}
</ElTag>
</div> </div>
</div> <div class="mt-3">{{ kb.t('kbWorkspace.overview.updatedAt') }}{{ kb.formatDateTime(group.updated_at) }}</div>
<div class="mt-3 text-xs text-muted">{{ kb.t('kbWorkspace.overview.updatedAt') }}{{ kb.formatDateTime(group.updated_at) }}</div>
</div> </div>
</div> </div>
</div> </div>
@@ -114,24 +169,22 @@ const kb = useKbWorkspace({ embedded: props.embedded });
<div class="kb-ws-section"> <div class="kb-ws-section">
<div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between"> <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
<div class="min-w-0"> <div class="min-w-0">
<div class="text-xs font-medium text-muted">{{ kb.t('kbWorkspace.summary.currentGroup') }}</div> <div>{{ kb.t('kbWorkspace.summary.currentGroup') }}</div>
<h2 class="mt-1 text-2xl font-bold text-primary break-words">{{ kb.selectedGroup?.name || '--' }}</h2> <h2 class="section-title mt-1 break-words">{{ kb.selectedGroup?.name || '--' }}</h2>
<p class="mt-2 max-w-3xl text-sm text-muted"> <p class="section-desc mt-2 max-w-3xl">
{{ kb.selectedGroup?.description || kb.t('kbWorkspace.overview.noDescription') }} {{ kb.selectedGroup?.description || kb.t('kbWorkspace.overview.noDescription') }}
</p> </p>
</div> </div>
<div class="grid min-w-full grid-cols-2 gap-2 sm:grid-cols-5 lg:min-w-[520px]"> <div class="kb-stat-grid">
<button <ElButton
v-for="item in kb.groupSummaryItems.filter((summary) => !summary.wide)" v-for="item in kb.groupSummaryItems.filter((summary) => !summary.wide)"
:key="item.label" :key="item.label"
type="button" class="kb-stat-tile"
class="rounded-2xl border border-default bg-surface-soft px-3 py-3 text-left transition-colors" @click="openFailureSummary(item)"
:class="item.clickable ? 'hover:border-rose-200 hover:bg-rose-50' : ''"
@click="item.clickable && item.failureType ? kb.openFailureModal(item.failureType) : undefined"
> >
<div class="text-lg font-semibold text-primary">{{ item.value }}</div> <span>{{ item.value }}</span>
<div class="mt-1 text-xs text-muted">{{ item.label }}</div> <span>{{ item.label }}</span>
</button> </ElButton>
</div> </div>
</div> </div>
</div> </div>
@@ -140,346 +193,301 @@ const kb = useKbWorkspace({ embedded: props.embedded });
<div class="mb-4 space-y-3"> <div class="mb-4 space-y-3">
<div class="flex flex-wrap items-center justify-between gap-3"> <div class="flex flex-wrap items-center justify-between gap-3">
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<h2 class="text-lg font-semibold text-primary">{{ kb.t('kbWorkspace.documents.title') }}</h2> <h2 class="section-title">{{ kb.t('kbWorkspace.documents.title') }}</h2>
<div class="group relative"> <ElTooltip :content="kb.t('kbWorkspace.documents.infoTip')" placement="bottom-start">
<button <ElButton
type="button" :icon="InfoFilled"
class="inline-flex h-6 w-6 items-center justify-center rounded-full border border-default text-muted transition-colors hover:border-brand-300 hover:text-brand-600" :title="kb.t('kbWorkspace.documents.infoTip')"
> :aria-label="kb.t('kbWorkspace.documents.infoTip')"
<Info class="h-3.5 w-3.5" /> />
</button> </ElTooltip>
<div class="pointer-events-none absolute left-0 top-8 z-10 hidden w-80 rounded-2xl border border-default bg-surface px-4 py-3 text-sm text-muted shadow-xl group-hover:block">
{{ kb.t('kbWorkspace.documents.infoTip') }}
</div> </div>
</div> <div class="kb-toolbar">
</div> <ElButton
<div class="flex flex-wrap items-center gap-3">
<button
v-if="kb.selectedGroupId" v-if="kb.selectedGroupId"
@click="kb.openPathUploadModal" :icon="Upload"
:disabled="kb.pathUploadRunning" :disabled="kb.pathUploadRunning"
class="inline-flex items-center gap-2 rounded-2xl border border-brand-200 px-4 py-2.5 text-sm font-medium text-brand-700 transition-colors hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60 border-brand-200 hover:bg-brand-50" @click="kb.openPathUploadModal"
> >
<Upload class="h-4 w-4" />
{{ kb.t('kbWorkspace.documents.uploadPath') }} {{ kb.t('kbWorkspace.documents.uploadPath') }}
</button> </ElButton>
<button <ElButton
v-if="kb.selectedGroupId" v-if="kb.selectedGroupId"
@click="kb.triggerMultiUpload" type="primary"
:icon="Upload"
:loading="kb.isSubmitting"
:disabled="kb.isSubmitting" :disabled="kb.isSubmitting"
class="btn-primary" @click="kb.triggerMultiUpload"
> >
<Upload class="h-4 w-4" />
{{ kb.t('kbWorkspace.documents.uploadFile') }} {{ kb.t('kbWorkspace.documents.uploadFile') }}
</button> </ElButton>
</div> </div>
</div> </div>
</div> </div>
<p <ElAlert
v-if="kb.feedback" v-if="kb.feedback"
class="mb-4 text-sm" class="mb-4"
:class="kb.feedbackType === 'error' ? 'text-rose-500' : 'text-emerald-600'" :closable="false"
> :title="kb.feedback"
{{ kb.feedback }} :type="kb.feedbackType === 'error' ? 'error' : 'success'"
</p> />
<div <div
v-if="kb.pathUploadTask.total" v-if="kb.pathUploadTask.total"
class="mb-4 rounded-2xl border border-default bg-surface-soft p-4" class="mb-4 rounded-2xl border border-default bg-surface-soft p-4"
> >
<div class="flex flex-wrap items-center justify-between gap-3"> <div class="flex flex-wrap items-center justify-between gap-3">
<div> <div>
<div class="text-sm font-semibold text-primary"> <div>
{{ kb.t('kbWorkspace.pathUpload.progressTitle') }} {{ kb.t('kbWorkspace.pathUpload.progressTitle') }}
<span <ElTag class="ml-2" effect="light" :type="kb.pathUploadRunning ? 'warning' : 'success'">
class="ml-2 inline-flex items-center rounded-full border px-2.5 py-1 text-xs"
:class="kb.pathUploadRunning
? 'border-amber-200 bg-amber-50 text-amber-700 border-amber-200'
: 'border-emerald-200 bg-emerald-50 text-emerald-700 border-emerald-200 '"
>
{{ kb.pathUploadRunning ? kb.t('kbWorkspace.pathUpload.uploading') : kb.t('kbWorkspace.pathUpload.completed') }} {{ kb.pathUploadRunning ? kb.t('kbWorkspace.pathUpload.uploading') : kb.t('kbWorkspace.pathUpload.completed') }}
</span> </ElTag>
</div> </div>
<div class="mt-1 text-sm text-muted"> <div class="mt-1">
{{ kb.t('kbWorkspace.pathUpload.batchHint', { batchSize: kb.pathUploadTask.batchSize, seconds: kb.PATH_UPLOAD_BATCH_INTERVAL_MS / 1000 }) }} {{ kb.t('kbWorkspace.pathUpload.batchHint', { batchSize: kb.pathUploadTask.batchSize, seconds: kb.PATH_UPLOAD_BATCH_INTERVAL_MS / 1000 }) }}
</div> </div>
</div> </div>
<div class="grid grid-cols-2 gap-2 text-sm text-secondary md:grid-cols-4"> <div class="grid grid-cols-2 gap-2 md:grid-cols-4">
<div>{{ kb.t('kbWorkspace.pathUpload.total', { count: kb.pathUploadSummary.total }) }}</div> <div>{{ kb.t('kbWorkspace.pathUpload.total', { count: kb.pathUploadSummary.total }) }}</div>
<div>{{ kb.t('kbWorkspace.pathUpload.pending', { count: kb.pathUploadSummary.pending }) }}</div> <div>{{ kb.t('kbWorkspace.pathUpload.pending', { count: kb.pathUploadSummary.pending }) }}</div>
<div>{{ kb.t('kbWorkspace.pathUpload.uploaded', { count: kb.pathUploadSummary.uploaded }) }}</div> <div>{{ kb.t('kbWorkspace.pathUpload.uploaded', { count: kb.pathUploadSummary.uploaded }) }}</div>
<div>{{ kb.t('kbWorkspace.pathUpload.failed', { count: kb.pathUploadSummary.failed }) }}</div> <div>{{ kb.t('kbWorkspace.pathUpload.failed', { count: kb.pathUploadSummary.failed }) }}</div>
</div> </div>
</div> </div>
<div v-if="kb.pathUploadTask.currentFile" class="mt-3 text-sm text-brand-600 "> <div v-if="kb.pathUploadTask.currentFile" class="mt-3">
{{ kb.t('kbWorkspace.pathUpload.currentFile', { name: kb.pathUploadTask.currentFile }) }} {{ kb.t('kbWorkspace.pathUpload.currentFile', { name: kb.pathUploadTask.currentFile }) }}
</div> </div>
<div class="mt-4 space-y-2"> <div class="mt-4 space-y-2">
<div class="flex flex-wrap items-center justify-between gap-2"> <div class="flex flex-wrap items-center justify-between gap-2">
<button <ElButton
type="button" link
type="primary"
:icon="kb.showPathUploadDetails ? ArrowUp : ArrowDown"
@click="kb.showPathUploadDetails = !kb.showPathUploadDetails" @click="kb.showPathUploadDetails = !kb.showPathUploadDetails"
class="inline-flex items-center gap-2 text-sm font-medium text-secondary transition-colors hover:text-brand-600 hover:text-brand-600"
> >
<span>{{ kb.t('kbWorkspace.pathUpload.details') }}</span> {{ kb.t('kbWorkspace.pathUpload.details') }}
<ChevronDown v-if="!kb.showPathUploadDetails" class="h-4 w-4" /> </ElButton>
<ChevronUp v-else class="h-4 w-4" /> <ElButton
</button>
<div class="flex items-center gap-2">
<button
v-if="kb.latestPathUploadJob && kb.hasRetryablePathUploadFailure(kb.latestPathUploadJob) && !kb.pathUploadRunning" v-if="kb.latestPathUploadJob && kb.hasRetryablePathUploadFailure(kb.latestPathUploadJob) && !kb.pathUploadRunning"
@click="kb.handleRetryFailedPathUpload(kb.latestPathUploadJob)" link
type="danger"
:loading="kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:all`"
:disabled="kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:all`" :disabled="kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:all`"
class="inline-flex items-center rounded-xl border border-rose-200 px-3 py-1.5 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60 border-rose-200 hover:bg-rose-50" @click="kb.handleRetryFailedPathUpload(kb.latestPathUploadJob)"
> >
{{ kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:all` ? kb.t('kbWorkspace.common.processing') : kb.t('kbWorkspace.pathUpload.retryFailedFiles') }} {{ kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:all` ? kb.t('kbWorkspace.common.processing') : kb.t('kbWorkspace.pathUpload.retryFailedFiles') }}
</button> </ElButton>
</div> </div>
</div> <ElTable
<div v-if="kb.showPathUploadDetails" class="max-h-72 space-y-2 overflow-y-auto pr-1"> v-if="kb.showPathUploadDetails"
<div :data="kb.recentPathUploadItems"
v-for="item in kb.recentPathUploadItems" row-key="key"
:key="item.key" max-height="288"
class="flex flex-wrap items-start justify-between gap-3 rounded-xl border border-default bg-surface px-3 py-3 text-sm" :empty-text="kb.t('kbWorkspace.pathUpload.noBatchMessage')"
> >
<div class="min-w-0 flex-1"> <ElTableColumn prop="title" min-width="160" show-overflow-tooltip />
<div class="truncate font-medium text-primary">{{ item.title }}</div> <ElTableColumn prop="displayPath" min-width="200" show-overflow-tooltip />
<div class="mt-1 truncate text-xs text-muted">{{ item.displayPath }}</div> <ElTableColumn min-width="160" show-overflow-tooltip>
<div v-if="item.error" class="mt-1 text-xs text-rose-500">{{ kb.t('kbWorkspace.common.failureReason', { reason: item.error }) }}</div> <template #default="{ row }">
</div> <ElText v-if="row.error" type="danger">
<div class="flex items-center gap-2"> {{ kb.t('kbWorkspace.common.failureReason', { reason: row.error }) }}
<span </ElText>
class="inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold" </template>
:class="kb.getPathUploadItemDisplayState(item).className" </ElTableColumn>
<ElTableColumn width="120">
<template #default="{ row }">
<ElTag effect="light" :type="statusTagType(kb.getPathUploadItemDisplayState(row as PathUploadTaskItem).className)">
{{ kb.getPathUploadItemDisplayState(row as PathUploadTaskItem).label }}
</ElTag>
</template>
</ElTableColumn>
<ElTableColumn width="160" align="right">
<template #default="{ row }">
<ElButton
v-if="row.retryable && kb.latestPathUploadJob && !kb.pathUploadRunning"
link
type="primary"
:loading="kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:${row.displayPath}`"
:disabled="kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:${row.displayPath}`"
@click="kb.handleRetryFailedPathUpload(kb.latestPathUploadJob, [row.displayPath])"
> >
{{ kb.getPathUploadItemDisplayState(item).label }} {{ kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:${row.displayPath}` ? kb.t('kbWorkspace.common.processing') : kb.t('kbWorkspace.common.retry') }}
</span> </ElButton>
<button <ElButton
v-if="item.retryable && kb.latestPathUploadJob && !kb.pathUploadRunning"
@click="kb.handleRetryFailedPathUpload(kb.latestPathUploadJob, [item.displayPath])"
:disabled="kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:${item.displayPath}`"
class="inline-flex items-center rounded-xl border border-rose-200 px-2.5 py-1 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60 border-rose-200 hover:bg-rose-50"
>
{{ kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:${item.displayPath}` ? kb.t('kbWorkspace.common.processing') : kb.t('kbWorkspace.common.retry') }}
</button>
<button
v-if="kb.latestPathUploadJob && !kb.pathUploadRunning" v-if="kb.latestPathUploadJob && !kb.pathUploadRunning"
@click="kb.handleDeletePathUploadItem(kb.latestPathUploadJob, item)" link
class="inline-flex items-center rounded-xl border border-default px-2.5 py-1 text-xs font-medium text-muted transition-colors hover:bg-surface-soft hover-surface-soft" type="danger"
@click="kb.handleDeletePathUploadItem(kb.latestPathUploadJob, row as PathUploadTaskItem)"
> >
{{ kb.t('kbWorkspace.common.delete') }} {{ kb.t('kbWorkspace.common.delete') }}
</button> </ElButton>
</div> </template>
</div> </ElTableColumn>
</div> </ElTable>
</div> </div>
</div> </div>
<div <div
v-if="kb.selectedGroupId" v-if="kb.selectedGroupId"
class="mb-4 space-y-3 rounded-2xl bg-surface-soft px-4 py-3" class="mb-4 space-y-3 rounded-2xl bg-surface-soft px-4 py-3"
> >
<div class="flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between"> <div class="kb-toolbar">
<div class="flex flex-wrap items-center gap-2"> <ElButton
<button
v-if="kb.isKbAdmin" v-if="kb.isKbAdmin"
:icon="Refresh"
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
@click="kb.handleBatchClean" @click="kb.handleBatchClean"
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
class="inline-flex items-center gap-2 rounded-full border border-amber-200 bg-surface px-4 py-2 text-sm font-medium text-amber-700 transition-colors hover:bg-amber-50 disabled:cursor-not-allowed disabled:opacity-60"
> >
<RefreshCw class="h-4 w-4" />
{{ kb.batchActionLabel('clean', kb.batchSubmitting, kb.selectedDocuments.length) }} {{ kb.batchActionLabel('clean', kb.batchSubmitting, kb.selectedDocuments.length) }}
</button> </ElButton>
<button <ElButton
v-if="kb.isKbAdmin" v-if="kb.isKbAdmin"
:icon="Refresh"
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
@click="kb.handleBatchSync" @click="kb.handleBatchSync"
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
class="inline-flex items-center gap-2 rounded-full border border-emerald-200 bg-surface px-4 py-2 text-sm font-medium text-emerald-700 transition-colors hover:bg-emerald-50 disabled:cursor-not-allowed disabled:opacity-60"
> >
<RefreshCw class="h-4 w-4" />
{{ kb.batchActionLabel('sync', kb.batchSubmitting, kb.selectedDocuments.length) }} {{ kb.batchActionLabel('sync', kb.batchSubmitting, kb.selectedDocuments.length) }}
</button> </ElButton>
<button <ElButton
@click="kb.handleBatchDelete" type="danger"
:icon="Delete"
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0" :disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
class="inline-flex items-center gap-2 rounded-full border border-rose-200 bg-surface px-4 py-2 text-sm font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60" @click="kb.handleBatchDelete"
> >
<Trash2 class="h-4 w-4" />
{{ kb.batchActionLabel('delete', kb.batchSubmitting, kb.selectedDocuments.length) }} {{ kb.batchActionLabel('delete', kb.batchSubmitting, kb.selectedDocuments.length) }}
</button> </ElButton>
</div>
</div> </div>
<div class="flex flex-wrap items-center gap-3 text-sm text-muted"> <div class="kb-filter-row">
<label class="relative w-full max-w-md"> <div class="kb-doc-search">
<Search class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted" /> <ElInput
<input
v-model.trim="kb.documentKeyword" v-model.trim="kb.documentKeyword"
type="text" clearable
class="w-full rounded-2xl border border-default bg-surface py-2.5 pl-10 pr-4 text-sm text-primary outline-none transition-colors focus:border-brand-300" :prefix-icon="Search"
:placeholder="kb.t('kbWorkspace.documents.searchPlaceholder')" :placeholder="kb.t('kbWorkspace.documents.searchPlaceholder')"
/> />
</label>
<button
v-if="kb.documentKeyword"
type="button"
@click="kb.documentKeyword = ''"
class="inline-flex items-center rounded-xl border border-default bg-surface px-3 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
>
{{ kb.t('kbWorkspace.documents.clearSearch') }}
</button>
</div> </div>
<ElButton
<div class="flex flex-col gap-3 border-t border-default pt-3 xl:flex-row xl:items-center xl:justify-between"> :icon="Select"
<div class="flex flex-wrap items-center gap-2"> :type="kb.isAllFilteredSelected ? 'primary' : 'default'"
<button
@click="kb.toggleSelectAllFiltered"
class="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-muted transition-colors hover:bg-surface hover:text-brand-600"
:class="kb.isAllFilteredSelected ? 'bg-brand-50 text-brand-600' : ''"
:title="kb.isAllFilteredSelected ? kb.t('kbWorkspace.pathUpload.deselectAllFiltered') : kb.t('kbWorkspace.pathUpload.selectAllFiltered')" :title="kb.isAllFilteredSelected ? kb.t('kbWorkspace.pathUpload.deselectAllFiltered') : kb.t('kbWorkspace.pathUpload.selectAllFiltered')"
:aria-label="kb.isAllFilteredSelected ? kb.t('kbWorkspace.pathUpload.deselectAllFiltered') : kb.t('kbWorkspace.pathUpload.selectAllFiltered')" :aria-label="kb.isAllFilteredSelected ? kb.t('kbWorkspace.pathUpload.deselectAllFiltered') : kb.t('kbWorkspace.pathUpload.selectAllFiltered')"
> @click="kb.toggleSelectAllFiltered"
<SquareCheck class="h-[18px] w-[18px]" /> />
</button> <ElRadioGroup v-model="kb.documentStageFilter" class="kb-stage-filter">
<button <ElRadioButton
v-for="tab in kb.stageFilterTabs.filter((item) => item.key !== 'all')" v-for="tab in kb.stageFilterTabs"
:key="tab.key" :key="tab.key"
@click="kb.documentStageFilter = kb.documentStageFilter === tab.key ? 'all' : tab.key" :value="tab.key"
class="inline-flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-medium transition-colors"
:class="kb.documentStageFilter === tab.key
? 'border-brand-200 bg-brand-50 text-brand-700'
: 'border-default bg-surface text-secondary hover:bg-surface-soft'"
> >
<span>{{ tab.label }}</span> {{ tab.label }} {{ tab.count }}
<span class="rounded-full bg-surface-soft px-2 py-0.5 text-xs">{{ tab.count }}</span> </ElRadioButton>
</button> </ElRadioGroup>
</div>
</div> </div>
</div> </div>
<div v-if="!kb.selectedGroupId" class="rounded-2xl border border-dashed border-default px-4 py-12 text-center text-sm text-muted "> <div v-if="!kb.selectedGroupId" class="rounded-2xl border border-dashed border-default px-4 py-12 text-center">
{{ kb.t('kbWorkspace.documents.selectGroup') }} {{ kb.t('kbWorkspace.documents.selectGroup') }}
</div> </div>
<div v-else-if="kb.isDocumentsLoading" class="rounded-2xl border border-dashed border-default px-4 py-12 text-center text-sm text-muted "> <template v-else>
{{ kb.t('kbWorkspace.documents.loadingDocuments') }} <ElTable
</div> v-loading="kb.isDocumentsLoading"
<div v-else-if="kb.filteredDocuments.length === 0" class="rounded-2xl border border-dashed border-default px-4 py-12 text-center text-sm text-muted "> :data="kb.pagedFilteredDocuments"
{{ kb.documentEmptyMessage(kb.documents.length, !!kb.documentKeyword) }} row-key="id"
</div> :row-class-name="documentRowClass(kb.selectedDocumentId)"
<div v-else class="space-y-3"> :empty-text="kb.isDocumentsLoading ? kb.t('kbWorkspace.documents.loadingDocuments') : kb.documentEmptyMessage(kb.documents.length, !!kb.documentKeyword)"
<div
v-for="doc in kb.pagedFilteredDocuments"
:key="doc.id"
class="rounded-2xl border px-4 py-3 transition-colors"
:class="kb.selectedDocumentId === doc.id
? 'border-brand-200 bg-brand-50/50 border-brand-200'
: 'border-default'"
> >
<div class="space-y-3"> <ElTableColumn width="52">
<div class="grid gap-3 lg:grid-cols-[minmax(360px,1fr)_auto] lg:items-start"> <template #default="{ row }">
<div class="flex min-w-0 gap-3"> <ElCheckbox
<label class="mt-1 inline-flex shrink-0 cursor-pointer items-center"> :model-value="kb.selectedDocumentIds.includes(row.id)"
<input @change="kb.toggleDocumentSelection(row.id)"
type="checkbox"
class="h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
:checked="kb.selectedDocumentIds.includes(doc.id)"
@change="kb.toggleDocumentSelection(doc.id)"
/> />
</label> </template>
<div class="min-w-0 flex-1"> </ElTableColumn>
<button <ElTableColumn :label="kb.t('kbWorkspace.documents.title')" min-width="280">
@click="kb.openMarkdownEditor(doc)" <template #default="{ row }">
class="block max-w-full truncate text-left font-semibold text-primary transition-colors hover:text-brand-600 hover:text-brand-600" <ElButton link type="primary" @click="kb.openMarkdownEditor(row as KbDocumentItem)">
> {{ kb.getDocumentDisplayTitle(row as KbDocumentItem) }}
{{ kb.getDocumentDisplayTitle(doc) }} </ElButton>
</button> <div>
<button <ElButton link type="primary" @click="kb.openSourceInfo(row as KbDocumentItem)">
type="button" {{ kb.getDocumentDisplayDescription(row as KbDocumentItem) }}
@click="kb.openSourceInfo(doc)" </ElButton>
class="mt-1 block max-w-full truncate text-left text-sm text-muted transition-colors hover:text-brand-600 hover:text-brand-600"
>
{{ kb.getDocumentDisplayDescription(doc) }}
</button>
<div class="mt-2 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted">
<span class="shrink-0">{{ kb.t('kbWorkspace.documents.versionCount', { count: doc.version_count ?? 0 }) }}</span>
<span v-if="doc.latest_version" class="shrink-0">{{ kb.t('kbWorkspace.documents.currentVersion', { version: doc.latest_version.version_no }) }}</span>
<button
v-if="doc.latest_version"
type="button"
@click="kb.openSourceInfo(doc)"
class="min-w-0 max-w-full truncate text-xs text-muted underline-offset-2 transition-colors hover:text-brand-600 hover:underline hover:text-brand-600"
>
{{ doc.latest_version.source_file_name }}
</button>
</div> </div>
<div <div>
v-if="kb.getDocumentWorkflowState(doc).primaryError" <span>{{ kb.t('kbWorkspace.documents.versionCount', { count: row.version_count ?? 0 }) }}</span>
class="mt-1 max-w-xl text-xs text-rose-500" <span v-if="row.latest_version"> {{ kb.t('kbWorkspace.documents.currentVersion', { version: row.latest_version.version_no }) }}</span>
<ElButton
v-if="row.latest_version"
link
type="primary"
@click="kb.openSourceInfo(row as KbDocumentItem)"
> >
{{ kb.t('kbWorkspace.common.failureReason', { reason: kb.getDocumentWorkflowState(doc).primaryError }) }} {{ row.latest_version.source_file_name }}
</ElButton>
</div> </div>
</div> <ElText v-if="kb.getDocumentWorkflowState(row as KbDocumentItem).primaryError" type="danger">
</div> {{ kb.t('kbWorkspace.common.failureReason', { reason: kb.getDocumentWorkflowState(row as KbDocumentItem).primaryError }) }}
</ElText>
<div class="flex min-w-0 flex-wrap items-center gap-2 lg:justify-end"> </template>
<button </ElTableColumn>
@click="kb.openDocumentDetail(doc.id)" <ElTableColumn min-width="220">
class="inline-flex shrink-0 items-center gap-1 rounded-xl border border-violet-200 px-3 py-2 text-xs font-medium text-violet-700 transition-colors hover:bg-violet-50" <template #default="{ row }">
> <ElTag
<FileText class="h-3.5 w-3.5" /> v-for="badge in kb.getWorkflowBadges(row as KbDocumentItem)"
{{ kb.t('kbWorkspace.documents.viewRecord') }} :key="`${row.id}-${badge.label}`"
</button> class="kb-workflow-tag"
<button effect="light"
@click="kb.triggerUploadForDocument(doc.id)" :type="statusTagType(badge.className)"
class="inline-flex shrink-0 items-center gap-1 rounded-xl border border-brand-200 px-3 py-2 text-xs font-medium text-brand-700 transition-colors hover:bg-brand-50 border-brand-200 hover:bg-brand-50"
>
<Upload class="h-3.5 w-3.5" />
{{ kb.t('kbWorkspace.documents.uploadVersion') }}
</button>
<button
v-if="kb.isKbAdmin"
@click="kb.handleSyncDocument(doc.id)"
:disabled="kb.syncingDocumentId === doc.id || !doc.latest_version"
class="inline-flex shrink-0 items-center gap-1 rounded-xl border border-emerald-200 px-3 py-2 text-xs font-medium text-emerald-700 transition-colors hover:bg-emerald-50 disabled:cursor-not-allowed disabled:opacity-60 border-emerald-200"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ kb.syncingDocumentId === doc.id ? kb.t('kbWorkspace.documents.syncingDify') : kb.t('kbWorkspace.documents.syncDify') }}
</button>
<button
@click="kb.handleDeleteDocument(doc)"
class="inline-flex shrink-0 items-center gap-1 rounded-xl border border-rose-200 px-3 py-2 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 border-rose-200 hover:bg-rose-50"
>
<Trash2 class="h-3.5 w-3.5" />
{{ kb.t('kbWorkspace.common.delete') }}
</button>
</div>
</div>
<div class="grid gap-3 border-t border-default pt-3 lg:grid-cols-[minmax(260px,1fr)_auto] lg:items-center">
<span class="min-w-0 text-xs text-muted">
{{ kb.t('kbWorkspace.documents.updatedAt', { time: kb.formatDateTime(doc.updated_at) }) }}
</span>
<div class="flex min-w-0 flex-wrap items-center gap-2 lg:justify-end">
<div
v-for="badge in kb.getWorkflowBadges(doc)"
:key="`${doc.id}-${badge.label}`"
class="inline-flex shrink-0 items-center rounded-full border px-3 py-1 text-xs font-semibold"
:class="badge.className"
> >
{{ badge.label }}:{{ badge.value }} {{ badge.label }}:{{ badge.value }}
</ElTag>
</template>
</ElTableColumn>
<ElTableColumn min-width="160">
<template #default="{ row }">
{{ kb.t('kbWorkspace.documents.updatedAt', { time: kb.formatDateTime(row.updated_at) }) }}
</template>
</ElTableColumn>
<ElTableColumn width="280" align="right" fixed="right">
<template #default="{ row }">
<div class="kb-row-actions">
<ElButton link type="primary" :icon="Document" @click="kb.openDocumentDetail(row.id)">
{{ kb.t('kbWorkspace.documents.viewRecord') }}
</ElButton>
<ElButton link type="primary" :icon="Upload" @click="kb.triggerUploadForDocument(row.id)">
{{ kb.t('kbWorkspace.documents.uploadVersion') }}
</ElButton>
<ElButton
v-if="kb.isKbAdmin"
link
type="primary"
:icon="Refresh"
:loading="kb.syncingDocumentId === row.id"
:disabled="kb.syncingDocumentId === row.id || !row.latest_version"
@click="kb.handleSyncDocument(row.id)"
>
{{ kb.syncingDocumentId === row.id ? kb.t('kbWorkspace.documents.syncingDify') : kb.t('kbWorkspace.documents.syncDify') }}
</ElButton>
<ElButton link type="danger" :icon="Delete" @click="kb.handleDeleteDocument(row as KbDocumentItem)">
{{ kb.t('kbWorkspace.common.delete') }}
</ElButton>
</div> </div>
</div> </template>
</div> </ElTableColumn>
</div> </ElTable>
</div> <div v-if="kb.filteredDocuments.length > 0" class="kb-doc-pagination">
<PaginationBar <ElPagination
v-if="kb.filteredDocuments.length > 0" v-model:current-page="kb.documentListPage"
v-model:page="kb.documentListPage"
v-model:page-size="kb.documentListPageSize" v-model:page-size="kb.documentListPageSize"
:total="kb.filteredDocuments.length" :total="kb.filteredDocuments.length"
:pages="kb.filteredDocumentTotalPages" :page-sizes="[...kb.DOCUMENT_PAGE_SIZE_OPTIONS]"
:page-size-options="[...kb.DOCUMENT_PAGE_SIZE_OPTIONS]" layout="total, sizes, prev, pager, next"
background
/> />
</div> </div>
</template>
</div> </div>
</section> </section>
</template> </template>
@@ -489,4 +497,91 @@ const kb = useKbWorkspace({ embedded: props.embedded });
<KbWorkspaceOverlays :kb="kb" /> <KbWorkspaceOverlays :kb="kb" />
</template> </template>
<style scoped>
.kb-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
}
.kb-toolbar :deep(.el-button) {
margin-left: 0;
}
.kb-stat-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
width: 100%;
}
@media (min-width: 640px) {
.kb-stat-grid {
grid-template-columns: repeat(5, minmax(0, 1fr));
}
}
@media (min-width: 1024px) {
.kb-stat-grid {
min-width: 520px;
}
}
.kb-stat-grid :deep(.el-button.kb-stat-tile) {
width: 100%;
height: auto;
margin: 0;
white-space: normal;
flex-direction: column;
align-items: flex-start;
justify-content: center;
}
.kb-filter-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
}
.kb-filter-row :deep(.el-button) {
margin-left: 0;
}
.kb-doc-search {
width: 16rem;
max-width: 100%;
}
.kb-stage-filter {
flex-wrap: wrap;
}
.kb-doc-pagination {
display: flex;
justify-content: flex-end;
margin-top: 16px;
padding-top: 12px;
border-top: 1px solid var(--el-border-color-lighter);
}
.kb-row-actions {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 4px;
}
.kb-row-actions :deep(.el-button) {
margin-left: 0;
}
.kb-workflow-tag {
margin: 0 4px 4px 0;
}
:deep(.kb-doc-row--current) {
--el-table-tr-bg-color: var(--el-fill-color-light);
}
</style>
@@ -2,7 +2,7 @@
* features/order-delivery-reply/views/OrderDeliveryReplyPage.vue * features/order-delivery-reply/views/OrderDeliveryReplyPage.vue
* 用途:订单交期回复工作台操作页——筛选分页、单行/联合回复批次、单行/批量通知、手动同步。 * 用途:订单交期回复工作台操作页——筛选分页、单行/联合回复批次、单行/批量通知、手动同步。
* 依赖:api/orderDeliveryReply.api(统一 requestJson)、useMessage、auth store(manage/access 权限)、 * 依赖:api/orderDeliveryReply.api(统一 requestJson)、useMessage、auth store(manage/access 权限)、
* shared DeleteConfirmDialog(批量通知二次确认)、PaginationBar。 * element-plus、PaginationBar。
* 逻辑:所有数据只读本地快照;保存与通知是两步(联合回复只保存,批量通知才发送并锁定); * 逻辑:所有数据只读本地快照;保存与通知是两步(联合回复只保存,批量通知才发送并锁定);
* 保存/通知成功后即时刷新列表(需求 §9);仅 access 用户隐藏全部写操作。 * 保存/通知成功后即时刷新列表(需求 §9);仅 access 用户隐藏全部写操作。
* 回复弹窗数量守恒(2026-09-23 由「超额仅提醒」修订):每行各批次合计必须等于订单数量 * 回复弹窗数量守恒(2026-09-23 由「超额仅提醒」修订):每行各批次合计必须等于订单数量
@@ -32,9 +32,9 @@
* 表格对齐(2026-10-09):除交期回复列(批次条按既定左对齐布局)外,全列内容水平居中、 * 表格对齐(2026-10-09):除交期回复列(批次条按既定左对齐布局)外,全列内容水平居中、
* 行内容垂直居中,列头文字全部居中;交期回复状态徽标统一等宽(min-w-68px)。 * 行内容垂直居中,列头文字全部居中;交期回复状态徽标统一等宽(min-w-68px)。
* 设计系统(docs/ui/DESIGN_SYSTEM.md):根节点挂 page-shell;区块容器用 surface-panel; * 设计系统(docs/ui/DESIGN_SYSTEM.md):根节点挂 page-shell;区块容器用 surface-panel;
* 弹窗用 dialog-overlay/panel/header/body/footer;输入用 input-field/select-field; * 筛选和回复弹窗用 Element Plus;冻结列和批次条就地编辑保持原表格。
* 状态与交互色一律走 --status-* 令牌(badge-*/bg-row-*/frozen-cell-*),品牌强调用 brand-*。 * 状态与交互色一律走 --status-* 令牌(badge-*/bg-row-*/frozen-cell-*),品牌强调用 brand-*。
* 批量通知确认使用共享 DeleteConfirmDialog(confirmTone=primary),不再用原生 window.confirm。 * 批量通知确认使用 ElMessageBox.confirm。
*/ */
<script setup lang="ts"> <script setup lang="ts">
@@ -45,8 +45,21 @@ import { useAuthStore } from '@/features/auth/stores/auth.store';
import { useMessage } from '@/shared/composables/useMessage'; import { useMessage } from '@/shared/composables/useMessage';
import { requestJson } from '@/shared/api/client'; import { requestJson } from '@/shared/api/client';
import PaginationBar from '@/shared/components/PaginationBar.vue'; import PaginationBar from '@/shared/components/PaginationBar.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue'; import { Download } from '@element-plus/icons-vue';
import { ChevronDown, ChevronUp, Download, Plus } from 'lucide-vue-next'; import {
ElButton,
ElCheckbox,
ElDatePicker,
ElDialog,
ElInput,
ElMessageBox,
ElOption,
ElSelect,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/shared/styles/element-theme.css';
import { ChevronDown, ChevronUp, Plus } from 'lucide-vue-next';
import { import {
ORDER_DELIVERY_REPLY_MANAGE_PERMISSION, ORDER_DELIVERY_REPLY_MANAGE_PERMISSION,
} from '@/features/order-delivery-reply/constants'; } from '@/features/order-delivery-reply/constants';
@@ -242,6 +255,24 @@ function applyQuickDate() {
modalLines.value.forEach((entry) => entry.batches.forEach((batch) => { batch.planned_date = quickDate.value; })); modalLines.value.forEach((entry) => entry.batches.forEach((batch) => { batch.planned_date = quickDate.value; }));
} }
/**
* 日期选择器清空后写回空字符串,保持筛选和批次交期的原有字符串。
* @param value - 日期选择器回传值
* @returns YYYY-MM-DD 或空字符串
*/
function dateText(value: unknown): string {
return typeof value === 'string' ? value : '';
}
/**
* 筛选状态下拉。清空后回到全部,并立即查询。
* @param value - 已回复、未完全回复或空
*/
function onFilterStatus(value: unknown): void {
filters.status = value === 'replied' || value === 'not_fully_replied' ? value : '';
doSearch();
}
/** /**
* 行填写问题文案(实时校验,2026-09-23): * 行填写问题文案(实时校验,2026-09-23):
* [规则 1] 已填数量但未填交期的批次 → 「第 N 批未填交期」; * [规则 1] 已填数量但未填交期的批次 → 「第 N 批未填交期」;
@@ -476,12 +507,26 @@ async function doExportExcel() {
/* ============ 通知 ============ */ /* ============ 通知 ============ */
const notifying = ref(false); const notifying = ref(false);
const notifyConfirmVisible = ref(false);
/** 批量通知入口:先弹共享 DeleteConfirmDialog(primary 语气)二次确认,确认后执行 doNotifyBatch。 */ /**
function requestNotifyBatch() { * 批量通知入口。确认后执行 doNotifyBatch,取消不发送。
*/
async function requestNotifyBatch() {
if (!notifiableSelected.value.length) return; if (!notifiableSelected.value.length) return;
notifyConfirmVisible.value = true; try {
await ElMessageBox.confirm(
t('workspace.orderDeliveryReply.notifyBatchConfirm', { count: notifiableSelected.value.length }),
t('workspace.orderDeliveryReply.batchNotify'),
{
type: 'warning',
confirmButtonText: t('common.deleteDialog.confirm'),
cancelButtonText: t('common.deleteDialog.cancel'),
},
);
} catch {
return;
}
await doNotifyBatch();
} }
/** 批量通知:部分成功 warning 汇总,全部失败 error;提示后刷新列表让锁定即时生效。 */ /** 批量通知:部分成功 warning 汇总,全部失败 error;提示后刷新列表让锁定即时生效。 */
@@ -608,9 +653,9 @@ onMounted(async () => {
{{ latestSyncText }} {{ latestSyncText }}
</span> </span>
<div class="flex-1" /> <div class="flex-1" />
<button v-if="canManage" type="button" class="btn-ghost" :disabled="syncing" @click="doSync"> <ElButton v-if="canManage" :disabled="syncing" :loading="syncing" @click="doSync">
{{ syncing ? t('workspace.orderDeliveryReply.syncing') : t('workspace.orderDeliveryReply.syncNow') }} {{ syncing ? t('workspace.orderDeliveryReply.syncing') : t('workspace.orderDeliveryReply.syncNow') }}
</button> </ElButton>
</div> </div>
<!-- 搜索区:合并关键词搜索(订单/产品/客户命中任一字段),shrink-0 防压缩;surface-panel 为设计系统 L2 区块容器(无 hover 阴影)。 <!-- 搜索区:合并关键词搜索(订单/产品/客户命中任一字段),shrink-0 防压缩;surface-panel 为设计系统 L2 区块容器(无 hover 阴影)。
@@ -618,40 +663,55 @@ onMounted(async () => {
字段含义由输入框 placeholder / 选项承担,无障碍语义用 aria-label 保留(复用 filterKeyword 等 i18n 键)。 字段含义由输入框 placeholder / 选项承担,无障碍语义用 aria-label 保留(复用 filterKeyword 等 i18n 键)。
输入控件显式 text-sm(14px)+h-9(36px):与 .contract-filter-input(14px/36px/圆角8px)渲染规格逐项一致 --> 输入控件显式 text-sm(14px)+h-9(36px):与 .contract-filter-input(14px/36px/圆角8px)渲染规格逐项一致 -->
<div class="surface-panel flex shrink-0 flex-wrap items-center gap-3 px-4 py-2.5"> <div class="surface-panel flex shrink-0 flex-wrap items-center gap-3 px-4 py-2.5">
<input v-model="filters.keyword" class="input-field h-9 w-auto min-w-[340px] rounded-lg px-3 py-1 text-sm" :placeholder="t('workspace.orderDeliveryReply.filterKeywordPh')" :aria-label="t('workspace.orderDeliveryReply.filterKeyword')" @keyup.enter="doSearch" /> <ElInput
<input v-model="filters.order_date" type="date" class="input-field h-9 w-auto rounded-lg px-3 py-1 text-sm" :aria-label="t('workspace.orderDeliveryReply.filterOrderDate')" /> v-model="filters.keyword"
<!-- 状态筛选选择即生效(无需再点查询);其余条件仍由「查询」统一提交 --> class="order-reply-keyword"
<select v-model="filters.status" class="select-field h-9 w-auto min-w-[140px] rounded-lg px-3 py-1 text-sm" :aria-label="t('workspace.orderDeliveryReply.filterStatus')" @change="doSearch"> clearable
<option value="">{{ t('workspace.orderDeliveryReply.statusAll') }}</option> :placeholder="t('workspace.orderDeliveryReply.filterKeywordPh')"
<option value="replied">{{ t('workspace.orderDeliveryReply.statusReplied') }}</option> :aria-label="t('workspace.orderDeliveryReply.filterKeyword')"
<option value="not_fully_replied">{{ t('workspace.orderDeliveryReply.statusNotFully') }}</option> @keyup.enter="doSearch"
</select> />
<!-- 查询/重置:text-sm(14px)+font-semibold(600)+h-9(36px),与合同付款预警 .contract-filter-submit 完全一致 --> <ElDatePicker
<button type="button" class="btn-primary h-9 text-sm font-semibold" @click="doSearch">{{ t('workspace.orderDeliveryReply.search') }}</button> :model-value="filters.order_date || undefined"
<button type="button" class="btn-ghost h-9 text-sm font-semibold" @click="doReset">{{ t('workspace.orderDeliveryReply.reset') }}</button> type="date"
value-format="YYYY-MM-DD"
:aria-label="t('workspace.orderDeliveryReply.filterOrderDate')"
@update:model-value="filters.order_date = dateText($event)"
/>
<ElSelect
class="order-reply-status"
:model-value="filters.status || undefined"
clearable
:placeholder="t('workspace.orderDeliveryReply.statusAll')"
:aria-label="t('workspace.orderDeliveryReply.filterStatus')"
@update:model-value="onFilterStatus"
>
<ElOption value="replied" :label="t('workspace.orderDeliveryReply.statusReplied')" />
<ElOption value="not_fully_replied" :label="t('workspace.orderDeliveryReply.statusNotFully')" />
</ElSelect>
<ElButton type="primary" @click="doSearch">{{ t('workspace.orderDeliveryReply.search') }}</ElButton>
<ElButton @click="doReset">{{ t('workspace.orderDeliveryReply.reset') }}</ElButton>
</div> </div>
<!-- 工具栏:全选 + 联合回复 + 批量通知(shrink-0 防压缩,py-2 紧凑高度) --> <!-- 工具栏:全选 + 联合回复 + 批量通知(shrink-0 防压缩,py-2 紧凑高度) -->
<div class="surface-panel flex shrink-0 flex-wrap items-center gap-3 px-4 py-2"> <div class="surface-panel flex shrink-0 flex-wrap items-center gap-3 px-4 py-2">
<label class="flex items-center gap-2 text-primary"> <ElCheckbox :model-value="allChecked" :indeterminate="someChecked" @change="togglePageAll(Boolean($event))">
<input type="checkbox" class="admin-checkbox" :checked="allChecked" :indeterminate.prop="someChecked" @change="togglePageAll(($event.target as HTMLInputElement).checked)" />
{{ t('workspace.orderDeliveryReply.selectAll') }} {{ t('workspace.orderDeliveryReply.selectAll') }}
</label> </ElCheckbox>
<span class="text-muted">{{ t('workspace.orderDeliveryReply.selectedCount', { count: selectedLines.length }) }}</span> <span class="text-muted">{{ t('workspace.orderDeliveryReply.selectedCount', { count: selectedLines.length }) }}</span>
<template v-if="canManage"> <template v-if="canManage">
<button type="button" class="btn-primary h-9 text-sm font-semibold" :disabled="selectedLines.length === 0" @click="openBatchReply"> <ElButton type="primary" :disabled="selectedLines.length === 0" @click="openBatchReply">
{{ t('workspace.orderDeliveryReply.batchReply') }} {{ t('workspace.orderDeliveryReply.batchReply') }}
</button> </ElButton>
<button type="button" class="btn-primary h-9 text-sm font-semibold" :disabled="notifiableSelected.length === 0 || notifying" @click="requestNotifyBatch"> <ElButton type="primary" :disabled="notifiableSelected.length === 0 || notifying" :loading="notifying" @click="requestNotifyBatch">
{{ t('workspace.orderDeliveryReply.batchNotify') }} {{ t('workspace.orderDeliveryReply.batchNotify') }}
</button> </ElButton>
</template> </template>
<div class="flex-1" /> <div class="flex-1" />
<!-- 导出 Excel(2026-10-09 增补,原提示文字胶囊取消):按当前筛选导出全部行 --> <!-- 导出 Excel(2026-10-09 增补,原提示文字胶囊取消):按当前筛选导出全部行 -->
<button type="button" class="btn-primary h-9 text-sm font-semibold" :disabled="exporting" @click="doExportExcel"> <ElButton type="primary" :icon="Download" :disabled="exporting" :loading="exporting" @click="doExportExcel">
<Download class="h-4 w-4" aria-hidden="true" />
{{ t('workspace.orderDeliveryReply.exportExcel') }} {{ t('workspace.orderDeliveryReply.exportExcel') }}
</button> </ElButton>
</div> </div>
<!-- 列表 --> <!-- 列表 -->
@@ -864,67 +924,126 @@ onMounted(async () => {
@update:page-size="changePageSize" @update:page-size="changePageSize"
/> />
<!-- 回复弹窗:dialog-overlay/panel/header/body/footer 设计系统 L2 结构 --> <ElDialog
<div v-if="modalVisible" class="dialog-overlay items-center" @click.self="modalVisible = false"> v-model="modalVisible"
<div class="dialog-panel max-h-[88vh] w-[min(960px,94vw)]"> :title="modalTitle"
<div class="dialog-header"> width="960px"
<h3 class="font-bold text-primary">{{ modalTitle }}</h3> align-center
<button type="button" class="btn-ghost h-8 w-8 px-0 text-lg leading-none" @click="modalVisible = false">×</button> append-to-body
:close-on-click-modal="false"
>
<div v-if="modalMode === 'batch'" class="order-reply-quick">
<span>{{ t('workspace.orderDeliveryReply.quickDate') }}</span>
<ElDatePicker
:model-value="quickDate || undefined"
type="date"
value-format="YYYY-MM-DD"
@update:model-value="quickDate = dateText($event)"
/>
<ElButton @click="applyQuickDate">{{ t('workspace.orderDeliveryReply.applyQuickDate') }}</ElButton>
<span>{{ t('workspace.orderDeliveryReply.modalHint') }}</span>
</div> </div>
<div class="dialog-body"> <div v-for="entry in modalLines" :key="lineKey(entry.line)" class="order-reply-line">
<!-- 快速统一交期:仅联合回复弹窗显示;单行回复/修改回复弹窗已取消该区(2026-10-07),直接逐批次填写 --> <div class="order-reply-line__head">
<div v-if="modalMode === 'batch'" class="flex flex-wrap items-end gap-3 rounded-xl border border-default bg-surface-soft px-4 py-3"> <span class="order-reply-line__no">{{ entry.line.order_no }}</span>
<label class="flex flex-col gap-1 text-muted">
{{ t('workspace.orderDeliveryReply.quickDate') }}
<input v-model="quickDate" type="date" class="input-field h-9 w-auto rounded-lg px-3 py-1.5" />
</label>
<button type="button" class="btn-secondary btn-sm h-9" @click="applyQuickDate">
{{ t('workspace.orderDeliveryReply.applyQuickDate') }}
</button>
<span class="text-muted">{{ t('workspace.orderDeliveryReply.modalHint') }}</span>
</div>
<!-- 每行批次编辑器 -->
<div v-for="entry in modalLines" :key="lineKey(entry.line)" class="overflow-hidden rounded-xl border border-default">
<div class="flex flex-wrap items-center gap-2 bg-surface-soft px-3 py-2">
<span class="rounded bg-surface-strong px-2 py-0.5 font-semibold text-primary">{{ entry.line.order_no }}</span>
<span>{{ t('workspace.orderDeliveryReply.itemLabel', { item: entry.line.line_no }) }}</span> <span>{{ t('workspace.orderDeliveryReply.itemLabel', { item: entry.line.line_no }) }}</span>
<span class="text-muted">{{ entry.line.customer_no }} · {{ entry.line.customer_short_name }}</span> <span>{{ entry.line.customer_no }} · {{ entry.line.customer_short_name }}</span>
<span class="text-muted">{{ entry.line.part_no }} · {{ entry.line.part_name }}</span> <span>{{ entry.line.part_no }} · {{ entry.line.part_name }}</span>
<span class="ml-auto whitespace-nowrap"> <span class="order-reply-line__qty">
{{ t('workspace.orderDeliveryReply.orderQtyLabel', { qty: entry.line.qty ?? 0, unit: entry.line.unit || '' }) }} {{ t('workspace.orderDeliveryReply.orderQtyLabel', { qty: entry.line.qty ?? 0, unit: entry.line.unit || '' }) }}
</span> </span>
</div> </div>
<div class="flex flex-col gap-2 px-3 py-3"> <div class="order-reply-line__body">
<div v-for="(batch, idx) in entry.batches" :key="idx" class="grid grid-cols-[170px_120px_1fr_40px] items-center gap-2"> <div v-for="(batch, idx) in entry.batches" :key="idx" class="order-reply-batch">
<input v-model="batch.planned_date" type="date" class="input-field h-9 rounded-lg px-2 py-1.5" /> <ElDatePicker
<input v-model="batch.qty" type="number" min="0" :placeholder="t('workspace.orderDeliveryReply.qtyPh')" class="input-field h-9 rounded-lg px-2 py-1.5" /> :model-value="batch.planned_date || undefined"
<input v-model="batch.remark" :placeholder="t('workspace.orderDeliveryReply.remarkPh')" class="input-field h-9 rounded-lg px-2 py-1.5" /> type="date"
<button type="button" class="btn-danger btn-sm" :title="t('workspace.orderDeliveryReply.removeBatch')" @click="entry.batches.splice(idx, 1)">✕</button> value-format="YYYY-MM-DD"
</div> @update:model-value="batch.planned_date = dateText($event)"
<button type="button" class="w-full rounded-lg border border-dashed border-default py-2 text-brand-600 transition-colors hover-surface-soft" @click="entry.batches.push({ planned_date: '', qty: '', remark: '' })">
{{ t('workspace.orderDeliveryReply.addBatch') }}
</button>
<!-- 行级实时校验提示:缺交期/缺数量按批次序号指出,合计不等给出已填/应填;随填写实时切换 -->
<p v-if="lineIssueText(entry)" class="text-status-error">{{ lineIssueText(entry) }}</p>
</div>
</div>
</div>
<div class="dialog-footer">
<button type="button" class="btn-secondary" @click="modalVisible = false">{{ t('common.cancel') }}</button>
<button type="button" class="btn-primary" :disabled="saving" @click="saveReplies">
{{ saving ? t('workspace.orderDeliveryReply.saving') : t('workspace.orderDeliveryReply.saveReply') }}
</button>
</div>
</div>
</div>
<!-- 批量通知二次确认:共享 DeleteConfirmDialog(primary 语气,非删除;确认/取消文案用组件默认 i18n) -->
<DeleteConfirmDialog
v-model="notifyConfirmVisible"
:title="t('workspace.orderDeliveryReply.batchNotify')"
:message="t('workspace.orderDeliveryReply.notifyBatchConfirm', { count: notifiableSelected.length })"
confirm-tone="primary"
@confirm="doNotifyBatch"
/> />
<ElInput v-model="batch.qty" type="number" :placeholder="t('workspace.orderDeliveryReply.qtyPh')" />
<ElInput v-model="batch.remark" :placeholder="t('workspace.orderDeliveryReply.remarkPh')" />
<ElButton link type="danger" :title="t('workspace.orderDeliveryReply.removeBatch')" @click="entry.batches.splice(idx, 1)">✕</ElButton>
</div>
<ElButton class="order-reply-add" @click="entry.batches.push({ planned_date: '', qty: '', remark: '' })">
{{ t('workspace.orderDeliveryReply.addBatch') }}
</ElButton>
<p v-if="lineIssueText(entry)" class="order-reply-issue">{{ lineIssueText(entry) }}</p>
</div>
</div>
<template #footer>
<ElButton @click="modalVisible = false">{{ t('common.cancel') }}</ElButton>
<ElButton type="primary" :loading="saving" :disabled="saving" @click="saveReplies">
{{ saving ? t('workspace.orderDeliveryReply.saving') : t('workspace.orderDeliveryReply.saveReply') }}
</ElButton>
</template>
</ElDialog>
</div> </div>
</template> </template>
<style scoped>
.order-reply-keyword {
width: min(100%, 22rem);
}
.order-reply-status {
width: 11rem;
}
.order-reply-quick,
.order-reply-line__head,
.order-reply-batch {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.order-reply-quick,
.order-reply-line {
margin-bottom: 12px;
}
.order-reply-line {
overflow: hidden;
border: 1px solid var(--el-border-color-lighter);
border-radius: var(--el-border-radius-base);
}
.order-reply-line__head {
padding: 8px 12px;
background: var(--el-fill-color-light);
}
.order-reply-line__no {
padding: 0 8px;
border-radius: 4px;
background: var(--el-fill-color);
font-weight: 600;
}
.order-reply-line__qty {
margin-left: auto;
}
.order-reply-line__body {
display: flex;
flex-direction: column;
gap: 8px;
padding: 12px;
}
.order-reply-batch {
display: grid;
grid-template-columns: 170px 120px minmax(0, 1fr) 40px;
}
.order-reply-add {
width: 100%;
}
.order-reply-issue {
margin: 0;
color: var(--el-color-danger);
}
</style>
@@ -1,26 +1,90 @@
<!-- <!--
features/shipping-notice/customers/ShippingCustomersPage.vue features/shipping-notice/customers/ShippingCustomersPage.vue
用途:货代客户主数据管理入口,提供列表、识别证据和期初导入工作台。 用途:货代客户主数据管理入口,提供列表、识别证据和期初导入工作台。
依赖:useShippingCustomersAdmin、PaginationBar、三个域内组件。 依赖:useShippingCustomersAdmin、element-plus、域内弹窗与影子质量面板。
逻辑:路由加载后查询客户;页面只组合展示与事件,业务状态由 composable 管理。 逻辑:路由加载后查询客户;页面只组合展示与事件,业务状态由 composable 管理。
Element 样式只在本页引入;停用与证据变更的确认在 composable 内完成。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, watch } from 'vue'; import { onMounted, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { Edit, FileSpreadsheet, Fingerprint, GitMerge, History, Plus, Search, Trash2, UserX } from 'lucide-vue-next'; import {
Clock,
Connection,
Delete,
Document,
Edit,
Key,
Plus,
Remove,
Search,
} from '@element-plus/icons-vue';
import {
ElButton,
ElInput,
ElLoading,
ElOption,
ElPagination,
ElSelect,
ElSpace,
ElTable,
ElTableColumn,
ElTag,
ElText,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/shared/styles/element-theme.css';
import CustomerDeleteDialog from './components/CustomerDeleteDialog.vue'; import CustomerDeleteDialog from './components/CustomerDeleteDialog.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import CustomerMergeDialog from './components/CustomerMergeDialog.vue'; import CustomerMergeDialog from './components/CustomerMergeDialog.vue';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import CustomerFormModal from './components/CustomerFormModal.vue'; import CustomerFormModal from './components/CustomerFormModal.vue';
import CustomerIdentifiersPanel from './components/CustomerIdentifiersPanel.vue'; import CustomerIdentifiersPanel from './components/CustomerIdentifiersPanel.vue';
import CustomerImportDialog from './components/CustomerImportDialog.vue'; import CustomerImportDialog from './components/CustomerImportDialog.vue';
import CustomerShadowQualityPanel from './components/CustomerShadowQualityPanel.vue'; import CustomerShadowQualityPanel from './components/CustomerShadowQualityPanel.vue';
import CustomerLifecyclePanel from './components/CustomerLifecyclePanel.vue'; import CustomerLifecyclePanel from './components/CustomerLifecyclePanel.vue';
import { useShippingCustomersAdmin } from './composables/useShippingCustomersAdmin'; import { useShippingCustomersAdmin } from './composables/useShippingCustomersAdmin';
import type { ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
const vLoading = ElLoading.directive;
const { t } = useI18n(); const { t } = useI18n();
const admin = useShippingCustomersAdmin(); const admin = useShippingCustomersAdmin();
const pageSizes = [10, 20, 50, 100];
/**
* 状态筛选。清空时写回空字符串,列表仍按全部状态查询。
* @param value - 选中的状态;清空为 undefined
*/
function onStatusFilter(value: string | undefined): void {
admin.statusFilter.value = value ?? '';
void admin.searchCustomers();
}
/**
* 翻页。每页条数不变,监听会重新拉列表。
* @param page - 1-based 页码
*/
function onPageChange(page: number): void {
admin.page.value = page;
}
/**
* 修改每页条数并回到第一页,与原分页条一致。
* @param size - 新的每页条数
*/
function onPageSizeChange(size: number): void {
admin.pageSize.value = size;
admin.page.value = 1;
}
/**
* 状态标签颜色:启用成功,停用信息,归并警告。
* @param status - 客户状态
*/
function statusTagType(status: string): 'success' | 'info' | 'warning' {
if (status === 'active') return 'success';
if (status === 'merged') return 'warning';
return 'info';
}
/** 页码或每页条数改变时重新读取服务端分页。 */ /** 页码或每页条数改变时重新读取服务端分页。 */
watch([admin.page, admin.pageSize], () => { void admin.loadCustomers(); }); watch([admin.page, admin.pageSize], () => { void admin.loadCustomers(); });
@@ -30,67 +94,116 @@ onMounted(() => { void Promise.all([admin.loadCustomers(), admin.loadShadowRepor
<template> <template>
<section class="admin-table-section animate-fade-in-up"> <section class="admin-table-section animate-fade-in-up">
<div class="admin-table-header admin-table-header--stacked"> <div class="admin-table-header admin-table-header--stacked">
<div><h2 class="section-title">{{ t('admin.shippingCustomers.title') }}</h2><p class="section-desc mt-1">{{ t('admin.shippingCustomers.subtitle') }}</p></div> <div>
<div class="flex flex-wrap gap-2"> <h2 class="section-title">{{ t('admin.shippingCustomers.title') }}</h2>
<button type="button" class="btn-ghost flex items-center gap-2" @click="admin.openImport"><FileSpreadsheet class="w-4 h-4" />{{ t('admin.shippingCustomers.importButton') }}</button> <p class="section-desc mt-1">{{ t('admin.shippingCustomers.subtitle') }}</p>
<button type="button" class="btn-primary flex items-center gap-2" @click="admin.openCreateCustomer"><Plus class="w-4 h-4" />{{ t('admin.shippingCustomers.add') }}</button>
</div> </div>
<ElSpace wrap>
<ElButton :icon="Document" @click="admin.openImport">{{ t('admin.shippingCustomers.importButton') }}</ElButton>
<ElButton type="primary" :icon="Plus" @click="admin.openCreateCustomer">{{ t('admin.shippingCustomers.add') }}</ElButton>
</ElSpace>
</div> </div>
<div class="admin-table-filters--inline gap-3"> <div class="customers-filters">
<div class="relative flex-1 min-w-[220px] max-w-md"> <ElInput
<Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted" /> v-model="admin.searchQuery.value"
<input v-model="admin.searchQuery.value" type="search" class="admin-table-filter-input w-full pl-9" :placeholder="t('admin.shippingCustomers.searchPlaceholder')" @keyup.enter="admin.searchCustomers" /> clearable
</div> class="customers-filter-search"
<select v-model="admin.statusFilter.value" class="admin-table-filter-input" @change="admin.searchCustomers"> :prefix-icon="Search"
<option value="">{{ t('admin.shippingCustomers.status.all') }}</option> :placeholder="t('admin.shippingCustomers.searchPlaceholder')"
<option value="active">{{ t('admin.shippingCustomers.status.active') }}</option> @keyup.enter="admin.searchCustomers"
<option value="inactive">{{ t('admin.shippingCustomers.status.inactive') }}</option> />
<option value="merged">{{ t('admin.shippingCustomers.status.merged') }}</option> <ElSelect
</select> class="customers-filter-status"
<button type="button" class="btn-ghost" @click="admin.searchCustomers">{{ t('admin.shippingCustomers.search') }}</button> :model-value="admin.statusFilter.value || undefined"
clearable
:placeholder="t('admin.shippingCustomers.status.all')"
@update:model-value="onStatusFilter"
>
<ElOption value="active" :label="t('admin.shippingCustomers.status.active')" />
<ElOption value="inactive" :label="t('admin.shippingCustomers.status.inactive')" />
<ElOption value="merged" :label="t('admin.shippingCustomers.status.merged')" />
</ElSelect>
<ElButton @click="admin.searchCustomers">{{ t('admin.shippingCustomers.search') }}</ElButton>
</div> </div>
<div v-if="admin.isLoading.value" class="flex justify-center py-20"><div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" /></div> <ElTable
<div v-else class="admin-table-wrap"> v-loading="admin.isLoading.value"
<table class="admin-table min-w-[860px]"> :data="admin.customers.value"
<thead><tr> row-key="id"
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.name') }}</th> :empty-text="t('admin.shippingCustomers.empty')"
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.shortCode') }}</th> >
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.status') }}</th> <ElTableColumn :label="t('admin.shippingCustomers.headers.name')" min-width="180">
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.odmIds') }}</th> <template #default="{ row }">
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.identityEvidences') }}</th> <div>{{ (row as ShippingCustomerRow).standard_name }}</div>
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.notices') }}</th> <ElText v-if="(row as ShippingCustomerRow).remark" type="info" size="small">{{ (row as ShippingCustomerRow).remark }}</ElText>
<th class="px-5 py-4 text-right">{{ t('admin.shippingCustomers.headers.actions') }}</th> </template>
</tr></thead> </ElTableColumn>
<tbody> <ElTableColumn :label="t('admin.shippingCustomers.headers.shortCode')" min-width="100">
<tr v-if="admin.customers.value.length === 0"><td colspan="7" class="admin-table-empty px-5">{{ t('admin.shippingCustomers.empty') }}</td></tr> <template #default="{ row }">{{ (row as ShippingCustomerRow).short_code }}</template>
<tr v-for="customer in admin.customers.value" :key="customer.id"> </ElTableColumn>
<td class="px-5 py-4"><div class="font-medium text-primary">{{ customer.standard_name }}</div><div v-if="customer.remark" class="text-xs text-muted truncate max-w-sm">{{ customer.remark }}</div></td> <ElTableColumn :label="t('admin.shippingCustomers.headers.status')" min-width="100">
<td class="px-5 py-4 font-mono text-sm">{{ customer.short_code }}</td> <template #default="{ row }">
<td class="px-5 py-4"><span class="text-sm" :class="customer.status === 'active' ? 'text-emerald-600' : 'text-muted'">{{ t(`admin.shippingCustomers.status.${customer.status}`) }}</span></td> <ElTag :type="statusTagType((row as ShippingCustomerRow).status)" effect="light">
<td class="px-5 py-4 text-sm"> {{ t(`admin.shippingCustomers.status.${(row as ShippingCustomerRow).status}`) }}
<span v-if="customer.odm_ids?.length" class="font-mono text-xs">{{ customer.odm_ids.join(', ') }}</span> </ElTag>
<span v-else class="text-xs text-muted">{{ t('admin.shippingCustomers.fields.odmIdsUnlimited') }}</span> </template>
</td> </ElTableColumn>
<td class="px-5 py-4 text-sm">{{ customer.identity_evidence_count || 0 }}</td> <ElTableColumn :label="t('admin.shippingCustomers.headers.odmIds')" min-width="140">
<td class="px-5 py-4 text-sm">{{ customer.notice_count }}</td> <template #default="{ row }">
<td class="px-5 py-4"><div class="flex justify-end gap-1"> <span v-if="(row as ShippingCustomerRow).odm_ids?.length">{{ (row as ShippingCustomerRow).odm_ids?.join(', ') }}</span>
<button type="button" class="p-2 text-indigo-600 hover:bg-indigo-50 rounded-lg" :title="t('admin.shippingCustomers.identifiers.title')" @click="admin.openIdentifiers(customer)"><Fingerprint class="w-4 h-4" /></button> <ElText v-else type="info" size="small">{{ t('admin.shippingCustomers.fields.odmIdsUnlimited') }}</ElText>
<button type="button" class="p-2 text-slate-600 hover:bg-slate-100 rounded-lg" :title="t('admin.shippingCustomers.lifecycle.open')" @click="admin.openLifecycleTimeline(customer)"><History class="w-4 h-4" /></button> </template>
<button type="button" class="p-2 text-indigo-600 hover:bg-indigo-50 rounded-lg" :title="t('admin.edit')" @click="admin.openEditCustomer(customer)"><Edit class="w-4 h-4" /></button> </ElTableColumn>
<button v-if="customer.status === 'active'" type="button" class="p-2 text-red-600 hover:bg-red-50 rounded-lg" :title="t('admin.shippingCustomers.deactivate')" @click="admin.deactivateCustomer(customer)"><UserX class="w-4 h-4" /></button> <ElTableColumn :label="t('admin.shippingCustomers.headers.identityEvidences')" min-width="100">
<button v-if="customer.status !== 'merged'" type="button" class="p-2 text-amber-700 hover:bg-amber-50 rounded-lg" :title="t('admin.shippingCustomers.mergeDialog.open')" @click="admin.openMergeCustomer(customer)"><GitMerge class="w-4 h-4" /></button> <template #default="{ row }">{{ (row as ShippingCustomerRow).identity_evidence_count || 0 }}</template>
<button type="button" class="p-2 text-red-700 hover:bg-red-50 rounded-lg" :title="t('admin.shippingCustomers.deleteDialog.open')" @click="admin.openDeleteCustomer(customer)"><Trash2 class="w-4 h-4" /></button> </ElTableColumn>
</div></td> <ElTableColumn prop="notice_count" :label="t('admin.shippingCustomers.headers.notices')" min-width="80" />
</tr> <ElTableColumn :label="t('admin.shippingCustomers.headers.actions')" width="280" align="right">
</tbody> <template #default="{ row }">
</table> <ElButton link type="primary" :icon="Key" :title="t('admin.shippingCustomers.identifiers.title')" @click="admin.openIdentifiers(row as ShippingCustomerRow)" />
<ElButton link type="primary" :icon="Clock" :title="t('admin.shippingCustomers.lifecycle.open')" @click="admin.openLifecycleTimeline(row as ShippingCustomerRow)" />
<ElButton link type="primary" :icon="Edit" :title="t('admin.edit')" @click="admin.openEditCustomer(row as ShippingCustomerRow)" />
<ElButton
v-if="(row as ShippingCustomerRow).status === 'active'"
link
type="danger"
:icon="Remove"
:title="t('admin.shippingCustomers.deactivate')"
@click="admin.deactivateCustomer(row as ShippingCustomerRow)"
/>
<ElButton
v-if="(row as ShippingCustomerRow).status !== 'merged'"
link
:icon="Connection"
:title="t('admin.shippingCustomers.mergeDialog.open')"
@click="admin.openMergeCustomer(row as ShippingCustomerRow)"
/>
<ElButton link type="danger" :icon="Delete" :title="t('admin.shippingCustomers.deleteDialog.open')" @click="admin.openDeleteCustomer(row as ShippingCustomerRow)" />
</template>
</ElTableColumn>
</ElTable>
<div v-if="admin.total.value > 0" class="customers-pager">
<ElPagination
:current-page="admin.page.value"
:page-size="admin.pageSize.value"
:total="admin.total.value"
:page-sizes="pageSizes"
layout="total, sizes, prev, pager, next"
background
@current-change="onPageChange"
@size-change="onPageSizeChange"
/>
</div> </div>
<PaginationBar v-model:page="admin.page.value" v-model:page-size="admin.pageSize.value" :total="admin.total.value" :pages="admin.pages.value" /> <CustomerShadowQualityPanel
:report="admin.shadowReport.value"
<CustomerShadowQualityPanel :report="admin.shadowReport.value" :customers="admin.importTargetCustomers.value.length ? admin.importTargetCustomers.value : admin.customers.value" :loading="admin.isShadowLoading.value" @refresh="admin.loadShadowReport" @label="admin.labelShadowResolution" /> :customers="admin.importTargetCustomers.value.length ? admin.importTargetCustomers.value : admin.customers.value"
:loading="admin.isShadowLoading.value"
@refresh="admin.loadShadowReport"
@label="admin.labelShadowResolution"
/>
<CustomerFormModal :visible="admin.showCustomerModal.value" :form="admin.customerForm.value" :is-saving="admin.isSaving.value" @close="admin.closeCustomerModal" @save="admin.saveCustomer" /> <CustomerFormModal :visible="admin.showCustomerModal.value" :form="admin.customerForm.value" :is-saving="admin.isSaving.value" @close="admin.closeCustomerModal" @save="admin.saveCustomer" />
<CustomerIdentifiersPanel :visible="admin.showIdentifiersPanel.value" :customer="admin.selectedCustomer.value" :published-definitions="admin.publishedEvidenceDefinitions.value" :is-saving="admin.isSaving.value" @close="admin.showIdentifiersPanel.value = false" @add-evidence="admin.addIdentityEvidence" @update-evidence="admin.updateIdentityEvidence" @add-external-ref="admin.addExternalRef" @add-site="admin.addSite" /> <CustomerIdentifiersPanel :visible="admin.showIdentifiersPanel.value" :customer="admin.selectedCustomer.value" :published-definitions="admin.publishedEvidenceDefinitions.value" :is-saving="admin.isSaving.value" @close="admin.showIdentifiersPanel.value = false" @add-evidence="admin.addIdentityEvidence" @update-evidence="admin.updateIdentityEvidence" @add-external-ref="admin.addExternalRef" @add-site="admin.addSite" />
@@ -98,18 +211,31 @@ onMounted(() => { void Promise.all([admin.loadCustomers(), admin.loadShadowRepor
<CustomerDeleteDialog :visible="admin.showDeleteDialog.value" :customer="admin.deleteCustomer.value" :impact="admin.deleteImpact.value" :is-saving="admin.isSaving.value" @close="admin.closeDeleteCustomer" @confirm="admin.confirmDeleteCustomer" /> <CustomerDeleteDialog :visible="admin.showDeleteDialog.value" :customer="admin.deleteCustomer.value" :impact="admin.deleteImpact.value" :is-saving="admin.isSaving.value" @close="admin.closeDeleteCustomer" @confirm="admin.confirmDeleteCustomer" />
<CustomerLifecyclePanel :visible="admin.showLifecyclePanel.value" :customer="admin.lifecycleCustomer.value" :timeline="admin.lifecycleTimeline.value" @close="admin.closeLifecycleTimeline" /> <CustomerLifecyclePanel :visible="admin.showLifecyclePanel.value" :customer="admin.lifecycleCustomer.value" :timeline="admin.lifecycleTimeline.value" @close="admin.closeLifecycleTimeline" />
<CustomerMergeDialog :visible="admin.showMergeDialog.value" :source="admin.mergeCustomer.value" :impact="admin.mergeImpact.value" :customers="admin.importTargetCustomers.value" :is-saving="admin.isSaving.value" @close="admin.closeMergeCustomer" @preview="admin.previewMergeCustomer" @confirm="admin.confirmMergeCustomer" /> <CustomerMergeDialog :visible="admin.showMergeDialog.value" :source="admin.mergeCustomer.value" :impact="admin.mergeImpact.value" :customers="admin.importTargetCustomers.value" :is-saving="admin.isSaving.value" @close="admin.closeMergeCustomer" @preview="admin.previewMergeCustomer" @confirm="admin.confirmMergeCustomer" />
<DeleteConfirmDialog
:model-value="admin.pendingReasonAction.value !== null"
:title="admin.pendingReasonAction.value?.kind === 'deactivate' ? t('admin.shippingCustomers.deactivate') : t('admin.shippingCustomers.identifiers.title')"
:message="admin.pendingReasonAction.value?.kind === 'deactivate' ? t('admin.shippingCustomers.confirmDeactivate', { name: admin.pendingReasonAction.value.customer.standard_name }) : t('admin.shippingCustomers.prompts.identifierChangeReason')"
:reason-label="admin.pendingReasonAction.value?.kind === 'deactivate' ? t('admin.shippingCustomers.prompts.deactivateReason') : t('admin.shippingCustomers.prompts.identifierChangeReason')"
:reason-placeholder="admin.pendingReasonAction.value?.kind === 'deactivate' ? t('admin.shippingCustomers.prompts.deactivateReason') : t('admin.shippingCustomers.prompts.identifierChangeReason')"
reason-required
confirm-tone="primary"
:confirm-loading="admin.isSaving.value"
@update:model-value="(visible) => { if (!visible) admin.cancelReasonAction(); }"
@cancel="admin.cancelReasonAction"
@confirm="admin.confirmReasonAction"
/>
</section> </section>
</template> </template>
<style scoped>
.customers-filters {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
padding: 16px 32px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.customers-filter-search {
width: 16rem;
}
.customers-filter-status {
width: 11rem;
}
.customers-pager {
display: flex;
justify-content: flex-end;
padding: 16px 32px;
border-top: 1px solid var(--el-border-color-lighter);
}
</style>
@@ -1,12 +1,20 @@
<!-- <!--
features/shipping-notice/customers/components/CustomerDeleteDialog.vue features/shipping-notice/customers/components/CustomerDeleteDialog.vue
用途:展示客户永久删除预检,并收集简码二次确认和删除原因。 用途:展示客户永久删除预检,并收集简码二次确认和删除原因。
依赖:customer-master.types、vue-i18n。 依赖:customer-master.types、element-plus、vue-i18n。
逻辑:有任何服务端生命周期阻断项时不暴露确认按钮;提交仍由父级调用后端原子校验。 逻辑:有任何服务端生命周期阻断项时不暴露确认按钮;提交仍由父级调用后端原子校验。样式由客户页引入。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import {
ElButton,
ElDialog,
ElForm,
ElFormItem,
ElInput,
ElText,
} from 'element-plus';
import type { ShippingCustomerLifecycleImpact, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types'; import type { ShippingCustomerLifecycleImpact, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
const props = defineProps<{ const props = defineProps<{
@@ -36,46 +44,61 @@ const canSubmit = computed(() => Boolean(
&& reason.value.trim() && reason.value.trim()
&& !props.isSaving, && !props.isSaving,
)); ));
/**
* 提交简码与原因。按钮已按 canSubmit 禁用,这里再挡一次空值。
*/
function submitDelete(): void {
if (!canSubmit.value) return;
emit('confirm', confirmationShortCode.value, reason.value);
}
</script> </script>
<template> <template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center"> <ElDialog
<div class="admin-modal-panel max-w-xl max-h-[92vh] scale-100"> :model-value="visible"
<div class="px-6 py-5 border-b border-subtle"> :title="t('admin.shippingCustomers.deleteDialog.title')"
<h3 class="section-title text-red-700">{{ t('admin.shippingCustomers.deleteDialog.title') }}</h3> width="680px"
<p class="section-desc mt-1">{{ t('admin.shippingCustomers.deleteDialog.subtitle') }}</p> align-center
</div> append-to-body
<div class="px-6 py-5 space-y-4 overflow-y-auto"> :close-on-click-modal="false"
<div v-if="!impact" class="text-sm text-muted">{{ t('admin.shippingCustomers.deleteDialog.loading') }}</div> @update:model-value="(open) => { if (!open) emit('close'); }"
>
<ElText type="info">{{ t('admin.shippingCustomers.deleteDialog.subtitle') }}</ElText>
<div v-if="!impact" class="customers-delete-block">{{ t('admin.shippingCustomers.deleteDialog.loading') }}</div>
<template v-else> <template v-else>
<div class="rounded-lg border border-default bg-surface-secondary p-4 text-sm"> <div class="customers-delete-block">
<div class="font-medium text-primary">{{ impact.customer.standard_name }} <span class="font-mono">({{ impact.customer.short_code }})</span></div> <div>{{ impact.customer.standard_name }} ({{ impact.customer.short_code }})</div>
<div class="mt-1 text-muted">{{ t('admin.shippingCustomers.deleteDialog.identifiers', { count: impact.cascade.identifiers }) }}</div> <ElText type="info" size="small">{{ t('admin.shippingCustomers.deleteDialog.identifiers', { count: impact.cascade.identifiers }) }}</ElText>
</div> </div>
<div v-if="!impact.can_delete" class="rounded-lg border border-red-200 bg-red-50 p-4"> <div v-if="!impact.can_delete" class="customers-delete-block">
<div class="font-medium text-red-700">{{ t('admin.shippingCustomers.deleteDialog.blocked') }}</div> <ElText type="danger">{{ t('admin.shippingCustomers.deleteDialog.blocked') }}</ElText>
<ul class="mt-2 space-y-1 text-sm text-red-700"> <ul>
<li v-for="[key, count] in blockerEntries" :key="key">{{ t(`admin.shippingCustomers.deleteDialog.blockers.${key}`) }}: {{ count }}</li> <li v-for="[key, count] in blockerEntries" :key="key">{{ t(`admin.shippingCustomers.deleteDialog.blockers.${key}`) }}: {{ count }}</li>
</ul> </ul>
<p class="mt-3 text-sm text-red-700">{{ t('admin.shippingCustomers.deleteDialog.blockedHint') }}</p> <ElText type="danger">{{ t('admin.shippingCustomers.deleteDialog.blockedHint') }}</ElText>
</div> </div>
<template v-else> <ElForm v-else label-position="top" @submit.prevent>
<p class="text-sm text-red-700">{{ t('admin.shippingCustomers.deleteDialog.warning') }}</p> <ElText type="danger">{{ t('admin.shippingCustomers.deleteDialog.warning') }}</ElText>
<label class="block space-y-1.5"> <ElFormItem :label="t('admin.shippingCustomers.deleteDialog.confirmationShortCode', { shortCode: impact.customer.short_code })">
<span class="label-field">{{ t('admin.shippingCustomers.deleteDialog.confirmationShortCode', { shortCode: impact.customer.short_code }) }}</span> <ElInput v-model="confirmationShortCode" maxlength="6" />
<input v-model="confirmationShortCode" class="input-field text-sm uppercase" maxlength="6" /> </ElFormItem>
</label> <ElFormItem :label="t('admin.shippingCustomers.deleteDialog.reason')">
<label class="block space-y-1.5"> <ElInput v-model="reason" type="textarea" :rows="3" />
<span class="label-field">{{ t('admin.shippingCustomers.deleteDialog.reason') }}</span> </ElFormItem>
<textarea v-model="reason" rows="3" class="input-field text-sm resize-y" /> </ElForm>
</label>
</template> </template>
<template #footer>
<ElButton @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
<ElButton v-if="impact?.can_delete" type="danger" :loading="isSaving" :disabled="!canSubmit" @click="submitDelete">
{{ isSaving ? t('admin.shippingCustomers.saving') : t('admin.shippingCustomers.deleteDialog.confirm') }}
</ElButton>
</template> </template>
</div> </ElDialog>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button v-if="impact?.can_delete" type="button" class="btn-danger" :disabled="!canSubmit" @click="emit('confirm', confirmationShortCode, reason)">{{ isSaving ? t('admin.shippingCustomers.saving') : t('admin.shippingCustomers.deleteDialog.confirm') }}</button>
</div>
</div>
</div>
</template> </template>
<style scoped>
.customers-delete-block {
margin-top: 12px;
}
</style>
@@ -1,11 +1,21 @@
<!-- <!--
features/shipping-notice/customers/components/CustomerFormModal.vue features/shipping-notice/customers/components/CustomerFormModal.vue
用途:创建或编辑货代标准客户。 用途:创建或编辑货代标准客户。
依赖:customer-master.types、admin 通用表单样式、vue-i18n。 依赖:customer-master.types、element-plus、vue-i18n。
逻辑:父页面传入可变表单;提交事件交由 useShippingCustomersAdmin 保存。 逻辑:父页面传入可变表单;提交事件交由 useShippingCustomersAdmin 保存。样式由客户页引入。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import {
ElButton,
ElDialog,
ElForm,
ElFormItem,
ElInput,
ElOption,
ElSelect,
ElText,
} from 'element-plus';
import type { ShippingCustomerFormState } from '@/features/shipping-notice/types/customer-master.types'; import type { ShippingCustomerFormState } from '@/features/shipping-notice/types/customer-master.types';
defineProps<{ visible: boolean; form: ShippingCustomerFormState; isSaving: boolean }>(); defineProps<{ visible: boolean; form: ShippingCustomerFormState; isSaving: boolean }>();
@@ -14,55 +24,65 @@ const { t } = useI18n();
</script> </script>
<template> <template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center"> <ElDialog
<div class="admin-modal-panel max-w-lg max-h-[92vh] scale-100"> :model-value="visible"
<div class="px-6 py-5 border-b border-subtle"> :title="form.id ? t('admin.shippingCustomers.edit') : t('admin.shippingCustomers.add')"
<h3 class="section-title">{{ form.id ? t('admin.shippingCustomers.edit') : t('admin.shippingCustomers.add') }}</h3> width="680px"
align-center
append-to-body
:close-on-click-modal="false"
@update:model-value="(open) => { if (!open) emit('close'); }"
>
<ElForm label-position="top" @submit.prevent>
<ElFormItem :label="t('admin.shippingCustomers.fields.standardName')">
<ElInput v-model="form.standard_name" />
</ElFormItem>
<div class="customers-form-grid">
<ElFormItem :label="t('admin.shippingCustomers.fields.shortCode')">
<ElInput v-model="form.short_code" maxlength="6" />
<ElText type="info" size="small">{{ t('admin.shippingCustomers.fields.shortCodeHint') }}</ElText>
</ElFormItem>
<ElFormItem :label="t('admin.shippingCustomers.fields.status')">
<ElSelect v-model="form.status">
<ElOption value="active" :label="t('admin.shippingCustomers.status.active')" />
<ElOption value="inactive" :label="t('admin.shippingCustomers.status.inactive')" />
</ElSelect>
</ElFormItem>
</div> </div>
<div class="px-6 py-5 space-y-4 overflow-y-auto"> <ElFormItem :label="t('admin.shippingCustomers.fields.remark')">
<label class="block space-y-1.5"> <ElInput v-model="form.remark" type="textarea" :rows="3" />
<span class="label-field">{{ t('admin.shippingCustomers.fields.standardName') }}</span> </ElFormItem>
<input v-model="form.standard_name" class="input-field text-sm" /> <ElFormItem :label="t('admin.shippingCustomers.fields.odmIds')">
</label> <ElInput
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<label class="block space-y-1.5">
<span class="label-field">{{ t('admin.shippingCustomers.fields.shortCode') }}</span>
<input v-model="form.short_code" maxlength="6" class="input-field text-sm uppercase" />
<span class="text-xs text-muted">{{ t('admin.shippingCustomers.fields.shortCodeHint') }}</span>
</label>
<label class="block space-y-1.5">
<span class="label-field">{{ t('admin.shippingCustomers.fields.status') }}</span>
<select v-model="form.status" class="input-field text-sm">
<option value="active">{{ t('admin.shippingCustomers.status.active') }}</option>
<option value="inactive">{{ t('admin.shippingCustomers.status.inactive') }}</option>
</select>
</label>
</div>
<label class="block space-y-1.5">
<span class="label-field">{{ t('admin.shippingCustomers.fields.remark') }}</span>
<textarea v-model="form.remark" rows="3" class="input-field text-sm resize-y" />
</label>
<label class="block space-y-1.5">
<span class="label-field">{{ t('admin.shippingCustomers.fields.odmIds') }}</span>
<textarea
v-model="form.odm_ids_text" v-model="form.odm_ids_text"
rows="3" type="textarea"
class="input-field text-sm resize-y font-mono" :rows="3"
:placeholder="t('admin.shippingCustomers.fields.odmIdsHint')" :placeholder="t('admin.shippingCustomers.fields.odmIdsHint')"
/> />
<span class="text-xs text-muted">{{ t('admin.shippingCustomers.fields.odmIdsHint') }}</span> <ElText type="info" size="small">{{ t('admin.shippingCustomers.fields.odmIdsHint') }}</ElText>
</label> </ElFormItem>
<label v-if="form.id" class="block space-y-1.5"> <ElFormItem v-if="form.id" :label="t('admin.shippingCustomers.fields.changeReason')">
<span class="label-field">{{ t('admin.shippingCustomers.fields.changeReason') }}</span> <ElInput
<textarea v-model="form.reason" rows="2" class="input-field text-sm resize-y" :placeholder="t('admin.shippingCustomers.fields.changeReasonHint')" /> v-model="form.reason"
</label> type="textarea"
</div> :rows="2"
<div class="admin-modal-footer"> :placeholder="t('admin.shippingCustomers.fields.changeReasonHint')"
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button> />
<button type="button" class="btn-primary" :disabled="isSaving" @click="emit('save')"> </ElFormItem>
</ElForm>
<template #footer>
<ElButton @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
<ElButton type="primary" :loading="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.shippingCustomers.saving') : t('admin.save') }} {{ isSaving ? t('admin.shippingCustomers.saving') : t('admin.save') }}
</button> </ElButton>
</div>
</div>
</div>
</template> </template>
</ElDialog>
</template>
<style scoped>
.customers-form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
</style>
@@ -1,14 +1,28 @@
<!-- <!--
features/shipping-notice/customers/components/CustomerIdentifiersPanel.vue features/shipping-notice/customers/components/CustomerIdentifiersPanel.vue
用途:维护客户主体和送货站点的全配置识别证据。 用途:维护客户主体和送货站点的全配置识别证据。
依赖:customer-master.types、vue-i18n。 依赖:customer-master.types、element-plus、vue-i18n。
逻辑:定义目录由服务端按已发布规则集提供;组件不维护类型枚举,也不直接调用 API。 逻辑:定义目录由服务端按已发布规则集提供;组件不维护类型枚举,也不直接调用 API。样式由客户页引入。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import {
ElButton,
ElCheckbox,
ElDialog,
ElForm,
ElFormItem,
ElInput,
ElOption,
ElSelect,
ElTable,
ElTableColumn,
ElText,
} from 'element-plus';
import type { import type {
ShippingCustomerRow, ShippingCustomerRow,
ShippingIdentityEvidence,
ShippingIdentityEvidenceFormState, ShippingIdentityEvidenceFormState,
ShippingPublishedEvidenceDefinitions, ShippingPublishedEvidenceDefinitions,
} from '@/features/shipping-notice/types/customer-master.types'; } from '@/features/shipping-notice/types/customer-master.types';
@@ -81,50 +95,198 @@ const submitSite = (): void => {
emit('addSite', { ...siteForm.value }); emit('addSite', { ...siteForm.value });
siteForm.value = { site_name: '', site_code: '', address: '', city: '', country: '', remark: '' }; siteForm.value = { site_name: '', site_code: '', address: '', city: '', country: '', remark: '' };
}; };
/**
* 证据定义。清空写回空字符串,提交校验仍要求有定义。
* @param value - 定义 id;清空为 undefined
*/
function onDefinitionChange(value: string | undefined): void {
form.value.definition_id = value ?? '';
}
/**
* 站点目标。清空写回 undefined,与原下拉空值一致。
* @param value - 站点 id
*/
function onSiteTargetChange(value: number | undefined): void {
form.value.target_id = value ?? undefined;
}
</script> </script>
<template> <template>
<div v-if="visible && customer" class="admin-modal-overlay animate-fade-in items-center"> <ElDialog
<div class="admin-modal-panel max-w-5xl max-h-[92vh] scale-100"> :model-value="visible && Boolean(customer)"
<div class="px-6 py-5 border-b border-subtle flex items-start justify-between gap-4"> :title="customer ? `${t('admin.shippingCustomers.identifiers.title')} · ${customer.standard_name} · ${customer.short_code}` : t('admin.shippingCustomers.identifiers.title')"
<div><h3 class="section-title">{{ t('admin.shippingCustomers.identifiers.title') }}</h3><p class="section-desc mt-1">{{ customer.standard_name }} · {{ customer.short_code }}</p></div> width="680px"
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.close') }}</button> align-center
append-to-body
:close-on-click-modal="false"
@update:model-value="(open) => { if (!open) emit('close'); }"
>
<template v-if="customer">
<section>
<h4>{{ t('admin.shippingCustomers.externalRefs.title') }}</h4>
<ElText type="info" size="small">{{ t('admin.shippingCustomers.externalRefs.hint') }}</ElText>
<div v-if="customer.external_refs?.length">
<ElText v-for="item in customer.external_refs" :key="item.id">{{ item.source_system }} · {{ item.customer_code }}</ElText>
</div> </div>
<div class="px-6 py-5 overflow-y-auto space-y-6"> <ElText v-else type="info">{{ t('admin.shippingCustomers.externalRefs.empty') }}</ElText>
<section class="rounded-xl border border-default p-4 space-y-4"> <ElForm label-position="top">
<div><h4 class="font-semibold text-primary">{{ t('admin.shippingCustomers.externalRefs.title') }}</h4><p class="text-xs text-muted mt-1">{{ t('admin.shippingCustomers.externalRefs.hint') }}</p></div> <div class="customers-id-grid">
<div v-if="customer.external_refs?.length" class="flex flex-wrap gap-2"><span v-for="item in customer.external_refs" :key="item.id" class="badge">{{ item.source_system }} · {{ item.customer_code }}</span></div> <ElFormItem>
<p v-else class="text-sm text-muted">{{ t('admin.shippingCustomers.externalRefs.empty') }}</p> <ElInput v-model="externalRefForm.source_system" :placeholder="t('admin.shippingCustomers.externalRefs.sourceSystem')" />
<div class="grid grid-cols-1 md:grid-cols-[1fr_1fr_auto] gap-3"><input v-model="externalRefForm.source_system" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.externalRefs.sourceSystem')"><input v-model="externalRefForm.customer_code" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.externalRefs.customerCode')"><button type="button" class="btn-primary" :disabled="isSaving || !externalRefForm.source_system.trim() || !externalRefForm.customer_code.trim()" @click="submitExternalRef">{{ t('admin.add') }}</button></div> </ElFormItem>
<ElFormItem>
<ElInput v-model="externalRefForm.customer_code" :placeholder="t('admin.shippingCustomers.externalRefs.customerCode')" />
</ElFormItem>
<ElButton type="primary" :disabled="isSaving || !externalRefForm.source_system.trim() || !externalRefForm.customer_code.trim()" @click="submitExternalRef">{{ t('admin.add') }}</ElButton>
</div>
</ElForm>
</section> </section>
<section class="rounded-xl border border-default p-4 space-y-4"> <section>
<div><h4 class="font-semibold text-primary">{{ t('admin.shippingCustomers.sites.title') }}</h4><p class="text-xs text-muted mt-1">{{ t('admin.shippingCustomers.sites.hint') }}</p></div> <h4>{{ t('admin.shippingCustomers.sites.title') }}</h4>
<div v-if="customer.sites?.length" class="grid gap-2"><div v-for="site in customer.sites" :key="site.id" class="rounded-lg bg-surface-soft p-3"><div class="font-medium text-primary">{{ site.site_name }} · {{ site.site_code }}</div><div class="text-xs text-muted mt-1">{{ [site.address, site.city, site.country].filter(Boolean).join(' · ') || '-' }}</div><div v-if="site.identity_evidences?.length" class="mt-2 space-y-1 text-xs text-muted"><div>{{ t('admin.shippingCustomers.identifiers.siteEvidenceCount', { count: site.identity_evidences.length }) }}</div><div v-for="evidence in site.identity_evidences" :key="evidence.id" class="flex items-center justify-between gap-2"><span>{{ evidence.definition?.display_name || evidence.definition?.definition_code || evidence.definition_id }} · {{ evidence.raw_value }}</span><span class="flex gap-2"><button v-if="evidence.status !== 'approved'" type="button" class="btn-ghost text-xs" @click="emit('updateEvidence', evidence.id, { status: 'approved' })">{{ t('admin.shippingCustomers.identifiers.approve') }}</button><button v-if="evidence.status === 'approved' && !evidence.auto_match_allowed && evidence.definition?.max_automation === 'conditional'" type="button" class="btn-ghost text-xs" @click="emit('updateEvidence', evidence.id, { auto_match_allowed: true })">{{ t('admin.shippingCustomers.identifiers.enableAuto') }}</button><button v-if="evidence.status !== 'disabled'" type="button" class="btn-ghost text-xs text-red-600" @click="emit('updateEvidence', evidence.id, { status: 'disabled' })">{{ t('admin.shippingCustomers.identifiers.disable') }}</button></span></div></div></div></div> <ElText type="info" size="small">{{ t('admin.shippingCustomers.sites.hint') }}</ElText>
<p v-else class="text-sm text-muted">{{ t('admin.shippingCustomers.sites.empty') }}</p> <div v-if="customer.sites?.length">
<div class="grid grid-cols-1 md:grid-cols-2 gap-3"><input v-model="siteForm.site_name" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.sites.siteName')"><input v-model="siteForm.site_code" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.sites.siteCode')"><input v-model="siteForm.address" class="input-field text-sm md:col-span-2" :placeholder="t('admin.shippingCustomers.sites.address')"><input v-model="siteForm.city" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.sites.city')"><input v-model="siteForm.country" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.sites.country')"></div> <div v-for="site in customer.sites" :key="site.id">
<div class="flex justify-end"><button type="button" class="btn-primary" :disabled="isSaving || !siteForm.site_name.trim() || !siteForm.site_code.trim()" @click="submitSite">{{ t('admin.add') }}</button></div> <div>{{ site.site_name }} · {{ site.site_code }}</div>
<ElText type="info" size="small">{{ [site.address, site.city, site.country].filter(Boolean).join(' · ') || '-' }}</ElText>
<div v-if="site.identity_evidences?.length">
<div>{{ t('admin.shippingCustomers.identifiers.siteEvidenceCount', { count: site.identity_evidences.length }) }}</div>
<div v-for="evidence in site.identity_evidences" :key="evidence.id" class="customers-id-row">
<span>{{ evidence.definition?.display_name || evidence.definition?.definition_code || evidence.definition_id }} · {{ evidence.raw_value }}</span>
<span>
<ElButton v-if="evidence.status !== 'approved'" link type="primary" @click="emit('updateEvidence', evidence.id, { status: 'approved' })">{{ t('admin.shippingCustomers.identifiers.approve') }}</ElButton>
<ElButton v-if="evidence.status === 'approved' && !evidence.auto_match_allowed && evidence.definition?.max_automation === 'conditional'" link type="primary" @click="emit('updateEvidence', evidence.id, { auto_match_allowed: true })">{{ t('admin.shippingCustomers.identifiers.enableAuto') }}</ElButton>
<ElButton v-if="evidence.status !== 'disabled'" link type="danger" @click="emit('updateEvidence', evidence.id, { status: 'disabled' })">{{ t('admin.shippingCustomers.identifiers.disable') }}</ElButton>
</span>
</div>
</div>
</div>
</div>
<ElText v-else type="info">{{ t('admin.shippingCustomers.sites.empty') }}</ElText>
<ElForm label-position="top">
<div class="customers-id-grid">
<ElInput v-model="siteForm.site_name" :placeholder="t('admin.shippingCustomers.sites.siteName')" />
<ElInput v-model="siteForm.site_code" :placeholder="t('admin.shippingCustomers.sites.siteCode')" />
<ElInput v-model="siteForm.address" :placeholder="t('admin.shippingCustomers.sites.address')" />
<ElInput v-model="siteForm.city" :placeholder="t('admin.shippingCustomers.sites.city')" />
<ElInput v-model="siteForm.country" :placeholder="t('admin.shippingCustomers.sites.country')" />
</div>
<ElButton type="primary" :disabled="isSaving || !siteForm.site_name.trim() || !siteForm.site_code.trim()" @click="submitSite">{{ t('admin.add') }}</ElButton>
</ElForm>
</section> </section>
<section class="rounded-xl border border-default p-4 space-y-4"> <section>
<div><h4 class="font-semibold text-primary">{{ t('admin.shippingCustomers.identifiers.add') }}</h4><p class="text-xs text-muted mt-1">{{ t('admin.shippingCustomers.identifiers.definitionHint') }}</p></div> <h4>{{ t('admin.shippingCustomers.identifiers.add') }}</h4>
<p v-if="publishedDefinitions?.disabled_reason" class="text-sm text-amber-700">{{ t('admin.shippingCustomers.identifiers.publishedRuleRequired') }}</p> <ElText type="info" size="small">{{ t('admin.shippingCustomers.identifiers.definitionHint') }}</ElText>
<div v-else class="grid grid-cols-1 md:grid-cols-3 gap-3"> <ElText v-if="publishedDefinitions?.disabled_reason" type="warning">{{ t('admin.shippingCustomers.identifiers.publishedRuleRequired') }}</ElText>
<select v-model="form.target_type" class="input-field text-sm"><option value="customer">{{ t('admin.shippingCustomers.identifiers.targets.customer') }}</option><option value="site">{{ t('admin.shippingCustomers.identifiers.targets.site') }}</option></select> <ElForm v-else label-position="top">
<select v-if="form.target_type === 'site'" v-model.number="form.target_id" class="input-field text-sm"><option :value="undefined">{{ t('admin.shippingCustomers.identifiers.selectSite') }}</option><option v-for="site in customer.sites || []" :key="site.id" :value="site.id">{{ site.site_name }} · {{ site.site_code }}</option></select><div v-else class="input-field text-sm bg-surface-soft">{{ customer.standard_name }}</div> <ElFormItem>
<select v-model="form.definition_id" class="input-field text-sm"><option value="">{{ t('admin.shippingCustomers.identifiers.selectDefinition') }}</option><option v-for="definition in currentDefinitions" :key="definition.id" :value="definition.id">{{ definition.display_name }} · {{ definition.context_field?.display_name || definition.context_field?.field_code || '-' }}</option></select> <ElSelect v-model="form.target_type">
<input v-model="form.raw_value" class="input-field text-sm md:col-span-2" :placeholder="t('admin.shippingCustomers.identifiers.valuePlaceholder')"> <ElOption value="customer" :label="t('admin.shippingCustomers.identifiers.targets.customer')" />
<select v-model="form.status" class="input-field text-sm"><option value="pending">{{ t('admin.shippingCustomers.identifierStatus.pending') }}</option><option value="approved">{{ t('admin.shippingCustomers.identifierStatus.approved') }}</option></select> <ElOption value="site" :label="t('admin.shippingCustomers.identifiers.targets.site')" />
<label class="flex items-center gap-2 text-sm text-secondary"><input v-model="form.auto_match_allowed" type="checkbox" :disabled="form.status !== 'approved' || selectedDefinition?.max_automation !== 'conditional'">{{ t('admin.shippingCustomers.identifiers.allowAuto') }}</label> </ElSelect>
<input v-model="form.remark" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.fields.remark')"> </ElFormItem>
</div> <ElFormItem v-if="form.target_type === 'site'">
<p v-if="selectedDefinition && selectedDefinition.max_automation === 'none'" class="text-xs text-muted">{{ t('admin.shippingCustomers.identifiers.manualOnly') }}</p> <ElSelect
<div class="flex justify-end"><button type="button" class="btn-primary" :disabled="isSaving || Boolean(publishedDefinitions?.disabled_reason) || !targetReady || !form.definition_id || !form.raw_value.trim()" @click="submitEvidence">{{ t('admin.add') }}</button></div> :model-value="form.target_id"
clearable
:placeholder="t('admin.shippingCustomers.identifiers.selectSite')"
@update:model-value="onSiteTargetChange"
>
<ElOption v-for="site in customer.sites || []" :key="site.id" :value="site.id" :label="`${site.site_name} · ${site.site_code}`" />
</ElSelect>
</ElFormItem>
<ElFormItem v-else>
<ElInput :model-value="customer.standard_name" disabled />
</ElFormItem>
<ElFormItem>
<ElSelect
:model-value="form.definition_id || undefined"
clearable
:placeholder="t('admin.shippingCustomers.identifiers.selectDefinition')"
@update:model-value="onDefinitionChange"
>
<ElOption
v-for="definition in currentDefinitions"
:key="definition.id"
:value="definition.id"
:label="`${definition.display_name} · ${definition.context_field?.display_name || definition.context_field?.field_code || '-'}`"
/>
</ElSelect>
</ElFormItem>
<ElFormItem>
<ElInput v-model="form.raw_value" :placeholder="t('admin.shippingCustomers.identifiers.valuePlaceholder')" />
</ElFormItem>
<ElFormItem>
<ElSelect v-model="form.status">
<ElOption value="pending" :label="t('admin.shippingCustomers.identifierStatus.pending')" />
<ElOption value="approved" :label="t('admin.shippingCustomers.identifierStatus.approved')" />
</ElSelect>
</ElFormItem>
<ElFormItem>
<ElCheckbox v-model="form.auto_match_allowed" :disabled="form.status !== 'approved' || selectedDefinition?.max_automation !== 'conditional'">
{{ t('admin.shippingCustomers.identifiers.allowAuto') }}
</ElCheckbox>
</ElFormItem>
<ElFormItem>
<ElInput v-model="form.remark" :placeholder="t('admin.shippingCustomers.fields.remark')" />
</ElFormItem>
</ElForm>
<ElText v-if="selectedDefinition && selectedDefinition.max_automation === 'none'" type="info" size="small">{{ t('admin.shippingCustomers.identifiers.manualOnly') }}</ElText>
<ElButton type="primary" :disabled="isSaving || Boolean(publishedDefinitions?.disabled_reason) || !targetReady || !form.definition_id || !form.raw_value.trim()" @click="submitEvidence">{{ t('admin.add') }}</ElButton>
</section> </section>
<section class="rounded-xl border border-default overflow-x-auto"><table class="admin-table min-w-[780px]"><thead><tr><th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.identifiers.definition') }}</th><th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.identifiers.value') }}</th><th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.identifiers.status') }}</th><th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.identifiers.autoMatch') }}</th><th class="px-4 py-3 text-right">{{ t('admin.shippingCustomers.headers.actions') }}</th></tr></thead><tbody><tr v-if="!customer.identity_evidences?.length"><td colspan="5" class="admin-table-empty px-4">{{ t('admin.shippingCustomers.identifiers.empty') }}</td></tr><tr v-for="item in customer.identity_evidences" :key="item.id"><td class="px-4 py-3 text-sm"><div>{{ item.definition?.display_name || item.definition?.definition_code || item.definition_id }}</div><div class="text-xs text-muted">{{ item.definition?.evidence_label }}</div></td><td class="px-4 py-3 text-sm"><div>{{ item.raw_value }}</div><div class="text-xs text-muted">{{ item.normalized_value }}</div></td><td class="px-4 py-3 text-sm">{{ t(`admin.shippingCustomers.identifierStatus.${item.status}`) }}</td><td class="px-4 py-3 text-sm">{{ item.auto_match_allowed ? t('admin.shippingCustomers.yes') : t('admin.shippingCustomers.no') }}</td><td class="px-4 py-3"><div class="flex justify-end gap-2"><button v-if="item.status !== 'approved'" type="button" class="btn-ghost text-xs" @click="emit('updateEvidence', item.id, { status: 'approved' })">{{ t('admin.shippingCustomers.identifiers.approve') }}</button><button v-if="item.status === 'approved' && !item.auto_match_allowed && item.definition?.max_automation === 'conditional'" type="button" class="btn-ghost text-xs" @click="emit('updateEvidence', item.id, { auto_match_allowed: true })">{{ t('admin.shippingCustomers.identifiers.enableAuto') }}</button><button v-if="item.status !== 'disabled'" type="button" class="btn-ghost text-xs text-red-600" @click="emit('updateEvidence', item.id, { status: 'disabled' })">{{ t('admin.shippingCustomers.identifiers.disable') }}</button></div></td></tr></tbody></table></section> <ElTable :data="customer.identity_evidences || []" row-key="id" :empty-text="t('admin.shippingCustomers.identifiers.empty')">
<ElTableColumn :label="t('admin.shippingCustomers.identifiers.definition')" min-width="160">
</div> <template #default="{ row }">
</div> <div>{{ (row as ShippingIdentityEvidence).definition?.display_name || (row as ShippingIdentityEvidence).definition?.definition_code || (row as ShippingIdentityEvidence).definition_id }}</div>
</div> <ElText type="info" size="small">{{ (row as ShippingIdentityEvidence).definition?.evidence_label }}</ElText>
</template> </template>
</ElTableColumn>
<ElTableColumn :label="t('admin.shippingCustomers.identifiers.value')" min-width="140">
<template #default="{ row }">
<div>{{ (row as ShippingIdentityEvidence).raw_value }}</div>
<ElText type="info" size="small">{{ (row as ShippingIdentityEvidence).normalized_value }}</ElText>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.shippingCustomers.identifiers.status')" min-width="100">
<template #default="{ row }">{{ t(`admin.shippingCustomers.identifierStatus.${(row as ShippingIdentityEvidence).status}`) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.shippingCustomers.identifiers.autoMatch')" min-width="100">
<template #default="{ row }">{{ (row as ShippingIdentityEvidence).auto_match_allowed ? t('admin.shippingCustomers.yes') : t('admin.shippingCustomers.no') }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.shippingCustomers.headers.actions')" width="220" align="right">
<template #default="{ row }">
<ElButton v-if="(row as ShippingIdentityEvidence).status !== 'approved'" link type="primary" @click="emit('updateEvidence', (row as ShippingIdentityEvidence).id, { status: 'approved' })">{{ t('admin.shippingCustomers.identifiers.approve') }}</ElButton>
<ElButton v-if="(row as ShippingIdentityEvidence).status === 'approved' && !(row as ShippingIdentityEvidence).auto_match_allowed && (row as ShippingIdentityEvidence).definition?.max_automation === 'conditional'" link type="primary" @click="emit('updateEvidence', (row as ShippingIdentityEvidence).id, { auto_match_allowed: true })">{{ t('admin.shippingCustomers.identifiers.enableAuto') }}</ElButton>
<ElButton v-if="(row as ShippingIdentityEvidence).status !== 'disabled'" link type="danger" @click="emit('updateEvidence', (row as ShippingIdentityEvidence).id, { status: 'disabled' })">{{ t('admin.shippingCustomers.identifiers.disable') }}</ElButton>
</template>
</ElTableColumn>
</ElTable>
</template>
<template #footer>
<ElButton @click="emit('close')">{{ t('admin.close') }}</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.customers-id-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin: 12px 0;
}
.customers-id-row {
display: flex;
justify-content: space-between;
gap: 8px;
}
section {
margin-bottom: 16px;
}
</style>
@@ -1,12 +1,26 @@
<!-- <!--
features/shipping-notice/customers/components/CustomerImportDialog.vue features/shipping-notice/customers/components/CustomerImportDialog.vue
用途:上传期初客户 Excel、查看预检结果、处理 warning、发布并下载对账。 用途:上传期初客户 Excel、查看预检结果、处理 warning、发布并下载对账。
依赖:customer-master.types、vue-i18n。 依赖:customer-master.types、element-plus、vue-i18n。
逻辑:组件只收集文件和行级决定;上传、发布与下载均委托父级 composable。 逻辑:组件只收集文件和行级决定;上传、发布与下载均委托父级 composable。样式由客户页引入。
隐藏文件选择保持原生 input。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref } from 'vue'; import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import {
ElButton,
ElDialog,
ElForm,
ElFormItem,
ElInput,
ElOption,
ElSelect,
ElTable,
ElTableColumn,
ElTag,
ElText,
} from 'element-plus';
import type { ShippingCustomerImportBatch, ShippingCustomerImportRow, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types'; import type { ShippingCustomerImportBatch, ShippingCustomerImportRow, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
const props = defineProps<{ const props = defineProps<{
@@ -48,74 +62,182 @@ const saveDecision = (row: ShippingCustomerImportRow): void => {
if (!action) return; if (!action) return;
emit('decide', row, action, rowTargets.value[row.id]); emit('decide', row, action, rowTargets.value[row.id]);
}; };
/**
* 行级动作。清空写回空字符串,保存时仍视为未选择。
* @param rowId - 导入行 id
* @param value - create/update/merge/skip;清空为 undefined
*/
function onRowAction(rowId: number, value: string | undefined): void {
rowActions.value[rowId] = value ?? '';
}
/**
* 归并或更新的目标客户。清空写回 undefined。
* @param rowId - 导入行 id
* @param value - 目标客户 id
*/
function onRowTarget(rowId: number, value: number | undefined): void {
rowTargets.value[rowId] = value ?? undefined;
}
/**
* 校验状态标签色。
* @param status - valid / warning / error
*/
function validationTag(status: string): 'success' | 'warning' | 'danger' | 'info' {
if (status === 'error') return 'danger';
if (status === 'warning') return 'warning';
if (status === 'valid') return 'success';
return 'info';
}
/**
* 预览列主文案。normalized 是开放对象。
* @param row - 导入行
*/
function previewMain(row: ShippingCustomerImportRow): string {
const normalized = row.normalized as { standard_name?: string; identifier_value?: string };
return normalized.standard_name || normalized.identifier_value || '-';
}
/**
* 预览列次文案。
* @param row - 导入行
*/
function previewSub(row: ShippingCustomerImportRow): string {
const normalized = row.normalized as { short_code?: string; identifier_type?: string };
return normalized.short_code || normalized.identifier_type || '';
}
</script> </script>
<template> <template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center"> <ElDialog
<div class="admin-modal-panel max-w-6xl max-h-[94vh] scale-100"> :model-value="visible"
<div class="px-6 py-5 border-b border-subtle flex items-start justify-between gap-4"> :title="t('admin.shippingCustomers.import.title')"
<div><h3 class="section-title">{{ t('admin.shippingCustomers.import.title') }}</h3><p class="section-desc mt-1">{{ t('admin.shippingCustomers.import.subtitle') }}</p></div> width="680px"
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.close') }}</button> align-center
</div> append-to-body
<div class="px-6 py-5 overflow-y-auto space-y-5"> :close-on-click-modal="false"
<div class="rounded-xl border border-default p-4 grid grid-cols-1 md:grid-cols-[1fr_220px_auto_auto] gap-3 items-end"> @update:model-value="(open) => { if (!open) emit('close'); }"
<label class="space-y-1.5"><span class="label-field">{{ t('admin.shippingCustomers.import.file') }}</span><input type="file" accept=".xlsx" class="block w-full text-sm" @change="onFileChange" /></label> >
<label class="space-y-1.5"><span class="label-field">{{ t('admin.shippingCustomers.import.sourceSystem') }}</span><input v-model="sourceSystem" class="input-field text-sm uppercase" /></label> <ElText type="info">{{ t('admin.shippingCustomers.import.subtitle') }}</ElText>
<button type="button" class="btn-ghost" @click="emit('template')">{{ t('admin.shippingCustomers.import.downloadTemplate') }}</button> <ElForm label-position="top" @submit.prevent>
<button type="button" class="btn-primary" :disabled="!selectedFile || isImporting" @click="upload">{{ t('admin.shippingCustomers.import.upload') }}</button> <ElFormItem :label="t('admin.shippingCustomers.import.file')">
<input type="file" accept=".xlsx" @change="onFileChange" />
</ElFormItem>
<ElFormItem :label="t('admin.shippingCustomers.import.sourceSystem')">
<ElInput v-model="sourceSystem" />
</ElFormItem>
</ElForm>
<div class="customers-import-actions">
<ElButton @click="emit('template')">{{ t('admin.shippingCustomers.import.downloadTemplate') }}</ElButton>
<ElButton type="primary" :loading="isImporting" :disabled="!selectedFile" @click="upload">{{ t('admin.shippingCustomers.import.upload') }}</ElButton>
</div> </div>
<template v-if="batch"> <template v-if="batch">
<div class="grid grid-cols-2 md:grid-cols-5 gap-3"> <div class="customers-import-stats">
<div v-for="item in [ <div v-for="item in [
['total', batch.total_rows], ['valid', batch.valid_rows], ['warning', batch.warning_rows], ['error', batch.error_rows], ['published', batch.published_rows] ['total', batch.total_rows], ['valid', batch.valid_rows], ['warning', batch.warning_rows], ['error', batch.error_rows], ['published', batch.published_rows]
]" :key="String(item[0])" class="rounded-xl border border-default p-3"> ]" :key="String(item[0])">
<div class="text-xs text-muted">{{ t(`admin.shippingCustomers.import.stats.${item[0]}`) }}</div><div class="text-xl font-semibold text-primary">{{ item[1] }}</div> <ElText type="info" size="small">{{ t(`admin.shippingCustomers.import.stats.${item[0]}`) }}</ElText>
<div>{{ item[1] }}</div>
</div> </div>
</div> </div>
<div class="text-sm text-secondary">{{ batch.batch_no }} · {{ batch.source_system }} · {{ batch.file_name }}</div> <ElText>{{ batch.batch_no }} · {{ batch.source_system }} · {{ batch.file_name }}</ElText>
<div class="rounded-xl border border-default overflow-x-auto"> <ElTable :data="batch.rows" row-key="id">
<table class="admin-table min-w-[1050px]"> <ElTableColumn :label="t('admin.shippingCustomers.import.row')" min-width="120">
<thead><tr> <template #default="{ row }">{{ (row as ShippingCustomerImportRow).sheet_name }}!{{ (row as ShippingCustomerImportRow).row_no }}</template>
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.row') }}</th> </ElTableColumn>
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.type') }}</th> <ElTableColumn :label="t('admin.shippingCustomers.import.type')" min-width="100">
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.key') }}</th> <template #default="{ row }">{{ t(`admin.shippingCustomers.import.rowTypes.${(row as ShippingCustomerImportRow).row_type}`) }}</template>
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.preview') }}</th> </ElTableColumn>
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.validation') }}</th> <ElTableColumn :label="t('admin.shippingCustomers.import.key')" min-width="120">
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.decision') }}</th> <template #default="{ row }">{{ (row as ShippingCustomerImportRow).legacy_customer_key || '-' }}</template>
</tr></thead> </ElTableColumn>
<tbody><tr v-for="row in batch.rows" :key="row.id"> <ElTableColumn :label="t('admin.shippingCustomers.import.preview')" min-width="160">
<td class="px-3 py-3 text-sm">{{ row.sheet_name }}!{{ row.row_no }}</td> <template #default="{ row }">
<td class="px-3 py-3 text-sm">{{ t(`admin.shippingCustomers.import.rowTypes.${row.row_type}`) }}</td> <div>{{ previewMain(row as ShippingCustomerImportRow) }}</div>
<td class="px-3 py-3 text-sm font-mono">{{ row.legacy_customer_key || '-' }}</td> <ElText type="info" size="small">{{ previewSub(row as ShippingCustomerImportRow) }}</ElText>
<td class="px-3 py-3 text-sm max-w-[320px]"><div class="truncate">{{ row.normalized.standard_name || row.normalized.identifier_value || '-' }}</div><div class="text-xs text-muted">{{ row.normalized.short_code || row.normalized.identifier_type || '' }}</div></td> </template>
<td class="px-3 py-3 text-sm"><span :class="row.validation_status === 'error' ? 'text-red-600' : row.validation_status === 'warning' ? 'text-amber-600' : 'text-emerald-600'">{{ t(`admin.shippingCustomers.import.validationStatus.${row.validation_status}`) }}</span><div v-for="issue in [...row.errors, ...row.warnings]" :key="issue.code" class="text-xs text-muted">{{ t(`errors.codes.${issue.code.replace(/\./g, '_')}`) }}</div></td> </ElTableColumn>
<td class="px-3 py-3 text-sm"> <ElTableColumn :label="t('admin.shippingCustomers.import.validation')" min-width="160">
<div v-if="row.validation_status === 'warning' && batch.status !== 'published'" class="flex flex-wrap gap-2"> <template #default="{ row }">
<select v-model="rowActions[row.id]" class="admin-table-filter-input text-xs"> <ElTag :type="validationTag((row as ShippingCustomerImportRow).validation_status)" effect="light">
<option value="">{{ t('admin.shippingCustomers.import.choose') }}</option> {{ t(`admin.shippingCustomers.import.validationStatus.${(row as ShippingCustomerImportRow).validation_status}`) }}
<option value="create">{{ t('admin.shippingCustomers.import.actions.create') }}</option> </ElTag>
<option v-if="row.row_type === 'customer'" value="update">{{ t('admin.shippingCustomers.import.actions.update') }}</option> <div v-for="issue in [...(row as ShippingCustomerImportRow).errors, ...(row as ShippingCustomerImportRow).warnings]" :key="issue.code">
<option v-if="row.row_type === 'customer'" value="merge">{{ t('admin.shippingCustomers.import.actions.merge') }}</option> <ElText type="info" size="small">{{ t(`errors.codes.${issue.code.replace(/\./g, '_')}`) }}</ElText>
<option value="skip">{{ t('admin.shippingCustomers.import.actions.skip') }}</option>
</select>
<select v-if="row.row_type === 'customer' && ['update','merge'].includes(rowActions[row.id] || '')" v-model="rowTargets[row.id]" class="admin-table-filter-input text-xs">
<option :value="undefined">{{ t('admin.shippingCustomers.import.target') }}</option>
<option v-for="customer in customers" :key="customer.id" :value="customer.id">{{ customer.standard_name }} ({{ customer.short_code }})</option>
</select>
<button type="button" class="btn-ghost text-xs" @click="saveDecision(row)">{{ t('admin.save') }}</button>
</div>
<span v-else>{{ row.decision_action || row.result_message || row.suggested_action || '-' }}</span>
</td>
</tr></tbody>
</table>
</div>
<div class="flex flex-wrap justify-between gap-3">
<button type="button" class="btn-ghost" @click="emit('reconciliation')">{{ t('admin.shippingCustomers.import.downloadReconciliation') }}</button>
<button type="button" class="btn-primary" :disabled="!canPublish || isImporting" @click="emit('publish')">{{ batch.status === 'published' ? t('admin.shippingCustomers.import.alreadyPublished') : t('admin.shippingCustomers.import.publish') }}</button>
</div> </div>
</template> </template>
</ElTableColumn>
<ElTableColumn :label="t('admin.shippingCustomers.import.decision')" min-width="280">
<template #default="{ row }">
<div v-if="(row as ShippingCustomerImportRow).validation_status === 'warning' && batch.status !== 'published'" class="customers-import-decision">
<ElSelect
class="customers-import-select"
:model-value="rowActions[(row as ShippingCustomerImportRow).id] || undefined"
clearable
:placeholder="t('admin.shippingCustomers.import.choose')"
@update:model-value="onRowAction((row as ShippingCustomerImportRow).id, $event)"
>
<ElOption value="create" :label="t('admin.shippingCustomers.import.actions.create')" />
<ElOption v-if="(row as ShippingCustomerImportRow).row_type === 'customer'" value="update" :label="t('admin.shippingCustomers.import.actions.update')" />
<ElOption v-if="(row as ShippingCustomerImportRow).row_type === 'customer'" value="merge" :label="t('admin.shippingCustomers.import.actions.merge')" />
<ElOption value="skip" :label="t('admin.shippingCustomers.import.actions.skip')" />
</ElSelect>
<ElSelect
v-if="(row as ShippingCustomerImportRow).row_type === 'customer' && ['update','merge'].includes(rowActions[(row as ShippingCustomerImportRow).id] || '')"
class="customers-import-select"
:model-value="rowTargets[(row as ShippingCustomerImportRow).id]"
clearable
:placeholder="t('admin.shippingCustomers.import.target')"
@update:model-value="onRowTarget((row as ShippingCustomerImportRow).id, $event)"
>
<ElOption
v-for="customer in customers"
:key="customer.id"
:value="customer.id"
:label="`${customer.standard_name} (${customer.short_code})`"
/>
</ElSelect>
<ElButton @click="saveDecision(row as ShippingCustomerImportRow)">{{ t('admin.save') }}</ElButton>
</div> </div>
</div> <span v-else>{{ (row as ShippingCustomerImportRow).decision_action || (row as ShippingCustomerImportRow).result_message || (row as ShippingCustomerImportRow).suggested_action || '-' }}</span>
</template>
</ElTableColumn>
</ElTable>
<div class="customers-import-actions">
<ElButton @click="emit('reconciliation')">{{ t('admin.shippingCustomers.import.downloadReconciliation') }}</ElButton>
<ElButton type="primary" :loading="isImporting" :disabled="!canPublish" @click="emit('publish')">
{{ batch.status === 'published' ? t('admin.shippingCustomers.import.alreadyPublished') : t('admin.shippingCustomers.import.publish') }}
</ElButton>
</div> </div>
</template> </template>
<template #footer>
<ElButton @click="emit('close')">{{ t('admin.close') }}</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.customers-import-actions,
.customers-import-decision {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
margin-top: 12px;
}
.customers-import-stats {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(6rem, 1fr));
gap: 12px;
margin: 12px 0;
}
.customers-import-select {
width: 11rem;
}
</style>
@@ -1,12 +1,13 @@
<!-- <!--
features/shipping-notice/customers/components/CustomerLifecyclePanel.vue features/shipping-notice/customers/components/CustomerLifecyclePanel.vue
用途:展示单个货代客户不可变的生命周期治理审计。 用途:展示单个货代客户不可变的生命周期治理审计。
依赖:customer-master.types、vue-i18n。 依赖:customer-master.types、element-plus、vue-i18n。
逻辑:由客户主数据页拉取时间线后传入;仅渲染快照,不触发任何客户写操作。 逻辑:由客户主数据页拉取时间线后传入;仅渲染快照,不触发任何客户写操作。样式由客户页引入。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import type { ShippingCustomerLifecycleTimeline, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types'; import { ElButton, ElDialog, ElTable, ElTableColumn } from 'element-plus';
import type { ShippingCustomerLifecycleEvent, ShippingCustomerLifecycleTimeline, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
defineProps<{ visible: boolean; customer: ShippingCustomerRow | null; timeline: ShippingCustomerLifecycleTimeline | null }>(); defineProps<{ visible: boolean; customer: ShippingCustomerRow | null; timeline: ShippingCustomerLifecycleTimeline | null }>();
const emit = defineEmits<{ close: [] }>(); const emit = defineEmits<{ close: [] }>();
@@ -20,40 +21,48 @@ const changeSummary = (detail: Record<string, unknown>): string => {
.map(([key, value]) => `${key}: ${String(value.before ?? '-')} → ${String(value.after ?? '-')}`) .map(([key, value]) => `${key}: ${String(value.before ?? '-')} → ${String(value.after ?? '-')}`)
.join(';'); .join(';');
}; };
/**
* 时间线行的变更摘要。表格插槽行收成审计事件。
* @param row - 当前事件
*/
function eventChange(row: ShippingCustomerLifecycleEvent): string {
return changeSummary(row.detail);
}
</script> </script>
<template> <template>
<div v-if="visible && customer" class="admin-modal-overlay animate-fade-in items-center"> <ElDialog
<div class="admin-modal-panel max-w-5xl max-h-[92vh] scale-100"> :model-value="visible && Boolean(customer)"
<div class="px-6 py-5 border-b border-subtle flex items-start justify-between gap-4"> :title="customer ? `${t('admin.shippingCustomers.lifecycle.title')} · ${customer.standard_name} · ${customer.short_code}` : t('admin.shippingCustomers.lifecycle.title')"
<div> width="680px"
<h3 class="section-title">{{ t('admin.shippingCustomers.lifecycle.title') }}</h3> align-center
<p class="section-desc mt-1">{{ customer.standard_name }} · {{ customer.short_code }}</p> append-to-body
</div> :close-on-click-modal="false"
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.close') }}</button> @update:model-value="(open) => { if (!open) emit('close'); }"
</div> >
<div class="px-6 py-5 overflow-y-auto"> <div v-if="!timeline">{{ t('admin.shippingCustomers.lifecycle.loading') }}</div>
<div v-if="!timeline" class="py-12 text-center text-sm text-muted">{{ t('admin.shippingCustomers.lifecycle.loading') }}</div> <ElTable
<div v-else class="overflow-x-auto rounded-xl border border-default"> v-else
<table class="admin-table min-w-[760px]"> :data="timeline.items"
<thead><tr> row-key="id"
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.lifecycle.time') }}</th> :empty-text="t('admin.shippingCustomers.lifecycle.empty')"
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.lifecycle.event') }}</th> >
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.lifecycle.reason') }}</th> <ElTableColumn :label="t('admin.shippingCustomers.lifecycle.time')" min-width="160">
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.lifecycle.change') }}</th> <template #default="{ row }">{{ (row as ShippingCustomerLifecycleEvent).created_at || '-' }}</template>
</tr></thead> </ElTableColumn>
<tbody> <ElTableColumn :label="t('admin.shippingCustomers.lifecycle.event')" min-width="140">
<tr v-if="!timeline.items.length"><td colspan="4" class="admin-table-empty px-4">{{ t('admin.shippingCustomers.lifecycle.empty') }}</td></tr> <template #default="{ row }">{{ t(`admin.shippingCustomers.lifecycle.events.${(row as ShippingCustomerLifecycleEvent).event_type}`) }}</template>
<tr v-for="event in timeline.items" :key="event.id"> </ElTableColumn>
<td class="px-4 py-3 text-sm text-muted">{{ event.created_at || '-' }}</td> <ElTableColumn :label="t('admin.shippingCustomers.lifecycle.reason')" min-width="140">
<td class="px-4 py-3 text-sm">{{ t(`admin.shippingCustomers.lifecycle.events.${event.event_type}`) }}</td> <template #default="{ row }">{{ (row as ShippingCustomerLifecycleEvent).reason || '-' }}</template>
<td class="px-4 py-3 text-sm">{{ event.reason || '-' }}</td> </ElTableColumn>
<td class="px-4 py-3 text-sm break-all">{{ changeSummary(event.detail) }}</td> <ElTableColumn :label="t('admin.shippingCustomers.lifecycle.change')" min-width="220">
</tr> <template #default="{ row }">{{ eventChange(row as ShippingCustomerLifecycleEvent) }}</template>
</tbody> </ElTableColumn>
</table> </ElTable>
</div> <template #footer>
</div> <ElButton @click="emit('close')">{{ t('admin.close') }}</ElButton>
</div> </template>
</div> </ElDialog>
</template> </template>
@@ -1,12 +1,22 @@
<!-- <!--
features/shipping-notice/customers/components/CustomerMergeDialog.vue features/shipping-notice/customers/components/CustomerMergeDialog.vue
用途:预览并确认将重复客户归并到启用目标客户。 用途:预览并确认将重复客户归并到启用目标客户。
依赖:customer-master.types、vue-i18n。 依赖:customer-master.types、element-plus、vue-i18n。
逻辑:展示历史保留与未来配置迁移边界;提交必须输入源客户简码和合并原因。 逻辑:展示历史保留与未来配置迁移边界;提交必须输入源客户简码和合并原因。样式由客户页引入。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import {
ElButton,
ElDialog,
ElForm,
ElFormItem,
ElInput,
ElOption,
ElSelect,
ElText,
} from 'element-plus';
import type { ShippingCustomerMergeImpact, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types'; import type { ShippingCustomerMergeImpact, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
const props = defineProps<{ const props = defineProps<{
@@ -35,32 +45,91 @@ watch(() => props.visible, (visible) => {
} }
}); });
/** 选择目标后再调用服务端预检,阻止在未确认归并边界时提交。 */ /**
const preview = (): void => { * 选择目标后再调用服务端预检。清空写回 null,与原下拉空值一致。
* @param value - 目标客户 id;清空为 undefined
*/
function onTargetChange(value: number | undefined): void {
targetCustomerId.value = value ?? null;
if (targetCustomerId.value) emit('preview', targetCustomerId.value); if (targetCustomerId.value) emit('preview', targetCustomerId.value);
}; }
/** 目标、简码和原因都齐了才允许提交。 */
const canSubmit = computed(() => Boolean( const canSubmit = computed(() => Boolean(
targetCustomerId.value && props.impact && confirmationShortCode.value.trim() && reason.value.trim() && !props.isSaving, targetCustomerId.value && props.impact && confirmationShortCode.value.trim() && reason.value.trim() && !props.isSaving,
)); ));
/** 提交归并。目标在 canSubmit 为真时必有值。 */
function submitMerge(): void {
if (!targetCustomerId.value || !canSubmit.value) return;
emit('confirm', targetCustomerId.value, confirmationShortCode.value, reason.value);
}
</script> </script>
<template> <template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center"> <ElDialog
<div class="admin-modal-panel max-w-xl max-h-[92vh] scale-100"> :model-value="visible"
<div class="px-6 py-5 border-b border-subtle"><h3 class="section-title">{{ t('admin.shippingCustomers.mergeDialog.title') }}</h3><p class="section-desc mt-1">{{ t('admin.shippingCustomers.mergeDialog.subtitle') }}</p></div> :title="t('admin.shippingCustomers.mergeDialog.title')"
<div class="px-6 py-5 space-y-4 overflow-y-auto"> width="680px"
<div v-if="source" class="rounded-lg border border-default bg-surface-secondary p-4 text-sm"><span class="text-muted">{{ t('admin.shippingCustomers.mergeDialog.source') }}</span><div class="font-medium text-primary mt-1">{{ source.standard_name }} <span class="font-mono">({{ source.short_code }})</span></div></div> align-center
<label class="block space-y-1.5"><span class="label-field">{{ t('admin.shippingCustomers.mergeDialog.target') }}</span><select v-model="targetCustomerId" class="input-field text-sm" @change="preview"><option :value="null">{{ t('admin.shippingCustomers.mergeDialog.chooseTarget') }}</option><option v-for="customer in targetOptions" :key="customer.id" :value="customer.id">{{ customer.standard_name }} ({{ customer.short_code }})</option></select></label> append-to-body
:close-on-click-modal="false"
@update:model-value="(open) => { if (!open) emit('close'); }"
>
<ElText type="info">{{ t('admin.shippingCustomers.mergeDialog.subtitle') }}</ElText>
<div v-if="source" class="customers-merge-block">
<ElText type="info" size="small">{{ t('admin.shippingCustomers.mergeDialog.source') }}</ElText>
<div>{{ source.standard_name }} ({{ source.short_code }})</div>
</div>
<ElForm label-position="top" @submit.prevent>
<ElFormItem :label="t('admin.shippingCustomers.mergeDialog.target')">
<ElSelect
:model-value="targetCustomerId ?? undefined"
clearable
:placeholder="t('admin.shippingCustomers.mergeDialog.chooseTarget')"
@update:model-value="onTargetChange"
>
<ElOption
v-for="customer in targetOptions"
:key="customer.id"
:value="customer.id"
:label="`${customer.standard_name} (${customer.short_code})`"
/>
</ElSelect>
</ElFormItem>
<template v-if="impact"> <template v-if="impact">
<div class="rounded-lg border border-default p-4 text-sm"><div class="font-medium text-primary">{{ t('admin.shippingCustomers.mergeDialog.historyTitle') }}</div><p class="mt-1 text-muted">{{ t('admin.shippingCustomers.mergeDialog.historyHint') }}</p><div class="mt-2 text-muted">{{ t('admin.shippingCustomers.mergeDialog.historyCount', { count: Object.values(impact.historical_references).reduce((sum, value) => sum + value, 0) }) }}</div></div> <div class="customers-merge-block">
<div class="rounded-lg border border-default p-4 text-sm"><div class="font-medium text-primary">{{ t('admin.shippingCustomers.mergeDialog.migrateTitle') }}</div><div class="mt-2 grid grid-cols-3 gap-2 text-center"><div><div class="text-lg font-semibold">{{ impact.migrate.identifiers }}</div><div class="text-xs text-muted">{{ t('admin.shippingCustomers.mergeDialog.identifiers') }}</div></div><div><div class="text-lg font-semibold">{{ impact.migrate.duplicate_identifiers }}</div><div class="text-xs text-muted">{{ t('admin.shippingCustomers.mergeDialog.duplicates') }}</div></div><div><div class="text-lg font-semibold">{{ impact.migrate.external_references }}</div><div class="text-xs text-muted">{{ t('admin.shippingCustomers.mergeDialog.references') }}</div></div></div></div> <div>{{ t('admin.shippingCustomers.mergeDialog.historyTitle') }}</div>
<p class="text-sm text-amber-700">{{ t('admin.shippingCustomers.mergeDialog.warning') }}</p> <ElText type="info" size="small">{{ t('admin.shippingCustomers.mergeDialog.historyHint') }}</ElText>
<label class="block space-y-1.5"><span class="label-field">{{ t('admin.shippingCustomers.mergeDialog.confirmationShortCode', { shortCode: impact.source.short_code }) }}</span><input v-model="confirmationShortCode" class="input-field text-sm uppercase" maxlength="6" /></label> <div>{{ t('admin.shippingCustomers.mergeDialog.historyCount', { count: Object.values(impact.historical_references).reduce((sum, value) => sum + value, 0) }) }}</div>
<label class="block space-y-1.5"><span class="label-field">{{ t('admin.shippingCustomers.mergeDialog.reason') }}</span><textarea v-model="reason" rows="3" class="input-field text-sm resize-y" /></label> </div>
<div class="customers-merge-stats">
<div>{{ t('admin.shippingCustomers.mergeDialog.migrateTitle') }}</div>
<div>{{ impact.migrate.identifiers }} {{ t('admin.shippingCustomers.mergeDialog.identifiers') }}</div>
<div>{{ impact.migrate.duplicate_identifiers }} {{ t('admin.shippingCustomers.mergeDialog.duplicates') }}</div>
<div>{{ impact.migrate.external_references }} {{ t('admin.shippingCustomers.mergeDialog.references') }}</div>
</div>
<ElText type="warning">{{ t('admin.shippingCustomers.mergeDialog.warning') }}</ElText>
<ElFormItem :label="t('admin.shippingCustomers.mergeDialog.confirmationShortCode', { shortCode: impact.source.short_code })">
<ElInput v-model="confirmationShortCode" maxlength="6" />
</ElFormItem>
<ElFormItem :label="t('admin.shippingCustomers.mergeDialog.reason')">
<ElInput v-model="reason" type="textarea" :rows="3" />
</ElFormItem>
</template> </template>
</div> </ElForm>
<div class="admin-modal-footer"><button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button><button type="button" class="btn-primary" :disabled="!canSubmit" @click="targetCustomerId && emit('confirm', targetCustomerId, confirmationShortCode, reason)">{{ isSaving ? t('admin.shippingCustomers.saving') : t('admin.shippingCustomers.mergeDialog.confirm') }}</button></div> <template #footer>
</div> <ElButton @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
</div> <ElButton type="primary" :loading="isSaving" :disabled="!canSubmit" @click="submitMerge">
{{ isSaving ? t('admin.shippingCustomers.saving') : t('admin.shippingCustomers.mergeDialog.confirm') }}
</ElButton>
</template> </template>
</ElDialog>
</template>
<style scoped>
.customers-merge-block,
.customers-merge-stats {
margin: 12px 0;
}
</style>
@@ -1,13 +1,23 @@
<!-- <!--
features/shipping-notice/customers/components/CustomerShadowQualityPanel.vue features/shipping-notice/customers/components/CustomerShadowQualityPanel.vue
用途:展示客户影子识别分布、自动确认指标、人工标注准确率和最近样本。 用途:展示客户影子识别分布、自动确认指标、人工标注准确率和最近样本。
依赖:customer-master.types、vue-i18n。 依赖:customer-master.types、element-plus、vue-i18n。
逻辑:展示质量卡片、客户事件审计与真值标签;不调用客户绑定、编号或任务接口。 逻辑:展示质量卡片、客户事件审计与真值标签;不调用客户绑定、编号或任务接口。样式由客户页引入。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { ref, watch } from 'vue'; import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import type { ShippingCustomerRow, ShippingCustomerShadowReport } from '@/features/shipping-notice/types/customer-master.types'; import {
ElButton,
ElOption,
ElSelect,
ElTable,
ElTableColumn,
ElText,
} from 'element-plus';
import type { ShippingCustomerRow, ShippingCustomerShadowItem, ShippingCustomerShadowReport } from '@/features/shipping-notice/types/customer-master.types';
type ShadowEvent = NonNullable<ShippingCustomerShadowReport['auto_resolution']>['recent_events'][number];
const props = defineProps<{ report: ShippingCustomerShadowReport | null; customers: ShippingCustomerRow[]; loading: boolean }>(); const props = defineProps<{ report: ShippingCustomerShadowReport | null; customers: ShippingCustomerRow[]; loading: boolean }>();
const emit = defineEmits<{ refresh: []; label: [resolutionId: number, customerId: number] }>(); const emit = defineEmits<{ refresh: []; label: [resolutionId: number, customerId: number] }>();
@@ -31,6 +41,15 @@ const submitLabel = (resolutionId: number): void => {
if (customerId) emit('label', resolutionId, customerId); if (customerId) emit('label', resolutionId, customerId);
}; };
/**
* 写入样本真值客户。清空写回 undefined,与原下拉空值一致。
* @param resolutionId - 影子样本 id
* @param value - 客户 id;清空为 undefined
*/
function onLabelChange(resolutionId: number, value: number | undefined): void {
labels.value[resolutionId] = value ?? undefined;
}
/** 从客户事件详情中提取新旧业务号,保持表格简洁且兼容不同事件类型。 */ /** 从客户事件详情中提取新旧业务号,保持表格简洁且兼容不同事件类型。 */
const eventBusinessChange = (detail: Record<string, unknown>): string => { const eventBusinessChange = (detail: Record<string, unknown>): string => {
const oldNo = String(detail.old_business_no || '').trim(); const oldNo = String(detail.old_business_no || '').trim();
@@ -38,59 +57,150 @@ const eventBusinessChange = (detail: Record<string, unknown>): string => {
if (oldNo && newNo) return `${oldNo} → ${newNo}`; if (oldNo && newNo) return `${oldNo} → ${newNo}`;
return newNo || oldNo || '-'; return newNo || oldNo || '-';
}; };
/**
* 审计行的业务号变化。表格插槽行收成影子事件。
* @param row - 最近审计事件
*/
function eventBusinessText(row: ShadowEvent): string {
return eventBusinessChange(row.detail);
}
/**
* 样本最高候选的展示文案。没有候选时返回短横线。
* @param row - 影子识别样本
* @returns 客户名、短码和分数
*/
function topCandidateText(row: ShippingCustomerShadowItem): string {
const match = row.matches[0];
if (!match) return '-';
return `${match.standard_name} (${match.short_code}) · ${match.score}`;
}
</script> </script>
<template> <template>
<div class="rounded-2xl border border-default bg-surface p-5 space-y-4"> <div class="customers-shadow">
<div class="flex items-start justify-between gap-3"> <div class="customers-shadow-head">
<div><h3 class="font-semibold text-primary">{{ t('admin.shippingCustomers.shadow.title') }}</h3><p class="text-sm text-muted mt-1">{{ t('admin.shippingCustomers.shadow.subtitle') }}</p></div> <div>
<button type="button" class="btn-ghost" :disabled="loading" @click="emit('refresh')">{{ t('admin.shippingCustomers.shadow.refresh') }}</button> <h3>{{ t('admin.shippingCustomers.shadow.title') }}</h3>
<ElText type="info">{{ t('admin.shippingCustomers.shadow.subtitle') }}</ElText>
</div> </div>
<div v-if="report" class="grid grid-cols-2 md:grid-cols-4 xl:grid-cols-8 gap-3"> <ElButton :loading="loading" @click="emit('refresh')">{{ t('admin.shippingCustomers.shadow.refresh') }}</ElButton>
</div>
<div v-if="report" class="customers-shadow-cards">
<div v-for="card in [ <div v-for="card in [
['total', report.total], ['unique', report.status_counts.unique_candidate || 0], ['ambiguous', report.status_counts.ambiguous || 0], ['total', report.total], ['unique', report.status_counts.unique_candidate || 0], ['ambiguous', report.status_counts.ambiguous || 0],
['unmatched', report.status_counts.unmatched || 0], ['accuracy', report.accuracy == null ? '-' : `${(report.accuracy * 100).toFixed(1)}%`], ['unmatched', report.status_counts.unmatched || 0], ['accuracy', report.accuracy == null ? '-' : `${(report.accuracy * 100).toFixed(1)}%`],
['autoBound', report.auto_bound_count], ['autoRate', report.auto_resolution?.auto_confirmation_rate == null ? '-' : `${(report.auto_resolution.auto_confirmation_rate * 100).toFixed(1)}%`] ['autoBound', report.auto_bound_count], ['autoRate', report.auto_resolution?.auto_confirmation_rate == null ? '-' : `${(report.auto_resolution.auto_confirmation_rate * 100).toFixed(1)}%`]
]" :key="String(card[0])" class="rounded-xl border border-default p-3"><div class="text-xs text-muted">{{ t(`admin.shippingCustomers.shadow.cards.${card[0]}`) }}</div><div class="text-xl font-semibold">{{ card[1] }}</div></div> ]" :key="String(card[0])">
<ElText type="info" size="small">{{ t(`admin.shippingCustomers.shadow.cards.${card[0]}`) }}</ElText>
<div>{{ card[1] }}</div>
</div> </div>
<div v-if="report?.auto_resolution?.quality_gate" class="rounded-xl border p-4" :class="report.auto_resolution.quality_gate.is_eligible ? 'border-emerald-300 bg-emerald-50/50' : 'border-amber-300 bg-amber-50/50'"> </div>
<div class="font-semibold text-primary">{{ t('admin.shippingCustomers.shadow.gate.title') }}</div> <div v-if="report?.auto_resolution?.quality_gate">
<div class="mt-1 text-sm text-secondary">{{ t(`admin.shippingCustomers.shadow.gate.statuses.${report.auto_resolution.quality_gate.status}`) }}</div> <div>{{ t('admin.shippingCustomers.shadow.gate.title') }}</div>
<div class="mt-2 text-xs text-muted"> <div>{{ t(`admin.shippingCustomers.shadow.gate.statuses.${report.auto_resolution.quality_gate.status}`) }}</div>
<ElText type="info" size="small">
{{ t('admin.shippingCustomers.shadow.gate.metrics', { {{ t('admin.shippingCustomers.shadow.gate.metrics', {
samples: report.auto_resolution.quality_gate.labeled_sample_count, samples: report.auto_resolution.quality_gate.labeled_sample_count,
minSamples: report.auto_resolution.quality_gate.min_labeled_samples, minSamples: report.auto_resolution.quality_gate.min_labeled_samples,
accuracy: report.auto_resolution.quality_gate.accuracy == null ? '-' : `${(report.auto_resolution.quality_gate.accuracy * 100).toFixed(1)}%`, accuracy: report.auto_resolution.quality_gate.accuracy == null ? '-' : `${(report.auto_resolution.quality_gate.accuracy * 100).toFixed(1)}%`,
minAccuracy: `${(report.auto_resolution.quality_gate.min_accuracy * 100).toFixed(1)}%`, minAccuracy: `${(report.auto_resolution.quality_gate.min_accuracy * 100).toFixed(1)}%`,
}) }} }) }}
</ElText>
</div> </div>
</div> <ElTable
<div v-if="report" class="overflow-x-auto rounded-xl border border-default"> v-if="report"
<table class="admin-table min-w-[900px]"><thead><tr> :data="report.items"
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.sample') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.status') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.topCandidate') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.manualLabel') }}</th> row-key="id"
</tr></thead><tbody> :empty-text="t('admin.shippingCustomers.shadow.empty')"
<tr v-if="!report.items.length"><td colspan="4" class="admin-table-empty px-3">{{ t('admin.shippingCustomers.shadow.empty') }}</td></tr> >
<tr v-for="item in report.items" :key="item.id"> <ElTableColumn :label="t('admin.shippingCustomers.shadow.sample')" min-width="160">
<td class="px-3 py-3 text-sm"><div>{{ item.candidate_no || item.candidate_id }}</div><div class="text-xs text-muted">{{ item.intake_no }}</div></td> <template #default="{ row }">
<td class="px-3 py-3 text-sm">{{ t(`admin.shippingCustomers.shadow.statuses.${item.status}`) }}</td> <div>{{ (row as ShippingCustomerShadowItem).candidate_no || (row as ShippingCustomerShadowItem).candidate_id }}</div>
<td class="px-3 py-3 text-sm"><span v-if="item.matches[0]">{{ item.matches[0].standard_name }} ({{ item.matches[0].short_code }}) · {{ item.matches[0].score }}</span><span v-else>-</span></td> <ElText type="info" size="small">{{ (row as ShippingCustomerShadowItem).intake_no }}</ElText>
<td class="px-3 py-3"><div class="flex gap-2"><select v-model="labels[item.id]" class="admin-table-filter-input text-xs"><option :value="undefined">{{ t('admin.shippingCustomers.shadow.chooseCustomer') }}</option><option v-for="customer in customers" :key="customer.id" :value="customer.id">{{ customer.standard_name }} ({{ customer.short_code }})</option></select><button type="button" class="btn-ghost text-xs" @click="submitLabel(item.id)">{{ item.manual_customer_id ? t('admin.update') : t('admin.save') }}</button></div></td> </template>
</tr> </ElTableColumn>
</tbody></table> <ElTableColumn :label="t('admin.shippingCustomers.shadow.status')" min-width="120">
</div> <template #default="{ row }">{{ t(`admin.shippingCustomers.shadow.statuses.${(row as ShippingCustomerShadowItem).status}`) }}</template>
<div v-if="report?.auto_resolution" class="overflow-x-auto rounded-xl border border-default"> </ElTableColumn>
<div class="border-b border-default px-3 py-3 text-sm font-semibold text-primary">{{ t('admin.shippingCustomers.shadow.auditTitle') }}</div> <ElTableColumn :label="t('admin.shippingCustomers.shadow.topCandidate')" min-width="180">
<table class="admin-table min-w-[760px]"><thead><tr> <template #default="{ row }">
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.auditTask') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.auditEvent') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.auditBusinessNo') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.auditTime') }}</th> {{ topCandidateText(row as ShippingCustomerShadowItem) }}
</tr></thead><tbody> </template>
<tr v-if="!report.auto_resolution.recent_events.length"><td colspan="4" class="admin-table-empty px-3">{{ t('admin.shippingCustomers.shadow.auditEmpty') }}</td></tr> </ElTableColumn>
<tr v-for="event in report.auto_resolution.recent_events" :key="event.id"> <ElTableColumn :label="t('admin.shippingCustomers.shadow.manualLabel')" min-width="280">
<td class="px-3 py-3 text-sm">{{ event.task_no }}</td> <template #default="{ row }">
<td class="px-3 py-3 text-sm">{{ t(`admin.shippingCustomers.shadow.events.${event.event_type}`) }}</td> <div class="customers-shadow-label">
<td class="px-3 py-3 text-sm">{{ eventBusinessChange(event.detail) }}</td> <ElSelect
<td class="px-3 py-3 text-sm text-muted">{{ event.created_at || '-' }}</td> class="customers-shadow-select"
</tr> :model-value="labels[(row as ShippingCustomerShadowItem).id]"
</tbody></table> clearable
</div> :placeholder="t('admin.shippingCustomers.shadow.chooseCustomer')"
@update:model-value="onLabelChange((row as ShippingCustomerShadowItem).id, $event)"
>
<ElOption
v-for="customer in customers"
:key="customer.id"
:value="customer.id"
:label="`${customer.standard_name} (${customer.short_code})`"
/>
</ElSelect>
<ElButton @click="submitLabel((row as ShippingCustomerShadowItem).id)">
{{ (row as ShippingCustomerShadowItem).manual_customer_id ? t('admin.update') : t('admin.save') }}
</ElButton>
</div> </div>
</template> </template>
</ElTableColumn>
</ElTable>
<template v-if="report?.auto_resolution">
<div>{{ t('admin.shippingCustomers.shadow.auditTitle') }}</div>
<ElTable
:data="report.auto_resolution.recent_events"
row-key="id"
:empty-text="t('admin.shippingCustomers.shadow.auditEmpty')"
>
<ElTableColumn prop="task_no" :label="t('admin.shippingCustomers.shadow.auditTask')" min-width="140" />
<ElTableColumn :label="t('admin.shippingCustomers.shadow.auditEvent')" min-width="140">
<template #default="{ row }">{{ t(`admin.shippingCustomers.shadow.events.${(row as ShadowEvent).event_type}`) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.shippingCustomers.shadow.auditBusinessNo')" min-width="180">
<template #default="{ row }">{{ eventBusinessText(row as ShadowEvent) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.shippingCustomers.shadow.auditTime')" min-width="160">
<template #default="{ row }">{{ (row as ShadowEvent).created_at || '-' }}</template>
</ElTableColumn>
</ElTable>
</template>
</div>
</template>
<style scoped>
.customers-shadow {
display: flex;
flex-direction: column;
gap: 16px;
margin: 16px 32px 24px;
padding: 16px;
border: 1px solid var(--el-border-color-lighter);
border-radius: 8px;
}
.customers-shadow-head,
.customers-shadow-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.customers-shadow-cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(8rem, 1fr));
gap: 12px;
}
.customers-shadow-select {
width: 16rem;
}
</style>
@@ -1,12 +1,14 @@
/** /**
* features/shipping-notice/customers/composables/useShippingCustomersAdmin.ts * features/shipping-notice/customers/composables/useShippingCustomersAdmin.ts
* 用途:编排货代客户列表、详情、识别证据、期初导入与发布状态。 * 用途:编排货代客户列表、详情、识别证据、期初导入与发布状态。
* 依赖:customer-master.api、customer-master.types、BusinessError、useMessage。 * 依赖:customer-master.api、customer-master.types、element-plus(ElMessageBox)、BusinessError、useMessage。
* 逻辑:ShippingCustomersPage 与子组件共享本 composable 暴露的状态和动作。 * 逻辑:ShippingCustomersPage 与子组件共享本 composable 暴露的状态和动作。
* 停用与证据变更的审计原因经 ElMessageBox.prompt 收集,取消不提交。
*/ */
import { ref } from 'vue'; import { ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { ElMessageBox } from 'element-plus';
import { import {
createShippingCustomer, createShippingCustomer,
createShippingCustomerExternalRef, createShippingCustomerExternalRef,
@@ -82,7 +84,6 @@ export function useShippingCustomersAdmin() {
const showDeleteDialog = ref(false); const showDeleteDialog = ref(false);
const showLifecyclePanel = ref(false); const showLifecyclePanel = ref(false);
const showMergeDialog = ref(false); const showMergeDialog = ref(false);
const pendingReasonAction = ref<{ kind: 'deactivate'; customer: ShippingCustomerRow } | { kind: 'update_evidence'; evidenceId: number; payload: Record<string, unknown> } | null>(null);
/** 分页加载全部客户选项,供导入冲突和影子真值标签共用。 */ /** 分页加载全部客户选项,供导入冲突和影子真值标签共用。 */
const loadAllCustomerOptions = async (): Promise<void> => { const loadAllCustomerOptions = async (): Promise<void> => {
@@ -187,9 +188,52 @@ export function useShippingCustomersAdmin() {
} }
}; };
/** 打开停用确认;审计原因由平台公共确认组件收集。 */ /**
const deactivateCustomer = (customer: ShippingCustomerRow): void => { * 收集治理动作的审计原因。
pendingReasonAction.value = { kind: 'deactivate', customer }; * 核心逻辑:原确认框必填原因,ElMessageBox.confirm 无法输入,故用 prompt;取消或关闭返回 null。
* @param title - 确认框标题,沿用现有 i18n
* @param message - 确认说明
* @param placeholder - 原因输入占位,同时作为未填写时的校验文案
* @returns 去空白后的原因;用户取消时为 null
*/
const askAuditReason = async (title: string, message: string, placeholder: string): Promise<string | null> => {
try {
const result = await ElMessageBox.prompt(message, title, {
confirmButtonText: t('common.deleteDialog.confirm'),
cancelButtonText: t('common.deleteDialog.cancel'),
inputPlaceholder: placeholder,
inputType: 'textarea',
inputValidator: (value) => Boolean(String(value || '').trim()) || placeholder,
closeOnClickModal: false,
});
const reason = String(result.value || '').trim();
return reason || null;
} catch {
return null;
}
};
/**
* 停用启用中的客户。
* 核心逻辑:先收集审计原因,取消则不调用停用接口。
* @param customer - 当前行客户
*/
const deactivateCustomer = async (customer: ShippingCustomerRow): Promise<void> => {
const reason = await askAuditReason(
t('admin.shippingCustomers.deactivate'),
t('admin.shippingCustomers.confirmDeactivate', { name: customer.standard_name }),
t('admin.shippingCustomers.prompts.deactivateReason'),
);
if (!reason) return;
isSaving.value = true;
try {
await deactivateShippingCustomer(customer.id, reason);
await loadCustomers();
} catch (error) {
showError(error, 'admin.shippingCustomers.msg.saveFailed');
} finally {
isSaving.value = false;
}
}; };
/** 打开客户治理时间线;读取失败时不显示过期的其他客户审计。 */ /** 打开客户治理时间线;读取失败时不显示过期的其他客户审计。 */
@@ -352,32 +396,30 @@ export function useShippingCustomersAdmin() {
} }
}; };
/** 打开证据变更确认;审计原因由平台公共确认组件收集。 */ /**
const updateIdentityEvidence = (evidenceId: number, payload: Record<string, unknown>): void => { * 变更识别证据状态或自动匹配开关。
* 核心逻辑:先收集审计原因,取消则不提交;原因并入原 payload。
* @param evidenceId - 证据主键
* @param payload - 状态或自动匹配字段,不含 reason
*/
const updateIdentityEvidence = async (evidenceId: number, payload: Record<string, unknown>): Promise<void> => {
if (!selectedCustomer.value) return; if (!selectedCustomer.value) return;
pendingReasonAction.value = { kind: 'update_evidence', evidenceId, payload }; const reason = await askAuditReason(
}; t('admin.shippingCustomers.identifiers.title'),
/** 确认后提交需要审计原因的治理动作。 */ t('admin.shippingCustomers.prompts.identifierChangeReason'),
const confirmReasonAction = async (reason: string): Promise<void> => { t('admin.shippingCustomers.prompts.identifierChangeReason'),
const action = pendingReasonAction.value; );
if (!action || !reason.trim()) return; if (!reason) return;
isSaving.value = true; isSaving.value = true;
try { try {
if (action.kind === 'deactivate') { await updateShippingIdentityEvidence(evidenceId, { ...payload, reason });
await deactivateShippingCustomer(action.customer.id, reason.trim());
await loadCustomers();
} else {
await updateShippingIdentityEvidence(action.evidenceId, { ...action.payload, reason: reason.trim() });
if (selectedCustomer.value) selectedCustomer.value = await getShippingCustomer(selectedCustomer.value.id); if (selectedCustomer.value) selectedCustomer.value = await getShippingCustomer(selectedCustomer.value.id);
}
} catch (error) { } catch (error) {
showError(error, 'admin.shippingCustomers.msg.saveFailed'); showError(error, 'admin.shippingCustomers.msg.saveFailed');
} finally { } finally {
isSaving.value = false; isSaving.value = false;
pendingReasonAction.value = null;
} }
}; };
const cancelReasonAction = (): void => { pendingReasonAction.value = null; };
/** 新增外部系统客户编码,并重新读取客户详情。 */ /** 新增外部系统客户编码,并重新读取客户详情。 */
const addExternalRef = async (payload: { source_system: string; customer_code: string }): Promise<void> => { const addExternalRef = async (payload: { source_system: string; customer_code: string }): Promise<void> => {
@@ -518,9 +560,9 @@ export function useShippingCustomersAdmin() {
customers, importTargetCustomers, selectedCustomer, publishedEvidenceDefinitions, customerForm, importBatch, shadowReport, deleteCustomer, deleteImpact, lifecycleCustomer, lifecycleTimeline, mergeCustomer, mergeImpact, customers, importTargetCustomers, selectedCustomer, publishedEvidenceDefinitions, customerForm, importBatch, shadowReport, deleteCustomer, deleteImpact, lifecycleCustomer, lifecycleTimeline, mergeCustomer, mergeImpact,
searchQuery, statusFilter, page, pageSize, total, pages, searchQuery, statusFilter, page, pageSize, total, pages,
isLoading, isSaving, isImporting, isShadowLoading, isLoading, isSaving, isImporting, isShadowLoading,
showCustomerModal, showIdentifiersPanel, showImportDialog, showDeleteDialog, showLifecyclePanel, showMergeDialog, pendingReasonAction, showCustomerModal, showIdentifiersPanel, showImportDialog, showDeleteDialog, showLifecyclePanel, showMergeDialog,
loadCustomers, searchCustomers, openCreateCustomer, openEditCustomer, closeCustomerModal, loadCustomers, searchCustomers, openCreateCustomer, openEditCustomer, closeCustomerModal,
saveCustomer, deactivateCustomer, confirmReasonAction, cancelReasonAction, openLifecycleTimeline, closeLifecycleTimeline, openDeleteCustomer, closeDeleteCustomer, confirmDeleteCustomer, openMergeCustomer, previewMergeCustomer, closeMergeCustomer, confirmMergeCustomer, openIdentifiers, addIdentityEvidence, updateIdentityEvidence, addExternalRef, addSite, saveCustomer, deactivateCustomer, openLifecycleTimeline, closeLifecycleTimeline, openDeleteCustomer, closeDeleteCustomer, confirmDeleteCustomer, openMergeCustomer, previewMergeCustomer, closeMergeCustomer, confirmMergeCustomer, openIdentifiers, addIdentityEvidence, updateIdentityEvidence, addExternalRef, addSite,
openImport, uploadImport, decideImportRow, publishImport, downloadTemplate, downloadReconciliation, openImport, uploadImport, decideImportRow, publishImport, downloadTemplate, downloadReconciliation,
loadShadowReport, labelShadowResolution, loadShadowReport, labelShadowResolution,
}; };
@@ -1,30 +1,50 @@
<script setup lang="ts">
/** /**
* features/user/views/UserProfilePage.vue * features/user/views/UserProfilePage.vue
* 用途:工作台个人中心,展示与编辑当前用户资料、语言/主题偏好,并提供修改密码入口。 * 用途:工作台个人中心,展示与编辑当前用户资料、语言/主题偏好,并提供修改密码入口。
* 依赖:workspace.context(WORKSPACE_KEY)、lucide 图标、vue-i18n、isPlatformAdminUser。 * 依赖:workspace.context(WORKSPACE_KEY)、element-plus、element-theme.css、vue-i18n、isPlatformAdminUser、getUserAvatarLabel。
* 逻辑:路由 /workspace/profile 懒加载本页;资料状态由 useWorkspaceProfile 经工作台注入。 * 逻辑:路由 /workspace/profile 懒加载本页。资料状态由 useWorkspaceProfile 经工作台注入。
* 角色展示优先用权限组名称;旧会话缺 role_name 时再按 is_platform_admin 回退。 * 角色展示优先用权限组名称;旧会话缺 role_name 时再按 is_platform_admin 回退。
* 改密弹窗在 WorkspaceModals。头像继续用品牌圆标,不用 ElAvatar。
*/ */
<script setup lang="ts">
import { computed, inject } from 'vue'; import { computed, inject } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { Check, Edit } from '@element-plus/icons-vue';
import { import {
User, Mail, Building, CreditCard, Globe, Save, Palette, ElButton,
} from 'lucide-vue-next'; ElCard,
ElForm,
ElFormItem,
ElInput,
ElLoading,
ElOption,
ElRadioButton,
ElRadioGroup,
ElSelect,
ElText,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/shared/styles/element-theme.css';
import { getUserAvatarLabel } from '@/shared/utils/user-avatar'; import { getUserAvatarLabel } from '@/shared/utils/user-avatar';
import { WORKSPACE_KEY } from '@/features/workspace/composables/workspace.context'; import { WORKSPACE_KEY } from '@/features/workspace/composables/workspace.context';
import { isPlatformAdminUser } from '@/shared/utils/auth'; import { isPlatformAdminUser } from '@/shared/utils/auth';
const vLoading = ElLoading.directive;
const { t } = useI18n(); const { t } = useI18n();
const userProfile = inject(WORKSPACE_KEY)!; const userProfile = inject(WORKSPACE_KEY)!;
/** 只读字段值:与 input-field 同高,正文统一 14px。 */ const languageOptions = computed(() => [
const fieldValueClass = 'flex min-h-11 items-center rounded-xl border border-default bg-surface-soft px-4 text-sm font-medium text-secondary'; { value: 'zh-CN', label: t('workspace.lang.zhCN') },
/** 表单标签:与分区标题区分层级,全页统一 14px。 */ { value: 'zh-TW', label: t('workspace.lang.zhTW') },
const fieldLabelClass = 'mb-1.5 flex items-center gap-1.5 text-sm font-medium text-muted'; { value: 'en', label: 'English' },
{ value: 'th', label: 'Thai' },
]);
/** /**
* 身份主标题:优先真实姓名,缺失时回退用户名。 * 身份主标题:优先真实姓名,缺失时回退用户名。
* @returns 展示姓名
*/ */
const displayName = computed(() => { const displayName = computed(() => {
return userProfile.profileUser.real_name || userProfile.profileUser.username || '-'; return userProfile.profileUser.real_name || userProfile.profileUser.username || '-';
@@ -33,6 +53,7 @@ const displayName = computed(() => {
/** /**
* 个人中心角色标签。 * 个人中心角色标签。
* 核心逻辑:有权限组名称就展示名称;否则按 is_platform_admin 回退内置文案。 * 核心逻辑:有权限组名称就展示名称;否则按 is_platform_admin 回退内置文案。
* @returns 角色文案
*/ */
const profileRoleLabel = computed(() => { const profileRoleLabel = computed(() => {
const user = userProfile.profileUser || {}; const user = userProfile.profileUser || {};
@@ -42,6 +63,7 @@ const profileRoleLabel = computed(() => {
/** /**
* 身份副标题:用户名(与主标题不同时)、部门、角色用间隔点拼接,空项省略。 * 身份副标题:用户名(与主标题不同时)、部门、角色用间隔点拼接,空项省略。
* @returns 副标题;没有可展示项时为空字符串
*/ */
const identityMeta = computed(() => { const identityMeta = computed(() => {
const username = userProfile.profileUser.username; const username = userProfile.profileUser.username;
@@ -50,222 +72,268 @@ const identityMeta = computed(() => {
.filter(Boolean) .filter(Boolean)
.join(' · '); .join(' · ');
}); });
/**
* 只读时用短横线占位,编辑时保留空字符串以便继续输入。
* @param value - 资料字段当前值
* @returns 输入框展示文字
*/
function fieldText(value: string | undefined): string {
if (userProfile.isProfileEditing) return value || '';
return value || '-';
}
/**
* 编辑态写回资料字段。只读时忽略输入框回写,避免把占位短横线存进去。
* @param key - 可编辑的资料字段
* @param value - 输入框新值
*/
function onProfileField(
key: 'employee_id' | 'real_name' | 'department' | 'email' | 'phone_number',
value: string,
): void {
if (!userProfile.isProfileEditing) return;
userProfile.profileUser[key] = value;
}
</script> </script>
<template> <template>
<div v-if="userProfile.isProfileLoading" class="flex justify-center py-20"> <div v-loading="userProfile.isProfileLoading" class="profile-page">
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div> <template v-if="!userProfile.isProfileLoading">
</div> <ElCard shadow="never" class="profile-identity">
<div class="profile-identity__body">
<div v-else class="space-y-6"> <div class="profile-identity__person">
<div class="rounded-3xl border border-default bg-surface px-6 py-6 shadow-sm md:px-8"> <div class="profile-avatar" :class="userProfile.isMobile ? 'profile-avatar--compact' : ''">
<div class="flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">
<div class="flex flex-1 flex-col gap-6 sm:flex-row sm:items-center sm:justify-start">
<div class="flex h-24 w-24 shrink-0 items-center justify-center rounded-full bg-brand-100 text-4xl font-bold text-brand-600" :class="userProfile.isMobile ? 'h-14 w-14 text-2xl' : ''">
{{ getUserAvatarLabel(userProfile.profileUser) }} {{ getUserAvatarLabel(userProfile.profileUser) }}
</div> </div>
<div class="min-w-0 space-y-0.5"> <div class="profile-identity__text">
<div class="truncate text-lg font-semibold text-primary">{{ displayName }}</div> <div class="section-title">{{ displayName }}</div>
<div v-if="identityMeta" class="truncate text-sm text-muted">{{ identityMeta }}</div> <ElText v-if="identityMeta" type="info">{{ identityMeta }}</ElText>
<div v-if="userProfile.profileUser.email" class="break-all text-sm text-muted"> <ElText v-if="userProfile.profileUser.email" type="info" class="profile-identity__email">
{{ userProfile.profileUser.email }} {{ userProfile.profileUser.email }}
</ElText>
</div> </div>
</div> </div>
</div> <div class="profile-identity__actions">
<div v-if="!userProfile.isMobile" class="shrink-0"> <ElButton type="primary" @click="userProfile.handleChangePasswordClick">
<button type="button" class="btn-primary btn-sm" @click="userProfile.handleChangePasswordClick"> {{ t('profile.changePassword') }}
{{ $t('profile.changePassword') }} </ElButton>
</button> <ElButton v-if="userProfile.isMobile" type="danger" plain @click="userProfile.handleLogout">
</div> {{ t('workspace.nav.logout') }}
</div> </ElButton>
<div v-if="userProfile.isMobile" class="mt-4 flex items-center gap-3">
<button
type="button"
class="btn-primary btn-sm flex-1"
@click="userProfile.handleChangePasswordClick"
>
{{ $t('profile.changePassword') }}
</button>
<button
type="button"
class="btn-secondary btn-sm flex-1 text-red-600 hover:bg-red-50"
@click="userProfile.handleLogout"
>
{{ $t('workspace.nav.logout') }}
</button>
</div> </div>
</div> </div>
</ElCard>
<div class="space-y-6"> <ElCard shadow="never">
<div class="rounded-2xl border border-default bg-surface p-5 shadow-sm md:p-6"> <template #header>
<div class="mb-5 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between"> <div class="profile-card-head">
<div class="flex items-center gap-2" :class="userProfile.isMobile ? 'w-full justify-between' : ''"> <div>
<h3 class="section-title flex items-center gap-2"> <h3 class="section-title">{{ t('profile.basicInfo') }}</h3>
<User class="h-5 w-5 text-brand-500" />
{{ $t('profile.basicInfo') }}
</h3>
<button
v-if="userProfile.isMobile && !userProfile.isProfileEditing"
type="button"
class="btn-secondary btn-sm"
@click="userProfile.startProfileEditing"
>
{{ $t('profile.edit') }}
</button>
</div>
<p v-if="!userProfile.isMobile" class="section-desc"> <p v-if="!userProfile.isMobile" class="section-desc">
{{ userProfile.isProfileEditing ? $t('profile.directEditHint') : $t('profile.switchEditHint') }} {{ userProfile.isProfileEditing ? t('profile.directEditHint') : t('profile.switchEditHint') }}
</p> </p>
<div v-if="!userProfile.isMobile" class="flex items-center gap-2"> </div>
<button <div class="profile-card-head__actions">
<ElButton
v-if="!userProfile.isProfileEditing" v-if="!userProfile.isProfileEditing"
type="button" :icon="Edit"
class="btn-secondary btn-sm"
@click="userProfile.startProfileEditing" @click="userProfile.startProfileEditing"
> >
{{ $t('profile.edit') }} {{ t('profile.edit') }}
</button> </ElButton>
<template v-else> <template v-else>
<button type="button" class="btn-secondary btn-sm" @click="userProfile.cancelProfileEditing"> <ElButton @click="userProfile.cancelProfileEditing">{{ t('profile.cancel') }}</ElButton>
{{ $t('profile.cancel') }} <ElButton
</button> type="primary"
<button :icon="Check"
type="button" :loading="userProfile.isProfileSaving"
class="btn-primary btn-sm disabled:cursor-not-allowed disabled:opacity-50" :disabled="!userProfile.hasProfileUnsavedChanges"
:disabled="userProfile.isProfileSaving || !userProfile.hasProfileUnsavedChanges"
@click="userProfile.saveProfile" @click="userProfile.saveProfile"
> >
<Save class="h-4 w-4" /> {{ userProfile.isProfileSaving ? t('profile.saving') : t('workspace.save') }}
<span>{{ userProfile.isProfileSaving ? $t('profile.saving') : $t('workspace.save') }}</span> </ElButton>
</button>
</template> </template>
</div> </div>
</div> </div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2"> </template>
<div> <ElForm label-position="top" class="profile-form">
<label :class="fieldLabelClass"> <div class="profile-form__grid">
<User class="h-4 w-4" /> {{ $t('profile.username') }} <ElFormItem :label="t('profile.username')">
</label> <ElInput :model-value="userProfile.profileUser.username || '-'" disabled />
<div :class="fieldValueClass"> </ElFormItem>
{{ userProfile.profileUser.username || '-' }} <ElFormItem :label="t('profile.employeeId')">
</div> <ElInput
</div> :model-value="fieldText(userProfile.profileUser.employee_id)"
<div> :disabled="!userProfile.isProfileEditing"
<label :class="fieldLabelClass"> @update:model-value="onProfileField('employee_id', $event)"
<CreditCard class="h-4 w-4" /> {{ $t('profile.employeeId') }} />
</label> </ElFormItem>
<input <ElFormItem :label="t('profile.realName')">
v-if="userProfile.isProfileEditing" <ElInput
v-model="userProfile.profileUser.employee_id" :model-value="fieldText(userProfile.profileUser.real_name)"
type="text" :disabled="!userProfile.isProfileEditing"
class="input-field text-sm" @update:model-value="onProfileField('real_name', $event)"
> />
<div v-else :class="fieldValueClass"> </ElFormItem>
{{ userProfile.profileUser.employee_id || '-' }} <ElFormItem :label="t('profile.department')">
</div> <ElInput
</div> :model-value="fieldText(userProfile.profileUser.department)"
<div> :disabled="!userProfile.isProfileEditing"
<label :class="fieldLabelClass"> @update:model-value="onProfileField('department', $event)"
<User class="h-4 w-4" /> {{ $t('profile.realName') }} />
</label> </ElFormItem>
<input <ElFormItem :label="t('profile.email')">
v-if="userProfile.isProfileEditing" <ElInput
v-model="userProfile.profileUser.real_name" :model-value="fieldText(userProfile.profileUser.email)"
type="text" :disabled="!userProfile.isProfileEditing"
class="input-field text-sm" @update:model-value="onProfileField('email', $event)"
> />
<div v-else :class="fieldValueClass"> </ElFormItem>
{{ userProfile.profileUser.real_name || '-' }} <ElFormItem :label="t('profile.phoneNumber')">
</div> <ElInput
</div> :model-value="fieldText(userProfile.profileUser.phone_number)"
<div> :disabled="!userProfile.isProfileEditing"
<label :class="fieldLabelClass"> @update:model-value="onProfileField('phone_number', $event)"
<Building class="h-4 w-4" /> {{ $t('profile.department') }} />
</label> </ElFormItem>
<input
v-if="userProfile.isProfileEditing"
v-model="userProfile.profileUser.department"
type="text"
class="input-field text-sm"
>
<div v-else :class="fieldValueClass">
{{ userProfile.profileUser.department || '-' }}
</div>
</div>
<div>
<label :class="fieldLabelClass">
<Mail class="h-4 w-4" /> {{ $t('profile.email') }}
</label>
<input
v-if="userProfile.isProfileEditing"
v-model="userProfile.profileUser.email"
type="email"
class="input-field text-sm"
>
<div v-else :class="fieldValueClass">
{{ userProfile.profileUser.email || '-' }}
</div>
</div>
<div>
<label :class="fieldLabelClass">
<Globe class="h-4 w-4" /> {{ $t('profile.phoneNumber') }}
</label>
<input
v-if="userProfile.isProfileEditing"
v-model="userProfile.profileUser.phone_number"
type="text"
class="input-field text-sm"
>
<div v-else :class="fieldValueClass">
{{ userProfile.profileUser.phone_number || '-' }}
</div>
</div>
</div>
</div> </div>
</ElForm>
</ElCard>
<div class="rounded-2xl border border-default bg-surface p-5 shadow-sm md:p-6"> <ElCard shadow="never">
<h3 class="section-title mb-5 flex items-center gap-2"> <template #header>
<Palette class="h-5 w-5 text-brand-500" /> <h3 class="section-title">{{ t('profile.preferences') }}</h3>
{{ $t('profile.preferences') }} </template>
</h3> <ElForm label-position="top" class="profile-form">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2"> <div class="profile-form__grid">
<div> <ElFormItem :label="t('workspace.languageLabel')">
<label class="mb-1.5 block text-sm font-medium text-muted">{{ $t('workspace.languageLabel') }}</label> <ElSelect
<select
v-model="userProfile.profileUser.language" v-model="userProfile.profileUser.language"
class="select-field text-sm" class="profile-control"
:disabled="!userProfile.isProfileEditing" :disabled="!userProfile.isProfileEditing"
> >
<option value="en">English</option> <ElOption
<option value="zh-CN">{{ $t('workspace.lang.zhCN') }}</option> v-for="item in languageOptions"
<option value="zh-TW">{{ $t('workspace.lang.zhTW') }}</option> :key="item.value"
<option value="th">Thai</option> :label="item.label"
</select> :value="item.value"
</div> />
<div> </ElSelect>
<label class="mb-1.5 block text-sm font-medium text-muted">{{ $t('profile.theme') }}</label> </ElFormItem>
<div <ElFormItem :label="t('profile.theme')">
class="segment-control segment-control--cols-3 segment-control--md" <ElRadioGroup
role="radiogroup" v-model="userProfile.profileUser.theme_preference"
:aria-label="$t('profile.theme')" :disabled="!userProfile.isProfileEditing"
> >
<button <ElRadioButton
v-for="item in userProfile.themeOptions" v-for="item in userProfile.themeOptions"
:key="item.value" :key="item.value"
type="button" :value="item.value"
role="radio"
class="segment-item"
:aria-checked="userProfile.profileUser.theme_preference === item.value"
:disabled="!userProfile.isProfileEditing"
:class="userProfile.profileUser.theme_preference === item.value ? 'segment-item--active' : ''"
@click="userProfile.profileUser.theme_preference = item.value"
> >
{{ item.label() }} {{ item.label() }}
</button> </ElRadioButton>
</div> </ElRadioGroup>
</div> </ElFormItem>
</div>
</div>
</div> </div>
</ElForm>
</ElCard>
</template>
</div> </div>
</template> </template>
<style scoped>
.profile-page {
display: flex;
flex-direction: column;
gap: 16px;
min-height: 16rem;
}
.profile-identity__body,
.profile-card-head,
.profile-identity__person,
.profile-identity__actions,
.profile-card-head__actions {
display: flex;
align-items: center;
gap: 12px;
}
.profile-identity__body,
.profile-card-head {
justify-content: space-between;
}
.profile-identity__person {
min-width: 0;
}
.profile-identity__text {
display: flex;
min-width: 0;
flex-direction: column;
gap: 2px;
}
.profile-identity__email {
word-break: break-all;
}
.profile-avatar {
display: flex;
width: 72px;
height: 72px;
flex: none;
align-items: center;
justify-content: center;
border-radius: 999px;
background: var(--el-color-primary-light-9);
color: var(--el-color-primary);
font-size: var(--el-font-size-extra-large);
font-weight: 600;
}
.profile-avatar--compact {
width: 48px;
height: 48px;
font-size: var(--el-font-size-large);
}
.profile-identity__actions,
.profile-card-head__actions {
flex: none;
}
.profile-form__grid {
display: grid;
grid-template-columns: 1fr;
gap: 0 16px;
}
.profile-control {
width: 100%;
}
@media (min-width: 768px) {
.profile-form__grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 640px) {
.profile-identity__body,
.profile-card-head {
align-items: stretch;
flex-direction: column;
}
.profile-identity__actions {
width: 100%;
}
.profile-identity__actions :deep(.el-button) {
flex: 1;
}
}
</style>
@@ -1,116 +1,101 @@
<script setup lang="ts"> <script setup lang="ts">
/** /**
* features/workspace/components/WorkspaceModals.vue * features/workspace/components/WorkspaceModals.vue
* 工作台弹窗:公告详情、修改密码、快捷问题删除、意见反馈。 * 用途:工作台共用弹窗。公告详情、修改密码、快捷问题删除、意见反馈。
* 依赖:workspace.context、DeleteConfirmDialog、GeneralFeedbackDialog、element-plus。
* 逻辑:WorkspaceLayout 挂载本组件。修改密码和公告详情用 Element 对话框。
* 快捷问题删除仍走原有确认弹窗,意见反馈走 GeneralFeedbackDialog。
*/ */
import { inject } from 'vue'; import { inject } from 'vue';
import { X } from 'lucide-vue-next'; import { ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElTag } from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/shared/styles/element-theme.css';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue'; import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import GeneralFeedbackDialog from '@/shared/components/GeneralFeedbackDialog.vue'; import GeneralFeedbackDialog from '@/shared/components/GeneralFeedbackDialog.vue';
import { getAuthHeaders } from '@/shared/utils/auth'; import { getAuthHeaders } from '@/shared/utils/auth';
import { WORKSPACE_KEY } from '../composables/workspace.context'; import { WORKSPACE_KEY } from '../composables/workspace.context';
const ws = inject(WORKSPACE_KEY)! as any; const ws = inject(WORKSPACE_KEY)! as any;
/**
* 提交修改密码。三个密码都填写后才请求,取消和空表单不提交。
*/
function submitPassword(): void {
const form = ws.passwordForm;
if (!String(form.current || '').trim() || !String(form.new || '').trim() || !String(form.confirm || '').trim()) {
return;
}
void ws.handleChangePassword();
}
</script> </script>
<template> <template>
<div> <div>
<div <ElDialog
v-if="ws.showAnnouncementModal && ws.selectedAnnouncement" :model-value="Boolean(ws.showAnnouncementModal && ws.selectedAnnouncement)"
class="dialog-overlay z-50 items-center animate-fade-in" :title="ws.selectedAnnouncement?.title || ''"
@click.self="ws.showAnnouncementModal = false" width="680px"
align-center
append-to-body
:close-on-click-modal="false"
@update:model-value="ws.showAnnouncementModal = $event"
> >
<div class="dialog-panel max-w-2xl max-h-[85vh] animate-slide-up"> <ElTag v-if="ws.selectedAnnouncement" effect="light">
<div class="dialog-header"> {{ new Date(ws.selectedAnnouncement.created_at).toLocaleDateString() }}
<div class="min-w-0"> </ElTag>
<span class="inline-flex rounded-full bg-brand-50 px-2 py-1 text-xs font-bold text-brand-600">{{ new Date(ws.selectedAnnouncement.created_at).toLocaleDateString() }}</span> <p class="workspace-announcement">{{ ws.selectedAnnouncement?.content }}</p>
<h3 class="mt-2 text-2xl font-bold text-primary">{{ ws.selectedAnnouncement.title }}</h3> <template #footer>
</div> <ElButton type="primary" @click="ws.showAnnouncementModal = false">{{ $t('admin.close') }}</ElButton>
<button type="button" class="btn-icon-ds shrink-0" :aria-label="$t('admin.close')" @click="ws.showAnnouncementModal = false"> </template>
<X class="w-5 h-5" /> </ElDialog>
</button>
</div>
<div class="dialog-body">
<p class="whitespace-pre-wrap leading-relaxed text-secondary">{{ ws.selectedAnnouncement.content }}</p>
</div>
<div class="dialog-footer">
<button type="button" @click="ws.showAnnouncementModal = false" class="btn-primary">
{{ $t('admin.close') }}
</button>
</div>
</div>
</div>
<div <ElDialog
v-if="ws.CHANGE_PASSWORD_ENABLED && ws.showPasswordModal" v-if="ws.CHANGE_PASSWORD_ENABLED"
class="dialog-overlay z-50 items-center" v-model="ws.showPasswordModal"
:title="$t('profile.changePassword')"
width="480px"
align-center
append-to-body
:close-on-click-modal="false"
:close-on-press-escape="!ws.isChangingPassword"
:show-close="!ws.isChangingPassword"
> >
<div class="dialog-panel max-w-md"> <ElForm label-position="top" @submit.prevent="submitPassword">
<div class="dialog-header"> <ElFormItem :label="$t('profile.currentPassword')">
<h3 class="section-title">{{ $t('profile.changePassword') || 'Change Password' }}</h3> <ElInput
<button
type="button"
class="btn-icon-ds"
:aria-label="$t('admin.close')"
:disabled="ws.isChangingPassword"
@click="ws.showPasswordModal = false"
>
<X class="w-5 h-5" />
</button>
</div>
<form @submit.prevent="ws.handleChangePassword">
<div class="dialog-body">
<div>
<label class="label-field">{{ $t('profile.currentPassword') || 'Current Password' }}</label>
<input
v-model="ws.passwordForm.current" v-model="ws.passwordForm.current"
type="password" type="password"
class="input-field mt-1" show-password
:disabled="ws.isChangingPassword" :disabled="ws.isChangingPassword"
required
/> />
</div> </ElFormItem>
<div> <ElFormItem :label="$t('profile.newPassword')">
<label class="label-field">{{ $t('profile.newPassword') || 'New Password' }}</label> <ElInput
<input
v-model="ws.passwordForm.new" v-model="ws.passwordForm.new"
type="password" type="password"
class="input-field mt-1" show-password
:disabled="ws.isChangingPassword" :disabled="ws.isChangingPassword"
required
/> />
</div> </ElFormItem>
<div> <ElFormItem :label="$t('profile.confirmPassword')">
<label class="label-field">{{ $t('profile.confirmPassword') || 'Confirm Password' }}</label> <ElInput
<input
v-model="ws.passwordForm.confirm" v-model="ws.passwordForm.confirm"
type="password" type="password"
class="input-field mt-1" show-password
:disabled="ws.isChangingPassword" :disabled="ws.isChangingPassword"
required
/> />
</div> </ElFormItem>
</div> </ElForm>
<div class="dialog-footer"> <template #footer>
<button <ElButton :disabled="ws.isChangingPassword" @click="ws.showPasswordModal = false">
type="button" {{ $t('profile.cancel') }}
:disabled="ws.isChangingPassword" </ElButton>
@click="ws.showPasswordModal = false" <ElButton type="primary" :loading="ws.isChangingPassword" @click="submitPassword">
class="btn-secondary flex-1 disabled:opacity-50 disabled:cursor-not-allowed" {{ ws.isChangingPassword ? $t('profile.changingPassword') : $t('profile.changePassword') }}
> </ElButton>
{{ $t('profile.cancel') || 'Cancel' }} </template>
</button> </ElDialog>
<button
type="submit"
:disabled="ws.isChangingPassword"
class="btn-primary flex-1 disabled:opacity-50 disabled:cursor-not-allowed"
>
{{ ws.isChangingPassword ? $t('profile.changingPassword') : ($t('profile.changePassword') || 'Update') }}
</button>
</div>
</form>
</div>
</div>
<DeleteConfirmDialog <DeleteConfirmDialog
v-model="ws.showDeleteQuickQuestionDialog" v-model="ws.showDeleteQuickQuestionDialog"
@@ -127,3 +112,12 @@ const ws = inject(WORKSPACE_KEY)! as any;
/> />
</div> </div>
</template> </template>
<style scoped>
.workspace-announcement {
margin: 12px 0 0;
white-space: pre-wrap;
line-height: 1.7;
color: var(--el-text-color-regular);
}
</style>
@@ -1,12 +1,16 @@
<script setup lang="ts">
/** /**
* features/workspace/pages/FeedbackPage.vue * features/workspace/pages/FeedbackPage.vue
* 意见反馈占位页;进入路由时由编排层打开 GeneralFeedbackDialog。 * 用途:意见反馈占位页。真正的表单由编排层打开 GeneralFeedbackDialog。
* 依赖:element-plus、element-theme.css。
* 逻辑:进入路由时工作台打开反馈弹窗,本页只保留空状态。
*/ */
<script setup lang="ts">
import { ElEmpty } from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/shared/styles/element-theme.css';
</script> </script>
<template> <template>
<div class="flex flex-col items-center justify-center py-20 text-muted"> <ElEmpty :description="$t('workspace.nav.feedback')" />
<p class="text-sm">{{ $t('workspace.nav.feedback') }}</p>
</div>
</template> </template>
+505 -167
View File
@@ -1,64 +1,139 @@
<script setup lang="ts">
/** /**
* features/workspace/pages/HomePage.vue * features/workspace/pages/HomePage.vue
* 应用管理 / 最近更新:收藏应用、快捷问题、嵌入 Agent、公告与应用列表。 * 用途:AI 工作台的应用管理和最近更新。收藏应用、快捷问题、嵌入 Agent、公告和应用列表。
* 依赖:workspace.context、AnnouncementCardCarousel、element-plus、element-theme.css。
* 逻辑:路由按 workspaceFocus 决定展示哪些分区。分区顺序和折叠仍由工作台状态管理。
* 应用卡片保持原有点击进入对话。快捷问题的新增和编辑用 Element 表单。
*/ */
<script setup lang="ts">
import { inject } from 'vue'; import { inject } from 'vue';
import { import {
LayoutGrid, Star, GripVertical, Plus, Trash2, Edit, ExternalLink, ArrowDown,
Bot, Megaphone, ChevronDown, ChevronUp, ArrowUp,
} from 'lucide-vue-next'; Bell,
Delete,
Edit,
Grid,
Monitor,
Plus,
Rank,
Star,
StarFilled,
TopRight,
} from '@element-plus/icons-vue';
import {
ElButton,
ElCard,
ElEmpty,
ElForm,
ElFormItem,
ElIcon,
ElInput,
ElOption,
ElRadioButton,
ElRadioGroup,
ElSelect,
ElTag,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/shared/styles/element-theme.css';
import AnnouncementCardCarousel from '@/shared/components/AnnouncementCardCarousel.vue'; import AnnouncementCardCarousel from '@/shared/components/AnnouncementCardCarousel.vue';
import { WORKSPACE_KEY } from '../composables/workspace.context'; import { WORKSPACE_KEY } from '../composables/workspace.context';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
const ws = inject(WORKSPACE_KEY)! as any; const ws = inject(WORKSPACE_KEY)! as any;
/**
* 应用分类单选。「全部」在 Element 里用空字符串,写回状态时仍是 null。
* @param value - 被选中的分类
*/
function onCategoryChange(value: string | number | boolean | undefined): void {
ws.selectedCategory = value ? String(value) : null;
}
/**
* 快捷问题的目标应用。未选择时下拉值为 undefined,保存仍写 null。
* @param value - 应用主键
*/
function onQuestionAgentChange(value: string | number | boolean | undefined): void {
ws.newQuestion.agent_id = value == null || value === '' ? null : Number(value);
}
/**
* 分区标题图标。公告、收藏、嵌入和其余列表各用一个 Element 图标。
* @param sectionId - 分区 id
* @returns 图标组件
*/
function sectionIcon(sectionId: string) {
if (sectionId === 'announcements') return Bell;
if (sectionId === 'favorites') return StarFilled;
if (sectionId === 'embedded') return Monitor;
return Grid;
}
/**
* 公告和收藏没有内容时,把提示放在标题旁边,避免空状态插图把分区撑高。
* @param section - 当前分区
* @returns 提示文案;有内容或已折叠时为空
*/
function sectionEmptyHint(section: { id: string; collapsed?: boolean }): string {
if (section.collapsed) return '';
if (section.id === 'announcements' && ws.announcements.length === 0) return t('workspace.announcements.noData');
if (section.id === 'favorites' && ws.favoriteAgents.length === 0) return t('workspace.noFavorites');
return '';
}
</script> </script>
<template> <template>
<div v-if="ws.wecomEntryHint" class="rounded-2xl border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-700"> <div v-if="ws.wecomEntryHint" class="workspace-hint">
{{ ws.wecomEntryHint }} {{ ws.wecomEntryHint }}
</div> </div>
<div <ElCard
v-for="(section, index) in ws.layoutSections" v-for="(section, index) in ws.layoutSections"
:id="`workspace-section-${section.id}`" :id="`workspace-section-${section.id}`"
:key="section.id" :key="section.id"
class="bg-transparent md:bg-surface md:rounded-3xl md:border md:border-subtle md:p-8 md:shadow-soft relative group transition-all scroll-mt-6" shadow="never"
:class="{ 'opacity-50 border-brand-300 border-dashed': ws.draggedSectionIndex === index }" class="workspace-section"
:class="{
'workspace-section--dragging': ws.draggedSectionIndex === index,
'workspace-section--compact': sectionEmptyHint(section),
}"
draggable="true" draggable="true"
@dragstart="ws.onDragStart(index)" @dragstart="ws.onDragStart(index)"
@dragover="ws.onDragOver" @dragover="ws.onDragOver"
@drop="ws.onDrop(index)" @drop="ws.onDrop(index)"
> >
<div class="absolute left-2 top-8 cursor-move opacity-0 group-hover:opacity-100 p-2 text-slate-300 hover:text-muted transition-opacity hidden md:block"> <div
<GripVertical class="w-5 h-5" /> class="workspace-section__head"
:class="{ 'workspace-section__head--compact': sectionEmptyHint(section) }"
>
<div class="workspace-section__lead">
<ElButton text class="workspace-section__title" @click="ws.toggleSectionCollapse(section)">
<ElIcon class="workspace-section__icon"><component :is="sectionIcon(section.id)" /></ElIcon>
<span class="section-title">{{ t(ws.getSectionTitleKey(section.id)) }}</span>
<ElIcon><component :is="section.collapsed ? ArrowDown : ArrowUp" /></ElIcon>
</ElButton>
<span v-if="sectionEmptyHint(section)" class="workspace-empty">{{ sectionEmptyHint(section) }}</span>
</div>
<ElButton
v-if="section.id === 'quick_questions' && !ws.isAddingQuestion && !section.collapsed"
link
type="primary"
:icon="Plus"
@click="ws.openAddQuestionForm"
>
{{ t('workspace.quickQuestions.add') }}
</ElButton>
<ElIcon class="workspace-section__grip">
<Rank />
</ElIcon>
</div> </div>
<div class="md:pl-6"> <div v-show="!section.collapsed">
<div class="flex justify-between items-center mb-6"> <div v-if="section.id === 'announcements' && ws.announcements.length > 0" class="workspace-announcements">
<h2 class="text-lg md:text-xl font-semibold text-primary flex items-center gap-2.5 cursor-pointer select-none" @click="ws.toggleSectionCollapse(section)">
<div class="p-2 rounded-lg" :class="{
'bg-emerald-50 text-emerald-600': section.id === 'announcements',
'bg-yellow-50 text-yellow-600': section.id === 'favorites',
'bg-brand-50 text-brand-600': section.id === 'quick_questions',
'bg-purple-50 text-purple-600': section.id === 'embedded',
'bg-slate-100 text-secondary': section.id === 'all_agents'
}">
<component :is="section.id === 'announcements' ? Megaphone : (section.id === 'favorites' ? Star : (section.id === 'embedded' ? Bot : LayoutGrid))" class="w-5 h-5" />
</div>
{{ $t(ws.getSectionTitleKey(section.id)) }}
<component :is="section.collapsed ? ChevronDown : ChevronUp" class="w-4 h-4 text-muted" />
</h2>
<button v-if="section.id === 'quick_questions' && !ws.isAddingQuestion && !section.collapsed" @click="ws.openAddQuestionForm" class="btn-ghost text-sm text-brand-600 hover:text-brand-700 hover:bg-brand-50">
<Plus class="w-4 h-4" /> {{ $t('workspace.quickQuestions.add') }}
</button>
</div>
<div v-show="!section.collapsed" class="animate-fade-in">
<!-- Content: Announcements -->
<div v-if="section.id === 'announcements'">
<div v-if="ws.announcements.length === 0" class="text-muted text-sm italic py-8 text-center bg-surface-soft rounded-xl border border-dashed border-default">{{ $t('workspace.announcements.noData') }}</div>
<div v-else class="max-w-2xl">
<AnnouncementCardCarousel <AnnouncementCardCarousel
:announcements="ws.announcements" :announcements="ws.announcements"
variant="workspace" variant="workspace"
@@ -67,142 +142,405 @@ const ws = inject(WORKSPACE_KEY)! as any;
@select="ws.openAnnouncement" @select="ws.openAnnouncement"
/> />
</div> </div>
</div>
<!-- Content: Favorites --> <div v-if="section.id === 'favorites' && ws.favoriteAgents.length > 0" class="workspace-card-grid">
<div v-if="section.id === 'favorites'"> <article
<div v-if="ws.favoriteAgents.length === 0" class="text-muted text-sm italic py-4 bg-surface-soft rounded-xl text-center border border-dashed border-default">{{ $t('workspace.noFavorites') }}</div> v-for="agent in ws.favoriteAgents"
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 sm:gap-6"> :key="agent.id"
<div v-for="agent in ws.favoriteAgents" :key="agent.id" @click="ws.navigateToChat(agent.id)" class="workspace-app-card"
class="card p-4 sm:p-5 cursor-pointer relative group/card hover:-translate-y-1 hover:shadow-lg hover:border-brand-200 bg-gradient-to-br from-white to-slate-50/50">
<div class="w-8 h-8 sm:w-12 sm:h-12 bg-brand-100 rounded-xl flex items-center justify-center text-brand-600 mb-3 sm:mb-4 shadow-sm group-hover/card:scale-110 transition-transform duration-300">
<img v-if="agent.icon_url" :src="agent.icon_url" class="w-5 h-5 sm:w-7 sm:h-7" />
<Bot v-else class="w-5 h-5 sm:w-7 sm:h-7" />
</div>
<div class="text-[15px] sm:text-base font-semibold text-primary mb-1 group-hover/card:text-brand-700 transition-colors truncate">{{ agent.name }}</div>
<div class="text-[13px] sm:text-xs text-muted truncate">{{ agent.description }}</div>
<button @click.stop="ws.toggleFavorite(agent.id)" class="absolute top-3 right-3 text-yellow-400 hover:text-yellow-500 hover:scale-110 transition-all opacity-0 group-hover/card:opacity-100">
<Star class="w-5 h-5 fill-current" />
</button>
</div>
</div>
</div>
<!-- Content: Quick Questions -->
<div v-if="section.id === 'quick_questions'">
<!-- Add Question Form -->
<div v-if="ws.isAddingQuestion" class="mb-6 p-6 bg-surface-soft border border-default rounded-2xl space-y-4 animate-fade-in">
<h3 class="font-bold text-primary">{{ ws.editingQuestionId ? $t('workspace.quickQuestions.edit') : $t('workspace.quickQuestions.addNew') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
<div class="space-y-1.5">
<label class="text-xs font-semibold text-muted uppercase">{{ $t('workspace.quickQuestions.fields.title') }}</label>
<input v-model="ws.newQuestion.title" class="input-field" :placeholder="$t('workspace.quickQuestions.fields.titlePlaceholder')" />
</div>
<div class="space-y-1.5">
<label class="text-xs font-semibold text-muted uppercase">{{ $t('workspace.quickQuestions.fields.targetAgent') }}</label>
<select v-model="ws.newQuestion.agent_id" class="input-field" :disabled="ws.agents.length === 0">
<option :value="null" disabled>{{ ws.agents.length === 0 ? $t('workspace.noAgents') : $t('workspace.quickQuestions.fields.selectAgent') }}</option>
<option v-for="agent in ws.agents" :key="agent.id" :value="agent.id">{{ agent.name }}</option>
</select>
</div>
<div class="col-span-1 md:col-span-2 space-y-1.5">
<label class="text-xs font-semibold text-muted uppercase">{{ $t('workspace.quickQuestions.fields.content') }}</label>
<textarea v-model="ws.newQuestion.question" rows="3" class="input-field" :placeholder="$t('workspace.quickQuestions.fields.contentPlaceholder')"></textarea>
</div>
</div>
<div class="flex justify-end gap-3 pt-2">
<button @click="ws.cancelAddQuestion" class="btn-secondary">{{ $t('workspace.cancel') }}</button>
<button @click="ws.saveQuickQuestion" class="btn-primary">{{ $t('workspace.save') }}</button>
</div>
</div>
<div v-if="ws.filteredQuickQuestions.length === 0 && !ws.isAddingQuestion" class="text-muted text-sm italic py-8 text-center bg-surface-soft rounded-xl border border-dashed border-default">{{ $t('workspace.quickQuestions.noDefined') }}</div>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<div v-for="qq in ws.filteredQuickQuestions" :key="qq.id"
@click="ws.navigateWithQuickQuestion(qq.agent_id, qq.question)"
class="group/item p-4 bg-surface border border-default rounded-xl hover:border-brand-500 hover:shadow-md transition-all cursor-pointer flex flex-col gap-3 relative h-full">
<div class="flex justify-between items-start">
<h4 class="font-bold text-primary group-hover/item:text-brand-600 transition-colors">{{ qq.title }}</h4>
<span class="text-[10px] font-bold px-2 py-0.5 bg-slate-100 text-secondary rounded-full uppercase tracking-wide">
{{ ws.getAgentName(qq.agent_id) }}
</span>
</div>
<p class="text-sm text-secondary line-clamp-2 leading-relaxed">{{ qq.question }}</p>
<div class="absolute top-2 right-2 flex gap-1 opacity-0 group-hover/item:opacity-100 transition-opacity bg-surface/90 backdrop-blur-sm p-1 rounded-lg">
<button @click.stop="ws.editQuickQuestion(qq)" class="p-1.5 rounded-lg text-muted hover:text-brand-600 hover:bg-brand-50 transition-colors">
<Edit class="w-4 h-4" />
</button>
<button @click.stop="ws.removeQuickQuestion(qq.id)" class="p-1.5 rounded-lg text-muted hover:text-red-600 hover:bg-red-50 transition-colors">
<Trash2 class="w-4 h-4" />
</button>
</div>
</div>
</div>
</div>
<!-- Content: Embedded Agents -->
<div v-if="section.id === 'embedded'">
<div v-if="ws.embeddedAgents.length === 0" class="text-muted text-sm italic py-4 bg-surface-soft rounded-xl text-center border border-dashed border-default">{{ $t('workspace.embedded.noData') }}</div>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div v-for="agent in ws.embeddedAgents" :key="agent.id" class="border border-default rounded-2xl overflow-hidden bg-surface shadow-sm hover:shadow-md transition-shadow h-[500px] flex flex-col">
<div class="bg-surface-soft px-4 py-3 text-sm font-bold text-secondary flex justify-between items-center border-b border-subtle">
<span>{{ agent.name }}</span>
<a :href="`/chat/${agent.id}`" target="_blank" class="text-brand-600 hover:text-brand-700 hover:bg-brand-50 p-1.5 rounded-lg transition-colors"><ExternalLink class="w-4 h-4"/></a>
</div>
<iframe v-if="agent.iframe_url" :src="agent.iframe_url" class="w-full flex-1 border-none bg-surface"></iframe>
<div v-else class="flex items-center justify-center flex-1 text-muted bg-surface-soft/50">{{ $t('workspace.embedded.noUrl') }}</div>
</div>
</div>
</div>
<!-- Content: All Agents -->
<div v-if="section.id === 'all_agents'">
<div class="mb-4 flex flex-wrap gap-2">
<button
type="button"
class="rounded-full px-3 py-1.5 text-xs font-medium transition-colors"
:class="!ws.selectedCategory ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'"
@click="ws.selectedCategory = null"
>
{{ $t('workspace.agentCategory.all') }}
</button>
<button
v-for="category in ws.agentCategories"
:key="category"
type="button"
class="rounded-full px-3 py-1.5 text-xs font-medium transition-colors"
:class="ws.selectedCategory === category ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'"
@click="ws.selectedCategory = category"
>
{{ category }}
</button>
</div>
<div class="mb-6">
<input v-model="ws.searchQuery" type="text" :placeholder="$t('workspace.search')" class="input-field max-w-md shadow-sm" />
</div>
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 sm:gap-6">
<div v-for="agent in ws.otherAgents" :key="agent.id"
@click="ws.navigateToChat(agent.id)" @click="ws.navigateToChat(agent.id)"
class="card card-mobile-compact cursor-pointer relative group/card hover:-translate-y-1 hover:border-brand-200"> >
<div class="flex items-start justify-between mb-2 sm:mb-4"> <div class="workspace-app-card__icon">
<div class="w-8 h-8 sm:w-10 sm:h-10 bg-surface-soft rounded-xl flex items-center justify-center text-muted group-hover/card:bg-brand-50 group-hover/card:text-brand-600 transition-colors"> <img v-if="agent.icon_url" :src="agent.icon_url" alt="" />
<img v-if="agent.icon_url" :src="agent.icon_url" class="w-4 h-4 sm:w-6 sm:h-6" /> <ElIcon v-else><Monitor /></ElIcon>
<Bot v-else class="w-4 h-4 sm:w-6 sm:h-6" />
</div>
<button @click.stop="ws.toggleFavorite(agent.id)" class="text-slate-200 hover:text-yellow-400 transition-colors">
<Star class="w-5 h-5" :class="{ 'fill-yellow-400 text-yellow-400': ws.favoriteAgentIds.includes(agent.id) }" />
</button>
</div>
<h3 class="text-[15px] sm:text-base font-semibold text-primary mb-1 group-hover/card:text-brand-700 transition-colors line-clamp-1 sm:line-clamp-2 leading-tight">{{ agent.name }}</h3>
<p class="text-[13px] sm:text-xs text-muted line-clamp-1 sm:line-clamp-2 h-4 sm:h-8 leading-relaxed">{{ agent.description }}</p>
</div>
</div> </div>
<h3 class="workspace-app-card__name">{{ agent.name }}</h3>
<p class="workspace-app-card__desc">{{ agent.description }}</p>
<ElButton
class="workspace-app-card__star"
link
:icon="StarFilled"
:title="t('workspace.favorites')"
@click.stop="ws.toggleFavorite(agent.id)"
/>
</article>
</div> </div>
<div v-if="section.id === 'quick_questions'">
<ElCard v-if="ws.isAddingQuestion" shadow="never" class="workspace-question-form">
<h3 class="section-title">
{{ ws.editingQuestionId ? t('workspace.quickQuestions.edit') : t('workspace.quickQuestions.addNew') }}
</h3>
<ElForm label-position="top">
<div class="workspace-question-form__grid">
<ElFormItem :label="t('workspace.quickQuestions.fields.title')">
<ElInput v-model="ws.newQuestion.title" :placeholder="t('workspace.quickQuestions.fields.titlePlaceholder')" />
</ElFormItem>
<ElFormItem :label="t('workspace.quickQuestions.fields.targetAgent')">
<ElSelect
class="workspace-question-form__select"
:model-value="ws.newQuestion.agent_id ?? undefined"
:disabled="ws.agents.length === 0"
:placeholder="ws.agents.length === 0 ? t('workspace.noAgents') : t('workspace.quickQuestions.fields.selectAgent')"
@update:model-value="onQuestionAgentChange"
>
<ElOption v-for="agent in ws.agents" :key="agent.id" :label="agent.name" :value="agent.id" />
</ElSelect>
</ElFormItem>
<ElFormItem class="workspace-question-form__wide" :label="t('workspace.quickQuestions.fields.content')">
<ElInput
v-model="ws.newQuestion.question"
type="textarea"
:rows="3"
:placeholder="t('workspace.quickQuestions.fields.contentPlaceholder')"
/>
</ElFormItem>
</div>
<div class="workspace-question-form__actions">
<ElButton @click="ws.cancelAddQuestion">{{ t('workspace.cancel') }}</ElButton>
<ElButton type="primary" @click="ws.saveQuickQuestion">{{ t('workspace.save') }}</ElButton>
</div>
</ElForm>
</ElCard>
<ElEmpty
v-if="ws.filteredQuickQuestions.length === 0 && !ws.isAddingQuestion"
:description="t('workspace.quickQuestions.noDefined')"
/>
<div v-else class="workspace-question-grid">
<article
v-for="qq in ws.filteredQuickQuestions"
:key="qq.id"
class="workspace-question-card"
@click="ws.navigateWithQuickQuestion(qq.agent_id, qq.question)"
>
<div class="workspace-question-card__head">
<h4>{{ qq.title }}</h4>
<ElTag effect="light">{{ ws.getAgentName(qq.agent_id) }}</ElTag>
</div>
<p>{{ qq.question }}</p>
<div class="workspace-question-card__actions">
<ElButton link type="primary" :icon="Edit" :title="t('workspace.quickQuestions.edit')" @click.stop="ws.editQuickQuestion(qq)" />
<ElButton link type="danger" :icon="Delete" :title="t('workspace.quickQuestions.deleteDialog.title')" @click.stop="ws.removeQuickQuestion(qq.id)" />
</div>
</article>
</div>
</div>
<div v-if="section.id === 'embedded'">
<ElEmpty v-if="ws.embeddedAgents.length === 0" :description="t('workspace.embedded.noData')" />
<div v-else class="workspace-embed-grid">
<article v-for="agent in ws.embeddedAgents" :key="agent.id" class="workspace-embed">
<div class="workspace-embed__bar">
<span>{{ agent.name }}</span>
<a class="workspace-embed__open" :href="`/chat/${agent.id}`" target="_blank" rel="noopener">
<ElIcon><TopRight /></ElIcon>
</a>
</div>
<iframe v-if="agent.iframe_url" :src="agent.iframe_url" class="workspace-embed__frame" />
<ElEmpty v-else :description="t('workspace.embedded.noUrl')" />
</article>
</div>
</div>
<div v-if="section.id === 'all_agents'" class="workspace-agents">
<ElRadioGroup
class="workspace-categories"
:model-value="ws.selectedCategory || ''"
@update:model-value="onCategoryChange"
>
<ElRadioButton value="">{{ t('workspace.agentCategory.all') }}</ElRadioButton>
<ElRadioButton v-for="category in ws.agentCategories" :key="category" :value="category">
{{ category }}
</ElRadioButton>
</ElRadioGroup>
<ElInput
v-model="ws.searchQuery"
class="workspace-search"
clearable
:placeholder="t('workspace.search')"
/>
<div class="workspace-card-grid">
<article
v-for="agent in ws.otherAgents"
:key="agent.id"
class="workspace-app-card"
@click="ws.navigateToChat(agent.id)"
>
<div class="workspace-app-card__top">
<div class="workspace-app-card__icon">
<img v-if="agent.icon_url" :src="agent.icon_url" alt="" />
<ElIcon v-else><Monitor /></ElIcon>
</div>
<ElButton
link
:icon="ws.favoriteAgentIds.includes(agent.id) ? StarFilled : Star"
:title="t('workspace.favorites')"
:class="{ 'workspace-app-card__star--on': ws.favoriteAgentIds.includes(agent.id) }"
@click.stop="ws.toggleFavorite(agent.id)"
/>
</div>
<h3 class="workspace-app-card__name">{{ agent.name }}</h3>
<p class="workspace-app-card__desc">{{ agent.description }}</p>
</article>
</div> </div>
</div> </div>
</div> </div>
</ElCard>
</template> </template>
<style scoped>
.workspace-hint {
margin-bottom: 16px;
padding: 12px 16px;
border: 1px solid var(--el-color-primary-light-7);
border-radius: var(--el-border-radius-base);
background: var(--el-color-primary-light-9);
color: var(--el-color-primary);
}
.workspace-section {
width: 100%;
margin-bottom: 16px;
}
.workspace-section--compact :deep(.el-card__body) {
padding-top: 8px;
padding-bottom: 8px;
}
.workspace-section__head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 16px;
}
.workspace-section__head--compact {
margin-bottom: 0;
}
.workspace-section__lead {
display: flex;
min-width: 0;
align-items: center;
gap: 12px;
}
.workspace-empty {
color: var(--el-text-color-secondary);
font-size: var(--el-font-size-small);
}
.workspace-section__title {
display: inline-flex;
align-items: center;
gap: 8px;
border: 0;
background: transparent;
cursor: pointer;
}
.workspace-section__icon {
color: var(--el-color-primary);
}
.workspace-section__grip {
color: var(--el-text-color-secondary);
cursor: grab;
}
.workspace-card-grid,
.workspace-question-grid,
.workspace-embed-grid {
display: grid;
gap: 16px;
}
.workspace-card-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.workspace-question-grid {
grid-template-columns: 1fr;
}
.workspace-embed-grid {
grid-template-columns: 1fr;
}
.workspace-app-card,
.workspace-question-card {
position: relative;
padding: 16px;
border: 1px solid var(--el-border-color-lighter);
border-radius: var(--el-border-radius-base);
background: var(--el-bg-color);
cursor: pointer;
}
.workspace-app-card__top,
.workspace-question-card__head,
.workspace-embed__bar,
.workspace-question-form__actions {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.workspace-app-card__icon {
display: flex;
width: 40px;
height: 40px;
align-items: center;
justify-content: center;
border-radius: 8px;
background: var(--el-color-primary-light-9);
color: var(--el-color-primary);
}
.workspace-app-card__icon img {
width: 24px;
height: 24px;
}
.workspace-app-card__name,
.workspace-question-card h4 {
margin: 8px 0 4px;
color: var(--el-text-color-primary);
font-size: var(--el-font-size-base);
font-weight: 600;
}
.workspace-app-card__desc,
.workspace-question-card p {
display: -webkit-box;
overflow: hidden;
margin: 0;
color: var(--el-text-color-secondary);
font-size: var(--el-font-size-small);
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
.workspace-app-card__star {
position: absolute;
top: 8px;
right: 8px;
}
.workspace-app-card__star--on {
color: var(--el-color-warning);
}
.workspace-question-card__actions {
position: absolute;
top: 8px;
right: 8px;
display: none;
}
.workspace-question-card:hover .workspace-question-card__actions {
display: flex;
}
.workspace-question-form {
margin-bottom: 16px;
}
.workspace-question-form__grid {
display: grid;
grid-template-columns: 1fr;
gap: 0 16px;
}
.workspace-question-form__select {
width: 100%;
}
.workspace-question-form__actions {
justify-content: flex-end;
}
.workspace-agents {
display: flex;
width: 100%;
flex-direction: column;
align-items: stretch;
}
.workspace-categories {
display: flex;
width: fit-content;
max-width: 100%;
flex-wrap: wrap;
}
.workspace-search {
display: flex;
width: min(100%, 24rem);
margin-top: 12px;
margin-bottom: 16px;
}
.workspace-announcements {
max-width: 42rem;
}
.workspace-embed {
display: flex;
height: 500px;
flex-direction: column;
overflow: hidden;
border: 1px solid var(--el-border-color-lighter);
border-radius: var(--el-border-radius-base);
}
.workspace-embed__bar {
padding: 8px 12px;
border-bottom: 1px solid var(--el-border-color-lighter);
background: var(--el-fill-color-light);
}
.workspace-embed__open {
display: inline-flex;
color: var(--el-color-primary);
}
.workspace-embed__frame {
width: 100%;
flex: 1;
border: 0;
}
@media (min-width: 768px) {
.workspace-card-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.workspace-question-grid,
.workspace-question-form__grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.workspace-question-form__wide {
grid-column: 1 / -1;
}
}
@media (min-width: 1024px) {
.workspace-card-grid,
.workspace-embed-grid {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
.workspace-embed-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.workspace-question-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
</style>
@@ -1,116 +1,243 @@
<script setup lang="ts">
/** /**
* features/workspace/pages/ScheduleRunsPage.vue * features/workspace/pages/ScheduleRunsPage.vue
* 排程执行记录:筛选、列表展示与结果 Excel 下载。 * 用途:工作台排程执行记录。筛选、列表和结果 Excel 下载。
* 依赖:workspace.context、element-plus、element-theme.css。
* 逻辑:筛选状态仍放在 useWorkspaceSchedule。查询和重置调用原有方法。
* 时间筛选继续使用本地日期时间字符串,清空后写回空字符串。
*/ */
<script setup lang="ts">
import { inject } from 'vue'; import { inject } from 'vue';
import { RefreshCw, Search, Download } from 'lucide-vue-next'; import { useI18n } from 'vue-i18n';
import { Download, Refresh, Search } from '@element-plus/icons-vue';
import {
ElButton,
ElDatePicker,
ElEmpty,
ElInput,
ElLoading,
ElOption,
ElSelect,
ElTable,
ElTableColumn,
ElTag,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/shared/styles/element-theme.css';
import { WORKSPACE_KEY } from '../composables/workspace.context'; import { WORKSPACE_KEY } from '../composables/workspace.context';
const vLoading = ElLoading.directive;
const { t } = useI18n();
const ws = inject(WORKSPACE_KEY)! as any; const ws = inject(WORKSPACE_KEY)! as any;
/**
* 执行状态对应的标签颜色。
* @param status - 执行状态
* @returns ElTag 的 type
*/
function scheduleStatusType(status: string): 'success' | 'warning' | 'danger' | 'info' {
if (status === 'success') return 'success';
if (status === 'failed') return 'danger';
if (status === 'running' || status === 'partial_failed') return 'warning';
return 'info';
}
/**
* 把日期选择器的清空值写回空字符串,避免把 null 传给原有筛选。
* @param key - 开始或结束时间
* @param value - 选择器回传值
*/
function onScheduleDate(key: 'wsScheduleStartedAfter' | 'wsScheduleStartedBefore', value: unknown): void {
ws[key] = typeof value === 'string' ? value : '';
}
/**
* 状态下拉清空后回到「全部」。
* @param value - 状态值
*/
function onScheduleStatus(value: unknown): void {
ws.wsScheduleStatusFilter = typeof value === 'string' && value ? value : 'all';
}
/**
* 状态下拉选项。全部由占位符表示,不作为可选值。
* @returns 除 all 以外的状态
*/
function scheduleStatusChoices(): { value: string; label: string }[] {
const options = (ws.wsScheduleStatusOptions || []) as { value: string; label: string }[];
return options.filter((item) => item.value !== 'all');
}
/**
* 触发方式文案。
* @param triggerType - 接口返回的触发类型
* @returns 已有 i18n 文案
*/
function triggerLabel(triggerType: string): string {
if (triggerType === 'manual') return t('workspace.schedule.trigger.manual');
if (triggerType === 'test') return t('workspace.schedule.trigger.test');
return t('workspace.schedule.trigger.timed');
}
/**
* 耗时展示。
* @param durationMs - 毫秒
* @returns 秒或毫秒;没有耗时时为短横线
*/
function durationText(durationMs: number | null | undefined): string {
if (durationMs == null) return '-';
return durationMs >= 1000 ? `${(durationMs / 1000).toFixed(1)}s` : `${durationMs}ms`;
}
</script> </script>
<template> <template>
<div class="space-y-5 animate-fade-in-up"> <div class="schedule-runs">
<div class="flex items-center justify-between"> <div class="schedule-runs__head">
<h2 class="text-2xl font-bold text-primary">{{ $t('workspace.schedule.title') }}</h2> <h2 class="section-title">{{ t('workspace.schedule.title') }}</h2>
<button <ElButton :icon="Refresh" @click="ws.loadWorkspaceScheduleRuns">
@click="ws.loadWorkspaceScheduleRuns" {{ t('workspace.schedule.refresh') }}
class="inline-flex items-center gap-1.5 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft" </ElButton>
</div>
<div class="schedule-runs__filters">
<label>
<span>{{ t('workspace.schedule.filters.name') }}</span>
<ElInput v-model="ws.wsScheduleNameFilter" class="schedule-runs__name" :placeholder="t('workspace.schedule.filters.namePlaceholder')" />
</label>
<label>
<span>{{ t('workspace.schedule.filters.start') }}</span>
<ElDatePicker
:model-value="ws.wsScheduleStartedAfter || undefined"
type="datetime"
value-format="YYYY-MM-DDTHH:mm:ss"
@update:model-value="onScheduleDate('wsScheduleStartedAfter', $event)"
/>
</label>
<label>
<span>{{ t('workspace.schedule.filters.end') }}</span>
<ElDatePicker
:model-value="ws.wsScheduleStartedBefore || undefined"
type="datetime"
value-format="YYYY-MM-DDTHH:mm:ss"
@update:model-value="onScheduleDate('wsScheduleStartedBefore', $event)"
/>
</label>
<label>
<span>{{ t('workspace.schedule.filters.status') }}</span>
<ElSelect
class="schedule-runs__status"
:model-value="ws.wsScheduleStatusFilter === 'all' ? undefined : ws.wsScheduleStatusFilter"
:placeholder="t('workspace.schedule.status.all')"
clearable
@update:model-value="onScheduleStatus"
@clear="onScheduleStatus(undefined)"
> >
<RefreshCw class="h-3.5 w-3.5" /> <ElOption
{{ $t('workspace.schedule.refresh') }} v-for="option in scheduleStatusChoices()"
</button> :key="option.value"
:label="option.label"
:value="option.value"
/>
</ElSelect>
</label>
<ElButton type="primary" :icon="Search" @click="ws.loadWorkspaceScheduleRuns">
{{ t('workspace.schedule.search') }}
</ElButton>
<ElButton @click="ws.resetWsScheduleFilters">{{ t('workspace.schedule.reset') }}</ElButton>
</div> </div>
<div class="flex flex-wrap items-end gap-3 rounded-2xl border border-default/80 bg-surface/70 px-4 py-3 shadow-sm">
<div>
<label class="mb-1 block text-xs font-medium text-muted">{{ $t('workspace.schedule.filters.name') }}</label>
<input type="text" v-model="ws.wsScheduleNameFilter" :placeholder="$t('workspace.schedule.filters.namePlaceholder')" :class="['!w-[150px]', ws.wsScheduleFilterInputClass]" />
</div>
<div>
<label class="mb-1 block text-xs font-medium text-muted">{{ $t('workspace.schedule.filters.start') }}</label>
<input type="datetime-local" step="1" v-model="ws.wsScheduleStartedAfter" :class="['!w-[170px]', ws.wsScheduleFilterInputClass]" />
</div>
<div>
<label class="mb-1 block text-xs font-medium text-muted">{{ $t('workspace.schedule.filters.end') }}</label>
<input type="datetime-local" step="1" v-model="ws.wsScheduleStartedBefore" :class="['!w-[170px]', ws.wsScheduleFilterInputClass]" />
</div>
<div>
<label class="mb-1 block text-xs font-medium text-muted">{{ $t('workspace.schedule.filters.status') }}</label>
<select v-model="ws.wsScheduleStatusFilter" :class="['!w-[120px]', ws.wsScheduleFilterInputClass]">
<option v-for="o in ws.wsScheduleStatusOptions" :key="o.value" :value="o.value">{{ o.label }}</option>
</select>
</div>
<button
@click="ws.loadWorkspaceScheduleRuns"
class="inline-flex items-center gap-1 rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-brand-700"
>
<Search class="h-3.5 w-3.5" />
{{ $t('workspace.schedule.search') }}
</button>
<button
@click="ws.resetWsScheduleFilters"
class="rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
>
{{ $t('workspace.schedule.reset') }}
</button>
</div>
<div v-if="ws.workspaceScheduleLoading" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">{{ $t('workspace.schedule.loading') }}</div>
<div v-else-if="ws.workspaceScheduleRuns.length === 0" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">{{ $t('workspace.schedule.empty') }}</div>
<div v-else class="overflow-hidden rounded-2xl border border-default bg-surface">
<div class="max-h-[calc(100vh-17rem)] overflow-auto scrollbar-thin">
<table class="w-full min-w-[1080px] text-sm">
<thead class="sticky top-0 z-10">
<tr class="border-b border-subtle bg-surface-soft">
<th class="min-w-[120px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.name') }}</th>
<th class="min-w-[168px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.runNo') }}</th>
<th class="min-w-[72px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.triggerType') }}</th>
<th class="min-w-[152px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.start') }}</th>
<th class="min-w-[152px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.end') }}</th>
<th class="min-w-[64px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.duration') }}</th>
<th class="min-w-[88px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.status') }}</th>
<th class="min-w-[72px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.total') }}</th>
<th class="min-w-[72px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.success') }}</th>
<th class="min-w-[72px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.failed') }}</th>
<th class="min-w-[72px] whitespace-nowrap bg-surface-soft px-4 py-3 text-left font-semibold text-secondary">{{ $t('workspace.schedule.columns.detail') }}</th> <ElEmpty v-if="!ws.workspaceScheduleLoading && ws.workspaceScheduleRuns.length === 0" :description="t('workspace.schedule.empty')" />
</tr> <ElTable
</thead> v-else
<tbody> v-loading="ws.workspaceScheduleLoading"
<tr v-for="r in ws.workspaceScheduleRuns" :key="r.id" class="border-b border-slate-50 transition-colors hover:bg-surface-soft/50"> class="schedule-runs__table"
<td class="whitespace-nowrap px-4 py-3 font-medium text-primary">{{ r.schedule_name || '-' }}</td> :data="ws.workspaceScheduleRuns"
<td class="whitespace-nowrap px-4 py-3 font-mono text-xs text-muted">{{ r.run_no }}</td> row-key="id"
<td class="whitespace-nowrap px-4 py-3 text-muted">{{ r.trigger_type === 'manual' ? $t('workspace.schedule.trigger.manual') : r.trigger_type === 'test' ? $t('workspace.schedule.trigger.test') : $t('workspace.schedule.trigger.timed') }}</td> :empty-text="t('workspace.schedule.empty')"
<td class="whitespace-nowrap px-4 py-3 text-muted">{{ ws.formatDateTime(r.started_at) }}</td>
<td class="whitespace-nowrap px-4 py-3 text-muted">{{ ws.formatDateTime(r.finished_at) }}</td>
<td class="whitespace-nowrap px-4 py-3 text-muted">{{ r.duration_ms != null ? (r.duration_ms >= 1000 ? (r.duration_ms / 1000).toFixed(1) + 's' : r.duration_ms + 'ms') : '-' }}</td>
<td class="whitespace-nowrap px-4 py-3">
<span class="inline-flex shrink-0 items-center whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-semibold" :class="ws.getWsScheduleStatusBadge(r.status).cls">
{{ ws.getWsScheduleStatusBadge(r.status).label }}
</span>
<span v-if="r.error_message && r.error_message !== '无待处理数据'" class="ml-1 text-xs text-muted" :title="r.error_message">...</span>
<span v-else-if="r.error_message === '无待处理数据'" class="ml-1 text-xs text-muted">({{ $t('workspace.schedule.noPendingData') }})</span>
</td>
<td class="whitespace-nowrap px-4 py-3 text-muted">{{ r.total_count || 0 }}</td>
<td class="whitespace-nowrap px-4 py-3 font-medium text-emerald-600">{{ r.success_count ?? 0 }}</td>
<td class="whitespace-nowrap px-4 py-3 font-medium text-rose-600">{{ r.failed_count ?? 0 }}</td>
<td class="whitespace-nowrap px-4 py-3">
<a
v-if="r.total_count > 0 && r.excel_file_name"
href="#"
@click.prevent="ws.downloadWsScheduleExcel(r.id)"
class="inline-flex items-center gap-1 rounded-lg border border-default px-2 py-1 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
> >
<Download class="h-3 w-3" /> <ElTableColumn :label="t('workspace.schedule.columns.name')" min-width="140">
{{ $t('workspace.schedule.download') }} <template #default="{ row }">{{ row.schedule_name || '-' }}</template>
</a> </ElTableColumn>
<span v-else class="text-xs text-slate-300">-</span> <ElTableColumn prop="run_no" :label="t('workspace.schedule.columns.runNo')" min-width="180" />
</td> <ElTableColumn :label="t('workspace.schedule.columns.triggerType')" min-width="100">
</tr> <template #default="{ row }">{{ triggerLabel(row.trigger_type) }}</template>
</tbody> </ElTableColumn>
</table> <ElTableColumn :label="t('workspace.schedule.columns.start')" min-width="170">
</div> <template #default="{ row }">{{ ws.formatDateTime(row.started_at) }}</template>
</div> </ElTableColumn>
<ElTableColumn :label="t('workspace.schedule.columns.end')" min-width="170">
<template #default="{ row }">{{ ws.formatDateTime(row.finished_at) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('workspace.schedule.columns.duration')" min-width="90">
<template #default="{ row }">{{ durationText(row.duration_ms) }}</template>
</ElTableColumn>
<ElTableColumn :label="t('workspace.schedule.columns.status')" min-width="140">
<template #default="{ row }">
<ElTag effect="light" :type="scheduleStatusType(row.status)">
{{ ws.getWsScheduleStatusBadge(row.status).label }}
</ElTag>
<span v-if="row.error_message && row.error_message !== '无待处理数据'" :title="row.error_message">...</span>
<span v-else-if="row.error_message === '无待处理数据'">({{ t('workspace.schedule.noPendingData') }})</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('workspace.schedule.columns.total')" min-width="80">
<template #default="{ row }">{{ row.total_count || 0 }}</template>
</ElTableColumn>
<ElTableColumn :label="t('workspace.schedule.columns.success')" min-width="80">
<template #default="{ row }">{{ row.success_count ?? 0 }}</template>
</ElTableColumn>
<ElTableColumn :label="t('workspace.schedule.columns.failed')" min-width="80">
<template #default="{ row }">{{ row.failed_count ?? 0 }}</template>
</ElTableColumn>
<ElTableColumn :label="t('workspace.schedule.columns.detail')" width="120" align="right">
<template #default="{ row }">
<ElButton
v-if="row.total_count > 0 && row.excel_file_name"
link
type="primary"
:icon="Download"
@click="ws.downloadWsScheduleExcel(row.id)"
>
{{ t('workspace.schedule.download') }}
</ElButton>
<span v-else>-</span>
</template>
</ElTableColumn>
</ElTable>
</div> </div>
</template> </template>
<style scoped>
.schedule-runs__head,
.schedule-runs__filters {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: 12px;
}
.schedule-runs__head {
align-items: center;
justify-content: space-between;
margin-bottom: 16px;
}
.schedule-runs__filters {
margin-bottom: 16px;
}
.schedule-runs__filters label {
display: flex;
flex-direction: column;
gap: 4px;
color: var(--el-text-color-secondary);
font-size: var(--el-font-size-small);
}
.schedule-runs__name {
width: 16rem;
}
.schedule-runs__status {
width: 11rem;
}
</style>
@@ -3,6 +3,7 @@
* 用途:锁定人工上传确认弹窗无障碍与无凭据提交契约。 * 用途:锁定人工上传确认弹窗无障碍与无凭据提交契约。
* 依赖:vitest、@vue/test-utils、vue-i18n、shipping-tasks API mock。 * 依赖:vitest、@vue/test-utils、vue-i18n、shipping-tasks API mock。
* 逻辑:打开时具备 dialog 角色;Escape 关闭;无需截图/PDF或回执即可确认;关闭后恢复先前焦点。 * 逻辑:打开时具备 dialog 角色;Escape 关闭;无需截图/PDF或回执即可确认;关闭后恢复先前焦点。
* ElDialog 传送到 body,断言改查 document.body,业务结果不变。
*/ */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mount, flushPromises } from '@vue/test-utils'; import { mount, flushPromises } from '@vue/test-utils';
@@ -59,9 +60,14 @@ describe('ManualUploadEvidenceDialog', () => {
it('exposes dialog accessibility attributes when open', async () => { it('exposes dialog accessibility attributes when open', async () => {
const wrapper = mountDialog(true); const wrapper = mountDialog(true);
await nextTick(); await nextTick();
const dialog = wrapper.get('[data-testid="manual-upload-evidence-dialog"]'); await flushPromises();
expect(dialog.attributes('role')).toBe('dialog'); const marked = document.body.querySelector('[data-testid="manual-upload-evidence-dialog"]');
expect(dialog.attributes('aria-modal')).toBe('true'); const dialog = marked?.getAttribute('role') === 'dialog'
? marked
: marked?.closest('[role="dialog"]') || document.body.querySelector('[role="dialog"]');
expect(dialog?.getAttribute('role')).toBe('dialog');
expect(dialog?.getAttribute('aria-modal')).toBe('true');
expect(dialog?.textContent).toContain('登记人工上传');
wrapper.unmount(); wrapper.unmount();
}); });
@@ -92,10 +98,11 @@ describe('ManualUploadEvidenceDialog', () => {
it('submits with business_no without file evidence or freight receipt', async () => { it('submits with business_no without file evidence or freight receipt', async () => {
const wrapper = mountDialog(true); const wrapper = mountDialog(true);
await nextTick(); await nextTick();
const submit = wrapper.findAll('button').find((btn) => btn.text().includes('确认已上传')); await flushPromises();
const submit = Array.from(document.body.querySelectorAll('button')).find((btn) => btn.textContent?.includes('确认已上传'));
expect(submit).toBeTruthy(); expect(submit).toBeTruthy();
expect(submit!.attributes('disabled')).toBeUndefined(); expect(submit!.hasAttribute('disabled')).toBe(false);
await submit!.trigger('click'); submit!.click();
await flushPromises(); await flushPromises();
expect(wrapper.emitted('success')).toHaveLength(1); expect(wrapper.emitted('success')).toHaveLength(1);
wrapper.unmount(); wrapper.unmount();
@@ -1,13 +1,14 @@
/** /**
* features/workspace/shipping-task-center/ManualUploadEvidenceDialog.vue * features/workspace/shipping-task-center/ManualUploadEvidenceDialog.vue
* 用途:人工确认货代已上传当前发货通知 Excel 的对话框。 * 用途:人工确认货代已上传当前发货通知 Excel 的对话框。
* 依赖:workspace shipping-tasks.api、Vue watch/nextTick。 * 依赖:workspace shipping-tasks.api、element-plus、Vue watch/nextTick。
* 逻辑:由 TaskTodoPanel 在 mark_manual_uploaded 动作时打开;不采集截图/PDF或回执号; * 逻辑:由 TaskTodoPanel 在 mark_manual_uploaded 动作时打开;不采集截图/PDF或回执号。
* 对齐复核弹层无障碍:role=dialog、aria-modal、焦点陷阱、Escape、关闭后焦点恢复。 * 对话框语义、Escape 与焦点恢复交给 ElDialog;样式由任务中心页或对话页引入。
*/ */
<script setup lang="ts"> <script setup lang="ts">
import { nextTick, onBeforeUnmount, ref, watch } from 'vue'; import { nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { ElButton, ElDialog, ElText } from 'element-plus';
import { markWorkspaceShippingManualUploaded } from '@/features/workspace/api/shipping-tasks.api'; import { markWorkspaceShippingManualUploaded } from '@/features/workspace/api/shipping-tasks.api';
const props = defineProps<{ const props = defineProps<{
@@ -25,29 +26,10 @@ const emit = defineEmits<{
const { t } = useI18n(); const { t } = useI18n();
const busy = ref(false); const busy = ref(false);
const error = ref(''); const error = ref('');
const panelRef = ref<HTMLElement | null>(null);
let previouslyFocused: HTMLElement | null = null; let previouslyFocused: HTMLElement | null = null;
const FOCUSABLE_SELECTOR = [
'a[href]',
'button:not([disabled])',
'textarea:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(',');
/** /**
* 收集弹窗内可聚焦控件,供 Tab 陷阱使用。 * 关闭对话框并清空错误。提交中不允许关。
*/
function focusableNodes(): HTMLElement[] {
if (!panelRef.value) return [];
return Array.from(panelRef.value.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))
.filter((node) => !node.hasAttribute('disabled') && node.getAttribute('aria-hidden') !== 'true');
}
/**
* 关闭对话框并清空本地表单。
*/ */
function close() { function close() {
if (busy.value) return; if (busy.value) return;
@@ -56,38 +38,22 @@ function close() {
} }
/** /**
* Escape 关闭;Tab / Shift+Tab 在弹窗内循环。 * ElDialog 关闭前拦截。提交中不调用 done,遮罩和 Escape 都留在弹窗里。
* @param done - Element 提供的真正关闭回调
*/
function onBeforeClose(done: () => void) {
if (busy.value) return;
done();
}
/**
* Escape 关闭。ElDialog 在 jsdom 里不一定收到测试派发的键盘事件,这里与它对齐。
* @param event - 文档上的按键
*/ */
function onKeydown(event: KeyboardEvent) { function onKeydown(event: KeyboardEvent) {
if (!props.open) return; if (!props.open || event.key !== 'Escape' || busy.value) return;
if (event.key === 'Escape') {
if (busy.value) return;
event.preventDefault(); event.preventDefault();
event.stopPropagation();
close(); close();
return;
}
if (event.key !== 'Tab') return;
const nodes = focusableNodes();
const first = nodes[0];
const last = nodes[nodes.length - 1];
if (!first || !last) {
event.preventDefault();
return;
}
const active = document.activeElement as HTMLElement | null;
const inside = Boolean(active && panelRef.value?.contains(active));
if (event.shiftKey) {
if (!inside || active === first) {
event.preventDefault();
last.focus();
}
return;
}
if (!inside || active === last) {
event.preventDefault();
first.focus();
}
} }
watch( watch(
@@ -99,8 +65,6 @@ watch(
? document.activeElement ? document.activeElement
: null; : null;
document.addEventListener('keydown', onKeydown, true); document.addEventListener('keydown', onKeydown, true);
await nextTick();
(focusableNodes()[0] || panelRef.value)?.focus();
return; return;
} }
if (!isOpen && wasOpen) { if (!isOpen && wasOpen) {
@@ -143,50 +107,25 @@ async function submit() {
</script> </script>
<template> <template>
<div <ElDialog
v-if="open" :model-value="open"
class="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" :title="t('workspace.shippingNotice.manualUpload.title')"
@click.self="close" width="480px"
> align-center
<div append-to-body
ref="panelRef" :close-on-click-modal="false"
role="dialog" :close-on-press-escape="!busy"
aria-modal="true" :before-close="onBeforeClose"
:aria-labelledby="'manual-upload-evidence-title'"
tabindex="-1"
class="w-full max-w-md rounded-2xl border border-default bg-surface p-5 shadow-xl outline-none"
data-testid="manual-upload-evidence-dialog" data-testid="manual-upload-evidence-dialog"
@update:model-value="(value) => { if (!value) close(); }"
> >
<h3 <ElText>{{ t('workspace.shippingNotice.manualUpload.hint') }}</ElText>
id="manual-upload-evidence-title" <ElText v-if="error" type="danger">{{ error }}</ElText>
class="text-base font-semibold text-primary" <template #footer>
> <ElButton :disabled="busy" @click="close">{{ t('workspace.shippingNotice.manualUpload.cancel') }}</ElButton>
{{ $t('workspace.shippingNotice.manualUpload.title') }} <ElButton type="primary" :loading="busy" :disabled="busy || disabled" @click="submit">
</h3> {{ busy ? t('workspace.shippingNotice.manualUpload.submitting') : t('workspace.shippingNotice.manualUpload.submit') }}
<p class="mt-1 text-sm text-muted"> </ElButton>
{{ $t('workspace.shippingNotice.manualUpload.hint') }} </template>
</p> </ElDialog>
<p v-if="error" class="mt-3 text-sm text-rose-600" role="alert">{{ error }}</p>
<div class="mt-5 flex justify-end gap-2">
<button
type="button"
class="rounded-xl border border-default px-3 py-1.5 text-sm"
:disabled="busy"
@click="close"
>
{{ $t('workspace.shippingNotice.manualUpload.cancel') }}
</button>
<button
type="button"
class="rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
:disabled="busy || disabled"
@click="submit"
>
{{ busy ? $t('workspace.shippingNotice.manualUpload.submitting') : $t('workspace.shippingNotice.manualUpload.submit') }}
</button>
</div>
</div>
</div>
</template> </template>
@@ -1,14 +1,15 @@
<!-- <!--
features/workspace/shipping-task-center/ShippingDoneLineReport.vue features/workspace/shipping-task-center/ShippingDoneLineReport.vue
用途:已完成桶「通知完成」子视图——跨 OT 平铺的明细行报表(13 列 + 筛选 + 导出)。 用途:已完成桶「通知完成」子视图——跨 OT 平铺的明细行报表(13 列 + 筛选 + 导出)。
依赖:shipping-tasks.api 类型;导出下载由父级执行。 依赖:shipping-tasks.api 类型、element-plus;导出下载由父级执行。
逻辑:只读报表(无抽屉、无行操作);首列 OT/business 编号仅页面展示, 逻辑:只读报表(无抽屉、无行操作);首列 OT/business 编号仅页面展示,
导出为固定 12 列标准格式(后端裁决);分页按明细行计。 导出为固定 12 列标准格式(后端裁决);分页按明细行计。样式由任务中心页引入。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { Download } from 'lucide-vue-next'; import { computed } from 'vue';
import type { ShippingDoneLineItem } from '@/features/workspace/api/shipping-tasks.api'; import { Download } from '@element-plus/icons-vue';
import type { ShippingDoneLineFilters } from '@/features/workspace/api/shipping-tasks.api'; import { ElButton, ElDatePicker, ElInput, ElPagination, ElTable, ElTableColumn } from 'element-plus';
import type { ShippingDoneLineFilters, ShippingDoneLineItem } from '@/features/workspace/api/shipping-tasks.api';
const props = defineProps<{ const props = defineProps<{
items: ShippingDoneLineItem[]; items: ShippingDoneLineItem[];
@@ -27,13 +28,26 @@ const emit = defineEmits<{
(event: 'export'): void; (event: 'export'): void;
}>(); }>();
const totalPages = () => Math.max(1, Math.ceil(props.total / props.pageSize)); const totalPages = computed(() => Math.max(1, Math.ceil(props.total / props.pageSize)));
function setFilter(key: keyof ShippingDoneLineFilters, event: Event) { /**
const value = String((event.target as HTMLInputElement).value || ''); * 写回一条筛选草稿。日期清空写回空字符串,与原 input 空值一致。
emit('update:filters', { ...props.filters, [key]: value }); * @param key - 筛选字段
* @param value - 输入值;日期清空为 undefined
*/
function setFilter(key: keyof ShippingDoneLineFilters, value: string | undefined) {
emit('update:filters', { ...props.filters, [key]: value || '' });
} }
/**
* 明细行主键。
* @param line - 完成明细
*/
function doneLineKey(line: ShippingDoneLineItem): string {
return `${line.task_no}-${line.line_no}-${line.part_number || ''}`;
}
/** 通知父级按当前筛选导出。 */
function onExport(): void { function onExport(): void {
emit('export'); emit('export');
} }
@@ -42,140 +56,125 @@ function onExport(): void {
<template> <template>
<div class="space-y-3"> <div class="space-y-3">
<div class="flex flex-wrap items-end gap-3 rounded-2xl border border-default bg-surface px-4 py-3"> <div class="flex flex-wrap items-end gap-3 rounded-2xl border border-default bg-surface px-4 py-3">
<label class="space-y-1"> <label class="done-filter">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.customer') }}</span> <span>{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.customer') }}</span>
<input <ElInput
type="text" :model-value="filters?.customer || ''"
class="input-field text-sm min-w-[10rem]"
:value="filters?.customer || ''"
:placeholder="$t('workspace.shippingNotice.myTodos.filters.customerPlaceholder')" :placeholder="$t('workspace.shippingNotice.myTodos.filters.customerPlaceholder')"
data-testid="done-lines-filter-customer" data-testid="done-lines-filter-customer"
@change="setFilter('customer', $event)" @update:model-value="setFilter('customer', $event)"
@keyup.enter="emit('apply')" @keyup.enter="emit('apply')"
> />
</label> </label>
<label class="space-y-1"> <label class="done-filter">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.partNumber') }}</span> <span>{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.partNumber') }}</span>
<input <ElInput
type="text" :model-value="filters?.part_number || ''"
class="input-field text-sm min-w-[10rem]"
:value="filters?.part_number || ''"
data-testid="done-lines-filter-part" data-testid="done-lines-filter-part"
@change="setFilter('part_number', $event)" @update:model-value="setFilter('part_number', $event)"
@keyup.enter="emit('apply')" @keyup.enter="emit('apply')"
> />
</label> </label>
<label class="space-y-1"> <label class="done-filter">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.dateFrom') }}</span> <span>{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.dateFrom') }}</span>
<input <ElDatePicker
:model-value="filters?.notice_date_from || undefined"
type="date" type="date"
class="input-field text-sm" value-format="YYYY-MM-DD"
:value="filters?.notice_date_from || ''"
data-testid="done-lines-filter-date-from" data-testid="done-lines-filter-date-from"
@change="setFilter('notice_date_from', $event)" @update:model-value="setFilter('notice_date_from', $event)"
> />
</label> </label>
<label class="space-y-1"> <label class="done-filter">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.dateTo') }}</span> <span>{{ $t('workspace.shippingNotice.myTodos.doneReport.filters.dateTo') }}</span>
<input <ElDatePicker
:model-value="filters?.notice_date_to || undefined"
type="date" type="date"
class="input-field text-sm" value-format="YYYY-MM-DD"
:value="filters?.notice_date_to || ''"
data-testid="done-lines-filter-date-to" data-testid="done-lines-filter-date-to"
@change="setFilter('notice_date_to', $event)" @update:model-value="setFilter('notice_date_to', $event)"
> />
</label> </label>
<div class="flex gap-2"> <div class="flex gap-2">
<button <ElButton type="primary" :loading="loading" @click="emit('apply')">
type="button"
class="rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
:disabled="loading"
@click="emit('apply')"
>
{{ $t('workspace.shippingNotice.myTodos.filters.apply') }} {{ $t('workspace.shippingNotice.myTodos.filters.apply') }}
</button> </ElButton>
<button <ElButton
type="button" :icon="Download"
class="inline-flex items-center gap-1.5 rounded-xl border border-brand-300 px-3 py-1.5 text-sm font-medium text-brand-700 hover:bg-brand-50 disabled:opacity-50" :loading="exportBusy"
:disabled="exportBusy || loading || !total" :disabled="loading || !total"
data-testid="done-lines-export" data-testid="done-lines-export"
@click="onExport" @click="onExport"
> >
<Download class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.myTodos.doneReport.export') }} {{ $t('workspace.shippingNotice.myTodos.doneReport.export') }}
</button> </ElButton>
</div> </div>
</div> </div>
<div v-if="loading" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted"> <div v-if="loading">{{ $t('workspace.shippingNotice.loading') }}</div>
{{ $t('workspace.shippingNotice.loading') }} <div v-else-if="!items.length">{{ $t('workspace.shippingNotice.myTodos.empty') }}</div>
</div> <div v-else data-testid="done-lines-table">
<div v-else-if="!items.length" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted"> <ElTable :data="items" :row-key="doneLineKey">
{{ $t('workspace.shippingNotice.myTodos.empty') }} <ElTableColumn :label="$t('workspace.shippingNotice.myTodos.doneReport.columns.taskNo')" min-width="140">
</div> <template #default="{ row }">{{ (row as ShippingDoneLineItem).business_no || (row as ShippingDoneLineItem).task_no }}</template>
<div v-else class="overflow-x-auto rounded-2xl border border-default bg-surface"> </ElTableColumn>
<table class="w-full min-w-[1200px] border-collapse text-[13px]" data-testid="done-lines-table"> <ElTableColumn :label="$t('workspace.shippingNotice.myTodos.doneReport.columns.customer')" min-width="120">
<thead> <template #default="{ row }">{{ (row as ShippingDoneLineItem).customer_name || '—' }}</template>
<tr class="border-b border-default bg-surface-soft/60 text-left text-xs text-muted"> </ElTableColumn>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.taskNo') }}</th> <ElTableColumn :label="$t('workspace.shippingNotice.myTodos.doneReport.columns.customerCode')" min-width="120">
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.customer') }}</th> <template #default="{ row }">{{ (row as ShippingDoneLineItem).customer_code || '—' }}</template>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.customerCode') }}</th> </ElTableColumn>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.orderDate') }}</th> <ElTableColumn :label="$t('workspace.shippingNotice.myTodos.doneReport.columns.orderDate')" min-width="120">
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.lineNo') }}</th> <template #default="{ row }">{{ (row as ShippingDoneLineItem).order_date || '—' }}</template>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.partNumber') }}</th> </ElTableColumn>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.qty') }}</th> <ElTableColumn :label="$t('workspace.shippingNotice.myTodos.doneReport.columns.lineNo')" min-width="80">
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.requiredDate') }}</th> <template #default="{ row }">{{ (row as ShippingDoneLineItem).line_no }}</template>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.customerPo') }}</th> </ElTableColumn>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.usedQty') }}</th> <ElTableColumn :label="$t('workspace.shippingNotice.myTodos.doneReport.columns.partNumber')" min-width="140">
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.openQty') }}</th> <template #default="{ row }">{{ (row as ShippingDoneLineItem).part_number || '—' }}</template>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.sourceOrderNo') }}</th> </ElTableColumn>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.doneReport.columns.unitPrice') }}</th> <ElTableColumn :label="$t('workspace.shippingNotice.myTodos.doneReport.columns.qty')" min-width="80">
</tr> <template #default="{ row }">{{ (row as ShippingDoneLineItem).qty ?? '' }}</template>
</thead> </ElTableColumn>
<tbody> <ElTableColumn :label="$t('workspace.shippingNotice.myTodos.doneReport.columns.requiredDate')" min-width="120">
<tr <template #default="{ row }">{{ (row as ShippingDoneLineItem).required_date || '—' }}</template>
v-for="line in items" </ElTableColumn>
:key="`${line.task_no}-${line.line_no}`" <ElTableColumn :label="$t('workspace.shippingNotice.myTodos.doneReport.columns.customerPo')" min-width="120">
class="border-b border-[#f0f3f8]" <template #default="{ row }">{{ (row as ShippingDoneLineItem).customer_po_number || '—' }}</template>
> </ElTableColumn>
<td class="px-3 py-2 font-mono text-xs font-semibold text-primary"> <ElTableColumn :label="$t('workspace.shippingNotice.myTodos.doneReport.columns.usedQty')" min-width="100">
{{ line.business_no || line.task_no }} <template #default="{ row }">{{ (row as ShippingDoneLineItem).used_qty ?? '' }}</template>
</td> </ElTableColumn>
<td class="px-3 py-2">{{ line.customer_name || '—' }}</td> <ElTableColumn :label="$t('workspace.shippingNotice.myTodos.doneReport.columns.openQty')" min-width="100">
<td class="px-3 py-2">{{ line.customer_code || '—' }}</td> <template #default="{ row }">{{ (row as ShippingDoneLineItem).open_qty ?? '' }}</template>
<td class="px-3 py-2 tabular-nums">{{ line.order_date || '—' }}</td> </ElTableColumn>
<td class="px-3 py-2 tabular-nums">{{ line.line_no }}</td> <ElTableColumn :label="$t('workspace.shippingNotice.myTodos.doneReport.columns.sourceOrderNo')" min-width="140">
<td class="px-3 py-2 font-mono">{{ line.part_number || '—' }}</td> <template #default="{ row }">{{ (row as ShippingDoneLineItem).source_order_number || '—' }}</template>
<td class="px-3 py-2 tabular-nums">{{ line.qty ?? '' }}</td> </ElTableColumn>
<td class="px-3 py-2 tabular-nums">{{ line.required_date || '—' }}</td> <ElTableColumn :label="$t('workspace.shippingNotice.myTodos.doneReport.columns.unitPrice')" min-width="100">
<td class="px-3 py-2">{{ line.customer_po_number || '—' }}</td> <template #default="{ row }">{{ (row as ShippingDoneLineItem).unit_price ?? '' }}</template>
<td class="px-3 py-2 tabular-nums">{{ line.used_qty ?? '' }}</td> </ElTableColumn>
<td class="px-3 py-2 tabular-nums">{{ line.open_qty ?? '' }}</td> </ElTable>
<td class="px-3 py-2 font-mono">{{ line.source_order_number || '—' }}</td>
<td class="px-3 py-2 tabular-nums">{{ line.unit_price ?? '' }}</td>
</tr>
</tbody>
</table>
</div> </div>
<div v-if="totalPages() > 1" class="flex items-center justify-between gap-2 text-xs text-muted"> <ElPagination
<button v-if="totalPages > 1"
type="button" :current-page="page"
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50" :page-size="pageSize"
:disabled="page <= 1 || loading" :total="total"
@click="emit('page-change', page - 1)" layout="prev, pager, next"
> background
{{ $t('workspace.shippingNotice.pagination.previous') }} :disabled="loading"
</button> @current-change="emit('page-change', $event)"
<span>{{ page }}/{{ totalPages() }}</span> />
<button
type="button"
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50"
:disabled="page >= totalPages() || loading"
@click="emit('page-change', page + 1)"
>
{{ $t('workspace.shippingNotice.pagination.next') }}
</button>
</div>
</div> </div>
</template> </template>
<style scoped>
.done-filter {
display: flex;
flex-direction: column;
gap: 4px;
width: 12rem;
}
</style>
@@ -1,13 +1,25 @@
/** /**
* features/workspace/shipping-task-center/ShippingRunProgressTable.vue * features/workspace/shipping-task-center/ShippingRunProgressTable.vue
* 用途:任务中心「我的识别」续办表——展示用户自有抽取 Run 的阶段、耗时、取消态与续办动作。 * 用途:任务中心「我的识别」续办表——展示用户自有抽取 Run 的阶段、耗时、取消态与续办动作。
* 依赖:shipping.api 分页列表/取消/重试、vue-i18n、vue-router、orderExtractionProgressDisplay。 * 依赖:shipping.api 分页列表/取消/重试、element-plus、vue-i18n、vue-router、orderExtractionProgressDisplay。
* 逻辑:事实来自后端投影;打开会话/复核深链到 Chat;取消/重试复用工作台 API。 * 逻辑:事实来自后端投影;打开会话/复核深链到 Chat;取消/重试复用工作台 API。样式由任务中心页引入。
*/ */
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, ref, watch } from 'vue'; import { onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import {
ElButton,
ElInput,
ElLoading,
ElOption,
ElPagination,
ElSelect,
ElTable,
ElTableColumn,
ElTag,
ElText,
} from 'element-plus';
import { import {
cancelWorkspaceShippingOrderExtractionRun, cancelWorkspaceShippingOrderExtractionRun,
listShippingChatAgents, listShippingChatAgents,
@@ -18,6 +30,7 @@ import {
import type { ShippingOrderExtractionRun } from '@/features/chat/types/shipping.api.types'; import type { ShippingOrderExtractionRun } from '@/features/chat/types/shipping.api.types';
import { formatOrderExtractionElapsed, resolveOrderExtractionRunStageKey } from '@/features/chat/shipping/orderExtractionProgressDisplay'; import { formatOrderExtractionElapsed, resolveOrderExtractionRunStageKey } from '@/features/chat/shipping/orderExtractionProgressDisplay';
const vLoading = ElLoading.directive;
const { t, te } = useI18n(); const { t, te } = useI18n();
const router = useRouter(); const router = useRouter();
@@ -32,6 +45,7 @@ const total = ref(0);
const rows = ref<ShippingOrderExtractionRun[]>([]); const rows = ref<ShippingOrderExtractionRun[]>([]);
const chatAgentId = ref<number | null>(null); const chatAgentId = ref<number | null>(null);
const error = ref(''); const error = ref('');
const statusOptions = ['queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'];
/** /**
* 解析货代 Chat Agent,供会话深链。 * 解析货代 Chat Agent,供会话深链。
@@ -70,6 +84,7 @@ async function load() {
/** /**
* 用户可见阶段文案;无投影时回退状态文案。 * 用户可见阶段文案;无投影时回退状态文案。
* v2:key 构造改走共享 resolveOrderExtractionRunStageKey(输出不变,仅事实解析同源)。 * v2:key 构造改走共享 resolveOrderExtractionRunStageKey(输出不变,仅事实解析同源)。
* @param run - 识别 Run
*/ */
function stageLabel(run: ShippingOrderExtractionRun): string { function stageLabel(run: ShippingOrderExtractionRun): string {
const stage = String(run.current_activity?.user_visible_stage || '').trim(); const stage = String(run.current_activity?.user_visible_stage || '').trim();
@@ -83,6 +98,7 @@ function stageLabel(run: ShippingOrderExtractionRun): string {
/** /**
* 打开所属会话;活动 Run 进入聊天进度面。 * 打开所属会话;活动 Run 进入聊天进度面。
* @param run - 识别 Run
*/ */
async function openInChat(run: ShippingOrderExtractionRun) { async function openInChat(run: ShippingOrderExtractionRun) {
const agentId = Number(run.agent_id || chatAgentId.value || 0); const agentId = Number(run.agent_id || chatAgentId.value || 0);
@@ -97,7 +113,11 @@ async function openInChat(run: ShippingOrderExtractionRun) {
await router.push({ path: `/chat/${agentId}`, query }); await router.push({ path: `/chat/${agentId}`, query });
} }
/** 请求取消整批;排队立即取消,执行中进入正在取消。 */ /**
* 请求取消整批;排队立即取消,执行中进入正在取消。
* @param run - 识别 Run
* @param reason - 可选取消原因
*/
async function submitCancelRun(run: ShippingOrderExtractionRun, reason?: string | null) { async function submitCancelRun(run: ShippingOrderExtractionRun, reason?: string | null) {
if (actingRunNo.value) return; if (actingRunNo.value) return;
actingRunNo.value = run.run_no; actingRunNo.value = run.run_no;
@@ -117,6 +137,7 @@ async function submitCancelRun(run: ShippingOrderExtractionRun, reason?: string
/** /**
* 展开/收起单行取消表单。 * 展开/收起单行取消表单。
* @param run - 识别 Run
*/ */
function beginCancelRun(run: ShippingOrderExtractionRun) { function beginCancelRun(run: ShippingOrderExtractionRun) {
if (pendingCancelRunNo.value === run.run_no) { if (pendingCancelRunNo.value === run.run_no) {
@@ -130,6 +151,7 @@ function beginCancelRun(run: ShippingOrderExtractionRun) {
/** /**
* 重试失败附件。 * 重试失败附件。
* @param run - 识别 Run
*/ */
async function retryRun(run: ShippingOrderExtractionRun) { async function retryRun(run: ShippingOrderExtractionRun) {
if (actingRunNo.value) return; if (actingRunNo.value) return;
@@ -144,6 +166,23 @@ async function retryRun(run: ShippingOrderExtractionRun) {
} }
} }
/**
* 状态筛选。清空写回空字符串,接口仍查全部状态。
* @param value - 状态码;清空为 undefined
*/
function onStatusChange(value: string | undefined): void {
status.value = value ?? '';
}
/**
* 翻页并重新加载。
* @param nextPage - 1-based 页码
*/
function onPageChange(nextPage: number): void {
page.value = nextPage;
void load();
}
watch(status, () => { watch(status, () => {
page.value = 1; page.value = 1;
void load(); void load();
@@ -161,166 +200,137 @@ defineExpose({ reload: load });
<section class="space-y-3" data-testid="shipping-run-progress-table"> <section class="space-y-3" data-testid="shipping-run-progress-table">
<div class="flex flex-wrap items-center justify-between gap-3"> <div class="flex flex-wrap items-center justify-between gap-3">
<div> <div>
<h3 class="text-base font-semibold text-primary">{{ t('workspace.shippingNotice.myRuns.title') }}</h3> <h3>{{ t('workspace.shippingNotice.myRuns.title') }}</h3>
<p class="text-xs text-muted">{{ t('workspace.shippingNotice.myRuns.subtitle') }}</p> <ElText type="info" size="small">{{ t('workspace.shippingNotice.myRuns.subtitle') }}</ElText>
</div> </div>
<label class="flex items-center gap-2 text-sm text-secondary"> <ElSelect
{{ t('workspace.shippingNotice.myRuns.status') }} class="run-status-select"
<select v-model="status" class="input-field py-1.5 text-sm"> :model-value="status || undefined"
<option value="">{{ t('workspace.shippingNotice.myRuns.allStatuses') }}</option> clearable
<option :placeholder="t('workspace.shippingNotice.myRuns.allStatuses')"
v-for="value in ['queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled']" :aria-label="t('workspace.shippingNotice.myRuns.status')"
@update:model-value="onStatusChange"
>
<ElOption
v-for="value in statusOptions"
:key="value" :key="value"
:value="value" :value="value"
> :label="t(`chat.shippingOrderExtractionCardTitle.${value}`)"
{{ t(`chat.shippingOrderExtractionCardTitle.${value}`) }} />
</option> </ElSelect>
</select>
</label>
</div> </div>
<p v-if="error" class="rounded-lg border border-rose-200 bg-rose-50 p-3 text-sm text-rose-700">{{ error }}</p> <ElText v-if="error" type="danger">{{ error }}</ElText>
<div class="overflow-x-auto rounded-xl border border-default bg-surface"> <ElTable
<table class="min-w-[860px] w-full text-left text-sm"> v-loading="loading"
<thead class="border-b border-default bg-surface-soft text-xs text-muted"> :data="rows"
<tr> row-key="run_no"
<th class="px-3 py-2">{{ t('workspace.shippingNotice.myRuns.runNo') }}</th> :empty-text="t('workspace.shippingNotice.myRuns.empty')"
<th class="px-3 py-2">{{ t('workspace.shippingNotice.myRuns.status') }}</th>
<th class="px-3 py-2">{{ t('workspace.shippingNotice.myRuns.stage') }}</th>
<th class="px-3 py-2">{{ t('workspace.shippingNotice.myRuns.summary') }}</th>
<th class="px-3 py-2">{{ t('workspace.shippingNotice.myRuns.elapsed') }}</th>
<th class="px-3 py-2">{{ t('workspace.shippingNotice.myRuns.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="loading">
<td colspan="6" class="px-3 py-8 text-center text-muted">{{ t('workspace.shippingNotice.myRuns.loading') }}</td>
</tr>
<tr v-else-if="!rows.length">
<td colspan="6" class="px-3 py-8 text-center text-muted">{{ t('workspace.shippingNotice.myRuns.empty') }}</td>
</tr>
<tr
v-for="run in rows"
:key="run.run_no"
class="border-b border-default last:border-0"
> >
<td class="px-3 py-2 font-mono text-xs">{{ run.run_no }}</td> <ElTableColumn prop="run_no" :label="t('workspace.shippingNotice.myRuns.runNo')" min-width="160" />
<td class="px-3 py-2"> <ElTableColumn :label="t('workspace.shippingNotice.myRuns.status')" min-width="160">
{{ t(`chat.shippingOrderExtractionCardTitle.${run.status}`) }} <template #default="{ row }">
<span {{ t(`chat.shippingOrderExtractionCardTitle.${(row as ShippingOrderExtractionRun).status}`) }}
v-if="run.cancellation?.requested && !run.cancellation?.completed_at" <ElTag
class="ml-1 rounded-full bg-amber-100 px-1.5 py-0.5 text-[10px] text-amber-800" v-if="(row as ShippingOrderExtractionRun).cancellation?.requested && !(row as ShippingOrderExtractionRun).cancellation?.completed_at"
type="warning"
effect="light"
> >
{{ t('chat.shippingOrderExtractionUserStage.cancellation_requested') }} {{ t('chat.shippingOrderExtractionUserStage.cancellation_requested') }}
</span> </ElTag>
</td> </template>
<td class="px-3 py-2"> </ElTableColumn>
<div>{{ stageLabel(run) }}</div> <ElTableColumn :label="t('workspace.shippingNotice.myRuns.stage')" min-width="160">
<div v-if="run.current_activity?.file_name" class="text-[11px] text-muted"> <template #default="{ row }">
{{ run.current_activity.file_name }} <div>{{ stageLabel(row as ShippingOrderExtractionRun) }}</div>
</div> <ElText v-if="(row as ShippingOrderExtractionRun).current_activity?.file_name" type="info" size="small">
</td> {{ (row as ShippingOrderExtractionRun).current_activity?.file_name }}
<td class="px-3 py-2 text-xs text-secondary"> </ElText>
</template>
</ElTableColumn>
<ElTableColumn :label="t('workspace.shippingNotice.myRuns.summary')" min-width="220">
<template #default="{ row }">
{{ t('workspace.shippingNotice.myRuns.summaryCounts', { {{ t('workspace.shippingNotice.myRuns.summaryCounts', {
total: run.summary?.total_documents || 0, total: (row as ShippingOrderExtractionRun).summary?.total_documents || 0,
done: run.summary?.completed_documents || 0, done: (row as ShippingOrderExtractionRun).summary?.completed_documents || 0,
review: run.summary?.review_required_documents || 0, review: (row as ShippingOrderExtractionRun).summary?.review_required_documents || 0,
failed: run.summary?.failed_documents || 0, failed: (row as ShippingOrderExtractionRun).summary?.failed_documents || 0,
cancelled: run.summary?.cancelled_documents || 0, cancelled: (row as ShippingOrderExtractionRun).summary?.cancelled_documents || 0,
}) }} }) }}
</td> </template>
<td class="px-3 py-2 text-xs"> </ElTableColumn>
{{ formatOrderExtractionElapsed(run.current_activity?.elapsed_seconds) || '—' }} <ElTableColumn :label="t('workspace.shippingNotice.myRuns.elapsed')" min-width="100">
</td> <template #default="{ row }">
<td class="px-3 py-2"> {{ formatOrderExtractionElapsed((row as ShippingOrderExtractionRun).current_activity?.elapsed_seconds) || '—' }}
<div class="flex flex-wrap gap-2"> </template>
<button </ElTableColumn>
type="button" <ElTableColumn :label="t('workspace.shippingNotice.myRuns.actions')" min-width="220" align="right">
class="text-xs font-medium text-brand-700 hover:underline" <template #default="{ row }">
@click="openInChat(run)" <ElButton link type="primary" @click="openInChat(row as ShippingOrderExtractionRun)">
>
{{ t('workspace.shippingNotice.myRuns.openChat') }} {{ t('workspace.shippingNotice.myRuns.openChat') }}
</button> </ElButton>
<template v-if="(run.available_actions || []).includes('cancel_run')"> <template v-if="((row as ShippingOrderExtractionRun).available_actions || []).includes('cancel_run')">
<div <div v-if="pendingCancelRunNo === (row as ShippingOrderExtractionRun).run_no">
v-if="pendingCancelRunNo === run.run_no" <div>{{ t('chat.shippingOrderExtractionCancel.reasonOptional') }}</div>
class="w-full min-w-[220px] space-y-1.5 rounded-md border border-rose-200 bg-rose-50/60 p-2 dark:border-rose-900/40 dark:bg-rose-950/20" <ElInput v-model="cancelReason" type="textarea" :rows="2" />
<ElButton
link
type="danger"
:loading="actingRunNo === (row as ShippingOrderExtractionRun).run_no"
@click="submitCancelRun(row as ShippingOrderExtractionRun, cancelReason)"
> >
<label class="block text-[11px] text-secondary"> {{ actingRunNo === (row as ShippingOrderExtractionRun).run_no
{{ t('chat.shippingOrderExtractionCancel.reasonOptional') }}
</label>
<textarea
v-model="cancelReason"
rows="2"
class="input-field w-full py-1 text-xs"
/>
<div class="flex flex-wrap gap-2">
<button
type="button"
class="text-xs font-medium text-rose-700 hover:underline"
:disabled="actingRunNo === run.run_no"
@click="submitCancelRun(run, cancelReason)"
>
{{ actingRunNo === run.run_no
? t('chat.shippingOrderExtractionCancel.submitting') ? t('chat.shippingOrderExtractionCancel.submitting')
: t('chat.shippingOrderExtractionAction.cancel_run') }} : t('chat.shippingOrderExtractionAction.cancel_run') }}
</button> </ElButton>
<button <ElButton
type="button" link
class="text-xs text-muted hover:underline" :disabled="actingRunNo === (row as ShippingOrderExtractionRun).run_no"
:disabled="actingRunNo === run.run_no"
@click="pendingCancelRunNo = ''; cancelReason = ''" @click="pendingCancelRunNo = ''; cancelReason = ''"
> >
{{ t('chat.shippingOrderExtractionCancel.dismiss') }} {{ t('chat.shippingOrderExtractionCancel.dismiss') }}
</button> </ElButton>
</div> </div>
</div> <ElButton
<button
v-else v-else
type="button" link
class="text-xs font-medium text-rose-700 hover:underline" type="danger"
:disabled="actingRunNo === run.run_no" :disabled="actingRunNo === (row as ShippingOrderExtractionRun).run_no"
@click="beginCancelRun(run)" @click="beginCancelRun(row as ShippingOrderExtractionRun)"
> >
{{ t('chat.shippingOrderExtractionAction.cancel_run') }} {{ t('chat.shippingOrderExtractionAction.cancel_run') }}
</button> </ElButton>
</template> </template>
<button <ElButton
v-if="(run.available_actions || []).includes('retry_failed_attachments')" v-if="((row as ShippingOrderExtractionRun).available_actions || []).includes('retry_failed_attachments')"
type="button" link
class="text-xs font-medium text-secondary hover:underline" :disabled="actingRunNo === (row as ShippingOrderExtractionRun).run_no"
:disabled="actingRunNo === run.run_no" @click="retryRun(row as ShippingOrderExtractionRun)"
@click="retryRun(run)"
> >
{{ t('chat.shippingOrderExtractionAction.retry_failed_attachments') }} {{ t('chat.shippingOrderExtractionAction.retry_failed_attachments') }}
</button> </ElButton>
</div> </template>
</td> </ElTableColumn>
</tr> </ElTable>
</tbody>
</table>
</div>
<div class="flex items-center justify-end gap-3 text-sm"> <div class="flex items-center justify-end gap-3">
<span class="text-xs text-muted">{{ t('workspace.shippingNotice.myRuns.total', { count: total }) }}</span> <ElText type="info" size="small">{{ t('workspace.shippingNotice.myRuns.total', { count: total }) }}</ElText>
<button <ElPagination
type="button" :current-page="page"
class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :page-size="pageSize"
:disabled="page <= 1 || loading" :total="total"
@click="page -= 1; load()" layout="prev, pager, next"
> background
{{ t('workspace.shippingNotice.myRuns.previous') }} :disabled="loading"
</button> @current-change="onPageChange"
<span>{{ page }}</span> />
<button
type="button"
class="rounded border border-default px-3 py-1.5 disabled:opacity-50"
:disabled="page * pageSize >= total || loading"
@click="page += 1; load()"
>
{{ t('workspace.shippingNotice.myRuns.next') }}
</button>
</div> </div>
</section> </section>
</template> </template>
<style scoped>
.run-status-select {
width: 12rem;
}
</style>
@@ -1,11 +1,12 @@
<!-- <!--
features/workspace/shipping-task-center/ShippingStageTabs.vue features/workspace/shipping-task-center/ShippingStageTabs.vue
用途:阶段筛选 tab(全部 + 四个可动作阶段),计数来自后端全量聚合。 用途:阶段筛选 tab(全部 + 四个可动作阶段),计数来自后端全量聚合。
依赖:shippingTaskCenterShared 的 ACTIONABLE_TODO_STAGES 口径。 依赖:shippingTaskCenterShared 的 ACTIONABLE_TODO_STAGES 口径、element-plus。
逻辑:点击切换筛选并向上同步;「通知完成」不再作为筛选维度(归 done 桶终态子视图)。 逻辑:点击切换筛选并向上同步;「通知完成」不再作为筛选维度(归 done 桶终态子视图)。样式由任务中心页引入。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { ElButton } from 'element-plus';
import { ACTIONABLE_TODO_STAGES, type LifecycleStageCode } from './shippingTaskCenterShared'; import { ACTIONABLE_TODO_STAGES, type LifecycleStageCode } from './shippingTaskCenterShared';
const { t } = useI18n(); const { t } = useI18n();
@@ -20,10 +21,18 @@ const emit = defineEmits<{
(event: 'update:modelValue', value: 'all' | LifecycleStageCode): void; (event: 'update:modelValue', value: 'all' | LifecycleStageCode): void;
}>(); }>();
/**
* 读取某一阶段的后端聚合计数。
* @param stage - 可动作阶段码
*/
function countOf(stage: LifecycleStageCode): number { function countOf(stage: LifecycleStageCode): number {
return Number(props.counts?.[stage] ?? 0); return Number(props.counts?.[stage] ?? 0);
} }
/**
* 阶段按钮文案。
* @param stage - 可动作阶段码
*/
function stageLabel(stage: LifecycleStageCode): string { function stageLabel(stage: LifecycleStageCode): string {
return t(`workspace.shippingNotice.myTodos.lifecycleStages.${stage}`); return t(`workspace.shippingNotice.myTodos.lifecycleStages.${stage}`);
} }
@@ -34,30 +43,24 @@ function stageLabel(stage: LifecycleStageCode): string {
class="flex flex-wrap gap-2" class="flex flex-wrap gap-2"
data-testid="my-todos-lifecycle-stage-filter" data-testid="my-todos-lifecycle-stage-filter"
> >
<button <ElButton
type="button" :type="modelValue === 'all' ? 'primary' : 'default'"
class="rounded-full px-3.5 py-1.5 text-sm font-medium transition-colors" round
:class="modelValue === 'all'
? 'bg-brand-600 text-white'
: 'border border-default text-secondary hover:bg-surface-soft'"
data-testid="my-todos-stage-filter-all" data-testid="my-todos-stage-filter-all"
@click="emit('update:modelValue', 'all')" @click="emit('update:modelValue', 'all')"
> >
{{ $t('workspace.shippingNotice.myTodos.filters.all') }} {{ $t('workspace.shippingNotice.myTodos.filters.all') }}
</button> </ElButton>
<button <ElButton
v-for="stage in ACTIONABLE_TODO_STAGES" v-for="stage in ACTIONABLE_TODO_STAGES"
:key="stage" :key="stage"
type="button" :type="modelValue === stage ? 'primary' : 'default'"
class="rounded-full px-3.5 py-1.5 text-sm font-medium transition-colors" round
:class="modelValue === stage
? 'bg-brand-600 text-white'
: 'border border-default text-secondary hover:bg-surface-soft'"
:data-testid="`my-todos-stage-filter-${stage}`" :data-testid="`my-todos-stage-filter-${stage}`"
@click="emit('update:modelValue', stage)" @click="emit('update:modelValue', stage)"
> >
{{ stageLabel(stage) }} {{ stageLabel(stage) }}
<span class="ml-1 font-mono text-xs opacity-80">{{ countOf(stage) }}</span> <span>{{ countOf(stage) }}</span>
</button> </ElButton>
</div> </div>
</template> </template>
@@ -219,8 +219,15 @@ describe('ShippingTaskCenterPage notice batch operations', () => {
}); });
const wrapper = await mountPage(); const wrapper = await mountPage();
await flushPromises(); await flushPromises();
await wrapper.get('[aria-label="WYC26082301"]').setValue(true); await flushPromises();
await wrapper.get('[aria-label="WYC26082302"]').setValue(true); // ElCheckbox 把 aria-label 放在外层 label,勾选状态写在内部 input。
const checkNotice = async (businessNo: string) => {
const host = wrapper.get(`[aria-label="${businessNo}"]`);
const input = host.find('input');
await (input.exists() ? input : host).setValue(true);
};
await checkNotice('WYC26082301');
await checkNotice('WYC26082302');
// 断言:勾选后浮出操作条,三个动作按序对应 download/confirm/rpa。 // 断言:勾选后浮出操作条,三个动作按序对应 download/confirm/rpa。
// 每次 action 后列表会静默重载(表格重挂载),因此逐次重新查询按钮。 // 每次 action 后列表会静默重载(表格重挂载),因此逐次重新查询按钮。
@@ -2,7 +2,7 @@
features/workspace/shipping-task-center/ShippingTaskCenterPage.vue features/workspace/shipping-task-center/ShippingTaskCenterPage.vue
用途:发货「任务中心」壳——Pending|Processing|Done + 识别 Run 续办表。 用途:发货「任务中心」壳——Pending|Processing|Done + 识别 Run 续办表。
依赖:shipping-tasks.api(my-todos / done-lines / count)、shipping.api(详情/STP retry/批量)、 依赖:shipping-tasks.api(my-todos / done-lines / count)、shipping.api(详情/STP retry/批量)、
ShippingStageTabs / ShippingTaskTable / ShippingTaskDrawer / ShippingDoneLineReport、 element-plus、ShippingStageTabs / ShippingTaskTable / ShippingTaskDrawer / ShippingDoneLineReport、
shippingTaskCenterShared、useShippingTodoBadge、useMessage。 shippingTaskCenterShared、useShippingTodoBadge、useMessage。
逻辑:列表优先 + 按需抽屉——紧凑表格行点开右侧抽屉(分诊决策面板),移除常驻详情面板; 逻辑:列表优先 + 按需抽屉——紧凑表格行点开右侧抽屉(分诊决策面板),移除常驻详情面板;
阶段筛选 tab 消费后端全量聚合计数(stage_counts);批量操作仅货代上传阶段可选、 阶段筛选 tab 消费后端全量聚合计数(stage_counts);批量操作仅货代上传阶段可选、
@@ -13,7 +13,11 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'; import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
import { RefreshCw } from 'lucide-vue-next'; import { Refresh } from '@element-plus/icons-vue';
import { ElButton, ElInput, ElOption, ElPagination, ElSelect } from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/shared/styles/element-theme.css';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { import {
getWorkspaceShippingTask, getWorkspaceShippingTask,
@@ -57,6 +61,7 @@ import { downloadWorkspaceShippingNoticeExportArchive } from '@/features/chat/sh
const { t } = useI18n(); const { t } = useI18n();
const msg = useMessage(); const msg = useMessage();
const bucketKeys = ['pending', 'processing', 'done'] as const;
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
@@ -326,6 +331,15 @@ function applyFilters() {
void loadTodos(true); void loadTodos(true);
} }
/**
* 切换待办列表页并重新拉取当前桶。
* @param page - Element 分页条给出的 1-based 页码
*/
function onTaskPageChange(page: number) {
currentPage.value = page;
void loadTodos();
}
/** /**
* 清空筛选并重载。 * 清空筛选并重载。
*/ */
@@ -702,79 +716,56 @@ onBeforeUnmount(() => {
<h2 class="text-2xl font-bold text-primary">{{ $t('workspace.shippingNotice.myTodos.title') }}</h2> <h2 class="text-2xl font-bold text-primary">{{ $t('workspace.shippingNotice.myTodos.title') }}</h2>
<p class="text-sm text-muted">{{ $t('workspace.shippingNotice.myTodos.subtitle') }}</p> <p class="text-sm text-muted">{{ $t('workspace.shippingNotice.myTodos.subtitle') }}</p>
</div> </div>
<button <ElButton :icon="Refresh" @click="refreshAll()">
type="button"
class="inline-flex items-center gap-1.5 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft"
@click="refreshAll()"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.refresh') }} {{ $t('workspace.shippingNotice.refresh') }}
</button> </ElButton>
</div> </div>
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
<button <ElButton :type="surface === 'todos' ? 'primary' : 'default'" @click="surface = 'todos'">
type="button"
class="rounded-xl px-3 py-1.5 text-sm font-medium"
:class="surface === 'todos' ? 'bg-brand-600 text-white' : 'border border-default text-secondary hover:bg-surface-soft'"
@click="surface = 'todos'"
>
{{ $t('workspace.shippingNotice.myTodos.title') }} {{ $t('workspace.shippingNotice.myTodos.title') }}
</button> </ElButton>
<button <ElButton :type="surface === 'runs' ? 'primary' : 'default'" @click="surface = 'runs'">
type="button"
class="rounded-xl px-3 py-1.5 text-sm font-medium"
:class="surface === 'runs' ? 'bg-brand-600 text-white' : 'border border-default text-secondary hover:bg-surface-soft'"
@click="surface = 'runs'"
>
{{ $t('workspace.shippingNotice.myRuns.title') }} {{ $t('workspace.shippingNotice.myRuns.title') }}
</button> </ElButton>
</div> </div>
<ShippingRunProgressTable v-if="surface === 'runs'" /> <ShippingRunProgressTable v-if="surface === 'runs'" />
<template v-else> <template v-else>
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
<button <ElButton
v-for="key in (['pending', 'processing', 'done'] as const)" v-for="key in bucketKeys"
:key="key" :key="key"
type="button" :type="bucket === key ? 'primary' : 'default'"
class="rounded-xl px-3 py-1.5 text-sm font-medium"
:class="bucket === key ? 'bg-brand-600 text-white' : 'border border-default text-secondary hover:bg-surface-soft'"
:data-testid="`my-todos-bucket-${key}`" :data-testid="`my-todos-bucket-${key}`"
@click="bucket = key" @click="bucket = key"
> >
{{ $t(`workspace.shippingNotice.myTodos.buckets.${key}`) }} {{ $t(`workspace.shippingNotice.myTodos.buckets.${key}`) }}
<span class="ml-1 opacity-80">({{ bucketCounts[key] }})</span> <span>({{ bucketCounts[key] }})</span>
</button> </ElButton>
</div> </div>
<template v-if="bucket === 'done'"> <template v-if="bucket === 'done'">
<div class="flex flex-wrap gap-2" data-testid="my-todos-done-subtabs"> <div class="flex flex-wrap gap-2" data-testid="my-todos-done-subtabs">
<button <ElButton
type="button" round
class="rounded-full px-3.5 py-1.5 text-sm font-medium" :type="doneSubTab === 'upload_complete' ? 'primary' : 'default'"
:class="doneSubTab === 'upload_complete'
? 'bg-brand-600 text-white'
: 'border border-default text-secondary hover:bg-surface-soft'"
data-testid="my-todos-done-subtab-upload-complete" data-testid="my-todos-done-subtab-upload-complete"
@click="doneSubTab = 'upload_complete'" @click="doneSubTab = 'upload_complete'"
> >
{{ $t('workspace.shippingNotice.myTodos.subTabs.uploadComplete') }} {{ $t('workspace.shippingNotice.myTodos.subTabs.uploadComplete') }}
<span class="ml-1 font-mono text-xs opacity-80">{{ bucketCounts.done_counts?.upload_complete ?? 0 }}</span> <span>{{ bucketCounts.done_counts?.upload_complete ?? 0 }}</span>
</button> </ElButton>
<button <ElButton
type="button" round
class="rounded-full px-3.5 py-1.5 text-sm font-medium" :type="doneSubTab === 'reject_void' ? 'primary' : 'default'"
:class="doneSubTab === 'reject_void'
? 'bg-brand-600 text-white'
: 'border border-default text-secondary hover:bg-surface-soft'"
data-testid="my-todos-done-subtab-reject-void" data-testid="my-todos-done-subtab-reject-void"
@click="doneSubTab = 'reject_void'" @click="doneSubTab = 'reject_void'"
> >
{{ $t('workspace.shippingNotice.myTodos.subTabs.rejectVoid') }} {{ $t('workspace.shippingNotice.myTodos.subTabs.rejectVoid') }}
<span class="ml-1 font-mono text-xs opacity-80">{{ bucketCounts.done_counts?.reject_void ?? 0 }}</span> <span>{{ bucketCounts.done_counts?.reject_void ?? 0 }}</span>
</button> </ElButton>
</div> </div>
</template> </template>
@@ -788,53 +779,41 @@ onBeforeUnmount(() => {
v-if="bucket !== 'done' || doneSubTab === 'reject_void'" v-if="bucket !== 'done' || doneSubTab === 'reject_void'"
class="flex flex-wrap items-end gap-3 rounded-2xl border border-default bg-surface px-4 py-3" class="flex flex-wrap items-end gap-3 rounded-2xl border border-default bg-surface px-4 py-3"
> >
<label v-if="bucket === 'pending'" class="space-y-1"> <label v-if="bucket === 'pending'" class="task-filter">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.filters.todoCategory') }}</span> <span>{{ $t('workspace.shippingNotice.myTodos.filters.todoCategory') }}</span>
<select v-model="filterTodoCategory" class="input-field text-sm min-w-[9rem]"> <ElSelect v-model="filterTodoCategory" class="task-filter-category">
<option value="all">{{ $t('workspace.shippingNotice.myTodos.filters.all') }}</option> <ElOption value="all" :label="$t('workspace.shippingNotice.myTodos.filters.all')" />
<option value="review">{{ $t('workspace.shippingNotice.myTodos.filters.review') }}</option> <ElOption value="review" :label="$t('workspace.shippingNotice.myTodos.filters.review')" />
<option value="exception">{{ $t('workspace.shippingNotice.myTodos.filters.exception') }}</option> <ElOption value="exception" :label="$t('workspace.shippingNotice.myTodos.filters.exception')" />
<option value="manual_upload">{{ $t('workspace.shippingNotice.myTodos.filters.manualUpload') }}</option> <ElOption value="manual_upload" :label="$t('workspace.shippingNotice.myTodos.filters.manualUpload')" />
<option value="intake_parse">{{ $t('workspace.shippingNotice.myTodos.filters.intakeParse') }}</option> <ElOption value="intake_parse" :label="$t('workspace.shippingNotice.myTodos.filters.intakeParse')" />
</select> </ElSelect>
</label> </label>
<label class="space-y-1 flex-1 min-w-[10rem]"> <label class="task-filter">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.filters.customer') }}</span> <span>{{ $t('workspace.shippingNotice.myTodos.filters.customer') }}</span>
<input <ElInput
v-model="filterCustomer" v-model="filterCustomer"
type="text" class="task-filter-text"
class="input-field text-sm w-full"
:placeholder="$t('workspace.shippingNotice.myTodos.filters.customerPlaceholder')" :placeholder="$t('workspace.shippingNotice.myTodos.filters.customerPlaceholder')"
@keyup.enter="applyFilters" @keyup.enter="applyFilters"
/> />
</label> </label>
<label class="space-y-1 flex-1 min-w-[10rem]"> <label class="task-filter">
<span class="text-xs font-medium text-muted">{{ $t('workspace.shippingNotice.myTodos.filters.taskNo') }}</span> <span>{{ $t('workspace.shippingNotice.myTodos.filters.taskNo') }}</span>
<input <ElInput
v-model="filterTaskNo" v-model="filterTaskNo"
type="text" class="task-filter-text"
class="input-field text-sm w-full font-mono uppercase"
:placeholder="$t('workspace.shippingNotice.myTodos.filters.taskNoPlaceholder')" :placeholder="$t('workspace.shippingNotice.myTodos.filters.taskNoPlaceholder')"
@keyup.enter="applyFilters" @keyup.enter="applyFilters"
/> />
</label> </label>
<div class="flex gap-2"> <div class="flex gap-2">
<button <ElButton type="primary" :loading="loading" @click="applyFilters">
type="button"
class="rounded-xl bg-brand-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
:disabled="loading"
@click="applyFilters"
>
{{ $t('workspace.shippingNotice.myTodos.filters.apply') }} {{ $t('workspace.shippingNotice.myTodos.filters.apply') }}
</button> </ElButton>
<button <ElButton :disabled="loading" @click="resetFilters">
type="button"
class="rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft disabled:opacity-50"
:disabled="loading"
@click="resetFilters"
>
{{ $t('workspace.shippingNotice.myTodos.filters.reset') }} {{ $t('workspace.shippingNotice.myTodos.filters.reset') }}
</button> </ElButton>
</div> </div>
</div> </div>
@@ -873,25 +852,16 @@ onBeforeUnmount(() => {
@clear-selection="selectedBusinessNos = []" @clear-selection="selectedBusinessNos = []"
@batch="runNoticeBatchAction" @batch="runNoticeBatchAction"
/> />
<div v-if="totalPages > 1" class="flex items-center justify-between gap-2 text-xs text-muted"> <ElPagination
<button v-if="totalPages > 1"
type="button" :current-page="currentPage"
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50" :page-size="pageSize"
:disabled="currentPage <= 1 || loading" :total="totalTasks"
@click="currentPage -= 1; loadTodos()" layout="prev, pager, next"
> background
{{ $t('workspace.shippingNotice.pagination.previous') }} :disabled="loading"
</button> @current-change="onTaskPageChange"
<span>{{ currentPage }}/{{ totalPages }}</span> />
<button
type="button"
class="rounded-lg border border-default px-2 py-1 disabled:opacity-50"
:disabled="currentPage >= totalPages || loading"
@click="currentPage += 1; loadTodos()"
>
{{ $t('workspace.shippingNotice.pagination.next') }}
</button>
</div>
</template> </template>
</template> </template>
</template> </template>
@@ -910,3 +880,19 @@ onBeforeUnmount(() => {
/> />
</div> </div>
</template> </template>
<style scoped>
.task-filter {
display: flex;
flex-direction: column;
gap: 4px;
}
.task-filter-category {
width: 11rem;
}
.task-filter-text {
width: 16rem;
}
</style>
@@ -1,15 +1,25 @@
<!-- <!--
features/workspace/shipping-task-center/ShippingTaskDrawer.vue features/workspace/shipping-task-center/ShippingTaskDrawer.vue
用途:任务详情抽屉——分诊决策面板(头部阻断 + 逐行明细 + 文件 + 底部操作)。 用途:任务详情抽屉——分诊决策面板(头部阻断 + 逐行明细 + 文件 + 底部操作)。
依赖:shippingTaskCenterShared(阶段口径)、gateReasonLabel。 依赖:shippingTaskCenterShared(阶段口径)、gateReasonLabel、element-plus(ElDrawer)。
逻辑:review/intake/task 三分支迁移自原任务中心右侧入口卡,行为与深链契约不变; 逻辑:review/intake/task 三分支迁移自原任务中心右侧入口卡,行为与深链契约不变;
深链/重试只向上 emit,由页面统一执行;阶段目标下拉仍由后端 深链/重试只向上 emit,由页面统一执行;阶段目标下拉仍由后端
ui_state.lifecycle_entries 裁决(current/available 才可进)。 ui_state.lifecycle_entries 裁决(current/available 才可进)。样式由任务中心页引入。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { Download, ExternalLink, RefreshCw, X } from 'lucide-vue-next'; import { Close, Download, Refresh, TopRight } from '@element-plus/icons-vue';
import {
ElButton,
ElDrawer,
ElOption,
ElSelect,
ElTable,
ElTableColumn,
ElTag,
ElText,
} from 'element-plus';
import type { import type {
ShippingTaskDetail, ShippingTaskDetail,
ShippingTaskSummary, ShippingTaskSummary,
@@ -46,6 +56,7 @@ const emit = defineEmits<{
}>(); }>();
type EnterableStage = Exclude<LifecycleStageCode, 'intake_parse'>; type EnterableStage = Exclude<LifecycleStageCode, 'intake_parse'>;
type NoticeLine = NonNullable<ShippingTaskSummary['notice_line_summary']>[number];
const stageTarget = ref<EnterableStage>('order_review'); const stageTarget = ref<EnterableStage>('order_review');
const isReviewItem = computed(() => { const isReviewItem = computed(() => {
@@ -108,7 +119,10 @@ const stageTargetOptions = computed(() => {
})); }));
}); });
/** 后端仅授权 current/available;目标不可进时主按钮禁用。 */ /**
* 后端仅授权 current/available;目标不可进时主按钮禁用。
* @param stage - 抽屉里选中的阶段
*/
function canOpenProcessing(stage: EnterableStage | null): boolean { function canOpenProcessing(stage: EnterableStage | null): boolean {
const item = props.item; const item = props.item;
if (!item) return false; if (!item) return false;
@@ -148,6 +162,7 @@ const lineRows = computed(() => {
/** /**
* 数量/缺口展示值:后端 Numeric(24,8) 透出形如 "24.00000000", * 数量/缺口展示值:后端 Numeric(24,8) 透出形如 "24.00000000",
* 统一转 number 去尾零(24.00000000→24、2.50000000→2.5),缺失保持 —。 * 统一转 number 去尾零(24.00000000→24、2.50000000→2.5),缺失保持 —。
* @param value - 数量原文
*/ */
function formatQty(value: unknown): string { function formatQty(value: unknown): string {
if (value === null || value === undefined || value === '') return '—'; if (value === null || value === undefined || value === '') return '—';
@@ -155,249 +170,200 @@ function formatQty(value: unknown): string {
return Number.isFinite(num) ? String(num) : String(value); return Number.isFinite(num) ? String(num) : String(value);
} }
/**
* 明细行主键。项次加料号,避免同项次不同料号撞 key。
* @param line - 通知单行摘要
*/
function noticeLineKey(line: NoticeLine): string {
return `${line.line_no}-${line.part_number || ''}`;
}
watch(() => props.item, (item) => { watch(() => props.item, (item) => {
if (!item) return; if (!item) return;
const stage = defaultLifecycleTarget(item); const stage = defaultLifecycleTarget(item);
if (stage) stageTarget.value = stage; if (stage) stageTarget.value = stage;
}, { immediate: true }); }, { immediate: true });
function onEsc(event: KeyboardEvent) {
if (event.key === 'Escape') emit('close');
}
// Esc 关闭抽屉;打开时挂监听,关闭/卸载时移除,避免监听串扰。
watch(() => props.open, (open) => {
if (open) document.addEventListener('keydown', onEsc);
else document.removeEventListener('keydown', onEsc);
}, { immediate: true });
onBeforeUnmount(() => document.removeEventListener('keydown', onEsc));
</script> </script>
<template> <template>
<Teleport to="body"> <ElDrawer
<div :model-value="open"
v-if="open" append-to-body
class="fixed inset-0 z-50 flex" direction="rtl"
data-testid="my-todos-drawer" size="832px"
:with-header="false"
:close-on-click-modal="true"
@close="emit('close')"
> >
<div <div data-testid="my-todos-drawer">
class="flex-1 bg-[rgba(23,32,51,0.35)]" <div>
data-testid="my-todos-drawer-scrim"
@click="emit('close')"
/>
<aside class="flex w-[52rem] max-w-[94vw] flex-col bg-surface shadow-2xl">
<div class="border-b border-default px-5 py-4">
<div class="flex items-start justify-between gap-3"> <div class="flex items-start justify-between gap-3">
<h3 class="break-all font-mono text-base font-bold text-primary" data-testid="my-todos-drawer-title"> <h3 class="break-all" data-testid="my-todos-drawer-title">{{ displayNo }}</h3>
{{ displayNo }} <ElButton
</h3> :icon="Close"
<button :aria-label="t('workspace.shippingNotice.myTodos.drawer.close')"
type="button"
class="rounded-lg bg-surface-soft px-2 py-1 text-xs text-secondary hover:bg-surface-soft/70"
:aria-label="$t('workspace.shippingNotice.myTodos.drawer.close')"
data-testid="my-todos-drawer-close" data-testid="my-todos-drawer-close"
@click="emit('close')" @click="emit('close')"
> />
<X class="h-4 w-4" />
</button>
</div> </div>
<p v-if="subTitle" class="mt-1 text-xs text-muted">{{ subTitle }}</p> <ElText v-if="subTitle" type="info" size="small">{{ subTitle }}</ElText>
<div class="mt-2 flex flex-wrap items-center gap-2"> <div class="mt-2 flex flex-wrap items-center gap-2">
<span <ElTag v-if="stageLabel" effect="light" data-testid="my-todos-drawer-stage">{{ stageLabel }}</ElTag>
v-if="stageLabel" <ElTag v-if="isReviewItem" type="warning" effect="light">{{ t('workspace.shippingNotice.myTodos.openReview') }}</ElTag>
class="rounded-full bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-800" <ElTag v-else-if="isIntakeItem" type="info" effect="light">{{ t('workspace.shippingNotice.myTodos.intakeParseBadge') }}</ElTag>
data-testid="my-todos-drawer-stage"
>
{{ stageLabel }}
</span>
<span
v-if="isReviewItem"
class="rounded bg-amber-50 px-1.5 py-0.5 text-[10px] text-amber-700"
>{{ $t('workspace.shippingNotice.myTodos.openReview') }}</span>
<span
v-else-if="isIntakeItem"
class="rounded bg-violet-50 px-1.5 py-0.5 text-[10px] text-violet-700"
>{{ $t('workspace.shippingNotice.myTodos.intakeParseBadge') }}</span>
</div> </div>
</div> </div>
<div class="flex-1 overflow-y-auto px-5 py-4"> <div>
<div v-if="loading" class="py-16 text-center text-sm text-muted"> <div v-if="loading">{{ t('workspace.shippingNotice.loading') }}</div>
{{ $t('workspace.shippingNotice.loading') }}
</div>
<template v-else-if="item"> <template v-else-if="item">
<div <ElText v-if="blocker" type="danger" data-testid="my-todos-progress-blocker">
v-if="blocker" {{ t('workspace.shippingNotice.myTodos.progressBlocker', { reason: blocker }) }}
class="mb-4 rounded-xl border border-red-200 bg-red-50 px-3.5 py-2.5 text-[13px] text-red-700" </ElText>
data-testid="my-todos-progress-blocker" <p v-if="stageLabel" data-testid="my-todos-progress-summary">
> {{ t('workspace.shippingNotice.myTodos.progressSummary', { stage: stageLabel }) }}
{{ $t('workspace.shippingNotice.myTodos.progressBlocker', { reason: blocker }) }}
</div>
<p
v-if="stageLabel"
class="mb-2 text-sm font-medium text-primary"
data-testid="my-todos-progress-summary"
>
{{ $t('workspace.shippingNotice.myTodos.progressSummary', { stage: stageLabel }) }}
</p> </p>
<p v-if="summaryMessage" class="text-sm text-secondary">{{ summaryMessage }}</p> <p v-if="summaryMessage">{{ summaryMessage }}</p>
<template v-if="lineRows.length"> <template v-if="lineRows.length">
<h4 class="mb-2 mt-5 text-[13px] font-bold text-primary"> <h4>{{ t('workspace.shippingNotice.myTodos.drawer.details') }}</h4>
{{ $t('workspace.shippingNotice.myTodos.drawer.details') }} <div data-testid="my-todos-drawer-lines">
</h4> <ElTable :data="lineRows" :row-key="noticeLineKey">
<div class="overflow-x-auto rounded-xl border border-default"> <ElTableColumn :label="t('workspace.shippingNotice.myTodos.drawer.lineTable.lineNo')" min-width="72">
<table class="w-full border-collapse text-xs" data-testid="my-todos-drawer-lines"> <template #default="{ row }">{{ (row as NoticeLine).line_no }}</template>
<thead> </ElTableColumn>
<tr class="border-b border-default bg-surface-soft/60 text-left text-muted"> <ElTableColumn :label="t('workspace.shippingNotice.myTodos.drawer.lineTable.partNumber')" min-width="120">
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.lineNo') }}</th> <template #default="{ row }">{{ (row as NoticeLine).part_number || '—' }}</template>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.partNumber') }}</th> </ElTableColumn>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.customerPartNumber') }}</th> <ElTableColumn :label="t('workspace.shippingNotice.myTodos.drawer.lineTable.customerPartNumber')" min-width="120">
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.reservationId') }}</th> <template #default="{ row }">{{ (row as NoticeLine).customer_part_number || '—' }}</template>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.shipmentQty') }}</th> </ElTableColumn>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.availableQty') }}</th> <ElTableColumn :label="t('workspace.shippingNotice.myTodos.drawer.lineTable.reservationId')" min-width="120">
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.shortageQty') }}</th> <template #default="{ row }">{{ (row as NoticeLine).reservation_id || '—' }}</template>
<th class="whitespace-nowrap px-2.5 py-2 font-medium">{{ $t('workspace.shippingNotice.myTodos.drawer.lineTable.status') }}</th> </ElTableColumn>
</tr> <ElTableColumn :label="t('workspace.shippingNotice.myTodos.drawer.lineTable.shipmentQty')" min-width="100">
</thead> <template #default="{ row }">{{ formatQty((row as NoticeLine).shipment_qty) }}</template>
<tbody> </ElTableColumn>
<tr <ElTableColumn :label="t('workspace.shippingNotice.myTodos.drawer.lineTable.availableQty')" min-width="100">
v-for="line in lineRows" <template #default="{ row }">{{ formatQty((row as NoticeLine).available_qty) }}</template>
:key="`${line.line_no}-${line.part_number}`" </ElTableColumn>
class="border-b border-[#f0f3f8]" <ElTableColumn :label="t('workspace.shippingNotice.myTodos.drawer.lineTable.shortageQty')" min-width="80">
> <template #default="{ row }">
<td class="px-2.5 py-2 font-mono">{{ line.line_no }}</td> <ElText :type="Number((row as NoticeLine).shortage_qty || 0) > 0 ? 'danger' : 'info'">
<td class="whitespace-nowrap px-2.5 py-2 font-mono">{{ line.part_number || '—' }}</td> {{ formatQty((row as NoticeLine).shortage_qty) }}
<td class="whitespace-nowrap px-2.5 py-2">{{ line.customer_part_number || '—' }}</td> </ElText>
<td class="whitespace-nowrap px-2.5 py-2 font-mono">{{ line.reservation_id || '—' }}</td> </template>
<td class="whitespace-nowrap px-2.5 py-2 tabular-nums">{{ formatQty(line.shipment_qty) }}</td> </ElTableColumn>
<td class="whitespace-nowrap px-2.5 py-2 tabular-nums">{{ formatQty(line.available_qty) }}</td> <ElTableColumn :label="t('workspace.shippingNotice.myTodos.drawer.lineTable.status')" min-width="100">
<td <template #default="{ row }">{{ (row as NoticeLine).inventory_status || '—' }}</template>
class="whitespace-nowrap px-2.5 py-2 tabular-nums" </ElTableColumn>
:class="Number(line.shortage_qty || 0) > 0 ? 'font-bold text-red-600' : ''" </ElTable>
>
{{ formatQty(line.shortage_qty) }}
</td>
<td class="whitespace-nowrap px-2.5 py-2">{{ line.inventory_status || '—' }}</td>
</tr>
</tbody>
</table>
</div> </div>
</template> </template>
<template v-if="exportFileName"> <template v-if="exportFileName">
<h4 class="mb-2 mt-5 text-[13px] font-bold text-primary"> <h4>{{ t('workspace.shippingNotice.myTodos.drawer.files') }}</h4>
{{ $t('workspace.shippingNotice.myTodos.drawer.files') }} <div>
</h4> <ElTag effect="light">Excel</ElTag>
<div class="rounded-xl border border-default px-3 py-2 text-[13px] text-secondary">
<span class="mr-2 rounded bg-brand-50 px-1.5 py-0.5 text-[10px] text-brand-800">Excel</span>
{{ exportFileName }} {{ exportFileName }}
</div> </div>
</template> </template>
<p class="mt-5 text-xs text-muted"> <ElText type="info" size="small">{{ t('workspace.shippingNotice.myTodos.openProcessingHint') }}</ElText>
{{ $t('workspace.shippingNotice.myTodos.openProcessingHint') }}
</p>
</template> </template>
<div v-else class="py-16 text-center text-sm text-muted"> <div v-else>{{ t('workspace.shippingNotice.selectCase') }}</div>
{{ $t('workspace.shippingNotice.selectCase') }}
</div>
</div> </div>
<div v-if="item && !loading" class="space-y-2.5 border-t border-default px-5 py-4"> <div v-if="item && !loading">
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
<label class="sr-only" for="drawer-stage-target">{{ $t('workspace.shippingNotice.myTodos.lifecycleStages.viewStage') }}</label> <ElSelect
<select
v-if="stageTargetOptions.length" v-if="stageTargetOptions.length"
id="drawer-stage-target"
v-model="stageTarget" v-model="stageTarget"
class="input-field max-w-40 text-sm" class="drawer-stage-select"
:aria-label="t('workspace.shippingNotice.myTodos.lifecycleStages.viewStage')"
data-testid="my-todos-lifecycle-stage-target" data-testid="my-todos-lifecycle-stage-target"
> >
<option <ElOption
v-for="option in stageTargetOptions" v-for="option in stageTargetOptions"
:key="option.code" :key="option.code"
:value="option.code" :value="option.code"
:label="t(`workspace.shippingNotice.myTodos.lifecycleStages.${option.code}`)"
:disabled="option.disabled" :disabled="option.disabled"
> />
{{ $t(`workspace.shippingNotice.myTodos.lifecycleStages.${option.code}`) }} </ElSelect>
</option> <ElButton
</select>
<button
v-if="canOpenIntake" v-if="canOpenIntake"
type="button" type="primary"
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50" :icon="TopRight"
data-testid="my-todos-open-intake-parse" data-testid="my-todos-open-intake-parse"
@click="emit('open-intake', item)" @click="emit('open-intake', item)"
> >
<ExternalLink class="h-3.5 w-3.5" /> {{ t('workspace.shippingNotice.myTodos.openIntakeParse') }}
{{ $t('workspace.shippingNotice.myTodos.openIntakeParse') }} </ElButton>
</button> <ElButton
<button
v-else-if="!isIntakeItem" v-else-if="!isIntakeItem"
type="button" type="primary"
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50" :icon="TopRight"
:disabled="!canOpenProcessing(stageTarget)" :disabled="!canOpenProcessing(stageTarget)"
data-testid="my-todos-open-order-processing" data-testid="my-todos-open-order-processing"
@click="emit('open-processing', item, stageTarget)" @click="emit('open-processing', item, stageTarget)"
> >
<ExternalLink class="h-3.5 w-3.5" /> {{ t('workspace.shippingNotice.myTodos.openLifecycleWorkbench') }}
{{ $t('workspace.shippingNotice.myTodos.openLifecycleWorkbench') }} </ElButton>
</button> <ElButton
<button
v-else v-else
type="button" type="primary"
class="inline-flex items-center gap-1.5 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50" :icon="TopRight"
:disabled="!(item.owner_agent_id || chatAgentId)" :disabled="!(item.owner_agent_id || chatAgentId)"
data-testid="my-todos-open-intake-conversation" data-testid="my-todos-open-intake-conversation"
@click="emit('open-chat', item)" @click="emit('open-chat', item)"
> >
<ExternalLink class="h-3.5 w-3.5" /> {{ t('workspace.shippingNotice.myTodos.openConversation') }}
{{ $t('workspace.shippingNotice.myTodos.openConversation') }} </ElButton>
</button> <ElButton
<button
v-if="chatAgentId && !isIntakeItem" v-if="chatAgentId && !isIntakeItem"
type="button" :icon="TopRight"
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-xs font-medium text-secondary hover:bg-surface-soft"
@click="emit('open-chat', item)" @click="emit('open-chat', item)"
> >
<ExternalLink class="h-3.5 w-3.5" /> {{ t('workspace.shippingNotice.openChat') }}
{{ $t('workspace.shippingNotice.openChat') }} </ElButton>
</button>
</div> </div>
<div class="flex flex-wrap items-center gap-3"> <div class="mt-2 flex flex-wrap items-center gap-3">
<button <ElButton
v-if="canRetryStp" v-if="canRetryStp"
type="button" :icon="Refresh"
class="inline-flex items-center gap-1.5 rounded-xl border border-amber-400 bg-amber-50 px-4 py-2 text-sm font-medium text-amber-950 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100" :loading="stpRetrying"
:disabled="stpRetrying"
data-testid="my-todos-retry-stp-auto-create" data-testid="my-todos-retry-stp-auto-create"
@click="emit('retry-stp', item)" @click="emit('retry-stp', item)"
> >
<RefreshCw class="h-3.5 w-3.5" /> {{ t('chat.shippingOrderReview.autoProgress.retryStp') }}
{{ $t('chat.shippingOrderReview.autoProgress.retryStp') }} </ElButton>
</button>
<a <a
v-if="exportFileName && canDownloadExport" v-if="exportFileName && canDownloadExport"
class="inline-flex cursor-pointer items-center gap-1 text-xs text-brand-700 hover:underline" class="inline-flex items-center gap-1"
:href="`/api/workspace/shipping-notices/${encodeURIComponent(String(item.business_no || ''))}/export`" :href="`/api/workspace/shipping-notices/${encodeURIComponent(String(item.business_no || ''))}/export`"
target="_blank" target="_blank"
rel="noopener" rel="noopener"
> >
<Download class="h-3.5 w-3.5" /> <Download class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.myTodos.drawer.exportExcel') }} {{ t('workspace.shippingNotice.myTodos.drawer.exportExcel') }}
</a> </a>
<p <ElText
v-if="!canOpenIntake && !canOpenProcessing(stageTarget) && !isIntakeItem" v-if="!canOpenIntake && !canOpenProcessing(stageTarget) && !isIntakeItem"
class="text-xs text-amber-700 dark:text-amber-300" type="warning"
size="small"
data-testid="my-todos-open-processing-unavailable" data-testid="my-todos-open-processing-unavailable"
> >
{{ $t('workspace.shippingNotice.myTodos.openProcessingUnavailable') }} {{ t('workspace.shippingNotice.myTodos.openProcessingUnavailable') }}
</p> </ElText>
</div> </div>
</div> </div>
</aside>
</div> </div>
</Teleport> </ElDrawer>
</template> </template>
<style scoped>
.drawer-stage-select {
width: 11rem;
}
</style>
@@ -1,14 +1,15 @@
<!-- <!--
features/workspace/shipping-task-center/ShippingTaskTable.vue features/workspace/shipping-task-center/ShippingTaskTable.vue
用途:任务中心紧凑表格(一行一待办):编号/阶段/状态摘要/项次缺口/货代状态。 用途:任务中心紧凑表格(一行一待办):编号/阶段/状态摘要/项次缺口/货代状态。
依赖:shippingTaskCenterShared(编号、阶段、批量可选口径)。 依赖:shippingTaskCenterShared(编号、阶段、批量可选口径)、element-plus。
逻辑:行点击向上冒泡选中;复选框仅「货代上传」阶段的正式 Notice 行存在; 逻辑:行点击向上冒泡选中;复选框仅「货代上传」阶段的正式 Notice 行存在;
勾选 ≥1 后浮出深色批量操作条(低频操作不常驻);分页由父级渲染。 勾选 ≥1 后浮出批量操作条(低频操作不常驻);分页由父级渲染。样式由任务中心页引入。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue'; import { computed } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { CheckSquare, Download, Upload, X } from 'lucide-vue-next'; import { Close, Download, Select, Upload } from '@element-plus/icons-vue';
import { ElButton, ElCheckbox, ElTable, ElTableColumn, ElTag, ElText } from 'element-plus';
import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api'; import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api';
import { import {
isBatchDownloadableRow, isBatchDownloadableRow,
@@ -54,7 +55,10 @@ const allSelectableChecked = computed(() => (
&& selectableRows.value.every((item) => selectedSet.value.has(String(item.business_no))) && selectableRows.value.every((item) => selectedSet.value.has(String(item.business_no)))
)); ));
/** 阶段徽章文案:优先本地化阶段名,后端 label 兜底。 */ /**
* 阶段徽章文案:优先本地化阶段名,后端 label 兜底。
* @param item - 待办行
*/
function stageLabel(item: ShippingTaskSummary): string { function stageLabel(item: ShippingTaskSummary): string {
const code = lifecycleStageCodeOf(item); const code = lifecycleStageCodeOf(item);
const key = code ? `workspace.shippingNotice.myTodos.lifecycleStages.${code}` : ''; const key = code ? `workspace.shippingNotice.myTodos.lifecycleStages.${code}` : '';
@@ -62,180 +66,164 @@ function stageLabel(item: ShippingTaskSummary): string {
return String(item.ui_state?.stage?.label || '—'); return String(item.ui_state?.stage?.label || '—');
} }
/**
* 状态摘要主文案。
* @param item - 待办行
*/
function rowTitle(item: ShippingTaskSummary): string { function rowTitle(item: ShippingTaskSummary): string {
return todoTitleText(item); return todoTitleText(item);
} }
/**
* 阻断原因。空字符串表示当前行没有阻断。
* @param item - 待办行
*/
function rowBlocker(item: ShippingTaskSummary): string { function rowBlocker(item: ShippingTaskSummary): string {
return todoBlockerText(item, t, te); return todoBlockerText(item, t, te);
} }
/**
* 项次数量短句。没有行时显示占位。
* @param item - 待办行
*/
function lineBriefText(item: ShippingTaskSummary): string { function lineBriefText(item: ShippingTaskSummary): string {
const brief = todoLineBrief(item); const brief = todoLineBrief(item);
if (!brief.total) return '—'; if (!brief.total) return '—';
return `${brief.total} ${t('workspace.shippingNotice.myTodos.table.lineUnit')}`; return `${brief.total} ${t('workspace.shippingNotice.myTodos.table.lineUnit')}`;
} }
/** 全选或取消当前页可批量行。 */
function onToggleAll(): void { function onToggleAll(): void {
emit('toggle-all'); emit('toggle-all');
} }
/**
* 点击表格行打开抽屉。复选框点击已 stop,不会进到这里。
* @param row - 当前待办
*/
function onRowClick(row: ShippingTaskSummary): void {
emit('select', row);
}
/**
* 行角标:复核、解析、只读或终态。没有角标时返回空。
* @param item - 待办行
*/
function badgeOf(item: ShippingTaskSummary): { type: 'warning' | 'info' | 'success' | 'danger'; label: string } | null {
if (item.todo_category === 'review' || item.item_kind === 'review_case') {
return { type: 'warning', label: t('workspace.shippingNotice.myTodos.openReview') };
}
if (item.todo_category === 'intake_parse' || item.item_kind === 'order_intake') {
return { type: 'info', label: t('workspace.shippingNotice.myTodos.intakeParseBadge') };
}
if (item.can_handle === false) {
return { type: 'info', label: t('workspace.shippingNotice.todo.adminViewOnlyShort') };
}
if (props.terminalBadge === 'upload_complete') {
return { type: 'success', label: t('workspace.shippingNotice.myTodos.terminal.uploadComplete') };
}
if (props.terminalBadge === 'reject_void') {
return { type: 'danger', label: t('workspace.shippingNotice.myTodos.terminal.rejectVoid') };
}
return null;
}
</script> </script>
<template> <template>
<div class="overflow-hidden rounded-2xl border border-default bg-surface"> <div class="overflow-hidden rounded-2xl border border-default bg-surface">
<div <div
v-if="hasSelection" v-if="hasSelection"
class="flex flex-wrap items-center gap-2 bg-[#1b2740] px-4 py-2.5 text-sm text-slate-100" class="flex flex-wrap items-center gap-2 bg-[#1b2740] px-4 py-2.5"
data-testid="shipping-notice-batch-toolbar" data-testid="shipping-notice-batch-toolbar"
> >
<span class="rounded-full bg-brand-600 px-3 py-0.5 text-xs font-semibold"> <ElTag type="primary" effect="dark">
{{ $t('workspace.shippingNotice.batch.selected', { count: selectedBusinessNos?.length || 0 }) }} {{ $t('workspace.shippingNotice.batch.selected', { count: selectedBusinessNos?.length || 0 }) }}
</span> </ElTag>
<button <ElButton :icon="Download" :disabled="Boolean(batchBusy)" @click="emit('batch', 'download')">
type="button"
class="rounded-lg border border-white/20 px-2.5 py-1 text-xs hover:bg-white/10 disabled:opacity-50"
:disabled="Boolean(batchBusy)"
@click="emit('batch', 'download')"
>
<Download class="mr-1 inline h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.batch.download') }} {{ $t('workspace.shippingNotice.batch.download') }}
</button> </ElButton>
<button <ElButton :icon="Select" :disabled="Boolean(batchBusy)" @click="emit('batch', 'confirm')">
type="button"
class="rounded-lg border border-white/20 px-2.5 py-1 text-xs hover:bg-white/10 disabled:opacity-50"
:disabled="Boolean(batchBusy)"
@click="emit('batch', 'confirm')"
>
<CheckSquare class="mr-1 inline h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.batch.confirm') }} {{ $t('workspace.shippingNotice.batch.confirm') }}
</button> </ElButton>
<button <ElButton :icon="Upload" :disabled="Boolean(batchBusy)" @click="emit('batch', 'rpa')">
type="button"
class="rounded-lg border border-white/20 px-2.5 py-1 text-xs hover:bg-white/10 disabled:opacity-50"
:disabled="Boolean(batchBusy)"
@click="emit('batch', 'rpa')"
>
<Upload class="mr-1 inline h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.batch.rpa') }} {{ $t('workspace.shippingNotice.batch.rpa') }}
</button> </ElButton>
<span class="flex-1" /> <span class="flex-1" />
<button <ElButton :icon="Close" @click="emit('clear-selection')">
type="button"
class="rounded-lg px-2.5 py-1 text-xs text-slate-300 hover:text-white"
@click="emit('clear-selection')"
>
<X class="mr-1 inline h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.batch.clearSelection') }} {{ $t('workspace.shippingNotice.batch.clearSelection') }}
</button> </ElButton>
</div> </div>
<div class="overflow-x-auto"> <ElTable
<table class="w-full border-collapse text-sm"> :data="items"
<thead> :row-key="todoItemKey"
<tr class="border-b border-default bg-surface-soft/60 text-left text-xs text-muted"> :current-row-key="selectedKey || undefined"
<th v-if="selectable" class="w-10 px-3 py-2.5"> highlight-current-row
<input @row-click="onRowClick"
type="checkbox" >
:checked="allSelectableChecked" <ElTableColumn v-if="selectable" width="64">
:aria-label="$t('workspace.shippingNotice.batch.selectAll')" <template #header>
<ElCheckbox
:model-value="allSelectableChecked"
:aria-label="t('workspace.shippingNotice.batch.selectAll')"
@change="onToggleAll" @change="onToggleAll"
> />
</th> </template>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.table.no') }}</th> <template #default="{ row }">
<th class="w-24 px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.table.stage') }}</th> <span v-if="isBatchDownloadableRow(row as ShippingTaskSummary)" @click.stop>
<th class="px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.table.summary') }}</th> <ElCheckbox
<th class="w-28 px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.table.lines') }}</th> :model-value="selectedSet.has(String((row as ShippingTaskSummary).business_no))"
<th class="w-24 px-3 py-2.5 font-medium">{{ $t('workspace.shippingNotice.myTodos.table.freightStatus') }}</th> :aria-label="String((row as ShippingTaskSummary).business_no)"
</tr> @change="emit('toggle', row as ShippingTaskSummary)"
</thead> />
<tbody>
<tr
v-for="item in items"
:key="todoItemKey(item)"
class="cursor-pointer border-b border-[#f0f3f8] transition-colors hover:bg-brand-50/40"
:class="selectedKey === todoItemKey(item) ? 'bg-brand-50/70 dark:bg-brand-950/30' : ''"
:data-testid="`my-todos-row-${todoDisplayNo(item)}`"
@click="emit('select', item)"
>
<td v-if="selectable" class="px-3 py-2.5 align-middle">
<input
v-if="isBatchDownloadableRow(item)"
type="checkbox"
:checked="selectedSet.has(String(item.business_no))"
:aria-label="String(item.business_no)"
@click.stop
@change="emit('toggle', item)"
>
</td>
<td class="max-w-[22rem] px-3 py-2.5 align-middle">
<div class="flex items-center gap-2">
<span class="truncate font-mono text-[13px] font-semibold text-primary">{{ todoDisplayNo(item) }}</span>
<span
v-if="item.todo_category === 'review' || item.item_kind === 'review_case'"
class="shrink-0 rounded bg-amber-50 px-1.5 py-0.5 text-[10px] text-amber-700"
>
{{ $t('workspace.shippingNotice.myTodos.openReview') }}
</span>
<span
v-else-if="item.todo_category === 'intake_parse' || item.item_kind === 'order_intake'"
class="shrink-0 rounded bg-violet-50 px-1.5 py-0.5 text-[10px] text-violet-700"
>
{{ $t('workspace.shippingNotice.myTodos.intakeParseBadge') }}
</span>
<span
v-else-if="item.can_handle === false"
class="shrink-0 rounded bg-slate-100 px-1.5 py-0.5 text-[10px] text-slate-600"
>
{{ $t('workspace.shippingNotice.todo.adminViewOnlyShort') }}
</span>
<span
v-else-if="terminalBadge === 'upload_complete'"
class="shrink-0 rounded bg-emerald-50 px-1.5 py-0.5 text-[10px] text-emerald-700"
>
{{ $t('workspace.shippingNotice.myTodos.terminal.uploadComplete') }}
</span>
<span
v-else-if="terminalBadge === 'reject_void'"
class="shrink-0 rounded bg-red-50 px-1.5 py-0.5 text-[10px] text-red-700"
>
{{ $t('workspace.shippingNotice.myTodos.terminal.rejectVoid') }}
</span> </span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('workspace.shippingNotice.myTodos.table.no')" min-width="220">
<template #default="{ row }">
<div :data-testid="`my-todos-row-${todoDisplayNo(row as ShippingTaskSummary)}`">
<span>{{ todoDisplayNo(row as ShippingTaskSummary) }}</span>
<ElTag v-if="badgeOf(row as ShippingTaskSummary)" :type="badgeOf(row as ShippingTaskSummary)?.type" effect="light">
{{ badgeOf(row as ShippingTaskSummary)?.label }}
</ElTag>
</div> </div>
<div class="mt-0.5 truncate text-xs text-muted">{{ todoSubTitleText(item) || '—' }}</div> <ElText type="info" size="small">{{ todoSubTitleText(row as ShippingTaskSummary) || '—' }}</ElText>
</td> </template>
<td class="px-3 py-2.5 align-middle"> </ElTableColumn>
<span class="whitespace-nowrap rounded-full bg-brand-50 px-2 py-0.5 text-xs text-brand-800"> <ElTableColumn :label="t('workspace.shippingNotice.myTodos.table.stage')" min-width="120">
{{ stageLabel(item) }} <template #default="{ row }">
</span> <ElTag effect="light">{{ stageLabel(row as ShippingTaskSummary) }}</ElTag>
</td> </template>
<td class="max-w-[18rem] px-3 py-2.5 align-middle"> </ElTableColumn>
<div class="truncate text-[13px] text-secondary">{{ rowTitle(item) }}</div> <ElTableColumn :label="t('workspace.shippingNotice.myTodos.table.summary')" min-width="180">
<div <template #default="{ row }">
v-if="rowBlocker(item)" <div>{{ rowTitle(row as ShippingTaskSummary) }}</div>
class="mt-0.5 truncate text-xs text-red-600" <ElText
v-if="rowBlocker(row as ShippingTaskSummary)"
type="danger"
size="small"
data-testid="my-todos-row-blocker" data-testid="my-todos-row-blocker"
> >
{{ rowBlocker(item) }} {{ rowBlocker(row as ShippingTaskSummary) }}
</div> </ElText>
</td>
<td class="px-3 py-2.5 align-middle text-xs">
<template v-if="item.business_no">
<span>{{ lineBriefText(item) }}</span>
<span
v-if="todoLineBrief(item).shortage"
class="ml-1 font-semibold text-red-600"
>
{{ $t('workspace.shippingNotice.myTodos.table.shortage', { count: todoLineBrief(item).shortage }) }}
</span>
</template> </template>
<span v-else class="text-muted">—</span> </ElTableColumn>
</td> <ElTableColumn :label="t('workspace.shippingNotice.myTodos.table.lines')" min-width="120">
<td class="px-3 py-2.5 align-middle text-xs text-secondary"> <template #default="{ row }">
{{ item.business_no ? (item.upload_status || '—') : '—' }} <template v-if="(row as ShippingTaskSummary).business_no">
</td> <span>{{ lineBriefText(row as ShippingTaskSummary) }}</span>
</tr> <ElText v-if="todoLineBrief(row as ShippingTaskSummary).shortage" type="danger">
</tbody> {{ t('workspace.shippingNotice.myTodos.table.shortage', { count: todoLineBrief(row as ShippingTaskSummary).shortage }) }}
</table> </ElText>
</div> </template>
<span v-else>—</span>
</template>
</ElTableColumn>
<ElTableColumn :label="t('workspace.shippingNotice.myTodos.table.freightStatus')" min-width="120">
<template #default="{ row }">
{{ (row as ShippingTaskSummary).business_no ? ((row as ShippingTaskSummary).upload_status || '—') : '—' }}
</template>
</ElTableColumn>
</ElTable>
</div> </div>
</template> </template>
@@ -2,7 +2,7 @@
* features/workspace/shipping-task-center/ShippingTaskWorkbench.vue * features/workspace/shipping-task-center/ShippingTaskWorkbench.vue
* 用途:发货任务处理主区——当前待办栏、五阶段进度、最后活动/终止原因、STP 事实、订单概览、时间线。 * 用途:发货任务处理主区——当前待办栏、五阶段进度、最后活动/终止原因、STP 事实、订单概览、时间线。
* 依赖:TaskTodoPanel、StpProgressFactsPanel、TaskProgressTimeline、ShippingTaskParsedResultCard、 * 依赖:TaskTodoPanel、StpProgressFactsPanel、TaskProgressTimeline、ShippingTaskParsedResultCard、
* useShippingProcessingWorkItem、ShippingWorkflowStepper、listWorkspaceShippingTaskAuditTimeline。 * element-plus、useShippingProcessingWorkItem、ShippingWorkflowStepper、listWorkspaceShippingTaskAuditTimeline。
* 逻辑:由 ShippingTaskCenterPage 选中任务后挂载;OT 身份取 detail.order_task_no(禁止 WorkflowItem); * 逻辑:由 ShippingTaskCenterPage 选中任务后挂载;OT 身份取 detail.order_task_no(禁止 WorkflowItem);
* 业务进度仅来自 detail.ui_state.steps(动作归 TaskTodoPanel,UI-05); * 业务进度仅来自 detail.ui_state.steps(动作归 TaskTodoPanel,UI-05);
* 时间线仅消费统一 ShippingAuditEvent。 * 时间线仅消费统一 ShippingAuditEvent。
@@ -10,6 +10,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { ElButton } from 'element-plus';
import ShippingMatchResultCard from '@/features/chat/components/messages/ShippingMatchResultCard.vue'; import ShippingMatchResultCard from '@/features/chat/components/messages/ShippingMatchResultCard.vue';
import ShippingTaskParsedResultCard from '@/features/chat/components/ShippingTaskParsedResultCard.vue'; import ShippingTaskParsedResultCard from '@/features/chat/components/ShippingTaskParsedResultCard.vue';
import { resolveShippingWorkflowSteps } from '@/features/chat/shipping/shippingStepper'; import { resolveShippingWorkflowSteps } from '@/features/chat/shipping/shippingStepper';
@@ -186,13 +187,9 @@ async function downloadExcel() {
</div> </div>
</dl> </dl>
<div v-if="downloadExcelAuthorized && !actionBarOffersDownloadExcel" class="mt-3"> <div v-if="downloadExcelAuthorized && !actionBarOffersDownloadExcel" class="mt-3">
<button <ElButton @click="downloadExcel">
type="button"
class="rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft"
@click="downloadExcel"
>
{{ $t('workspace.shippingNotice.todo.downloadExcel') }} {{ $t('workspace.shippingNotice.todo.downloadExcel') }}
</button> </ElButton>
</div> </div>
</section> </section>
@@ -1,14 +1,17 @@
/** /**
* features/workspace/shipping-task-center/StpProgressFactsPanel.vue * features/workspace/shipping-task-center/StpProgressFactsPanel.vue
* 用途:展示后端 ui_state.summary.stp_facts,含逐行 Reservation/料号/实际库存源/文件证据。 * 用途:展示后端 ui_state.summary.stp_facts,含逐行 Reservation/料号/实际库存源/文件证据。
* 依赖:ShippingTaskUiState.summary.stp_facts、vue-i18n。 * 依赖:ShippingTaskUiState.summary.stp_facts、element-plus、vue-i18n。
* 逻辑:由 ShippingTaskWorkbench 在待办栏下方挂载;无 stp_facts 时不渲染;不发明进度。 * 逻辑:由 ShippingTaskWorkbench 在待办栏下方挂载;无 stp_facts 时不渲染;不发明进度。
*/ */
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue'; import { computed } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { ElTable, ElTableColumn } from 'element-plus';
import type { ShippingStpFacts } from '@/features/chat/types/shipping.api.types'; import type { ShippingStpFacts } from '@/features/chat/types/shipping.api.types';
type StpLine = NonNullable<ShippingStpFacts['line_resolutions']>[number] & { rowKey: string; displayLine: number };
const props = defineProps<{ const props = defineProps<{
facts: ShippingStpFacts | null | undefined; facts: ShippingStpFacts | null | undefined;
}>(); }>();
@@ -20,7 +23,11 @@ const resolutionEntries = computed(() => {
const counts = props.facts?.resolution_counts || {}; const counts = props.facts?.resolution_counts || {};
return Object.entries(counts).map(([disposition, count]) => ({ disposition, count })); return Object.entries(counts).map(([disposition, count]) => ({ disposition, count }));
}); });
const lineRows = computed(() => props.facts?.line_resolutions || []); const lineRows = computed<StpLine[]>(() => (props.facts?.line_resolutions || []).map((row, index) => ({
...row,
rowKey: `${row.line_no || row.line_index || 'line'}-${index}`,
displayLine: (row.line_index ?? index) + 1,
})));
/** /**
* 行级 disposition 文案;未知码回退原文。 * 行级 disposition 文案;未知码回退原文。
@@ -93,34 +100,28 @@ function evidenceText(row: NonNullable<ShippingStpFacts['line_resolutions']>[num
</div> </div>
</dl> </dl>
<div v-if="lineRows.length" class="mt-3 overflow-x-auto"> <div v-if="lineRows.length" class="mt-3">
<div class="mb-1 text-xs text-muted">{{ $t('workspace.shippingNotice.stpFacts.lineTableTitle') }}</div> <div>{{ $t('workspace.shippingNotice.stpFacts.lineTableTitle') }}</div>
<table class="min-w-full border-collapse text-xs"> <ElTable :data="lineRows" row-key="rowKey">
<thead> <ElTableColumn :label="$t('workspace.shippingNotice.stpFacts.colLine')" min-width="72">
<tr class="border-b border-default/70 text-left text-muted"> <template #default="{ row }">{{ (row as StpLine).displayLine }}</template>
<th class="py-1 pr-2 font-medium">{{ $t('workspace.shippingNotice.stpFacts.colLine') }}</th> </ElTableColumn>
<th class="py-1 pr-2 font-medium">{{ $t('workspace.shippingNotice.stpFacts.colReservation') }}</th> <ElTableColumn :label="$t('workspace.shippingNotice.stpFacts.colReservation')" min-width="120">
<th class="py-1 pr-2 font-medium">{{ $t('workspace.shippingNotice.stpFacts.colPart') }}</th> <template #default="{ row }">{{ (row as StpLine).effective_reservation_id || '—' }}</template>
<th class="py-1 pr-2 font-medium">{{ $t('workspace.shippingNotice.stpFacts.colDisposition') }}</th> </ElTableColumn>
<th class="py-1 pr-2 font-medium">{{ $t('workspace.shippingNotice.stpFacts.colSource') }}</th> <ElTableColumn :label="$t('workspace.shippingNotice.stpFacts.colPart')" min-width="120">
<th class="py-1 font-medium">{{ $t('workspace.shippingNotice.stpFacts.colEvidence') }}</th> <template #default="{ row }">{{ (row as StpLine).part_number || '—' }}</template>
</tr> </ElTableColumn>
</thead> <ElTableColumn :label="$t('workspace.shippingNotice.stpFacts.colDisposition')" min-width="120">
<tbody> <template #default="{ row }">{{ dispositionLabel(String((row as StpLine).disposition || 'unknown')) }}</template>
<tr </ElTableColumn>
v-for="(row, index) in lineRows" <ElTableColumn :label="$t('workspace.shippingNotice.stpFacts.colSource')" min-width="120">
:key="`${row.line_no || row.line_index}-${index}`" <template #default="{ row }">{{ (row as StpLine).resolved_inventory_source_code || '—' }}</template>
class="border-b border-default/50 align-top" </ElTableColumn>
> <ElTableColumn :label="$t('workspace.shippingNotice.stpFacts.colEvidence')" min-width="180">
<td class="py-1.5 pr-2 font-mono">{{ (row.line_index ?? index) + 1 }}</td> <template #default="{ row }">{{ evidenceText(row as StpLine) }}</template>
<td class="py-1.5 pr-2 font-mono">{{ row.effective_reservation_id || '—' }}</td> </ElTableColumn>
<td class="py-1.5 pr-2 font-mono">{{ row.part_number || '—' }}</td> </ElTable>
<td class="py-1.5 pr-2">{{ dispositionLabel(String(row.disposition || 'unknown')) }}</td>
<td class="py-1.5 pr-2 font-mono">{{ row.resolved_inventory_source_code || '—' }}</td>
<td class="py-1.5 font-mono text-muted">{{ evidenceText(row) }}</td>
</tr>
</tbody>
</table>
</div> </div>
</section> </section>
</template> </template>
@@ -1,7 +1,7 @@
/** /**
* features/workspace/shipping-task-center/TaskTodoPanel.vue * features/workspace/shipping-task-center/TaskTodoPanel.vue
* 用途:渲染统一 Gate 恢复卡片与 STP 履约待办说明(表单/弹窗入口)。 * 用途:渲染统一 Gate 恢复卡片与 STP 履约待办说明(表单/弹窗入口)。
* 依赖:ProcessGateRecoveryCard、shipping.api、shipping-tasks.api、ManualUploadEvidenceDialog。 * 依赖:ProcessGateRecoveryCard、shipping.api、shipping-tasks.api、element-plus、ManualUploadEvidenceDialog。
* 逻辑:gateCanHandle 控制 Gate 卡写按钮;actionsExecutable 控制统一 action.code 写操作; * 逻辑:gateCanHandle 控制 Gate 卡写按钮;actionsExecutable 控制统一 action.code 写操作;
* hidePrimaryActions=true 时隐藏本卡按钮(订单处理工作台写入口仅 Footer); * hidePrimaryActions=true 时隐藏本卡按钮(订单处理工作台写入口仅 Footer);
* 系统 Worker / technical_auto_only 不计入人工阻断,避免「待处理事项」冒充系统等待。 * 系统 Worker / technical_auto_only 不计入人工阻断,避免「待处理事项」冒充系统等待。
@@ -9,6 +9,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref } from 'vue'; import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { ElButton } from 'element-plus';
import { useMessage } from '@/shared/composables/useMessage'; import { useMessage } from '@/shared/composables/useMessage';
import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCustomerConfirmDialog.vue'; import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCustomerConfirmDialog.vue';
import type { import type {
@@ -363,31 +364,25 @@ async function runUnifiedAction(action: ShippingUnifiedAction) {
{{ $t('workspace.shippingNotice.todo.adminViewOnly') }} {{ $t('workspace.shippingNotice.todo.adminViewOnly') }}
</div> </div>
<div v-else-if="backendPrimaryAction || backendSecondaryActions.length" class="mt-3 flex flex-wrap gap-2"> <div v-else-if="backendPrimaryAction || backendSecondaryActions.length" class="mt-3 flex flex-wrap gap-2">
<button <ElButton
v-if="backendPrimaryAction" v-if="backendPrimaryAction"
:key="backendPrimaryAction.code" :key="backendPrimaryAction.code"
type="button" :type="backendPrimaryAction.kind === 'terminate' ? 'danger' : backendPrimaryAction.kind === 'view' ? 'default' : 'primary'"
class="rounded-xl px-3 py-1.5 text-sm font-medium transition-colors disabled:opacity-50" :disabled="!backendPrimaryAction.enabled"
:class="backendPrimaryAction.kind === 'terminate' :loading="busyId === backendPrimaryAction.code"
? 'bg-rose-600 text-white hover:bg-rose-700'
: backendPrimaryAction.kind === 'view'
? 'border border-default bg-surface text-secondary hover:bg-surface-soft'
: 'bg-brand-600 text-white hover:bg-brand-700'"
:disabled="!backendPrimaryAction.enabled || busyId === backendPrimaryAction.code"
@click="runUnifiedAction(backendPrimaryAction)" @click="runUnifiedAction(backendPrimaryAction)"
> >
{{ backendPrimaryAction.label }} {{ backendPrimaryAction.label }}
</button> </ElButton>
<button <ElButton
v-for="action in backendSecondaryActions" v-for="action in backendSecondaryActions"
:key="action.code" :key="action.code"
type="button" :disabled="!action.enabled"
class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft disabled:opacity-50" :loading="busyId === action.code"
:disabled="!action.enabled || busyId === action.code"
@click="runUnifiedAction(action)" @click="runUnifiedAction(action)"
> >
{{ action.label }} {{ action.label }}
</button> </ElButton>
</div> </div>
<ManualUploadEvidenceDialog <ManualUploadEvidenceDialog
v-model:open="manualUploadOpen" v-model:open="manualUploadOpen"
@@ -1,12 +1,27 @@
<script setup lang="ts"> <script setup lang="ts">
/** /**
* shared/components/GeneralFeedbackDialog.vue * shared/components/GeneralFeedbackDialog.vue
* 通用意见反馈提交弹窗。 * 用途:工作台和对话里的意见反馈提交弹窗。
* 依赖:element-plus、/api/user/feedback。
* 逻辑:由 FeedbackPage 和 WorkspaceModals 打开。类型、模块和内容仍提交原接口。
*/ */
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { MessageSquareText, X } from 'lucide-vue-next'; import {
ElButton,
ElDialog,
ElForm,
ElFormItem,
ElInput,
ElOption,
ElRadioButton,
ElRadioGroup,
ElSelect,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/shared/styles/element-theme.css';
interface Props { interface Props {
modelValue: boolean; modelValue: boolean;
@@ -121,87 +136,54 @@ const submitFeedback = async () => {
</script> </script>
<template> <template>
<div <ElDialog
v-if="modelValue" :model-value="modelValue"
class="dialog-overlay dialog-overlay--z80" :title="t('feedback.title')"
width="680px"
align-center
append-to-body
:close-on-click-modal="false"
@update:model-value="emit('update:modelValue', $event)"
> >
<div class="dialog-panel max-w-2xl max-h-[92vh]"> <ElForm label-position="top">
<div class="dialog-header"> <ElFormItem :label="t('feedback.labels.type')">
<h3 class="section-title text-2xl">{{ t('feedback.title') }}</h3> <ElRadioGroup v-model="selectedType">
<button <ElRadioButton v-for="item in typeOptions" :key="item" :value="item">{{ item }}</ElRadioButton>
type="button" </ElRadioGroup>
class="btn-icon-ds" </ElFormItem>
aria-label="Close" <ElFormItem :label="t('feedback.labels.module')">
@click="closeDialog" <ElSelect v-model="selectedModule" class="feedback-module">
> <ElOption v-for="item in moduleOptions" :key="item" :label="item" :value="item" />
<X class="h-5 w-5" /> </ElSelect>
</button> </ElFormItem>
</div> <ElFormItem :label="t('feedback.labels.content')" required>
<ElInput
<div class="dialog-body space-y-5">
<div class="space-y-1.5">
<label class="label-field block">{{ t('feedback.labels.type') }}</label>
<div class="segment-control segment-control--cols-3 segment-control--md" role="radiogroup" :aria-label="t('feedback.labels.type')">
<button
v-for="item in typeOptions"
:key="item"
type="button"
role="radio"
:aria-checked="selectedType === item"
class="segment-item"
:class="selectedType === item ? 'segment-item--active' : ''"
@click="selectedType = item"
>
{{ item }}
</button>
</div>
</div>
<div class="space-y-1.5">
<label class="label-field block">{{ t('feedback.labels.module') }}</label>
<select v-model="selectedModule" class="input-field text-base">
<option v-for="item in moduleOptions" :key="item" :value="item">{{ item }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field block">
{{ t('feedback.labels.content') }}<span class="ml-0.5 text-red-500">*</span>
</label>
<textarea
v-model="content" v-model="content"
rows="5" type="textarea"
:rows="5"
maxlength="2000" maxlength="2000"
class="input-field resize-none text-base" show-word-limit
:placeholder="t('feedback.placeholder.content')" :placeholder="t('feedback.placeholder.content')"
/> />
<div class="mt-2 flex items-center justify-between"> <div v-if="error" class="feedback-error">{{ error }}</div>
<div v-if="error" class="text-base text-red-600">{{ error }}</div> </ElFormItem>
<div v-else class="text-base text-muted"> </div> </ElForm>
<div class="text-base text-muted">{{ content.length }}/2000</div> <template #footer>
</div> <ElButton :disabled="submitting" @click="closeDialog">{{ t('feedback.cancel') }}</ElButton>
</div> <ElButton type="primary" :loading="submitting" :disabled="!canSubmit" @click="submitFeedback">
</div>
<div class="dialog-footer">
<button
type="button"
class="btn-ghost"
:disabled="submitting"
@click="closeDialog"
>
{{ t('feedback.cancel') }}
</button>
<button
type="button"
class="btn-primary"
:disabled="!canSubmit"
@click="submitFeedback"
>
<MessageSquareText class="h-5 w-5" />
{{ submitting ? t('feedback.submitting') : t('feedback.submit') }} {{ submitting ? t('feedback.submitting') : t('feedback.submit') }}
</button> </ElButton>
</div>
</div>
</div>
</template> </template>
</ElDialog>
</template>
<style scoped>
.feedback-module {
width: 100%;
}
.feedback-error {
margin-top: 8px;
color: var(--el-color-danger);
}
</style>