refactor(frontend): 重构前端第二版

This commit is contained in:
sophie committed 2026-06-11 13:47:06 +08:00
1 parent 2631f78b00
commit 4b562cfa82
205 files changed
+15399 -12015

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
/** 请假(leave)子模块 barrel:纯函数 + handler 工厂 */
export * from './leaveDateTime';
export * from './leaveDisplay';
export * from './leaveIntent';
export * from './leavePayload';
export * from './leaveLocalMessage';
export * from './useChatLeaveOaLogin';
export * from './useChatLeaveAgentPicker';
export * from './useChatLeaveForm';
export * from './useChatLeaveFlow';
@@ -0,0 +1,50 @@
/**
* 请假:日期时间解析、按天/按小时时长计算。
*/
import { LEAVE_TYPE_BY_DAY } from '../constants/leave';
export function formatDateTime(date: Date): string {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${year}-${month}-${day}T${hours}:${minutes}`;
}
export function parseDateTime(value: string): Date | null {
const normalized = (value || '').trim().replace('T', ' ');
const match = normalized.match(/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})$/);
if (!match) return null;
const [, year, month, day, hour, minute] = match;
const date = new Date(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute));
return Number.isNaN(date.getTime()) ? null : date;
}
export function isLeaveTypeByDay(leaveType: string): boolean {
return LEAVE_TYPE_BY_DAY.has(leaveType);
}
export function calculateDurationHours(startTime: string, endTime: string): number {
const start = parseDateTime(startTime);
const end = parseDateTime(endTime);
if (!start || !end || end.getTime() <= start.getTime()) return 0;
return Number((((end.getTime() - start.getTime()) / 1000 / 60 / 60)).toFixed(2));
}
export function syncLeaveDuration(form: { leaveType: string; startTime: string; endTime: string; durationHours: number }) {
if (isLeaveTypeByDay(form.leaveType)) {
const start = parseDateTime(form.startTime);
const end = parseDateTime(form.endTime);
if (!start || !end || end.getTime() <= start.getTime()) {
form.durationHours = 0;
return;
}
const startDate = new Date(start.getFullYear(), start.getMonth(), start.getDate());
const endDate = new Date(end.getFullYear(), end.getMonth(), end.getDate());
const days = Math.max(1, Math.round((endDate.getTime() - startDate.getTime()) / (24 * 3600 * 1000)) + 1);
form.durationHours = days * 8;
} else {
form.durationHours = calculateDurationHours(form.startTime, form.endTime);
}
}
@@ -0,0 +1,36 @@
/**
* 请假:假种标签、时长/是否展示、余额数字格式化。
*/
import { LEAVE_TYPES } from '../constants/leave';
import { isLeaveTypeByDay } from './leaveDateTime';
export function getLeaveTypeLabel(val: string): string {
const item = LEAVE_TYPES.find((x) => x.value === val);
return item ? item.label : val;
}
export function formatDurationLabel(
hours: number,
leaveType: string | undefined,
t: (key: string) => string,
): string {
if (!hours) return `0 ${isLeaveTypeByDay(leaveType || '') ? t('chat.dayUnit') : t('chat.hourUnit')}`;
if (isLeaveTypeByDay(leaveType || '')) {
const days = Math.round(hours / 8);
return `${days} ${t('chat.dayUnit')}`;
}
return `${hours} ${t('chat.hourUnit')}`;
}
export function formatYesNoLabel(value: 0 | 1 | null): string {
if (value === 0) return '是';
if (value === 1) return '否';
return '未选择';
}
export function formatLeaveBalanceNumber(value: unknown, t: (key: string) => string): string {
if (value === null || value === undefined) return t('chat.noData');
const num = Number(value);
if (Number.isNaN(num)) return String(value);
return Number.isInteger(num) ? String(num) : num.toFixed(2);
}
@@ -0,0 +1,149 @@
/**
* 请假:自然语言意图解析与强/弱意图区分。
*/
import { LEAVE_TYPE_MAP } from '../constants/leave';
import type { ExtractedLeaveInfo } from '../types/leave.types';
import { calculateDurationHours, isLeaveTypeByDay, parseDateTime } from './leaveDateTime';
export function extractLeaveTypeFromIntent(content: string): string {
if (!content) return '';
for (const [key, val] of Object.entries(LEAVE_TYPE_MAP)) {
if (content.includes(key)) return val;
}
return '';
}
export function extractLeaveInfoFromIntent(content: string): ExtractedLeaveInfo | null {
const normalized = content.replace(/\s+/g, ' ').trim();
let leaveType = extractLeaveTypeFromIntent(normalized);
let startTime = '';
let endTime = '';
let durationHours = 0;
const today = new Date();
const thisYear = today.getFullYear();
const parseDateStr = (m: RegExpMatchArray | null, groupOffset: number): Date | null => {
if (!m) return null;
const rawMo = m[groupOffset];
const rawDa = m[groupOffset + 1];
if (!rawMo || !rawDa) return null;
const mo = parseInt(rawMo, 10);
const da = parseInt(rawDa, 10);
if (Number.isNaN(mo) || Number.isNaN(da) || mo < 1 || mo > 12 || da < 1 || da > 31) return null;
return new Date(thisYear, mo - 1, da, 9, 0);
};
const fmtDt = (d: Date, hour: number, minute: number) => {
const y = d.getFullYear();
const mo = String(d.getMonth() + 1).padStart(2, '0');
const da = String(d.getDate()).padStart(2, '0');
const h = String(hour).padStart(2, '0');
const mi = String(minute).padStart(2, '0');
return `${y}-${mo}-${da}T${h}:${mi}`;
};
let startDay: Date | null = null;
let endDay: Date | null = null;
const startHM = { h: 9, m: 0 };
let endHM = { h: 18, m: 0 };
const rangeM = normalized.match(/从?(\d{1,2})[月./-](\d{1,2})[日号]?[到至—\-–](\d{1,2})[月./-]?(\d{1,2})[日号]?/);
if (rangeM) {
const s = parseDateStr(rangeM, 1);
if (rangeM[3] && rangeM[3].length <= 2 && rangeM[4] && rangeM[4].length <= 2) {
const eMo = parseInt(rangeM[3]!, 10);
const eDa = parseInt(rangeM[4]!, 10);
if (!Number.isNaN(eMo) && eMo >= 1 && eMo <= 12 && !Number.isNaN(eDa) && eDa >= 1 && eDa <= 31) {
endDay = new Date(thisYear, eMo - 1, eDa, 18, 0);
} else if (!Number.isNaN(eDa) && eDa >= 1 && eDa <= 31 && s) {
endDay = new Date(thisYear, s.getMonth(), eDa, 18, 0);
}
}
if (s) startDay = s;
}
if (!startDay) {
const singleM = normalized.match(/(\d{1,2})[月./-](\d{1,2})[日号]?/);
if (singleM) {
const s = parseDateStr(singleM, 1);
if (s) {
startDay = s;
const dayUnitM = normalized.match(/(\d+\.?\d*)\s*[天日]/);
if (dayUnitM?.[1]) {
const days = parseFloat(dayUnitM[1]);
if (days > 1) endDay = new Date(s.getFullYear(), s.getMonth(), s.getDate() + Math.ceil(days) - 1, 18, 0);
else endDay = new Date(s.getFullYear(), s.getMonth(), s.getDate(), 18, 0);
} else {
endDay = new Date(s.getFullYear(), s.getMonth(), s.getDate(), 18, 0);
}
}
}
}
const hourM = normalized.match(/(\d+\.?\d*)\s*小时/);
if (hourM?.[1]) {
durationHours = parseFloat(hourM[1]);
if (startDay && !endDay) {
endDay = new Date(startDay.getTime() + durationHours * 3600000);
}
}
const dayM = normalized.match(/(\d+\.?\d*)\s*[天日]/);
if (dayM?.[1] && !hourM) {
const days = parseFloat(dayM[1]);
durationHours = days * 8;
if (startDay && !endDay) {
endDay = new Date(startDay.getFullYear(), startDay.getMonth(), startDay.getDate() + Math.ceil(days) - 1, 18, 0);
}
}
if (startDay) {
if (durationHours > 0 && durationHours <= 8 && !endDay) {
endDay = new Date(startDay.getTime() + durationHours * 3600000);
}
startTime = fmtDt(startDay, startHM.h, startHM.m);
}
if (endDay) {
if (hourM && durationHours <= 8) {
endHM = { h: 9 + Math.floor(durationHours), m: (durationHours % 1) * 60 };
} else if (!hourM && durationHours > 0 && durationHours <= 8) {
endHM = { h: 9 + Math.floor(durationHours), m: 0 };
}
endTime = fmtDt(endDay, endHM.h, endHM.m);
}
if (startTime && endTime) {
if (isLeaveTypeByDay(leaveType)) {
const s = parseDateTime(startTime);
const e = parseDateTime(endTime);
if (s && e && e.getTime() > s.getTime()) {
const sd = new Date(s.getFullYear(), s.getMonth(), s.getDate());
const ed = new Date(e.getFullYear(), e.getMonth(), e.getDate());
const days = Math.max(1, Math.round((ed.getTime() - sd.getTime()) / (24 * 3600 * 1000)) + 1);
durationHours = days * 8;
}
} else {
durationHours = durationHours || calculateDurationHours(startTime, endTime);
}
}
if (!leaveType && !startTime) return null;
return { leaveType, startTime, endTime, durationHours };
}
export function getLeaveIntentNormalized(content: string): string {
return (content || '').replace(/\s+/g, '');
}
/** 区分「真请假」与「咨询流程/材料」类弱意图 */
export function isStrongLeaveIntent(content: string): boolean {
const normalized = getLeaveIntentNormalized(content);
const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定|请假管理办法|请假制度)/;
const materialConsultationIntent = /(提交哪些|提交什么|需要哪些|需要什么|要提交哪些|要提交什么|哪些资料|哪些材料|什么资料|什么材料|申请材料|所需资料|所需材料)/;
if (weakConsultationIntent.test(normalized)) return false;
if (materialConsultationIntent.test(normalized)) return false;
if (/^(请假|休假|年假|事假|病假|调休|休年假|请事假|请病假|请年假)$/.test(normalized)) return true;
return /(我要请|申请请|发起请|请假申请|我要休|申请休|想请|帮我请|代我请|提交请|帮我申请|我要申请|想申请|申请.*假|请.*假|休.*假)/.test(normalized);
}
@@ -0,0 +1,43 @@
/**
* 请假:本地消息 ID 生成与落库。
*/
import { saveLocalChatMessage } from '../api/chat.api';
import type { ChatMessage } from '../types/chat.types';
import type { ComputedRef, Ref } from 'vue';
export interface LeaveLocalMessageContext {
conversationId: Ref<string | null>;
currentAgentId: ComputedRef<number>;
}
export function createLeaveLocalMessageApi(ctx: LeaveLocalMessageContext) {
let leaveFlowCounter = 0;
const newLocalMessageId = (prefix: string) => {
leaveFlowCounter += 1;
return `${prefix}-${Date.now()}-${leaveFlowCounter}`;
};
const saveLocalMessageToBackend = async (chatMsg: ChatMessage, userQuery = '') => {
try {
const data = await saveLocalChatMessage({
conversation_id: ctx.conversationId.value,
type: chatMsg.type,
content: chatMsg.content,
payload: chatMsg.payload,
query: userQuery,
agent_id: ctx.currentAgentId.value,
});
if (!ctx.conversationId.value && data.conversation_id) {
ctx.conversationId.value = data.conversation_id;
}
if (data.chat_log_id) {
chatMsg.chat_log_id = data.chat_log_id;
}
} catch (e) {
console.error('Failed to save local message', e);
}
};
return { newLocalMessageId, saveLocalMessageToBackend };
}
@@ -0,0 +1,34 @@
/**
* 请假:leave-form / leave-confirmation / leave-result payload 读取。
*/
import type { ChatMessage } from '../types/chat.types';
import type {
LeaveConfirmationPayload,
LeaveFormPayload,
LeaveRequestFormData,
LeaveResultPayload,
} from '../types/leave.types';
import type { Ref } from 'vue';
export function getLeaveFormPayload(chatMsg: ChatMessage): LeaveFormPayload | null {
return chatMsg?.type === 'leave-form' && chatMsg?.payload ? chatMsg.payload as LeaveFormPayload : null;
}
export function getLeaveConfirmationPayload(chatMsg: ChatMessage): LeaveConfirmationPayload | null {
return chatMsg?.type === 'leave-confirmation' && chatMsg?.payload ? chatMsg.payload as LeaveConfirmationPayload : null;
}
export function getLeaveResultPayload(chatMsg: ChatMessage): LeaveResultPayload | null {
return chatMsg?.type === 'leave-result' && chatMsg?.payload ? chatMsg.payload as LeaveResultPayload : null;
}
export function findMessageIndexByLocalId(messages: Ref<ChatMessage[]>, localId: string): number {
return messages.value.findIndex((m) => m?.local_id === localId || (m?.payload as LeaveFormPayload | undefined)?.formId === localId);
}
export function getLeaveAgentDisplayValue(form: LeaveRequestFormData): string {
if (!form.agentName) return '';
const parts = [form.agentName];
if (form.agentEmployeeId) parts.push(form.agentEmployeeId);
return parts.join(' / ');
}
@@ -0,0 +1,159 @@
/**
* 请假:OA 员工(代理人/申请人)搜索选择弹窗。
*/
import { ref } from 'vue';
import { listOaEmployees } from '../api/chat.api';
import {
findMessageIndexByLocalId,
getLeaveFormPayload,
} from './leavePayload';
import type { ChatMessage } from '../types/chat.types';
import type { LeaveAgentOption } from '../types/leave.types';
import type { ComputedRef, Ref } from 'vue';
export interface LeaveAgentPickerContext {
currentAgentId: ComputedRef<number>;
messages: Ref<ChatMessage[]>;
saveLocalMessageToBackend: (chatMsg: ChatMessage) => Promise<void>;
}
export function createLeaveAgentPickerApi(ctx: LeaveAgentPickerContext) {
const leaveAgentOptions = ref<LeaveAgentOption[]>([]);
const leaveAgentLoading = ref(false);
const leaveAgentKeyword = ref('');
const leaveAgentPage = ref(1);
const leaveAgentHasMore = ref(true);
const showLeaveAgentDialog = ref(false);
const leaveUserSelectRole = ref<'agent' | 'applicant'>('agent');
const activeLeaveAgentFormId = ref<string | null>(null);
const fetchLeaveAgents = async (isLoadMore = false) => {
if (leaveAgentLoading.value) return;
if (!isLoadMore) {
leaveAgentPage.value = 1;
leaveAgentOptions.value = [];
}
leaveAgentLoading.value = true;
try {
const data = await listOaEmployees(ctx.currentAgentId.value, {
keyword: leaveAgentKeyword.value,
page: leaveAgentPage.value,
page_size: 20,
});
if (isLoadMore) {
leaveAgentOptions.value.push(...data.items);
} else {
leaveAgentOptions.value = data.items;
}
leaveAgentHasMore.value = leaveAgentOptions.value.length < data.total;
} catch (e) {
console.error('Failed to load OA employees', e);
} finally {
leaveAgentLoading.value = false;
}
};
const handleAgentSearch = () => {
void fetchLeaveAgents(false);
};
const loadMoreAgents = () => {
if (!leaveAgentHasMore.value) return;
leaveAgentPage.value += 1;
void fetchLeaveAgents(true);
};
const loadAllAgents = async () => {
if (!leaveAgentHasMore.value || leaveAgentLoading.value) return;
leaveAgentLoading.value = true;
try {
const data = await listOaEmployees(ctx.currentAgentId.value, {
keyword: leaveAgentKeyword.value,
page: 1,
page_size: 100000,
});
leaveAgentOptions.value = data.items;
leaveAgentHasMore.value = false;
} catch (e) {
console.error('Failed to load all OA employees', e);
} finally {
leaveAgentLoading.value = false;
}
};
const openLeaveAgentDialog = (chatMsg: ChatMessage, role: 'agent' | 'applicant' = 'agent') => {
const payload = getLeaveFormPayload(chatMsg);
if (!payload || payload.submitting || payload.confirmationGenerated) return;
activeLeaveAgentFormId.value = payload.formId;
leaveUserSelectRole.value = role;
showLeaveAgentDialog.value = true;
leaveAgentKeyword.value = '';
void fetchLeaveAgents(false);
};
const closeLeaveAgentDialog = () => {
showLeaveAgentDialog.value = false;
activeLeaveAgentFormId.value = null;
};
const selectLeaveAgent = (option: LeaveAgentOption) => {
if (!activeLeaveAgentFormId.value) return;
const sourceIndex = findMessageIndexByLocalId(ctx.messages, activeLeaveAgentFormId.value);
if (sourceIndex < 0) {
closeLeaveAgentDialog();
return;
}
const sourceMsg = ctx.messages.value[sourceIndex];
if (!sourceMsg) {
closeLeaveAgentDialog();
return;
}
const payload = getLeaveFormPayload(sourceMsg);
if (!payload) {
closeLeaveAgentDialog();
return;
}
if (leaveUserSelectRole.value === 'agent') {
payload.form.agentUid = option.uid;
payload.form.agentEmployeeId = option.employeeId;
payload.form.agentName = option.name;
payload.form.agentJobTitle = option.jobtitle;
payload.form.agentJobTitleName = option.jobtitleName;
payload.form.agentDepartmentId = option.departmentid;
payload.form.agentSubCompanyId1 = option.subcompanyid1;
payload.form.agentDepartmentName = option.departmentName;
payload.form.agentSubCompanyName = option.subcompanyName;
} else {
payload.form.applicantUid = option.uid;
payload.form.employeeId = option.employeeId;
payload.form.applicantName = option.name;
payload.form.applicantJobTitle = option.jobtitle;
payload.form.applicantJobTitleName = option.jobtitleName;
payload.form.applicantDepartmentId = option.departmentid;
payload.form.applicantSubCompanyId1 = option.subcompanyid1;
payload.form.applicantDepartmentName = option.departmentName;
payload.form.applicantSubCompanyName = option.subcompanyName;
}
closeLeaveAgentDialog();
void ctx.saveLocalMessageToBackend(sourceMsg);
};
return {
leaveAgentOptions,
leaveAgentLoading,
leaveAgentKeyword,
leaveAgentPage,
leaveAgentHasMore,
showLeaveAgentDialog,
leaveUserSelectRole,
handleAgentSearch,
loadMoreAgents,
loadAllAgents,
openLeaveAgentDialog,
closeLeaveAgentDialog,
selectLeaveAgent,
};
}
@@ -0,0 +1,158 @@
/**
* 请假:强意图拦截、插入 leave-form 消息、Markdown 链接触发。
*/
import { listOaEmployees } from '../api/chat.api';
import { NEED_BALANCE_CHECK_TYPES } from '../constants/leave';
import { isStrongLeaveIntent, extractLeaveInfoFromIntent, extractLeaveTypeFromIntent } from './leaveIntent';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ExtractedLeaveInfo, LeaveFormPayload, LeaveRequestFormData } from '../types/leave.types';
import type { ComputedRef, Ref } from 'vue';
export interface LeaveFlowContext {
canUseLeaveFeature: ComputedRef<boolean>;
isThinking: Ref<boolean>;
messages: Ref<ChatMessage[]>;
conversationId: Ref<string | null>;
history: Ref<ChatSessionItem[]>;
currentAgentId: ComputedRef<number>;
loadHistory: () => Promise<void>;
newLocalMessageId: (prefix: string) => string;
saveLocalMessageToBackend: (chatMsg: ChatMessage, userQuery?: string) => Promise<void>;
createLeaveFormData: (content?: string, extractedInfo?: ExtractedLeaveInfo | null) => LeaveRequestFormData;
checkLeaveBalance: (leaveTypeCode: string) => Promise<{
has_balance?: boolean;
leave_type_label?: string;
year?: string | number;
total_hours?: unknown;
used_hours?: unknown;
remaining_hours?: unknown;
} | null>;
formatLeaveBalanceNumber: (value: unknown) => string;
msg: { warning: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
}
export function createLeaveFlowApi(ctx: LeaveFlowContext) {
const ensureHistoryListed = async () => {
if (ctx.history.value.length === 0 || !ctx.history.value.some((h) => h.conversation_id === ctx.conversationId.value)) {
await ctx.loadHistory();
}
};
const startLocalLeaveFlow = async (content: string) => {
const extractedInfo = extractLeaveInfoFromIntent(content);
const initialLeaveType = extractedInfo?.leaveType || extractLeaveTypeFromIntent(content);
if (initialLeaveType && NEED_BALANCE_CHECK_TYPES.has(initialLeaveType)) {
ctx.messages.value.push({ role: 'user', content, type: 'text' });
const thinkingMsg: ChatMessage = {
role: 'assistant',
type: 'text',
content: ctx.t('chat.queryLeaveBalance'),
};
ctx.messages.value.push(thinkingMsg);
const balance = await ctx.checkLeaveBalance(initialLeaveType);
const thinkingIndex = ctx.messages.value.indexOf(thinkingMsg);
if (thinkingIndex >= 0) {
ctx.messages.value.splice(thinkingIndex, 1);
}
if (balance && !balance.has_balance) {
const unit = initialLeaveType === '010' ? ctx.t('chat.dayUnit') : ctx.t('chat.hourUnit');
const detailLines = [
ctx.t('chat.leaveBalanceInsufficient', { label: balance.leave_type_label }),
'',
`| ${ctx.t('chat.leaveBalanceTableLeaveType')} | ${ctx.t('chat.leaveBalanceTableYear')} | ${ctx.t('chat.leaveBalanceTableAvailable')} | ${ctx.t('chat.leaveBalanceTableUsed')} | ${ctx.t('chat.leaveBalanceTableRemaining')} |`,
'| :---: | :---: | :---: | :---: | :---: |',
`| ${balance.leave_type_label} | ${balance.year} | ${ctx.formatLeaveBalanceNumber(balance.total_hours)}${unit} | ${ctx.formatLeaveBalanceNumber(balance.used_hours)}${unit} | ${ctx.formatLeaveBalanceNumber(balance.remaining_hours)}${unit} |`,
'',
ctx.t('chat.leaveBalanceContactHr'),
];
const noBalanceMsg: ChatMessage = {
role: 'assistant',
type: 'text',
content: detailLines.join('\n'),
};
ctx.messages.value.push(noBalanceMsg);
await ctx.saveLocalMessageToBackend(noBalanceMsg, content);
await ensureHistoryListed();
return;
}
}
const formId = ctx.newLocalMessageId('leave-form');
const payload: LeaveFormPayload = {
formId,
form: ctx.createLeaveFormData(content, extractedInfo),
submitting: false,
confirmationGenerated: false,
};
if (!initialLeaveType || !NEED_BALANCE_CHECK_TYPES.has(initialLeaveType)) {
ctx.messages.value.push({ role: 'user', content, type: 'text' });
}
const formMsg: ChatMessage = {
role: 'assistant',
type: 'leave-form',
content: ctx.t('chat.leaveFormIntro'),
payload,
local_id: formId,
local_only: true,
};
ctx.messages.value.push(formMsg);
try {
const keyword = payload.form.applicantName || payload.form.employeeId;
if (keyword) {
const data = await listOaEmployees(ctx.currentAgentId.value, { keyword, page: 1, page_size: 1 });
const match = (data.items || []).find((item) => item.employeeId === payload.form.employeeId);
if (match) {
payload.form.fillerJobTitle = match.jobtitle || '';
payload.form.fillerJobTitleName = match.jobtitleName || '';
payload.form.fillerDepartmentId = match.departmentid || '';
payload.form.fillerSubCompanyId1 = match.subcompanyid1 || '';
payload.form.fillerDepartmentName = match.departmentName || '';
payload.form.fillerSubCompanyName = match.subcompanyName || '';
payload.form.applicantUid = match.uid || '';
payload.form.applicantJobTitle = match.jobtitle || '';
payload.form.applicantJobTitleName = match.jobtitleName || '';
payload.form.applicantDepartmentId = match.departmentid || '';
payload.form.applicantSubCompanyId1 = match.subcompanyid1 || '';
payload.form.applicantDepartmentName = match.departmentName || '';
payload.form.applicantSubCompanyName = match.subcompanyName || '';
}
}
} catch (e) {
console.error('Failed to prefill OA user info', e);
}
await ctx.saveLocalMessageToBackend(formMsg, content);
await ensureHistoryListed();
};
const tryHandleLeaveSend = (content: string) => {
if (!ctx.canUseLeaveFeature.value || !isStrongLeaveIntent(content)) return false;
void startLocalLeaveFlow(content);
return true;
};
const handleLeaveMarkdownClick = (event: MouseEvent) => {
const target = event.target as HTMLElement | null;
const actionElement = target?.closest?.('[data-leave-action]') as HTMLElement | null;
if (!actionElement) return false;
const action = actionElement.getAttribute('data-leave-action');
if (action !== 'start-leave-flow' || ctx.isThinking.value) return false;
event.preventDefault();
if (!ctx.canUseLeaveFeature.value) {
ctx.msg.warning('请在“通用入口”或“人事规章”入口使用请假功能');
return true;
}
void startLocalLeaveFlow('我要请假');
return true;
};
return { startLocalLeaveFlow, tryHandleLeaveSend, handleLeaveMarkdownClick };
}
@@ -0,0 +1,262 @@
/**
* 请假:表单初始数据、校验、余额断言、确认与 OA 提交。
*/
import { getLeaveBalance, submitLeaveWorkflow } from '@/features/auth/api/user.api';
import { NEED_BALANCE_CHECK_TYPES } from '../constants/leave';
import { formatLeaveBalanceNumber, getLeaveTypeLabel } from './leaveDisplay';
import {
calculateDurationHours,
formatDateTime,
isLeaveTypeByDay,
parseDateTime,
syncLeaveDuration,
} from './leaveDateTime';
import { extractLeaveTypeFromIntent } from './leaveIntent';
import {
findMessageIndexByLocalId,
getLeaveConfirmationPayload,
getLeaveFormPayload,
} from './leavePayload';
import type { ChatMessage } from '../types/chat.types';
import type {
ExtractedLeaveInfo,
LeaveConfirmationPayload,
LeaveRequestFormData,
} from '../types/leave.types';
import type { ComputedRef, Ref } from 'vue';
export interface LeaveFormContext {
messages: Ref<ChatMessage[]>;
currentUserDisplayName: ComputedRef<string>;
currentUserEmployeeId: ComputedRef<string>;
newLocalMessageId: (prefix: string) => string;
saveLocalMessageToBackend: (chatMsg: ChatMessage, userQuery?: string) => Promise<void>;
msg: { warning: (text: string) => void; error: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
}
export function createLeaveFormApi(ctx: LeaveFormContext) {
const createLeaveFormData = (content?: string, extractedInfo?: ExtractedLeaveInfo | null): LeaveRequestFormData => {
const now = new Date();
const initialLeaveType = extractedInfo?.leaveType || extractLeaveTypeFromIntent(content || '');
const isByDay = isLeaveTypeByDay(initialLeaveType);
const sameDayEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 18, 0);
const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000);
const defaultStart = formatDateTime(now);
const defaultEnd = isByDay ? formatDateTime(sameDayEnd) : formatDateTime(oneHourLater);
const startTime = extractedInfo?.startTime || defaultStart;
const endTime = extractedInfo?.endTime || defaultEnd;
let durationHours: number;
if (isByDay) {
const start = parseDateTime(startTime);
const end = parseDateTime(endTime);
if (start && end && end.getTime() > start.getTime()) {
const startDate = new Date(start.getFullYear(), start.getMonth(), start.getDate());
const endDate = new Date(end.getFullYear(), end.getMonth(), end.getDate());
const days = Math.max(1, Math.round((endDate.getTime() - startDate.getTime()) / (24 * 3600 * 1000)) + 1);
durationHours = days * 8;
} else {
durationHours = 8;
}
} else if (extractedInfo?.durationHours) {
durationHours = extractedInfo.durationHours;
} else {
durationHours = calculateDurationHours(startTime, endTime);
}
return {
applicantName: ctx.currentUserDisplayName.value,
employeeId: ctx.currentUserEmployeeId.value,
applicantUid: '',
applyTime: formatDateTime(now),
fillerName: ctx.currentUserDisplayName.value,
agentUid: '',
agentEmployeeId: '',
agentName: '',
leaveType: initialLeaveType,
startTime,
endTime,
durationHours,
isOutOfOffice: 1,
isWorkInjury: 1,
};
};
const checkLeaveBalance = async (leaveTypeCode: string) => {
try {
return await getLeaveBalance(leaveTypeCode);
} catch (e) {
console.error('Failed to check leave balance', e);
return null;
}
};
const validateLeaveForm = (form: LeaveRequestFormData) => {
if (!form.applicantName.trim()) return ctx.t('chat.leaveApplicantRequired');
if (!form.employeeId.trim()) return ctx.t('chat.employeeIdRequired');
if (!form.leaveType.trim()) return ctx.t('chat.leaveTypeRequired');
if (!form.agentUid.trim()) return ctx.t('chat.leaveAgentRequired');
if (!parseDateTime(form.startTime)) return ctx.t('chat.startTimeRequired');
if (!parseDateTime(form.endTime)) return ctx.t('chat.endTimeRequired');
syncLeaveDuration(form);
if (form.durationHours <= 0) return ctx.t('chat.durationInvalid');
return '';
};
const assertBalanceForForm = async (form: LeaveRequestFormData) => {
if (!NEED_BALANCE_CHECK_TYPES.has(form.leaveType)) return true;
const balance = await checkLeaveBalance(form.leaveType);
if (!balance || balance.remaining_hours === null || balance.remaining_hours === undefined) return true;
const requestedHours = form.durationHours;
if (requestedHours <= balance.remaining_hours) return true;
const isByDay = isLeaveTypeByDay(form.leaveType);
const unit = isByDay ? ctx.t('chat.dayUnit') : ctx.t('chat.hourUnit');
const requestedDisplay = isByDay ? Math.round(requestedHours / 8) : requestedHours;
const remainingDisplay = isByDay ? Math.round(balance.remaining_hours / 8) : balance.remaining_hours;
const label = getLeaveTypeLabel(form.leaveType);
ctx.msg.warning(ctx.t('chat.durationExceedsBalance', {
label,
requested: `${requestedDisplay}${unit}`,
remaining: `${remainingDisplay}${unit}`,
}));
return false;
};
const submitLeaveForm = async (chatMsg: ChatMessage) => {
const payload = getLeaveFormPayload(chatMsg);
if (!payload) return;
syncLeaveDuration(payload.form);
const error = validateLeaveForm(payload.form);
if (error) {
ctx.msg.warning(error);
return;
}
if (!(await assertBalanceForForm(payload.form))) return;
const existingConfirmIndex = ctx.messages.value.findIndex(
(item) => item?.type === 'leave-confirmation' && (item?.payload as LeaveConfirmationPayload | undefined)?.formId === payload.formId,
);
if (existingConfirmIndex >= 0) {
ctx.messages.value.splice(existingConfirmIndex, 1);
}
payload.confirmationGenerated = true;
const summary = JSON.parse(JSON.stringify(payload.form)) as LeaveRequestFormData;
const confirmMsg: ChatMessage = {
role: 'assistant',
type: 'leave-confirmation',
content: ctx.t('chat.leaveConfirmPrompt'),
payload: {
formId: payload.formId,
form: summary,
submitting: false,
},
local_id: ctx.newLocalMessageId('leave-confirm'),
local_only: true,
};
ctx.messages.value.push(confirmMsg);
void ctx.saveLocalMessageToBackend(chatMsg);
void ctx.saveLocalMessageToBackend(confirmMsg);
};
const editLeaveConfirmation = (chatMsg: ChatMessage, index: number) => {
const payload = getLeaveConfirmationPayload(chatMsg);
if (!payload) return;
const sourceIndex = findMessageIndexByLocalId(ctx.messages, payload.formId);
if (sourceIndex >= 0) {
const sourceMsg = ctx.messages.value[sourceIndex];
if (sourceMsg) {
const sourcePayload = getLeaveFormPayload(sourceMsg);
if (sourcePayload) {
sourcePayload.confirmationGenerated = false;
void ctx.saveLocalMessageToBackend(sourceMsg);
}
}
}
ctx.messages.value.splice(index, 1);
};
const confirmLeaveSubmission = async (chatMsg: ChatMessage) => {
const payload = getLeaveConfirmationPayload(chatMsg);
if (!payload || payload.submitting) return;
if (!(await assertBalanceForForm(payload.form))) return;
payload.submitting = true;
const sourceIndex = findMessageIndexByLocalId(ctx.messages, payload.formId);
let sourceMsg: ChatMessage | undefined;
if (sourceIndex >= 0) {
sourceMsg = ctx.messages.value[sourceIndex];
if (sourceMsg) {
const sourcePayload = getLeaveFormPayload(sourceMsg);
if (sourcePayload) {
sourcePayload.submitting = true;
sourcePayload.confirmationGenerated = true;
}
}
}
try {
const data = await submitLeaveWorkflow(payload.form);
const resultMsg: ChatMessage = {
role: 'assistant',
type: 'leave-result',
content: ctx.t('chat.leaveResultSubmitted'),
payload: {
formId: payload.formId,
success: true,
referenceNo: data.request_id || '-',
submittedAt: data.submitted_at || formatDateTime(new Date()),
requestName: data.request_name || '',
},
local_id: ctx.newLocalMessageId('leave-result'),
local_only: true,
};
ctx.messages.value.push(resultMsg);
payload.confirmed = true;
payload.submitting = false;
void ctx.saveLocalMessageToBackend(chatMsg);
void ctx.saveLocalMessageToBackend(resultMsg);
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : ctx.t('chat.oaLeaveSubmitFailed');
ctx.msg.error(errorMessage);
const resultMsg: ChatMessage = {
role: 'assistant',
type: 'leave-result',
content: ctx.t('chat.leaveSubmitFailedPrefix', { error: errorMessage }),
payload: {
formId: payload.formId,
success: false,
referenceNo: '-',
submittedAt: formatDateTime(new Date()),
errorMessage,
},
local_id: ctx.newLocalMessageId('leave-result'),
local_only: true,
};
ctx.messages.value.push(resultMsg);
void ctx.saveLocalMessageToBackend(resultMsg);
} finally {
payload.submitting = false;
if (sourceMsg) {
const sourcePayload = getLeaveFormPayload(sourceMsg);
if (sourcePayload) {
sourcePayload.submitting = false;
}
}
}
};
return {
createLeaveFormData,
checkLeaveBalance,
submitLeaveForm,
editLeaveConfirmation,
confirmLeaveSubmission,
formatLeaveBalanceNumber: (value: unknown) => formatLeaveBalanceNumber(value, ctx.t),
};
}
@@ -0,0 +1,110 @@
/**
* 请假:OA 自动登录弹窗与 VerifyLogin 表单提交。
*/
import { ref } from 'vue';
import {
OA_AUTO_LOGIN_TARGET,
OA_LEAVE_APPLY_PATH,
OA_PASSWORD_STORAGE_KEY,
OA_REQUEST_VIEW_PATH,
OA_VERIFY_LOGIN_URL,
} from '../constants/leave';
import type { ComputedRef } from 'vue';
export interface LeaveOaLoginContext {
currentUserEmployeeId: ComputedRef<string>;
msg: { warning: (text: string) => void };
t: (key: string) => string;
}
export function createLeaveOaLoginApi(ctx: LeaveOaLoginContext) {
const showOALoginDialog = ref(false);
const oaLoginEmployeeId = ref('');
const oaLoginPassword = ref(localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '');
const oaLoginGopage = ref('');
const oaLoginTarget = ref(OA_AUTO_LOGIN_TARGET);
const openOAAutoLoginPage = (gopage: string, username: string, password: string, target = OA_AUTO_LOGIN_TARGET) => {
const popup = window.open('about:blank', target);
if (!popup) {
ctx.msg.warning(ctx.t('chat.oaPopupBlocked'));
return;
}
const formHtml = `
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>${ctx.t('chat.oaLoggingTitle')}</title></head>
<body>
<p style="text-align:center;margin-top:100px;font-family:sans-serif;color:#666;">${ctx.t('chat.oaLoggingBody')}</p>
<form id="oaLoginForm" action="${OA_VERIFY_LOGIN_URL}" method="POST">
<input type="hidden" name="loginid" value="${username}" />
<input type="hidden" name="userpassword" value="${password.replace(/"/g, '&quot;')}" />
<input type="hidden" name="gopage" value="${gopage}" />
<input type="hidden" name="logintype" value="1" />
</form>
<script>document.getElementById('oaLoginForm').submit();<\/script>
</body>
</html>
`;
popup.document.open();
popup.document.write(formHtml);
popup.document.close();
};
const openOALeaveRequestDirectly = () => {
const employeeId = ctx.currentUserEmployeeId.value;
if (!employeeId || employeeId === '-') {
ctx.msg.warning(ctx.t('chat.noEmployeeId'));
return;
}
oaLoginEmployeeId.value = employeeId;
oaLoginPassword.value = localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '';
oaLoginGopage.value = OA_LEAVE_APPLY_PATH;
oaLoginTarget.value = OA_AUTO_LOGIN_TARGET;
showOALoginDialog.value = true;
};
const confirmOALogin = () => {
if (!oaLoginPassword.value.trim()) {
ctx.msg.warning(ctx.t('chat.oaPasswordRequired'));
return;
}
localStorage.setItem(OA_PASSWORD_STORAGE_KEY, oaLoginPassword.value.trim());
showOALoginDialog.value = false;
openOAAutoLoginPage(oaLoginGopage.value, oaLoginEmployeeId.value, oaLoginPassword.value.trim(), oaLoginTarget.value);
};
const cancelOALogin = () => {
showOALoginDialog.value = false;
};
const openOARequestDirectly = (requestId: string) => {
const normalizedRequestId = String(requestId || '').trim();
if (!normalizedRequestId || normalizedRequestId === '-') {
ctx.msg.warning(ctx.t('chat.oaRequestMissing'));
return;
}
const employeeId = ctx.currentUserEmployeeId.value;
if (!employeeId || employeeId === '-') {
ctx.msg.warning(ctx.t('chat.noEmployeeId'));
return;
}
oaLoginEmployeeId.value = employeeId;
oaLoginPassword.value = localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '';
oaLoginGopage.value = `${OA_REQUEST_VIEW_PATH}${encodeURIComponent(normalizedRequestId)}`;
oaLoginTarget.value = `hxops-oa-request-${normalizedRequestId}`;
showOALoginDialog.value = true;
};
return {
showOALoginDialog,
oaLoginEmployeeId,
oaLoginPassword,
confirmOALogin,
cancelOALogin,
openOALeaveRequestDirectly,
openOARequestDirectly,
};
}