fix: fix merge conflicts

This commit is contained in:
sophie committed 2026-09-02 11:49:20 +08:00
commit 03b9b46ebd
114 files changed
+11408 -2996

No files matched your search

+22 -2
View File
@@ -1,14 +1,16 @@
/**
* app/router/guards.ts
* 全局路由守卫:认证、权限、旧 URL 兼容、document.title。
* 依赖:vue-router、config、auth.store、i18n、adminModulePath、isPublicPath。
* 逻辑:beforeEach 做登录/管理员校验;afterEach 将 meta.title(i18n key 或字面量)解析为浏览器标题。
* 依赖:vue-router、config、auth.store、i18n、adminModulePath、isPublicPath、useMessage、contract-payment 权限常量。
* 逻辑:beforeEach 做登录/管理员/功能权限校验;afterEach 将 meta.title(i18n key 或字面量)解析为浏览器标题。
*/
import type { Router } from 'vue-router';
import { config } from '@/config';
import { adminModulePath } from '@/features/admin/constants/modules';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import { CONTRACT_PAYMENT_ACCESS_PERMISSION } from '@/features/contract-payment/constants';
import { isPublicPath } from '@/shared/constants/routes';
import { useMessage } from '@/shared/composables/useMessage';
import i18n from '@/i18n';
/**
@@ -54,6 +56,11 @@ function setupChunkLoadRecovery(router: Router): void {
});
}
/**
注册全局 beforeEach / afterEach:登录、管理员、功能权限与页面标题。
* 核心逻辑:requiresAdmin 仍静默回应用管理;requiresFeaturePermission 会提示后再跳转,避免用户以为入口损坏。
* @param router - 应用根路由实例
*/
export function setupRouterGuards(router: Router): void {
router.beforeEach((to, _from, next) => {
const auth = useAuthStore();
@@ -81,6 +88,19 @@ export function setupRouterGuards(router: Router): void {
return;
}
const requiredFeature = to.matched
.map((record) => record.meta.requiresFeaturePermission)
.find((key): key is string => Boolean(key));
if (requiredFeature && !auth.hasFeaturePermission(requiredFeature)) {
// 无专项权限时提示后再回应用管理,避免静默跳转让用户以为菜单坏了。
const messageKey = requiredFeature === CONTRACT_PAYMENT_ACCESS_PERMISSION
? 'errors.codes.CONTRACT_PAYMENT_FORBIDDEN'
: 'errors.codes.AUTH_FORBIDDEN';
useMessage().warning(String(i18n.global.t(messageKey)));
next('/workspace/applications');
return;
}
next();
});
@@ -1,10 +1,11 @@
/**
* app/router/routes/workspace.routes.ts
* 工作台路由表:/workspace 布局壳 + 各业务子页面懒加载。
* 依赖:vue-router;meta.title 存 i18n key(workspace.*),由 guards 解析为 document.title。
* 逻辑:WorkspaceLayout 嵌套应用首页、知识库、排程、反馈等子页。
* 依赖:vue-router、contract-payment 权限常量;meta.title 存 i18n key(workspace.*),由 guards 解析为 document.title。
* 逻辑:WorkspaceLayout 嵌套应用首页、知识库、排程、反馈等子页;合同付款子路由用 requiresFeaturePermission 而非 requiresAdmin。
*/
import type { RouteRecordRaw } from 'vue-router';
import { CONTRACT_PAYMENT_ACCESS_PERMISSION } from '@/features/contract-payment/constants';
export const workspaceRoutes: RouteRecordRaw[] = [
{
@@ -83,6 +84,30 @@ export const workspaceRoutes: RouteRecordRaw[] = [
component: () => import('@/features/workspace/pages/AccountingVoucherCheckPage.vue'),
meta: { title: 'workspace.nav.accountingVoucherCheck', requiresAdmin: true },
},
{
path: 'contract-payment',
name: 'workspace-contract-payment',
component: () => import('@/features/contract-payment/views/ContractPaymentPage.vue'),
meta: { title: 'workspace.nav.contractPayment', requiresFeaturePermission: CONTRACT_PAYMENT_ACCESS_PERMISSION },
},
{
path: 'contract-payment/review',
name: 'workspace-contract-payment-review',
component: () => import('@/features/contract-payment/views/ContractPaymentReviewPage.vue'),
meta: { title: 'workspace.nav.contractPaymentReview', requiresFeaturePermission: CONTRACT_PAYMENT_ACCESS_PERMISSION },
},
{
path: 'contract-payment/weekly-batches',
name: 'workspace-contract-payment-weekly-batches',
component: () => import('@/features/contract-payment/views/ContractPaymentWeeklyBatchesPage.vue'),
meta: { title: 'workspace.nav.contractPaymentWeeklyBatches', requiresFeaturePermission: CONTRACT_PAYMENT_ACCESS_PERMISSION },
},
{
path: 'contract-payment/contracts/:contractId',
name: 'workspace-contract-payment-detail',
component: () => import('@/features/contract-payment/views/ContractPaymentDetailPage.vue'),
meta: { title: 'workspace.nav.contractPayment', requiresFeaturePermission: CONTRACT_PAYMENT_ACCESS_PERMISSION },
},
{
path: 'feedback',
name: 'workspace-feedback',
+16
View File
@@ -0,0 +1,16 @@
/**
* app/router/vue-router.d.ts
* 用途:扩展 vue-router RouteMeta,供工作台功能权限与管理员门闩使用。
* 依赖:vue-router。
* 逻辑:必须带 export {} 做成模块增强,避免覆盖 vue-router 的完整类型导出。
*/
export {};
declare module 'vue-router' {
interface RouteMeta {
requiresAdmin?: boolean;
requiresFeaturePermission?: string;
title?: string;
workspaceFocus?: string;
}
}
@@ -217,10 +217,19 @@ onMounted(() => {
>
{{ t('admin.role.' + user.role) }}
</span>
<div v-if="user.feature_permissions?.training_hr_manage" class="mt-2">
<span class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700">
<div v-if="user.feature_permissions?.training_hr_manage || user.feature_permissions?.['contract_payment.access']" class="mt-2 flex flex-wrap gap-1.5">
<span
v-if="user.feature_permissions?.training_hr_manage"
class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700"
>
{{ t('admin.user.fields.trainingHrManage') }}
</span>
<span
v-if="user.feature_permissions?.['contract_payment.access']"
class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700"
>
{{ t('admin.user.fields.contractPaymentAccess') }}
</span>
</div>
</td>
<td class="px-6 py-4 text-right">
@@ -1,6 +1,6 @@
/**
* features/admin/modules/users/components/UserFormModal.vue
* 创建/编辑用户弹窗。
* 创建/编辑用户弹窗,含角色与功能权限勾选(培训 HR、合同付款预警访问)。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
@@ -105,6 +105,17 @@ const { t } = useI18n();
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.trainingHrManageHint') }}</span>
</span>
</label>
<label class="flex items-start gap-3 rounded-xl border border-default bg-white px-4 py-3">
<input
v-model="form.feature_permissions['contract_payment.access']"
type="checkbox"
class="mt-0.5 h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
/>
<span class="space-y-1">
<span class="block text-sm font-medium text-primary">{{ t('admin.user.fields.contractPaymentAccess') }}</span>
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.contractPaymentAccessHint') }}</span>
</span>
</label>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
@@ -205,6 +205,7 @@ export function useUsersAdmin() {
phone_number: user.phone_number || '',
feature_permissions: {
training_hr_manage: Boolean(user.feature_permissions?.training_hr_manage),
'contract_payment.access': Boolean(user.feature_permissions?.['contract_payment.access']),
},
agent_ids: user.agent_ids || [],
};
@@ -2,6 +2,7 @@
* features/admin/types/admin.types.ts
* 管理后台域公共类型。
*/
import type { FeaturePermissions } from '@/shared/utils/auth';
export type AdminModuleId =
| 'dashboard'
@@ -60,9 +61,7 @@ export interface AdminUserRow {
real_name?: string;
employee_id?: string;
phone_number?: string;
feature_permissions?: {
training_hr_manage?: boolean;
};
feature_permissions?: FeaturePermissions;
agent_ids: number[];
}
@@ -15,6 +15,7 @@ export interface UserFormState {
phone_number: string;
feature_permissions: {
training_hr_manage: boolean;
'contract_payment.access': boolean;
};
agent_ids: number[];
}
@@ -53,6 +54,7 @@ export const createEmptyUserForm = (): UserFormState => ({
phone_number: '',
feature_permissions: {
training_hr_manage: false,
'contract_payment.access': false,
},
agent_ids: [],
});
+24 -16
View File
@@ -1,6 +1,8 @@
/**
* features/auth/stores/auth.store.ts
* 认证全局状态;Phase 0 仍委托 utils/auth 读写 storage。
* 依赖:shared/utils/auth、contract-payment 权限常量。
* 逻辑:登录态同步到 Pinia;hasFeaturePermission 供路由守卫与侧栏判断专项权限。
*/
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
@@ -11,24 +13,12 @@ import {
saveAuthUser,
logoutAuth as logoutAuthStorage,
refreshAccessToken as refreshAccessTokenStorage,
type AuthUser,
type FeaturePermissions,
} from '@/shared/utils/auth';
import { CONTRACT_PAYMENT_ACCESS_PERMISSION } from '@/features/contract-payment/constants';
export interface AuthUser {
id?: number;
username?: string;
real_name?: string;
employee_id?: string;
role?: string;
feature_permissions?: {
training_hr_manage?: boolean;
[key: string]: boolean | undefined;
};
token?: string;
access_token?: string;
refresh_token?: string;
expires_in?: number;
token_expires_at?: number;
}
export type { AuthUser, FeaturePermissions };
let _syncBound = false;
@@ -44,6 +34,23 @@ export const useAuthStore = defineStore('auth', () => {
const isGuest = computed(() => user.value?.role === 'guest');
const token = computed(() => getAuthToken());
/**
* 判断当前登录用户是否具备指定功能权限。
* 核心逻辑:读取登录态 feature_permissions 的显式布尔值;键缺失时,合同付款访问与后端角色默认对齐(admin 为 true),避免权限键新增前写入的旧会话被误拦。
* @param permissionKey - 后端 User.get_feature_permissions 下发的键
* @returns 显式为 true,或键缺失且命中角色默认时返回 true
*/
const hasFeaturePermission = (permissionKey: string): boolean => {
const bag = user.value?.feature_permissions;
if (bag && Object.prototype.hasOwnProperty.call(bag, permissionKey)) {
return Boolean(bag[permissionKey]);
}
if (permissionKey === CONTRACT_PAYMENT_ACCESS_PERMISSION) {
return user.value?.role === 'admin';
}
return false;
};
const login = (nextUser: AuthUser, remember = false): void => {
saveAuthUser(nextUser, remember);
syncFromStorage();
@@ -68,6 +75,7 @@ export const useAuthStore = defineStore('auth', () => {
isAdmin,
isGuest,
token,
hasFeaturePermission,
syncFromStorage,
login,
logout,
@@ -0,0 +1,47 @@
/**
* 合同付款预警 API 类型与请求封装。
* 依赖:统一 requestJson;后端 /api/contract-payment。
* 逻辑:台账/合同详情查询、待发送摘要、每日扫描入队、周五汇总入队及批次附件下载。
*/
import { requestBlob, requestJson } from '@/shared/api/client';
export interface PaymentNode {
id: number; node_code: string; node_type: string; amount?: string | null; percentage?: string | null;
anchor_type?: string | null; anchor_date?: string | null; due_date?: string | null; paid_at?: string | null; status: string;
}
export interface PaymentAlert { id: number; node_id: number; alert_round: number; scheduled_at?: string | null; sent_at?: string | null; recipient_user_id?: number | null; status: string; }
export interface ContractAttachment {
id: number; source: string; file_name: string; mime_type?: string | null; asset_no?: string | null;
dms_path?: string | null; created_at?: string | null; status: string;
}
export interface ContractPaymentContract {
id: number; contract_no?: string | null; workflow_no?: string | null; purchase_order_no?: string | null;
supplier_name?: string | null; total_amount?: string | null; currency?: string | null; applicant_name?: string | null;
effective_date?: string | null; delivery_due_date?: string | null; oa_archive_at?: string | null;
status: string; parse_status: string; plan_status: string; parse_issues?: string[]; nodes: PaymentNode[]; alerts?: PaymentAlert[]; attachments?: ContractAttachment[];
}
export interface ContractListResponse { total: number; page: number; page_size: number; pages: number; items: ContractPaymentContract[]; }
export interface AlertBatch { id: number; batch_no: string; week_key: string; status: string; summary?: { total?: number; stages?: Record<string, number> }; excel_file_name?: string | null; excel_file_size?: number | null; sent_at?: string | null; }
export interface AlertSummary { pending_count: number; next_send_at?: string | null; timezone?: string | null; }
export const listContractPaymentContracts = (params?: { keyword?: string; parse_status?: string; reviewOnly?: boolean; page?: number; pageSize?: number }) => {
const query = new URLSearchParams(); if (params?.keyword) query.set('keyword', params.keyword); if (params?.parse_status) query.set('parse_status', params.parse_status); if (params?.reviewOnly) query.set('review_only', '1'); if (params?.page) query.set('page', String(params.page)); if (params?.pageSize) query.set('page_size', String(params.pageSize));
const suffix = query.toString() ? `?${query.toString()}` : ''; return requestJson<ContractListResponse>(`/api/contract-payment/contracts${suffix}`);
};
/** 获取单份合同的概览、原文附件、付款计划与预警审计详情。 */
export const getContractPaymentContract = (contractId: number) => requestJson<ContractPaymentContract>(`/api/contract-payment/contracts/${contractId}`);
/** 用已归档的盖章合同原文重新解析,并返回覆盖后的合同详情。 */
export const reparseContractPaymentContract = (contractId: number) => requestJson<{ contract: ContractPaymentContract; parse_result: { status: string }; attachment_name: string }>(`/api/contract-payment/contracts/${contractId}/reparse`, { method: 'POST' });
/** 下载当前登录用户有权限访问的合同原文附件。 */
export const downloadContractPaymentAttachment = (contractId: number, attachmentId: number) => requestBlob(`/api/contract-payment/contracts/${contractId}/attachments/${attachmentId}/download`);
/** 提交 OA 合同同步;force 为 true 时由后端显式覆盖本次 OA 返回的非空主表字段。 */
export const enqueueContractPaymentSync = (force = false) => requestJson<{ job_id: string }>('/api/contract-payment/sync', { method: 'POST', body: JSON.stringify({ force }) });
/** 提交存量合同批量重解析,直接使用已归档附件刷新历史解析结果。 */
export const enqueueContractPaymentReparse = () => requestJson<{ job_id: string }>('/api/contract-payment/sync', { method: 'POST', body: JSON.stringify({ reparse_existing: true }) });
export const enqueueContractPaymentAlertScan = () => requestJson<{ job_id: string }>('/api/contract-payment/alerts/run', { method: 'POST' });
export const enqueueContractPaymentWeeklyAlert = () => requestJson<{ job_id: string }>('/api/contract-payment/alerts/weekly-run', { method: 'POST' });
/** 查询本周待发送笔数和下一次周五汇总发送时间。 */
export const getContractPaymentAlertSummary = () => requestJson<AlertSummary>('/api/contract-payment/alerts/summary');
export const listContractPaymentAlertBatches = () => requestJson<{ items: AlertBatch[] }>('/api/contract-payment/alert-batches');
/** 下载已归档的合同付款预警周汇总 Excel 明细。 */
export const downloadContractPaymentAlertBatchExcel = (batchId: number) => requestBlob(`/api/contract-payment/alert-batches/${batchId}/excel`);
@@ -0,0 +1,7 @@
/**
* features/contract-payment/constants.ts
* 用途:合同付款预警前端权限键与路由 meta 共用常量。
* 依赖:无。
* 逻辑:路由守卫、侧栏与用户管理勾选读取同一键,须与后端 User._role_default_feature_permissions 一致。
*/
export const CONTRACT_PAYMENT_ACCESS_PERMISSION = 'contract_payment.access' as const;
@@ -0,0 +1,22 @@
/**
* features/contract-payment/utils/currency.ts
* 用途:合同付款预警域的币别展示工具,统一台账与详情页面的币别过滤规则。
* 依赖:无(纯函数)。
* 逻辑:OA「合同书币别」为下拉单选项;未实际选择时同步原始值会误抓取全部候选项
* (如“美元 人民币 台币 泰铢”),本工具据此判定是否视为未获取。
*/
/** OA 合同书币别下拉的候选币别,用于识别“未选择时误抓取的全部候选项”。 */
export const CURRENCY_OPTIONS = ['美元', '人民币', '台币', '泰铢'];
/**
* 返回可展示的合同币别,过滤 OA 下拉框未选择时误抓取的全部候选项。
* 核心逻辑:单一币别正常展示;同一原始值包含两个及以上预置候选币别时视为未获取。
* @param currency - 后端同步的原始币别文本,可为空。
* @returns 可展示的单一币别;未获取或候选项串联时返回空字符串。
*/
export function displayCurrency(currency?: string | null): string {
const normalized = String(currency || '').trim();
const matchedCount = CURRENCY_OPTIONS.filter((option) => normalized.includes(option)).length;
return matchedCount >= 2 ? '' : normalized;
}
@@ -0,0 +1,72 @@
/**
* features/contract-payment/utils/paymentStatus.ts
* 用途:合同付款节点的到期/逾期判定,以及台账级“按节点聚合的付款状态”推导。
* 依赖:contract-payment.api 的 PaymentNode 类型、浏览器 Date。
* 逻辑:付款节点到期/逾期以节点 due_date 为准;台账状态按节点聚合,供列表页一行一眼看是否逾期。
*/
import type { PaymentNode } from '../api/contract-payment.api';
/**
* 判断某个日期是否临近到期(含今天起 7 天内)。
* 核心逻辑:与 isNodeOverdue 共用 UTC 日期归一;范围内(0..7 天)判定为临近到期。
* @param due - 到期日期(YYYY-MM-DD)。
* @returns 是否临近到期。
*/
export function isNodeNearDue(due?: string | null): boolean {
if (!due) return false;
const target = new Date(`${due}T00:00:00Z`);
if (Number.isNaN(target.getTime())) return false;
const today = new Date(`${new Date().toISOString().slice(0, 10)}T00:00:00Z`);
const days = Math.round((target.getTime() - today.getTime()) / 86400000);
return days >= 0 && days <= 7;
}
/**
* 判断某个日期是否已逾期(早于今天)。
* 核心逻辑:与 isNodeNearDue 共用 UTC 日期归一;due_date 早于今天即判定为逾期。
* @param due - 到期日期(YYYY-MM-DD)。
* @returns 是否已逾期。
*/
export function isNodeOverdue(due?: string | null): boolean {
if (!due) return false;
const target = new Date(`${due}T00:00:00Z`);
if (Number.isNaN(target.getTime())) return false;
const today = new Date(`${new Date().toISOString().slice(0, 10)}T00:00:00Z`);
const days = Math.round((target.getTime() - today.getTime()) / 86400000);
return days < 0;
}
/**
* 返回付款节点的“到期判断基准日期”。
* 核心逻辑:优先用 due_date;因历史合同预付款节点可能只写 anchor_date(合同归档日)而未写 due_date,
* 回退到 anchor_date,避免把已归档的预付款漏判为未逾期。展示层页码与本判断共用同一基准(due || anchor)。
* @param node - 付款节点。
* @returns 到期基准日期(YYYY-MM-DD);两者皆空时返回 null。
*/
export function nodeDueReference(node: Pick<PaymentNode, 'due_date' | 'anchor_date'>): string | null {
return node.due_date || node.anchor_date || null;
}
/** 台账级付款状态编码:进行中 / 即将到期 / 已逾期 / 已完成 / 待补充。 */
export type ContractNodeStatusCode = 'active' | 'due' | 'overdue' | 'completed' | 'needs_completion';
/**
* 按付款节点聚合出合同台账的进度/逾期状态。
* 核心逻辑:先在合同层排除「待补充」(非激活或解析待确认);否则若存在未付且已过 due_date 的
* 节点 → 已逾期;存在 7 天内到期 → 即将到期;仍有未付节点 → 进行中;全部节点已付 → 已完成。
* @param nodes - 合同的付款节点列表。
* @returns 台账状态编码。
*/
export function aggregateContractNodeStatus(nodes: PaymentNode[]): ContractNodeStatusCode {
if (!nodes || nodes.length === 0) return 'needs_completion';
const active = nodes.filter((n) => String(n.status || '').trim().toLowerCase() === 'active');
if (active.length === 0) {
// 无进行中的节点:存在已付则视为整个付款计划已完成,否则判为待补充。
const hasPaid = nodes.some((n) => String(n.status || '').trim().toLowerCase() === 'paid' || !!n.paid_at);
return hasPaid ? 'completed' : 'needs_completion';
}
if (active.some((n) => isNodeOverdue(nodeDueReference(n)))) return 'overdue';
if (active.some((n) => isNodeNearDue(nodeDueReference(n)))) return 'due';
return 'active';
}
@@ -0,0 +1,351 @@
<!--
features/contract-payment/views/ContractPaymentDetailPage.vue
用途:展示单份采购合同的概览、原文附件、付款计划及企业微信预警审计。
依赖:contract-payment.api、vue-router、统一消息提示;由合同付款台账的行点击进入。
逻辑:以合同 ID 调用已有详情接口,所有付款任务按付款节点和预警轮次聚合呈现。
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ArrowLeft, CircleHelp, Download, FileText, RefreshCw } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { formatLocalDateTime, formatNaiveDate, formatNaiveDateTime } from '@/shared/utils/dateTime';
import { useMessage } from '@/shared/composables/useMessage';
import {
downloadContractPaymentAttachment,
getContractPaymentContract,
reparseContractPaymentContract,
type ContractAttachment,
type ContractPaymentContract,
type PaymentNode,
} from '../api/contract-payment.api';
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
import { displayCurrency } from '../utils/currency';
import { isNodeNearDue, isNodeOverdue, nodeDueReference } from '../utils/paymentStatus';
const { t, te } = useI18n();
const route = useRoute();
const router = useRouter();
const msg = useMessage();
const contract = ref<ContractPaymentContract | null>(null);
const loading = ref(false);
const downloadingId = ref<number | null>(null);
const reparsing = ref(false);
const activeTab = ref<'plan' | 'attachments' | 'alerts'>('plan');
const contractId = computed(() => Number(route.params.contractId));
const orderedNodes = computed(() => {
const order = ['prepayment', 'shipment', 'acceptance', 'warranty'];
return [...(contract.value?.nodes || [])].sort((left, right) => order.indexOf(left.node_type) - order.indexOf(right.node_type));
});
/**
* 以整数格式显示付款比例,保持台账和详情页面的金额比例表达一致。
* 核心逻辑:数值比例四舍五入为整数;异常原值原样显示,避免页面误显示为零。
* @param percentage - 接口返回的付款比例。
* @returns 适合页面展示的比例文本。
*/
function displayPercentage(percentage?: string | null): string {
if (percentage === undefined || percentage === null || percentage === '') return '—';
const value = Number(percentage);
return Number.isFinite(value) ? String(Math.round(value)) : String(percentage);
}
/**
* 返回付款阶段的本地化名称。
* 核心逻辑:现有四阶段使用 i18n;服务端新增阶段保留原始编码,保证审计信息仍可阅读。
* @param nodeType - 付款节点类型。
* @returns 本地化阶段名称或原始节点类型。
*/
function displayNodeType(nodeType: string): string {
const key = `admin.contractPayment.nodeType.${nodeType}`;
return te(key) ? t(key) : nodeType;
}
/**
* 格式化预警计划日期为原墙面时钟的 YYYY-MM-DD HH:mm:ss。
* 核心逻辑:scheduled_at 是业务日期(节点触发日)与零点组合的墙面时钟,不做时区换算,
* 避免把「8 月 22 日触发」误显示为次日;空值回退 '—',非法日期回退原值以便排障。
* @param iso - 后端返回的 ISO 计划日期字符串。
* @returns 墙面时钟时间文本。
*/
function displayScheduledAt(iso?: string | null): string {
return iso ? formatNaiveDateTime(iso) : '—';
}
/**
* 格式化预警发送时间为用户本地时间的 YYYY-MM-DD HH:mm:ss。
* 核心逻辑:sent_at 由后端以 UTC 存储(datetime.utcnow),需换算到浏览器时区展示。
* @param iso - 后端返回的 ISO 发送时间字符串。
* @returns 本地时间文本。
*/
function displaySentAt(iso?: string | null): string {
return iso ? formatLocalDateTime(iso) : '—';
}
/**
* 返回合同解析/计划状态的本地化文本。
* 核心逻辑:将后端编码(parsed / needs_review / pending / active)映射到 i18n;未知编码回退原值,便于排障。
* @param state - 后端返回的解析状态或计划状态编码。
* @returns 本地化状态文本;空值时返回 '—'。
*/
function displayContractState(state?: string | null): string {
const normalized = String(state || '').trim().toLowerCase();
if (!normalized) return '—';
const key = `admin.contractPayment.stateLabel.${normalized}`;
return te(key) ? t(key) : state || '—';
}
/**
* 返回付款节点的展示预警日期。
* 核心逻辑:预付款为“归档日 +7/14/21 天”多轮规则,节点不存单一 due_date;
* 有 due_date 时原样展示,否则对预付款按首轮(归档日 +7 天)推算并标注“首轮”,避免空“预警日期”误导。
* @param node - 当前付款节点。
* @returns 用户可见的预警日期文本;无依据时返回 '—'。
*/
function displayAlertDate(node: PaymentNode): string {
// 预付款优先按「归档日 +7 天首轮」展示预警日期,与 due_date(仅用于到期/逾期判断)解耦。
// 预付款的 due_date = 合同归档日期,若直接走下面的 due_date 分支会丢失「首轮 +7」信息。
if (node.node_type === 'prepayment' && node.anchor_date) {
const anchor = new Date(`${node.anchor_date}T00:00:00Z`);
if (!Number.isNaN(anchor.getTime())) {
anchor.setUTCDate(anchor.getUTCDate() + 7);
return `${t('admin.contractPayment.alertFirstRound')} ${anchor.toISOString().slice(0, 10)}`;
}
}
if (node.due_date) return node.due_date;
return '—';
}
/**
* 当前处于“进行中”的付款节点 id:按阶段顺序取第一个“未完成且非待复核”的节点。
* 核心逻辑:付款四阶段按预付款→出货款→验收款→质保款先后推进,同一时间只有当前阶段进行中;
* 已付款/待复核的节点不占用“进行中”,后续阶段显示为待处理。
*/
const currentActiveNodeId = computed(() => {
for (const node of orderedNodes.value) {
const state = String(node.status || '').trim().toLowerCase();
if (state === 'active') return node.id;
}
return null;
});
/**
* 推导付款节点的展示状态与时间线色调。
* 核心逻辑:已付/待复核沿用后端明确状态;未完成时按“无到期事实→待起算、临近到期→即将到期、
* 当前阶段→进行中、其余→待处理”分层,避免同页多阶段都误标为进行中。
* @param node - 当前付款节点。
* @returns 用户可见的状态文本与对应色调。
*/
function nodeStatusInfo(node: PaymentNode): { label: string; tone: 'paid' | 'current' | 'due' | 'overdue' | 'pending' | 'review' } {
const state = String(node.status || '').trim().toLowerCase();
if (state === 'paid') return { label: t('admin.contractPayment.nodeStatus.paid'), tone: 'paid' };
if (state === 'needs_review') return { label: t('admin.contractPayment.nodeStatus.review'), tone: 'review' };
const isCurrent = node.id === currentActiveNodeId.value;
if (!node.due_date && !node.anchor_date) return { label: t('admin.contractPayment.nodeStatus.notStarted'), tone: 'pending' };
// 到期/逾期判断:以「due_date || anchor_date」为基准;历史合同预付款可能只有 anchor_date(归档日),
// 回退到 anchor_date 避免把已归档的预付款漏判为未逾期。
const dueRef = nodeDueReference(node);
if (dueRef) {
if (isNodeOverdue(dueRef)) return { label: t('admin.contractPayment.nodeStatus.overdue'), tone: 'overdue' };
if (isNodeNearDue(dueRef)) return { label: t('admin.contractPayment.nodeStatus.upcoming'), tone: 'due' };
}
return isCurrent
? { label: t('admin.contractPayment.nodeStatus.active'), tone: 'current' }
: { label: t('admin.contractPayment.nodeStatus.pending'), tone: 'pending' };
}
/**
* 返回付款节点的付款日期展示文本。
* 核心逻辑:已付款显示 ERP apa_file 付款日期,未付显示“未付”。
* @param node - 当前付款节点。
* @returns 用户可见的付款日期文本。
*/
function nodePayDateText(node: PaymentNode): string {
if (String(node.status || '').trim().toLowerCase() === 'paid') return node.paid_at || '—';
return '—';
}
/**
* 映射单条预警的发送状态。
* 核心逻辑:与批次审计状态复用同一组 i18n 键,未知状态保留后端文本以支持排障。
* @param status - 后端预警记录状态。
* @returns 用户可见状态文本。
*/
function displayAlertStatus(status?: string | null): string {
const normalized = String(status || '').trim().toLowerCase();
const key = `admin.contractPayment.batchStatus.${normalized}`;
return normalized && te(key) ? t(key) : (status || '—');
}
/**
* 按节点查询已有的预警发送任务。
* 核心逻辑:合同详情接口已返回完整审计列表,前端只做关联展示,不再额外请求或推导发送结果。
* @param node - 当前付款节点。
* @returns 该节点的预警记录,按接口原有计划日期顺序显示。
*/
function alertsForNode(node: PaymentNode) {
return (contract.value?.alerts || []).filter((alert) => alert.node_id === node.id);
}
/**
* 加载当前路由合同的完整详情。
* 核心逻辑:ID 非法时返回台账;接口失败保留空态并展示统一业务错误。
* @returns 完成后更新详情数据及加载状态。
*/
async function load(): Promise<void> {
if (!Number.isInteger(contractId.value) || contractId.value <= 0) {
await router.replace(WORKSPACE_PATHS.contractPayment);
return;
}
loading.value = true;
try {
contract.value = await getContractPaymentContract(contractId.value);
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.contractPayment.detailLoadFailed'));
} finally {
loading.value = false;
}
}
/**
* 下载合同详情中的原文附件。
* 核心逻辑:经合同附件专用受控接口取 Blob,再由浏览器保存,避免直接暴露存储地址。
* @param attachment - 当前合同的附件记录。
* @returns 下载完成后释放临时对象 URL;失败时给出统一提示。
*/
async function downloadAttachment(attachment: ContractAttachment): Promise<void> {
if (!contract.value) return;
downloadingId.value = attachment.id;
try {
const { blob, filename } = await downloadContractPaymentAttachment(contract.value.id, attachment.id);
const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = objectUrl;
anchor.download = filename || attachment.file_name;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
URL.revokeObjectURL(objectUrl);
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.contractPayment.attachmentDownloadFailed'));
} finally {
downloadingId.value = null;
}
}
/**
* 从当前合同已归档的权威原文附件重新执行付款解析。
* 核心逻辑:调用服务端受控重解析接口;成功后直接以返回的新详情刷新页面,避免页面继续展示旧节点。
* @returns 重解析完成后更新当前合同;失败时显示后端返回的可处理原因。
*/
async function reparseContract(): Promise<void> {
if (!contract.value || reparsing.value) return;
reparsing.value = true;
try {
const result = await reparseContractPaymentContract(contract.value.id);
contract.value = result.contract;
msg.success(t('admin.contractPaymentReparse.success', { attachment: result.attachment_name }));
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.contractPaymentReparse.failed'));
} finally {
reparsing.value = false;
}
}
/**
* 返回合同付款预警台账。
* 核心逻辑:使用路由常量而非浏览器历史,避免从周汇总或外部链接进入详情时返回错误页面。
* @returns 路由跳转完成。
*/
async function backToLedger(): Promise<void> {
await router.push(WORKSPACE_PATHS.contractPayment);
}
onMounted(() => void load());
</script>
<template>
<section class="section-gap animate-fade-in-up">
<header class="mb-5 flex items-start justify-between gap-3">
<div v-if="contract" class="min-w-0">
<h2 class="text-2xl font-bold text-primary">{{ contract.contract_no || t('admin.contractPayment.contractNoPending') }}</h2>
<p class="mt-1 text-sm text-muted">{{ contract.supplier_name || '—' }}<span v-if="contract.purchase_order_no"> · {{ contract.purchase_order_no }}</span></p>
</div>
<div class="flex shrink-0 gap-2"><button class="btn-secondary-ds" :disabled="reparsing" @click="reparseContract"><RefreshCw class="h-4 w-4" :class="{ 'animate-spin': reparsing }" />{{ t('admin.contractPaymentReparse.action') }}</button><button class="btn-secondary-ds" @click="backToLedger"><ArrowLeft class="h-4 w-4" />{{ t('admin.contractPayment.backToLedger') }}</button></div>
</header>
<div v-if="loading && !contract" class="detail-empty">{{ t('admin.contractPayment.detailLoading') }}</div>
<template v-else-if="contract">
<div class="detail-summary-grid">
<div class="detail-summary-card"><span>{{ t('admin.contractPayment.amount') }}</span><strong>{{ contract.total_amount || '—' }}<template v-if="displayCurrency(contract.currency)"> {{ displayCurrency(contract.currency) }}</template></strong></div>
<div class="detail-summary-card"><span>{{ t('admin.contractPayment.purchaseOrder') }}</span><strong>{{ contract.purchase_order_no || '—' }}</strong></div>
<div class="detail-summary-card"><span>{{ t('admin.contractPayment.workflowNo') }}</span><strong>{{ contract.workflow_no || '—' }}</strong></div>
<div class="detail-summary-card"><span>{{ t('admin.contractPayment.applicant') }}</span><strong>{{ contract.applicant_name || '—' }}</strong></div>
</div>
<section class="detail-panel mt-4">
<h3>{{ t('admin.contractPayment.detailOverview') }}</h3>
<dl class="detail-description-list">
<div><dt>{{ t('admin.contractPayment.parseStatus') }}</dt><dd>{{ displayContractState(contract.parse_status) }}</dd></div>
<div><dt>{{ t('admin.contractPayment.planStatus') }}</dt><dd>{{ displayContractState(contract.plan_status) }}</dd></div>
<div><dt><span class="help-label" :data-help="t('admin.contractPayment.archiveDateHint')">{{ t('admin.contractPayment.archiveDate') }}<CircleHelp class="ml-1 inline h-3.5 w-3.5 align-middle" /></span></dt><dd>{{ contract.oa_archive_at ? formatNaiveDate(contract.oa_archive_at) : '—' }}</dd></div>
<div><dt>{{ t('admin.contractPayment.deliveryDate') }}</dt><dd>{{ contract.delivery_due_date || '—' }}</dd></div>
</dl>
<div v-if="contract.parse_issues?.length" class="detail-parse-issues">
<strong>{{ t('admin.contractPayment.parseIssueTitle') }}</strong>
<ul><li v-for="issue in contract.parse_issues" :key="issue">{{ issue }}</li></ul>
</div>
</section>
<div class="detail-tabs mt-4" role="tablist">
<button :class="{ active: activeTab === 'plan' }" @click="activeTab = 'plan'">{{ t('admin.contractPayment.detailPaymentPlan') }}</button>
<button :class="{ active: activeTab === 'attachments' }" @click="activeTab = 'attachments'">{{ t('admin.contractPayment.detailAttachments') }}</button>
<button :class="{ active: activeTab === 'alerts' }" @click="activeTab = 'alerts'">{{ t('admin.contractPayment.detailAlertHistory') }}</button>
</div>
<section v-if="activeTab === 'attachments'" class="detail-panel mt-4">
<h3>{{ t('admin.contractPayment.detailAttachments') }}</h3>
<div v-if="!contract.attachments?.length" class="detail-empty">{{ t('admin.contractPayment.attachmentsEmpty') }}</div>
<div v-for="attachment in contract.attachments" :key="attachment.id" class="attachment-row">
<FileText class="h-5 w-5 text-blue-500" />
<div class="min-w-0 flex-1"><strong class="block truncate">{{ attachment.file_name }}</strong></div>
<button class="btn-secondary-ds" :disabled="downloadingId === attachment.id || !attachment.asset_no" @click="downloadAttachment(attachment)"><Download class="h-4 w-4" />{{ t('admin.contractPayment.downloadAttachment') }}</button>
</div>
</section>
<section v-else-if="activeTab === 'plan'" class="detail-panel mt-4">
<h3>{{ t('admin.contractPayment.detailPaymentPlan') }}</h3>
<div v-if="!orderedNodes.length" class="detail-empty">{{ t('admin.contractPayment.paymentPlanEmpty') }}</div>
<div v-for="node in orderedNodes" :key="node.id" class="payment-node-row">
<span class="timeline-dot" :class="`dot-${nodeStatusInfo(node).tone}`"></span>
<div class="payment-node-card">
<div class="flex flex-wrap items-center justify-between gap-2"><strong>{{ displayNodeType(node.node_type) }} · {{ node.amount || '—' }} / {{ displayPercentage(node.percentage) }}%</strong><span class="node-status" :class="`status-${nodeStatusInfo(node).tone}`">{{ nodeStatusInfo(node).label }}</span></div>
<p class="payment-node-pay-line">{{ t('admin.contractPayment.payDate') }}:{{ nodePayDateText(node) }}</p>
<p>{{ t('admin.contractPayment.anchorDate') }}:{{ node.anchor_date || '—' }} · {{ t('admin.contractPayment.alertDate') }}:{{ displayAlertDate(node) }}</p>
<div v-if="alertsForNode(node).length" class="node-alert-list"><span v-for="alert in alertsForNode(node)" :key="alert.id">{{ t('admin.contractPayment.alertRound', { round: alert.alert_round }) }} · {{ displayScheduledAt(alert.scheduled_at) }} · {{ displayAlertStatus(alert.status) }}</span></div>
</div>
</div>
</section>
<section v-else class="detail-panel mt-4">
<h3>{{ t('admin.contractPayment.detailAlertHistory') }}</h3>
<div v-if="!contract.alerts?.length" class="detail-empty">{{ t('admin.contractPayment.alertAuditEmpty') }}</div>
<div v-for="alert in contract.alerts" :key="alert.id" class="alert-row">
<strong>{{ t('admin.contractPayment.alertRound', { round: alert.alert_round }) }}</strong>
<span>{{ orderedNodes.find((node) => node.id === alert.node_id) ? displayNodeType(orderedNodes.find((node) => node.id === alert.node_id)!.node_type) : '—' }}</span>
<span>{{ t('admin.contractPayment.alertScheduledAt') }}:{{ displayScheduledAt(alert.scheduled_at) }}</span>
<span>{{ t('admin.contractPayment.alertSentAt') }}:{{ displaySentAt(alert.sent_at) }}</span>
<span class="node-status">{{ displayAlertStatus(alert.status) }}</span>
</div>
</section>
</template>
</section>
</template>
<style scoped>
.detail-summary-grid { display: grid; grid-template-columns: repeat(4, minmax(150px, 1fr)); gap: 12px; }.detail-summary-card { min-height: 82px; padding: 14px; border: 1px solid #d7e1ef; border-radius: 12px; background: #f8fbff; }.detail-summary-card span { display: block; color: #58749f; font-size: 12px; }.detail-summary-card strong { display: block; margin-top: 6px; color: #102d59; font-size: 14px; word-break: break-word; }.detail-tabs { display: flex; width: fit-content; max-width: 100%; overflow-x: auto; border: 1px solid #d7e1ef; border-radius: 999px; background: #f1f5fb; padding: 4px; }.detail-tabs button { flex: none; border-radius: 999px; padding: 8px 14px; color: #58749f; font-size: 13px; font-weight: 700; }.detail-tabs button.active { background: #fff; color: #2875d5; box-shadow: 0 1px 3px rgba(35, 68, 113, .12); }.detail-panel { border: 1px dashed #b9cbe2; border-radius: 12px; background: #fff; padding: 18px; }.detail-panel h3 { margin-bottom: 14px; color: #102d59; font-size: 16px; font-weight: 750; }.detail-description-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 28px; }.detail-description-list div { display: flex; gap: 8px; }.detail-description-list dt { color: #58749f; }.detail-description-list dd { color: #102d59; font-weight: 650; }.detail-note { margin-top: 16px; border-radius: 8px; background: #f7faff; padding: 10px 12px; color: #58749f; font-size: 13px; }.attachment-row { display: flex; align-items: center; gap: 12px; border-top: 1px solid #e4ecf6; padding: 13px 0; }.attachment-row:first-of-type { border-top: 0; }.attachment-row span { color: #58749f; font-size: 12px; }.payment-node-row { position: relative; display: flex; gap: 14px; padding: 0 0 18px 6px; }.payment-node-row::before { position: absolute; top: 18px; bottom: -2px; left: 12px; width: 2px; background: #d7e1ef; content: ''; }.payment-node-row:last-child::before { display: none; }.timeline-dot { z-index: 1; width: 14px; height: 14px; margin-top: 8px; flex: none; border-radius: 999px; background: #fff; border: 2px solid #3b82e5; }.payment-node-card { flex: 1; border: 1px solid #d7e1ef; border-radius: 12px; padding: 13px 15px; }.payment-node-card strong { color: #102d59; }.payment-node-card p { margin-top: 5px; color: #58749f; font-size: 13px; }.node-status { display: inline-flex; min-height: 22px; align-items: center; border-radius: 999px; background: #edf5ff; padding: 2px 8px; color: #2563eb; font-size: 12px; font-weight: 700; }.node-alert-list { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }.node-alert-list span { border-radius: 6px; background: #f7faff; padding: 4px 7px; color: #58749f; font-size: 12px; }.alert-row { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 18px; border-top: 1px solid #e4ecf6; padding: 12px 0; color: #58749f; font-size: 13px; }.alert-row:first-of-type { border-top: 0; }.alert-row strong { color: #102d59; }.detail-empty { padding: 38px; color: var(--text-muted); text-align: center; } @media (max-width: 1280px) { .detail-summary-grid { grid-template-columns: repeat(3, minmax(160px, 1fr)); } } @media (max-width: 640px) { .detail-summary-grid, .detail-description-list { grid-template-columns: 1fr; }.attachment-row { align-items: flex-start; flex-wrap: wrap; }.attachment-row button { margin-left: 32px; } }
.help-label { position: relative; cursor: help; }.help-label::after { position: absolute; z-index: 20; top: calc(100% + 6px); left: 0; width: max-content; max-width: min(280px, 70vw); padding: 7px 9px; border-radius: 6px; background: #334155; color: #fff; content: attr(data-help); font-size: 11px; font-weight: 400; line-height: 1.45; opacity: 0; pointer-events: none; transition: opacity .15s ease; white-space: normal; }.help-label:hover::after { opacity: 1; }.detail-parse-issues { margin-top: 14px; border-radius: 8px; background: #fff7ed; padding: 10px 12px; color: #9a3412; font-size: 13px; }.detail-parse-issues strong { display: block; margin-bottom: 4px; font-weight: 700; }.detail-parse-issues ul { margin: 0; padding-left: 16px; }.detail-parse-issues li { line-height: 1.6; }
.timeline-dot.dot-paid, .timeline-dot.dot-current { background: #16a34a; border-color: #16a34a; }.timeline-dot.dot-due { background: #ea580c; border-color: #ea580c; }.timeline-dot.dot-overdue { background: #dc2626; border-color: #dc2626; }.timeline-dot.dot-pending { background: #fff; border-color: #93a7c8; }.timeline-dot.dot-review { background: #f59e0b; border-color: #f59e0b; }.node-status.status-paid { background: #e8f7ee; color: #16a34a; }.node-status.status-current { background: #e8f7ee; color: #16a34a; }.node-status.status-due { background: #fff4e8; color: #ea580c; }.node-status.status-overdue { background: #fee2e2; color: #dc2626; }.node-status.status-pending { background: #eef3fa; color: #5c76a0; }.node-status.status-review { background: #fff7ed; color: #c2410c; }.payment-node-pay-line { margin-top: 6px; color: #102d59; font-weight: 650; }
</style>
@@ -0,0 +1,263 @@
<!--
合同付款预警工作台:展示合同台账、付款阶段字段、本周待发送摘要,并提供预警任务入口。
依赖:contract-payment.api、PaginationBar、统一消息提示;周汇总批次由独立页面展示。
-->
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { CalendarClock, RefreshCw, Search, Send } from 'lucide-vue-next';
import { BusinessError } from '@/shared/api/client';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { useMessage } from '@/shared/composables/useMessage';
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
import {
enqueueContractPaymentAlertScan,
enqueueContractPaymentReparse,
enqueueContractPaymentSync,
enqueueContractPaymentWeeklyAlert,
getContractPaymentAlertSummary,
listContractPaymentContracts,
type AlertSummary,
type ContractPaymentContract,
} from '../api/contract-payment.api';
import { displayCurrency } from '../utils/currency';
import { aggregateContractNodeStatus, type ContractNodeStatusCode } from '../utils/paymentStatus';
const { t } = useI18n();
const router = useRouter();
const msg = useMessage(); const keyword = ref(''); const loading = ref(false); const actionLoading = ref(false);
const showForceSyncConfirm = ref(false);
const showReparseExistingConfirm = ref(false);
const contracts = ref<ContractPaymentContract[]>([]);
const alertSummary = ref<AlertSummary | null>(null);
const page = ref(1); const pageSize = ref(20); const total = ref(0); const pages = ref(1);
const stage = (item: ContractPaymentContract, name: string) => item.nodes.find((node) => node.node_type === name);
/**
* 以整数格式展示付款比例,不改变接口返回的精确比例值。
* 核心逻辑:兼容字符串或数值;非数值保持原样,避免将异常数据错误改写为零。
* @param percentage - 节点的原始付款比例。
* @returns 去除无意义小数位后的比例文本。
*/
const displayPercentage = (percentage?: string | null): string => {
if (percentage === undefined || percentage === null || percentage === '') return '—';
const value = Number(percentage);
return Number.isFinite(value) ? String(Math.round(value)) : String(percentage);
};
/**
* 将付款节点拆为原型表格需要的金额比例行和日期行。
* 核心逻辑:节点不存在时显示短横线;存在但日期未明确时仅显示“待补充日期”,避免把锚点日期误当付款日期。
* @param item - 合同台账行。
* @param name - 付款节点类型。
* @returns 表格单元格展示所需的金额比例、日期及是否为待补充状态。
*/
const paymentCell = (item: ContractPaymentContract, name: string) => {
const node = stage(item, name);
if (!node) return { amountRatio: '—', date: '', missingDate: false };
const amountRatio = node.amount || node.percentage ? `${node.amount || '—'} / ${displayPercentage(node.percentage)}%` : '—';
const date = node.due_date || node.anchor_date || '';
return { amountRatio, date, missingDate: !date };
};
/**
* 按付款节点聚合台账状态:进行中 / 即将到期 / 已逾期 / 已完成 / 待补充。
* 核心逻辑:合同层先排除「待补充」(非激活或解析待确认);否则按节点到期/逾期状态取最高优先级展示,
* 让台账行一眼看出是否有逾期款。 @param item - 合同台账行。 @returns 状态标签和对应的视觉色调。
*/
const displayStatus = (item: ContractPaymentContract) => {
if (item.status !== 'active' || item.parse_status === 'needs_review') {
return { label: t('admin.contractPayment.statusNeedsCompletion'), tone: 'needs-completion' };
}
const code = aggregateContractNodeStatus(item.nodes || []);
const map: Record<ContractNodeStatusCode, { label: string; tone: string }> = {
overdue: { label: t('admin.contractPayment.statusOverdue'), tone: 'overdue' },
due: { label: t('admin.contractPayment.statusUpcoming'), tone: 'due' },
active: { label: t('admin.contractPayment.statusActive'), tone: 'normal' },
completed: { label: t('admin.contractPayment.statusCompleted'), tone: 'completed' },
needs_completion: { label: t('admin.contractPayment.statusNeedsCompletion'), tone: 'needs-completion' },
};
return map[code];
};
/**
* 将下次发送的 UTC 时间格式化为业务时区(默认上海)的年月日时分。
* 核心逻辑:使用接口返回的 timezone,避免浏览器本地时区把周五 18:00 显示成错误日期。
* @param iso - 后端返回的 UTC ISO 时间。
* @param timeZone - 业务时区名称。
* @returns `YYYY-MM-DD HH:mm`;无法解析时回退原值。
*/
function formatNextSendAt(iso?: string | null, timeZone?: string | null): string {
if (!iso) return '—';
const date = new Date(iso);
if (Number.isNaN(date.getTime())) return iso;
try {
return new Intl.DateTimeFormat('sv-SE', {
timeZone: timeZone || 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).format(date).replace('T', ' ');
} catch {
return iso;
}
}
const weeklyPendingText = computed(() => {
if (!alertSummary.value) return '';
const count = alertSummary.value.pending_count ?? 0;
const datetime = formatNextSendAt(alertSummary.value.next_send_at, alertSummary.value.timezone);
if (!alertSummary.value.next_send_at) {
return t('admin.contractPayment.weeklyPendingCountOnly', { count });
}
return t('admin.contractPayment.weeklyPendingSummary', { count, datetime });
});
/**
* 刷新本周待发送笔数和下一次周五发送时间。
* 核心逻辑:与合同列表分开请求,摘要失败不阻断台账展示。
*/
async function refreshSummary(): Promise<void> {
try {
alertSummary.value = await getContractPaymentAlertSummary();
} catch {
if (!alertSummary.value) alertSummary.value = { pending_count: 0, next_send_at: null, timezone: 'Asia/Shanghai' };
}
}
/**
* 加载当前页合同台账。
* 核心逻辑:合同列表使用服务端分页;搜索和每页条数变化均从第一页开始,并并行刷新待发送摘要。
* @param resetPage - 为 true 时重置为第一页,用于关键词查询。
* @returns 完成后更新当前列表、分页元数据和待发送摘要。
*/
async function load(resetPage = false): Promise<void> {
if (resetPage) page.value = 1;
loading.value = true;
try {
const [result] = await Promise.all([
listContractPaymentContracts({ keyword: keyword.value.trim(), page: page.value, pageSize: pageSize.value }),
refreshSummary(),
]);
contracts.value = result.items || [];
total.value = result.total || 0;
pages.value = result.pages || 1;
page.value = result.page || 1;
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.contractPayment.loadFailed'));
} finally {
loading.value = false;
}
}
/**
* 提交合同付款预警后台任务。
* 核心逻辑:按操作类型调用相应的异步接口,任务入队成功后仅展示任务编号,不等待长耗时同步或发送完成。
* @param action - sync 同步 OA、force-sync 强制覆盖、reparse-existing 刷新存量解析、scan 扫描预警、weekly 周汇总。
* @returns 任务提交完成后显示成功或失败提示。
*/
async function submitAction(action: 'sync' | 'force-sync' | 'reparse-existing' | 'scan' | 'weekly'): Promise<void> {
actionLoading.value = true;
try {
if (action === 'sync' || action === 'force-sync') {
await enqueueContractPaymentSync(action === 'force-sync');
} else if (action === 'reparse-existing') {
await enqueueContractPaymentReparse();
} else if (action === 'scan') {
await enqueueContractPaymentAlertScan();
} else {
await enqueueContractPaymentWeeklyAlert();
}
msg.success(t('admin.contractPayment.jobSubmitted'));
if (action === 'scan' || action === 'weekly') {
await refreshSummary();
}
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.contractPayment.actionFailed'));
} finally {
actionLoading.value = false;
}
}
/**
* 触发任务入口;强制覆盖同步先弹出统一确认框,其余直接提交。
* 核心逻辑:用公共确认组件替代原生 confirm,避免浏览器差异;确认后仍走统一的提交逻辑。
* @param action - 待提交的预警任务类型。
*/
function run(action: 'sync' | 'force-sync' | 'reparse-existing' | 'scan' | 'weekly'): void {
if (action === 'force-sync') {
showForceSyncConfirm.value = true;
return;
}
if (action === 'reparse-existing') {
showReparseExistingConfirm.value = true;
return;
}
void submitAction(action);
}
/** 强制覆盖同步确认后的提交回调。 */
function confirmForceSync(): void {
void submitAction('force-sync');
}
/** 存量合同批量重解析确认后的提交回调。 */
function confirmReparseExisting(): void {
void submitAction('reparse-existing');
}
/**
* 进入所选合同的付款计划和预警审计详情。
* 核心逻辑:仅使用台账已返回的内部主键构造路由,合同编号为空时仍可安全查看详情。
* @param contractId - 合同台账主键。
* @returns 详情路由跳转完成。
*/
async function openContractDetail(contractId: number): Promise<void> {
await router.push(WORKSPACE_PATHS.contractPaymentDetail(contractId));
}
onMounted(() => void load());
</script>
<template>
<section class="section-gap animate-fade-in-up">
<div class="flex flex-wrap items-start justify-between gap-4"><div><h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPayment.title') }}</h2><p class="text-sm text-muted mt-1">{{ t('admin.contractPayment.subtitle') }}</p></div><div class="flex gap-2"><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.sync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('force-sync')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.forceSync') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('reparse-existing')"><RefreshCw class="w-4 h-4" />{{ t('admin.contractPayment.reparseExisting') }}</button><button class="btn-secondary-ds" :disabled="actionLoading" @click="run('scan')"><CalendarClock class="w-4 h-4" />{{ t('admin.contractPayment.scanAlerts') }}</button><button class="btn-primary" :disabled="actionLoading" @click="run('weekly')"><Send class="w-4 h-4" />{{ t('admin.contractPayment.weeklySend') }}</button></div></div>
<div class="surface-panel rounded-2xl p-4 mt-5"><div class="flex flex-wrap gap-3 items-center"><div class="relative w-full md:w-[360px]"><Search class="absolute left-3 top-2.5 w-4 h-4 text-muted" /><input v-model="keyword" class="input-field pl-9" :placeholder="t('admin.contractPayment.searchPlaceholder')" @keyup.enter="load(true)" /></div><button class="btn-secondary-ds" @click="load(true)">{{ t('admin.contractPayment.search') }}</button><span v-if="weeklyPendingText" class="text-xs text-muted">{{ weeklyPendingText }}</span></div></div>
<div class="surface-panel contract-ledger-panel mt-4 overflow-x-auto">
<table class="contract-ledger-table text-sm">
<thead><tr>
<th>{{ t('admin.contractPayment.contractSupplier') }}</th><th>{{ t('admin.contractPayment.amount') }}</th>
<th v-for="nodeType in ['prepayment', 'shipment', 'acceptance', 'warranty']" :key="nodeType"><span>{{ t(`admin.contractPayment.nodeType.${nodeType}`) }}</span><small>{{ t('admin.contractPayment.amountRatioDate') }}</small></th>
<th>{{ t('admin.contractPayment.applicant') }}</th><th>{{ t('admin.contractPayment.statusLabel') }}</th>
</tr></thead>
<tbody>
<tr v-for="item in contracts" :key="item.id" class="contract-ledger-row" @click="openContractDetail(item.id)">
<td class="contract-identify"><strong>{{ t('admin.contractPayment.contractPrefix') }}:{{ item.contract_no || t('admin.contractPayment.contractNoPending') }}</strong><span>{{ t('admin.contractPayment.workflowNo') }}:{{ item.workflow_no || '—' }}</span><span>{{ t('admin.contractPayment.purchaseOrder') }}:{{ item.purchase_order_no || '—' }}</span><span>{{ item.supplier_name || '—' }}</span></td>
<td class="contract-money">{{ item.total_amount || '—' }}<span v-if="displayCurrency(item.currency)"> {{ displayCurrency(item.currency) }}</span></td>
<td v-for="nodeType in ['prepayment', 'shipment', 'acceptance', 'warranty']" :key="nodeType" class="contract-payment-cell"><template v-if="paymentCell(item, nodeType).amountRatio !== '—'"><strong>{{ paymentCell(item, nodeType).amountRatio }}</strong><span :class="{ 'contract-date-pending': paymentCell(item, nodeType).missingDate }">{{ paymentCell(item, nodeType).date || t('admin.contractPayment.datePending') }}</span></template><span v-else>—</span></td>
<td class="contract-applicant">{{ item.applicant_name || '—' }}</td>
<td><span class="contract-status" :class="displayStatus(item).tone">{{ displayStatus(item).label }}</span></td>
</tr>
<tr v-if="!loading && !contracts.length"><td colspan="8" class="contract-empty">{{ t('admin.contractPayment.empty') }}</td></tr>
</tbody>
</table>
</div>
<PaginationBar v-model:page="page" v-model:page-size="pageSize" :total="total" :pages="pages" :visible="total > 0 || !!keyword.trim()" @update:page="() => load()" @update:page-size="() => load()" />
<DeleteConfirmDialog
v-model="showForceSyncConfirm"
:title="t('admin.contractPayment.forceSync')"
:message="t('admin.contractPayment.forceSyncConfirm')"
confirm-tone="primary"
@confirm="confirmForceSync"
/>
<DeleteConfirmDialog
v-model="showReparseExistingConfirm"
:title="t('admin.contractPayment.reparseExisting')"
:message="t('admin.contractPayment.reparseExistingConfirm')"
confirm-tone="primary"
@confirm="confirmReparseExisting"
/>
</section>
</template>
<style scoped>
.contract-ledger-panel { border: 1px solid #d7e1ef; border-radius: 14px; background: #fff; box-shadow: 0 6px 20px rgba(33, 65, 111, .05); }
.contract-ledger-table { width: 100%; min-width: 1260px; border-collapse: collapse; color: #183c72; }
.contract-ledger-table th { height: 59px; padding: 11px 12px; background: #f7faff; border-bottom: 1px solid #d7e1ef; color: #426493; font-size: 13px; font-weight: 700; line-height: 1.35; text-align: left; vertical-align: top; white-space: nowrap; }
.contract-ledger-table th small { display: block; margin-top: 2px; font-size: 12px; font-weight: 600; }
.contract-ledger-table td { padding: 12px; border-bottom: 1px solid #d7e1ef; vertical-align: top; line-height: 1.5; }
.contract-ledger-table tbody tr:last-child td { border-bottom: 0; }
.contract-ledger-table tbody tr:hover { background: #fbfdff; }.contract-ledger-row { cursor: pointer; }
.contract-ledger-table th:nth-child(1) { width: 22%; }.contract-ledger-table th:nth-child(2) { width: 8.5%; }.contract-ledger-table th:nth-child(n+3):nth-child(-n+6) { width: 13.5%; }.contract-ledger-table th:nth-child(7) { width: 7.5%; }.contract-ledger-table th:nth-child(8) { width: 7%; }
.contract-identify strong, .contract-payment-cell strong { display: block; color: #102d59; font-weight: 750; }.contract-identify span, .contract-payment-cell span { display: block; margin-top: 3px; color: #58749f; }.contract-identify strong { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; }.contract-money { color: #102d59; white-space: nowrap; }.contract-payment-cell { color: #102d59; }.contract-date-pending { color: #5c76a0; }.contract-applicant { white-space: nowrap; color: #102d59; }.contract-status { display: inline-flex; align-items: center; min-height: 23px; padding: 2px 9px; border-radius: 999px; font-size: 12px; font-weight: 700; white-space: nowrap; }.contract-status.normal { color: #2563eb; background: #edf5ff; }.contract-status.due { color: #ea580c; background: #fff4e8; }.contract-status.overdue { color: #dc2626; background: #fee2e2; }.contract-status.completed { color: #16a34a; background: #e8f7ee; }.contract-status.needs-completion { color: #c2410c; background: #fff4e8; }.contract-empty { padding: 34px !important; color: var(--text-muted); text-align: center; }
</style>
@@ -0,0 +1,81 @@
<!--
features/contract-payment/views/ContractPaymentReviewPage.vue
用途:集中展示关键解析事实缺失或冲突的合同,供管理员下载原文并人工确认。
依赖:contract-payment.api、PaginationBar、工作台路由与统一消息提示。
逻辑:后端以 review_only 过滤 needs_review 合同;页面不推导付款节点,也不触发预警任务。
-->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { Search } from 'lucide-vue-next';
import { BusinessError } from '@/shared/api/client';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { useMessage } from '@/shared/composables/useMessage';
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
import { listContractPaymentContracts, type ContractPaymentContract } from '../api/contract-payment.api';
const router = useRouter();
const { t } = useI18n();
const msg = useMessage();
const keyword = ref('');
const loading = ref(false);
const contracts = ref<ContractPaymentContract[]>([]);
const page = ref(1);
const pageSize = ref(20);
const total = ref(0);
const pages = ref(1);
/**
* 读取需要人工确认的合同列表。
* 核心逻辑:明确传入 reviewOnly,避免前端仅按显示状态过滤而遗漏后端新产生的待确认合同。
* @param resetPage - 为 true 时重置到第一页,供关键词查询使用。
* @returns 请求完成后更新分页数据;失败时保留已有列表并提示原因。
*/
async function load(resetPage = false): Promise<void> {
if (resetPage) page.value = 1;
loading.value = true;
try {
const result = await listContractPaymentContracts({
keyword: keyword.value.trim(), reviewOnly: true, page: page.value, pageSize: pageSize.value,
});
contracts.value = result.items || [];
total.value = result.total || 0;
pages.value = result.pages || 1;
page.value = result.page || 1;
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.contractPaymentReview.loadFailed'));
} finally {
loading.value = false;
}
}
/**
* 打开待确认合同详情,以便查看解析问题并下载原文人工核验。
* 核心逻辑:仍复用现有合同详情页,避免新页面复制附件权限与下载逻辑。
* @param contractId - 合同付款台账主键。
* @returns 路由跳转完成。
*/
async function openContractDetail(contractId: number): Promise<void> {
await router.push(WORKSPACE_PATHS.contractPaymentDetail(contractId));
}
onMounted(() => void load());
</script>
<template>
<section class="section-gap animate-fade-in-up">
<div><h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPaymentReview.title') }}</h2><p class="mt-1 text-sm text-muted">{{ t('admin.contractPaymentReview.subtitle') }}</p></div>
<div class="surface-panel mt-5 rounded-2xl p-4"><div class="flex flex-wrap items-center gap-3"><div class="relative w-full md:w-[360px]"><Search class="absolute left-3 top-2.5 h-4 w-4 text-muted" /><input v-model="keyword" class="input-field pl-9" :placeholder="t('admin.contractPaymentReview.searchPlaceholder')" @keyup.enter="load(true)" /></div><button class="btn-secondary-ds" @click="load(true)">{{ t('admin.contractPayment.search') }}</button></div></div>
<div class="surface-panel mt-4 overflow-x-auto rounded-2xl">
<table class="review-table text-sm"><thead><tr><th>{{ t('admin.contractPaymentReview.contractWorkflow') }}</th><th>{{ t('admin.contractPayment.purchaseOrder') }}</th><th>{{ t('admin.contractPayment.supplier') }}</th><th>{{ t('admin.contractPayment.amount') }}</th><th>{{ t('admin.contractPaymentReview.reason') }}</th></tr></thead>
<tbody><tr v-for="item in contracts" :key="item.id" class="cursor-pointer hover:bg-surface-soft" @click="openContractDetail(item.id)"><td><strong>{{ item.contract_no || t('admin.contractPayment.contractNoPending') }}</strong><span>{{ item.workflow_no || '—' }}</span></td><td>{{ item.purchase_order_no || '—' }}</td><td>{{ item.supplier_name || '—' }}</td><td>{{ item.total_amount || '—' }}</td><td><ul><li v-for="issue in item.parse_issues || [t('admin.contractPaymentReview.fallbackIssue')]" :key="issue">{{ issue }}</li></ul></td></tr><tr v-if="!loading && !contracts.length"><td colspan="5" class="py-9 text-center text-muted">{{ t('admin.contractPaymentReview.empty') }}</td></tr></tbody>
</table>
</div>
<PaginationBar v-model:page="page" v-model:page-size="pageSize" :total="total" :pages="pages" :visible="total > 0 || !!keyword.trim()" @update:page="() => load()" @update:page-size="() => load()" />
</section>
</template>
<style scoped>
.review-table { width: 100%; min-width: 980px; border-collapse: collapse; color: #183c72; }.review-table th { padding: 13px 14px; border-bottom: 1px solid #d7e1ef; background: #f7faff; color: #426493; text-align: left; }.review-table td { padding: 13px 14px; border-bottom: 1px solid #d7e1ef; vertical-align: top; }.review-table tbody tr:last-child td { border-bottom: 0; }.review-table strong, .review-table span { display: block; }.review-table strong { color: #102d59; }.review-table span, .review-table li { color: #9a3412; }.review-table ul { margin: 0; padding-left: 18px; }.review-table li + li { margin-top: 3px; }
</style>
@@ -0,0 +1,197 @@
<!--
features/contract-payment/views/ContractPaymentWeeklyBatchesPage.vue
用途:独立展示合同付款预警的周汇总批次及其企业微信发送审计摘要,并下载 Excel 明细。
依赖:contract-payment.api、统一消息提示;由工作台“合同付款预警 > 周汇总批次”路由加载。
逻辑:后端扫描产生的批次在此集中查看;Excel 经受控接口下载,手动发送仅提交异步任务。
-->
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { CalendarClock, Download, RefreshCw, Send } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { formatLocalDateTime } from '@/shared/utils/dateTime';
import { useMessage } from '@/shared/composables/useMessage';
import {
downloadContractPaymentAlertBatchExcel,
enqueueContractPaymentWeeklyAlert,
listContractPaymentAlertBatches,
type AlertBatch,
} from '../api/contract-payment.api';
const { t, te } = useI18n();
const msg = useMessage();
const batches = ref<AlertBatch[]>([]);
const loading = ref(false);
const actionLoading = ref(false);
const downloadingId = ref<number | null>(null);
/**
* 加载合同付款周汇总批次列表。
* 核心逻辑:只读取后端已保存的批次和发送审计摘要;无批次时展示空状态,不由页面自行生成。
* @returns 完成后更新批次列表和加载状态。
*/
async function load(): Promise<void> {
loading.value = true;
try {
const result = await listContractPaymentAlertBatches();
batches.value = result.items || [];
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.contractPayment.weeklyBatchesLoadFailed'));
} finally {
loading.value = false;
}
}
/**
* 手动提交本周汇总发送任务。
* 核心逻辑:调用异步入队接口,避免浏览器等待企业微信发送和 Excel 文件生成完成。
* @returns 提交结果通过统一消息提示反馈,成功后刷新批次列表。
*/
async function runWeeklyAlert(): Promise<void> {
actionLoading.value = true;
try {
await enqueueContractPaymentWeeklyAlert();
msg.success(t('admin.contractPayment.weeklyBatchSubmitted'));
await load();
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.contractPayment.actionFailed'));
} finally {
actionLoading.value = false;
}
}
/**
* 判断批次是否已归档 Excel,供下载按钮启用。
* 核心逻辑:文件名或大小任一存在即视为可下载;真正有无字节由下载接口校验。
* @param batch - 周汇总批次。
* @returns 是否展示下载入口。
*/
function hasExcel(batch: AlertBatch): boolean {
return Boolean(batch.excel_file_name || batch.excel_file_size);
}
/**
* 下载指定周汇总批次的 Excel 明细。
* 核心逻辑:经受控接口取 Blob 后由浏览器保存,与合同原文附件下载同一路径。
* @param batch - 当前行的周汇总批次。
*/
async function downloadExcel(batch: AlertBatch): Promise<void> {
if (!hasExcel(batch) || downloadingId.value === batch.id) return;
downloadingId.value = batch.id;
try {
const { blob, filename } = await downloadContractPaymentAlertBatchExcel(batch.id);
const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = objectUrl;
anchor.download = filename || batch.excel_file_name || `contract-payment-alert-${batch.id}.xlsx`;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
URL.revokeObjectURL(objectUrl);
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.contractPayment.excelDownloadFailed'));
} finally {
downloadingId.value = null;
}
}
/**
* 返回批次状态的本地化文本。
* 核心逻辑:已知状态使用 i18n 翻译,服务端未来新增状态时回退展示原始值,避免列表无法展示。
* @param status - 后端保存的批次状态。
* @returns 本地化状态或原始状态。
*/
function displayStatus(status?: string | null): string {
const normalized = String(status || '').trim().toLowerCase();
const key = `admin.contractPayment.batchStatus.${normalized}`;
return normalized && te(key) ? t(key) : (status || '—');
}
/**
* 格式化批次发送时间为用户本地时间的 YYYY-MM-DD HH:mm:ss。
* 核心逻辑:发送时间由后端以 UTC 存储(datetime.utcnow),需换算到浏览器时区展示;
* 空值回退 '—',非法日期回退原值以便排障。
* @param iso - 后端返回的 ISO 发送时间字符串。
* @returns 本地时间文本。
*/
function displaySentAt(iso?: string | null): string {
return iso ? formatLocalDateTime(iso) : '—';
}
onMounted(() => void load());
</script>
<template>
<section class="section-gap animate-fade-in-up">
<div class="flex flex-wrap items-start justify-between gap-4">
<div>
<h2 class="text-2xl font-bold text-primary">{{ t('admin.contractPayment.weeklyBatchesTitle') }}</h2>
<p class="mt-1 text-sm text-muted">{{ t('admin.contractPayment.weeklyBatchesSubtitle') }}</p>
</div>
<div class="flex gap-2">
<button class="btn-secondary-ds" :disabled="loading" @click="() => load()">
<RefreshCw class="h-4 w-4" />{{ t('admin.contractPayment.refresh') }}
</button>
<button class="btn-primary" :disabled="actionLoading" @click="runWeeklyAlert">
<Send class="h-4 w-4" />{{ t('admin.contractPayment.weeklySend') }}
</button>
</div>
</div>
<div class="surface-panel mt-5 overflow-x-auto rounded-2xl">
<table class="weekly-batch-table text-sm">
<thead>
<tr>
<th>{{ t('admin.contractPayment.batchNo') }}</th>
<th>{{ t('admin.contractPayment.weekKey') }}</th>
<th>{{ t('admin.contractPayment.batchStatusLabel') }}</th>
<th>{{ t('admin.contractPayment.batchTotal') }}</th>
<th>{{ t('admin.contractPayment.batchExcel') }}</th>
<th>{{ t('admin.contractPayment.batchSentAt') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="batch in batches" :key="batch.id">
<td class="font-mono font-semibold text-primary">{{ batch.batch_no || '—' }}</td>
<td>{{ batch.week_key || '—' }}</td>
<td><span class="batch-status">{{ displayStatus(batch.status) }}</span></td>
<td>{{ batch.summary?.total || 0 }}</td>
<td>
<button
v-if="hasExcel(batch)"
class="excel-download"
type="button"
:disabled="downloadingId === batch.id"
:title="t('admin.contractPayment.downloadExcel')"
@click="downloadExcel(batch)"
>
<Download class="h-4 w-4" />
<span class="truncate">{{ batch.excel_file_name }}</span>
</button>
<span v-else class="text-muted">—</span>
</td>
<td>{{ displaySentAt(batch.sent_at) }}</td>
</tr>
<tr v-if="!loading && !batches.length">
<td colspan="6" class="weekly-batch-empty">
<CalendarClock class="mx-auto mb-2 h-5 w-5" />
{{ t('admin.contractPayment.weeklyBatchesEmpty') }}
</td>
</tr>
</tbody>
</table>
</div>
</section>
</template>
<style scoped>
.weekly-batch-table { width: 100%; min-width: 860px; border-collapse: collapse; color: #183c72; }
.weekly-batch-table th { padding: 14px 16px; border-bottom: 1px solid #d7e1ef; background: #f7faff; color: #426493; font-size: 13px; font-weight: 700; text-align: left; white-space: nowrap; }
.weekly-batch-table td { padding: 14px 16px; border-bottom: 1px solid #d7e1ef; vertical-align: middle; }
.weekly-batch-table tbody tr:last-child td { border-bottom: 0; }
.weekly-batch-table tbody tr:hover { background: #fbfdff; }
.batch-status { display: inline-flex; min-height: 24px; align-items: center; border-radius: 999px; background: #edf5ff; padding: 2px 9px; color: #2563eb; font-size: 12px; font-weight: 700; }
.excel-download { display: inline-flex; max-width: 360px; align-items: center; gap: 6px; color: #2563eb; font-weight: 650; }
.excel-download:disabled { opacity: .55; }
.weekly-batch-empty { padding: 36px !important; color: var(--text-muted); text-align: center; }
</style>
@@ -1,20 +1,22 @@
<script setup lang="ts">
/**
* features/workspace/components/WorkspaceSidebar.vue
* 工作台左侧导航:子路由链接、关联服务入口、返回聊天与退出登录。
* 依赖:WORKSPACE_PATHS、workspace.context、ExternalSystemLinks。
* 逻辑:底部关联服务复用 ws-nav-btn,与返回聊天/退出登录对齐。
* 工作台左侧导航:子路由链接、货代/合同付款二级菜单、关联服务入口、返回聊天与退出登录。
* 依赖:WORKSPACE_PATHS、workspace.context、ExternalSystemLinks、auth.store、contract-payment 权限常量。
* 逻辑:底部关联服务复用 ws-nav-btn,与返回聊天/退出登录对齐;合同付款菜单仅在具备 contract_payment.access 时展示。
*/
import { computed, inject, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import {
LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package, PanelLeftClose, PanelLeftOpen, ClipboardCheck,
LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package, PanelLeftClose, PanelLeftOpen, ClipboardCheck, CalendarClock,
ChevronDown, ChevronRight, ContactRound, Inbox, FileDown,
} from 'lucide-vue-next';
import { WORKSPACE_PATHS } from '../constants/routes';
import { WORKSPACE_KEY } from '../composables/workspace.context';
import { useShippingTodoBadge } from '../composables/useShippingTodoBadge';
import { ExternalSystemLinks } from '@/features/sso';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import { CONTRACT_PAYMENT_ACCESS_PERMISSION } from '@/features/contract-payment/constants';
const props = defineProps<{
collapsed?: boolean;
@@ -24,7 +26,15 @@ const ws = inject(WORKSPACE_KEY)! as any;
const route = useRoute();
const shippingRouteNames = ['workspace-shipping-customers', 'workspace-shipping-tasks', 'workspace-shipping-my-tasks'] as const;
const shippingExpanded = ref(false);
const contractPaymentRouteNames = ['workspace-contract-payment', 'workspace-contract-payment-review', 'workspace-contract-payment-weekly-batches'] as const;
const contractPaymentExpanded = ref(false);
const isAdmin = computed(() => String(ws.currentUser?.role || '').trim().toLowerCase() === 'admin');
const auth = useAuthStore();
/**
* 当前用户是否可看见并进入合同付款预警工作台。
* 核心逻辑:读取登录态 feature_permissions.contract_payment.access;admin 默认 true,普通用户需显式授予。
*/
const canAccessContractPayment = computed(() => auth.hasFeaturePermission(CONTRACT_PAYMENT_ACCESS_PERMISSION));
const { pendingBadge, startShippingTodoBadgePolling, stopShippingTodoBadgePolling } = useShippingTodoBadge();
const primaryLinkItems = [
@@ -40,17 +50,26 @@ const secondaryLinkItems = [
{ path: WORKSPACE_PATHS.updates, labelKey: 'workspace.nav.updates', icon: Megaphone, match: ['workspace-updates'] },
] as const;
/**
* 判断导航项是否匹配当前工作台子路由。
* 核心逻辑:只按路由名称精确匹配,避免路径前缀导致同一菜单下的子项同时高亮。
* @param match - 当前菜单项可激活的路由名称集合。
* @returns 当前路由命中任一名称时返回 true。
*/
function isActive(match: readonly string[]) {
return match.includes(String(route.name || ''));
}
/** 当前路由进入货代子页面时自动展开一级菜单,保证激活项可见。 */
/** 当前路由进入货代或合同付款子页面时自动展开对应一级菜单,保证激活项可见。 */
watch(
() => route.name,
(routeName) => {
if (shippingRouteNames.includes(String(routeName || '') as typeof shippingRouteNames[number])) {
shippingExpanded.value = true;
}
if (contractPaymentRouteNames.includes(String(routeName || '') as typeof contractPaymentRouteNames[number])) {
contractPaymentExpanded.value = true;
}
},
{ immediate: true },
);
@@ -64,6 +83,15 @@ const toggleShippingMenu = (): void => {
shippingExpanded.value = !shippingExpanded.value;
};
/** 展开或收起合同付款预警目录;侧栏折叠时图标直接进入合同台账。 */
const toggleContractPaymentMenu = (): void => {
if (props.collapsed) {
void ws.router.push(WORKSPACE_PATHS.contractPayment);
return;
}
contractPaymentExpanded.value = !contractPaymentExpanded.value;
};
onMounted(() => {
startShippingTodoBadgePolling();
});
@@ -170,6 +198,48 @@ onBeforeUnmount(() => {
</RouterLink>
</div>
</div>
<div v-if="canAccessContractPayment">
<button
type="button"
class="ws-nav-btn w-full"
:class="[
{ 'ws-nav-btn--active': isActive(contractPaymentRouteNames) },
collapsed ? 'justify-center px-0' : '',
]"
:title="$t('workspace.nav.contractPayment')"
@click="toggleContractPaymentMenu"
>
<CalendarClock class="h-[18px] w-[18px]" />
<span v-if="!collapsed" class="flex-1">{{ $t('workspace.nav.contractPayment') }}</span>
<component v-if="!collapsed" :is="contractPaymentExpanded ? ChevronDown : ChevronRight" class="h-4 w-4" />
</button>
<div v-if="!collapsed && contractPaymentExpanded" class="mt-1 space-y-1 pl-5">
<RouterLink
:to="WORKSPACE_PATHS.contractPayment"
class="ws-nav-btn py-2.5 text-[13px]"
:class="{ 'ws-nav-btn--active': isActive(['workspace-contract-payment']) }"
>
<CalendarClock class="h-4 w-4" />
<span>{{ $t('workspace.nav.contractPaymentLedger') }}</span>
</RouterLink>
<RouterLink
:to="WORKSPACE_PATHS.contractPaymentReview"
class="ws-nav-btn py-2.5 text-[13px]"
:class="{ 'ws-nav-btn--active': isActive(['workspace-contract-payment-review']) }"
>
<ClipboardCheck class="h-4 w-4" />
<span>{{ $t('workspace.nav.contractPaymentReview') }}</span>
</RouterLink>
<RouterLink
:to="WORKSPACE_PATHS.contractPaymentWeeklyBatches"
class="ws-nav-btn py-2.5 text-[13px]"
:class="{ 'ws-nav-btn--active': isActive(['workspace-contract-payment-weekly-batches']) }"
>
<Inbox class="h-4 w-4" />
<span>{{ $t('workspace.nav.contractPaymentWeeklyBatches') }}</span>
</RouterLink>
</div>
</div>
<RouterLink
v-for="item in secondaryLinkItems"
:key="item.path"
@@ -1,11 +1,14 @@
/**
* features/workspace/composables/useWorkspaceHome.ts
* 应用管理/最近更新:首页数据、布局分区、收藏、快捷问题。
* 依赖:requestJson、auth 存储、auth.store。
* 逻辑:拉取 /api/user/home 后把 feature_permissions 写回登录态,供侧栏和路由守卫使用。
*/
import { computed, ref, type Ref } from 'vue';
import { config } from '@/config';
import { getAuthHeaders } from '@/shared/utils/auth';
import { getAuthHeaders, patchStoredAuthUser } from '@/shared/utils/auth';
import { BusinessError, requestJson } from '@/shared/api/client';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import {
SECTION_TITLE_KEY_MAP,
type WorkspaceAgent,
@@ -111,7 +114,13 @@ export function useWorkspaceHome(deps: WorkspaceDeps, options: HomeOptions) {
username: data.user.username,
role: data.user.role,
default_agent_id: data.user.default_agent_id,
feature_permissions: data.user.feature_permissions || {},
};
if (data.user?.feature_permissions && typeof data.user.feature_permissions === 'object') {
// 首页刷新把服务端有效权限写回登录态,避免管理员刚授权后必须重新登录。
patchStoredAuthUser({ feature_permissions: data.user.feature_permissions });
useAuthStore().syncFromStorage();
}
agents.value = data.agents || [];
quickQuestions.value = data.quick_questions || [];
favoriteAgentIds.value = data.favorite_agent_ids || [];
@@ -1,6 +1,8 @@
/**
* features/workspace/composables/useWorkspaceSession.ts
* 登录态:当前用户、知识库权限判断、登出与 401 清理。
* 依赖:logoutAuth、getStoredAuthUser。
* 逻辑:从本地登录态恢复 id/username/role/feature_permissions,供工作台侧栏判断专项权限。
*/
import { computed, type Ref } from 'vue';
import { logoutAuth, getStoredAuthUser } from '@/shared/utils/auth';
@@ -53,6 +55,7 @@ export function useWorkspaceSession(deps: WorkspaceDeps, options: SessionOptions
id: user.id || 0,
username: user.username || '',
role: user.role || 'user',
feature_permissions: user.feature_permissions,
};
} catch {
localStorage.removeItem('hxops_user');
@@ -15,6 +15,10 @@ export const WORKSPACE_PATHS = {
shippingNoticeTasks: '/workspace/shipping-notice/tasks',
shippingNoticeMyTasks: '/workspace/shipping-notice/my-tasks',
accountingVoucherCheck: '/workspace/accounting-voucher-check',
contractPayment: '/workspace/contract-payment',
contractPaymentReview: '/workspace/contract-payment/review',
contractPaymentWeeklyBatches: '/workspace/contract-payment/weekly-batches',
contractPaymentDetail: (contractId: number) => `/workspace/contract-payment/contracts/${contractId}`,
feedback: '/workspace/feedback',
history: '/workspace/history',
} as const;
@@ -30,6 +34,7 @@ export const LEGACY_VIEW_TO_PATH: Record<string, string> = {
receipt_reports: WORKSPACE_PATHS.receiptReports,
shipping_notice: WORKSPACE_PATHS.shippingNotice,
accounting_voucher_check: WORKSPACE_PATHS.accountingVoucherCheck,
contract_payment: WORKSPACE_PATHS.contractPayment,
history: WORKSPACE_PATHS.history,
};
@@ -5,12 +5,14 @@
import type { ThemePreference } from '@/shared/composables/useTheme';
import type { WecomMatchField } from '@/shared/utils/wecom';
import type { WecomLoginDialogContent } from '@/shared/utils/wecom';
import type { FeaturePermissions } from '@/shared/utils/auth';
export interface WorkspaceUser {
id: number;
username: string;
role: string;
default_agent_id?: number | null;
feature_permissions?: FeaturePermissions;
}
export type WorkspaceSidebarItem =
@@ -22,6 +24,7 @@ export type WorkspaceSidebarItem =
| 'schedule_runs'
| 'receipt_reports'
| 'shipping_notice'
| 'contract_payment'
| 'history';
export interface WorkspaceAgent {
+8
View File
@@ -1216,6 +1216,8 @@
"featurePermissions": "Feature Permissions",
"trainingHrManage": "Training HR Admin",
"trainingHrManageHint": "Allows this user to open the employee training agent HR Management view for stats, filtering, and Excel export.",
"contractPaymentAccess": "Contract payment alert access",
"contractPaymentAccessHint": "Allows this user to open the contract payment workbench (ledger, review, weekly batches) and trigger sync or scans.",
"password": "Password",
"passwordHint": "(leave blank to keep)",
"noAgents": "No agents available."
@@ -4772,6 +4774,12 @@
"deleted": "Linked service deleted"
}
},
"contractPayment": {
"title": "Contract Payment Alerts", "subtitle": "Sync OA contract, acceptance, and vendor prepayment requests; notify procurement roles through three escalation rounds.", "sync": "Sync OA data", "forceSync": "Force overwrite OA fields", "forceSyncConfirm": "This will overwrite existing OA data with non-empty fields returned this time and record an audit trail. Continue?", "reparseExisting": "Reparse existing contracts", "reparseExistingConfirm": "This will refresh all existing contract parsing results from archived attachments using the current rules. OA fields will not be synced or overwritten. Continue?", "scanAlerts": "Scan to generate alerts", "jobSubmitted": "Job submitted", "actionFailed": "Action failed", "loadFailed": "Failed to load contracts", "searchPlaceholder": "Search contract or purchase order number", "allStatus": "All", "search": "Search", "ledger": "Contract ledger", "items": "items", "empty": "No contract data", "purchaseOrder": "Purchase order", "supplier": "Supplier", "amount": "Contract amount", "deliveryDate": "Delivery due date", "timeline": "Payment plan timeline", "notAvailable": "—", "stats": {"contracts": "Contracts", "pendingParse": "Pending contracts", "readyPlans": "Plans ready", "alerts": "Alert nodes"}, "status": {"completed": "Completed", "needs_review": "Needs review", "pending": "Pending parse"}, "stateLabel": {"parsed": "Parsed", "needs_review": "Needs review", "pending": "Pending parse", "active": "Active"}, "nodeType": {"prepayment": "Prepayment", "shipment": "Shipment payment", "acceptance": "Acceptance payment", "warranty": "Warranty payment"}, "ruleConfirmed": "Confirmed", "prepaymentRule": "Alerts at 7/14/21 days after contract archival; request status comes from OA vendor prepayment requests.", "shipmentRule": "Alerts 7 days before delivery, on the due date, and 14 days after; request status comes from OA vendor prepayment requests.", "acceptanceRule": "Alerts at 30/40/60 days after acceptance archival; warranty alerts are 7 days before, on, and 14 days after maturity.", "pendingAlerts": "Pending alerts", "processing": "Payment initiated", "dataPending": "Data pending", "paid": "Paid", "amountRatioDate": "Amount / ratio · date", "applicant": "Applicant", "statusLabel": "Status", "contractPrefix": "Contract", "datePending": "Date pending", "statusNormal": "Normal", "statusNeedsCompletion": "Needs completion", "statusOverdue": "Overdue", "statusUpcoming": "Due soon", "statusActive": "In progress", "statusCompleted": "Completed", "totalPrefix": "Total", "contractSupplier": "Contract / supplier", "nextAlert": "Next alert", "triggerBasis": "Trigger basis", "alertDate": "Alert date", "alertFirstRound": "Round 1", "payDate": "Payment date", "processStatus": "Status", "owner": "Procurement owner", "oaData": "OA data", "contractRule": "Contract rule", "ownerDefault": "Procurement owner", "workflowNo": "Workflow number", "contractNoPending": "Contract number pending attachment parsing", "synced": "Synced", "detailSubtitle": "OA data, payment nodes, and WeCom alert records", "backToOverview": "Back to overview", "contractInfo": "OA contract details", "alertHistory": "Alert history", "alertRound": "Alert round {round}", "alertAudit": "Alert delivery record", "alertAuditEmpty": "No alert records", "alertNode": "Payment stage", "alertScheduledAt": "Scheduled date", "alertSentAt": "Sent at", "alertStatus": {"pending": "Pending", "sent": "Sent", "failed": "Failed"}, "roundValue": "Round {round}", "weeklyBatchesTitle": "Weekly Summary Batches", "weeklyBatchesSubtitle": "Review recipient-level payment-alert summaries, Excel attachments, and delivery records.", "refresh": "Refresh", "weeklySend": "Send alerts", "weeklyBatchSubmitted": "Send alert job submitted", "weeklyBatchesLoadFailed": "Failed to load weekly summary batches", "batchNo": "Batch no.", "weekKey": "Week", "batchStatusLabel": "Delivery status", "batchTotal": "Summary count", "batchExcel": "Excel attachment", "batchSentAt": "Sent at", "weeklyBatchesEmpty": "No weekly summary batches", "weeklyPendingSummary": "{count} pending this week · next send {datetime}", "weeklyPendingCountOnly": "{count} pending this week", "downloadExcel": "Download Excel", "excelDownloadFailed": "Failed to download the alert attachment", "batchStatus": {"pending": "Pending", "sent": "Sent", "failed": "Failed", "processing": "Processing", "resolved": "Alerts stopped"}, "backToLedger": "Back", "detailLoadFailed": "Failed to load contract details", "detailLoading": "Loading contract details…", "detailOverview": "Contract Overview", "detailAttachments": "Original Attachments", "detailPaymentPlan": "Payment Plan", "detailAlertHistory": "Alert History", "archiveDate": "Contract archive date", "archiveDateHint": "This date is when the contract application form was archived", "parseStatus": "Parsing status", "parseIssueTitle": "Parse issues", "planStatus": "Plan status", "attachmentsEmpty": "No archived original contract attachments", "downlLine truncated
},
"contractPaymentReview": {"title": "Contracts for Confirmation", "subtitle": "Contracts that do not match the equipment procurement synonym title groups, fail payment-ratio validation, or conflict with OA fields are excluded from payment alerts. Download the original contract to verify it.", "searchPlaceholder": "Contract number, purchase order, or supplier", "loadFailed": "Failed to load contracts for confirmation", "contractWorkflow": "Contract / workflow number", "reason": "Reason for confirmation", "fallbackIssue": "Parsing result requires manual confirmation", "empty": "No contracts need confirmation"},
"contractPaymentReparse": {"action": "Reparse contract original", "success": "Reparsed with attachment “{attachment}”", "failed": "Failed to reparse contract"},
"contractPaymentReview": {"title": "Contracts for Confirmation", "subtitle": "Contracts that do not match the equipment procurement synonym title groups, fail payment-ratio validation, or conflict with OA fields are excluded from payment alerts. Download the original contract to verify it.", "searchPlaceholder": "Contract number, purchase order, or supplier", "loadFailed": "Failed to load contracts for confirmation", "contractWorkflow": "Contract / workflow number", "reason": "Reason for confirmation", "fallbackIssue": "Parsing result requires manual confirmation", "empty": "No contracts need confirmation"},
"procurementContract": {
"title": "Procurement Contract Review",
"subtitle": "Manage templates, risk red-line rules, and review history",
+1
View File
@@ -127,6 +127,7 @@
"AUTH_SSO_IDENTITY_UNSUPPORTED": "The current session is not backed by Casdoor. Log in again and retry.",
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "The peer-service login assertion could not be issued. Please retry.",
"AUTH_FORBIDDEN": "You do not have permission to perform this action.",
"CONTRACT_PAYMENT_FORBIDDEN": "You do not have access to contract payment alerts.",
"SHIPPING_TASK_SELECTION_INVALID": "Select between 1 and 100 shipping tasks.",
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "A reason is required to delete or void tasks.",
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "The task is uploading externally or has been uploaded. It can only be archived.",
+5 -1
View File
@@ -109,7 +109,11 @@
"backToChat": "Back to Chat",
"backShort": "Back",
"logout": "Logout",
"accountingVoucherCheck": "Voucher Check"
"accountingVoucherCheck": "Voucher Check",
"contractPayment": "Contract Payment Alerts",
"contractPaymentLedger": "Contract Ledger",
"contractPaymentReview": "Contracts for Confirmation",
"contractPaymentWeeklyBatches": "Weekly Summary Batches"
},
"kb": {
"accessDenied": "Administrator access is required to open the knowledge base."
+8
View File
@@ -1216,6 +1216,8 @@
"featurePermissions": "สิทธิ์ฟีเจอร์",
"trainingHrManage": "จัดการ HR การฝึกอบรม",
"trainingHrManageHint": "เมื่อเปิดแล้ว ผู้ใช้นี้จะเข้าใช้มุมมอง HR 管理 ใน employee training agent เพื่อดูสถิติ คัดกรองข้อมูล และส่งออก Excel ได้",
"contractPaymentAccess": "สิทธิ์แจ้งเตือนการชำระเงินตามสัญญา",
"contractPaymentAccessHint": "เมื่อเปิดแล้ว ผู้ใช้นี้จะเข้าโต๊ะทำงานแจ้งเตือนการชำระเงินตามสัญญา (บัญชีสัญญา รายการรอยืนยัน และชุดสรุปรายสัปดาห์) และสั่งซิงค์หรือสแกนได้",
"password": "รหัสผ่าน",
"passwordHint": "(เว้นว่างไว้หากไม่ต้องการเปลี่ยน)",
"noAgents": "ไม่มีตัวแทนที่ใช้ได้"
@@ -4641,6 +4643,12 @@
"deleted": "ลบบริการแล้ว"
}
},
"contractPayment": {
"title": "แจ้งเตือนการชำระเงินตามสัญญา", "subtitle": "ซิงก์สัญญา OA การรับมอบ และคำขอเบิกเงินล่วงหน้าของผู้ขาย พร้อมแจ้งเตือน 3 ระดับ", "sync": "ซิงก์ข้อมูล OA", "forceSync": "เขียนทับฟิลด์ OA แบบบังคับ", "forceSyncConfirm": "ระบบจะเขียนทับข้อมูล OA เดิมด้วยฟิลด์ที่ไม่ว่างจาก OA ครั้งนี้และบันทึกการตรวจสอบ ต้องการดำเนินการต่อหรือไม่?", "reparseExisting": "แยกวิเคราะห์สัญญาเดิมทั้งหมดใหม่", "reparseExistingConfirm": "ระบบจะรีเฟรชผลการแยกข้อมูลของสัญญาเดิมทั้งหมดจากไฟล์แนบที่จัดเก็บตามกฎปัจจุบัน โดยจะไม่ซิงก์หรือเขียนทับฟิลด์ OA ต้องการดำเนินการต่อหรือไม่?", "scanAlerts": "สแกนเพื่อสร้างแจ้งเตือน", "jobSubmitted": "ส่งงานแล้ว", "actionFailed": "ดำเนินการไม่สำเร็จ", "loadFailed": "โหลดสัญญาไม่สำเร็จ", "searchPlaceholder": "ค้นหาเลขที่สัญญาหรือใบสั่งซื้อ", "allStatus": "ทั้งหมด", "search": "ค้นหา", "ledger": "ทะเบียนสัญญา", "items": "รายการ", "empty": "ไม่มีข้อมูลสัญญา", "purchaseOrder": "ใบสั่งซื้อ", "supplier": "ผู้ขาย", "amount": "มูลค่าสัญญา", "deliveryDate": "กำหนดส่งมอบ", "timeline": "ไทม์ไลน์แผนการชำระเงิน", "notAvailable": "—", "stats": {"contracts": "สัญญา", "pendingParse": "สัญญาที่รอดำเนินการ", "readyPlans": "แผนพร้อมใช้", "alerts": "จุดแจ้งเตือน"}, "status": {"completed": "เสร็จสิ้น", "needs_review": "ต้องตรวจสอบ", "pending": "รอแยกข้อมูล"}, "stateLabel": {"parsed": "แยกข้อมูลแล้ว", "needs_review": "ต้องตรวจสอบ", "pending": "รอแยกข้อมูล", "active": "ใช้งานอยู่"}, "nodeType": {"prepayment": "เงินล่วงหน้า", "shipment": "เงินก่อนส่ง", "acceptance": "เงินรับมอบ", "warranty": "เงินประกัน"}, "ruleConfirmed": "ยืนยันแล้ว", "prepaymentRule": "แจ้งเตือนวันที่ 7/14/21 หลังจัดเก็บสัญญา; สถานะคำขออ้างอิง OA.", "shipmentRule": "แจ้งเตือนก่อนกำหนดส่ง 7 วัน วันครบกำหนด และหลังครบกำหนด 14 วัน; สถานะคำขออ้างอิง OA.", "acceptanceRule": "แจ้งเตือนวันที่ 30/40/60 หลังจัดเก็บใบรับมอบ; เงินประกันแจ้งก่อนครบกำหนด 7 วัน วันครบกำหนด และหลังครบกำหนด 14 วัน.", "pendingAlerts": "แจ้งเตือนที่รอดำเนินการ", "processing": "เริ่มชำระแล้ว", "dataPending": "รอข้อมูล", "paid": "ชำระแล้ว", "amountRatioDate": "จำนวนเงิน / สัดส่วน · วันที่", "applicant": "ผู้ขอ", "statusLabel": "สถานะ", "contractPrefix": "สัญญา", "datePending": "รอระบุวันที่", "statusNormal": "ปกติ", "statusNeedsCompletion": "ต้องเติมข้อมูล", "statusOverdue": "เกินกำหนดชำระ", "statusUpcoming": "ใกล้ถึงกำหนด", "statusActive": "กำลังดำเนินการ", "statusCompleted": "เสร็จสิ้น", "totalPrefix": "รวม", "contractSupplier": "สัญญา / ผู้ขาย", "nextAlert": "แจ้งเตือนถัดไป", "triggerBasis": "เกณฑ์เริ่ม", "alertDate": "วันที่แจ้งเตือน", "alertFirstRound": "รอบ 1", "payDate": "วันที่ชำระLine truncated
},
"contractPaymentReview": {"title": "สัญญาที่รอยืนยัน", "subtitle": "สัญญาที่ไม่ตรงกับกลุ่มหัวข้อคำพ้องของสัญญาจัดซื้ออุปกรณ์ ตรวจสอบสัดส่วนการชำระเงินไม่ผ่าน หรือขัดแย้งกับฟิลด์ OA จะไม่เข้าสู่การแจ้งเตือนการชำระเงิน โปรดดาวน์โหลดต้นฉบับเพื่อตรวจสอบ", "searchPlaceholder": "เลขที่สัญญา ใบสั่งซื้อ หรือผู้ขาย", "loadFailed": "โหลดสัญญาที่รอยืนยันไม่สำเร็จ", "contractWorkflow": "เลขที่สัญญา / เวิร์กโฟลว์", "reason": "เหตุผลที่ต้องยืนยัน", "fallbackIssue": "ผลการแยกข้อมูลต้องยืนยันโดยผู้ใช้", "empty": "ไม่มีสัญญาที่รอยืนยัน"},
"contractPaymentReparse": {"action": "แยกข้อมูลจากต้นฉบับอีกครั้ง", "success": "แยกข้อมูลใหม่ด้วยไฟล์แนบ “{attachment}” แล้ว", "failed": "แยกข้อมูลสัญญาใหม่ไม่สำเร็จ"},
"contractPaymentReview": {"title": "สัญญาที่รอยืนยัน", "subtitle": "สัญญาที่ไม่ตรงกับกลุ่มหัวข้อคำพ้องของสัญญาจัดซื้ออุปกรณ์ ตรวจสอบสัดส่วนการชำระเงินไม่ผ่าน หรือขัดแย้งกับฟิลด์ OA จะไม่เข้าสู่การแจ้งเตือนการชำระเงิน โปรดดาวน์โหลดต้นฉบับเพื่อตรวจสอบ", "searchPlaceholder": "เลขที่สัญญา ใบสั่งซื้อ หรือผู้ขาย", "loadFailed": "โหลดสัญญาที่รอยืนยันไม่สำเร็จ", "contractWorkflow": "เลขที่สัญญา / เวิร์กโฟลว์", "reason": "เหตุผลที่ต้องยืนยัน", "fallbackIssue": "ผลการแยกข้อมูลต้องยืนยันโดยผู้ใช้", "empty": "ไม่มีสัญญาที่รอยืนยัน"},
"procurementContract": {
"title": "ตรวจสอบสัญญาจัดซื้อ",
"subtitle": "จัดการเทมเพลต กฎเส้นแดงความเสี่ยง และประวัติการตรวจสอบ",
+1
View File
@@ -127,6 +127,7 @@
"AUTH_SSO_IDENTITY_UNSUPPORTED": "เซสชันปัจจุบันไม่ได้ยืนยันผ่าน Casdoor โปรดเข้าสู่ระบบใหม่",
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "ไม่สามารถออกข้อมูลยืนยันการเข้าสู่ระบบสำหรับบริการในผลิตภัณฑ์ได้ โปรดลองใหม่",
"AUTH_FORBIDDEN": "คุณไม่มีสิทธิ์ดำเนินการนี้",
"CONTRACT_PAYMENT_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงการแจ้งเตือนการชำระเงินตามสัญญา",
"SHIPPING_TASK_SELECTION_INVALID": "เลือกงานจัดส่งได้ 1 ถึง 100 งาน",
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "ต้องระบุเหตุผลในการลบหรือยกเลิกงาน",
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "งานกำลังอัปโหลดภายนอกหรืออัปโหลดแล้ว จึงทำได้เพียงเก็บถาวร",
+5 -1
View File
@@ -100,7 +100,11 @@
"backToChat": "กลับไปแชท",
"logout": "ออกจากระบบ",
"backShort": "กลับ",
"accountingVoucherCheck": "ตรวจเอกสารบัญชี"
"accountingVoucherCheck": "ตรวจเอกสารบัญชี",
"contractPayment": "การแจ้งเตือนการชำระเงินตามสัญญา",
"contractPaymentLedger": "ทะเบียนสัญญา",
"contractPaymentReview": "สัญญาที่รอยืนยัน",
"contractPaymentWeeklyBatches": "ชุดสรุปรายสัปดาห์"
},
"receiptReports": {
"title": "ไฟล์รับสินค้า",
+40 -1
View File
@@ -46,7 +46,8 @@
"overview": "概览",
"linkedServices": "关联服务",
"procurementContract": "采购合同审查",
"trainingConfig": "培训配置"
"trainingConfig": "培训配置",
"contractPayment": "合同付款预警"
},
"shippingFieldAssets": {
"title": "字段资产库",
@@ -1349,6 +1350,8 @@
"featurePermissions": "功能权限",
"trainingHrManage": "培训 HR 管理",
"trainingHrManageHint": "勾选后可进入员工培训 Agent 的【HR 管理】视图,查看统计、筛选记录并导出 Excel。",
"contractPaymentAccess": "合同付款预警访问",
"contractPaymentAccessHint": "勾选后可进入工作台合同付款预警(台账、待确认、周汇总),并触发同步与扫描。",
"password": "密码",
"passwordHint": "(留空表示不修改)",
"noAgents": "暂无可用应用"
@@ -4756,6 +4759,42 @@
"deleted": "关联服务已删除"
}
},
"contractPayment": {
"title": "合同付款预警",
"subtitle": "同步 OA 合同、验收和厂商预付款请款作业,按三轮规则通知采购岗位",
"sync": "同步 OA 数据",
"forceSync": "强制覆盖 OA 字段",
"forceSyncConfirm": "将用本次 OA 返回的非空字段覆盖已有 OA 数据,并记录变更审计。是否继续?",
"reparseExisting": "批量重新解析存量合同",
"reparseExistingConfirm": "将使用已归档的合同附件按当前规则刷新全部存量合同的解析结果,不会同步或覆盖 OA 字段。是否继续?",
"scanAlerts": "扫描生成预警",
"jobSubmitted": "任务已提交",
"actionFailed": "操作失败",
"loadFailed": "加载合同失败",
"searchPlaceholder": "搜索合同编号或采购单号",
"allStatus": "全部",
"search": "查询",
"ledger": "合同台账",
"items": "条",
"empty": "暂无合同数据",
"purchaseOrder": "采购单号",
"supplier": "供应商",
"amount": "合同金额",
"deliveryDate": "交货期限",
"timeline": "付款计划时间线",
"notAvailable": "—",
"stats": {"contracts": "合同总数", "pendingParse": "待处理合同", "readyPlans": "计划已生成", "alerts": "待预警节点"},
"status": {"completed": "已完成", "needs_review": "待复核", "pending": "待解析"}, "stateLabel": {"parsed": "已解析", "needs_review": "待复核", "pending": "待解析", "active": "已生效"},
"nodeType": {"prepayment": "预付款", "shipment": "出货款", "acceptance": "验收款", "warranty": "质保款"},
"ruleConfirmed": "已确定",
"prepaymentRule": "合同归档后第 7/14/21 天预警;请款以 OA 厂商预付款请款作业为准。",
"shipmentRule": "交货期限前 7 天、到期日、到期后 14 天预警;请款以 OA 厂商预付款请款作业为准。",
"acceptanceRule": "验收归档后第 30/40/60 天预警;质保款在质保到期前 7 天、到期日、到期后 14 天预警。",
"pendingAlerts": "待处理预警", "processing": "已发起付款", "dataPending": "数据待确认", "paid": "已付款", "amountRatioDate": "金额 / 比例 · 日期", "applicant": "申请人", "statusLabel": "状态", "contractPrefix": "合同", "datePending": "待补充日期", "statusNormal": "正常", "statusNeedsCompletion": "待补充", "statusOverdue": "已逾期", "statusUpcoming": "即将到期", "statusActive": "进行中", "statusCompleted": "已完成",
"totalPrefix": "共", "contractSupplier": "合同号 / 供应商", "nextAlert": "下一预警", "triggerBasis": "触发依据", "alertDate": "预警日期", "alertFirstRound": "首轮", "payDate": "付款日期", "processStatus": "处理状态", "owner": "采购负责人", "oaData": "OA 数据", "contractRule": "合同规则", "ownerDefault": "采购负责人", "workflowNo": "流程编号", "contractNoPending": "合同号待从附件解析", "synced": "已同步", "detailSubtitle": "OA 数据、付款节点与企业微信提醒记录", "backToOverview": "返回总览", "contractInfo": "OA 合同信息", "alertHistory": "预警记录", "alertRound": "第 {round} 次预警", "alertAudit": "预警发送记录", "alertAuditEmpty": "暂无预警记录", "alertNode": "付款节点", "alertScheduledAt": "计划日期", "alertSentAt": "发送时间", "alertStatus": {"pending": "待发送", "sent": "已发送", "failed": "发送失败"}, "roundValue": "第 {round} 次", "weeklyBatchesTitle": "周汇总批次", "weeklyBatchesSubtitle": "查看按收件人生成的付款预警周汇总、Excel 附件及发送记录。", "refresh": "刷新", "weeklySend": "发送预警", "weeklyBatchSubmitted": "发送预警任务已提交", "weeklyBatchesLoadFailed": "加载周汇总批次失败", "batchNo": "批次号", "weekKey": "周次", "batchStatusLabel": "发送状态", "batchTotal": "汇总笔数", "batchExcel": "Excel 附件", "batchSentAt": "发送时间", "weeklyBatchesEmpty": "暂无周汇总批次", "weeklyPendingSummary": "本周待发送 {count} 笔 · 下次发送 {datetime}", "weeklyPendingCountOnly": "本周待发送 {count} 笔", "downloadExcel": "下载 Excel", "excelDownloadFailed": "下载预警附件失败", "batchStatus": {"pending": "待发送", "sent": "已发送", "failed": "发送失败", "processing": "处理中", "resolved": "已停止提醒"}, "backToLedger": "返回", "detailLoadFailed": "加载合同详情失败", "detailLoading": "正在加载合同详情…", "detailOverview": "合同概览", "detailAttachments": "原文附件", "detailPaymentPlan": "付款计划", "detailAlertHistory": "预警记录", "archiveDate": "合同归档日期", "archiveDateHint": "该日期为合同申请单的归档日期", "parseStatus": "解析状态", "parseIssueTitle": "解析提示", "planStatus": "计划状态", "attachmentsEmpty": "暂无已归档的合同原文附件", "downloadAttachment": "下载附件", "attachmentDownloadFailed": "下载合同附件失败", "paymentPlanEmpty": "暂无可展示的付款计划", "anchorDate": "日期依据", "nodeStatus": {"pending": "待处理", "active": "进行中", "paid": "已付", "processing": "处理中", "resolved": "已停止提醒", "upcoming": "即将到期", "notStarted": "待起算", "overdue": "已逾期", "review": "待复核"}, "reparse": "重新解析合同原文", "reparseSuccess": "已使用附件“{attachment}”重新解析", "reparseFailed": "重新解析合同失败", "reviewTitle": "待确认合同", "reviewSubtitle": "未匹配设备采购合同同义标题组、付款比例校验失败或关键字段冲突的合同不会进入付款预警,请下载原文核对。", "reviewSearchPlaceholder": "合同编号、采购编号或供应商", "reviewLoadFailed": "待确认合同加载失败", "reviewContractWorkflow": "合同号 / 流程编号", "reviewReason": "待确认原因", "reviewFallbackIssue": "解析结果待人工确认", "reviewEmpty": "暂无待确认合同"
},
"contractPaymentReview": {"title": "待确认合同", "subtitle": "未匹配设备采购合同同义标题组、付款比例校验失败或关键字段冲突的合同不会进入付款预警,请下载原文核对。", "searchPlaceholder": "合同编号、采购编号或供应商", "loadFailed": "待确认合同加载失败", "contractWorkflow": "合同号 / 流程编号", "reason": "待确认原因", "fallbackIssue": "解析结果待人工确认", "empty": "暂无待确认合同"},
"contractPaymentReparse": {"action": "重新解析合同原文", "success": "已使用附件“{attachment}”重新解析", "failed": "重新解析合同失败"},
"procurementContract": {
"title": "采购合同审查",
"subtitle": "维护标准合同模板、风险红线规则并查看审查历史",
+1
View File
@@ -127,6 +127,7 @@
"AUTH_SSO_IDENTITY_UNSUPPORTED": "当前登录不是 Casdoor 身份,请重新登录后重试。",
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "平级服务登录声明签发失败,请重试。",
"AUTH_FORBIDDEN": "你没有权限执行该操作。",
"CONTRACT_PAYMENT_FORBIDDEN": "你没有合同付款预警的访问权限。",
"SHIPPING_TASK_SELECTION_INVALID": "请选择 1 到 100 个发货任务。",
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "删除或作废任务必须填写原因。",
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "任务正在外部上传或已上传,只能归档,不能作废或删除。",
+5 -1
View File
@@ -109,7 +109,11 @@
"backToChat": "返回聊天",
"backShort": "返",
"logout": "退出登录",
"accountingVoucherCheck": "立账凭证"
"accountingVoucherCheck": "立账凭证",
"contractPayment": "合同付款预警",
"contractPaymentLedger": "合同台账",
"contractPaymentReview": "待确认合同",
"contractPaymentWeeklyBatches": "周汇总批次"
},
"kb": {
"accessDenied": "需要管理员权限才能访问知识库。"
+8
View File
@@ -1221,6 +1221,8 @@
"featurePermissions": "功能權限",
"trainingHrManage": "培訓 HR 管理",
"trainingHrManageHint": "勾選後可進入員工培訓 Agent 的【HR 管理】視圖,查看統計、篩選記錄並匯出 Excel。",
"contractPaymentAccess": "合約付款預警存取",
"contractPaymentAccessHint": "勾選後可進入工作臺合約付款預警(臺帳、待確認、週彙總),並觸發同步與掃描。",
"password": "密碼",
"passwordHint": "(留空表示不修改)",
"noAgents": "暫無可用應用"
@@ -4646,6 +4648,12 @@
"deleted": "關聯服務已刪除"
}
},
"contractPayment": {
"title": "合約付款預警", "subtitle": "同步 OA 合約、驗收和廠商預付款請款作業,按三輪規則通知採購職位", "sync": "同步 OA 資料", "forceSync": "強制覆蓋 OA 欄位", "forceSyncConfirm": "將以本次 OA 回傳的非空欄位覆蓋既有 OA 資料,並記錄變更稽核。是否繼續?", "reparseExisting": "批量重新解析既有合約", "reparseExistingConfirm": "將使用已歸檔的合約附件依目前規則更新所有既有合約的解析結果,不會同步或覆蓋 OA 欄位。是否繼續?", "scanAlerts": "掃描產生預警", "jobSubmitted": "工作已提交", "actionFailed": "操作失敗", "loadFailed": "載入合約失敗", "searchPlaceholder": "搜尋合約編號或採購單號", "allStatus": "全部", "search": "查詢", "ledger": "合約台帳", "items": "筆", "empty": "暫無合約資料", "purchaseOrder": "採購單號", "supplier": "供應商", "amount": "合約金額", "deliveryDate": "交貨期限", "timeline": "付款計畫時間線", "notAvailable": "—", "stats": {"contracts": "合約總數", "pendingParse": "待處理合約", "readyPlans": "計畫已產生", "alerts": "待預警節點"}, "status": {"completed": "已完成", "needs_review": "待覆核", "pending": "待解析"}, "stateLabel": {"parsed": "已解析", "needs_review": "待複核", "pending": "待解析", "active": "已生效"}, "nodeType": {"prepayment": "預付款", "shipment": "出貨款", "acceptance": "驗收款", "warranty": "質保款"}, "ruleConfirmed": "已確定", "prepaymentRule": "合約歸檔後第 7/14/21 天預警;請款以 OA 廠商預付款請款作業為準。", "shipmentRule": "交貨期限前 7 天、到期日、到期後 14 天預警;請款以 OA 廠商預付款請款作業為準。", "acceptanceRule": "驗收歸檔後第 30/40/60 天預警;質保款在質保到期前 7 天、到期日、到期後 14 天預警。", "pendingAlerts": "待處理預警", "processing": "已發起付款", "dataPending": "資料待確認", "paid": "已付款", "amountRatioDate": "金額 / 比例 · 日期", "applicant": "申請人", "statusLabel": "狀態", "contractPrefix": "合約", "datePending": "待補充日期", "statusNormal": "正常", "statusNeedsCompletion": "待補充", "statusOverdue": "已逾期", "statusUpcoming": "即將到期", "statusActive": "進行中", "statusCompleted": "已完成", "totalPrefix": "共", "contractSupplier": "合約號 / 供應商", "nextAlert": "下一預警", "triggerBasis": "觸發依據", "alertDate": "預警日期", "alertFirstRound": "首輪", "payDate": "付款日期", "processStatus": "處理狀態", "owner": "採購負責人", "oaData": "OA 資料", "contractRule": "合約規則", "ownerDefault": "採購負責人", "workflowNo": "流程編號", "contractNoPending": "合約號待從附件解析", "synced": "已同步", "detailSubtitle": "OA 資料、付款節點與企業微信提醒記錄", "backToOverview": "返回總覽", "contractInfo": "OA 合約資訊", "alertHistory": "預警記錄", "alertRound": "第 {round} 次預警", "alertAudit": "預警發送記錄", "alertAuditEmpty": "暫無預警記錄", "alertNode": "付款節點", "alertScheduledAt": "計畫日期", "alertSentAt": "發送時間", "alertStatus": {"pending": "待發送", "sent": "已發送", "failed": "發送失敗"}, "roundValue": "第 {round} 次", "weeklyBatchesTitle": "週彙總批次", "weeklyBatchesSubtitle": "查看依收件人產生的付款預警週彙總、Excel 附件與發送記錄。", "refresh": "重新整理", "weeklySend": "傳送預警", "weeklyBatchSubmitted": "發送預警任務已提交", "weeklyBatchesLoadFailed": "載入週彙總批次失敗", "batchNo": "批次號", "weekKey": "週次", "batchStatusLabel": "發送狀態", "batchTotal": "彙總筆數", "batchExcel": "Excel 附件", "batchSentAt": "發送時間", "weeklyBatchesEmpty": "暫無週彙總批次", "weeklyPendingSummary": "本週待發送 {count} 筆 · 下次發送 {datetime}", "weeklyPendingCountOnly": "本週待發送 {count} 筆", "downloadExcel": "下載 Excel", "excelDownloadFailed": "下載預警附件失敗", "batchStatus": {"pending": "待發送", "sent": "已發送", "failed": "發送失敗", "processing": "處理中", "resolved": "已停止提醒"}, "backToLedger": "返回", "detailLoadFailed": "載入合約詳情失敗", "detailLoading": "正在載入合約詳情…", "detailOverview": "合約概覽", "detailAttachments": "原文附件", "detailPaymentPlan": "付款計畫", "detailAlertHistory": "預警記錄", "archiveDate": "合約歸檔日期", "archiveDateHint": "該日期為合約申請單的歸檔日期", "parseStatus": "解析狀態", "parseIssueTitle": "解析提示", "planStatus": "計畫狀態", "attachmentsEmpty": "暫無已歸檔的合約原文附件", "downloadAttachment": "下載附件", "attachmentDownloadFailed": "下載合約附件失敗", "paymentPlanEmpty": "暫無可展示的付款計畫", "anchorDate": "日期依據", "nodeStatus": {"pending":Line truncated
},
"contractPaymentReview": {"title": "待確認合約", "subtitle": "未符合設備採購合約同義標題組、付款比例驗證失敗或關鍵欄位衝突的合約,不會進入付款預警,請下載原文核對。", "searchPlaceholder": "合約編號、採購單號或供應商", "loadFailed": "待確認合約載入失敗", "contractWorkflow": "合約號 / 流程編號", "reason": "待確認原因", "fallbackIssue": "解析結果待人工確認", "empty": "暫無待確認合約"},
"contractPaymentReparse": {"action": "重新解析合約原文", "success": "已使用附件“{attachment}”重新解析", "failed": "重新解析合約失敗"},
"contractPaymentReview": {"title": "待確認合約", "subtitle": "未符合設備採購合約同義標題組、付款比例驗證失敗或關鍵欄位衝突的合約,不會進入付款預警,請下載原文核對。", "searchPlaceholder": "合約編號、採購單號或供應商", "loadFailed": "待確認合約載入失敗", "contractWorkflow": "合約號 / 流程編號", "reason": "待確認原因", "fallbackIssue": "解析結果待人工確認", "empty": "暫無待確認合約"},
"procurementContract": {
"title": "採購合同審查",
"subtitle": "維護標準合同模板、風險紅線規則並查看審查歷史",
+1
View File
@@ -127,6 +127,7 @@
"AUTH_SSO_IDENTITY_UNSUPPORTED": "目前登入不是 Casdoor 身份,請重新登入後再試。",
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "平級服務登入聲明簽發失敗,請重試。",
"AUTH_FORBIDDEN": "你沒有權限執行此操作。",
"CONTRACT_PAYMENT_FORBIDDEN": "你沒有合約付款預警的存取權限。",
"SHIPPING_TASK_SELECTION_INVALID": "請選擇 1 到 100 個發貨任務。",
"SHIPPING_TASK_DELETE_REASON_REQUIRED": "刪除或作廢任務必須填寫原因。",
"SHIPPING_TASK_EXTERNAL_VOID_BLOCKED": "任務正在外部上傳或已上傳,只能歸檔,不能作廢或刪除。",
+5 -1
View File
@@ -109,7 +109,11 @@
"backToChat": "返回聊天",
"backShort": "返",
"logout": "退出登錄",
"accountingVoucherCheck": "立帳憑證"
"accountingVoucherCheck": "立帳憑證",
"contractPayment": "合約付款預警",
"contractPaymentLedger": "合約台帳",
"contractPaymentReview": "待確認合約",
"contractPaymentWeeklyBatches": "週彙總批次"
},
"kb": {
"accessDenied": "需要管理員權限才能存取知識庫。"
+29 -5
View File
@@ -2,18 +2,21 @@
* shared/utils/auth.ts
* 用途:统一封装登录态、记住我偏好、登录页账号密码自动回填、跨标签登出同步等认证相关本地存储能力。
* 依赖:浏览器 localStorage/sessionStorage、Casdoor refresh 接口。
* 逻辑:把“认证凭据”和“登录页自动回填资料”分开管理,既支持 30 天免登录,也支持按业务确认方案回填账号密码。
* 逻辑:把“认证凭据”和“登录页自动回填资料”分开管理,既支持 30 天免登录,也支持按业务确认方案回填账号密码;首页刷新可通过 patchStoredAuthUser 就地更新功能权限。
*/
export type FeaturePermissions = {
training_hr_manage?: boolean;
'contract_payment.access'?: boolean;
[key: string]: boolean | undefined;
};
export interface AuthUser {
id?: number;
username?: string;
real_name?: string;
employee_id?: string;
role?: string;
feature_permissions?: {
training_hr_manage?: boolean;
[key: string]: boolean | undefined;
};
feature_permissions?: FeaturePermissions;
token?: string;
access_token?: string;
refresh_token?: string;
@@ -107,6 +110,27 @@ export const getStoredAuthUser = (): AuthUser | null => {
return null;
};
/**
* 就地更新当前登录用户的若干字段,不改变 remember / expiry 所在存储。
* 核心逻辑:按 sessionStorage → localStorage 找到现有 payload,合并 partial 后写回同一位置。
* @param partial - 需要覆盖的用户字段(如首页刷新得到的 feature_permissions)
* @returns 合并后的用户;当前没有登录态时返回 null
*/
export const patchStoredAuthUser = (partial: Partial<AuthUser>): AuthUser | null => {
const candidates: Array<[Storage, string]> = [
[sessionStorage, AUTH_USER_KEY],
[localStorage, AUTH_USER_KEY],
];
for (const [storage, key] of candidates) {
const payload = readStoredAuthPayload(storage, key);
if (!payload?.user) continue;
const nextUser = { ...payload.user, ...partial };
storage.setItem(key, JSON.stringify({ ...payload, user: nextUser }));
return nextUser;
}
return null;
};
export const getAuthToken = (): string => {
const user = getStoredAuthUser();
const token = user?.access_token || user?.token;
+37
View File
@@ -31,3 +31,40 @@ export function formatLocalDateTime(iso?: string | null): string {
const pad = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
/**
* Format an API timestamp as `YYYY-MM-DD HH:mm:ss`, preserving the source wall-clock time.
* Use for OA-sourced naive timestamps (e.g. contract archive date) where the stored value is the
* local time as shown on the source page and must NOT be shifted by the browser timezone.
* Backend may serialize microseconds (e.g. `...26.660127`); they are trimmed for reliable parsing.
* Empty values return `-`; invalid dates fall back to the original string for troubleshooting.
*
* @param iso - API timestamp string.
* @returns Wall-clock display text.
*/
export function formatNaiveDateTime(iso?: string | null): string {
if (!iso) return '-';
const normalized = iso.replace(/(\.\d{3})\d+/, '$1');
const d = new Date(normalized);
if (Number.isNaN(d.getTime())) return iso;
const pad = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
/**
* Format an API timestamp as `YYYY-MM-DD`, preserving the source wall-clock day.
* Use for OA-sourced naive timestamps (e.g. contract archive date) where only the date is
* meaningful and the trailing time part must not be shown. Parsing mirrors formatNaiveDateTime.
* Empty values return `-`; invalid dates fall back to the original string for troubleshooting.
*
* @param iso - API timestamp string.
* @returns Wall-clock date text (`YYYY-MM-DD`).
*/
export function formatNaiveDate(iso?: string | null): string {
if (!iso) return '-';
const normalized = iso.replace(/(\.\d{3})\d+/, '$1');
const d = new Date(normalized);
if (Number.isNaN(d.getTime())) return iso;
const pad = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}