优化第一次

This commit is contained in:
Weiming committed 2026-10-09 16:36:02 +08:00
1 parent 3a4e81a070
commit 459339719d
83 files changed
+7000 -1766

No files matched your search

+1 -2
View File
@@ -1,8 +1,7 @@
# dependencies
node_modules/
# build output
dist/
# build output (dist is intentionally versioned for deployment)
build/
.next/
out/
+1
View File
@@ -0,0 +1 @@
.snapshot-fields[data-v-6378499a]{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1px;margin:0;overflow:hidden;border:1px solid var(--line);border-radius:6px;background:var(--line)}.snapshot-field[data-v-6378499a]{min-width:0;padding:12px 14px;background:#fff}.snapshot-field.full[data-v-6378499a]{grid-column:1 / -1}.snapshot-field dt[data-v-6378499a]{margin-bottom:5px;color:var(--quiet);font-size:11px;font-weight:700}.snapshot-field dd[data-v-6378499a]{margin:0;overflow-wrap:anywhere}.snapshot-field .preserve-lines[data-v-6378499a]{white-space:pre-wrap}.expense-snapshot dd[data-v-6378499a]{margin-top:9px}.snapshot-warning[data-v-6378499a]{margin-bottom:9px;padding:8px 10px;border:1px solid #f1cf8d;border-radius:6px;background:#fff9e9;color:#805a16;font-size:11px}.finance-facts .source-grid[data-v-6378499a]{margin-top:0}@media (max-width: 680px){.snapshot-fields[data-v-6378499a]{grid-template-columns:1fr}.snapshot-field.full[data-v-6378499a]{grid-column:1}}
+1
View File
@@ -0,0 +1 @@
import{d as at,a as et,u as ot,o as ut,c as u,b as t,t as e,m as E,e as A,p as V,l as D,k as H,F as m,f as T,n as S,x as g,h as it,g as rt,r as L,y as f,B as dt,j as o}from"./index-CXCTlxVW.js";import{_ as pt}from"./_plugin-vue_export-helper-DlAUqK2U.js";const vt={class:"page-head"},ct={class:"head-actions"},mt={key:0,class:"load-wrap",role:"status"},yt={key:1,class:"card empty-state",role:"alert"},bt={key:2,class:"card empty-state"},Et={key:0,class:"inline-alert danger",role:"alert"},St={class:"detail-layout"},gt={class:"status-strip","aria-label":"报销流程独立状态"},Nt={class:"workflow","aria-label":"报销流程"},At={key:0,class:"section-card","aria-labelledby":"feishu-snapshot-title"},_t={class:"section-title"},Tt={class:"snapshot-fields"},ft={key:1,class:"snapshot-field full expense-snapshot"},kt={key:0,class:"snapshot-warning",role:"note"},ht={key:1,class:"table-wrap"},Pt={class:"data-table responsive-table"},Ct=["data-label"],It={key:2},Dt={key:1,class:"section-card"},Mt={class:"section-title"},Ot={class:"form-grid"},wt={class:"field"},Lt=["value"],Rt={class:"field"},$t=["value"],Xt={class:"field"},jt=["value"],Ut={class:"field"},Bt=["value"],Kt={class:"field"},Vt=["value"],Ht={class:"field full"},Yt=["value"],xt={key:2,class:"section-card finance-facts"},Ft={class:"source-grid"},Gt={class:"source-card"},qt={class:"source-card-head"},zt={class:"source-grid"},Wt={key:3,class:"section-card"},Jt={class:"section-title"},Qt={key:0,class:"table-wrap"},Zt={class:"data-table responsive-table"},tl={"data-label":"日期"},ll={"data-label":"类别"},sl={"data-label":"说明"},nl={"data-label":"附件"},al={"data-label":"金额",class:"amount"},el={class:"section-card"},ol={class:"section-title"},ul={key:0,class:"table-wrap"},il={class:"data-table responsive-table"},rl={"data-label":"发票号码"},dl={"data-label":"发票金额",class:"amount"},pl={"data-label":"校验状态"},vl={key:1,class:"empty-state"},cl={class:"section-card"},ml={class:"section-title"},yl={key:0,class:"attachment-grid"},bl={key:1,class:"empty-state"},El={class:"section-card"},Sl={class:"timeline"},gl={class:"card side-panel"},Nl={class:"summary-block"},Al={class:"amount-highlight"},_l={class:"summary-row"},Tl={class:"summary-row"},fl={class:"summary-total"},kl={class:"summary-block"},hl={key:0},Pl={key:1,class:"muted-copy"},Cl=at({__name:"ApplicationDetail",setup(Il){const P=it(),Y=rt(),_=et(),k=ot(),M=L(!0),C=L(""),O=L(!1),n=f(()=>O.value?_.getById(String(P.params.id)):null),x=f(()=>{var s;return!!n.value&&n.value.applicantName===((s=k.userInfo)==null?void 0:s.realName)&&(n.value.applicationStatus==="草稿"||n.value.approvalStatus==="退回")}),F=f(()=>n.value?`/applications/${n.value.id}/edit`:"/applications"),w=f(()=>{var s,l;return((l=(s=n.value)==null?void 0:s.formSnapshot)==null?void 0:l.mode)==="FEISHU"}),G=f(()=>{var s,l;return w.value&&((l=(s=n.value)==null?void 0:s.formSnapshot)==null?void 0:l.fields.some(i=>i.binding==="EXPENSE_ITEMS"||i.type==="EXPENSE_ITEMS"))}),y=s=>`¥ ${Number(s||0).toLocaleString("zh-CN",{minimumFractionDigits:2})}`,N=s=>({草稿:"draft",已提交:"info",审批中:"pending",审批通过:"success",退回:"danger",待收单:"pending",已收单:"success",未付款:"neutral",部分付款:"info",已付款:"success",未触发:"neutral"})[s]||"neutral",q=()=>window.print(),z=f(()=>n.value?[{name:"申请",value:n.value.applicationStatus,tone:N(n.value.applicationStatus)},{name:"审批",value:n.value.approvalStatus,tone:N(n.value.approvalStatus)},{name:"收单",value:n.value.receiptStatus,tone:N(n.value.receiptStatus)},{name:"付款",value:n.value.paymentStatus,tone:N(n.value.paymentStatus)}]:[]),W=f(()=>{const s=n.value;return s?[{name:"申请提交",copy:s.applicationStatus==="草稿"?"尚未提交申请":`${s.applicantName} 已提交报销申请`,done:s.applicationStatus!=="草稿",time:s.submitTime||s.createdAt||"待触发"},{name:"飞书审批",copy:s.approvalStatus==="退回"?`退回:${s.returnReason||"需补充信息"}`:s.approvalStatus==="审批通过"?"审批通过,结果已同步":`当前节点:${s.currentApprovalNode}`,done:s.approvalStatus!=="未触发",time:s.updatedAt||"待触发"},{name:"财务收单",copy:s.receiptStatus==="已收单"?"财务已完成收单":s.receiptStatus==="待收单"?"等待财务办理收单":"审批通过后激活",done:s.receiptStatus==="已收单",time:s.updatedAt||"待触发"},{name:"付款登记",copy:s.paymentStatus==="未付款"?"等待外部支付并登记凭据":`累计已付 ${y(_.paidAmount(s))}`,done:s.paymentStatus==="已付款",time:s.updatedAt||"待办理"}]:[]}),J=s=>{var p;const l=n.value;if(!l)return;const i=(p=l.formSnapshot)==null?void 0:p.values;return i&&Object.prototype.hasOwnProperty.call(i,s.valueKey)?i[s.valueKey]:{APPLICATION_NO:l.applicationNo,TITLE:l.title,APPLICANT_NAME:l.applicantName,APPLICANT_CONTACT:l.applicantName,APPLICANT_DEPARTMENT:l.departmentName,DEPARTMENT:l.departmentName,EXPENSE_TYPE:l.expenseTypeName||l.category,TOTLine truncated
+1
View File
@@ -0,0 +1 @@
import{d as J,a as K,u as O,r as S,w as Z,o as aa,c as i,b as t,p as w,l as _,e as y,F as T,x as D,q as E,v as ta,G as R,t as o,m as h,H as A,h as ea,y as v,B as la,j as n,f as g,n as C,k as I}from"./index-CXCTlxVW.js";import{u as sa,_ as na}from"./useListPagination-BTBVezsP.js";const oa={class:"page-content route-list-page"},ia={class:"page-head"},ra={class:"head-actions"},ua=["disabled"],pa={key:0,class:"load-wrap",role:"status","aria-live":"polite"},da={key:1,class:"card empty-state",role:"alert"},ca={key:2,class:"page-content"},va={key:0,class:"inline-alert",role:"status","aria-live":"polite"},ba={class:"card fill-list-card primary-list-card"},ya={class:"tabs",role:"tablist","aria-label":"报销列表筛选"},ga=["id","aria-selected","onClick"],ma=["aria-labelledby"],ka={class:"filter-bar"},fa={class:"filter-search"},Sa={class:"tag info","aria-live":"polite"},_a={key:0,class:"table-wrap"},ha={class:"data-table responsive-table","aria-label":"报销申请列表"},Ca={"data-label":"报销单号"},Na={"data-label":"报销事项"},wa={"data-label":"报销金额",class:"amount"},$a={"data-label":"申请状态"},Ba={"data-label":"审批状态"},xa={"data-label":"收单状态"},za={"data-label":"付款状态"},Ea={"data-label":"操作"},Fa={key:1,class:"empty-state"},Va={key:2,class:"empty-state"},P="applications-list-panel",Ma=J({__name:"Applications",setup(qa){const s=K(),m=O(),F=ea(),r=S(String(F.query.q||"")),u=S("all"),d=S(""),c=S(""),b=S(!!s.reimbursements.length),V=v(()=>m.canEdit("reimbursement.application.create")&&m.canRead("page.application-create")),Q=[{key:"all",label:"全部"},{key:"mine",label:"我发起的"},{key:"approval",label:"审批中"},{key:"returned",label:"退回补充"},{key:"paid",label:"已付款"}],q=l=>{var a,p;return l.applicantName===(((a=m.userInfo)==null?void 0:a.realName)||((p=s.user)==null?void 0:p.realName))},k=(l,a)=>a==="all"||a==="mine"&&q(l)||a==="approval"&&l.approvalStatus==="审批中"||a==="returned"&&l.approvalStatus==="退回"||a==="paid"&&l.paymentStatus==="已付款",j=v(()=>({all:s.reimbursements.length,mine:s.reimbursements.filter(l=>k(l,"mine")).length,approval:s.reimbursements.filter(l=>k(l,"approval")).length,returned:s.reimbursements.filter(l=>k(l,"returned")).length,paid:s.reimbursements.filter(l=>k(l,"paid")).length})),f=v(()=>{const l=r.value.trim().toLowerCase();return s.reimbursements.filter(a=>(!l||`${a.applicationNo} ${a.title} ${a.applicantName} ${a.payeeName}`.toLowerCase().includes(l))&&(!d.value||a.applicationStatus===d.value)&&(!c.value||a.approvalStatus===c.value)&&k(a,u.value))}),{page:$,pageSize:B,paginatedItems:G}=sa(f,{resetSources:[r,u,d,c]});Z(()=>F.query.q,l=>{const a=String(l||"");r.value!==a&&(r.value=a)},{flush:"sync"});const L=v(()=>s.loading||!b.value),U=v(()=>b.value&&s.source==="error"),H=v(()=>b.value&&!!s.error&&!U.value),W=v(()=>!!(r.value.trim()||d.value||c.value||u.value!=="all")),x=async()=>{b.value=!1,await s.load(),b.value=!0},M=()=>{r.value="",d.value="",c.value="",u.value="all"},X=l=>m.canEdit("reimbursement.application.edit")&&m.canRead("page.application-edit")&&q(l)&&(l.applicationStatus==="草稿"||l.approvalStatus==="退回"),Y=l=>`¥ ${Number(l||0).toLocaleString("zh-CN",{minimumFractionDigits:2})}`,N=l=>({草稿:"draft",已提交:"info",审批中:"pending",审批通过:"success",退回:"danger",待收单:"pending",已收单:"success",未付款:"neutral",部分付款:"info",已付款:"success",未触发:"neutral"})[l]||"neutral";return aa(async()=>{s.reimbursements.length||await s.load(),b.value=!0}),(l,a)=>{const p=la("router-link");return n(),i("div",oa,[t("div",ia,[a[6]||(a[6]=t("div",null,[t("span",{class:"eyebrow"},"MY EXPENSES"),t("h1",null,"我的报销"),t("p",null,"集中查看报销申请及审批、收单、付款进度。")],-1)),t("div",ra,[t("button",{class:"btn",type:"button",disabled:L.value,onClick:x},"刷新",8,ua),V.value?(n(),w(p,{key:0,class:"btn primary",to:"/applications/new"},{default:_(()=>[...a[5]||(a[5]=[g("+ 发起报销",-1)])]),_:1})):y("",!0)])]),L.value?(n(),i("div",pa,[...a[7]||(a[7]=[t("span",{class:"loader","aria-hidden":"true"},null,-1),t("p",null,"正在加载报销记录…",-1)])])):U.value?(n(),i("div",da,[a[8]||(a[8]=t("strong",null,"报销记录暂时无法加载",-1)),a[9]||(a[9]=t("span",null,"请检查网络连接后重试,系统不会以空列表代替异常数据。",-1)),t("button",{class:"btn",type:"button",onClick:x},"重新加载")])):(n(),i("div",ca,[H.value?(n(),i("div",va,[a[10]||(a[10]=t("b",{"aria-hidden":"true"},"i",-1)),a[11]||(a[11]=t("span",null,"数据服务暂时不可用,当前记录可能不完整。",-1)),t("button",{class:"btn small",type:"button",onClick:x},"重试")])):y("",!0),t("div",ba,[t("div",ya,[(n(),i(T,null,D(Q,e=>t("button",{id:`application-tab-${e.key}`,key:e.key,class:C(["tab",{active:u.value===e.key}]),type:"button",role:"tab","aria-selected":u.value===e.key,"aria-controls":P,onClick:z=>u.value=e.key},[g(o(e.label)+" ",1),t("smalLine truncated
+1
View File
@@ -0,0 +1 @@
import{d as Z,u as tt,a as lt,o as st,w as nt,c as o,b as t,t as s,F as y,m as v,p as D,e as b,l as p,k as u,f as d,n as w,x as C,r as I,y as r,B as m,j as e}from"./index-CXCTlxVW.js";const at={class:"dashboard-page"},et={class:"page-head"},ot={class:"eyebrow"},it={key:0},ut={key:1},dt={class:"head-actions"},rt=["disabled"],ct={key:0,class:"load-wrap",role:"status","aria-live":"polite"},pt={key:1,class:"card dashboard-error",role:"alert"},vt={class:"welcome-panel"},gt={key:0},bt={key:1},_t={key:0,class:"metrics"},yt={class:"metric warn"},mt={class:"metric"},ft={class:"metric"},ht={class:"metric success"},kt={key:1,class:"metrics finance-dashboard-metrics"},wt={class:"metric warn"},St={class:"metric"},At={class:"metric success"},Nt={class:"metric"},Ct={key:2,class:"grid two"},Ft={class:"card fill-list-card"},Et={class:"card-head"},Qt={class:"tag danger"},Rt={class:"card-body task-list fill-card-body"},Dt={class:"task-icon danger-icon","aria-hidden":"true"},$t={key:0,class:"empty-state"},xt={class:"card fill-list-card"},Bt={class:"card-body task-list fill-card-body"},Tt={class:"finance-line"},Wt={class:"flow-badge","aria-hidden":"true"},Pt={class:"finance-line"},Vt={class:"flow-badge payment-badge","aria-hidden":"true"},Lt={key:0,class:"empty-state compact-empty"},Mt={key:3,class:"grid two"},jt={class:"card fill-list-card"},zt={class:"card-head"},qt={class:"tag pending"},It={class:"card-body task-list fill-card-body"},Ut={class:"flow-badge receipt-badge","aria-hidden":"true"},Yt={key:0,class:"empty-state"},Gt={class:"card fill-list-card"},Ht={class:"card-head"},Jt={class:"tag info"},Kt={class:"card-body task-list fill-card-body"},Ot={class:"flow-badge payment-badge","aria-hidden":"true"},Xt={key:0,class:"empty-state"},Zt={key:4,class:"card section-gap"},tl={class:"card-head"},ll={class:"card-body"},sl={class:"table-wrap"},nl={key:0,class:"data-table responsive-table"},al={"data-label":"报销单号"},el={"data-label":"报销人 / 事项"},ol={"data-label":"申请金额",class:"amount"},il={"data-label":"收单状态"},ul={class:"tag success"},dl={"data-label":"付款状态"},rl={"data-label":"未付余额",class:"amount"},cl={"data-label":"操作"},pl={key:0,class:"empty-state"},vl={key:5,class:"card section-gap"},gl={class:"card-head"},bl={class:"card-body"},_l={class:"table-wrap"},yl={key:0,class:"data-table responsive-table"},ml={"data-label":"报销单号"},fl={"data-label":"报销事项"},hl={"data-label":"报销金额",class:"amount"},kl={"data-label":"申请状态"},wl={"data-label":"审批状态"},Sl={"data-label":"收单状态"},Al={"data-label":"付款状态"},Nl={"data-label":"操作"},Cl={key:0,class:"empty-state"},Ql=Z({__name:"Dashboard",setup(Fl){const f=tt(),i=lt(),F=I(!1),E=I(""),$=r(()=>{var a,l;return((a=f.userInfo)==null?void 0:a.realName)||((l=i.user)==null?void 0:l.realName)||"用户"}),g=r(()=>f.canAny(["page.finance-receipt","page.source-documents","page.payments","page.operation-log"])),h=r(()=>g.value?i.reimbursements:i.reimbursements.filter(a=>a.applicantName===$.value)),S=r(()=>h.value.filter(a=>a.approvalStatus==="退回")),x=r(()=>h.value.filter(a=>a.approvalStatus==="审批中")),Q=r(()=>i.reimbursements.filter(a=>a.approvalStatus==="审批通过"&&a.receiptStatus==="待收单")),k=r(()=>i.reimbursements.filter(a=>a.receiptStatus==="已收单")),A=r(()=>k.value.filter(a=>i.balance(a)>0)),R=r(()=>h.value.filter(a=>a.receiptStatus==="已收单"&&i.balance(a)>0)),P=r(()=>R.value.reduce((a,l)=>a+i.balance(l),0)),U=r(()=>A.value.reduce((a,l)=>a+i.balance(l),0)),Y=r(()=>k.value.reduce((a,l)=>a+l.totalAmount,0)),G=r(()=>{const a=new Date;return`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}`}),V=r(()=>h.value.filter(a=>String(a.createdAt||a.submitTime).slice(0,7)===G.value)),H=r(()=>V.value.reduce((a,l)=>a+l.totalAmount,0)),J=r(()=>V.value.length),K=r(()=>i.source==="fallback"?"服务暂不可用,当前展示缓存数据":i.error?"同步需要关注,请稍后重试":i.source==="api"?"业务数据已更新":"正在同步业务数据"),_=a=>`¥ ${Number(a||0).toLocaleString("zh-CN",{minimumFractionDigits:2})}`,L=a=>(a==null?void 0:a.slice(0,16))||"-",N=a=>({草稿:"draft",已提交:"info",审批中:"pending",审批通过:"success",退回:"danger",待收单:"pending",已收单:"success",未付款:"neutral",部分付款:"info",已付款:"success",未触发:"neutral",已取消:"neutral"})[a]||"neutral",B=async()=>{if(E.value="",!g.value){(!i.reimbursements.length||i.source==="error")&&await i.load();return}F.value=!0,i.financeQueueError="";try{const a=[];await i.loadFinanceQueue("receipt"),i.financeQueueError&&a.push(i.financeQueueError),await i.loadFinanceQueue("payment"),i.financeQueueError&&!a.includes(i.financeQueueError)&&a.push(i.financeQueueError),E.value=a.join(";")}finally{F.value=!1}},M=()=>{B()};return st(async()=>{await B()}),nt(g,()=>{B()}),(a,l)=>{const c=m("router-link"),O=m("Plus"),T=m("Refresh"),j=m("WarningFilled"),W=m("CircleCheckFilled"),z=m("Wallet"Line truncated
+1
View File
@@ -0,0 +1 @@
import{d as y,o as b,c as l,b as a,F as f,x as h,m as c,t as u,p as k,H as _,e as E,r as g,M as x,j as t,n as C}from"./index-CXCTlxVW.js";import{u as z,_ as S}from"./useListPagination-BTBVezsP.js";const w={class:"page-content route-list-page"},B={class:"card fill-list-card primary-list-card"},N={key:0,class:"table-wrap",tabindex:"0",role:"region","aria-label":"费用类型列表"},P={class:"data-table responsive-table"},T={"data-label":"编码"},V={"data-label":"名称"},F={"data-label":"分类"},I={class:"tag"},L={"data-label":"状态"},M={key:1,class:"empty-state",role:"alert"},U={key:2,class:"empty-state"},j={key:3,class:"load-wrap",role:"status"},R=y({__name:"ExpenseTypes",setup(A){const o=g([]),r=g(!1),n=g(""),{page:d,pageSize:i,paginatedItems:m}=z(o),v=async()=>{r.value=!1,n.value="";try{o.value=await x.get("/metadata/expense-types")||[]}catch(p){n.value=p instanceof Error?p.message:"请求失败,请稍后重试。"}finally{r.value=!0}};return b(v),(p,e)=>(t(),l("div",w,[e[6]||(e[6]=a("div",{class:"page-head"},[a("div",null,[a("span",{class:"eyebrow"},"EXPENSE TYPES"),a("h1",null,"费用类型"),a("p",null,"管理费用类型分类。")])],-1)),a("div",B,[r.value&&!n.value&&o.value.length>0?(t(),l("div",N,[a("table",P,[e[2]||(e[2]=a("thead",null,[a("tr",null,[a("th",null,"编码"),a("th",null,"名称"),a("th",null,"分类"),a("th",null,"状态")])],-1)),a("tbody",null,[(t(!0),l(f,null,h(c(m),s=>(t(),l("tr",{key:s.id},[a("td",T,[a("small",null,u(s.code),1)]),a("td",V,[a("strong",null,u(s.name),1)]),a("td",F,[a("span",I,u(s.category),1)]),a("td",L,[a("span",{class:C(["tag",s.status==="ACTIVE"?"success":"draft"])},u(s.status),3)])]))),128))])])])):n.value?(t(),l("div",M,[e[3]||(e[3]=a("strong",null,"费用类型加载失败",-1)),a("span",null,u(n.value),1),a("button",{class:"btn small",type:"button",onClick:v},"重试")])):r.value?(t(),l("div",U,[...e[4]||(e[4]=[a("strong",null,"暂无费用类型",-1)])])):(t(),l("div",j,[...e[5]||(e[5]=[a("span",{class:"loader","aria-hidden":"true"},null,-1),a("span",null,"正在加载费用类型…",-1)])])),r.value&&!n.value&&o.value.length?(t(),k(S,{key:4,page:c(d),"onUpdate:page":e[0]||(e[0]=s=>_(d)?d.value=s:null),"page-size":c(i),"onUpdate:pageSize":e[1]||(e[1]=s=>_(i)?i.value=s:null),total:o.value.length,"aria-label":"费用类型列表分页"},null,8,["page","page-size","total"])):E("",!0)])]))}});export{R as default};
+1
View File
@@ -0,0 +1 @@
import{d as P,a as j,u as H,o as K,c as n,b as t,k as $,l as x,F as z,e as F,t as o,q as W,v as G,x as J,m as k,p as O,H as L,r as _,y as r,B as X,j as a,f as Q,n as V,E as A}from"./index-CXCTlxVW.js";import{u as Y,_ as Z}from"./useListPagination-BTBVezsP.js";const tt={class:"page-content route-list-page"},st={class:"page-head"},et={class:"head-actions"},lt=["disabled"],at={key:0,class:"load-wrap",role:"status","aria-live":"polite"},nt={key:1,class:"card empty-state",role:"alert"},ot={key:0,class:"inline-alert",role:"status","aria-live":"polite"},it={class:"finance-kpis"},rt={class:"card fill-list-card primary-list-card"},ut={class:"filter-bar"},dt={class:"filter-search"},pt={class:"tag info","aria-live":"polite"},ct={key:0,class:"table-wrap"},vt={class:"data-table responsive-table","aria-label":"财务收单队列"},gt={"data-label":"报销单号"},yt={"data-label":"报销人 / 事项"},bt={"data-label":"申请金额",class:"amount"},ft={"data-label":"审批状态"},mt={class:"tag success"},kt={"data-label":"收单状态"},_t={"data-label":"付款状态"},St={"data-label":"操作"},ht=["disabled","aria-busy","onClick"],Ct={key:1,class:"muted-copy"},Nt={key:2,class:"muted-copy"},wt={key:3,class:"muted-copy"},Et={key:1,class:"empty-state"},Bt={key:2,class:"empty-state"},Lt=P({__name:"FinanceReceipt",setup($t){const i=j(),D=H(),S=r(()=>D.canEdit("finance.receipt.confirm")),g=_(""),p=_(!1),d=_(new Set),c=r(()=>i.reimbursements.filter(l=>l.approvalStatus==="审批通过")),R=r(()=>c.value.filter(l=>l.receiptStatus==="待收单")),U=r(()=>c.value.filter(l=>l.receiptStatus==="已收单")),I=r(()=>c.value.reduce((l,s)=>l+s.totalAmount,0)),v=r(()=>{const l=g.value.trim().toLowerCase();return c.value.filter(s=>`${s.applicationNo} ${s.applicantName} ${s.title}`.toLowerCase().includes(l))}),{page:b,pageSize:f,paginatedItems:M}=Y(v,{resetSources:[g]}),h=r(()=>i.loading||!p.value),C=r(()=>p.value&&(i.source==="error"||!!i.financeQueueError)),T=r(()=>p.value&&!!i.error&&!C.value),N=l=>`¥ ${Number(l||0).toLocaleString("zh-CN",{minimumFractionDigits:2})}`,w=l=>({待收单:"pending",已收单:"success",未付款:"neutral",部分付款:"info",已付款:"success"})[l]||"neutral",E=l=>String(l),m=l=>d.value.has(E(l)),y=async()=>{p.value=!1,i.error="",i.financeQueueError="",await i.loadFinanceQueue("receipt"),p.value=!0},q=async l=>{if(!S.value)return;const s=E(l.id);if(!d.value.has(s)){d.value=new Set(d.value).add(s);try{await i.receive(l.id),A.success(`${l.applicationNo} 已完成财务收单`)}catch(u){A.error(u instanceof Error?u.message:"收单失败,请重试")}finally{const u=new Set(d.value);u.delete(s),d.value=u}}};return K(()=>{y()}),(l,s)=>{const u=X("router-link");return a(),n("div",tt,[t("div",st,[s[4]||(s[4]=t("div",null,[t("span",{class:"eyebrow"},"FINANCE RECEIPT"),t("h1",null,"财务待收单"),t("p",null,"审批通过的报销进入收单队列,财务处理结果独立记录。")],-1)),t("div",et,[t("button",{class:"btn",type:"button",disabled:h.value,onClick:y},"刷新",8,lt),$(u,{class:"btn primary",to:"/payments"},{default:x(()=>[...s[3]||(s[3]=[Q("查看待付款",-1)])]),_:1})])]),h.value?(a(),n("div",at,[...s[5]||(s[5]=[t("span",{class:"loader","aria-hidden":"true"},null,-1),t("p",null,"正在读取收单队列…",-1)])])):C.value?(a(),n("div",nt,[s[6]||(s[6]=t("strong",null,"收单队列暂时无法加载",-1)),s[7]||(s[7]=t("span",null,"请检查网络连接后重试,系统不会以空列表代替异常数据。",-1)),t("button",{class:"btn",type:"button",onClick:y},"重新加载")])):(a(),n(z,{key:2},[T.value?(a(),n("div",ot,[s[8]||(s[8]=t("b",{"aria-hidden":"true"},"i",-1)),s[9]||(s[9]=t("span",null,"数据服务暂时不可用,当前队列可能不完整。",-1)),t("button",{class:"btn small",type:"button",onClick:y},"重试")])):F("",!0),t("div",it,[t("div",null,[s[10]||(s[10]=t("span",null,"待收单",-1)),t("strong",null,o(R.value.length),1),s[11]||(s[11]=t("small",null,"审批已完成",-1))]),t("div",null,[s[12]||(s[12]=t("span",null,"已收单",-1)),t("strong",null,o(U.value.length),1),s[13]||(s[13]=t("small",null,"等待付款执行",-1))]),t("div",null,[s[14]||(s[14]=t("span",null,"收单金额",-1)),t("strong",null,o(N(I.value)),1),s[15]||(s[15]=t("small",null,"不等同于已付款",-1))])]),t("div",rt,[s[22]||(s[22]=t("div",{class:"card-head"},[t("div",null,[t("h2",null,"收单队列"),t("p",null,"确认收单后,报销单进入付款处理环节。")]),t("span",{class:"tag info"},"财务处理")],-1)),t("div",ut,[t("label",dt,[s[16]||(s[16]=t("span",{"aria-hidden":"true"},"⌕",-1)),W(t("input",{"onUpdate:modelValue":s[0]||(s[0]=e=>g.value=e),type:"search","aria-label":"搜索待收单",placeholder:"搜索报销单号、报销人或事项"},null,512),[[G,g.value]])]),s[17]||(s[17]=t("span",{class:"filter-spacer"},null,-1)),t("span",pt,o(v.value.length)+" 笔结果",1)]),v.value.length?(a(),n("div",ct,[t("table",vt,[s[18]||(s[18]=t("caption",{class:"sr-only"},"财务收单队Line truncated
+1
View File
@@ -0,0 +1 @@
.kingdee-bind-panel.embedded .panel-card[data-v-bf209813]{box-shadow:none;border:1px solid var(--line)}.filter-hint[data-v-bf209813]{color:var(--muted);font-size:12px}.self-mark[data-v-bf209813]{margin-left:6px;color:var(--muted);font-size:11px}.check-option.full[data-v-bf209813]{grid-column:1 / -1;display:flex;align-items:center;gap:8px;margin-top:4px}.scheduled-page[data-v-3008b096]{min-width:0}.scheduled-page.scheduled-embedded[data-v-3008b096]{height:100%;min-height:0;flex:1 1 0;overflow:hidden}.task-card[data-v-3008b096],.history-card[data-v-3008b096]{min-width:0}.scheduled-embedded .task-card[data-v-3008b096]{flex:0 0 auto}.scheduled-embedded .history-card[data-v-3008b096]{min-height:0;flex:1 1 0;overflow:hidden}.scheduled-embedded .history-card>.history-table-wrap[data-v-3008b096]{min-height:0;max-height:none;flex:1 1 auto;overflow:auto}.task-head[data-v-3008b096],.history-head[data-v-3008b096],.detail-title-row[data-v-3008b096]{display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:12px}.task-head>div[data-v-3008b096],.history-head>div[data-v-3008b096],.detail-title-row>div[data-v-3008b096]:first-child{min-width:0;flex:1 1 280px}.task-head p[data-v-3008b096],.detail-title-row p[data-v-3008b096],.history-head p[data-v-3008b096]{overflow-wrap:anywhere}.page-state[data-v-3008b096]{min-height:180px;padding:30px 18px}.page-state .btn[data-v-3008b096],.detail-state .btn[data-v-3008b096],.history-state .btn[data-v-3008b096]{margin-top:12px}.task-layout[data-v-3008b096]{display:grid;grid-template-columns:minmax(210px,.34fr) minmax(0,1fr);gap:18px;padding:0 22px 22px}.task-list-warning[data-v-3008b096]{grid-column:1 / -1}.task-selector[data-v-3008b096]{display:grid;align-content:start;gap:7px}.task-option[data-v-3008b096]{width:100%;padding:12px;border:1px solid var(--line);border-radius:var(--radius);background:#fff;color:var(--body);text-align:left}.task-option[data-v-3008b096]:hover,.task-option.active[data-v-3008b096]{border-color:#a8c4df;background:var(--blue-soft)}.task-option-title[data-v-3008b096]{display:flex;align-items:center;justify-content:space-between;gap:8px}.task-option strong[data-v-3008b096]{color:var(--text);font-size:12px;overflow-wrap:anywhere}.task-option small[data-v-3008b096]{display:block;margin-top:4px;color:var(--muted);font-size:10px}.status-dot-small[data-v-3008b096]{width:8px;height:8px;flex:none;border-radius:50%;background:var(--quiet)}.status-dot-small.success[data-v-3008b096]{background:var(--success)}.status-dot-small.running[data-v-3008b096]{background:var(--blue);box-shadow:0 0 0 3px var(--blue-soft)}.task-detail[data-v-3008b096]{min-width:0;padding:16px;border:1px solid var(--line);border-radius:var(--radius);background:var(--surface-raised)}.detail-state[data-v-3008b096]{min-height:160px}.detail-title-row h3[data-v-3008b096]{font-size:16px}.detail-actions[data-v-3008b096]{display:flex;flex-wrap:wrap;gap:8px}.inline-note[data-v-3008b096]{margin:12px 0 0;padding:9px 11px;border-left:3px solid var(--blue);background:var(--blue-soft);color:var(--body);font-size:11px}.task-summary[data-v-3008b096]{display:grid;grid-template-columns:repeat(3,minmax(145px,1fr));gap:1px;margin-top:16px;overflow:hidden;border:1px solid var(--line);border-radius:6px;background:var(--line)}.task-summary>div[data-v-3008b096]{min-width:0;padding:11px 12px;background:#fff}.task-summary dt[data-v-3008b096]{color:var(--muted);font-size:10px}.task-summary dt span[data-v-3008b096]{color:var(--quiet);font-weight:400}.task-summary dd[data-v-3008b096]{margin-top:3px;overflow-wrap:anywhere;color:var(--body);font-size:12px}.state-badge[data-v-3008b096]{display:inline-flex;align-items:center;min-height:22px;padding:2px 8px;border-radius:99px;background:#eef1f4;color:var(--muted);font-size:10px;font-weight:700;white-space:nowrap}.state-badge.success[data-v-3008b096]{background:var(--success-soft);color:var(--success)}.state-badge.danger[data-v-3008b096]{background:var(--danger-soft);color:var(--danger)}.state-badge.running[data-v-3008b096],.state-badge.queued[data-v-3008b096]{background:var(--blue-soft);color:var(--blue-dark)}.history-card[data-v-3008b096]{display:flex;margin-top:16px;flex-direction:column}.history-state[data-v-3008b096]{min-height:180px;padding:30px 18px}.history-table-wrap[data-v-3008b096]{margin:0 18px}.history-table[data-v-3008b096]{min-width:920px}.history-table td[data-v-3008b096]{vertical-align:top}.history-table td>small[data-v-3008b096],.history-table td>span[data-v-3008b096]:not(.state-badge){display:block}.history-table td>small[data-v-3008b096]{margin-top:3px;color:var(--quiet);font-size:10px}.counts-summary[data-v-3008b096]{max-width:300px;color:var(--body);line-height:1.65}.error-detail[data-v-3008b096]{margin-top:5px;max-width:260px;color:var(--danger)}.error-detail summary[data-v-3008b096]{cursor:pointer;font-size:10px}.error-detail p[data-v-3008b096]{margin-top:4px;overflow-wrap:anywhere;white-space:pre-wrap}.schedule-dialog[data-v-3008b096]{widtLine truncated
+1
View File
@@ -0,0 +1 @@
import{M as ee,d as Te,u as xe,o as Re,D as Fe,j as u,c as o,n as R,b as e,t as i,e as k,q as J,v as he,F as j,x as pe,m as Ae,p as Le,H as He,I as Pe,f as de,Q as ca,y as _,r as c,K as va,A as pa,E as L,z as Oe,w as _e,N as ba,B as fa,k as ze,R as ga,S as Ie,h as ya,g as ma}from"./index-CXCTlxVW.js";import{a as De}from"./admin-C9Owgj_V.js";import{u as ka,_ as Ge}from"./useListPagination-BTBVezsP.js";import{_ as Be}from"./_plugin-vue_export-helper-DlAUqK2U.js";const ye={list:()=>ee.get("/kingdee/account-bindings"),me:()=>ee.get("/kingdee/account-bindings/me"),bind:(w,U)=>ee.put(`/kingdee/account-bindings/${w}`,U),unbind:w=>ee.delete(`/kingdee/account-bindings/${w}`),test:w=>ee.post(`/kingdee/account-bindings/${w}/test`)},ha={key:0,class:"inline-alert danger",role:"alert"},_a={class:"filter-bar"},$a={key:0,class:"filter-search"},wa={key:1,class:"filter-hint"},Ea={class:"tag info"},Ca={key:0,class:"load-wrap",role:"status"},Sa={key:1,class:"table-wrap",tabindex:"0",role:"region","aria-label":"金蝶账号绑定列表"},Ua={class:"data-table responsive-table"},Na={"data-label":"财务人员"},Aa={key:0,class:"self-mark"},Ia={"data-label":"工号"},Da={"data-label":"金蝶账号"},Ta={"data-label":"绑定状态"},xa={"data-label":"操作",class:"actions-cell"},Ra=["onClick"],La=["disabled","onClick"],Ba=["onClick"],Ma={key:2,class:"empty-state"},Xa={class:"modal-head","data-dialog-drag-handle":""},Va={id:"kingdee-bind-title"},qa=["disabled"],Ha={class:"modal-body"},Pa={class:"form-grid"},Fa={class:"field"},Oa=["disabled"],za={class:"field"},Ga=["disabled","placeholder"],Ka={class:"check-option full"},Qa=["disabled"],Ya={class:"modal-actions"},Za=["disabled"],ja=["disabled"],Ja=Te({__name:"KingdeeAccountBindingPanel",props:{embedded:{type:Boolean}},setup(w,{expose:U}){const I=xe(),ae=_(()=>{var n;return Number(((n=I.userInfo)==null?void 0:n.id)||0)||null}),F=_(()=>I.canRead("finance.kingdee.account.view-all")),Y=_(()=>I.canEdit("finance.kingdee.account.bind")),B=_(()=>I.canEdit("finance.kingdee.account.bind-own")),E=_(()=>I.canEdit("finance.kingdee.account.unbind")),N=_(()=>I.canEdit("finance.kingdee.account.unbind-own")),b=n=>Y.value||B.value&&n.userId===ae.value,q=n=>E.value||N.value&&n.userId===ae.value,m=c([]),C=c(!1),y=c(""),O=c(""),g=c(!1),A=c(null),M=c(null),x=c(null),$=va({kingdeeUsername:"",kingdeePassword:"",verifyLogin:!0}),X=n=>{var T,W;const s=(W=(T=n==null?void 0:n.response)==null?void 0:T.data)==null?void 0:W.message;return typeof s=="string"&&s.trim()?s:n instanceof Error&&n.message?n.message:"请求失败,请稍后重试。"},H=_(()=>{const n=O.value.trim().toLowerCase();return n?m.value.filter(s=>[s.realName,s.employeeNo,s.kingdeeUsername].some(T=>String(T||"").toLowerCase().includes(n))):m.value}),P=_(()=>m.value.filter(n=>n.bound).length),{page:D,pageSize:V,paginatedItems:te}=ka(H,{resetSources:[O]}),S=async()=>{C.value=!0,y.value="";try{await I.loadPermissions(),m.value=await ye.list()||[]}catch(n){y.value=X(n)}finally{C.value=!1}},Z=async n=>{var s;b(n)&&(x.value=n,$.kingdeeUsername=n.kingdeeUsername||"",$.kingdeePassword="",$.verifyLogin=!0,await pa(),(s=M.value)==null||s.showModal())},z=()=>{var n;g.value||((n=M.value)==null||n.close(),x.value=null)},d=async()=>{if(!(!x.value||!b(x.value)||g.value)){g.value=!0;try{const n=await ye.bind(x.value.userId,{kingdeeUsername:$.kingdeeUsername,kingdeePassword:$.kingdeePassword,verifyLogin:$.verifyLogin}),s=m.value.findIndex(T=>T.userId===n.userId);s>=0?m.value[s]=n:m.value.push(n),L.success("金蝶账号已绑定"),z()}catch(n){L.error(`绑定失败:${X(n)}`)}finally{g.value=!1}}},t=async n=>{if(!(!b(n)||A.value!=null)){A.value=n.userId;try{const s=await ye.test(n.userId);s!=null&&s.success?L.success(s.message||"验证成功"):L.error((s==null?void 0:s.message)||"验证失败")}catch(s){L.error(`验证失败:${X(s)}`)}finally{A.value=null}}},v=async n=>{if(q(n)){try{await Oe.confirm(`确认解绑 ${n.realName} 的金蝶账号?解绑后该员工将无法变更金蝶财务单据。`,"解绑确认",{type:"warning",confirmButtonText:"解绑",cancelButtonText:"取消"})}catch{return}try{await ye.unbind(n.userId);const s=m.value.findIndex(T=>T.userId===n.userId);s>=0&&(m.value[s]={...m.value[s],bound:!1,kingdeeUsername:null,boundAt:null,updatedAt:null,boundBy:null}),L.success("已解绑")}catch(s){L.error(`解绑失败:${X(s)}`)}}};return Re(()=>{S()}),U({reload:S}),(n,s)=>{var W,ve;const T=Fe("dialog-drag");return u(),o("div",{class:R(["kingdee-bind-panel",{embedded:w.embedded}])},[y.value?(u(),o("div",ha,[s[6]||(s[6]=e("b",null,"!",-1)),e("span",null,i(y.value),1),e("button",{class:"btn small",type:"button",onClick:S},"重试")])):k("",!0),e("div",{class:R(["card fill-list-card primary-list-card",{"panel-card":w.embedded}])},[e("div",_a,[F.value?(u(),o("label",$a,[s[7]||(s[7]=e("span",{"aria-hidden":"true"},"🔍",-1)),J(e("input",{"onUpdate:modelValue":s[0]||(s[0]=p=>O.value=p),type:"search",placeholder:"搜索姓名、工号或金蝶账Line truncated
+1
View File
@@ -0,0 +1 @@
.mobile-menu[data-v-35559d08]{display:none}@media (max-width: 900px){.mobile-menu[data-v-35559d08]{display:grid}}.notification-glyph[data-v-35559d08]{width:18px;height:18px;fill:none;stroke:currentColor;stroke-linecap:round;stroke-linejoin:round;stroke-width:1.7}.notification-count[data-v-35559d08]{position:absolute;top:1px;right:-3px;min-width:16px;height:16px;padding:0 4px;border:2px solid #fff;border-radius:99px;background:var(--danger);color:#fff;font-size:9px;font-weight:800;line-height:12px;text-align:center}.notification-dialog[data-v-35559d08]{width:min(450px,calc(100vw - 24px))}.notification-dialog-panel[data-v-35559d08]{animation:notification-pop-35559d08 .16s ease-out}@keyframes notification-pop-35559d08{0%{opacity:0;transform:translateY(-5px) scale(.985)}to{opacity:1;transform:translateY(0) scale(1)}}.notification-modal-head[data-v-35559d08]{display:flex;align-items:flex-start;justify-content:space-between;gap:14px;padding:18px 21px 15px;border-bottom:1px solid var(--line);background:#f8fafc;cursor:grab;-webkit-user-select:none;-moz-user-select:none;user-select:none;touch-action:none}.notification-modal-head[data-v-35559d08]:active{cursor:grabbing}.notification-modal-head h2[data-v-35559d08]{margin-top:4px;font-size:19px}.notification-modal-head p[data-v-35559d08]{margin-top:3px;color:var(--muted);font-size:11px}.notification-modal-body[data-v-35559d08]{max-height:min(480px,calc(100vh - 190px));padding:10px 12px;overflow-y:auto;background:#f6f8fa}.notification-list[data-v-35559d08]{display:grid;gap:7px;list-style:none}.notification-item[data-v-35559d08]{display:grid;width:100%;grid-template-columns:34px minmax(0,1fr) auto;align-items:start;gap:11px;min-height:76px;padding:12px;border:1px solid var(--line);border-radius:6px;background:#fff;color:var(--text);text-align:left}.notification-item.actionable[data-v-35559d08]{cursor:pointer}.notification-item.actionable[data-v-35559d08]:hover{border-color:#b8cee4;background:#f7faff}.notification-item[data-v-35559d08]:focus-visible{position:relative;z-index:1;outline:3px solid #72adff;outline-offset:-3px}.notification-item-icon[data-v-35559d08]{display:grid;place-items:center;width:34px;height:34px;border-radius:8px;background:var(--blue-soft);color:var(--blue);font-size:14px;font-weight:800}.notification-item-icon.danger[data-v-35559d08]{background:var(--danger-soft);color:var(--danger)}.notification-item-icon.pending[data-v-35559d08]{background:var(--warning-soft);color:var(--warning)}.notification-item-icon.success[data-v-35559d08]{background:var(--success-soft);color:var(--success)}.notification-item-copy[data-v-35559d08]{display:block;min-width:0}.notification-item-copy strong[data-v-35559d08],.notification-item-copy span[data-v-35559d08],.notification-item-copy small[data-v-35559d08]{display:block}.notification-item-copy strong[data-v-35559d08]{font-size:12px}.notification-item-copy span[data-v-35559d08]{margin-top:2px;color:var(--body);font-size:11px;line-height:1.55}.notification-item-copy small[data-v-35559d08]{margin-top:5px;color:var(--quiet);font-size:10px}.notification-item-link[data-v-35559d08]{padding-top:8px;color:var(--blue);font-size:11px;white-space:nowrap}.notification-item-link svg[data-v-35559d08]{width:14px;height:14px;vertical-align:-3px}.notification-empty[data-v-35559d08]{padding:38px 20px}.notification-empty-icon[data-v-35559d08]{display:grid;place-items:center;width:34px;height:34px;margin:0 auto 7px;border-radius:50%;background:var(--success-soft);color:var(--success);font-weight:800}.notification-empty strong[data-v-35559d08],.notification-empty span[data-v-35559d08]:not(.notification-empty-icon){display:block;text-align:center}.notification-empty strong[data-v-35559d08]{color:var(--body);font-size:13px}.notification-empty span[data-v-35559d08]:not(.notification-empty-icon){margin-top:3px;color:var(--muted);font-size:11px}.notification-modal-actions[data-v-35559d08]{display:flex;justify-content:flex-end;padding:13px 21px;border-top:1px solid var(--line);background:var(--surface-raised)}@media (max-width: 680px){.notification-modal-head[data-v-35559d08]{padding:16px 17px 13px}.notification-modal-body[data-v-35559d08]{padding:8px}.notification-item[data-v-35559d08]{grid-template-columns:34px minmax(0,1fr);padding:11px}.notification-item-link[data-v-35559d08]{grid-column:2;padding-top:0}.notification-modal-actions[data-v-35559d08]{padding:12px 17px}}@media (prefers-reduced-motion: reduce){.notification-dialog-panel[data-v-35559d08]{animation:none}}
+1
View File
@@ -0,0 +1 @@
import{d as Bt,u as It,a as Mt,o as Ft,w as z,c as y,b as e,n as f,k as c,l as C,m as r,e as g,p as N,t as m,q as K,v as Ut,s as Pt,f as _,F as Lt,x as Ot,h as qt,g as Vt,r as x,y as k,z as Ht,A as zt,i as Kt,B as d,j as l,C as Qt,D as Yt,E as jt}from"./index-CXCTlxVW.js";import{_ as Zt}from"./_plugin-vue_export-helper-DlAUqK2U.js";const Gt={class:"app-shell"},Jt={class:"main-nav","aria-label":"主导航"},Xt={key:0,class:"nav-group"},te={"aria-hidden":"true"},ee={key:1,class:"nav-group"},ae={"aria-hidden":"true"},ne={class:"nav-count"},se={"aria-hidden":"true"},oe={"aria-hidden":"true"},ie={key:2,class:"nav-group"},re={"aria-hidden":"true"},le={class:"nav-count warning"},ue={"aria-hidden":"true"},ce={class:"nav-count"},de={key:3,class:"nav-group admin-nav"},pe={"aria-hidden":"true"},ge={"aria-hidden":"true"},ve={"aria-hidden":"true"},fe={"aria-hidden":"true"},me={"aria-hidden":"true"},he={class:"sidebar-foot"},be={class:"main-area"},ye={class:"topbar"},ke={class:"topbar-left"},_e=["aria-expanded"],Ce={class:"breadcrumb"},Ne={class:"topbar-tools"},$e={class:"search-box"},Se=["aria-label"],Ee={key:0,class:"notification-count","aria-hidden":"true"},we={class:"avatar","aria-hidden":"true"},Ae={key:0,class:"data-sync-banner",role:"status"},Te={id:"main-content",class:"page-stage","aria-live":"polite"},We={class:"app-dialog__panel notification-dialog-panel","aria-describedby":"notification-dialog-description"},Re={class:"notification-modal-head","data-dialog-drag-handle":"",title:"拖动通知面板"},De={id:"notification-dialog-description"},xe={key:0,class:"notification-modal-body"},Be={class:"notification-list","aria-label":"通知列表"},Ie=["aria-label","onClick"],Me={class:"notification-item-copy"},Fe={key:0,class:"notification-item-link","aria-hidden":"true"},Ue={key:1,class:"notification-empty empty-state"},Pe={class:"notification-empty-icon","aria-hidden":"true"},Le=Bt({__name:"Layout",setup(Oe){const o=qt(),B=Vt(),h=It(),i=Mt(),v=x(!1),I=x(""),Q=x(null),w=x(null),A=x([]);let T=null;Ft(async()=>{var p,u,n;const a=(p=h.userInfo)==null?void 0:p.userType;let t=!1;if(h.token&&h.token!=="demo-local-session")try{const S=await h.refreshToken();t=!!(a&&a!==((u=S.user)==null?void 0:u.userType))}catch{try{await h.fetchUserInfo(),t=!!(a&&a!==((n=h.userInfo)==null?void 0:n.userType))}catch{}}t&&(i.reset(),o.path!=="/dashboard"&&await B.replace("/dashboard"));try{await h.loadPermissions()}catch{}V()});const P=k(()=>{var a;return((a=h.userInfo)==null?void 0:a.realName)||"用户"}),Y=a=>{const t={SUPER_ADMIN:"超级管理员",ADMIN:"系统管理员",FINANCE:"财务人员",EMPLOYEE:"员工"};if(typeof(a==null?void 0:a.isSuperAdmin)=="boolean"||Array.isArray(a==null?void 0:a.roleCodes)){const n=((a==null?void 0:a.roleCodes)||[]).map(D=>String(D).trim().toUpperCase());if((a==null?void 0:a.isSuperAdmin)===!0||n.includes("SUPER_ADMIN"))return t.SUPER_ADMIN;const S=["ADMIN","FINANCE","EMPLOYEE"].find(D=>n.includes(D));return S?t[S]:"普通用户"}const u=String((a==null?void 0:a.userType)||"").trim().toUpperCase();return t[u]||(a==null?void 0:a.userType)||"普通用户"},L=k(()=>Y(h.userInfo)),j=k(()=>{var t;return((t=o.meta)==null?void 0:t.title)||"工作台"}),b=a=>h.canRead(a),R=a=>h.canAny(a),Z=k(()=>b("page.integration-config")?"/integration-config":b("page.kingdee-account-binding")?{path:"/integration-config",query:{tab:"kingdee"}}:{path:"/integration-config",query:{tab:"scheduled-tasks"}}),G={Dashboard:"page.dashboard",Applications:"page.applications",ApplicationNew:"page.application-create",ApplicationDetail:"page.applications",ApplicationEdit:"page.application-edit"},O=k(()=>G[String(o.name||"")]||""),q=k(()=>!!O.value&&b(O.value)),V=async()=>{!q.value||i.reimbursements.length||i.loading||await i.load()};z(()=>o.name,()=>{V()});const J=k(()=>i.reimbursements.filter(a=>a.applicantName===P.value).length),X=k(()=>i.reimbursements.filter(a=>a.receiptStatus==="待收单").length),tt=k(()=>i.reimbursements.filter(a=>i.balance(a)>0&&a.receiptStatus==="已收单").length),et=k(()=>i.error&&i.source!=="fallback"?"同步异常":{api:"已同步",fallback:"使用缓存",error:"同步异常",connecting:"同步中"}[i.source]),at=k(()=>i.error&&i.source!=="fallback"?"error":i.source),nt=k(()=>i.source==="fallback"?"数据服务暂不可用,当前展示缓存数据。":i.source==="error"?"暂时无法同步业务数据,当前未展示业务记录。":i.error?"数据同步需要关注,请稍后重试。":i.source==="api"?"业务数据已更新。":"正在同步业务数据…"),W=k(()=>Math.max(0,Math.floor(Number(i.notifications)||0))),st=k(()=>W.value?`打开通知(${W.value}条未读)`:"打开通知(暂无未读)"),ot=()=>{I.value.trim()&&B.push({path:"/applications",query:{q:I.value.trim()}})},it=()=>Ht.alert("申请、审批、收单和付款是四个独立状态;金蝶来源单据只读,付款登记支持分次付款并保留幂等键。","工作台帮助",{confirmButtonText:"知道了"}),$=(a,t)=>{const Line truncated
+1
View File
@@ -0,0 +1 @@
import{d as _,u as L,a as C,o as E,E as c,c as n,b as s,t as y,e as b,f as R,g as F,h as S,r as p,i as A,j as i}from"./index-CXCTlxVW.js";const T="/assets/feishu-logo-BpH7Hif1.png",q={class:"login-screen","aria-labelledby":"loginTitle"},B={class:"login-panel"},I={class:"login-layout"},O={class:"login-card","aria-labelledby":"loginCardTitle","aria-describedby":"loginCardDescription"},U={key:0,class:"login-loading",role:"status","aria-live":"polite"},x={key:0},D={key:1,class:"login-action"},M={key:0,class:"inline-alert danger",role:"alert"},N=["disabled","aria-busy"],V={key:0,class:"login-button-spinner","aria-hidden":"true"},H={key:1,src:T,alt:""},W=_({__name:"Login",setup(Z){const k=F(),r=S(),t=L(),m=C(),l=p(!1),u=p(!0),h=p(""),o=p(""),w=async()=>{const d=t.beginFeishuLogin();l.value=!0,o.value="";try{const e=await A.getAuthUrl();if(!e.authUrl)throw new Error("获取飞书授权地址失败");window.location.assign(e.authUrl)}catch(e){const g=(e==null?void 0:e.message)==="获取飞书授权地址失败"?e.message:"暂时无法连接认证服务,请稍后重试";o.value=g,(e==null?void 0:e.message)==="获取飞书授权地址失败"&&c.error(e.message),t.clearFeishuLogin(d)}finally{l.value=!1}};return E(async()=>{const d=r.query.token,e=r.query.code,g=r.query.state,f=r.query.error;if((d||e||f||g)&&window.history.replaceState({},document.title,window.location.pathname),f){const a=sessionStorage.getItem("feishuOAuthAttempt");(!a||t.isCurrentFeishuLogin(a))&&(t.logout(),t.clearFeishuLogin(a)),m.reset(),u.value=!1,o.value="飞书授权未完成,请重新登录",c.error(o.value);return}if(e){const a=sessionStorage.getItem("feishuOAuthAttempt");h.value="正在交换授权码…";try{m.reset(),await t.feishuLogin(e,g,a||void 0),c.success("登录成功"),await k.replace("/dashboard")}catch(v){(!a||t.isCurrentFeishuLogin(a))&&(t.logout(),t.clearFeishuLogin(a)),m.reset(),u.value=!1,o.value=(v==null?void 0:v.message)||"登录失败,请重试",c.error(o.value)}return}u.value=!1}),(d,e)=>(i(),n("main",q,[s("div",B,[e[7]||(e[7]=s("header",{class:"login-brand"},[s("span",{class:"brand-mark","aria-hidden":"true"},[s("i"),s("i")]),s("span",null,[s("strong",null,"零差云控"),s("small",null,"ZEROERR · 统一费用付款平台")])],-1)),s("div",I,[e[6]||(e[6]=s("section",{class:"login-copy","aria-describedby":"loginIntro"},[s("span",{class:"eyebrow login-eyebrow"},"企业登录"),s("h1",{id:"loginTitle"},"统一费用付款平台"),s("p",{id:"loginIntro"},"使用飞书账号登录,连接付款申请、审批、收单与付款办理。")],-1)),s("section",O,[e[3]||(e[3]=s("h2",{id:"loginCardTitle"},"飞书登录",-1)),e[4]||(e[4]=s("p",{id:"loginCardDescription"},"使用企业飞书账号完成安全身份验证。",-1)),u.value?(i(),n("div",U,[e[1]||(e[1]=s("span",{class:"login-spinner","aria-hidden":"true"},null,-1)),s("span",null,[e[0]||(e[0]=s("strong",null,"正在验证身份…",-1)),h.value?(i(),n("small",x,y(h.value),1)):b("",!0)])])):(i(),n("div",D,[o.value?(i(),n("div",M,[e[2]||(e[2]=s("b",{"aria-hidden":"true"},"!",-1)),s("span",null,y(o.value),1)])):b("",!0),s("button",{class:"btn primary login-submit",type:"button",disabled:l.value,"aria-busy":l.value,onClick:w},[l.value?(i(),n("span",V)):(i(),n("img",H)),R(" "+y(l.value?"正在前往飞书…":"使用飞书登录"),1)],8,N)])),e[5]||(e[5]=s("div",{class:"login-card-foot"}," 身份授权由飞书提供,本平台不存储飞书密码。通讯录同步用于员工资料与业务管理,不作为登录条件。 ",-1))])]),e[8]||(e[8]=s("footer",{class:"login-foot"},"零差云控 · ZEROERR · 统一费用付款平台",-1))])]))}});export{W as default};
+1
View File
@@ -0,0 +1 @@
.filter-card[data-v-9172a3a4]{margin-bottom:16px;padding:16px 22px}.log-filters[data-v-9172a3a4]{display:flex;flex-wrap:wrap;align-items:end;gap:16px}.log-filters .field[data-v-9172a3a4]{min-width:180px;flex:1 1 180px;gap:6px}.log-filters .btn[data-v-9172a3a4]{flex:0 0 auto}.log-method[data-v-9172a3a4]{display:inline-block;min-width:3.2em;margin-right:6px;font:700 11px var(--mono)}.log-method.is-get[data-v-9172a3a4]{color:var(--blue)}.log-method.is-post[data-v-9172a3a4]{color:var(--success)}.log-method.is-put[data-v-9172a3a4]{color:#b7791f}.log-method.is-delete[data-v-9172a3a4]{color:var(--danger)}.mono[data-v-9172a3a4]{font:600 12px var(--mono)}.log-detail[data-v-9172a3a4]{display:block;max-width:420px;color:var(--muted);overflow-wrap:anywhere}@media (max-width: 720px){.log-filters[data-v-9172a3a4]{flex-direction:column;align-items:stretch}.log-filters .btn[data-v-9172a3a4]{width:100%}.log-detail[data-v-9172a3a4]{max-width:none}}
+1
View File
@@ -0,0 +1 @@
import{d as L,o as M,c as o,b as t,q as f,G as U,F as b,x as m,v as z,s as O,t as e,m as h,p as P,H as y,e as A,r as p,M as B,j as n,n as k}from"./index-CXCTlxVW.js";import{u as F,_ as V}from"./useListPagination-BTBVezsP.js";import{_ as D}from"./_plugin-vue_export-helper-DlAUqK2U.js";const G={class:"page-content route-list-page"},I={class:"page-head"},N={class:"head-actions"},j=["disabled"],H={class:"card filter-card"},K={class:"log-filters"},R={class:"field"},$=["value"],q={class:"field"},J={class:"card fill-list-card primary-list-card"},Q={class:"card-head"},W={key:0,class:"table-wrap",tabindex:"0",role:"region","aria-label":"操作日志列表"},X={class:"data-table responsive-table"},Y={"data-label":"时间"},Z={"data-label":"操作人"},tt={"data-label":"分类"},st={class:"tag neutral"},lt={"data-label":"接口"},at={"data-label":"状态"},et={"data-label":"耗时"},nt={class:"mono"},ot={"data-label":"详情"},rt={class:"log-detail"},ut={key:1,class:"empty-state",role:"alert"},it={key:2,class:"empty-state"},dt={key:3,class:"load-wrap",role:"status"},pt=L({__name:"Logs",setup(ct){const r=p([]),u=p(!1),i=p(""),c=p(""),v=p(""),C=["接口访问","认证登录","报销申请","付款操作","收单操作","飞书通讯录","飞书集成","配置管理","人员权限","主数据","自动任务","系统日志"],{page:g,pageSize:_,paginatedItems:S}=F(r),T=a=>String(a||"").split(/\s+/)[0]||"—",x=a=>{const s=String(a||"").split(/\s+/);return s.length>1?s.slice(1).join(" "):"—"},E=a=>{const s=String(a||"").toUpperCase();return s==="GET"?"is-get":s==="POST"?"is-post":s==="PUT"||s==="PATCH"?"is-put":s==="DELETE"?"is-delete":""},w=a=>a==null?"neutral":a>=400?"danger":a>=200&&a<300?"success":"neutral",d=async()=>{u.value=!1,i.value="";try{const a={limit:200};c.value&&(a.category=c.value),v.value&&(a.operator=v.value),r.value=await B.get("/logs",{params:a})||[]}catch(a){i.value=a instanceof Error?a.message:"请求失败,请稍后重试。"}finally{u.value=!0}};return M(d),(a,s)=>(n(),o("div",G,[t("div",I,[s[4]||(s[4]=t("div",null,[t("span",{class:"eyebrow"},"OPERATION LOGS"),t("h1",null,"操作日志"),t("p",null,"记录变更类接口访问(不含查看),按时间倒序排列。")],-1)),t("div",N,[t("button",{class:"btn",type:"button",disabled:!u.value,onClick:d},"刷新",8,j)])]),t("div",H,[t("div",K,[t("label",R,[s[6]||(s[6]=t("span",null,"分类",-1)),f(t("select",{"onUpdate:modelValue":s[0]||(s[0]=l=>c.value=l),class:"select",onChange:d},[s[5]||(s[5]=t("option",{value:""},"全部",-1)),(n(),o(b,null,m(C,l=>t("option",{key:l,value:l},e(l),9,$)),64))],544),[[U,c.value]])]),t("label",q,[s[7]||(s[7]=t("span",null,"操作人",-1)),f(t("input",{"onUpdate:modelValue":s[1]||(s[1]=l=>v.value=l),type:"search",placeholder:"姓名",autocomplete:"off",onKeyup:O(d,["enter"])},null,544),[[z,v.value,void 0,{trim:!0}]])]),t("button",{class:"btn primary",type:"button",onClick:d},"查询")])]),t("div",J,[t("div",Q,[s[8]||(s[8]=t("div",null,[t("h2",null,"接口访问记录"),t("p",null,"包含方法、路径、状态码与耗时。")],-1)),t("span",null,e(r.value.length)+" 条",1)]),u.value&&!i.value&&r.value.length?(n(),o("div",W,[t("table",X,[s[9]||(s[9]=t("thead",null,[t("tr",null,[t("th",null,"时间"),t("th",null,"操作人"),t("th",null,"分类"),t("th",null,"接口"),t("th",null,"状态"),t("th",null,"耗时"),t("th",null,"详情")])],-1)),t("tbody",null,[(n(!0),o(b,null,m(h(S),l=>(n(),o("tr",{key:l.id},[t("td",Y,[t("small",null,e(l.time||"—"),1)]),t("td",Z,[t("strong",null,e(l.operator||"匿名"),1)]),t("td",tt,[t("span",st,e(l.category||"接口访问"),1)]),t("td",lt,[t("strong",{class:k(["log-method",E(l.method)])},e(l.method||T(l.action)),3),t("small",null,e(l.path||x(l.action)),1)]),t("td",at,[t("span",{class:k(["tag",w(l.statusCode)])},e(l.statusCode??"—"),3)]),t("td",et,[t("span",nt,e(l.durationMs!=null?`${l.durationMs} ms`:"—"),1)]),t("td",ot,[t("small",rt,e(l.detail||"—"),1)])]))),128))])])])):i.value?(n(),o("div",ut,[s[10]||(s[10]=t("strong",null,"操作日志加载失败",-1)),t("span",null,e(i.value),1),t("button",{class:"btn small",type:"button",onClick:d},"重试")])):u.value?(n(),o("div",it,[...s[11]||(s[11]=[t("strong",null,"暂无操作日志",-1),t("span",null,"访问任意接口后会自动出现在这里。",-1)])])):(n(),o("div",dt,[...s[12]||(s[12]=[t("span",{class:"loader","aria-hidden":"true"},null,-1),t("span",null,"正在加载操作日志…",-1)])])),u.value&&!i.value&&r.value.length?(n(),P(V,{key:4,page:h(g),"onUpdate:page":s[2]||(s[2]=l=>y(g)?g.value=l:null),"page-size":h(_),"onUpdate:pageSize":s[3]||(s[3]=l=>y(_)?_.value=l:null),total:r.value.length,"aria-label":"操作日志分页"},null,8,["page","page-size","total"])):A("",!0)])]))}}),ht=D(pt,[["__scopeId","data-v-9172a3a4"]]);export{ht as default};
+1
View File
@@ -0,0 +1 @@
import{d as f,o as y,c as e,b as a,F as k,x as h,m as c,t as o,p as C,H as _,e as x,r as g,M as z,j as t,n as b}from"./index-CXCTlxVW.js";import{u as E,_ as w}from"./useListPagination-BTBVezsP.js";const B={class:"page-content route-list-page"},S={class:"card fill-list-card primary-list-card"},A={key:0,class:"table-wrap",tabindex:"0",role:"region","aria-label":"付款对象列表"},D={class:"data-table responsive-table"},M={"data-label":"账户名称"},N={"data-label":"银行"},P={"data-label":"账号"},V={"data-label":"默认"},F={"data-label":"状态"},I={key:1,class:"empty-state",role:"alert"},L={key:2,class:"empty-state"},U={key:3,class:"load-wrap",role:"status"},T=f({__name:"Payees",setup(j){const u=g([]),r=g(!1),n=g(""),{page:d,pageSize:i,paginatedItems:m}=E(u),v=async()=>{r.value=!1,n.value="";try{u.value=await z.get("/metadata/payees")||[]}catch(p){n.value=p instanceof Error?p.message:"请求失败,请稍后重试。"}finally{r.value=!0}};return y(v),(p,l)=>(t(),e("div",B,[l[6]||(l[6]=a("div",{class:"page-head"},[a("div",null,[a("span",{class:"eyebrow"},"PAYEES"),a("h1",null,"付款对象"),a("p",null,"管理收款方账户信息。")])],-1)),a("div",S,[r.value&&!n.value&&u.value.length>0?(t(),e("div",A,[a("table",D,[l[2]||(l[2]=a("thead",null,[a("tr",null,[a("th",null,"账户名称"),a("th",null,"银行"),a("th",null,"账号"),a("th",null,"默认"),a("th",null,"状态")])],-1)),a("tbody",null,[(t(!0),e(k,null,h(c(m),s=>(t(),e("tr",{key:s.id},[a("td",M,[a("strong",null,o(s.name),1)]),a("td",N,[a("small",null,o(s.bankName),1)]),a("td",P,[a("small",null,o(s.bankAccountMask||"已脱敏"),1)]),a("td",V,[a("span",{class:b(["tag",s.isDefault?"success":"draft"])},o(s.isDefault?"默认":"否"),3)]),a("td",F,[a("span",{class:b(["tag",s.status==="ACTIVE"?"success":"draft"])},o(s.status),3)])]))),128))])])])):n.value?(t(),e("div",I,[l[3]||(l[3]=a("strong",null,"付款对象加载失败",-1)),a("span",null,o(n.value),1),a("button",{class:"btn small",type:"button",onClick:v},"重试")])):r.value?(t(),e("div",L,[...l[4]||(l[4]=[a("strong",null,"暂无付款对象",-1)])])):(t(),e("div",U,[...l[5]||(l[5]=[a("span",{class:"loader","aria-hidden":"true"},null,-1),a("span",null,"正在加载付款对象…",-1)])])),r.value&&!n.value&&u.value.length?(t(),C(w,{key:4,page:c(d),"onUpdate:page":l[0]||(l[0]=s=>_(d)?d.value=s:null),"page-size":c(i),"onUpdate:pageSize":l[1]||(l[1]=s=>_(i)?i.value=s:null),total:u.value.length,"aria-label":"付款对象列表分页"},null,8,["page","page-size","total"])):x("",!0)])]))}});export{T as default};
+1
View File
@@ -0,0 +1 @@
import{d as se,a as ne,u as oe,o as ie,c as i,b as e,k as R,l as q,F as H,e as w,t as n,q as S,v as P,x as ue,m as d,p as re,H as Y,I as j,f as A,r as c,y as v,B as de,j as o,n as pe,A as ce,E as ve,D as me}from"./index-CXCTlxVW.js";import{u as be,_ as ye}from"./useListPagination-BTBVezsP.js";import{_ as fe}from"./_plugin-vue_export-helper-DlAUqK2U.js";const ge={class:"page-content route-list-page"},_e={class:"page-head"},ke={class:"head-actions"},he=["disabled"],Ce={key:0,class:"load-wrap",role:"status","aria-live":"polite"},Ne={key:1,class:"card empty-state",role:"alert"},Ee={key:0,class:"inline-alert",role:"status","aria-live":"polite"},xe={class:"finance-kpis"},we={class:"card fill-list-card primary-list-card"},Se={class:"filter-bar"},Be={class:"filter-search"},De={class:"tag info","aria-live":"polite"},$e={key:0,class:"table-wrap"},Fe={class:"data-table responsive-table","aria-label":"付款登记队列"},Pe={"data-label":"报销单号"},Ae={"data-label":"报销人 / 收款人"},Me={"data-label":"申请金额",class:"amount"},Ue={"data-label":"累计已付",class:"amount"},ze={"data-label":"未付余额",class:"amount"},Le={"data-label":"收单状态"},Ve={class:"tag success"},Qe={"data-label":"付款状态"},Te={"data-label":"操作"},Ie=["disabled","aria-busy","onClick"],Re={key:1,class:"muted-copy"},qe={key:2,class:"muted-copy"},He={key:1,class:"empty-state"},Ye={key:2,class:"empty-state"},je={class:"modal-head","data-dialog-drag-handle":""},Ke={id:"payment-dialog-description"},Oe=["disabled"],We={class:"modal-body payment-dialog-body"},Ge={class:"payment-summary"},Je={class:"form-grid payment-fields"},Xe={class:"field"},Ze=["max","aria-invalid"],ea={id:"pay-amount-help",class:"form-help"},aa={class:"field full"},la={key:0,id:"payment-form-error",class:"amount-error",role:"alert"},ta={class:"modal-actions"},sa=["disabled"],na=["disabled","aria-busy"],oa=se({__name:"Payments",setup(ia){const s=ne(),K=oe(),B=v(()=>K.canEdit("finance.payment.register")),k=c(""),y=c(!1),u=c(null),b=c(null),h=c(0),C=c(""),M=c(""),r=c(!1),m=c("");let D=null;const N=v(()=>s.reimbursements.filter(l=>l.receiptStatus==="已收单")),U=v(()=>N.value.filter(l=>s.balance(l)>0)),O=v(()=>N.value.filter(l=>s.balance(l)<=0)),W=v(()=>U.value.reduce((l,a)=>l+s.balance(a),0)),f=v(()=>{const l=k.value.trim().toLowerCase();return N.value.filter(a=>`${a.applicationNo} ${a.applicantName} ${a.title} ${a.payeeName}`.toLowerCase().includes(l))}),{page:$,pageSize:F,paginatedItems:G}=be(f,{resetSources:[k]}),z=v(()=>s.loading||!y.value),L=v(()=>y.value&&(s.source==="error"||!!s.financeQueueError)),J=v(()=>y.value&&!!s.error&&!L.value),p=l=>`¥ ${Number(l||0).toLocaleString("zh-CN",{minimumFractionDigits:2})}`,X=l=>({未付款:"neutral",部分付款:"info",已付款:"success"})[l]||"neutral",E=async()=>{y.value=!1,s.error="",s.financeQueueError="",await s.loadFinanceQueue("payment"),y.value=!0},Z=async l=>{var a;!B.value||r.value||(D=document.activeElement instanceof HTMLElement?document.activeElement:null,u.value=l,h.value=Number(s.balance(l).toFixed(2)),C.value="",M.value=`reim-${l.id}-${Number(s.balance(l).toFixed(2)).toFixed(2)}`,m.value="",b.value&&(b.value.open||b.value.showModal(),await ce(),(a=document.getElementById("pay-amount"))==null||a.focus()))},V=()=>{const l=D;D=null,u.value=null,l!=null&&l.isConnected&&l.focus()},g=()=>{var l;r.value||((l=b.value)!=null&&l.open&&b.value.close(),V())},ee=()=>V(),ae=l=>{l.preventDefault(),r.value||g()},le=l=>{if(r.value){l.preventDefault();return}g()},te=async()=>{if(!B.value||!u.value||r.value)return;const l=s.balance(u.value),a=Number(h.value);if(!Number.isFinite(a)||!(a>0)||a>l+.005){m.value=`付款金额须大于 0 且不超过未付余额 ${p(l)}`;return}r.value=!0,m.value="";let _=!1;try{await s.pay(u.value.id,Number(a.toFixed(2)),C.value.trim(),M.value),_=!0}catch(x){m.value=x instanceof Error?x.message:"付款失败,请检查后重试"}finally{r.value=!1}_&&(g(),ve.success("付款记录已登记"))};return ie(()=>{E()}),(l,a)=>{const _=de("router-link"),x=me("dialog-drag");return o(),i("div",ge,[e("div",_e,[a[6]||(a[6]=e("div",null,[e("span",{class:"eyebrow"},"PAYMENT QUEUE"),e("h1",null,"待付款"),e("p",null,"收单完成后进入付款队列,支持分次付款并保留付款凭据。")],-1)),e("div",ke,[e("button",{class:"btn",type:"button",disabled:z.value,onClick:E},"刷新",8,he),R(_,{class:"btn primary",to:"/finance-receipt"},{default:q(()=>[...a[5]||(a[5]=[A("返回待收单",-1)])]),_:1})])]),z.value?(o(),i("div",Ce,[...a[7]||(a[7]=[e("span",{class:"loader","aria-hidden":"true"},null,-1),e("p",null,"正在读取付款队列…",-1)])])):L.value?(o(),i("div",Ne,[a[8]||(a[8]=e("strong",null,"付款队列暂时无法加载",-1)),a[9]||(a[9]=e("span",null,"请检查网络连接后重试,系统不会以空列表代替异常数据。",-1)),e("button",{class:"btn",type:"button",onClick:E},"重新加载")])):(o(),i(H,{key:2},[J.value?(o(),i("div",Ee,[a[10]||(a[10]=e("b",{"aria-hidLine truncated
+1
View File
@@ -0,0 +1 @@
.payment-dialog-body[data-v-2bb72ae8]{background:#fff}.payment-summary[data-v-2bb72ae8]{overflow:hidden;border-color:#d7e0e8;border-radius:6px}.payment-summary>div[data-v-2bb72ae8]{padding:12px 14px;background:var(--surface-raised)}.payment-summary>div[data-v-2bb72ae8]:last-child{background:var(--blue-soft)}.payment-summary strong[data-v-2bb72ae8]{color:var(--navy);font-size:15px}.payment-summary>div:last-child strong[data-v-2bb72ae8]{color:var(--blue-dark)}.payment-fields[data-v-2bb72ae8]{grid-template-columns:1fr;gap:14px;padding:15px 0 0}.payment-fields .field[data-v-2bb72ae8]:first-child{max-width:310px}.payment-fields textarea[data-v-2bb72ae8]{min-height:78px}.amount-error[data-v-2bb72ae8]{margin:12px 0 0;padding:9px 11px;border-left:3px solid var(--danger);background:var(--danger-soft)}@media (max-width: 560px){.payment-summary[data-v-2bb72ae8]{grid-template-columns:1fr}.payment-fields .field[data-v-2bb72ae8]:first-child{max-width:none}.payment-dialog .modal-actions[data-v-2bb72ae8]{flex-direction:column-reverse}.payment-dialog .modal-actions .btn[data-v-2bb72ae8]{width:100%;min-height:44px}}
+1
View File
@@ -0,0 +1 @@
.feishu-fields[data-v-f631eabb]{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px 20px;padding:20px 22px 22px}.dynamic-field[data-v-f631eabb]{min-width:0}.expense-field[data-v-f631eabb],.display-field[data-v-f631eabb],.unsupported-field[data-v-f631eabb]{grid-column:1 / -1}.expense-field[data-v-f631eabb]{display:flex;flex-direction:column;gap:16px;margin:8px 0 0;padding:20px 0 0;border-top:1px solid var(--line)}.expense-field .expense-items[data-v-f631eabb]{padding:0}.expense-field .expense-item[data-v-f631eabb]{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px 20px;align-items:start;padding:16px}.expense-field .expense-item>.field[data-v-f631eabb]{min-width:0}.expense-field .expense-item>.attachment-field[data-v-f631eabb]{grid-column:1 / -1}.expense-field .remove-item[data-v-f631eabb]{grid-column:1 / -1;justify-self:end;margin-top:0}.expense-field .amount-summary[data-v-f631eabb]{margin:4px 0 0}.amount-control-wrap[data-v-f631eabb]{display:flex;flex-direction:column;gap:6px;min-width:0}.amount-control[data-v-f631eabb]{display:grid;grid-template-columns:minmax(0,1fr) 108px;gap:8px;align-items:center}.amount-control select[data-v-f631eabb]{min-height:var(--control-height)}.amount-mismatch-tip[data-v-f631eabb]{display:block;margin-top:6px}.department-picker[data-v-f631eabb]{position:relative}.department-menu[data-v-f631eabb]{position:absolute;z-index:5;top:calc(100% + 4px);right:0;left:0;max-height:240px;margin:0;padding:6px;overflow:auto;list-style:none;border:1px solid var(--line);border-radius:6px;background:#fff;box-shadow:var(--card-shadow)}.department-menu button[data-v-f631eabb]{width:100%;padding:8px 10px;border:0;border-radius:4px;background:transparent;text-align:left}.department-menu button[data-v-f631eabb]:hover{background:var(--blue-soft);color:var(--blue)}.department-empty[data-v-f631eabb]{padding:8px 10px;color:var(--muted)}.compact-title[data-v-f631eabb]{margin:0;padding:0;border-bottom:0}.compact-title h3[data-v-f631eabb]{margin:0;font-size:15px}.compact-title em[data-v-f631eabb]{color:var(--danger);font-style:normal}.display-field[data-v-f631eabb],.unsupported-field[data-v-f631eabb]{padding:16px 18px;border:1px solid var(--line);border-radius:7px;background:var(--surface)}.display-field p[data-v-f631eabb]{margin:8px 0 0;color:var(--muted);white-space:pre-wrap;line-height:1.65}.unsupported-field[data-v-f631eabb]{display:flex;flex-direction:column;gap:6px;border-color:#e5bfbc;background:var(--danger-soft);color:var(--danger)}.expense-child-warning[data-v-f631eabb]{margin:0}.field-error[data-v-f631eabb]{color:var(--danger)}.field [aria-invalid=true][data-v-f631eabb]{border-color:var(--danger)}.attachment-field[data-v-f631eabb]{grid-column:1 / -1}.attachment-input[data-v-f631eabb]{padding:10px}.attachment-list[data-v-f631eabb]{display:flex;margin:10px 0 0;padding:0;flex-direction:column;gap:8px;list-style:none}.attachment-list li[data-v-f631eabb]{display:flex;min-width:0;align-items:center;justify-content:space-between;gap:14px;padding:12px 14px;border:1px solid var(--line);border-radius:7px;background:var(--surface)}.attachment-list li>div[data-v-f631eabb]{min-width:0}.attachment-list strong[data-v-f631eabb],.attachment-list small[data-v-f631eabb]{display:block;overflow-wrap:anywhere}.attachment-list small[data-v-f631eabb]{margin-top:3px;color:var(--quiet)}.attachment-list .is-failed[data-v-f631eabb]{border-color:#e5bfbc;background:var(--danger-soft)}.attachment-list .is-failed small[data-v-f631eabb]{color:var(--danger)}.attachment-remove[data-v-f631eabb]{border:0;background:transparent;color:var(--danger);cursor:pointer;font:inherit}.attachment-remove[data-v-f631eabb]:disabled{cursor:wait;opacity:.6}select[multiple][data-v-f631eabb]{min-height:104px}.sr-only[data-v-f631eabb]{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@media (max-width: 680px){.feishu-fields[data-v-f631eabb]{grid-template-columns:1fr;gap:18px;padding:16px}.dynamic-field[data-v-f631eabb]{grid-column:1}.expense-field .expense-item[data-v-f631eabb],.amount-control[data-v-f631eabb]{grid-template-columns:1fr}}.application-form[data-v-b41a0b46]{display:flex;flex-direction:column;gap:18px}.application-form[data-v-b41a0b46] .page-head{margin-bottom:0}.application-form[data-v-b41a0b46] .step-rail,.application-form[data-v-b41a0b46] .inline-alert{margin:0}.form-page[data-v-b41a0b46]{display:flex;flex-direction:column;gap:16px}.form-page .section-card[data-v-b41a0b46]{margin:0}.form-page .section-gap[data-v-b41a0b46]{margin-top:0}.form-page[data-v-b41a0b46] .form-grid{gap:16px 20px;padding:20px 22px 22px}.form-page[data-v-b41a0b46] .field{gap:8px}.definition-bar[data-v-b41a0b46]{display:flex;align-items:center;flex-wrap:wrap;gap:10px 18px;margin:0;padding:14px 18px;border:1px solid #bfd3e8;border-radius:8px;background:var(--blue-soft);color:var(--blue);font-size:12px}.definition-state[data-v-b41a0b46]{display:flex;min-heightLine truncated
+1
View File
@@ -0,0 +1 @@
import{d as lt,o as ut,c as i,F as x,x as R,r as I,j as l,b as s,f as O,t as E,e as T,n as Ie,m as It,q as z,v as ie,I as dt,y as N,J as Te,K as qe,u as Nt,a as kt,w as Je,k as Ze,l as it,L as Ct,G as $t,A as Qe,E as et,B as Pt,g as Lt,h as Mt,D as Dt}from"./index-CXCTlxVW.js";import{f as Ot}from"./feishuDirectory-BmPyCMe4.js";import{_ as ct}from"./_plugin-vue_export-helper-DlAUqK2U.js";const xt=50*1024*1024,wt=".pdf,.png,.jpg,.jpeg,.doc,.docx,.xls,.xlsx,application/pdf,image/png,image/jpeg,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",Ft=new Set(["pdf","png","jpg","jpeg","doc","docx","xls","xlsx"]),qt=p=>(p==null?void 0:p.id)==null||!p.fileName?null:{id:p.id,fileName:p.fileName,contentType:p.contentType||p.fileType||"",fileSize:Number(p.fileSize||0)},Rt=(p,A=[])=>{const m=p==null?void 0:p.id,P=m==null?[]:A.filter(F=>(F==null?void 0:F.expenseItemId)!=null&&String(F.expenseItemId)===String(m)),$=[...(p==null?void 0:p.attachments)||[],...(p==null?void 0:p.attachmentMetadata)||[],...P],L=new Map;return $.forEach(F=>{const H=qt(F);H&&!L.has(String(H.id))&&L.set(String(H.id),H)}),[...L.values()]},Xt=(p,A)=>{const m=new Map;return[...(p==null?void 0:p.attachmentIds)||[],...A.map($=>$.id)].forEach($=>m.set(String($),$)),[...m.values()]},pt=(p,A)=>{const m=new Set(A.filter(P=>P.id!=null).map(P=>String(P.id)));return p.filter(P=>!m.has(String(P)))},Ut=p=>{var m;const A=((m=p.name.split(".").pop())==null?void 0:m.toLowerCase())||"";return Ft.has(A)?p.size>xt?"文件超过 50MB,无法上传":"":"不支持该文件类型,请选择 PDF、PNG/JPEG、DOC/DOCX 或 XLS/XLSX 文件"},Re=9999999999e-2,Bt=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/,Vt={empty:"请填写金额",invalid:"金额须为有效数字,例如 128.50",non_positive:"金额须大于 0",too_many_decimals:"金额最多保留两位小数",too_large:`单笔金额不能超过 ${Re.toLocaleString("zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2})} 元`},Le=(p,A="金额")=>p==="empty"?`请填写${A}`:p==="invalid"?`${A}须为有效数字,例如 128.50`:p==="non_positive"?`${A}须大于 0`:p==="too_many_decimals"?`${A}最多保留两位小数`:p==="too_large"?`${A}不能超过 ${Re.toLocaleString("zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2})} 元`:Vt[p],G=p=>{if(p==null||p==="")return"empty";if(typeof p=="number")return Number.isFinite(p)?p<=0?"non_positive":Math.round(p*100)/100!==p?"too_many_decimals":p>Re?"too_large":null:"invalid";const A=String(p).trim();if(!A)return"empty";if(/[eE]/.test(A)||!/^-?\d/.test(A))return"invalid";if(A.startsWith("-"))return"non_positive";if(!/^\d+(\.\d+)?$/.test(A))return"invalid";if(A.includes(".")&&A.split(".")[1].length>2)return"too_many_decimals";if(!Bt.test(A))return"invalid";const m=Number(A);return Number.isFinite(m)?m<=0?"non_positive":m>Re?"too_large":null:"invalid"},Me=p=>{if(G(p))return 0;const m=typeof p=="number"?p:Number(String(p).trim());return Math.round(m*100)/100},Kt={class:"feishu-fields"},Ht=["aria-labelledby"],Yt={class:"section-title compact-title"},jt=["id"],zt={key:0},Gt={key:0,class:"unsupported-field expense-child-warning",role:"alert"},Wt={class:"expense-items"},Jt={class:"sr-only"},Zt=["for"],Qt={key:0},en=["id","accept","disabled","aria-required","aria-invalid","aria-describedby","onChange"],tn=["id"],nn=["aria-label"],an=["disabled","aria-label","onClick"],sn=["id"],rn=["id","value","required","disabled","onChange"],on=["value"],ln=["id","value","maxlength","required","readonly","onInput"],un={key:3,class:"amount-control-wrap"},dn={class:"amount-control"},cn=["id","value","required","readonly","aria-invalid","aria-describedby","onInput","onBlur"],pn=["aria-label","value","disabled","onChange"],yn=["value"],vn=["id"],mn=["id"],En=["id","value","type","maxlength","required","readonly","onInput"],gn=["disabled","aria-label","onClick"],bn={key:1,class:"field-error amount-mismatch-tip",role:"status"},Tn={key:1,class:"dynamic-field display-field",role:"note"},hn={key:2,class:"field dynamic-field applicant-contact"},_n=["for"],An={key:0},fn=["id","value","aria-describedby"],Sn=["id"],In={key:3,class:"field dynamic-field applicant-department"},Nn=["for"],kn={key:0},Cn=["id","placeholder","aria-describedby"],$n={key:0,class:"department-menu",role:"listbox"},Pn=["onMousedown"],Ln={key:0,class:"department-empty"},Mn=["id"],Dn={key:4,class:"dynamic-field unsupported-field",role:"alert"},On=["for"],xn={key:0},wn=["id","value","aria-describedby"],Fn=["id","value","aria-describedby"],qn=["id"],Rn=["id","value","maxlength","required","aria-required","aria-invalid","aria-describedby","onInput"],Xn=["id","value","required","aria-required","aria-invalid","aria-describedby","onChange"],Un=["value"],Bn=["id","value","required","aria-required","aria-invalid","aria-describedby","onChange"],Vn=["value"],Kn={key:4,class:"amount-control"},Hn=["id","value","maxlength","requiLine truncated
+1
View File
@@ -0,0 +1 @@
import{d as h,o as k,c as n,b as e,q as C,v as S,t as o,F as D,x as w,m,p as x,H as f,e as E,r as p,M as N,y as z,j as s}from"./index-CXCTlxVW.js";import{u as L,_ as U}from"./useListPagination-BTBVezsP.js";const B={class:"page-content route-list-page"},M={class:"card fill-list-card primary-list-card"},R={class:"filter-bar"},F={class:"filter-search"},P={class:"tag info"},T={key:0,class:"table-wrap",tabindex:"0",role:"region","aria-label":"业务单据列表"},V={class:"data-table responsive-table"},q={"data-label":"单据编号"},O={"data-label":"类型"},$={class:"tag"},j={"data-label":"金额",class:"amount"},H={"data-label":"日期"},I={"data-label":"来源"},A={key:1,class:"empty-state",role:"alert"},G={key:2,class:"empty-state"},J={key:3,class:"load-wrap",role:"status"},X=h({__name:"Sources",setup(K){const u=p(""),c=p([]),i=p(!1),r=p(""),_=async()=>{i.value=!1,r.value="";try{c.value=await N.get("/sources")||[]}catch(t){r.value=t instanceof Error?t.message:"请求失败,请稍后重试。"}finally{i.value=!0}};k(_);const d=z(()=>{if(!u.value)return c.value;const t=u.value.toLowerCase();return c.value.filter(a=>(a.sourceDocNo||"").toLowerCase().includes(t))}),{page:v,pageSize:g,paginatedItems:b}=L(d,{resetSources:[u]}),y=t=>`¥ ${(t||0).toLocaleString("zh-CN",{minimumFractionDigits:2})}`;return(t,a)=>(s(),n("div",B,[a[9]||(a[9]=e("div",{class:"page-head"},[e("div",null,[e("span",{class:"eyebrow"},"SOURCE DOCUMENTS"),e("h1",null,"业务单据"),e("p",null,"来自金蝶 ERP 的源单据,只读展示。")])],-1)),e("div",M,[e("div",R,[e("label",F,[a[3]||(a[3]=e("span",{"aria-hidden":"true"},"🔍",-1)),C(e("input",{type:"search","onUpdate:modelValue":a[0]||(a[0]=l=>u.value=l),placeholder:"搜索单据编号","aria-label":"搜索"},null,512),[[S,u.value]])]),a[4]||(a[4]=e("span",{class:"filter-spacer"},null,-1)),e("span",P,o(d.value.length)+" 笔",1)]),i.value&&!r.value&&d.value.length>0?(s(),n("div",T,[e("table",V,[a[5]||(a[5]=e("thead",null,[e("tr",null,[e("th",null,"单据编号"),e("th",null,"类型"),e("th",{class:"amount"},"金额"),e("th",null,"日期"),e("th",null,"来源")])],-1)),e("tbody",null,[(s(!0),n(D,null,w(m(b),l=>(s(),n("tr",{key:l.id},[e("td",q,[e("strong",null,o(l.sourceDocNo),1)]),e("td",O,[e("span",$,o(l.sourceDocType),1)]),e("td",j,o(y(l.amount)),1),e("td",H,[e("small",null,o(l.sourceDate),1)]),e("td",I,[e("small",null,o(l.sourceSystem),1)])]))),128))])])])):r.value?(s(),n("div",A,[a[6]||(a[6]=e("strong",null,"业务单据加载失败",-1)),e("span",null,o(r.value),1),e("button",{class:"btn small",type:"button",onClick:_},"重试")])):i.value?(s(),n("div",G,[...a[7]||(a[7]=[e("strong",null,"暂无业务单据",-1),e("span",null,"金蝶 ERP 数据同步后会自动显示",-1)])])):(s(),n("div",J,[...a[8]||(a[8]=[e("span",{class:"loader","aria-hidden":"true"},null,-1),e("span",null,"正在加载业务单据…",-1)])])),i.value&&!r.value&&d.value.length?(s(),x(U,{key:4,page:m(v),"onUpdate:page":a[1]||(a[1]=l=>f(v)?v.value=l:null),"page-size":m(g),"onUpdate:pageSize":a[2]||(a[2]=l=>f(g)?g.value=l:null),total:d.value.length,"aria-label":"业务单据列表分页"},null,8,["page","page-size","total"])):E("",!0)])]))}});export{X as default};
+1
View File
@@ -0,0 +1 @@
.permission-editor[data-v-b877440e]{display:grid;gap:14px}.editor-head[data-v-b877440e]{display:flex;align-items:end;justify-content:space-between;gap:16px}.editor-head h3[data-v-b877440e],.column-head h3[data-v-b877440e]{font-size:15px}.editor-head p[data-v-b877440e],.column-head p[data-v-b877440e],.permission-rules[data-v-b877440e],.compatibility-card p[data-v-b877440e]{color:var(--muted);font-size:11px}.permission-search[data-v-b877440e]{width:min(320px,100%)}.permission-search input[data-v-b877440e]{width:100%}.permission-summary[data-v-b877440e],.permission-rules[data-v-b877440e]{display:flex;gap:10px;padding:10px 12px;border:1px solid var(--line);border-radius:7px;background:var(--surface)}.permission-columns[data-v-b877440e]{display:grid;grid-template-columns:minmax(0,2fr) minmax(280px,1fr);align-items:start;gap:14px}.permission-column[data-v-b877440e]{display:grid;min-width:0;gap:10px}.column-head[data-v-b877440e]{display:flex;align-items:end;justify-content:space-between;gap:10px;padding:0 2px}.column-head>span[data-v-b877440e]{color:var(--muted);font-size:11px;white-space:nowrap}.module-card[data-v-b877440e],.field-module[data-v-b877440e]{border:1px solid var(--line);border-radius:9px;background:#fff;overflow:hidden}.branch-title[data-v-b877440e]{display:flex;align-items:center;gap:9px;padding:12px 14px;cursor:pointer}.branch-title>span[data-v-b877440e],.action-list label>span[data-v-b877440e],.field-list label>span[data-v-b877440e]{display:grid;min-width:0;gap:2px}.branch-title code[data-v-b877440e],.action-list code[data-v-b877440e],.field-list code[data-v-b877440e],.field-module code[data-v-b877440e],.compatibility-card code[data-v-b877440e]{color:var(--quiet);font:10px var(--mono);overflow-wrap:anywhere}.page-grid[data-v-b877440e]{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;padding:0 12px 12px}.page-card[data-v-b877440e]{min-width:0;border:1px solid var(--line);border-radius:7px;background:var(--surface-raised)}.page-title[data-v-b877440e]{border-bottom:1px solid var(--line)}.action-list[data-v-b877440e],.field-list[data-v-b877440e]{display:grid;gap:1px;padding:8px}.action-list label[data-v-b877440e],.field-list label[data-v-b877440e]{display:flex;align-items:center;gap:8px;padding:7px;border-radius:5px;font-size:11px}.action-list label[data-v-b877440e]:hover,.field-list label[data-v-b877440e]:hover{background:var(--blue-soft)}.page-empty[data-v-b877440e]{padding:9px 12px;color:var(--quiet);font-size:10px}.field-module>header[data-v-b877440e]{display:grid;gap:2px;padding:11px 12px;border-bottom:1px solid var(--line);background:var(--surface)}.field-page+.field-page[data-v-b877440e]{border-top:1px solid var(--line)}.field-page-title[data-v-b877440e]{display:grid;gap:2px;padding:9px 12px 3px}.field-list label[data-v-b877440e]{justify-content:space-between}.field-list select[data-v-b877440e],.compatibility-card select[data-v-b877440e]{min-width:84px;padding:6px}.compatibility-card[data-v-b877440e]{padding:13px;border:1px dashed var(--warning);border-radius:8px;background:var(--warning-soft)}.compatibility-card ul[data-v-b877440e]{display:grid;gap:6px;margin-top:8px;padding:0;list-style:none}.compatibility-card li[data-v-b877440e]{display:flex;align-items:center;justify-content:space-between;gap:10px}@media (max-width:900px){.permission-columns[data-v-b877440e]{grid-template-columns:1fr}.editor-head[data-v-b877440e]{align-items:stretch;flex-direction:column}.permission-search[data-v-b877440e]{width:100%}.page-grid[data-v-b877440e]{grid-template-columns:1fr}.permission-summary[data-v-b877440e],.permission-rules[data-v-b877440e]{flex-direction:column}}@media (max-width:560px){.field-list label[data-v-b877440e]{align-items:stretch;flex-direction:column}.field-list select[data-v-b877440e]{width:100%;min-height:44px;font-size:16px}}.permission-editor[data-v-b877440e]{gap:12px;padding:14px 16px 16px}.editor-head[data-v-b877440e]{align-items:center}.editor-head h3[data-v-b877440e]{color:var(--navy);font-size:14px}.permission-search input[data-v-b877440e]{min-height:38px;padding:7px 10px;border:1px solid var(--line-strong);border-radius:6px;background:#fff;color:var(--text)}.permission-summary[data-v-b877440e],.permission-rules[data-v-b877440e]{align-items:baseline;border:0;border-radius:5px}.permission-summary[data-v-b877440e]{border-left:3px solid var(--blue);background:var(--blue-soft);color:var(--body)}.permission-readonly[data-v-b877440e]{padding:9px 12px;border-left:3px solid var(--warning);background:#fff8e8;color:var(--muted);font-size:11px}.permission-summary strong[data-v-b877440e],.permission-rules strong[data-v-b877440e]{flex:none;color:var(--navy);font-size:11px}.permission-rules[data-v-b877440e]{padding-top:8px;padding-bottom:8px;background:#f7f9fb}.permission-columns[data-v-b877440e]{grid-template-columns:minmax(0,1.55fr) minmax(300px,1fr);gap:16px}.permission-column[data-v-b877440e]{align-content:start}.column-head[data-v-b877440e]{min-height:42px;align-items:centeLine truncated
+1
View File
@@ -0,0 +1 @@
import{d as It,u as Gt,c as n,b as e,q as me,v as Fe,t as i,e as f,F as W,x as ye,y as I,r as p,j as s,f as le,o as Qt,N as Jt,B as za,p as Et,l as Ha,w as _t,n as Ke,k as it,O as Fa,I as kt,m as k,H as rt,E as oe,G as Ka,P as gt,A as Tt,K as ua,h as ja,z as Lt,Q as da,g as qa,D as Wa}from"./index-CXCTlxVW.js";import{a as ie}from"./admin-C9Owgj_V.js";import{_ as Vt}from"./_plugin-vue_export-helper-DlAUqK2U.js";import{f as xt,d as pa}from"./feishuDirectory-BmPyCMe4.js";import{u as Yt,_ as Xt}from"./useListPagination-BTBVezsP.js";const Ze=c=>{const L=String(c.type||"").trim().toUpperCase();return L==="FIELD"?"field":L==="ACTION"||L==="BUTTON"?"action":L==="MODULE"?"module":L==="PAGE"?"page":L==="MENU"?c.code.startsWith("module.")||!c.parentCode?"module":"page":c.code.startsWith("application:")?"field":!c.code.startsWith("module.")&&!c.code.startsWith("page.")?"action":c.code.startsWith("module.")?"module":"page"},Ya=c=>{const L=new Map(c.map(m=>[m.code,{...m,children:[]}])),A=[];L.forEach(m=>{const N=m.parentCode?L.get(m.parentCode):void 0;N?N.children.push(m):A.push(m)});const E=m=>m.sort((N,P)=>N.code.localeCompare(P.code,"zh-CN")).forEach(N=>E(N.children));return E(A),A},Ot=c=>[c,...c.children.flatMap(Ot)],Xa=(c,L)=>{const A=Ot(c).filter(m=>Ze(m)!=="field"),E=A.filter(m=>(L[m.code]||"HIDDEN")!=="HIDDEN").length;return{checked:!!A.length&&E===A.length,indeterminate:E>0&&E<A.length}},Qa=(c,L,A)=>{const E={...A};return Ot(c).forEach(m=>{const N=Ze(m);N!=="field"&&(E[m.code]=L?N==="action"?"EDIT":"READ":"HIDDEN")}),E},Ja=c=>{const L={...(c==null?void 0:c.permissionAccess)||{}};return c!=null&&c.permissionAccess||((c==null?void 0:c.permissionCodes)||[]).forEach(A=>{L[A]="EDIT"}),Object.entries((c==null?void 0:c.fieldPermissions)||{}).forEach(([A,E])=>{L[A]=E}),L},Za=(c,L)=>{const A=new Set(L.filter(N=>Ze(N)==="field").map(N=>N.code)),E={...c},m=Object.fromEntries(Object.entries(c).filter(([N])=>A.has(N)));return{permissionAccess:E,permissionCodes:Object.entries(E).filter(([N,P])=>!A.has(N)&&P!=="HIDDEN").map(([N])=>N),fieldPermissions:m}},Q=c=>!!(c&&(c.groupCode==="DEFAULT_EMPLOYEE"||c.membershipMode==="DYNAMIC")),Ut=c=>(c==null?void 0:c.groupCode)==="SUPER_ADMIN_GROUP",ca=c=>[...c].sort((L,A)=>{const E=m=>Q(m)?0:Ut(m)?1:2;return E(L)-E(A)}),el=c=>c===null?"无法确认":String(c),tl=(c,L)=>!c.selectable||c.assignedGroupId!==null,ht=c=>`local:${c}`,va=c=>`directory:${JSON.stringify([c.generationId,c.openId])}`,al=c=>({generationId:c.generationId,openId:c.openId,...c.userId==null?{}:{userId:c.userId}}),ll={class:"permission-editor","aria-labelledby":"permission-editor-title"},sl={class:"editor-head"},nl={class:"permission-search"},ol={class:"permission-summary",role:"status"},il={key:0,class:"permission-readonly",role:"note"},rl={class:"permission-columns"},ul={class:"permission-column menu-column","aria-labelledby":"menu-permission-title"},dl={class:"column-head"},cl={key:0,class:"empty-state compact-empty"},vl={class:"branch-title"},pl=["checked",".indeterminate","disabled","onChange"],ml={class:"page-grid"},yl={class:"branch-title page-title"},bl=["checked",".indeterminate","disabled","onChange"],fl={key:0,class:"action-list","aria-label":"关键动作"},gl=["checked","disabled","onChange"],hl={key:1,class:"page-empty"},_l={class:"permission-column field-column","aria-labelledby":"field-permission-title"},kl={class:"column-head"},El={key:0,class:"empty-state compact-empty"},Il={class:"field-page-title"},Cl={class:"field-list"},Sl=["value","aria-label","disabled","onChange"],Al={key:1,class:"compatibility-card","aria-labelledby":"compat-title"},wl=["value","aria-label","disabled","onChange"],$l=It({__name:"RolePermissionEditor",props:{catalog:{},modelValue:{}},emits:["update:modelValue"],setup(c,{emit:L}){const A=c,E=L,m=Gt(),N=I(()=>m.canEdit("system.role.permission.configure")),P=p(""),U=I(()=>Ya(A.catalog)),j=I(()=>new Set(A.catalog.map(y=>y.code))),V=I(()=>Object.entries(A.modelValue).filter(([y])=>!j.value.has(y)).map(([y,v])=>({code:y,level:v}))),T=I(()=>P.value.trim().toLocaleLowerCase()),se=y=>!T.value||`${y.name} ${y.code}`.toLocaleLowerCase().includes(T.value),te=y=>Ot(y).slice(1),H=y=>Ze(y)!=="field"&&se(y)||y.children.some(H),F=I(()=>U.value.filter(H)),q=y=>y.children.filter(v=>Ze(v)!=="field"&&(se(y)||H(v))),J=(y,v)=>te(y).filter($=>Ze($)==="action"&&(se(v)||se(y)||se($))),ve=I(()=>U.value.map(y=>({code:y.code,name:y.name,pages:y.children.map(v=>({code:v.code,name:v.name,fields:te(v).filter($=>Ze($)==="field")})).filter(v=>v.fields.length)})).filter(y=>y.pages.length)),x=I(()=>ve.value.map(y=>{const v=se(y),$=y.pages.map(d=>{const w=v||se(d);return{...d,fields:w?d.fields:d.fields.filter(se)}}).filter(d=>d.fields.length);return{...y,pages:$}}).filter(y=>y.pages.length)),re=y=>A.modelValue[y]||"HIDDEN",Se=(y,v)=>{N.value&&E("update:modelValue",{...A.modelValue,[y]:v})},ke=y=>Xa(y,A.modelValue),Ge=(y,v)=>{N.value&&E("update:modelValue",Qa(y,v.target.checked,A.modelValue))},we=I(()=>F.value.reduce((yLine truncated
+1
View File
@@ -0,0 +1 @@
const s=(t,r)=>{const o=t.__vccOpts||t;for(const[c,e]of r)o[c]=e;return o};export{s as _};
+1
View File
@@ -0,0 +1 @@
import{M as s}from"./index-CXCTlxVW.js";const r={listRoles:()=>s.get("/roles"),createRole:e=>s.post("/roles",e),updateRole:(e,i)=>s.put(`/roles/${e}`,i),deleteRole:e=>s.delete(`/roles/${e}`),listPermissions:()=>s.get("/roles/permissions"),getRolePermissions:e=>s.get(`/roles/${e}/permissions`),updateRolePermissions:(e,i)=>s.put(`/roles/${e}/permissions`,i),listGroups:()=>s.get("/user-groups"),createGroup:e=>s.post("/user-groups",e),updateGroup:(e,i)=>s.put(`/user-groups/${e}`,i),deleteGroup:e=>s.delete(`/user-groups/${e}`),getGroupRoles:e=>s.get(`/user-groups/${e}/roles`),updateGroupRoles:(e,i)=>s.put(`/user-groups/${e}/roles`,i,{suppressErrorNotification:!0}),getGroupMembers:e=>s.get(`/user-groups/${e}/members`),updateGroupMembers:(e,i)=>s.put(`/user-groups/${e}/members`,i,{suppressErrorNotification:!0}),listCandidates:(e,i)=>{const n=i==null?void 0:i.trim(),t={...e===void 0?{}:{groupId:e},...n?{q:n}:{}};return s.get("/user-groups/candidates",Object.keys(t).length?{params:t}:void 0)},searchGroupMemberCandidates:(e,i="")=>s.get(`/user-groups/${e}/member-candidates`,{params:{q:i.trim()}}),getIntegrationConfig:()=>s.get("/integrations/config"),updateIntegrationConfig:(e,i,n)=>s.put("/integrations/config",{provider:e,enabled:i,values:n}),testIntegration:e=>s.post("/integrations/config/test",{provider:e}),syncFeishuApprovalDefinition:()=>s.post("/feishu/approval/definition/sync",void 0,{suppressErrorNotification:!0}),listKingdeeSyncConfigs:()=>s.get("/integrations/kingdee/sync-configs"),createKingdeeSyncConfig:e=>s.post("/integrations/kingdee/sync-configs",e),getKingdeeSyncConfig:e=>s.get(`/integrations/kingdee/sync-configs/${e}`),updateKingdeeSyncConfig:(e,i)=>s.put(`/integrations/kingdee/sync-configs/${e}`,i),deleteKingdeeSyncConfig:e=>s.delete(`/integrations/kingdee/sync-configs/${e}`),previewKingdeeSyncConfig:e=>s.post(`/integrations/kingdee/sync-configs/${e}/preview`),prepareKingdeeSyncTable:e=>s.post(`/integrations/kingdee/sync-configs/${e}/prepare-table`),syncKingdeeConfig:e=>s.post(`/integrations/kingdee/sync-configs/${e}/sync`),listKingdeeSyncRuns:e=>s.get(`/integrations/kingdee/sync-configs/${e}/runs`)};export{r as a};
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

+1
View File
@@ -0,0 +1 @@
import{M as i}from"./index-CXCTlxVW.js";const o=t=>t.availabilityState==="AVAILABLE"||t.availabilityState==="NEVER_SYNCED"||t.availabilityState==="UNAVAILABLE"?t.availabilityState:t.snapshotState==="FRESH"?"AVAILABLE":t.snapshotState==="NEVER_SYNCED"?"NEVER_SYNCED":"UNAVAILABLE",s=36e4,n={sync:t=>i.post("/feishu/directory/sync",void 0,{timeout:s,signal:t}),status:t=>i.get("/feishu/directory/status",{signal:t}),organization:(t,a=!1)=>i.get("/feishu/directory/organization",{signal:t,params:{includeUsers:a}}),organizationMembers:(t,a,r=!0)=>i.get("/feishu/directory/organization/members",{signal:a,params:{departmentId:t,includeDescendants:r}})};export{o as d,n as f};
+1
View File
@@ -0,0 +1 @@
:root{--el-color-white:#fff;--el-color-black:#000;--el-color-primary-rgb:64, 158, 255;--el-color-success-rgb:103, 194, 58;--el-color-warning-rgb:230, 162, 60;--el-color-danger-rgb:245, 108, 108;--el-color-error-rgb:245, 108, 108;--el-color-info-rgb:144, 147, 153;--el-font-size-extra-large:20px;--el-font-size-large:18px;--el-font-size-medium:16px;--el-font-size-base:14px;--el-font-size-small:13px;--el-font-size-extra-small:12px;--el-font-family:"Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;--el-font-weight-primary:500;--el-font-line-height-primary:24px;--el-index-normal:1;--el-index-top:1000;--el-index-popper:2000;--el-border-radius-base:4px;--el-border-radius-small:2px;--el-border-radius-round:20px;--el-border-radius-circle:100%;--el-transition-duration:.3s;--el-transition-duration-fast:.2s;--el-transition-function-ease-in-out-bezier:cubic-bezier(.645, .045, .355, 1);--el-transition-function-fast-bezier:cubic-bezier(.23, 1, .32, 1);--el-transition-all:all var(--el-transition-duration) var(--el-transition-function-ease-in-out-bezier);--el-transition-fade:opacity var(--el-transition-duration) var(--el-transition-function-fast-bezier);--el-transition-md-fade:transform var(--el-transition-duration) var(--el-transition-function-fast-bezier), opacity var(--el-transition-duration) var(--el-transition-function-fast-bezier);--el-transition-fade-linear:opacity var(--el-transition-duration-fast) linear;--el-transition-border:border-color var(--el-transition-duration-fast) var(--el-transition-function-ease-in-out-bezier);--el-transition-box-shadow:box-shadow var(--el-transition-duration-fast) var(--el-transition-function-ease-in-out-bezier);--el-transition-color:color var(--el-transition-duration-fast) var(--el-transition-function-ease-in-out-bezier);--el-component-size-large:40px;--el-component-size:32px;--el-component-size-small:24px;--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--el-color-primary:#409eff;--el-color-primary-light-3:#79bbff;--el-color-primary-light-5:#a0cfff;--el-color-primary-light-7:#c6e2ff;--el-color-primary-light-8:#d9ecff;--el-color-primary-light-9:#ecf5ff;--el-color-primary-dark-2:#337ecc;--el-color-success:#67c23a;--el-color-success-light-3:#95d475;--el-color-success-light-5:#b3e19d;--el-color-success-light-7:#d1edc4;--el-color-success-light-8:#e1f3d8;--el-color-success-light-9:#f0f9eb;--el-color-success-dark-2:#529b2e;--el-color-warning:#e6a23c;--el-color-warning-light-3:#eebe77;--el-color-warning-light-5:#f3d19e;--el-color-warning-light-7:#f8e3c5;--el-color-warning-light-8:#faecd8;--el-color-warning-light-9:#fdf6ec;--el-color-warning-dark-2:#b88230;--el-color-danger:#f56c6c;--el-color-danger-light-3:#f89898;--el-color-danger-light-5:#fab6b6;--el-color-danger-light-7:#fcd3d3;--el-color-danger-light-8:#fde2e2;--el-color-danger-light-9:#fef0f0;--el-color-danger-dark-2:#c45656;--el-color-error:#f56c6c;--el-color-error-light-3:#f89898;--el-color-error-light-5:#fab6b6;--el-color-error-light-7:#fcd3d3;--el-color-error-light-8:#fde2e2;--el-color-error-light-9:#fef0f0;--el-color-error-dark-2:#c45656;--el-color-info:#909399;--el-color-info-light-3:#b1b3b8;--el-color-info-light-5:#c8c9cc;--el-color-info-light-7:#dedfe0;--el-color-info-light-8:#e9e9eb;--el-color-info-light-9:#f4f4f5;--el-color-info-dark-2:#73767a;--el-bg-color:#fff;--el-bg-color-page:#f2f3f5;--el-bg-color-overlay:#fff;--el-text-color-primary:#303133;--el-text-color-regular:#606266;--el-text-color-secondary:#909399;--el-text-color-placeholder:#a8abb2;--el-text-color-disabled:#c0c4cc;--el-border-color:#dcdfe6;--el-border-color-light:#e4e7ed;--el-border-color-lighter:#ebeef5;--el-border-color-extra-light:#f2f6fc;--el-border-color-dark:#d4d7de;--el-border-color-darker:#cdd0d6;--el-fill-color:#f0f2f5;--el-fill-color-light:#f5f7fa;--el-fill-color-lighter:#fafafa;--el-fill-color-extra-light:#fafcff;--el-fill-color-dark:#ebedf0;--el-fill-color-darker:#e6e8eb;--el-fill-color-blank:#fff;--el-box-shadow:0px 12px 32px 4px #0000000a, 0px 8px 20px #00000014;--el-box-shadow-light:0px 0px 12px #0000001f;--el-box-shadow-lighter:0px 0px 6px #0000001f;--el-box-shadow-dark:0px 16px 48px 16px #00000014, 0px 12px 32px #0000001f, 0px 8px 16px -8px #00000029;--el-disabled-bg-color:var(--el-fill-color-light);--el-disabled-text-color:var(--el-text-color-placeholder);--el-disabled-border-color:var(--el-border-color-light);--el-overlay-color:#000c;--el-overlay-color-light:#000000b3;--el-overlay-color-lighter:#00000080;--el-mask-color:#ffffffe6;--el-mask-color-extra-light:#ffffff4d;--el-border-width:1px;--el-border-style:solid;--el-border-color-hover:var(--el-text-color-disabled);--el-border:var(--el-border-width) var(--el-border-style) var(--el-border-color);--el-svg-monochrome-grey:var(--el-border-color)}.fade-in-linear-enter-active,.fade-in-linear-leave-active{transition:var(--el-transition-fade-linear)}.fade-in-linear-enter-from,.fade-in-linear-leave-to{opacity:0}.el-Line truncated
+101
View File
@@ -0,0 +1,101 @@
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Layout-DdioVC-1.js","assets/_plugin-vue_export-helper-DlAUqK2U.js","assets/Layout-CJcHDlfg.css","assets/Applications-DGthee3d.js","assets/useListPagination-BTBVezsP.js","assets/ReimbursementForm-CbZhelW2.js","assets/feishuDirectory-BmPyCMe4.js","assets/ReimbursementForm-5SgtrqLX.css","assets/ApplicationDetail-rMAybPuv.js","assets/ApplicationDetail-BF_Dd4fL.css","assets/FinanceReceipt-KvOQKX8l.js","assets/Sources-wU15iXEo.js","assets/Payments-CKaVaFZj.js","assets/Payments-CuwJVGQD.css","assets/Logs-DnbqcxT8.js","assets/Logs-BZtnCaMO.css","assets/ExpenseTypes-D9imPj3p.js","assets/Payees-Dvbc8Wvp.js","assets/Users-KkxvzObE.js","assets/admin-C9Owgj_V.js","assets/Users-DnaquuV_.css","assets/IntegrationConfig-CzZwjqVQ.js","assets/IntegrationConfig-BA1PArOj.css"])))=>i.map(i=>d[i]);
(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))a(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const l of r.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&a(l)}).observe(document,{childList:!0,subtree:!0});function n(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function a(o){if(o.ep)return;o.ep=!0;const r=n(o);fetch(o.href,r)}})();/**
* @vue/shared v3.5.42
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/function th(e){const t=Object.create(null);for(const n of e.split(","))t[n]=1;return n=>n in t}const wn={},$s=[],ht=()=>{},G3=()=>!1,lf=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),sf=e=>e.startsWith("onUpdate:"),jn=Object.assign,nh=(e,t)=>{const n=e.indexOf(t);n>-1&&e.splice(n,1)},dC=Object.prototype.hasOwnProperty,Dt=(e,t)=>dC.call(e,t),we=Array.isArray,al=e=>Ku(e)==="[object Map]",Sr=e=>Ku(e)==="[object Set]",ll=e=>Ku(e)==="[object Date]",Ue=e=>typeof e=="function",Be=e=>typeof e=="string",qa=e=>typeof e=="symbol",it=e=>e!==null&&typeof e=="object",sl=e=>(it(e)||Ue(e))&&Ue(e.then)&&Ue(e.catch),X3=Object.prototype.toString,Ku=e=>X3.call(e),fC=e=>Ku(e).slice(8,-1),du=e=>Ku(e)==="[object Object]",uf=e=>Be(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,Ji=th(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),cf=e=>{const t=Object.create(null);return n=>t[n]||(t[n]=e(n))},pC=/-\w/g,ta=cf(e=>e.replace(pC,t=>t.slice(1).toUpperCase())),hC=/\B([A-Z])/g,Or=cf(e=>e.replace(hC,"-$1").toLowerCase()),ju=cf(e=>e.charAt(0).toUpperCase()+e.slice(1)),Bl=cf(e=>e?`on${ju(e)}`:""),Fo=(e,t)=>!Object.is(e,t),Gc=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},J3=(e,t,n,a=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:a,value:n})},df=e=>{const t=parseFloat(e);return isNaN(t)?e:t},vC=e=>{const t=Be(e)?Number(e):NaN;return isNaN(t)?e:t};let Cm;const ff=()=>Cm||(Cm=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function Ye(e){if(we(e)){const t={};for(let n=0;n<e.length;n++){const a=e[n],o=Be(a)?bC(a):Ye(a);if(o)for(const r in o)t[r]=o[r]}return t}else if(Be(e)||it(e))return e}const mC=/;(?![^(]*\))/g,gC=/:([^]+)/,yC=/\/\*[^]*?\*\//g;function bC(e){const t={};return e.replace(yC,"").split(mC).forEach(n=>{if(n){const a=n.split(gC);a.length>1&&(t[a[0].trim()]=a[1].trim())}}),t}function I(e){let t="";if(Be(e))t=e;else if(we(e))for(let n=0;n<e.length;n++){const a=I(e[n]);a&&(t+=a+" ")}else if(it(e))for(const n in e)e[n]&&(t+=n+" ");return t.trim()}function mr(e){if(!e)return null;let{class:t,style:n}=e;return t&&!Be(t)&&(e.class=I(t)),n&&(e.style=Ye(n)),e}const wC="itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly",_C=th(wC);function Z3(e){return!!e||e===""}function CC(e,t){if(e.length!==t.length)return!1;let n=!0;for(let a=0;n&&a<e.length;a++)n=wo(e[a],t[a]);return n}function Sm(e,t){if(e.size!==t.size)return!1;const n=Array.from(t),a=new Uint8Array(n.length);for(const o of e){let r=-1;for(let l=0;l<n.length;l++)if(!a[l]&&wo(o,n[l])){r=l;break}if(r<0)return!1;a[r]=1}return!0}function wo(e,t){if(e===t)return!0;let n=ll(e),a=ll(t);if(n||a)return n&&a?e.getTime()===t.getTime():!1;if(n=qa(e),a=qa(t),n||a)return e===t;if(n=we(e),a=we(t),n||a)return n&&a?CC(e,t):!1;if(n=it(e),a=it(t),n||a){if(!n||!a)return!1;if(n=al(e),a=al(t),n||a||(n=Sr(e),a=Sr(t),n||a))return n&&a?Sm(e,t):!1;const o=Object.keys(e).length,r=Object.keys(t).length;if(o!==r)return!1;for(const l in e){const s=e.hasOwnProperty(l),u=t.hasOwnProperty(l);if(s&&!u||!s&&u||!wo(e[l],t[l]))return!1}}return String(e)===String(t)}function ah(e,t){return e.findIndex(n=>wo(n,t))}const Q3=e=>!!(e&&e.__v_isRef===!0),Ee=e=>Be(e)?e:e==null?"":we(e)||it(e)&&(e.toString===X3||!Ue(e.toString))?Q3(e)?Ee(e.value):JSON.stringify(e,e6,2):String(e),e6=(e,t)=>Q3(t)?e6(e,t.value):al(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((n,[a,o],r)=>(n[v0(a,r)+" =>"]=o,n),{})}:Sr(t)?{[`Set(${t.size})`]:[...t.values()].map(n=>v0(n))}:qa(t)?v0(t):it(t)&&!we(t)&&!du(t)?String(t):t,v0=(e,t="")=>{var n;return qa(e)?`Symbol(${(n=e.description)!=null?n:t})`:e};/**
* @vue/reactivity v3.5.42
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/let Yn;class t6{constructor(t=!1){this.detached=t,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!t&&Yn&&(Yn.active?(this.parent=Yn,this.index=(Yn.scopes||(Yn.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let t,n;if(this.scopes){const a=this.scopes.slice();for(t=0,n=a.length;t<n;t++)a[t].pause()}for(t=0,n=this.effects.length;t<n;t++)this.effects[t].pause()}}resume(){if(this._active&&this._isPaused){this._isPaused=!1;let t,n;if(this.scopes){const o=this.scopes.slice();for(t=0,n=o.length;t<n;t++)o[t].resume()}const a=this.effects.slice();for(t=0,n=a.length;t<n;t++)a[t].resume()}}run(t){if(this._active){const n=Yn;try{return Yn=this,t()}finally{Yn=n}}}on(){++this._on===1&&(this.prevScope=Yn,Yn=this)}off(){if(this._on>0&&--this._on===0){if(Yn===this)Yn=this.prevScope;else{let t=Yn;for(;t;){if(t.prevScope===this){t.prevScope=this.prevScope;break}t=t.prevScope}}this.prevScope=void 0}}stop(t){if(this._active){this._active=!1;let n,a;for(n=0,a=this.effects.length;n<a;n++)this.effects[n].stop();for(this.effects.length=0,n=0,a=this.cleanups.length;n<a;n++)this.cleanups[n]();if(this.cleanups.length=0,this.scopes){const o=this.scopes.slice();for(n=0,a=o.length;n<a;n++)o[n].stop(!0);this.scopes.length=0}if(!this.detached&&this.parent&&!t){const o=this.parent.scopes.pop();o&&o!==this&&(this.parent.scopes[this.index]=o,o.index=this.index)}this.parent=void 0}}}function oh(e){return new t6(e)}function pf(){return Yn}function rh(e,t=!1){Yn&&Yn.cleanups.push(e)}let xn;const m0=new WeakSet;class n6{constructor(t){this.fn=t,this.deps=void 0,this.depsTail=void 0,this.flags=5,this.next=void 0,this.cleanup=void 0,this.scheduler=void 0,Yn&&(Yn.active?Yn.effects.push(this):this.flags&=-2)}pause(){this.flags|=64}resume(){this.flags&64&&(this.flags&=-65,m0.has(this)&&(m0.delete(this),this.trigger()))}notify(){this.flags&2&&!(this.flags&32)||this.flags&8||o6(this)}run(){if(!(this.flags&1))return this.fn();this.flags|=2,xm(this),r6(this);const t=xn,n=mo;xn=this,mo=!0;try{return this.fn()}finally{l6(this),xn=t,mo=n,this.flags&=-3}}stop(){if(this.flags&1){for(let t=this.deps;t;t=t.nextDep)ih(t);this.deps=this.depsTail=void 0,xm(this),this.onStop&&this.onStop(),this.flags&=-2}}trigger(){this.flags&64?m0.add(this):this.scheduler?this.scheduler():this.runIfDirty()}runIfDirty(){Tp(this)&&this.run()}get dirty(){return Tp(this)}}let a6=0,Zi,Qi;function o6(e,t=!1){if(e.flags|=8,t){e.next=Qi,Qi=e;return}e.next=Zi,Zi=e}function lh(){a6++}function sh(){if(--a6>0)return;if(Qi){let t=Qi;for(Qi=void 0;t;){const n=t.next;t.next=void 0,t.flags&=-9,t=n}}let e;for(;Zi;){let t=Zi;for(Zi=void 0;t;){const n=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(a){e||(e=a)}t=n}}if(e)throw e}function r6(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function l6(e){let t,n=e.depsTail,a=n;for(;a;){const o=a.prevDep;a.version===-1?(a===n&&(n=o),ih(a),SC(a)):t=a,a.dep.activeLink=a.prevActiveLink,a.prevActiveLink=void 0,a=o}e.deps=t,e.depsTail=n}function Tp(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(s6(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function s6(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===fu)||(e.globalVersion=fu,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!Tp(e))))return;e.flags|=2;const t=e.dep,n=xn,a=mo;xn=e,mo=!0;try{r6(e);const o=e.fn(e._value);(t.version===0||Fo(o,e._value))&&(e.flags|=128,e._value=o,t.version++)}catch(o){throw t.version++,o}finally{xn=n,mo=a,l6(e),e.flags&=-3}}function ih(e,t=!1){const{dep:n,prevSub:a,nextSub:o}=e;if(a&&(a.nextSub=o,e.prevSub=void 0),o&&(o.prevSub=a,e.nextSub=void 0),n.subs===e&&(n.subs=a,!a&&n.computed)){n.computed.flags&=-5;for(let r=n.computed.deps;r;r=r.nextDep)ih(r,!0)}!t&&!--n.sc&&n.map&&n.map.delete(n.key)}function SC(e){const{prevDep:t,nextDep:n}=e;t&&(t.nextDep=n,e.prevDep=void 0),n&&(n.prevDep=t,e.nextDep=void 0)}let mo=!0;const i6=[];function xr(){i6.push(mo),mo=!1}function kr(){const e=i6.pop();mo=e===void 0?!0:e}function xm(e){const{cleanup:t}=e;if(e.cleanup=void 0,t){const n=xn;xn=void 0;try{t()}finally{xn=n}}}let fu=0;class xC{constructor(t,n){this.sub=t,this.dep=n,this.version=n.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class uh{constructor(t){this.computed=t,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(t){if(!xn||!mo||xn===this.computed)return;let n=this.activeLink;if(n===void 0||n.sub!==xn)n=this.activeLink=new xC(xn,this),xn.deps?(n.prevDep=xn.depsTail,xn.depsTail.nextDep=n,xn.depsTail=n):xn.deps=xn.depsTail=n,u6(n);else if(n.version===-1&&(n.version=this.version,n.nextDep)){const a=n.nextDep;a.prevDep=n.prevDep,n.prevDep&&(n.prevDep.nextDep=a),n.prevDep=xn.depsTailLine truncated
* @vue/runtime-core v3.5.42
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/function Wu(e,t,n,a){try{return a?e(...a):e()}catch(o){wf(o,t,n)}}function ro(e,t,n,a){if(Ue(e)){const o=Wu(e,t,n,a);return o&&sl(o)&&o.catch(r=>{wf(r,t,n)}),o}if(we(e)){const o=[];for(let r=0;r<e.length;r++)o.push(ro(e[r],t,n,a));return o}}function wf(e,t,n,a=!0){const o=t?t.vnode:null,{errorHandler:r,throwUnhandledErrorInProduction:l}=t&&t.appContext.config||wn;if(t){let s=t.parent;const u=t.proxy,c=`https://vuejs.org/error-reference/#runtime-${n}`;for(;s;){const d=s.ec;if(d){for(let f=0;f<d.length;f++)if(d[f](e,u,c)===!1)return}s=s.parent}if(r){xr(),Wu(r,null,10,[e,u,c]),kr();return}}GC(e,n,o,a,l)}function GC(e,t,n,a=!0,o=!1){if(o)throw e;console.error(e)}const xa=[];let Do=-1;const Ps=[];let Jr=null,Ts=0;const _6=Promise.resolve();let wd=null;function Ie(e){const t=wd||_6;return e?t.then(this?e.bind(this):e):t}function XC(e){let t=Do+1,n=xa.length;for(;t<n;){const a=t+n>>>1,o=xa[a],r=hu(o);r<e||r===e&&o.flags&2?t=a+1:n=a}return t}function ch(e){if(!(e.flags&1)){const t=hu(e),n=xa[xa.length-1];!n||!(e.flags&2)&&t>=hu(n)?xa.push(e):xa.splice(XC(t),0,e),e.flags|=1,C6()}}function C6(){wd||(wd=_6.then(x6))}function JC(e){if(!we(e))Jr&&e.id===-1?Jr.splice(Ts+1,0,e):e.flags&1||(Ps.push(e),e.flags|=1);else for(let t=0;t<e.length;t++)Ps.push(e[t]);C6()}function Em(e,t,n=Do+1){for(;n<xa.length;n++){const a=xa[n];if(a&&a.flags&2){if(e&&a.id!==e.uid)continue;xa.splice(n,1),n--,a.flags&4&&(a.flags&=-2),a(),a.flags&4||(a.flags&=-2)}}}function S6(e){if(Ps.length){const t=[...new Set(Ps)].sort((n,a)=>hu(n)-hu(a));if(Ps.length=0,Jr){for(let n=0;n<t.length;n++)Jr.push(t[n]);return}for(Jr=t,Ts=0;Ts<Jr.length;Ts++){const n=Jr[Ts];n.flags&4&&(n.flags&=-2),n.flags&8||n(),n.flags&=-2}Jr=null,Ts=0}}const hu=e=>e.id==null?e.flags&2?-1:1/0:e.id;function x6(e){try{for(Do=0;Do<xa.length;Do++){const t=xa[Do];t&&!(t.flags&8)&&(t.flags&4&&(t.flags&=-2),Wu(t,t.i,t.i?15:14),t.flags&4||(t.flags&=-2))}}finally{for(;Do<xa.length;Do++){const t=xa[Do];t&&(t.flags&=-2)}Do=-1,xa.length=0,S6(),wd=null,(xa.length||Ps.length)&&x6()}}let aa=null,k6=null;function _d(e){const t=aa;return aa=e,k6=e&&e.type.__scopeId||null,t}function re(e,t=aa,n){if(!t||e._n)return e;const a=(...o)=>{a._d&&kd(-1);const r=_d(t),l=yr.length;let s;try{s=e(...o)}finally{for(let u=yr.length;u>l;u--)_h();_d(r),a._d&&kd(1)}return s};return a._n=!0,a._c=!0,a._d=!0,a}function vt(e,t){if(aa===null)return e;const n=Ef(aa),a=e.dirs||(e.dirs=[]);for(let o=0;o<t.length;o++){let[r,l,s,u=wn]=t[o];r&&(Ue(r)&&(r={mounted:r,updated:r}),r.deep&&pr(l),a.push({dir:r,instance:n,value:l,oldValue:void 0,arg:s,modifiers:u}))}return e}function yl(e,t,n,a){const o=e.dirs,r=t&&t.dirs;for(let l=0;l<o.length;l++){const s=o[l];r&&(s.oldValue=r[l].value);let u=s.dir[a];u&&(xr(),ro(u,n,8,[e.el,s,e,t]),kr())}}function Tt(e,t){if(pa){let n=pa.provides;const a=pa.parent&&pa.parent.provides;a===n&&(n=pa.provides=Object.create(a)),n[e]=t}}function Le(e,t,n=!1){const a=gt();if(a||zl){let o=zl?zl._context.provides:a?a.parent==null||a.ce?a.vnode.appContext&&a.vnode.appContext.provides:a.parent.provides:void 0;if(o&&e in o)return o[e];if(arguments.length>1)return n&&Ue(t)?t.call(a&&a.proxy):t}}function dh(){return!!(gt()||zl)}const ZC=Symbol.for("v-scx"),QC=()=>Le(ZC);function ma(e,t){return fh(e,null,t)}function fe(e,t,n){return fh(e,t,n)}function fh(e,t,n=wn){const{immediate:a,deep:o,flush:r,once:l}=n,s=jn({},n),u=t&&a||!t&&r!=="post";let c;if(yu){if(r==="sync"){const m=QC();c=m.__watcherHandles||(m.__watcherHandles=[])}else if(!u){const m=()=>{};return m.stop=ht,m.resume=ht,m.pause=ht,m}}const d=pa;s.call=(m,v,h)=>ro(m,d,v,h);let f=!1;r==="post"?s.scheduler=m=>{Ca(m,d&&d.suspense)}:r!=="sync"&&(f=!0,s.scheduler=(m,v)=>{v?m():ch(m)}),s.augmentJob=m=>{t&&(m.flags|=4),f&&(m.flags|=2,d&&(m.id=d.uid,m.i=d))};const p=YC(e,t,s);return yu&&(c?c.push(p):u&&p()),p}function eS(e,t,n){const a=this.proxy,o=Be(e)?e.includes(".")?E6(a,e):()=>a[e]:e.bind(a,a);let r;Ue(t)?r=t:(r=t.handler,n=t);const l=Uu(this),s=fh(o,r.bind(a),n);return l(),s}function E6(e,t){const n=t.split(".");return()=>{let a=e;for(let o=0;o<n.length&&a;o++)a=a[n[o]];return a}}const jr=new WeakMap,T6=Symbol("_vte"),_f=e=>e.__isTeleport,Tl=e=>e&&(e.disabled||e.disabled===""),tS=e=>e&&(e.defer||e.defer===""),Tm=e=>typeof SVGElement<"u"&&e instanceof SVGElement,Mm=e=>typeof MathMLElement=="function"&&e instanceof MathMLElement,Ap=(e,t)=>{const n=e&&e.to;return Be(n)?t?t(n):null:n},nS={name:"Teleport",__isTeleport:!0,process(e,t,n,a,o,r,l,s,u,c){const{mc:d,pc:f,pbc:p,o:{insert:m,querySelector:v,createText:h,createComment:g,parentNode:y}}=c,b=Tl(t.props);let{dynamicChildren:C}=t;const w=(M,E,T)=>{M.shapeFlag&16&&d(M.children,E,T,o,r,l,s,u)},S=(M=t)=>{const E=Tl(M.props),T=M.target=Ap(M.props,v),N=Rp(T,M,h,m);T&&(l!=="svg"&&Tm(T)?l="svg":l!=="mathml"&&Mm(T)&&(l="mathml"),o&&o.isCE&&(o.ce._teleportTargets||(o.ce._teleportTargets=new Set)).add(T),E||(w(M,T,N),Hi(M,!1)))},k=M=>{const E=()=>{if(jr.get(M)===E){if(jr.delete(M),Tl(M.props)){const T=y(M.el)||n;w Line truncated
* @vue/runtime-dom v3.5.42
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/let Lp;const Fm=typeof window<"u"&&window.trustedTypes;if(Fm)try{Lp=Fm.createPolicy("vue",{createHTML:e=>e})}catch{}const ly=Lp?e=>Lp.createHTML(e):e=>e,XS="http://www.w3.org/2000/svg",JS="http://www.w3.org/1998/Math/MathML",ur=typeof document<"u"?document:null,Km=ur&&ur.createElement("template"),ZS={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,a)=>{const o=t==="svg"?ur.createElementNS(XS,e):t==="mathml"?ur.createElementNS(JS,e):n?ur.createElement(e,{is:n}):ur.createElement(e);return e==="select"&&a&&a.multiple!=null&&o.setAttribute("multiple",a.multiple),o},createText:e=>ur.createTextNode(e),createComment:e=>ur.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>ur.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,n,a,o,r){const l=n?n.previousSibling:t.lastChild;if(o&&(o===r||o.nextSibling))for(;t.insertBefore(o.cloneNode(!0),n),!(o===r||!(o=o.nextSibling)););else{Km.innerHTML=ly(a==="svg"?`<svg>${e}</svg>`:a==="mathml"?`<math>${e}</math>`:e);const s=Km.content;if(a==="svg"||a==="mathml"){const u=s.firstChild;for(;u.firstChild;)s.appendChild(u.firstChild);s.removeChild(u)}t.insertBefore(s,n)}return[l?l.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},Hr="transition",Mi="animation",js=Symbol("_vtc"),sy={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},iy=jn({},O6,sy),QS=e=>(e.displayName="Transition",e.props=iy,e),Gn=QS((e,{slots:t})=>Je(rS,uy(e),t)),wl=(e,t=[])=>{we(e)?e.forEach(n=>n(...t)):e&&e(...t)},jm=e=>e?we(e)?e.some(t=>t.length>1):e.length>1:!1;function uy(e){const t={};for(const $ in e)$ in sy||(t[$]=e[$]);if(e.css===!1)return t;const{name:n="v",type:a,duration:o,enterFromClass:r=`${n}-enter-from`,enterActiveClass:l=`${n}-enter-active`,enterToClass:s=`${n}-enter-to`,appearFromClass:u=r,appearActiveClass:c=l,appearToClass:d=s,leaveFromClass:f=`${n}-leave-from`,leaveActiveClass:p=`${n}-leave-active`,leaveToClass:m=`${n}-leave-to`}=e,v=ex(o),h=v&&v[0],g=v&&v[1],{onBeforeEnter:y,onEnter:b,onEnterCancelled:C,onLeave:w,onLeaveCancelled:S,onBeforeAppear:k=y,onAppear:M=b,onAppearCancelled:E=C}=t,T=($,V,U,D)=>{$._enterCancelled=D,Wr($,V?d:s),Wr($,V?c:l),U&&U()},N=($,V)=>{$._isLeaving=!1,Wr($,f),Wr($,m),Wr($,p),V&&V()},P=$=>(V,U)=>{const D=$?M:b,F=()=>T(V,$,U);wl(D,[V,F]),Wm(()=>{Wr(V,$?u:r),Bo(V,$?d:s),jm(D)||qm(V,a,h,F)})};return jn(t,{onBeforeEnter($){wl(y,[$]),Bo($,r),Bo($,l)},onBeforeAppear($){wl(k,[$]),Bo($,u),Bo($,c)},onEnter:P(!1),onAppear:P(!0),onLeave($,V){$._isLeaving=!0;const U=()=>N($,V);Bo($,f),$._enterCancelled?(Bo($,p),Vp($)):(Vp($),Bo($,p)),Wm(()=>{$._isLeaving&&(Wr($,f),Bo($,m),jm(w)||qm($,a,g,U))}),wl(w,[$,U])},onEnterCancelled($){T($,!1,void 0,!0),wl(C,[$])},onAppearCancelled($){T($,!0,void 0,!0),wl(E,[$])},onLeaveCancelled($){N($),wl(S,[$])}})}function ex(e){if(e==null)return null;if(it(e))return[C0(e.enter),C0(e.leave)];{const t=C0(e);return[t,t]}}function C0(e){return vC(e)}function Bo(e,t){t.split(/\s+/).forEach(n=>n&&e.classList.add(n)),(e[js]||(e[js]=new Set)).add(t)}function Wr(e,t){t.split(/\s+/).forEach(a=>a&&e.classList.remove(a));const n=e[js];n&&(n.delete(t),n.size||(e[js]=void 0))}function Wm(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}let tx=0;function qm(e,t,n,a){const o=e._endId=++tx,r=()=>{o===e._endId&&a()};if(n!=null)return setTimeout(r,n);const{type:l,timeout:s,propCount:u}=cy(e,t);if(!l)return a();const c=l+"end";let d=0;const f=()=>{e.removeEventListener(c,p),r()},p=m=>{m.target===e&&++d>=u&&f()};setTimeout(()=>{d<u&&f()},s+1),e.addEventListener(c,p)}function cy(e,t){const n=window.getComputedStyle(e),a=v=>(n[v]||"").split(", "),o=a(`${Hr}Delay`),r=a(`${Hr}Duration`),l=Um(o,r),s=a(`${Mi}Delay`),u=a(`${Mi}Duration`),c=Um(s,u);let d=null,f=0,p=0;t===Hr?l>0&&(d=Hr,f=l,p=r.length):t===Mi?c>0&&(d=Mi,f=c,p=u.length):(f=Math.max(l,c),d=f>0?l>c?Hr:Mi:null,p=d?d===Hr?r.length:u.length:0);const m=d===Hr&&/\b(?:transform|all)(?:,|$)/.test(a(`${Hr}Property`).toString());return{type:d,timeout:f,propCount:p,hasTransform:m}}function Um(e,t){for(;e.length<t.length;)e=e.concat(e);return Math.max(...t.map((n,a)=>Ym(n)+Ym(e[a])))}function Ym(e){return e==="auto"?0:Number(e.slice(0,-1).replace(",","."))*1e3}function Vp(e){return(e?e.ownerDocument:document).body.offsetHeight}function nx(e,t,n){const a=e[js];a&&(t=(t?[t,...a]:[...a]).join(" ")),t==null?e.removeAttribute("class"):n?e.setAttribute("class",t):e.className=t}const Md=Symbol("_vod"),Ch=Symbol("_vsh"),Bt={name:"show",beforeMount(e,{value:t},{transition:n}){e[Md]=e.style.display==="none"?"":e.style.display,n&&t?n.beforeEnter(e):Oi(e,t)},mounted(e,{value:t},{tra Line truncated
`))),e[Ha]=il(o);const r=a||o.props&&o.props.type==="number";hr(e,t?"change":"input",l=>{l.target.composing||e[Ha](k0(e.value,n,r))}),(n||r)&&hr(e,"change",()=>{e.value=k0(e.value,n,r)}),t||(hr(e,"compositionstart",kx),hr(e,"compositionend",n1),hr(e,"change",n1))},mounted(e,{value:t,modifiers:{trim:n,number:a}}){const o=t??"",r=e[Tc];delete e[Tc],r!==void 0&&(e.type==="text"||e.type==="textarea")&&e.value!==r?e[Ha](k0(e.value,n,a)):e.value=o},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:a,trim:o,number:r}},l){if(e[Ha]=il(l),e.composing)return;const s=(r||e.type==="number")&&!/^0\d/.test(e.value)?df(e.value):e.value,u=t??"";if(s===u)return;const c=e.getRootNode();(c instanceof Document||c instanceof ShadowRoot)&&c.activeElement===e&&e.type!=="range"&&(a&&t===n||o&&e.value.trim()===u)||(e.value=u)}},my={deep:!0,created(e,t,n){e[Ha]=il(n),hr(e,"change",()=>{const a=e._modelValue,o=Ws(e),r=e.checked,l=e[Ha];if(we(a)){const s=ah(a,o),u=s!==-1;if(r&&!u)l(a.concat(o));else if(!r&&u){const c=[...a];c.splice(s,1),l(c)}}else if(Sr(a)){const s=new Set(a);r?s.add(o):s.delete(o),l(s)}else l(yy(e,r))})},mounted:a1,beforeUpdate(e,t,n){e[Ha]=il(n),a1(e,t,n)}};function a1(e,{value:t,oldValue:n},a){e._modelValue=t;let o;if(we(t))o=ah(t,a.props.value)>-1;else if(Sr(t))o=t.has(a.props.value);else{if(t===n)return;o=wo(t,yy(e,!0))}e.checked!==o&&(e.checked=o)}const gy={created(e,{value:t},n){e.checked=wo(t,n.props.value),e[Ha]=il(n),hr(e,"change",()=>{e[Ha](Ws(e))})},beforeUpdate(e,{value:t,oldValue:n},a){e[Ha]=il(a),t!==n&&(e.checked=wo(t,a.props.value))}},ape={deep:!0,created(e,{value:t,modifiers:{number:n}},a){e._modelValue=t,hr(e,"change",()=>{const o=Array.prototype.filter.call(e.options,u=>u.selected).map(u=>n?df(Ws(u)):Ws(u)),r=e.multiple,l=r?Sr(e._modelValue)?new Set(o):o:o[0],s=e._pendingValue=[r,r?we(l)?o.slice():o:l];try{e[Ha](l)}finally{Ie(()=>{e._pendingValue===s&&(e._pendingValue=void 0)})}}),e[Ha]=il(a)},mounted(e,{value:t}){o1(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[Ha]=il(n)},updated(e,{value:t}){const n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!Ex(t,n[1],n[0]))&&o1(e,t)}};function Ex(e,t,n){if(!n||we(e))return wo(e,t);if(Sr(e)){if(e.size!==t.length)return!1;for(const a of t)if(!e.has(a))return!1;return!0}return!1}function o1(e,t){const n=e.multiple,a=we(t);if(!(n&&!a&&!Sr(t))){for(let o=0,r=e.options.length;o<r;o++){const l=e.options[o],s=Ws(l);if(n)if(a){const u=typeof s;u==="string"||u==="number"?l.selected=t.some(c=>String(c)===String(s)):l.selected=ah(t,s)>-1}else l.selected=t.has(s);else if(wo(Ws(l),t)){e.selectedIndex!==o&&(e.selectedIndex=o);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function Ws(e){return"_value"in e?e._value:e.value}function yy(e,t){const n=t?"_trueValue":"_falseValue";return n in e?e[n]:t}const Tx=["ctrl","shift","alt","meta"],Mx={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&e.button!==0,middle:e=>"button"in e&&e.button!==1,right:e=>"button"in e&&e.button!==2,exact:(e,t)=>Tx.some(n=>e[`${n}Key`]&&!t.includes(n))},Ze=(e,t)=>{if(!e)return e;const n=e._withMods||(e._withMods={}),a=t.join(".");return n[a]||(n[a]=(o,...r)=>{for(let l=0;l<t.length;l++){const s=Mx[t[l]];if(s&&s(o,t))return}return e(o,...r)})},Ox={esc:"escape",space:" ",up:"arrow-up",left:"arrow-left",right:"arrow-right",down:"arrow-down",delete:"backspace"},cn=(e,t)=>{const n=e._withKeys||(e._withKeys={}),a=t.join(".");return n[a]||(n[a]=o=>{if(!("key"in o))return;const r=Or(o.key);if(t.some(l=>l===r||Ox[l]===r))return e(o)})},Ax=jn({patchProp:mx},ZS);let r1;function by(){return r1||(r1=PS(Ax))}const ul=(...e)=>{by().render(...e)},wy=(...e)=>{const t=by().createApp(...e),{mount:n}=t;return t.mount=a=>{const o=Nx(a);if(!o)return;const r=t._component;!Ue(r)&&!r.render&&!r.template&&(r.template=o.innerHTML),o.nodeType===1&&(o.textContent="");const l=n(o,!1,Rx(o));return o instanceof Element&&(o.removeAttribute("v-cloak"),o.setAttribute("data-v-app","")),l},t};function Rx(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function Nx(e){return Be(e)?document.querySelector(e):e}/*!
* pinia v2.3.1
* (c) 2025 Eduardo San Martin Morote
* @license MIT
*/let _y;const Tf=e=>_y=e,Cy=Symbol();function Bp(e){return e&&typeof e=="object"&&Object.prototype.toString.call(e)==="[object Object]"&&typeof e.toJSON!="function"}var nu;(function(e){e.direct="direct",e.patchObject="patch object",e.patchFunction="patch function"})(nu||(nu={}));function $x(){const e=oh(!0),t=e.run(()=>B({}));let n=[],a=[];const o=no({install(r){Tf(o),o._a=r,r.provide(Cy,o),r.config.globalProperties.$pinia=o,a.forEach(l=>n.push(l)),a=[]},use(r){return this._a?n.push(r):a.push(r),this},_p:n,_a:null,_e:e,_s:new Map,state:t});return o}const Sy=()=>{};function l1(e,t,n,a=Sy){e.push(t);const o=()=>{const r=e.indexOf(t);r>-1&&(e.splice(r,1),a())};return!n&&pf()&&rh(o),o}function ys(e,...t){e.slice().forEach(n=>{n(...t)})}const Px=e=>e(),s1=Symbol(),E0=Symbol();function Dp(e,t){e instanceof Map&&t instanceof Map?t.forEach((n,a)=>e.set(a,n)):e instanceof Set&&t instanceof Set&&t.forEach(e.add,e);for(const n in t){if(!t.hasOwnProperty(n))continue;const a=t[n],o=e[n];Bp(o)&&Bp(a)&&e.hasOwnProperty(n)&&!Jt(a)&&!gr(a)?e[n]=Dp(o,a):e[n]=a}return e}const Ix=Symbol();function Lx(e){return!Bp(e)||!e.hasOwnProperty(Ix)}const{assign:qr}=Object;function Vx(e){return!!(Jt(e)&&e.effect)}function Bx(e,t,n,a){const{state:o,actions:r,getters:l}=t,s=n.state.value[e];let u;function c(){s||(n.state.value[e]=o?o():{});const d=Vn(n.state.value[e]);return qr(d,r,Object.keys(l||{}).reduce((f,p)=>(f[p]=no(x(()=>{Tf(n);const m=n._s.get(e);return l[p].call(m,m)})),f),{}))}return u=xy(e,c,t,n,a,!0),u}function xy(e,t,n={},a,o,r){let l;const s=qr({actions:{}},n),u={deep:!0};let c,d,f=[],p=[],m;const v=a.state.value[e];!r&&!v&&(a.state.value[e]={});let h;function g(E){let T;c=d=!1,typeof E=="function"?(E(a.state.value[e]),T={type:nu.patchFunction,storeId:e,events:m}):(Dp(a.state.value[e],E),T={type:nu.patchObject,payload:E,storeId:e,events:m});const N=h=Symbol();Ie().then(()=>{h===N&&(c=!0)}),d=!0,ys(f,T,a.state.value[e])}const y=r?function(){const{state:T}=n,N=T?T():{};this.$patch(P=>{qr(P,N)})}:Sy;function b(){l.stop(),f=[],p=[],a._s.delete(e)}const C=(E,T="")=>{if(s1 in E)return E[E0]=T,E;const N=function(){Tf(a);const P=Array.from(arguments),$=[],V=[];function U(O){$.push(O)}function D(O){V.push(O)}ys(p,{args:P,name:N[E0],store:S,after:U,onError:D});let F;try{F=E.apply(this&&this.$id===e?this:S,P)}catch(O){throw ys(V,O),O}return F instanceof Promise?F.then(O=>(ys($,O),O)).catch(O=>(ys(V,O),Promise.reject(O))):(ys($,F),F)};return N[s1]=!0,N[E0]=T,N},w={_p:a,$id:e,$onAction:l1.bind(null,p),$patch:g,$reset:y,$subscribe(E,T={}){const N=l1(f,E,T.detached,()=>P()),P=l.run(()=>fe(()=>a.state.value[e],$=>{(T.flush==="sync"?d:c)&&E({storeId:e,type:nu.direct,events:m},$)},qr({},u,T)));return N},$dispose:b},S=zt(w);a._s.set(e,S);const M=(a._a&&a._a.runWithContext||Px)(()=>a._e.run(()=>(l=oh()).run(()=>t({action:C}))));for(const E in M){const T=M[E];if(Jt(T)&&!Vx(T)||gr(T))r||(v&&Lx(T)&&(Jt(T)?T.value=v[E]:Dp(T,v[E])),a.state.value[e][E]=T);else if(typeof T=="function"){const N=C(T,E);M[E]=N,s.actions[E]=T}}return qr(S,M),qr(Qt(S),M),Object.defineProperty(S,"$state",{get:()=>a.state.value[e],set:E=>{g(T=>{qr(T,E)})}}),a._p.forEach(E=>{qr(S,l.run(()=>E({store:S,app:a._a,pinia:a,options:s})))}),v&&r&&n.hydrate&&n.hydrate(S.$state,v),c=!0,d=!0,S}/*! #__NO_SIDE_EFFECTS__ */function ky(e,t,n){let a,o;const r=typeof t=="function";typeof e=="string"?(a=e,o=r?n:t):(o=e,a=e.id);function l(s,u){const c=dh();return s=s||(c?Le(Cy,null):null),s&&Tf(s),s=_y,s._s.has(a)||(r?xy(a,t,o,s):Bx(a,o,s)),s._s.get(a)}return l.$id=a,l}const Se={tab:"Tab",enter:"Enter",space:"Space",left:"ArrowLeft",up:"ArrowUp",right:"ArrowRight",down:"ArrowDown",esc:"Escape",delete:"Delete",backspace:"Backspace",numpadEnter:"NumpadEnter",pageUp:"PageUp",pageDown:"PageDown",home:"Home",end:"End"},i1=["left","center","right"],Dx=["year","years","month","months","date","dates","week","quarter","quarters","datetime","datetimerange","daterange","monthrange","yearrange","quarterrange"],T0=["sun","mon","tue","wed","thu","fri","sat"],st="update:modelValue",wt="change",Rn="input",u1=Symbol("INSTALLED_KEY"),Oo=["","default","small","large"];function Ey(e,t){var n;const a=Mt();return ma(()=>{a.value=e()},{...t,flush:(n=t==null?void 0:t.flush)!==null&&n!==void 0?n:"sync"}),Fs(a)}function cl(e,t){return pf()?(rh(e,t),!0):!1}const M0=new WeakMap,zx=(...e)=>{var t;const n=e[0],a=(t=gt())===null||t===void 0?void 0:t.proxy,o=a??pf();if(o==null&&!dh())throw new Error("injectLocal must be called in setup");return o&&M0.has(o)&&n in M0.get(o)?M0.get(o)[n]:Le(...e)},Vt=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const Hx=e=>typeof e<"u",Ty=e=>e!=null,Fx=Object.prototype.toString,Kx=e=>Fx.call(e)==="[object Object]",Mf=(e,t,n)=>Math.min(n,Math.max(t,e)),Zn=()=>{},qs=jx();function jx(){var e,t,n;return Vt&&!!(!((e=window)===null||e===void 0||(e=e.navigator)===null||e===void 0)&&e.userAgent)&&(/iP(?:ad|hone|od)/.test(window.navigatoLine truncated
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @param {?boolean} capture Check if the capture phase is supported.
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/const t2="_Mousewheel",J1=function(e,t){if(e&&e.addEventListener){Mb(e);const n=function(a){const o=jO(a);t&&Reflect.apply(t,this,[a,o])};e[t2]={wheelHandler:n},e.addEventListener("wheel",n,{passive:!0})}},Mb=e=>{var t;(t=e._Mousewheel)!=null&&t.wheelHandler&&(e.removeEventListener("wheel",e[t2].wheelHandler),e[t2]=null)},Z1={beforeMount(e,t){J1(e,t.value)},unmounted(e){Mb(e)},updated(e,t){t.value!==t.oldValue&&J1(e,t.value)}},xu=e=>Object.keys(e),Ob=e=>Object.entries(e),ol=(e,t,n)=>({get value(){return kn(e,t,n)},set value(a){OO(e,t,a)}}),WO="__epPropKey",J=e=>e,qO=e=>it(e)&&!!e.__epPropKey,Ro=(e,t)=>{if(!it(e)||qO(e))return e;const{values:n,required:a,default:o,type:r,validator:l}=e,s={type:r,required:!!a,validator:n||l?u=>{let c=!1,d=[];if(n&&(d=Array.from(n),Dt(e,"default")&&d.push(o),c||(c=d.includes(u))),l&&(c||(c=l(u))),!c&&d.length>0){const f=[...new Set(d)].map(p=>JSON.stringify(p)).join(", ");GS(`Invalid prop: validation failed${t?` for prop "${t}"`:""}. Expected one of [${f}], got value ${JSON.stringify(u)}.`)}return c}:void 0,[WO]:!0};return Dt(e,"default")&&(s.default=o),s},Te=e=>Gs(Object.entries(e).map(([t,n])=>[t,Ro(n,t)])),UO=Te({zIndex:{type:J([Number,String]),default:100},target:{type:String,default:""},offset:{type:Number,default:0},position:{type:String,values:["top","bottom"],default:"top"},teleported:Boolean,appendTo:{type:J([String,Object]),default:"body"}}),YO={scroll:({scrollTop:e,fixed:t})=>Ke(e)&&Yt(t),[wt]:e=>Yt(e)};var Ab=class extends Error{constructor(e){super(e),this.name="ElementPlusError"}};function pn(e,t){throw new Ab(`[${e}] ${t}`)}function qt(e,t){{const n=Be(e)?new Ab(`[${e}] ${t}`):e;console.warn(n)}}const GO=["class","style"],XO=/^on[A-Z]/,zf=(e={})=>{const{excludeListeners:t=!1,excludeKeys:n}=e,a=x(()=>((n==null?void 0:n.value)||[]).concat(GO)),o=gt();return o?x(()=>{var r;return Gs(Object.entries((r=o.proxy)==null?void 0:r.$attrs).filter(([l])=>!a.value.includes(l)&&!(t&&XO.test(l))))}):(qt("use-attrs","getCurrentInstance() returned null. useAttrs() must be called at the top of a setup function"),x(()=>({})))};function Hh(){const e=Mt(),t=B(0),n=x(()=>({minWidth:`${Math.max(t.value,11)}px`}));return rn(e,()=>{var o;t.value=((o=e.value)==null?void 0:o.getBoundingClientRect().width)??0}),{calculatorRef:e,calculatorWidth:t,inputStyle:n}}const Wo=({from:e,replacement:t,scope:n,version:a,ref:o,type:r="API"},l)=>{fe(()=>i(l),s=>{s&&qt(n,`[${r}] ${e} is about to be deprecated in version ${a}, please use ${t} instead.
For more detail, please visit: ${o}
`)},{immediate:!0})},Fh=(e="")=>e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d"),P0=e=>ju(e),JO="utils/dom/style",Rb=(e="")=>e.split(" ").filter(t=>!!t.trim()),ao=(e,t)=>{if(!e||!t)return!1;if(t.includes(" "))throw new Error("className should not contain space.");return e.classList.contains(t)},eo=(e,t)=>{!e||!t.trim()||e.classList.add(...Rb(t))},ha=(e,t)=>{!e||!t.trim()||e.classList.remove(...Rb(t))},vr=(e,t)=>{var a;if(!Vt||!e||!t||gb(e))return"";let n=ta(t);n==="float"&&(n="cssFloat");try{const o=e.style[n];if(o)return o;const r=(a=document.defaultView)==null?void 0:a.getComputedStyle(e,"");return r?r[n]:""}catch{return e.style[n]}},Nb=(e,t,n)=>{if(!(!e||!t))if(it(t))Ob(t).forEach(([a,o])=>Nb(e,a,o));else{const a=ta(t);e.style[a]=n}};function gn(e,t="px"){if(!e&&e!==0)return"";if(Ke(e)||IO(e))return`${e}${t}`;if(Be(e))return e;qt(JO,"binding value must be a string or number")}const $b=(e,t,n,a)=>{const o={offsetX:0,offsetY:0},r=B(!1),l=(p,m)=>{if(e.value){const{offsetX:v,offsetY:h}=o,g=e.value.getBoundingClientRect(),y=Math.max(g.left,0),b=Math.max(g.top,0),C=g.width,w=g.height,S=document.documentElement.clientWidth,k=document.documentElement.clientHeight,M=-y+v,E=-b+h,T=S-y-C+v,N=k-b-(w<k?w:0)+h;a!=null&&a.value||(p=Ra(p,M,T),m=Ra(m,E,N)),o.offsetX=p,o.offsetY=m,e.value.style.transform=`translate(${gn(p)}, ${gn(m)})`}},s=p=>{const m=p.clientX,v=p.clientY,{offsetX:h,offsetY:g}=o,y=C=>{r.value||(r.value=!0),l(h+C.clientX-m,g+C.clientY-v)},b=()=>{r.value=!1,document.removeEventListener("mousemove",y),document.removeEventListener("mouseup",b)};document.addEventListener("mousemove",y),document.addEventListener("mouseup",b)},u=()=>{t.value&&e.value&&(t.value.addEventListener("mousedown",s),window.addEventListener("resize",f))},c=()=>{t.value&&e.value&&(t.value.removeEventListener("mousedown",s),window.removeEventListener("resize",f))},d=()=>{o.offsetX=0,o.offsetY=0,e.value&&(e.value.style.transform="")},f=()=>{const{offsetX:p,offsetY:m}=o;l(p,m)};return yt(()=>{ma(()=>{n.value?u():c()})}),Ht(()=>{c()}),{isDragging:r,resetPosition:d,updatePosition:f}};var ZO={name:"en",el:{breadcrumb:{label:"Breadcrumb"},colorpicker:{confirm:"OK",clear:"Clear",defaultLabel:"color picker",description:"current color is {color}. press enter to select a new color.",alphaLabel:"pick alpha value",alphaDescription:"alpha {alpha}, current color is {color}",hueLabel:"pick hue value",hueDescription:"hue {hue}, current color is {color}",svLabel:"pick saturation and brightness value",svDescription:"saturation {saturation}, brightness {brightness}, current color is {color}",predefineDescription:"select {value} as the color"},datepicker:{now:"Now",today:"Today",cancel:"Cancel",clear:"Clear",confirm:"OK",dateTablePrompt:"Use the arrow keys and enter to select the day of the month",monthTablePrompt:"Use the arrow keys and enter to select the month",quarterTablePrompt:"Use the arrow keys and enter to select the quarter",yearTablePrompt:"Use the arrow keys and enter to select the year",selectedDate:"Selected date",selectDate:"Select date",selectTime:"Select time",startDate:"Start Date",startTime:"Start Time",endDate:"End Date",endTime:"End Time",prevYear:"Previous Year",nextYear:"Next Year",prevMonth:"Previous Month",nextMonth:"Next Month",year:"",month1:"January",month2:"February",month3:"March",month4:"April",month5:"May",month6:"June",month7:"July",month8:"August",month9:"September",month10:"October",month11:"November",month12:"December",weeks:{sun:"Sun",mon:"Mon",tue:"Tue",wed:"Wed",thu:"Thu",fri:"Fri",sat:"Sat"},weeksFull:{sun:"Sunday",mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday"},months:{jan:"Jan",feb:"Feb",mar:"Mar",apr:"Apr",may:"May",jun:"Jun",jul:"Jul",aug:"Aug",sep:"Sep",oct:"Oct",nov:"Nov",dec:"Dec"}},input:{characters:"{count} / {max} characters"},inputNumber:{decrease:"decrease number",increase:"increase number"},select:{loading:"Loading",noMatch:"No matching data",noData:"No data",placeholder:"Select"},mention:{loading:"Loading"},dropdown:{toggleDropdown:"Toggle Dropdown"},cascader:{noMatch:"No matching data",loading:"Loading",placeholder:"Select",noData:"No data"},pagination:{goto:"Go to",pagesize:"/page",total:"Total {total}",pageClassifier:"",page:"Page",prev:"Go to previous page",next:"Go to next page",currentPage:"page {pager}",prevPages:"Previous {pager} pages",nextPages:"Next {pager} pages",deprecationWarning:"Deprecated usages detected, please refer to the el-pagination documentation for more details"},dialog:{close:"Close this dialog"},drawer:{close:"Close this dialog"},messagebox:{title:"Message",confirm:"OK",cancel:"Cancel",error:"Illegal input",close:"Close this dialog"},upload:{deleteTip:"press delete to remove",delete:"Delete",preview:"Preview",continue:"Continue"},slider:{defaultLabel:"slider between {min} and {max}",defaultRangeStartLabel:"pick start value",defaultRangeEndLabel:"pick end value"},table:{emptyText:"No Data",confirmFilter:"Confirm",resetFilter:"R Line truncated
usage: app.provide(ID_INJECTION_KEY, {
prefix: number,
current: number,
})`);const n=Kh();return Ey(()=>i(e)||`${n.value}-id-${t.prefix}-${t.current++}`)};let Ms=[];const dg=e=>{Xt(e)===Se.esc&&Ms.forEach(t=>t(e))},vR=e=>{yt(()=>{Ms.length===0&&document.addEventListener("keydown",dg),Vt&&Ms.push(e)}),Ht(()=>{Ms=Ms.filter(t=>t!==e),Ms.length===0&&Vt&&document.removeEventListener("keydown",dg)})},Xb=()=>{const e=Kh(),t=tv(),n=x(()=>`${e.value}-popper-container-${t.prefix}`);return{id:n,selector:x(()=>`#${n.value}`)}},mR=e=>{const t=document.createElement("div");return t.id=e,document.body.appendChild(t),t},gR=()=>{const{id:e,selector:t}=Xb();return xf(()=>{Vt&&(document.body.querySelector(t.value)||mR(e.value))}),{id:e,selector:t}},yR=Te({showAfter:{type:Number,default:0},hideAfter:{type:Number,default:200},autoClose:{type:Number,default:0}}),bR={showAfter:0,hideAfter:200,autoClose:0},wR=({showAfter:e,hideAfter:t,autoClose:n,open:a,close:o})=>{const{registerTimeout:r}=cg(),{registerTimeout:l,cancelTimeout:s}=cg();return{onOpen:(d,f=i(e))=>{r(()=>{a(d);const p=i(n);Ke(p)&&p>0&&l(()=>{o(d)},p)},f)},onClose:(d,f=i(t))=>{s(),r(()=>{o(d)},f)}}},Jb=Symbol("elForwardRef"),_R=e=>{Tt(Jb,{setForwardRef:n=>{e.value=n}})},CR=e=>({mounted(t){e(t)},updated(t){e(t)},unmounted(){e(null)}}),fg={current:0},pg=B(0),Zb=2e3,hg=Symbol("elZIndexContextKey"),Qb=Symbol("zIndexContextKey"),oc=e=>{const t=gt()?Le(hg,fg):fg,n=e||(gt()?Le(Qb,void 0):void 0),a=x(()=>{const l=i(n);return Ke(l)?l:Zb}),o=x(()=>a.value+pg.value),r=()=>(t.current++,pg.value=t.current,o.value);return!Vt&&!Le(hg)&&qt("ZIndexInjection",`Looks like you are using server rendering, you must provide a z-index provider to ensure the hydration process to be succeed
usage: app.provide(ZINDEX_INJECTION_KEY, { current: 0 })`),{initialZIndex:a,currentZIndex:o,nextZIndex:r}},ei=Math.min,Fl=Math.max,Ld=Math.round,Nc=Math.floor,wr=e=>({x:e,y:e}),SR={left:"right",right:"left",bottom:"top",top:"bottom"};function e8(e,t,n){return Fl(e,ei(t,n))}function rc(e,t){return typeof e=="function"?e(t):e}function ti(e){return e.split("-")[0]}function lc(e){return e.split("-")[1]}function t8(e){return e==="x"?"y":"x"}function nv(e){return e==="y"?"height":"width"}function el(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function av(e){return t8(el(e))}function xR(e,t,n){n===void 0&&(n=!1);const a=lc(e),o=av(e),r=nv(o);let l=o==="x"?a===(n?"end":"start")?"right":"left":a==="start"?"bottom":"top";return t.reference[r]>t.floating[r]&&(l=Vd(l)),[l,Vd(l)]}function kR(e){const t=Vd(e);return[r2(e),t,r2(t)]}function r2(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const vg=["left","right"],mg=["right","left"],ER=["top","bottom"],TR=["bottom","top"];function MR(e,t,n){switch(e){case"top":case"bottom":return n?t?mg:vg:t?vg:mg;case"left":case"right":return t?ER:TR;default:return[]}}function OR(e,t,n,a){const o=lc(e);let r=MR(ti(e),n==="start",a);return o&&(r=r.map(l=>l+"-"+o),t&&(r=r.concat(r.map(r2)))),r}function Vd(e){const t=ti(e);return SR[t]+e.slice(t.length)}function AR(e){var t,n,a,o;return{top:(t=e.top)!=null?t:0,right:(n=e.right)!=null?n:0,bottom:(a=e.bottom)!=null?a:0,left:(o=e.left)!=null?o:0}}function n8(e){return typeof e!="number"?AR(e):{top:e,right:e,bottom:e,left:e}}function Bd(e){const{x:t,y:n,width:a,height:o}=e;return{width:a,height:o,top:n,left:t,right:t+a,bottom:n+o,x:t,y:n}}function gg(e,t,n){let{reference:a,floating:o}=e;const r=el(t),l=av(t),s=nv(l),u=ti(t),c=r==="y",d=a.x+a.width/2-o.width/2,f=a.y+a.height/2-o.height/2,p=a[s]/2-o[s]/2;let m;switch(u){case"top":m={x:d,y:a.y-o.height};break;case"bottom":m={x:d,y:a.y+a.height};break;case"right":m={x:a.x+a.width,y:f};break;case"left":m={x:a.x-o.width,y:f};break;default:m={x:a.x,y:a.y}}const v=lc(t);return v&&(m[l]+=p*(v==="end"?1:-1)*(n&&c?-1:1)),m}async function a8(e,t){var n;t===void 0&&(t={});const{x:a,y:o,platform:r,rects:l,elements:s,strategy:u}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:f="floating",altBoundary:p=!1,padding:m=0}=rc(t,e),v=n8(m),g=s[p?f==="floating"?"reference":"floating":f],y=Bd(await r.getClippingRect({element:(n=await(r.isElement==null?void 0:r.isElement(g)))==null||n?g:g.contextElement||await(r.getDocumentElement==null?void 0:r.getDocumentElement(s.floating)),boundary:c,rootBoundary:d,strategy:u})),b=f==="floating"?{x:a,y:o,width:l.floating.width,height:l.floating.height}:l.reference,C=await(r.getOffsetParent==null?void 0:r.getOffsetParent(s.floating)),w=await(r.isElement==null?void 0:r.isElement(C))&&await(r.getScale==null?void 0:r.getScale(C))||{x:1,y:1},S=Bd(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:b,offsetParent:C,strategy:u}):b);return{top:(y.top-S.top+v.top)/w.y,bottom:(S.bottom-y.bottom+v.bottom)/w.y,left:(y.left-S.left+v.left)/w.x,right:(S.right-y.right+v.right)/w.x}}const RR=50,NR=async(e,t,n)=>{const{placement:a="bottom",strategy:o="absolute",middleware:r=[],platform:l}=n,s=l.detectOverflow?l:{...l,detectOverflow:a8},u=await(l.isRTL==null?void 0:l.isRTL(t));let c=await l.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:f}=gg(c,a,u),p=a,m=0;const v={};for(let h=0;h<r.length;h++){const g=r[h];if(!g)continue;const{name:y,fn:b}=g,{x:C,y:w,data:S,reset:k}=await b({x:d,y:f,initialPlacement:a,placement:p,strategy:o,middlewareData:v,rects:c,platform:s,elements:{reference:e,floating:t}});d=C??d,f=w??f,v[y]={...v[y],...S},k&&m<RR&&(m++,typeof k=="object"&&(k.placement&&(p=k.placement),k.rects&&(c=k.rects===!0?await l.getElementRects({reference:e,floating:t,strategy:o}):k.rects),{x:d,y:f}=gg(c,p,u)),h=-1)}return{x:d,y:f,placement:p,strategy:o,middlewareData:v}},$R=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:a,placement:o,rects:r,platform:l,elements:s,middlewareData:u}=t,{element:c,padding:d=0}=rc(e,t)||{};if(c==null)return{};const f=n8(d),p={x:n,y:a},m=av(o),v=nv(m),h=await l.getDimensions(c),g=m==="y",y=g?"top":"left",b=g?"bottom":"right",C=g?"clientHeight":"clientWidth",w=r.reference[v]+r.reference[m]-p[m]-r.floating[v],S=p[m]-r.reference[m],k=await(l.getOffsetParent==null?void 0:l.getOffsetParent(c));let M=k?k[C]:0;(!M||!await(l.isElement==null?void 0:l.isElement(k)))&&(M=s.floating[C]||r.floating[v]);const E=w/2-S/2,T=M/2-h[v]/2-1,N=ei(f[y],T),P=ei(f[b],T),$=M-h[v]-P,V=M/2-h[v]/2+E,U=e8(N,V,$),D=!u.arrow&&lc(o)!=null&&V!==U&&r.reference[v]/2-(V<N?N:P)-h[v]/2<0,F=D?V<N?V-N:V-$:0;return{[m]:p[m]+F,data:{[m]:U,centerOffset:V-U-F,...D&&{alignmentOffset:F}},reset:D}}}),PR=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,a;const{placement:o,middlewareData:r,rects:l,initialPlacement:s,platform:u,el Line truncated
(?:
(?:`+a+":){7}(?:"+a+`|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
(?:`+a+":){6}(?:"+n+"|:"+a+`|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
(?:`+a+":){5}(?::"+n+"|(?::"+a+`){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
(?:`+a+":){4}(?:(?::"+a+"){0,1}:"+n+"|(?::"+a+`){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
(?:`+a+":){3}(?:(?::"+a+"){0,2}:"+n+"|(?::"+a+`){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
(?:`+a+":){2}(?:(?::"+a+"){0,3}:"+n+"|(?::"+a+`){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
(?:`+a+":){1}(?:(?::"+a+"){0,4}:"+n+"|(?::"+a+`){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
(?::(?:(?::`+a+"){0,5}:"+n+"|(?::"+a+`){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
`).replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),r=new RegExp("(?:^"+n+"$)|(?:^"+o+"$)"),l=new RegExp("^"+n+"$"),s=new RegExp("^"+o+"$"),u=function(w){return w&&w.exact?r:new RegExp("(?:"+t(w)+n+t(w)+")|(?:"+t(w)+o+t(w)+")","g")};u.v4=function(C){return C&&C.exact?l:new RegExp(""+t(C)+n+t(C),"g")},u.v6=function(C){return C&&C.exact?s:new RegExp(""+t(C)+o+t(C),"g")};var c="(?:(?:[a-z]+:)?//)",d="(?:\\S+(?::\\S*)?@)?",f=u.v4().source,p=u.v6().source,m="(?:(?:[a-z\\u00a1-\\uffff0-9][-_]*)*[a-z\\u00a1-\\uffff0-9]+)",v="(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*",h="(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))",g="(?::\\d{2,5})?",y='(?:[/?#][^\\s"]*)?',b="(?:"+c+"|www\\.)"+d+"(?:localhost|"+f+"|"+p+"|"+m+v+h+")"+g+y;return Pc=new RegExp("(?:^"+b+"$)","i"),Pc},Og={email:/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+\.)+[a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}))$/,hex:/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i},Wi={integer:function(t){return Wi.number(t)&&parseInt(t,10)===t},float:function(t){return Wi.number(t)&&!Wi.integer(t)},array:function(t){return Array.isArray(t)},regexp:function(t){if(t instanceof RegExp)return!0;try{return!!new RegExp(t)}catch{return!1}},date:function(t){return typeof t.getTime=="function"&&typeof t.getMonth=="function"&&typeof t.getYear=="function"&&!isNaN(t.getTime())},number:function(t){return isNaN(t)?!1:typeof t=="number"},object:function(t){return typeof t=="object"&&!Wi.array(t)},method:function(t){return typeof t=="function"},email:function(t){return typeof t=="string"&&t.length<=320&&!!t.match(Og.email)},url:function(t){return typeof t=="string"&&t.length<=2048&&!!t.match(vK())},hex:function(t){return typeof t=="string"&&!!t.match(Og.hex)}},mK=function(t,n,a,o,r){if(t.required&&n===void 0){U8(t,n,a,o,r);return}var l=["integer","float","array","regexp","object","method","email","number","date","url","hex"],s=t.type;l.indexOf(s)>-1?Wi[s](n)||o.push(ja(r.messages.types[s],t.fullField,t.type)):s&&typeof n!==t.type&&o.push(ja(r.messages.types[s],t.fullField,t.type))},gK=function(t,n,a,o,r){var l=typeof t.len=="number",s=typeof t.min=="number",u=typeof t.max=="number",c=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,d=n,f=null,p=typeof n=="number",m=typeof n=="string",v=Array.isArray(n);if(p?f="number":m?f="string":v&&(f="array"),!f)return!1;v&&(d=n.length),m&&(d=n.replace(c,"_").length),l?d!==t.len&&o.push(ja(r.messages[f].len,t.fullField,t.len)):s&&!u&&d<t.min?o.push(ja(r.messages[f].min,t.fullField,t.min)):u&&!s&&d>t.max?o.push(ja(r.messages[f].max,t.fullField,t.max)):s&&u&&(d<t.min||d>t.max)&&o.push(ja(r.messages[f].range,t.fullField,t.min,t.max))},ws="enum",yK=function(t,n,a,o,r){t[ws]=Array.isArray(t[ws])?t[ws]:[],t[ws].indexOf(n)===-1&&o.push(ja(r.messages[ws],t.fullField,t[ws].join(", ")))},bK=function(t,n,a,o,r){if(t.pattern){if(t.pattern instanceof RegExp)t.pattern.lastIndex=0,t.pattern.test(n)||o.push(ja(r.messages.pattern.mismatch,t.fullField,n,t.pattern));else if(typeof t.pattern=="string"){var l=new RegExp(t.pattern);l.test(n)||o.push(ja(r.messages.pattern.mismatch,t.fullField,n,t.pattern))}}},tn={required:U8,whitespace:hK,type:mK,range:gK,enum:yK,pattern:bK},wK=function(t,n,a,o,r){var l=[],s=t.required||!t.required&&o.hasOwnProperty(t.field);if(s){if(Xn(n,"string")&&!t.required)return a();tn.required(t,n,o,l,r,"string"),Xn(n,"string")||(tn.type(t,n,o,l,r),tn.range(t,n,o,l,r),tn.pattern(t,n,o,l,r),t.whitespace===!0&&tn.whitespace(t,n,o,l,r))}a(l)},_K=function(t,n,a,o,r){var l=[],s=t.required||!t.required&&o.hasOwnProperty(t.field);if(s){if(Xn(n)&&!t.required)return a();tn.required(t,n,o,l,r),n!==void 0&&tn.type(t,n,o,l,r)}a(l)},CK=function(t,n,a,o,r){var l=[],s=t.required||!t.required&&o.hasOwnProperty(t.field);if(s){if(n===""&&(n=void 0),Xn(n)&&!t.required)return a();tn.required(t,n,o,l,r),n!==void 0&&(tn.type(t,n,o,l,r),tn.range(t,n,o,l,r))}a(l)},SK=function(t,n,a,o,r){var l=[],s=t.required||!t.required&&o.hasOwnProperty(t.field);if(s){if(Xn(n)&&!t.required)return a();tn.required(t,n,o,l,r),n!==void 0&&tn.type(t,n,o,l,r)}a(l)},xK=function(t,n,a,o,r){var l=[],s=t.required||!t.required&&o.hasOwnProperty(t.field);if(s){if(Xn(n)&&!t.required)return a();tn.required(t,n,o,l,r),Xn(n)||tn.type(t,n,o,l,r)}a(l)},kK=function(t,n,a,o,r){var l=[],s=t.required||!t.required&&o.hasOwnProperty(t.field);if(s){if(Xn(n)&&!t.required)return a();tn.required(t,n,o,l,r),n!==void 0&&(tn.type(t,n,o,l,r),tn.range(t,n,o,l,r))}a(l)},EK=function(t,n,a,o,r){var l=[],s=t.required||!t.required&&o.hasOwnProperty(t.field);if(s){if(Xn(n)&&!t.required)return a();tn.required(t,n,o,l,r),n!==void 0&&(tn.type(t,n,o,l,r),tn.range(t,n,o,l,r))}a(l)},TK=function(t,n,a,o,r){var l=[],s=t.required||!t.required&&o.hasOwnProperty(t.field);if(s){if(n==null&&!t.required)return a();tn.required(t,n,o,l,r,"array"),n!=null&&(tn.type(t,n,o,l,r),tn.range(t,n,o,l,r))}a(l)},MK=function(t,n,a,o,r){var Line truncated
You should set
width/height
to number when your layout is
horizontal/vertical
`);const c=Math.max(0,t*n-u),d=Math.min(c,r*n),f=Math.max(0,(r+1)*n-u);switch(l==="smart"&&(s>=f-u&&s<=d+u?l=to:l=jo),l){case Nu:return d;case"end":return f;case jo:{const p=Math.round(f+(d-f)/2);return p<Math.ceil(u/2)?0:p>c+Math.floor(u/2)?c:p}case to:default:return s>=f&&s<=d?s:s<f?f:d}},getStartIndexForOffset:({total:e,itemSize:t},n)=>Math.max(0,Math.min(e-1,Math.floor(n/t))),getStopIndexForStartIndex:({height:e,total:t,itemSize:n,layout:a,width:o},r,l)=>{const s=r*n,u=Pu(a)?o:e,c=Math.ceil((u+l-s)/n);return Math.max(0,Math.min(t-1,r+c-1))},initCache(){},clearCache:!0,validateProps(){}}),HU="ElDynamicSizeList",Rs=(e,t,n)=>{const{itemSize:a}=e,{items:o,lastVisitedIndex:r}=n;if(t>r){let l=0;if(r>=0){const s=o[r];l=s.offset+s.size}for(let s=r+1;s<=t;s++){const u=a(s);o[s]={offset:l,size:u},l+=u}n.lastVisitedIndex=t}return o[t]},FU=(e,t,n)=>{const{items:a,lastVisitedIndex:o}=t;return(o>0?a[o].offset:0)>=n?zw(e,t,0,o,n):KU(e,t,Math.max(0,o),n)},zw=(e,t,n,a,o)=>{for(;n<=a;){const r=n+Math.floor((a-n)/2),l=Rs(e,r,t).offset;if(l===o)return r;l<o?n=r+1:l>o&&(a=r-1)}return Math.max(0,n-1)},KU=(e,t,n,a)=>{const{total:o}=e;let r=1;for(;n<o&&Rs(e,n,t).offset<a;)n+=r,r*=2;return zw(e,t,Math.floor(n/2),Math.min(n,o-1),a)},s4=({total:e},{items:t,estimatedItemSize:n,lastVisitedIndex:a})=>{let o=0;if(a>=e&&(a=e-1),a>=0){const l=t[a];o=l.offset+l.size}const r=(e-a-1)*n;return o+r},jU=Dw({name:"ElDynamicSizeList",getItemOffset:(e,t,n)=>Rs(e,t,n).offset,getItemSize:(e,t,{items:n})=>n[t].size,getEstimatedTotalSize:s4,getOffset:(e,t,n,a,o)=>{const{height:r,layout:l,width:s}=e,u=Pu(l)?s:r,c=Rs(e,t,o),d=s4(e,o),f=Math.max(0,Math.min(d-u,c.offset)),p=Math.max(0,c.offset-u+c.size);switch(n==="smart"&&(a>=p-u&&a<=f+u?n=to:n=jo),n){case Nu:return f;case"end":return p;case jo:return Math.round(p+(f-p)/2);case to:default:return a>=p&&a<=f?a:a<p?p:f}},getStartIndexForOffset:(e,t,n)=>FU(e,n,t),getStopIndexForStartIndex:(e,t,n,a)=>{const{height:o,total:r,layout:l,width:s}=e,u=Pu(l)?s:o,c=Rs(e,t,a),d=n+u;let f=c.offset+c.size,p=t;for(;p<r-1&&f<d;)p++,f+=Rs(e,p,a).size;return p},initCache({estimatedItemSize:e=50},t){const n={items:{},estimatedItemSize:e,lastVisitedIndex:-1};return n.clearCacheAfterIndex=(a,o=!0)=>{var r,l;n.lastVisitedIndex=Math.min(n.lastVisitedIndex,a-1),(r=t.exposed)==null||r.getItemStyleCache(-1),o&&((l=t.proxy)==null||l.$forceUpdate())},n},clearCache:!1,validateProps:({itemSize:e})=>{typeof e!="function"&&pn(HU,`
itemSize is required as function, but the given value was ${typeof e}
`)}}),WU=({atXEndEdge:e,atXStartEdge:t,atYEndEdge:n,atYStartEdge:a},o)=>{let r=null,l=0,s=0;const u=(d,f)=>{const p=d<0&&t.value||d>0&&e.value,m=f<0&&a.value||f>0&&n.value;return p||m};return{hasReachedEdge:u,onWheel:d=>{So(r);let f=d.deltaX,p=d.deltaY;if(Math.abs(f)>Math.abs(p)?p=0:f=0,d.shiftKey&&p!==0&&(f=p,p=0),u(f,p)){d.deltaX!==0&&f===0&&d.preventDefault();return}l+=f,s+=p,d.preventDefault(),r=ga(()=>{o(l,s),l=0,s=0})}}},qU=(e,t,n,a,o,r,l)=>{const s=B(0),u=B(0);let c,d=0,f=0;const p=v=>{So(c),s.value=v.touches[0].clientX,u.value=v.touches[0].clientY,d=0,f=0},m=v=>{v.preventDefault(),So(c),d+=s.value-v.touches[0].clientX,f+=u.value-v.touches[0].clientY,s.value=v.touches[0].clientX,u.value=v.touches[0].clientY,c=ga(()=>{const h=a.value-i(r),g=o.value-i(l);n({scrollLeft:Math.min(t.value.scrollLeft+d,h),scrollTop:Math.min(t.value.scrollTop+f,g)}),d=0,f=0})};return Kt(e,"touchstart",p,{passive:!0}),Kt(e,"touchmove",m,{passive:!1}),{touchStartX:s,touchStartY:u,handleTouchStart:p,handleTouchMove:m}},Hw=({name:e,clearCache:t,getColumnPosition:n,getColumnStartIndexForOffset:a,getColumnStopIndexForStartIndex:o,getEstimatedTotalHeight:r,getEstimatedTotalWidth:l,getColumnOffset:s,getRowOffset:u,getRowPosition:c,getRowStartIndexForOffset:d,getRowStopIndexForStartIndex:f,initCache:p,injectToInstance:m,validateProps:v})=>j({name:e??"ElVirtualList",props:jl,emits:[jd,Wd],setup(h,{emit:g,expose:y,slots:b}){const C=be("vl");v(h);const w=gt(),S=B(p(h,w));m==null||m(w,S);const k=B(),M=B(),E=B(),T=B(),N=B({isScrolling:!1,scrollLeft:Ke(h.initScrollLeft)?h.initScrollLeft:0,scrollTop:Ke(h.initScrollTop)?h.initScrollTop:0,updateRequested:!1,xAxisScrollDir:qd,yAxisScrollDir:qd}),P=Vw(),$=x(()=>Number.parseInt(`${h.height}`,10)),V=x(()=>Number.parseInt(`${h.width}`,10)),U=x(()=>{const{totalColumn:ge,totalRow:Oe,columnCache:_e}=h,{isScrolling:$e,xAxisScrollDir:ze,scrollLeft:Qe}=i(N);if(ge===0||Oe===0)return[0,0,0,0];const et=a(h,Qe,i(S)),Xe=o(h,et,Qe,i(S)),_t=!$e||ze==="backward"?Math.max(1,_e):1,Rt=!$e||ze==="forward"?Math.max(1,_e):1;return[Math.max(0,et-_t),Math.max(0,Math.min(ge-1,Xe+Rt)),et,Xe]}),D=x(()=>{const{totalColumn:ge,totalRow:Oe,rowCache:_e}=h,{isScrolling:$e,yAxisScrollDir:ze,scrollTop:Qe}=i(N);if(ge===0||Oe===0)return[0,0,0,0];const et=d(h,Qe,i(S)),Xe=f(h,et,Qe,i(S)),_t=!$e||ze==="backward"?Math.max(1,_e):1,Rt=!$e||ze==="forward"?Math.max(1,_e):1;return[Math.max(0,et-_t),Math.max(0,Math.min(Oe-1,Xe+Rt)),et,Xe]}),F=x(()=>r(h,i(S))),O=x(()=>l(h,i(S))),L=x(()=>[{position:"relative",overflow:"hidden",WebkitOverflowScrolling:"touch",willChange:"transform"},{direction:h.direction,height:Ke(h.height)?`${h.height}px`:h.height,width:Ke(h.width)?`${h.width}px`:h.width},h.style??{}]),H=x(()=>{const ge=`${i(O)}px`;return{height:`${i(F)}px`,pointerEvents:i(N).isScrolling?"none":void 0,width:ge,margin:0,boxSizing:"border-box"}}),z=()=>{const{totalColumn:ge,totalRow:Oe}=h;if(ge>0&&Oe>0){const[Xe,_t,Rt,Ut]=i(U),[$t,jt,an,ke]=i(D);g(jd,{columnCacheStart:Xe,columnCacheEnd:_t,rowCacheStart:$t,rowCacheEnd:jt,columnVisibleStart:Rt,columnVisibleEnd:Ut,rowVisibleStart:an,rowVisibleEnd:ke})}const{scrollLeft:_e,scrollTop:$e,updateRequested:ze,xAxisScrollDir:Qe,yAxisScrollDir:et}=i(N);g(Wd,{xAxisScrollDir:Qe,scrollLeft:_e,yAxisScrollDir:et,scrollTop:$e,updateRequested:ze})},W=ge=>{const{clientHeight:Oe,clientWidth:_e,scrollHeight:$e,scrollLeft:ze,scrollTop:Qe,scrollWidth:et}=ge.currentTarget,Xe=i(N);if(Xe.scrollTop===Qe&&Xe.scrollLeft===ze)return;let _t=ze;if(r4(h.direction))switch(Yd()){case $u:_t=-ze;break;case Tv:_t=et-_e-ze;break}N.value={...Xe,isScrolling:!0,scrollLeft:_t,scrollTop:Math.max(0,Math.min(Qe,$e-Oe)),updateRequested:!0,xAxisScrollDir:Ui(Xe.scrollLeft,_t),yAxisScrollDir:Ui(Xe.scrollTop,Qe)},Ie(()=>K()),Y(),z()},q=(ge,Oe)=>{const _e=i($),$e=(F.value-_e)/Oe*ge;ee({scrollTop:Math.min(F.value-_e,$e)})},Q=(ge,Oe)=>{const _e=i(V),$e=(O.value-_e)/Oe*ge;ee({scrollLeft:Math.min(O.value-_e,$e)})},{onWheel:ne}=WU({atXStartEdge:x(()=>N.value.scrollLeft<=0),atXEndEdge:x(()=>N.value.scrollLeft>=O.value-i(V)),atYStartEdge:x(()=>N.value.scrollTop<=0),atYEndEdge:x(()=>N.value.scrollTop>=F.value-i($))},(ge,Oe)=>{var ze,Qe,et,Xe;(Qe=(ze=M.value)==null?void 0:ze.onMouseUp)==null||Qe.call(ze),(Xe=(et=E.value)==null?void 0:et.onMouseUp)==null||Xe.call(et);const _e=i(V),$e=i($);ee({scrollLeft:Math.min(N.value.scrollLeft+ge,O.value-_e),scrollTop:Math.min(N.value.scrollTop+Oe,F.value-$e)})});Kt(k,"wheel",ne,{passive:!1});const ee=({scrollLeft:ge=N.value.scrollLeft,scrollTop:Oe=N.value.scrollTop})=>{ge=Math.max(ge,0),Oe=Math.max(Oe,0);const _e=i(N);Oe===_e.scrollTop&&ge===_e.scrollLeft||(N.value={..._e,xAxisScrollDir:Ui(_e.scrollLeft,ge),yAxisScrollDir:Ui(_e.scrollTop,Oe),scrollLeft:ge,scrollTop:Oe,updateRequested:!0},Ie(()=>K()),Y(),z())},{touchStartX:oe,touchStartY:X,handleTouchStart:ie,handleTouchMove:ue}=qU(k,N,ee,O,F,V,$),G=(ge=0,Oe=0,_e=to)=>{const $e=i(N);Oe=Math.max(0,Math.min(Oe,h.totalColumn-1)),ge=Math.max(0,Math.min(ge,h.totalR Line truncated
"columnWidth" must be passed as number,
instead ${typeof e} was given.
`),Ke(t)||pn(i4,`
"columnWidth" must be passed as number,
instead ${typeof t} was given.
`)}}),{max:Gd,min:Fw,floor:Kw}=Math,u4="ElDynamicSizeGrid",YU={column:"columnWidth",row:"rowHeight"},E2={column:"lastVisitedColumnIndex",row:"lastVisitedRowIndex"},dr=(e,t,n,a)=>{const[o,r,l]=[n[a],e[YU[a]],n[E2[a]]];if(t>l){let s=0;if(l>=0){const u=o[l];s=u.offset+u.size}for(let u=l+1;u<=t;u++){const c=r(u);o[u]={offset:s,size:c},s+=c}n[E2[a]]=t}return o[t]},jw=(e,t,n,a,o,r)=>{for(;n<=a;){const l=n+Kw((a-n)/2),s=dr(e,l,t,r).offset;if(s===o)return l;s<o?n=l+1:a=l-1}return Gd(0,n-1)},GU=(e,t,n,a,o)=>{const r=o==="column"?e.totalColumn:e.totalRow;let l=1;for(;n<r&&dr(e,n,t,o).offset<a;)n+=l,l*=2;return jw(e,t,Kw(n/2),Fw(n,r-1),a,o)},c4=(e,t,n,a)=>{const[o,r]=[t[a],t[E2[a]]];return(r>0?o[r].offset:0)>=n?jw(e,t,0,r,n,a):GU(e,t,Gd(0,r),n,a)},Ww=({totalRow:e},{estimatedRowHeight:t,lastVisitedRowIndex:n,row:a})=>{let o=0;if(n>=e&&(n=e-1),n>=0){const l=a[n];o=l.offset+l.size}const r=(e-n-1)*t;return o+r},qw=({totalColumn:e},{column:t,estimatedColumnWidth:n,lastVisitedColumnIndex:a})=>{let o=0;if(a>e&&(a=e-1),a>=0){const l=t[a];o=l.offset+l.size}const r=(e-a-1)*n;return o+r},XU={column:qw,row:Ww},d4=(e,t,n,a,o,r,l)=>{const[s,u]=[r==="row"?e.height:e.width,XU[r]],c=dr(e,t,o,r),d=Gd(0,Fw(u(e,o)-s,c.offset)),f=Gd(0,c.offset-s+l+c.size);switch(n==="smart"&&(a>=f-s&&a<=d+s?n=to:n=jo),n){case Nu:return d;case"end":return f;case jo:return Math.round(f+(d-f)/2);case to:default:return a>=f&&a<=d?a:f>d||a<f?f:d}},JU=Hw({name:"ElDynamicSizeGrid",getColumnPosition:(e,t,n)=>{const a=dr(e,t,n,"column");return[a.size,a.offset]},getRowPosition:(e,t,n)=>{const a=dr(e,t,n,"row");return[a.size,a.offset]},getColumnOffset:(e,t,n,a,o,r)=>d4(e,t,n,a,o,"column",r),getRowOffset:(e,t,n,a,o,r)=>d4(e,t,n,a,o,"row",r),getColumnStartIndexForOffset:(e,t,n)=>c4(e,n,t,"column"),getColumnStopIndexForStartIndex:(e,t,n,a)=>{const o=dr(e,t,a,"column"),r=n+e.width;let l=o.offset+o.size,s=t;for(;s<e.totalColumn-1&&l<r;)s++,l+=dr(e,t,a,"column").size;return s},getEstimatedTotalHeight:Ww,getEstimatedTotalWidth:qw,getRowStartIndexForOffset:(e,t,n)=>c4(e,n,t,"row"),getRowStopIndexForStartIndex:(e,t,n,a)=>{const{totalRow:o,height:r}=e,l=dr(e,t,a,"row"),s=n+r;let u=l.size+l.offset,c=t;for(;c<o-1&&u<s;)c++,u+=dr(e,c,a,"row").size;return c},injectToInstance:(e,t)=>{const n=({columnIndex:r,rowIndex:l},s)=>{var u,c;s=Ot(s)?!0:s,Ke(r)&&(t.value.lastVisitedColumnIndex=Math.min(t.value.lastVisitedColumnIndex,r-1)),Ke(l)&&(t.value.lastVisitedRowIndex=Math.min(t.value.lastVisitedRowIndex,l-1)),(u=e.exposed)==null||u.getItemStyleCache.value(-1,null,null),s&&((c=e.proxy)==null||c.$forceUpdate())},a=(r,l)=>{n({columnIndex:r},l)},o=(r,l)=>{n({rowIndex:r},l)};Object.assign(e.proxy,{resetAfterColumnIndex:a,resetAfterRowIndex:o,resetAfter:n})},initCache:({estimatedColumnWidth:e=50,estimatedRowHeight:t=50})=>({column:{},estimatedColumnWidth:e,estimatedRowHeight:t,lastVisitedColumnIndex:-1,lastVisitedRowIndex:-1,row:{}}),clearCache:!1,validateProps:({columnWidth:e,rowHeight:t})=>{Ue(e)||pn(u4,`
"columnWidth" must be passed as function,
instead ${typeof e} was given.
`),Ue(t)||pn(u4,`
"rowHeight" must be passed as function,
instead ${typeof t} was given.
`)}}),Uw={modelValue:{type:[Number,String,Boolean],default:void 0},label:{type:[String,Boolean,Number,Object],default:void 0},value:{type:[String,Boolean,Number,Object],default:void 0},indeterminate:Boolean,disabled:{type:Boolean,default:void 0},checked:Boolean,name:{type:String,default:void 0},trueValue:{type:[String,Number],default:void 0},falseValue:{type:[String,Number],default:void 0},trueLabel:{type:[String,Number],default:void 0},falseLabel:{type:[String,Number],default:void 0},id:{type:String,default:void 0},border:Boolean,size:Ln,tabindex:[String,Number],validateEvent:{type:Boolean,default:!0},ariaLabel:String,...ya(["ariaControls"])},Yw={[st]:e=>Be(e)||Ke(e)||Yt(e),change:e=>Be(e)||Ke(e)||Yt(e)},yi=Symbol("checkboxGroupContextKey"),ZU=Te({modelValue:{type:J(Array),default:()=>[]},disabled:{type:Boolean,default:void 0},min:Number,max:Number,size:Ln,fill:String,textColor:String,tag:{type:String,default:"div"},validateEvent:{type:Boolean,default:!0},options:{type:J(Array)},props:{type:J(Object),default:()=>Gw},type:{type:String,values:["checkbox","button"],default:"checkbox"},...ya(["ariaLabel"])}),QU={[st]:e=>we(e),change:e=>we(e)},Gw={label:"label",value:"value",disabled:"disabled"},eY=({model:e,isChecked:t})=>{const n=Le(yi,void 0),a=Le(hs,void 0),o=x(()=>{var s,u;const r=(s=n==null?void 0:n.max)==null?void 0:s.value,l=(u=n==null?void 0:n.min)==null?void 0:u.value;return!Ot(r)&&e.value.length>=r&&!t.value||!Ot(l)&&e.value.length<=l&&t.value});return{isDisabled:dn(x(()=>{var r;return n===void 0?(a==null?void 0:a.disabled)??o.value:((r=n.disabled)==null?void 0:r.value)||o.value})),isLimitDisabled:o}},tY=(e,{model:t,isLimitExceeded:n,hasOwnLabel:a,isDisabled:o,isLabeledByFormItem:r})=>{const l=Le(yi,void 0),{formItem:s}=qn(),{emit:u}=gt();function c(v){return[!0,e.trueValue,e.trueLabel].includes(v)?e.trueValue??e.trueLabel??!0:e.falseValue??e.falseLabel??!1}function d(v,h){u(wt,c(v),h)}function f(v){if(n.value)return;const h=v.target;u(wt,c(h.checked),v)}async function p(v){n.value||!a.value&&!o.value&&r.value&&(v.composedPath().some(h=>h.tagName==="LABEL")||(t.value=c([!1,e.falseValue,e.falseLabel].includes(t.value)),await Ie(),d(t.value,v)))}const m=x(()=>(l==null?void 0:l.validateEvent)||e.validateEvent);return fe(()=>e.modelValue,()=>{m.value&&(s==null||s.validate("change").catch(ht))}),{handleChange:f,onClickRoot:p}},nY=e=>{const t=B(!1),{emit:n,vnode:a}=gt(),o=Le(yi,void 0),r=x(()=>Ot(o)===!1),l=B(!1),s=x(()=>{const c=a.props??{};return"modelValue"in c||"model-value"in c}),u=x({get(){var c;return r.value?(c=o==null?void 0:o.modelValue)==null?void 0:c.value:s.value?e.modelValue:t.value},set(c){var d,f;r.value&&we(c)?(l.value=((d=o==null?void 0:o.max)==null?void 0:d.value)!==void 0&&c.length>(o==null?void 0:o.max.value)&&c.length>u.value.length,l.value===!1&&((f=o==null?void 0:o.changeEvent)==null||f.call(o,c))):(n(st,c),t.value=c)}});return{model:u,isGroup:r,isLimitExceeded:l}},aY=(e,t,{model:n})=>{const a=Le(yi,void 0),o=B(!1),r=x(()=>Fa(e.value)?e.label:e.value),l=x(()=>{const s=n.value;return Yt(s)?s:we(s)?it(r.value)?s.map(Qt).some(u=>vn(u,r.value)):s.map(Qt).includes(r.value):s!=null?s===e.trueValue||s===e.trueLabel:!!s});return{checkboxButtonSize:Nn(x(()=>{var s;return(s=a==null?void 0:a.size)==null?void 0:s.value}),{prop:!0}),isChecked:l,isFocused:o,checkboxSize:Nn(x(()=>{var s;return(s=a==null?void 0:a.size)==null?void 0:s.value})),hasOwnLabel:x(()=>!!t.default||!Fa(r.value)),actualValue:r}},Xw=(e,t)=>{const{formItem:n}=qn(),{model:a,isGroup:o,isLimitExceeded:r}=nY(e),{isFocused:l,isChecked:s,checkboxButtonSize:u,checkboxSize:c,hasOwnLabel:d,actualValue:f}=aY(e,t,{model:a}),{isDisabled:p}=eY({model:a,isChecked:s}),{inputId:m,isLabeledByFormItem:v}=Va(e,{formItemContext:n,disableIdGeneration:d,disableIdManagement:o}),{handleChange:h,onClickRoot:g}=tY(e,{model:a,isLimitExceeded:r,hasOwnLabel:d,isDisabled:p,isLabeledByFormItem:v});return(()=>{function b(){we(a.value)&&!a.value.includes(f.value)?a.value.push(f.value):a.value=e.trueValue??e.trueLabel??!0}e.checked&&b()})(),Wo({from:"label act as value",replacement:"value",version:"3.0.0",scope:"el-checkbox",ref:"https://element-plus.org/en-US/component/checkbox.html"},x(()=>o.value&&Fa(e.value))),Wo({from:"true-label",replacement:"true-value",version:"3.0.0",scope:"el-checkbox",ref:"https://element-plus.org/en-US/component/checkbox.html"},x(()=>!!e.trueLabel)),Wo({from:"false-label",replacement:"false-value",version:"3.0.0",scope:"el-checkbox",ref:"https://element-plus.org/en-US/component/checkbox.html"},x(()=>!!e.falseLabel)),{inputId:m,isLabeledByFormItem:v,isChecked:s,isDisabled:p,isFocused:l,checkboxButtonSize:u,checkboxSize:c,hasOwnLabel:d,model:a,actualValue:f,handleChange:h,onClickRoot:g}},oY=["id","indeterminate","name","tabindex","disabled"];var rY=j({name:"ElCheckbox",__name:"checkbox",props:Uw,emits:Yw,setup(e){const t=e,{inputId:n,isLabeledByFormItem:a,isChecked:o,isDisabled:r,isFocused:l,checkboxSize:s,hasOwnLabel:u,mode Line truncated
Add an empty element to avoid render label,
do not use empty fragment here for https://github.com/vuejs/vue-next/pull/2485
`),N[2]||(N[2]=A("span",null,null,-1))]),_:1},8,["model-value","label","disabled"])):p.value&&e.node.checked?(_(),de(i(De),{key:2,class:I(i(r).e("prefix"))},{default:re(()=>[te(i(es))]),_:1},8,["class"])):se("v-if",!0),se(" content "),te(i(SY),{node:e.node},null,8,["node"]),se(" postfix "),p.value?se("v-if",!0):(_(),R(je,{key:3},[e.node.loading?(_(),de(i(De),{key:0,class:I([i(r).is("loading"),i(r).e("postfix")])},{default:re(()=>[te(i(uo))]),_:1},8,["class"])):(_(),de(i(De),{key:1,class:I(["arrow-right",i(r).e("postfix")])},{default:re(()=>[te(i(oa))]),_:1},8,["class"]))],64))],42,xY))}}),f4=kY,EY=j({name:"ElCascaderMenu",__name:"menu",props:{nodes:{type:Array,required:!0},index:{type:Number,required:!0},virtualScroll:{type:Boolean,required:!1,default:!1},itemSize:{type:Number,required:!1,default:34},height:{type:Number,required:!1,default:204}},setup(e,{expose:t}){const n=e,a=gt(),o=be("cascader-menu"),{t:r}=kt(),l=na();let s,u;const c=Le(e0),d=B(),f=B(),p=x(()=>!n.nodes.length),m=x(()=>!c.initialLoaded),v=x(()=>`${l.value}-${n.index}`),h=()=>{var E,T,N,P;let M;if(c.expandingNode){const{level:$,pathNodes:V}=c.expandingNode;n.index<$?M=(E=V[n.index])==null?void 0:E.uid:n.index===$&&c.checkedNodes.length>0&&(M=(N=(T=c.checkedNodes[0])==null?void 0:T.pathNodes[n.index])==null?void 0:N.uid)}else c.checkedNodes.length>0&&n.index<c.checkedNodes[0].pathNodes.length&&(M=(P=c.checkedNodes[0].pathNodes[n.index])==null?void 0:P.uid);return M!==void 0?n.nodes.findIndex($=>$.uid===M):-1},g=M=>M?n.nodes.findIndex(E=>`${v.value}-${E.uid}`===M):-1,y=M=>{var T;const E=Ra(M,0,n.nodes.length-1);(T=f.value)==null||T.scrollToItem(E)},b=M=>{if(!n.nodes.length)return;const E=Ra(M,0,n.nodes.length-1);y(E),Ie(()=>{var N;const T=(N=a.vnode.el)==null?void 0:N.querySelector(`#${v.value}-${n.nodes[E].uid}`);T&&Bs(T)})},C=M=>{s=M.target},w=M=>{var E,T,N;if(!(!c.isHoverMenu||!s||!d.value))if(s.contains(M.target)){S();const P=a.vnode.el,{left:$}=P.getBoundingClientRect(),{offsetWidth:V,offsetHeight:U}=P,D=M.clientX-$,F=s.offsetTop,O=F+s.offsetHeight,L=n.virtualScroll?((T=(E=f.value)==null?void 0:E.states)==null?void 0:T.scrollOffset)||0:((N=P.querySelector(`.${o.e("wrap")}`))==null?void 0:N.scrollTop)||0;d.value.innerHTML=`
<path style="pointer-events: auto;" fill="transparent" d="M${D} ${F} L${V} ${L} V${F} Z" />
<path style="pointer-events: auto;" fill="transparent" d="M${D} ${O} L${V} ${U+L} V${O} Z" />
`}else u||(u=window.setTimeout(k,c.config.hoverThreshold))},S=()=>{u&&(clearTimeout(u),u=void 0)},k=()=>{d.value&&(d.value.innerHTML="",S())};return t({getActiveNodeIndex:h,getNodeIndexById:g,scrollToItem:y,focusNodeAt:b,virtualListRef:f,get $el(){return a.vnode.el}}),(M,E)=>{var T;return e.virtualScroll?(_(),R("div",{key:v.value,class:I(i(o).b()),onMousemove:w,onMouseleave:k},[te(i(hc),{ref_key:"virtualListRef",ref:f,height:e.height,"item-size":e.itemSize,data:e.nodes,total:e.nodes.length,"class-name":i(o).e("list"),"inner-element":"ul","inner-props":{role:"menu",class:i(o).is("empty",p.value)}},{default:re(({data:N,index:P,style:$})=>[(_(),de(f4,{key:N[P].uid,node:N[P],"menu-id":v.value,style:Ye($),onExpand:C},null,8,["node","menu-id","style"]))]),_:1},8,["height","item-size","data","total","class-name","inner-props"]),m.value?(_(),R("div",{key:0,class:I(i(o).e("empty-text"))},[te(i(De),{size:14,class:I(i(o).is("loading"))},{default:re(()=>[te(i(uo))]),_:1},8,["class"]),xt(" "+Ee(i(r)("el.cascader.loading")),1)],2)):p.value?(_(),R("div",{key:1,class:I(i(o).e("empty-text"))},[le(M.$slots,"empty",{},()=>[xt(Ee(i(r)("el.cascader.noData")),1)])],2)):(T=i(c))!=null&&T.isHoverMenu?(_(),R(je,{key:2},[se(" eslint-disable vue/html-self-closing "),(_(),R("svg",{ref_key:"hoverZone",ref:d,class:I(i(o).e("hover-zone"))},null,2))],2112)):se("v-if",!0),se(" eslint-enable vue/html-self-closing ")],34)):(_(),de(i(Eo),{key:v.value,tag:"ul",role:"menu",class:I(i(o).b()),"wrap-class":i(o).e("wrap"),"view-class":[i(o).e("list"),i(o).is("empty",p.value)],onMousemove:w,onMouseleave:k},{default:re(()=>{var N;return[(_(!0),R(je,null,St(e.nodes,P=>(_(),de(f4,{key:P.uid,node:P,"menu-id":v.value,onExpand:C},null,8,["node","menu-id"]))),128)),m.value?(_(),R("div",{key:0,class:I(i(o).e("empty-text"))},[te(i(De),{size:14,class:I(i(o).is("loading"))},{default:re(()=>[te(i(uo))]),_:1},8,["class"]),xt(" "+Ee(i(r)("el.cascader.loading")),1)],2)):p.value?(_(),R("div",{key:1,class:I(i(o).e("empty-text"))},[le(M.$slots,"empty",{},()=>[xt(Ee(i(r)("el.cascader.noData")),1)])],2)):(N=i(c))!=null&&N.isHoverMenu?(_(),R(je,{key:2},[se(" eslint-disable vue/html-self-closing "),(_(),R("svg",{ref_key:"hoverZone",ref:d,class:I(i(o).e("hover-zone"))},null,2))],2112)):se("v-if",!0),se(" eslint-enable vue/html-self-closing ")]}),_:3},8,["class","wrap-class","view-class"]))}}}),TY=EY;let MY=0;const OY=e=>{const t=[e];let{parent:n}=e;for(;n;)t.unshift(n),n=n.parent;return t};var T2=class M2{constructor(t,n,a,o=!1){this.data=t,this.config=n,this.parent=a,this.root=o,this.uid=MY++,this.checked=!1,this.indeterminate=!1,this.loading=!1;const{value:r,label:l,children:s}=n,u=t[s],c=OY(this);this.level=o?0:a?a.level+1:1,this.value=t[r],this.label=t[l],this.pathNodes=c,this.pathValues=c.map(d=>d.value),this.pathLabels=c.map(d=>d.label),this.childrenData=u,this.children=(u||[]).map(d=>new M2(d,n,this)),this.loaded=!n.lazy||this.isLeaf||!ka(u),this.text=""}get isDisabled(){const{data:t,parent:n,config:a}=this,{disabled:o,checkStrictly:r}=a;return(Ue(o)?o(t,this):!!t[o])||!r&&!!(n!=null&&n.isDisabled)}get isLeaf(){const{data:t,config:n,childrenData:a,loaded:o}=this,{lazy:r,leaf:l}=n,s=Ue(l)?l(t,this):t[l];return Ot(s)?r&&!o?!1:!(we(a)&&a.length):!!s}get valueByOption(){return this.config.emitPath?this.pathValues:this.value}appendChild(t){const{childrenData:n,children:a}=this,o=new M2(t,this.config,this);return we(n)?n.push(t):this.childrenData=[t],a.push(o),o}calcText(t,n){const a=t?this.pathLabels.join(n):this.label;return this.text=a,a}broadcast(t){this.children.forEach(n=>{var a;n&&(n.broadcast(t),(a=n.onParentCheck)==null||a.call(n,t))})}emit(){var n;const{parent:t}=this;t&&((n=t.onChildCheck)==null||n.call(t),t.emit())}onParentCheck(t){this.isDisabled||this.setCheckState(t)}onChildCheck(){const{children:t}=this,n=t.filter(o=>!o.isDisabled),a=n.length?n.every(o=>o.checked):!1;this.setCheckState(a)}setCheckState(t){const n=this.children.length,a=this.children.reduce((o,r)=>o+(r.checked?1:r.indeterminate?.5:0),0);this.checked=this.loaded&&this.children.filter(o=>!o.isDisabled).every(o=>o.loaded&&o.checked)&&t,this.indeterminate=this.loaded&&a!==n&&a>0}doCheck(t){if(this.checked===t)return;const{checkStrictly:n,multiple:a}=this.config;n||!a?this.checked=t:(this.broadcast(t),this.setCheckState(t),this.emit())}};const O2=(e,t)=>e.reduce((n,a)=>(a.isLeaf?n.push(a):(!t&&n.push(a),n=n.concat(O2(a.children,t))),n),[]);var p4=class{constructor(e,t){this.config=t;const n=(e||[]).map(a=>new T2(a,this.config));this.nodes=n,this.allNodes=O2(n,!1),this.leafNodes=O2(n,!0)}getNodes(){return this.nodes}getFlattedNodes(e){return e?this.leafNodes:this.allNodes}appendNode(e,t){const n=t?t.appendChild(e):new T2(e,this.config);t||this.nodes.push(n),this.appendAllNodesAndLeafNodes(n)}appendNodes(e,t){e.length>0?e.forEach(n=>this.appendNode(n,t)):t&&t.isLeaf&&this.leafNodes.push(t)}appendAllNodesAndLeafNodes(e){this.allNodes.push(e),e.isLeaf&&this.leafNodes.push(e),e.children&&e. Line truncated
M 50 50
m 0 ${w?"":"-"}${C}
a ${C} ${C} 0 1 1 0 ${w?"-":""}${C*2}
a ${C} ${C} 0 1 1 0 ${w?"":"-"}${C*2}
`}),u=x(()=>2*Math.PI*l.value),c=x(()=>n.type==="dashboard"?.75:1),d=x(()=>`${-1*u.value*(1-c.value)/2}px`),f=x(()=>({strokeDasharray:`${u.value*c.value}px, ${u.value}px`,strokeDashoffset:d.value})),p=x(()=>({strokeDasharray:`${u.value*c.value*(n.percentage/100)}px, ${u.value}px`,strokeDashoffset:d.value,transition:"stroke-dasharray 0.6s ease 0s, stroke 0.6s ease, opacity ease 0.6s"})),m=x(()=>{let C;return n.color?C=b(n.percentage):C=t[n.status]||t.default,C}),v=x(()=>n.status==="warning"?cc:n.type==="line"?n.status==="success"?Gf:$o:n.status==="success"?es:Ya),h=x(()=>n.type==="line"?12+n.strokeWidth*.4:n.width*.111111+2),g=x(()=>n.format(n.percentage));function y(C){const w=100/C.length;return C.map((S,k)=>Be(S)?{color:S,percentage:(k+1)*w}:S).sort((S,k)=>S.percentage-k.percentage)}const b=C=>{var S;const{color:w}=n;if(Ue(w))return w(C);if(Be(w))return w;{const k=y(w);for(const M of k)if(M.percentage>C)return M.color;return(S=k[k.length-1])==null?void 0:S.color}};return(C,w)=>(_(),R("div",{class:I([i(a).b(),i(a).m(e.type),i(a).is(e.status),{[i(a).m("without-text")]:!e.showText,[i(a).m("text-inside")]:e.textInside}]),role:"progressbar","aria-valuenow":e.percentage,"aria-valuemin":"0","aria-valuemax":"100"},[e.type==="line"?(_(),R("div",{key:0,class:I(i(a).b("bar"))},[A("div",{class:I(i(a).be("bar","outer")),style:Ye({height:`${e.strokeWidth}px`})},[A("div",{class:I([i(a).be("bar","inner"),{[i(a).bem("bar","inner","indeterminate")]:e.indeterminate},{[i(a).bem("bar","inner","striped")]:e.striped},{[i(a).bem("bar","inner","striped-flow")]:e.stripedFlow}]),style:Ye(o.value)},[(e.showText||C.$slots.default)&&e.textInside?(_(),R("div",{key:0,class:I(i(a).be("bar","innerText"))},[le(C.$slots,"default",{percentage:e.percentage},()=>[A("span",null,Ee(g.value),1)])],2)):se("v-if",!0)],6)],6)],2)):(_(),R("div",{key:1,class:I(i(a).b("circle")),style:Ye({height:`${e.width}px`,width:`${e.width}px`})},[(_(),R("svg",une,[A("path",{class:I(i(a).be("circle","track")),d:s.value,stroke:`var(${i(a).cssVarName("fill-color-light")}, #e5e9f2)`,"stroke-linecap":e.strokeLinecap,"stroke-width":r.value,fill:"none",style:Ye(f.value)},null,14,cne),A("path",{class:I(i(a).be("circle","path")),d:s.value,stroke:m.value,fill:"none",opacity:e.percentage?1:0,"stroke-linecap":e.strokeLinecap,"stroke-width":r.value,style:Ye(p.value)},null,14,dne)]))],6)),(e.showText||C.$slots.default)&&!e.textInside?(_(),R("div",{key:2,class:I(i(a).e("text")),style:Ye({fontSize:`${h.value}px`})},[le(C.$slots,"default",{percentage:e.percentage},()=>[e.status?(_(),de(i(De),{key:1},{default:re(()=>[(_(),de(dt(v.value)))]),_:1})):(_(),R("span",fne,Ee(g.value),1))])],6)):se("v-if",!0)],10,ine))}}),hne=pne;const zv=ut(hne),vne=Te({modelValue:{type:Number,default:0},id:{type:String,default:void 0},lowThreshold:{type:Number,default:2},highThreshold:{type:Number,default:4},max:{type:Number,default:5},colors:{type:J([Array,Object]),default:()=>mn(["","",""])},voidColor:{type:String,default:""},disabledVoidColor:{type:String,default:""},icons:{type:J([Array,Object]),default:()=>[ji,ji,ji]},voidIcon:{type:Gt,default:()=>I8},disabledVoidIcon:{type:Gt,default:()=>ji},disabled:{type:Boolean,default:void 0},allowHalf:Boolean,showText:Boolean,showScore:Boolean,textColor:{type:String,default:""},texts:{type:J(Array),default:()=>mn(["Extremely bad","Disappointed","Fair","Satisfied","Surprise"])},scoreTemplate:{type:String,default:"{value}"},size:Ln,clearable:Boolean,...ya(["ariaLabel"])}),mne={[wt]:e=>Ke(e),[st]:e=>Ke(e)},gne=["id","aria-label","aria-labelledby","aria-valuenow","aria-valuetext","aria-valuemax","tabindex","aria-disabled"],yne=["onMousemove","onClick"];var bne=j({name:"ElRate",__name:"rate",props:vne,emits:mne,setup(e,{expose:t,emit:n}){function a(L,H){const z=q=>it(q),W=H[Object.keys(H).map(q=>+q).filter(q=>{const Q=H[q];return z(Q)&&Q.excluded?L<q:L<=q}).sort((q,Q)=>q-Q)[0]];return z(W)&&W.value||W}const o=e,r=n,l=Le(tr,void 0),s=Nn(),u=be("rate"),{inputId:c,isLabeledByFormItem:d}=Va(o,{formItemContext:l}),f=B(Ra(o.modelValue,0,o.max)),p=B(-1),m=B(!0),v=B([]),h=x(()=>v.value.map(L=>L.$el.clientWidth)),g=x(()=>[u.b(),u.m(s.value)]),y=dn(),b=x(()=>u.cssVarBlock({"void-color":o.voidColor,"disabled-void-color":o.disabledVoidColor,"fill-color":k.value})),C=x(()=>{let L="";return o.showScore?L=o.scoreTemplate.replace(/\{\s*value\s*\}/,y.value?`${o.modelValue}`:`${f.value}`):o.showText&&(L=o.texts[Math.ceil(f.value)-1]),L}),w=x(()=>o.modelValue*100-Math.floor(o.modelValue)*100),S=x(()=>we(o.colors)?{[o.lowThreshold]:o.colors[0],[o.highThreshold]:{value:o.colors[1],excluded:!0},[o.max]:o.colors[2]}:o.colors),k=x(()=>{const L=a(f.value,S.value);return it(L)?"":L}),M=x(()=>{let L="";return y.value?L=`${w.value}%`:o.allowHalf&&(L="50%"),{color:k.value,width:L}}),E=x(()=>{let L=we(o.icons)?[...o.icons]:{...o.icons};return L=no(L),we(L)?{[o.lowThreshold]:L[0],[o.highThreshold]:{value:L[1],excluded:!0},[o.max]:L[2]}:L}),T=x(()=>a(o.modelValue,E.value)),N=x(()=>y.va Line truncated
`||c==="\r")){l=u;continue}if(r.includes(c)){const d=l===-1?a:l;s={pattern:o.slice(u+1,d),start:u+1,end:d,prefix:c,prefixIndex:u,splitIndex:l,selectionEnd:a};break}}return s},Wie=(e,t={debug:!1,useSelectionEnd:!1})=>{const n=e.selectionStart!==null?e.selectionStart:0,a=e.selectionEnd!==null?e.selectionEnd:0,o=t.useSelectionEnd?a:n,r=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize","MozTabSize"];if(t.debug){const p=document.querySelector("#input-textarea-caret-position-mirror-div");p!=null&&p.parentNode&&p.parentNode.removeChild(p)}const l=document.createElement("div");l.id="input-textarea-caret-position-mirror-div",document.body.appendChild(l);const s=l.style,u=window.getComputedStyle(e),c=e.nodeName==="INPUT";s.whiteSpace=c?"nowrap":"pre-wrap",c||(s.wordWrap="break-word"),s.position="absolute",t.debug||(s.visibility="hidden"),r.forEach(p=>{if(c&&p==="lineHeight")if(u.boxSizing==="border-box"){const m=Number.parseInt(u.height),v=Number.parseInt(u.paddingTop)+Number.parseInt(u.paddingBottom)+Number.parseInt(u.borderTopWidth)+Number.parseInt(u.borderBottomWidth),h=v+Number.parseInt(u.lineHeight);m>h?s.lineHeight=`${m-v}px`:m===h?s.lineHeight=u.lineHeight:s.lineHeight="0"}else s.lineHeight=u.height;else s[p]=u[p]}),Af()?e.scrollHeight>Number.parseInt(u.height)&&(s.overflowY="scroll"):s.overflow="hidden",l.textContent=e.value.slice(0,Math.max(0,o)),c&&l.textContent&&(l.textContent=l.textContent.replace(/\s/g," "));const d=document.createElement("span");d.textContent=e.value.slice(Math.max(0,o))||".",d.style.position="relative",d.style.left=`${-e.scrollLeft}px`,d.style.top=`${-e.scrollTop}px`,l.appendChild(d);const f={top:d.offsetTop+Number.parseInt(u.borderTopWidth),left:d.offsetLeft+Number.parseInt(u.borderLeftWidth),height:Number.parseInt(u.fontSize)*1.5};return t.debug?d.style.backgroundColor="#aaa":document.body.removeChild(l),f.left>=e.clientWidth&&(f.left=e.clientWidth),f},qie=Te({...gv,options:{type:J(Array),default:()=>[]},prefix:{type:J([String,Array]),default:"@",validator:e=>Be(e)?e.length===1:e.every(t=>Be(t)&&t.length===1)},split:{type:String,default:" ",validator:e=>e.length===1},filterOption:{type:J([Boolean,Function]),default:()=>Kie,validator:e=>e===!1?!0:Ue(e)},placement:{type:J(String),default:"bottom"},showArrow:Boolean,offset:{type:Number,default:0},whole:Boolean,checkIsWhole:{type:J(Function)},modelValue:String,loading:Boolean,popperClass:nn.popperClass,popperStyle:nn.popperStyle,popperOptions:{type:J(Object),default:()=>({})},props:{type:J(Object),default:()=>r_}}),Uie={[st]:e=>Be(e),"whole-remove":(e,t)=>Be(e)&&Be(t),input:e=>Be(e),search:(e,t)=>Be(e)&&Be(t),select:(e,t)=>it(e)&&Be(t),focus:e=>e instanceof FocusEvent,blur:e=>e instanceof FocusEvent},r_={value:"value",label:"label",disabled:"disabled"},Yie=Te({options:{type:J(Array),default:()=>[]},loading:Boolean,disabled:Boolean,contentId:String,ariaLabel:String}),Gie={select:e=>Be(e.value)},Xie=["id","aria-disabled","aria-selected","onMousemove","onClick"];var Jie=j({name:"ElMentionDropdown",__name:"mention-dropdown",props:Yie,emits:Gie,setup(e,{expose:t,emit:n}){const a=e,o=n,r=be("mention"),{t:l}=kt(),s=B(-1),u=B(),c=B(),d=B(),f=(w,S)=>[r.be("dropdown","item"),r.is("hovering",s.value===S),r.is("disabled",w.disabled||a.disabled)],p=w=>{w.disabled||a.disabled||o("select",w)},m=w=>{s.value=w},v=x(()=>a.disabled||a.options.every(w=>w.disabled)),h=x(()=>a.options[s.value]),g=()=>{!h.value||h.value.disabled||a.disabled||o("select",h.value)},y=w=>{const{options:S}=a;if(S.length===0||v.value)return;w==="next"?(s.value++,s.value===S.length&&(s.value=0)):w==="prev"&&(s.value--,s.value<0&&(s.value=S.length-1));const k=S[s.value];if(k.disabled){y(w);return}Ie(()=>b(k))},b=w=>{var E,T,N,P;const{options:S}=a,k=S.findIndex($=>$.value===w.value),M=(E=c.value)==null?void 0:E[k];if(M){const $=(N=(T=d.value)==null?void 0:T.querySelector)==null?void 0:N.call(T,`.${r.be("dropdown","wrap")}`);$&&Wh($,M)}(P=u.value)==null||P.handleScroll()};return fe(()=>a.options,()=>{v.value||a.options.length===0?s.value=-1:s.value=a.options.findIndex(w=>!w.disabled)},{immediate:!0}),t({hoveringIndex:s,navigateOptions:y,selectHoverOption:g,hoverOption:h}),(w,S)=>(_(),R("div",{ref_key:"dropdownRef",ref:d,class:I(i(r).b("dropdown"))},[w.$slots.header?(_(),R("div",{key:0,class:I(i(r).be("dropdown","header"))},[le(w.$slots,"header")],2)):se("v-if",!0),vt(te(i(Eo),{id:e.contentId,ref_key:"scrollbarRef",ref:u,tag:"ul","wrap-class":i(r).be("dropdown","wrap"),"view-class":i(r).be("dropdown","list"),role:"listbox","aria-label":e.ariaLabel,"aria-orientation":"vertical"},{default:re(()=>[(_(!0),R(je,null,St(e.options,( Line truncated
* vue-router v4.6.4
* (c) 2025 Eduardo San Martin Morote
* @license MIT
*/const As=typeof document<"u";function h_(e){return typeof e=="object"||"displayName"in e||"props"in e||"__vccOpts"in e}function Cce(e){return e.__esModule||e[Symbol.toStringTag]==="Module"||e.default&&h_(e.default)}const fn=Object.assign;function up(e,t){const n={};for(const a in t){const o=t[a];n[a]=To(o)?o.map(e):e(o)}return n}const cu=()=>{},To=Array.isArray;function r3(e,t){const n={};for(const a in e)n[a]=a in t?t[a]:e[a];return n}const v_=/#/g,Sce=/&/g,xce=/\//g,kce=/=/g,Ece=/\?/g,m_=/\+/g,Tce=/%5B/g,Mce=/%5D/g,g_=/%5E/g,Oce=/%60/g,y_=/%7B/g,Ace=/%7C/g,b_=/%7D/g,Rce=/%20/g;function fm(e){return e==null?"":encodeURI(""+e).replace(Ace,"|").replace(Tce,"[").replace(Mce,"]")}function Nce(e){return fm(e).replace(y_,"{").replace(b_,"}").replace(g_,"^")}function Y2(e){return fm(e).replace(m_,"%2B").replace(Rce,"+").replace(v_,"%23").replace(Sce,"%26").replace(Oce,"`").replace(y_,"{").replace(b_,"}").replace(g_,"^")}function $ce(e){return Y2(e).replace(kce,"%3D")}function Pce(e){return fm(e).replace(v_,"%23").replace(Ece,"%3F")}function Ice(e){return Pce(e).replace(xce,"%2F")}function zu(e){if(e==null)return null;try{return decodeURIComponent(""+e)}catch{}return""+e}const Lce=/\/$/,Vce=e=>e.replace(Lce,"");function cp(e,t,n="/"){let a,o={},r="",l="";const s=t.indexOf("#");let u=t.indexOf("?");return u=s>=0&&u>s?-1:u,u>=0&&(a=t.slice(0,u),r=t.slice(u,s>0?s:t.length),o=e(r.slice(1))),s>=0&&(a=a||t.slice(0,s),l=t.slice(s,t.length)),a=Hce(a??t,n),{fullPath:a+r+l,path:a,query:o,hash:zu(l)}}function Bce(e,t){const n=t.query?e(t.query):"";return t.path+(n&&"?")+n+(t.hash||"")}function l3(e,t){return!t||!e.toLowerCase().startsWith(t.toLowerCase())?e:e.slice(t.length)||"/"}function Dce(e,t,n){const a=t.matched.length-1,o=n.matched.length-1;return a>-1&&a===o&&si(t.matched[a],n.matched[o])&&w_(t.params,n.params)&&e(t.query)===e(n.query)&&t.hash===n.hash}function si(e,t){return(e.aliasOf||e)===(t.aliasOf||t)}function w_(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(var n in e)if(!zce(e[n],t[n]))return!1;return!0}function zce(e,t){return To(e)?s3(e,t):To(t)?s3(t,e):(e==null?void 0:e.valueOf())===(t==null?void 0:t.valueOf())}function s3(e,t){return To(t)?e.length===t.length&&e.every((n,a)=>n===t[a]):e.length===1&&e[0]===t}function Hce(e,t){if(e.startsWith("/"))return e;if(!e)return t;const n=t.split("/"),a=e.split("/"),o=a[a.length-1];(o===".."||o===".")&&a.push("");let r=n.length-1,l,s;for(l=0;l<a.length;l++)if(s=a[l],s!==".")if(s==="..")r>1&&r--;else break;return n.slice(0,r).join("/")+"/"+a.slice(l).join("/")}const Fr={path:"/",name:void 0,params:{},query:{},hash:"",fullPath:"/",matched:[],meta:{},redirectedFrom:void 0};let G2=function(e){return e.pop="pop",e.push="push",e}({}),dp=function(e){return e.back="back",e.forward="forward",e.unknown="",e}({});function Fce(e){if(!e)if(As){const t=document.querySelector("base");e=t&&t.getAttribute("href")||"/",e=e.replace(/^\w+:\/\/[^\/]+/,"")}else e="/";return e[0]!=="/"&&e[0]!=="#"&&(e="/"+e),Vce(e)}const Kce=/^[^#]+#/;function jce(e,t){return e.replace(Kce,"#")+t}function Wce(e,t){const n=document.documentElement.getBoundingClientRect(),a=e.getBoundingClientRect();return{behavior:t.behavior,left:a.left-n.left-(t.left||0),top:a.top-n.top-(t.top||0)}}const c0=()=>({left:window.scrollX,top:window.scrollY});function qce(e){let t;if("el"in e){const n=e.el,a=typeof n=="string"&&n.startsWith("#"),o=typeof n=="string"?a?document.getElementById(n.slice(1)):document.querySelector(n):n;if(!o)return;t=Wce(o,e)}else t=e;"scrollBehavior"in document.documentElement.style?window.scrollTo(t):window.scrollTo(t.left!=null?t.left:window.scrollX,t.top!=null?t.top:window.scrollY)}function i3(e,t){return(history.state?history.state.position-t:-1)+e}const X2=new Map;function Uce(e,t){X2.set(e,t)}function Yce(e){const t=X2.get(e);return X2.delete(e),t}function Gce(e){return typeof e=="string"||e&&typeof e=="object"}function __(e){return typeof e=="string"||typeof e=="symbol"}let In=function(e){return e[e.MATCHER_NOT_FOUND=1]="MATCHER_NOT_FOUND",e[e.NAVIGATION_GUARD_REDIRECT=2]="NAVIGATION_GUARD_REDIRECT",e[e.NAVIGATION_ABORTED=4]="NAVIGATION_ABORTED",e[e.NAVIGATION_CANCELLED=8]="NAVIGATION_CANCELLED",e[e.NAVIGATION_DUPLICATED=16]="NAVIGATION_DUPLICATED",e}({});const C_=Symbol("");In.MATCHER_NOT_FOUND+"",In.NAVIGATION_GUARD_REDIRECT+"",In.NAVIGATION_ABORTED+"",In.NAVIGATION_CANCELLED+"",In.NAVIGATION_DUPLICATED+"";function ii(e,t){return fn(new Error,{type:e,[C_]:!0},t)}function ir(e,t){return e instanceof Error&&C_ in e&&(t==null||!!(e.type&t))}const Xce=["params","query","hash"];function Jce(e){if(typeof e=="string")return e;if(e.path!=null)return e.path;const t={};for(const n of Xce)n in e&&(t[n]=e[n]);return JSON.stringify(t,null,2)}function Zce(e){const t={};if(e===""||e==="?")return t;const n=(e[0]==="?"?e.slice(1):e).split("&");for(let a=0;a<n.length;++a){const o=n[a].replace(m_," "),r=o.indexOf("="),l=zu(r<0?o:o.slice(0,r)),s=r<0?null:zu(o.slice(r+1));if(l in t){let uLine truncated
* vue-router v4.6.4
* (c) 2025 Eduardo San Martin Morote
* @license MIT
*/let nde=()=>location.protocol+"//"+location.host;function S_(e,t){const{pathname:n,search:a,hash:o}=t,r=e.indexOf("#");if(r>-1){let l=o.includes(e.slice(r))?e.slice(r).length:1,s=o.slice(l);return s[0]!=="/"&&(s="/"+s),l3(s,"")}return l3(n,e)+a+o}function ade(e,t,n,a){let o=[],r=[],l=null;const s=({state:p})=>{const m=S_(e,location),v=n.value,h=t.value;let g=0;if(p){if(n.value=m,t.value=p,l&&l===v){l=null;return}g=h?p.position-h.position:0}else a(m);o.forEach(y=>{y(n.value,v,{delta:g,type:G2.pop,direction:g?g>0?dp.forward:dp.back:dp.unknown})})};function u(){l=n.value}function c(p){o.push(p);const m=()=>{const v=o.indexOf(p);v>-1&&o.splice(v,1)};return r.push(m),m}function d(){if(document.visibilityState==="hidden"){const{history:p}=window;if(!p.state)return;p.replaceState(fn({},p.state,{scroll:c0()}),"")}}function f(){for(const p of r)p();r=[],window.removeEventListener("popstate",s),window.removeEventListener("pagehide",d),document.removeEventListener("visibilitychange",d)}return window.addEventListener("popstate",s),window.addEventListener("pagehide",d),document.addEventListener("visibilitychange",d),{pauseListeners:u,listen:c,destroy:f}}function d3(e,t,n,a=!1,o=!1){return{back:e,current:t,forward:n,replaced:a,position:window.history.length,scroll:o?c0():null}}function ode(e){const{history:t,location:n}=window,a={value:S_(e,n)},o={value:t.state};o.value||r(a.value,{back:null,current:a.value,forward:null,position:t.length-1,replaced:!0,scroll:null},!0);function r(u,c,d){const f=e.indexOf("#"),p=f>-1?(n.host&&document.querySelector("base")?e:e.slice(f))+u:nde()+e+u;try{t[d?"replaceState":"pushState"](c,"",p),o.value=c}catch(m){console.error(m),n[d?"replace":"assign"](p)}}function l(u,c){r(u,fn({},t.state,d3(o.value.back,u,o.value.forward,!0),c,{position:o.value.position}),!0),a.value=u}function s(u,c){const d=fn({},o.value,t.state,{forward:u,scroll:c0()});r(d.current,d,!0),r(u,fn({},d3(a.value,u,null),{position:d.position+1},c),!1),a.value=u}return{location:a,state:o,push:s,replace:l}}function rde(e){e=Fce(e);const t=ode(e),n=ade(e,t.state,t.location,t.replace);function a(r,l=!0){l||n.pauseListeners(),history.go(r)}const o=fn({location:"",base:e,go:a,createHref:jce.bind(null,e)},t,n);return Object.defineProperty(o,"location",{enumerable:!0,get:()=>t.location.value}),Object.defineProperty(o,"state",{enumerable:!0,get:()=>t.state.value}),o}let Ll=function(e){return e[e.Static=0]="Static",e[e.Param=1]="Param",e[e.Group=2]="Group",e}({});var Un=function(e){return e[e.Static=0]="Static",e[e.Param=1]="Param",e[e.ParamRegExp=2]="ParamRegExp",e[e.ParamRegExpEnd=3]="ParamRegExpEnd",e[e.EscapeNext=4]="EscapeNext",e}(Un||{});const lde={type:Ll.Static,value:""},sde=/[a-zA-Z0-9_]/;function ide(e){if(!e)return[[]];if(e==="/")return[[lde]];if(!e.startsWith("/"))throw new Error(`Invalid path "${e}"`);function t(m){throw new Error(`ERR (${n})/"${c}": ${m}`)}let n=Un.Static,a=n;const o=[];let r;function l(){r&&o.push(r),r=[]}let s=0,u,c="",d="";function f(){c&&(n===Un.Static?r.push({type:Ll.Static,value:c}):n===Un.Param||n===Un.ParamRegExp||n===Un.ParamRegExpEnd?(r.length>1&&(u==="*"||u==="+")&&t(`A repeatable param (${c}) must be alone in its segment. eg: '/:ids+.`),r.push({type:Ll.Param,value:c,regexp:d,repeatable:u==="*"||u==="+",optional:u==="*"||u==="?"})):t("Invalid state to consume buffer"),c="")}function p(){c+=u}for(;s<e.length;){if(u=e[s++],u==="\\"&&n!==Un.ParamRegExp){a=n,n=Un.EscapeNext;continue}switch(n){case Un.Static:u==="/"?(c&&f(),l()):u===":"?(f(),n=Un.Param):p();break;case Un.EscapeNext:p(),n=a;break;case Un.Param:u==="("?n=Un.ParamRegExp:sde.test(u)?p():(f(),n=Un.Static,u!=="*"&&u!=="?"&&u!=="+"&&s--);break;case Un.ParamRegExp:u===")"?d[d.length-1]=="\\"?d=d.slice(0,-1)+u:n=Un.ParamRegExpEnd:d+=u;break;case Un.ParamRegExpEnd:f(),n=Un.Static,u!=="*"&&u!=="?"&&u!=="+"&&s--,d="";break;default:t("Unknown state");break}}return n===Un.ParamRegExp&&t(`Unfinished custom RegExp for param "${c}"`),f(),l(),o}const f3="[^/]+?",ude={sensitive:!1,strict:!1,start:!0,end:!0};var Sa=function(e){return e[e._multiplier=10]="_multiplier",e[e.Root=90]="Root",e[e.Segment=40]="Segment",e[e.SubSegment=30]="SubSegment",e[e.Static=40]="Static",e[e.Dynamic=20]="Dynamic",e[e.BonusCustomRegExp=10]="BonusCustomRegExp",e[e.BonusWildcard=-50]="BonusWildcard",e[e.BonusRepeatable=-20]="BonusRepeatable",e[e.BonusOptional=-8]="BonusOptional",e[e.BonusStrict=.7000000000000001]="BonusStrict",e[e.BonusCaseSensitive=.25]="BonusCaseSensitive",e}(Sa||{});const cde=/[.+*?^${}()[\]/\\]/g;function dde(e,t){const n=fn({},ude,t),a=[];let o=n.start?"^":"";const r=[];for(const c of e){const d=c.length?[]:[Sa.Root];n.strict&&!c.length&&(o+="/");for(let f=0;f<c.length;f++){const p=c[f];let m=Sa.Segment+(n.sensitive?Sa.BonusCaseSensitive:0);if(p.type===Ll.Static)f||(o+="/"),o+=p.value.replace(cde,"\\$&"),m+=Sa.Static;else if(p.type===Ll.Param){const{value:v,repeatable:h,optional:g,regexp:y}=p;r.push({name:v,repeatable:h,optional:g});const b=y||f3;if(Line truncated
`).forEach(function(l){o=l.indexOf(":"),n=l.substring(0,o).trim().toLowerCase(),a=l.substring(o+1).trim();const s=me.hasOwnProp(t,n);!n||s&&me.hasOwnProp(Cfe,n)||(n==="set-cookie"?s?t[n].push(a):t[n]=[a]:t[n]=s?t[n]+", "+a:a)}),t};function xfe(e){let t=0,n=e.length;for(;t<n;){const a=e.charCodeAt(t);if(a!==9&&a!==32)break;t+=1}for(;n>t;){const a=e.charCodeAt(n-1);if(a!==9&&a!==32)break;n-=1}return t===0&&n===e.length?e:e.slice(t,n)}const kfe=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),Efe=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function vm(e,t){return me.isArray(e)?e.map(n=>vm(n,t)):xfe(String(e).replace(t,""))}const Tfe=e=>vm(e,kfe),Mfe=e=>vm(e,Efe);function V_(e){const t=Object.create(null);return me.forEach(e.toJSON(),(n,a)=>{t[a]=Mfe(n)}),t}const S3=Symbol("internals");function Vi(e){return e&&String(e).trim().toLowerCase()}function vd(e){return e===!1||e==null?e:me.isArray(e)?e.map(vd):Tfe(String(e))}function Ofe(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let a;for(;a=n.exec(e);)t[a[1]]=a[2];return t}const Afe=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function pp(e){let t=0,n=e.length;for(;t<n;){const a=e.charCodeAt(t);if(a!==9&&a!==32)break;t+=1}for(;n>t;){const a=e.charCodeAt(n-1);if(a!==9&&a!==32)break;n-=1}return t===0&&n===e.length?e:e.slice(t,n)}function Rfe(e){const t=e.length-1;if(t<1||e.charCodeAt(0)!==34||e.charCodeAt(t)!==34)return e;let n="";for(let a=1;a<t;a++){const o=e.charCodeAt(a);if(o===34||o===92&&(a+=1,a>=t))return e;n+=e[a]}return n}function Nfe(e){const t=Object.create(null),n=String(e);let a=0,o=!1,r=!1;function l(s){const u=pp(n.slice(a,s)),c=u.indexOf("=");if(c<1)return;const d=pp(u.slice(0,c));if(!Afe.test(d))return;const f=d.toLowerCase();if(f==="__proto__"||f==="constructor"||f==="prototype")return;const p=pp(u.slice(c+1));t[f]=Rfe(p)}for(let s=0;s<n.length;s++){const u=n.charCodeAt(s);o?r?r=!1:u===92?r=!0:u===34&&(o=!1):u===34?o=!0:(u===44||u===59)&&(l(s),a=s+1)}return l(n.length),t}const $fe=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function hp(e,t,n,a,o){if(me.isFunction(a))return a.call(this,t,n);if(o&&(t=n),!!me.isString(t)){if(me.isString(a))return t.indexOf(a)!==-1;if(me.isRegExp(a))return a.test(t)}}function Pfe(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,a)=>n.toUpperCase()+a)}function Ife(e,t){const n=me.toCamelCase(" "+t);["get","set","has"].forEach(a=>{Object.defineProperty(e,a+n,{__proto__:null,value:function(o,r,l){return this[a].call(this,t,o,r,l)},configurable:!0})})}let va=class{constructor(t){t&&this.set(t)}set(t,n,a){const o=this;function r(s,u,c){const d=Vi(u);if(!d)return;const f=me.findKey(o,d);(!f||o[f]===void 0||c===!0||c===void 0&&o[f]!==!1)&&(o[f||u]=vd(s))}const l=(s,u)=>me.forEach(s,(c,d)=>r(c,d,u));if(me.isPlainObject(t)||t instanceof this.constructor)l(t,n);else if(me.isString(t)&&(t=t.trim())&&!$fe(t))l(Sfe(t),n);else if(me.isObject(t)&&me.isSafeIterable(t)){let s=Object.create(null),u,c;for(const d of t){if(!me.isArray(d))throw new TypeError("Object iterator must return a key-value pair");c=d[0],me.hasOwnProp(s,c)?(u=s[c],s[c]=me.isArray(u)?[...u,d[1]]:[u,d[1]]):s[c]=d[1]}l(s,n)}else t!=null&&r(n,t,a);return this}get(t,n){if(t=Vi(t),t){const a=me.findKey(this,t);if(a){const o=this[a];if(!n)return o;if(n===!0)return Ofe(o);if(me.isFunction(n))return n.call(this,o,a);if(me.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Vi(t),t){const a=me.findKey(this,t);return!!(a&&this[a]!==void 0&&(!n||hp(this,this[a],a,n)))}return!1}delete(t,n){const a=this;let o=!1;function r(l){if(l=Vi(l),l){const s=me.findKey(a,l);s&&(!n||hp(a,a[s],s,n))&&(delete a[s],o=!0)}}return me.isArray(t)?t.forEach(r):r(t),o}clear(t){const n=Object.keys(this);let a=n.length,o=!1;for(;a--;){const r=n[a];(!t||hp(this,this[r],r,t,!0))&&(delete this[r],o=!0)}return o}normalize(t){const n=this,a={};return me.forEach(this,(o,r)=>{const l=me.findKey(a,r);if(l){n[l]=vd(o),delete n[r];return}const s=t?Pfe(r):String(r).trim();s!==r&&delete n[r],n[s]=vd(o),a[s]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return me.forEach(this,(a,o)=>{a!=null&&a!==!1&&(n[o]=t&&me.isArray(a)?a.join(", "):a)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
`)}getSetCookie(){const t=this.get("set-cookie");return me.isArray(t)?t:t==null||t===!1?[]:[t]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static parseParameters(t){return Nfe(t)}static concat(t,...n){const a=new this(t);return n.forEach(o=>a.set(o)),a}static accessor(t){const a=(this[S3]=this[S3]={accessors:{}}).accessors,o=this.prototype;function r(l){const s=Vi(l);a[s]||(Ife(o,l),a[s]=!0)}return me.isArray(t)?t.forEach(r):r(t),this}};va.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);me.reduceDescriptors(va.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(a){this[n]=a}}});me.freezeMethods(va);const af="[REDACTED ****]";function Lfe(e){if(me.hasOwnProp(e,"toJSON"))return!0;let t=Object.getPrototypeOf(e);for(;t&&t!==Object.prototype;){if(me.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}function Vfe(e,t){const n=new Set(t.map(r=>String(r).toLowerCase())),a=[],o=r=>{if(r===null||typeof r!="object"||me.isBuffer(r))return r;if(a.indexOf(r)!==-1)return;r instanceof va&&(r=r.toJSON()),a.push(r);let l;if(me.isArray(r))l=[],r.forEach((s,u)=>{const c=o(s);me.isUndefined(c)||(l[u]=c)});else{if(!me.isPlainObject(r)&&Lfe(r))return a.pop(),r;l=Object.create(null);for(const[s,u]of Object.entries(r)){const c=n.has(s.toLowerCase())?af:o(u);me.isUndefined(c)||(l[s]=c)}}return a.pop(),l};return o(e)}function x3(e){try{return String(e)}catch{return""}}function Bfe(e){return e.errors.map(n=>{try{return n&&n.message?x3(n.message):x3(n)}catch{return""}}).filter(Boolean).join("; ")||e.name||"AggregateError"}let pt=class B_ extends Error{static from(t,n,a,o,r,l){let s=t.message;!s&&me.isArray(t.errors)&&t.errors.length&&(s=Bfe(t));const u=new B_(s,n||t.code,a,o,r);return Object.defineProperty(u,"cause",{__proto__:null,value:t,writable:!0,enumerable:!1,configurable:!0}),u.name=t.name,t.status!=null&&u.status==null&&(u.status=t.status),l&&Object.assign(u,l),u}constructor(t,n,a,o,r){super(t),Object.defineProperty(this,"message",{__proto__:null,value:t,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,n&&(this.code=n),a&&(this.config=a),o&&(this.request=o),r&&(this.response=r,this.status=r.status)}toJSON(){const t=this.config,n=t&&me.hasOwnProp(t,"redact")?t.redact:void 0,a=me.isArray(n)&&n.length>0?Vfe(t,n):me.toJSONObject(t);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:a,code:this.code,status:this.status}}};pt.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";pt.ERR_BAD_OPTION="ERR_BAD_OPTION";pt.ECONNABORTED="ECONNABORTED";pt.ETIMEDOUT="ETIMEDOUT";pt.ECONNREFUSED="ECONNREFUSED";pt.ERR_NETWORK="ERR_NETWORK";pt.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";pt.ERR_DEPRECATED="ERR_DEPRECATED";pt.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";pt.ERR_BAD_REQUEST="ERR_BAD_REQUEST";pt.ERR_CANCELED="ERR_CANCELED";pt.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";pt.ERR_INVALID_URL="ERR_INVALID_URL";pt.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const Dfe=null,D_=100;function Q2(e){return me.isPlainObject(e)||me.isArray(e)}function z_(e){return me.endsWith(e,"[]")?e.slice(0,-2):e}function vp(e,t,n){return e?e.concat(t).map(function(o,r){return o=z_(o),!n&&r?"["+o+"]":o}).join(n?".":""):t}function zfe(e){return me.isArray(e)&&!e.some(Q2)}const Hfe=me.toFlatObject(me,{},null,function(t){return/^is[A-Z]/.test(t)});function p0(e,t,n){if(!me.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const a=(b,C)=>{const w=me.getSafeProp(n,b);return me.isUndefined(w)?C:w},o=a("metaTokens",!0),r=a("visitor")||h,l=a("dots",!1),s=a("indexes",!1),u=a("Blob")||typeof Blob<"u"&&Blob,c=a("maxDepth",D_),d=u&&me.isSpecCompliantForm(t),f=[];if(!me.isFunction(r))throw new TypeError("visitor must be a function");function p(b){if(b===null)return"";if(me.isDate(b))return b.toISOString();if(me.isBoolean(b))return b.toString();if(!d&&me.isBlob(b))throw new pt("Blob is not supported. Use a Buffer instead.");if(me.isArrayBuffer(b)||me.isTypedArray(b)){if(d&&typeof u=="function")return new u([b]);throw new pt("Blob is not supported. Use a Buffer instead.",pt.ERR_NOT_SUPPORT)}return b}function m(b){if(b>c)throw new pt("Object is too deeply nested ("+b+" levels). Max depth: "+c,pt.ERR_FORM_DATA_DEPTH_EXCEEDED)}function v(b,C){if(c===1/0)return JSON.stringify(b);const w=[];return JSON.stringify(b,function(k,M){if(!me.isObject(M))return M;for(;w.length&&w[w.length-1]!==this;)w.pop();return w.push(M),m(C+w.length-1),M})}function h(b,C,w){let S=b;if(me.isReactNative(t)&&me.isReactNativeBlob(b))return t.append(vp(w,C,l),p(b)),!1;if(b&&!w&&typeof b=="object"){if(me.endsWith(C,"{}"))C=o?C:C.slice(0,-2),b=v(b,1);else if(me.isArray(b)&&zfe(b)||(me.isFileList(b)||me.endsWith(C,"[]"))&&(S=me.toArray(b)))return C=z_( Line truncated
`+l.map(D3).join(`
`):" "+D3(l[0]):"as no adapter specified";throw new pt("There is no suitable adapter to dispatch the request "+s,pt.ERR_NOT_SUPPORT)}return o}const eC={getAdapter:P0e,adapters:wm};function yp(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new _c(null,e)}function bp(e){const t=me.toSafeFlatObject(e);return yp(t),t.headers=va.from(me.getSafeProp(t,"headers")),t.data=mp.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),eC.getAdapter(t.adapter||wc.adapter,t)(t).then(function(o){yp(t),t.response=o;try{o.data=mp.call(t,t.transformResponse,o)}finally{delete t.response}return o.headers=va.from(o.headers),o},function(o){if(!U_(o)&&(yp(t),o&&o.response)){t.response=o.response;try{o.response.data=mp.call(t,t.transformResponse,o.response)}finally{delete t.response}o.response.headers=va.from(o.response.headers)}return Promise.reject(o)})}const h0={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{h0[e]=function(a){return typeof a===e||"a"+(t<1?"n ":" ")+e}});const z3={};h0.transitional=function(t,n,a){function o(r,l){return"[Axios v"+bm+"] Transitional option '"+r+"'"+l+(a?". "+a:"")}return(r,l,s)=>{if(t===!1)throw new pt(o(l," has been removed"+(n?" in "+n:"")),pt.ERR_DEPRECATED);return n&&!z3[l]&&(z3[l]=!0,console.warn(o(l," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(r,l,s):!0}};h0.spelling=function(t){return(n,a)=>(console.warn(`${a} is likely a misspelling of ${t}`),!0)};function I0e(e,t,n){if(typeof e!="object"||e===null)throw new pt("options must be an object",pt.ERR_BAD_OPTION_VALUE);const a=Object.keys(e);let o=a.length;for(;o-- >0;){const r=a[o],l=Object.prototype.hasOwnProperty.call(t,r)?t[r]:void 0;if(l){const s=e[r],u=s===void 0||l(s,r,e);if(u!==!0)throw new pt("option "+r+" must be "+u,pt.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new pt("Unknown option "+r,pt.ERR_BAD_OPTION)}}const md={assertOptions:I0e,validators:h0},ia=md.validators;let ql=class{constructor(t){this.defaults=t||{},this.interceptors={request:new T3,response:new T3}}async request(t,n){try{return await this._request(t,n)}catch(a){if(a instanceof Error)try{let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const r=o.stack;let l="";if(typeof r=="string"){const s=r.indexOf(`
`);l=s===-1?"":r.slice(s+1)}if(!a.stack)a.stack=l;else if(l){const s=l.indexOf(`
`),u=s===-1?-1:l.indexOf(`
`,s+1),c=u===-1?"":l.slice(u+1);String(a.stack).endsWith(c)||(a.stack+=`
`+l)}}catch{}throw a}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=is(this.defaults,n);const{transitional:a,paramsSerializer:o,headers:r}=n;a!==void 0&&md.assertOptions(a,{silentJSONParsing:ia.transitional(ia.boolean),forcedJSONParsing:ia.transitional(ia.boolean),clarifyTimeoutError:ia.transitional(ia.boolean),legacyInterceptorReqResOrdering:ia.transitional(ia.boolean),advertiseZstdAcceptEncoding:ia.transitional(ia.boolean),validateStatusUndefinedResolves:ia.transitional(ia.boolean)},!1),o!=null&&(me.isFunction(o)?n.paramsSerializer={serialize:o}:md.assertOptions(o,{encode:ia.function,serialize:ia.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),md.assertOptions(n,{baseUrl:ia.spelling("baseURL"),withXsrfToken:ia.spelling("withXSRFToken")},!0),n.method=(me.getSafeProp(n,"method")||me.getSafeProp(this.defaults,"method")||"get").toLowerCase();let l=r&&me.merge(r.common,r[n.method]);r&&me.forEach(q_.concat("common"),v=>{delete r[v]}),n.headers=va.concat(l,r);const s=[];let u=!0;this.interceptors.request.forEach(function(h){if(typeof h.runWhen=="function"&&h.runWhen(n)===!1)return;u=u&&h.synchronous;const g=n.transitional||gm;g&&g.legacyInterceptorReqResOrdering?s.unshift(h.fulfilled,h.rejected):s.push(h.fulfilled,h.rejected)});const c=[];this.interceptors.response.forEach(function(h){c.push(h.fulfilled,h.rejected)});let d,f=0,p;if(!u){const v=[bp.bind(this),void 0];for(v.unshift(...s),v.push(...c),p=v.length,d=Promise.resolve(n);f<p;)d=d.then(v[f++],v[f++]);return d}p=s.length;let m=n;for(;f<p;){const v=s[f++],h=s[f++];try{m=v?v(m):m}catch(g){if(!h){d=Promise.reject(g);break}try{const y=h.call(this,g);me.isThenable(y)&&(d=Promise.resolve(y).then(()=>bp.call(this,m)))}catch(y){d=Promise.reject(y)}break}}if(!d)try{d=bp.call(this,m)}catch(v){d=Promise.reject(v)}for(f=0,p=c.length;f<p;)d=d.then(c[f++],c[f++]);return d}getUri(t){t=is(this.defaults,t);const n=X_(t.baseURL,t.url,t.allowAbsoluteUrls,t);return F_(n,t.params,t.paramsSerializer)}};me.forEach(["delete","get","head","options"],function(t){ql.prototype[t]=function(n,a){return this.request(is(a||{},{method:t,url:n,data:a&&me.hasOwnProp(a,"data")?a.data:void 0}))}});me.forEach(["post","put","patch","query"],function(t){function n(a){return function(r,l,s){return this.request(is(s||{},{method:t,headers:a?{"Content-Type":"multipart/form-data"}:{},url:r,data:l}))}}ql.prototype[t]=n(),t!=="query"&&(ql.prototype[t+"Form"]=n(!0))});let L0e=class tC{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(r){n=r});const a=this;this.promise.then(o=>{if(!a._listeners)return;let r=a._listeners.length;for(;r-- >0;)a._listeners[r](o);a._listeners=null}),this.promise.then=o=>{let r;const l=new Promise(s=>{a.subscribe(s),r=s}).then(o);return l.cancel=function(){a.unsubscribe(r)},l},t(function(r,l,s){a.reason||(a.reason=new _c(r,l,s),n(a.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=a=>{t.abort(a)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new tC(function(o){t=o}),cancel:t}}};function V0e(e){return function(n){return e.apply(null,n)}}function B0e(e){return me.isObject(e)&&e.isAxiosError===!0}const gd={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,Timeou Line truncated
+1
View File
@@ -0,0 +1 @@
import{d as v,c as z,b as f,t as b,k as h,y as l,B as P,j as y,w as g,r as S,T as _}from"./index-CXCTlxVW.js";const L=["aria-label"],E={class:"app-list-pagination__summary","aria-live":"polite"},I=v({__name:"AppListPagination",props:{page:{},pageSize:{},total:{},disabled:{type:Boolean,default:!1},ariaLabel:{default:"列表分页"},pageSizes:{default:()=>[10,20,50]}},emits:["update:page","update:pageSize"],setup(n,{emit:i}){const e=n,o=i,s=l({get:()=>e.page,set:a=>o("update:page",a)}),u=l({get:()=>e.pageSize,set:a=>o("update:pageSize",a)}),r=l(()=>{if(!e.total)return"共 0 条";const a=(e.page-1)*e.pageSize+1,t=Math.min(e.total,e.page*e.pageSize);return`第 ${a}–${t} 条,共 ${e.total} 条`});return(a,t)=>{const p=P("el-pagination");return y(),z("nav",{class:"app-list-pagination","aria-label":n.ariaLabel},[f("p",E,b(r.value),1),h(p,{"current-page":s.value,"onUpdate:currentPage":t[0]||(t[0]=c=>s.value=c),"page-size":u.value,"onUpdate:pageSize":t[1]||(t[1]=c=>u.value=c),"page-sizes":n.pageSizes,total:n.total,disabled:n.disabled,"pager-count":5,layout:"sizes, prev, pager, next, jumper",small:"",background:""},null,8,["current-page","page-size","page-sizes","total","disabled"])],8,L)}}}),M=[10,20,50],x=20;function k(n,i={}){var d;const e=S(1),o=Number(i.initialPageSize),s=S(M.includes(o)?o:x),u=l(()=>_(n)||[]),r=l(()=>u.value.length),a=l(()=>Math.max(1,Math.ceil(r.value/s.value))),t=()=>{e.value=Math.min(Math.max(1,Math.trunc(Number(e.value)||1)),a.value)},p=()=>{e.value=1},c=l(()=>{const m=(e.value-1)*s.value;return u.value.slice(m,m+s.value)});return g(s,p,{flush:"sync"}),g(r,t,{flush:"sync"}),(d=i.resetSources)!=null&&d.length&&g(i.resetSources,p,{flush:"sync"}),{page:e,pageSize:s,total:r,totalPages:a,paginatedItems:c,resetPage:p,clampPage:t}}export{I as _,k as u};
+13
View File
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>财务系统 - 统一费用支付平台</title>
<script type="module" crossorigin src="/assets/index-CXCTlxVW.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-Bvt50oQ6.css">
</head>
<body>
<div id="app"></div>
</body>
</html>
-1
View File
@@ -2,7 +2,6 @@
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>财务系统 - 统一费用支付平台</title>
</head>
+390 -126
View File
@@ -9,15 +9,10 @@
"version": "1.0.0",
"dependencies": {
"@element-plus/icons-vue": "^2.3.0",
"@vueuse/core": "^10.7.0",
"axios": "^1.6.0",
"dayjs": "^1.11.0",
"echarts": "^5.4.0",
"element-plus": "^2.5.0",
"lodash-es": "^4.17.21",
"pinia": "^2.1.0",
"vue": "^3.4.0",
"vue-echarts": "^6.6.0",
"vue-router": "^4.2.0"
},
"devDependencies": {
@@ -28,6 +23,7 @@
"tailwindcss": "^3.4.0",
"typescript": "^5.3.0",
"vite": "^5.0.0",
"vitest": "^2.1.9",
"vue-tsc": "^3.3.11"
}
},
@@ -1348,12 +1344,6 @@
"@types/lodash": "*"
}
},
"node_modules/@types/web-bluetooth": {
"version": "0.0.20",
"resolved": "https://registry.npmmirror.com/@types/web-bluetooth/-/web-bluetooth-0.0.20.tgz",
"integrity": "sha512-g9gZnnXVq7gM7v3tJCWV/qw7w+KeOlSHAhgF9RytFyifW6AF61hdT2ucrYhPq9hLs5JIryeupHV3qGk95dH9ow==",
"license": "MIT"
},
"node_modules/@vitejs/plugin-vue": {
"version": "5.2.4",
"resolved": "https://registry.npmmirror.com/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz",
@@ -1368,6 +1358,129 @@
"vue": "^3.2.25"
}
},
"node_modules/@vitest/expect": {
"version": "2.1.9",
"resolved": "https://registry.npmmirror.com/@vitest/expect/-/expect-2.1.9.tgz",
"integrity": "sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/spy": "2.1.9",
"@vitest/utils": "2.1.9",
"chai": "^5.1.2",
"tinyrainbow": "^1.2.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/mocker": {
"version": "2.1.9",
"resolved": "https://registry.npmmirror.com/@vitest/mocker/-/mocker-2.1.9.tgz",
"integrity": "sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/spy": "2.1.9",
"estree-walker": "^3.0.3",
"magic-string": "^0.30.12"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"msw": "^2.4.9",
"vite": "^5.0.0"
},
"peerDependenciesMeta": {
"msw": {
"optional": true
},
"vite": {
"optional": true
}
}
},
"node_modules/@vitest/mocker/node_modules/estree-walker": {
"version": "3.0.3",
"resolved": "https://registry.npmmirror.com/estree-walker/-/estree-walker-3.0.3.tgz",
"integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/estree": "^1.0.0"
}
},
"node_modules/@vitest/pretty-format": {
"version": "2.1.9",
"resolved": "https://registry.npmmirror.com/@vitest/pretty-format/-/pretty-format-2.1.9.tgz",
"integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"tinyrainbow": "^1.2.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/runner": {
"version": "2.1.9",
"resolved": "https://registry.npmmirror.com/@vitest/runner/-/runner-2.1.9.tgz",
"integrity": "sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/utils": "2.1.9",
"pathe": "^1.1.2"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/snapshot": {
"version": "2.1.9",
"resolved": "https://registry.npmmirror.com/@vitest/snapshot/-/snapshot-2.1.9.tgz",
"integrity": "sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/pretty-format": "2.1.9",
"magic-string": "^0.30.12",
"pathe": "^1.1.2"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/spy": {
"version": "2.1.9",
"resolved": "https://registry.npmmirror.com/@vitest/spy/-/spy-2.1.9.tgz",
"integrity": "sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"tinyspy": "^3.0.2"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/utils": {
"version": "2.1.9",
"resolved": "https://registry.npmmirror.com/@vitest/utils/-/utils-2.1.9.tgz",
"integrity": "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/pretty-format": "2.1.9",
"loupe": "^3.1.2",
"tinyrainbow": "^1.2.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@volar/language-core": {
"version": "2.4.28",
"resolved": "https://registry.npmmirror.com/@volar/language-core/-/language-core-2.4.28.tgz",
@@ -1517,42 +1630,6 @@
"integrity": "sha512-2rPxex1jQf4jvl9MOHl6YaXCPcrNqz/FstMOEh3QWY+/OME9nQTvl9WYeCwhW7AFjaR0SnngZGlp/wkR6rkI6g==",
"license": "MIT"
},
"node_modules/@vueuse/core": {
"version": "10.11.1",
"resolved": "https://registry.npmmirror.com/@vueuse/core/-/core-10.11.1.tgz",
"integrity": "sha512-guoy26JQktXPcz+0n3GukWIy/JDNKti9v6VEMu6kV2sYBsWuGiTU8OWdg+ADfUbHg3/3DlqySDe7JmdHrktiww==",
"license": "MIT",
"dependencies": {
"@types/web-bluetooth": "^0.0.20",
"@vueuse/metadata": "10.11.1",
"@vueuse/shared": "10.11.1",
"vue-demi": ">=0.14.8"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/@vueuse/metadata": {
"version": "10.11.1",
"resolved": "https://registry.npmmirror.com/@vueuse/metadata/-/metadata-10.11.1.tgz",
"integrity": "sha512-IGa5FXd003Ug1qAZmyE8wF3sJ81xGLSqTqtQ6jaVfkeZ4i5kS2mwQF61yhVqojRnenVew5PldLyRgvdl4YYuSw==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/@vueuse/shared": {
"version": "10.11.1",
"resolved": "https://registry.npmmirror.com/@vueuse/shared/-/shared-10.11.1.tgz",
"integrity": "sha512-LHpC8711VFZlDaYUXEBbFBCQ7GS3dVU9mjOhhMhXP6txTV4EhYQg/KGnQuvt/sPAtoUKq7VVUnL6mVtFoL42sA==",
"license": "MIT",
"dependencies": {
"vue-demi": ">=0.14.8"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/agent-base": {
"version": "6.0.2",
"resolved": "https://registry.npmmirror.com/agent-base/-/agent-base-6.0.2.tgz",
@@ -1613,6 +1690,16 @@
"dev": true,
"license": "MIT"
},
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmmirror.com/assertion-error/-/assertion-error-2.0.1.tgz",
"integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/async-validator": {
"version": "4.2.5",
"resolved": "https://registry.npmmirror.com/async-validator/-/async-validator-4.2.5.tgz",
@@ -1747,6 +1834,16 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
"node_modules/cac": {
"version": "6.7.14",
"resolved": "https://registry.npmmirror.com/cac/-/cac-6.7.14.tgz",
"integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmmirror.com/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
@@ -1791,6 +1888,33 @@
],
"license": "CC-BY-4.0"
},
"node_modules/chai": {
"version": "5.3.3",
"resolved": "https://registry.npmmirror.com/chai/-/chai-5.3.3.tgz",
"integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",
"dev": true,
"license": "MIT",
"dependencies": {
"assertion-error": "^2.0.1",
"check-error": "^2.1.1",
"deep-eql": "^5.0.1",
"loupe": "^3.1.0",
"pathval": "^2.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/check-error": {
"version": "2.1.3",
"resolved": "https://registry.npmmirror.com/check-error/-/check-error-2.1.3.tgz",
"integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 16"
}
},
"node_modules/chokidar": {
"version": "5.0.0",
"resolved": "https://registry.npmmirror.com/chokidar/-/chokidar-5.0.0.tgz",
@@ -1871,6 +1995,16 @@
}
}
},
"node_modules/deep-eql": {
"version": "5.0.2",
"resolved": "https://registry.npmmirror.com/deep-eql/-/deep-eql-5.0.2.tgz",
"integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmmirror.com/delayed-stream/-/delayed-stream-1.0.0.tgz",
@@ -1919,16 +2053,6 @@
"node": ">= 0.4"
}
},
"node_modules/echarts": {
"version": "5.6.0",
"resolved": "https://registry.npmmirror.com/echarts/-/echarts-5.6.0.tgz",
"integrity": "sha512-oTbVTsXfKuEhxftHqL5xprgLoc0k7uScAwtryCgWF6hPYFLRwOUHiFmHGCBKP5NPFNkDVopOieyUqYGH8Fa3kA==",
"license": "Apache-2.0",
"dependencies": {
"tslib": "2.3.0",
"zrender": "5.6.1"
}
},
"node_modules/electron-to-chromium": {
"version": "1.5.420",
"resolved": "https://registry.npmmirror.com/electron-to-chromium/-/electron-to-chromium-1.5.420.tgz",
@@ -2036,6 +2160,13 @@
"node": ">= 0.4"
}
},
"node_modules/es-module-lexer": {
"version": "1.7.0",
"resolved": "https://registry.npmmirror.com/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
"integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==",
"dev": true,
"license": "MIT"
},
"node_modules/es-object-atoms": {
"version": "1.1.2",
"resolved": "https://registry.npmmirror.com/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
@@ -2118,6 +2249,16 @@
"integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
"license": "MIT"
},
"node_modules/expect-type": {
"version": "1.4.0",
"resolved": "https://registry.npmmirror.com/expect-type/-/expect-type-1.4.0.tgz",
"integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/fast-glob": {
"version": "3.3.3",
"resolved": "https://registry.npmmirror.com/fast-glob/-/fast-glob-3.3.3.tgz",
@@ -2499,6 +2640,13 @@
"lodash-es": "*"
}
},
"node_modules/loupe": {
"version": "3.2.1",
"resolved": "https://registry.npmmirror.com/loupe/-/loupe-3.2.1.tgz",
"integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
"dev": true,
"license": "MIT"
},
"node_modules/magic-string": {
"version": "0.30.21",
"resolved": "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.21.tgz",
@@ -2692,6 +2840,23 @@
"dev": true,
"license": "MIT"
},
"node_modules/pathe": {
"version": "1.1.2",
"resolved": "https://registry.npmmirror.com/pathe/-/pathe-1.1.2.tgz",
"integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",
"dev": true,
"license": "MIT"
},
"node_modules/pathval": {
"version": "2.0.1",
"resolved": "https://registry.npmmirror.com/pathval/-/pathval-2.0.1.tgz",
"integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 14.16"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz",
@@ -2956,12 +3121,6 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/resize-detector": {
"version": "0.3.0",
"resolved": "https://registry.npmmirror.com/resize-detector/-/resize-detector-0.3.0.tgz",
"integrity": "sha512-R/tCuvuOHQ8o2boRP6vgx8hXCCy87H1eY9V5imBYeVNyNVpuL9ciReSccLj2gDcax9+2weXy3bc8Vv+NRXeEvQ==",
"license": "MIT"
},
"node_modules/resolve": {
"version": "1.22.12",
"resolved": "https://registry.npmmirror.com/resolve/-/resolve-1.22.12.tgz",
@@ -3086,6 +3245,13 @@
"@parcel/watcher": "^2.4.1"
}
},
"node_modules/siginfo": {
"version": "2.0.0",
"resolved": "https://registry.npmmirror.com/siginfo/-/siginfo-2.0.0.tgz",
"integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
"dev": true,
"license": "ISC"
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -3095,6 +3261,20 @@
"node": ">=0.10.0"
}
},
"node_modules/stackback": {
"version": "0.0.2",
"resolved": "https://registry.npmmirror.com/stackback/-/stackback-0.0.2.tgz",
"integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
"dev": true,
"license": "MIT"
},
"node_modules/std-env": {
"version": "3.10.0",
"resolved": "https://registry.npmmirror.com/std-env/-/std-env-3.10.0.tgz",
"integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",
"dev": true,
"license": "MIT"
},
"node_modules/sucrase": {
"version": "3.35.1",
"resolved": "https://registry.npmmirror.com/sucrase/-/sucrase-3.35.1.tgz",
@@ -3256,6 +3436,20 @@
"node": ">=0.8"
}
},
"node_modules/tinybench": {
"version": "2.9.0",
"resolved": "https://registry.npmmirror.com/tinybench/-/tinybench-2.9.0.tgz",
"integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
"dev": true,
"license": "MIT"
},
"node_modules/tinyexec": {
"version": "0.3.2",
"resolved": "https://registry.npmmirror.com/tinyexec/-/tinyexec-0.3.2.tgz",
"integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==",
"dev": true,
"license": "MIT"
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -3273,6 +3467,36 @@
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
"node_modules/tinypool": {
"version": "1.1.1",
"resolved": "https://registry.npmmirror.com/tinypool/-/tinypool-1.1.1.tgz",
"integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^18.0.0 || >=20.0.0"
}
},
"node_modules/tinyrainbow": {
"version": "1.2.0",
"resolved": "https://registry.npmmirror.com/tinyrainbow/-/tinyrainbow-1.2.0.tgz",
"integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/tinyspy": {
"version": "3.0.2",
"resolved": "https://registry.npmmirror.com/tinyspy/-/tinyspy-3.0.2.tgz",
"integrity": "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmmirror.com/to-regex-range/-/to-regex-range-5.0.1.tgz",
@@ -3293,12 +3517,6 @@
"dev": true,
"license": "Apache-2.0"
},
"node_modules/tslib": {
"version": "2.3.0",
"resolved": "https://registry.npmmirror.com/tslib/-/tslib-2.3.0.tgz",
"integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==",
"license": "0BSD"
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmmirror.com/typescript/-/typescript-5.9.3.tgz",
@@ -3411,6 +3629,95 @@
}
}
},
"node_modules/vite-node": {
"version": "2.1.9",
"resolved": "https://registry.npmmirror.com/vite-node/-/vite-node-2.1.9.tgz",
"integrity": "sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==",
"dev": true,
"license": "MIT",
"dependencies": {
"cac": "^6.7.14",
"debug": "^4.3.7",
"es-module-lexer": "^1.5.4",
"pathe": "^1.1.2",
"vite": "^5.0.0"
},
"bin": {
"vite-node": "vite-node.mjs"
},
"engines": {
"node": "^18.0.0 || >=20.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/vitest": {
"version": "2.1.9",
"resolved": "https://registry.npmmirror.com/vitest/-/vitest-2.1.9.tgz",
"integrity": "sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/expect": "2.1.9",
"@vitest/mocker": "2.1.9",
"@vitest/pretty-format": "^2.1.9",
"@vitest/runner": "2.1.9",
"@vitest/snapshot": "2.1.9",
"@vitest/spy": "2.1.9",
"@vitest/utils": "2.1.9",
"chai": "^5.1.2",
"debug": "^4.3.7",
"expect-type": "^1.1.0",
"magic-string": "^0.30.12",
"pathe": "^1.1.2",
"std-env": "^3.8.0",
"tinybench": "^2.9.0",
"tinyexec": "^0.3.1",
"tinypool": "^1.0.1",
"tinyrainbow": "^1.2.0",
"vite": "^5.0.0",
"vite-node": "2.1.9",
"why-is-node-running": "^2.3.0"
},
"bin": {
"vitest": "vitest.mjs"
},
"engines": {
"node": "^18.0.0 || >=20.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"@edge-runtime/vm": "*",
"@types/node": "^18.0.0 || >=20.0.0",
"@vitest/browser": "2.1.9",
"@vitest/ui": "2.1.9",
"happy-dom": "*",
"jsdom": "*"
},
"peerDependenciesMeta": {
"@edge-runtime/vm": {
"optional": true
},
"@types/node": {
"optional": true
},
"@vitest/browser": {
"optional": true
},
"@vitest/ui": {
"optional": true
},
"happy-dom": {
"optional": true
},
"jsdom": {
"optional": true
}
}
},
"node_modules/vscode-uri": {
"version": "3.2.0",
"resolved": "https://registry.npmmirror.com/vscode-uri/-/vscode-uri-3.2.0.tgz",
@@ -3471,57 +3778,6 @@
}
}
},
"node_modules/vue-echarts": {
"version": "6.7.3",
"resolved": "https://registry.npmmirror.com/vue-echarts/-/vue-echarts-6.7.3.tgz",
"integrity": "sha512-vXLKpALFjbPphW9IfQPOVfb1KjGZ/f8qa/FZHi9lZIWzAnQC1DgnmEK3pJgEkyo6EP7UnX6Bv/V3Ke7p+qCNXA==",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"resize-detector": "^0.3.0",
"vue-demi": "^0.13.11"
},
"peerDependencies": {
"@vue/composition-api": "^1.0.5",
"@vue/runtime-core": "^3.0.0",
"echarts": "^5.4.1",
"vue": "^2.6.12 || ^3.1.1"
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
},
"@vue/runtime-core": {
"optional": true
}
}
},
"node_modules/vue-echarts/node_modules/vue-demi": {
"version": "0.13.11",
"resolved": "https://registry.npmmirror.com/vue-demi/-/vue-demi-0.13.11.tgz",
"integrity": "sha512-IR8HoEEGM65YY3ZJYAjMlKygDQn25D5ajNFNoKh9RSDMQtlzCxtfQjdQgv9jjK+m3377SsJXY8ysq8kLCZL25A==",
"hasInstallScript": true,
"license": "MIT",
"bin": {
"vue-demi-fix": "bin/vue-demi-fix.js",
"vue-demi-switch": "bin/vue-demi-switch.js"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
},
"peerDependencies": {
"@vue/composition-api": "^1.0.0-rc.1",
"vue": "^3.0.0-0 || ^2.6.0"
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
}
}
},
"node_modules/vue-router": {
"version": "4.6.4",
"resolved": "https://registry.npmmirror.com/vue-router/-/vue-router-4.6.4.tgz",
@@ -3554,13 +3810,21 @@
"typescript": ">=5.0.0"
}
},
"node_modules/zrender": {
"version": "5.6.1",
"resolved": "https://registry.npmmirror.com/zrender/-/zrender-5.6.1.tgz",
"integrity": "sha512-OFXkDJKcrlx5su2XbzJvj/34Q3m6PvyCZkVPHGYpcCJ52ek4U/ymZyfuV1nKE23AyBJ51E/6Yr0mhZ7xGTO4ag==",
"license": "BSD-3-Clause",
"node_modules/why-is-node-running": {
"version": "2.3.0",
"resolved": "https://registry.npmmirror.com/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
"integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
"dev": true,
"license": "MIT",
"dependencies": {
"tslib": "2.3.0"
"siginfo": "^2.0.0",
"stackback": "0.0.2"
},
"bin": {
"why-is-node-running": "cli.js"
},
"engines": {
"node": ">=8"
}
}
}
+2 -6
View File
@@ -6,20 +6,15 @@
"scripts": {
"dev": "vite",
"build": "vite build",
"test": "node --test src/feishuDirectory.test.mjs src/layout.test.mjs",
"test": "vitest",
"preview": "vite preview"
},
"dependencies": {
"@element-plus/icons-vue": "^2.3.0",
"@vueuse/core": "^10.7.0",
"axios": "^1.6.0",
"dayjs": "^1.11.0",
"echarts": "^5.4.0",
"element-plus": "^2.5.0",
"lodash-es": "^4.17.21",
"pinia": "^2.1.0",
"vue": "^3.4.0",
"vue-echarts": "^6.6.0",
"vue-router": "^4.2.0"
},
"devDependencies": {
@@ -30,6 +25,7 @@
"tailwindcss": "^3.4.0",
"typescript": "^5.3.0",
"vite": "^5.0.0",
"vitest": "^2.1.9",
"vue-tsc": "^3.3.11"
}
}
+2 -2
View File
@@ -41,7 +41,7 @@ const clearSessionAndRedirect = () => {
const checkDailySession = () => {
const hadSession = Boolean(
localStorage.getItem(TOKEN_KEY) ||
sessionStorage.getItem(TOKEN_KEY) ||
localStorage.getItem(USER_INFO_KEY) ||
localStorage.getItem(AUTH_DAY_KEY) ||
userStore.token,
@@ -67,7 +67,7 @@ const handleStorage = (event: StorageEvent) => {
if (storageSyncTimer !== null) window.clearTimeout(storageSyncTimer)
storageSyncTimer = window.setTimeout(() => {
storageSyncTimer = null
const token = localStorage.getItem(TOKEN_KEY)
const token = sessionStorage.getItem(TOKEN_KEY)
const valid = userStore.ensureDailyAuth()
if (!valid || !token) {
clearSessionAndRedirect()
+206 -41
View File
@@ -1,24 +1,7 @@
import request from './request'
export type Status = 'ACTIVE' | 'INACTIVE'
export interface AdminUser {
id: number
employeeNo: string
realName: string
avatarUrl?: string
email?: string
departmentName?: string
position?: string
userType?: string
status: string
feishuStatus?: string
feishuOpenId?: string
feishuUserId?: string
lastLoginAt?: string
roleCodes?: string[]
groupNames?: string[]
}
export type PermissionAccess = 'HIDDEN' | 'READ' | 'EDIT'
export interface Role {
id: number
@@ -31,17 +14,27 @@ export interface Role {
permissionCount?: number
}
export type RolePayload = Pick<Role, 'roleCode' | 'roleName' | 'description' | 'status'>
export interface PermissionItem {
code: string
name: string
type: string
/** ACTION and legacy BUTTON both represent editable operations. Unknown values remain accepted for compatibility. */
type: 'MODULE' | 'PAGE' | 'MENU' | 'FIELD' | 'ACTION' | 'BUTTON' | (string & {})
parentCode?: string
resource?: string
defaultAccess?: PermissionAccess
}
export interface RolePermissions {
permissionCodes: string[]
fieldPermissions: Record<string, 'HIDDEN' | 'READ' | 'EDIT'>
fieldPermissions: Record<string, PermissionAccess>
permissionAccess: Record<string, PermissionAccess>
}
export interface UpdateRolePermissionsPayload extends RolePermissions {
/** Snapshot read before editing; server rejects stale concurrent edits with 409. */
expectedPermissionAccess: Record<string, PermissionAccess>
}
export interface UserGroup {
@@ -50,18 +43,81 @@ export interface UserGroup {
groupName: string
description?: string
status: Status | string
memberCount?: number
roleCount?: number
builtIn: boolean
membershipMode: 'DYNAMIC' | 'EXPLICIT'
memberCount: number | null
membershipResolved: boolean
snapshotState?: string | null
roleCount: number
}
export type UserGroupPayload = Pick<UserGroup, 'groupCode' | 'groupName' | 'description' | 'status'>
export interface DirectoryIdentity {
/** Identity alias for the directory's currentRevision. */
generationId: string
openId: string
/** Legacy identity hint. Directory v1 identities are keyed by openId. */
userId?: string | null
}
export interface GroupCandidate {
id: number
id: number | null
realName: string
employeeNo?: string
employeeNo?: string | null
/** @deprecated Legacy candidate endpoint compatibility. */
departmentName?: string
departmentNames: string[]
feishuOpenId?: string
feishuUserId?: string
status: string
/** @deprecated Legacy candidate endpoint compatibility. */
status?: string
assignedGroupId: number | null
assignedGroupName?: string | null
eligible: boolean
selectable: boolean
directoryIdentity?: DirectoryIdentity
}
export type GroupMemberSnapshotState = 'FRESH' | 'NEVER_SYNCED' | 'STALE' | 'CONTEXT_CHANGED' | 'UNAVAILABLE'
export type DirectoryAvailabilityState = 'AVAILABLE' | 'NEVER_SYNCED' | 'UNAVAILABLE'
export type DirectoryContextState = 'MATCH' | 'CHANGED' | 'UNKNOWN'
export interface GroupMemberCandidates {
snapshotState: GroupMemberSnapshotState
/** Optional while older backend nodes are still serving traffic. */
availabilityState?: DirectoryAvailabilityState | null
additionsAllowed?: boolean
currentRevision?: string | null
contextState?: DirectoryContextState | null
currentMembers: GroupCandidate[]
matches: GroupCandidate[]
blockedMatchesPresent: boolean
limit: number
truncated: boolean
}
export interface GroupMembers {
userIds: number[]
dynamic: boolean
editable: boolean
membershipResolved: boolean
snapshotState?: string | null
}
export interface UpdateGroupMembersPayload {
userIds: number[]
directoryIdentities: DirectoryIdentity[]
expectedUserIds: number[]
}
export interface UpdateGroupMembersResponse {
userIds: number[]
}
export interface UpdateGroupRolesPayload {
roleIds: number[]
expectedRoleIds: number[]
}
export interface IntegrationField {
@@ -70,51 +126,160 @@ export interface IntegrationField {
value?: unknown
secret: boolean
configured: boolean
readOnly?: boolean
inputType?: 'text' | 'password' | 'url' | 'boolean'
placeholder?: string
helpText?: string
}
export interface IntegrationProvider {
enabled: boolean
readOnly?: boolean
source?: string
fields: IntegrationField[]
}
export interface IntegrationConfig {
feishu: IntegrationProvider
kingdee: IntegrationProvider
kingdee?: IntegrationProvider
}
export interface FeishuApprovalDefinitionSyncResult {
success?: boolean
message?: string
syncedAt?: string
fetchedAt?: string
approvalCode?: string
eventSubscribed?: boolean
changed?: boolean
nodeCount?: number
[key: string]: unknown
}
export type KingdeeSyncConfigId = number | string
export type KingdeeSyncDataType = 'STRING' | 'INTEGER' | 'BIGINT' | 'DECIMAL' | 'DATE' | 'DATETIME' | 'BOOLEAN' | 'JSON'
export type KingdeeSyncFilterOperator = 'EQ' | 'NE' | 'GT' | 'GE' | 'LT' | 'LE' | 'LIKE' | 'IN'
export interface KingdeeSyncField {
sourceFieldKey: string
targetColumnName: string
fieldComment: string
dataType: KingdeeSyncDataType
fieldLength: number | null
sortOrder: number
}
export interface KingdeeSyncFilter {
sourceFieldKey: string
operator: KingdeeSyncFilterOperator
filterValue: string
sortOrder: number
}
export interface KingdeeSyncConfigPayload {
configName: string
formId: string
targetTableName: string
targetTableComment: string
enabled: boolean
maxRowsPerRun: number
fields: KingdeeSyncField[]
filters: KingdeeSyncFilter[]
}
export interface KingdeeSyncConfig extends KingdeeSyncConfigPayload {
id: KingdeeSyncConfigId
createdAt?: string
updatedAt?: string
}
export interface KingdeeSyncPreview {
filterString: string
rows: Array<Record<string, unknown>>
truncated: boolean
}
export type KingdeeSyncRunStatus = 'RUNNING' | 'SUCCEEDED' | 'PARTIAL' | 'FAILED'
export interface KingdeeSyncRun {
id: KingdeeSyncConfigId
fetchedCount: number | null
insertedCount: number | null
updatedCount: number | null
failedCount: number | null
status: KingdeeSyncRunStatus
startedAt: string | null
finishedAt: string | null
errorMessage: string | null
configId?: KingdeeSyncConfigId
filterString?: string | null
}
export interface KingdeePrepareTableResult {
success?: boolean
message?: string
[key: string]: unknown
}
export const adminApi = {
listUsers: (): Promise<AdminUser[]> => request.get('/auth/users'),
updateUserRoles: (id: number, roleIds: number[]): Promise<AdminUser> =>
request.put(`/auth/users/${id}/roles`, { roleIds }),
listRoles: (): Promise<Role[]> => request.get('/roles'),
createRole: (body: Pick<Role, 'roleCode' | 'roleName' | 'description' | 'status'>): Promise<Role> =>
createRole: (body: RolePayload): Promise<Role> =>
request.post('/roles', body),
updateRole: (id: number, body: Partial<Pick<Role, 'roleCode' | 'roleName' | 'description' | 'status'>>): Promise<Role> =>
updateRole: (id: number, body: RolePayload): Promise<Role> =>
request.put(`/roles/${id}`, body),
deleteRole: (id: number): Promise<void> => request.delete(`/roles/${id}`),
listPermissions: (): Promise<PermissionItem[]> => request.get('/roles/permissions'),
getRolePermissions: (id: number): Promise<RolePermissions> => request.get(`/roles/${id}/permissions`),
updateRolePermissions: (id: number, body: RolePermissions): Promise<void> =>
updateRolePermissions: (id: number, body: UpdateRolePermissionsPayload): Promise<void> =>
request.put(`/roles/${id}/permissions`, body),
listGroups: (): Promise<UserGroup[]> => request.get('/user-groups'),
createGroup: (body: Pick<UserGroup, 'groupCode' | 'groupName' | 'description' | 'status'>): Promise<UserGroup> =>
createGroup: (body: UserGroupPayload): Promise<UserGroup> =>
request.post('/user-groups', body),
updateGroup: (id: number, body: Partial<Pick<UserGroup, 'groupCode' | 'groupName' | 'description' | 'status'>>): Promise<UserGroup> =>
updateGroup: (id: number, body: UserGroupPayload): Promise<UserGroup> =>
request.put(`/user-groups/${id}`, body),
deleteGroup: (id: number): Promise<void> => request.delete(`/user-groups/${id}`),
getGroupRoles: (id: number): Promise<{ roleIds: number[] }> => request.get(`/user-groups/${id}/roles`),
updateGroupRoles: (id: number, roleIds: number[]): Promise<void> =>
request.put(`/user-groups/${id}/roles`, { roleIds }),
getGroupMembers: (id: number): Promise<{ userIds: number[] }> => request.get(`/user-groups/${id}/members`),
updateGroupMembers: (id: number, userIds: number[]): Promise<void> =>
request.put(`/user-groups/${id}/members`, { userIds }),
listCandidates: (): Promise<GroupCandidate[]> => request.get('/user-groups/candidates'),
updateGroupRoles: (id: number, body: UpdateGroupRolesPayload): Promise<void> =>
request.put(`/user-groups/${id}/roles`, body, { suppressErrorNotification: true }),
getGroupMembers: (id: number): Promise<GroupMembers> => request.get(`/user-groups/${id}/members`),
updateGroupMembers: (id: number, body: UpdateGroupMembersPayload): Promise<UpdateGroupMembersResponse> =>
request.put(`/user-groups/${id}/members`, body, { suppressErrorNotification: true }),
listCandidates: (groupId?: number, q?: string): Promise<GroupCandidate[]> => {
const query = q?.trim()
const params = {
...(groupId === undefined ? {} : { groupId }),
...(query ? { q: query } : {}),
}
return request.get('/user-groups/candidates', Object.keys(params).length ? { params } : undefined)
},
searchGroupMemberCandidates: (groupId: number, q = ''): Promise<GroupMemberCandidates> =>
request.get(`/user-groups/${groupId}/member-candidates`, { params: { q: q.trim() } }),
getIntegrationConfig: (): Promise<IntegrationConfig> => request.get('/integrations/config'),
updateIntegrationConfig: (provider: 'FEISHU' | 'KINGDEE', enabled: boolean, values: Record<string, unknown>): Promise<void> =>
request.put('/integrations/config', { provider, enabled, values }),
testIntegration: (provider: 'FEISHU' | 'KINGDEE'): Promise<{ provider: string; configured: boolean; success: boolean; message: string }> =>
request.post('/integrations/config/test', { provider }),
syncFeishuApprovalDefinition: (): Promise<FeishuApprovalDefinitionSyncResult> =>
request.post('/feishu/approval/definition/sync', undefined, { suppressErrorNotification: true }),
listKingdeeSyncConfigs: (): Promise<KingdeeSyncConfig[]> =>
request.get('/integrations/kingdee/sync-configs'),
createKingdeeSyncConfig: (body: KingdeeSyncConfigPayload): Promise<KingdeeSyncConfig> =>
request.post('/integrations/kingdee/sync-configs', body),
getKingdeeSyncConfig: (id: KingdeeSyncConfigId): Promise<KingdeeSyncConfig> =>
request.get(`/integrations/kingdee/sync-configs/${id}`),
updateKingdeeSyncConfig: (id: KingdeeSyncConfigId, body: KingdeeSyncConfigPayload): Promise<KingdeeSyncConfig> =>
request.put(`/integrations/kingdee/sync-configs/${id}`, body),
deleteKingdeeSyncConfig: (id: KingdeeSyncConfigId): Promise<void> =>
request.delete(`/integrations/kingdee/sync-configs/${id}`),
previewKingdeeSyncConfig: (id: KingdeeSyncConfigId): Promise<KingdeeSyncPreview> =>
request.post(`/integrations/kingdee/sync-configs/${id}/preview`),
prepareKingdeeSyncTable: (id: KingdeeSyncConfigId): Promise<KingdeePrepareTableResult> =>
request.post(`/integrations/kingdee/sync-configs/${id}/prepare-table`),
syncKingdeeConfig: (id: KingdeeSyncConfigId): Promise<KingdeeSyncRun> =>
request.post(`/integrations/kingdee/sync-configs/${id}/sync`),
listKingdeeSyncRuns: (id: KingdeeSyncConfigId): Promise<KingdeeSyncRun[]> =>
request.get(`/integrations/kingdee/sync-configs/${id}/runs`),
}
+2
View File
@@ -9,6 +9,8 @@ export interface UserProfile {
departmentName: string
position: string
userType: string
roleCodes?: string[]
isSuperAdmin?: boolean
status: string
feishuStatus: string
lastLoginAt: string
+1 -1
View File
@@ -29,7 +29,7 @@ const item = (id: string, title: string, owner: string, department: string, amou
sourceDocNo: `TRIP${date.replace(/-/g, '')}`, sourceStatus: '已同步', payeeName: owner, payeeBankId: 1,
bankName: owner === '李志豪' ? '中国工商银行苏州新区支行' : '招商银行苏州工业园区支行', bankAccountMask: owner === '李志豪' ? '6222 **** 0728' : '6214 **** 8001',
returnReason, submitTime: `${date} 09:42`, createdAt: `${date} 09:42`, updatedAt: `${date} 10:24`,
expenseItems: [{ id: `${id}-1`, seqNo: 1, expenseDate: date, category, description: title, amount }],
expenseItems: [{ id: `${id}-1`, seqNo: 1, expenseDate: date, category, description: title, amount, attachmentIds: [] }],
invoices: amount === 3286.5 ? [] : [{ id: `${id}-invoice`, invoiceNo: `0330026001114${id.slice(-5)}`, invoiceType: '增值税普通发票', issueDate: date, amount, sellerName: '业务服务商', verifyStatus: '已校验' }],
attachments: [{ id: `${id}-attachment`, fileName: `${category}证明材料.pdf`, fileType: 'PDF', fileUrl: '' }], approvalRecords: [], payments: [],
})
+38 -11
View File
@@ -1,10 +1,34 @@
import request from './request'
export type DirectorySnapshotState = 'UNAVAILABLE' | 'NEVER_SYNCED' | 'FRESH' | 'STALE' | 'CONTEXT_CHANGED'
export type DirectoryAvailabilityState = 'AVAILABLE' | 'NEVER_SYNCED' | 'UNAVAILABLE'
export type DirectoryContextState = 'MATCH' | 'CHANGED' | 'UNKNOWN'
export interface DirectoryAvailabilityContract {
snapshotState: DirectorySnapshotState
/** Additive fields are optional for rolling compatibility with older nodes. */
availabilityState?: DirectoryAvailabilityState | null
additionsAllowed?: boolean
currentRevision?: string | null
contextState?: DirectoryContextState | null
}
export const directoryAvailability = (value: DirectoryAvailabilityContract): DirectoryAvailabilityState => {
if (value.availabilityState === 'AVAILABLE' || value.availabilityState === 'NEVER_SYNCED' || value.availabilityState === 'UNAVAILABLE') {
return value.availabilityState
}
// Older backends did not expose availability. Only their FRESH state is safe
// to treat as usable; all other legacy states deliberately fail closed.
return value.snapshotState === 'FRESH'
? 'AVAILABLE'
: value.snapshotState === 'NEVER_SYNCED' ? 'NEVER_SYNCED' : 'UNAVAILABLE'
}
export interface DirectoryRun {
runId: string
trigger: 'MANUAL' | 'STARTUP'
trigger: 'MANUAL' | 'STARTUP' | 'SCHEDULED'
state: 'RUNNING' | 'SUCCEEDED' | 'FAILED'
startedAt: string
startedAt: string | null
finishedAt: string | null
complete: boolean
applied: boolean
@@ -13,10 +37,9 @@ export interface DirectoryRun {
errorMessage: string | null
}
export interface DirectoryStatus {
export interface DirectoryStatus extends DirectoryAvailabilityContract {
configured: boolean
running: boolean
snapshotState: 'UNAVAILABLE' | 'NEVER_SYNCED' | 'FRESH' | 'STALE' | 'CONTEXT_CHANGED'
maxStatusAgeSeconds: number
lastSuccessfulRunId: string | null
lastSuccessfulAt: string | null
@@ -36,19 +59,16 @@ export interface DirectoryDepartment {
export interface DirectoryOrganizationUser {
openId: string
userId: string
userId: string | null
name: string
email: string
mobile: string
jobTitle: string
employeeType: number | null
avatarUrl: string
employmentStatus: string
departmentIds: string[]
}
export interface DirectoryOrganization {
snapshotState: DirectoryStatus['snapshotState']
export interface DirectoryOrganization extends DirectoryAvailabilityContract {
lastSuccessfulAt: string | null
departments: DirectoryDepartment[]
users: DirectoryOrganizationUser[]
@@ -61,6 +81,13 @@ export const feishuDirectoryApi = {
request.post('/feishu/directory/sync', undefined, { timeout: DIRECTORY_SYNC_TIMEOUT, signal }),
status: (signal?: AbortSignal): Promise<DirectoryStatus> =>
request.get('/feishu/directory/status', { signal }),
organization: (signal?: AbortSignal): Promise<DirectoryOrganization> =>
request.get('/feishu/directory/organization', { signal }),
/** Departments (+ optional full users). Default omits users so the shell paints quickly. */
organization: (signal?: AbortSignal, includeUsers = false): Promise<DirectoryOrganization> =>
request.get('/feishu/directory/organization', { signal, params: { includeUsers } }),
/** Members for one department tree; used after the organization shell is ready. */
organizationMembers: (departmentId: string, signal?: AbortSignal, includeDescendants = true): Promise<DirectoryOrganization> =>
request.get('/feishu/directory/organization/members', {
signal,
params: { departmentId, includeDescendants },
}),
}
+23
View File
@@ -0,0 +1,23 @@
import request from './request'
export interface KingdeeAccountBinding {
userId: number
realName: string
employeeNo?: string | null
status?: string | null
bound: boolean
kingdeeUsername?: string | null
boundAt?: string | null
updatedAt?: string | null
boundBy?: number | null
}
export const kingdeeAccountsApi = {
list: (): Promise<KingdeeAccountBinding[]> => request.get('/kingdee/account-bindings'),
me: (): Promise<KingdeeAccountBinding> => request.get('/kingdee/account-bindings/me'),
bind: (userId: number, body: { kingdeeUsername: string; kingdeePassword: string; verifyLogin?: boolean }): Promise<KingdeeAccountBinding> =>
request.put(`/kingdee/account-bindings/${userId}`, body),
unbind: (userId: number): Promise<void> => request.delete(`/kingdee/account-bindings/${userId}`),
test: (userId: number): Promise<{ success: boolean; message: string }> =>
request.post(`/kingdee/account-bindings/${userId}/test`),
}
+120 -4
View File
@@ -65,6 +65,57 @@ export interface ReimApplicationDetail {
payments: PaymentRecord[]
paidAmountSnapshot?: number
remainingAmountSnapshot?: number
formSnapshot?: ReimbursementFormSnapshot
}
export type ReimbursementFormMode = 'FEISHU' | 'LOCAL'
export type ReimbursementFormSnapshotMode = ReimbursementFormMode | 'LEGACY'
export type ReimbursementFormFieldType = 'TEXT' | 'TEXTAREA' | 'DECIMAL' | 'DATE' | 'SINGLE_SELECT' | 'MULTI_SELECT' | 'CONTACT' | 'DEPARTMENT' | 'DISPLAY' | 'EXPENSE_ITEMS' | 'ATTACHMENT' | 'FORMULA'
export type ReimbursementFormFieldBinding = 'APPLICATION_NO' | 'TITLE' | 'APPLICANT_NAME' | 'APPLICANT_CONTACT' | 'APPLICANT_DEPARTMENT' | 'DEPARTMENT' | 'EXPENSE_TYPE' | 'TOTAL_AMOUNT' | 'DESCRIPTION' | 'SOURCE_DOC_NO' | 'EXPENSE_ITEMS' | 'EXPENSE_DATE' | 'EXPENSE_CATEGORY' | 'EXPENSE_DESCRIPTION' | 'EXPENSE_AMOUNT' | 'EXPENSE_ATTACHMENT' | 'CUSTOM'
export interface ReimbursementFormOption {
value: string
label: string
}
export interface ReimbursementFormField {
id: string
customId?: string
valueKey: string
providerType?: string
type: ReimbursementFormFieldType
binding: ReimbursementFormFieldBinding
label: string
required: boolean
readOnly: boolean
currency?: string
maxLength?: number
options: ReimbursementFormOption[]
children: ReimbursementFormField[]
}
export interface ReimbursementFormDefinition {
mode: ReimbursementFormMode
approvalCode?: string
definitionFingerprint?: string
formFingerprint?: string
fetchedAt?: string
fields: ReimbursementFormField[]
}
export interface ExpenseTypeMetadata {
id: number
code: string
name: string
category: string
description: string
}
export interface ReimbursementFormSnapshot {
mode: ReimbursementFormSnapshotMode
fingerprint?: string
fields: ReimbursementFormField[]
values: Record<string, unknown>
}
export interface ExpenseItem {
@@ -74,6 +125,16 @@ export interface ExpenseItem {
category: string
description?: string
amount: number
attachmentIds: Array<number | string>
attachments?: ReimbursementFormAttachment[]
attachmentMetadata?: ReimbursementFormAttachment[]
}
export interface ReimbursementFormAttachment {
id: number | string
fileName: string
contentType: string
fileSize: number
}
export interface CreateApplicationRequest {
@@ -85,6 +146,38 @@ export interface CreateApplicationRequest {
payeeName: string
payeeBankId: number
items: ExpenseItem[]
formFingerprint?: string
formValues?: Record<string, unknown>
}
export type ApprovalRouteSource = 'FEISHU' | 'LOCAL'
export interface ApprovalRouteNode {
order: number
nodeKey: string
nodeName: string
nodeType?: string
approvalMode?: string
approverLabels: string[]
dynamic: boolean
}
export interface ApprovalRoutePreview {
applicationId: number | string
source: ApprovalRouteSource
nodes: ApprovalRouteNode[]
routeFingerprint: string
snapshotFingerprint?: string
previewToken: string
expiresAt: string
snapshotFetchedAt?: string
staleSnapshot: boolean
exact: boolean
warning?: string
}
export interface SubmitReimbursementRequest {
previewToken: string
}
export interface Invoice {
@@ -100,8 +193,11 @@ export interface Invoice {
export interface Attachment {
id: number | string
fileName: string
fileType: string
fileUrl: string
fileType?: string
contentType?: string
fileSize?: number
fileUrl?: string
expenseItemId?: number | string
}
export interface ApprovalRecord {
@@ -130,6 +226,23 @@ export interface PaymentRecord {
}
export const reimbursementApi = {
getFormDefinition: (): Promise<ReimbursementFormDefinition> =>
request.get('/v1/reimbursements/form-definition', { suppressErrorNotification: true }),
getExpenseTypes: (): Promise<ExpenseTypeMetadata[]> =>
request.get('/metadata/expense-types', { suppressErrorNotification: true }),
uploadFormAttachment: (file: File, formFingerprint: string, controlId: string): Promise<ReimbursementFormAttachment> => {
const data = new FormData()
data.append('file', file)
data.append('formFingerprint', formFingerprint)
data.append('controlId', controlId)
return request.post('/v1/reimbursements/form-attachments', data, { headers: { 'Content-Type': 'multipart/form-data' }, suppressErrorNotification: true })
},
deleteFormAttachment: (id: number | string): Promise<void> =>
request.delete(`/v1/reimbursements/form-attachments/${encodeURIComponent(String(id))}`, { suppressErrorNotification: true }),
getWorkbench: (): Promise<any> =>
request.get('/v1/reimbursements/workbench'),
@@ -148,8 +261,11 @@ export const reimbursementApi = {
update: (id: number | string, data: CreateApplicationRequest): Promise<ReimApplicationDetail> =>
request.put(`/v1/reimbursements/${id}`, data),
submit: (id: number | string): Promise<ReimApplicationDetail> =>
request.post(`/v1/reimbursements/${id}/submit`),
getRoutePreview: (id: number | string): Promise<ApprovalRoutePreview> =>
request.get(`/v1/reimbursements/${id}/route-preview`),
submit: (id: number | string, data: SubmitReimbursementRequest): Promise<ReimApplicationDetail> =>
request.post(`/v1/reimbursements/${id}/submit`, data),
receive: (id: number | string): Promise<ReimApplicationDetail> =>
request.post(`/v1/reimbursements/${id}/receive`),
+24 -14
View File
@@ -3,13 +3,18 @@ import type { AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
type ClientRequestConfig = AxiosRequestConfig & { suppressErrorNotification?: boolean }
type ApiClient = {
get<T = unknown>(url: string, config?: AxiosRequestConfig): Promise<T>
post<T = unknown>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T>
put<T = unknown>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T>
delete<T = unknown>(url: string, config?: AxiosRequestConfig): Promise<T>
get<T = unknown>(url: string, config?: ClientRequestConfig): Promise<T>
post<T = unknown>(url: string, data?: unknown, config?: ClientRequestConfig): Promise<T>
put<T = unknown>(url: string, data?: unknown, config?: ClientRequestConfig): Promise<T>
delete<T = unknown>(url: string, config?: ClientRequestConfig): Promise<T>
}
const suppressErrorNotification = (config: unknown) =>
Boolean((config as { suppressErrorNotification?: boolean } | undefined)?.suppressErrorNotification)
const axiosClient = axios.create({
// Keep the same-origin default for Vite/Nginx proxy deployments while
// allowing a static build to call an explicitly configured API origin.
@@ -22,8 +27,12 @@ const axiosClient = axios.create({
})
const clearSessionAndRedirect = () => {
localStorage.removeItem('token')
sessionStorage.removeItem('token')
localStorage.removeItem('token') // remove credentials left by pre-hardening builds
localStorage.removeItem('userInfo')
localStorage.removeItem('finance.auth-day')
sessionStorage.removeItem('token')
sessionStorage.removeItem('userInfo')
if (router.currentRoute.value.path !== '/login') {
void router.push('/login')
}
@@ -36,7 +45,7 @@ const requestToken = (config: unknown): string | undefined => {
const clearOnlyIfRequestOwnsSession = (config: unknown) => {
const issuedToken = requestToken(config)
if (issuedToken && localStorage.getItem('token') === issuedToken) clearSessionAndRedirect()
if (issuedToken && sessionStorage.getItem('token') === issuedToken) clearSessionAndRedirect()
}
let lastNotification = ''
@@ -53,7 +62,7 @@ const notifyOnce = (message: string, type: 'error' | 'warning' | 'info' = 'error
// Request interceptor - attach JWT token
axiosClient.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token')
const token = sessionStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
@@ -74,7 +83,7 @@ axiosClient.interceptors.response.use(
if (res.code !== 200) {
if (res.code === 401) clearOnlyIfRequestOwnsSession(response.config)
notifyOnce(res.message || '请求失败')
if (!suppressErrorNotification(response.config)) notifyOnce(res.message || '请求失败')
return Promise.reject(new Error(res.message || '请求失败'))
}
return res.data
@@ -82,24 +91,25 @@ axiosClient.interceptors.response.use(
(error) => {
if (error.response) {
const { status, data } = error.response
const silent = suppressErrorNotification(error.config)
switch (status) {
case 401:
clearOnlyIfRequestOwnsSession(error.config)
notifyOnce('登录已过期,请重新登录')
if (!silent) notifyOnce('登录已过期,请重新登录')
break
case 403:
notifyOnce('权限不足')
if (!silent) notifyOnce('权限不足')
break
case 404:
notifyOnce('请求的资源不存在')
if (!silent) notifyOnce('请求的资源不存在')
break
case 409:
notifyOnce(data?.message || '业务冲突')
if (!silent) notifyOnce(data?.message || '业务冲突')
break
default:
notifyOnce(data?.message || '服务器错误')
if (!silent) notifyOnce(data?.message || '服务器错误')
}
} else {
} else if (!suppressErrorNotification(error.config)) {
notifyOnce('网络连接失败')
}
return Promise.reject(error)
+75
View File
@@ -0,0 +1,75 @@
import request from './request'
export type ScheduledTaskStatus = 'IDLE' | 'RUNNING'
export type ScheduledRunTrigger = 'MANUAL' | 'STARTUP' | 'SCHEDULED'
export type ScheduledRunState = 'QUEUED' | 'RUNNING' | 'SUCCEEDED' | 'FAILED'
export type ScheduledIntervalHours = 1 | 2 | 3 | 6 | 12 | 24
export interface ScheduledTask {
code: string
name: string
enabled: boolean
intervalHours: ScheduledIntervalHours
timeZone: string
nextDueAt: string | null
lastClaimedAt: string | null
version: number
status: ScheduledTaskStatus
}
export interface ScheduledRunCounts {
departments: number
usersSeen: number
eligible: number
excluded: number
created: number
updated: number
ineligible: number
outOfScope: number
}
export interface ScheduledTaskRun {
runId: string
trigger: ScheduledRunTrigger
state: ScheduledRunState
queuedAt: string
startedAt: string | null
finishedAt: string | null
attempts: number
complete: boolean
applied: boolean
counts: ScheduledRunCounts
errorCode: string | null
errorMessage: string | null
}
export interface ScheduledRunPage {
items: ScheduledTaskRun[]
page: number
size: number
total: number
}
export interface UpdateScheduledTaskRequest {
enabled: boolean
intervalHours: ScheduledIntervalHours
version: number
}
export const SCHEDULED_TASK_REQUEST_TIMEOUT = 15_000
export const SCHEDULED_TASK_EXECUTE_TIMEOUT = 20_000
const pathFor = (code: string) => `/scheduled-tasks/${encodeURIComponent(code)}`
export const scheduledTasksApi = {
list: (signal?: AbortSignal): Promise<ScheduledTask[]> =>
request.get('/scheduled-tasks', { signal, timeout: SCHEDULED_TASK_REQUEST_TIMEOUT }),
detail: (code: string, signal?: AbortSignal): Promise<ScheduledTask> =>
request.get(pathFor(code), { signal, timeout: SCHEDULED_TASK_REQUEST_TIMEOUT }),
updateSchedule: (code: string, body: UpdateScheduledTaskRequest, signal?: AbortSignal): Promise<ScheduledTask> =>
request.put(`${pathFor(code)}/schedule`, body, { signal, timeout: SCHEDULED_TASK_REQUEST_TIMEOUT, suppressErrorNotification: true }),
execute: (code: string, signal?: AbortSignal): Promise<ScheduledTaskRun> =>
request.post(`${pathFor(code)}/execute`, undefined, { signal, timeout: SCHEDULED_TASK_EXECUTE_TIMEOUT, suppressErrorNotification: true }),
runs: (code: string, page = 0, size = 20, signal?: AbortSignal): Promise<ScheduledRunPage> =>
request.get(`${pathFor(code)}/runs`, { params: { page, size }, signal, timeout: SCHEDULED_TASK_REQUEST_TIMEOUT }),
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

+1105 -407
View File
File diff suppressed because it is too large.
+23 -12
View File
@@ -1,8 +1,9 @@
<template>
<section class="card directory-panel" aria-labelledby="directory-title">
<div class="card-head directory-head">
<div><h2 id="directory-title">飞书通讯录同步</h2><p>同步飞书员工资料与目录状态;不作为 OAuth 登录条件;同步失败不覆盖上次结果</p></div>
<div><h2 id="directory-title">飞书通讯录同步</h2><p>同步飞书员工资料与目录状态;不作为 OAuth 登录条件;同步失败会保留当前目录</p></div>
<div class="directory-actions">
<router-link v-if="canManageSchedule" class="btn small" to="/scheduled-tasks">管理自动同步</router-link>
<button class="btn small" type="button" :disabled="loading || submitting" @click="refreshStatus">{{ loading ? '查询中…' : '刷新状态' }}</button>
<button v-if="canSync" class="btn primary" type="button" :disabled="syncDisabled" :aria-busy="submitting" @click="sync">{{ submitting || status?.running ? '同步中…' : '同步飞书通讯录' }}</button>
</div>
@@ -15,14 +16,16 @@
<template v-if="status">
<p v-if="!status.configured">飞书通讯录尚未配置,请联系管理员配置应用凭证与通讯录权限。</p>
<dl class="directory-meta">
<div><dt>通讯录快照</dt><dd>{{ snapshotLabels[status.snapshotState] }}</dd></div>
<div><dt>上次成功同步 <span class="time-zone-label">本地时间</span></dt><dd>{{ formatLocalDateTime(status.lastSuccessfulAt, '暂无') }}</dd></div>
<div><dt>快照有效至 <span class="time-zone-label">本地时间</span></dt><dd>{{ formatLocalDateTime(status.snapshotExpiresAt) }}</dd></div>
<div><dt>当前目录</dt><dd>{{ availabilityLabels[currentAvailability] }}</dd></div>
<div><dt>上次成功更新 <span class="time-zone-label">本地时间</span></dt><dd>{{ formatLocalDateTime(status.lastSuccessfulAt, '暂无') }}</dd></div>
<div><dt>当前版本</dt><dd>{{ status.currentRevision || status.lastSuccessfulRunId || '暂无' }}</dd></div>
<div><dt>配置上下文</dt><dd>{{ contextLabels[currentContext] }}</dd></div>
</dl>
<p v-if="status.snapshotState === 'STALE' || status.snapshotState === 'CONTEXT_CHANGED'">快照已过期或应用上下文已变化,请重新同步以更新目录资料与业务候选人。</p>
<p v-if="currentContext === 'CHANGED'" class="directory-warning" role="status">应用配置上下文已变化,这是更新提示,不会停用已经可用的当前目录;可同步以更新资料。</p>
<p v-else-if="status.snapshotState === 'STALE'" class="directory-warning" role="status">服务返回旧版 STALE 状态;{{ currentAvailability === 'AVAILABLE' ? '当前目录仍可继续使用,建议同步更新资料。' : '当前服务未确认目录可用,请同步后再添加成员。' }}</p>
</template>
<template v-if="run">
<p>最近运行:{{ run.trigger === 'STARTUP' ? '启动同步' : '手动同步' }} · {{ stateLabels[run.state] }} · {{ run.applied ? '已提交' : '未提交,不覆盖上次结果' }}</p>
<p>最近运行:{{ triggerLabels[run.trigger] }} · {{ stateLabels[run.state] }} · {{ run.applied ? '已提交' : '未提交,保留当前目录' }}</p>
<p class="muted-copy">运行时间(本地时间):{{ formatLocalDateTime(run.startedAt) }} — {{ formatLocalDateTime(run.finishedAt, '尚未结束') }} · 运行 ID:{{ run.runId }}</p>
<p v-if="run.state === 'FAILED' || run.errorMessage" class="directory-failure" role="alert">{{ run.errorCode || '同步失败' }}:{{ run.errorMessage || '同步未完成,请检查配置后重试。' }}</p>
<dl class="directory-counts"><div v-for="(label, key) in countLabels" :key="key"><dt>{{ label }}</dt><dd>{{ run.counts[key] }}</dd></div></dl>
@@ -34,27 +37,34 @@
<script setup lang="ts">
import { computed, onMounted, onBeforeUnmount, ref } from 'vue'
import { feishuDirectoryApi, type DirectoryRun, type DirectoryStatus } from '@/api/feishuDirectory'
import { directoryAvailability, feishuDirectoryApi, type DirectoryContextState, type DirectoryRun, type DirectoryStatus } from '@/api/feishuDirectory'
import { useUserStore } from '@/store/user'
const emit = defineEmits<{ committed: [] }>()
const userStore = useUserStore()
// Deliberately never use Users.vue's legacy administrator/demo fallback.
const canSync = computed(() => userStore.hasPermission('system:feishu:sync'))
const canRead = computed(() => canSync.value || userStore.hasPermission('system:feishu:bind'))
const canSync = computed(() => userStore.canEdit('system.feishu.directory.sync'))
const canRead = computed(() => userStore.canRead('page.feishu-directory'))
const canManageSchedule = computed(() => userStore.canRead('page.scheduled-tasks'))
const status = ref<DirectoryStatus | null>(null)
const run = ref<DirectoryRun | null>(null)
const loading = ref(false)
const submitting = ref(false)
const uncertain = ref(true)
const error = ref('')
const currentAvailability = computed(() => status.value ? directoryAvailability(status.value) : 'UNAVAILABLE')
const currentContext = computed<DirectoryContextState>(() => {
if (status.value?.contextState === 'MATCH' || status.value?.contextState === 'CHANGED' || status.value?.contextState === 'UNKNOWN') return status.value.contextState
return status.value?.snapshotState === 'CONTEXT_CHANGED' ? 'CHANGED' : 'UNKNOWN'
})
const syncDisabled = computed(() => !canSync.value || loading.value || submitting.value || uncertain.value || !status.value?.configured || status.value.running)
const controller = new AbortController()
let disposed = false
let timer: ReturnType<typeof setTimeout> | undefined
let observedSuccess: string | null | undefined
const snapshotLabels = { UNAVAILABLE: '不可用', NEVER_SYNCED: '尚未同步', FRESH: '有效', STALE: '已过期', CONTEXT_CHANGED: '应用上下文已变化' }
const availabilityLabels = { AVAILABLE: '可用', NEVER_SYNCED: '尚未同步', UNAVAILABLE: '不可用' }
const contextLabels: Record<DirectoryContextState, string> = { MATCH: '一致', CHANGED: '已变化(仅提示)', UNKNOWN: '未知' }
const stateLabels = { RUNNING: '运行中', SUCCEEDED: '成功', FAILED: '失败' }
const triggerLabels: Record<DirectoryRun['trigger'], string> = { MANUAL: '手动同步', STARTUP: '启动同步', SCHEDULED: '自动同步' }
const countLabels = { departments: '部门', usersSeen: '扫描员工', excluded: '排除', created: '新增用户', updated: '更新用户', outOfScope: '可见范围外' }
// Date getters intentionally use the browser's local timezone instead of
@@ -130,11 +140,12 @@ onBeforeUnmount(() => { disposed = true; clearTimeout(timer); controller.abort()
.directory-head > div:first-child { flex: 1 1 320px; min-width: 0; }
.directory-head p, .directory-body { overflow-wrap: anywhere; }
.directory-actions { display: flex; flex-wrap: wrap; gap: 8px; }
.directory-body { padding: 0 18px 16px; font-size: 12px; color: var(--muted); }
.directory-body { padding: 0 22px 20px; font-size: 12px; color: var(--muted); }
.directory-body p { margin: 10px 0; }
.directory-meta, .directory-counts { display: grid; gap: 12px; margin: 12px 0 0; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); }
.directory-counts { grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); }
dt { color: var(--muted); } dd { margin: 4px 0 0; color: var(--body); }
.time-zone-label { color: var(--quiet); font-size: 10px; font-weight: 400; white-space: nowrap; }
.directory-failure { color: var(--danger); }
.directory-warning { color: var(--warning); }
</style>
@@ -0,0 +1,262 @@
<template>
<div class="kingdee-bind-panel" :class="{ embedded: embedded }">
<div v-if="loadError" class="inline-alert danger" role="alert">
<b>!</b><span>{{ loadError }}</span>
<button class="btn small" type="button" @click="load">重试</button>
</div>
<div class="card fill-list-card primary-list-card" :class="{ 'panel-card': embedded }">
<div class="filter-bar">
<label v-if="canViewAll" class="filter-search">
<span aria-hidden="true">&#x1F50D;</span>
<input v-model="search" type="search" placeholder="搜索姓名、工号或金蝶账号" aria-label="搜索财务人员">
</label>
<span v-else class="filter-hint">当前权限:仅查看本人</span>
<span class="filter-spacer"></span>
<span class="tag info">{{ filtered.length }} 人</span>
<span class="tag" :class="boundCount ? 'success' : 'neutral'">已绑定 {{ boundCount }}</span>
</div>
<div v-if="loading" class="load-wrap" role="status">
<span class="loader" aria-hidden="true"></span><span>正在加载绑定列表…</span>
</div>
<div v-else-if="!loadError && filtered.length" class="table-wrap" tabindex="0" role="region" aria-label="金蝶账号绑定列表">
<table class="data-table responsive-table">
<thead>
<tr>
<th>财务人员</th>
<th>工号</th>
<th>金蝶账号</th>
<th>绑定状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="item in paginatedItems" :key="item.userId">
<td data-label="财务人员">
<strong>{{ item.realName }}</strong>
<small v-if="item.userId === meId" class="self-mark">本人</small>
</td>
<td data-label="工号"><small>{{ item.employeeNo || '—' }}</small></td>
<td data-label="金蝶账号"><small>{{ item.kingdeeUsername || '—' }}</small></td>
<td data-label="绑定状态">
<span class="tag" :class="item.bound ? 'success' : 'neutral'">{{ item.bound ? '已绑定' : '未绑定' }}</span>
</td>
<td data-label="操作" class="actions-cell">
<button v-if="canBindRow(item)" class="table-action" type="button" @click="openBind(item)">
{{ item.bound ? '重新绑定' : '绑定' }}
</button>
<button v-if="canBindRow(item) && item.bound" class="table-action" type="button" :disabled="testingId === item.userId" @click="testBinding(item)">
{{ testingId === item.userId ? '验证中…' : '验证' }}
</button>
<button v-if="canUnbindRow(item) && item.bound" class="table-action danger-action" type="button" @click="unbind(item)">解绑</button>
</td>
</tr>
</tbody>
</table>
</div>
<div v-else-if="!loading && !loadError" class="empty-state">
<strong>{{ canViewAll ? '暂无财务人员' : '暂无本人记录' }}</strong>
<span>{{ canViewAll ? '请先为用户分配「财务」角色,或授予「变更金蝶财务单据」权限。' : '当前账号不在可绑定范围内,或尚无权限。' }}</span>
</div>
<AppListPagination
v-if="!loading && !loadError && filtered.length && canViewAll"
v-model:page="page"
v-model:page-size="pageSize"
:total="filtered.length"
aria-label="金蝶账号绑定列表分页"
/>
</div>
<dialog ref="bindDialog" v-dialog-drag class="app-dialog" aria-labelledby="kingdee-bind-title" @cancel.prevent="closeBind">
<form @submit.prevent="saveBind">
<div class="modal-head" data-dialog-drag-handle>
<div>
<span class="eyebrow">BIND KINGDEE ACCOUNT</span>
<h2 id="kingdee-bind-title">绑定金蝶账号 · {{ editing?.realName }}</h2>
<p>填写该人员在金蝶云星空的登录用户名与密码;保存前默认验证登录。</p>
</div>
<button class="modal-close" type="button" aria-label="关闭" :disabled="saving" @click="closeBind">×</button>
</div>
<div class="modal-body">
<div class="form-grid">
<div class="field">
<label for="kingdee-username">金蝶用户名 <em>*</em></label>
<input id="kingdee-username" v-model.trim="form.kingdeeUsername" required autocomplete="username" :disabled="saving">
</div>
<div class="field">
<label for="kingdee-password">金蝶密码 <em>*</em></label>
<input id="kingdee-password" v-model="form.kingdeePassword" type="password" required autocomplete="new-password" :disabled="saving" :placeholder="editing?.bound ? '请重新输入密码' : '请输入金蝶密码'">
</div>
<label class="check-option full">
<input v-model="form.verifyLogin" type="checkbox" :disabled="saving">
<span>保存前验证金蝶登录</span>
</label>
</div>
</div>
<div class="modal-actions">
<button class="btn" type="button" :disabled="saving" @click="closeBind">取消</button>
<button class="btn primary" type="submit" :disabled="saving">{{ saving ? '保存中…' : '保存绑定' }}</button>
</div>
</form>
</dialog>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AppListPagination from '@/components/common/AppListPagination.vue'
import { useListPagination } from '@/composables/useListPagination'
import { kingdeeAccountsApi, type KingdeeAccountBinding } from '@/api/kingdeeAccounts'
import { useUserStore } from '@/store/user'
defineProps<{ embedded?: boolean }>()
const userStore = useUserStore()
const meId = computed(() => Number(userStore.userInfo?.id || 0) || null)
const canViewAll = computed(() => userStore.canRead('finance.kingdee.account.view-all'))
const canBindAll = computed(() => userStore.canEdit('finance.kingdee.account.bind'))
const canBindOwn = computed(() => userStore.canEdit('finance.kingdee.account.bind-own'))
const canUnbindAll = computed(() => userStore.canEdit('finance.kingdee.account.unbind'))
const canUnbindOwn = computed(() => userStore.canEdit('finance.kingdee.account.unbind-own'))
const canBindRow = (item: KingdeeAccountBinding) =>
canBindAll.value || (canBindOwn.value && item.userId === meId.value)
const canUnbindRow = (item: KingdeeAccountBinding) =>
canUnbindAll.value || (canUnbindOwn.value && item.userId === meId.value)
const items = ref<KingdeeAccountBinding[]>([])
const loading = ref(false)
const loadError = ref('')
const search = ref('')
const saving = ref(false)
const testingId = ref<number | null>(null)
const bindDialog = ref<HTMLDialogElement | null>(null)
const editing = ref<KingdeeAccountBinding | null>(null)
const form = reactive({ kingdeeUsername: '', kingdeePassword: '', verifyLogin: true })
const errorText = (error: unknown) => {
const responseMessage = (error as { response?: { data?: { message?: unknown } } })?.response?.data?.message
if (typeof responseMessage === 'string' && responseMessage.trim()) return responseMessage
return error instanceof Error && error.message ? error.message : '请求失败,请稍后重试。'
}
const filtered = computed(() => {
const q = search.value.trim().toLowerCase()
if (!q) return items.value
return items.value.filter(item =>
[item.realName, item.employeeNo, item.kingdeeUsername]
.some(value => String(value || '').toLowerCase().includes(q)))
})
const boundCount = computed(() => items.value.filter(item => item.bound).length)
const { page, pageSize, paginatedItems } = useListPagination(filtered, { resetSources: [search] })
const load = async () => {
loading.value = true
loadError.value = ''
try {
await userStore.loadPermissions()
items.value = await kingdeeAccountsApi.list() || []
} catch (error) {
loadError.value = errorText(error)
} finally {
loading.value = false
}
}
const openBind = async (item: KingdeeAccountBinding) => {
if (!canBindRow(item)) return
editing.value = item
form.kingdeeUsername = item.kingdeeUsername || ''
form.kingdeePassword = ''
form.verifyLogin = true
await nextTick()
bindDialog.value?.showModal()
}
const closeBind = () => {
if (saving.value) return
bindDialog.value?.close()
editing.value = null
}
const saveBind = async () => {
if (!editing.value || !canBindRow(editing.value) || saving.value) return
saving.value = true
try {
const saved = await kingdeeAccountsApi.bind(editing.value.userId, {
kingdeeUsername: form.kingdeeUsername,
kingdeePassword: form.kingdeePassword,
verifyLogin: form.verifyLogin,
})
const index = items.value.findIndex(item => item.userId === saved.userId)
if (index >= 0) items.value[index] = saved
else items.value.push(saved)
ElMessage.success('金蝶账号已绑定')
closeBind()
} catch (error) {
ElMessage.error(`绑定失败:${errorText(error)}`)
} finally {
saving.value = false
}
}
const testBinding = async (item: KingdeeAccountBinding) => {
if (!canBindRow(item) || testingId.value != null) return
testingId.value = item.userId
try {
const result = await kingdeeAccountsApi.test(item.userId)
if (result?.success) ElMessage.success(result.message || '验证成功')
else ElMessage.error(result?.message || '验证失败')
} catch (error) {
ElMessage.error(`验证失败:${errorText(error)}`)
} finally {
testingId.value = null
}
}
const unbind = async (item: KingdeeAccountBinding) => {
if (!canUnbindRow(item)) return
try {
await ElMessageBox.confirm(`确认解绑 ${item.realName} 的金蝶账号?解绑后该员工将无法变更金蝶财务单据。`, '解绑确认', {
type: 'warning',
confirmButtonText: '解绑',
cancelButtonText: '取消',
})
} catch {
return
}
try {
await kingdeeAccountsApi.unbind(item.userId)
const index = items.value.findIndex(row => row.userId === item.userId)
if (index >= 0) {
items.value[index] = {
...items.value[index],
bound: false,
kingdeeUsername: null,
boundAt: null,
updatedAt: null,
boundBy: null,
}
}
ElMessage.success('已解绑')
} catch (error) {
ElMessage.error(`解绑失败:${errorText(error)}`)
}
}
onMounted(() => { void load() })
defineExpose({ reload: load })
</script>
<style scoped>
.kingdee-bind-panel.embedded .panel-card {
box-shadow: none;
border: 1px solid var(--line);
}
.filter-hint { color: var(--muted); font-size: 12px; }
.self-mark { margin-left: 6px; color: var(--muted); font-size: 11px; }
.check-option.full { grid-column: 1 / -1; display: flex; align-items: center; gap: 8px; margin-top: 4px; }
</style>
+522
View File
@@ -0,0 +1,522 @@
<template>
<section class="sync-panel primary-list-card" aria-labelledby="kingdee-sync-title">
<div class="sync-head">
<div>
<span class="eyebrow">KINGDEE SYNC</span>
<h3 id="kingdee-sync-title">金蝶单据同步规则</h3>
<p>配置单据字段映射、过滤条件和同步目标表;过滤条件只接受结构化值,不接受原始 SQL。</p>
</div>
<button v-if="canCreate" class="btn primary small" type="button" @click="openCreate">新建同步规则</button>
</div>
<div v-if="!canView" class="sync-empty" role="alert">
<strong>无权查看同步规则</strong><span>当前账号没有集成查看权限。</span>
</div>
<div v-else-if="loading" class="sync-loading" role="status" aria-live="polite"><span class="loader" aria-hidden="true"></span>正在加载同步规则…</div>
<div v-else-if="loadError" class="inline-alert danger sync-alert" role="alert"><span>{{ loadError }}</span><button class="btn small" type="button" @click="loadConfigs">重试</button></div>
<template v-else>
<div v-if="!configs.length" class="sync-empty"><strong>暂无同步规则</strong><span>新建规则后,可以创建目标表并执行单据同步。</span></div>
<div v-else class="table-scroll" role="region" aria-label="金蝶同步规则列表" tabindex="0">
<el-table :data="pagedConfigs" row-key="id" size="small" empty-text="暂无同步规则">
<el-table-column prop="configName" label="配置名称" min-width="150" />
<el-table-column prop="formId" label="formId" min-width="140" />
<el-table-column prop="targetTableName" label="目标表" min-width="150" />
<el-table-column label="字段 / 过滤" width="105">
<template #default="scope">{{ scope.row.fields.length }} / {{ scope.row.filters.length }}</template>
</el-table-column>
<el-table-column label="状态" width="90">
<template #default="scope"><el-tag :type="scope.row.enabled ? 'success' : 'info'" size="small">{{ scope.row.enabled ? '已启用' : '已停用' }}</el-tag></template>
</el-table-column>
<el-table-column label="操作" fixed="right" width="155">
<template #default="scope">
<div class="row-actions">
<el-button v-if="canView" link type="primary" size="small" @click="openEdit(scope.row.id)">{{ canUpdate ? '编辑' : '查看' }}</el-button>
<el-button v-if="canDelete" link type="danger" size="small" @click="deleteConfig(scope.row)">删除</el-button>
<span v-if="!canUpdate && !canDelete" class="muted-copy">只读</span>
</div>
</template>
</el-table-column>
</el-table>
</div>
<AppListPagination v-if="configs.length" v-model:page="currentPage" v-model:page-size="pageSize" :total="configs.length" aria-label="金蝶同步规则分页" />
</template>
<el-dialog ref="dialogRef" v-model="dialogVisible" :aria-label="editingId === null ? '新建金蝶同步规则' : '编辑金蝶同步规则'" width="min(1080px, 96vw)" align-center :draggable="desktopDialogDrag" :before-close="beforeKingdeeDialogClose" :close-on-click-modal="!dialogBusy" :close-on-press-escape="!dialogBusy" :show-close="!dialogBusy" destroy-on-close class="kingdee-sync-dialog" @closed="resetKingdeeDialogPosition">
<template #header>
<div class="dialog-title-block">
<span class="eyebrow">KINGDEE SYNC RULE</span>
<h2>{{ editingId === null ? '新建金蝶同步规则' : '编辑金蝶同步规则' }}</h2>
<p>配置来源单据、目标表及字段映射;结构变更请在同步前完成目标表校验。</p>
</div>
</template>
<div v-if="detailLoading" class="sync-loading" role="status"><span class="loader" aria-hidden="true"></span>正在加载规则详情…</div>
<div v-else class="dialog-content">
<div v-if="detailError" class="inline-alert danger" role="alert"><span>{{ detailError }}</span></div>
<el-form v-else ref="formRef" :model="draft" label-position="top" @submit.prevent>
<div v-if="validationError" class="form-error" role="alert">{{ validationError }}</div>
<div class="sync-form-grid">
<el-form-item label="单据名称" required :error="fieldError('configName')"><el-input v-model="draft.configName" :disabled="!canManage" maxlength="100" show-word-limit placeholder="例如:销售订单" /></el-form-item>
<el-form-item label="金蝶单据标识(formId)" required :error="fieldError('formId')"><el-input v-model="draft.formId" :disabled="!canManage" maxlength="100" placeholder="例如:SAL_SaleOrder" /></el-form-item>
<el-form-item label="数据库表名" required :error="fieldError('targetTableName')"><el-input v-model="draft.targetTableName" :disabled="!canManage" maxlength="63" placeholder="例如:kd_sale_order" /></el-form-item>
<el-form-item label="表注释名"><el-input v-model="draft.targetTableComment" :disabled="!canManage" maxlength="200" placeholder="可选" /></el-form-item>
<el-form-item label="启用"><el-switch v-model="draft.enabled" :disabled="!canManage" active-text="启用" inactive-text="停用" /></el-form-item>
<el-form-item label="最大同步行数" required :error="fieldError('maxRowsPerRun')"><el-input-number v-model="draft.maxRowsPerRun" :disabled="!canManage" :min="1" :max="100000" controls-position="right" /></el-form-item>
</div>
<div class="subsection-head"><div><h4>字段映射</h4><p>必须包含 FBillNo 作为不可变来源主键;排序按列表顺序提交。</p></div><el-button v-if="canManage" type="primary" plain size="small" @click="addField">新增字段</el-button></div>
<div v-if="fieldError('fields')" class="form-error compact-error" role="alert">{{ fieldError('fields') }}</div>
<div class="mapping-list">
<div v-for="(field, index) in draft.fields" :key="field._key" class="mapping-row">
<el-form-item label="源字段标识" required><el-input v-model="field.sourceFieldKey" :disabled="!canManage" placeholder="如:FMaterialId" /></el-form-item>
<el-form-item label="数据库字段名" required><el-input v-model="field.targetColumnName" :disabled="!canManage" placeholder="如:material_id" /></el-form-item>
<el-form-item label="字段注释"><el-input v-model="field.fieldComment" :disabled="!canManage" placeholder="可选" /></el-form-item>
<el-form-item label="类型" required><el-select v-model="field.dataType" :disabled="!canManage" placeholder="选择类型" @change="onDataTypeChange(field)"><el-option v-for="type in dataTypes" :key="type" :label="type" :value="type" /></el-select></el-form-item>
<el-form-item label="长度"><el-input-number v-model="field.fieldLength" :disabled="!canManage || field.dataType !== 'STRING'" :min="1" :max="10000" controls-position="right" placeholder="可选" /></el-form-item>
<el-button v-if="canManage" class="remove-row" link type="danger" :disabled="draft.fields.length <= 1" :aria-label="`删除第${index + 1}条字段`" @click="removeField(index)">删除</el-button>
</div>
</div>
<div class="subsection-head filter-head"><div><h4>过滤条件</h4><p>服务端会将结构化条件转换为查询条件,请勿填写 SQL 片段。</p></div><el-button v-if="canManage" type="primary" plain size="small" @click="addFilter">新增过滤</el-button></div>
<div class="filter-list">
<div v-for="(filter, index) in draft.filters" :key="filter._key" class="filter-row">
<el-form-item label="源字段标识"><el-input v-model="filter.sourceFieldKey" :disabled="!canManage" placeholder="如:FDocumentStatus" /></el-form-item>
<el-form-item label="操作符"><el-select v-model="filter.operator" :disabled="!canManage"><el-option v-for="operator in operators" :key="operator.value" :label="operator.label" :value="operator.value" /></el-select></el-form-item>
<el-form-item label="过滤值"><el-input v-model="filter.filterValue" :disabled="!canManage" placeholder="结构化值,如:A,B" /></el-form-item>
<el-button v-if="canManage" class="remove-row" link type="danger" :aria-label="`删除第${index + 1}条过滤条件`" @click="removeFilter(index)">删除</el-button>
</div>
<div v-if="!draft.filters.length" class="muted-copy filter-empty">未配置过滤条件,将按金蝶接口返回规则执行。</div>
</div>
</el-form>
<div v-if="!detailLoading && !detailError" class="detail-actions" aria-label="同步规则操作">
<el-button type="primary" :disabled="!canManage || actionLoading === 'save'" :loading="actionLoading === 'save'" @click="saveConfig">保存配置</el-button>
<el-button v-if="canPrepare" :disabled="editingId === null || Boolean(actionLoading)" :loading="actionLoading === 'prepare'" @click="prepareTable">创建/校验目标表</el-button>
<el-button v-if="canPreview" :disabled="editingId === null || Boolean(actionLoading)" :loading="actionLoading === 'preview'" @click="previewData">预览数据</el-button>
<el-button type="success" :disabled="syncDisabled" :loading="syncInProgress" @click="syncNow">{{ activeRun ? '同步运行中' : '立即同步' }}</el-button>
</div>
<div v-if="prepareResult" class="result-note" :class="prepareResult.success === false ? 'result-danger' : 'result-success'" role="status">{{ prepareResult.message || (prepareResult.success === false ? '目标表处理失败' : '目标表已创建或校验通过') }}</div>
<section v-if="previewResult" class="result-section" aria-labelledby="preview-result-title">
<div class="result-title"><h4 id="preview-result-title">预览结果</h4><el-tag v-if="previewResult.truncated" type="warning" size="small">结果已截断</el-tag></div>
<p class="result-meta">过滤条件:{{ previewResult.filterString || '无' }} · 返回 {{ previewResult.rows.length }} 行</p>
<div v-if="!previewResult.rows.length" class="muted-copy">暂无符合条件的数据。</div>
<div v-else class="table-scroll preview-table" role="region" aria-label="同步数据预览" tabindex="0"><el-table :data="previewResult.rows" size="small"><el-table-column v-for="column in previewColumns" :key="column" :prop="column" :label="column" min-width="140"><template #default="scope">{{ formatCell(scope.row[column]) }}</template></el-table-column></el-table></div>
</section>
<div v-if="runNotice" class="result-note" :class="runNoticeDanger ? 'result-danger' : 'result-pending'" :role="runNoticeDanger ? 'alert' : 'status'" aria-live="polite">
<span>{{ runNotice }}</span><el-button v-if="pollingTimedOut" link type="primary" size="small" :loading="runLoading" @click="refreshRunStatus">刷新运行状态</el-button>
</div>
<section v-if="latestRun || runs.length" class="result-section" aria-labelledby="run-result-title">
<div class="result-title"><h4 id="run-result-title">运行结果</h4><span v-if="runLoading" class="muted-copy" role="status">正在查询状态…</span></div>
<div v-if="latestRun" class="run-summary" role="status" aria-live="polite"><span>状态:{{ latestRun.status }}</span><span>fetched:{{ latestRun.fetchedCount ?? 0 }}</span><span>inserted:{{ latestRun.insertedCount ?? 0 }}</span><span>updated:{{ latestRun.updatedCount ?? 0 }}</span><span>failed:{{ latestRun.failedCount ?? 0 }}</span><span v-if="latestRun.errorMessage" class="run-error">{{ latestRun.errorMessage }}</span></div>
<div v-if="runs.length" class="table-scroll run-table" role="region" aria-label="历史运行结果" tabindex="0"><el-table :data="runs" size="small"><el-table-column prop="status" label="status" width="110" /><el-table-column prop="fetchedCount" label="fetched" width="95" /><el-table-column prop="insertedCount" label="inserted" width="95" /><el-table-column prop="updatedCount" label="updated" width="95" /><el-table-column prop="failedCount" label="failed" width="85" /><el-table-column label="运行时间" min-width="180"><template #default="scope">{{ formatDate(scope.row.startedAt) }}</template></el-table-column></el-table></div>
</section>
</div>
<template #footer><el-button :disabled="dialogBusy" @click="requestKingdeeDialogClose">关闭</el-button></template>
</el-dialog>
</section>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { adminApi, type KingdeePrepareTableResult, type KingdeeSyncConfig, type KingdeeSyncConfigId, type KingdeeSyncConfigPayload, type KingdeeSyncDataType, type KingdeeSyncFilterOperator, type KingdeeSyncPreview, type KingdeeSyncRun } from '@/api/admin'
import AppListPagination from '@/components/common/AppListPagination.vue'
import { useListPagination } from '@/composables/useListPagination'
type DraftField = KingdeeSyncConfigPayload['fields'][number] & { _key: string }
type DraftFilter = KingdeeSyncConfigPayload['filters'][number] & { _key: string }
type KingdeeSyncDraft = Omit<KingdeeSyncConfigPayload, 'fields' | 'filters'> & { fields: DraftField[]; filters: DraftFilter[] }
type Action = '' | 'save' | 'prepare' | 'preview' | 'sync'
type DialogPositionInstance = { resetPosition: () => void }
const props = withDefaults(defineProps<{ canView: boolean; canCreate: boolean; canUpdate: boolean; canDelete: boolean; canPrepare: boolean; canPreview: boolean; canSync: boolean }>(), { canView: false, canCreate: false, canUpdate: false, canDelete: false, canPrepare: false, canPreview: false, canSync: false })
const dataTypes: KingdeeSyncDataType[] = ['STRING', 'INTEGER', 'BIGINT', 'DECIMAL', 'DATE', 'DATETIME', 'BOOLEAN', 'JSON']
const operators: Array<{ value: KingdeeSyncFilterOperator; label: string }> = [
{ value: 'EQ', label: '等于(EQ)' }, { value: 'NE', label: '不等于(NE)' }, { value: 'GT', label: '大于(GT)' }, { value: 'GE', label: '大于等于(GE)' },
{ value: 'LT', label: '小于(LT)' }, { value: 'LE', label: '小于等于(LE)' }, { value: 'LIKE', label: '包含(LIKE)' }, { value: 'IN', label: '集合(IN)' },
]
const configs = ref<KingdeeSyncConfig[]>([])
const loading = ref(false)
const loaded = ref(false)
const loadError = ref('')
const dialogVisible = ref(false)
const dialogRef = ref<DialogPositionInstance>()
const desktopDragMedia = window.matchMedia('(min-width: 761px)')
const desktopDialogDrag = ref(desktopDragMedia.matches)
const resetKingdeeDialogPosition = () => { dialogRef.value?.resetPosition() }
const updateDesktopDialogDrag = (event: MediaQueryListEvent) => { desktopDialogDrag.value = event.matches;if(!event.matches)resetKingdeeDialogPosition() }
desktopDragMedia.addEventListener('change', updateDesktopDialogDrag)
window.addEventListener('resize', resetKingdeeDialogPosition)
const editingId = ref<KingdeeSyncConfigId | null>(null)
const detailLoading = ref(false)
const detailError = ref('')
const formRef = ref<FormInstance>()
const draft = ref<KingdeeSyncDraft>(emptyDraft())
const validationError = ref('')
const actionLoading = ref<Action>('')
const prepareResult = ref<KingdeePrepareTableResult | null>(null)
const previewResult = ref<KingdeeSyncPreview | null>(null)
const latestRun = ref<KingdeeSyncRun | null>(null)
const runs = ref<KingdeeSyncRun[]>([])
const runLoading = ref(false)
const runNotice = ref('')
const runNoticeDanger = ref(false)
const pollingTimedOut = ref(false)
const pollingRunId = ref<KingdeeSyncConfigId | null>(null)
const syncUncertain = ref(false)
const POLL_FAST_INTERVAL_MS = 2000
const POLL_SLOW_INTERVAL_MS = 5000
const POLL_BACKOFF_AFTER_MS = 30 * 1000
const POLL_TIMEOUT_MS = 31 * 60 * 1000
const terminalStatuses = new Set(['SUCCEEDED', 'PARTIAL', 'FAILED'])
let pollTimer: ReturnType<typeof setTimeout> | undefined
let pollStartedAt = 0
let pollDeadline = 0
let runContext = 0
let pollingBaseline = new Set<string>()
let configLoadGeneration = 0
let configRefreshQueued = false
let configLoadPromise: Promise<void> | null = null
const { page: currentPage, pageSize, paginatedItems: pagedConfigs } = useListPagination(configs)
const previewColumns = computed(() => {
const columns = new Set<string>()
previewResult.value?.rows.forEach(row => Object.keys(row).forEach(key => columns.add(key)))
return Array.from(columns)
})
const activeRun = computed(() => runs.value.find(run => run.status === 'RUNNING') || (latestRun.value?.status === 'RUNNING' ? latestRun.value : null))
const canManage = computed(() => editingId.value === null ? props.canCreate : props.canUpdate)
const syncInProgress = computed(() => actionLoading.value === 'sync' || Boolean(activeRun.value) || syncUncertain.value)
const syncDisabled = computed(() => !props.canSync || editingId.value === null || Boolean(actionLoading.value) || Boolean(activeRun.value) || syncUncertain.value)
const dialogBusy = computed(() => detailLoading.value || runLoading.value || Boolean(actionLoading.value) || syncInProgress.value)
function beforeKingdeeDialogClose(done: () => void) { if (!dialogBusy.value) done() }
function requestKingdeeDialogClose() { if (!dialogBusy.value) dialogVisible.value = false }
function key(prefix: string) { return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2)}` }
function emptyField(): DraftField { return { _key: key('field'), sourceFieldKey: '', targetColumnName: '', fieldComment: '', dataType: 'STRING', fieldLength: null, sortOrder: 0 } }
function emptyFilter(): DraftFilter { return { _key: key('filter'), sourceFieldKey: '', operator: 'EQ', filterValue: '', sortOrder: 0 } }
function emptyDraft(): KingdeeSyncDraft { return { configName: '', formId: '', targetTableName: '', targetTableComment: '', enabled: true, maxRowsPerRun: 1000, fields: [emptyField()], filters: [] } }
function normalizeDraft(config: Partial<KingdeeSyncConfig>): KingdeeSyncDraft {
return {
configName: String(config.configName || ''), formId: String(config.formId || ''), targetTableName: String(config.targetTableName || ''), targetTableComment: String(config.targetTableComment || ''),
enabled: config.enabled !== false, maxRowsPerRun: Number(config.maxRowsPerRun) || 1000,
fields: (Array.isArray(config.fields) && config.fields.length ? config.fields : [emptyField()]).map((field, index) => ({ ...field, _key: key('field'), fieldComment: field.fieldComment || '', fieldLength: field.fieldLength ?? null, sortOrder: index })),
filters: (Array.isArray(config.filters) ? config.filters : []).map((filter, index) => ({ ...filter, _key: key('filter'), filterValue: String(filter.filterValue || ''), sortOrder: index })),
}
}
function stopRunTracking() {
if (pollTimer) clearTimeout(pollTimer)
pollTimer = undefined
pollingRunId.value = null
pollStartedAt = 0
pollDeadline = 0
}
function resetResults() {
stopRunTracking(); prepareResult.value = null; previewResult.value = null; latestRun.value = null; runs.value = []; validationError.value = ''; detailError.value = ''
runNotice.value = ''; runNoticeDanger.value = false; pollingTimedOut.value = false; syncUncertain.value = false
}
function loadConfigs(): Promise<void> {
if (!props.canView) return Promise.resolve()
// Every request invalidates an older response. Calls made while a request is
// in flight are coalesced into exactly one subsequent refresh.
configLoadGeneration += 1
configRefreshQueued = true
if (!configLoadPromise) {
loading.value = true
configLoadPromise = drainConfigLoads().finally(() => {
loading.value = false
configLoadPromise = null
})
}
return configLoadPromise
}
async function drainConfigLoads() {
while (configRefreshQueued && props.canView) {
configRefreshQueued = false
const generation = configLoadGeneration
loadError.value = ''
try {
const result = await adminApi.listKingdeeSyncConfigs()
if (generation !== configLoadGeneration || !props.canView) continue
configs.value = Array.isArray(result) ? result : []
loaded.value = true
if (currentPage.value > Math.max(1, Math.ceil(configs.value.length / pageSize.value))) currentPage.value = 1
} catch (error) {
if (generation === configLoadGeneration && props.canView) loadError.value = errorText(error)
}
}
}
watch(() => props.canView, value => {
if (value && !loaded.value) void loadConfigs()
else if (!value) { configLoadGeneration += 1; configRefreshQueued = false }
}, { immediate: true })
function openCreate() { if (!props.canCreate) return; runContext += 1; editingId.value = null; draft.value = emptyDraft(); resetResults(); dialogVisible.value = true }
async function openEdit(id: KingdeeSyncConfigId) {
if (!props.canView) return
const context = ++runContext
editingId.value = id; draft.value = emptyDraft(); resetResults(); dialogVisible.value = true; detailLoading.value = true
try {
const config = await adminApi.getKingdeeSyncConfig(id)
if (!isCurrentRunContext(id, context)) return
draft.value = normalizeDraft(config)
await loadRuns(id, context)
} catch (error) { if (isCurrentRunContext(id, context)) detailError.value = errorText(error) }
finally { if (isCurrentRunContext(id, context)) detailLoading.value = false }
}
async function deleteConfig(config: KingdeeSyncConfig) {
if (!props.canDelete) return
try { await ElMessageBox.confirm(`确定删除同步规则“${config.configName}”吗?`, '删除确认', { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }) }
catch { return }
try { await adminApi.deleteKingdeeSyncConfig(config.id); ElMessage.success('同步规则已删除'); await loadConfigs() }
catch (error) { ElMessage.error(`删除失败:${errorText(error)}`) }
}
function addField() { if (canManage.value) draft.value.fields.push(emptyField()) }
function removeField(index: number) { if (canManage.value && draft.value.fields.length > 1) draft.value.fields.splice(index, 1) }
function onDataTypeChange(field: DraftField) { if (field.dataType !== 'STRING') field.fieldLength = null }
function addFilter() { if (canManage.value) draft.value.filters.push(emptyFilter()) }
function removeFilter(index: number) { if (canManage.value) draft.value.filters.splice(index, 1) }
function fieldError(field: string) {
if (!validationError.value) return ''
if (field === 'fields' && validationError.value.includes('字段')) return validationError.value
if (field === 'configName' && validationError.value.includes('单据名称')) return validationError.value
if (field === 'formId' && validationError.value.includes('formId')) return validationError.value
if (field === 'targetTableName' && validationError.value.includes('数据库表名')) return validationError.value
if (field === 'maxRowsPerRun' && validationError.value.includes('最大同步行数')) return validationError.value
return ''
}
function validateDraft() {
const value = draft.value
if (!value.configName.trim()) validationError.value = '请填写单据名称。'
else if (!value.formId.trim()) validationError.value = '请填写金蝶单据标识(formId)。'
else if (!value.targetTableName.trim()) validationError.value = '请填写数据库表名。'
else if (!Number.isInteger(value.maxRowsPerRun) || value.maxRowsPerRun < 1 || value.maxRowsPerRun > 100000) validationError.value = '最大同步行数必须是1到100000之间的整数。'
else if (!value.fields.length) validationError.value = '至少配置一条字段映射。'
else if (value.fields.some(field => !field.sourceFieldKey.trim() || !field.targetColumnName.trim())) validationError.value = '请填写每条字段映射的源字段标识和数据库字段名。'
else if (!value.fields.some(field => field.sourceFieldKey.trim().toLowerCase() === 'fbillno')) validationError.value = '字段映射必须包含 FBillNo 作为不可变来源主键。'
else if (value.fields.some(field => !dataTypes.includes(field.dataType))) validationError.value = '字段类型不在允许范围内。'
else if (value.filters.some(filter => !filter.sourceFieldKey.trim() || !filter.filterValue.trim())) validationError.value = '请完整填写过滤条件的源字段标识和过滤值。'
else if (value.filters.some(filter => !operators.some(item => item.value === filter.operator))) validationError.value = '过滤条件操作符不在允许范围内。'
else validationError.value = ''
return !validationError.value
}
function buildPayload(): KingdeeSyncConfigPayload {
return {
configName: draft.value.configName.trim(), formId: draft.value.formId.trim(), targetTableName: draft.value.targetTableName.trim(), targetTableComment: draft.value.targetTableComment.trim(), enabled: draft.value.enabled, maxRowsPerRun: draft.value.maxRowsPerRun,
fields: draft.value.fields.map((field, index) => ({ sourceFieldKey: field.sourceFieldKey.trim(), targetColumnName: field.targetColumnName.trim(), fieldComment: field.fieldComment.trim(), dataType: field.dataType, fieldLength: field.fieldLength === null ? null : Number(field.fieldLength), sortOrder: index })),
filters: draft.value.filters.map((filter, index) => ({ sourceFieldKey: filter.sourceFieldKey.trim(), operator: filter.operator, filterValue: filter.filterValue.trim(), sortOrder: index })),
}
}
async function saveConfig() {
if (!canManage.value || actionLoading.value || !validateDraft()) return
const id = editingId.value
const context = runContext
let currentId = id
const payload = buildPayload()
actionLoading.value = 'save'
try {
const result = id === null ? await adminApi.createKingdeeSyncConfig(payload) : await adminApi.updateKingdeeSyncConfig(id, payload)
if (!isCurrentActionContext(id, context)) return
currentId = result.id
editingId.value = result.id; draft.value = normalizeDraft(result); ElMessage.success('同步规则已保存'); await loadConfigs()
} catch (error) {
if (isCurrentActionContext(id, context)) ElMessage.error(`保存失败:${errorText(error)}`)
} finally {
if (isCurrentActionContext(currentId, context)) actionLoading.value = ''
}
}
async function prepareTable() {
if (!props.canPrepare || editingId.value === null || actionLoading.value) return
const id = editingId.value
const context = runContext
actionLoading.value = 'prepare'; prepareResult.value = null
try {
const result = await adminApi.prepareKingdeeSyncTable(id)
if (!isCurrentActionContext(id, context)) return
prepareResult.value = result || { success: true, message: '目标表已创建或校验通过' }
ElMessage.success(prepareResult.value.message || '目标表已创建或校验通过')
} catch (error) {
if (!isCurrentActionContext(id, context)) return
prepareResult.value = { success: false, message: errorText(error) }; ElMessage.error(`目标表处理失败:${errorText(error)}`)
} finally { if (isCurrentActionContext(id, context)) actionLoading.value = '' }
}
async function previewData() {
if (!props.canPreview || editingId.value === null || actionLoading.value) return
const id = editingId.value
const context = runContext
actionLoading.value = 'preview'; previewResult.value = null
try {
const result = await adminApi.previewKingdeeSyncConfig(id)
if (!isCurrentActionContext(id, context)) return
previewResult.value = result; ElMessage.success('数据预览已完成')
} catch (error) {
if (isCurrentActionContext(id, context)) ElMessage.error(`预览失败:${errorText(error)}`)
} finally { if (isCurrentActionContext(id, context)) actionLoading.value = '' }
}
async function syncNow() {
if (syncDisabled.value || editingId.value === null) return
const id = editingId.value
const context = runContext
const baseline = new Set(runs.value.map(run => String(run.id)))
actionLoading.value = 'sync'; pollingTimedOut.value = false; runNotice.value = ''; runNoticeDanger.value = false
try {
const submittedRun = await adminApi.syncKingdeeConfig(id)
if (!isCurrentRunContext(id, context)) return
latestRun.value = submittedRun
runs.value = [submittedRun, ...runs.value.filter(run => String(run.id) !== String(submittedRun.id))]
if (submittedRun.status === 'RUNNING') {
runNotice.value = '同步任务已提交,正在后台运行。'
beginPolling(id, submittedRun.id, context, baseline)
} else {
finishRun(submittedRun)
}
} catch {
if (!isCurrentRunContext(id, context)) return
// A client timeout does not prove that the server rejected the task. Keep
// submission disabled while run history is used to reconcile the outcome.
syncUncertain.value = true
runNotice.value = '同步请求结果未确认,正在查询服务器运行状态,请勿重复提交。'
ElMessage.warning('同步请求结果未确认,正在查询运行状态')
const history = await fetchRuns(id, context)
if (!history || !isCurrentRunContext(id, context)) return
const running = history.find(run => run.status === 'RUNNING')
if (running) beginPolling(id, running.id, context, baseline)
else beginPolling(id, null, context, baseline)
} finally { if (isCurrentRunContext(id, context)) actionLoading.value = '' }
}
function isCurrentRunContext(id: KingdeeSyncConfigId, context: number) {
return isCurrentActionContext(id, context)
}
function isCurrentActionContext(id: KingdeeSyncConfigId | null, context: number) {
return dialogVisible.value && context === runContext && (id === null ? editingId.value === null : String(editingId.value) === String(id))
}
async function fetchRuns(id: KingdeeSyncConfigId, context: number) {
runLoading.value = true
try {
const result = await adminApi.listKingdeeSyncRuns(id)
if (!isCurrentRunContext(id, context)) return null
runs.value = Array.isArray(result) ? result : []
latestRun.value = runs.value[0] || null
return runs.value
} catch {
if (isCurrentRunContext(id, context)) runNotice.value = '暂时无法查询运行状态,将自动重试。'
return null
} finally { if (isCurrentRunContext(id, context)) runLoading.value = false }
}
async function loadRuns(id: KingdeeSyncConfigId, context = runContext) {
const history = await fetchRuns(id, context)
if (!history || !isCurrentRunContext(id, context)) return
const running = history.find(run => run.status === 'RUNNING')
if (running) {
runNotice.value = '检测到正在运行的同步任务,正在查询状态。'
beginPolling(id, running.id, context, new Set(history.map(run => String(run.id))))
} else {
syncUncertain.value = false
}
}
function beginPolling(id: KingdeeSyncConfigId, runId: KingdeeSyncConfigId | null, context: number, baseline: Set<string>) {
stopRunTracking()
pollingRunId.value = runId
pollingBaseline = baseline
pollStartedAt = Date.now()
pollDeadline = pollStartedAt + POLL_TIMEOUT_MS
syncUncertain.value = syncUncertain.value || runId === null
schedulePoll(id, context)
}
function schedulePoll(id: KingdeeSyncConfigId, context: number) {
if (!isCurrentRunContext(id, context)) return
const remaining = pollDeadline - Date.now()
if (remaining <= 0) { handlePollingTimeout(); return }
const interval = Date.now() - pollStartedAt >= POLL_BACKOFF_AFTER_MS ? POLL_SLOW_INTERVAL_MS : POLL_FAST_INTERVAL_MS
pollTimer = setTimeout(() => void pollRuns(id, context), Math.min(interval, remaining))
}
async function pollRuns(id: KingdeeSyncConfigId, context: number) {
pollTimer = undefined
if (!isCurrentRunContext(id, context)) return
if (Date.now() >= pollDeadline) { handlePollingTimeout(); return }
const history = await fetchRuns(id, context)
if (!isCurrentRunContext(id, context)) return
if (history) {
let tracked = pollingRunId.value === null ? undefined : history.find(run => String(run.id) === String(pollingRunId.value))
if (!tracked && pollingRunId.value === null) tracked = history.find(run => run.status === 'RUNNING') || history.find(run => !pollingBaseline.has(String(run.id)))
if (tracked?.status === 'RUNNING') {
pollingRunId.value = tracked.id; syncUncertain.value = false; runNotice.value = '同步任务正在后台运行。'
} else if (tracked && terminalStatuses.has(tracked.status)) {
latestRun.value = tracked; stopRunTracking(); syncUncertain.value = false; finishRun(tracked); return
}
}
schedulePoll(id, context)
}
function finishRun(run: KingdeeSyncRun) {
if (run.status === 'SUCCEEDED') { runNotice.value = '同步任务已成功完成。'; runNoticeDanger.value = false; ElMessage.success('同步任务已完成') }
else if (run.status === 'PARTIAL') { runNotice.value = `同步任务部分完成${run.errorMessage ? `:${run.errorMessage}` : '。'}`; runNoticeDanger.value = true; ElMessage.warning('同步任务部分完成') }
else if (run.status === 'FAILED') { runNotice.value = `同步任务失败${run.errorMessage ? `:${run.errorMessage}` : '。'}`; runNoticeDanger.value = true; ElMessage.error('同步任务失败') }
}
function handlePollingTimeout() {
stopRunTracking(); pollingTimedOut.value = true
runNotice.value = '运行状态查询已超时;这不代表同步任务失败,请刷新状态确认结果。'
runNoticeDanger.value = false
}
async function refreshRunStatus() {
if (editingId.value === null || runLoading.value) return
const id = editingId.value; const context = runContext
pollingTimedOut.value = false; runNotice.value = ''
const history = await fetchRuns(id, context)
if (!history || !isCurrentRunContext(id, context)) return
const running = history.find(run => run.status === 'RUNNING')
syncUncertain.value = false
if (running) { runNotice.value = '同步任务正在后台运行。'; beginPolling(id, running.id, context, new Set(history.map(run => String(run.id)))) }
else if (history[0] && terminalStatuses.has(history[0].status)) finishRun(history[0])
}
watch(dialogVisible, visible => {
if (!visible) { runContext += 1; stopRunTracking(); actionLoading.value = ''; syncUncertain.value = false }
})
onBeforeUnmount(() => { runContext += 1; stopRunTracking(); desktopDragMedia.removeEventListener('change', updateDesktopDialogDrag);window.removeEventListener('resize', resetKingdeeDialogPosition) })
function formatCell(value: unknown) { return typeof value === 'object' && value !== null ? JSON.stringify(value) : String(value ?? '') }
function formatDate(value: unknown) { const date = new Date(typeof value === 'string' || typeof value === 'number' ? value : ''); return Number.isFinite(date.getTime()) ? date.toLocaleString() : '—' }
function errorText(error: unknown) { return error instanceof Error && error.message ? error.message : '请求失败,请稍后重试。' }
</script>
<style scoped>
.sync-panel { min-width: 0; margin: 18px 0 4px; padding: 16px 0 0; border-top: 1px solid var(--line); }
.sync-head { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 0 0 14px; }
.sync-head > div { min-width: 0; flex: 1 1 320px; }
.sync-head h3 { margin-top: 2px; font-size: 16px; }
.sync-head p { margin-top: 4px; color: var(--muted); font-size: 12px; overflow-wrap: anywhere; }
.sync-empty, .sync-loading { display: flex; min-height: 78px; align-items: center; justify-content: center; gap: 8px; padding: 18px; color: var(--muted); text-align: center; }
.sync-empty { flex-direction: column; border: 1px dashed var(--line-strong); border-radius: var(--radius); }
.sync-empty strong { color: var(--body); }
.sync-alert { margin: 0 0 12px; }
.table-scroll { width: 100%; overflow-x: auto; }
.table-scroll :deep(.el-table) { min-width: 720px; }
.row-actions { display: flex; align-items: center; gap: 2px; white-space: nowrap; }
.dialog-content { min-width: 0; padding: 0 1px 2px; }
.sync-form-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0 14px; }
.mapping-list, .filter-list { display: grid; gap: 10px; }
.mapping-row { display: grid; grid-template-columns: minmax(130px, 1.2fr) minmax(130px, 1.2fr) minmax(120px, 1fr) minmax(125px, .8fr) minmax(100px, .7fr) auto; align-items: start; gap: 8px; padding: 12px; border: 1px solid var(--line); border-radius: 6px; background: #fafbfd; }
.filter-row { display: grid; grid-template-columns: minmax(160px, 1fr) minmax(150px, .8fr) minmax(180px, 1.3fr) auto; align-items: start; gap: 8px; padding: 12px; border: 1px solid var(--line); border-radius: 6px; background: #fafbfd; }
.mapping-row :deep(.el-form-item), .filter-row :deep(.el-form-item) { margin-bottom: 0; }
.remove-row { margin-top: 30px; }
.subsection-head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px; margin: 16px 0 10px; padding-top: 15px; border-top: 1px solid var(--line); }
.subsection-head h4, .result-title h4 { color: var(--text); font-size: 13px; }
.subsection-head p, .result-meta { color: var(--muted); font-size: 11px; }
.filter-head { margin-top: 8px; }
.filter-empty { padding: 10px; border: 1px dashed var(--line-strong); border-radius: var(--radius); }
.form-error { margin-bottom: 12px; color: var(--danger); font-size: 12px; }
.compact-error { margin-top: -2px; }
.detail-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 18px; padding: 14px; border: 1px solid #cdddea; border-radius: 6px; background: #f4f8fc; }
.result-note { margin-top: 12px; padding: 8px 10px; border-radius: 5px; font-size: 12px; }
.result-success { color: var(--success); background: var(--success-soft); }
.result-danger { color: var(--danger); background: var(--danger-soft); }
.result-pending { display: flex; align-items: center; justify-content: space-between; gap: 8px; color: var(--body); background: var(--surface-raised); border: 1px solid var(--line); }
.result-section { margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--line); }
.result-title { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
.result-meta { margin-bottom: 8px; overflow-wrap: anywhere; }
.preview-table :deep(.el-table), .run-table :deep(.el-table) { min-width: 520px; }
.run-summary { display: flex; flex-wrap: wrap; gap: 8px 18px; margin: 8px 0; color: var(--body); font: 12px var(--mono); }
.run-error { flex-basis: 100%; color: var(--danger); overflow-wrap: anywhere; }
@media (max-width: 860px) { .sync-form-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } .mapping-row { grid-template-columns: repeat(2, minmax(0, 1fr)); } .filter-row { grid-template-columns: repeat(2, minmax(0, 1fr)); } .remove-row { margin-top: 0; justify-self: start; } }
@media (max-width: 560px) { .sync-form-grid { grid-template-columns: 1fr; } .mapping-row, .filter-row { grid-template-columns: 1fr; padding: 10px; } .detail-actions { align-items: stretch; flex-direction: column; } .detail-actions :deep(.el-button) { width: 100%; min-height: 44px; margin-left: 0; } }
</style>
+623 -32
View File
@@ -1,50 +1,641 @@
<template>
<div>
<div class="page-head"><div><span class="eyebrow">{{ id ? 'EDIT DRAFT' : 'NEW REIMBURSEMENT' }}</span><h1>{{ id && existing?.approvalStatus === '退回' ? '补充退回报销' : id ? '编辑报销草稿' : '发起员工报销' }}</h1><p>{{ id ? '沿用原报销单号,补充材料后重新提交。' : '填写个人垫付费用,提交前检查发票、附件与金额。' }}</p></div><router-link class="btn" to="/applications">取消</router-link></div>
<div v-if="loadError" class="inline-alert danger" role="alert"><b>!</b><span>{{ loadError }}</span></div>
<div class="application-form">
<div class="page-head">
<div>
<span class="eyebrow">{{ id ? 'EDIT DRAFT' : 'NEW REIMBURSEMENT' }}</span>
<h1>{{ id && existing?.approvalStatus === '退回' ? '补充退回报销' : id ? '编辑报销草稿' : '发起员工报销' }}</h1>
<p>{{ id ? '沿用原报销单号,核对表单内容后重新提交。' : '按当前审批模板填写个人垫付费用。' }}</p>
</div>
<router-link class="btn" to="/applications">取消</router-link>
</div>
<div v-if="loadError && !definitionError" class="inline-alert danger" role="alert"><b>!</b><span>{{ loadError }}</span></div>
<div v-if="!loading && attachmentIntegrityError" class="inline-alert danger" role="alert"><b>!</b><span>{{ attachmentIntegrityError }}</span></div>
<div v-if="staleDefinition" class="inline-alert danger conflict-alert" role="alert"><b>409</b><span><strong>审批模板已更新,当前内容不能保存或提交</strong><br>当前页面仍保留原模板及全部输入。升级前不会删除或改写任何值。</span><button v-if="definition?.mode === 'FEISHU'" class="btn small" type="button" :disabled="migratingDefinition" :aria-busy="migratingDefinition" @click="migrateStaleDefinition">{{ migratingDefinition ? '正在读取最新模板…' : '升级到最新模板并核对' }}</button></div>
<div v-if="migrationNotice" class="inline-alert migration-alert" role="status"><b>↑</b><span><strong>草稿已升级到当前飞书审批模板</strong><br>{{ migrationNotice }}</span></div>
<div class="step-rail"><div class="step done"><span>1</span><strong>填写报销</strong></div><div class="step active"><span>2</span><strong>材料校验</strong></div><div class="step"><span>3</span><strong>飞书审批</strong></div><div class="step"><span>4</span><strong>财务付款</strong></div></div>
<form v-if="!loading" class="form-page" @submit.prevent="save(true)">
<section class="section-card"><div class="section-title"><h2>1. 报销信息</h2><span>员工报销 · * 为必填项</span></div><div class="form-grid">
<div class="field"><label for="title">报销事项 <em>*</em></label><input id="title" v-model.trim="form.title" required maxlength="100" placeholder="例如:上海客户现场技术交流差旅"></div>
<div class="field"><label for="category">费用类型 <em>*</em></label><select id="category" v-model="form.category" required><option v-for="type in expenseTypes" :key="type.id" :value="type.label">{{ type.label }}</option></select></div>
<div v-if="showField('application:amount')" class="field"><label for="amount">报销金额(元) <em v-if="editableField('application:amount')">*</em></label><input id="amount" v-model.number="form.totalAmount" type="number" min="0.01" step="0.01" :readonly="readonlyField('application:amount')" :required="editableField('application:amount')" :aria-describedby="readonlyField('application:amount') ? 'amount-permission-help' : undefined"><small v-if="readonlyField('application:amount')" id="amount-permission-help" class="form-help">当前字段只读</small></div>
<div class="field"><label>报销人 / 部门</label><input readonly :value="`${userName} · ${department}`"></div>
<div v-if="showField('application:payeeName')" class="field"><label for="payee">收款人 <em v-if="editableField('application:payeeName')">*</em></label><input id="payee" v-model.trim="form.payeeName" :readonly="readonlyField('application:payeeName')" maxlength="100" :required="editableField('application:payeeName')"><small v-if="readonlyField('application:payeeName')" class="form-help">当前字段只读</small></div>
<div v-if="showField('application:bankAccount')" class="field"><label for="bank">收款账户 ID <em v-if="editableField('application:bankAccount')">*</em></label><input id="bank" v-model.number="form.payeeBankId" type="number" min="1" step="1" :readonly="readonlyField('application:bankAccount')" :required="editableField('application:bankAccount')"><small class="form-help">{{ readonlyField('application:bankAccount') ? '当前字段只读;账户信息不会明文展示。' : '后端当前按账户 ID 关联,详情页只显示脱敏账号。' }}</small></div>
<div class="field full"><label for="description">费用说明 <em>*</em></label><textarea id="description" v-model.trim="form.description" required maxlength="500" rows="3"></textarea></div>
</div></section>
<section class="section-card section-gap"><div class="section-title"><h2>2. 费用明细</h2><button class="btn small" type="button" @click="addItem">+ 添加明细</button></div><div class="expense-items"><div v-for="(item, index) in form.items" :key="item.key" class="expense-item"><div class="field"><label :for="`expense-date-${item.key}`">日期 <em>*</em></label><input :id="`expense-date-${item.key}`" v-model="item.expenseDate" type="date" required></div><div class="field"><label :for="`expense-category-${item.key}`">类别 <em>*</em></label><input :id="`expense-category-${item.key}`" v-model.trim="item.category" required maxlength="50"></div><div class="field"><label :for="`expense-amount-${item.key}`">金额 <em>*</em></label><input :id="`expense-amount-${item.key}`" v-model.number="item.amount" type="number" min="0.01" step="0.01" required></div><div class="field"><label :for="`expense-description-${item.key}`">说明 <em>*</em></label><input :id="`expense-description-${item.key}`" v-model.trim="item.description" required maxlength="200"></div><button v-if="form.items.length > 1" class="remove-item" type="button" :aria-label="`删除第 ${index + 1} 条费用明细`" @click="removeItem(index)">删除</button></div></div><div class="amount-summary" :class="{ 'amount-mismatch': form.totalAmount > 0 && !amountMatches }"><span>明细合计</span><strong>{{ money(itemsTotal) }}</strong><span>申请金额 {{ money(form.totalAmount) }}</span></div></section>
<section class="section-card section-gap"><div class="section-title"><h2>3. 发票与附件</h2><span>至少一份材料后可提交</span></div><div class="form-grid"><div class="field"><label for="invoice-no">发票号码</label><input id="invoice-no" v-model.trim="invoiceNumber" maxlength="80"></div><div class="field"><label for="invoice-amount">发票金额</label><input id="invoice-amount" v-model.number="invoiceAmount" type="number" min="0" step="0.01"></div><div class="field"><label for="invoice-file">发票影像</label><input id="invoice-file" type="file" accept="image/*,.pdf" @change="selectFile($event, 'invoice')"><small class="form-help">{{ invoiceFile || '尚未选择文件' }}</small></div><div class="field"><label for="attachment-file">其他附件</label><input id="attachment-file" type="file" multiple @change="selectFile($event, 'attachment')"><small class="form-help">{{ attachmentFiles || '尚未选择文件' }}</small></div></div></section>
<div class="form-actions"><button class="btn" type="button" :disabled="saving" @click="save(false)">保存草稿</button><button class="btn primary" type="submit" :disabled="saving" :aria-busy="saving">{{ saving ? '保存中…' : '提交报销' }}</button></div>
</form><div v-else class="card load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在读取报销信息…</span></div>
<div v-if="loading" class="card load-wrap" role="status" aria-live="polite"><span class="loader" aria-hidden="true"></span><span>正在读取飞书报销模板…</span></div>
<div v-else-if="definitionError" class="card definition-state" role="alert"><strong>模板暂时无法加载</strong><span>{{ definitionError }}</span><div><button class="btn" type="button" @click="loadPage">重新检查</button><router-link class="btn" to="/applications">返回我的报销</router-link></div></div>
<form v-else class="form-page" @submit.prevent="save(true)">
<div v-if="isFeishu" class="definition-bar" aria-label="飞书表单模板信息"><strong>飞书审批表单</strong><span>版本 {{ shortFingerprint }}</span><span v-if="definition?.fetchedAt">同步于 {{ formatDateTime(definition.fetchedAt) }}</span></div>
<section v-if="isFeishu" class="section-card" aria-labelledby="feishu-form-title">
<div class="section-title"><h2 id="feishu-form-title">飞书审批信息</h2><span>按模板顺序 · * 为必填项</span></div>
<FeishuFormFields :fields="activeFields" :form-values="formValues" :form="form" :derived="derivedValues" :show-errors="showValidationErrors" :items-total="itemsTotal" :amount-matches="amountMatches" :expense-types="expenseTypes" :form-fingerprint="pinnedFingerprint" @add-item="addItem" @remove-item="removeItem" @upload-state-change="attachmentRevision++" />
</section>
<section v-if="hasSupplementFields" class="section-card" :class="{ 'section-gap': isFeishu }" aria-labelledby="finance-supplement-title">
<div class="section-title"><h2 id="finance-supplement-title">财务补充信息</h2><span>审批与付款必需 · * 为必填项</span></div>
<div class="form-grid">
<div v-if="missingBinding('TITLE')" class="field"><label for="title">报销事项 <em>*</em></label><input id="title" v-model.trim="form.title" required maxlength="100"></div>
<div v-if="missingBinding('EXPENSE_TYPE')" class="field"><label for="expense-type">费用类型 <em>*</em></label><select id="expense-type" v-model.number="form.expenseTypeId" required @change="syncExpenseType"><option value="" disabled>请选择</option><option v-for="type in expenseTypes" :key="type.id" :value="type.id">{{ type.name }}</option></select></div>
<div v-if="missingBinding('TOTAL_AMOUNT') && showField('application:amount')" class="field"><label for="amount">报销金额(元) <em>*</em></label><input id="amount" v-model.number="form.totalAmount" type="number" min="0.01" step="0.01" :readonly="readonlyField('application:amount')" required><small v-if="readonlyField('application:amount')" class="form-help">当前字段只读</small></div>
<div v-if="missingBinding('DESCRIPTION')" class="field full"><label for="description">费用说明 <em>*</em></label><textarea id="description" v-model.trim="form.description" required maxlength="500" rows="3"></textarea></div>
<div v-if="showField('application:payeeName')" class="field"><label for="payee">收款人 <em>*</em></label><input id="payee" v-model.trim="form.payeeName" :readonly="readonlyField('application:payeeName')" maxlength="100" required><small v-if="readonlyField('application:payeeName')" class="form-help">当前字段只读</small></div>
<div v-if="showField('application:bankAccount')" class="field"><label for="bank">收款账户 ID <em>*</em></label><input id="bank" v-model.number="form.payeeBankId" type="number" min="1" step="1" :readonly="readonlyField('application:bankAccount')" required><small class="form-help">{{ readonlyField('application:bankAccount') ? '当前字段只读;账户信息不会明文展示。' : '后端按账户 ID 关联,详情页只显示脱敏账号。' }}</small></div>
</div>
</section>
<section v-if="missingBinding('EXPENSE_ITEMS')" class="section-card section-gap" aria-labelledby="expense-items-title">
<div class="section-title"><h2 id="expense-items-title">费用明细</h2><button class="btn small" type="button" @click="addItem">+ 添加明细</button></div>
<div class="expense-items">
<div v-for="(item, index) in form.items" :key="item.key" class="expense-item">
<div class="field"><label :for="`expense-date-${item.key}`">日期 <em>*</em></label><input :id="`expense-date-${item.key}`" v-model="item.expenseDate" type="date" required></div>
<div class="field"><label :for="`expense-category-${item.key}`">类别 <em>*</em></label><input :id="`expense-category-${item.key}`" v-model.trim="item.category" required maxlength="50"></div>
<div class="field">
<label :for="`expense-amount-${item.key}`">金额 <em>*</em></label>
<input
:id="`expense-amount-${item.key}`"
:value="localAmountText(item)"
type="text"
inputmode="decimal"
autocomplete="off"
placeholder="0.00"
required
:aria-invalid="showValidationErrors && Boolean(itemAmountError(item))"
@input="setLocalItemAmount(item, $event)"
@blur="normalizeLocalItemAmount(item)"
>
<small v-if="showValidationErrors && itemAmountError(item)" class="field-error" role="alert">! {{ itemAmountError(item) }}</small>
<small v-else class="form-help">请填写大于 0 的金额,最多两位小数,上限 99,999,999.99 元</small>
</div>
<div class="field"><label :for="`expense-description-${item.key}`">说明 <em>*</em></label><input :id="`expense-description-${item.key}`" v-model.trim="item.description" required maxlength="200"></div>
<button v-if="form.items.length > 1" class="remove-item" type="button" :aria-label="`删除第 ${index + 1} 条费用明细`" @click="removeItem(index)">删除</button>
</div>
</div>
<div class="amount-summary" :class="{ 'amount-mismatch': form.totalAmount > 0 && !amountMatches }"><span>明细合计</span><strong>{{ money(itemsTotal) }}</strong><span>申请金额 {{ money(form.totalAmount) }}</span></div>
<small v-if="form.totalAmount > 0 && !amountMatches" class="field-error" role="status">明细合计须与申请金额一致,请核对各行金额。</small>
</section>
<div v-if="canWriteApplication" class="form-actions"><button class="btn" type="button" :disabled="saving || staleDefinition || hasAttachmentBlocks" :title="hasAttachmentBlocks ? attachmentBlockMessage : undefined" @click="save(false)">{{ saving ? '保存中…' : '保存草稿' }}</button><button v-if="canSubmit" class="btn primary" type="submit" :disabled="saving || staleDefinition || hasUnsupported || hasAttachmentBlocks" :title="hasAttachmentBlocks ? attachmentBlockMessage : undefined" :aria-busy="saving">{{ saving ? '处理中…' : '提交报销' }}</button></div>
</form>
<dialog ref="previewDialog" v-dialog-drag class="app-dialog route-dialog" aria-modal="true" aria-labelledby="route-dialog-title" aria-describedby="route-dialog-description" @cancel="handleDialogCancel" @click="handleBackdropClick">
<div class="app-dialog__panel route-dialog-panel">
<header class="route-dialog-head" data-dialog-drag-handle>
<div><span class="eyebrow">APPROVAL PREVIEW</span><h2 id="route-dialog-title">确认审批路线</h2><p id="route-dialog-description">以下为预计审批路径,实际审批人可能在提交时由飞书确定。</p></div>
<button class="modal-close" type="button" aria-label="关闭审批路线预览" :disabled="submitting" @click="closePreview">×</button>
</header>
<div class="route-dialog-body">
<dl class="route-summary" aria-label="报销摘要"><div><dt>报销事项</dt><dd>{{ form.title }}</dd></div><div><dt>费用类型</dt><dd>{{ form.category }}</dd></div><div><dt>报销金额</dt><dd>{{ money(form.totalAmount) }}</dd></div></dl>
<div v-if="previewLoading" class="route-state" role="status" aria-live="polite"><span class="loader" aria-hidden="true"></span><span>正在获取预计审批路径…</span></div>
<div v-else-if="previewError" class="route-state route-error" role="alert"><strong>审批路线预览失败</strong><span>{{ previewError }}</span><button ref="retryButton" class="btn small" type="button" :disabled="previewLoading || submitting" @click="requestPreview">重新预览</button></div>
<template v-else-if="preview">
<div class="route-meta"><span class="tag">{{ preview.source === 'FEISHU' ? 'FEISHU · 飞书' : 'LOCAL · 本地流程' }}</span><span>{{ preview.exact ? '按当前配置精确预览' : '提交时可能动态调整' }}</span><span v-if="preview.snapshotFetchedAt">最后同步时间:{{ formatDateTime(preview.snapshotFetchedAt) }}</span></div>
<div v-if="preview.staleSnapshot || preview.warning" class="route-warning" role="status" aria-live="polite"><strong>路线提示</strong><span>{{ preview.warning || '通讯录或审批配置快照可能不是最新状态,请确认后提交。' }}</span></div>
<h3>预计审批路径</h3>
<ol v-if="orderedNodes.length" class="route-list" aria-label="预计审批路径节点">
<li v-for="node in orderedNodes" :key="`${node.order}-${node.nodeKey}`">
<span class="route-order" aria-hidden="true">{{ node.order }}</span>
<div><strong>{{ node.nodeName }}</strong><small v-if="node.nodeType || node.approvalMode">{{ [node.nodeType, node.approvalMode].filter(Boolean).join(' · ') }}</small><ul v-if="node.approverLabels.length" class="approver-list" aria-label="审批人"><li v-for="label in node.approverLabels" :key="label">{{ label }}</li></ul><p v-if="node.dynamic" class="dynamic-approver"><strong>动态审批人</strong><span>提交时由飞书确定</span></p><p v-else-if="!node.approverLabels.length" class="quiet-copy">未提供审批人信息</p></div>
</li>
</ol>
<div v-else class="route-state" role="status"><strong>暂无审批节点</strong><span>当前预览未返回审批节点,请返回修改或重新预览。</span></div>
</template>
</div>
<footer class="route-dialog-actions"><button class="btn" type="button" :disabled="submitting" @click="closePreview">返回修改</button><button v-if="canSubmit" class="btn primary" type="button" :disabled="!preview || previewLoading || submitting || hasAttachmentBlocks" :aria-busy="submitting" @click="confirmSubmit">{{ submitting ? '提交中…' : '确认提交' }}</button></footer>
</div>
</dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { CreateApplicationRequest, ExpenseItem } from '@/api/reimbursement'
import { reimbursementApi, type ApprovalRoutePreview, type CreateApplicationRequest, type ExpenseItem, type ExpenseTypeMetadata, type ReimbursementFormAttachment, type ReimbursementFormDefinition, type ReimbursementFormField } from '@/api/reimbursement'
import FeishuFormFields from '@/components/reimbursement/FeishuFormFields.vue'
import { attachmentIdsMissingMetadata, expenseItemAttachmentMetadata, hydratedAttachmentIds } from '@/modules/reimbursementAttachments'
import { useUserStore } from '@/store/user'
import { useWorkbenchStore } from '@/store/workbench'
import { inspectMoneyAmount, moneyAmountMessage, normalizeMoneyAmount } from '@/utils/moneyAmount'
type FieldLevel = 'HIDDEN' | 'READ' | 'EDIT'
interface FormItem extends ExpenseItem { key: number; description: string }
const route = useRoute(); const router = useRouter(); const userStore = useUserStore(); const store = useWorkbenchStore(); const id = computed(() => route.params.id ? String(route.params.id) : ''); const existing = computed(() => id.value ? store.getById(id.value) : null); const loading = ref(true); const saving = ref(false); const loadError = ref(''); const invoiceNumber = ref(''); const invoiceAmount = ref(0); const invoiceFile = ref(''); const attachmentFiles = ref(''); let nextKey = 1
const userName = computed(() => userStore.userInfo?.realName || store.user?.realName || '用户'); const department = computed(() => userStore.userInfo?.departmentName || store.user?.departmentName || '销售中心'); const expenseTypes = [{ id: 1, label: '差旅交通' }, { id: 2, label: '住宿费' }, { id: 3, label: '业务招待' }, { id: 4, label: '差旅补贴' }, { id: 5, label: '办公费用' }]; const newItem = (value?: Partial<ExpenseItem>): FormItem => ({ key: nextKey++, expenseDate: value?.expenseDate || new Date().toISOString().slice(0, 10), category: value?.category || '', description: value?.description || '', amount: Number(value?.amount || 0), seqNo: value?.seqNo }); const form = reactive({ title: '', category: '差旅交通', totalAmount: 0, description: '', payeeName: '', payeeBankId: undefined as number | undefined, items: [newItem()] })
interface AttachmentEntry extends ReimbursementFormAttachment { localKey: string; status: 'uploaded' | 'pending' | 'failed' | 'deleting'; error?: string }
interface FormItem extends ExpenseItem { key: number; description: string; attachmentFiles: AttachmentEntry[] }
// A missing field entry remains editable for compatibility with older roles.
// Only a successfully loaded field permission can hide or lock a control.
const fieldLevel = (code: string): FieldLevel => { if (!userStore.permissionsLoaded || userStore.permissionsError) return 'EDIT'; return userStore.fieldPermissions[code] || 'EDIT' }; const showField = (code: string) => fieldLevel(code) !== 'HIDDEN'; const readonlyField = (code: string) => fieldLevel(code) === 'READ'; const editableField = (code: string) => fieldLevel(code) === 'EDIT'
const itemsTotal = computed(() => form.items.reduce((sum, item) => sum + (Number(item.amount) || 0), 0)); const amountMatches = computed(() => form.items.length > 0 && form.totalAmount > 0 && Math.abs(itemsTotal.value - form.totalAmount) < 0.005); const hasMaterials = computed(() => Boolean(invoiceNumber.value || invoiceAmount.value > 0 || invoiceFile.value || attachmentFiles.value || existing.value?.invoices.length || existing.value?.attachments.length)); const money = (value: number) => `¥ ${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`
const hydrate = () => { const item = existing.value; if (!item) return; form.title = item.title; form.category = item.category || '差旅交通'; form.totalAmount = item.totalAmount; form.description = item.description; form.payeeName = item.payeeName || userName.value; form.payeeBankId = item.payeeBankId; form.items = item.expenseItems.length ? item.expenseItems.map(newItem) : [newItem({ amount: item.totalAmount, category: item.category, description: item.title })]; invoiceNumber.value = item.invoices[0]?.invoiceNo || ''; invoiceAmount.value = item.invoices[0]?.amount || 0 }
const addItem = () => form.items.push(newItem()); const removeItem = (index: number) => form.items.splice(index, 1); const selectFile = (event: Event, type: 'invoice' | 'attachment') => { const input = event.target as HTMLInputElement; const names = [...(input.files || [])].map(file => file.name).join('、'); if (type === 'invoice') invoiceFile.value = names; else attachmentFiles.value = names }
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const store = useWorkbenchStore()
const id = computed(() => route.params.id ? String(route.params.id) : '')
const existing = computed(() => id.value ? store.getById(id.value) : null)
const loading = ref(true)
const saving = ref(false)
const submitting = ref(false)
const loadError = ref('')
const definitionError = ref('')
const definition = ref<ReimbursementFormDefinition | null>(null)
const expenseTypes = ref<ExpenseTypeMetadata[]>([])
const activeFields = ref<ReimbursementFormField[]>([])
const activeMode = ref<'FEISHU' | 'LOCAL'>('LOCAL')
const pinnedFingerprint = ref<string>()
const formValues = reactive<Record<string, unknown>>({})
const staleDefinition = ref(false)
const migrationNotice = ref('')
const migratingDefinition = ref(false)
const showValidationErrors = ref(false)
const previewDialog = ref<HTMLDialogElement | null>(null)
const retryButton = ref<HTMLButtonElement | null>(null)
const preview = ref<ApprovalRoutePreview | null>(null)
const previewLoading = ref(false)
const previewError = ref('')
const persistedApplicationId = ref<string | number>('')
const attachmentRevision = ref(0)
let previewRequestVersion = 0
let nextKey = 1
const userName = computed(() => userStore.userInfo?.realName || store.user?.realName || '用户')
const department = computed(() => userStore.userInfo?.departmentName || store.user?.departmentName || '—')
const newItem = (value?: Partial<ExpenseItem>, applicationAttachments: Parameters<typeof expenseItemAttachmentMetadata>[1] = []): FormItem => {
const files = expenseItemAttachmentMetadata(value, applicationAttachments)
const attachmentIds = hydratedAttachmentIds(value, files)
return { key: nextKey++, expenseDate: value?.expenseDate || new Date().toISOString().slice(0, 10), category: value?.category || '', description: value?.description || '', amount: Number(value?.amount || 0), seqNo: value?.seqNo, attachmentIds, attachmentFiles: files.map(file => ({ ...file, localKey: `saved-${file.id}`, status: 'uploaded' })) }
}
const form = reactive({ title: '', expenseTypeId: undefined as number | undefined, category: '', totalAmount: 0, description: '', payeeName: '', payeeBankId: undefined as number | undefined, items: [newItem()] })
const canWriteApplication = computed(() => userStore.canEdit(id.value ? 'reimbursement.application.edit' : 'reimbursement.application.create'))
const canSubmit = computed(() => userStore.canEdit('reimbursement.application.submit'))
const fieldLevel = (code: string): FieldLevel => userStore.access(code)
const showField = (code: string) => fieldLevel(code) !== 'HIDDEN'
const readonlyField = (code: string) => fieldLevel(code) === 'READ'
const itemsTotal = computed(() => form.items.reduce((sum, item) => sum + (Number(item.amount) || 0), 0))
const amountMatches = computed(() => form.items.length > 0 && form.totalAmount > 0 && Math.abs(itemsTotal.value - form.totalAmount) < 0.005)
const localAmountDrafts = reactive<Record<number, string>>({})
const localAmountSource = (item: FormItem) => (localAmountDrafts[item.key] != null ? localAmountDrafts[item.key] : (item.amount > 0 ? item.amount : ''))
const localAmountText = (item: FormItem) => (localAmountDrafts[item.key] != null ? localAmountDrafts[item.key] : (item.amount > 0 ? String(item.amount) : ''))
const setLocalItemAmount = (item: FormItem, event: Event) => {
const text = (event.target as HTMLInputElement).value.trimStart()
localAmountDrafts[item.key] = text
const issue = inspectMoneyAmount(text)
if (!issue) item.amount = normalizeMoneyAmount(text)
else if (!text.trim()) item.amount = 0
else {
const parsed = Number(text)
item.amount = Number.isFinite(parsed) && parsed >= 0 ? parsed : 0
}
}
const normalizeLocalItemAmount = (item: FormItem) => {
const text = localAmountDrafts[item.key]
if (text == null) return
if (!inspectMoneyAmount(text)) {
item.amount = normalizeMoneyAmount(text)
delete localAmountDrafts[item.key]
}
}
const itemAmountError = (item: FormItem) => {
const issue = inspectMoneyAmount(localAmountSource(item))
return issue ? moneyAmountMessage(issue, '金额') : ''
}
const orderedNodes = computed(() => [...(preview.value?.nodes || [])].sort((a, b) => a.order - b.order))
const isFeishu = computed(() => activeMode.value === 'FEISHU')
const canonicalWriterTypes: Partial<Record<ReimbursementFormField['binding'], ReimbursementFormField['type'][]>> = {
TITLE: ['TEXT', 'TEXTAREA'], EXPENSE_TYPE: ['SINGLE_SELECT'], TOTAL_AMOUNT: ['DECIMAL'], DESCRIPTION: ['TEXT', 'TEXTAREA'],
}
const expenseChildBindings = new Set<ReimbursementFormField['binding']>(['EXPENSE_DATE', 'EXPENSE_CATEGORY', 'EXPENSE_DESCRIPTION', 'EXPENSE_AMOUNT', 'EXPENSE_ATTACHMENT'])
const compatibleExpenseChild = (child: ReimbursementFormField) => {
if (child.type === 'DISPLAY') return !child.required
if (child.binding === 'EXPENSE_DATE') return child.type === 'DATE'
if (child.binding === 'EXPENSE_CATEGORY') return child.type === 'TEXT' || child.type === 'SINGLE_SELECT'
if (child.binding === 'EXPENSE_DESCRIPTION') return child.type === 'TEXT' || child.type === 'TEXTAREA'
if (child.binding === 'EXPENSE_AMOUNT') return child.type === 'DECIMAL'
if (child.binding === 'EXPENSE_ATTACHMENT') return child.type === 'ATTACHMENT'
return false
}
const validExpenseChild = (child: ReimbursementFormField) => !child.readOnly && child.type !== 'DISPLAY' && compatibleExpenseChild(child)
const writableCanonicalField = (field: ReimbursementFormField) => {
if (field.binding === 'TOTAL_AMOUNT' && field.type === 'FORMULA') return true
if (field.readOnly || field.type === 'DISPLAY') return false
if (field.binding === 'EXPENSE_ITEMS') return field.type === 'EXPENSE_ITEMS'
&& ['EXPENSE_DATE', 'EXPENSE_DESCRIPTION', 'EXPENSE_AMOUNT'].every(binding => field.children.some(child => child.binding === binding && validExpenseChild(child)))
return Boolean(canonicalWriterTypes[field.binding]?.includes(field.type))
}
const renderedBindings = computed(() => new Set(activeFields.value.filter(writableCanonicalField).map(field => field.binding)))
const rowReasonCaptured = computed(() => activeFields.value.some(field => field.type === 'EXPENSE_ITEMS' && field.binding === 'EXPENSE_ITEMS' && field.children.some(child => child.binding === 'EXPENSE_DESCRIPTION' && validExpenseChild(child))))
const missingBinding = (binding: string) => !isFeishu.value || (!(['TITLE', 'DESCRIPTION'].includes(binding) && rowReasonCaptured.value) && !renderedBindings.value.has(binding as ReimbursementFormField['binding']))
const hasSupplementFields = computed(() => ['TITLE', 'EXPENSE_TYPE', 'TOTAL_AMOUNT', 'DESCRIPTION'].some(missingBinding) || showField('application:payeeName') || showField('application:bankAccount'))
const shortFingerprint = computed(() => pinnedFingerprint.value?.slice(0, 8) || '未知')
const hasUnsupported = computed(() => activeFields.value.some(field => {
if (field.type === 'CONTACT') return field.binding !== 'APPLICANT_CONTACT'
if (field.type === 'DEPARTMENT' || field.binding === 'APPLICANT_DEPARTMENT') return field.type !== 'DEPARTMENT' || field.binding !== 'APPLICANT_DEPARTMENT'
if (!['TEXT', 'TEXTAREA', 'DECIMAL', 'DATE', 'SINGLE_SELECT', 'MULTI_SELECT', 'DISPLAY', 'EXPENSE_ITEMS', 'FORMULA'].includes(field.type)) return true
if (field.type !== 'EXPENSE_ITEMS' && field.binding !== 'EXPENSE_ITEMS') return false
return field.children.some(child => !(child.type === 'DISPLAY' && !child.required) && (!expenseChildBindings.has(child.binding) || !compatibleExpenseChild(child)))
}))
const attachmentFields = computed(() => activeFields.value.filter(field => field.type === 'EXPENSE_ITEMS' && field.binding === 'EXPENSE_ITEMS').flatMap(field => field.children.filter(child => child.type === 'ATTACHMENT' && child.binding === 'EXPENSE_ATTACHMENT')))
const attachmentRequired = computed(() => attachmentFields.value.some(field => field.required))
const attachmentIntegrityError = computed(() => {
void attachmentRevision.value
const missing = form.items.flatMap(item => attachmentIdsMissingMetadata(item.attachmentIds, item.attachmentFiles))
return missing.length ? `附件信息不完整(ID:${missing.join('、')}),请刷新详情;如仍异常,请联系管理员处理后再保存。` : ''
})
const attachmentBlockMessage = computed(() => attachmentIntegrityError.value || '请先处理正在上传、移除中或失败的附件')
const hasAttachmentBlocks = computed(() => {
void attachmentRevision.value
return Boolean(attachmentIntegrityError.value) || form.items.some(item => item.attachmentFiles.some(file => file.status === 'pending' || file.status === 'failed' || file.status === 'deleting'))
})
const derivedValues = computed<Record<string, string>>(() => ({ APPLICATION_NO: existing.value?.applicationNo || '保存后生成', APPLICANT_NAME: userName.value, APPLICANT_CONTACT: userName.value, APPLICANT_DEPARTMENT: department.value, DEPARTMENT: department.value, REIMBURSEMENT_DATE: existing.value?.createdAt?.slice(0, 10) || new Intl.DateTimeFormat('sv-SE', { timeZone: 'Asia/Shanghai' }).format(new Date()), SOURCE_DOC_NO: existing.value?.sourceDocNo || '—' }))
const money = (value: number) => `¥ ${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`
const formatDateTime = (value: string) => { const date = new Date(value); return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN', { hour12: false }) }
const hydrate = () => {
const item = existing.value
if (!item) { form.payeeName = userName.value; return }
persistedApplicationId.value = item.id
form.title = item.title
form.expenseTypeId = item.expenseTypeId || undefined
form.category = item.expenseTypeName || item.category
form.totalAmount = item.totalAmount
form.description = item.description
form.payeeName = item.payeeName || userName.value
form.payeeBankId = item.payeeBankId || undefined
form.items = item.expenseItems.length ? item.expenseItems.map(expense => newItem(expense, item.attachments)) : [newItem({ amount: item.totalAmount, category: item.category, description: item.title })]
if (item.formSnapshot?.mode === 'FEISHU') {
activeMode.value = 'FEISHU'
pinnedFingerprint.value = item.formSnapshot.fingerprint
activeFields.value = item.formSnapshot.fields || []
Object.assign(formValues, item.formSnapshot.values || {})
activeFields.value.filter(field => field.binding === 'APPLICANT_CONTACT' || field.binding === 'APPLICANT_DEPARTMENT').forEach(field => delete formValues[field.valueKey])
}
}
const localDefinition = (): ReimbursementFormDefinition => ({ mode: 'LOCAL', fields: [] })
/** One short retry — sync may still be flushing the snapshot when the create page opens. */
const loadFormDefinitionWithRetry = async (): Promise<ReimbursementFormDefinition> => {
try {
return await reimbursementApi.getFormDefinition()
} catch (firstError) {
await new Promise(resolve => setTimeout(resolve, 600))
try {
return await reimbursementApi.getFormDefinition()
} catch {
throw firstError
}
}
}
const loadPage = async () => {
loading.value = true
definitionError.value = ''
loadError.value = ''
staleDefinition.value = false
migrationNotice.value = ''
Object.keys(formValues).forEach(key => delete formValues[key])
try {
if (id.value) {
const detail = await store.loadDetail(id.value, { strict: true })
if (store.source === 'api' && !detail?.formSnapshot) throw new Error('报销详情缺少表单快照,无法安全编辑,请刷新或联系管理员。')
if (store.source === 'api' && detail?.formSnapshot && !['FEISHU', 'LOCAL', 'LEGACY'].includes(detail.formSnapshot.mode)) throw new Error('报销详情的表单快照模式无效,无法安全编辑。')
} else if (!store.reimbursements.length) await store.load()
hydrate()
if (id.value && !existing.value) throw new Error('未找到该报销单,无法编辑')
const [definitionResult, expenseTypesResult] = await Promise.allSettled([loadFormDefinitionWithRetry(), reimbursementApi.getExpenseTypes()])
if (expenseTypesResult.status === 'rejected') throw expenseTypesResult.reason
expenseTypes.value = expenseTypesResult.value
if (definitionResult.status === 'fulfilled') definition.value = definitionResult.value
else if (store.source === 'fallback') definition.value = localDefinition()
else throw definitionResult.reason
if (!definition.value || !Array.isArray(definition.value.fields)) throw new Error('审批模板响应格式无效,请联系管理员重新同步')
if (!Array.isArray(expenseTypes.value) || !expenseTypes.value.length) throw new Error('没有可用费用类型,无法填写报销。')
const snapshot = existing.value?.formSnapshot
if (definition.value.mode === 'FEISHU' && (!definition.value.fields.length || !definition.value.formFingerprint)) {
if (!definition.value.fields.length) throw new Error('审批模板没有可用字段,请联系管理员重新同步')
throw new Error('审批模板缺少表单版本,无法安全保存,请联系管理员重新同步')
}
if (!id.value && definition.value.mode === 'FEISHU') {
activeFields.value = definition.value.fields
activeMode.value = 'FEISHU'
pinnedFingerprint.value = definition.value.formFingerprint
} else if (snapshot?.mode === 'FEISHU') {
const currentFingerprint = definition.value.formFingerprint
staleDefinition.value = definition.value.mode !== 'FEISHU' || !snapshot.fingerprint || !currentFingerprint || snapshot.fingerprint !== currentFingerprint
} else if (id.value && (snapshot?.mode === 'LOCAL' || snapshot?.mode === 'LEGACY') && definition.value.mode === 'FEISHU') {
activeFields.value = definition.value.fields
activeMode.value = 'FEISHU'
pinnedFingerprint.value = definition.value.formFingerprint
Object.keys(formValues).forEach(key => delete formValues[key])
migrationNotice.value = '原有报销、付款和费用明细已保留;新模板自定义字段从空值开始,请逐项核对并填写后再保存。'
} else {
activeFields.value = []
activeMode.value = 'LOCAL'
pinnedFingerprint.value = undefined
}
} catch (error) {
definitionError.value = errorMessage(error, '无法读取审批模板,请稍后重试。')
} finally {
loading.value = false
}
}
const addItem = () => form.items.push(newItem({ category: form.category }))
const removeItem = async (index: number) => {
const item = form.items[index]
if (!item || item.attachmentFiles.some(file => file.status === 'pending' || file.status === 'deleting')) return
loadError.value = ''
for (const attachmentId of [...item.attachmentIds]) {
const metadata = item.attachmentFiles.find(file => String(file.id) === String(attachmentId))
if (metadata) {
metadata.status = 'deleting'
metadata.error = undefined
attachmentRevision.value++
}
try {
await reimbursementApi.deleteFormAttachment(attachmentId)
item.attachmentIds = item.attachmentIds.filter(id => String(id) !== String(attachmentId))
item.attachmentFiles = item.attachmentFiles.filter(file => String(file.id) !== String(attachmentId))
attachmentRevision.value++
} catch (error) {
if (metadata) {
metadata.status = 'failed'
metadata.error = errorMessage(error, '附件移除失败,请重试')
}
loadError.value = `附件“${metadata?.fileName || attachmentId}”删除失败;此前已删除的附件不会恢复,本条明细及剩余附件已保留,请重试移除。`
attachmentRevision.value++
return
}
}
form.items.splice(index, 1)
}
const syncExpenseType = () => { const type = expenseTypes.value.find(entry => entry.id === form.expenseTypeId); form.category = type?.category || type?.name || ''; form.items.forEach(item => { item.category = form.category }) }
const permissionBlock = (code: string, label: string, value: unknown) => { const level = fieldLevel(code); const missing = value === undefined || value === null || value === '' || Number(value) === 0; return level !== 'EDIT' && missing ? `当前字段“${label}”为${level === 'HIDDEN' ? '隐藏' : '只读'},但业务接口仍要求该字段,请联系管理员开放字段权限后再提交。` : '' }
const save = async (submit: boolean) => { loadError.value = ''; const hiddenRequired = [permissionBlock('application:amount', '报销金额', form.totalAmount), permissionBlock('application:payeeName', '收款人', form.payeeName), permissionBlock('application:bankAccount', '收款账户', form.payeeBankId)].find(Boolean); if (hiddenRequired) { loadError.value = hiddenRequired; return } if (!form.title || !form.description || !(form.totalAmount > 0) || !form.payeeName || !(form.payeeBankId && form.items.length && amountMatches.value) || form.items.some(item => !item.expenseDate || !item.category || !item.description || !(item.amount > 0))) { loadError.value = '请完善报销信息,并确保费用明细合计等于报销金额'; return } if (submit && !hasMaterials.value) { loadError.value = '提交前请至少添加一份发票或附件材料'; return } saving.value = true; const payload: CreateApplicationRequest = { title: form.title, expenseTypeId: expenseTypes.find(type => type.label === form.category)?.id || 1, category: form.category, totalAmount: Number(form.totalAmount.toFixed(2)), description: form.description, payeeName: form.payeeName, payeeBankId: form.payeeBankId, items: form.items.map((item, index) => ({ seqNo: index + 1, expenseDate: item.expenseDate, category: item.category, description: item.description, amount: Number(item.amount.toFixed(2)) })) }; try { const saved = await store.save(payload, id.value || undefined); if (store.source === 'fallback') { if (invoiceNumber.value || invoiceAmount.value || invoiceFile.value) saved.invoices = [{ id: `${saved.id}-invoice`, invoiceNo: invoiceNumber.value, invoiceType: '发票影像', issueDate: new Date().toISOString().slice(0, 10), amount: invoiceAmount.value, sellerName: '', verifyStatus: '待校验' }]; if (attachmentFiles.value) saved.attachments = attachmentFiles.value.split('、').map((file, index) => ({ id: `${saved.id}-attachment-${index}`, fileName: file, fileType: 'FILE', fileUrl: '' })) } if (submit) await store.submit(saved.id); ElMessage.success(submit ? '报销已提交' : '草稿已保存'); router.replace(`/applications/${saved.id}`) } catch (error) { loadError.value = error instanceof Error ? error.message : '保存失败,请稍后重试'; ElMessage.error(loadError.value) } finally { saving.value = false } }
onMounted(async () => { if (id.value) await store.loadDetail(id.value); else if (!store.reimbursements.length) await store.load(); hydrate(); if (id.value && !existing.value) loadError.value = '未找到该报销单,无法编辑'; loading.value = false })
const errorMessage = (error: unknown, fallback: string) => {
const responseMessage = (error as { response?: { data?: { message?: unknown } } })?.response?.data?.message
if (typeof responseMessage === 'string' && responseMessage.trim()) return responseMessage.trim()
return error instanceof Error && error.message ? error.message : fallback
}
const isConflict = (error: unknown) => (error as { response?: { status?: number } } | null)?.response?.status === 409
const conflictMessage = (error: unknown) => String((error as { response?: { data?: { message?: unknown } } } | null)?.response?.data?.message || '')
const isFormConflict = (error: unknown) => isConflict(error) && /表单|模板|fingerprint/i.test(conflictMessage(error))
const compatibleCustomType = (oldField: ReimbursementFormField, currentField: ReimbursementFormField) => {
if (oldField.type === currentField.type) return true
const textTypes = new Set<ReimbursementFormField['type']>(['TEXT', 'TEXTAREA'])
return textTypes.has(oldField.type) && textTypes.has(currentField.type)
}
const migrateStaleDefinition = async () => {
if (!staleDefinition.value || migratingDefinition.value) return
migratingDefinition.value = true
loadError.value = ''
try {
const latest = await reimbursementApi.getFormDefinition()
if (latest.mode !== 'FEISHU' || !latest.formFingerprint || !Array.isArray(latest.fields) || !latest.fields.length) throw new Error('当前没有可迁移的飞书审批模板,请联系管理员检查同步状态。')
const oldCustomFields = new Map(activeFields.value.filter(field => field.binding === 'CUSTOM').map(field => [field.valueKey, field]))
const previousValues = { ...formValues }
const preserved: Record<string, unknown> = {}
latest.fields.filter(field => field.binding === 'CUSTOM').forEach(field => {
const oldField = oldCustomFields.get(field.valueKey)
if (oldField && compatibleCustomType(oldField, field) && Object.prototype.hasOwnProperty.call(previousValues, field.valueKey)) preserved[field.valueKey] = previousValues[field.valueKey]
})
Object.keys(formValues).forEach(key => delete formValues[key])
Object.assign(formValues, preserved)
definition.value = latest
activeFields.value = latest.fields
activeMode.value = 'FEISHU'
pinnedFingerprint.value = latest.formFingerprint
staleDefinition.value = false
showValidationErrors.value = false
migrationNotice.value = '报销、付款和费用明细保持不变;仅保留了键与类型兼容的自定义值,已移除或类型变化的字段未迁移。请核对全部字段后再手动保存。'
} catch (error) {
loadError.value = errorMessage(error, '无法读取最新审批模板,原模板和值未发生变化。')
} finally {
migratingDefinition.value = false
}
}
const invalidatePreview = (closeDialog = false) => {
previewRequestVersion += 1
preview.value = null
previewError.value = ''
previewLoading.value = false
if (closeDialog && previewDialog.value?.open) previewDialog.value.close()
}
const openPreview = async () => {
if (!previewDialog.value?.open) previewDialog.value?.showModal()
await nextTick()
}
const closePreview = () => {
if (submitting.value) return
invalidatePreview(true)
}
const handleDialogCancel = (event: Event) => {
event.preventDefault()
closePreview()
}
const handleBackdropClick = (event: MouseEvent) => {
if (event.target === previewDialog.value) closePreview()
}
const requestPreview = async () => {
if (previewLoading.value || submitting.value || !persistedApplicationId.value) return
const version = ++previewRequestVersion
preview.value = null
previewError.value = ''
previewLoading.value = true
try {
const result = await store.previewRoute(persistedApplicationId.value)
if (version === previewRequestVersion) preview.value = result
} catch (error) {
if (version === previewRequestVersion) {
if (isFormConflict(error)) {
staleDefinition.value = true
loadError.value = '审批模板已更新(409)。已保留当前输入,请刷新后按最新模板重新核对。'
previewDialog.value?.close()
} else previewError.value = errorMessage(error, '无法获取预计审批路径,请重试。')
}
} finally {
if (version === previewRequestVersion) previewLoading.value = false
}
await nextTick()
if (previewError.value) retryButton.value?.focus()
}
const submittedCustomValues = () => Object.fromEntries(activeFields.value
.filter(field => field.binding === 'CUSTOM' && !field.readOnly && field.type !== 'CONTACT' && field.type !== 'DISPLAY' && field.type !== 'EXPENSE_ITEMS')
.map(field => [field.valueKey, formValues[field.valueKey]]))
const payload = (): CreateApplicationRequest => ({
title: form.title,
expenseTypeId: form.expenseTypeId!,
category: form.category,
totalAmount: Number(form.totalAmount.toFixed(2)),
description: form.description,
payeeName: form.payeeName,
payeeBankId: form.payeeBankId!,
items: form.items.map((item, index) => ({ seqNo: index + 1, expenseDate: item.expenseDate, category: item.category, description: item.description, amount: normalizeMoneyAmount(item.amount), attachmentIds: [...item.attachmentIds] })),
...(isFeishu.value ? { formFingerprint: pinnedFingerprint.value, formValues: submittedCustomValues() } : {}),
})
const validate = () => {
if (staleDefinition.value) return '审批模板已更新,请刷新后重新核对并录入。'
if (hasUnsupported.value) return '审批模板包含当前系统不支持的控件,无法保存或提交,请联系管理员。'
if (attachmentIntegrityError.value) return attachmentIntegrityError.value
if (hasAttachmentBlocks.value) return '请等待附件上传或移除完成,并处理上传失败的文件。'
if (attachmentRequired.value && form.items.some(item => !item.attachmentIds.length)) return '请为每条费用明细上传必填附件。'
const hiddenRequired = [permissionBlock('application:amount', '报销金额', form.totalAmount), permissionBlock('application:payeeName', '收款人', form.payeeName), permissionBlock('application:bankAccount', '收款账户', form.payeeBankId)].find(Boolean)
if (hiddenRequired) return hiddenRequired
const missingCustom = activeFields.value.find(field => field.binding === 'CUSTOM' && field.required && !field.readOnly && (formValues[field.valueKey] == null || formValues[field.valueKey] === '' || (Array.isArray(formValues[field.valueKey]) && !(formValues[field.valueKey] as unknown[]).length)))
if (missingCustom) return `请填写飞书表单必填项“${missingCustom.label}”`
const invalidDecimal = activeFields.value.find(field => field.binding === 'CUSTOM' && field.type === 'DECIMAL' && !field.readOnly && formValues[field.valueKey] != null && formValues[field.valueKey] !== '' && !/^-?\d+(\.\d+)?$/.test(String(formValues[field.valueKey])))
if (invalidDecimal) return `飞书表单字段“${invalidDecimal.label}”须为有效数字`
const badAmountIndex = form.items.findIndex(item => inspectMoneyAmount(localAmountSource(item) || item.amount))
if (badAmountIndex >= 0) {
const item = form.items[badAmountIndex]
const issue = inspectMoneyAmount(localAmountSource(item) || item.amount)!
return `第 ${badAmountIndex + 1} 条费用明细:${moneyAmountMessage(issue, '金额')}`
}
const totalIssue = inspectMoneyAmount(form.totalAmount > 0 ? form.totalAmount : '')
if (totalIssue) return moneyAmountMessage(totalIssue, '申请金额')
if (!form.title || !form.description || !form.expenseTypeId || !form.category || !form.payeeName || !form.payeeBankId || !form.items.length) return '请完善必填信息后再保存'
if (form.items.some(item => !item.expenseDate || !item.category || !item.description)) return '请完善费用明细的日期、类别和说明'
if (!amountMatches.value) return '明细合计须与申请金额一致,请核对各行金额'
return ''
}
const save = async (submit: boolean) => {
if (!canWriteApplication.value || (submit && !canSubmit.value)) return
if (saving.value || submitting.value) return
showValidationErrors.value = true
loadError.value = validate()
if (loadError.value) return
saving.value = true
try {
const isNewDraft = !persistedApplicationId.value
const saved = await store.save(payload(), persistedApplicationId.value || undefined)
persistedApplicationId.value = saved.id
showValidationErrors.value = false
if (!submit) {
ElMessage.success('草稿已保存')
await router.replace(`/applications/${saved.id}`)
return
}
// Persist the edit URL before previewing so reload/close resumes this draft.
// The same form component is reused, and the dialog is opened only after navigation settles.
if (isNewDraft) await router.replace(`/applications/${saved.id}/edit`)
await openPreview()
await requestPreview()
} catch (error) {
if (isConflict(error)) {
staleDefinition.value = true
loadError.value = '审批模板已更新(409)。已保留当前输入,请刷新后按最新模板重新核对。'
} else loadError.value = errorMessage(error, '保存报销草稿失败,请重试。')
ElMessage.error(loadError.value)
} finally {
saving.value = false
}
}
const confirmSubmit = async () => {
if (!canSubmit.value || submitting.value || !preview.value || !persistedApplicationId.value) return
const token = preview.value.previewToken
submitting.value = true
previewError.value = ''
try {
await store.submit(persistedApplicationId.value, token)
ElMessage.success('报销已提交')
previewDialog.value?.close()
await router.replace(`/applications/${persistedApplicationId.value}`)
} catch (error) {
if (isFormConflict(error)) {
staleDefinition.value = true
loadError.value = '审批模板已更新(409)。已保留当前输入,请刷新后按最新模板重新核对。'
previewDialog.value?.close()
} else if (isConflict(error)) {
invalidatePreview(false)
previewError.value = '审批路线已变化或预览已过期,请重新预览后再提交。'
} else {
previewError.value = errorMessage(error, '提交失败,请保留当前页面并重试。')
}
} finally {
submitting.value = false
}
await nextTick()
if (previewError.value) retryButton.value?.focus()
}
watch(() => JSON.stringify({ form, formValues }), () => {
if (preview.value && !submitting.value) invalidatePreview(false)
})
watch([itemsTotal, () => activeFields.value], () => {
if (activeFields.value.some(field => field.binding === 'TOTAL_AMOUNT' && field.type === 'FORMULA')) form.totalAmount = Number(itemsTotal.value.toFixed(2))
}, { deep: true, immediate: true })
watch([rowReasonCaptured, () => form.items.map(item => item.description).join('\u0000')], () => {
if (!rowReasonCaptured.value) return
const reasons = form.items.map(item => item.description.trim()).filter(Boolean)
form.title = (reasons[0] || '').slice(0, 100)
form.description = reasons.join(';').slice(0, 500)
}, { immediate: true })
onMounted(loadPage)
</script>
<style scoped>
.form-actions { display: flex; justify-content: flex-end; gap: 9px; padding: 16px 0; }
@media (max-width: 560px) { .form-actions { flex-direction: column-reverse; } .form-actions .btn { width: 100%; } }
.application-form {
display: flex;
flex-direction: column;
gap: 18px;
}
.application-form :deep(.page-head) { margin-bottom: 0; }
.application-form :deep(.step-rail) { margin: 0; }
.application-form :deep(.inline-alert) { margin: 0; }
.form-page { display: flex; flex-direction: column; gap: 16px; }
.form-page .section-card { margin: 0; }
.form-page .section-gap { margin-top: 0; }
.form-page :deep(.form-grid) {
gap: 16px 20px;
padding: 20px 22px 22px;
}
.form-page :deep(.field) { gap: 8px; }
.definition-bar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 10px 18px;
margin: 0;
padding: 14px 18px;
border: 1px solid #bfd3e8;
border-radius: 8px;
background: var(--blue-soft);
color: var(--blue);
font-size: 12px;
}
.definition-state { display: flex; min-height: 220px; align-items: center; justify-content: center; flex-direction: column; gap: 14px; padding: 36px; text-align: center; }
.definition-state > div { display: flex; gap: 10px; }
.conflict-alert { align-items: center; }
.conflict-alert .btn { flex: 0 0 auto; margin-left: auto; }
.migration-alert { border-color: #b9d7c4; background: var(--success-soft); color: var(--success); }
.form-actions { display: flex; justify-content: flex-end; gap: 12px; padding: 8px 0 4px; }
.route-dialog { width: min(680px, calc(100vw - 32px)); max-width: 100%; max-height: calc(100dvh - 32px); }
.route-dialog-panel { display: flex; min-width: 0; max-height: calc(100dvh - 32px); flex-direction: column; }
.route-dialog-body { min-width: 0; padding: 20px 24px; overflow-x: hidden; overflow-y: auto; }
.route-summary { display: grid; grid-template-columns: minmax(0, 1.5fr) minmax(0, .8fr) minmax(0, .8fr); gap: 1px; margin: 0 0 18px; overflow: hidden; border: 1px solid #d7e0e8; border-radius: 6px; background: var(--line); }
.route-summary div { min-width: 0; padding: 11px 12px; background: var(--surface-raised); }
.route-summary dt { color: var(--quiet); font-size: 10px; }
.route-summary dd { margin: 3px 0 0; overflow-wrap: anywhere; font-size: 12px; font-weight: 600; }
.route-state { display: flex; min-height: 150px; align-items: center; justify-content: center; flex-direction: column; gap: 9px; padding: 22px; border: 1px dashed var(--line-strong); border-radius: 6px; background: var(--surface-raised); color: var(--muted); text-align: center; }
.route-error { border-style: solid; border-color: #e5bfbc; background: var(--danger-soft); color: var(--danger); }
.route-meta { display: flex; align-items: center; flex-wrap: wrap; gap: 9px; margin-bottom: 12px; color: var(--muted); font-size: 11px; }
.route-warning { display: flex; flex-direction: column; gap: 4px; margin: 0 0 16px; padding: 11px 13px; border: 1px solid #f1cf8d; border-radius: 7px; background: #fff9e9; color: #805a16; overflow-wrap: anywhere; font-size: 11px; }
.route-warning small { opacity: .85; }
.route-dialog-body h3 { margin: 0 0 10px; font-size: 13px; }
.route-list { display: flex; margin: 0; padding: 0; flex-direction: column; gap: 9px; list-style: none; }
.route-list > li { position: relative; display: grid; min-width: 0; grid-template-columns: 28px minmax(0, 1fr); gap: 11px; padding: 12px; border: 1px solid var(--line); border-radius: 6px; background: #fff; }
.route-list > li::before { position: absolute; top: 0; bottom: 0; left: 0; width: 3px; background: #bfd3e8; content: ""; }
.route-order { display: grid; width: 28px; height: 28px; place-items: center; border-radius: 50%; background: var(--blue-soft); color: var(--blue); font: 600 11px var(--mono); }
.route-list strong, .route-list small { display: block; overflow-wrap: anywhere; }
.route-list small { margin-top: 3px; color: var(--quiet); font-size: 10px; }
.approver-list { display: flex; flex-wrap: wrap; gap: 5px; margin: 8px 0 0; padding: 0; list-style: none; }
.approver-list li { max-width: 100%; padding: 3px 7px; border-radius: 4px; background: var(--blue-soft); color: var(--blue); overflow-wrap: anywhere; font-size: 10px; }
.dynamic-approver { display: flex; align-items: baseline; flex-wrap: wrap; gap: 6px; margin: 8px 0 0; color: var(--muted); font-size: 11px; }
.dynamic-approver strong { color: var(--body); }
.quiet-copy { margin: 7px 0 0; color: var(--quiet); font-size: 11px; }
.route-dialog-actions { display: flex; justify-content: flex-end; gap: 9px; padding: 13px 24px; border-top: 1px solid var(--line); background: var(--surface-raised); }
@media (max-width: 560px) {
.definition-state > div { width: 100%; flex-direction: column; }
.conflict-alert { align-items: flex-start; }
.conflict-alert .btn { width: 100%; margin-left: 0; }
.form-actions { flex-direction: column-reverse; }
.form-actions .btn { width: 100%; }
.route-dialog { width: calc(100vw - 20px); max-height: calc(100dvh - 20px); }
.route-dialog-panel { max-height: calc(100dvh - 20px); }
.route-dialog-body { padding-right: 17px; padding-left: 17px; }
.route-summary { grid-template-columns: 1fr; }
.route-dialog-actions { flex-direction: column-reverse; }
.route-dialog-actions .btn { width: 100%; }
}
@media (prefers-reduced-motion: reduce) { .route-dialog { scroll-behavior: auto; } }
</style>
@@ -0,0 +1,138 @@
<template>
<section class="permission-editor" aria-labelledby="permission-editor-title">
<header class="editor-head">
<div><h3 id="permission-editor-title">细粒度权限</h3><p>模块 → 页面 → 按钮分层授权;字段权限独立配置,目录异常时禁止保存。</p></div>
<label class="permission-search"><span class="sr-only">搜索权限</span><input v-model="query" type="search" placeholder="搜索名称或编码" aria-label="搜索权限名称或编码"></label>
</header>
<div class="permission-summary" role="status"><strong>授权摘要</strong><span>{{ summary }}</span></div>
<div v-if="!mayConfigure" class="permission-readonly" role="note">当前账号只能查看权限配置,不能修改。</div>
<div class="permission-rules"><strong>权限粒度</strong><span>页面 READ 表示可查看、EDIT 表示可编辑;按钮 EDIT 表示允许执行该操作。字段 READ/EDIT 分别为只读/可编辑,HIDDEN 均为无权。模块/页面勾选仅批量设置菜单与按钮,不触碰字段;搜索时批量框禁用以免改动隐藏项,可单独编辑可见项。</span></div>
<div v-if="catalogError" class="inline-alert danger" role="alert">{{ catalogError }}</div>
<div class="permission-columns">
<section class="permission-column menu-column" aria-labelledby="menu-permission-title">
<div class="column-head"><div><h3 id="menu-permission-title">菜单与按钮权限</h3><p>按模块 → 页面 → 按钮配置</p></div><span>{{ menuResultCount }} 项</span></div>
<div v-if="!visibleMenuRoots.length" class="empty-state compact-empty"><strong>未找到菜单或按钮</strong><span>请调整搜索关键字。</span></div>
<div v-for="module in visibleMenuRoots" :key="module.code" class="module-card">
<label class="branch-title">
<input type="checkbox" :checked="state(module).checked" :indeterminate.prop="state(module).indeterminate" :disabled="!mayConfigure || Boolean(normalizedQuery) || Boolean(catalogError)" :title="catalogError || (normalizedQuery ? '搜索筛选期间禁止批量修改,以保护隐藏权限' : undefined)" @change="toggle(module, $event)">
<span><strong>{{ module.name }}</strong><code>{{ module.code }}</code></span>
</label>
<div class="page-grid">
<article v-for="page in menuPages(module)" :key="page.code" class="page-card">
<label class="branch-title page-title">
<input type="checkbox" :checked="state(page).checked" :indeterminate.prop="state(page).indeterminate" :disabled="!mayConfigure || Boolean(normalizedQuery) || Boolean(catalogError)" :title="catalogError || (normalizedQuery ? '搜索筛选期间禁止批量修改,以保护隐藏权限' : undefined)" @change="toggle(page, $event)">
<span><strong>{{ page.name }}</strong><code>{{ page.code }}</code></span>
</label>
<div v-if="actions(page, module).length" class="action-list" aria-label="关键动作">
<label v-for="item in actions(page, module)" :key="item.code"><input type="checkbox" :checked="level(item.code) === 'EDIT'" :disabled="!mayConfigure || Boolean(catalogError)" @change="set(item.code, ($event.target as HTMLInputElement).checked ? 'EDIT' : 'HIDDEN')"><span>{{ item.name }}<code>{{ item.code }}</code></span></label>
</div>
<div v-else class="page-empty">该页面无匹配按钮</div>
</article>
</div>
</div>
</section>
<section class="permission-column field-column" aria-labelledby="field-permission-title">
<div class="column-head"><div><h3 id="field-permission-title">表单字段权限</h3><p>按所属模块 / 页面配置</p></div><span>{{ fieldResultCount }} 个字段</span></div>
<div v-if="!visibleFieldGroups.length" class="empty-state compact-empty"><strong>未找到表单字段</strong><span>当前目录没有匹配字段,或请调整搜索关键字。</span></div>
<section v-for="module in visibleFieldGroups" :key="module.code" class="field-module">
<header><strong>{{ module.name }}</strong><code>{{ module.code }}</code></header>
<article v-for="page in module.pages" :key="page.code" class="field-page">
<div class="field-page-title"><strong>{{ page.name }}</strong><code>{{ page.code }}</code></div>
<div class="field-list">
<label v-for="item in page.fields" :key="item.code"><span>{{ item.name }}<code>{{ item.code }}</code></span><select :value="level(item.code)" :aria-label="`${item.name}字段权限`" :disabled="!mayConfigure || Boolean(catalogError)" @change="set(item.code, ($event.target as HTMLSelectElement).value as PermissionAccess)"><option value="HIDDEN">隐藏</option><option value="READ">只读</option><option value="EDIT">编辑</option></select></label>
</div>
</article>
</section>
</section>
</div>
<section v-if="compatibility.length" class="compatibility-card" aria-labelledby="compat-title"><h4 id="compat-title">兼容权限</h4><p>以下权限不在当前目录中,保存时会原样保留,避免静默丢失。</p><ul><li v-for="item in compatibility" :key="item.code"><code>{{ item.code }}</code><select :value="item.level" :aria-label="`${item.code}兼容权限`" :disabled="!mayConfigure || Boolean(catalogError)" @change="set(item.code, ($event.target as HTMLSelectElement).value as PermissionAccess)"><option value="HIDDEN">隐藏</option><option value="READ">只读</option><option value="EDIT">编辑</option></select></li></ul></section>
</section>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import type { PermissionAccess, PermissionItem } from '@/api/admin'
import { branchState, buildPermissionForest, descendants, permissionKind, toggleBranch, validatePermissionCatalog, type PermissionBranch } from '@/composables/permissionEditor'
import { useUserStore } from '@/store/user'
type FieldPage = { code: string; name: string; fields: PermissionBranch[] }
type FieldModule = { code: string; name: string; pages: FieldPage[] }
const props = defineProps<{ catalog: PermissionItem[]; modelValue: Record<string, PermissionAccess> }>()
const emit = defineEmits<{ 'update:modelValue': [Record<string, PermissionAccess>] }>()
const userStore = useUserStore()
const mayConfigure = computed(() => userStore.canEdit('system.role.permission.configure'))
const query = ref('')
const catalogError = computed(() => validatePermissionCatalog(props.catalog))
const forest = computed(() => buildPermissionForest(props.catalog))
const known = computed(() => new Set(props.catalog.map(item => item.code)))
const compatibility = computed(() => Object.entries(props.modelValue).filter(([code]) => !known.value.has(code)).map(([code, level]) => ({ code, level })))
const normalizedQuery = computed(() => query.value.trim().toLocaleLowerCase())
const textMatches = (item: Pick<PermissionItem, 'name' | 'code'>) => !normalizedQuery.value || `${item.name} ${item.code}`.toLocaleLowerCase().includes(normalizedQuery.value)
const nested = (branch: PermissionBranch) => descendants(branch).slice(1)
const menuMatches = (branch: PermissionBranch): boolean => (permissionKind(branch) !== 'field' && textMatches(branch)) || branch.children.some(menuMatches)
const visibleMenuRoots = computed(() => forest.value.filter(menuMatches))
const menuPages = (module: PermissionBranch) => module.children.filter(page => permissionKind(page) !== 'field' && (textMatches(module) || menuMatches(page)))
const actions = (page: PermissionBranch, module: PermissionBranch) => nested(page).filter(item => permissionKind(item) === 'action' && (textMatches(module) || textMatches(page) || textMatches(item)))
const allFieldGroups = computed<FieldModule[]>(() => forest.value.map(module => ({
code: module.code,
name: module.name,
pages: module.children.map(page => ({ code: page.code, name: page.name, fields: nested(page).filter(item => permissionKind(item) === 'field') })).filter(page => page.fields.length),
})).filter(module => module.pages.length))
const visibleFieldGroups = computed<FieldModule[]>(() => allFieldGroups.value.map(module => {
const moduleMatch = textMatches(module)
const pages = module.pages.map(page => {
const contextMatch = moduleMatch || textMatches(page)
return { ...page, fields: contextMatch ? page.fields : page.fields.filter(textMatches) }
}).filter(page => page.fields.length)
return { ...module, pages }
}).filter(module => module.pages.length))
const level = (code: string): PermissionAccess => props.modelValue[code] || 'HIDDEN'
const set = (code: string, value: PermissionAccess) => { if (mayConfigure.value && !catalogError.value) emit('update:modelValue', { ...props.modelValue, [code]: value }) }
const state = (branch: PermissionBranch) => branchState(branch, props.modelValue)
const toggle = (branch: PermissionBranch, event: Event) => { if (mayConfigure.value && !normalizedQuery.value && !catalogError.value) emit('update:modelValue', toggleBranch(branch, (event.target as HTMLInputElement).checked, props.modelValue)) }
const menuResultCount = computed(() => visibleMenuRoots.value.reduce((count, module) => count + 1 + menuPages(module).reduce((pageCount, page) => pageCount + 1 + actions(page, module).length, 0), 0))
const fieldResultCount = computed(() => visibleFieldGroups.value.reduce((count, module) => count + module.pages.reduce((pageCount, page) => pageCount + page.fields.length, 0), 0))
const summary = computed(() => {
const entries = Object.entries(props.modelValue).filter(([, value]) => value !== 'HIDDEN')
const edit = entries.filter(([, value]) => value === 'EDIT').length
const read = entries.filter(([, value]) => value === 'READ').length
return `${entries.length} 项已授权(${read} 项只读,${edit} 项可编辑)`
})
</script>
<style scoped>
.permission-editor{display:grid;gap:14px}.editor-head{display:flex;align-items:end;justify-content:space-between;gap:16px}.editor-head h3,.column-head h3{font-size:15px}.editor-head p,.column-head p,.permission-rules,.compatibility-card p{color:var(--muted);font-size:11px}.permission-search{width:min(320px,100%)}.permission-search input{width:100%}.permission-summary,.permission-rules{display:flex;gap:10px;padding:10px 12px;border:1px solid var(--line);border-radius:7px;background:var(--surface)}.permission-columns{display:grid;grid-template-columns:minmax(0,2fr) minmax(280px,1fr);align-items:start;gap:14px}.permission-column{display:grid;min-width:0;gap:10px}.column-head{display:flex;align-items:end;justify-content:space-between;gap:10px;padding:0 2px}.column-head>span{color:var(--muted);font-size:11px;white-space:nowrap}.module-card,.field-module{border:1px solid var(--line);border-radius:9px;background:#fff;overflow:hidden}.branch-title{display:flex;align-items:center;gap:9px;padding:12px 14px;cursor:pointer}.branch-title>span,.action-list label>span,.field-list label>span{display:grid;min-width:0;gap:2px}.branch-title code,.action-list code,.field-list code,.field-module code,.compatibility-card code{color:var(--quiet);font:10px var(--mono);overflow-wrap:anywhere}.page-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;padding:0 12px 12px}.page-card{min-width:0;border:1px solid var(--line);border-radius:7px;background:var(--surface-raised)}.page-title{border-bottom:1px solid var(--line)}.action-list,.field-list{display:grid;gap:1px;padding:8px}.action-list label,.field-list label{display:flex;align-items:center;gap:8px;padding:7px;border-radius:5px;font-size:11px}.action-list label:hover,.field-list label:hover{background:var(--blue-soft)}.page-empty{padding:9px 12px;color:var(--quiet);font-size:10px}.field-module>header{display:grid;gap:2px;padding:11px 12px;border-bottom:1px solid var(--line);background:var(--surface)}.field-page+.field-page{border-top:1px solid var(--line)}.field-page-title{display:grid;gap:2px;padding:9px 12px 3px}.field-list label{justify-content:space-between}.field-list select,.compatibility-card select{min-width:84px;padding:6px}.compatibility-card{padding:13px;border:1px dashed var(--warning);border-radius:8px;background:var(--warning-soft)}.compatibility-card ul{display:grid;gap:6px;margin-top:8px;padding:0;list-style:none}.compatibility-card li{display:flex;align-items:center;justify-content:space-between;gap:10px}
@media(max-width:900px){.permission-columns{grid-template-columns:1fr}.editor-head{align-items:stretch;flex-direction:column}.permission-search{width:100%}.page-grid{grid-template-columns:1fr}.permission-summary,.permission-rules{flex-direction:column}}
@media(max-width:560px){.field-list label{align-items:stretch;flex-direction:column}.field-list select{width:100%;min-height:44px;font-size:16px}}
/* The editor sits inside the role section shell; use spacing and tone instead
of another outer border so the large dialog does not become box-within-box. */
.permission-editor { gap: 12px; padding: 14px 16px 16px; }
.editor-head { align-items: center; }
.editor-head h3 { color: var(--navy); font-size: 14px; }
.permission-search input { min-height: 38px; padding: 7px 10px; border: 1px solid var(--line-strong); border-radius: 6px; background: #fff; color: var(--text); }
.permission-summary, .permission-rules { align-items: baseline; border: 0; border-radius: 5px; }
.permission-summary { border-left: 3px solid var(--blue); background: var(--blue-soft); color: var(--body); }
.permission-readonly { padding: 9px 12px; border-left: 3px solid var(--warning); background: #fff8e8; color: var(--muted); font-size: 11px; }
.permission-summary strong, .permission-rules strong { flex: none; color: var(--navy); font-size: 11px; }
.permission-rules { padding-top: 8px; padding-bottom: 8px; background: #f7f9fb; }
.permission-columns { grid-template-columns: minmax(0, 1.55fr) minmax(300px, 1fr); gap: 16px; }
.permission-column { align-content: start; }
.column-head { min-height: 42px; align-items: center; padding: 0 1px 8px; border-bottom: 1px solid var(--line); }
.column-head h3 { color: var(--navy); font-size: 13px; }
.module-card, .field-module { border-color: #d7e0e8; border-radius: 6px; box-shadow: 0 1px 2px rgba(16, 42, 67, .03); }
.branch-title { padding: 10px 12px; }
.page-grid { gap: 8px; padding: 0 10px 10px; }
.page-card { border-color: #e2e7ec; border-radius: 5px; background: #fafbfd; }
.action-list label, .field-list label { min-height: 38px; }
.action-list label:hover, .field-list label:hover { background: #f0f6fd; }
.field-list select { min-height: 34px; border: 1px solid var(--line-strong); border-radius: 5px; background: #fff; color: var(--body); }
@media(max-width:900px){.permission-editor{padding:13px}.permission-columns{grid-template-columns:1fr}.editor-head{gap:10px}}
@media(max-width:560px){.permission-editor{padding:11px}.permission-summary,.permission-rules{gap:4px}.column-head{align-items:flex-start}.page-grid{padding-right:8px;padding-left:8px}}
</style>
@@ -0,0 +1,47 @@
<template>
<nav class="app-list-pagination" :aria-label="ariaLabel">
<p class="app-list-pagination__summary" aria-live="polite">{{ summary }}</p>
<el-pagination
v-model:current-page="currentPage"
v-model:page-size="currentPageSize"
:page-sizes="pageSizes"
:total="total"
:disabled="disabled"
:pager-count="5"
layout="sizes, prev, pager, next, jumper"
small
background
/>
</nav>
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = withDefaults(defineProps<{
page: number
pageSize: number
total: number
disabled?: boolean
ariaLabel?: string
pageSizes?: number[]
}>(), {
disabled: false,
ariaLabel: '列表分页',
pageSizes: () => [10, 20, 50],
})
const emit = defineEmits<{
'update:page': [value: number]
'update:pageSize': [value: number]
}>()
const currentPage = computed({ get: () => props.page, set: value => emit('update:page', value) })
const currentPageSize = computed({ get: () => props.pageSize, set: value => emit('update:pageSize', value) })
const summary = computed(() => {
if (!props.total) return '共 0 条'
const start = (props.page - 1) * props.pageSize + 1
const end = Math.min(props.total, props.page * props.pageSize)
return `第 ${start}–${end} 条,共 ${props.total} 条`
})
</script>
@@ -0,0 +1,560 @@
<template>
<div class="feishu-fields">
<template v-for="field in fields" :key="field.id">
<section v-if="field.type === 'EXPENSE_ITEMS' && field.binding === 'EXPENSE_ITEMS'" class="dynamic-field expense-field" :aria-labelledby="`${controlId(field)}-label`">
<div class="section-title compact-title">
<h3 :id="`${controlId(field)}-label`">{{ field.label }} <em v-if="field.required">*</em></h3>
<button v-if="!field.readOnly" class="btn small" type="button" @click="$emit('add-item')">+ 添加明细</button>
</div>
<div v-if="expenseFieldUnsupported(field)" class="unsupported-field expense-child-warning" role="alert">
<strong>费用明细结构暂不支持</strong><span>模板包含无法识别或不兼容的明细列,已停止猜测字段含义,请联系管理员重新同步模板。</span>
</div>
<div class="expense-items">
<fieldset v-for="(item, index) in form.items" :key="item.key" class="expense-item">
<legend class="sr-only">{{ field.label }}第 {{ index + 1 }} 条</legend>
<div v-for="column in itemColumns(field)" :key="column.key" class="field" :class="{ 'attachment-field': column.key === 'attachmentIds' }">
<label :for="`${controlId(field)}-${item.key}-${column.key}`">{{ column.label }} <em v-if="column.required">*</em></label>
<template v-if="column.key === 'attachmentIds'">
<input
:id="`${controlId(field)}-${item.key}-${column.key}`"
class="attachment-input" type="file" multiple :accept="attachmentAccept"
:disabled="field.readOnly || column.readOnly || itemHasPendingUploads(item)"
:aria-required="column.required" :aria-invalid="attachmentHasError(item, column.required)"
:aria-describedby="attachmentDescriptionIds(field, item, column.required)"
@change="uploadAttachments(item, column.child, $event)"
>
<small :id="`${controlId(field)}-${item.key}-attachment-help`" class="form-help">支持 PDF、PNG/JPEG、DOC/DOCX、XLS/XLSX,单个文件不超过 50MB;可一次选择多个文件并依次上传。</small>
<ul v-if="item.attachmentFiles.length" class="attachment-list" :aria-label="`第 ${index + 1} 条费用明细附件`" aria-live="polite">
<li v-for="attachment in item.attachmentFiles" :key="attachment.localKey" :class="`is-${attachment.status}`">
<div><strong>{{ attachment.fileName }}</strong><small>{{ attachmentStatus(attachment) }}</small></div>
<button v-if="!field.readOnly && attachment.status !== 'pending'" class="attachment-remove" type="button" :disabled="attachment.status === 'deleting'" :aria-label="`移除附件 ${attachment.fileName}`" @click="removeAttachment(item, attachment)">{{ attachment.status === 'deleting' ? '移除中…' : '移除' }}</button>
</li>
</ul>
<small v-if="attachmentError(item, column.required)" :id="`${controlId(field)}-${item.key}-attachment-error`" class="field-error" role="alert">! {{ attachmentError(item, column.required) }}</small>
</template>
<select
v-else-if="column.type === 'SINGLE_SELECT'"
:id="`${controlId(field)}-${item.key}-${column.key}`"
:value="item[column.key]"
:required="column.required && !field.readOnly"
:disabled="field.readOnly || column.readOnly"
@change="setItemValue(item, column.key, $event)"
><option value="">请选择</option><option v-for="option in column.options" :key="option.value" :value="option.label">{{ option.label }}</option></select>
<textarea
v-else-if="column.type === 'TEXTAREA'"
:id="`${controlId(field)}-${item.key}-${column.key}`" :value="String(item[column.key] ?? '')" rows="2"
:maxlength="column.maxLength" :required="column.required && !field.readOnly" :readonly="field.readOnly || column.readOnly"
@input="setItemValue(item, column.key, $event)"
></textarea>
<div v-else-if="column.type === 'DECIMAL'" class="amount-control-wrap">
<div class="amount-control">
<input
:id="`${controlId(field)}-${item.key}-${column.key}`"
:value="amountInputText(item)"
type="text"
inputmode="decimal"
autocomplete="off"
placeholder="0.00"
:required="column.required && !field.readOnly"
:readonly="field.readOnly || column.readOnly"
:aria-invalid="amountHasError(item, column.required)"
:aria-describedby="amountDescriptionIds(field, item, column)"
@input="setItemAmount(item, $event)"
@blur="normalizeItemAmount(item)"
>
<select
v-if="currencyOptions(column.child).length"
:aria-label="`${column.label}币种`"
:value="rowCurrency(column.child, index)"
:disabled="field.readOnly || column.readOnly"
@change="setRowCurrency(column.child, index, $event)"
>
<option v-for="option in currencyOptions(column.child)" :key="option.value" :value="option.value">{{ option.label }}</option>
</select>
</div>
<small v-if="amountHasError(item, column.required)" :id="`${controlId(field)}-${item.key}-amount-error`" class="field-error" role="alert">! {{ amountError(item, column.label, column.required) }}</small>
<small v-else :id="`${controlId(field)}-${item.key}-amount-help`" class="form-help">请填写大于 0 的金额,最多两位小数,上限 99,999,999.99 元</small>
</div>
<input v-else
:id="`${controlId(field)}-${item.key}-${column.key}`" :value="item[column.key]"
:type="column.type === 'DATE' ? 'date' : 'text'"
:maxlength="column.maxLength" :required="column.required && !field.readOnly" :readonly="field.readOnly || column.readOnly"
@input="setItemValue(item, column.key, $event)">
</div>
<button v-if="!field.readOnly && form.items.length > 1" class="remove-item" type="button" :disabled="itemHasPendingUploads(item)" :aria-label="`删除第 ${index + 1} 条费用明细`" @click="$emit('remove-item', index)">删除</button>
</fieldset>
</div>
<div class="amount-summary" :class="{ 'amount-mismatch': form.totalAmount > 0 && !amountMatches }">
<span>明细合计</span><strong>{{ money(itemsTotal) }}</strong><span>申请金额 {{ money(form.totalAmount) }}</span>
</div>
<small v-if="form.totalAmount > 0 && !amountMatches" class="field-error amount-mismatch-tip" role="status">明细合计须与申请金额一致,请核对各行金额。</small>
</section>
<div v-else-if="field.type === 'DISPLAY'" class="dynamic-field display-field" role="note">
<strong>{{ field.label }}</strong><p>{{ displayValue(field) }}</p>
</div>
<div v-else-if="isApplicantContact(field)" class="field dynamic-field applicant-contact">
<label :for="controlId(field)">{{ field.label }} <em v-if="field.required">*</em></label>
<input :id="controlId(field)" :value="applicantContactLabel" readonly :aria-describedby="`${controlId(field)}-help`">
<small :id="`${controlId(field)}-help`" class="form-help">当前申请人,由系统自动带入且不会作为自定义值提交</small>
</div>
<div v-else-if="isApplicantDepartment(field)" class="field dynamic-field applicant-department">
<label :for="controlId(field)">{{ field.label }} <em v-if="field.required">*</em></label>
<div class="department-picker" @focusout="departmentOpen = false">
<input
:id="controlId(field)"
v-model="departmentQuery"
type="search"
autocomplete="off"
:placeholder="selectedDepartmentName(field) || '搜索飞书部门'"
:aria-describedby="`${controlId(field)}-help`"
@focus="departmentOpen = true"
@input="departmentOpen = true"
>
<ul v-if="departmentOpen" class="department-menu" role="listbox">
<li v-for="department in filteredDepartments" :key="department.id">
<button type="button" @mousedown.prevent="chooseDepartment(field, department)">{{ department.name }}</button>
</li>
<li v-if="!filteredDepartments.length" class="department-empty">没有匹配的部门</li>
</ul>
</div>
<small :id="`${controlId(field)}-help`" class="form-help">可搜索并选择飞书组织架构中的部门。未改选时仍使用申请人当前部门。</small>
</div>
<div v-else-if="isRuntimeUnsupported(field)" class="dynamic-field unsupported-field" role="alert">
<strong>暂不支持「{{ field.label }}」类型</strong><span>该控件无法在本系统编辑,请联系管理员。</span>
</div>
<div v-else class="field dynamic-field" :class="{ full: field.type === 'TEXTAREA' }">
<label :for="controlId(field)">{{ field.label }} <em v-if="field.required">*</em></label>
<template v-if="!canEditField(field)">
<textarea v-if="field.type === 'TEXTAREA'" :id="controlId(field)" :value="String(fieldValue(field) ?? '')" readonly rows="3" :aria-describedby="`${controlId(field)}-help`"></textarea>
<input v-else :id="controlId(field)" :value="displayValue(field)" readonly :aria-describedby="`${controlId(field)}-help`">
<small :id="`${controlId(field)}-help`" class="form-help">{{ field.type === 'FORMULA' ? '由费用明细自动计算,只读' : '只读信息,不会作为自定义值提交' }}</small>
</template>
<textarea
v-else-if="field.type === 'TEXTAREA'"
:id="controlId(field)" :value="String(fieldValue(field) ?? '')" rows="3"
:maxlength="field.maxLength" :required="field.required" :aria-required="field.required"
:aria-invalid="hasError(field)" :aria-describedby="hasError(field) ? `${controlId(field)}-error` : undefined"
@input="setFieldValue(field, ($event.target as HTMLTextAreaElement).value)"
></textarea>
<select
v-else-if="field.type === 'SINGLE_SELECT'"
:id="controlId(field)" :value="String(fieldValue(field) ?? '')" :required="field.required" :aria-required="field.required"
:aria-invalid="hasError(field)" :aria-describedby="hasError(field) ? `${controlId(field)}-error` : undefined"
@change="setFieldValue(field, ($event.target as HTMLSelectElement).value)"
>
<option value="">请选择</option><option v-for="option in field.options" :key="option.value" :value="option.value">{{ option.label }}</option>
</select>
<select
v-else-if="field.type === 'MULTI_SELECT'"
:id="controlId(field)" :value="arrayValue(field)" multiple :required="field.required" :aria-required="field.required"
:aria-invalid="hasError(field)" :aria-describedby="hasError(field) ? `${controlId(field)}-error` : `${controlId(field)}-help`"
@change="setMultiValue(field, $event)"
>
<option v-for="option in field.options" :key="option.value" :value="option.value">{{ option.label }}</option>
</select>
<div v-else-if="field.type === 'DECIMAL'" class="amount-control">
<input
:id="controlId(field)" :value="fieldValue(field) as string | number | undefined"
type="text" inputmode="decimal" :maxlength="field.maxLength"
:required="field.required" :aria-required="field.required" :aria-invalid="hasError(field)"
:aria-describedby="hasError(field) ? `${controlId(field)}-error` : `${controlId(field)}-help`"
@input="setFieldValue(field, ($event.target as HTMLInputElement).value)"
>
<select
v-if="currencyOptions(field).length"
:aria-label="`${field.label}币种`"
:value="fieldCurrency(field)"
@change="setFieldCurrency(field, $event)"
>
<option v-for="option in currencyOptions(field)" :key="option.value" :value="option.value">{{ option.label }}</option>
</select>
</div>
<input
v-else
:id="controlId(field)" :value="fieldValue(field) as string | number | undefined"
:type="field.type === 'DATE' ? 'date' : 'text'"
:maxlength="field.maxLength"
:required="field.required" :aria-required="field.required" :aria-invalid="hasError(field)"
:aria-describedby="hasError(field) ? `${controlId(field)}-error` : undefined"
@input="setFieldValue(field, ($event.target as HTMLInputElement).value)"
>
<small v-if="field.type === 'MULTI_SELECT'" :id="`${controlId(field)}-help`" class="form-help">按住 Ctrl(macOS 使用 Command)可多选</small>
<small v-if="field.type === 'DECIMAL' && field.binding === 'TOTAL_AMOUNT' && !hasError(field)" :id="`${controlId(field)}-help`" class="form-help">请填写大于 0 的金额,最多两位小数,上限 99,999,999.99 元</small>
<small v-else-if="field.type === 'DECIMAL' && !hasError(field)" :id="`${controlId(field)}-help`" class="form-help">请输入有效数字</small>
<small v-if="hasError(field)" :id="`${controlId(field)}-error`" class="field-error" role="alert">! {{ fieldError(field) }}</small>
</div>
</template>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { reimbursementApi, type ExpenseItem, type ExpenseTypeMetadata, type ReimbursementFormAttachment, type ReimbursementFormField, type ReimbursementFormOption } from '@/api/reimbursement'
import { feishuDirectoryApi } from '@/api/feishuDirectory'
import { ATTACHMENT_ACCEPT, attachmentFileValidationError, attachmentIdsMissingMetadata } from '@/modules/reimbursementAttachments'
import { inspectMoneyAmount, moneyAmountMessage, normalizeMoneyAmount } from '@/utils/moneyAmount'
type ItemKey = 'expenseDate' | 'category' | 'description' | 'amount' | 'attachmentIds'
type AttachmentStatus = 'uploaded' | 'pending' | 'failed' | 'deleting'
interface AttachmentEntry extends Partial<ReimbursementFormAttachment> { localKey: string; fileName: string; status: AttachmentStatus; error?: string }
interface FormItem extends ExpenseItem { key: number; description: string; attachmentFiles: AttachmentEntry[] }
interface FormModel { title: string; expenseTypeId?: number; category: string; totalAmount: number; description: string; items: FormItem[] }
const props = defineProps<{
fields: ReimbursementFormField[]
formValues: Record<string, unknown>
form: FormModel
derived: Record<string, string>
showErrors: boolean
itemsTotal: number
amountMatches: boolean
expenseTypes: ExpenseTypeMetadata[]
formFingerprint?: string
}>()
const emit = defineEmits<{ (event: 'add-item'): void; (event: 'remove-item', index: number): void; (event: 'upload-state-change'): void }>()
const derivedBindings = new Set(['APPLICATION_NO', 'APPLICANT_NAME', 'APPLICANT_CONTACT', 'APPLICANT_DEPARTMENT', 'DEPARTMENT', 'SOURCE_DOC_NO'])
const supportedTypes = new Set(['TEXT', 'TEXTAREA', 'DECIMAL', 'DATE', 'SINGLE_SELECT', 'MULTI_SELECT'])
const knownTypes = new Set([...supportedTypes, 'DISPLAY', 'EXPENSE_ITEMS', 'FORMULA'])
const canonicalEditorTypes: Partial<Record<ReimbursementFormField['binding'], ReimbursementFormField['type'][]>> = {
TITLE: ['TEXT', 'TEXTAREA'], EXPENSE_TYPE: ['SINGLE_SELECT'], TOTAL_AMOUNT: ['DECIMAL'], DESCRIPTION: ['TEXT', 'TEXTAREA'],
}
const safeId = (value: string) => value.replace(/[^a-zA-Z0-9_-]/g, '-')
const controlId = (field: ReimbursementFormField) => `feishu-${safeId(field.id)}`
const isApplicantContact = (field: ReimbursementFormField) => field.type === 'CONTACT' && field.binding === 'APPLICANT_CONTACT'
const isApplicantDepartment = (field: ReimbursementFormField) => field.type === 'DEPARTMENT' && field.binding === 'APPLICANT_DEPARTMENT'
const isRuntimeUnsupported = (field: ReimbursementFormField) => {
if (field.type === 'DEPARTMENT' || field.binding === 'APPLICANT_DEPARTMENT') return !isApplicantDepartment(field)
return !knownTypes.has(field.type) && !isApplicantContact(field)
}
const applicantContactLabel = computed(() => props.derived.APPLICANT_CONTACT || props.derived.APPLICANT_NAME || '—')
const applicantDepartmentLabel = computed(() => props.derived.APPLICANT_DEPARTMENT || '—')
const canEditField = (field: ReimbursementFormField) => {
if (field.readOnly || derivedBindings.has(field.binding) || !supportedTypes.has(field.type)) return false
if (field.binding === 'CUSTOM') return true
return Boolean(canonicalEditorTypes[field.binding]?.includes(field.type))
}
const isEmpty = (value: unknown) => value == null || value === '' || (Array.isArray(value) && value.length === 0)
const fieldError = (field: ReimbursementFormField) => {
if (field.binding === 'EXPENSE_TYPE' && props.form.category && !props.form.expenseTypeId) return `${field.label}无法与系统费用类型唯一匹配,请联系管理员检查模板选项`
if (field.required && isEmpty(fieldValue(field))) return `${field.label}为必填项`
if (field.type === 'DECIMAL' && !isEmpty(fieldValue(field))) {
if (field.binding === 'TOTAL_AMOUNT') {
const issue = inspectMoneyAmount(fieldValue(field))
if (issue && issue !== 'empty') return moneyAmountMessage(issue, field.label)
} else if (!/^-?\d+(\.\d+)?$/.test(String(fieldValue(field)))) {
return `${field.label}须为有效数字,例如 128.50`
}
}
return ''
}
const hasError = (field: ReimbursementFormField) => props.showErrors && canEditField(field) && Boolean(fieldError(field))
const arrayValue = (field: ReimbursementFormField) => Array.isArray(fieldValue(field)) ? fieldValue(field) as string[] : []
const money = (value: number) => `¥ ${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`
const unique = (matches: ExpenseTypeMetadata[]) => matches.length === 1 ? matches[0] : undefined
const matchExpenseType = (option: ReimbursementFormOption | undefined): ExpenseTypeMetadata | undefined => {
if (!option) return undefined
if (/^\d+$/.test(option.value)) {
const byId = unique(props.expenseTypes.filter(type => type.id === Number(option.value)))
if (byId) return byId
}
const byCode = unique(props.expenseTypes.filter(type => type.code === option.value))
if (byCode) return byCode
return unique(props.expenseTypes.filter(type => type.name === option.label))
}
const fieldValue = (field: ReimbursementFormField): unknown => {
if (field.binding === 'APPLICANT_CONTACT') return applicantContactLabel.value
if (field.binding === 'APPLICANT_DEPARTMENT') return applicantDepartmentLabel.value
if (field.binding === 'CUSTOM') return props.formValues[field.valueKey]
if (field.binding === 'TITLE') return props.form.title
if (field.binding === 'EXPENSE_TYPE') {
if (field.type !== 'SINGLE_SELECT') return props.form.category
return field.options.find(option => matchExpenseType(option)?.id === props.form.expenseTypeId)?.value
|| ''
}
if (field.binding === 'TOTAL_AMOUNT') return props.itemsTotal
if (field.binding === 'DESCRIPTION') return props.form.description
return props.derived[field.binding] || ''
}
const displayValue = (field: ReimbursementFormField) => {
const value = fieldValue(field)
if (Array.isArray(value)) return value.map(entry => field.options.find(option => option.value === String(entry))?.label || String(entry)).join('、') || '—'
if (field.type === 'FORMULA' && field.binding === 'TOTAL_AMOUNT') return `${field.currency || 'CNY'} ${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
if (field.type === 'SINGLE_SELECT') return field.options.find(option => option.value === String(value))?.label || String(value || '—')
return String(value ?? '') || '—'
}
const setFieldValue = (field: ReimbursementFormField, value: string) => {
if (!canEditField(field)) return
if (field.binding === 'CUSTOM') props.formValues[field.valueKey] = value
else if (field.binding === 'TITLE') props.form.title = value
else if (field.binding === 'EXPENSE_TYPE') {
const option = field.options.find(entry => entry.value === value)
const matched = matchExpenseType(option)
props.form.expenseTypeId = matched?.id
props.form.category = matched?.category || option?.label || ''
} else if (field.binding === 'TOTAL_AMOUNT') props.form.totalAmount = Number(value) || 0
else if (field.binding === 'DESCRIPTION') props.form.description = value
}
const setMultiValue = (field: ReimbursementFormField, event: Event) => {
if (field.binding !== 'CUSTOM' || field.readOnly) return
props.formValues[field.valueKey] = [...(event.target as HTMLSelectElement).selectedOptions].map(option => option.value)
}
const childBindingKeys: Partial<Record<ReimbursementFormField['binding'], ItemKey>> = {
EXPENSE_DATE: 'expenseDate', EXPENSE_CATEGORY: 'category', EXPENSE_DESCRIPTION: 'description', EXPENSE_AMOUNT: 'amount', EXPENSE_ATTACHMENT: 'attachmentIds',
}
const supportedChildTypes: Record<ItemKey, Set<ReimbursementFormField['type']>> = {
expenseDate: new Set(['DATE']), category: new Set(['TEXT', 'SINGLE_SELECT']), description: new Set(['TEXT', 'TEXTAREA']), amount: new Set(['DECIMAL']), attachmentIds: new Set(['ATTACHMENT']),
}
const expenseFieldUnsupported = (field: ReimbursementFormField) => field.children.some(child => {
if (child.type === 'DISPLAY' && !child.required) return false
const key = childBindingKeys[child.binding]
return !key || !supportedChildTypes[key].has(child.type)
})
const itemColumns = (field: ReimbursementFormField) => {
const ordered: { key: ItemKey; label: string; required: boolean; readOnly: boolean; type: ReimbursementFormField['type']; maxLength?: number; options: ReimbursementFormField['options']; child: ReimbursementFormField }[] = []
field.children.forEach(child => {
if (child.type === 'DISPLAY' && !child.required) return
const key = childBindingKeys[child.binding]
if (key && supportedChildTypes[key].has(child.type) && !ordered.some(column => column.key === key)) ordered.push({ key, label: child.label, required: child.required, readOnly: child.readOnly, type: child.type, maxLength: child.maxLength, options: child.options, child })
})
return ordered
}
const setItemValue = (item: FormItem, key: ItemKey, event: Event) => {
if (key === 'attachmentIds' || key === 'amount') return
item[key] = (event.target as HTMLInputElement).value
}
const amountDrafts = reactive<Record<number, string>>({})
const amountSource = (item: FormItem) => (amountDrafts[item.key] != null ? amountDrafts[item.key] : (item.amount > 0 ? item.amount : ''))
const amountInputText = (item: FormItem) => {
if (amountDrafts[item.key] != null) return amountDrafts[item.key]
return item.amount > 0 ? String(item.amount) : ''
}
const setItemAmount = (item: FormItem, event: Event) => {
const text = (event.target as HTMLInputElement).value.trimStart()
amountDrafts[item.key] = text
const issue = inspectMoneyAmount(text)
if (!issue) item.amount = normalizeMoneyAmount(text)
else if (!text.trim()) item.amount = 0
else {
const parsed = Number(text)
item.amount = Number.isFinite(parsed) && parsed >= 0 ? parsed : 0
}
}
const normalizeItemAmount = (item: FormItem) => {
const text = amountDrafts[item.key]
if (text == null) return
if (!inspectMoneyAmount(text)) {
item.amount = normalizeMoneyAmount(text)
delete amountDrafts[item.key]
}
}
const amountError = (item: FormItem, label: string, required: boolean) => {
const issue = inspectMoneyAmount(amountSource(item))
if (!issue) return ''
if (issue === 'empty' && !required) return ''
return moneyAmountMessage(issue, label)
}
const amountHasError = (item: FormItem, required: boolean) => props.showErrors && Boolean(amountError(item, '金额', required))
const amountDescriptionIds = (field: ReimbursementFormField, item: FormItem, column: { required: boolean }) =>
amountHasError(item, column.required)
? `${controlId(field)}-${item.key}-amount-error`
: `${controlId(field)}-${item.key}-amount-help`
const currencyKey = (field: ReimbursementFormField) => `__currency__${field.valueKey}`
const currencyOptions = (field: ReimbursementFormField) => field.options?.length ? field.options : (field.currency ? [{ value: field.currency, label: field.currency }] : [])
const fieldCurrency = (field: ReimbursementFormField) => String(props.formValues[currencyKey(field)] || field.currency || currencyOptions(field)[0]?.value || 'CNY')
const setFieldCurrency = (field: ReimbursementFormField, event: Event) => { props.formValues[currencyKey(field)] = (event.target as HTMLSelectElement).value }
const rowCurrency = (field: ReimbursementFormField, index: number) => {
const stored = props.formValues[currencyKey(field)]
return Array.isArray(stored) && stored[index] ? String(stored[index]) : (field.currency || currencyOptions(field)[0]?.value || 'CNY')
}
const setRowCurrency = (field: ReimbursementFormField, index: number, event: Event) => {
const next = Array.isArray(props.formValues[currencyKey(field)]) ? [...props.formValues[currencyKey(field)] as string[]] : []
next[index] = (event.target as HTMLSelectElement).value
props.formValues[currencyKey(field)] = next
}
const departments = ref<{ id: string; name: string }[]>([])
const departmentQuery = ref('')
const departmentOpen = ref(false)
const filteredDepartments = computed(() => {
const keyword = departmentQuery.value.trim().toLowerCase()
return departments.value.filter(department => !keyword || department.name.toLowerCase().includes(keyword)).slice(0, 30)
})
const selectedDepartmentName = (field: ReimbursementFormField) => {
const id = String(props.formValues[field.valueKey] || '')
return departments.value.find(department => department.id === id)?.name || ''
}
const chooseDepartment = (field: ReimbursementFormField, department: { id: string; name: string }) => {
props.formValues[field.valueKey] = department.id
departmentQuery.value = department.name
departmentOpen.value = false
}
onMounted(async () => {
try {
const organization = await feishuDirectoryApi.organization()
departments.value = (organization.departments || []).map(department => ({ id: department.id, name: department.name }))
} catch { departments.value = [] }
})
const attachmentAccept = ATTACHMENT_ACCEPT
const itemHasPendingUploads = (item: FormItem) => item.attachmentFiles.some(file => file.status === 'pending' || file.status === 'deleting')
const attachmentError = (item: FormItem, required: boolean) => {
const failed = item.attachmentFiles.find(file => file.status === 'failed')
if (failed) return failed.error || `${failed.fileName}上传失败,请移除后重新选择`
const missing = attachmentIdsMissingMetadata(item.attachmentIds, item.attachmentFiles)
if (missing.length) return `附件信息不完整(ID:${missing.join('、')}),请刷新详情;如仍异常,请联系管理员处理`
if (props.showErrors && required && !item.attachmentIds.length) return '该条费用明细必须上传附件'
return ''
}
const attachmentHasError = (item: FormItem, required: boolean) => Boolean(attachmentError(item, required))
const attachmentDescriptionIds = (field: ReimbursementFormField, item: FormItem, required: boolean) => [
`${controlId(field)}-${item.key}-attachment-help`,
attachmentHasError(item, required) ? `${controlId(field)}-${item.key}-attachment-error` : '',
].filter(Boolean).join(' ')
const attachmentStatus = (attachment: AttachmentEntry) => {
if (attachment.status === 'pending') return '正在上传…'
if (attachment.status === 'deleting') return '正在移除…'
if (attachment.status === 'failed') return attachment.error || '上传失败'
const size = Number(attachment.fileSize || 0)
return size ? `已上传 · ${(size / 1024 / 1024).toFixed(size >= 1024 * 1024 ? 1 : 2)} MB` : '已上传'
}
const uploadAttachments = async (item: FormItem, child: ReimbursementFormField, event: Event) => {
const input = event.target as HTMLInputElement
const files = [...(input.files || [])]
input.value = ''
for (const file of files) {
const localKey = `${Date.now()}-${Math.random().toString(36).slice(2)}`
const invalid = attachmentFileValidationError(file)
const entry: AttachmentEntry = { localKey, fileName: file.name, fileSize: file.size, contentType: file.type, status: invalid ? 'failed' : 'pending', error: invalid }
item.attachmentFiles.push(entry)
emit('upload-state-change')
if (invalid) continue
try {
if (!props.formFingerprint) throw new Error('表单版本缺失,无法上传附件')
const uploaded = await reimbursementApi.uploadFormAttachment(file, props.formFingerprint, child.id)
Object.assign(entry, uploaded, { status: 'uploaded', error: undefined })
if (!item.attachmentIds.some(id => String(id) === String(uploaded.id))) item.attachmentIds.push(uploaded.id)
} catch (error) {
entry.status = 'failed'
entry.error = error instanceof Error && error.message ? error.message : '上传失败,请移除后重试'
}
emit('upload-state-change')
}
}
const removeAttachment = async (item: FormItem, attachment: AttachmentEntry) => {
if (attachment.status === 'pending' || attachment.status === 'deleting') return
if (attachment.id == null) {
item.attachmentFiles = item.attachmentFiles.filter(file => file.localKey !== attachment.localKey)
emit('upload-state-change')
return
}
attachment.status = 'deleting'
attachment.error = undefined
emit('upload-state-change')
try {
await reimbursementApi.deleteFormAttachment(attachment.id)
item.attachmentIds = item.attachmentIds.filter(id => String(id) !== String(attachment.id))
item.attachmentFiles = item.attachmentFiles.filter(file => file.localKey !== attachment.localKey)
} catch (error) {
attachment.status = 'failed'
attachment.error = error instanceof Error && error.message ? error.message : '附件移除失败,请重试'
}
emit('upload-state-change')
}
</script>
<style scoped>
.feishu-fields {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px 20px;
padding: 20px 22px 22px;
}
.dynamic-field { min-width: 0; }
.expense-field,
.display-field,
.unsupported-field { grid-column: 1 / -1; }
.expense-field {
display: flex;
flex-direction: column;
gap: 16px;
margin: 8px 0 0;
padding: 20px 0 0;
border-top: 1px solid var(--line);
}
.expense-field .expense-items { padding: 0; }
.expense-field .expense-item {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 16px 20px;
align-items: start;
padding: 16px;
}
.expense-field .expense-item > .field { min-width: 0; }
.expense-field .expense-item > .attachment-field { grid-column: 1 / -1; }
.expense-field .remove-item { grid-column: 1 / -1; justify-self: end; margin-top: 0; }
.expense-field .amount-summary { margin: 4px 0 0; }
.amount-control-wrap { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
.amount-control { display: grid; grid-template-columns: minmax(0, 1fr) 108px; gap: 8px; align-items: center; }
.amount-control select { min-height: var(--control-height); }
.amount-mismatch-tip { display: block; margin-top: 6px; }
.department-picker { position: relative; }
.department-menu { position: absolute; z-index: 5; top: calc(100% + 4px); right: 0; left: 0; max-height: 240px; margin: 0; padding: 6px; overflow: auto; list-style: none; border: 1px solid var(--line); border-radius: 6px; background: #fff; box-shadow: var(--card-shadow); }
.department-menu button { width: 100%; padding: 8px 10px; border: 0; border-radius: 4px; background: transparent; text-align: left; }
.department-menu button:hover { background: var(--blue-soft); color: var(--blue); }
.department-empty { padding: 8px 10px; color: var(--muted); }
.compact-title {
margin: 0;
padding: 0;
border-bottom: 0;
}
.compact-title h3 { margin: 0; font-size: 15px; }
.compact-title em { color: var(--danger); font-style: normal; }
.display-field,
.unsupported-field {
padding: 16px 18px;
border: 1px solid var(--line);
border-radius: 7px;
background: var(--surface);
}
.display-field p { margin: 8px 0 0; color: var(--muted); white-space: pre-wrap; line-height: 1.65; }
.unsupported-field { display: flex; flex-direction: column; gap: 6px; border-color: #e5bfbc; background: var(--danger-soft); color: var(--danger); }
.expense-child-warning { margin: 0; }
.field-error { color: var(--danger); }
.field [aria-invalid="true"] { border-color: var(--danger); }
.attachment-field { grid-column: 1 / -1; }
.attachment-input { padding: 10px; }
.attachment-list { display: flex; margin: 10px 0 0; padding: 0; flex-direction: column; gap: 8px; list-style: none; }
.attachment-list li {
display: flex;
min-width: 0;
align-items: center;
justify-content: space-between;
gap: 14px;
padding: 12px 14px;
border: 1px solid var(--line);
border-radius: 7px;
background: var(--surface);
}
.attachment-list li > div { min-width: 0; }
.attachment-list strong,
.attachment-list small { display: block; overflow-wrap: anywhere; }
.attachment-list small { margin-top: 3px; color: var(--quiet); }
.attachment-list .is-failed { border-color: #e5bfbc; background: var(--danger-soft); }
.attachment-list .is-failed small { color: var(--danger); }
.attachment-remove { border: 0; background: transparent; color: var(--danger); cursor: pointer; font: inherit; }
.attachment-remove:disabled { cursor: wait; opacity: .6; }
select[multiple] { min-height: 104px; }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
@media (max-width: 680px) {
.feishu-fields { grid-template-columns: 1fr; gap: 18px; padding: 16px; }
.dynamic-field { grid-column: 1; }
.expense-field .expense-item { grid-template-columns: 1fr; }
.amount-control { grid-template-columns: 1fr; }
}
</style>
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, it } from 'vitest'
import type { PermissionItem } from '@/api/admin'
import { buildPermissionForest, hasUnsavedRoleDraft, hydrateRolePermissions, permissionKind, toggleBranch, validatePermissionCatalog } from './permissionEditor'
const item = (code: string, type: string, parentCode?: string): PermissionItem => ({ code, name: code, type, parentCode })
describe('permission editor catalog safety', () => {
it('rejects empty and duplicate codes, self parents and cycles', () => {
expect(validatePermissionCatalog([item('', 'PAGE')])).toContain('空编码')
expect(validatePermissionCatalog([item('x', 'PAGE'), item('x', 'ACTION')])).toContain('重复编码')
expect(validatePermissionCatalog([item('x', 'PAGE', 'x')])).toContain('自身')
expect(validatePermissionCatalog([item('a', 'PAGE', 'b'), item('b', 'PAGE', 'a')])).toContain('循环')
})
it('retains orphan legacy entries as roots and keeps unknown types compatible', () => {
const forest = buildPermissionForest([item('legacy', 'OLD', 'missing')])
expect(forest).toHaveLength(1)
expect(permissionKind(forest[0])).toBe('action')
expect(permissionKind(item('button', 'BUTTON'))).toBe('action')
})
it('bulk changes the complete unfiltered menu tree but never fields', () => {
const [module] = buildPermissionForest([item('module.a', 'MODULE'), item('page.a', 'PAGE', 'module.a'), item('button.a', 'ACTION', 'page.a'), item('field.a', 'FIELD', 'page.a')])
const updated = toggleBranch(module, true, {})
expect(updated).toEqual({ 'module.a': 'READ', 'page.a': 'READ', 'button.a': 'EDIT' })
})
it('can protect hidden search results while allowing matched branch items', () => {
const [module] = buildPermissionForest([item('module.a', 'MODULE'), item('page.a', 'PAGE', 'module.a'), item('button.visible', 'ACTION', 'page.a'), item('button.hidden', 'ACTION', 'page.a')])
const updated = toggleBranch(module, true, {}, new Set(['module.a', 'page.a', 'button.visible']))
expect(updated).toEqual({ 'module.a': 'READ', 'page.a': 'READ', 'button.visible': 'EDIT' })
})
it('rejects missing/malformed role payload instead of granting empty permissions', () => {
expect(() => hydrateRolePermissions(undefined)).toThrow('缺失或格式无效')
expect(() => hydrateRolePermissions({ permissionAccess: [] as unknown as Record<string, 'READ'> })).toThrow('格式无效')
})
it('strictly validates every permission map entry and code list member', () => {
expect(() => hydrateRolePermissions({ permissionCodes: [1] as unknown as string[] })).toThrow('字符串数组')
expect(() => hydrateRolePermissions({ permissionAccess: { '': 'READ' } })).toThrow('无效编码或权限值')
expect(() => hydrateRolePermissions({ permissionAccess: { x: 'ALLOW' as never } })).toThrow('无效编码或权限值')
expect(() => hydrateRolePermissions({ fieldPermissions: { x: null as never } })).toThrow('无效编码或权限值')
})
it('tracks form and permission changes against baselines and retains retry drafts', () => {
const savedForm = { roleCode: 'new', roleName: '新角色' }
const permissionBase = JSON.stringify({})
expect(hasUnsavedRoleDraft(savedForm, { x: 'EDIT' }, JSON.stringify(savedForm), permissionBase)).toBe(true)
expect(hasUnsavedRoleDraft(savedForm, { x: 'EDIT' }, JSON.stringify(savedForm), JSON.stringify({ x: 'EDIT' }))).toBe(false)
expect(hasUnsavedRoleDraft({ ...savedForm, roleName: '改名' }, { x: 'EDIT' }, JSON.stringify(savedForm), JSON.stringify({ x: 'EDIT' }))).toBe(true)
})
})
+109
View File
@@ -0,0 +1,109 @@
import type { PermissionAccess, PermissionItem, RolePermissions } from '@/api/admin'
export type PermissionBranch = PermissionItem & { children: PermissionBranch[] }
export const hasUnsavedRoleDraft = (form: unknown, permissions: unknown, formBaseline: string, permissionBaseline: string): boolean => JSON.stringify(form) !== formBaseline || JSON.stringify(permissions) !== permissionBaseline
export const validatePermissionCatalog = (catalog: PermissionItem[]): string | null => {
if (!Array.isArray(catalog) || catalog.length === 0) return '权限目录为空,无法安全编辑角色权限。'
const codes = new Set<string>()
for (const item of catalog) {
if (!item || typeof item.code !== 'string' || !item.code.trim() || item.code.trim() !== item.code) return '权限目录存在空编码或无效空格,已禁止保存。'
if (typeof item.name !== 'string' || !item.name.trim()) return `权限「${item.code}」缺少名称,已禁止保存。`
if (item.parentCode !== undefined && item.parentCode !== null && typeof item.parentCode !== 'string') return `权限「${item.code}」的父级编码格式无效,已禁止保存。`
if (codes.has(item.code)) return `权限目录存在重复编码「${item.code}」,已禁止保存。`
codes.add(item.code)
}
const parents = new Map(catalog.map(item => [item.code, item.parentCode]))
for (const item of catalog) if (item.parentCode === item.code) return `权限「${item.code}」不能以自身为父级,已禁止保存。`
for (const item of catalog) {
const path = new Set<string>([item.code])
let parent = item.parentCode
while (parent && parents.has(parent)) {
if (path.has(parent)) return `权限「${item.code}」的父级关系存在循环(涉及「${parent}」),已禁止保存。`
path.add(parent)
parent = parents.get(parent)
}
}
return null
}
export const permissionKind = (item: PermissionItem) => {
const type = String(item.type || '').trim().toUpperCase()
// Explicit backend types are authoritative. In particular, BUTTON codes may
// use the legacy `application:*` namespace also used by old field codes.
if (type === 'FIELD') return 'field'
if (type === 'ACTION' || type === 'BUTTON') return 'action'
if (type === 'MODULE') return 'module'
if (type === 'PAGE') return 'page'
if (type === 'MENU') return item.code.startsWith('module.') || !item.parentCode ? 'module' : 'page'
// Code inference is compatibility-only for missing or unknown types.
if (item.code.startsWith('application:')) return 'field'
if (!item.code.startsWith('module.') && !item.code.startsWith('page.')) return 'action'
return item.code.startsWith('module.') ? 'module' : 'page'
}
export const buildPermissionForest = (catalog: PermissionItem[]): PermissionBranch[] => {
const branches = new Map(catalog.map(item => [item.code, { ...item, children: [] as PermissionBranch[] }]))
const roots: PermissionBranch[] = []
branches.forEach(branch => {
const parent = branch.parentCode ? branches.get(branch.parentCode) : undefined
if (parent) parent.children.push(branch)
else roots.push(branch)
})
const sort = (items: PermissionBranch[]) => items.sort((a, b) => a.code.localeCompare(b.code, 'zh-CN')).forEach(item => sort(item.children))
sort(roots)
return roots
}
export const descendants = (branch: PermissionBranch): PermissionBranch[] => [branch, ...branch.children.flatMap(descendants)]
export const branchState = (branch: PermissionBranch, access: Record<string, PermissionAccess>) => {
const selectable = descendants(branch).filter(item => permissionKind(item) !== 'field')
const selected = selectable.filter(item => (access[item.code] || 'HIDDEN') !== 'HIDDEN').length
return { checked: Boolean(selectable.length) && selected === selectable.length, indeterminate: selected > 0 && selected < selectable.length }
}
export const toggleBranch = (branch: PermissionBranch, checked: boolean, source: Record<string, PermissionAccess>, allowedCodes?: Set<string>) => {
const next = { ...source }
descendants(branch).forEach(item => {
if (allowedCodes && !allowedCodes.has(item.code)) return
const kind = permissionKind(item)
// Menu bulk actions never mutate field grants. Fields are managed in their
// own column and retain their explicit HIDDEN/READ/EDIT value.
if (kind === 'field') return
next[item.code] = checked ? (kind === 'action' ? 'EDIT' : 'READ') : 'HIDDEN'
})
return next
}
export const matchesPermission = (branch: PermissionBranch, query: string): boolean => {
const value = query.trim().toLocaleLowerCase()
return !value || `${branch.name} ${branch.code}`.toLocaleLowerCase().includes(value) || branch.children.some(child => matchesPermission(child, value))
}
export const hydrateRolePermissions = (value: Partial<RolePermissions> | undefined) => {
if (!value || typeof value !== 'object' || (!Array.isArray(value.permissionCodes) && !isAccessMap(value.permissionAccess) && !isAccessMap(value.fieldPermissions))) throw new Error('角色权限响应缺失或格式无效,已禁止保存。')
if ((value.permissionCodes !== undefined && !Array.isArray(value.permissionCodes)) || (value.permissionAccess !== undefined && !isAccessMap(value.permissionAccess)) || (value.fieldPermissions !== undefined && !isAccessMap(value.fieldPermissions))) throw new Error('角色权限响应格式无效,已禁止保存。')
if (value.permissionCodes !== undefined && !(value.permissionCodes as unknown[]).every(code => typeof code === 'string' && code.trim().length > 0)) throw new Error('角色权限编码列表必须是非空字符串数组,已禁止保存。')
for (const [mapName, map] of [['permissionAccess', value.permissionAccess], ['fieldPermissions', value.fieldPermissions]] as const) {
if (map === undefined) continue
for (const [code, level] of Object.entries(map)) {
if (!code.trim() || !['HIDDEN', 'READ', 'EDIT'].includes(String(level))) throw new Error(`角色权限${mapName}包含无效编码或权限值,已禁止保存。`)
}
}
const access: Record<string, PermissionAccess> = { ...(value?.permissionAccess || {}) }
if (!value?.permissionAccess) (value?.permissionCodes || []).forEach(code => { access[code] = 'EDIT' })
Object.entries(value?.fieldPermissions || {}).forEach(([code, level]) => { access[code] = level })
return access
}
const isAccessMap = (value: unknown): value is Record<string, PermissionAccess> => Boolean(value && typeof value === 'object' && !Array.isArray(value))
export const serializeRolePermissions = (access: Record<string, PermissionAccess>, catalog: PermissionItem[]): RolePermissions => {
const fields = new Set(catalog.filter(item => permissionKind(item) === 'field').map(item => item.code))
// Explicit HIDDEN values are revocations and must survive a round-trip.
const permissionAccess = { ...access }
const fieldPermissions = Object.fromEntries(Object.entries(access).filter(([code]) => fields.has(code))) as Record<string, PermissionAccess>
return { permissionAccess, permissionCodes: Object.entries(permissionAccess).filter(([code, level]) => !fields.has(code) && level !== 'HIDDEN').map(([code]) => code), fieldPermissions }
}
+31
View File
@@ -0,0 +1,31 @@
import { computed, ref, toValue, watch, type MaybeRefOrGetter, type WatchSource } from 'vue'
export const LIST_PAGE_SIZES = [10, 20, 50] as const
const DEFAULT_LIST_PAGE_SIZE = 20
export function useListPagination<T>(
source: MaybeRefOrGetter<readonly T[]>,
options: { resetSources?: WatchSource[]; initialPageSize?: number } = {},
) {
const page = ref(1)
const requestedSize = Number(options.initialPageSize)
const pageSize = ref<number>(LIST_PAGE_SIZES.includes(requestedSize as 10 | 20 | 50) ? requestedSize : DEFAULT_LIST_PAGE_SIZE)
const items = computed(() => toValue(source) || [])
const total = computed(() => items.value.length)
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
const clampPage = () => {
page.value = Math.min(Math.max(1, Math.trunc(Number(page.value) || 1)), totalPages.value)
}
const resetPage = () => { page.value = 1 }
const paginatedItems = computed(() => {
const start = (page.value - 1) * pageSize.value
return items.value.slice(start, start + pageSize.value)
})
watch(pageSize, resetPage, { flush: 'sync' })
watch(total, clampPage, { flush: 'sync' })
if (options.resetSources?.length) watch(options.resetSources, resetPage, { flush: 'sync' })
return { page, pageSize, total, totalPages, paginatedItems, resetPage, clampPage }
}
+41
View File
@@ -0,0 +1,41 @@
import type { DirectoryIdentity, GroupCandidate, UserGroup } from '@/api/admin'
export const isDefaultGroup = (group?: UserGroup | null) =>
Boolean(group && (group.groupCode === 'DEFAULT_EMPLOYEE' || group.membershipMode === 'DYNAMIC'))
export const isSuperAdminGroup = (group?: UserGroup | null) =>
group?.groupCode === 'SUPER_ADMIN_GROUP'
export const sortUserGroups = (groups: UserGroup[]) =>
[...groups].sort((left, right) => {
const rank = (group: UserGroup) => isDefaultGroup(group) ? 0 : isSuperAdminGroup(group) ? 1 : 2
return rank(left) - rank(right)
})
export const memberCountText = (count: number | null) => count === null ? '无法确认' : String(count)
export const belongsToCurrentGroup = (candidate: GroupCandidate, groupId: number) =>
candidate.assignedGroupId === groupId
export const candidateDisabled = (candidate: GroupCandidate, groupId: number) =>
!candidate.selectable || candidate.assignedGroupId !== null
export type MemberSelectionKey = string
export const localMemberKey = (id: number): MemberSelectionKey => `local:${id}`
export const directoryIdentityKey = (identity: DirectoryIdentity): MemberSelectionKey =>
`directory:${JSON.stringify([identity.generationId, identity.openId])}`
export const directoryIdentityPayload = (identity: DirectoryIdentity): DirectoryIdentity => ({
generationId: identity.generationId,
openId: identity.openId,
...(identity.userId == null ? {} : { userId: identity.userId }),
})
export const candidateKey = (candidate: GroupCandidate, baselineIds: ReadonlySet<number>): MemberSelectionKey => {
if (candidate.id !== null && baselineIds.has(candidate.id)) return localMemberKey(candidate.id)
if (candidate.directoryIdentity) return directoryIdentityKey(candidate.directoryIdentity)
if (candidate.id !== null) return `readonly-local:${candidate.id}`
return `readonly-directory:${JSON.stringify([candidate.realName, candidate.employeeNo ?? '', candidate.departmentNames ?? []])}`
}
+125
View File
@@ -0,0 +1,125 @@
import type { Directive } from 'vue'
type DragState = {
cleanupPointer?: () => void
observer: MutationObserver
onResize: () => void
onClose: () => void
}
const states = new WeakMap<HTMLDialogElement, DragState>()
const gap = 12
const interactiveSelector = 'button,input,select,textarea,a,[contenteditable="true"],[role="button"]'
const handleSelector = '[data-dialog-drag-handle],.modal-head,.route-dialog-head,.notification-modal-head'
const dragEnabled = () => window.matchMedia('(min-width: 761px)').matches
const resetPosition = (dialog: HTMLDialogElement) => {
dialog.style.removeProperty('left')
dialog.style.removeProperty('top')
dialog.style.removeProperty('right')
dialog.style.removeProperty('bottom')
dialog.style.removeProperty('margin')
dialog.dataset.dialogDragged = 'false'
}
const constrainPosition = (dialog: HTMLDialogElement) => {
if (!dialog.open || dialog.dataset.dialogDragged !== 'true') return
const rect = dialog.getBoundingClientRect()
const handle = dialog.querySelector<HTMLElement>(handleSelector)
const titleHeight = Math.max(44, handle?.getBoundingClientRect().height || 0)
const maxLeft = Math.max(gap, window.innerWidth - rect.width - gap)
const maxTop = Math.max(gap, window.innerHeight - Math.min(rect.height, titleHeight) - gap)
const left = Math.min(Math.max(gap, rect.left), maxLeft)
const top = Math.min(Math.max(gap, rect.top), maxTop)
dialog.style.left = `${left}px`
dialog.style.top = `${top}px`
}
export const dialogDrag: Directive<HTMLDialogElement> = {
mounted(dialog) {
const onPointerDown = (event: PointerEvent) => {
if (!dialog.open || !dragEnabled() || event.button !== 0 || !['mouse', 'pen'].includes(event.pointerType)) return
const target = event.target as HTMLElement
const handle = target.closest<HTMLElement>(handleSelector)
if (!handle || !dialog.contains(handle) || target.closest(interactiveSelector)) return
const state = states.get(dialog)
if (!state) return
state.cleanupPointer?.()
const rect = dialog.getBoundingClientRect()
const offsetX = event.clientX - rect.left
const offsetY = event.clientY - rect.top
dialog.style.margin = '0'
dialog.style.right = 'auto'
dialog.style.bottom = 'auto'
dialog.style.left = `${rect.left}px`
dialog.style.top = `${rect.top}px`
dialog.dataset.dialogDragged = 'true'
dialog.classList.add('is-dialog-dragging')
handle.setPointerCapture(event.pointerId)
const move = (moveEvent: PointerEvent) => {
if (moveEvent.pointerId !== event.pointerId) return
const width = dialog.offsetWidth
const height = dialog.offsetHeight
const titleHeight = Math.max(44, handle.offsetHeight)
const maxLeft = Math.max(gap, window.innerWidth - width - gap)
const maxTop = Math.max(gap, window.innerHeight - Math.min(height, titleHeight) - gap)
dialog.style.left = `${Math.min(Math.max(gap, moveEvent.clientX - offsetX), maxLeft)}px`
dialog.style.top = `${Math.min(Math.max(gap, moveEvent.clientY - offsetY), maxTop)}px`
}
let stopped = false
const stop = () => {
if (stopped) return
stopped = true
handle.removeEventListener('pointermove', move)
handle.removeEventListener('pointerup', stop)
handle.removeEventListener('pointercancel', stop)
handle.removeEventListener('lostpointercapture', stop)
try {
if (handle.hasPointerCapture(event.pointerId)) handle.releasePointerCapture(event.pointerId)
} catch { /* capture may already have been released by the browser */ }
dialog.classList.remove('is-dialog-dragging')
if (state.cleanupPointer === stop) state.cleanupPointer = undefined
constrainPosition(dialog)
}
state.cleanupPointer = stop
handle.addEventListener('pointermove', move)
handle.addEventListener('pointerup', stop)
handle.addEventListener('pointercancel', stop)
handle.addEventListener('lostpointercapture', stop)
event.preventDefault()
}
const onClose = () => {
const state = states.get(dialog)
state?.cleanupPointer?.()
dialog.classList.remove('is-dialog-dragging')
resetPosition(dialog)
}
const onResize = () => dragEnabled() ? constrainPosition(dialog) : resetPosition(dialog)
const observer = new MutationObserver(() => {
if (dialog.open) resetPosition(dialog)
else onClose()
})
const state: DragState = { observer, onResize, onClose }
states.set(dialog, state)
dialog.addEventListener('pointerdown', onPointerDown)
dialog.addEventListener('close', onClose)
window.addEventListener('resize', onResize)
observer.observe(dialog, { attributes: true, attributeFilter: ['open'] })
;(dialog as HTMLDialogElement & { __dialogDragPointerDown?: (event: PointerEvent) => void }).__dialogDragPointerDown = onPointerDown
},
unmounted(dialog) {
const state = states.get(dialog)
const element = dialog as HTMLDialogElement & { __dialogDragPointerDown?: (event: PointerEvent) => void }
if (element.__dialogDragPointerDown) dialog.removeEventListener('pointerdown', element.__dialogDragPointerDown)
state?.cleanupPointer?.()
state?.observer.disconnect()
if (state) {
dialog.removeEventListener('close', state.onClose)
window.removeEventListener('resize', state.onResize)
}
states.delete(dialog)
},
}
-373
View File
@@ -1,373 +0,0 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { parse } from '@vue/compiler-sfc'
import ts from 'typescript'
import { computed, ref, watch } from 'vue'
const source = path => readFileSync(new URL(path, import.meta.url), 'utf8')
const panel = parse(source('./components/FeishuDirectoryPanel.vue')).descriptor
const result = (overrides = {}) => ({ runId: 'new', state: 'SUCCEEDED', complete: true, applied: true, ...overrides })
const snapshot = (overrides = {}) => ({ configured: true, running: false, lastSuccessfulRunId: null, lastRun: null, ...overrides })
// Execute the actual setup state machine with injected API/lifecycle/timers.
// No DOM dependency; template/layout checks below supplement these tests.
function setup(api, permissions = ['system:feishu:sync']) {
let cleanup, scheduled
const events = []
const script = ts.transpileModule(panel.scriptSetup.content.replace(/^import .*$/gm, ''), {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },
}).outputText
const state = new Function('computed', 'ref', 'onMounted', 'onBeforeUnmount', 'defineEmits', 'useUserStore', 'feishuDirectoryApi', 'setTimeout', 'clearTimeout', `${script}\nreturn { refreshStatus, sync, syncDisabled, status, error, run, formatLocalDateTime };`)(
computed, ref, () => {}, fn => { cleanup = fn }, () => event => events.push(event),
() => ({ hasPermission: code => permissions.includes(code) }), api,
fn => { scheduled = fn; return 1 }, () => { scheduled = undefined },
)
return { ...state, events, cleanup: () => cleanup(), poll: () => scheduled?.() }
}
test('directory route and menu are permission-only entry points', () => {
const router = source('./router/index.ts')
const layout = source('./views/Layout.vue')
const page = parse(source('./views/FeishuDirectory.vue')).descriptor
assert.match(router, /path: 'feishu-directory'/)
assert.match(router, /name: 'FeishuDirectory'/)
assert.match(router, /permission: \['system:feishu:sync', 'system:feishu:bind'\]/)
assert.doesNotMatch(router.slice(router.indexOf("name: 'FeishuDirectory'"), router.indexOf("name: 'IntegrationConfig'")), /system:user:view|demo-local-session|legacy/i)
assert.match(layout, /v-if="canAccess\('feishu-directory'\)"[\s\S]*to="\/feishu-directory"/)
assert.match(layout, /'feishu-directory': \['system:feishu:sync', 'system:feishu:bind'\]/)
assert.match(page.template.content, /FeishuDirectoryPanel/)
assert.doesNotMatch(page.template.content, /FEISHU DIRECTORY|<h1>飞书通讯录<\/h1>|查看飞书通讯录同步状态和最近运行记录|通讯录设置/)
assert.doesNotMatch(page.scriptSetup.content, /canViewIntegration|system:integration:view/)
assert.doesNotMatch(page.template.content, /secret|credential|token/i)
})
test('directory timestamps use browser local time and safe fallbacks', () => {
const state = setup({ status: async () => snapshot() })
const previousTz = process.env.TZ
process.env.TZ = 'Asia/Shanghai'
try {
assert.equal(state.formatLocalDateTime('2026-01-02T03:04:05.000Z'), '2026-01-02 11:04:05')
} finally {
if (previousTz === undefined) delete process.env.TZ
else process.env.TZ = previousTz
}
assert.equal(state.formatLocalDateTime('not-a-date'), '—')
assert.equal(state.formatLocalDateTime(null, '暂无'), '暂无')
assert.match(panel.template.content, /formatLocalDateTime\(run\.startedAt/)
assert.match(panel.template.content, /本地时间/)
})
test('API uses unwrapped endpoints, no POST body and bounded-sync timeout headroom', () => {
const api = source('./api/feishuDirectory.ts')
assert.match(api, /DIRECTORY_SYNC_TIMEOUT = 360_000/)
assert.match(api, /request.post\('\/feishu\/directory\/sync', undefined, \{ timeout: DIRECTORY_SYNC_TIMEOUT, signal \}\)/)
assert.match(api, /request.get\('\/feishu\/directory\/status'/)
assert.match(api, /organization: \(signal\?[\s\S]*request.get\('\/feishu\/directory\/organization'/)
for (const field of ['email', 'mobile', 'jobTitle', 'employeeType', 'avatarUrl', 'employmentStatus']) assert.match(api, new RegExp(`\\b${field}\\b`))
assert.doesNotMatch(api, /eligibilityReason|eligible\??:/)
assert.doesNotMatch(api, /\/api\/feishu/)
})
test('organization API types expose Feishu IDs and detail fields', () => {
const api = source('./api/feishuDirectory.ts')
assert.match(api, /order: string\b/)
assert.match(api, /employeeType: number \| null/)
for (const field of ['userId', 'openId', 'email', 'mobile', 'jobTitle', 'avatarUrl', 'employmentStatus']) {
assert.match(api, new RegExp(`\\b${field}: string\\b`))
assert.doesNotMatch(api, new RegExp(`\\b${field}: string \\| null`))
}
assert.doesNotMatch(api, /employee(?:No|Number)/)
})
test('bind-only and missing permissions cannot submit; no legacy fallback', async () => {
for (const permissions of [[], ['system:feishu:bind']]) {
let posts = 0
const state = setup({ status: async () => snapshot(), sync: async () => { posts++ } }, permissions)
await state.refreshStatus()
await state.sync()
assert.equal(state.syncDisabled.value, true)
assert.equal(posts, 0)
}
assert.match(panel.template.content, /v-if="canSync"/)
assert.doesNotMatch(panel.scriptSetup.content, /legacyAdmin|useLegacyFallback|userType/)
const users = source('./views/Users.vue')
assert.doesNotMatch(users, /FeishuDirectoryPanel|refreshDirectoryData/)
})
test('organization tree renders departments and employees with safe empty and refresh states', () => {
const parsed = parse(source('./views/FeishuDirectory.vue'))
const { template, scriptSetup } = parsed.descriptor
assert.deepEqual(parsed.errors, [])
assert.match(template.content, /@committed="refreshOrganization"/)
assert.match(template.content, /class="organization-tree"[^>]*role="tree"/)
assert.match(template.content, /v-for="item in visibleDepartments"/)
assert.match(template.content, /aria-expanded=/)
assert.match(template.content, /class="department-members"/)
assert.match(template.content, /v-for="user in paginatedSelectedUsers"/)
assert.match(template.content, /class="pagination-footer"/)
assert.match(template.content, /<el-pagination[\s\S]*v-model:current-page="selectedPage"/)
assert.match(template.content, /v-model:page-size="pageSize"/)
assert.match(template.content, /:page-sizes="pageSizes"/)
assert.match(template.content, /:total="selectedUsers\.length"/)
assert.match(template.content, /layout="total, sizes, prev, pager, next, jumper"/)
assert.match(template.content, /@current-change="handlePageChange"/)
assert.match(template.content, /@size-change="handlePageSizeChange"/)
for (const field of ['userId', 'openId', 'jobTitle', 'email', 'mobile', 'employmentStatus', 'employeeType', 'avatarUrl']) assert.match(template.content, new RegExp(`user\\.${field}`))
assert.match(template.content, /user\.avatarUrl[\s\S]*:src="user\.avatarUrl"[\s\S]*:alt=/)
assert.match(template.content, /暂无组织架构|通讯录快照不可用/)
assert.match(template.content, /组织架构加载失败/)
assert.match(scriptSetup.content, /normalizeOrganization/)
assert.match(scriptSetup.content, /createsCycle/)
assert.match(scriptSetup.content, /descendantDepartmentIds/)
assert.match(scriptSetup.content, /departmentIds\.some/)
assert.match(scriptSetup.content, /const seen = new Set/)
assert.match(scriptSetup.content, /system:feishu:sync.*system:feishu:bind/)
assert.match(template.content, /userId[::][^<]*user\.userId/)
assert.match(template.content, /openId[::][^<]*user\.openId/)
assert.match(scriptSetup.content, /userId: userId \|\| '--'/)
assert.match(scriptSetup.content, /openId: openId \|\| '--'/)
assert.doesNotMatch(template.content + scriptSetup.content, /employee(?:No|Number)/)
assert.doesNotMatch(template.content + scriptSetup.content, /eligible|eligibilityReason|符合资格|不符合资格/)
assert.doesNotMatch(scriptSetup.content, /demo-local-session|legacyAdmin|useLegacyFallback|system:user:view/)
assert.doesNotMatch(panel.template.content + panel.scriptSetup.content, /符合资格|不符合资格|eligibilityReason/)
})
test('organization employee pagination is computed without DOM and layout keeps panels scrollable', () => {
const page = parse(source('./views/FeishuDirectory.vue')).descriptor
const script = ts.transpileModule(page.scriptSetup.content.replace(/^import .*$/gm, ''), {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },
}).outputText
const state = new Function('computed', 'ref', 'watch', 'onMounted', 'onBeforeUnmount', 'useUserStore', 'feishuDirectoryApi', `${script}\nreturn { applyOrganization, selectDepartment, selectedPage, pageSize, pageSizes, totalPages, selectedUsers, paginatedSelectedUsers, handlePageChange, handlePageSizeChange };`)(
computed,
ref,
watch,
() => {},
() => {},
() => ({ permissionsLoaded: false, permissionsError: '', hasPermission: () => false }),
{ organization: async () => ({}) },
)
const organization = {
snapshotState: 'FRESH',
departments: [
{ id: 'root', name: '总部', parentId: '', order: 0, memberCount: 25 },
{ id: 'other', name: '其他', parentId: '', order: 1, memberCount: 0 },
],
users: Array.from({ length: 25 }, (_, index) => ({
userId: `user-${index + 1}`,
openId: `open-${index + 1}`,
name: `员工${index + 1}`,
departmentIds: ['root'],
})),
}
state.applyOrganization(organization)
assert.equal(state.pageSize.value, 10)
assert.deepEqual(state.pageSizes, [10, 20, 50, 100])
assert.equal(state.selectedUsers.value.length, 25)
assert.equal(state.totalPages.value, 3)
assert.deepEqual(state.paginatedSelectedUsers.value.map(user => user.userId), ['user-1', 'user-2', 'user-3', 'user-4', 'user-5', 'user-6', 'user-7', 'user-8', 'user-9', 'user-10'])
state.handlePageChange(2)
assert.equal(state.selectedPage.value, 2)
assert.equal(state.paginatedSelectedUsers.value[0].userId, 'user-11')
state.handlePageChange(3)
assert.equal(state.selectedPage.value, 3)
assert.equal(state.paginatedSelectedUsers.value.length, 5)
state.handlePageChange(99)
assert.equal(state.selectedPage.value, 3)
state.handlePageChange(0)
assert.equal(state.selectedPage.value, 1)
state.handlePageChange(3)
state.handlePageSizeChange(20)
assert.equal(state.pageSize.value, 20)
assert.equal(state.selectedPage.value, 1)
assert.equal(state.totalPages.value, 2)
assert.equal(state.paginatedSelectedUsers.value.length, 20)
state.handlePageChange(99)
assert.equal(state.selectedPage.value, 2)
state.handlePageSizeChange(100)
assert.equal(state.pageSize.value, 100)
assert.equal(state.selectedPage.value, 1)
assert.equal(state.totalPages.value, 1)
state.applyOrganization(organization)
assert.equal(state.selectedPage.value, 1)
state.handlePageChange(2)
state.selectDepartment('other')
assert.equal(state.selectedPage.value, 1)
assert.equal(state.totalPages.value, 1)
const styles = page.styles.map(style => style.content).join('\n')
assert.match(styles, /\.directory-page \{[^}]*min-height: 100%/)
assert.match(styles, /\.organization-card \{[^}]*flex: 1 1 auto/)
assert.match(styles, /\.organization-layout \{[^}]*flex: 1 1 0/)
assert.match(styles, /\.organization-layout \{[^}]*height: auto[^}]*min-height: 0/)
assert.doesNotMatch(styles, /\.organization-layout \{[^}]*height: clamp\(/)
assert.match(styles, /min-height: 0/)
assert.match(styles, /\.member-list[^}]*overflow-y: auto/)
assert.match(styles, /\.pagination-footer[^}]*flex: none/)
})
test('department counts aggregate unique employees across descendants', () => {
const page = parse(source('./views/FeishuDirectory.vue')).descriptor
assert.match(page.template.content, /departmentMemberCounts\.get\(item\.node\.id\)/)
assert.match(page.scriptSetup.content, /const departmentMemberCounts = computed/)
assert.match(page.scriptSetup.content, /descendantDepartmentIds\.value\.get\(department\.id\)/)
assert.match(page.scriptSetup.content, /counts\.set\(department\.id, usersInDepartments\(ids\)\.length\)/)
const script = ts.transpileModule(page.scriptSetup.content.replace(/^import .*$/gm, ''), {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },
}).outputText
const state = new Function('computed', 'ref', 'watch', 'onMounted', 'onBeforeUnmount', 'useUserStore', 'feishuDirectoryApi', `${script}\nreturn { applyOrganization, departmentMemberCounts, selectedUsers };`)(
computed,
ref,
watch,
() => {},
() => {},
() => ({ permissionsLoaded: false, permissionsError: '', hasPermission: () => false }),
{ organization: async () => ({}) },
)
state.applyOrganization({
snapshotState: 'FRESH',
lastSuccessfulAt: null,
departments: [
{ id: 'root', name: '总部', parentId: '', order: 0, memberCount: 1 },
{ id: 'child', name: '子部门', parentId: 'root', order: 0, memberCount: 2 },
],
users: [
{ openId: 'open-root', userId: 'employee-root', name: '甲', email: '', mobile: '', jobTitle: '', employeeType: 1, avatarUrl: '', employmentStatus: '', departmentIds: ['root'] },
{ openId: 'open-child', userId: 'employee-child', name: '乙', email: '', mobile: '', jobTitle: '', employeeType: null, avatarUrl: '', employmentStatus: '', departmentIds: ['child'] },
{ openId: 'open-child-duplicate', userId: 'employee-child', name: '乙', email: '', mobile: '', jobTitle: '', employeeType: null, avatarUrl: '', employmentStatus: '', departmentIds: ['child'] },
],
})
assert.equal(state.departmentMemberCounts.value.get('root'), 2)
assert.equal(state.departmentMemberCounts.value.get('child'), 1)
assert.equal(state.selectedUsers.value.length, 2)
assert.equal(state.selectedUsers.value.find(user => user.userId === 'employee-root').employeeType, 1)
assert.equal(state.selectedUsers.value.find(user => user.userId === 'employee-child').employeeType, null)
})
test('organization normalization provides safe Feishu ID fallbacks and an ID-free deduplication key', () => {
const page = parse(source('./views/FeishuDirectory.vue')).descriptor
const script = ts.transpileModule(page.scriptSetup.content.replace(/^import .*$/gm, ''), {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },
}).outputText
const state = new Function('computed', 'ref', 'watch', 'onMounted', 'onBeforeUnmount', 'useUserStore', 'feishuDirectoryApi', `${script}\nreturn { applyOrganization, selectedUsers };`)(
computed,
ref,
watch,
() => {},
() => {},
() => ({ permissionsLoaded: false, permissionsError: '', hasPermission: () => false }),
{ organization: async () => ({}) },
)
state.applyOrganization({
snapshotState: 'FRESH',
lastSuccessfulAt: null,
departments: [{ id: 'root', name: '总部', parentId: '', order: 0, memberCount: 2 }],
users: [
{ name: '无 ID 员工', email: '', mobile: '', departmentIds: ['root'] },
{ name: '无 ID 员工', email: '', mobile: '', departmentIds: ['root'] },
],
})
assert.equal(state.selectedUsers.value.length, 1)
assert.equal(state.selectedUsers.value[0].userId, '--')
assert.equal(state.selectedUsers.value[0].openId, '--')
assert.equal(state.selectedUsers.value[0].jobTitle, '--')
assert.equal(state.selectedUsers.value[0].email, '--')
assert.equal(state.selectedUsers.value[0].mobile, '--')
assert.equal(state.selectedUsers.value[0].employmentStatus, '--')
assert.equal(state.selectedUsers.value[0].employeeType, null)
assert.match(page.template.content, /user\.employeeType \?\? '--'/)
})
test('department order stays precise for decimal strings and accepts legacy numbers', () => {
const page = parse(source('./views/FeishuDirectory.vue')).descriptor
const script = ts.transpileModule(page.scriptSetup.content.replace(/^import .*$/gm, ''), {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },
}).outputText
const state = new Function('computed', 'ref', 'watch', 'onMounted', 'onBeforeUnmount', 'useUserStore', 'feishuDirectoryApi', `${script}\nreturn { applyOrganization, departmentNodes };`)(
computed,
ref,
watch,
() => {},
() => {},
() => ({ permissionsLoaded: false, permissionsError: '', hasPermission: () => false }),
{ organization: async () => ({}) },
)
state.applyOrganization({
snapshotState: 'FRESH',
lastSuccessfulAt: null,
departments: [
{ id: 'larger', name: '较大', parentId: '', order: '9007199254740993', memberCount: 0 },
{ id: 'smaller', name: '较小', parentId: '', order: '9007199254740992', memberCount: 0 },
{ id: 'legacy', name: '旧版', parentId: '', order: 3, memberCount: 0 },
],
users: [],
})
assert.deepEqual(state.departmentNodes.value.map(node => [node.id, node.order]), [
['legacy', '3'],
['smaller', '9007199254740992'],
['larger', '9007199254740993'],
])
})
test('duplicate submits blocked and committed success emitted only once', async () => {
let resolve, posts = 0, current = snapshot()
const state = setup({ status: async () => current, sync: () => { posts++; return new Promise(done => { resolve = done }) } })
await state.refreshStatus()
const pending = state.sync()
await state.sync()
assert.equal(posts, 1)
assert.equal(state.syncDisabled.value, true)
current = snapshot({ lastSuccessfulRunId: 'new', lastRun: result() })
resolve(result())
await pending
assert.deepEqual(state.events, ['committed'])
assert.equal(state.syncDisabled.value, false)
})
test('timeout queries status, stays locked on status failure, then polls running to success', async () => {
let fail = false, current = snapshot(), reads = 0
const state = setup({ status: async () => { reads++; if (fail) throw Error('offline'); return current }, sync: async () => { fail = true; throw Error('timeout') } })
await state.refreshStatus()
await state.sync()
assert.equal(reads, 2)
assert.equal(state.syncDisabled.value, true)
assert.match(state.error.value, /重试查询状态/)
fail = false
current = snapshot({ running: true, lastRun: result({ state: 'RUNNING', applied: false }) })
await state.refreshStatus()
assert.equal(state.syncDisabled.value, true)
current = snapshot({ lastSuccessfulRunId: 'new', lastRun: result() })
await state.poll()
assert.deepEqual(state.events, ['committed'])
assert.equal(state.syncDisabled.value, false)
state.cleanup()
assert.equal(state.poll(), undefined)
})
test('failed run preserves last success and exposes server failure without success event', async () => {
let current = snapshot({ lastSuccessfulRunId: 'old', lastSuccessfulAt: 'yesterday' })
const failed = result({ state: 'FAILED', applied: false, complete: false, errorCode: 'LIMIT', errorMessage: '超出限制' })
const state = setup({ status: async () => current, sync: async () => { current = { ...current, lastRun: failed }; throw Error('503') } })
await state.refreshStatus()
await state.sync()
assert.deepEqual(state.events, [])
assert.equal(state.status.value.lastSuccessfulAt, 'yesterday')
assert.equal(state.run.value.errorCode, 'LIMIT')
assert.equal(state.syncDisabled.value, false)
})
test('unconfigured service is disabled; panel has accessible status, retry and wrapping layout', async () => {
const state = setup({ status: async () => snapshot({ configured: false }) })
await state.refreshStatus()
assert.equal(state.syncDisabled.value, true)
assert.match(panel.template.content, /aria-live="polite"/)
assert.match(panel.template.content, /role="alert"/)
assert.match(panel.template.content, /同步飞书员工资料与目录状态;不作为 OAuth 登录条件;同步失败不覆盖上次结果/)
assert.match(panel.styles[0].content, /flex-wrap: wrap/)
assert.match(panel.styles[0].content, /overflow-wrap: anywhere/)
assert.match(source('./views/Login.vue'), /通讯录同步用于员工资料与业务管理,不作为登录条件/)
})
-95
View File
@@ -1,95 +0,0 @@
// Structural layout regressions. Run with: node --test src/layout.test.mjs
// These checks do not replace viewport/browser measurements.
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { parse as parseVue } from '@vue/compiler-sfc'
import postcss from 'postcss'
const source = path => readFileSync(new URL(path, import.meta.url), 'utf8')
const css = postcss.parse(source('./assets/main.css'))
test('finance summary cards fill three columns without a vacant fourth track', () => {
assert.equal(declarations('.finance-kpis')['grid-template-columns'], 'repeat(3, minmax(0, 1fr))')
css.walkRules(rule => {
if (!rule.selector.split(',').map(selector => selector.trim()).includes('.finance-kpis')) return
if (rule.parent.type !== 'atrule') return
const tracks = rule.nodes.find(node => node.prop === 'grid-template-columns')?.value
assert.notEqual(tracks, 'repeat(2, minmax(0, 1fr))')
})
})
function declarations(selector, stylesheet = css, responsive = false) {
const values = {}
stylesheet.walkRules(selector, rule => {
if (!responsive && rule.parent.type === 'atrule') return
rule.walkDecls(declaration => { values[declaration.prop] = declaration.value })
})
return values
}
test('list pages opt in without fixed table or row heights', () => {
for (const name of ['Applications', 'FinanceReceipt', 'Payments', 'Sources', 'Logs', 'ExpenseTypes', 'Payees', 'Users']) {
const { descriptor, errors } = parseVue(source(`./views/${name}.vue`))
assert.deepEqual(errors, [])
assert.match(descriptor.template.content, /class="[^"]*page-content/)
}
assert.equal(declarations('.main-area').display, 'flex')
assert.equal(declarations('.main-area')['min-height'], '100vh')
assert.equal(declarations('.page-stage').flex, '1 0 auto')
assert.equal(declarations('.data-table').height, undefined)
assert.equal(declarations('.table-wrap')['overflow-x'], 'auto')
assert.match(source('./views/Applications.vue'), /role="tabpanel"\s+class="fill-list-card"/)
})
test('metadata tables have keyboard-accessible local scroll regions and loading states', () => {
for (const name of ['Sources', 'ExpenseTypes', 'Payees']) {
const template = parseVue(source(`./views/${name}.vue`)).descriptor.template.content
assert.match(template, /class="table-wrap"[^<]*tabindex="0"[^<]*role="region"[^<]*><table/)
assert.match(template, /v-else class="load-wrap" role="status"/)
}
})
test('group list starts full width and only splits when a group is selected', () => {
const text = source('./views/Users.vue')
const styles = postcss.parse(parseVue(text).descriptor.styles[0].content)
assert.match(text, /:class="\{ 'has-group-detail': selectedGroup \}"/)
assert.equal(declarations('.group-layout', styles)['grid-template-columns'], 'minmax(0, 1fr)')
assert.equal(declarations('.has-group-detail .group-layout', styles)['grid-template-columns'], 'minmax(0, .9fr) minmax(0, 1.1fr)')
assert.equal(declarations('.candidate-copy', styles)['min-width'], '0')
})
test('system management navigation is visible for admin, integration, or Feishu access', () => {
const template = parseVue(source('./views/Layout.vue')).descriptor.template.content
assert.match(template, /class="nav-group admin-nav" v-if="canAccess\('admin'\) \|\| canAccess\('integration'\) \|\| canAccess\('feishu-directory'\)"/)
assert.match(template, /<router-link v-if="canAccess\('admin'\)" to="\/users"/)
assert.match(template, /<router-link v-if="canAccess\('integration'\)" to="\/integration-config"/)
assert.match(template, /<router-link v-if="canAccess\('feishu-directory'\)" to="\/feishu-directory"/)
})
test('provider cards stretch with footer actions following a growing body', () => {
const styles = postcss.parse(parseVue(source('./views/IntegrationConfig.vue')).descriptor.styles[0].content)
assert.equal(declarations('.integration-grid', styles)['align-items'], 'stretch')
assert.match(declarations('.integration-grid', styles)['grid-template-columns'], /auto-fit/)
assert.equal(declarations('.integration-card', styles)['flex-direction'], 'column')
assert.equal(declarations('.integration-body', styles).flex, '1')
assert.equal(declarations('.integration-actions', styles)['margin-top'], 'auto')
})
test('expense rows have four field tracks and an action track only with a delete button', () => {
const tracks = declarations('.expense-item')['grid-template-columns']
assert.equal((tracks.match(/minmax\(/g) || []).length, 4)
assert.match(tracks, /^minmax\(160px,/)
assert.equal(declarations('.expense-item:has(> .remove-item)')['grid-template-columns'], `${tracks} 34px`)
const responsive = []
css.walkRules(rule => {
if (rule.parent.type === 'atrule' && rule.selector.includes('.expense-item:has')) {
responsive.push([rule.parent.params, rule.nodes.find(node => node.prop === 'grid-template-columns')?.value])
}
})
assert.deepEqual(responsive, [
['(max-width: 1180px)', 'repeat(2, minmax(0, 1fr))'],
['(max-width: 680px)', 'minmax(0, 1fr)'],
])
assert.equal(declarations('.side-panel').height, 'max-content')
assert.equal(declarations('.detail-layout')['grid-template-columns'], 'minmax(0, 1fr) 295px')
})
+2
View File
@@ -6,6 +6,7 @@ import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import App from './App.vue'
import router from './router'
import { dialogDrag } from './directives/dialogDrag'
import './assets/main.css'
const app = createApp(App)
@@ -18,4 +19,5 @@ for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.use(createPinia())
app.use(router)
app.use(ElementPlus, { locale: zhCn })
app.directive('dialog-drag', dialogDrag)
app.mount('#app')
@@ -0,0 +1,47 @@
import { describe, expect, it } from 'vitest'
import {
MAX_ATTACHMENT_SIZE,
attachmentFileValidationError,
attachmentIdsMissingMetadata,
expenseItemAttachmentMetadata,
hydratedAttachmentIds,
} from './reimbursementAttachments'
describe('attachment file policy', () => {
it.each(['receipt.pdf', 'scan.PNG', 'photo.jpeg', 'memo.doc', 'memo.docx', 'sheet.xls', 'sheet.xlsx'])(
'accepts supported file %s up to and including 50MB',
name => expect(attachmentFileValidationError({ name, size: MAX_ATTACHMENT_SIZE })).toBe(''),
)
it('rejects unsupported extensions and files over 50MB', () => {
expect(attachmentFileValidationError({ name: 'archive.zip', size: 20 })).toContain('不支持')
expect(attachmentFileValidationError({ name: 'large.pdf', size: MAX_ATTACHMENT_SIZE + 1 })).toContain('超过 50MB')
})
})
describe('saved attachment hydration', () => {
const item = {
id: 42,
attachmentIds: [7, 8, 9],
attachments: [{ id: 7, fileName: 'per-item.pdf', contentType: 'application/pdf', fileSize: 100 }],
}
const topLevel = [
{ id: 8, expenseItemId: '42', fileName: 'legacy.jpg', fileType: 'image/jpeg', fileSize: 200 },
{ id: 10, expenseItemId: 99, fileName: 'other-row.pdf', fileType: 'application/pdf', fileSize: 300 },
]
it('combines per-item metadata with matching legacy top-level metadata only', () => {
const metadata = expenseItemAttachmentMetadata(item, topLevel)
expect(metadata).toEqual([
item.attachments[0],
{ id: 8, fileName: 'legacy.jpg', contentType: 'image/jpeg', fileSize: 200 },
])
expect(hydratedAttachmentIds(item, metadata)).toEqual([7, 8, 9])
expect(attachmentIdsMissingMetadata(item.attachmentIds, metadata)).toEqual([9])
})
it('derives ids from visible metadata when an older detail omits attachmentIds', () => {
const metadata = expenseItemAttachmentMetadata({ id: 42 }, topLevel)
expect(hydratedAttachmentIds({ id: 42 }, metadata)).toEqual([8])
})
})
+77
View File
@@ -0,0 +1,77 @@
import type { ExpenseItem, ReimbursementFormAttachment } from '@/api/reimbursement'
export const MAX_ATTACHMENT_SIZE = 50 * 1024 * 1024
export const ATTACHMENT_ACCEPT = '.pdf,.png,.jpg,.jpeg,.doc,.docx,.xls,.xlsx,application/pdf,image/png,image/jpeg,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
const acceptedExtensions = new Set(['pdf', 'png', 'jpg', 'jpeg', 'doc', 'docx', 'xls', 'xlsx'])
export interface AttachmentMetadataCandidate {
id?: number | string
fileName?: string
contentType?: string
fileType?: string
fileSize?: number
expenseItemId?: number | string
}
export interface AttachmentFileCandidate {
name: string
size: number
}
const normalizeAttachment = (file: AttachmentMetadataCandidate): ReimbursementFormAttachment | null => {
if (file?.id == null || !file.fileName) return null
return {
id: file.id,
fileName: file.fileName,
contentType: file.contentType || file.fileType || '',
fileSize: Number(file.fileSize || 0),
}
}
/** Combines current per-item metadata with legacy application-level metadata. */
export const expenseItemAttachmentMetadata = (
item?: Partial<ExpenseItem>,
applicationAttachments: AttachmentMetadataCandidate[] = [],
): ReimbursementFormAttachment[] => {
const itemId = item?.id
const legacyMatches = itemId == null
? []
: applicationAttachments.filter(file => file?.expenseItemId != null && String(file.expenseItemId) === String(itemId))
const candidates: AttachmentMetadataCandidate[] = [
...(item?.attachments || []),
...(item?.attachmentMetadata || []),
...legacyMatches,
]
const unique = new Map<string, ReimbursementFormAttachment>()
candidates.forEach(candidate => {
const file = normalizeAttachment(candidate)
if (file && !unique.has(String(file.id))) unique.set(String(file.id), file)
})
return [...unique.values()]
}
export const hydratedAttachmentIds = (
item: Partial<ExpenseItem> | undefined,
metadata: ReimbursementFormAttachment[],
): Array<number | string> => {
const unique = new Map<string, number | string>()
const ids = [...(item?.attachmentIds || []), ...metadata.map(file => file.id)]
ids.forEach(id => unique.set(String(id), id))
return [...unique.values()]
}
export const attachmentIdsMissingMetadata = (
attachmentIds: Array<number | string>,
metadata: Array<{ id?: number | string }>,
): Array<number | string> => {
const visibleIds = new Set(metadata.filter(file => file.id != null).map(file => String(file.id)))
return attachmentIds.filter(id => !visibleIds.has(String(id)))
}
export const attachmentFileValidationError = (file: AttachmentFileCandidate): string => {
const extension = file.name.split('.').pop()?.toLowerCase() || ''
if (!acceptedExtensions.has(extension)) return '不支持该文件类型,请选择 PDF、PNG/JPEG、DOC/DOCX 或 XLS/XLSX 文件'
if (file.size > MAX_ATTACHMENT_SIZE) return '文件超过 50MB,无法上传'
return ''
}
+40 -40
View File
@@ -21,85 +21,91 @@ const routes: RouteRecordRaw[] = [
path: 'dashboard',
name: 'Dashboard',
component: () => import('@/views/Dashboard.vue'),
meta: { title: '工作台', permission: ['applications', 'reimbursement:view-own'] },
meta: { title: '工作台', permission: 'page.dashboard' },
},
{
path: 'applications',
name: 'Applications',
component: () => import('@/views/Applications.vue'),
meta: { title: '我的报销', permission: ['applications', 'reimbursement:view-own'], roles: ['EMPLOYEE', 'FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
meta: { title: '我的报销', permission: 'page.applications' },
},
{
path: 'applications/new',
name: 'ApplicationNew',
component: () => import('@/components/ReimbursementForm.vue'),
meta: { title: '发起报销', permission: 'reimbursement:create', roles: ['EMPLOYEE', 'FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
meta: { title: '发起报销', permission: 'page.application-create' },
},
{
path: 'applications/:id',
name: 'ApplicationDetail',
component: () => import('@/views/ApplicationDetail.vue'),
meta: { title: '报销单详情', hidden: true, permission: ['applications', 'reimbursement:view-own'], roles: ['EMPLOYEE', 'FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
meta: { title: '报销单详情', hidden: true, permission: 'page.applications' },
},
{
path: 'applications/:id/edit',
name: 'ApplicationEdit',
component: () => import('@/components/ReimbursementForm.vue'),
meta: { title: '编辑报销', hidden: true, permission: 'reimbursement:create', roles: ['EMPLOYEE', 'FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
meta: { title: '编辑报销', hidden: true, permission: 'page.application-edit' },
},
{
path: 'finance-receipt',
name: 'FinanceReceipt',
component: () => import('@/views/FinanceReceipt.vue'),
meta: { title: '财务待收单', permission: 'receipt:manage', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
meta: { title: '财务待收单', permission: 'page.finance-receipt' },
},
{
path: 'sources',
name: 'Sources',
component: () => import('@/views/Sources.vue'),
meta: { title: '业务单据', permission: 'reimbursement:view-all', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
meta: { title: '业务单据', permission: 'page.source-documents' },
},
{
path: 'payments',
name: 'Payments',
component: () => import('@/views/Payments.vue'),
meta: { title: '待付款', permission: 'payment:register', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
meta: { title: '待付款', permission: 'page.payments' },
},
{
path: 'kingdee-accounts',
redirect: { path: '/integration-config', query: { tab: 'kingdee' } },
},
{
path: 'logs',
name: 'Logs',
component: () => import('@/views/Logs.vue'),
meta: { title: '操作日志', permission: 'approval:view', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
meta: { title: '操作日志', permission: 'page.operation-log' },
},
{
path: 'expense-types',
name: 'ExpenseTypes',
component: () => import('@/views/ExpenseTypes.vue'),
meta: { title: '费用类型', permission: 'master-data:manage', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
meta: { title: '费用类型', permission: 'page.expense-types' },
},
{
path: 'payees',
name: 'Payees',
component: () => import('@/views/Payees.vue'),
meta: { title: '付款对象', permission: 'master-data:manage', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
meta: { title: '付款对象', permission: 'page.payees' },
},
{
path: 'users',
name: 'Users',
component: () => import('@/views/Users.vue'),
meta: { title: '用户管理', permission: 'system:user:view', roles: ['ADMIN', 'SUPER_ADMIN'] },
meta: { title: '人员与角色', permission: ['page.groups', 'page.roles', 'page.feishu-directory'] },
},
{
path: 'feishu-directory',
name: 'FeishuDirectory',
component: () => import('@/views/FeishuDirectory.vue'),
meta: { title: '飞书通讯录', permission: ['system:feishu:sync', 'system:feishu:bind'] },
redirect: { path: '/users', query: { tab: 'directory' } },
},
{
path: 'scheduled-tasks',
redirect: { path: '/integration-config', query: { tab: 'scheduled-tasks' } },
},
{
path: 'integration-config',
name: 'IntegrationConfig',
component: () => import('@/views/IntegrationConfig.vue'),
meta: { title: '配置管理', permission: 'system:integration:view', roles: ['ADMIN', 'SUPER_ADMIN'] },
meta: { title: '配置管理', permission: ['page.integration-config', 'page.kingdee-account-binding', 'page.scheduled-tasks'] },
},
],
},
@@ -111,7 +117,7 @@ router.beforeEach(async (to, _from, next) => {
const userStore = useUserStore()
const workbench = useWorkbenchStore()
const requiresAuth = to.matched.some(r => r.meta.requiresAuth)
const hadSession = Boolean(localStorage.getItem(TOKEN_KEY) || localStorage.getItem(AUTH_DAY_KEY) || userStore.token)
const hadSession = Boolean(sessionStorage.getItem(TOKEN_KEY) || localStorage.getItem(AUTH_DAY_KEY) || userStore.token)
const isOAuthCallback = to.path === '/login' && Boolean(to.query.token || to.query.code || to.query.error)
const dailyValid = userStore.ensureDailyAuth()
@@ -133,38 +139,32 @@ router.beforeEach(async (to, _from, next) => {
}
}
if (to.path === '/login' && token && !isOAuthCallback) return next('/dashboard')
if (to.path === '/login' && token && !isOAuthCallback && !to.query.permissionError && !to.query.denied) return next('/dashboard')
const requiredRoles = to.matched.flatMap(r => (r.meta.roles as string[] | undefined) || [])
const requiredPermissions = to.matched.flatMap(record => {
const permission = record.meta.permission as string | string[] | undefined
return permission ? (Array.isArray(permission) ? permission : [permission]) : []
})
const userType = userStore.userInfo?.userType || ''
const useLegacyFallback = token === DEMO_SESSION_TOKEN
// The directory is permission-only, including for the local demo session;
// never allow its route through the unrelated legacy role fallback.
const isFeishuDirectoryRoute = to.matched.some(record => record.name === 'FeishuDirectory')
// A real session is permission-first. Legacy userType checks are retained
// only for the local demo session or when the permission service itself is
// unavailable, so a custom role cannot be rejected by stale role metadata.
if (requiredPermissions.length > 0 && (!useLegacyFallback || isFeishuDirectoryRoute)) {
if (requiredPermissions.length > 0) {
try {
await userStore.loadPermissions()
} catch {
if (!requiredRoles.includes(userType)) {
return next({ path: '/dashboard', query: { denied: String(to.meta.title || '该页面') } })
}
return next({ path: '/login', query: { permissionError: '1' } })
}
if (userStore.permissionsLoaded && !userStore.permissionsError) {
if (!requiredPermissions.some(permission => userStore.hasPermission(permission))) {
return next({ path: '/dashboard', query: { denied: String(to.meta.title || '该页面') } })
}
}
} else if (requiredRoles.length > 0 && (!requiredPermissions.length || useLegacyFallback)) {
if (!requiredRoles.includes(userType)) {
return next({ path: '/dashboard', query: { denied: String(to.meta.title || '该页面') } })
if (!requiredPermissions.some(permission => userStore.canRead(permission))) {
const candidates = [
['/dashboard', 'page.dashboard'], ['/applications', 'page.applications'],
['/finance-receipt', 'page.finance-receipt'], ['/sources', 'page.source-documents'],
['/payments', 'page.payments'],
['/logs', 'page.operation-log'],
['/expense-types', 'page.expense-types'], ['/payees', 'page.payees'],
['/users', ['page.groups', 'page.roles', 'page.feishu-directory']],
['/integration-config', ['page.integration-config', 'page.kingdee-account-binding', 'page.scheduled-tasks']],
] as Array<[string, string | string[]]>
const first = candidates.find(([, code]) => (Array.isArray(code) ? code : [code]).some(userStore.canRead))?.[0]
if (!first) return next({ path: '/login', query: { denied: '无可访问页面' } })
if (first === to.path) return next(false)
return next({ path: first, query: { denied: String(to.meta.title || '该页面') } })
}
}
-12
View File
@@ -1,12 +0,0 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useAppStore = defineStore('app', () => {
const sidebarCollapsed = ref(false)
const loading = ref(false)
const notifications = ref(3)
const toggleSidebar = () => { sidebarCollapsed.value = !sidebarCollapsed.value }
return { sidebarCollapsed, loading, notifications, toggleSidebar }
})
+97 -26
View File
@@ -2,6 +2,7 @@ import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authApi, type UserProfile } from '@/api/auth'
import request from '@/api/request'
import type { PermissionAccess } from '@/api/admin'
import {
AUTH_DAY_KEY,
DEMO_SESSION_TOKEN,
@@ -26,19 +27,40 @@ const FEISHU_OAUTH_ATTEMPT_KEY = 'feishuOAuthAttempt'
const randomAttemptId = () => {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID()
return `${Date.now()}-${Math.random().toString(36).slice(2)}`
if (typeof crypto === 'undefined' || typeof crypto.getRandomValues !== 'function') {
throw new Error('当前浏览器不支持安全的登录校验,请使用 HTTPS 后重试')
}
const bytes = crypto.getRandomValues(new Uint8Array(16))
return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')
}
export const useUserStore = defineStore('user', () => {
const token = ref(localStorage.getItem(TOKEN_KEY) || '')
// Keep bearer credentials scoped to this browser tab/session, not durable localStorage.
const token = ref(sessionStorage.getItem(TOKEN_KEY) || '')
const userInfo = ref<UserProfile | null>(readStoredUser())
const permissionCodes = ref<string[]>([])
const fieldPermissions = ref<Record<string, 'HIDDEN' | 'READ' | 'EDIT'>>({})
const roleCodes = ref<string[]>([])
const fieldPermissions = ref<Record<string, PermissionAccess>>({})
const permissionAccess = ref<Record<string, PermissionAccess>>({})
const permissionsLoaded = ref(false)
const permissionsError = ref('')
let permissionRequest: Promise<void> | null = null
let permissionGeneration = 0
let sessionVersion = 0
const clearPermissions = (invalidateRequests = true) => {
if (invalidateRequests) {
permissionGeneration += 1
permissionRequest = null
}
permissionCodes.value = []
roleCodes.value = []
fieldPermissions.value = {}
permissionAccess.value = {}
permissionsLoaded.value = false
permissionsError.value = ''
}
const isLoggedIn = computed(() => !!token.value)
const isFinance = computed(() => ['FINANCE', 'ADMIN', 'SUPER_ADMIN'].includes(userInfo.value?.userType || ''))
@@ -53,9 +75,11 @@ export const useUserStore = defineStore('user', () => {
const completeLogin = (jwt: string, user: UserProfile) => {
if (!jwt || !isValidUser(user)) throw new Error('登录响应缺少有效身份信息')
sessionVersion += 1
clearPermissions()
token.value = jwt
userInfo.value = user
localStorage.setItem(TOKEN_KEY, jwt)
sessionStorage.setItem(TOKEN_KEY, jwt)
localStorage.removeItem(TOKEN_KEY)
localStorage.setItem(USER_INFO_KEY, JSON.stringify(user))
saveAuthDay()
}
@@ -96,9 +120,11 @@ export const useUserStore = defineStore('user', () => {
const setToken = async (jwt: string) => {
if (!jwt) throw new Error('登录响应缺少有效令牌')
sessionVersion += 1
clearPermissions()
token.value = jwt
userInfo.value = null
localStorage.setItem(TOKEN_KEY, jwt)
sessionStorage.setItem(TOKEN_KEY, jwt)
localStorage.removeItem(TOKEN_KEY)
localStorage.removeItem(USER_INFO_KEY)
await fetchUserInfo()
// fetchUserInfo validates the callback token and user before this marker
@@ -111,7 +137,7 @@ export const useUserStore = defineStore('user', () => {
const requestToken = token.value
if (!requestToken) throw new Error('未登录')
const response = await authApi.refreshToken()
if (requestVersion !== sessionVersion || token.value !== requestToken || localStorage.getItem(TOKEN_KEY) !== requestToken) {
if (requestVersion !== sessionVersion || token.value !== requestToken || sessionStorage.getItem(TOKEN_KEY) !== requestToken) {
throw new Error('登录状态已更新,请重新登录')
}
completeLogin(response.token, response.user)
@@ -120,7 +146,7 @@ export const useUserStore = defineStore('user', () => {
const fetchUserInfo = async () => {
const requestVersion = sessionVersion
const requestToken = token.value || localStorage.getItem(TOKEN_KEY) || ''
const requestToken = token.value || sessionStorage.getItem(TOKEN_KEY) || ''
if (!requestToken) {
logout()
throw new Error('未登录')
@@ -128,7 +154,7 @@ export const useUserStore = defineStore('user', () => {
try {
const user = await authApi.getUserInfo()
if (requestVersion !== sessionVersion || token.value !== requestToken || localStorage.getItem(TOKEN_KEY) !== requestToken) {
if (requestVersion !== sessionVersion || token.value !== requestToken || sessionStorage.getItem(TOKEN_KEY) !== requestToken) {
throw new Error('登录状态已更新,请重新加载页面')
}
if (!isValidUser(user)) throw new Error('用户信息无效')
@@ -137,7 +163,7 @@ export const useUserStore = defineStore('user', () => {
return user
} catch (error) {
// Do not let a late response from an old session clear a newer login.
if (requestVersion === sessionVersion && token.value === requestToken && localStorage.getItem(TOKEN_KEY) === requestToken) logout()
if (requestVersion === sessionVersion && token.value === requestToken && sessionStorage.getItem(TOKEN_KEY) === requestToken) logout()
throw error
}
}
@@ -148,16 +174,17 @@ export const useUserStore = defineStore('user', () => {
* migration when it already has a complete locally-verified user object.
*/
const ensureDailyAuth = (): boolean => {
const storedToken = localStorage.getItem(TOKEN_KEY) || ''
const storedToken = sessionStorage.getItem(TOKEN_KEY) || ''
const storedDay = localStorage.getItem(AUTH_DAY_KEY)
const storedUser = readStoredUser()
if (!storedToken) {
const hadState = Boolean(token.value || userInfo.value || storedUser || storedDay)
const hadState = Boolean(token.value || userInfo.value || storedUser || storedDay || permissionsLoaded.value || permissionRequest)
token.value = ''
userInfo.value = null
if (hadState) {
sessionVersion += 1
clearPermissions()
clearStoredSession()
}
return false
@@ -167,6 +194,10 @@ export const useUserStore = defineStore('user', () => {
// writes its complete token/user pair synchronously. Give that pair a
// marker on first use, while still rejecting any explicitly stale marker.
if (!storedDay && storedToken === DEMO_SESSION_TOKEN && isValidUser(storedUser)) {
if (token.value !== storedToken) {
sessionVersion += 1
clearPermissions()
}
token.value = storedToken
userInfo.value = storedUser
saveAuthDay()
@@ -175,12 +206,17 @@ export const useUserStore = defineStore('user', () => {
if (storedDay !== getBusinessDay()) {
sessionVersion += 1
clearPermissions()
clearStoredSession()
token.value = ''
userInfo.value = null
return false
}
if (token.value !== storedToken) {
sessionVersion += 1
clearPermissions()
}
token.value = storedToken
userInfo.value = storedUser
return true
@@ -188,43 +224,72 @@ export const useUserStore = defineStore('user', () => {
const logout = () => {
sessionVersion += 1
clearPermissions()
token.value = ''
userInfo.value = null
permissionCodes.value = []
fieldPermissions.value = {}
permissionsLoaded.value = false
permissionsError.value = ''
clearStoredSession()
}
const loadPermissions = async (force = false) => {
if (!force && permissionsLoaded.value && !permissionsError.value) return
if (permissionRequest && !force) return permissionRequest
permissionRequest = (async () => {
permissionsError.value = ''
const requestGeneration = ++permissionGeneration
const requestSessionVersion = sessionVersion
const requestToken = token.value
clearPermissions(false)
let currentRequest!: Promise<void>
const isCurrentRequest = () => requestGeneration === permissionGeneration
&& requestSessionVersion === sessionVersion
&& requestToken === token.value
currentRequest = (async () => {
try {
const result = await request.get<{
roleCodes?: string[]
permissionCodes?: string[]
fieldPermissions?: Record<string, 'HIDDEN' | 'READ' | 'EDIT'>
fieldPermissions?: Record<string, PermissionAccess>
permissionAccess?: Record<string, PermissionAccess>
}>('/roles/current-permissions')
permissionCodes.value = Array.isArray(result?.permissionCodes) ? result.permissionCodes : []
fieldPermissions.value = result?.fieldPermissions || {}
if (!isCurrentRequest()) return
const nextPermissionCodes = Array.isArray(result?.permissionCodes) ? result.permissionCodes : []
const nextRoleCodes = Array.isArray(result?.roleCodes) ? result.roleCodes : []
const validLevel = (value: unknown): value is PermissionAccess => value === 'HIDDEN' || value === 'READ' || value === 'EDIT'
const nextFieldPermissions = Object.fromEntries(Object.entries(result?.fieldPermissions || {}).filter((entry): entry is [string, PermissionAccess] => validLevel(entry[1])))
const suppliedAccess = Object.fromEntries(Object.entries(result?.permissionAccess || {}).filter((entry): entry is [string, PermissionAccess] => validLevel(entry[1])))
// Old responses carry only granted codes and field levels. Project them
// into the new access model without granting anything that was absent.
const hasAccessContract = Boolean(result && Object.prototype.hasOwnProperty.call(result, 'permissionAccess'))
const nextPermissionAccess = hasAccessContract
? suppliedAccess
: {
...Object.fromEntries(nextPermissionCodes.map(code => [code, 'EDIT' as PermissionAccess])),
...nextFieldPermissions,
}
if (!isCurrentRequest()) return
permissionCodes.value = nextPermissionCodes
roleCodes.value = nextRoleCodes
fieldPermissions.value = nextFieldPermissions
permissionAccess.value = nextPermissionAccess
permissionsLoaded.value = true
} catch (error) {
permissionCodes.value = []
fieldPermissions.value = {}
permissionsLoaded.value = false
if (!isCurrentRequest()) return
clearPermissions(false)
permissionsError.value = error instanceof Error ? error.message : '权限加载失败'
throw error
} finally {
permissionRequest = null
if (isCurrentRequest() && permissionRequest === currentRequest) permissionRequest = null
}
})()
return permissionRequest
permissionRequest = currentRequest
return currentRequest
}
const hasPermission = (code: string) => permissionsLoaded.value && !permissionsError.value && permissionCodes.value.includes(code)
const access = (code: string): PermissionAccess => permissionsLoaded.value && !permissionsError.value
? (permissionAccess.value[code] || 'HIDDEN')
: 'HIDDEN'
const canRead = (code: string) => access(code) === 'READ' || access(code) === 'EDIT'
const canEdit = (code: string) => access(code) === 'EDIT'
const canAny = (codes: string[]) => codes.some(canRead)
const hasPermission = canRead
return {
token,
@@ -241,11 +306,17 @@ export const useUserStore = defineStore('user', () => {
fetchUserInfo,
ensureDailyAuth,
permissionCodes,
roleCodes,
fieldPermissions,
permissionAccess,
permissionsLoaded,
permissionsError,
loadPermissions,
hasPermission,
access,
canRead,
canEdit,
canAny,
logout,
}
})
+26 -7
View File
@@ -1,6 +1,6 @@
import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { accountsPayableApi, cashierApi, reimbursementApi, type CreateApplicationRequest, type PaymentRecord, type ReimApplicationDetail, type ReimApplicationSummary } from '@/api/reimbursement'
import { accountsPayableApi, cashierApi, reimbursementApi, type ApprovalRoutePreview, type CreateApplicationRequest, type PaymentRecord, type ReimApplicationDetail, type ReimApplicationSummary } from '@/api/reimbursement'
import { cloneFallback, createFallbackDetail, fallbackLogin, type FallbackUser } from '@/api/fallback'
export type DataSource = 'connecting' | 'api' | 'fallback' | 'error'
@@ -93,7 +93,7 @@ export const useWorkbenchStore = defineStore('workbench', () => {
}
}
const loadList = async () => { if (reimbursements.value.length) return; await load() }
const loadDetail = async (id: string | number) => {
const loadDetail = async (id: string | number, options?: { strict?: boolean }) => {
const requestVersion = sessionVersion
await loadList()
if (requestVersion !== sessionVersion) return null
@@ -102,12 +102,15 @@ export const useWorkbenchStore = defineStore('workbench', () => {
const detail = await reimbursementApi.getDetail(id)
if (requestVersion !== sessionVersion) return null
const normalized = normalize(detail)
reimbursements.value = reimbursements.value.map(item => String(item.id) === String(id) ? normalized : item)
reimbursements.value = reimbursements.value.some(item => String(item.id) === String(id))
? reimbursements.value.map(item => String(item.id) === String(id) ? normalized : item)
: [...reimbursements.value, normalized]
const detailPayments = (detail.payments || []).map((payment: any) => normalizePayment({ ...payment, applicationId: id }))
payments.value = payments.value.filter(payment => String(payment.applicationId) !== String(id)).concat(detailPayments)
refreshPaymentStatuses()
return normalized
} catch {
} catch (error) {
if (options?.strict) throw error
return getById(id)
}
}
@@ -149,10 +152,26 @@ export const useWorkbenchStore = defineStore('workbench', () => {
const local = () => { const existing = id ? getById(id) : null; if (existing && (existing.applicantName !== user.value?.realName || !['草稿', '退回', '已取消'].includes(existing.approvalStatus === '退回' ? '退回' : existing.approvalStatus === '已取消' ? '已取消' : existing.applicationStatus))) throw new Error('只能修改本人草稿、退回或已取消的报销'); const result = existing ? normalize({ ...existing, ...payload, expenseItems: payload.items }) : createFallbackDetail(payload, `BX${new Date().toISOString().slice(0, 10).replace(/-/g, '')}${String(Date.now()).slice(-4)}`, user.value || fallbackLogin().user); if (existing) reimbursements.value = reimbursements.value.map(item => item.id === existing.id ? result : item); else reimbursements.value.unshift(result); return result }
const result = await saveMutation(() => id ? reimbursementApi.update(id, payload) : reimbursementApi.create(payload), local); if (requestVersion !== sessionVersion) throw new Error('登录状态已更新,请重新加载页面'); if (source.value !== 'fallback') { const normalized = normalize(result); if (id) reimbursements.value = reimbursements.value.map(item => String(item.id) === String(id) ? normalized : item); else reimbursements.value.unshift(normalized); return normalized } return result
}
const submit = async (id: string | number) => { const requestVersion = sessionVersion; const local = () => { const item = getById(id); if (!item) throw new Error('报销单不存在'); if (item.applicantName !== user.value?.realName) throw new Error('只能提交本人报销'); if (item.applicationStatus !== '草稿' && item.approvalStatus !== '退回' && item.approvalStatus !== '已取消') throw new Error('只能提交草稿、退回或已取消报销'); item.applicationStatus = '已提交'; item.approvalStatus = '审批中'; item.currentApprovalNode = '部门负责人审批'; return item }; const result = await saveMutation(() => reimbursementApi.submit(id), local); if (requestVersion !== sessionVersion) throw new Error('登录状态已更新,请重新加载页面'); if (source.value !== 'fallback' && result) { const normalized = normalize(result); reimbursements.value = reimbursements.value.map(item => String(item.id) === String(id) ? normalized : item); return normalized } return result }
const previewRoute = async (id: string | number): Promise<ApprovalRoutePreview> => {
if (source.value !== 'fallback') return reimbursementApi.getRoutePreview(id)
const item = getById(id)
if (!item) throw new Error('报销单不存在')
return {
applicationId: id,
source: 'LOCAL',
nodes: [{ order: 1, nodeKey: 'department-manager', nodeName: '部门负责人审批', approverLabels: ['部门负责人'], dynamic: false }],
routeFingerprint: `local-${id}`,
previewToken: `local-preview-${id}-${Date.now()}`,
expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(),
staleSnapshot: false,
exact: false,
warning: '当前为本地开发数据,预计审批路径仅用于界面演示。',
}
}
const submit = async (id: string | number, previewToken: string) => { const requestVersion = sessionVersion; if (!previewToken) throw new Error('审批路线预览已失效,请重新预览'); const local = () => { const item = getById(id); if (!item) throw new Error('报销单不存在'); if (item.applicantName !== user.value?.realName) throw new Error('只能提交本人报销'); if (item.applicationStatus !== '草稿' && item.approvalStatus !== '退回' && item.approvalStatus !== '已取消') throw new Error('只能提交草稿、退回或已取消报销'); item.applicationStatus = '已提交'; item.approvalStatus = '审批中'; item.currentApprovalNode = '部门负责人审批'; return item }; const result = await saveMutation(() => reimbursementApi.submit(id, { previewToken }), local); if (requestVersion !== sessionVersion) throw new Error('登录状态已更新,请重新加载页面'); if (source.value !== 'fallback' && result) { const normalized = normalize(result); reimbursements.value = reimbursements.value.map(item => String(item.id) === String(id) ? normalized : item); return normalized } return result }
const receive = async (id: string | number) => { const requestVersion = sessionVersion; const item = getById(id); if (!item) throw new Error('报销单不存在'); if (item.approvalStatus !== '审批通过') throw new Error('仅审批通过的报销可以收单'); if (source.value === 'fallback') { if (!['FINANCE', 'ADMIN', 'SUPER_ADMIN'].includes(user.value?.userType || '')) throw new Error('仅财务人员可以确认收单'); item.receiptStatus = '已收单'; item.updatedAt = new Date().toISOString(); return item } const result = await reimbursementApi.receive(id); if (requestVersion !== sessionVersion) throw new Error('登录状态已更新,请重新加载页面'); const normalized = normalize(result); reimbursements.value = reimbursements.value.map(row => String(row.id) === String(id) ? normalized : row); return normalized }
const pay = async (id: string | number, amount: number, remark: string, idempotencyKey: string) => { const requestVersion = sessionVersion; const item = getById(id); if (!item) throw new Error('报销单不存在'); if (item.receiptStatus !== '已收单') throw new Error('申请尚未完成财务收单,无法付款'); if (!(amount > 0) || amount > balance(item) + 0.005) throw new Error(`付款金额须大于 0 且不超过未付余额 ¥ ${balance(item).toFixed(2)}`); const local = () => { const previous = fallbackPaymentKeys.get(idempotencyKey); if (previous) return previous; const record: PaymentRecord = { id: `PAY-${Date.now()}`, paymentNo: `PAY-${new Date().toISOString().slice(0, 10).replace(/-/g, '')}-${String(Date.now()).slice(-4)}`, applicationId: id, paymentAmount: amount, totalAmount: item.totalAmount, paidAmount: amount, remainingAmount: balance(item) - amount, paymentMethod: '银行转账', paymentStatus: '有效', operatorName: user.value?.realName || '财务人员', paymentTime: new Date().toISOString().slice(0, 16).replace('T', ' '), remark: remark || idempotencyKey }; fallbackPaymentKeys.set(idempotencyKey, record); payments.value.unshift(record); refreshPaymentStatuses(); return record }; const result = await saveMutation(() => (amount < balance(item) ? cashierApi.partialPayment(id, amount, remark, idempotencyKey) : cashierApi.executePayment(id, amount, remark, idempotencyKey)), local); if (requestVersion !== sessionVersion) throw new Error('登录状态已更新,请重新加载页面'); if (source.value !== 'fallback') { const record = normalizePayment({ ...(result || {}), applicationId: id, paymentStatus: result?.paymentStatus || result?.status || '有效', totalAmount: item.totalAmount }); payments.value.unshift(record); refreshPaymentStatuses() } return result }
const reset = () => { sessionVersion += 1; queueVersions.receipt += 1; queueVersions.payment += 1; loadPromise = null; user.value = null; reimbursements.value = []; payments.value = []; source.value = 'connecting'; loading.value = false; error.value = ''; financeQueueError.value = ''; notifications.value = 0; fallbackPaymentKeys.clear() }
const loginFallback = (employeeNo?: string) => { reset(); const result = fallbackLogin(employeeNo); user.value = result.user; localStorage.setItem('token', result.token); localStorage.setItem('userInfo', JSON.stringify(result.user)); return result }
return { user, reimbursements, payments, source, loading, error, financeQueueError, notifications, summaries, balance, paidAmount, load, loadList, loadDetail, loadFinanceQueue, getById, save, submit, receive, pay, loginFallback, reset, refreshPaymentStatuses }
const loginFallback = (employeeNo?: string) => { reset(); const result = fallbackLogin(employeeNo); user.value = result.user; sessionStorage.setItem('token', result.token); localStorage.removeItem('token'); localStorage.setItem('userInfo', JSON.stringify(result.user)); return result }
return { user, reimbursements, payments, source, loading, error, financeQueueError, notifications, summaries, balance, paidAmount, load, loadList, loadDetail, loadFinanceQueue, getById, save, previewRoute, submit, receive, pay, loginFallback, reset, refreshPaymentStatuses }
})
+4 -1
View File
@@ -33,9 +33,12 @@ export const saveAuthDay = (day = getBusinessDay()) => {
}
export const clearStoredSession = () => {
localStorage.removeItem(TOKEN_KEY)
sessionStorage.removeItem(TOKEN_KEY)
localStorage.removeItem(TOKEN_KEY) // purge credentials persisted by older builds
localStorage.removeItem(USER_INFO_KEY)
localStorage.removeItem(AUTH_DAY_KEY)
// Also clear credentials from any sessionStorage-based intermediate builds.
sessionStorage.removeItem(USER_INFO_KEY)
}
const millisecondsUntilNextBusinessDay = () => {
+61
View File
@@ -0,0 +1,61 @@
/** Money amount rules aligned with DECIMAL(18,2) and normal reimbursement UX. */
export const MONEY_MAX = 99_999_999.99
export const MONEY_MIN = 0.01
const MONEY_PATTERN = /^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/
export type MoneyAmountIssue =
| 'empty'
| 'invalid'
| 'non_positive'
| 'too_many_decimals'
| 'too_large'
const MESSAGES: Record<MoneyAmountIssue, string> = {
empty: '请填写金额',
invalid: '金额须为有效数字,例如 128.50',
non_positive: '金额须大于 0',
too_many_decimals: '金额最多保留两位小数',
too_large: `单笔金额不能超过 ${MONEY_MAX.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} 元`,
}
export const moneyAmountMessage = (issue: MoneyAmountIssue, label = '金额') => {
if (issue === 'empty') return `请填写${label}`
if (issue === 'invalid') return `${label}须为有效数字,例如 128.50`
if (issue === 'non_positive') return `${label}须大于 0`
if (issue === 'too_many_decimals') return `${label}最多保留两位小数`
if (issue === 'too_large') {
return `${label}不能超过 ${MONEY_MAX.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} 元`
}
return MESSAGES[issue]
}
/** Inspect a typed amount (input string or numeric model). */
export const inspectMoneyAmount = (value: unknown): MoneyAmountIssue | null => {
if (value == null || value === '') return 'empty'
if (typeof value === 'number') {
if (!Number.isFinite(value)) return 'invalid'
if (value <= 0) return 'non_positive'
if (Math.round(value * 100) / 100 !== value) return 'too_many_decimals'
if (value > MONEY_MAX) return 'too_large'
return null
}
const text = String(value).trim()
if (!text) return 'empty'
if (/[eE]/.test(text) || !/^-?\d/.test(text)) return 'invalid'
if (text.startsWith('-')) return 'non_positive'
if (!/^\d+(\.\d+)?$/.test(text)) return 'invalid'
if (text.includes('.') && text.split('.')[1].length > 2) return 'too_many_decimals'
if (!MONEY_PATTERN.test(text)) return 'invalid'
const amount = Number(text)
if (!Number.isFinite(amount)) return 'invalid'
if (amount <= 0) return 'non_positive'
if (amount > MONEY_MAX) return 'too_large'
return null
}
export const normalizeMoneyAmount = (value: unknown): number => {
const issue = inspectMoneyAmount(value)
if (issue) return 0
const amount = typeof value === 'number' ? value : Number(String(value).trim())
return Math.round(amount * 100) / 100
}
+154 -12
View File
@@ -1,27 +1,169 @@
<template>
<div>
<div class="page-head"><div><span class="eyebrow">REIMBURSEMENT DETAIL</span><h1>报销单详情</h1><p>{{ item ? `${item.applicationNo} · ${item.title}` : `单号:${route.params.id}` }}</p></div><div class="head-actions"><button class="btn" @click="router.back()">← 返回</button><button v-if="item" class="btn" @click="print">打印详情</button><router-link v-if="canEdit" class="btn primary" :to="editRoute">{{ item?.approvalStatus === '退回' ? '补充材料' : '编辑草稿' }}</router-link></div></div>
<div v-if="store.loading" class="load-wrap"><span class="loader"></span><p>正在读取报销详情…</p></div>
<div class="page-head"><div><span class="eyebrow">REIMBURSEMENT DETAIL</span><h1>报销单详情</h1><p>{{ item ? `${item.applicationNo} · ${item.title}` : `单号:${route.params.id}` }}</p></div><div class="head-actions"><button class="btn" @click="router.back()">← 返回</button><button v-if="item" class="btn" @click="print">打印详情</button><router-link v-if="canEdit && userStore.canEdit('reimbursement.application.edit') && userStore.canRead('page.application-edit')" class="btn primary" :to="editRoute">{{ item?.approvalStatus === '退回' ? '补充信息' : '编辑草稿' }}</router-link></div></div>
<div v-if="detailLoading" class="load-wrap" role="status"><span class="loader"></span><p>正在读取报销详情…</p></div>
<div v-else-if="detailError" class="card empty-state" role="alert"><strong>报销详情加载失败</strong><span>{{ detailError }}</span><button class="btn" type="button" @click="loadDetail">重新加载</button><router-link class="btn" to="/applications">返回我的报销</router-link></div>
<div v-else-if="!item" class="card empty-state"><strong>未找到该报销单</strong><span>单号「{{ route.params.id }}」不存在或已被删除,请返回我的报销重试。</span><router-link class="btn" to="/applications">返回我的报销</router-link></div>
<template v-else>
<div v-if="item.approvalStatus === '退回'" class="inline-alert danger" role="alert"><b>!</b><span><strong>审批退回,需补充材料</strong><br>{{ item.returnReason || '请查看审批意见' }}</span><router-link class="btn small" :to="`/applications/${item.id}/edit`">去补充</router-link></div>
<div v-if="item.approvalStatus === '退回'" class="inline-alert danger" role="alert"><b>!</b><span><strong>审批退回,需补充信息</strong><br>{{ item.returnReason || '请查看审批意见' }}</span><router-link v-if="userStore.canEdit('reimbursement.application.edit') && userStore.canRead('page.application-edit')" class="btn small" :to="`/applications/${item.id}/edit`">去补充</router-link></div>
<div class="detail-layout"><div>
<div class="status-strip" aria-label="报销流程独立状态"><div><small>申请状态</small><span class="tag" :class="tone(item.applicationStatus)">{{ item.applicationStatus }}</span></div><div><small>审批状态</small><span class="tag" :class="tone(item.approvalStatus)">{{ item.approvalStatus }}</span></div><div><small>收单状态</small><span class="tag" :class="tone(item.receiptStatus)">{{ item.receiptStatus }}</span></div><div><small>付款状态</small><span class="tag" :class="tone(item.paymentStatus)">{{ item.paymentStatus }}</span></div></div>
<div class="workflow" aria-label="报销流程"><div v-for="(step,index) in workflow" :key="step.name" class="workflow-step" :class="step.tone"><span>{{ index + 1 }}</span><div><strong>{{ step.name }}</strong><small>{{ step.value }}</small></div></div></div>
<section class="section-card"><div class="section-title"><h2>报销信息</h2><span>{{ item.category }}</span></div><div class="form-grid"><div class="field"><label>报销人 / 部门</label><input readonly :value="`${item.applicantName} / ${item.departmentName}`"></div><div class="field"><label>费用类型</label><input readonly :value="`${item.expenseTypeName} · ${item.category}`"></div><div class="field"><label>申请金额</label><input readonly :value="money(item.totalAmount)"></div><div class="field"><label>申请日期</label><input readonly :value="item.createdAt?.slice(0,10) || '-' "></div><div class="field"><label>收款人 / 账户</label><input readonly :value="`${item.payeeName} · ${item.bankAccountMask || '已脱敏'}`"></div><div class="field full"><label>报销说明</label><textarea readonly :value="item.description"></textarea></div></div></section>
<section v-if="hasFeishuSnapshot" class="section-card" aria-labelledby="feishu-snapshot-title">
<div class="section-title"><div><span class="eyebrow">HISTORICAL SNAPSHOT</span><h2 id="feishu-snapshot-title">飞书审批表单</h2></div><span>提交版本 {{ item.formSnapshot?.fingerprint?.slice(0, 8) || '未知' }} · 历史快照</span></div>
<dl class="snapshot-fields">
<template v-for="field in item.formSnapshot?.fields || []" :key="field.id">
<div v-if="field.type !== 'EXPENSE_ITEMS' && field.binding !== 'EXPENSE_ITEMS'" class="snapshot-field" :class="{ full: field.type === 'TEXTAREA' || field.type === 'DISPLAY' }">
<dt>{{ field.label }}</dt><dd :class="{ 'preserve-lines': field.type === 'TEXTAREA' || field.type === 'DISPLAY' }">{{ snapshotDisplay(field) }}</dd>
</div>
<div v-else class="snapshot-field full expense-snapshot">
<dt>{{ field.label }}</dt>
<dd><div v-if="hasUnknownExpenseChild(field)" class="snapshot-warning" role="note">该历史明细包含当前版本无法识别的列,仅展示有明确绑定的列。</div><div v-if="expenseRows(field).length && detailColumns(field).length" class="table-wrap"><table class="data-table responsive-table"><thead><tr><th v-for="column in detailColumns(field)" :key="column.valueKey" :class="{ amount: column.binding === 'EXPENSE_AMOUNT' }">{{ column.label }}</th></tr></thead><tbody><tr v-for="(expense, rowIndex) in expenseRows(field)" :key="rowIndex"><td v-for="column in detailColumns(field)" :key="column.valueKey" :data-label="column.label" :class="{ amount: column.binding === 'EXPENSE_AMOUNT' }">{{ expenseCell(expense, column, rowIndex) }}</td></tr></tbody></table></div><span v-else>—</span></dd>
</div>
</template>
</dl>
</section>
<section v-if="!hasFeishuSnapshot" class="section-card"><div class="section-title"><h2>报销信息</h2><span>{{ item.category }}</span></div><div class="form-grid"><div class="field"><label>报销人 / 部门</label><input readonly :value="`${item.applicantName} / ${item.departmentName}`"></div><div class="field"><label>费用类型</label><input readonly :value="`${item.expenseTypeName} · ${item.category}`"></div><div class="field"><label>申请金额</label><input readonly :value="money(item.totalAmount)"></div><div class="field"><label>申请日期</label><input readonly :value="item.createdAt?.slice(0,10) || '-' "></div><div class="field"><label>收款人 / 账户</label><input readonly :value="`${item.payeeName} · ${item.bankAccountMask || '已脱敏'}`"></div><div class="field full"><label>报销说明</label><textarea readonly :value="item.description"></textarea></div></div></section>
<section v-else class="section-card finance-facts"><div class="section-title"><h2>财务与付款信息</h2><span>系统记录</span></div><div class="source-grid"><div><span>收款人</span><strong>{{ item.payeeName || '—' }}</strong></div><div><span>收款账户</span><strong>{{ item.bankAccountMask || '已脱敏' }}</strong></div><div><span>开户银行</span><strong>{{ item.bankName || '—' }}</strong></div><div><span>申请日期</span><strong>{{ item.createdAt?.slice(0, 10) || '—' }}</strong></div></div></section>
<section class="source-card"><div class="source-card-head"><div><span class="eyebrow">KINGDEE SOURCE · READ ONLY</span><h3>{{ item.sourceDocNo || '未关联源单' }} <small>{{ item.sourceStatus }}</small></h3></div><span class="tag success">只读</span></div><div class="source-grid"><div><span>来源系统</span><strong>{{ item.sourceDocNo ? '金蝶 ERP' : '暂无' }}</strong></div><div><span>源单编号</span><strong>{{ item.sourceDocNo || '—' }}</strong></div><div><span>来源状态</span><strong>{{ item.sourceStatus }}</strong></div><div><span>收款人</span><strong>{{ item.payeeName }}</strong></div><div><span>开户银行</span><strong>{{ item.bankName || '—' }}</strong></div><div><span>账号</span><strong>{{ item.bankAccountMask || '已脱敏' }}</strong></div></div><p><b>只读说明</b> 来源单据由外部系统同步,需修改业务事实请回到金蝶维护后重新同步。</p></section>
<section class="section-card"><div class="section-title"><h2>费用明细</h2><span>{{ item.expenseItems.length }} 条</span></div><div v-if="item.expenseItems.length" class="table-wrap"><table class="data-table responsive-table"><thead><tr><th>日期</th><th>类别</th><th>说明</th><th class="amount">金额</th></tr></thead><tbody><tr v-for="expense in item.expenseItems" :key="expense.id || expense.seqNo"><td data-label="日期">{{ expense.expenseDate }}</td><td data-label="类别">{{ expense.category }}</td><td data-label="说明">{{ expense.description }}</td><td data-label="金额" class="amount">{{ money(expense.amount) }}</td></tr></tbody></table></div></section>
<section class="section-card"><div class="section-title"><h2>发票</h2><span>{{ item.invoices.length }} 张</span></div><div v-if="item.invoices.length" class="table-wrap"><table class="data-table responsive-table"><thead><tr><th>发票号码</th><th class="amount">发票金额</th><th>校验状态</th></tr></thead><tbody><tr v-for="invoice in item.invoices" :key="invoice.id"><td data-label="发票号码">{{ invoice.invoiceNo }}</td><td data-label="发票金额" class="amount">{{ money(invoice.amount) }}</td><td data-label="校验状态">{{ invoice.verifyStatus }}</td></tr></tbody></table></div><div v-else class="empty-state"><strong>暂无发票</strong><span>请按费用事项补充发票或证明材料</span></div></section>
<section class="section-card"><div class="section-title"><h2>附件材料</h2><span>{{ item.attachments.length }} 份</span></div><div v-if="item.attachments.length" class="attachment-grid"><div v-for="file in item.attachments" :key="file.id" class="attachment-item"><span class="file-icon">PDF</span><div><strong>{{ file.fileName }}</strong><small>{{ file.fileType }} · 只读材料</small></div></div></div><div v-else class="empty-state">尚未上传附件</div></section>
<section v-if="!snapshotHasExpenses" class="section-card"><div class="section-title"><h2>费用明细</h2><span>{{ item.expenseItems.length }} 条</span></div><div v-if="item.expenseItems.length" class="table-wrap"><table class="data-table responsive-table"><thead><tr><th>日期</th><th>类别</th><th>说明</th><th>附件</th><th class="amount">金额</th></tr></thead><tbody><tr v-for="expense in item.expenseItems" :key="expense.id || expense.seqNo"><td data-label="日期">{{ expense.expenseDate }}</td><td data-label="类别">{{ expense.category }}</td><td data-label="说明">{{ expense.description }}</td><td data-label="附件">{{ expenseAttachmentNames(expense) }}</td><td data-label="金额" class="amount">{{ money(expense.amount) }}</td></tr></tbody></table></div></section>
<section class="section-card"><div class="section-title"><h2>发票</h2><span>{{ item.invoices.length }} 张</span></div><div v-if="item.invoices.length" class="table-wrap"><table class="data-table responsive-table"><thead><tr><th>发票号码</th><th class="amount">发票金额</th><th>校验状态</th></tr></thead><tbody><tr v-for="invoice in item.invoices" :key="invoice.id"><td data-label="发票号码">{{ invoice.invoiceNo }}</td><td data-label="发票金额" class="amount">{{ money(invoice.amount) }}</td><td data-label="校验状态">{{ invoice.verifyStatus }}</td></tr></tbody></table></div><div v-else class="empty-state"><strong>暂无发票</strong></div></section>
<section class="section-card"><div class="section-title"><h2>附件材料</h2><span>{{ item.attachments.length }} 份</span></div><div v-if="item.attachments.length" class="attachment-grid"><div v-for="file in item.attachments" :key="file.id" class="attachment-item"><span class="file-icon">FILE</span><div><strong>{{ file.fileName }}</strong><small>{{ file.fileType }} · 只读材料</small></div></div></div><div v-else class="empty-state">暂无附件</div></section>
<section class="section-card"><div class="section-title"><h2>审批、收单与付款时间线</h2><span>状态留痕</span></div><div class="timeline"><div v-for="entry in timeline" :key="entry.name" class="timeline-item" :class="entry.done ? 'done' : 'pending'"><span class="timeline-dot"></span><div><strong>{{ entry.name }}</strong><p>{{ entry.copy }}</p><time>{{ entry.time }}</time></div></div></div></section>
</div><aside class="card side-panel"><div class="summary-block"><h3>金额汇总</h3><div class="amount-highlight">{{ money(item.totalAmount) }}</div><div class="summary-row"><span>已付款</span><strong>{{ money(store.paidAmount(item)) }}</strong></div><div class="summary-row"><span>未付款</span><strong>{{ money(store.balance(item)) }}</strong></div><div class="summary-total"><span>付款进度</span><strong>{{ item.totalAmount ? `${Math.round(store.paidAmount(item) / item.totalAmount * 100)}%` : '0%' }}</strong></div></div><div class="summary-block"><h3>付款记录</h3><div v-if="item.payments.length"><div v-for="payment in item.payments" :key="payment.id" class="payment-record"><strong>{{ payment.paymentNo }}</strong><span>{{ money(payment.paymentAmount) }} · {{ payment.paymentTime }}</span><small>{{ payment.paymentMethod }} · {{ payment.operatorName }}</small></div></div><div v-else class="muted-copy">暂无实际付款记录</div></div></aside></div>
</template>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted } from 'vue'; import { useRoute, useRouter } from 'vue-router'; import { useUserStore } from '@/store/user'; import { useWorkbenchStore } from '@/store/workbench'
const route=useRoute(); const router=useRouter(); const store=useWorkbenchStore(); const userStore=useUserStore(); const item=computed(()=>store.getById(String(route.params.id))); const canEdit=computed(()=>!!item.value && item.value.applicantName===userStore.userInfo?.realName && (item.value.applicationStatus==='草稿'||item.value.approvalStatus==='退回')); const editRoute=computed(()=>item.value?`/applications/${item.value.id}/edit`:'/applications'); const money=(v:number)=>`¥ ${Number(v||0).toLocaleString('zh-CN',{minimumFractionDigits:2})}`; const tone=(v:string)=>({草稿:'draft',已提交:'info',审批中:'pending',审批通过:'success',退回:'danger',待收单:'pending',已收单:'success',未付款:'neutral',部分付款:'info',已付款:'success',未触发:'neutral'} as Record<string,string>)[v]||'neutral'; const print=()=>window.print()
const workflow=computed(()=>item.value?[{name:'申请',value:item.value.applicationStatus,tone:tone(item.value.applicationStatus)},{name:'审批',value:item.value.approvalStatus,tone:tone(item.value.approvalStatus)},{name:'收单',value:item.value.receiptStatus,tone:tone(item.value.receiptStatus)},{name:'付款',value:item.value.paymentStatus,tone:tone(item.value.paymentStatus)}]:[])
const timeline=computed(()=>{const current=item.value;if(!current)return[];return[{name:'申请提交',copy:current.applicationStatus==='草稿'?'尚未提交申请':`${current.applicantName} 已提交报销申请`,done:current.applicationStatus!=='草稿',time:current.submitTime||current.createdAt||'待触发'},{name:'飞书审批',copy:current.approvalStatus==='退回'?`退回:${current.returnReason||'需补充材料'}`:current.approvalStatus==='审批通过'?'审批通过,结果已同步':`当前节点:${current.currentApprovalNode}`,done:current.approvalStatus!=='未触发',time:current.updatedAt||'待触发'},{name:'财务收单',copy:current.receiptStatus==='已收单'?'财务已完成收单':current.receiptStatus==='待收单'?'等待财务办理收单':'审批通过后激活',done:current.receiptStatus==='已收单',time:current.updatedAt||'待触发'},{name:'付款登记',copy:current.paymentStatus==='未付款'?'等待外部支付并登记凭据':`累计已付 ${money(store.paidAmount(current))}`,done:current.paymentStatus==='已付款',time:current.updatedAt||'待办理'}]})
onMounted(()=>{void store.loadDetail(String(route.params.id))})
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { ExpenseItem, ReimbursementFormAttachment, ReimbursementFormField } from '@/api/reimbursement'
import { useUserStore } from '@/store/user'
import { useWorkbenchStore } from '@/store/workbench'
type ExpenseKey = 'expenseDate' | 'category' | 'description' | 'amount'
type SnapshotRow = Record<string, unknown>
const route = useRoute()
const router = useRouter()
const store = useWorkbenchStore()
const userStore = useUserStore()
const detailLoading = ref(true)
const detailError = ref('')
const detailReady = ref(false)
const item = computed(() => detailReady.value ? store.getById(String(route.params.id)) : null)
const canEdit = computed(() => !!item.value && item.value.applicantName === userStore.userInfo?.realName && (item.value.applicationStatus === '草稿' || item.value.approvalStatus === '退回'))
const editRoute = computed(() => item.value ? `/applications/${item.value.id}/edit` : '/applications')
const hasFeishuSnapshot = computed(() => item.value?.formSnapshot?.mode === 'FEISHU')
const snapshotHasExpenses = computed(() => hasFeishuSnapshot.value && item.value?.formSnapshot?.fields.some(field => field.binding === 'EXPENSE_ITEMS' || field.type === 'EXPENSE_ITEMS'))
const money = (value: number) => `¥ ${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`
const tone = (value: string) => ({ 草稿: 'draft', 已提交: 'info', 审批中: 'pending', 审批通过: 'success', 退回: 'danger', 待收单: 'pending', 已收单: 'success', 未付款: 'neutral', 部分付款: 'info', 已付款: 'success', 未触发: 'neutral' } as Record<string, string>)[value] || 'neutral'
const print = () => window.print()
const workflow = computed(() => item.value ? [{ name: '申请', value: item.value.applicationStatus, tone: tone(item.value.applicationStatus) }, { name: '审批', value: item.value.approvalStatus, tone: tone(item.value.approvalStatus) }, { name: '收单', value: item.value.receiptStatus, tone: tone(item.value.receiptStatus) }, { name: '付款', value: item.value.paymentStatus, tone: tone(item.value.paymentStatus) }] : [])
const timeline = computed(() => { const current = item.value; if (!current) return []; return [{ name: '申请提交', copy: current.applicationStatus === '草稿' ? '尚未提交申请' : `${current.applicantName} 已提交报销申请`, done: current.applicationStatus !== '草稿', time: current.submitTime || current.createdAt || '待触发' }, { name: '飞书审批', copy: current.approvalStatus === '退回' ? `退回:${current.returnReason || '需补充信息'}` : current.approvalStatus === '审批通过' ? '审批通过,结果已同步' : `当前节点:${current.currentApprovalNode}`, done: current.approvalStatus !== '未触发', time: current.updatedAt || '待触发' }, { name: '财务收单', copy: current.receiptStatus === '已收单' ? '财务已完成收单' : current.receiptStatus === '待收单' ? '等待财务办理收单' : '审批通过后激活', done: current.receiptStatus === '已收单', time: current.updatedAt || '待触发' }, { name: '付款登记', copy: current.paymentStatus === '未付款' ? '等待外部支付并登记凭据' : `累计已付 ${money(store.paidAmount(current))}`, done: current.paymentStatus === '已付款', time: current.updatedAt || '待办理' }] })
const boundValue = (field: ReimbursementFormField): unknown => {
const current = item.value
if (!current) return undefined
const snapshotValues = current.formSnapshot?.values
if (snapshotValues && Object.prototype.hasOwnProperty.call(snapshotValues, field.valueKey)) return snapshotValues[field.valueKey]
const values: Record<string, unknown> = { APPLICATION_NO: current.applicationNo, TITLE: current.title, APPLICANT_NAME: current.applicantName, APPLICANT_CONTACT: current.applicantName, APPLICANT_DEPARTMENT: current.departmentName, DEPARTMENT: current.departmentName, EXPENSE_TYPE: current.expenseTypeName || current.category, TOTAL_AMOUNT: current.totalAmount, DESCRIPTION: current.description, SOURCE_DOC_NO: current.sourceDocNo }
return values[field.binding]
}
const contactDisplayLabel = (value: unknown) => {
if (!value || typeof value !== 'object' || Array.isArray(value)) return '—'
const contact = value as { display_label?: unknown; label?: unknown }
const label = contact.display_label ?? contact.label
return typeof label === 'string' && label.trim() ? label.trim() : '—'
}
const departmentDisplayLabel = (value: unknown) => {
if (!value || typeof value !== 'object' || Array.isArray(value)) return '—'
const label = (value as { display_label?: unknown }).display_label
return typeof label === 'string' && label.trim() ? label.trim() : '—'
}
const snapshotDisplay = (field: ReimbursementFormField) => {
const value = boundValue(field)
if (value == null || value === '') return field.type === 'DISPLAY' ? field.label : '—'
if (field.type === 'CONTACT') {
const snapshotValues = item.value?.formSnapshot?.values
const hasSnapshotValue = Boolean(snapshotValues && Object.prototype.hasOwnProperty.call(snapshotValues, field.valueKey))
return hasSnapshotValue ? contactDisplayLabel(value) : (field.binding === 'APPLICANT_CONTACT' ? item.value?.applicantName || '—' : '—')
}
if (field.type === 'DEPARTMENT') return departmentDisplayLabel(value)
if (field.binding === 'TOTAL_AMOUNT' || field.type === 'DECIMAL') return money(Number(value))
if (Array.isArray(value)) return value.map(entry => field.options.find(option => option.value === String(entry))?.label || String(entry)).join('、') || '—'
if (field.type === 'SINGLE_SELECT') return field.options.find(option => option.value === String(value))?.label || String(value)
if (typeof value === 'object') return departmentDisplayLabel(value)
return String(value)
}
const expenseBindingKeys: Partial<Record<ReimbursementFormField['binding'], ExpenseKey>> = { EXPENSE_DATE: 'expenseDate', EXPENSE_CATEGORY: 'category', EXPENSE_DESCRIPTION: 'description', EXPENSE_AMOUNT: 'amount' }
const isExpenseDetailColumn = (child: ReimbursementFormField) => Boolean(expenseBindingKeys[child.binding]) || (child.binding === 'EXPENSE_ATTACHMENT' && child.type === 'ATTACHMENT')
const detailColumns = (field: ReimbursementFormField) => field.children.filter(child => child.type !== 'DISPLAY' && isExpenseDetailColumn(child))
const hasUnknownExpenseChild = (field: ReimbursementFormField) => field.children.some(child => child.type !== 'DISPLAY' && !isExpenseDetailColumn(child))
const expenseRows = (field: ReimbursementFormField): SnapshotRow[] => {
const saved = item.value?.formSnapshot?.values?.[field.valueKey]
const columns = detailColumns(field)
if (Array.isArray(saved) && saved.every(row => row && typeof row === 'object' && !Array.isArray(row) && columns.every(child => Object.prototype.hasOwnProperty.call(row, child.valueKey)))) return saved as SnapshotRow[]
return (item.value?.expenseItems || []).map(expense => Object.fromEntries(detailColumns(field).map(child => {
const key = expenseBindingKeys[child.binding]
return [child.valueKey, key ? expense[key] : child.binding === 'EXPENSE_ATTACHMENT' ? expense.attachments || expense.attachmentMetadata || expense.attachmentIds : undefined]
})))
}
const safeAttachmentMetadata = (expense?: Partial<ExpenseItem>): ReimbursementFormAttachment[] => {
const files = [...(expense?.attachments || []), ...(expense?.attachmentMetadata || [])]
const unique = new Map<string, ReimbursementFormAttachment>()
files.forEach(file => { if (file?.id != null && file.fileName) unique.set(String(file.id), file) })
return [...unique.values()]
}
const expenseAttachmentNames = (expense?: Partial<ExpenseItem>) => safeAttachmentMetadata(expense).map(file => file.fileName).join('、') || '—'
const snapshotAttachmentNames = (value: unknown, rowIndex: number) => {
const values = Array.isArray(value) ? value : value == null ? [] : [value]
const directNames = values.map(entry => typeof entry === 'object' && entry && 'fileName' in entry ? String((entry as { fileName: unknown }).fileName || '') : '').filter(Boolean)
if (directNames.length) return directNames.join('、')
const detailExpense = item.value?.expenseItems[rowIndex]
const metadata = safeAttachmentMetadata(detailExpense)
if (!values.length) return metadata.map(file => file.fileName).join('、') || '—'
const ids = new Set(values.map(value => String(typeof value === 'object' && value && 'id' in value ? (value as { id: unknown }).id : value)))
return metadata.filter(file => ids.has(String(file.id))).map(file => file.fileName).join('、') || '—'
}
const expenseCell = (expense: SnapshotRow, child: ReimbursementFormField, rowIndex: number) => {
const value = expense[child.valueKey]
if (child.binding === 'EXPENSE_ATTACHMENT') return snapshotAttachmentNames(value, rowIndex)
if (value == null || value === '') return '—'
if (child.binding === 'EXPENSE_AMOUNT') return money(Number(value))
if (child.type === 'SINGLE_SELECT') return child.options.find(option => option.value === String(value))?.label || String(value)
return String(value)
}
const loadDetail = async () => {
detailLoading.value = true
detailError.value = ''
detailReady.value = false
try {
const detail = await store.loadDetail(String(route.params.id), { strict: true })
if (store.source === 'api' && !detail?.formSnapshot) throw new Error('服务端详情缺少表单快照,已停止使用列表摘要替代历史详情。')
if (!detail) throw new Error('未找到该报销单或当前无权查看。')
detailReady.value = true
} catch (error) {
detailError.value = error instanceof Error && error.message ? error.message : '无法读取权威报销详情,请稍后重试。'
} finally {
detailLoading.value = false
}
}
onMounted(loadDetail)
</script>
<style scoped>
.snapshot-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1px; margin: 0; overflow: hidden; border: 1px solid var(--line); border-radius: 6px; background: var(--line); }
.snapshot-field { min-width: 0; padding: 12px 14px; background: #fff; }
.snapshot-field.full { grid-column: 1 / -1; }
.snapshot-field dt { margin-bottom: 5px; color: var(--quiet); font-size: 11px; font-weight: 700; }
.snapshot-field dd { margin: 0; overflow-wrap: anywhere; }
.snapshot-field .preserve-lines { white-space: pre-wrap; }
.expense-snapshot dd { margin-top: 9px; }
.snapshot-warning { margin-bottom: 9px; padding: 8px 10px; border: 1px solid #f1cf8d; border-radius: 6px; background: #fff9e9; color: #805a16; font-size: 11px; }
.finance-facts .source-grid { margin-top: 0; }
@media (max-width: 680px) { .snapshot-fields { grid-template-columns: 1fr; } .snapshot-field.full { grid-column: 1; } }
</style>
+19 -8
View File
@@ -1,5 +1,5 @@
<template>
<div class="page-content">
<div class="page-content route-list-page">
<div class="page-head">
<div>
<span class="eyebrow">MY EXPENSES</span>
@@ -8,7 +8,7 @@
</div>
<div class="head-actions">
<button class="btn" type="button" :disabled="loadingState" @click="reload">刷新</button>
<router-link class="btn primary" to="/applications/new">+ 发起报销</router-link>
<router-link v-if="canCreate" class="btn primary" to="/applications/new">+ 发起报销</router-link>
</div>
</div>
@@ -30,7 +30,7 @@
<button class="btn small" type="button" @click="reload">重试</button>
</div>
<div class="card fill-list-card">
<div class="card fill-list-card primary-list-card">
<div class="tabs" role="tablist" aria-label="报销列表筛选">
<button
v-for="tab in tabs"
@@ -91,7 +91,7 @@
</tr>
</thead>
<tbody>
<tr v-for="item in filtered" :key="item.id">
<tr v-for="item in paginatedItems" :key="item.id">
<td data-label="报销单号">
<router-link class="table-action strong-link" :to="`/applications/${item.id}`">{{ item.applicationNo }}</router-link>
<small>{{ item.createdAt?.slice(0, 10) || '-' }}</small>
@@ -114,18 +114,19 @@
</tr>
</tbody>
</table>
</div>
</div>
<div v-else-if="!store.reimbursements.length" class="empty-state">
<strong>暂无报销记录</strong>
<span>发起一笔报销后,申请进度会显示在这里。</span>
<router-link class="btn primary" to="/applications/new">发起报销</router-link>
<router-link v-if="canCreate" class="btn primary" to="/applications/new">发起报销</router-link>
</div>
<div v-else class="empty-state">
<strong>没有符合条件的报销</strong>
<span>请调整搜索关键词或筛选条件。</span>
<button class="btn" type="button" @click="clearFilters">清除筛选</button>
</div>
<AppListPagination v-if="filtered.length" v-model:page="page" v-model:page-size="pageSize" :total="filtered.length" aria-label="报销申请列表分页" />
</div>
</div>
</div>
@@ -133,9 +134,11 @@
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import type { ReimApplicationDetail } from '@/api/reimbursement'
import AppListPagination from '@/components/common/AppListPagination.vue'
import { useListPagination } from '@/composables/useListPagination'
import { useUserStore } from '@/store/user'
import { useWorkbenchStore } from '@/store/workbench'
@@ -151,6 +154,7 @@ const applicationFilter = ref('')
const approvalFilter = ref('')
const hasLoaded = ref(Boolean(store.reimbursements.length))
const applicationsPanelId = 'applications-list-panel'
const canCreate = computed(() => userStore.canEdit('reimbursement.application.create') && userStore.canRead('page.application-create'))
const tabs: ApplicationTab[] = [
{ key: 'all', label: '全部' },
@@ -187,6 +191,13 @@ const filtered = computed(() => {
matchesTab(item, currentTab.value)
))
})
const { page, pageSize, paginatedItems } = useListPagination(filtered, {
resetSources: [query, currentTab, applicationFilter, approvalFilter],
})
watch(() => route.query.q, value => {
const nextQuery = String(value || '')
if (query.value !== nextQuery) query.value = nextQuery
}, { flush: 'sync' })
const loadingState = computed(() => store.loading || !hasLoaded.value)
const hasBlockingError = computed(() => hasLoaded.value && store.source === 'error')
@@ -206,7 +217,7 @@ const clearFilters = () => {
currentTab.value = 'all'
}
const editable = (item: ReimApplicationDetail) => isMine(item) && (item.applicationStatus === '草稿' || item.approvalStatus === '退回')
const editable = (item: ReimApplicationDetail) => userStore.canEdit('reimbursement.application.edit') && userStore.canRead('page.application-edit') && isMine(item) && (item.applicationStatus === '草稿' || item.approvalStatus === '退回')
const money = (value: number) => `¥ ${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`
const tone = (value: string) => ({
草稿: 'draft', 已提交: 'info', 审批中: 'pending', 审批通过: 'success', 退回: 'danger',
+5 -6
View File
@@ -9,12 +9,12 @@
</div>
<div class="head-actions">
<template v-if="isFinance">
<router-link class="btn" to="/finance-receipt">查看待收单</router-link>
<router-link class="btn" to="/payments">查看待付款</router-link>
<router-link v-if="userStore.canRead('page.finance-receipt')" class="btn" to="/finance-receipt">查看待收单</router-link>
<router-link v-if="userStore.canRead('page.payments')" class="btn" to="/payments">查看待付款</router-link>
</template>
<template v-else>
<router-link class="btn primary" to="/applications/new"><Plus /> 发起报销</router-link>
<router-link class="btn" to="/applications">查看我的报销</router-link>
<router-link v-if="userStore.canEdit('reimbursement.application.create') && userStore.canRead('page.application-create')" class="btn primary" to="/applications/new"><Plus /> 发起报销</router-link>
<router-link v-if="userStore.canRead('page.applications')" class="btn" to="/applications">查看我的报销</router-link>
</template>
<button class="btn" type="button" :disabled="store.loading || financeQueueLoading" @click="refresh">
<Refresh /> 刷新数据
@@ -233,8 +233,7 @@ const financeQueueLoading = ref(false)
const financeQueueError = ref('')
const userName = computed(() => userStore.userInfo?.realName || store.user?.realName || '用户')
const userType = computed(() => userStore.userInfo?.userType || store.user?.userType || '')
const isFinance = computed(() => ['FINANCE', 'ADMIN', 'SUPER_ADMIN'].includes(userType.value))
const isFinance = computed(() => userStore.canAny(['page.finance-receipt', 'page.source-documents', 'page.payments', 'page.operation-log']))
const mine = computed(() => isFinance.value
? store.reimbursements
: store.reimbursements.filter(item => item.applicantName === userName.value))
+16 -9
View File
@@ -1,5 +1,5 @@
<template>
<div class="page-content">
<div class="page-content route-list-page">
<div class="page-head">
<div>
<span class="eyebrow">EXPENSE TYPES</span>
@@ -7,27 +7,34 @@
<p>管理费用类型分类。</p>
</div>
</div>
<div class="card fill-list-card">
<div class="table-wrap" v-if="items.length > 0" tabindex="0" role="region" aria-label="费用类型列表"><table class="data-table">
<div class="card fill-list-card primary-list-card">
<div class="table-wrap" v-if="loaded && !error && items.length > 0" tabindex="0" role="region" aria-label="费用类型列表"><table class="data-table responsive-table">
<thead><tr><th>编码</th><th>名称</th><th>分类</th><th>状态</th></tr></thead>
<tbody>
<tr v-for="item in items" :key="item.id">
<td><small>{{ item.code }}</small></td>
<td><strong>{{ item.name }}</strong></td>
<td><span class="tag">{{ item.category }}</span></td>
<td><span class="tag" :class="item.status==='ACTIVE'?'success':'draft'">{{ item.status }}</span></td>
<tr v-for="item in paginatedItems" :key="item.id">
<td data-label="编码"><small>{{ item.code }}</small></td>
<td data-label="名称"><strong>{{ item.name }}</strong></td>
<td data-label="分类"><span class="tag">{{ item.category }}</span></td>
<td data-label="状态"><span class="tag" :class="item.status==='ACTIVE'?'success':'draft'">{{ item.status }}</span></td>
</tr>
</tbody>
</table></div>
<div v-else-if="error" class="empty-state" role="alert"><strong>费用类型加载失败</strong><span>{{ error }}</span><button class="btn small" type="button" @click="load">重试</button></div>
<div class="empty-state" v-else-if="loaded"><strong>暂无费用类型</strong></div>
<div v-else class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载费用类型…</span></div>
<AppListPagination v-if="loaded && !error && items.length" v-model:page="page" v-model:page-size="pageSize" :total="items.length" aria-label="费用类型列表分页" />
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import request from '@/api/request'
import AppListPagination from '@/components/common/AppListPagination.vue'
import { useListPagination } from '@/composables/useListPagination'
const items = ref<any[]>([])
const loaded = ref(false)
onMounted(async () => { try { items.value = await request.get('/metadata/expense-types') || [] } catch {} finally { loaded.value = true } })
const error = ref('')
const { page, pageSize, paginatedItems } = useListPagination(items)
const load = async () => { loaded.value = false; error.value = ''; try { items.value = await request.get('/metadata/expense-types') || [] } catch (e) { error.value = e instanceof Error ? e.message : '请求失败,请稍后重试。' } finally { loaded.value = true } }
onMounted(load)
</script>
+144 -109
View File
@@ -1,8 +1,8 @@
<template>
<div class="directory-page page-content">
<div class="directory-page" :class="{ 'page-content route-list-page': !embedded, 'directory-embedded': embedded }">
<FeishuDirectoryPanel @committed="refreshOrganization" />
<section class="card organization-card" aria-labelledby="organization-title">
<section class="card organization-card primary-list-card" aria-labelledby="organization-title">
<div class="card-head organization-head">
<div>
<span class="eyebrow">ORGANIZATION</span>
@@ -10,7 +10,7 @@
<p>选择部门查看该部门及下级部门的飞书员工资料。</p>
</div>
<div class="organization-actions">
<span v-if="organization" class="muted-copy">快照状态:{{ snapshotLabels[organization.snapshotState] }}</span>
<span v-if="organization" class="muted-copy">当前目录:{{ availabilityLabels[organization.availabilityState] }}</span>
<button class="btn small" type="button" :disabled="organizationLoading || !canRead" @click="refreshOrganization">{{ organizationLoading ? '加载中…' : '刷新组织架构' }}</button>
</div>
</div>
@@ -28,17 +28,19 @@
<span>{{ organizationError }}</span>
<button class="btn small" type="button" @click="refreshOrganization">重试</button>
</div>
<div v-else-if="!hasSnapshot" class="empty-state organization-state">
<strong>{{ organization?.snapshotState === 'UNAVAILABLE' ? '通讯录快照不可用' : '暂无组织架构' }}</strong>
<span>{{ organization?.snapshotState === 'NEVER_SYNCED' ? '首次同步成功后,组织架构会显示在这里。' : '同步成功后,组织架构会显示在这里。' }}</span>
<div v-else-if="!hasAvailableDirectory" class="empty-state organization-state">
<strong>{{ organization?.availabilityState === 'UNAVAILABLE' ? '当前目录不可用' : '暂无组织架构' }}</strong>
<span>{{ organization?.availabilityState === 'NEVER_SYNCED' ? '首次同步成功后,组织架构会显示在这里。' : '当前服务尚未确认目录可用,同步成功后会显示在这里。' }}</span>
</div>
<div v-else class="organization-layout">
<div class="organization-tree-wrap">
<div class="organization-summary">
<span>最近成功同步(本地时间):{{ formatLocalDateTime(organization?.lastSuccessfulAt, '暂无') }}</span>
<span>{{ departments.length }} 个部门 · {{ users.length }} 名员工</span>
<span>最近成功更新(本地时间):{{ formatLocalDateTime(organization?.lastSuccessfulAt, '暂无') }}</span>
<span>当前版本:{{ organization?.currentRevision || '暂无' }}</span>
<span>{{ departments.length }} 个部门 · {{ totalMemberCount }} 名员工</span>
</div>
<p v-if="organization?.snapshotState === 'STALE' || organization?.snapshotState === 'CONTEXT_CHANGED'" class="inline-note" role="status">当前展示的是过期或上下文已变化的快照,请同步后再作为最新目录使用。</p>
<p v-if="organization?.contextState === 'CHANGED'" class="inline-note" role="status">应用配置上下文已变化,仅作为诊断提示;当前目录仍可继续使用,可同步以更新资料。</p>
<p v-else-if="organization?.snapshotState === 'STALE'" class="inline-note" role="status">服务返回旧版 STALE 状态;当前目录已确认可用,仍可继续使用。</p>
<ul class="organization-tree" role="tree" aria-label="飞书组织架构">
<li v-for="item in visibleDepartments" :key="item.node.id" role="treeitem" :aria-level="item.depth + 1" :aria-expanded="item.node.children.length ? isExpanded(item.node.id) : undefined" :aria-selected="selectedDepartmentId === item.node.id">
<div class="department-row" :style="{ '--department-depth': item.depth }">
@@ -56,9 +58,18 @@
<section class="department-members" aria-labelledby="members-title">
<div class="section-title">
<h3 id="members-title">{{ selectedDepartment?.name || '部门员工' }}<small v-if="selectedDepartment?.children.length" class="children-label">(含下级部门)</small></h3>
<span>{{ selectedUsers.length }} 人</span>
<span>{{ membersLoading ? '加载中…' : `${selectedUsers.length} 人` }}</span>
</div>
<div v-if="!selectedUsers.length" class="empty-state compact-empty">
<div v-if="membersLoading" class="load-wrap compact-empty" role="status" aria-live="polite">
<span class="loader" aria-hidden="true"></span>
<span>正在加载部门员工…</span>
</div>
<div v-else-if="membersError" class="empty-state compact-empty" role="alert">
<strong>员工加载失败</strong>
<span>{{ membersError }}</span>
<button class="btn small" type="button" @click="refreshMembers">重试</button>
</div>
<div v-else-if="!selectedUsers.length" class="empty-state compact-empty">
<strong>该部门暂无员工</strong>
<span>请选择其他部门查看员工。</span>
</div>
@@ -71,27 +82,14 @@
<span>userId:{{ user.userId }}</span>
<span>openId:{{ user.openId }}</span>
<dl class="member-details">
<div><dt>职位</dt><dd>{{ user.jobTitle }}</dd></div>
<div><dt>邮箱</dt><dd>{{ user.email }}</dd></div>
<div><dt>手机</dt><dd>{{ user.mobile }}</dd></div>
<div><dt>任职状态</dt><dd>{{ user.employmentStatus }}</dd></div>
<div><dt>员工类型</dt><dd>{{ user.employeeType ?? '--' }}</dd></div>
</dl>
<div><dt>职位</dt><dd>{{ user.jobTitle }}</dd></div>
<div><dt>邮箱</dt><dd>{{ user.email }}</dd></div>
<div><dt>手机</dt><dd>{{ user.mobile }}</dd></div>
</dl>
</div>
</div>
</div>
<footer v-if="selectedUsers.length" class="pagination-footer" aria-label="员工列表分页">
<el-pagination
v-model:current-page="selectedPage"
v-model:page-size="pageSize"
:page-sizes="pageSizes"
:total="selectedUsers.length"
layout="total, sizes, prev, pager, next, jumper"
small
@current-change="handlePageChange"
@size-change="handlePageSizeChange"
/>
</footer>
<AppListPagination v-if="!membersLoading && !membersError && selectedUsers.length" v-model:page="selectedPage" v-model:page-size="pageSize" :total="selectedUsers.length" aria-label="部门员工列表分页" />
</section>
</div>
</section>
@@ -101,32 +99,39 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import FeishuDirectoryPanel from '@/components/FeishuDirectoryPanel.vue'
import { feishuDirectoryApi, type DirectoryDepartment, type DirectoryOrganization, type DirectoryOrganizationUser } from '@/api/feishuDirectory'
import AppListPagination from '@/components/common/AppListPagination.vue'
import { useListPagination } from '@/composables/useListPagination'
import { directoryAvailability, feishuDirectoryApi, type DirectoryAvailabilityState, type DirectoryContextState, type DirectoryDepartment, type DirectoryOrganization, type DirectoryOrganizationUser, type DirectorySnapshotState } from '@/api/feishuDirectory'
import { useUserStore } from '@/store/user'
withDefaults(defineProps<{ embedded?: boolean }>(), { embedded: false })
type DepartmentNode = DirectoryDepartment & { children: DepartmentNode[] }
type VisibleDepartment = { node: DepartmentNode; depth: number }
type SafeOrganizationUser = Pick<DirectoryOrganizationUser, 'userId' | 'openId' | 'name' | 'email' | 'mobile' | 'jobTitle' | 'employeeType' | 'avatarUrl' | 'employmentStatus' | 'departmentIds'> & { internalKey: string }
type SafeOrganization = Omit<DirectoryOrganization, 'users'> & { users: SafeOrganizationUser[] }
type SafeOrganizationUser = Pick<DirectoryOrganizationUser, 'userId' | 'openId' | 'name' | 'email' | 'mobile' | 'jobTitle' | 'avatarUrl' | 'departmentIds'> & { internalKey: string }
type SafeOrganization = Omit<DirectoryOrganization, 'users' | 'availabilityState' | 'contextState' | 'currentRevision'> & {
users: SafeOrganizationUser[]
availabilityState: DirectoryAvailabilityState
contextState: DirectoryContextState
currentRevision: string | null
}
const userStore = useUserStore()
const canRead = computed(() => (
userStore.permissionsLoaded
&& !userStore.permissionsError
&& (userStore.hasPermission('system:feishu:sync') || userStore.hasPermission('system:feishu:bind'))
))
const canRead = computed(() => userStore.canRead('page.feishu-directory'))
const organization = ref<SafeOrganization | null>(null)
const organizationLoading = ref(false)
const organizationError = ref('')
const selectedDepartmentId = ref<string | null>(null)
const selectedPage = ref(1)
const pageSizes = [10, 20, 50, 100]
const pageSize = ref(10)
const expandedDepartmentIds = ref<Set<string>>(new Set())
const snapshotLabels = { UNAVAILABLE: '不可用', NEVER_SYNCED: '尚未同步', FRESH: '有效', STALE: '已过期', CONTEXT_CHANGED: '应用上下文已变化' }
const memberUsers = ref<SafeOrganizationUser[]>([])
const membersLoading = ref(false)
const membersError = ref('')
const availabilityLabels: Record<DirectoryAvailabilityState, string> = { AVAILABLE: '可用', NEVER_SYNCED: '尚未同步', UNAVAILABLE: '不可用' }
const disposed = ref(false)
let organizationController: AbortController | null = null
let organizationRequest = 0
let membersController: AbortController | null = null
let membersRequest = 0
const formatLocalDateTime = (value: unknown, fallback = '—') => {
const date = value instanceof Date
@@ -175,10 +180,6 @@ const compareDepartmentOrder = (left: string, right: string) => {
return leftValue < rightValue ? -1 : leftValue > rightValue ? 1 : 0
}
const safeEmployeeType = (value: unknown): number | null => (
typeof value === 'number' && Number.isInteger(value) ? value : null
)
const normalizeOrganization = (value: unknown): SafeOrganization => {
const source = value && typeof value === 'object' ? value as Partial<DirectoryOrganization> : {}
const departmentIds = new Set<string>()
@@ -212,28 +213,43 @@ const normalizeOrganization = (value: unknown): SafeOrganization => {
const email = text(candidate.email, '--')
const mobile = text(candidate.mobile, '--')
users.push({
internalKey: userId || openId || `${name}-${email}-${mobile}`,
internalKey: openId || userId || `${name}-${email}-${mobile}`,
userId: userId || '--',
openId: openId || '--',
name,
email,
mobile,
jobTitle: text(candidate.jobTitle, '--'),
employeeType: safeEmployeeType(candidate.employeeType),
avatarUrl: safeAvatarUrl(candidate.avatarUrl),
employmentStatus: text(candidate.employmentStatus, '--'),
departmentIds: departmentIdsForUser,
})
})
}
const snapshotState = ['UNAVAILABLE', 'NEVER_SYNCED', 'FRESH', 'STALE', 'CONTEXT_CHANGED'].includes(String(source.snapshotState))
? source.snapshotState as DirectoryOrganization['snapshotState']
? source.snapshotState as DirectorySnapshotState
: 'UNAVAILABLE'
return { snapshotState, lastSuccessfulAt: source.lastSuccessfulAt || null, departments, users }
const availabilityState = directoryAvailability({ snapshotState, availabilityState: source.availabilityState })
const contextState: DirectoryContextState = source.contextState === 'MATCH' || source.contextState === 'CHANGED' || source.contextState === 'UNKNOWN'
? source.contextState
: snapshotState === 'CONTEXT_CHANGED' ? 'CHANGED' : 'UNKNOWN'
return {
snapshotState,
availabilityState,
contextState,
currentRevision: text(source.currentRevision) || null,
lastSuccessfulAt: source.lastSuccessfulAt || null,
departments,
users,
}
}
const departments = computed(() => organization.value?.departments || [])
const users = computed(() => organization.value?.users || [])
const totalMemberCount = computed(() => {
const ids = new Set(departments.value.map(department => department.id))
return departments.value
.filter(department => !department.parentId || department.parentId === '0' || !ids.has(department.parentId))
.reduce((sum, department) => sum + department.memberCount, 0)
})
const departmentNodes = computed(() => {
const nodes = new Map<string, DepartmentNode>()
departments.value.forEach(department => nodes.set(department.id, { ...department, children: [] }))
@@ -267,17 +283,6 @@ const departmentIndex = computed(() => {
visit(departmentNodes.value)
return index
})
const descendantDepartmentIds = computed(() => {
const result = new Map<string, Set<string>>()
const collect = (node: DepartmentNode): Set<string> => {
const ids = new Set([node.id])
node.children.forEach(child => collect(child).forEach(id => ids.add(id)))
result.set(node.id, ids)
return ids
}
departmentNodes.value.forEach(root => collect(root))
return result
})
const visibleDepartments = computed<VisibleDepartment[]>(() => {
const result: VisibleDepartment[] = []
const visit = (nodes: DepartmentNode[], depth: number) => nodes.forEach(node => {
@@ -288,54 +293,24 @@ const visibleDepartments = computed<VisibleDepartment[]>(() => {
return result
})
const selectedDepartment = computed(() => selectedDepartmentId.value ? departmentIndex.value.get(selectedDepartmentId.value) || null : null)
const selectedDepartmentIds = computed(() => selectedDepartmentId.value ? descendantDepartmentIds.value.get(selectedDepartmentId.value) || new Set<string>() : new Set<string>())
const usersInDepartments = (departmentIds: ReadonlySet<string>) => {
const seen = new Set<string>()
return users.value
.filter(user => user.departmentIds.some(departmentId => departmentIds.has(departmentId)))
.filter(user => {
if (seen.has(user.internalKey)) return false
seen.add(user.internalKey)
return true
})
}
const departmentMemberCounts = computed(() => {
const counts = new Map<string, number>()
departments.value.forEach(department => {
const ids = descendantDepartmentIds.value.get(department.id) || new Set([department.id])
counts.set(department.id, usersInDepartments(ids).length)
})
departments.value.forEach(department => counts.set(department.id, department.memberCount))
return counts
})
const selectedUsers = computed<SafeOrganizationUser[]>(() => {
if (!selectedDepartmentId.value) return []
return usersInDepartments(selectedDepartmentIds.value)
})
const totalPages = computed(() => Math.max(1, Math.ceil(selectedUsers.value.length / pageSize.value)))
const paginatedSelectedUsers = computed(() => {
const page = Math.min(selectedPage.value, totalPages.value)
const start = (page - 1) * pageSize.value
return selectedUsers.value.slice(start, start + pageSize.value)
})
const hasSnapshot = computed(() => Boolean(organization.value && !['UNAVAILABLE', 'NEVER_SYNCED'].includes(organization.value.snapshotState) && departments.value.length))
const selectedUsers = computed<SafeOrganizationUser[]>(() => memberUsers.value)
const { page: selectedPage, pageSize, totalPages, paginatedItems: paginatedSelectedUsers, clampPage } = useListPagination(selectedUsers, { resetSources: [selectedDepartmentId] })
const hasAvailableDirectory = computed(() => organization.value?.availabilityState === 'AVAILABLE')
const isExpanded = (id: string) => expandedDepartmentIds.value.has(id)
const clampPage = (page: number) => Math.min(Math.max(1, Number.isFinite(page) ? Math.trunc(page) : 1), totalPages.value)
const handlePageChange = (page: number) => {
selectedPage.value = clampPage(page)
selectedPage.value = page
clampPage()
}
const handlePageSizeChange = (size: number) => {
const nextSize = Number(size)
pageSize.value = pageSizes.includes(nextSize) ? nextSize : pageSizes[0]
pageSize.value = [10, 20, 50].includes(Number(size)) ? Number(size) : 10
selectedPage.value = 1
}
watch(pageSize, () => {
selectedPage.value = 1
}, { flush: 'sync' })
watch([selectedPage, () => selectedUsers.value.length], () => {
const page = clampPage(selectedPage.value)
if (selectedPage.value !== page) selectedPage.value = page
}, { flush: 'sync' })
const toggleDepartment = (id: string) => {
const next = new Set(expandedDepartmentIds.value)
if (next.has(id)) next.delete(id)
@@ -374,19 +349,54 @@ const applyOrganization = (value: unknown) => {
if (!selectedDepartmentId.value || !knownIds.has(selectedDepartmentId.value)) selectedDepartmentId.value = roots[0]?.id || null
}
const refreshMembers = async () => {
if (!canRead.value || disposed.value || !selectedDepartmentId.value || !hasAvailableDirectory.value) {
memberUsers.value = []
membersError.value = ''
membersLoading.value = false
return
}
const departmentId = selectedDepartmentId.value
const requestId = ++membersRequest
membersController?.abort()
const controller = new AbortController()
membersController = controller
membersLoading.value = true
membersError.value = ''
selectedPage.value = 1
try {
const next = await feishuDirectoryApi.organizationMembers(departmentId, controller.signal, true)
if (disposed.value || requestId !== membersRequest) return
memberUsers.value = normalizeOrganization(next).users
} catch (error) {
if (disposed.value || requestId !== membersRequest || controller.signal.aborted) return
memberUsers.value = []
membersError.value = error instanceof Error && error.message ? error.message : '请求失败,请稍后重试。'
} finally {
if (requestId === membersRequest) membersLoading.value = false
}
}
const refreshOrganization = async () => {
if (!canRead.value || disposed.value) return
selectedPage.value = 1
const requestId = ++organizationRequest
organizationController?.abort()
membersController?.abort()
membersRequest += 1
const controller = new AbortController()
organizationController = controller
organizationLoading.value = true
organizationError.value = ''
memberUsers.value = []
membersError.value = ''
try {
const next = await feishuDirectoryApi.organization(controller.signal)
const next = await feishuDirectoryApi.organization(controller.signal, false)
if (disposed.value || requestId !== organizationRequest) return
const previousDepartmentId = selectedDepartmentId.value
applyOrganization(next)
// watch handles department changes; same selection still needs a fresh member fetch.
if (selectedDepartmentId.value === previousDepartmentId) void refreshMembers()
} catch (error) {
if (disposed.value || requestId !== organizationRequest || controller.signal.aborted) return
organizationError.value = error instanceof Error && error.message ? error.message : '请求失败,请稍后重试。'
@@ -395,17 +405,41 @@ const refreshOrganization = async () => {
}
}
watch(selectedDepartmentId, () => { void refreshMembers() })
onMounted(() => { void refreshOrganization() })
onBeforeUnmount(() => {
disposed.value = true
organizationRequest += 1
membersRequest += 1
organizationController?.abort()
membersController?.abort()
})
</script>
<style scoped>
.directory-page { min-height: 100%; min-width: 0; }
.directory-page > .directory-panel { margin-top: 0; }
.directory-page { display: flex; min-height: 100%; min-width: 0; flex: 1 1 auto; flex-direction: column; }
.directory-page > .directory-panel { margin-top: 0; flex: 0 0 auto; }
.directory-embedded {
display: flex;
height: 100%;
min-width: 0;
min-height: 0;
flex: 1 1 auto;
flex-direction: column;
gap: 16px;
overflow: hidden;
}
.directory-embedded .organization-card {
margin-top: 0;
flex: 1 1 0;
min-height: 0;
}
.directory-embedded .organization-layout {
flex: 1 1 0;
min-height: 0;
grid-template-rows: minmax(0, 1fr);
}
.organization-card { display: flex; flex: 1 1 auto; min-width: 0; min-height: 0; margin-top: 16px; flex-direction: column; }
.organization-head { flex-wrap: wrap; gap: 12px; }
.organization-head > div:first-child { min-width: 0; flex: 1 1 320px; }
@@ -413,8 +447,11 @@ onBeforeUnmount(() => {
.organization-actions { display: flex; align-items: center; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
.organization-state { min-height: 160px; padding: 28px 18px; flex: 1 1 auto; }
.organization-state .btn { margin-top: 12px; }
.organization-layout { display: grid; flex: 1 1 0; height: auto; min-height: 0; min-width: 0; align-items: stretch; grid-template-columns: minmax(220px, .8fr) minmax(300px, 1.2fr); gap: 16px; padding: 0 18px 18px; }
.organization-tree-wrap, .department-members { display: flex; min-width: 0; min-height: 0; height: 100%; flex-direction: column; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface-raised); overflow: hidden; }
.organization-layout { display: grid; flex: 1 1 auto; height: auto; min-height: 420px; min-width: 0; align-items: stretch; grid-template-columns: minmax(220px, .8fr) minmax(300px, 1.2fr); gap: 18px; padding: 0 22px 22px; }
.directory-embedded .organization-layout { min-height: 0; }
.organization-tree-wrap, .department-members { display: flex; min-width: 0; min-height: 320px; height: 100%; flex-direction: column; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface-raised); overflow: hidden; }
.directory-embedded .organization-tree-wrap,
.directory-embedded .department-members { min-height: 0; }
.organization-summary { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 5px 14px; padding: 12px 14px; border-bottom: 1px solid var(--line); color: var(--muted); font-size: 11px; }
.inline-note { margin: 10px 14px; color: var(--warning); font-size: 11px; }
.organization-tree { min-height: 0; flex: 1 1 auto; padding: 8px 0; overflow-y: auto; list-style: none; }
@@ -446,15 +483,13 @@ onBeforeUnmount(() => {
.member-details { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 7px 12px; margin-top: 9px; }
.member-details dt { color: var(--quiet); font-size: 10px; }
.member-details dd { margin: 1px 0 0; overflow-wrap: anywhere; color: var(--body); font-size: 11px; }
.pagination-footer { display: flex; min-width: 0; flex: none; align-items: center; justify-content: flex-end; gap: 8px; padding: 9px 14px; border-top: 1px solid var(--line); color: var(--muted); font-size: 11px; overflow: hidden; }
.pagination-footer :deep(.el-pagination) { width: 100%; max-width: 100%; min-width: 0; height: auto; flex-wrap: wrap; justify-content: flex-end; row-gap: 6px; white-space: normal; }
.pagination-footer :deep(.el-pagination .el-pager) { max-width: 100%; flex-wrap: wrap; }
.pagination-footer :deep(.el-pagination__jump) { margin-left: 0; }
@media (max-width: 760px) {
.organization-layout { grid-template-columns: minmax(0, 1fr); grid-template-rows: repeat(2, minmax(260px, 1fr)); flex: 1 1 auto; }
.organization-tree-wrap, .department-members { height: auto; min-height: 260px; }
.directory-embedded .organization-layout { grid-template-rows: minmax(0, .4fr) minmax(0, .6fr); }
.directory-embedded .organization-tree-wrap,
.directory-embedded .department-members { min-height: 0; }
.organization-actions { justify-content: flex-start; width: 100%; }
.pagination-footer :deep(.el-pagination) { justify-content: flex-start; }
}
@media (max-width: 450px) {
.organization-layout { padding-right: 12px; padding-left: 12px; }
+15 -5
View File
@@ -1,5 +1,5 @@
<template>
<div class="page-content">
<div class="page-content route-list-page">
<div class="page-head">
<div>
<span class="eyebrow">FINANCE RECEIPT</span>
@@ -36,7 +36,7 @@
<div><span>收单金额</span><strong>{{ money(total) }}</strong><small>不等同于已付款</small></div>
</div>
<div class="card fill-list-card">
<div class="card fill-list-card primary-list-card">
<div class="card-head">
<div><h2>收单队列</h2><p>确认收单后,报销单进入付款处理环节。</p></div>
<span class="tag info">财务处理</span>
@@ -60,7 +60,7 @@
</tr>
</thead>
<tbody>
<tr v-for="item in filtered" :key="item.id">
<tr v-for="item in paginatedItems" :key="item.id">
<td data-label="报销单号"><router-link class="table-action strong-link" :to="`/applications/${item.id}`">{{ item.applicationNo }}</router-link><small>{{ item.createdAt?.slice(0, 10) || '-' }}</small></td>
<td data-label="报销人 / 事项"><strong>{{ item.applicantName }}</strong><small>{{ item.title }}</small></td>
<td data-label="申请金额" class="amount">{{ money(item.totalAmount) }}</td>
@@ -69,14 +69,16 @@
<td data-label="付款状态"><span class="tag" :class="tone(item.paymentStatus)">{{ item.paymentStatus }}</span></td>
<td data-label="操作">
<button
v-if="item.receiptStatus === '待收单'"
v-if="item.receiptStatus === '待收单' && canConfirm"
class="btn small primary"
type="button"
:disabled="isReceiving(item.id)"
:aria-busy="isReceiving(item.id)"
@click="receive(item)"
>{{ isReceiving(item.id) ? '处理中…' : '确认收单' }}</button>
<span v-else class="muted-copy">已完成</span>
<span v-else-if="item.receiptStatus === '待收单'" class="muted-copy">无确认权限</span>
<span v-else-if="item.receiptStatus === '已收单'" class="muted-copy">已完成</span>
<span v-else class="muted-copy">无需处理</span>
</td>
</tr>
</tbody>
@@ -90,6 +92,7 @@
<strong>没有符合条件的收单记录</strong>
<span>请调整搜索关键词后重试。</span>
</div>
<AppListPagination v-if="filtered.length" v-model:page="page" v-model:page-size="pageSize" :total="filtered.length" aria-label="财务收单队列分页" />
</div>
</template>
</div>
@@ -99,9 +102,14 @@
import { computed, onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { ReimApplicationDetail } from '@/api/reimbursement'
import AppListPagination from '@/components/common/AppListPagination.vue'
import { useListPagination } from '@/composables/useListPagination'
import { useWorkbenchStore } from '@/store/workbench'
import { useUserStore } from '@/store/user'
const store = useWorkbenchStore()
const userStore = useUserStore()
const canConfirm = computed(() => userStore.canEdit('finance.receipt.confirm'))
const query = ref('')
const hasLoaded = ref(false)
const receiving = ref<Set<string>>(new Set())
@@ -113,6 +121,7 @@ const filtered = computed(() => {
const normalizedQuery = query.value.trim().toLowerCase()
return rows.value.filter(item => `${item.applicationNo} ${item.applicantName} ${item.title}`.toLowerCase().includes(normalizedQuery))
})
const { page, pageSize, paginatedItems } = useListPagination(filtered, { resetSources: [query] })
const loadingState = computed(() => store.loading || !hasLoaded.value)
const hasBlockingError = computed(() => hasLoaded.value && (store.source === 'error' || Boolean(store.financeQueueError)))
const hasDataNotice = computed(() => hasLoaded.value && Boolean(store.error) && !hasBlockingError.value)
@@ -130,6 +139,7 @@ const refreshQueue = async () => {
}
const receive = async (item: ReimApplicationDetail) => {
if (!canConfirm.value) return
const key = receivingKey(item.id)
if (receiving.value.has(key)) return
receiving.value = new Set(receiving.value).add(key)
+326 -47
View File
@@ -1,70 +1,349 @@
<template>
<div class="integration-page">
<div class="page-head">
<div><span class="eyebrow">INTEGRATIONS</span><h1>配置管理</h1><p>管理飞书和金蝶连接。敏感配置只会在输入非空时更新。</p></div>
<div>
<span class="eyebrow">SYSTEM GOVERNANCE</span>
<h1>配置管理</h1>
<p>管理飞书审批、金蝶账号绑定及自动任务。</p>
</div>
</div>
<div v-if="loadError" class="inline-alert danger" role="alert"><b>!</b><span>{{ loadError }}</span><button class="btn small" type="button" @click="loadConfig">重试</button></div>
<div v-if="loading" class="card load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载集成配置…</span></div>
<div v-else-if="!canView" class="card empty-state" role="alert"><strong>无权查看配置</strong><span>权限服务不可用或当前账号没有集成查看权限。</span></div>
<div v-else class="integration-grid">
<section v-for="provider in providers" :key="provider.key" class="card integration-card" :aria-labelledby="`${provider.key}-title`">
<div class="card-head"><div><span class="eyebrow">{{ provider.code }}</span><h2 :id="`${provider.key}-title`">{{ provider.label }}</h2><p>配置项由服务端动态提供。</p></div><span class="tag" :class="forms[provider.key].enabled ? 'success' : 'neutral'">{{ forms[provider.key].enabled ? '已启用' : '未启用' }}</span></div>
<div class="integration-body">
<div class="enabled-row"><div><strong>启用集成</strong><small>关闭后不会主动调用该服务。</small></div><label class="toggle"><input v-model="forms[provider.key].enabled" type="checkbox" :disabled="!canManage" :aria-label="`启用${provider.label}`"><span class="toggle-slider"></span></label></div>
<div v-if="!forms[provider.key].fields.length" class="empty-state compact-empty"><strong>暂无配置字段</strong><span>服务端尚未提供配置项。</span></div>
<div v-else class="form-grid integration-form"><div v-for="field in forms[provider.key].fields" :key="field.key" class="field"><label :for="`${provider.key}-${field.key}`">{{ field.label }} <small v-if="field.configured" class="configured-label">已配置</small></label><input v-if="field.secret" :id="`${provider.key}-${field.key}`" v-model="forms[provider.key].values[field.key]" type="password" autocomplete="new-password" :disabled="!canManage" placeholder="留空以保留原值" :aria-describedby="`${provider.key}-${field.key}-help`"><input v-else :id="`${provider.key}-${field.key}`" v-model="forms[provider.key].values[field.key]" type="text" :disabled="!canManage"><small :id="`${provider.key}-${field.key}-help`" class="form-help">{{ field.secret ? (field.configured ? '已配置,留空不会覆盖原密钥。' : '敏感值不会明文展示。') : (field.configured ? `当前值:${displayValue(field.value)}` : '尚未配置') }}</small></div></div>
<div v-if="!canOpenPage" class="card empty-state" role="alert">
<strong>无权查看配置</strong>
<span>当前账号没有配置管理、金蝶账号绑定或自动任务权限,可在「人员与角色」中分配。</span>
</div>
<template v-else>
<nav v-if="visibleTabs.length > 1" class="tabs integration-tabs" role="tablist" aria-label="配置分栏">
<button
v-for="tab in visibleTabs"
:id="`config-tab-${tab.key}`"
:key="tab.key"
class="tab"
:class="{ active: activeTab === tab.key }"
type="button"
role="tab"
:aria-selected="activeTab === tab.key"
:aria-controls="`config-panel-${tab.key}`"
@click="selectTab(tab.key)"
>{{ tab.label }}</button>
</nav>
<div
v-show="activeTab === 'feishu'"
id="config-panel-feishu"
role="tabpanel"
aria-labelledby="config-tab-feishu"
>
<div v-if="!canViewFeishu" class="card empty-state" role="alert">
<strong>无权查看飞书配置</strong>
<span>需要「配置管理」页面权限。</span>
</div>
<div class="modal-actions integration-actions"><span v-if="testResults[provider.key]" class="test-result" :class="testResults[provider.key]?.success ? 'success-copy' : 'danger-copy'" role="status">{{ testResults[provider.key]?.message }}</span><button class="btn" type="button" :disabled="!canTest || testing === provider.key" @click="testConnection(provider.key)">{{ testing === provider.key ? '测试中…' : '测试连接' }}</button><button class="btn primary" type="button" :disabled="!canManage || saving === provider.key" @click="saveProvider(provider.key)">{{ saving === provider.key ? '保存中…' : '保存配置' }}</button></div>
</section>
</div>
<template v-else>
<div v-if="loadError" class="inline-alert danger" role="alert">
<b>!</b><span>{{ loadError }}</span>
<button class="btn small" type="button" @click="loadConfig">重试</button>
</div>
<div v-if="loading" class="card load-wrap" role="status">
<span class="loader" aria-hidden="true"></span><span>正在加载飞书审批配置…</span>
</div>
<template v-else>
<div class="inline-note integration-note">
保存审批定义编码后,点击「验证并同步飞书审批」拉取流程定义并订阅事件,保障飞书审批状态变更后本系统实时更新。
</div>
<section class="card integration-card" aria-labelledby="feishu-approval-title">
<div class="card-head">
<div>
<span class="eyebrow">FEISHU</span>
<h2 id="feishu-approval-title">飞书审批配置</h2>
<p>仅配置审批定义编码;应用凭证与事件回调密钥在 application.yml / 环境变量中维护。</p>
</div>
<span class="tag" :class="feishuEnabled ? 'success' : 'neutral'">{{ feishuEnabled ? '飞书已启用' : '飞书未启用' }}</span>
</div>
<div class="integration-body">
<div class="form-grid integration-form">
<div class="field">
<label for="feishu-approvalCode">审批定义编码 <em>*</em></label>
<input
id="feishu-approvalCode"
v-model.trim="approvalCode"
type="text"
:disabled="!canManage || saving || approvalSyncing"
placeholder="例如:8A0D2B3C-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
autocomplete="off"
aria-describedby="feishu-approvalCode-help"
>
<small id="feishu-approvalCode-help" class="field-hint">
在飞书审批管理后台查看目标报销流程的 approval_code(审批定义 Code)。
<template v-if="configSource">当前来源:{{ configSource === 'database' ? '已保存到本系统' : '后端配置文件' }}。</template>
</small>
</div>
</div>
<div class="integration-tool">
<div>
<strong>验证并同步飞书审批</strong>
<small>校验该审批定义可用,同步流程节点到本系统,并订阅此审批的事件以实现状态实时更新。</small>
<span
v-if="approvalSyncStatus"
class="sync-status"
:class="approvalSyncStatus.success ? 'success-copy' : 'danger-copy'"
:role="approvalSyncStatus.success ? 'status' : 'alert'"
aria-live="polite"
>{{ approvalSyncStatus.message }}</span>
</div>
<button
v-if="canApprovalSync"
class="btn small"
type="button"
:disabled="approvalSyncing || saving || !approvalCode"
:aria-busy="approvalSyncing"
@click="syncApprovalDefinition"
>{{ approvalSyncing ? '验证中…' : '验证并同步飞书审批' }}</button>
</div>
</div>
<div class="modal-actions integration-actions">
<span v-if="saveHint" class="test-result" :class="saveHint.success ? 'success-copy' : 'danger-copy'" role="status">{{ saveHint.message }}</span>
<button
v-if="canManage"
class="btn primary"
type="button"
:disabled="saving || approvalSyncing || !approvalCode"
:aria-busy="saving"
@click="saveApprovalCode"
>{{ saving ? '保存中…' : '保存审批编码' }}</button>
</div>
</section>
</template>
</template>
</div>
<div
v-show="activeTab === 'kingdee'"
id="config-panel-kingdee"
role="tabpanel"
aria-labelledby="config-tab-kingdee"
>
<div v-if="!canViewKingdee" class="card empty-state" role="alert">
<strong>无权查看金蝶账号绑定</strong>
<span>需要「金蝶账号绑定」权限,可在角色中分配给财务或其他角色。</span>
</div>
<template v-else>
<div class="inline-note integration-note">
在「人员与角色」中可分别配置:查看本人/全部、绑定本人/全部、解绑本人/全部。财务默认仅本人;系统同步仍使用配置文件中的金蝶系统账号。
</div>
<KingdeeAccountBindingPanel embedded />
</template>
</div>
<div
v-show="activeTab === 'scheduled-tasks'"
id="config-panel-scheduled-tasks"
role="tabpanel"
aria-labelledby="config-tab-scheduled-tasks"
tabindex="0"
>
<ScheduledTasks v-if="canViewScheduledTasks && activeTab === 'scheduled-tasks'" embedded />
</div>
</template>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { adminApi, type IntegrationConfig, type IntegrationField } from '@/api/admin'
import { adminApi } from '@/api/admin'
import KingdeeAccountBindingPanel from '@/components/KingdeeAccountBindingPanel.vue'
import { useUserStore } from '@/store/user'
import ScheduledTasks from '@/views/ScheduledTasks.vue'
type StatusHint = { success: boolean; message: string }
type TabKey = 'feishu' | 'kingdee' | 'scheduled-tasks'
type ProviderKey = 'feishu' | 'kingdee'
type ProviderCode = 'FEISHU' | 'KINGDEE'
type ProviderForm = { enabled: boolean; fields: IntegrationField[]; values: Record<string, string> }
type TestResult = { success: boolean; message: string }
const userStore = useUserStore()
const providers: { key: ProviderKey; code: ProviderCode; label: string }[] = [{ key: 'feishu', code: 'FEISHU', label: '飞书集成' }, { key: 'kingdee', code: 'KINGDEE', label: '金蝶集成' }]
const forms = reactive<Record<ProviderKey, ProviderForm>>({ feishu: { enabled: false, fields: [], values: {} }, kingdee: { enabled: false, fields: [], values: {} } })
const loading = ref(false); const loadError = ref(''); const saving = ref<ProviderKey | ''>(''); const testing = ref<ProviderKey | ''>(''); const testResults = ref<Partial<Record<ProviderKey, TestResult>>>({})
const legacyAdmin = computed(() => ['ADMIN', 'SUPER_ADMIN'].includes(userStore.userInfo?.userType || ''))
const useLegacyFallback = computed(() => userStore.token === 'demo-local-session' || Boolean(userStore.permissionsError))
const canView = computed(() => userStore.permissionsLoaded && !userStore.permissionsError ? userStore.hasPermission('system:integration:view') : useLegacyFallback.value && legacyAdmin.value)
const canManage = computed(() => canView.value && (userStore.hasPermission('system:integration:manage') || (useLegacyFallback.value && legacyAdmin.value)))
const canTest = computed(() => canView.value && (userStore.hasPermission('system:integration:test') || (useLegacyFallback.value && legacyAdmin.value)))
const errorText = (error: unknown) => error instanceof Error && error.message ? error.message : '请求失败,请稍后重试。'
const displayValue = (value: unknown) => { const text = String(value ?? '').trim(); return text || '未配置' }
const loadConfig = async () => { loading.value = true; loadError.value = ''; try { await userStore.loadPermissions(); if (!canView.value) return; const config = await adminApi.getIntegrationConfig(); applyConfig(config) } catch (error) { loadError.value = errorText(error); ElMessage.error(`配置加载失败:${loadError.value}`) } finally { loading.value = false } }
const applyConfig = (config: IntegrationConfig) => { providers.forEach(provider => { const source = config?.[provider.key]; forms[provider.key].enabled = Boolean(source?.enabled); forms[provider.key].fields = Array.isArray(source?.fields) ? source.fields : []; forms[provider.key].values = {}; forms[provider.key].fields.forEach(field => { // Never copy a secret returned by the API into a displayable form value.
if (!field.secret) forms[provider.key].values[field.key] = String(field.value ?? '')
}) }) }
const buildValues = (key: ProviderKey) => { const values: Record<string, unknown> = {}; forms[key].fields.forEach(field => { const value = forms[key].values[field.key] || ''; if (!field.secret || value.trim()) values[field.key] = value }) ; return values }
const saveProvider = async (key: ProviderKey) => { saving.value = key; try { await adminApi.updateIntegrationConfig(key === 'feishu' ? 'FEISHU' : 'KINGDEE', forms[key].enabled, buildValues(key)); forms[key].fields.forEach(field => { if (field.secret && forms[key].values[field.key]) { field.configured = true; forms[key].values[field.key] = '' } }); ElMessage.success(`${key === 'feishu' ? '飞书' : '金蝶'}配置已保存`) } catch (error) { ElMessage.error(`配置保存失败:${errorText(error)}`) } finally { saving.value = '' } }
const testConnection = async (key: ProviderKey) => { testing.value = key; testResults.value[key] = undefined; try { const result = await adminApi.testIntegration(key === 'feishu' ? 'FEISHU' : 'KINGDEE'); testResults.value[key] = { success: Boolean(result?.success), message: result?.message || (result?.success ? '连接成功' : '连接失败') }; if (result?.success) ElMessage.success(testResults.value[key]?.message || '连接成功'); else ElMessage.error(testResults.value[key]?.message || '连接失败') } catch (error) { const message = errorText(error); testResults.value[key] = { success: false, message }; ElMessage.error(`连接测试失败:${message}`) } finally { testing.value = '' } }
onMounted(() => { void loadConfig() })
const route = useRoute()
const router = useRouter()
const loading = ref(false)
const loadError = ref('')
const saving = ref(false)
const approvalSyncing = ref(false)
const approvalCode = ref('')
const feishuEnabled = ref(false)
const configSource = ref('')
const approvalSyncStatus = ref<StatusHint | null>(null)
const saveHint = ref<StatusHint | null>(null)
const activeTab = ref<TabKey>('feishu')
const feishuLoaded = ref(false)
const canViewFeishu = computed(() => userStore.canRead('page.integration-config'))
const canViewKingdee = computed(() => userStore.canRead('page.kingdee-account-binding'))
const canViewScheduledTasks = computed(() => userStore.canRead('page.scheduled-tasks'))
const canOpenPage = computed(() => canViewFeishu.value || canViewKingdee.value || canViewScheduledTasks.value)
const canManage = computed(() => userStore.canEdit('system.integration.config.update'))
const canApprovalSync = computed(() => userStore.canEdit('system.integration.feishu.approval.sync'))
const visibleTabs = computed(() => {
const tabs: { key: TabKey; label: string }[] = []
// Config managers always see both sections; finance-only users see Kingdee.
if (canViewFeishu.value) {
tabs.push({ key: 'feishu', label: '飞书审批配置' })
}
if (canViewKingdee.value) tabs.push({ key: 'kingdee', label: '金蝶账号绑定' })
if (canViewScheduledTasks.value) tabs.push({ key: 'scheduled-tasks', label: '自动任务' })
return tabs
})
const errorText = (error: unknown) => {
const responseMessage = (error as { response?: { data?: { message?: unknown } } })?.response?.data?.message
if (typeof responseMessage === 'string' && responseMessage.trim()) return responseMessage
return error instanceof Error && error.message ? error.message : '请求失败,请稍后重试。'
}
const approvalSyncErrorText = (error: unknown) => {
const response = (error as { response?: { status?: number; data?: { message?: unknown } } } | null)?.response
const responseMessage = typeof response?.data?.message === 'string' ? response.data.message.trim() : ''
const thrownMessage = error instanceof Error ? error.message.trim() : ''
if (response?.status === 401 || response?.status === 403) {
return [responseMessage, thrownMessage].find(message => /权限|授权|无权|登录|认证/.test(message))
|| '权限不足或登录已过期,请重新登录后重试。'
}
if (response?.status === 400 || response?.status === 409 || response?.status === 502) {
return responseMessage || thrownMessage || '验证失败,请检查审批定义编码与飞书应用配置后重试。'
}
if (!response?.status && thrownMessage) return thrownMessage
return '验证失败,请检查审批定义编码与飞书应用配置后重试。'
}
const selectTab = (key: TabKey) => {
activeTab.value = key
const query = { ...route.query, tab: key }
void router.replace({ query })
}
const resolveTabFromRoute = () => {
const raw = String(route.query.tab || '').trim().toLowerCase()
if (raw === 'kingdee' && canViewKingdee.value) {
activeTab.value = 'kingdee'
return
}
if (raw === 'feishu' && canViewFeishu.value) {
activeTab.value = 'feishu'
return
}
if (raw === 'scheduled-tasks' && canViewScheduledTasks.value) {
activeTab.value = 'scheduled-tasks'
return
}
activeTab.value = visibleTabs.value[0]?.key || 'feishu'
}
const loadConfig = async () => {
if (!canViewFeishu.value) return
loading.value = true
loadError.value = ''
try {
const config = await adminApi.getIntegrationConfig()
const feishu = config?.feishu
feishuEnabled.value = Boolean(feishu?.enabled)
configSource.value = feishu?.source || ''
const field = (Array.isArray(feishu?.fields) ? feishu.fields : [])
.find(item => item.key === 'approvalCode')
approvalCode.value = String(field?.value ?? '').trim()
feishuLoaded.value = true
} catch (error) {
loadError.value = errorText(error)
ElMessage.error(`配置加载失败:${loadError.value}`)
} finally {
loading.value = false
}
}
const saveApprovalCode = async () => {
if (!canManage.value || saving.value || approvalSyncing.value) return
const code = approvalCode.value.trim()
if (!code) {
ElMessage.warning('请填写审批定义编码')
return
}
saving.value = true
saveHint.value = null
try {
await adminApi.updateIntegrationConfig('FEISHU', true, { approvalCode: code })
approvalCode.value = code
configSource.value = 'database'
saveHint.value = { success: true, message: '审批定义编码已保存' }
ElMessage.success('审批定义编码已保存')
} catch (error) {
const message = errorText(error)
saveHint.value = { success: false, message }
ElMessage.error(`保存失败:${message}`)
} finally {
saving.value = false
}
}
const syncApprovalDefinition = async () => {
if (!canApprovalSync.value || approvalSyncing.value || saving.value) return
if (!approvalCode.value.trim()) {
ElMessage.warning('请先填写并保存审批定义编码')
return
}
approvalSyncing.value = true
approvalSyncStatus.value = null
try {
const result = await adminApi.syncFeishuApprovalDefinition()
const message = result?.message
|| (result?.eventSubscribed === false
? '已验证审批定义;事件订阅已存在'
: '已验证审批定义并完成事件订阅')
approvalSyncStatus.value = { success: true, message }
ElMessage.success(message)
} catch (error) {
const message = approvalSyncErrorText(error)
approvalSyncStatus.value = { success: false, message }
ElMessage.error(message)
} finally {
approvalSyncing.value = false
}
}
watch(() => route.query.tab, () => resolveTabFromRoute())
watch(activeTab, key => {
if (key === 'feishu' && canViewFeishu.value && !feishuLoaded.value && !loading.value) {
void loadConfig()
}
})
onMounted(async () => {
await userStore.loadPermissions()
resolveTabFromRoute()
if (activeTab.value === 'feishu' && canViewFeishu.value) void loadConfig()
})
</script>
<style scoped>
.integration-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 350px), 1fr)); gap: 16px; align-items: stretch; }
.integration-page { display: flex; min-height: 0; flex: 1 1 auto; flex-direction: column; }
.integration-tabs { margin-bottom: 14px; }
.integration-page > [role="tabpanel"] { min-width: 0; }
#config-panel-scheduled-tasks { display: flex; min-height: 0; flex: 1 1 auto; flex-direction: column; }
.integration-note { margin-top: 0; margin-bottom: 14px; }
.integration-card { display: flex; flex-direction: column; min-width: 0; }
.integration-body { display: flex; flex: 1; flex-direction: column; min-width: 0; padding: 0 18px; }
.integration-body > .empty-state { flex: 1; }
.enabled-row { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 16px 0 12px; border-bottom: 1px solid var(--line); }
.enabled-row strong, .enabled-row small { display: block; }
.enabled-row strong { font-size: 12px; }
.enabled-row small { color: var(--muted); font-size: 11px; }
.integration-body { display: flex; flex: 1; flex-direction: column; min-width: 0; padding: 0 22px; }
.integration-form { padding: 17px 0 20px; grid-template-columns: minmax(0, 1fr); gap: 13px; }
.configured-label { margin-left: 5px; color: var(--success); font-weight: 400; }
.integration-tool { display: flex; align-items: center; justify-content: space-between; gap: 14px; padding: 13px 0 16px; border-top: 1px solid var(--line); }
.integration-tool > div { min-width: 0; }
.integration-tool strong, .integration-tool small, .sync-status { display: block; overflow-wrap: anywhere; }
.integration-tool strong { font-size: 12px; }
.integration-tool small { margin-top: 2px; color: var(--muted); font-size: 11px; }
.sync-status { margin-top: 5px; font-size: 11px; }
.field-hint { margin-top: 3px; color: var(--text); font-size: 12px; line-height: 1.55; overflow-wrap: anywhere; }
.integration-actions { align-items: center; min-height: 59px; flex-wrap: wrap; margin-top: auto; }
.test-result { min-width: 0; max-width: 100%; margin-right: auto; font-size: 11px; }
.success-copy { color: var(--success); }
.danger-copy { color: var(--danger); }
@media (max-width: 760px) { .integration-grid { grid-template-columns: 1fr; } .integration-actions { justify-content: flex-end; } .test-result { width: 100%; margin-right: 0; } }
@media (max-width: 760px) {
.integration-actions { justify-content: flex-end; }
.test-result { width: 100%; margin-right: 0; }
.integration-tool { align-items: stretch; flex-direction: column; }
.integration-tool .btn { width: 100%; }
}
</style>
+16
View File
@@ -0,0 +1,16 @@
<template>
<div class="page-content route-list-page">
<div class="page-head">
<div>
<span class="eyebrow">FINANCE · KINGDEE</span>
<h1>金蝶账号绑定</h1>
<p>财务角色须绑定个人金蝶云星空账号后,方可变更金蝶财务单据。系统同步仍使用配置文件中的系统账号。</p>
</div>
</div>
<KingdeeAccountBindingPanel />
</div>
</template>
<script setup lang="ts">
import KingdeeAccountBindingPanel from '@/components/KingdeeAccountBindingPanel.vue'
</script>
+99 -214
View File
@@ -12,62 +12,55 @@
</span>
</div>
<div class="product-name">
员工报销工作台
<span>财务与报销管理</span>
<strong>费用与付款</strong>
<span>SPEND OPERATIONS</span>
</div>
<nav class="main-nav" aria-label="主导航">
<div class="nav-group" v-if="canAccess('dashboard')">
<span>工作台</span>
<div class="nav-group" v-if="canAccess('page.dashboard')">
<span>工作空间</span>
<router-link to="/dashboard" @click="sidebarOpen = false" :class="{ active: route.path === '/dashboard' }" :aria-current="route.path === '/dashboard' ? 'page' : undefined">
<b aria-hidden="true"><House /></b> 工作台
<b aria-hidden="true"><House /></b> 首页
</router-link>
</div>
<div class="nav-group" v-if="canAccess('applications')">
<span>报销管理</span>
<router-link to="/applications" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/applications') }" :aria-current="route.path.startsWith('/applications') ? 'page' : undefined">
<b aria-hidden="true"><DocumentCopy /></b> 我的报销 <i class="nav-count">{{ mineCount }}</i>
<div class="nav-group" v-if="canAnyPage(['page.applications', 'page.application-create', 'page.application-edit', 'page.source-documents'])">
<span>申请与报销</span>
<router-link v-if="canAccess('page.applications')" to="/applications" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/applications') }" :aria-current="route.path.startsWith('/applications') ? 'page' : undefined">
<b aria-hidden="true"><DocumentCopy /></b> 付款申请 <i class="nav-count">{{ mineCount }}</i>
</router-link>
<router-link v-if="canAccess('application-create')" to="/applications/new" @click="sidebarOpen = false"><b aria-hidden="true"><Plus /></b> 发起报销</router-link>
</div>
<div class="nav-group" v-if="canAccess('finance')">
<span>财务处理</span>
<router-link v-if="canAccess('finance-receipt')" to="/finance-receipt" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/finance-receipt') }" :aria-current="route.path.startsWith('/finance-receipt') ? 'page' : undefined">
<b aria-hidden="true"><Tickets /></b> 财务待收单 <i class="nav-count warning">{{ receiptCount }}</i>
</router-link>
<router-link v-if="canAccess('sources')" to="/sources" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/sources') }" :aria-current="route.path.startsWith('/sources') ? 'page' : undefined">
<router-link v-if="canAccess('page.application-create')" to="/applications/new" @click="sidebarOpen = false"><b aria-hidden="true"><Plus /></b> 发起申请</router-link>
<router-link v-if="canAccess('page.source-documents')" to="/sources" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/sources') }" :aria-current="route.path.startsWith('/sources') ? 'page' : undefined">
<b aria-hidden="true"><Files /></b> 业务单据
</router-link>
<router-link v-if="canAccess('payments')" to="/payments" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/payments') }" :aria-current="route.path.startsWith('/payments') ? 'page' : undefined">
<b aria-hidden="true"><Wallet /></b> 待付款 <i class="nav-count">{{ paymentCount }}</i>
</div>
<div class="nav-group" v-if="canAnyPage(['page.finance-receipt', 'page.payments'])">
<span>财务处理</span>
<router-link v-if="canAccess('page.finance-receipt')" to="/finance-receipt" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/finance-receipt') }" :aria-current="route.path.startsWith('/finance-receipt') ? 'page' : undefined">
<b aria-hidden="true"><Tickets /></b> 财务处理中心 <i class="nav-count warning">{{ receiptCount }}</i>
</router-link>
<router-link v-if="canAccess('logs')" to="/logs" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/logs') }" :aria-current="route.path.startsWith('/logs') ? 'page' : undefined">
<b aria-hidden="true"><Memo /></b> 操作日志
<router-link v-if="canAccess('page.payments')" to="/payments" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/payments') }" :aria-current="route.path.startsWith('/payments') ? 'page' : undefined">
<b aria-hidden="true"><Wallet /></b> 待付款 <i class="nav-count">{{ paymentCount }}</i>
</router-link>
</div>
<div class="nav-group admin-nav" v-if="canAccess('master-data')">
<span>基础设置</span>
<router-link v-if="canAccess('expense-types')" to="/expense-types" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/expense-types') }" :aria-current="route.path.startsWith('/expense-types') ? 'page' : undefined">
<div class="nav-group admin-nav" v-if="canAnyPage(['page.expense-types', 'page.payees', 'page.roles', 'page.groups', 'page.integration-config', 'page.kingdee-account-binding', 'page.feishu-directory', 'page.scheduled-tasks', 'page.operation-log'])">
<span>管理中心</span>
<router-link v-if="canAnyPage(['page.groups', 'page.roles', 'page.feishu-directory'])" to="/users" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/users') }" :aria-current="route.path.startsWith('/users') ? 'page' : undefined">
<b aria-hidden="true"><Setting /></b> 人员与角色
</router-link>
<router-link v-if="canAccess('page.expense-types')" to="/expense-types" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/expense-types') }" :aria-current="route.path.startsWith('/expense-types') ? 'page' : undefined">
<b aria-hidden="true"><CollectionTag /></b> 费用类型
</router-link>
<router-link v-if="canAccess('payees')" to="/payees" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/payees') }" :aria-current="route.path.startsWith('/payees') ? 'page' : undefined">
<router-link v-if="canAccess('page.payees')" to="/payees" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/payees') }" :aria-current="route.path.startsWith('/payees') ? 'page' : undefined">
<b aria-hidden="true"><User /></b> 付款对象
</router-link>
</div>
<div class="nav-group admin-nav" v-if="canAccess('admin') || canAccess('integration') || canAccess('feishu-directory')">
<span>系统管理</span>
<router-link v-if="canAccess('admin')" to="/users" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/users') }" :aria-current="route.path.startsWith('/users') ? 'page' : undefined">
<b aria-hidden="true"><Setting /></b> 用户管理
</router-link>
<router-link v-if="canAccess('integration')" to="/integration-config" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/integration-config') }" :aria-current="route.path.startsWith('/integration-config') ? 'page' : undefined">
<b aria-hidden="true"><Connection /></b> 配置管理
</router-link>
<router-link v-if="canAccess('feishu-directory')" to="/feishu-directory" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/feishu-directory') }" :aria-current="route.path.startsWith('/feishu-directory') ? 'page' : undefined">
<b aria-hidden="true"><Connection /></b> 飞书通讯录
</router-link>
<router-link v-if="canAnyPage(['page.integration-config', 'page.kingdee-account-binding', 'page.scheduled-tasks'])" :to="configNavTo" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/integration-config') || route.path.startsWith('/scheduled-tasks') }" :aria-current="route.path.startsWith('/integration-config') || route.path.startsWith('/scheduled-tasks') ? 'page' : undefined">
<b aria-hidden="true"><Connection /></b> 配置管理
</router-link>
<router-link v-if="canAccess('page.operation-log')" to="/logs" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/logs') }" :aria-current="route.path.startsWith('/logs') ? 'page' : undefined">
<b aria-hidden="true"><Memo /></b> 操作日志
</router-link>
</div>
</nav>
<div class="sidebar-foot">
@@ -84,13 +77,13 @@
<div class="topbar-left">
<button class="icon-button mobile-menu" type="button" :aria-expanded="sidebarOpen" aria-controls="primary-navigation" @click="sidebarOpen = !sidebarOpen" aria-label="打开导航"><Menu /></button>
<div class="breadcrumb">
<span>报销管理</span>
<span>统一费用付款平台</span>
<i>/</i>
<strong>{{ pageTitle }}</strong>
</div>
</div>
<div class="topbar-tools">
<label class="search-box"><Search aria-hidden="true" /><input v-model="search" type="search" placeholder="搜索报销单号、事项或收款人" aria-label="全局搜索" @keyup.enter="runSearch"></label>
<label class="search-box"><Search aria-hidden="true" /><input v-model="search" type="search" placeholder="搜索付款申请、业务单据或收款对象" aria-label="全局搜索" @keyup.enter="runSearch"></label>
<button class="icon-button" type="button" @click="showHelp" aria-label="查看帮助" title="帮助"><QuestionFilled /></button>
<button ref="notificationButton" class="icon-button notification" @click="showNotifications" :aria-label="notificationButtonLabel" title="通知">
<Bell aria-hidden="true" />
@@ -103,7 +96,7 @@
</div>
</header>
<div class="data-sync-banner" role="status"><span class="source-pill" :class="sourceTone">{{ sourceLabel }}</span><p>{{ sourceMessage }}</p><button v-if="workbench.error || workbench.source === 'error'" class="btn small" type="button" @click="workbench.load">重新同步</button></div>
<div v-if="showDataSyncBanner" class="data-sync-banner" role="status"><span class="source-pill" :class="sourceTone">{{ sourceLabel }}</span><p>{{ sourceMessage }}</p><button v-if="workbench.error || workbench.source === 'error'" class="btn small" type="button" @click="workbench.load">重新同步</button></div>
<main id="main-content" class="page-stage" aria-live="polite">
<router-view />
</main>
@@ -111,17 +104,18 @@
<dialog
ref="notificationDialog"
class="notification-dialog"
v-dialog-drag
class="app-dialog notification-dialog"
aria-labelledby="notification-dialog-title"
aria-modal="true"
@click="handleDialogClick"
@cancel="handleDialogCancel"
@close="handleNotificationsClosed"
>
<section ref="notificationPanel" class="notification-dialog-panel" :style="notificationPanelStyle" aria-describedby="notification-dialog-description">
<header class="notification-modal-head" title="拖动通知面板" @pointerdown="startNotificationDrag">
<section class="app-dialog__panel notification-dialog-panel" aria-describedby="notification-dialog-description">
<header class="notification-modal-head" data-dialog-drag-handle title="拖动通知面板">
<div>
<span class="eyebrow">通知中心</span>
<span class="eyebrow">NOTIFICATION CENTER</span>
<h2 id="notification-dialog-title">通知</h2>
<p id="notification-dialog-description">
{{ notificationItems.length ? `共 ${notificationItems.length} 条待关注事项` : '暂无待关注事项' }}
@@ -163,7 +157,7 @@
<span>新的报销进度和付款状态会显示在这里。</span>
</div>
<footer class="notification-modal-actions">
<button class="btn small" type="button" @click="closeNotifications">关闭</button>
<button class="btn" type="button" @click="closeNotifications">关闭</button>
</footer>
</section>
</dialog>
@@ -171,10 +165,10 @@
</template>
<script setup lang="ts">
import { ref, computed, nextTick, onBeforeUnmount, onMounted, watch } from 'vue'
import { ref, computed, nextTick, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { authApi } from '@/api/auth'
import { authApi, type UserProfile } from '@/api/auth'
import { useWorkbenchStore } from '@/store/workbench'
import type { ReimApplicationDetail } from '@/api/reimbursement'
import { ElMessage, ElMessageBox } from 'element-plus'
@@ -198,16 +192,8 @@ const sidebarOpen = ref(false)
const search = ref('')
const notificationButton = ref<HTMLButtonElement | null>(null)
const notificationDialog = ref<HTMLDialogElement | null>(null)
const notificationPanel = ref<HTMLElement | null>(null)
const notificationItems = ref<NotificationItem[]>([])
const notificationPosition = ref({ left: 0, top: 0 })
let notificationTrigger: HTMLElement | null = null
let notificationDragOffset = { x: 0, y: 0 }
const notificationPanelStyle = computed(() => ({
left: `${notificationPosition.value.left}px`,
top: `${notificationPosition.value.top}px`,
}))
onMounted(async () => {
// 刷新时从后端获取最新的用户信息(包括角色变更)
@@ -237,76 +223,62 @@ onMounted(async () => {
// Management navigation is deliberately fail-closed. The request
// interceptor already reports the transport/API error to the user.
}
if (!workbench.reimbursements.length) void workbench.load()
void loadWorkbenchIfAllowed()
})
const userType = computed(() => userStore.userInfo?.userType || '')
const userName = computed(() => userStore.userInfo?.realName || '用户')
const userInitial = computed(() => userName.value.charAt(0) || '用')
const userTypeLabel = computed(() => {
const resolveUserTypeLabel = (profile: UserProfile | null) => {
const labels: Record<string, string> = {
'SUPER_ADMIN': '超级管理员',
'ADMIN': '系统管理员',
'FINANCE': '财务人员',
'EMPLOYEE': '员工',
SUPER_ADMIN: '超级管理员',
ADMIN: '系统管理员',
FINANCE: '财务人员',
EMPLOYEE: '员工',
}
return labels[userType.value] || userType.value || '普通用户'
})
const hasEffectiveRoleData = typeof profile?.isSuperAdmin === 'boolean' || Array.isArray(profile?.roleCodes)
if (hasEffectiveRoleData) {
const roleCodes = (profile?.roleCodes || []).map(code => String(code).trim().toUpperCase())
if (profile?.isSuperAdmin === true || roleCodes.includes('SUPER_ADMIN')) return labels.SUPER_ADMIN
const effectiveRole = ['ADMIN', 'FINANCE', 'EMPLOYEE'].find(code => roleCodes.includes(code))
return effectiveRole ? labels[effectiveRole] : '普通用户'
}
const fallbackType = String(profile?.userType || '').trim().toUpperCase()
return labels[fallbackType] || profile?.userType || '普通用户'
}
const userTypeLabel = computed(() => resolveUserTypeLabel(userStore.userInfo))
const pageTitle = computed(() => {
const meta = route.meta?.title as string
return meta || '工作台'
})
// Permission map: which modules each userType can access
const modulePermissions: Record<string, string[]> = {
ADMIN: ['dashboard', 'applications', 'finance', 'payments', 'sources', 'logs', 'master-data', 'admin'],
SUPER_ADMIN: ['dashboard', 'applications', 'finance', 'payments', 'sources', 'logs', 'master-data', 'admin'],
FINANCE: ['dashboard', 'applications', 'finance', 'payments', 'sources', 'logs', 'master-data'],
EMPLOYEE: ['dashboard', 'applications'],
// Navigation is derived exclusively from page.* permissions. Missing and
// failed permission state is hidden by the store's fail-closed accessors.
const canAccess = (code: string) => userStore.canRead(code)
const canAnyPage = (codes: string[]) => userStore.canAny(codes)
/** Finance-only users land on the Kingdee binding tab; admins open Feishu by default. */
const configNavTo = computed(() => {
if (canAccess('page.integration-config')) return '/integration-config'
if (canAccess('page.kingdee-account-binding')) {
return { path: '/integration-config', query: { tab: 'kingdee' } }
}
return { path: '/integration-config', query: { tab: 'scheduled-tasks' } }
})
const snapshotPermissionByRoute: Record<string, string> = {
Dashboard: 'page.dashboard',
Applications: 'page.applications',
ApplicationNew: 'page.application-create',
ApplicationDetail: 'page.applications',
ApplicationEdit: 'page.application-edit',
}
const permissions = computed(() => modulePermissions[userType.value] || ['dashboard'])
const legacyAdmin = computed(() => ['ADMIN', 'SUPER_ADMIN'].includes(userType.value))
const permissionByModule: Record<string, string[]> = {
dashboard: ['applications', 'reimbursement:view-own'],
applications: ['applications', 'reimbursement:view-own'],
'application-create': ['reimbursement:create'],
finance: ['receipt:manage', 'reimbursement:view-all', 'payment:register', 'approval:view'],
'finance-receipt': ['receipt:manage'],
payments: ['payment:register'],
sources: ['reimbursement:view-all'],
logs: ['approval:view'],
'master-data': ['master-data:manage'],
'expense-types': ['master-data:manage'],
payees: ['master-data:manage'],
'feishu-directory': ['system:feishu:sync', 'system:feishu:bind'],
}
const legacyModuleByRoute: Record<string, string> = {
dashboard: 'dashboard', applications: 'applications', 'application-create': 'applications',
finance: 'finance', 'finance-receipt': 'finance', payments: 'finance', sources: 'finance', logs: 'finance',
'expense-types': 'master-data', payees: 'master-data',
}
const useLegacyNavigation = computed(() => userStore.token === 'demo-local-session' || Boolean(userStore.permissionsError))
const hasSystemPermission = (code: string) => {
if (userStore.permissionsLoaded && !userStore.permissionsError) return userStore.hasPermission(code)
return useLegacyNavigation.value && legacyAdmin.value
}
const canAccess = (routeName: string) => {
if (routeName === 'admin') return hasSystemPermission('system:user:view')
if (routeName === 'integration') return hasSystemPermission('system:integration:view')
// Unlike the older navigation groups, this entry is never exposed by a
// demo/role fallback: it is granted only by the two directory permissions.
if (routeName === 'feishu-directory') {
return userStore.permissionsLoaded
&& !userStore.permissionsError
&& (permissionByModule[routeName] || []).some(code => userStore.hasPermission(code))
}
const required = permissionByModule[routeName] || [routeName]
if (userStore.permissionsLoaded && !userStore.permissionsError) return required.some(code => userStore.hasPermission(code))
return useLegacyNavigation.value && permissions.value.includes(legacyModuleByRoute[routeName] || routeName)
}
const currentSnapshotPermission = computed(() => snapshotPermissionByRoute[String(route.name || '')] || '')
const showDataSyncBanner = computed(() => Boolean(currentSnapshotPermission.value) && canAccess(currentSnapshotPermission.value))
const loadWorkbenchIfAllowed = async () => {
if (!showDataSyncBanner.value || workbench.reimbursements.length || workbench.loading) return
await workbench.load()
}
watch(() => route.name, () => { void loadWorkbenchIfAllowed() })
const mineCount = computed(() => workbench.reimbursements.filter(item => item.applicantName === userName.value).length)
const receiptCount = computed(() => workbench.reimbursements.filter(item => item.receiptStatus === '待收单').length)
const paymentCount = computed(() => workbench.reimbursements.filter(item => workbench.balance(item) > 0 && item.receiptStatus === '已收单').length)
@@ -347,7 +319,7 @@ const money = (value: unknown) => {
return `¥ ${Number.isFinite(amount) ? amount.toLocaleString('zh-CN', { minimumFractionDigits: 2 }) : '0.00'}`
}
const notificationTime = (item: ReimApplicationDetail) => displayText(item.updatedAt || item.createdAt, '刚刚')
const financeRoute = (item: ReimApplicationDetail) => canAccess('finance') ? '/finance-receipt' : applicationRoute(item)
const financeRoute = (item: ReimApplicationDetail) => canAccess('page.finance-receipt') ? '/finance-receipt' : applicationRoute(item)
const buildNotifications = (count: number) => {
const rows = workbench.reimbursements
@@ -376,7 +348,7 @@ const buildNotifications = (count: number) => {
id: `payment-${displayText(item.id, applicationName(item))}`,
title: '报销单待付款',
message: `${applicationName(item)} 已完成收单,待付款金额 ${money(workbench.balance(item))}。`,
time: notificationTime(item), icon: 'Wallet', tone: 'success', route: canAccess('finance') ? '/payments' : applicationRoute(item),
time: notificationTime(item), icon: 'Wallet', tone: 'success', route: canAccess('page.payments') ? '/payments' : applicationRoute(item),
}))
// Only render notifications that can be traced back to a real business row.
@@ -388,51 +360,6 @@ const buildNotifications = (count: number) => {
}))
}
const clampNotificationPosition = (left: number, top: number) => {
const panel = notificationPanel.value
const width = panel?.offsetWidth || 450
const height = panel?.offsetHeight || 360
return {
left: Math.min(Math.max(12, left), Math.max(12, window.innerWidth - width - 12)),
top: Math.min(Math.max(12, top), Math.max(12, window.innerHeight - height - 12)),
}
}
const positionNotificationPanel = () => {
const button = notificationButton.value
if (!button) return
const buttonRect = button.getBoundingClientRect()
const panelWidth = notificationPanel.value?.offsetWidth || 450
const preferredLeft = buttonRect.right - panelWidth
const preferredTop = buttonRect.bottom + 10
const top = preferredTop + (notificationPanel.value?.offsetHeight || 360) > window.innerHeight
? buttonRect.top - (notificationPanel.value?.offsetHeight || 360) - 10
: preferredTop
notificationPosition.value = clampNotificationPosition(preferredLeft, top)
}
const moveNotificationPanel = (event: PointerEvent) => {
notificationPosition.value = clampNotificationPosition(
event.clientX - notificationDragOffset.x,
event.clientY - notificationDragOffset.y,
)
}
const stopNotificationDrag = () => {
window.removeEventListener('pointermove', moveNotificationPanel)
window.removeEventListener('pointerup', stopNotificationDrag)
}
const startNotificationDrag = (event: PointerEvent) => {
if (event.button !== 0 || (event.target as HTMLElement).closest('button')) return
const panel = notificationPanel.value
if (!panel) return
const rect = panel.getBoundingClientRect()
notificationDragOffset = { x: event.clientX - rect.left, y: event.clientY - rect.top }
window.addEventListener('pointermove', moveNotificationPanel)
window.addEventListener('pointerup', stopNotificationDrag)
}
const restoreNotificationFocus = () => {
if (notificationTrigger?.isConnected) notificationTrigger.focus()
notificationTrigger = null
@@ -455,10 +382,8 @@ const showNotifications = async () => {
if (notificationDialog.value?.open) return
notificationTrigger = document.activeElement instanceof HTMLElement ? document.activeElement : null
notificationItems.value = buildNotifications(unreadNotificationCount.value)
positionNotificationPanel()
notificationDialog.value?.showModal()
await nextTick()
positionNotificationPanel()
notificationDialog.value?.querySelector<HTMLElement>('[data-notification-autofocus]')?.focus()
}
const openNotification = (item: NotificationItem) => {
@@ -466,16 +391,6 @@ const openNotification = (item: NotificationItem) => {
if (item.route) void router.push(item.route)
}
const repositionOpenNotificationPanel = () => {
if (notificationDialog.value?.open) positionNotificationPanel()
}
window.addEventListener('resize', repositionOpenNotificationPanel)
onBeforeUnmount(() => {
stopNotificationDrag()
window.removeEventListener('resize', repositionOpenNotificationPanel)
})
const handleLogout = () => {
if (userStore.token && userStore.token !== 'demo-local-session') void authApi.logout().catch(() => undefined)
workbench.reset()
@@ -494,41 +409,10 @@ watch(() => route.query.denied, value => { if (value) ElMessage.warning(`无权
.notification-count { position: absolute; top: 1px; right: -3px; min-width: 16px; height: 16px; padding: 0 4px; border: 2px solid #fff; border-radius: 99px; background: var(--danger); color: #fff; font-size: 9px; font-weight: 800; line-height: 12px; text-align: center; }
.notification-dialog {
display: block;
position: fixed;
inset: 0;
width: 100%;
max-width: none;
height: 100%;
max-height: none;
margin: 0;
padding: 0;
border: 0;
background: transparent;
color: var(--text);
overflow: hidden;
pointer-events: auto;
}
/* The author styles above must not override the browser's closed-dialog rule. */
.notification-dialog:not([open]) { display: none; }
.notification-dialog::backdrop {
background: transparent;
width: min(450px, calc(100vw - 24px));
}
.notification-dialog-panel {
position: fixed;
display: flex;
width: min(450px, calc(100vw - 24px));
max-height: min(680px, calc(100vh - 32px));
flex-direction: column;
border: 1px solid var(--line);
border-radius: 14px;
background: #fff;
box-shadow: 0 18px 48px #0926402b, 0 3px 10px #09264012;
overflow: hidden;
pointer-events: auto;
animation: notification-pop .16s ease-out;
}
@@ -555,9 +439,8 @@ watch(() => route.query.denied, value => { if (value) ElMessage.warning(`无权
.notification-modal-head h2 { margin-top: 4px; font-size: 19px; }
.notification-modal-head p { margin-top: 3px; color: var(--muted); font-size: 11px; }
.notification-modal-body { max-height: min(480px, calc(100vh - 190px)); padding: 0; overflow-y: auto; }
.notification-list { list-style: none; }
.notification-list li:last-child .notification-item { border-bottom: 0; }
.notification-modal-body { max-height: min(480px, calc(100vh - 190px)); padding: 10px 12px; overflow-y: auto; background: #f6f8fa; }
.notification-list { display: grid; gap: 7px; list-style: none; }
.notification-item {
display: grid;
@@ -565,16 +448,17 @@ watch(() => route.query.denied, value => { if (value) ElMessage.warning(`无权
grid-template-columns: 34px minmax(0, 1fr) auto;
align-items: start;
gap: 11px;
padding: 14px 18px;
border: 0;
border-bottom: 1px solid var(--line);
min-height: 76px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 6px;
background: #fff;
color: var(--text);
text-align: left;
}
.notification-item.actionable { cursor: pointer; }
.notification-item.actionable:hover { background: #f7faff; }
.notification-item.actionable:hover { border-color: #b8cee4; background: #f7faff; }
.notification-item:focus-visible { position: relative; z-index: 1; outline: 3px solid #72adff; outline-offset: -3px; }
.notification-item-icon {
@@ -610,12 +494,13 @@ watch(() => route.query.denied, value => { if (value) ElMessage.warning(`无权
.notification-empty strong { color: var(--body); font-size: 13px; }
.notification-empty span:not(.notification-empty-icon) { margin-top: 3px; color: var(--muted); font-size: 11px; }
.notification-modal-actions { display: flex; justify-content: flex-end; padding: 13px 21px; border-top: 1px solid var(--line); background: var(--surface); }
.notification-modal-actions { display: flex; justify-content: flex-end; padding: 13px 21px; border-top: 1px solid var(--line); background: var(--surface-raised); }
@media (max-width: 680px) {
.notification-dialog-panel { width: calc(100vw - 24px); max-height: calc(100vh - 24px); }
.notification-modal-head { padding: 16px 17px 13px; }
.notification-item { padding: 13px 15px; }
.notification-modal-body { padding: 8px; }
.notification-item { grid-template-columns: 34px minmax(0, 1fr); padding: 11px; }
.notification-item-link { grid-column: 2; padding-top: 0; }
.notification-modal-actions { padding: 12px 17px; }
}
+26 -42
View File
@@ -5,56 +5,54 @@
<span class="brand-mark" aria-hidden="true"><i></i><i></i></span>
<span>
<strong>零差云控</strong>
<small>ZEROERR · 财务管理平台</small>
<small>ZEROERR · 统一费用付款平台</small>
</span>
</header>
<div class="login-layout">
<section class="login-copy" aria-describedby="loginIntro">
<span class="eyebrow">FINANCE WORKSPACE</span>
<h1 id="loginTitle">让每一笔报销,<br><b>清晰地走完全流程</b></h1>
<p id="loginIntro">统一管理报销申请、审批进度与财务处理,让每一个环节都有据可查。</p>
<div class="login-points" aria-label="平台能力">
<span><b aria-hidden="true">01</b>申请与审批状态清晰可见</span>
<span><b aria-hidden="true">02</b>收单与付款记录独立留痕</span>
<span><b aria-hidden="true">03</b>企业统一身份认证,安全访问</span>
</div>
<span class="eyebrow login-eyebrow">企业登录</span>
<h1 id="loginTitle">统一费用付款平台</h1>
<p id="loginIntro">使用飞书账号登录,连接付款申请、审批、收单与付款办理。</p>
</section>
<section class="login-card" aria-labelledby="loginCardTitle" aria-describedby="loginCardDescription">
<div class="feishu-logo" aria-hidden="true">飞</div>
<span class="eyebrow">AUTHORIZED ENTRY</span>
<h2 id="loginCardTitle">使用飞书账号登录</h2>
<p id="loginCardDescription">通过飞书授权验证身份后即可进入系统;通讯录同步用于员工资料与业务管理,不作为登录条件。每日首次访问需重新完成授权。</p>
<h2 id="loginCardTitle">飞书登录</h2>
<p id="loginCardDescription">使用企业飞书账号完成安全身份验证。</p>
<div v-if="loading" class="login-loading" role="status" aria-live="polite">
<p>正在验证身份…</p>
<small>{{ loadingMessage }}</small>
<span class="login-spinner" aria-hidden="true"></span>
<span>
<strong>正在验证身份…</strong>
<small v-if="loadingMessage">{{ loadingMessage }}</small>
</span>
</div>
<div v-else>
<div v-else class="login-action">
<div v-if="loginError" class="inline-alert danger" role="alert">
<b aria-hidden="true">!</b>
<span>{{ loginError }}</span>
</div>
<button
class="btn"
class="btn primary login-submit"
type="button"
:disabled="feishuLoading"
:aria-busy="feishuLoading"
@click="handleFeishuLogin"
>
{{ feishuLoading ? '正在前往飞书…' : '飞书授权登录' }}
<span v-if="feishuLoading" class="login-button-spinner" aria-hidden="true"></span>
<img v-else src="@/assets/feishu-logo.png" alt="">
{{ feishuLoading ? '正在前往飞书…' : '使用飞书登录' }}
</button>
</div>
<div class="login-card-foot">
登录信息由飞书授权提供,本平台不单独维护登录密码
身份授权由飞书提供,本平台不存储飞书密码。通讯录同步用于员工资料与业务管理,不作为登录条件。
</div>
</section>
</div>
<footer class="login-foot">企业财务工作台 · 飞书统一身份认证</footer>
<footer class="login-foot">零差云控 · ZEROERR · 统一费用付款平台</footer>
</div>
</main>
</template>
@@ -104,7 +102,11 @@ onMounted(async () => {
const error = route.query.error as string | undefined
// Do not leave OAuth credentials or one-time codes in browser history.
if (token || code || error) window.history.replaceState({}, document.title, window.location.pathname)
if (token || code || error || state) {
// Replace the current history entry before making any network request. Do
// not retain OAuth credentials in the address bar, referrer, or history.
window.history.replaceState({}, document.title, window.location.pathname)
}
if (error) {
const attempt = sessionStorage.getItem('feishuOAuthAttempt')
@@ -114,27 +116,9 @@ onMounted(async () => {
}
workbench.reset()
loading.value = false
loginError.value = error
ElMessage.error(error)
return
}
if (token) {
loadingMessage.value = '正在获取用户信息…'
try {
// A token callback can follow an expired session or a different user.
// Clear business data before loading the new identity to prevent data
// from the previous session flashing in lists and notifications.
workbench.reset()
await userStore.setToken(token)
ElMessage.success('登录成功')
router.replace('/dashboard')
} catch (e: any) {
userStore.logout()
workbench.reset()
loading.value = false
loginError.value = e?.message || '登录验证失败,请重新授权'
}
// Provider errors may echo sensitive callback data; show a fixed message.
loginError.value = '飞书授权未完成,请重新登录'
ElMessage.error(loginError.value)
return
}
+142 -15
View File
@@ -1,32 +1,159 @@
<template>
<div class="page-content">
<div class="page-content route-list-page">
<div class="page-head">
<div>
<span class="eyebrow">OPERATION LOGS</span>
<h1>操作日志</h1>
<p>系统操作记录,按时间倒序排列。</p>
<p>记录变更类接口访问(不含查看),按时间倒序排列。</p>
</div>
<div class="head-actions">
<button class="btn" type="button" :disabled="!loaded" @click="load">刷新</button>
</div>
</div>
<div class="card fill-list-card">
<div class="timeline" v-if="items.length > 0">
<div class="timeline-item" v-for="item in items" :key="item.id">
<div class="tl-dot" :class="item.action"></div>
<div class="tl-content">
<strong>{{ item.operator }}</strong>
<span>{{ item.action }} · {{ item.detail }}</span>
<small>{{ item.time }}</small>
</div>
</div>
<div class="card filter-card">
<div class="log-filters">
<label class="field">
<span>分类</span>
<select v-model="category" class="select" @change="load">
<option value="">全部</option>
<option v-for="item in categoryOptions" :key="item" :value="item">{{ item }}</option>
</select>
</label>
<label class="field">
<span>操作人</span>
<input v-model.trim="operator" type="search" placeholder="姓名" autocomplete="off" @keyup.enter="load">
</label>
<button class="btn primary" type="button" @click="load">查询</button>
</div>
<div class="empty-state" v-else-if="loaded"><strong>暂无操作日志</strong></div>
</div>
<div class="card fill-list-card primary-list-card">
<div class="card-head">
<div>
<h2>接口访问记录</h2>
<p>包含方法、路径、状态码与耗时。</p>
</div>
<span>{{ items.length }} 条</span>
</div>
<div v-if="loaded && !error && items.length" class="table-wrap" tabindex="0" role="region" aria-label="操作日志列表">
<table class="data-table responsive-table">
<thead>
<tr>
<th>时间</th>
<th>操作人</th>
<th>分类</th>
<th>接口</th>
<th>状态</th>
<th>耗时</th>
<th>详情</th>
</tr>
</thead>
<tbody>
<tr v-for="item in paginatedItems" :key="item.id">
<td data-label="时间"><small>{{ item.time || '—' }}</small></td>
<td data-label="操作人"><strong>{{ item.operator || '匿名' }}</strong></td>
<td data-label="分类"><span class="tag neutral">{{ item.category || '接口访问' }}</span></td>
<td data-label="接口">
<strong class="log-method" :class="methodTone(item.method)">{{ item.method || methodFromAction(item.action) }}</strong>
<small>{{ item.path || pathFromAction(item.action) }}</small>
</td>
<td data-label="状态"><span class="tag" :class="statusTone(item.statusCode)">{{ item.statusCode ?? '—' }}</span></td>
<td data-label="耗时"><span class="mono">{{ item.durationMs != null ? `${item.durationMs} ms` : '—' }}</span></td>
<td data-label="详情"><small class="log-detail">{{ item.detail || '—' }}</small></td>
</tr>
</tbody>
</table>
</div>
<div v-else-if="error" class="empty-state" role="alert"><strong>操作日志加载失败</strong><span>{{ error }}</span><button class="btn small" type="button" @click="load">重试</button></div>
<div class="empty-state" v-else-if="loaded"><strong>暂无操作日志</strong><span>访问任意接口后会自动出现在这里。</span></div>
<div v-else class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载操作日志…</span></div>
<AppListPagination v-if="loaded && !error && items.length" v-model:page="page" v-model:page-size="pageSize" :total="items.length" aria-label="操作日志分页" />
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import request from '@/api/request'
const items = ref<any[]>([])
import AppListPagination from '@/components/common/AppListPagination.vue'
import { useListPagination } from '@/composables/useListPagination'
type LogItem = {
id: number | string
operator?: string
action?: string
detail?: string
category?: string
method?: string
path?: string
statusCode?: number
durationMs?: number
time?: string
}
const items = ref<LogItem[]>([])
const loaded = ref(false)
onMounted(async () => { try { items.value = await request.get('/logs') || [] } catch {} finally { loaded.value = true } })
const error = ref('')
const category = ref('')
const operator = ref('')
const categoryOptions = ['接口访问', '认证登录', '报销申请', '付款操作', '收单操作', '飞书通讯录', '飞书集成', '配置管理', '人员权限', '主数据', '自动任务', '系统日志']
const { page, pageSize, paginatedItems } = useListPagination(items)
const methodFromAction = (action?: string) => String(action || '').split(/\s+/)[0] || '—'
const pathFromAction = (action?: string) => {
const parts = String(action || '').split(/\s+/)
return parts.length > 1 ? parts.slice(1).join(' ') : '—'
}
const methodTone = (method?: string) => {
const value = String(method || '').toUpperCase()
if (value === 'GET') return 'is-get'
if (value === 'POST') return 'is-post'
if (value === 'PUT' || value === 'PATCH') return 'is-put'
if (value === 'DELETE') return 'is-delete'
return ''
}
const statusTone = (code?: number) => {
if (code == null) return 'neutral'
if (code >= 400) return 'danger'
if (code >= 200 && code < 300) return 'success'
return 'neutral'
}
const load = async () => {
loaded.value = false
error.value = ''
try {
const params: Record<string, string | number> = { limit: 200 }
if (category.value) params.category = category.value
if (operator.value) params.operator = operator.value
items.value = (await request.get('/logs', { params })) || []
} catch (e) {
error.value = e instanceof Error ? e.message : '请求失败,请稍后重试。'
} finally {
loaded.value = true
}
}
onMounted(load)
</script>
<style scoped>
.filter-card { margin-bottom: 16px; padding: 16px 22px; }
.log-filters { display: flex; flex-wrap: wrap; align-items: end; gap: 16px; }
.log-filters .field { min-width: 180px; flex: 1 1 180px; gap: 6px; }
.log-filters .btn { flex: 0 0 auto; }
.log-method { display: inline-block; min-width: 3.2em; margin-right: 6px; font: 700 11px var(--mono); }
.log-method.is-get { color: var(--blue); }
.log-method.is-post { color: var(--success); }
.log-method.is-put { color: #b7791f; }
.log-method.is-delete { color: var(--danger); }
.mono { font: 600 12px var(--mono); }
.log-detail { display: block; max-width: 420px; color: var(--muted); overflow-wrap: anywhere; }
@media (max-width: 720px) {
.log-filters { flex-direction: column; align-items: stretch; }
.log-filters .btn { width: 100%; }
.log-detail { max-width: none; }
}
</style>
+17 -10
View File
@@ -1,5 +1,5 @@
<template>
<div class="page-content">
<div class="page-content route-list-page">
<div class="page-head">
<div>
<span class="eyebrow">PAYEES</span>
@@ -7,28 +7,35 @@
<p>管理收款方账户信息。</p>
</div>
</div>
<div class="card fill-list-card">
<div class="table-wrap" v-if="items.length > 0" tabindex="0" role="region" aria-label="付款对象列表"><table class="data-table">
<div class="card fill-list-card primary-list-card">
<div class="table-wrap" v-if="loaded && !error && items.length > 0" tabindex="0" role="region" aria-label="付款对象列表"><table class="data-table responsive-table">
<thead><tr><th>账户名称</th><th>银行</th><th>账号</th><th>默认</th><th>状态</th></tr></thead>
<tbody>
<tr v-for="item in items" :key="item.id">
<td><strong>{{ item.name }}</strong></td>
<td><small>{{ item.bankName }}</small></td>
<td><small>{{ item.bankAccountMask || '已脱敏' }}</small></td>
<td><span class="tag" :class="item.isDefault?'success':'draft'">{{ item.isDefault?'默认':'' }}</span></td>
<td><span class="tag" :class="item.status==='ACTIVE'?'success':'draft'">{{ item.status }}</span></td>
<tr v-for="item in paginatedItems" :key="item.id">
<td data-label="账户名称"><strong>{{ item.name }}</strong></td>
<td data-label="银行"><small>{{ item.bankName }}</small></td>
<td data-label="账号"><small>{{ item.bankAccountMask || '已脱敏' }}</small></td>
<td data-label="默认"><span class="tag" :class="item.isDefault?'success':'draft'">{{ item.isDefault?'默认':'否' }}</span></td>
<td data-label="状态"><span class="tag" :class="item.status==='ACTIVE'?'success':'draft'">{{ item.status }}</span></td>
</tr>
</tbody>
</table></div>
<div v-else-if="error" class="empty-state" role="alert"><strong>付款对象加载失败</strong><span>{{ error }}</span><button class="btn small" type="button" @click="load">重试</button></div>
<div class="empty-state" v-else-if="loaded"><strong>暂无付款对象</strong></div>
<div v-else class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载付款对象…</span></div>
<AppListPagination v-if="loaded && !error && items.length" v-model:page="page" v-model:page-size="pageSize" :total="items.length" aria-label="付款对象列表分页" />
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import request from '@/api/request'
import AppListPagination from '@/components/common/AppListPagination.vue'
import { useListPagination } from '@/composables/useListPagination'
const items = ref<any[]>([])
const loaded = ref(false)
onMounted(async () => { try { items.value = await request.get('/metadata/payees') || [] } catch {} finally { loaded.value = true } })
const error = ref('')
const { page, pageSize, paginatedItems } = useListPagination(items)
const load = async () => { loaded.value = false; error.value = ''; try { items.value = await request.get('/metadata/payees') || [] } catch (e) { error.value = e instanceof Error ? e.message : '请求失败,请稍后重试。' } finally { loaded.value = true } }
onMounted(load)
</script>
+52 -15
View File
@@ -1,5 +1,5 @@
<template>
<div class="page-content">
<div class="page-content route-list-page">
<div class="page-head">
<div>
<span class="eyebrow">PAYMENT QUEUE</span>
@@ -36,7 +36,7 @@
<div><span>已付款</span><strong>{{ completed.length }}</strong><small>全额完成</small></div>
</div>
<div class="card fill-list-card">
<div class="card fill-list-card primary-list-card">
<div class="card-head">
<div><h2>付款登记队列</h2><p>登记结果后,付款状态自动派生并保留付款事实。</p></div>
<span class="tag info">财务处理</span>
@@ -60,7 +60,7 @@
</tr>
</thead>
<tbody>
<tr v-for="item in filtered" :key="item.id">
<tr v-for="item in paginatedItems" :key="item.id">
<td data-label="报销单号"><router-link class="table-action strong-link" :to="`/applications/${item.id}`">{{ item.applicationNo }}</router-link><small>{{ item.createdAt?.slice(0, 10) || '-' }}</small></td>
<td data-label="报销人 / 收款人"><strong>{{ item.applicantName }}</strong><small>{{ item.payeeName || '-' }}</small></td>
<td data-label="申请金额" class="amount">{{ money(item.totalAmount) }}</td>
@@ -70,14 +70,15 @@
<td data-label="付款状态"><span class="tag" :class="tone(item.paymentStatus)">{{ item.paymentStatus }}</span></td>
<td data-label="操作">
<button
v-if="store.balance(item) > 0"
v-if="store.balance(item) > 0 && canRegister"
class="btn small primary"
type="button"
:disabled="saving"
:aria-busy="saving && selected?.id === item.id"
@click="openPayment(item)"
>{{ saving && selected?.id === item.id ? '提交中…' : '登记付款' }}</button>
<span v-else class="muted-copy">已完成</span>
<span v-else-if="store.balance(item) <= 0" class="muted-copy">已完成</span>
<span v-else class="muted-copy">无操作权限</span>
</td>
</tr>
</tbody>
@@ -91,35 +92,39 @@
<strong>没有符合条件的付款记录</strong>
<span>请调整搜索关键词后重试。</span>
</div>
<AppListPagination v-if="filtered.length" v-model:page="page" v-model:page-size="pageSize" :total="filtered.length" aria-label="付款登记队列分页" />
</div>
</template>
<dialog
ref="dialog"
class="payment-dialog"
v-dialog-drag
class="app-dialog payment-dialog"
aria-modal="true"
aria-labelledby="payment-dialog-title"
aria-describedby="payment-dialog-description"
@close="handleDialogClose"
@click.self="closePayment"
@cancel="handlePaymentCancel"
@click.self="handlePaymentBackdrop"
>
<form v-if="selected" class="payment-form" @submit.prevent="submitPayment">
<div class="modal-head">
<div class="modal-head" data-dialog-drag-handle>
<div>
<span class="eyebrow">PAYMENT RECORD</span>
<h2 id="payment-dialog-title">登记付款</h2>
<p id="payment-dialog-description">{{ selected.applicationNo }} · {{ selected.title }}</p>
</div>
<button class="modal-close" type="button" aria-label="关闭付款登记窗口" @click="closePayment">×</button>
<button class="modal-close" type="button" aria-label="关闭付款登记窗口" :disabled="saving" @click="closePayment">×</button>
</div>
<div class="modal-body">
<div class="modal-body payment-dialog-body">
<div class="payment-summary">
<div><span>申请金额</span><strong>{{ money(selected.totalAmount) }}</strong></div>
<div><span>累计已付</span><strong>{{ money(store.paidAmount(selected)) }}</strong></div>
<div><span>未付余额</span><strong>{{ money(store.balance(selected)) }}</strong></div>
</div>
<div class="form-grid">
<div class="form-grid payment-fields">
<div class="field">
<label for="pay-amount">本次付款金额 <em>*</em></label>
<input
@@ -159,9 +164,14 @@
import { computed, nextTick, onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { ReimApplicationDetail } from '@/api/reimbursement'
import AppListPagination from '@/components/common/AppListPagination.vue'
import { useListPagination } from '@/composables/useListPagination'
import { useWorkbenchStore } from '@/store/workbench'
import { useUserStore } from '@/store/user'
const store = useWorkbenchStore()
const userStore = useUserStore()
const canRegister = computed(() => userStore.canEdit('finance.payment.register'))
const query = ref('')
const hasLoaded = ref(false)
const selected = ref<ReimApplicationDetail | null>(null)
@@ -181,6 +191,7 @@ const filtered = computed(() => {
const normalizedQuery = query.value.trim().toLowerCase()
return rows.value.filter(item => `${item.applicationNo} ${item.applicantName} ${item.title} ${item.payeeName}`.toLowerCase().includes(normalizedQuery))
})
const { page, pageSize, paginatedItems } = useListPagination(filtered, { resetSources: [query] })
const loadingState = computed(() => store.loading || !hasLoaded.value)
const hasBlockingError = computed(() => hasLoaded.value && (store.source === 'error' || Boolean(store.financeQueueError)))
const hasDataNotice = computed(() => hasLoaded.value && Boolean(store.error) && !hasBlockingError.value)
@@ -196,7 +207,7 @@ const refreshQueue = async () => {
}
const openPayment = async (item: ReimApplicationDetail) => {
if (saving.value) return
if (!canRegister.value || saving.value) return
trigger = document.activeElement instanceof HTMLElement ? document.activeElement : null
selected.value = item
amount.value = Number(store.balance(item).toFixed(2))
@@ -217,14 +228,17 @@ const restoreDialogFocus = () => {
}
const closePayment = () => {
if (saving.value) return
if (dialog.value?.open) dialog.value.close()
restoreDialogFocus()
}
const handleDialogClose = () => restoreDialogFocus()
const handlePaymentCancel = (event: Event) => { event.preventDefault();if(!saving.value)closePayment() }
const handlePaymentBackdrop = (event: MouseEvent) => { if(saving.value){event.preventDefault();return}closePayment() }
const submitPayment = async () => {
if (!selected.value || saving.value) return
if (!canRegister.value || !selected.value || saving.value) return
const max = store.balance(selected.value)
const enteredAmount = Number(amount.value)
if (!Number.isFinite(enteredAmount) || !(enteredAmount > 0) || enteredAmount > max + 0.005) {
@@ -234,16 +248,39 @@ const submitPayment = async () => {
saving.value = true
formError.value = ''
let succeeded = false
try {
await store.pay(selected.value.id, Number(enteredAmount.toFixed(2)), remark.value.trim(), idempotencyKey.value)
closePayment()
ElMessage.success('付款记录已登记')
succeeded = true
} catch (error) {
formError.value = error instanceof Error ? error.message : '付款失败,请检查后重试'
} finally {
saving.value = false
}
if (succeeded) {
closePayment()
ElMessage.success('付款记录已登记')
}
}
onMounted(() => { void refreshQueue() })
</script>
<style scoped>
.payment-dialog-body { background: #fff; }
.payment-summary { overflow: hidden; border-color: #d7e0e8; border-radius: 6px; }
.payment-summary > div { padding: 12px 14px; background: var(--surface-raised); }
.payment-summary > div:last-child { background: var(--blue-soft); }
.payment-summary strong { color: var(--navy); font-size: 15px; }
.payment-summary > div:last-child strong { color: var(--blue-dark); }
.payment-fields { grid-template-columns: 1fr; gap: 14px; padding: 15px 0 0; }
.payment-fields .field:first-child { max-width: 310px; }
.payment-fields textarea { min-height: 78px; }
.amount-error { margin: 12px 0 0; padding: 9px 11px; border-left: 3px solid var(--danger); background: var(--danger-soft); }
@media (max-width: 560px) {
.payment-summary { grid-template-columns: 1fr; }
.payment-fields .field:first-child { max-width: none; }
.payment-dialog .modal-actions { flex-direction: column-reverse; }
.payment-dialog .modal-actions .btn { width: 100%; min-height: 44px; }
}
</style>
+604
View File
@@ -0,0 +1,604 @@
<template>
<div class="scheduled-page page-content route-list-page" :class="{ 'scheduled-embedded': embedded }" :aria-busy="initialLoading || refreshing">
<section class="card task-card" aria-labelledby="scheduled-task-title">
<div class="card-head task-head">
<div>
<span class="eyebrow">SCHEDULED TASKS</span>
<h2 id="scheduled-task-title">自动任务</h2>
<p>查看固定系统任务的计划与运行状态。页面时间均按本地时间显示。</p>
</div>
<button class="btn small" type="button" :disabled="initialLoading || refreshing" @click="refreshAll">
{{ refreshing ? '刷新中…' : '刷新' }}
</button>
</div>
<div v-if="initialLoading" class="load-wrap page-state" role="status" aria-live="polite">
<span class="loader" aria-hidden="true"></span><span>正在加载自动任务…</span>
</div>
<div v-else-if="listError && !tasks.length" class="empty-state page-state" role="alert">
<strong>自动任务加载失败</strong><span>{{ listError }}</span>
<button class="btn small" type="button" @click="loadTasks">重试</button>
</div>
<div v-else-if="!tasks.length" class="empty-state page-state">
<strong>暂无自动任务</strong><span>系统尚未提供可管理的固定任务。</span>
</div>
<div v-else class="task-layout">
<div v-if="listError" class="inline-alert danger task-list-warning" role="alert">{{ listError }}</div>
<nav class="task-selector" aria-label="自动任务列表">
<button
v-for="item in tasks"
:key="item.code"
type="button"
class="task-option"
:class="{ active: item.code === selectedCode }"
:aria-current="item.code === selectedCode ? 'true' : undefined"
@click="selectTask(item.code)"
>
<span class="task-option-title"><strong>{{ item.name }}</strong><i class="status-dot-small" :class="taskTone(item)"></i></span>
<small>{{ item.enabled ? `每 ${item.intervalHours} 小时` : '计划已停用' }} · {{ item.status === 'RUNNING' ? '运行中' : '空闲' }}</small>
</button>
</nav>
<div class="task-detail">
<div v-if="detailError && !task" class="empty-state detail-state" role="alert">
<strong>任务详情加载失败</strong><span>{{ detailError }}</span>
<button class="btn small" type="button" @click="refreshSelected()">重试</button>
</div>
<template v-else-if="task">
<div class="detail-title-row">
<div>
<h3>{{ task.name }}</h3>
<p class="muted-copy">{{ task.enabled ? '自动执行已启用' : '自动执行已停用' }} · {{ intervalLabel(task.intervalHours) }} · 时区 {{ task.timeZone || '—' }}</p>
</div>
<div class="detail-actions">
<button v-if="canUpdate" class="btn" type="button" :disabled="refreshing" @click="openScheduleDialog">编辑计划</button>
<button v-if="canExecute" class="btn primary" type="button" :disabled="executeDisabled" :aria-busy="executing || executeUncertain" @click="confirmExecute">
{{ executeButtonLabel }}
</button>
</div>
</div>
<div v-if="detailError" class="inline-alert danger" role="alert">
<span>{{ detailError }}</span><button class="btn small" type="button" @click="refreshSelected()">重新加载</button>
</div>
<p v-if="executeNotice" class="inline-note" role="status">{{ executeNotice }}</p>
<dl class="task-summary" aria-label="任务状态摘要">
<div><dt>计划状态</dt><dd><span class="state-badge" :class="task.enabled ? 'success' : 'neutral'">{{ task.enabled ? '已启用' : '已停用' }}</span></dd></div>
<div><dt>执行间隔</dt><dd>{{ intervalLabel(task.intervalHours) }}</dd></div>
<div><dt>下次执行 <span>本地时间</span></dt><dd>{{ task.enabled ? formatLocalDateTime(task.nextDueAt, '待计算') : '—' }}</dd></div>
<div><dt>当前状态</dt><dd><span class="state-badge" :class="isActive ? 'running' : 'neutral'">{{ isActive ? '运行中' : '空闲' }}</span></dd></div>
<div><dt>最近运行</dt><dd>{{ latestRun ? `${stateLabels[latestRun.state]} · ${formatLocalDateTime(latestRun.queuedAt)}` : '暂无' }}</dd></div>
<div><dt>最近成功 <span>本地时间</span></dt><dd>{{ formatLocalDateTime(lastSuccess?.finishedAt, '暂无') }}</dd></div>
</dl>
</template>
</div>
</div>
</section>
<section v-if="task" class="card history-card primary-list-card" aria-labelledby="run-history-title">
<div class="card-head history-head">
<div><h2 id="run-history-title">运行记录</h2><p>按入队时间从新到旧显示;错误内容已作安全处理。</p></div>
<span class="muted-copy" aria-live="polite">{{ pollingLabel }}</span>
</div>
<div v-if="historyLoading" class="load-wrap history-state" role="status" aria-live="polite">
<span class="loader" aria-hidden="true"></span><span>正在加载运行记录…</span>
</div>
<div v-else-if="historyError" class="empty-state history-state" role="alert">
<strong>运行记录加载失败</strong><span>{{ historyError }}</span>
<button class="btn small" type="button" @click="loadHistory">重试</button>
</div>
<div v-else-if="!runs.length" class="empty-state history-state">
<strong>暂无运行记录</strong><span>任务执行后,结果会显示在这里。</span>
</div>
<div v-else class="table-wrap history-table-wrap" tabindex="0" role="region" aria-label="自动任务运行记录">
<table class="data-table history-table">
<thead><tr><th>状态</th><th>触发方式</th><th>入队时间</th><th>执行时间</th><th>结果统计</th><th>结果</th></tr></thead>
<tbody>
<tr v-for="run in runs" :key="run.runId">
<td data-label="状态"><span class="state-badge" :class="runTone(run.state)">{{ stateLabels[run.state] }}</span><small v-if="run.attempts > 1">第 {{ run.attempts }} 次尝试</small></td>
<td data-label="触发方式">{{ triggerLabels[run.trigger] }}</td>
<td data-label="入队时间"><time :datetime="run.queuedAt">{{ formatLocalDateTime(run.queuedAt) }}</time></td>
<td data-label="执行时间"><span>{{ formatLocalDateTime(run.startedAt, '尚未开始') }}</span><small>{{ run.finishedAt ? `完成于 ${formatLocalDateTime(run.finishedAt)}` : '尚未结束' }}</small></td>
<td data-label="结果统计"><span class="counts-summary">{{ countsSummary(run) }}</span></td>
<td data-label="结果">
<span>{{ run.complete ? (run.applied ? '已完成并生效' : '已完成,保留当前目录') : '尚未完成' }}</span>
<details v-if="run.errorCode || run.errorMessage" class="error-detail">
<summary>查看错误</summary><p>{{ safeError(run) }}</p>
</details>
</td>
</tr>
</tbody>
</table>
</div>
<AppListPagination
v-if="!historyLoading && !historyError && historyTotal"
v-model:page="historyPage"
v-model:page-size="historyPageSize"
:total="historyTotal"
:disabled="historyLoading"
:page-sizes="[10, 20, 50]"
aria-label="运行记录分页"
/>
</section>
<p class="sr-status" aria-live="polite" aria-atomic="true">{{ liveMessage }}</p>
<dialog ref="scheduleDialog" v-dialog-drag class="app-dialog schedule-dialog" aria-labelledby="schedule-dialog-title" aria-modal="true" @cancel="handleScheduleCancel" @click="handleScheduleBackdrop">
<section class="app-dialog__panel">
<header class="modal-head" data-dialog-drag-handle>
<div><span class="eyebrow">SCHEDULE CONFIGURATION</span><h2 id="schedule-dialog-title">编辑自动计划</h2><p>{{ task?.name }}</p></div>
<button class="modal-close" type="button" aria-label="关闭计划配置窗口" :disabled="scheduleSaving" @click="closeScheduleDialog"></button>
</header>
<div class="modal-body schedule-form">
<div v-if="scheduleError" class="inline-alert danger" role="alert">{{ scheduleError }}</div>
<label class="switch-row">
<span><strong>启用自动执行</strong><small>停用后不会按计划发起新运行,手动执行不受影响。</small></span>
<el-switch v-model="draftEnabled" :disabled="scheduleSaving" aria-label="启用自动执行" />
</label>
<fieldset :disabled="scheduleSaving">
<legend>执行间隔</legend>
<div class="interval-grid">
<label v-for="hours in intervalOptions" :key="hours" :class="{ selected: draftInterval === hours }">
<input v-model="draftInterval" type="radio" name="interval" :value="hours"><span>每 {{ hours }} 小时</span>
</label>
</div>
</fieldset>
<p class="form-hint">保存使用当前版本校验;如其他管理员已修改,将加载最新版本并保留本次选择。</p>
</div>
<footer class="modal-actions">
<button class="btn" type="button" :disabled="scheduleSaving" @click="closeScheduleDialog">取消</button>
<button class="btn primary" type="button" :disabled="scheduleSaving" :aria-busy="scheduleSaving" @click="saveSchedule">{{ scheduleSaving ? '保存中…' : '保存计划' }}</button>
</footer>
</section>
</dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AppListPagination from '@/components/common/AppListPagination.vue'
import { useUserStore } from '@/store/user'
import {
scheduledTasksApi,
type ScheduledIntervalHours,
type ScheduledTask,
type ScheduledTaskRun,
type ScheduledRunState,
} from '@/api/scheduledTasks'
const DEFAULT_TASK_CODE = 'FEISHU_DIRECTORY_SYNC'
withDefaults(defineProps<{ embedded?: boolean }>(), { embedded: false })
const intervalOptions: ScheduledIntervalHours[] = [1, 2, 3, 6, 12, 24]
const stateLabels = { QUEUED: '排队中', RUNNING: '运行中', SUCCEEDED: '成功', FAILED: '失败' } as const
const triggerLabels = { MANUAL: '手动', STARTUP: '启动时', SCHEDULED: '自动计划' } as const
const userStore = useUserStore()
const canUpdate = computed(() => userStore.canEdit('system.scheduled-task.config.update'))
const canExecute = computed(() => userStore.canEdit('system.scheduled-task.execute'))
const tasks = ref<ScheduledTask[]>([])
const selectedCode = ref('')
const task = ref<ScheduledTask | null>(null)
const runs = ref<ScheduledTaskRun[]>([])
const latestRuns = ref<ScheduledTaskRun[]>([])
const historyPage = ref(1)
const historyPageSize = ref(20)
const historyTotal = ref(0)
const initialLoading = ref(true)
const refreshing = ref(false)
const historyLoading = ref(false)
const listError = ref('')
const detailError = ref('')
const historyError = ref('')
const liveMessage = ref('')
const executing = ref(false)
const executeUncertain = ref(false)
const executeNotice = ref('')
const scheduleDialog = ref<HTMLDialogElement | null>(null)
const scheduleSaving = ref(false)
const scheduleError = ref('')
const draftEnabled = ref(false)
const draftInterval = ref<ScheduledIntervalHours>(24)
const draftVersion = ref(0)
let disposed = false
let readController: AbortController | null = null
let writeController: AbortController | null = null
let pollTimer: ReturnType<typeof setTimeout> | undefined
let activeSince = 0
let executeSubmittedAt = 0
let executeObservedActive = false
let executeIdleConfirmations = 0
let requestGeneration = 0
const orderedLatestRuns = computed(() => [...latestRuns.value].sort((a, b) => dateValue(b.queuedAt) - dateValue(a.queuedAt)))
const latestRun = computed(() => orderedLatestRuns.value[0] || null)
const lastSuccess = computed(() => orderedLatestRuns.value.find(item => item.state === 'SUCCEEDED') || null)
const hasActiveRun = computed(() => orderedLatestRuns.value.some(item => item.state === 'QUEUED' || item.state === 'RUNNING'))
const isActive = computed(() => task.value?.status === 'RUNNING' || hasActiveRun.value)
const executeDisabled = computed(() => !canExecute.value || executing.value || executeUncertain.value || refreshing.value || isActive.value)
const executeButtonLabel = computed(() => executing.value ? '提交中…' : executeUncertain.value ? '正在确认结果…' : isActive.value ? '任务运行中' : '立即运行')
const pollingLabel = computed(() => document.visibilityState === 'hidden' ? '页面不可见,已暂停更新' : isActive.value || executeUncertain.value ? '运行期间自动更新' : '每 30 秒自动更新')
const dateValue = (value: unknown) => {
const result = new Date(typeof value === 'string' || typeof value === 'number' ? value : '').getTime()
return Number.isFinite(result) ? result : 0
}
const formatLocalDateTime = (value: unknown, fallback = '—') => {
const date = value instanceof Date ? value : new Date(typeof value === 'string' || typeof value === 'number' ? value : '')
if (!Number.isFinite(date.getTime())) return fallback
const pad = (part: number) => String(part).padStart(2, '0')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
const intervalLabel = (hours: number) => `每 ${hours} 小时`
const taskTone = (item: ScheduledTask) => item.status === 'RUNNING' ? 'running' : item.enabled ? 'success' : 'neutral'
const runTone = (state: ScheduledRunState) => ({ QUEUED: 'queued', RUNNING: 'running', SUCCEEDED: 'success', FAILED: 'danger' }[state])
const countsSummary = (run: ScheduledTaskRun) => {
const count = run.counts || ({} as ScheduledTaskRun['counts'])
return `部门 ${Number(count.departments) || 0} · 扫描 ${Number(count.usersSeen) || 0} · 符合 ${Number(count.eligible) || 0} · 排除 ${Number(count.excluded) || 0} · 新增 ${Number(count.created) || 0} · 更新 ${Number(count.updated) || 0} · 不符合 ${Number(count.ineligible) || 0} · 范围外 ${Number(count.outOfScope) || 0}`
}
const safeError = (run: ScheduledTaskRun) => {
const raw = [run.errorCode, run.errorMessage].filter(Boolean).join(':').slice(0, 500)
return (raw || '运行失败,暂无更多信息。')
.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, '[已隐藏邮箱]')
.replace(/(?:\+?86[- ]?)?1\d{10}\b/g, '[已隐藏号码]')
.replace(/\b(?:token|secret|authorization|open[_-]?id|user[_-]?id)\s*[:=]\s*\S+/gi, '$1=[已隐藏]')
}
const messageOf = (error: unknown, fallback: string) => error instanceof Error && error.message ? error.message : fallback
const isConflict = (error: unknown) => Number((error as { response?: { status?: number } } | null)?.response?.status) === 409
const normalizeRuns = (items: ScheduledTaskRun[] | undefined) => Array.isArray(items)
? [...items].sort((a, b) => dateValue(b.queuedAt) - dateValue(a.queuedAt))
: []
function applyTask(next: ScheduledTask) {
task.value = next
const index = tasks.value.findIndex(item => item.code === next.code)
if (index >= 0) tasks.value[index] = next
else tasks.value.push(next)
}
function reconcileExecuteLock(active: boolean) {
if (!executeUncertain.value) return
if (active) {
executeObservedActive = true
executeIdleConfirmations = 0
return
}
if (executeObservedActive) {
executeUncertain.value = false
executeNotice.value = '本次运行已结束,状态已从服务器更新。'
return
}
if (Date.now() - executeSubmittedAt < 2_000) return
executeIdleConfirmations += 1
if (executeIdleConfirmations >= 2) {
executeUncertain.value = false
executeNotice.value = '服务器未发现进行中的运行,可以重新发起。'
}
}
function scheduleNextPoll() {
clearTimeout(pollTimer)
if (disposed || document.visibilityState === 'hidden' || !selectedCode.value) return
const active = isActive.value || executeUncertain.value
if (active && !activeSince) activeSince = Date.now()
if (!active) activeSince = 0
const delay = active ? (Date.now() - activeSince < 30_000 ? 2_000 : 5_000) : 30_000
pollTimer = setTimeout(() => void refreshSelected(true), delay)
}
async function loadTasks() {
if (disposed) return
readController?.abort()
const controller = new AbortController()
readController = controller
const generation = ++requestGeneration
initialLoading.value = true
listError.value = ''
try {
const result = await scheduledTasksApi.list(controller.signal)
if (disposed || generation !== requestGeneration) return
tasks.value = Array.isArray(result) ? result : []
const preferred = tasks.value.find(item => item.code === DEFAULT_TASK_CODE) || tasks.value[0]
selectedCode.value = preferred?.code || ''
if (preferred) await refreshSelected(false, generation)
} catch (error) {
if (!controller.signal.aborted && !disposed) listError.value = messageOf(error, '请求失败,请稍后重试。')
} finally {
if (generation === requestGeneration) initialLoading.value = false
scheduleNextPoll()
}
}
async function refreshSelected(background = false, inheritedGeneration?: number) {
if (disposed || !selectedCode.value || document.visibilityState === 'hidden') return
const code = selectedCode.value
readController?.abort()
const controller = new AbortController()
readController = controller
const generation = inheritedGeneration ?? ++requestGeneration
if (!background) refreshing.value = true
if (!runs.value.length) historyLoading.value = true
detailError.value = ''
historyError.value = ''
try {
const pageRequest = scheduledTasksApi.runs(code, historyPage.value - 1, historyPageSize.value, controller.signal)
const latestRequest = historyPage.value === 1 && historyPageSize.value === 50
? pageRequest
: scheduledTasksApi.runs(code, 0, 50, controller.signal)
const [detailResult, pageResult, latestResult] = await Promise.allSettled([
scheduledTasksApi.detail(code, controller.signal), pageRequest, latestRequest,
])
if (disposed || generation !== requestGeneration || code !== selectedCode.value) return
if (detailResult.status === 'fulfilled') applyTask(detailResult.value)
else detailError.value = messageOf(detailResult.reason, '任务详情请求失败,请稍后重试。')
if (pageResult.status === 'fulfilled') {
runs.value = normalizeRuns(pageResult.value.items)
historyTotal.value = Math.max(0, Number(pageResult.value.total) || 0)
} else historyError.value = messageOf(pageResult.reason, '运行记录请求失败,请稍后重试。')
if (latestResult.status === 'fulfilled') latestRuns.value = normalizeRuns(latestResult.value.items)
else if (pageResult.status === 'fulfilled' && historyPage.value === 1) latestRuns.value = normalizeRuns(pageResult.value.items)
const confirmedActive = detailResult.status === 'fulfilled' && detailResult.value.status === 'RUNNING'
|| latestResult.status === 'fulfilled' && latestRuns.value.some(item => item.state === 'QUEUED' || item.state === 'RUNNING')
if (detailResult.status === 'fulfilled' || latestResult.status === 'fulfilled') reconcileExecuteLock(confirmedActive)
if (detailResult.status === 'fulfilled' || pageResult.status === 'fulfilled') {
liveMessage.value = `已更新${detailResult.status === 'fulfilled' ? detailResult.value.name : '自动任务'}的状态和运行记录。`
}
} catch (error) {
if (!controller.signal.aborted && !disposed) {
const message = messageOf(error, '请求失败,请稍后重试。')
detailError.value = message
historyError.value = message
}
} finally {
if (generation === requestGeneration) {
refreshing.value = false
historyLoading.value = false
scheduleNextPoll()
}
}
}
async function loadHistory() {
await refreshSelected(false)
}
async function refreshAll() {
if (initialLoading.value || refreshing.value) return
await loadTasks()
}
function selectTask(code: string) {
if (code === selectedCode.value) return
selectedCode.value = code
task.value = tasks.value.find(item => item.code === code) || null
runs.value = []
latestRuns.value = []
historyPage.value = 1
historyTotal.value = 0
executeUncertain.value = false
executeNotice.value = ''
void refreshSelected()
}
function openScheduleDialog() {
if (!task.value || !canUpdate.value || scheduleSaving.value) return
draftEnabled.value = task.value.enabled
draftInterval.value = task.value.intervalHours
draftVersion.value = task.value.version
scheduleError.value = ''
scheduleDialog.value?.showModal()
}
function closeScheduleDialog() {
if (!scheduleSaving.value) scheduleDialog.value?.close()
}
function handleScheduleCancel(event: Event) {
if (scheduleSaving.value) event.preventDefault()
}
function handleScheduleBackdrop(event: MouseEvent) {
if (event.target !== event.currentTarget) return
if (scheduleSaving.value) event.preventDefault()
else closeScheduleDialog()
}
async function saveSchedule() {
if (!task.value || !canUpdate.value || scheduleSaving.value) return
const code = task.value.code
const intendedEnabled = draftEnabled.value
const intendedInterval = draftInterval.value
scheduleSaving.value = true
scheduleError.value = ''
writeController?.abort()
const controller = new AbortController()
writeController = controller
try {
const updated = await scheduledTasksApi.updateSchedule(code, { enabled: intendedEnabled, intervalHours: intendedInterval, version: draftVersion.value }, controller.signal)
if (disposed) return
applyTask(updated)
scheduleDialog.value?.close()
ElMessage.success('自动计划已保存')
liveMessage.value = '自动计划已保存。'
} catch (error) {
if (controller.signal.aborted || disposed) return
if (isConflict(error)) {
try {
const latest = await scheduledTasksApi.detail(code, controller.signal)
if (disposed) return
applyTask(latest)
draftVersion.value = latest.version
draftEnabled.value = intendedEnabled
draftInterval.value = intendedInterval
scheduleError.value = '计划已被其他管理员更新。已加载最新版本并保留你的选择,请确认后再次保存。'
} catch (reloadError) {
scheduleError.value = `计划版本冲突,且最新配置加载失败:${messageOf(reloadError, '请稍后重试。')}`
}
} else scheduleError.value = messageOf(error, '计划保存失败,请稍后重试。')
} finally {
scheduleSaving.value = false
scheduleNextPoll()
}
}
async function confirmExecute() {
if (executeDisabled.value || !task.value) return
executing.value = true
try {
await ElMessageBox.confirm(`确定立即运行“${task.value.name}”吗?`, '确认运行', { confirmButtonText: '立即运行', cancelButtonText: '取消', type: 'warning' })
} catch {
executing.value = false
return
}
if (!task.value || executeUncertain.value || isActive.value) {
executing.value = false
return
}
const code = task.value.code
executeUncertain.value = true
executeSubmittedAt = Date.now()
executeObservedActive = false
executeIdleConfirmations = 0
executeNotice.value = '运行请求已提交,正在向服务器确认结果,请勿重复操作。'
writeController?.abort()
const controller = new AbortController()
writeController = controller
try {
const accepted = await scheduledTasksApi.execute(code, controller.signal)
if (disposed) return
latestRuns.value = normalizeRuns([accepted, ...latestRuns.value.filter(item => item.runId !== accepted.runId)])
executeObservedActive = accepted.state === 'QUEUED' || accepted.state === 'RUNNING'
if (!executeObservedActive) executeUncertain.value = false
executeNotice.value = executeObservedActive ? '任务已受理,运行期间将自动更新。' : '运行已返回最终结果。'
} catch (error) {
if (!disposed && !controller.signal.aborted) executeNotice.value = '提交结果未确认(可能已被服务器受理),正在从服务器核对,请勿重复操作。'
} finally {
executing.value = false
await refreshSelected(true)
}
}
function handleVisibilityChange() {
clearTimeout(pollTimer)
if (document.visibilityState === 'hidden') {
readController?.abort()
return
}
void refreshSelected(true)
}
watch(historyPage, () => { if (!initialLoading.value) void loadHistory() })
watch(historyPageSize, () => {
if (historyPage.value !== 1) historyPage.value = 1
else if (!initialLoading.value) void loadHistory()
})
onMounted(() => {
document.addEventListener('visibilitychange', handleVisibilityChange)
void loadTasks()
})
onBeforeUnmount(() => {
disposed = true
requestGeneration += 1
clearTimeout(pollTimer)
readController?.abort()
writeController?.abort()
document.removeEventListener('visibilitychange', handleVisibilityChange)
})
</script>
<style scoped>
.scheduled-page { min-width: 0; }
.scheduled-page.scheduled-embedded { height: 100%; min-height: 0; flex: 1 1 0; overflow: hidden; }
.task-card, .history-card { min-width: 0; }
.scheduled-embedded .task-card { flex: 0 0 auto; }
.scheduled-embedded .history-card { min-height: 0; flex: 1 1 0; overflow: hidden; }
.scheduled-embedded .history-card > .history-table-wrap { min-height: 0; max-height: none; flex: 1 1 auto; overflow: auto; }
.task-head, .history-head, .detail-title-row { display: flex; align-items: flex-start; justify-content: space-between; flex-wrap: wrap; gap: 12px; }
.task-head > div, .history-head > div, .detail-title-row > div:first-child { min-width: 0; flex: 1 1 280px; }
.task-head p, .detail-title-row p, .history-head p { overflow-wrap: anywhere; }
.page-state { min-height: 180px; padding: 30px 18px; }
.page-state .btn, .detail-state .btn, .history-state .btn { margin-top: 12px; }
.task-layout { display: grid; grid-template-columns: minmax(210px, .34fr) minmax(0, 1fr); gap: 18px; padding: 0 22px 22px; }
.task-list-warning { grid-column: 1 / -1; }
.task-selector { display: grid; align-content: start; gap: 7px; }
.task-option { width: 100%; padding: 12px; border: 1px solid var(--line); border-radius: var(--radius); background: #fff; color: var(--body); text-align: left; }
.task-option:hover, .task-option.active { border-color: #a8c4df; background: var(--blue-soft); }
.task-option-title { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.task-option strong { color: var(--text); font-size: 12px; overflow-wrap: anywhere; }
.task-option small { display: block; margin-top: 4px; color: var(--muted); font-size: 10px; }
.status-dot-small { width: 8px; height: 8px; flex: none; border-radius: 50%; background: var(--quiet); }
.status-dot-small.success { background: var(--success); }
.status-dot-small.running { background: var(--blue); box-shadow: 0 0 0 3px var(--blue-soft); }
.task-detail { min-width: 0; padding: 16px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface-raised); }
.detail-state { min-height: 160px; }
.detail-title-row h3 { font-size: 16px; }
.detail-actions { display: flex; flex-wrap: wrap; gap: 8px; }
.inline-note { margin: 12px 0 0; padding: 9px 11px; border-left: 3px solid var(--blue); background: var(--blue-soft); color: var(--body); font-size: 11px; }
.task-summary { display: grid; grid-template-columns: repeat(3, minmax(145px, 1fr)); gap: 1px; margin-top: 16px; overflow: hidden; border: 1px solid var(--line); border-radius: 6px; background: var(--line); }
.task-summary > div { min-width: 0; padding: 11px 12px; background: #fff; }
.task-summary dt { color: var(--muted); font-size: 10px; }
.task-summary dt span { color: var(--quiet); font-weight: 400; }
.task-summary dd { margin-top: 3px; overflow-wrap: anywhere; color: var(--body); font-size: 12px; }
.state-badge { display: inline-flex; align-items: center; min-height: 22px; padding: 2px 8px; border-radius: 99px; background: #eef1f4; color: var(--muted); font-size: 10px; font-weight: 700; white-space: nowrap; }
.state-badge.success { background: var(--success-soft); color: var(--success); }
.state-badge.danger { background: var(--danger-soft); color: var(--danger); }
.state-badge.running, .state-badge.queued { background: var(--blue-soft); color: var(--blue-dark); }
.history-card { display: flex; margin-top: 16px; flex-direction: column; }
.history-state { min-height: 180px; padding: 30px 18px; }
.history-table-wrap { margin: 0 18px; }
.history-table { min-width: 920px; }
.history-table td { vertical-align: top; }
.history-table td > small, .history-table td > span:not(.state-badge) { display: block; }
.history-table td > small { margin-top: 3px; color: var(--quiet); font-size: 10px; }
.counts-summary { max-width: 300px; color: var(--body); line-height: 1.65; }
.error-detail { margin-top: 5px; max-width: 260px; color: var(--danger); }
.error-detail summary { cursor: pointer; font-size: 10px; }
.error-detail p { margin-top: 4px; overflow-wrap: anywhere; white-space: pre-wrap; }
.schedule-dialog { width: min(560px, calc(100vw - 24px)); }
.modal-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; padding: 19px var(--dialog-header-x); border-bottom: 1px solid var(--line); background: var(--surface-raised); }
.modal-head h2 { margin-top: 3px; font-size: 19px; }
.modal-head p { margin-top: 2px; color: var(--muted); font-size: 11px; }
.schedule-form { display: grid; gap: 18px; padding: 20px var(--dialog-body-x); }
.switch-row { display: flex; align-items: center; justify-content: space-between; gap: 18px; }
.switch-row > span { min-width: 0; }
.switch-row strong, .switch-row small { display: block; }
.switch-row strong { font-size: 13px; }
.switch-row small, .form-hint { margin-top: 3px; color: var(--muted); font-size: 11px; }
.schedule-form fieldset { border: 0; }
.schedule-form legend { margin-bottom: 8px; color: var(--body); font-size: 12px; font-weight: 700; }
.interval-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
.interval-grid label { position: relative; display: grid; min-height: 40px; place-items: center; border: 1px solid var(--line); border-radius: 6px; background: #fff; color: var(--body); cursor: pointer; }
.interval-grid label.selected { border-color: var(--blue); background: var(--blue-soft); color: var(--blue-dark); font-weight: 700; }
.interval-grid input { position: absolute; opacity: 0; pointer-events: none; }
.interval-grid label:focus-within { outline: 3px solid #7eb4f2; outline-offset: 2px; }
.sr-status { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
@media (max-width: 800px) {
.task-layout { grid-template-columns: minmax(0, 1fr); }
.task-selector { grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); }
.task-summary { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (max-width: 680px) {
.task-layout { padding-right: 12px; padding-left: 12px; }
.detail-actions { width: 100%; }
.detail-actions .btn { flex: 1; }
.task-summary { grid-template-columns: minmax(0, 1fr); }
.history-table-wrap { margin: 0 12px; overflow: visible; }
.history-table { min-width: 0; }
.history-table thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0, 0, 0, 0); }
.history-table, .history-table tbody, .history-table tr, .history-table td { display: block; width: 100%; }
.history-table tr { margin-bottom: 10px; padding: 7px 12px; border: 1px solid var(--line); border-radius: var(--radius); background: #fff; }
.history-table td { display: grid; grid-template-columns: 82px minmax(0, 1fr); gap: 9px; padding: 7px 0; border: 0; border-bottom: 1px solid var(--line); }
.history-table td:last-child { border-bottom: 0; }
.history-table td::before { content: attr(data-label); color: var(--muted); font-size: 10px; font-weight: 700; }
.history-table td > * { grid-column: 2; }
.history-table td::before { grid-column: 1; grid-row: 1 / span 3; }
.counts-summary, .error-detail { max-width: none; }
.interval-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
</style>
+17 -10
View File
@@ -1,5 +1,5 @@
<template>
<div class="page-content">
<div class="page-content route-list-page">
<div class="page-head">
<div>
<span class="eyebrow">SOURCE DOCUMENTS</span>
@@ -7,39 +7,46 @@
<p>来自金蝶 ERP 的源单据,只读展示。</p>
</div>
</div>
<div class="card fill-list-card">
<div class="card fill-list-card primary-list-card">
<div class="filter-bar">
<label class="filter-search"><span aria-hidden="true">&#x1F50D;</span><input type="search" v-model="search" placeholder="搜索单据编号" aria-label="搜索"></label>
<span class="filter-spacer"></span><span class="tag info">{{ filtered.length }} 笔</span>
</div>
<div class="table-wrap" v-if="filtered.length > 0" tabindex="0" role="region" aria-label="业务单据列表"><table class="data-table">
<div class="table-wrap" v-if="loaded && !error && filtered.length > 0" tabindex="0" role="region" aria-label="业务单据列表"><table class="data-table responsive-table">
<thead><tr><th>单据编号</th><th>类型</th><th class="amount">金额</th><th>日期</th><th>来源</th></tr></thead>
<tbody>
<tr v-for="item in filtered" :key="item.id">
<td><strong>{{ item.sourceDocNo }}</strong></td>
<td><span class="tag">{{ item.sourceDocType }}</span></td>
<td class="amount">{{ fmt(item.amount) }}</td>
<td><small>{{ item.sourceDate }}</small></td>
<td><small>{{ item.sourceSystem }}</small></td>
<tr v-for="item in paginatedItems" :key="item.id">
<td data-label="单据编号"><strong>{{ item.sourceDocNo }}</strong></td>
<td data-label="类型"><span class="tag">{{ item.sourceDocType }}</span></td>
<td data-label="金额" class="amount">{{ fmt(item.amount) }}</td>
<td data-label="日期"><small>{{ item.sourceDate }}</small></td>
<td data-label="来源"><small>{{ item.sourceSystem }}</small></td>
</tr>
</tbody>
</table></div>
<div v-else-if="error" class="empty-state" role="alert"><strong>业务单据加载失败</strong><span>{{ error }}</span><button class="btn small" type="button" @click="load">重试</button></div>
<div class="empty-state" v-else-if="loaded"><strong>暂无业务单据</strong><span>金蝶 ERP 数据同步后会自动显示</span></div>
<div v-else class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载业务单据…</span></div>
<AppListPagination v-if="loaded && !error && filtered.length" v-model:page="page" v-model:page-size="pageSize" :total="filtered.length" aria-label="业务单据列表分页" />
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import request from '@/api/request'
import AppListPagination from '@/components/common/AppListPagination.vue'
import { useListPagination } from '@/composables/useListPagination'
const search = ref('')
const items = ref<any[]>([])
const loaded = ref(false)
onMounted(async () => { try { items.value = await request.get('/sources') || [] } catch {} finally { loaded.value = true } })
const error = ref('')
const load = async () => { loaded.value = false; error.value = ''; try { items.value = await request.get('/sources') || [] } catch (e) { error.value = e instanceof Error ? e.message : '请求失败,请稍后重试。' } finally { loaded.value = true } }
onMounted(load)
const filtered = computed(() => {
if (!search.value) return items.value
const q = search.value.toLowerCase()
return items.value.filter(i => (i.sourceDocNo || '').toLowerCase().includes(q))
})
const { page, pageSize, paginatedItems } = useListPagination(filtered, { resetSources: [search] })
const fmt = (v: number) => `¥ ${(v||0).toLocaleString('zh-CN',{minimumFractionDigits:2})}`
</script>
+331 -51
View File
@@ -1,73 +1,353 @@
<template>
<div class="admin-page page-content" :class="{ 'has-group-detail': selectedGroup }">
<div class="page-head"><div><span class="eyebrow">SYSTEM MANAGEMENT</span><h1>用户管理</h1><p>统一管理用户、角色权限和飞书组织用户组。</p></div><div v-if="activeTab === 'roles' && can('system:role:manage')" class="head-actions"><button class="btn primary" type="button" @click="openRoleForm()">新建角色</button></div><div v-else-if="activeTab === 'groups' && can('system:group:manage')" class="head-actions"><button class="btn primary" type="button" @click="openGroupForm()">新建用户组</button><button v-if="selectedGroup" class="btn" type="button" @click="toggleGroupStatus(selectedGroup)">{{ selectedGroup.status === 'ACTIVE' ? '停用当前组' : '启用当前组' }}</button></div></div>
<div v-if="permissionsFailed" class="inline-alert danger" role="alert"><b>!</b><span>管理权限加载失败,管理项已隐藏。请重试后再进行操作。</span><button class="btn small" type="button" @click="retryPermissions">重试</button></div>
<nav v-if="availableTabs.length" class="tabs" aria-label="用户管理模块" role="tablist"><button v-if="can('system:user:view')" class="tab" :class="{ active: activeTab === 'users' }" type="button" :aria-selected="activeTab === 'users'" role="tab" @click="switchTab('users')">用户</button><button v-if="can('system:role:view')" class="tab" :class="{ active: activeTab === 'roles' }" type="button" :aria-selected="activeTab === 'roles'" role="tab" @click="switchTab('roles')">角色管理</button><button v-if="can('system:group:view')" class="tab" :class="{ active: activeTab === 'groups' }" type="button" :aria-selected="activeTab === 'groups'" role="tab" @click="switchTab('groups')">用户组 / 飞书绑定</button></nav>
<div class="admin-page page-content route-list-page">
<div class="page-head"><div><span class="eyebrow">SYSTEM MANAGEMENT</span><h1>人员与角色</h1><p>{{ pageDescription }}</p></div><div class="head-actions"><button v-if="activeTab==='roles' && canEdit('system.role.create')" class="btn primary" type="button" @click="openRoleForm()">新建角色</button><button v-if="activeTab==='groups' && canRead('page.groups') && canEdit('system.group.create')" class="btn primary" type="button" @click="openGroupForm()">新建用户组</button></div></div>
<div v-if="permissionsFailed" class="inline-alert danger" role="alert"><b>!</b><span>权限加载失败,所有管理能力已关闭。</span><button class="btn small" type="button" @click="retryPermissions">重试</button></div>
<nav v-if="availableTabs.length" class="tabs" role="tablist" aria-label="系统管理页面" @keydown="moveTab">
<button v-for="tab in availableTabs" :id="`admin-tab-${tab.key}`" :key="tab.key" class="tab" :class="{active:activeTab===tab.key}" type="button" role="tab" :aria-selected="activeTab===tab.key" :tabindex="activeTab===tab.key?0:-1" @click="switchTab(tab.key)">{{ tab.label }}</button>
</nav>
<div v-else-if="!permissionsFailed" class="card empty-state" role="alert"><strong>无可访问管理页面</strong><span>请联系管理员配置用户组、角色或飞书通讯录页面权限。</span></div>
<section v-if="activeTab === 'users' && can('system:user:view')" class="card admin-card"><div class="card-head"><div><h2>系统用户</h2><p>旧角色下拉仍可使用;多角色请打开角色分配。</p></div><span class="muted-copy">{{ users.length }} 人</span></div><div v-if="usersLoading" class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载用户…</span></div><div v-else-if="usersError" class="empty-state" role="alert"><strong>用户加载失败</strong><span>{{ usersError }}</span><button class="btn small" type="button" @click="loadUsers">重试</button></div><div v-else-if="!users.length" class="empty-state"><strong>暂无用户</strong><span>当前没有可管理的系统用户。</span></div><div v-else class="table-wrap"><table class="data-table" aria-label="系统用户列表"><thead><tr><th>员工号 / 部门</th><th>姓名</th><th>角色</th><th>状态</th><th>最后登录</th><th>操作</th></tr></thead><tbody><tr v-for="user in users" :key="user.id"><td><strong>{{ user.employeeNo || '-' }}</strong><small>{{ user.departmentName || '未分配部门' }}</small></td><td><strong>{{ user.realName || '未命名用户' }}</strong><small>{{ user.position || '' }}</small></td><td class="role-cell"><span v-if="user.roleCodes?.length" v-for="roleCode in user.roleCodes" :key="roleCode" class="tag info">{{ roleCode }}</span><span v-else class="tag neutral">{{ legacyRoleLabel(user.userType) }}</span><select class="select legacy-role" :value="legacyRole(user.userType)" :disabled="!can('system:user:manage') || statusSaving === user.id" aria-label="兼容旧角色选择" @change="updateLegacyRole(user, $event)"><option value="ADMIN">系统管理员</option><option value="FINANCE">财务人员</option><option value="EMPLOYEE">普通用户</option></select></td><td><button class="status-button" :class="user.status === 'ACTIVE' ? 'active' : 'inactive'" type="button" :disabled="!can('system:user:manage') || statusSaving === user.id" :aria-label="`${user.realName}:${user.status === 'ACTIVE' ? '停用' : '启用'}`" @click="toggleUserStatus(user)"><span class="status-dot-small" aria-hidden="true"></span>{{ user.status === 'ACTIVE' ? '正常' : '已停用' }}</button></td><td><small>{{ user.lastLoginAt || '-' }}</small></td><td><button class="table-action" type="button" :disabled="!can('system:user:manage')" @click="openUserRoles(user)">分配角色</button></td></tr></tbody></table></div></section>
<dialog ref="memberDialog" v-dialog-drag class="app-dialog admin-dialog member-dialog" aria-labelledby="member-dialog-title" @cancel="handleMemberDialogCancel"><form @submit.prevent="saveGroupMembers"><div class="modal-head" data-dialog-drag-handle><div><span class="eyebrow">GROUP MEMBERS</span><h2 id="member-dialog-title">绑定用户 · {{ memberGroup ? groupDisplayName(memberGroup) : '' }}</h2><p>维护用户组成员归属。</p></div><button class="modal-close" type="button" aria-label="关闭成员绑定窗口" :disabled="memberSaving" @click="closeMemberDialog">×</button></div><div class="modal-body binding-dialog-body">
<div v-if="memberGroup?.status!=='ACTIVE'" class="inline-alert warning" role="status"><b>!</b><span>停用后成员仍占用该组归属,但本组角色不会生效。</span></div><p v-if="isDefaultGroup(memberGroup)" class="binding-note default-group-note"><strong>普通用户组</strong>:组织内所有飞书用户,无需绑定。该组固定置顶且只读。</p><p v-else-if="isSuperAdminGroup(memberGroup)" class="binding-note default-group-note"><strong>默认超级管理员组</strong>:可按现有权限维护成员;后台会确保至少保留一名超级管理员。</p><div v-if="blockedCandidateWarning" class="inline-alert warning blocked-candidate-warning" role="alert" aria-live="assertive"><b>!</b><span>{{ blockedCandidateWarning }}</span></div>
<LoadState :loading="memberBindingLoading" :error="memberBindingError" label="成员绑定" @retry="reloadMemberDialog" /><template v-if="!memberBindingLoading&&!memberBindingError"><div v-if="!canViewMemberCandidates" class="member-list-restricted" role="note"><strong>{{ currentMemberIds.length }} 名成员</strong><span>需要成员管理或用户查看权限才能查看名单</span></div><template v-else><div v-if="snapshotAlert" class="inline-alert warning snapshot-alert" role="alert"><b>!</b><span>{{ snapshotAlert }}</span></div><label class="filter-search"><span class="sr-only">{{ candidateSearchLabel }}</span><input v-model="candidateKeyword" type="search" :placeholder="candidateSearchPlaceholder" autocomplete="off" :aria-label="candidateSearchLabel" :aria-controls="memberGroup ? `group-candidates-${memberGroup.id}` : undefined"></label><div class="candidate-state" aria-live="polite"><span v-if="candidateLoading" role="status">正在搜索候选人员…</span><span v-else-if="candidateError" class="candidate-error" role="alert">候选人员加载失败:{{ candidateError }} <button class="table-action" type="button" @click="loadCandidates(candidateKeyword)">重试</button></span><span v-else-if="candidateKeyword.trim()">找到 {{ candidateMatches.length }} 个匹配结果</span></div><div v-if="candidateTruncated&&!candidateLoading&&!candidateError" class="inline-alert warning truncation-notice" role="status"><span>结果较多,仅显示前 {{ candidateLimit }} 条,请缩小搜索范围。</span></div><div :id="memberGroup ? `group-candidates-${memberGroup.id}` : undefined" class="candidate-list" :aria-busy="candidateLoading"><div v-for="person in displayedCandidates" :key="person.id" class="candidate-row" :class="{disabled:memberCandidateDisabled(person)}"><label class="candidate-main"><input v-model="selectedMemberIds" type="checkbox" :value="person.id" :disabled="groupMembersDynamic||!groupMembersEditable||!canEdit('system.group.member.bind')||memberCandidateDisabled(person)"><span><strong>{{ memberDisplayName(person) }}</strong><small>{{ person.employeeNo||'无工号' }} · {{ departmentText(person) }}</small><small v-if="person.assignedGroupId!==null && person.assignedGroupId!==memberGroup?.id" class="assignment-note">不可选择,已属于:{{ person.assignedGroupName||'其他用户组' }}</small><small v-else-if="selectedMemberIds.includes(person.id) && !currentMembers.some(item=>item.id===person.id) && !candidateMatches.some(item=>item.id===person.id)" class="assignment-note selected-note">已选草稿(保留显示)</small></span></label><button v-if="memberCandidateDisabled(person)&&selectedMemberIds.includes(person.id)&&canEdit('system.group.member.bind')" class="table-action draft-remove" type="button" :aria-label="`从成员草稿移除 ${memberDisplayName(person)}`" @click="removeMemberDraft(person.id)">移出草稿</button></div><div v-if="showFreshEmpty" class="empty-state compact-empty" role="status"><span>{{ candidateKeyword.trim()?'没有匹配的飞书用户。':'当前没有可添加的飞书用户。' }}</span></div></div></template></template></div><div class="modal-actions"><button class="btn" type="button" :disabled="memberSaving" @click="closeMemberDialog">取消</button><button v-if="!isDefaultGroup(memberGroup)&&!groupMembersDynamic&&groupMembersEditable&&canEdit('system.group.member.bind')" class="btn primary" type="submit" :disabled="memberSaving||memberBindingLoading||!!memberBindingError||hasBlockedMemberDraft">{{ memberSaving?'保存中…':'保存成员' }}</button></div></form></dialog>
<section v-if="activeTab === 'roles' && can('system:role:view')" class="card admin-card"><div class="card-head"><div><h2>角色列表</h2><p>菜单、按钮和字段权限可分别配置。</p></div><span class="muted-copy">{{ roles.length }} 个角色</span></div><div v-if="rolesLoading" class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载角色…</span></div><div v-else-if="rolesError" class="empty-state" role="alert"><strong>角色加载失败</strong><span>{{ rolesError }}</span><button class="btn small" type="button" @click="loadRoles">重试</button></div><div v-else-if="!roles.length" class="empty-state"><strong>暂无角色</strong><span>创建角色后可配置其权限。</span></div><div v-else class="table-wrap"><table class="data-table" aria-label="角色列表"><thead><tr><th>角色</th><th>说明</th><th>状态</th><th>成员数</th><th>权限数</th><th>操作</th></tr></thead><tbody><tr v-for="role in roles" :key="role.id"><td><strong>{{ role.roleName }}</strong><small>{{ role.roleCode }}</small></td><td><span class="muted-copy">{{ role.description || '-' }}</span></td><td><span class="tag" :class="role.status === 'ACTIVE' ? 'success' : 'danger'">{{ role.status === 'ACTIVE' ? '启用' : '停用' }}</span></td><td>{{ role.memberCount ?? 0 }}</td><td>{{ role.permissionCount ?? 0 }}</td><td class="actions-cell"><button class="table-action" type="button" :disabled="!can('system:role:manage')" @click="openRoleForm(role)">{{ role.builtIn ? '查看 / 编辑' : '编辑' }}</button><button v-if="!role.builtIn && can('system:role:manage')" class="table-action" type="button" @click="toggleRoleStatus(role)">{{ role.status === 'ACTIVE' ? '停用' : '启用' }}</button><button v-if="!role.builtIn && can('system:role:manage')" class="table-action danger-action" type="button" @click="deleteRole(role)">删除</button></td></tr></tbody></table></div></section>
<dialog ref="groupRoleDialog" v-dialog-drag class="app-dialog admin-dialog group-role-dialog" aria-labelledby="group-role-dialog-title" @cancel="handleGroupRoleDialogCancel"><form @submit.prevent="saveGroupRoles"><div class="modal-head" data-dialog-drag-handle><div><span class="eyebrow">GROUP ROLES</span><h2 id="group-role-dialog-title">绑定角色 · {{ roleGroup ? groupDisplayName(roleGroup) : '' }}</h2><p>为当前用户组选择统一生效的角色。</p></div><button class="modal-close" type="button" aria-label="关闭角色绑定窗口" :disabled="groupRoleSaving" @click="closeGroupRoleDialog">×</button></div><div class="modal-body binding-dialog-body"><p v-if="isDefaultGroup(roleGroup)" class="binding-note default-group-note"><strong>普通用户组</strong>:系统默认组固定角色,只读且不可修改。</p><div v-if="isDefaultGroup(roleGroup)" class="fixed-role"><span class="tag info">EMPLOYEE</span><div><strong>普通用户</strong><small>系统默认组固定角色,只读且不可修改。</small></div></div><LoadState :loading="roleBindingLoading" :error="groupRoleCandidateError" label="角色绑定" @retry="loadGroupRoleBinding" /><template v-if="!isDefaultGroup(roleGroup)&&!roleBindingLoading&&!groupRoleCandidateError"><p class="binding-note">可多选启用中的角色;已绑定后停用的角色仅可移除,移除后不可重新选择。</p><div v-if="!roles.length" class="empty-state compact-empty"><strong>暂无角色候选</strong><span>当前没有可绑定角色。</span></div><div class="role-options group-role-options"><label v-for="role in roles" :key="role.id" class="check-option" :class="{disabled:role.status!=='ACTIVE'&&!selectedGroupRoleIds.includes(role.id)}"><input v-model="selectedGroupRoleIds" type="checkbox" :value="role.id" :disabled="!canEdit('system.group.role.bind')||(role.status!=='ACTIVE'&&!selectedGroupRoleIds.includes(role.id))"><span><strong>{{ role.roleName }}</strong><small>{{ role.roleCode }}<template v-if="role.description"> · {{ role.description }}</template><template v-if="role.status!=='ACTIVE'"> · {{ selectedGroupRoleIds.includes(role.id)?'已停用,仅可移除':'已停用,不可绑定' }}</template></small></span></label></div></template></div><div class="modal-actions"><button class="btn" type="button" :disabled="groupRoleSaving" @click="closeGroupRoleDialog">取消</button><button v-if="!isDefaultGroup(roleGroup)&&canEdit('system.group.role.bind')" class="btn primary" type="submit" :disabled="groupRoleSaving||roleBindingLoading||!!groupRoleCandidateError">{{ groupRoleSaving?'保存中…':'保存角色' }}</button></div></form></dialog>
<section v-if="activeTab === 'groups' && can('system:group:view')" class="group-layout"><div class="card admin-card"><div class="card-head"><div><h2>用户组</h2><p>每个用户组可以独立绑定人员和角色。</p></div><span class="muted-copy">{{ groups.length }} 个用户组</span></div><div v-if="groupsLoading" class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载用户组…</span></div><div v-else-if="groupsError" class="empty-state" role="alert"><strong>用户组加载失败</strong><span>{{ groupsError }}</span><button class="btn small" type="button" @click="loadGroups">重试</button></div><div v-else-if="!groups.length" class="empty-state"><strong>暂无用户组</strong><span>新建用户组后可以绑定飞书人员。</span></div><div v-else class="table-wrap"><table class="data-table" aria-label="用户组列表"><thead><tr><th>用户组</th><th>状态</th><th>成员</th><th>角色</th><th>操作</th></tr></thead><tbody><tr v-for="group in groups" :key="group.id" :class="{ selected: selectedGroup?.id === group.id }"><td><button class="link-button" type="button" @click="openGroupDetail(group)"><strong>{{ group.groupName }}</strong><small>{{ group.groupCode }}</small></button></td><td><span class="tag" :class="group.status === 'ACTIVE' ? 'success' : 'danger'">{{ group.status === 'ACTIVE' ? '启用' : '已停用' }}</span></td><td>{{ group.memberCount ?? 0 }}</td><td>{{ group.roleCount ?? 0 }}</td><td class="actions-cell"><button class="table-action" type="button" @click="openGroupDetail(group)">绑定详情</button><button class="table-action" type="button" :disabled="!can('system:group:manage')" @click="openGroupForm(group)">编辑</button><button v-if="can('system:group:manage')" class="table-action danger-action" type="button" @click="deleteGroup(group)">删除</button></td></tr></tbody></table></div></div>
<div v-if="selectedGroup" class="card group-detail"><div class="card-head"><div><span class="eyebrow">GROUP DETAIL</span><h2>{{ selectedGroup.groupName }}</h2><p>{{ selectedGroup.description || '绑定飞书组织人员和角色' }}</p></div><button class="modal-close" type="button" aria-label="关闭用户组详情" @click="selectedGroup = null">×</button></div><div v-if="groupDetailLoading" class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载绑定信息…</span></div><div v-else-if="groupDetailError" class="empty-state" role="alert"><strong>详情加载失败</strong><span>{{ groupDetailError }}</span><button class="btn small" type="button" @click="openGroupDetail(selectedGroup!)">重试</button></div><template v-else><section class="binding-section"><div class="section-title"><h2>飞书组织人员</h2><span>{{ selectedMemberIds.length }} 人已绑定</span></div><div class="filter-bar"><label class="filter-search"><span class="sr-only">关键字</span><input v-model.trim="candidateKeyword" type="search" placeholder="搜索姓名、工号或飞书 ID" aria-label="搜索候选人员"></label><label><span class="sr-only">部门</span><select v-model="candidateDepartment" class="select" aria-label="按部门筛选"><option value="">全部部门</option><option v-for="department in candidateDepartments" :key="department" :value="department">{{ department }}</option></select></label></div><div v-if="candidateLoading" class="load-wrap"><span class="loader" aria-hidden="true"></span><span>正在加载候选人员…</span></div><div v-else-if="!filteredCandidates.length" class="empty-state compact-empty"><strong>没有符合条件的候选人员</strong><span>可调整部门或关键字筛选。</span></div><div v-else class="candidate-list"><label v-for="candidate in filteredCandidates" :key="candidate.id" class="candidate-row"><input v-model="selectedMemberIds" type="checkbox" :value="candidate.id" :disabled="!can('system:group:manage')"><span class="candidate-copy"><strong>{{ candidate.realName }} <small>{{ candidate.employeeNo || '-' }}</small></strong><span>{{ candidate.departmentName || '未分配部门' }} · {{ candidate.status === 'ACTIVE' ? '在职' : '已停用' }}</span></span><span class="candidate-ids"><small>Open ID:{{ maskId(candidate.feishuOpenId) }}</small><small>User ID:{{ maskId(candidate.feishuUserId) }}</small></span></label></div><div class="binding-actions"><button class="btn primary" type="button" :disabled="!can('system:group:manage') || savingBinding === 'members'" @click="saveGroupMembers">{{ savingBinding === 'members' ? '保存中…' : '保存人员绑定' }}</button></div></section><section class="binding-section"><div class="section-title"><h2>绑定角色</h2><span>{{ selectedGroupRoleIds.length }} 个角色</span></div><div v-if="!roles.length" class="empty-state compact-empty"><strong>暂无可用角色</strong><span>需要角色查看权限才能配置用户组角色。</span></div><div v-else class="role-options"><label v-for="role in roles" :key="role.id" class="check-option"><input v-model="selectedGroupRoleIds" type="checkbox" :value="role.id" :disabled="!can('system:group:manage')"><span><strong>{{ role.roleName }}</strong><small>{{ role.roleCode }}</small></span></label></div><div class="binding-actions"><button class="btn primary" type="button" :disabled="!can('system:group:manage') || savingBinding === 'roles'" @click="saveGroupRoles">{{ savingBinding === 'roles' ? '保存中…' : '保存角色绑定' }}</button></div></section></template></div>
<section v-if="activeTab==='groups' && canReadWorkspace" class="management-workspace route-list-region" role="tabpanel" aria-labelledby="admin-tab-groups">
<div class="card admin-card primary-list-card"><div class="card-head"><div><h2>用户组</h2><p>分别维护成员归属与角色绑定。</p></div><span>{{ groups.length }} 个</span></div><LoadState :loading="groupsLoading" :error="groupsError" label="用户组" @retry="loadGroups" /><div v-if="!groupsLoading&&!groupsError&&groups.length" class="table-wrap" tabindex="0" role="region" aria-label="用户组列表"><table class="data-table responsive-table"><thead><tr><th>用户组</th><th>成员 / 角色</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="group in paginatedGroups" :key="group.id"><td data-label="用户组"><div class="group-name-line"><strong>{{ groupDisplayName(group) }}</strong><span v-if="isDefaultGroup(group)" class="tag info">普通用户组 · 无需绑定</span><span v-if="isSuperAdminGroup(group)" class="tag info">默认超级管理员组</span><span v-if="group.membershipMode==='DYNAMIC'" class="tag neutral">动态成员</span></div><small>{{ group.groupCode }}<template v-if="isDefaultGroup(group)"> · 组织内所有飞书用户</template></small></td><td data-label="成员 / 角色"><span :class="{'unresolved-count':group.memberCount===null}">{{ memberCountText(group.memberCount) }}</span> / {{ group.roleCount }}</td><td data-label="状态"><span class="tag" :class="group.status==='ACTIVE'?'success':'danger'">{{ group.status==='ACTIVE'?'启用':'停用' }}</span></td><td data-label="操作" class="actions-cell"><button class="table-action" type="button" aria-haspopup="dialog" :aria-label="`为${groupDisplayName(group)}绑定用户`" @click="openMemberDialog(group)">绑定用户</button><button class="table-action" type="button" aria-haspopup="dialog" :aria-label="`为${groupDisplayName(group)}绑定角色`" @click="openGroupRoleDialog(group)">绑定角色</button><button v-if="!isDefaultGroup(group) && canEdit('system.group.edit')" class="table-action" type="button" @click="openGroupForm(group)">编辑</button><button v-if="!isDefaultGroup(group) && canEdit('system.group.delete')" class="table-action danger-action" type="button" @click="deleteGroup(group)">删除</button></td></tr></tbody></table></div><div v-else-if="!groupsLoading&&!groupsError" class="empty-state"><strong>暂无用户组</strong></div><AppListPagination v-if="!groupsLoading&&!groupsError&&groups.length" v-model:page="groupPage" v-model:page-size="groupPageSize" :total="groups.length" aria-label="用户组列表分页" /></div>
</section>
<dialog ref="userRoleDialog" class="admin-dialog" aria-labelledby="user-role-title" @click.self="closeUserRoleDialog"><form @submit.prevent="saveUserRoles"><div class="modal-head"><div><span class="eyebrow">USER ROLES</span><h2 id="user-role-title">分配用户角色</h2><p>{{ selectedUser?.realName }} · {{ selectedUser?.employeeNo }}</p></div><button class="modal-close" type="button" aria-label="关闭角色分配窗口" @click="closeUserRoleDialog">×</button></div><div class="modal-body"><div v-if="!roles.length" class="empty-state compact-empty"><strong>暂无可分配角色</strong><span>请先确认角色查看权限和角色列表。</span></div><div v-else class="role-options"><label v-for="role in roles" :key="role.id" class="check-option"><input v-model="userRoleIds" type="checkbox" :value="role.id"><span><strong>{{ role.roleName }}</strong><small>{{ role.roleCode }} · {{ role.description || '无描述' }}</small></span></label></div></div><div class="modal-actions"><button class="btn" type="button" :disabled="userRoleSaving" @click="closeUserRoleDialog">取消</button><button class="btn primary" type="submit" :disabled="userRoleSaving || !can('system:user:manage')">{{ userRoleSaving ? '保存中…' : '保存角色' }}</button></div></form></dialog>
<section v-if="activeTab==='roles' && canRead('page.roles')" class="card admin-card primary-list-card" role="tabpanel" aria-labelledby="admin-tab-roles">
<div class="card-head"><div><h2>角色列表</h2><p>角色资料与权限配置分别受控。</p></div><span>{{ roles.length }} 个</span></div><LoadState :loading="rolesLoading" :error="rolesError" label="角色" @retry="loadRoles" />
<div v-if="!rolesLoading && !rolesError && roles.length" class="table-wrap"><table class="data-table responsive-table"><thead><tr><th>角色</th><th>说明</th><th>状态</th><th>权限</th><th>操作</th></tr></thead><tbody><tr v-for="role in paginatedRoles" :key="role.id"><td data-label="角色"><strong>{{ role.roleName }}</strong><small>{{ role.roleCode }}</small></td><td data-label="说明">{{ role.description||'-' }}</td><td data-label="状态"><span class="tag" :class="role.status==='ACTIVE'?'success':'danger'">{{ role.status==='ACTIVE'?'启用':'停用' }}</span></td><td data-label="权限">{{ role.permissionCount??0 }}</td><td data-label="操作" class="actions-cell"><button v-if="canEdit('system.role.edit') || canEdit('system.role.permission.configure')" class="table-action" type="button" @click="openRoleForm(role)">编辑 / 配权</button><button v-if="!role.builtIn && canEdit('system.role.delete')" class="table-action danger-action" type="button" @click="deleteRole(role)">删除</button></td></tr></tbody></table></div><div v-else-if="!rolesLoading&&!rolesError" class="empty-state"><strong>暂无角色</strong></div><AppListPagination v-if="!rolesLoading&&!rolesError&&roles.length" v-model:page="rolePage" v-model:page-size="rolePageSize" :total="roles.length" aria-label="角色列表分页" />
</section>
<dialog ref="roleDialog" class="admin-dialog wide-dialog" aria-labelledby="role-dialog-title" @click.self="closeRoleDialog"><form @submit.prevent="saveRole"><div class="modal-head"><div><span class="eyebrow">ROLE CONFIGURATION</span><h2 id="role-dialog-title">{{ editingRole ? '编辑角色' : '新建角色' }}</h2><p>权限变更保存后立即生效。</p></div><button class="modal-close" type="button" aria-label="关闭角色窗口" @click="closeRoleDialog">×</button></div><div class="modal-body"><div class="form-grid"><div class="field"><label for="role-code">角色编码 <em>*</em></label><input id="role-code" v-model.trim="roleForm.roleCode" :disabled="Boolean(editingRole)" required maxlength="50"></div><div class="field"><label for="role-name">角色名称 <em>*</em></label><input id="role-name" v-model.trim="roleForm.roleName" required maxlength="50"></div><div class="field"><label for="role-status">状态</label><select id="role-status" v-model="roleForm.status"><option value="ACTIVE">启用</option><option value="INACTIVE">停用</option></select></div><div class="field full"><label for="role-description">角色说明</label><textarea id="role-description" v-model.trim="roleForm.description" rows="2" maxlength="200"></textarea></div></div><div v-if="rolePermissionLoading" class="load-wrap compact-empty"><span class="loader" aria-hidden="true"></span><span>正在加载权限目录…</span></div><div v-else-if="rolePermissionError" class="empty-state compact-empty" role="alert"><strong>权限配置加载失败</strong><span>{{ rolePermissionError }}</span><button class="btn small" type="button" @click="loadRolePermissionData">重试</button></div><div v-else class="permission-editor"><div v-for="section in permissionSections" :key="section.kind" class="permission-column"><div class="section-title"><h2>{{ section.title }}</h2><span>勾选可用权限</span></div><div v-for="group in section.groups" :key="group.key" class="permission-group"><strong>{{ group.label }}</strong><div v-for="item in group.items" :key="item.code" class="permission-option"><template v-if="section.kind === 'field'"><span class="permission-name">{{ item.name }}<small>{{ item.code }}</small></span><span class="field-radios"><span v-for="level in fieldLevels" :key="level.value" class="radio-option"><input v-model="permissionForm.fieldPermissions[item.code]" type="radio" :name="`field-${item.code}`" :value="level.value">{{ level.label }}</span></span></template><template v-else><input v-model="permissionForm.permissionCodes" type="checkbox" :value="item.code"><span class="permission-name">{{ item.name }}<small>{{ item.code }}</small></span></template></div></div></div></div></div><div class="modal-actions"><button class="btn" type="button" :disabled="roleSaving" @click="closeRoleDialog">取消</button><button class="btn primary" type="submit" :disabled="roleSaving || !can('system:role:manage')">{{ roleSaving ? '保存中…' : '保存角色和权限' }}</button></div></form></dialog>
<section v-if="activeTab==='directory' && canRead('page.feishu-directory')" class="directory-tab-panel route-list-region" role="tabpanel" aria-labelledby="admin-tab-directory">
<FeishuDirectory embedded />
</section>
<dialog ref="groupDialog" class="admin-dialog" aria-labelledby="group-dialog-title" @click.self="closeGroupDialog"><form @submit.prevent="saveGroup"><div class="modal-head"><div><span class="eyebrow">USER GROUP</span><h2 id="group-dialog-title">{{ editingGroup ? '编辑用户组' : '新建用户组' }}</h2><p>用户组信息与人员、角色绑定分开保存。</p></div><button class="modal-close" type="button" aria-label="关闭用户组窗口" @click="closeGroupDialog">×</button></div><div class="modal-body"><div class="form-grid"><div class="field"><label for="group-code">组编码 <em>*</em></label><input id="group-code" v-model.trim="groupForm.groupCode" :disabled="Boolean(editingGroup)" required maxlength="50"></div><div class="field"><label for="group-name">组名称 <em>*</em></label><input id="group-name" v-model.trim="groupForm.groupName" required maxlength="80"></div><div class="field"><label for="group-status">状态</label><select id="group-status" v-model="groupForm.status"><option value="ACTIVE">启用</option><option value="INACTIVE">停用</option></select></div><div class="field full"><label for="group-description">说明</label><textarea id="group-description" v-model.trim="groupForm.description" rows="3" maxlength="200"></textarea></div></div></div><div class="modal-actions"><button class="btn" type="button" :disabled="groupSaving" @click="closeGroupDialog">取消</button><button class="btn primary" type="submit" :disabled="groupSaving || !can('system:group:manage')">{{ groupSaving ? '保存中…' : '保存用户组' }}</button></div></form></dialog>
<dialog ref="roleDialog" v-dialog-drag class="app-dialog admin-dialog wide-dialog" aria-labelledby="role-title" @cancel="handleRoleDialogCancel"><form @submit.prevent="saveRole"><div class="modal-head" data-dialog-drag-handle><div><span class="eyebrow">ROLE CONFIGURATION</span><h2 id="role-title">{{ editingRole?'编辑角色':'新建角色' }}</h2><p>维护角色身份与细粒度授权。权限保存后立即生效,加载异常时不会以空权限覆盖。</p></div><button class="modal-close" type="button" aria-label="关闭角色配置窗口" :disabled="roleSaving" @click="closeRoleDialog">×</button></div><div class="modal-body role-dialog-body"><section class="role-basic-section" aria-labelledby="role-basic-title"><div class="dialog-section-head"><div><span class="section-index">01</span><h3 id="role-basic-title">基础信息</h3></div><p>用于识别角色及说明适用范围</p></div><div class="form-grid role-basic-grid"><div class="field"><label for="role-code">角色编码 <em>*</em></label><input id="role-code" v-model.trim="roleForm.roleCode" required :disabled="roleSaving||!!editingRole||!canEdit(editingRole?'system.role.edit':'system.role.create')"></div><div class="field"><label for="role-name">角色名称 <em>*</em></label><input id="role-name" v-model.trim="roleForm.roleName" required :disabled="roleSaving||!canEdit(editingRole?'system.role.edit':'system.role.create')"></div><div class="field full"><label for="role-description">角色说明</label><textarea id="role-description" v-model.trim="roleForm.description" rows="2" :disabled="roleSaving||!canEdit(editingRole?'system.role.edit':'system.role.create')"></textarea></div></div></section><section class="role-permission-section" aria-labelledby="role-permission-section-title"><div class="dialog-section-head permission-section-head"><div><span class="section-index">02</span><h3 id="role-permission-section-title">权限范围</h3></div><p>菜单、操作与字段权限分别配置</p></div><div v-if="rolePermissionLoading" class="load-wrap modal-state" role="status"><span class="loader"></span><span>正在加载权限目录与角色权限…</span></div><div v-else-if="rolePermissionError" class="inline-alert danger permission-alert" role="alert"><span>{{ rolePermissionError }}</span><button class="btn small" type="button" @click="loadRolePermissionData">重试</button></div><RolePermissionEditor v-else-if="canEdit('system.role.permission.configure')" v-model="permissionDraft" :catalog="roleCatalog" /></section></div><div class="modal-actions"><button class="btn" type="button" :disabled="roleSaving" @click="closeRoleDialog">取消</button><button class="btn primary" type="submit" :disabled="roleSaving||rolePermissionLoading||!!rolePermissionError||!canSaveRole">{{ roleSaving?'保存中…':'保存角色' }}</button></div></form></dialog>
<dialog ref="groupDialog" v-dialog-drag class="app-dialog admin-dialog" aria-labelledby="group-title" @cancel="handleGroupDialogCancel"><form @submit.prevent="saveGroup"><div class="modal-head" data-dialog-drag-handle><div><span class="eyebrow">USER GROUP</span><h2 id="group-title">{{ editingGroup?'编辑用户组':'新建用户组' }}</h2><p>维护用户组基础资料,成员与角色绑定可在保存后单独配置。</p></div><button class="modal-close" type="button" aria-label="关闭用户组窗口" :disabled="groupSaving" @click="closeGroupDialog">×</button></div><div class="modal-body"><div class="form-grid group-form-grid"><div class="field"><label for="group-code">组编码 <em>*</em></label><input id="group-code" v-model.trim="groupForm.groupCode" required :disabled="groupSaving||!!editingGroup"></div><div class="field"><label for="group-name">名称 <em>*</em></label><input id="group-name" v-model.trim="groupForm.groupName" required :disabled="groupSaving"></div><div class="field"><label for="group-status">状态</label><select id="group-status" v-model="groupForm.status" class="select" :disabled="groupSaving||isDefaultGroup(editingGroup)"><option value="ACTIVE">启用</option><option value="INACTIVE">停用</option></select></div><div class="field full"><label for="group-description">说明</label><textarea id="group-description" v-model.trim="groupForm.description" rows="3" :disabled="groupSaving"></textarea></div><div v-if="isDefaultGroup(editingGroup)" class="inline-alert warning full" role="status"><span>系统默认组的编码和状态不可修改。</span></div><div v-else-if="editingGroup&&groupForm.status==='INACTIVE'" class="inline-alert warning full" role="status"><span>停用后成员仍占用该组归属,但本组角色不会生效。</span></div></div></div><div class="modal-actions"><button class="btn" type="button" :disabled="groupSaving" @click="closeGroupDialog">取消</button><button class="btn primary" type="submit" :disabled="groupSaving">{{ groupSaving?'保存中…':'保存用户组' }}</button></div></form></dialog>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import { computed, defineComponent, h, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/api/request'
import { adminApi, type AdminUser, type GroupCandidate, type PermissionItem, type Role, type UserGroup } from '@/api/admin'
import { adminApi, type DirectoryIdentity, type GroupCandidate, type GroupMemberCandidates, type PermissionAccess, type PermissionItem, type Role, type UserGroup } from '@/api/admin'
import { hasUnsavedRoleDraft, hydrateRolePermissions, serializeRolePermissions, validatePermissionCatalog } from '@/composables/permissionEditor'
import { candidateDisabled, directoryIdentityKey, directoryIdentityPayload, isDefaultGroup, isSuperAdminGroup, localMemberKey, memberCountText, sortUserGroups } from '@/composables/userGroupPolicy'
import RolePermissionEditor from '@/components/admin/permissions/RolePermissionEditor.vue'
import FeishuDirectory from '@/views/FeishuDirectory.vue'
import AppListPagination from '@/components/common/AppListPagination.vue'
import { useListPagination } from '@/composables/useListPagination'
import { useUserStore } from '@/store/user'
type Tab = 'users' | 'roles' | 'groups'; type PermissionLevel = 'HIDDEN' | 'READ' | 'EDIT'
const userStore = useUserStore(); const activeTab = ref<Tab>('users'); const users = ref<AdminUser[]>([]); const roles = ref<Role[]>([]); const groups = ref<UserGroup[]>([]); const usersLoading = ref(false); const rolesLoading = ref(false); const groupsLoading = ref(false); const usersError = ref(''); const rolesError = ref(''); const groupsError = ref(''); const roleCatalog = ref<PermissionItem[]>([])
const permissionsFailed = computed(() => Boolean(userStore.permissionsError)); const legacyAdmin = computed(() => ['ADMIN', 'SUPER_ADMIN'].includes(userStore.userInfo?.userType || '')); const useLegacyFallback = computed(() => userStore.token === 'demo-local-session' || Boolean(userStore.permissionsError)); const can = (permission: string) => userStore.permissionsLoaded && !userStore.permissionsError ? userStore.hasPermission(permission) : useLegacyFallback.value && legacyAdmin.value; const availableTabs = computed(() => (['users', 'roles', 'groups'] as Tab[]).filter(tab => can(`system:${tab === 'users' ? 'user' : tab === 'roles' ? 'role' : 'group'}:view`)))
const errorText = (error: unknown) => error instanceof Error && error.message ? error.message : '请求失败,请稍后重试。'; const show = async (dialog: HTMLDialogElement | null) => { await nextTick(); if (dialog && !dialog.open) dialog.showModal() }; const close = (dialog: HTMLDialogElement | null) => { if (dialog?.open) dialog.close() }; const switchTab = (tab: Tab) => { activeTab.value = tab; if (tab === 'roles' && !roles.value.length) void loadRoles(); if (tab === 'groups' && !groups.value.length) void loadGroups() }
const retryPermissions = async () => { try { await userStore.loadPermissions(true); activeTab.value = availableTabs.value[0] || 'users'; await loadInitialData() } catch (error) { ElMessage.error(errorText(error)) } }
const loadUsers = async () => { usersLoading.value = true; usersError.value = ''; try { users.value = await adminApi.listUsers() || [] } catch (error) { usersError.value = errorText(error); ElMessage.error(`用户加载失败:${usersError.value}`) } finally { usersLoading.value = false } }; const loadRoles = async () => { rolesLoading.value = true; rolesError.value = ''; try { roles.value = await adminApi.listRoles() || [] } catch (error) { rolesError.value = errorText(error); ElMessage.error(`角色加载失败:${rolesError.value}`) } finally { rolesLoading.value = false } }; const loadGroups = async () => { groupsLoading.value = true; groupsError.value = ''; try { groups.value = await adminApi.listGroups() || [] } catch (error) { groupsError.value = errorText(error); ElMessage.error(`用户组加载失败:${groupsError.value}`) } finally { groupsLoading.value = false } }; const loadInitialData = async () => { const jobs: Promise<unknown>[] = []; if (can('system:user:view')) jobs.push(loadUsers()); if (can('system:role:view')) jobs.push(loadRoles()); if (can('system:group:view')) jobs.push(loadGroups()); await Promise.all(jobs) }; onMounted(async () => { try { await userStore.loadPermissions(); activeTab.value = availableTabs.value[0] || 'users'; await loadInitialData() } catch (error) { ElMessage.error(errorText(error)) } })
const legacyRole = (value?: string) => ['ADMIN', 'FINANCE', 'EMPLOYEE'].includes(value || '') ? value as string : 'EMPLOYEE'; const legacyRoleLabel = (value?: string) => ({ ADMIN: '系统管理员', FINANCE: '财务人员', EMPLOYEE: '普通用户' }[legacyRole(value)] || '普通用户'); const statusSaving = ref<number | null>(null)
const updateLegacyRole = async (user: AdminUser, event: Event) => { const previous = user.userType; const next = (event.target as HTMLSelectElement).value; statusSaving.value = user.id; try { const updated = await request.put<AdminUser>(`/auth/users/${user.id}/role`, { userType: next }); Object.assign(user, updated || { userType: next }); ElMessage.success('旧角色已更新') } catch (error) { ElMessage.error(`角色更新失败:${errorText(error)}`); if (previous !== undefined) user.userType = previous } finally { statusSaving.value = null } }; const toggleUserStatus = async (user: AdminUser) => { const next = user.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'; statusSaving.value = user.id; try { const updated = await request.put<AdminUser>(`/auth/users/${user.id}/status`, { status: next }); Object.assign(user, updated || { status: next }); ElMessage.success('状态已更新') } catch (error) { ElMessage.error(`状态更新失败:${errorText(error)}`) } finally { statusSaving.value = null } }
const userRoleDialog = ref<HTMLDialogElement | null>(null); const selectedUser = ref<AdminUser | null>(null); const userRoleIds = ref<number[]>([]); const userRoleSaving = ref(false); const openUserRoles = async (user: AdminUser) => { selectedUser.value = user; userRoleIds.value = roles.value.filter(role => user.roleCodes?.includes(role.roleCode)).map(role => role.id); await show(userRoleDialog.value) }; const closeUserRoleDialog = () => { close(userRoleDialog.value); selectedUser.value = null }; const saveUserRoles = async () => { if (!selectedUser.value) return; userRoleSaving.value = true; try { const updated = await adminApi.updateUserRoles(selectedUser.value.id, userRoleIds.value); Object.assign(selectedUser.value, updated || {}); ElMessage.success('用户角色已保存'); closeUserRoleDialog() } catch (error) { ElMessage.error(`用户角色保存失败:${errorText(error)}`) } finally { userRoleSaving.value = false } }
const roleDialog = ref<HTMLDialogElement | null>(null); const editingRole = ref<Role | null>(null); const roleSaving = ref(false); const rolePermissionLoading = ref(false); const rolePermissionError = ref(''); const roleForm = reactive({ roleCode: '', roleName: '', description: '', status: 'ACTIVE' as string }); const permissionForm = reactive<{ permissionCodes: string[]; fieldPermissions: Record<string, PermissionLevel> }>({ permissionCodes: [], fieldPermissions: {} }); const fieldLevels: { value: PermissionLevel; label: string }[] = [{ value: 'HIDDEN', label: '隐藏' }, { value: 'READ', label: '只读' }, { value: 'EDIT', label: '编辑' }]
const permissionKind = (item: PermissionItem) => { const type = String(item.type || '').toUpperCase(); return type.includes('FIELD') ? 'field' : type.includes('BUTTON') || type.includes('ACTION') ? 'button' : 'menu' }; const permissionSections = computed(() => (['menu', 'button', 'field'].map(kind => { const items = roleCatalog.value.filter(item => permissionKind(item) === kind); const map = new Map<string, PermissionItem[]>(); items.forEach(item => { const key = item.parentCode || item.resource || 'common'; map.set(key, [...(map.get(key) || []), item]) }); return { kind, title: kind === 'menu' ? '菜单权限' : kind === 'button' ? '按钮权限' : '字段权限', groups: [...map.entries()].map(([key, values]) => ({ key, label: key === 'common' ? '通用' : (roleCatalog.value.find(item => item.code === key)?.name || key), items: values })) } })).filter(section => section.groups.length)); const resetPermissionForm = () => { permissionForm.permissionCodes = []; permissionForm.fieldPermissions = {}; roleCatalog.value.filter(item => permissionKind(item) === 'field').forEach(item => { permissionForm.fieldPermissions[item.code] = 'HIDDEN' }) }
const loadRolePermissionData = async () => { rolePermissionLoading.value = true; rolePermissionError.value = ''; try { if (!roleCatalog.value.length) roleCatalog.value = await adminApi.listPermissions() || []; resetPermissionForm(); if (editingRole.value) { const current = await adminApi.getRolePermissions(editingRole.value.id); permissionForm.permissionCodes = current?.permissionCodes || []; Object.entries(current?.fieldPermissions || {}).forEach(([code, level]) => { permissionForm.fieldPermissions[code] = level }) } } catch (error) { rolePermissionError.value = errorText(error); ElMessage.error(`权限目录加载失败:${rolePermissionError.value}`) } finally { rolePermissionLoading.value = false } }; const openRoleForm = async (role?: Role) => { editingRole.value = role || null; roleForm.roleCode = role?.roleCode || ''; roleForm.roleName = role?.roleName || ''; roleForm.description = role?.description || ''; roleForm.status = role?.status || 'ACTIVE'; rolePermissionError.value = ''; resetPermissionForm(); await show(roleDialog.value); await loadRolePermissionData() }; const closeRoleDialog = () => { close(roleDialog.value); editingRole.value = null }
const saveRole = async () => { if (!roleForm.roleCode || !roleForm.roleName) return; roleSaving.value = true; try { const body = { roleCode: roleForm.roleCode, roleName: roleForm.roleName, description: roleForm.description, status: roleForm.status }; const saved = editingRole.value ? await adminApi.updateRole(editingRole.value.id, body) : await adminApi.createRole(body); if (!saved?.id) throw new Error('角色保存响应无效'); await adminApi.updateRolePermissions(saved.id, { permissionCodes: permissionForm.permissionCodes, fieldPermissions: permissionForm.fieldPermissions }); await loadRoles(); ElMessage.success('角色和权限已保存'); closeRoleDialog() } catch (error) { ElMessage.error(`角色保存失败:${errorText(error)}`) } finally { roleSaving.value = false } }; const deleteRole = async (role: Role) => { try { await ElMessageBox.confirm(`确定删除角色“${role.roleName}”吗?删除后不可恢复。`, '确认删除', { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }); await adminApi.deleteRole(role.id); roles.value = roles.value.filter(item => item.id !== role.id); ElMessage.success('角色已删除') } catch (error: unknown) { if (error !== 'cancel' && error !== 'close') ElMessage.error(`角色删除失败:${errorText(error)}`) } }; const toggleRoleStatus = async (role: Role) => { try { const updated = await adminApi.updateRole(role.id, { status: role.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE' }); Object.assign(role, updated || {}); ElMessage.success('角色状态已更新') } catch (error) { ElMessage.error(`角色状态更新失败:${errorText(error)}`) } }
const groupDialog = ref<HTMLDialogElement | null>(null); const editingGroup = ref<UserGroup | null>(null); const groupSaving = ref(false); const groupForm = reactive({ groupCode: '', groupName: '', description: '', status: 'ACTIVE' as string }); const openGroupForm = async (group?: UserGroup) => { editingGroup.value = group || null; groupForm.groupCode = group?.groupCode || ''; groupForm.groupName = group?.groupName || ''; groupForm.description = group?.description || ''; groupForm.status = group?.status || 'ACTIVE'; await show(groupDialog.value) }; const closeGroupDialog = () => { close(groupDialog.value); editingGroup.value = null }; const saveGroup = async () => { if (!groupForm.groupCode || !groupForm.groupName) return; groupSaving.value = true; try { const body = { groupCode: groupForm.groupCode, groupName: groupForm.groupName, description: groupForm.description, status: groupForm.status }; const saved = editingGroup.value ? await adminApi.updateGroup(editingGroup.value.id, body) : await adminApi.createGroup(body); if (editingGroup.value) Object.assign(editingGroup.value, saved || body); else groups.value.unshift(saved); ElMessage.success('用户组已保存'); closeGroupDialog() } catch (error) { ElMessage.error(`用户组保存失败:${errorText(error)}`) } finally { groupSaving.value = false } }; const deleteGroup = async (group: UserGroup) => { try { await ElMessageBox.confirm(`确定删除用户组“${group.groupName}”吗?绑定关系也会被移除。`, '确认删除', { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }); await adminApi.deleteGroup(group.id); groups.value = groups.value.filter(item => item.id !== group.id); if (selectedGroup.value?.id === group.id) selectedGroup.value = null; ElMessage.success('用户组已删除') } catch (error: unknown) { if (error !== 'cancel' && error !== 'close') ElMessage.error(`用户组删除失败:${errorText(error)}`) } }
const selectedGroup = ref<UserGroup | null>(null); const groupDetailLoading = ref(false); const groupDetailError = ref(''); const candidates = ref<GroupCandidate[]>([]); const candidateLoading = ref(false); const candidateKeyword = ref(''); const candidateDepartment = ref(''); const selectedMemberIds = ref<number[]>([]); const selectedGroupRoleIds = ref<number[]>([]); const savingBinding = ref<'members' | 'roles' | ''>(''); const candidateDepartments = computed(() => [...new Set(candidates.value.map(candidate => candidate.departmentName).filter(Boolean) as string[])]); const filteredCandidates = computed(() => candidates.value.filter(candidate => { const query = candidateKeyword.value.toLowerCase(); const text = [candidate.realName, candidate.employeeNo, candidate.departmentName, candidate.feishuOpenId, candidate.feishuUserId].join(' ').toLowerCase(); return (!query || text.includes(query)) && (!candidateDepartment.value || candidate.departmentName === candidateDepartment.value) })); const maskId = (value?: string) => { const text = String(value || '').trim(); if (!text) return '-'; if (text.length <= 4) return '••••'; return `${text.slice(0, 2)}••••${text.slice(-2)}` }
const openGroupDetail = async (group: UserGroup) => { selectedGroup.value = group; groupDetailLoading.value = true; groupDetailError.value = ''; candidateKeyword.value = ''; candidateDepartment.value = ''; try { candidateLoading.value = true; const [members, assignedRoles, people] = await Promise.all([adminApi.getGroupMembers(group.id), adminApi.getGroupRoles(group.id), adminApi.listCandidates()]); selectedMemberIds.value = members?.userIds || []; selectedGroupRoleIds.value = assignedRoles?.roleIds || []; candidates.value = people || [] } catch (error) { groupDetailError.value = errorText(error); ElMessage.error(`用户组详情加载失败:${groupDetailError.value}`) } finally { candidateLoading.value = false; groupDetailLoading.value = false } }; const saveGroupMembers = async () => { if (!selectedGroup.value) return; savingBinding.value = 'members'; try { await adminApi.updateGroupMembers(selectedGroup.value.id, selectedMemberIds.value); selectedGroup.value.memberCount = selectedMemberIds.value.length; const item = groups.value.find(group => group.id === selectedGroup.value?.id); if (item) item.memberCount = selectedMemberIds.value.length; ElMessage.success('人员绑定已保存') } catch (error) { ElMessage.error(`人员绑定保存失败:${errorText(error)}`) } finally { savingBinding.value = '' } }; const saveGroupRoles = async () => { if (!selectedGroup.value) return; savingBinding.value = 'roles'; try { await adminApi.updateGroupRoles(selectedGroup.value.id, selectedGroupRoleIds.value); selectedGroup.value.roleCount = selectedGroupRoleIds.value.length; const item = groups.value.find(group => group.id === selectedGroup.value?.id); if (item) item.roleCount = selectedGroupRoleIds.value.length; ElMessage.success('角色绑定已保存') } catch (error) { ElMessage.error(`角色绑定保存失败:${errorText(error)}`) } finally { savingBinding.value = '' } }
const toggleGroupStatus = async (group: UserGroup) => { try { const updated = await adminApi.updateGroup(group.id, { status: group.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE' }); Object.assign(group, updated || {}); ElMessage.success('用户组状态已更新') } catch (error) { ElMessage.error(`用户组状态更新失败:${errorText(error)}`) } }
type Tab='groups'|'roles'|'directory'
const LoadState=defineComponent({props:{loading:Boolean,error:String,label:String},emits:['retry'],setup(p,{emit}){return()=>p.loading?h('div',{class:'load-wrap',role:'status'},`正在加载${p.label}…`):p.error?h('div',{class:'empty-state',role:'alert'},[h('strong',`${p.label}加载失败`),h('span',p.error),h('button',{class:'btn small',onClick:()=>emit('retry')},'重试')]):null}})
const userStore=useUserStore(); const canRead=userStore.canRead; const canEdit=userStore.canEdit
const route=useRoute(); const router=useRouter()
const canReadWorkspace=computed(()=>canRead('page.groups'))
const tabs:{key:Tab;label:string;permissions:string[]}[]=[{key:'groups',label:'用户组管理',permissions:['page.groups']},{key:'roles',label:'角色管理',permissions:['page.roles']},{key:'directory',label:'飞书通讯录',permissions:['page.feishu-directory']}]
const availableTabs=computed(()=>tabs.filter(tab=>tab.permissions.some(canRead))); const activeTab=ref<Tab>('groups'); const permissionsFailed=computed(()=>Boolean(userStore.permissionsError))
const pageDescription=computed(()=>activeTab.value==='directory'?'查看已同步的飞书组织架构与员工资料,并维护通讯录同步状态。':activeTab.value==='roles'?'维护角色资料与细粒度权限配置。':'通过用户组管理成员归属,并为用户组统一绑定角色权限。')
const roles=ref<Role[]>([]),groups=ref<UserGroup[]>([]); const rolesLoading=ref(false),groupsLoading=ref(false),rolesLoaded=ref(false); const rolesError=ref(''),groupsError=ref('')
const {page:groupPage,pageSize:groupPageSize,paginatedItems:paginatedGroups}=useListPagination(groups)
const {page:rolePage,pageSize:rolePageSize,paginatedItems:paginatedRoles}=useListPagination(roles)
const canLoadRoleCandidates=computed(()=>canRead('page.roles')||canEdit('system.group.role.bind')||canRead('page.groups'))
const canViewMemberCandidates=computed(()=>canEdit('system.group.member.bind')||canRead('page.users'))
const candidateSearchPlaceholder=computed(()=>canEdit('system.group.member.bind')?'搜索已同步飞书通讯录:姓名、User ID、Open ID、手机号、工号或部门':'搜索已同步飞书通讯录:姓名、工号或部门')
const candidateSearchLabel=computed(()=>canEdit('system.group.member.bind')?'搜索已同步的飞书通讯录,可按姓名、User ID、Open ID、手机号、工号或部门查询':'搜索已同步的飞书通讯录,可按姓名、工号或部门查询')
let roleLoadPromise:Promise<boolean>|null=null
const errorText=(error:unknown)=>{const responseMessage=(error as {response?:{data?:{message?:unknown}}})?.response?.data?.message;return typeof responseMessage==='string'&&responseMessage?responseMessage:error instanceof Error&&error.message?error.message:'请求失败,请稍后重试。'}
const loadRoles=async()=>{if(!canLoadRoleCandidates.value)return false;if(roleLoadPromise)return roleLoadPromise;rolesLoading.value=true;rolesError.value='';const current=(async()=>{try{roles.value=await adminApi.listRoles()||[];rolesLoaded.value=true;return true}catch(e){rolesLoaded.value=false;rolesError.value=errorText(e);ElMessage.error(`角色候选加载失败:${rolesError.value}`);return false}finally{rolesLoading.value=false}})();roleLoadPromise=current;try{return await current}finally{if(roleLoadPromise===current)roleLoadPromise=null}}; const loadGroups=async()=>{await loadList(groups,groupsLoading,groupsError,adminApi.listGroups,'用户组');if(!groupsError.value)groups.value=sortUserGroups(groups.value)}
async function loadList<T>(target:{value:T[]},loading:{value:boolean},error:{value:string},loader:()=>Promise<T[]>,label:string){loading.value=true;error.value='';try{target.value=await loader()||[]}catch(e){error.value=errorText(e);ElMessage.error(`${label}加载失败:${error.value}`)}finally{loading.value=false}}
const syncTabQuery=(tab:Tab)=>{if(String(route.query.tab||'')===tab)return;void router.replace({query:{...route.query,tab}})}
const activateTab=(tab:Tab)=>{activeTab.value=tab;if(tab==='groups'&&!groups.value.length)void loadGroups();if(tab==='roles'&&!rolesLoaded.value)void loadRoles()}
const switchTab=(tab:Tab)=>{if(!availableTabs.value.some(item=>item.key===tab))return;activateTab(tab);syncTabQuery(tab)}
const moveTab=(event:KeyboardEvent)=>{if(!['ArrowLeft','ArrowRight','Home','End'].includes(event.key))return;event.preventDefault();const current=availableTabs.value.findIndex(t=>t.key===activeTab.value);const next=event.key==='Home'?0:event.key==='End'?availableTabs.value.length-1:(current+(event.key==='ArrowRight'?1:-1)+availableTabs.value.length)%availableTabs.value.length;switchTab(availableTabs.value[next].key);nextTick(()=>document.getElementById(`admin-tab-${activeTab.value}`)?.focus())}
const resolveTab=(candidate:unknown):Tab|null=>{const key=String(candidate||'').trim() as Tab;return availableTabs.value.some(item=>item.key===key)?key:null}
const loadInitial=async()=>{const tab=resolveTab(route.query.tab)||availableTabs.value[0]?.key;if(!tab)return;activeTab.value=tab;syncTabQuery(tab);if(tab==='groups')await loadGroups();else if(tab==='roles')await loadRoles()}
const retryPermissions=async()=>{try{await userStore.loadPermissions(true);await loadInitial()}catch(e){ElMessage.error(errorText(e))}}
watch(()=>route.query.tab,tab=>{const next=resolveTab(tab);if(next&&next!==activeTab.value)activateTab(next)})
onMounted(async()=>{try{await userStore.loadPermissions();await loadInitial()}catch(e){ElMessage.error(errorText(e))}})
const groupDisplayName=(group:UserGroup)=>isDefaultGroup(group)?'普通用户组':isSuperAdminGroup(group)?'超级管理员组':group.groupName
type MemberCandidateOption=Omit<GroupCandidate,'id'>&{id:string;localUserId:number|null}
const memberDisplayName=(person:MemberCandidateOption)=>person.localUserId===userStore.userInfo?.id?'我(我的账号)':person.realName
const show=async(dialog:HTMLDialogElement|null)=>{await nextTick();if(dialog&&!dialog.open)dialog.showModal()}; const closeDialog=(dialog:HTMLDialogElement|null)=>dialog?.close()
const roleDialog=ref<HTMLDialogElement|null>(null),editingRole=ref<Role|null>(null),roleSaving=ref(false),rolePermissionLoading=ref(false),rolePermissionError=ref(''),roleCatalog=ref<PermissionItem[]>([]),permissionDraft=ref<Record<string,PermissionAccess>>({})
const roleForm=reactive({roleCode:'',roleName:'',description:'',status:'ACTIVE' as string}); const canSaveRole=computed(()=>canEdit(editingRole.value?'system.role.edit':'system.role.create')||(Boolean(editingRole.value)&&canEdit('system.role.permission.configure')))
const roleFormBaseline=ref(''), permissionBaseline=ref(''), roleDiscardPending=ref(false)
const roleHasUnsavedChanges=computed(()=>hasUnsavedRoleDraft(roleForm,permissionDraft.value,roleFormBaseline.value,permissionBaseline.value))
const snapshotRoleBaseline=()=>{roleFormBaseline.value=JSON.stringify(roleForm);permissionBaseline.value=JSON.stringify(permissionDraft.value)}
let rolePermissionGeneration=0
const currentRoleId=()=>editingRole.value?.id??null
const openRoleForm=async(role?:Role)=>{if(roleSaving.value)return;rolePermissionGeneration++;editingRole.value=role||null;Object.assign(roleForm,{roleCode:role?.roleCode||'',roleName:role?.roleName||'',description:role?.description||'',status:role?.status||'ACTIVE'});permissionDraft.value={};rolePermissionError.value='';snapshotRoleBaseline();await show(roleDialog.value);await loadRolePermissionData()}
const loadRolePermissionData=async()=>{const generation=++rolePermissionGeneration;const targetRoleId=currentRoleId();rolePermissionLoading.value=true;rolePermissionError.value='';try{const [catalog,current]=await Promise.all([adminApi.listPermissions(),targetRoleId!==null?adminApi.getRolePermissions(targetRoleId):Promise.resolve({permissionCodes:[],fieldPermissions:{},permissionAccess:{}})]);if(generation!==rolePermissionGeneration||currentRoleId()!==targetRoleId)return;if(!Array.isArray(catalog))throw new Error('权限目录响应无效');const catalogError=validatePermissionCatalog(catalog);if(catalogError)throw new Error(catalogError);const next=hydrateRolePermissions(current);catalog.forEach(item=>{if(!(item.code in next))next[item.code]='HIDDEN'});roleCatalog.value=catalog;permissionDraft.value=next;snapshotRoleBaseline()}catch(e){if(generation!==rolePermissionGeneration||currentRoleId()!==targetRoleId)return;rolePermissionError.value=errorText(e);ElMessage.error(`权限配置加载失败:${rolePermissionError.value}`)}finally{if(generation===rolePermissionGeneration&&currentRoleId()===targetRoleId)rolePermissionLoading.value=false}}
const finishCloseRoleDialog=()=>{rolePermissionGeneration++;rolePermissionLoading.value=false;rolePermissionError.value='';closeDialog(roleDialog.value);editingRole.value=null;permissionDraft.value={};roleCatalog.value=[];roleFormBaseline.value='';permissionBaseline.value=''}
const closeRoleDialog=async()=>{if(roleSaving.value||roleDiscardPending.value)return;if(roleHasUnsavedChanges.value){roleDiscardPending.value=true;try{await ElMessageBox.confirm('角色资料或权限草稿尚未保存,确定放弃本次修改吗?','确认放弃修改',{type:'warning',confirmButtonText:'放弃修改',cancelButtonText:'继续编辑'});finishCloseRoleDialog()}catch{}finally{roleDiscardPending.value=false}}else finishCloseRoleDialog()}
const handleRoleDialogCancel=(event:Event)=>{event.preventDefault();void closeRoleDialog()}
const saveRole=async()=>{
if(roleSaving.value||!canSaveRole.value||rolePermissionLoading.value||rolePermissionError.value||validatePermissionCatalog(roleCatalog.value)||!roleForm.roleCode||!roleForm.roleName)return
const targetRole=editingRole.value
const targetGeneration=rolePermissionGeneration
const formSnapshot={...roleForm}
const permissionSnapshot=serializeRolePermissions({...permissionDraft.value},[...roleCatalog.value])
const mayEditRole=canEdit(targetRole?'system.role.edit':'system.role.create')
const mayConfigurePermissions=canEdit('system.role.permission.configure')
roleSaving.value=true
let completedRoleId:number|null=null
try{
let saved=targetRole
if(mayEditRole){saved=targetRole?await adminApi.updateRole(targetRole.id,formSnapshot):await adminApi.createRole(formSnapshot);if(saved){Object.assign(roleForm,{roleCode:saved.roleCode,roleName:saved.roleName,description:saved.description||'',status:saved.status});roleFormBaseline.value=JSON.stringify(roleForm)}}
if(!saved?.id)throw new Error('角色保存响应无效')
if(!targetRole)editingRole.value=saved
if(mayConfigurePermissions){
try{await adminApi.updateRolePermissions(saved.id,{...permissionSnapshot,expectedPermissionAccess:JSON.parse(permissionBaseline.value||'{}')})}catch(e){await loadRoles();ElMessage.error(targetRole?`权限保存失败:${errorText(e)}`:`角色已创建,但权限保存失败:${errorText(e)}。权限草稿已保留,请重试。`);return}
}
await loadRoles()
ElMessage.success(mayConfigurePermissions?(mayEditRole?'角色和权限已保存':'角色权限已保存'):(targetRole?'角色资料已保存':'角色已创建'))
snapshotRoleBaseline()
completedRoleId=saved.id
}catch(e){
ElMessage.error(`角色资料保存失败:${errorText(e)}`)
}finally{
roleSaving.value=false
if(completedRoleId!==null&&targetGeneration===rolePermissionGeneration&&currentRoleId()===completedRoleId)closeRoleDialog()
}
}
const deleteRole=async(role:Role)=>{if(!canEdit('system.role.delete'))return;try{await ElMessageBox.confirm(`确定删除角色“${role.roleName}”吗?`,'确认删除',{type:'warning'});await adminApi.deleteRole(role.id);roles.value=roles.value.filter(r=>r.id!==role.id)}catch(e){if(e!=='cancel'&&e!=='close')ElMessage.error(errorText(e))}}
const groupDialog=ref<HTMLDialogElement|null>(null),editingGroup=ref<UserGroup|null>(null),groupSaving=ref(false),groupForm=reactive({groupCode:'',groupName:'',description:'',status:'ACTIVE' as string})
const closeGroupDialog=()=>{if(groupSaving.value)return;closeDialog(groupDialog.value)}
const handleGroupDialogCancel=(event:Event)=>{event.preventDefault();if(!groupSaving.value)closeGroupDialog()}
const openGroupForm=async(group?:UserGroup)=>{if(groupSaving.value||isDefaultGroup(group))return;const code=group?'system.group.edit':'system.group.create';if(!canEdit(code))return;editingGroup.value=group||null;Object.assign(groupForm,{groupCode:group?.groupCode||'',groupName:group?.groupName||'',description:group?.description||'',status:group?.status||'ACTIVE'});await show(groupDialog.value)}
const saveGroup=async()=>{const targetGroup=editingGroup.value;const code=targetGroup?'system.group.edit':'system.group.create';if(groupSaving.value||isDefaultGroup(targetGroup)||!canEdit(code))return;if(targetGroup&&targetGroup.status==='ACTIVE'&&groupForm.status==='INACTIVE'){try{await ElMessageBox.confirm('停用后成员仍占用该组归属,但本组角色不会生效。确定继续吗?','确认停用用户组',{type:'warning'})}catch(e){if(e==='cancel'||e==='close')return;throw e}}const payload={...groupForm};groupSaving.value=true;let savedSuccessfully=false;try{const saved=targetGroup?await adminApi.updateGroup(targetGroup.id,payload):await adminApi.createGroup(payload);if(targetGroup)Object.assign(targetGroup,saved);else groups.value=sortUserGroups([...groups.value,saved]);await loadGroups();savedSuccessfully=true;ElMessage.success('用户组已保存')}catch(e){ElMessage.error(errorText(e))}finally{groupSaving.value=false;if(savedSuccessfully)closeGroupDialog()}}
const memberDialog=ref<HTMLDialogElement|null>(null),groupRoleDialog=ref<HTMLDialogElement|null>(null)
const memberGroup=ref<UserGroup|null>(null),roleGroup=ref<UserGroup|null>(null)
const memberBindingLoading=ref(false),memberBindingError=ref(''),candidateLoading=ref(false),candidateError=ref(''),candidateKeyword=ref('')
const currentMembers=ref<MemberCandidateOption[]>([]),candidateMatches=ref<MemberCandidateOption[]>([]),candidateHistory=ref<MemberCandidateOption[]>([])
const selectedMemberIds=ref<string[]>([]),currentMemberIds=ref<string[]>([]),memberBaselineIds=ref<number[]>([])
const validDirectoryKeys=ref(new Set<string>())
const activeDirectoryRevision=ref<string|null>(null)
const directoryRevisionObserved=ref(false)
const groupMembersDynamic=ref(false),groupMembersEditable=ref(false),membershipSnapshotState=ref<string>('UNAVAILABLE')
const memberAdditionsAllowed=ref(false)
const candidateLimit=ref(0),candidateTruncated=ref(false),blockedMatchesPresent=ref(false),memberSaving=ref(false)
const roleBindingLoading=ref(false),roleBindingError=ref(''),selectedGroupRoleIds=ref<number[]>([]),roleBaselineIds=ref<number[]>([]),groupRoleSaving=ref(false)
let memberGeneration=0,roleBindingGeneration=0,candidateSearchGeneration=0
let candidateSearchTimer:ReturnType<typeof setTimeout>|undefined
let candidateWatchSuppressed=false
type DialogControl=HTMLButtonElement|HTMLInputElement|HTMLSelectElement|HTMLTextAreaElement
const memberDisabledState=new WeakMap<DialogControl,boolean>(),roleDisabledState=new WeakMap<DialogControl,boolean>()
const lockDialogControls=(dialog:HTMLDialogElement|null,locked:boolean,previous:WeakMap<DialogControl,boolean>)=>{const form=dialog?.querySelector('form');if(!form)return;form.toggleAttribute('inert',locked);form.classList.toggle('binding-save-locked',locked);form.setAttribute('aria-busy',String(locked));form.querySelectorAll<DialogControl>('button,input,select,textarea').forEach(control=>{if(locked){if(!previous.has(control))previous.set(control,control.disabled);control.disabled=true}else if(previous.has(control)){control.disabled=previous.get(control)??false;previous.delete(control)}})}
watch(memberSaving,locked=>void nextTick(()=>lockDialogControls(memberDialog.value,locked,memberDisabledState)),{flush:'sync'})
watch(groupRoleSaving,locked=>void nextTick(()=>lockDialogControls(groupRoleDialog.value,locked,roleDisabledState)),{flush:'sync'})
const sameIds=(left:number[],right:number[])=>left.length===right.length&&[...left].sort((a,b)=>a-b).every((id,index)=>id===[...right].sort((a,b)=>a-b)[index])
const sameKeys=(left:string[],right:string[])=>left.length===right.length&&[...left].sort().every((key,index)=>key===[...right].sort()[index])
const baselineMemberKeys=computed(()=>memberBaselineIds.value.map(localMemberKey))
const memberBindingDirty=computed(()=>!sameKeys(selectedMemberIds.value,baselineMemberKeys.value))
const roleBindingDirty=computed(()=>!sameIds(selectedGroupRoleIds.value,roleBaselineIds.value))
const displayedCandidates=computed(()=>{const byKey=new Map<string,MemberCandidateOption>();currentMembers.value.forEach(person=>byKey.set(person.id,person));candidateHistory.value.filter(person=>selectedMemberIds.value.includes(person.id)).forEach(person=>{if(!byKey.has(person.id))byKey.set(person.id,person)});candidateMatches.value.forEach(person=>{if(!byKey.has(person.id))byKey.set(person.id,person)});return [...byKey.values()]})
const snapshotAlert=computed(()=>{
if(memberAdditionsAllowed.value){
if(membershipSnapshotState.value==='STALE')return '服务返回旧版 STALE 状态;当前目录仍可用于添加用户,建议同步更新资料。'
if(membershipSnapshotState.value==='CONTEXT_CHANGED')return '飞书组织上下文已变化,仅作为诊断提示;当前目录仍可用于添加用户。'
return ''
}
return ({NEVER_SYNCED:'通讯录尚未同步,请先同步飞书通讯录后再添加用户;仍可移除现有成员。',STALE:'服务返回旧版 STALE 状态且未确认当前目录可用,暂不可添加用户;仍可移除现有成员。',CONTEXT_CHANGED:'飞书组织上下文已变化且未确认当前目录可用,暂不可添加用户;仍可移除现有成员。',UNAVAILABLE:'当前目录不可用,请检查集成配置或稍后重试;仍可移除现有成员。'}[membershipSnapshotState.value]||'')
})
const blockedCandidateWarning=computed(()=>!candidateKeyword.value.trim()||candidateLoading.value||candidateError.value||candidateMatches.value.length>0||!blockedMatchesPresent.value?'':'飞书目录中有匹配人员未在结果中返回,请确认成员绑定权限和当前目录状态后重试。')
const showFreshEmpty=computed(()=>memberAdditionsAllowed.value&&!candidateLoading.value&&!candidateError.value&&candidateMatches.value.length===0&&!blockedMatchesPresent.value)
const memberCandidateDisabled=(person:MemberCandidateOption)=>currentMemberIds.value.includes(person.id)?false:!memberAdditionsAllowed.value||!person.directoryIdentity||!validDirectoryKeys.value.has(person.id)||Boolean(memberGroup.value&&candidateDisabled({...person,id:person.localUserId},memberGroup.value.id))
const hasBlockedMemberDraft=computed(()=>selectedMemberIds.value.some(key=>!currentMemberIds.value.includes(key)&&(!candidateHistory.value.find(person=>person.id===key)||memberCandidateDisabled(candidateHistory.value.find(person=>person.id===key)!))))
const departmentText=(person:MemberCandidateOption)=>person.departmentNames?.length?person.departmentNames.join('、'):person.departmentName||'未分配部门'
const groupRoleCandidateError=computed(()=>isDefaultGroup(roleGroup.value)?'':roleBindingError.value||rolesError.value||(!roleBindingLoading.value&&selectedGroupRoleIds.value.length>0&&roles.value.length===0?'当前用户组已有角色,但角色候选为空,禁止保存以避免清空现有绑定。':''))
const confirmDiscard=async(kind:'成员'|'角色',dirty:boolean)=>{if(!dirty)return true;try{await ElMessageBox.confirm(`${kind}绑定尚未保存,确定放弃这些更改吗?`,'放弃未保存更改',{type:'warning'});return true}catch(e){if(e!=='cancel'&&e!=='close')ElMessage.error(errorText(e));return false}}
const candidateOption=(person:GroupCandidate,currentIds:ReadonlySet<number>):MemberCandidateOption=>{const id=person.id!==null&&currentIds.has(person.id)?localMemberKey(person.id):person.directoryIdentity?directoryIdentityKey(person.directoryIdentity):person.id!==null?`readonly-local:${person.id}`:`readonly-directory:${JSON.stringify([person.realName,person.employeeNo??'',person.departmentNames??[]])}`;return {...person,id,localUserId:person.id}}
const rememberCandidates=(people:MemberCandidateOption[])=>{const history=new Map(candidateHistory.value.map(person=>[person.id,person]));people.forEach(person=>history.set(person.id,person));candidateHistory.value=[...history.values()]}
const additionsAllowedFor=(result:GroupMemberCandidates)=>typeof result.additionsAllowed==='boolean'?result.additionsAllowed:result.availabilityState!==undefined&&result.availabilityState!==null?result.availabilityState==='AVAILABLE':result.snapshotState==='FRESH'
const revisionFor=(result:GroupMemberCandidates,people:MemberCandidateOption[])=>{
if(result.currentRevision!==undefined)return typeof result.currentRevision==='string'&&result.currentRevision.trim()?result.currentRevision.trim():null
const revisions=new Set(people.flatMap(person=>person.directoryIdentity?[person.directoryIdentity.generationId]:[]))
return revisions.size===1?[...revisions][0]:null
}
const loadGroupMemberBinding=async(preserveDraft=false)=>{const target=memberGroup.value;if(!target)return;const generation=memberGeneration;const draft=[...selectedMemberIds.value];memberBindingLoading.value=true;memberBindingError.value='';try{const members=await adminApi.getGroupMembers(target.id);if(generation!==memberGeneration||memberGroup.value?.id!==target.id)return;if(!members||!Array.isArray(members.userIds))throw new Error('成员绑定响应无效');currentMemberIds.value=members.userIds.map(localMemberKey);memberBaselineIds.value=[...members.userIds];selectedMemberIds.value=preserveDraft?draft.filter(key=>key.startsWith('directory:')||currentMemberIds.value.includes(key)):[...currentMemberIds.value];groupMembersDynamic.value=members.dynamic;groupMembersEditable.value=members.editable}catch(e){if(generation===memberGeneration&&memberGroup.value?.id===target.id)memberBindingError.value=errorText(e)}finally{if(generation===memberGeneration&&memberGroup.value?.id===target.id)memberBindingLoading.value=false}}
const loadCandidates=async(query=candidateKeyword.value)=>{
const target=memberGroup.value
if(!target||!canViewMemberCandidates.value)return
const dialogGeneration=memberGeneration
const searchGeneration=++candidateSearchGeneration
candidateLoading.value=true
candidateError.value=''
blockedMatchesPresent.value=false
try{
const result=await adminApi.searchGroupMemberCandidates(target.id,query.trim())
if(dialogGeneration!==memberGeneration||searchGeneration!==candidateSearchGeneration||memberGroup.value?.id!==target.id)return
if(!result||!Array.isArray(result.currentMembers)||!Array.isArray(result.matches))throw new Error('候选人员响应无效')
const currentIds=new Set(result.currentMembers.flatMap(person=>person.id===null?[]:[person.id]))
currentMembers.value=result.currentMembers.map(person=>candidateOption(person,currentIds))
candidateMatches.value=result.matches.map(person=>candidateOption(person,currentIds))
blockedMatchesPresent.value=Boolean(result.blockedMatchesPresent)
membershipSnapshotState.value=result.snapshotState
memberAdditionsAllowed.value=additionsAllowedFor(result)
candidateLimit.value=result.limit
candidateTruncated.value=result.truncated
const received=[...currentMembers.value,...candidateMatches.value]
const responseRevision=revisionFor(result,received)
const revisionObserved=result.currentRevision!==undefined||responseRevision!==null
if(revisionObserved&&directoryRevisionObserved.value&&responseRevision!==activeDirectoryRevision.value)validDirectoryKeys.value=new Set()
activeDirectoryRevision.value=responseRevision
directoryRevisionObserved.value=revisionObserved
if(memberAdditionsAllowed.value)received.forEach(person=>{if(person.directoryIdentity)validDirectoryKeys.value.add(person.id)})
rememberCandidates(received)
}catch(e){
if(dialogGeneration===memberGeneration&&searchGeneration===candidateSearchGeneration&&memberGroup.value?.id===target.id)candidateError.value=errorText(e)
}finally{
if(dialogGeneration===memberGeneration&&searchGeneration===candidateSearchGeneration&&memberGroup.value?.id===target.id)candidateLoading.value=false
}
}
const reloadMemberDialog=async()=>{await Promise.all([loadGroupMemberBinding(true),loadCandidates(candidateKeyword.value)])}
const resetMemberDialog=()=>{memberGeneration++;candidateSearchGeneration++;if(candidateSearchTimer)clearTimeout(candidateSearchTimer);candidateSearchTimer=undefined;memberGroup.value=null;memberBindingLoading.value=false;memberBindingError.value='';candidateLoading.value=false;candidateError.value='';candidateWatchSuppressed=true;candidateKeyword.value='';candidateWatchSuppressed=false;currentMembers.value=[];candidateMatches.value=[];candidateHistory.value=[];selectedMemberIds.value=[];currentMemberIds.value=[];memberBaselineIds.value=[];validDirectoryKeys.value=new Set();activeDirectoryRevision.value=null;directoryRevisionObserved.value=false;memberAdditionsAllowed.value=false;candidateTruncated.value=false;candidateLimit.value=0;blockedMatchesPresent.value=false;membershipSnapshotState.value='UNAVAILABLE'}
const openMemberDialog=async(group:UserGroup)=>{if(memberSaving.value)return;memberGeneration++;candidateSearchGeneration++;memberGroup.value=group;candidateWatchSuppressed=true;candidateKeyword.value='';candidateWatchSuppressed=false;groupMembersDynamic.value=group.membershipMode==='DYNAMIC';groupMembersEditable.value=false;currentMembers.value=[];candidateMatches.value=[];candidateHistory.value=[];selectedMemberIds.value=[];currentMemberIds.value=[];memberBaselineIds.value=[];validDirectoryKeys.value=new Set();activeDirectoryRevision.value=null;directoryRevisionObserved.value=false;memberAdditionsAllowed.value=false;blockedMatchesPresent.value=false;await show(memberDialog.value);await Promise.all([loadGroupMemberBinding(),loadCandidates('')])}
const closeMemberDialog=async()=>{if(memberSaving.value||!await confirmDiscard('成员',memberBindingDirty.value))return;closeDialog(memberDialog.value);resetMemberDialog()}
const handleMemberDialogCancel=(event:Event)=>{event.preventDefault();if(!memberSaving.value)void closeMemberDialog()}
const loadGroupRoleBinding=async(preserveDraft=false)=>{const target=roleGroup.value;if(!target||isDefaultGroup(target)){roleBindingLoading.value=false;roleBindingError.value='';selectedGroupRoleIds.value=[];roleBaselineIds.value=[];return}const generation=roleBindingGeneration;const draft=[...selectedGroupRoleIds.value];roleBindingLoading.value=true;roleBindingError.value='';try{const [assigned,ready]=await Promise.all([adminApi.getGroupRoles(target.id),rolesLoaded.value?Promise.resolve(true):loadRoles()]);if(generation!==roleBindingGeneration||roleGroup.value?.id!==target.id)return;if(!assigned||!Array.isArray(assigned.roleIds))throw new Error('角色绑定响应无效');selectedGroupRoleIds.value=preserveDraft?draft:[...assigned.roleIds];roleBaselineIds.value=[...assigned.roleIds];if(!ready)roleBindingError.value=rolesError.value||'角色候选加载失败'}catch(e){if(generation===roleBindingGeneration&&roleGroup.value?.id===target.id)roleBindingError.value=errorText(e)}finally{if(generation===roleBindingGeneration&&roleGroup.value?.id===target.id)roleBindingLoading.value=false}}
const openGroupRoleDialog=async(group:UserGroup)=>{if(groupRoleSaving.value)return;roleBindingGeneration++;roleGroup.value=group;selectedGroupRoleIds.value=[];roleBaselineIds.value=[];await show(groupRoleDialog.value);await loadGroupRoleBinding()}
const closeGroupRoleDialog=async()=>{if(groupRoleSaving.value||!await confirmDiscard('角色',roleBindingDirty.value))return;roleBindingGeneration++;closeDialog(groupRoleDialog.value);roleGroup.value=null;selectedGroupRoleIds.value=[];roleBaselineIds.value=[];roleBindingError.value='';roleBindingLoading.value=false}
const handleGroupRoleDialogCancel=(event:Event)=>{event.preventDefault();if(!groupRoleSaving.value)void closeGroupRoleDialog()}
watch(candidateKeyword,()=>{if(candidateWatchSuppressed||memberSaving.value||!memberGroup.value||!canViewMemberCandidates.value)return;candidateSearchGeneration++;candidateError.value='';blockedMatchesPresent.value=false;if(candidateSearchTimer)clearTimeout(candidateSearchTimer);candidateSearchTimer=setTimeout(()=>void loadCandidates(candidateKeyword.value),300)},{flush:'sync'})
onBeforeUnmount(()=>{memberGeneration++;roleBindingGeneration++;candidateSearchGeneration++;if(candidateSearchTimer)clearTimeout(candidateSearchTimer)})
const isConflict=(error:unknown)=>(error as {response?:{status?:number}})?.response?.status===409
const removeMemberDraft=(selectionKey:string)=>{if(memberSaving.value)return;selectedMemberIds.value=selectedMemberIds.value.filter(key=>key!==selectionKey)}
const refreshMembersAfterConflict=async(targetId:number,targetGeneration:number)=>{
const identities=selectedMemberIds.value.flatMap(key=>{const identity=candidateHistory.value.find(person=>person.id===key)?.directoryIdentity;return identity?[identity]:[]})
validDirectoryKeys.value=new Set()
activeDirectoryRevision.value=null
directoryRevisionObserved.value=false
await Promise.all([loadGroupMemberBinding(true),loadCandidates(candidateKeyword.value)])
if(memberGroup.value?.id!==targetId||memberGeneration!==targetGeneration)return
const revision=activeDirectoryRevision.value
const checks=await Promise.allSettled(identities.map(identity=>adminApi.searchGroupMemberCandidates(targetId,identity.openId)))
if(memberGroup.value?.id!==targetId||memberGeneration!==targetGeneration)return
const validated=new Set(validDirectoryKeys.value)
const refreshed:MemberCandidateOption[]=[]
checks.forEach((check,index)=>{
if(check.status!=='fulfilled'||!additionsAllowedFor(check.value))return
const people=[...check.value.currentMembers,...check.value.matches]
const currentIds=new Set(check.value.currentMembers.flatMap(person=>person.id===null?[]:[person.id]))
const options=people.map(person=>candidateOption(person,currentIds))
const checkedRevision=revisionFor(check.value,options)
if(revision&&checkedRevision!==revision)return
const expectedKey=directoryIdentityKey(identities[index])
options.forEach(person=>{if(person.id===expectedKey){validated.add(person.id);refreshed.push(person)}})
})
validDirectoryKeys.value=validated
rememberCandidates(refreshed)
selectedMemberIds.value=selectedMemberIds.value.filter(key=>currentMemberIds.value.includes(key)||validated.has(key))
}
const saveGroupMembers=async()=>{if(memberSaving.value)return;const target=memberGroup.value;if(!target||isDefaultGroup(target)||groupMembersDynamic.value||!groupMembersEditable.value||!canEdit('system.group.member.bind')||memberBindingLoading.value||memberBindingError.value||hasBlockedMemberDraft.value)return;const targetGroup=target,targetId=target.id,targetGeneration=memberGeneration;const selectedKeysSnapshot=[...selectedMemberIds.value],expectedUserIdsSnapshot=[...memberBaselineIds.value];const userIdsSnapshot=expectedUserIdsSnapshot.filter(id=>selectedKeysSnapshot.includes(localMemberKey(id)));const directoryIdentitiesSnapshot=selectedKeysSnapshot.flatMap(key=>{if(currentMemberIds.value.includes(key))return [];const identity=candidateHistory.value.find(person=>person.id===key)?.directoryIdentity;return identity?[directoryIdentityPayload(identity)]:[]}) as DirectoryIdentity[];memberSaving.value=true;try{const result=await adminApi.updateGroupMembers(targetId,{userIds:userIdsSnapshot,directoryIdentities:directoryIdentitiesSnapshot,expectedUserIds:expectedUserIdsSnapshot});if(!result||!Array.isArray(result.userIds))throw new Error('成员绑定响应无效');targetGroup.memberCount=result.userIds.length;if(memberGroup.value?.id===targetId&&memberGeneration===targetGeneration){memberBaselineIds.value=[...result.userIds];currentMemberIds.value=result.userIds.map(localMemberKey);selectedMemberIds.value=[...currentMemberIds.value];validDirectoryKeys.value=new Set();await loadCandidates(candidateKeyword.value)}ElMessage.success('成员绑定已保存')}catch(e){ElMessage.error(errorText(e));if(isConflict(e)&&memberGroup.value?.id===targetId&&memberGeneration===targetGeneration)await refreshMembersAfterConflict(targetId,targetGeneration)}finally{memberSaving.value=false}}
const saveGroupRoles=async()=>{if(groupRoleSaving.value)return;const target=roleGroup.value;if(!target||isDefaultGroup(target)||!canEdit('system.group.role.bind')||roleBindingLoading.value||groupRoleCandidateError.value)return;const targetGroup=target,targetId=target.id,targetGeneration=roleBindingGeneration;const roleIdsSnapshot=[...selectedGroupRoleIds.value],expectedRoleIdsSnapshot=[...roleBaselineIds.value];groupRoleSaving.value=true;try{await adminApi.updateGroupRoles(targetId,{roleIds:roleIdsSnapshot,expectedRoleIds:expectedRoleIdsSnapshot});targetGroup.roleCount=roleIdsSnapshot.length;if(roleGroup.value?.id===targetId&&roleBindingGeneration===targetGeneration)roleBaselineIds.value=[...roleIdsSnapshot];ElMessage.success('角色绑定已保存')}catch(e){ElMessage.error(errorText(e));if(isConflict(e)&&roleGroup.value?.id===targetId&&roleBindingGeneration===targetGeneration)await loadGroupRoleBinding(true)}finally{groupRoleSaving.value=false}}
const deleteGroup=async(group:UserGroup)=>{if(memberSaving.value||groupRoleSaving.value||isDefaultGroup(group)||!canEdit('system.group.delete'))return;try{await ElMessageBox.confirm(`确定删除用户组“${group.groupName}”吗?`,'确认删除',{type:'warning'});await adminApi.deleteGroup(group.id);groups.value=groups.value.filter(g=>g.id!==group.id)}catch(e){if(e!=='cancel'&&e!=='close')ElMessage.error(errorText(e))}}
</script>
<style scoped>
.admin-card{min-width:0}.role-cell{min-width:230px}.role-cell .tag{margin:2px 4px 2px 0}.legacy-role{display:block;width:150px;height:30px;margin-top:5px;padding:2px 8px;font-size:11px}.status-button{display:inline-flex;align-items:center;gap:6px;min-height:29px;padding:4px 7px;border:1px solid transparent;border-radius:5px;background:transparent;color:var(--body);font-size:11px}.status-button:hover{border-color:var(--line);background:var(--surface-raised)}.status-button.active{color:var(--success)}.status-button.inactive{color:var(--danger)}.status-dot-small{width:7px;height:7px;border-radius:50%;background:currentColor}.actions-cell{min-width:190px}.danger-action{color:var(--danger)}.group-layout{display:grid;grid-template-columns:minmax(420px,.9fr) minmax(430px,1.1fr);align-items:start;gap:16px}.group-detail{min-width:0}.group-detail .card-head{align-items:flex-start}.group-detail .card-head h2{margin-top:3px}.link-button{display:block;border:0;background:transparent;color:inherit;text-align:left}.link-button:hover strong{color:var(--blue)}.data-table tr.selected{background:var(--blue-soft)}.binding-section+.binding-section{border-top:1px solid var(--line)}.candidate-list{max-height:390px;overflow-y:auto}.candidate-row{display:flex;min-width:0;align-items:center;gap:10px;padding:11px 18px;border-bottom:1px solid var(--line);cursor:pointer}.candidate-row:hover{background:#fbfcfe}.candidate-row>input,.check-option>input,.permission-option>input{flex:none;width:16px;height:16px;accent-color:var(--blue)}.candidate-copy{min-width:145px;flex:1}.candidate-copy strong,.candidate-copy span,.candidate-ids small{display:block}.candidate-copy strong{font-size:12px}.candidate-copy strong small{display:inline;margin-left:5px;color:var(--quiet);font:10px var(--mono)}.candidate-copy span{color:var(--muted);font-size:11px}.candidate-ids{min-width:145px;color:var(--quiet);font:10px var(--mono);text-align:right}.binding-actions{display:flex;justify-content:flex-end;padding:12px 18px;border-top:1px solid var(--line);background:var(--surface-raised)}.role-options{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:9px;padding:16px 18px}.check-option{display:flex;min-width:0;align-items:flex-start;gap:9px;padding:10px;border:1px solid var(--line);border-radius:6px;background:#fff;cursor:pointer}.check-option:hover{border-color:#b9d2ee;background:var(--blue-soft)}.check-option span,.check-option strong,.check-option small{display:block;min-width:0}.check-option strong{font-size:12px}.check-option small{margin-top:2px;overflow:hidden;color:var(--muted);font-size:10px;text-overflow:ellipsis}.admin-dialog{width:min(650px,calc(100vw - 24px));max-height:min(90vh,820px);padding:0;border:0;border-radius:10px;overflow:auto;box-shadow:0 24px 70px rgba(16,42,67,.28)}.wide-dialog{width:min(1000px,calc(100vw - 24px))}.admin-dialog::backdrop{background:rgba(16,42,67,.52)}.admin-dialog .modal-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;padding:18px 21px;border-bottom:1px solid var(--line)}.admin-dialog .modal-head h2{margin-top:3px;font-size:17px}.admin-dialog .modal-head p{margin-top:3px;color:var(--muted);font-size:12px}.admin-dialog .modal-body{padding:0}.admin-dialog .form-grid{padding:19px 21px}.admin-dialog .modal-actions{position:sticky;bottom:0;z-index:1}.permission-editor{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1px;background:var(--line);border-top:1px solid var(--line)}.permission-column{min-width:0;background:#fff}.permission-column .section-title{padding:13px 15px}.permission-column .section-title h2{font-size:13px}.permission-group{padding:11px 15px 5px}.permission-group>strong{display:block;margin-bottom:7px;color:var(--muted);font-size:11px}.permission-option{display:flex;min-width:0;align-items:center;gap:7px;padding:5px 0;cursor:pointer;font-size:11px}.permission-name{min-width:0;flex:1}.permission-name small{display:block;overflow:hidden;color:var(--quiet);font:10px var(--mono);text-overflow:ellipsis}.field-radios{display:flex;flex-wrap:wrap;gap:5px;color:var(--muted);font-size:10px;white-space:nowrap}.radio-option{display:inline-flex!important;align-items:center;gap:2px;cursor:pointer}.radio-option input{width:13px;height:13px;accent-color:var(--blue)}.compact-empty{min-height:100px}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@media(max-width:980px){.group-layout{grid-template-columns:1fr}.permission-editor{grid-template-columns:1fr}}@media(max-width:620px){.role-options{grid-template-columns:1fr}.candidate-row{align-items:flex-start}.candidate-ids{min-width:0;text-align:left}.candidate-copy{min-width:0}.admin-dialog .form-grid{grid-template-columns:1fr}}
/* Only the active list grows; dialogs retain their existing width/height. */
.admin-card,
.group-detail { display: flex; flex-direction: column; }
.admin-card { flex: 1 0 auto; }
.admin-card > .empty-state,
.admin-card > .load-wrap,
.group-detail > .empty-state,
.group-detail > .load-wrap { flex: 1 0 auto; }
.group-layout { flex: 1 0 auto; grid-template-columns: minmax(0, 1fr); align-items: stretch; }
.has-group-detail .group-layout { grid-template-columns: minmax(0, .9fr) minmax(0, 1.1fr); }
.candidate-row { flex-wrap: wrap; }
.candidate-copy { min-width: 0; }
.candidate-ids { min-width: 0; max-width: 100%; overflow-wrap: anywhere; }
.group-detail .filter-search { min-width: 0; flex: 1 1 240px; }
.group-detail .filter-bar label { max-width: 100%; }
.group-detail .select { max-width: 100%; }
@media (max-width: 1180px) {
.has-group-detail .group-layout { grid-template-columns: minmax(0, 1fr); }
.directory-tab-panel {
display: flex;
min-width: 0;
min-height: 0;
flex: 1 1 0;
flex-direction: column;
overflow: hidden;
}
.directory-tab-panel :deep(.directory-page) {
height: 100%;
flex: 1 1 auto;
max-height: 100%;
min-height: 0;
overflow: hidden;
}
.admin-card { min-width: 0; }
.management-workspace { display: grid; min-width: 0; flex: 1 1 auto; gap: 16px; }
.actions-cell { min-width: 210px; }
.danger-action { color: var(--danger); }
.member-dialog { width: min(760px, calc(100vw - 24px)); max-width: calc(100vw - 24px); }
.group-role-dialog { width: min(620px, calc(100vw - 24px)); max-width: calc(100vw - 24px); }
.binding-dialog-body { max-height: calc(100dvh - 164px); overflow: auto; }
.snapshot-alert, .truncation-notice { margin-bottom: 10px; }
.blocked-candidate-warning { margin-bottom: 10px; }
.binding-section { padding: 14px; }
.binding-section + .binding-section { border-top: 1px solid var(--line); }
.candidate-list { max-height: 330px; overflow: auto; }
.candidate-state { min-height: 28px; padding: 6px 2px; color: var(--muted); font-size: 11px; }
.candidate-error { color: var(--danger); }
.candidate-row, .check-option { display: flex; align-items: center; gap: 10px; padding: 10px; }
.candidate-row { border-bottom: 1px solid var(--line); }
.candidate-row.disabled { background: #f6f8fa; color: var(--muted); cursor: not-allowed; }
.candidate-main { display: flex; min-width: 0; flex: 1; align-items: center; gap: 10px; }
.candidate-row span, .candidate-row small, .check-option span, .check-option small, .check-option strong { display: block; min-width: 0; }
.candidate-row input, .check-option input { width: 16px; height: 16px; flex: none; accent-color: var(--blue); }
.binding-actions { display: flex; justify-content: flex-end; padding-top: 10px; }
.draft-remove { flex: none; }
.member-list-restricted { display: grid; gap: 4px; padding: 14px; border: 1px dashed var(--line); border-radius: 6px; background: #f8fafc; }
.member-list-restricted strong { color: var(--navy); font-size: 12px; }
.member-list-restricted span { color: var(--muted); font-size: 11px; }
.group-name-line { display: flex; min-width: 0; align-items: center; flex-wrap: wrap; gap: 6px; }
.group-name-line .tag { margin: 0; }
.unresolved-count, .assignment-note { color: var(--warning) !important; font-weight: 700; }
.selected-note { color: var(--blue) !important; }
.binding-note { margin: 0 0 10px; color: var(--muted); font-size: 11px; line-height: 1.6; }
.default-group-note { padding: 9px 10px; border-left: 3px solid var(--blue); background: var(--blue-soft); }
.group-warning { margin: 12px 14px 0; }
.fixed-role { display: flex; align-items: center; gap: 12px; padding: 12px; border: 1px solid #b8cee4; border-radius: 6px; background: var(--blue-soft); }
.fixed-role strong, .fixed-role small { display: block; }
.fixed-role small { margin-top: 3px; color: var(--muted); font-size: 10px; }
.group-role-options { grid-template-columns: 1fr; }
.wide-dialog { width: min(1180px, calc(100vw - 24px)); max-width: calc(100vw - 24px); }
.wide-dialog .modal-body { max-height: calc(100dvh - 164px); overflow: auto; }
.role-option-body { padding: 16px; }
.role-options { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 9px; }
.check-option { min-width: 0; min-height: 62px; align-items: flex-start; border: 1px solid var(--line); border-radius: 6px; background: #fff; cursor: pointer; transition: border-color .15s ease, background-color .15s ease; }
.check-option:hover { border-color: #b8cee4; background: #f8fbff; }
.check-option:has(input:checked) { border-color: #9bbde2; background: var(--blue-soft); }
.check-option.disabled { border-color: var(--line); background: #f6f8fa; cursor: not-allowed; }
.check-option.disabled strong, .check-option.disabled small { color: var(--muted); }
.check-option strong { color: var(--text); font-size: 12px; }
.check-option small { margin-top: 2px; color: var(--muted); font-size: 10px; overflow-wrap: anywhere; }
.modal-state { min-height: 180px; }
.role-dialog-body { padding: 18px; background: #f6f8fa; }
.role-basic-section, .role-permission-section { overflow: hidden; border: 1px solid var(--line); border-radius: 7px; background: #fff; }
.role-permission-section { margin-top: 14px; }
.dialog-section-head { display: flex; min-width: 0; align-items: center; justify-content: space-between; gap: 14px; padding: 12px 16px; border-bottom: 1px solid var(--line); background: var(--surface-raised); }
.dialog-section-head > div { display: flex; min-width: 0; align-items: center; gap: 9px; }
.dialog-section-head h3 { color: var(--navy); font-size: 13px; }
.dialog-section-head p { color: var(--muted); font-size: 11px; text-align: right; }
.section-index { color: var(--blue); font: 700 10px var(--mono); letter-spacing: .04em; }
.role-basic-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 13px 16px; padding: 16px; }
.role-basic-grid textarea { min-height: 66px; }
.permission-alert { margin: 16px; }
.group-form-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 0; }
@media (max-width: 900px) {
.member-dialog, .group-role-dialog { width: calc(100vw - 18px); max-width: calc(100vw - 18px); }
.wide-dialog { width: calc(100vw - 18px); max-width: calc(100vw - 18px); }
}
@media (max-width: 560px) {
.candidate-ids { flex-basis: 100%; padding-left: 26px; text-align: left; }
.binding-dialog-body { padding: 11px; }
.candidate-row { align-items: flex-start; flex-wrap: wrap; padding: 10px 4px; }
.candidate-main { align-items: flex-start; }
.draft-remove { margin-left: 26px; }
.actions-cell { min-width: 0; }
.actions-cell .table-action { min-height: 36px; }
.role-options, .role-basic-grid, .group-form-grid { grid-template-columns: 1fr; }
.role-dialog-body { padding: 10px; }
.dialog-section-head { align-items: flex-start; flex-direction: column; gap: 3px; padding: 11px 13px; }
.dialog-section-head p { padding-left: 28px; text-align: left; }
.role-basic-grid { padding: 13px; }
.modal-actions { flex-direction: column-reverse; }
.modal-actions .btn { width: 100%; min-height: 44px; }
}
</style>
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.